Skip to content

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

1.0.4

sora6861213bfa5e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d2bd6f5..ac703e7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,49 @@
# Changelog
+## v1.0.4
+
+### New
+- Added custom in-app confirmation and alert dialogs (including a delete confirmation with brush preview for custom brushes), replacing all browser popups
+- Added a dedicated Filter settings dialog (`Gaussian Blur`, `Motion Blur`, `Unsharp Mask`, and `Film Grain`) with sliders and reset controls
+- Added detachable, free-floating windows for all studio panels with drag-and-drop docking, resizing, one-click Pin/Unpin, a panel menu, and automatic layout saving
+- Added Worldwide peer-to-peer collaborative rooms using short `INK-XXXX-XXXXXX` room codes (up to 8 guests) with auto-reconnect and optional custom server settings
+- Added Ribbon brush support for smooth, continuous decorative strokes
+- Added full Dual Brush support
+- Added two-color brush tip support using both primary and secondary colors
+- Added real-life pigment color mixing for brushes, Smudge, Blur, and Gradients — colors now blend naturally like real paint (blue + yellow makes vibrant green, red + yellow makes bright orange, and dark colors fade cleanly into light tones instead of turning gray)
+- Added a simple Regular / Pigment toggle and Pigment Strength slider for every brush so you can switch back to standard blending anytime
+- Added a new Blend section with 6 dedicated blending brushes
+- Added Rough Pen to the Pen section for organic, textured ink linework
+- Added Optical Blur and Blur Strength sliders in the Brush Inspector and Brush Studio for smoother blending
+
+### Improvements
+- Redesigned older dialogs and panels to match Ink Studio's dark theme with consistent buttons, layout, and `Esc` closing behavior
+- Made panel tab dragging smoother with clear drop previews and synced visibility when hiding/showing palettes (`Tab`)
+- Made Worldwide Room Code the default connection mode in Collaborative Drawing and improved reliability when syncing large canvases
+- Reworked `Chalk Painting` and `Blend Chalk Brush` from scratch with sharper tips, richer paper grain, and smoother blending
+- Greatly improved Clip Studio Paint (`.sut`) brush import with full-resolution tips and paper textures, better color jitter, blending, and accurate brush previews
+- Improved paper texture effects and brush color mixing to feel closer to Clip Studio Paint
+- Improved pen tablet responsiveness and stroke stabilization for lower lag, faster stroke response, and smoother line endings
+- Reworked G-Pen, Real G-Pen, and Textured Pen to better match the feel, tilt response, and edge texture of classic inking pens
+- Upgraded built-in brush tips to higher resolution so bristles and textures stay crisp at large sizes
+- Improved Brush Studio scratchpad and brush preview swatches so blending brushes and textured pens preview more accurately
+- Old built-in brush presets and Quick Access shortcuts now automatically update to the new brushes while keeping your Sketch and Natural Paint settings intact
+- Improved brush responsiveness and reduced lag across Blend, Natural Paint, and heavy oil brushes (especially Loaded Impasto Oil and Dry Bristle Rake), making blending much smoother on large canvases
+
+### Bug Fixes
+- Fixed strokes cutting off, ending short, or fading out early on Windows Ink tablets and tight curves
+- Fixed light stylus pressure turning into nearly invisible hairlines mid-stroke on `G-Pen` and `Real G-Pen`
+- Fixed heavy lag and end-of-stroke freezes when painting or blending with color-mixing brushes
+- Fixed brush strokes losing quality or blurring after using the Transform tool (`Ctrl+T`)
+- Fixed watercolor edges appearing too dark or disappearing on color-mixing brushes
+- Fixed some large imported `.sut` brushes getting the wrong size
+- Fixed semi-transparent strokes becoming overly dark when overlapping
+- Fixed Textured Pen not showing up when drawing over filled or opaque layers
+- Fixed subtle angle jitter looking inaccurate in brush list previews
+- Fixed pure blending brushes leaving foreground color on blank areas of the canvas
+- Fixed settings carrying over between brushes when switching presets
+- Fixed ghost strokes briefly reappearing on the canvas when drawing right after pressing `Ctrl+Z`
+
## v1.0.3
### New
diff --git a/package-lock.json b/package-lock.json
index 29bc690..fb0ae3c 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "ink-studio",
- "version": "1.0.3",
+ "version": "1.0.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "ink-studio",
- "version": "1.0.3",
+ "version": "1.0.4",
"license": "GPL-3.0",
"dependencies": {
"@tailwindcss/vite": "^4.3.3",
diff --git a/package.json b/package.json
index 9dbea85..68e9c56 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "ink-studio",
"private": true,
- "version": "1.0.3",
+ "version": "1.0.4",
"description": "Collaborative Drawing Studio",
"author": "Sora",
"license": "GPL-3.0",
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 7e31cce..bd30a0e 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -2021,7 +2021,7 @@ dependencies = [
[[package]]
name = "ink-studio"
-version = "1.0.3"
+version = "1.0.4"
dependencies = [
"axum",
"flate2",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 991ba45..0839ef1 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -1,10 +1,11 @@
[package]
name = "ink-studio"
-version = "1.0.3"
+version = "1.0.4"
description = "Collaborative Drawing Studio"
authors = ["Sora"]
license = "GPL-3.0"
edition = "2021"
+default-run = "ink-studio"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
diff --git a/src-tauri/src/bin/sut_inspect.rs b/src-tauri/src/bin/sut_inspect.rs
new file mode 100644
index 0000000..12129cf
--- /dev/null
+++ b/src-tauri/src/bin/sut_inspect.rs
@@ -0,0 +1,161 @@
+use std::env;
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::process;
+use tauri_app_lib::clip_parser::{
+ format_sut_inspection_human, inspect_sut_bytes, SutInspectionReport,
+};
+
+fn print_usage() {
+ eprintln!(
+ "Usage: sut_inspect [OPTIONS] <PATH> [PATH...]\n\
+ \n\
+ Inspect Clip Studio Paint .sut brush files or directories of .sut files.\n\
+ \n\
+ Options:\n\
+ --json Output structured JSON only\n\
+ --human Output human-readable report only\n\
+ --out <FILE> Write structured JSON report to <FILE>\n\
+ -h, --help Show this help message\n\
+ \n\
+ Default output prints both the human-readable coverage summary and structured JSON."
+ );
+}
+
+fn collect_sut_files(path: &Path, out: &mut Vec<PathBuf>) -> Result<(), String> {
+ if path.is_file() {
+ out.push(path.to_path_buf());
+ return Ok(());
+ }
+ if path.is_dir() {
+ let mut entries: Vec<PathBuf> = fs::read_dir(path)
+ .map_err(|e| format!("Failed to read directory '{}': {}", path.display(), e))?
+ .filter_map(|e| e.ok().map(|de| de.path()))
+ .collect();
+ entries.sort();
+ for entry in entries {
+ if entry.is_dir() {
+ collect_sut_files(&entry, out)?;
+ } else if entry
+ .extension()
+ .and_then(|s| s.to_str())
+ .map(|ext| ext.eq_ignore_ascii_case("sut"))
+ .unwrap_or(false)
+ {
+ out.push(entry);
+ }
+ }
+ return Ok(());
+ }
+ Err(format!("Path does not exist: '{}'", path.display()))
+}
+
+fn main() {
+ let args: Vec<String> = env::args().skip(1).collect();
+ if args.is_empty() {
+ print_usage();
+ process::exit(1);
+ }
+
+ let mut json_only = false;
+ let mut human_only = false;
+ let mut out_file: Option<PathBuf> = None;
+ let mut input_paths: Vec<PathBuf> = Vec::new();
+
+ let mut i = 0;
+ while i < args.len() {
+ match args[i].as_str() {
+ "-h" | "--help" => {
+ print_usage();
+ return;
+ }
+ "--json" => json_only = true,
+ "--human" => human_only = true,
+ "--out" => {
+ i += 1;
+ if i >= args.len() {
+ eprintln!("Error: --out requires a file path argument");
+ process::exit(1);
+ }
+ out_file = Some(PathBuf::from(&args[i]));
+ }
+ other if other.starts_with('-') => {
+ eprintln!("Unknown option: {}", other);
+ print_usage();
+ process::exit(1);
+ }
+ path_arg => input_paths.push(PathBuf::from(path_arg)),
+ }
+ i += 1;
+ }
+
+ if input_paths.is_empty() {
+ eprintln!("Error: no .sut file or directory path provided.");
+ print_usage();
+ process::exit(1);
+ }
+
+ let mut sut_files = Vec::new();
+ for p in &input_paths {
+ if let Err(err) = collect_sut_files(p, &mut sut_files) {
+ eprintln!("Error: {}", err);
+ process::exit(1);
+ }
+ }
+
+ if sut_files.is_empty() {
+ eprintln!("No .sut files found under the specified path(s).");
+ process::exit(1);
+ }
+
+ let mut reports: Vec<SutInspectionReport> = Vec::with_capacity(sut_files.len());
+ let mut had_error = false;
+
+ for file_path in &sut_files {
+ let label = file_path.display().to_string();
+ match fs::read(file_path) {
+ Ok(bytes) => match inspect_sut_bytes(&bytes, Some(&label)) {
+ Ok(report) => reports.push(report),
+ Err(err) => {
+ eprintln!("Failed to inspect '{}': {}", label, err);
+ had_error = true;
+ }
+ },
+ Err(err) => {
+ eprintln!("Failed to read '{}': {}", label, err);
+ had_error = true;
+ }
+ }
+ }
+
+ let json_payload = if reports.len() == 1 && sut_files.len() == 1 {
+ serde_json::to_string_pretty(&reports[0]).unwrap_or_else(|_| "{}".to_string())
+ } else {
+ serde_json::to_string_pretty(&reports).unwrap_or_else(|_| "[]".to_string())
+ };
+
+ if let Some(ref dest) = out_file {
+ if let Err(err) = fs::write(dest, &json_payload) {
+ eprintln!("Failed to write JSON output to '{}': {}", dest.display(), err);
+ process::exit(1);
+ }
+ }
+
+ if json_only {
+ println!("{}", json_payload);
+ } else if human_only {
+ for report in &reports {
+ println!("{}", format_sut_inspection_human(report));
+ }
+ } else {
+ for report in &reports {
+ println!("{}", format_sut_inspection_human(report));
+ }
+ println!("--- JSON REPORT ---");
+ println!("{}", json_payload);
+ }
+
+ if had_error {
+ process::exit(2);
+ }
+}
diff --git a/src-tauri/src/clip_parser.rs b/src-tauri/src/clip_parser.rs
index 21756fa..0af8167 100644
--- a/src-tauri/src/clip_parser.rs
+++ b/src-tauri/src/clip_parser.rs
@@ -3,11 +3,13 @@ use crate::doc_wire::{
MAX_CANVAS_DIM, TILE_PIXELS, TILE_SIZE,
};
use flate2::read::{DeflateDecoder, ZlibDecoder};
+use flate2::write::ZlibEncoder;
+use flate2::Compression;
use rayon::prelude::*;
use rusqlite::{config::DbConfig, types::Value, Connection, DatabaseName};
use serde::Serialize;
use std::collections::{HashMap, HashSet};
-use std::io::Read;
+use std::io::{Read, Write};
const MAX_BLOCKS_PER_LAYER: usize = 16384; // 128x128 tiles = 32768x32768 px
const MAX_COMPRESSED_TILE_BYTES: usize = 2 * 1024 * 1024;
@@ -15,6 +17,13 @@ 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 MAX_TAR_ENTRIES: usize = 512;
+const MAX_TAR_ENTRY_BYTES: usize = 64 * 1024 * 1024;
+const MAX_MATERIAL_DIM: u32 = 4096;
+const MAX_MATERIAL_RGBA_BYTES: usize = 64 * 1024 * 1024;
+const MAX_MATERIAL_XML_BYTES: usize = 2 * 1024 * 1024;
+const MAX_SUT_MATERIALS: usize = 256;
+const MAX_PNG_BYTES: usize = 32 * 1024 * 1024;
const SQLITE_SIG: &[u8; 16] = b"SQLite format 3\0";
@@ -1482,208 +1491,3068 @@ pub fn parse_clip_to_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {
}
// ---------------------------------------------------------------------------
-// Native .sut SQLite extractor (removes sql.js dependency from sutParser.ts)
+// Native .sut SQLite + MaterialFile TAR/.layer extractor
// ---------------------------------------------------------------------------
+const PNG_SIG: &[u8; 8] = &[0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
+
+fn crc32_table() -> &'static [u32; 256] {
+ static TABLE: std::sync::LazyLock<[u32; 256]> = std::sync::LazyLock::new(|| {
+ let mut table = [0u32; 256];
+ for (i, slot) in table.iter_mut().enumerate() {
+ let mut c = i as u32;
+ for _ in 0..8 {
+ if (c & 1) != 0 {
+ c = 0xedb8_8320 ^ (c >> 1);
+ } else {
+ c >>= 1;
+ }
+ }
+ *slot = c;
+ }
+ table
+ });
+ &TABLE
+}
+
+fn crc32_update(mut crc: u32, data: &[u8]) -> u32 {
+ let table = crc32_table();
+ for &b in data {
+ crc = table[((crc ^ (b as u32)) & 0xff) as usize] ^ (crc >> 8);
+ }
+ crc
+}
+
+fn write_png_chunk(out: &mut Vec<u8>, chunk_type: &[u8; 4], data: &[u8]) -> Result<(), String> {
+ let len = u32::try_from(data.len()).map_err(|_| "PNG chunk exceeds 4 GB".to_string())?;
+ out.extend_from_slice(&len.to_be_bytes());
+ out.extend_from_slice(chunk_type);
+ out.extend_from_slice(data);
+ let crc = !crc32_update(crc32_update(!0u32, chunk_type), data);
+ out.extend_from_slice(&crc.to_be_bytes());
+ Ok(())
+}
+
+/// Pure safe Rust lossless RGBA8 PNG encoder using PNG Sub row filtering + flate2 zlib.
+fn encode_rgba8_to_png(width: u32, height: u32, rgba: &[u8]) -> Result<Vec<u8>, String> {
+ if width == 0 || height == 0 || width > MAX_MATERIAL_DIM || height > MAX_MATERIAL_DIM {
+ return Err(format!("Invalid PNG material dimensions: {}x{}", width, height));
+ }
+ let row_bytes = (width as usize)
+ .checked_mul(4)
+ .ok_or_else(|| "PNG row stride overflow".to_string())?;
+ let expected = row_bytes
+ .checked_mul(height as usize)
+ .ok_or_else(|| "PNG buffer size overflow".to_string())?;
+ if expected > MAX_MATERIAL_RGBA_BYTES || rgba.len() != expected {
+ return Err("PNG RGBA buffer length mismatch or exceeds safety ceiling".to_string());
+ }
+
+ let mut enc = ZlibEncoder::new(Vec::new(), Compression::fast());
+ let mut filtered_row = vec![0u8; 1 + row_bytes];
+ filtered_row[0] = 1; // PNG Sub filter (bpp = 4)
+ for y in 0..(height as usize) {
+ let src = &rgba[y * row_bytes..(y + 1) * row_bytes];
+ for x in 0..row_bytes {
+ let left = if x >= 4 { src[x - 4] } else { 0 };
+ filtered_row[1 + x] = src[x].wrapping_sub(left);
+ }
+ enc.write_all(&filtered_row)
+ .map_err(|e| format!("Failed to zlib-compress PNG scanline: {}", e))?;
+ }
+ let idat = enc
+ .finish()
+ .map_err(|e| format!("Failed to finalize PNG zlib stream: {}", e))?;
+
+ let mut out = Vec::with_capacity(64 + idat.len());
+ out.extend_from_slice(PNG_SIG);
+
+ let mut ihdr = [0u8; 13];
+ ihdr[0..4].copy_from_slice(&width.to_be_bytes());
+ ihdr[4..8].copy_from_slice(&height.to_be_bytes());
+ ihdr[8] = 8; // bit depth
+ ihdr[9] = 6; // color type RGBA
+ ihdr[10] = 0; // compression method
+ ihdr[11] = 0; // filter method
+ ihdr[12] = 0; // interlace none
+ write_png_chunk(&mut out, b"IHDR", &ihdr)?;
+ write_png_chunk(&mut out, b"IDAT", &idat)?;
+ write_png_chunk(&mut out, b"IEND", &[])?;
+ Ok(out)
+}
+
+fn parse_png_dimensions(buf: &[u8]) -> Option<(u32, u32)> {
+ if buf.len() < 24 || buf.len() > MAX_PNG_BYTES {
+ return None;
+ }
+ if &buf[0..8] != PNG_SIG || &buf[12..16] != b"IHDR" {
+ return None;
+ }
+ let w = read_u32_be(buf, 16)?;
+ let h = read_u32_be(buf, 20)?;
+ if w == 0 || h == 0 || w > MAX_CANVAS_DIM || h > MAX_CANVAS_DIM {
+ return None;
+ }
+ Some((w, h))
+}
+
+fn png_paeth_predictor(a: u8, b: u8, c: u8) -> u8 {
+ let ai = a as i32;
+ let bi = b as i32;
+ let ci = c as i32;
+ let p = ai + bi - ci;
+ let pa = (p - ai).abs();
+ let pb = (p - bi).abs();
+ let pc = (p - ci).abs();
+ if pa <= pb && pa <= pc {
+ a
+ } else if pb <= pc {
+ b
+ } else {
+ c
+ }
+}
+
+/// Decodes standard non-interlaced 8-bit PNG (color types 0, 2, 4, 6) into RGBA8 to inspect
+/// expression color ("color" vs "gray") and dual-tone sub-color semantics on thumbnail fallbacks.
+fn decode_png_rgba8(buf: &[u8]) -> Option<(u32, u32, Vec<u8>)> {
+ let (w, h) = parse_png_dimensions(buf)?;
+ if buf.len() < 33 || w > MAX_MATERIAL_DIM || h > MAX_MATERIAL_DIM {
+ return None;
+ }
+ let bit_depth = buf[24];
+ let color_type = buf[25];
+ let compression = buf[26];
+ let filter_method = buf[27];
+ let interlace = buf[28];
+ if bit_depth != 8 || compression != 0 || filter_method != 0 || interlace != 0 {
+ return None;
+ }
+ let bpp: usize = match color_type {
+ 0 => 1, // Gray
+ 2 => 3, // RGB
+ 4 => 2, // Gray + Alpha
+ 6 => 4, // RGBA
+ _ => return None,
+ };
+
+ let mut idat = Vec::new();
+ let mut off = 8usize;
+ while off + 12 <= buf.len() {
+ let len = read_u32_be(buf, off)? as usize;
+ let data_end = off.checked_add(8)?.checked_add(len)?;
+ if data_end.checked_add(4)? > buf.len() {
+ return None;
+ }
+ let ctype = &buf[off + 4..off + 8];
+ if ctype == b"IDAT" {
+ idat.extend_from_slice(&buf[off + 8..data_end]);
+ }
+ off = data_end + 4;
+ if ctype == b"IEND" {
+ break;
+ }
+ }
+ if idat.is_empty() {
+ return None;
+ }
+
+ let stride = (w as usize).checked_mul(bpp)?;
+ let expected_raw = (h as usize).checked_mul(stride.checked_add(1)?)?;
+ if expected_raw == 0 || expected_raw > MAX_MATERIAL_RGBA_BYTES {
+ return None;
+ }
+ let raw = safe_unzlib(&idat, expected_raw)?;
+ if raw.len() != expected_raw {
+ return None;
+ }
+
+ let rgba_len = (w as usize).checked_mul(h as usize)?.checked_mul(4)?;
+ if rgba_len > MAX_MATERIAL_RGBA_BYTES {
+ return None;
+ }
+ let mut prev_row = vec![0u8; stride];
+ let mut cur_row = vec![0u8; stride];
+ let mut rgba = vec![0u8; rgba_len];
+
+ for y in 0..(h as usize) {
+ let row_in = &raw[y * (stride + 1)..(y + 1) * (stride + 1)];
+ let ftype = row_in[0];
+ let src = &row_in[1..];
+ match ftype {
+ 0 => cur_row.copy_from_slice(src),
+ 1 => {
+ for i in 0..stride {
+ let left = if i >= bpp { cur_row[i - bpp] } else { 0 };
+ cur_row[i] = src[i].wrapping_add(left);
+ }
+ }
+ 2 => {
+ for i in 0..stride {
+ cur_row[i] = src[i].wrapping_add(prev_row[i]);
+ }
+ }
+ 3 => {
+ for i in 0..stride {
+ let left = if i >= bpp { cur_row[i - bpp] as u16 } else { 0 };
+ let up = prev_row[i] as u16;
+ cur_row[i] = src[i].wrapping_add(((left + up) >> 1) as u8);
+ }
+ }
+ 4 => {
+ for i in 0..stride {
+ let left = if i >= bpp { cur_row[i - bpp] } else { 0 };
+ let up = prev_row[i];
+ let ul = if i >= bpp { prev_row[i - bpp] } else { 0 };
+ cur_row[i] = src[i].wrapping_add(png_paeth_predictor(left, up, ul));
+ }
+ }
+ _ => return None,
+ }
+
+ let dst_row = &mut rgba[y * (w as usize) * 4..(y + 1) * (w as usize) * 4];
+ match color_type {
+ 0 => {
+ for x in 0..(w as usize) {
+ let g = cur_row[x];
+ let di = x * 4;
+ dst_row[di] = g;
+ dst_row[di + 1] = g;
+ dst_row[di + 2] = g;
+ dst_row[di + 3] = 255;
+ }
+ }
+ 2 => {
+ for x in 0..(w as usize) {
+ let si = x * 3;
+ let di = x * 4;
+ dst_row[di] = cur_row[si];
+ dst_row[di + 1] = cur_row[si + 1];
+ dst_row[di + 2] = cur_row[si + 2];
+ dst_row[di + 3] = 255;
+ }
+ }
+ 4 => {
+ for x in 0..(w as usize) {
+ let si = x * 2;
+ let di = x * 4;
+ let g = cur_row[si];
+ dst_row[di] = g;
+ dst_row[di + 1] = g;
+ dst_row[di + 2] = g;
+ dst_row[di + 3] = cur_row[si + 1];
+ }
+ }
+ 6 => {
+ dst_row.copy_from_slice(&cur_row);
+ }
+ _ => return None,
+ }
+ std::mem::swap(&mut prev_row, &mut cur_row);
+ }
+
+ Some((w, h, rgba))
+}
+
+fn inspect_png_color_semantics(
+ png_bytes: &[u8],
+ xml_expr: Option<&str>,
+ is_paper_texture: bool,
+) -> (Option<String>, bool) {
+ let Some((_, _, rgba)) = decode_png_rgba8(png_bytes) else {
+ return (xml_expr.map(|s| s.to_string()), false);
+ };
+ let mut has_color = false;
+ let mut has_alpha = false;
+ for px in rgba.chunks_exact(4) {
+ let a = px[3];
+ if a < 240 {
+ has_alpha = true;
+ }
+ if a > 20 {
+ let r = px[0] as i32;
+ let g = px[1] as i32;
+ let b = px[2] as i32;
+ if (r - g).abs() > 20 || (g - b).abs() > 20 || (r - b).abs() > 20 {
+ has_color = true;
+ }
+ }
+ }
+ let expr = xml_expr
+ .map(|s| s.to_string())
+ .unwrap_or_else(|| if has_color { "color".to_string() } else { "gray".to_string() });
+ let has_sub_color = has_alpha && detect_has_sub_color(&rgba, &expr, is_paper_texture);
+ (Some(expr), has_sub_color)
+}
+
+struct TarEntry<'a> {
+ name: String,
+ data: &'a [u8],
+}
+
+fn parse_tar_cstr(slice: &[u8]) -> String {
+ let end = slice.iter().position(|&b| b == 0).unwrap_or(slice.len());
+ String::from_utf8_lossy(&slice[..end]).to_string()
+}
+
+fn parse_tar_size(field: &[u8]) -> Option<u64> {
+ if field.is_empty() {
+ return None;
+ }
+ // GNU base-256 binary size extension
+ if (field[0] & 0x80) != 0 {
+ let mut val: u64 = (field[0] & 0x7f) as u64;
+ for &b in &field[1..] {
+ val = val.checked_shl(8)?.checked_add(b as u64)?;
+ }
+ return Some(val);
+ }
+ let end = field.iter().position(|&b| b == 0).unwrap_or(field.len());
+ let s = std::str::from_utf8(&field[..end]).ok()?.trim();
+ if s.is_empty() {
+ return Some(0);
+ }
+ u64::from_str_radix(s, 8).ok()
+}
+
+/// Safe zero-copy USTAR/TAR archive parser with strict entry & size caps.
+fn parse_ustar_entries(buf: &[u8]) -> Vec<TarEntry<'_>> {
+ let mut entries = Vec::new();
+ let mut offset = 0usize;
+
+ while offset + 512 <= buf.len() && entries.len() < MAX_TAR_ENTRIES {
+ let header = &buf[offset..offset + 512];
+ if header.iter().all(|&b| b == 0) {
+ break;
+ }
+ let raw_name = parse_tar_cstr(&header[0..100]);
+ let full_name = if header.len() >= 500 && &header[257..262] == b"ustar" {
+ let prefix = parse_tar_cstr(&header[345..500]);
+ if !prefix.is_empty() {
+ format!("{}/{}", prefix.trim_end_matches('/'), raw_name)
+ } else {
+ raw_name
+ }
+ } else {
+ raw_name
+ };
+
+ let Some(size_u64) = parse_tar_size(&header[124..136]) else {
+ break;
+ };
+ if size_u64 > MAX_TAR_ENTRY_BYTES as u64 {
+ break;
+ }
+ let Ok(size) = usize::try_from(size_u64) else {
+ break;
+ };
+ let data_start = offset + 512;
+ let Some(data_end) = data_start.checked_add(size) else {
+ break;
+ };
+ if data_end > buf.len() {
+ break;
+ }
+
+ let typeflag = header[156];
+ let normalized_name = full_name
+ .replace('\\', "/")
+ .trim_start_matches("./")
+ .to_string();
+
+ // Keep regular files (0 or '0')
+ if (typeflag == 0 || typeflag == b'0') && !normalized_name.is_empty() {
+ entries.push(TarEntry {
+ name: normalized_name,
+ data: &buf[data_start..data_end],
+ });
+ }
+
+ let Some(padded) = size.div_ceil(512).checked_mul(512) else {
+ break;
+ };
+ let Some(next_off) = data_start.checked_add(padded) else {
+ break;
+ };
+ offset = next_off;
+ }
+
+ entries
+}
+
+#[derive(Debug, Default, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct ParsedLayerDataXml {
+ pub is_paper_texture: bool,
+ pub material_role: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub expression_color: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub width: Option<u32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub height: Option<u32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub tile_width: Option<u32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub tile_height: Option<u32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub tiling: Option<bool>,
+}
+
+fn decode_xml_text(bytes: &[u8]) -> String {
+ let capped = &bytes[..bytes.len().min(MAX_MATERIAL_XML_BYTES)];
+ if capped.len() >= 2 && capped[0] == 0xff && capped[1] == 0xfe {
+ let u16s: Vec<u16> = capped[2..]
+ .chunks_exact(2)
+ .map(|c| u16::from_le_bytes([c[0], c[1]]))
+ .collect();
+ return String::from_utf16_lossy(&u16s);
+ }
+ if capped.len() >= 2 && capped[0] == 0xfe && capped[1] == 0xff {
+ let u16s: Vec<u16> = capped[2..]
+ .chunks_exact(2)
+ .map(|c| u16::from_be_bytes([c[0], c[1]]))
+ .collect();
+ return String::from_utf16_lossy(&u16s);
+ }
+ String::from_utf8_lossy(capped).to_string()
+}
+
+fn normalize_expression_color_str(raw: &str) -> Option<&'static str> {
+ match raw.trim().to_ascii_lowercase().as_str() {
+ "monochrome" | "mono" | "binary" | "1bit" | "blackandwhite" | "bw" | "b&w" => {
+ Some("monochrome")
+ }
+ "gray" | "grey" | "grayscale" | "greyscale" | "8bit" => Some("gray"),
+ "color" | "colour" | "rgb" | "rgba" | "fullcolor" | "32bit" => Some("color"),
+ _ => None,
+ }
+}
+
+/// Extracts `(tag_lower, attrs_str, inner_text)` for simple leaf XML elements `<tag ...>text</tag>`.
+fn extract_xml_elements(xml: &str) -> Vec<(String, String, String)> {
+ let mut out = Vec::new();
+ let bytes = xml.as_bytes();
+ let mut pos = 0usize;
+ while pos < bytes.len() {
+ let Some(lt_rel) = xml[pos..].find('<') else {
+ break;
+ };
+ let lt = pos + lt_rel;
+ if lt + 1 >= bytes.len() {
+ break;
+ }
+ let next = bytes[lt + 1];
+ if next == b'/' || next == b'!' || next == b'?' {
+ pos = lt + 1;
+ continue;
+ }
+ let Some(gt_rel) = xml[lt + 1..].find('>') else {
+ break;
+ };
+ let gt = lt + 1 + gt_rel;
+ let open_inner = xml[lt + 1..gt].trim();
+ if open_inner.ends_with('/') {
+ // Self-closing tag: record with empty inner text so attributes can still be inspected
+ let stripped = open_inner.trim_end_matches('/').trim();
+ let mut parts = stripped.splitn(2, |c: char| c.is_ascii_whitespace());
+ if let Some(tag) = parts.next() {
+ let attrs = parts.next().unwrap_or("").trim().to_string();
+ out.push((tag.to_ascii_lowercase(), attrs, String::new()));
+ }
+ pos = gt + 1;
+ continue;
+ }
+ let mut parts = open_inner.splitn(2, |c: char| c.is_ascii_whitespace());
+ let Some(tag_raw) = parts.next() else {
+ pos = gt + 1;
+ continue;
+ };
+ let tag_lower = tag_raw.to_ascii_lowercase();
+ let attrs = parts.next().unwrap_or("").trim().to_string();
+
+ // Find matching closing tag `</tag>` case-insensitively
+ let close_needle = format!("</{}", tag_lower);
+ let after_open = gt + 1;
+ let xml_lower_slice = xml[after_open..].to_ascii_lowercase();
+ if let Some(close_rel) = xml_lower_slice.find(&close_needle) {
+ let inner = &xml[after_open..after_open + close_rel];
+ if !inner.contains('<') {
+ out.push((tag_lower, attrs, inner.trim().to_string()));
+ } else {
+ // Container tag (e.g. <datalist key="...">...</datalist>): still push with inner text for key-scoped search
+ out.push((tag_lower, attrs, inner.to_string()));
+ }
+ }
+ pos = gt + 1;
+ }
+ out
+}
+
+fn extract_xml_attr(attrs: &str, attr_name_lower: &str) -> Option<String> {
+ let lower = attrs.to_ascii_lowercase();
+ let needle = format!("{}=", attr_name_lower);
+ let idx = lower.find(&needle)?;
+ let rest = attrs[idx + needle.len()..].trim_start();
+ let quote = rest.chars().next()?;
+ if quote == '"' || quote == '\'' {
+ let after_q = &rest[1..];
+ let end = after_q.find(quote)?;
+ Some(after_q[..end].trim().to_string())
+ } else {
+ let end = rest
+ .find(|c: char| c.is_ascii_whitespace())
+ .unwrap_or(rest.len());
+ Some(rest[..end].trim().to_string())
+ }
+}
+
+fn parse_layer_data_xml(xml_bytes: &[u8]) -> ParsedLayerDataXml {
+ let mut parsed = ParsedLayerDataXml {
+ material_role: "BrushTip".to_string(),
+ ..Default::default()
+ };
+ let xml = decode_xml_text(xml_bytes);
+ if xml.trim().is_empty() {
+ return parsed;
+ }
+
+ let elements = extract_xml_elements(&xml);
+
+ // 1. Material role (PaperTexture vs BrushTip)
+ if xml.contains("<data>PaperTexture</data>") {
+ parsed.is_paper_texture = true;
+ parsed.material_role = "PaperTexture".to_string();
+ } else {
+ for (tag, attrs, inner) in &elements {
+ if matches!(
+ tag.as_str(),
+ "data" | "string" | "role" | "materialrole" | "materialtype" | "type" | "tag"
+ ) {
+ let v = inner.trim().to_ascii_lowercase();
+ if v == "papertexture" || v == "paper_texture" {
+ parsed.is_paper_texture = true;
+ parsed.material_role = "PaperTexture".to_string();
+ }
+ }
+ if let Some(role_attr) = extract_xml_attr(attrs, "role")
+ .or_else(|| extract_xml_attr(attrs, "materialrole"))
+ .or_else(|| extract_xml_attr(attrs, "type"))
+ {
+ let v = role_attr.to_ascii_lowercase();
+ if v == "papertexture" || v == "paper_texture" {
+ parsed.is_paper_texture = true;
+ parsed.material_role = "PaperTexture".to_string();
+ }
+ }
+ }
+ }
+
+ // 2. Expression Color (priority: explicit tag > explicit attr > keyed datalist > plist key/val > <data> token)
+ for (tag, attrs, inner) in &elements {
+ if matches!(
+ tag.as_str(),
+ "expressioncolor" | "colortype" | "colormode" | "expressionmode" | "color"
+ ) && !inner.contains('<')
+ {
+ if let Some(ec) = normalize_expression_color_str(inner) {
+ parsed.expression_color = Some(ec.to_string());
+ break;
+ }
+ }
+ for attr_key in ["expressioncolor", "colortype", "colormode", "color"] {
+ if let Some(v) = extract_xml_attr(attrs, attr_key) {
+ if let Some(ec) = normalize_expression_color_str(&v) {
+ parsed.expression_color = Some(ec.to_string());
+ break;
+ }
+ }
+ }
+ if parsed.expression_color.is_some() {
+ break;
+ }
+ }
+
+ if parsed.expression_color.is_none() {
+ for (tag, attrs, inner) in &elements {
+ if tag == "datalist" || tag == "data" || tag == "info" {
+ if let Some(key_val) = extract_xml_attr(attrs, "key") {
+ let kl = key_val.to_ascii_lowercase();
+ if kl.contains("color") || kl.contains("expression") {
+ if !inner.contains('<') {
+ if let Some(ec) = normalize_expression_color_str(inner) {
+ parsed.expression_color = Some(ec.to_string());
+ break;
+ }
+ } else {
+ for (sub_tag, _, sub_inner) in extract_xml_elements(inner) {
+ if matches!(sub_tag.as_str(), "data" | "string" | "value") {
+ if let Some(ec) = normalize_expression_color_str(&sub_inner) {
+ parsed.expression_color = Some(ec.to_string());
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ if parsed.expression_color.is_some() {
+ break;
+ }
+ }
+ }
+
+ if parsed.expression_color.is_none() {
+ for (tag, _, inner) in &elements {
+ if tag == "data" && !inner.contains('<') {
+ if let Some(ec) = normalize_expression_color_str(inner) {
+ parsed.expression_color = Some(ec.to_string());
+ break;
+ }
+ }
+ }
+ }
+
+ // 3. Optional dimension & tiling hints
+ let parse_dim = |s: &str| -> Option<u32> {
+ let v: f64 = s.trim().parse().ok()?;
+ if v.is_finite() && v >= 1.0 && v <= MAX_MATERIAL_DIM as f64 {
+ Some(v.round() as u32)
+ } else {
+ None
+ }
+ };
+ for (tag, attrs, inner) in &elements {
+ if !inner.contains('<') {
+ match tag.as_str() {
+ "width" | "canvaswidth" | "bitmapwidth" | "imagewidth" => {
+ if parsed.width.is_none() {
+ parsed.width = parse_dim(inner);
+ }
+ }
+ "height" | "canvasheight" | "bitmapheight" | "imageheight" => {
+ if parsed.height.is_none() {
+ parsed.height = parse_dim(inner);
+ }
+ }
+ "tilewidth" | "blockwidth" => {
+ if parsed.tile_width.is_none() {
+ parsed.tile_width = parse_dim(inner);
+ }
+ }
+ "tileheight" | "blockheight" => {
+ if parsed.tile_height.is_none() {
+ parsed.tile_height = parse_dim(inner);
+ }
+ }
+ "tiling" | "tile" | "repeat" => {
+ if parsed.tiling.is_none() {
+ match inner.trim().to_ascii_lowercase().as_str() {
+ "true" | "1" | "yes" => parsed.tiling = Some(true),
+ "false" | "0" | "no" => parsed.tiling = Some(false),
+ _ => {}
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+ if parsed.width.is_none() {
+ if let Some(w) = extract_xml_attr(attrs, "width").and_then(|s| parse_dim(&s)) {
+ parsed.width = Some(w);
+ }
+ }
+ if parsed.height.is_none() {
+ if let Some(h) = extract_xml_attr(attrs, "height").and_then(|s| parse_dim(&s)) {
+ parsed.height = Some(h);
+ }
+ }
+ }
+
+ parsed
+}
+
+/// Decodes a decompressed 256x256 CSP material tile into RGBA8 while preserving exact
+/// 2-channel monochrome/gray semantics and paper texture density.
+fn decode_csp_material_tile_to_rgba(
+ raw: &[u8],
+ default_fill: u32,
+ is_paper_texture: bool,
+) -> Option<Vec<u8>> {
+ // For PaperTexture 1-plane alpha-only (65536) or 1-bit (8192), always encode density in alpha
+ // with ink=0 (black) so compositing over white recovers exact height = 255 - density.
+ let eff_fill = if is_paper_texture && (raw.len() == TILE_PIXELS || raw.len() == 8192) {
+ 0
+ } else {
+ default_fill
+ };
+ decode_csp_tile_to_rgba(raw, eff_fill)
+}
+
+fn infer_expression_color_from_tile_len(len: usize) -> &'static str {
+ if len >= TILE_PIXELS * 4 {
+ "color"
+ } else if len >= TILE_PIXELS {
+ "gray"
+ } else {
+ "monochrome"
+ }
+}
+
+fn detect_has_sub_color(rgba: &[u8], expression_color: &str, is_paper_texture: bool) -> bool {
+ if is_paper_texture || (expression_color != "gray" && expression_color != "monochrome") {
+ return false;
+ }
+ let mut opaque_count: usize = 0;
+ let mut dark_count: usize = 0;
+ let mut light_count: usize = 0;
+ for px in rgba.chunks_exact(4) {
+ let a = px[3];
+ if a >= 16 {
+ opaque_count += 1;
+ let lum = ((77u32 * (px[0] as u32) + 150u32 * (px[1] as u32) + 29u32 * (px[2] as u32))
+ >> 8) as u8;
+ if lum <= 120 {
+ dark_count += 1;
+ }
+ if lum >= 160 {
+ light_count += 1;
+ }
+ }
+ }
+ if opaque_count == 0 {
+ return false;
+ }
+ let min_sig = (opaque_count / 500).max(1);
+ dark_count >= min_sig && light_count >= min_sig
+}
+
+struct DecodedLayerImage {
+ width: u32,
+ height: u32,
+ rgba: Vec<u8>,
+ expression_color: String,
+ has_sub_color: bool,
+}
+
+fn composite_pixel_over(dst: &mut [u8], src: &[u8]) {
+ let sa = src[3] as u32;
+ if sa == 0 {
+ return;
+ }
+ if sa == 255 || dst[3] == 0 {
+ dst[0] = src[0];
+ dst[1] = src[1];
+ dst[2] = src[2];
+ dst[3] = src[3];
+ return;
+ }
+ let da = dst[3] as u32;
+ let inv_sa = 255 - sa;
+ let out_a = sa + ((da * inv_sa + 127) / 255);
+ if out_a == 0 {
+ return;
+ }
+ let da_term = (da * inv_sa + 127) / 255;
+ for c in 0..3 {
+ let num = (src[c] as u32) * sa + (dst[c] as u32) * da_term;
+ dst[c] = ((num + out_a / 2) / out_a).min(255) as u8;
+ }
+ dst[3] = out_a.min(255) as u8;
+}
+
+/// Decodes a CSP `data/*.layer` (`CSFCHUNK` + SQLite + `Exta` `BlockData` tiles) into a
+/// full-resolution RGBA8 image with exact expression color and sub-color detection.
+fn decode_csp_layer_to_rgba(
+ layer_bytes: &[u8],
+ xml_meta: &ParsedLayerDataXml,
+) -> Option<DecodedLayerImage> {
+ let chunks = parse_csp_chunks(layer_bytes);
+ let exta_chunks = extract_exta_chunks(&chunks);
+ if exta_chunks.is_empty() {
+ return None;
+ }
+
+ struct LayerSource {
+ offscreen: OffscreenRecord,
+ offset_x: i32,
+ offset_y: i32,
+ }
+
+ let mut canvas_w_opt: Option<u32> = None;
+ let mut canvas_h_opt: Option<u32> = None;
+ let mut sources: Vec<LayerSource> = Vec::new();
+
+ if let Some(sqlite_data) = find_sqlite_data(&chunks, layer_bytes) {
+ if let Ok(conn) = open_readonly_mem_sqlite(sqlite_data) {
+ let tables = get_table_names(&conn);
+
+ for c in query_table(&conn, &tables, "Canvas") {
+ let cw = get_f64(&c, &["CanvasWidth"], 0.0).round() as i64;
+ let ch = get_f64(&c, &["CanvasHeight"], 0.0).round() as i64;
+ if cw > 0 && ch > 0 {
+ canvas_w_opt = Some(cw.clamp(1, MAX_MATERIAL_DIM as i64) as u32);
+ canvas_h_opt = Some(ch.clamp(1, MAX_MATERIAL_DIM as i64) as u32);
+ break;
+ }
+ }
+
+ 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
+ };
+ let mut full_scale_offscreens = HashSet::<i64>::new();
+ 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 {
+ let off_id = get_i64(&row, &["Offscreen"], 0);
+ let scale = get_f64(&row, &["ThisScale"], 1.0);
+ if off_id > 0 && (scale - 1.0).abs() < 0.001 {
+ full_scale_offscreens.insert(off_id);
+ }
+ mipmap_info_by_id.insert(
+ main_id,
+ MipmapInfoRecord {
+ offscreen_id: off_id,
+ this_scale: scale,
+ 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();
+ let mut all_offscreens = Vec::<OffscreenRecord>::new();
+ for row in query_table(&conn, &tables, "Offscreen") {
+ let main_id = get_i64(&row, &["MainId"], -1);
+ 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()),
+ };
+ if main_id >= 0 {
+ offscreen_by_id.insert(main_id, rec.clone());
+ }
+ if layer_id >= 0 {
+ offscreens_by_layer_id
+ .entry(layer_id)
+ .or_default()
+ .push(rec.clone());
+ }
+ all_offscreens.push(rec);
+ }
+
+ let resolve_mipmap = |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
+ };
+
+ let fallback_w = canvas_w_opt.or(xml_meta.width).unwrap_or(TILE_SIZE as u32);
+ let fallback_h = canvas_h_opt.or(xml_meta.height).unwrap_or(TILE_SIZE as u32);
+
+ let layer_rows = query_table(&conn, &tables, "Layer");
+ for row in &layer_rows {
+ let vis = get_i64(row, &["LayerVisibility"], 1);
+ if (vis & 1) == 0 {
+ continue;
+ }
+ let layer_folder = get_opt_i64(row, &["LayerFolder"]);
+ let first_child = get_i64(row, &["LayerFirstChildIndex"], 0);
+ if layer_folder.map_or(false, |v| v != 0) || first_child > 0 {
+ continue;
+ }
+ let main_id = get_i64(row, &["MainId"], -1);
+ let mm = get_i64(row, &["LayerRenderMipmap"], 0);
+ let off_opt = resolve_mipmap(mm)
+ .or_else(|| {
+ let direct = get_i64(row, &["LayerRenderOffscreen"], 0);
+ if direct > 0 {
+ offscreen_by_id.get(&direct).cloned()
+ } else {
+ None
+ }
+ })
+ .or_else(|| {
+ let cands = offscreens_by_layer_id.get(&main_id)?;
+ cands
+ .iter()
+ .filter(|c| {
+ !c.block_data_id.is_empty()
+ && exta_chunks.contains_key(&c.block_data_id)
+ })
+ .max_by_key(|c| {
+ let a = parse_offscreen_attribute(
+ c.attribute.as_deref(),
+ fallback_w,
+ fallback_h,
+ );
+ (
+ full_scale_offscreens.contains(&c.main_id) as u8,
+ (a.bitmap_width as u64) * (a.bitmap_height as u64),
+ )
+ })
+ .cloned()
+ });
+
+ if let Some(off) = off_opt {
+ let ox = (get_f64(row, &["LayerOffsetX", "LayerMoveOffsetX"], 0.0)
+ + get_f64(
+ row,
+ &["LayerRenderOffscrOffsetX", "LayerRenderOffsetX"],
+ 0.0,
+ ))
+ .round() as i32;
+ let oy = (get_f64(row, &["LayerOffsetY", "LayerMoveOffsetY"], 0.0)
+ + get_f64(
+ row,
+ &["LayerRenderOffscrOffsetY", "LayerRenderOffsetY"],
+ 0.0,
+ ))
+ .round() as i32;
+ sources.push(LayerSource {
+ offscreen: off,
+ offset_x: ox,
+ offset_y: oy,
+ });
+ }
+ }
+
+ if sources.is_empty() && !all_offscreens.is_empty() {
+ if let Some(best) = all_offscreens
+ .into_iter()
+ .filter(|c| {
+ !c.block_data_id.is_empty() && exta_chunks.contains_key(&c.block_data_id)
+ })
+ .max_by_key(|c| {
+ let a = parse_offscreen_attribute(
+ c.attribute.as_deref(),
+ fallback_w,
+ fallback_h,
+ );
+ (
+ full_scale_offscreens.contains(&c.main_id) as u8,
+ (a.bitmap_width as u64) * (a.bitmap_height as u64),
+ )
+ })
+ {
+ sources.push(LayerSource {
+ offscreen: best,
+ offset_x: 0,
+ offset_y: 0,
+ });
+ }
+ }
+ }
+ }
+
+ // Fallback when .layer has raw Exta block data without a SQLite Layer/Offscreen table
+ if sources.is_empty() && exta_chunks.len() == 1 {
+ if let Some((ext_id, _)) = exta_chunks.iter().next() {
+ sources.push(LayerSource {
+ offscreen: OffscreenRecord {
+ main_id: 0,
+ block_data_id: ext_id.clone(),
+ attribute: None,
+ },
+ offset_x: 0,
+ offset_y: 0,
+ });
+ }
+ }
+
+ if sources.is_empty() {
+ return None;
+ }
+
+ // Resolve output dimensions (Canvas -> Offscreen.Attribute -> layerData.xml -> default 256)
+ let first_attr = parse_offscreen_attribute(
+ sources[0].offscreen.attribute.as_deref(),
+ canvas_w_opt.or(xml_meta.width).unwrap_or(TILE_SIZE as u32),
+ canvas_h_opt.or(xml_meta.height).unwrap_or(TILE_SIZE as u32),
+ );
+ let out_w = canvas_w_opt
+ .or_else(|| {
+ if sources[0].offscreen.attribute.is_some() && first_attr.bitmap_width > 0 {
+ Some(first_attr.bitmap_width)
+ } else {
+ None
+ }
+ })
+ .or(xml_meta.width)
+ .unwrap_or(first_attr.bitmap_width)
+ .clamp(1, MAX_MATERIAL_DIM);
+ let out_h = canvas_h_opt
+ .or_else(|| {
+ if sources[0].offscreen.attribute.is_some() && first_attr.bitmap_height > 0 {
+ Some(first_attr.bitmap_height)
+ } else {
+ None
+ }
+ })
+ .or(xml_meta.height)
+ .unwrap_or(first_attr.bitmap_height)
+ .clamp(1, MAX_MATERIAL_DIM);
+
+ let total_bytes = (out_w as usize)
+ .checked_mul(out_h as usize)?
+ .checked_mul(4)?;
+ if total_bytes == 0 || total_bytes > MAX_MATERIAL_RGBA_BYTES {
+ return None;
+ }
+
+ let mut canvas_rgba = vec![0u8; total_bytes];
+ let mut decoded_block_count: usize = 0;
+ let mut inferred_expr: Option<&'static str> = None;
+ let out_w_i32 = out_w as i32;
+ let out_h_i32 = out_h as i32;
+
+ for (layer_idx, src) in sources.iter().enumerate() {
+ let payload = if let Some(&p) = exta_chunks.get(&src.offscreen.block_data_id) {
+ p
+ } else if src.offscreen.block_data_id.is_empty() && exta_chunks.len() == 1 {
+ *exta_chunks.values().next()?
+ } else {
+ continue;
+ };
+
+ let attr = parse_offscreen_attribute(src.offscreen.attribute.as_deref(), out_w, out_h);
+ let expected = (attr.block_grid_width as usize)
+ .saturating_mul(attr.block_grid_height as usize)
+ .clamp(1, MAX_BLOCKS_PER_LAYER);
+ let blocks = parse_block_data_payload_parallel(payload, expected);
+ if blocks.is_empty() {
+ continue;
+ }
+ let gw = attr.block_grid_width.max(1) as usize;
+ let is_paper = xml_meta.is_paper_texture;
+ let default_fill = attr.default_fill;
+
+ for (_, raw) in &blocks {
+ if inferred_expr.is_none() {
+ inferred_expr = Some(infer_expression_color_from_tile_len(raw.len()));
+ }
+ }
+
+ let decoded_tiles: Vec<(usize, Vec<u8>)> = blocks
+ .into_par_iter()
+ .filter_map(|(bidx, raw)| {
+ decode_csp_material_tile_to_rgba(&raw, default_fill, is_paper)
+ .map(|rgba| (bidx, rgba))
+ })
+ .collect();
+
+ for (bidx, tile_rgba) in decoded_tiles {
+ decoded_block_count += 1;
+ let col = (bidx % gw) as i32;
+ let row_i = (bidx / gw) as i32;
+ let tile_dx = col * (TILE_SIZE as i32) + src.offset_x;
+ let tile_dy = row_i * (TILE_SIZE as i32) + src.offset_y;
+
+ let x0 = (-tile_dx).max(0);
+ let y0 = (-tile_dy).max(0);
+ let x1 = (TILE_SIZE as i32)
+ .min(out_w_i32 - tile_dx)
+ .min(attr.bitmap_width as i32 - col * (TILE_SIZE as i32));
+ let y1 = (TILE_SIZE as i32)
+ .min(out_h_i32 - tile_dy)
+ .min(attr.bitmap_height as i32 - row_i * (TILE_SIZE as i32));
+ if x0 >= x1 || y0 >= y1 {
+ continue;
+ }
+
+ if layer_idx == 0 {
+ for sy in y0..y1 {
+ let dy = (tile_dy + sy) as usize;
+ let sx_start = x0 as usize;
+ let sx_end = x1 as usize;
+ let src_off = ((sy as usize) * TILE_SIZE + sx_start) * 4;
+ let dst_off = (dy * (out_w as usize) + (tile_dx + x0) as usize) * 4;
+ let copy_len = (sx_end - sx_start) * 4;
+ canvas_rgba[dst_off..dst_off + copy_len]
+ .copy_from_slice(&tile_rgba[src_off..src_off + copy_len]);
+ }
+ } else {
+ for sy in y0..y1 {
+ let dy = (tile_dy + sy) as usize;
+ for sx in x0..x1 {
+ let dx = (tile_dx + sx) as usize;
+ let si = ((sy as usize) * TILE_SIZE + (sx as usize)) * 4;
+ let di = (dy * (out_w as usize) + dx) * 4;
+ composite_pixel_over(&mut canvas_rgba[di..di + 4], &tile_rgba[si..si + 4]);
+ }
+ }
+ }
+ }
+ }
+
+ if decoded_block_count == 0 {
+ return None;
+ }
+
+ let expression_color = xml_meta
+ .expression_color
+ .clone()
+ .unwrap_or_else(|| inferred_expr.unwrap_or("gray").to_string());
+ let has_sub_color =
+ detect_has_sub_color(&canvas_rgba, &expression_color, xml_meta.is_paper_texture);
+
+ Some(DecodedLayerImage {
+ width: out_w,
+ height: out_h,
+ rgba: canvas_rgba,
+ expression_color,
+ has_sub_color,
+ })
+}
+
+struct DecodedMaterialBlob {
+ png_bytes: Option<Vec<u8>>,
+ width: Option<u32>,
+ height: Option<u32>,
+ expression_color: Option<String>,
+ is_paper_texture: bool,
+ has_sub_color: bool,
+ source: &'static str, // "layer" | "thumbnail" | "none"
+ tar_entry_summaries: Vec<(String, usize)>,
+ xml_meta: ParsedLayerDataXml,
+}
+
+fn decode_material_file_blob(file_data: &[u8]) -> DecodedMaterialBlob {
+ let tar_entries = parse_ustar_entries(file_data);
+ let tar_entry_summaries: Vec<(String, usize)> = tar_entries
+ .iter()
+ .map(|e| (e.name.clone(), e.data.len()))
+ .collect();
+
+ if !tar_entries.is_empty() {
+ let xml_meta = tar_entries
+ .iter()
+ .find(|e| {
+ let lower = e.name.to_ascii_lowercase();
+ lower.ends_with("icedata/layerdata.xml") || lower.ends_with("layerdata.xml")
+ })
+ .map(|e| parse_layer_data_xml(e.data))
+ .unwrap_or_else(|| ParsedLayerDataXml {
+ material_role: "BrushTip".to_string(),
+ ..Default::default()
+ });
+
+ // 1. Primary path: locate and decode full-resolution data/*.layer
+ let layer_entry = tar_entries
+ .iter()
+ .find(|e| e.name.to_ascii_lowercase() == "data/material_0.layer")
+ .or_else(|| {
+ tar_entries.iter().find(|e| {
+ let l = e.name.to_ascii_lowercase();
+ l.starts_with("data/") && l.ends_with(".layer")
+ })
+ })
+ .or_else(|| {
+ tar_entries
+ .iter()
+ .find(|e| e.name.to_ascii_lowercase().ends_with(".layer"))
+ });
+
+ if let Some(le) = layer_entry {
+ if let Some(decoded) = decode_csp_layer_to_rgba(le.data, &xml_meta) {
+ if let Ok(png) = encode_rgba8_to_png(decoded.width, decoded.height, &decoded.rgba) {
+ return DecodedMaterialBlob {
+ png_bytes: Some(png),
+ width: Some(decoded.width),
+ height: Some(decoded.height),
+ expression_color: Some(decoded.expression_color),
+ is_paper_texture: xml_meta.is_paper_texture,
+ has_sub_color: decoded.has_sub_color,
+ source: "layer",
+ tar_entry_summaries,
+ xml_meta,
+ };
+ }
+ }
+ }
+
+ // 2. Strict fallback: thumbnail.png ONLY when data/*.layer is missing or unreadable
+ let thumb_entry = tar_entries
+ .iter()
+ .find(|e| e.name.to_ascii_lowercase().ends_with("thumbnail.png"))
+ .or_else(|| {
+ tar_entries
+ .iter()
+ .find(|e| e.name.to_ascii_lowercase().ends_with(".png"))
+ });
+ if let Some(te) = thumb_entry {
+ if let Some((w, h)) = parse_png_dimensions(te.data) {
+ let (expression_color, has_sub_color) = inspect_png_color_semantics(
+ te.data,
+ xml_meta.expression_color.as_deref(),
+ xml_meta.is_paper_texture,
+ );
+ return DecodedMaterialBlob {
+ png_bytes: Some(te.data.to_vec()),
+ width: Some(w),
+ height: Some(h),
+ expression_color,
+ is_paper_texture: xml_meta.is_paper_texture,
+ has_sub_color,
+ source: "thumbnail",
+ tar_entry_summaries,
+ xml_meta,
+ };
+ }
+ }
+
+ return DecodedMaterialBlob {
+ png_bytes: None,
+ width: xml_meta.width,
+ height: xml_meta.height,
+ expression_color: xml_meta.expression_color.clone(),
+ is_paper_texture: xml_meta.is_paper_texture,
+ has_sub_color: false,
+ source: "none",
+ tar_entry_summaries,
+ xml_meta,
+ };
+ }
+
+ // Raw PNG fallback if MaterialFile.FileData is directly a PNG (non-TAR)
+ if let Some((w, h)) = parse_png_dimensions(file_data) {
+ return DecodedMaterialBlob {
+ png_bytes: Some(file_data.to_vec()),
+ width: Some(w),
+ height: Some(h),
+ expression_color: None,
+ is_paper_texture: false,
+ has_sub_color: false,
+ source: "thumbnail",
+ tar_entry_summaries,
+ xml_meta: ParsedLayerDataXml {
+ material_role: "BrushTip".to_string(),
+ ..Default::default()
+ },
+ };
+ }
+
+ DecodedMaterialBlob {
+ png_bytes: None,
+ width: None,
+ height: None,
+ expression_color: None,
+ is_paper_texture: false,
+ has_sub_color: false,
+ source: "none",
+ tar_entry_summaries,
+ xml_meta: ParsedLayerDataXml {
+ material_role: "BrushTip".to_string(),
+ ..Default::default()
+ },
+ }
+}
+
+fn format_node_uuid(row: &SqlRow) -> Option<String> {
+ for &key in &["NodeUuid", "NodeUUID", "Uuid", "UUID"] {
+ if let Some(val) = row.get(key) {
+ match val {
+ Value::Text(s) => {
+ let t = s.trim().trim_end_matches('\0');
+ if !t.is_empty() {
+ return Some(t.to_string());
+ }
+ }
+ Value::Blob(b) if !b.is_empty() => {
+ if b.len() == 16 {
+ return Some(format!(
+ "{}-{}-{}-{}-{}",
+ hex::encode(&b[0..4]),
+ hex::encode(&b[4..6]),
+ hex::encode(&b[6..8]),
+ hex::encode(&b[8..10]),
+ hex::encode(&b[10..16]),
+ ));
+ }
+ if b.iter().all(|&c| c == 0 || (0x20..=0x7e).contains(&c)) {
+ let s = String::from_utf8_lossy(b)
+ .trim()
+ .trim_end_matches('\0')
+ .to_string();
+ if !s.is_empty() {
+ return Some(s);
+ }
+ }
+ return Some(hex::encode(b));
+ }
+ _ => {}
+ }
+ }
+ }
+ None
+}
+
+fn get_case_insensitive_opt_i64(row: &SqlRow, target_keys_lower: &[&str]) -> Option<i64> {
+ for (k, v) in row {
+ let kl = k.to_ascii_lowercase();
+ if target_keys_lower.iter().any(|&t| t == kl) {
+ match v {
+ Value::Integer(i) => return Some(*i),
+ Value::Real(f) if f.is_finite() => return Some(f.trunc() as i64),
+ _ => {}
+ }
+ }
+ }
+ None
+}
+
+struct SelectedSutNodesAndVariants {
+ node_name: Option<String>,
+ node_uuid: Option<String>,
+ variant_id: Option<i64>,
+ dual_variant_id: Option<i64>,
+ node_init_variant_id: Option<i64>,
+ primary_variant: Option<SqlRow>,
+ dual_variant: Option<SqlRow>,
+ all_nodes: Vec<SqlRow>,
+ all_variants: Vec<SqlRow>,
+}
+
+fn select_sut_nodes_and_variants(
+ conn: &Connection,
+ tables: &HashSet<String>,
+) -> SelectedSutNodesAndVariants {
+ let all_nodes = query_table(conn, tables, "Node");
+ let all_variants = query_table(conn, tables, "Variant");
+
+ let mut variant_by_variant_id = HashMap::<i64, usize>::new();
+ let mut variant_by_pw_id = HashMap::<i64, usize>::new();
+ for (idx, vrow) in all_variants.iter().enumerate() {
+ if let Some(vid) = get_opt_i64(vrow, &["VariantID"]) {
+ variant_by_variant_id.entry(vid).or_insert(idx);
+ }
+ if let Some(pwid) = get_opt_i64(vrow, &["_PW_ID"]) {
+ variant_by_pw_id.entry(pwid).or_insert(idx);
+ }
+ }
+
+ let resolve_variant_idx = |vid: i64| -> Option<usize> {
+ variant_by_variant_id
+ .get(&vid)
+ .or_else(|| variant_by_pw_id.get(&vid))
+ .copied()
+ };
+
+ // Priority 1: Node row with NodeVariantId > 0 matching an existing VariantID / _PW_ID
+ let chosen_node_idx: Option<usize> = all_nodes
+ .iter()
+ .enumerate()
+ .filter(|(_, n)| {
+ get_opt_i64(n, &["NodeVariantId"])
+ .filter(|&v| v > 0)
+ .and_then(resolve_variant_idx)
+ .is_some()
+ })
+ .max_by_key(|(idx, n)| {
+ let has_name = !get_str(n, &["NodeName"], "").trim().is_empty();
+ // Prefer named node, tie-break by earlier row index
+ (has_name as u8, std::cmp::Reverse(*idx))
+ })
+ .map(|(idx, _)| idx)
+ // Priority 2: any Node row with NodeVariantId > 0
+ .or_else(|| {
+ all_nodes
+ .iter()
+ .position(|n| get_opt_i64(n, &["NodeVariantId"]).map_or(false, |v| v > 0))
+ })
+ // Priority 3: Node row with NodeInitVariantId > 0 matching a Variant row
+ .or_else(|| {
+ all_nodes.iter().position(|n| {
+ get_opt_i64(n, &["NodeInitVariantId"])
+ .filter(|&v| v > 0)
+ .and_then(resolve_variant_idx)
+ .is_some()
+ })
+ })
+ // Priority 4: first Node row with non-empty NodeName, or first row
+ .or_else(|| {
+ all_nodes
+ .iter()
+ .position(|n| !get_str(n, &["NodeName"], "").trim().is_empty())
+ })
+ .or_else(|| if !all_nodes.is_empty() { Some(0) } else { None });
+
+ let chosen_node = chosen_node_idx.and_then(|i| all_nodes.get(i));
+
+ let node_name = chosen_node
+ .and_then(|n| {
+ let s = get_str(n, &["NodeName"], "");
+ let t = s.trim();
+ if t.is_empty() {
+ None
+ } else {
+ Some(t.to_string())
+ }
+ })
+ .or_else(|| {
+ all_nodes.iter().find_map(|n| {
+ let s = get_str(n, &["NodeName"], "");
+ let t = s.trim();
+ if t.is_empty() {
+ None
+ } else {
+ Some(t.to_string())
+ }
+ })
+ });
+
+ let node_uuid = chosen_node.and_then(format_node_uuid);
+ let node_variant_id = chosen_node
+ .and_then(|n| get_opt_i64(n, &["NodeVariantId"]))
+ .filter(|&v| v > 0);
+ let node_init_variant_id = chosen_node
+ .and_then(|n| get_opt_i64(n, &["NodeInitVariantId"]))
+ .filter(|&v| v > 0);
+
+ let primary_idx = node_variant_id
+ .and_then(resolve_variant_idx)
+ .or_else(|| node_init_variant_id.and_then(resolve_variant_idx))
+ .or_else(|| {
+ if !all_variants.is_empty() {
+ Some(0)
+ } else {
+ None
+ }
+ });
+
+ let variant_id = node_variant_id.or_else(|| {
+ primary_idx
+ .and_then(|i| all_variants.get(i))
+ .and_then(|v| get_opt_i64(v, &["VariantID", "_PW_ID"]))
+ });
+
+ let init_variant_idx = node_init_variant_id.and_then(resolve_variant_idx);
+
+ // Secondary / Dual Variant resolution
+ let dual_idx: Option<usize> = primary_idx.and_then(|p_idx| {
+ let p_row = &all_variants[p_idx];
+ // Priority 1: Explicit DualBrushVariantId / DualVariantId / SecondaryVariantId reference
+ if let Some(dvid) = get_case_insensitive_opt_i64(
+ p_row,
+ &[
+ "dualbrushvariantid",
+ "dualvariantid",
+ "brushdualvariantid",
+ "secondaryvariantid",
+ "subvariantid",
+ ],
+ )
+ .filter(|&v| v > 0)
+ {
+ if let Some(idx) = resolve_variant_idx(dvid) {
+ if idx != p_idx {
+ return Some(idx);
+ }
+ }
+ }
+ // Priority 2: Another Node row pointing to a distinct Variant row
+ for (n_idx, n) in all_nodes.iter().enumerate() {
+ if Some(n_idx) == chosen_node_idx {
+ continue;
+ }
+ if let Some(nvid) = get_opt_i64(n, &["NodeVariantId"]).filter(|&v| v > 0) {
+ if let Some(idx) = resolve_variant_idx(nvid) {
+ if idx != p_idx {
+ return Some(idx);
+ }
+ }
+ }
+ }
+ // Priority 3: Another Variant row distinct from both primary and NodeInitVariantId
+ if let Some(idx) = (0..all_variants.len())
+ .find(|&idx| idx != p_idx && Some(idx) != init_variant_idx)
+ {
+ return Some(idx);
+ }
+ // Priority 4: NodeInitVariantId pointing to a distinct Variant row
+ if let Some(idx) = init_variant_idx {
+ if idx != p_idx {
+ return Some(idx);
+ }
+ }
+ None
+ });
+
+ let primary_variant = primary_idx.map(|i| all_variants[i].clone());
+ let dual_variant = dual_idx.map(|i| all_variants[i].clone());
+ let dual_variant_id = dual_variant
+ .as_ref()
+ .and_then(|v| get_opt_i64(v, &["VariantID", "_PW_ID"]));
+
+ SelectedSutNodesAndVariants {
+ node_name,
+ node_uuid,
+ variant_id,
+ dual_variant_id,
+ node_init_variant_id,
+ primary_variant,
+ dual_variant,
+ all_nodes,
+ all_variants,
+ }
+}
+
+fn split_variant_row(
+ row: &SqlRow,
+ blobs: &mut Vec<u8>,
+) -> Result<(HashMap<String, serde_json::Value>, HashMap<String, SutVariantBlobRef>), String> {
+ let mut scalars = HashMap::new();
+ let mut blob_refs = HashMap::new();
+ for (cname, val) in row {
+ match val {
+ Value::Null => {}
+ Value::Integer(i) => {
+ scalars.insert(cname.clone(), serde_json::Value::from(*i));
+ }
+ Value::Real(f) if f.is_finite() => {
+ scalars.insert(cname.clone(), serde_json::Value::from(*f));
+ }
+ Value::Text(t) => {
+ scalars.insert(cname.clone(), serde_json::Value::from(t.clone()));
+ }
+ 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);
+ blob_refs.insert(cname.clone(), SutVariantBlobRef { offset: off, len });
+ }
+ _ => {}
+ }
+ }
+ Ok((scalars, blob_refs))
+}
+
+#[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,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub decoded_png_offset: Option<u32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub decoded_png_len: Option<u32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub width: Option<u32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub height: Option<u32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub expression_color: Option<String>,
+ pub is_paper_texture: bool,
+ pub has_sub_color: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub decoded_from_layer: Option<bool>,
+}
+
+#[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 SutMaterialRow {
+pub struct SutExtractMeta {
+ pub node_name: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub node_uuid: Option<String>,
+ pub variant_id: Option<i64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub node_init_variant_id: Option<i64>,
+ pub variant_scalars: HashMap<String, serde_json::Value>,
+ pub variant_blobs: HashMap<String, SutVariantBlobRef>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub dual_variant_scalars: Option<HashMap<String, serde_json::Value>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub dual_variant_blobs: Option<HashMap<String, SutVariantBlobRef>>,
+ pub materials: Vec<SutMaterialRow>,
+}
+
+/// Extracts Node, Variant (primary + optional dual/secondary), and full-resolution decoded
+/// 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 selected = select_sut_nodes_and_variants(&conn, &tables);
+
+ let mut blobs = Vec::<u8>::new();
+ let (variant_scalars, variant_blobs) = if let Some(ref pv) = selected.primary_variant {
+ split_variant_row(pv, &mut blobs)?
+ } else {
+ (HashMap::new(), HashMap::new())
+ };
+
+ let (dual_variant_scalars, dual_variant_blobs) = if let Some(ref dv) = selected.dual_variant {
+ let (ds, db) = split_variant_row(dv, &mut blobs)?;
+ (Some(ds), Some(db))
+ } else {
+ (None, None)
+ };
+
+ let mut raw_materials: Vec<(String, String, Vec<u8>, String)> = 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().take(MAX_SUT_MATERIALS) {
+ if !item.2.is_empty() {
+ raw_materials.push(item);
+ }
+ }
+ }
+ }
+ }
+
+ // Decode all MaterialFile TAR + data/*.layer archives in parallel via Rayon
+ let decoded_materials: Vec<((String, String, Vec<u8>, String), DecodedMaterialBlob)> =
+ raw_materials
+ .into_par_iter()
+ .map(|item| {
+ let decoded = decode_material_file_blob(&item.2);
+ (item, decoded)
+ })
+ .collect();
+
+ let mut materials = Vec::with_capacity(decoded_materials.len());
+ for ((pw_id, original_path, data, catalog_path), decoded) in decoded_materials {
+ 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);
+
+ let (decoded_png_offset, decoded_png_len) = if let Some(png) = decoded.png_bytes {
+ let png_off = u32::try_from(blobs.len())
+ .map_err(|_| "SUT decoded PNG payload exceeds 4 GB".to_string())?;
+ let png_len = u32::try_from(png.len())
+ .map_err(|_| "SUT decoded PNG exceeds 4 GB".to_string())?;
+ blobs.extend_from_slice(&png);
+ (Some(png_off), Some(png_len))
+ } else {
+ (None, None)
+ };
+
+ materials.push(SutMaterialRow {
+ pw_id,
+ original_path,
+ catalog_path,
+ file_data_offset: off,
+ file_data_len: len,
+ decoded_png_offset,
+ decoded_png_len,
+ width: decoded.width,
+ height: decoded.height,
+ expression_color: decoded.expression_color,
+ is_paper_texture: decoded.is_paper_texture,
+ has_sub_color: decoded.has_sub_color,
+ decoded_from_layer: Some(decoded.source == "layer"),
+ });
+ }
+
+ let meta = SutExtractMeta {
+ node_name: selected.node_name,
+ node_uuid: selected.node_uuid,
+ variant_id: selected.variant_id,
+ node_init_variant_id: selected.node_init_variant_id,
+ variant_scalars,
+ variant_blobs,
+ dual_variant_scalars,
+ dual_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)
+}
+
+fn sql_row_to_debug_json(row: &SqlRow) -> serde_json::Value {
+ let mut keys: Vec<&String> = row.keys().collect();
+ keys.sort();
+ let mut map = serde_json::Map::new();
+ for k in keys {
+ let v = match &row[k] {
+ Value::Null => serde_json::Value::Null,
+ Value::Integer(i) => serde_json::Value::from(*i),
+ Value::Real(f) => {
+ if f.is_finite() {
+ serde_json::Value::from(*f)
+ } else {
+ serde_json::Value::Null
+ }
+ }
+ Value::Text(s) => serde_json::Value::from(s.clone()),
+ Value::Blob(b) => {
+ let preview_len = b.len().min(32);
+ serde_json::json!({
+ "byteLength": b.len(),
+ "hexPreview": hex::encode(&b[..preview_len]),
+ })
+ }
+ };
+ map.insert(k.clone(), v);
+ }
+ serde_json::Value::Object(map)
+}
+
+/// Dumps all `Node`, `Variant`, and `MaterialFile` metadata (including TAR entries,
+/// parsed `icedata/layerData.xml`, and `data/*.layer` decode summary) of any `.sut` file
+/// as structured JSON for debugging and inspection.
+#[allow(dead_code)]
+pub fn dump_sut_metadata_json(bytes: &[u8]) -> Result<serde_json::Value, 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 sorted_tables: Vec<String> = tables.iter().cloned().collect();
+ sorted_tables.sort();
+
+ let selected = select_sut_nodes_and_variants(&conn, &tables);
+
+ let nodes_json: Vec<serde_json::Value> = selected
+ .all_nodes
+ .iter()
+ .map(sql_row_to_debug_json)
+ .collect();
+ let variants_json: Vec<serde_json::Value> = selected
+ .all_variants
+ .iter()
+ .map(sql_row_to_debug_json)
+ .collect();
+
+ let mut materials_json = Vec::new();
+ for row in query_table(&conn, &tables, "MaterialFile")
+ .into_iter()
+ .take(MAX_SUT_MATERIALS)
+ {
+ let pw_id = match row.get("_PW_ID") {
+ Some(Value::Integer(i)) => i.to_string(),
+ Some(Value::Text(s)) => s.clone(),
+ _ => String::new(),
+ };
+ let original_path = get_str(&row, &["OriginalPath"], "");
+ let catalog_path = get_str(&row, &["CatalogPath"], "");
+ let file_data = get_bytes(&row, &["FileData"]).unwrap_or(&[]);
+ let decoded = decode_material_file_blob(file_data);
+ let tar_entries: Vec<serde_json::Value> = decoded
+ .tar_entry_summaries
+ .iter()
+ .map(|(name, size)| serde_json::json!({ "name": name, "size": size }))
+ .collect();
+ materials_json.push(serde_json::json!({
+ "pwId": pw_id,
+ "originalPath": original_path,
+ "catalogPath": catalog_path,
+ "fileDataLen": file_data.len(),
+ "tarEntries": tar_entries,
+ "layerDataXml": decoded.xml_meta,
+ "decoded": {
+ "source": decoded.source,
+ "width": decoded.width,
+ "height": decoded.height,
+ "expressionColor": decoded.expression_color,
+ "isPaperTexture": decoded.is_paper_texture,
+ "hasSubColor": decoded.has_sub_color,
+ "pngBytes": decoded.png_bytes.as_ref().map(|p| p.len()),
+ }
+ }));
+ }
+
+ Ok(serde_json::json!({
+ "tables": sorted_tables,
+ "selected": {
+ "nodeName": selected.node_name,
+ "nodeUuid": selected.node_uuid,
+ "variantId": selected.variant_id,
+ "dualVariantId": selected.dual_variant_id,
+ "nodeInitVariantId": selected.node_init_variant_id,
+ "hasDualVariant": selected.dual_variant.is_some(),
+ },
+ "nodes": nodes_json,
+ "variants": variants_json,
+ "materials": materials_json,
+ }))
+}
+
+// ---------------------------------------------------------------------------
+// .sut Coverage Inspector (mapped vs unmapped Variant columns & material report)
+// ---------------------------------------------------------------------------
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SutMappedColumnReport {
+ pub column: String,
+ pub ink_studio_field: String,
+ pub raw_value: serde_json::Value,
+ pub parsed_value: serde_json::Value,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SutUnmappedColumnReport {
+ pub column: String,
+ pub value: serde_json::Value,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SutVariantCoverageReport {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub variant_id: Option<i64>,
+ pub total_columns: usize,
+ pub mapped_count: usize,
+ pub unmapped_non_default_count: usize,
+ pub unmapped_default_count: usize,
+ pub coverage_percent: f64,
+ pub mapped_columns: Vec<SutMappedColumnReport>,
+ pub unmapped_non_default_columns: Vec<SutUnmappedColumnReport>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SutMaterialInspectionEntry {
pub pw_id: String,
pub original_path: String,
pub catalog_path: String,
- pub file_data_offset: u32,
- pub file_data_len: u32,
+ pub file_data_len: usize,
+ pub decoded_source: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub width: Option<u32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub height: Option<u32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub expression_color: Option<String>,
+ pub is_paper_texture: bool,
+ pub has_sub_color: bool,
+ pub tar_entries: Vec<(String, usize)>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SutInspectionSelection {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub node_name: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub node_uuid: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub variant_id: Option<i64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub dual_variant_id: Option<i64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub node_init_variant_id: Option<i64>,
+ pub has_dual_variant: bool,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SutInspectionReport {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub file: Option<String>,
+ pub tables: Vec<String>,
+ pub selected: SutInspectionSelection,
+ pub nodes: Vec<serde_json::Value>,
+ pub materials: Vec<SutMaterialInspectionEntry>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub primary_variant: Option<SutVariantCoverageReport>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub dual_variant: Option<SutVariantCoverageReport>,
+ pub warnings: Vec<String>,
+}
+
+fn sql_value_to_debug_json(val: &Value) -> serde_json::Value {
+ match val {
+ Value::Null => serde_json::Value::Null,
+ Value::Integer(i) => serde_json::Value::from(*i),
+ Value::Real(f) => {
+ if f.is_finite() {
+ serde_json::Value::from(*f)
+ } else {
+ serde_json::Value::Null
+ }
+ }
+ Value::Text(s) => serde_json::Value::from(s.clone()),
+ Value::Blob(b) => {
+ let preview_len = b.len().min(32);
+ serde_json::json!({
+ "byteLength": b.len(),
+ "hexPreview": hex::encode(&b[..preview_len]),
+ })
+ }
+ }
+}
+
+fn is_sql_value_non_default(val: &Value) -> bool {
+ match val {
+ Value::Null => false,
+ Value::Integer(i) => *i != 0,
+ Value::Real(f) => f.is_finite() && f.abs() > 1e-9,
+ Value::Text(s) => !s.trim().is_empty(),
+ Value::Blob(b) => !b.is_empty() && b.iter().any(|&x| x != 0),
+ }
+}
+
+fn parse_effector_summary_json(blob: &[u8]) -> serde_json::Value {
+ if blob.len() < 44 {
+ return serde_json::json!({ "byteLength": blob.len() });
+ }
+ let header_len = read_u32_be(blob, 0).unwrap_or(48) as usize;
+ let flags = read_u32_be(blob, 8).unwrap_or(0);
+ let read_i32_be = |off: usize| -> i32 { read_u32_be(blob, off).unwrap_or(0) as i32 };
+ let p_min = (read_i32_be(12).max(0) as f64 / 100.0).clamp(0.0, 1.0);
+ let t_min = (read_i32_be(16).max(0) as f64 / 100.0).clamp(0.0, 1.0);
+ let v_min = (read_i32_be(20).max(0) as f64 / 100.0).clamp(0.0, 1.0);
+ let r_min = (read_i32_be(24).max(0) as f64 / 100.0).clamp(0.0, 1.0);
+ let p_curve_len = read_u32_be(blob, 32).unwrap_or(0) as usize;
+ let t_curve_len = read_u32_be(blob, 36).unwrap_or(0) as usize;
+ let raw_tilt_max = if header_len >= 48 && blob.len() >= 44 {
+ read_u32_be(blob, 40).unwrap_or(100)
+ } else {
+ 100
+ };
+ let tilt_max = if raw_tilt_max > 100 && raw_tilt_max <= 1000 {
+ raw_tilt_max as f64 / 100.0
+ } else {
+ 1.0
+ };
+ let v_curve_len = read_u32_be(blob, 44).unwrap_or(0) as usize;
+ let t_inv = (flags & 0x2200) != 0;
+ let v_inv = (flags & 0x8800) != 0;
+
+ let mut curve_count = 0usize;
+ let mut off = if header_len >= 44 && header_len <= blob.len() { header_len } else { 48 };
+ if off + 12 <= blob.len()
+ && read_u32_be(blob, off) != Some(12)
+ && blob.len() >= 56
+ && read_u32_be(blob, 44) == Some(12)
+ {
+ off = 44;
+ }
+ while off + 12 <= blob.len() {
+ let magic = read_u32_be(blob, off).unwrap_or(0);
+ let n_pts = read_u32_be(blob, off + 4).unwrap_or(0) as usize;
+ let pt_sz = read_u32_be(blob, off + 8).unwrap_or(0) as usize;
+ if magic != 12 || pt_sz != 16 || n_pts > 256 || off + 12 + n_pts * 16 > blob.len() {
+ break;
+ }
+ curve_count += 1;
+ off += 12 + n_pts * 16;
+ }
+
+ serde_json::json!({
+ "usePressure": (flags & 0x10) != 0,
+ "useTilt": (flags & 0x20) != 0,
+ "useVelocity": (flags & 0x40) != 0,
+ "useRandom": (flags & (0x80 | 0x01)) != 0,
+ "pressureMin": p_min,
+ "tiltMin": t_min,
+ "tiltMax": tilt_max,
+ "invertTilt": t_inv,
+ "velocityMin": v_min,
+ "invertVelocity": v_inv,
+ "randomMin": r_min,
+ "maxValue": 1.0,
+ "curveCount": curve_count,
+ "pressureCurveBytes": p_curve_len,
+ "tiltCurveBytes": t_curve_len,
+ "velocityCurveBytes": v_curve_len,
+ "sourceFlagsHex": format!("0x{:x}", flags),
+ })
+}
+
+fn parse_inout_target_summary_json(blob: &[u8]) -> serde_json::Value {
+ if blob.len() < 12 {
+ return serde_json::json!({ "byteLength": blob.len() });
+ }
+ let magic = read_u32_be(blob, 0).unwrap_or(0);
+ let count = read_u32_be(blob, 4).unwrap_or(0) as usize;
+ let entry_size = read_u32_be(blob, 8).unwrap_or(0) as usize;
+ if magic != 12 || entry_size != 12 || 12 + count * 12 > blob.len() {
+ return serde_json::json!({ "byteLength": blob.len() });
+ }
+ let mut targets = Vec::new();
+ for i in 0..count {
+ let off = 12 + i * 12;
+ let param_id = read_u32_be(blob, off).unwrap_or(0);
+ let enabled = read_u32_be(blob, off + 4).unwrap_or(0) != 0;
+ let val = read_u32_be(blob, off + 8).unwrap_or(0);
+ if !enabled {
+ continue;
+ }
+ let name = match param_id {
+ 0x03e9 | 0x03fc => "opacity",
+ 0x03fd => "size",
+ 0x0411 => "density",
+ 0x043a => "amountOfPaint",
+ 0x043c => "densityOfPaint",
+ _ => "other",
+ };
+ targets.push(serde_json::json!({
+ "paramIdHex": format!("0x{:04x}", param_id),
+ "target": name,
+ "minRatio": (val as f64 / 100.0).clamp(0.0, 1.0),
+ }));
+ }
+ serde_json::json!({ "targets": targets })
+}
+
+fn extract_catalog_refs_from_blob(blob: &[u8]) -> Vec<String> {
+ let mut out = Vec::new();
+ let scan = |text: &str, out: &mut Vec<String>| {
+ let bytes = text.as_bytes();
+ let mut i = 0usize;
+ while i + 4 < bytes.len() {
+ if bytes[i] == b'.' && bytes[i + 1] == b':' {
+ let mut end = i + 2;
+ while end < bytes.len()
+ && (bytes[end].is_ascii_alphanumeric()
+ || matches!(bytes[end], b':' | b'_' | b'-' | b'.'))
+ {
+ end += 1;
+ }
+ let cand = &text[i..end];
+ if cand.matches(':').count() >= 3 && !out.iter().any(|s| s == cand) {
+ out.push(cand.to_string());
+ }
+ i = end;
+ } else {
+ i += 1;
+ }
+ }
+ };
+
+ // UTF-16LE
+ if blob.len() >= 2 {
+ let le_u16: Vec<u16> = blob
+ .chunks_exact(2)
+ .map(|c| u16::from_le_bytes([c[0], c[1]]))
+ .collect();
+ scan(&String::from_utf16_lossy(&le_u16), &mut out);
+ let be_u16: Vec<u16> = blob
+ .chunks_exact(2)
+ .map(|c| u16::from_be_bytes([c[0], c[1]]))
+ .collect();
+ scan(&String::from_utf16_lossy(&be_u16), &mut out);
+ }
+ let latin1: String = blob.iter().map(|&b| b as char).collect();
+ scan(&latin1, &mut out);
+ out
+}
+
+fn decode_sut_brush_size(raw: f64) -> f64 {
+ if !raw.is_finite() || raw <= 0.0 {
+ return 16.0;
+ }
+ if raw > 20000.0 {
+ (raw / 100.0).clamp(0.5, 2000.0)
+ } else if raw > 2000.0 {
+ (raw / 10.0).clamp(0.5, 2000.0)
+ } else {
+ raw.clamp(0.5, 2000.0)
+ }
+}
+
+fn decode_sut_hardness(raw: f64) -> f64 {
+ if !raw.is_finite() {
+ return 1.0;
+ }
+ if raw <= 0.0 {
+ 0.05
+ } else if raw < 1.0 {
+ raw.clamp(0.05, 1.0)
+ } else if (raw - raw.round()).abs() < 1e-6 && raw >= 1.0 && raw <= 5.0 {
+ (raw / 5.0).clamp(0.05, 1.0)
+ } else {
+ (raw / 100.0).clamp(0.05, 1.0)
+ }
+}
+
+fn map_sut_texture_mode(n: i64) -> &'static str {
+ match n {
+ 0 => "normal",
+ 1 => "multiply",
+ 2 => "subtract",
+ 3 => "compare",
+ 4 => "overlay",
+ 5 => "color-burn",
+ 6 => "linear-burn",
+ 7 => "height",
+ 8 => "outline",
+ _ => "multiply",
+ }
+}
+
+fn map_sut_brush_combine_mode(n: i64) -> &'static str {
+ match n {
+ 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 => "add",
+ 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",
+ 27 | 32 => "behind",
+ 28 | 33 => "clear",
+ 29 | 31 => "compare-density",
+ 30 => "pass-through",
+ 36 => "divide",
+ _ => "normal",
+ }
+}
+
+fn map_sut_pattern_order(n: i64) -> &'static str {
+ match n {
+ 0 => "sequential",
+ 1 => "reverse",
+ 2 => "once",
+ 3 => "random",
+ 4 => "random-no-repeat",
+ 5 => "direction",
+ _ => "sequential",
+ }
+}
+
+fn map_sut_dual_composite(n: i64) -> &'static str {
+ match n {
+ 0 => "multiply",
+ 1 => "subtract",
+ 2 => "darken",
+ 3 => "lighten",
+ 4 => "screen",
+ 5 => "color-burn",
+ 6 => "linear-burn",
+ 7 => "color-dodge",
+ 8 => "color-dodge-glow",
+ 9 => "add",
+ 10 => "add-glow",
+ 11 => "overlay",
+ 12 => "soft-light",
+ 13 => "hard-light",
+ 14 => "vivid-light",
+ 15 => "linear-light",
+ 16 => "pin-light",
+ 17 => "hard-mix",
+ 18 => "difference",
+ 19 => "exclusion",
+ 20 => "darker-color",
+ 21 => "lighter-color",
+ 22 => "divide",
+ 23 => "hue",
+ 24 => "saturation",
+ 25 => "color",
+ 26 => "luminosity",
+ 27 => "normal",
+ 28 => "height",
+ 29 => "compare-density",
+ _ => "multiply",
+ }
+}
+
+fn value_as_f64(val: &Value) -> Option<f64> {
+ match val {
+ Value::Integer(i) => Some(*i as f64),
+ Value::Real(f) if f.is_finite() => Some(*f),
+ _ => None,
+ }
+}
+
+fn value_as_bool(val: &Value) -> bool {
+ match val {
+ Value::Null => false,
+ Value::Integer(i) => *i != 0,
+ Value::Real(f) => f.is_finite() && *f != 0.0,
+ Value::Text(s) => !s.is_empty() && s != "0" && !s.eq_ignore_ascii_case("false"),
+ Value::Blob(b) => !b.is_empty(),
+ }
+}
+
+fn norm_pct01(raw: f64) -> f64 {
+ if raw <= 0.0 {
+ 0.0
+ } else if raw < 1.0 {
+ raw.clamp(0.0, 1.0)
+ } else {
+ (raw / 100.0).clamp(0.0, 1.0)
+ }
}
-#[derive(Debug, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct SutVariantBlobRef {
- pub offset: u32,
- pub len: u32,
+/// Maps a single SQLite `Variant` column name + value to its Ink Studio target field and
+/// parsed value (mirroring `src/utils/sutParser.ts`). Returns `None` if unmapped.
+fn map_variant_column_to_ink_studio(
+ col_name: &str,
+ val: &Value,
+ is_dual_row: bool,
+) -> Option<(&'static str, serde_json::Value)> {
+ let cl = col_name.to_ascii_lowercase();
+ let num = value_as_f64(val);
+ let as_i64 = num.map(|f| f.round() as i64);
+
+ // Strip optional "dual" prefix for DualBrush* columns on primary variant
+ let (prefix_is_dual, key): (bool, &str) = if !is_dual_row && cl.starts_with("dual") {
+ (true, &cl[4..])
+ } else {
+ (is_dual_row, cl.as_str())
+ };
+
+ // Exact match for structural Variant routing columns
+ match cl.as_str() {
+ "_pw_id" | "variantid" => return None,
+ "usedualbrush" => return Some(("dualBrush", serde_json::json!(value_as_bool(val)))),
+ "dualbrushcompositeMode" | "dualbrushcompositemode" | "dualbrushmode" | "dualcompositemode" => {
+ let parsed = as_i64
+ .map(map_sut_dual_composite)
+ .map(serde_json::Value::from)
+ .unwrap_or_else(|| sql_value_to_debug_json(val));
+ return Some(("dualBrushCompositeMode", parsed));
+ }
+ "dualbrushvariantid" | "dualvariantid" | "brushdualvariantid" | "secondaryvariantid" | "subvariantid" => {
+ return Some(("dualVariantId", sql_value_to_debug_json(val)));
+ }
+ "dualpatternimagearray" => {
+ let refs = match val {
+ Value::Blob(b) => extract_catalog_refs_from_blob(b),
+ _ => Vec::new(),
+ };
+ return Some(("dualBrushConfig.tipDataUrl", serde_json::json!(refs)));
+ }
+ "brushlinksize" | "dualbrushlinksize" | "linksize" => {
+ return Some(("dualLinkSize", serde_json::json!(value_as_bool(val))));
+ }
+ _ => {}
+ }
+
+ let field_and_val: Option<(&'static str, serde_json::Value)> = match key {
+ "brushsizeunit" | "sizeunit" => Some((
+ if prefix_is_dual { "dualSizeUnit" } else { "brushSizeUnit" },
+ serde_json::json!(as_i64),
+ )),
+ "brushsizespecifiedbyscreen" | "sizespecifiedbyscreen" => Some((
+ "brushSizeSpecifiedByScreen",
+ serde_json::json!(value_as_bool(val)),
+ )),
+ "brushsize" | "size" | "pensize" | "brushsizeval" | "linewidth" => Some((
+ if prefix_is_dual { "dualSize" } else { "size" },
+ serde_json::json!(num.map(decode_sut_brush_size)),
+ )),
+ "brushsizeeffector" | "sizeeffector" => Some((
+ "sizeSensor",
+ match val {
+ Value::Blob(b) => parse_effector_summary_json(b),
+ _ => sql_value_to_debug_json(val),
+ },
+ )),
+ "opacityeffector" | "brushopacityeffector" => Some((
+ "opacitySensor",
+ match val {
+ Value::Blob(b) => parse_effector_summary_json(b),
+ _ => sql_value_to_debug_json(val),
+ },
+ )),
+ "brushdensityeffector" | "brushfloweffector" | "densityeffector" => Some((
+ "densitySensor",
+ match val {
+ Value::Blob(b) => parse_effector_summary_json(b),
+ _ => sql_value_to_debug_json(val),
+ },
+ )),
+ "brushintervaleffector" | "intervaleffector" => Some((
+ "intervalSensor",
+ match val {
+ Value::Blob(b) => parse_effector_summary_json(b),
+ _ => sql_value_to_debug_json(val),
+ },
+ )),
+ "texturedensityeffector" => Some((
+ "textureDensitySensor",
+ match val {
+ Value::Blob(b) => parse_effector_summary_json(b),
+ _ => sql_value_to_debug_json(val),
+ },
+ )),
+ "brushthicknesseffector" | "thicknesseffector" => Some((
+ "thicknessSensor",
+ match val {
+ Value::Blob(b) => parse_effector_summary_json(b),
+ _ => sql_value_to_debug_json(val),
+ },
+ )),
+ "brushautointervaltype" => {
+ let mapped = match as_i64.unwrap_or(0) {
+ 1 => serde_json::json!(0.04),
+ 2 => serde_json::json!(0.10),
+ 3 => serde_json::json!(0.22),
+ _ => serde_json::json!("fixed"),
+ };
+ Some((if prefix_is_dual { "dualSpacing(auto)" } else { "spacing(auto)" }, mapped))
+ }
+ "brushinterval" | "interval" | "spacing" | "brushspacing" => Some((
+ if prefix_is_dual { "dualSpacing" } else { "spacing" },
+ serde_json::json!(num.map(|r| (r / 100.0).clamp(0.003, 2.0))),
+ )),
+ "opacity" | "brushopacity" => Some(("opacity", serde_json::json!(num.map(norm_pct01)))),
+ "brushdensity" | "density" | "brushflow" | "flow" | "inkamount" => Some((
+ if prefix_is_dual { "dualDensity" } else { "flow" },
+ serde_json::json!(num.map(norm_pct01)),
+ )),
+ "brushadjustflowbyinterval" | "brushadjustdensitybygap" | "adjustdensitybygap" => {
+ Some(("adjustDensityByGap", serde_json::json!(value_as_bool(val))))
+ }
+ "brushcombinemode" | "brushblendmode" | "compositemode" => Some((
+ "brushCombineMode",
+ as_i64
+ .map(map_sut_brush_combine_mode)
+ .map(serde_json::Value::from)
+ .unwrap_or_else(|| sql_value_to_debug_json(val)),
+ )),
+ "blendbrushtips" | "brushmixmode" | "brushalphacombine" | "brushtipcombinemode" => {
+ let m = match as_i64.unwrap_or(2) {
+ 0 => "normal",
+ 1 => "compare",
+ _ => "darken",
+ };
+ Some(("blendTipsMode", serde_json::json!(m)))
+ }
+ "brushhardness" | "hardness" => Some((
+ if prefix_is_dual { "dualHardness" } else { "hardness" },
+ serde_json::json!(num.map(decode_sut_hardness)),
+ )),
+ "brushhardnessunit" | "brushhardnesstype" => {
+ Some(("hardnessUnit", sql_value_to_debug_json(val)))
+ }
+ "brushpatternordertype" | "brushpatternrepeattype" => Some((
+ if prefix_is_dual { "dualSubTipOrder" } else { "subTipOrder" },
+ as_i64
+ .map(map_sut_pattern_order)
+ .map(serde_json::Value::from)
+ .unwrap_or_else(|| sql_value_to_debug_json(val)),
+ )),
+ "brushthickness" | "thickness" => Some((
+ if prefix_is_dual { "dualThickness" } else { "thickness" },
+ serde_json::json!(num.map(|r| (r / 100.0).clamp(0.05, 20.0))),
+ )),
+ "brushverticalthicknes" | "brushverticalthickness" | "verticalthickness" => Some((
+ if prefix_is_dual { "dualThicknessVertical" } else { "thicknessVertical" },
+ serde_json::json!(!value_as_bool(val)),
+ )),
+ "brushpatternreversehorizontal" | "brushflipx" | "fliphorizontal" | "brushfliph" => {
+ let m = match as_i64.unwrap_or(0) {
+ 1 | 2 => "alternate",
+ 3 => "random",
+ _ => "none",
+ };
+ Some((if prefix_is_dual { "dualFlipH" } else { "flipH" }, serde_json::json!(m)))
+ }
+ "brushpatternreversevertical" | "brushflipy" | "flipvertical" | "brushflipv" => {
+ let m = match as_i64.unwrap_or(0) {
+ 1 | 2 => "alternate",
+ 3 => "random",
+ _ => "none",
+ };
+ Some((if prefix_is_dual { "dualFlipV" } else { "flipV" }, serde_json::json!(m)))
+ }
+ "brushrotation" | "rotation" | "brushangle" | "angle" => Some((
+ if prefix_is_dual { "dualAngle" } else { "angle" },
+ serde_json::json!(num.map(|r| ((r % 360.0) + 360.0) % 360.0)),
+ )),
+ "brushrotationeffector" | "rotationeffector" | "angledynamics" => Some((
+ if prefix_is_dual { "dualAngleDynamics" } else { "angleDynamics" },
+ match val {
+ Value::Blob(b) => parse_effector_summary_json(b),
+ _ => {
+ if let Some(raw) = as_i64 {
+ let mode = if (raw & 0x0f) == 3 {
+ if (raw & 0x40) != 0 && (raw & 0x80) != 0 {
+ "direction-random"
+ } else if (raw & 0x100) != 0 {
+ "initial-direction"
+ } else if (raw & 0x40) != 0 {
+ "direction"
+ } else if (raw & 0x80) != 0 {
+ "random"
+ } else if (raw & 0x20) != 0 {
+ "twist"
+ } else if (raw & 0x10) != 0 {
+ "tilt"
+ } else {
+ "none"
+ }
+ } else {
+ match raw & 0x0f {
+ 2 => "tilt",
+ 4 => "random",
+ 5 => "twist",
+ 6 => "initial-direction",
+ 7 => "direction-random",
+ _ => "none",
+ }
+ };
+ serde_json::json!(mode)
+ } else {
+ sql_value_to_debug_json(val)
+ }
+ }
+ },
+ )),
+ "brushrotationrandomscale" | "rotationrandomscale" => Some((
+ "rotationRandomScale",
+ serde_json::json!(num.map(norm_pct01)),
+ )),
+ "antialias" | "brushantialias" => Some((
+ "antiAlias",
+ serde_json::json!(as_i64.map(|v| v.clamp(0, 3))),
+ )),
+ "flickerreduction" | "brushstabilization" => Some((
+ "stabilization",
+ serde_json::json!(as_i64.map(|v| v.clamp(0, 50))),
+ )),
+ "brushuserevision" => Some(("postCorrectionEnabled", serde_json::json!(value_as_bool(val)))),
+ "brushrevision" | "brushpostcorrection" | "postcorrection" => Some((
+ "postCorrection",
+ serde_json::json!(as_i64.map(|v| (v / 2).clamp(0, 5))),
+ )),
+ "brushsharpencorner" | "brushsharpangles" | "sharpangles" => {
+ Some(("sharpCorners", serde_json::json!(value_as_bool(val))))
+ }
+ "brushribbon" | "ribbon" => Some((
+ if prefix_is_dual { "dualIsRibbon" } else { "isRibbon" },
+ serde_json::json!(value_as_bool(val)),
+ )),
+ "brushchangebrushcolor" | "brushcolorjitter" => {
+ Some(("dynamics.colorJitterEnabled", serde_json::json!(value_as_bool(val))))
+ }
+ "brushchangecolorperstroke" | "brushchangebrushcolorperstroke" | "colorjitterperstroke" => {
+ Some(("dynamics.colorJitterPerStroke", serde_json::json!(value_as_bool(val))))
+ }
+ "brushsubcolormix" | "brushmixsubcolor" | "subcolormix" => {
+ Some(("dynamics.foregroundBackgroundJitter", serde_json::json!(num.map(norm_pct01))))
+ }
+ "brushsubcolormixeffector" | "subcolormixeffector" => Some((
+ "dynamics.subColorMixSensor",
+ match val {
+ Value::Blob(b) => parse_effector_summary_json(b),
+ _ => sql_value_to_debug_json(val),
+ },
+ )),
+ "brushrandomhue" | "brushhuejitter" | "randomhue" => {
+ Some(("dynamics.hueJitter", serde_json::json!(num.map(norm_pct01))))
+ }
+ "brushrandomhueeffector" | "brushhueeffector" | "randomhueeffector" => Some((
+ "dynamics.hueJitterSensor",
+ match val {
+ Value::Blob(b) => parse_effector_summary_json(b),
+ _ => sql_value_to_debug_json(val),
+ },
+ )),
+ "brushrandomsaturation" | "brushsaturationjitter" | "randomsaturation" => {
+ Some(("dynamics.saturationJitter", serde_json::json!(num.map(norm_pct01))))
+ }
+ "brushrandomsaturationeffector" | "brushsaturationeffector" | "randomsaturationeffector" => Some((
+ "dynamics.saturationJitterSensor",
+ match val {
+ Value::Blob(b) => parse_effector_summary_json(b),
+ _ => sql_value_to_debug_json(val),
+ },
+ )),
+ "brushrandomluminance" | "brushrandombrightness" | "brushluminancejitter" | "randomluminance" => {
+ Some(("dynamics.brightnessJitter", serde_json::json!(num.map(norm_pct01))))
+ }
+ "brushrandomluminanceeffector"
+ | "brushrandombrightnesseffector"
+ | "brushluminanceeffector"
+ | "randomluminanceeffector" => Some((
+ "dynamics.luminanceJitterSensor",
+ match val {
+ Value::Blob(b) => parse_effector_summary_json(b),
+ _ => sql_value_to_debug_json(val),
+ },
+ )),
+ "brushusewatercolor" | "brushusewatercolor2" | "colormixing" | "enablecolormixing" => {
+ Some(("colorMixing", serde_json::json!(value_as_bool(val))))
+ }
+ "brushmixcolor" | "amountofpaint" | "paintamount" | "colormixamount" => {
+ Some(("amountOfPaint", serde_json::json!(num.map(norm_pct01))))
+ }
+ "brushmixalpha" | "densityofpaint" | "paintdensity" => {
+ Some(("densityOfPaint", serde_json::json!(num.map(norm_pct01))))
+ }
+ "brushmixcolorextension" | "colorstretch" | "stretch" => {
+ Some(("colorStretch", serde_json::json!(num.map(norm_pct01))))
+ }
+ "brushmixcoloreffector" | "amountofpainteffector" => Some((
+ "amountOfPaintSensor",
+ match val {
+ Value::Blob(b) => parse_effector_summary_json(b),
+ _ => sql_value_to_debug_json(val),
+ },
+ )),
+ "brushmixalphaeffector" | "densityofpainteffector" => Some((
+ "densityOfPaintSensor",
+ match val {
+ Value::Blob(b) => parse_effector_summary_json(b),
+ _ => sql_value_to_debug_json(val),
+ },
+ )),
+ "brushmixcolorextensioneffector" | "colorstretcheffector" => Some((
+ "colorStretchSensor",
+ match val {
+ Value::Blob(b) => parse_effector_summary_json(b),
+ _ => sql_value_to_debug_json(val),
+ },
+ )),
+ "brushmixgroundcolor" | "mixgroundcolor" => {
+ Some(("mixGroundColor", serde_json::json!(value_as_bool(val))))
+ }
+ "brushuseblur" | "useblur" => Some(("useBlur", serde_json::json!(value_as_bool(val)))),
+ "brushblur" | "blurstrength" | "brushblurstrength" => {
+ Some(("blurStrength", serde_json::json!(num.map(norm_pct01))))
+ }
+ "brushwatercolor" | "mixingmode" => {
+ let m = match as_i64.unwrap_or(0) {
+ 1 => "running_color",
+ 2 | 3 => "smear",
+ _ => "blend",
+ };
+ Some(("mixingMode", serde_json::json!(m)))
+ }
+ "brushcolormixingmode" | "perceptualmixing" => {
+ Some(("perceptualMixing", serde_json::json!(as_i64 == Some(1))))
+ }
+ "brushusewateredge" | "usewateredge" => {
+ Some(("wetEdgeEnabled", serde_json::json!(value_as_bool(val))))
+ }
+ "brushwateredgeradius" | "wateredgeradius" => {
+ Some(("wetEdgeRadius", serde_json::json!(num)))
+ }
+ "brushwateredgealphapower" | "wateredgealphapower" => {
+ Some(("wetEdgeAlphaPower", serde_json::json!(num.map(norm_pct01))))
+ }
+ "brushwateredgevaluepower" | "wateredgevaluepower" => {
+ Some(("wetEdgeValuePower", serde_json::json!(num.map(norm_pct01))))
+ }
+ "texturedensity" | "grain" | "brushtexturedensity" => {
+ Some(("textureDensity", serde_json::json!(num.map(norm_pct01))))
+ }
+ "texturescale2" | "texturescale" => {
+ Some(("paperTextureScale", serde_json::json!(num.map(|r| r / 100.0))))
+ }
+ "texturerotate" => Some(("paperTextureRotate", serde_json::json!(num))),
+ "textureposition" | "texturemappingmode" => {
+ let m = match as_i64.unwrap_or(0) {
+ 1 => "brush-aligned",
+ 2 => "stroke-flow",
+ 3 => "random-per-stroke",
+ _ => "canvas-locked",
+ };
+ Some(("grainMappingMode", serde_json::json!(m)))
+ }
+ "textureoffsetx" | "papertextureoffsetx" => {
+ Some(("paperTextureOffsetX", serde_json::json!(num)))
+ }
+ "textureoffsety" | "papertextureoffsety" => {
+ Some(("paperTextureOffsetY", serde_json::json!(num)))
+ }
+ "texturecompositemode" | "texturemode" | "brushtexturemode" => Some((
+ "paperTextureMode",
+ as_i64
+ .map(map_sut_texture_mode)
+ .map(serde_json::Value::from)
+ .unwrap_or_else(|| sql_value_to_debug_json(val)),
+ )),
+ "texturereversedensity" | "textureinvert" | "brushtextureinvert" => {
+ Some(("paperTextureInverted", serde_json::json!(value_as_bool(val))))
+ }
+ "textureforplot" => {
+ Some(("paperTextureApplyEachPlot", serde_json::json!(value_as_bool(val))))
+ }
+ "texturestressdensity" => {
+ Some(("paperTextureEmphasizeDensity", serde_json::json!(value_as_bool(val))))
+ }
+ "texturebrightness" => Some((
+ "paperTextureBrightness",
+ serde_json::json!(num.map(|v| v.clamp(-100.0, 100.0))),
+ )),
+ "texturecontrast" => Some((
+ "paperTextureContrast",
+ serde_json::json!(num.map(|v| v.clamp(-100.0, 100.0))),
+ )),
+ "textureimage" => {
+ let refs = match val {
+ Value::Blob(b) => extract_catalog_refs_from_blob(b),
+ _ => Vec::new(),
+ };
+ Some(("paperTexture", serde_json::json!(refs)))
+ }
+ "brushusepatternimage" => {
+ Some(("usePatternImage", serde_json::json!(value_as_bool(val))))
+ }
+ "brushpatternimagearray" => {
+ let refs = match val {
+ Value::Blob(b) => extract_catalog_refs_from_blob(b),
+ _ => Vec::new(),
+ };
+ Some((
+ if prefix_is_dual { "dualSubTips" } else { "subTips" },
+ serde_json::json!(refs),
+ ))
+ }
+ "brushusespray" | "usespray" => Some((
+ if prefix_is_dual { "dualSpray.enabled" } else { "spray.enabled" },
+ serde_json::json!(value_as_bool(val)),
+ )),
+ "brushspraysize" | "spraysize" => Some((
+ if prefix_is_dual { "dualSpray.size" } else { "spray.size" },
+ serde_json::json!(num),
+ )),
+ "brushspraydensity" | "spraydensity" => Some((
+ if prefix_is_dual { "dualSpray.density" } else { "spray.density" },
+ serde_json::json!(num),
+ )),
+ "brushspraybias" | "spraybias" => Some((
+ if prefix_is_dual { "dualSpray.bias" } else { "spray.bias" },
+ serde_json::json!(num.map(|v| (v / 100.0).clamp(-1.0, 1.0))),
+ )),
+ "brushspraydeviation" | "spraydeviation" => Some((
+ if prefix_is_dual { "dualSpray.deviation" } else { "spray.deviation" },
+ serde_json::json!(num.map(|v| (v / 100.0).clamp(-1.0, 1.0))),
+ )),
+ "brushsprayparticlesize" | "sprayparticlesize" => Some((
+ if prefix_is_dual { "dualSpray.particleSize" } else { "spray.particleSize" },
+ serde_json::json!(num.map(decode_sut_brush_size)),
+ )),
+ "brushspraylinksize" | "spraylinksize" => Some((
+ if prefix_is_dual { "dualSpray.linkSize" } else { "spray.linkSize" },
+ serde_json::json!(value_as_bool(val)),
+ )),
+ "brushspraysizeeffector" | "spraysizeeffector" => Some((
+ if prefix_is_dual { "dualSpray.sizeSensor" } else { "spray.sizeSensor" },
+ match val {
+ Value::Blob(b) => parse_effector_summary_json(b),
+ _ => sql_value_to_debug_json(val),
+ },
+ )),
+ "brushspraydensityeffector" | "spraydensityeffector" => Some((
+ if prefix_is_dual { "dualSpray.densitySensor" } else { "spray.densitySensor" },
+ match val {
+ Value::Blob(b) => parse_effector_summary_json(b),
+ _ => sql_value_to_debug_json(val),
+ },
+ )),
+ "brushspraydirection" | "spraydirection" => Some((
+ if prefix_is_dual { "dualSpray.direction" } else { "spray.direction" },
+ serde_json::json!(num.map(|r| ((r % 360.0) + 360.0) % 360.0)),
+ )),
+ "brushspraydirectioneffector" | "spraydirectioneffector" => Some((
+ if prefix_is_dual { "dualSpray.directionSensor" } else { "spray.directionSensor" },
+ match val {
+ Value::Blob(b) => parse_effector_summary_json(b),
+ _ => sql_value_to_debug_json(val),
+ },
+ )),
+ "brushusein" => Some(("taper.useIn", serde_json::json!(value_as_bool(val)))),
+ "brushuseout" => Some(("taper.useOut", serde_json::json!(value_as_bool(val)))),
+ "brushinlength" => Some(("taper.inLength", serde_json::json!(num))),
+ "brushinratio" => Some(("taper.inRatio", serde_json::json!(num.map(norm_pct01)))),
+ "brushoutlength" => Some(("taper.outLength", serde_json::json!(num))),
+ "brushoutratio" => Some(("taper.outRatio", serde_json::json!(num.map(norm_pct01)))),
+ "brushinouttype" => Some(("taper.inOutType", serde_json::json!(as_i64))),
+ "brushinoutbyspeed" => Some(("taper.inOutBySpeed", serde_json::json!(value_as_bool(val)))),
+ "brushinouttarget" => Some((
+ "taper.targets",
+ match val {
+ Value::Blob(b) => parse_inout_target_summary_json(b),
+ _ => sql_value_to_debug_json(val),
+ },
+ )),
+ _ => None,
+ };
+
+ field_and_val
}
-#[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>,
+fn build_variant_coverage_report(
+ row: &SqlRow,
+ variant_id: Option<i64>,
+ is_dual_row: bool,
+) -> SutVariantCoverageReport {
+ let mut keys: Vec<&String> = row.keys().collect();
+ keys.sort();
+
+ let mut mapped_columns = Vec::new();
+ let mut unmapped_non_default_columns = Vec::new();
+ let mut unmapped_default_count = 0usize;
+
+ for k in &keys {
+ let kl = k.to_ascii_lowercase();
+ if kl == "_pw_id" || kl == "variantid" {
+ continue;
+ }
+ let val = &row[*k];
+ if let Some((ink_field, parsed)) = map_variant_column_to_ink_studio(k, val, is_dual_row) {
+ if !matches!(val, Value::Null) {
+ mapped_columns.push(SutMappedColumnReport {
+ column: (*k).clone(),
+ ink_studio_field: ink_field.to_string(),
+ raw_value: sql_value_to_debug_json(val),
+ parsed_value: parsed,
+ });
+ }
+ } else if is_sql_value_non_default(val) {
+ unmapped_non_default_columns.push(SutUnmappedColumnReport {
+ column: (*k).clone(),
+ value: sql_value_to_debug_json(val),
+ });
+ } else {
+ unmapped_default_count += 1;
+ }
+ }
+
+ let mapped_count = mapped_columns.len();
+ let unmapped_non_default_count = unmapped_non_default_columns.len();
+ let denom = mapped_count + unmapped_non_default_count;
+ let coverage_percent = if denom == 0 {
+ 100.0
+ } else {
+ ((mapped_count as f64 / denom as f64) * 1000.0).round() / 10.0
+ };
+
+ SutVariantCoverageReport {
+ variant_id,
+ total_columns: keys.len(),
+ mapped_count,
+ unmapped_non_default_count,
+ unmapped_default_count,
+ coverage_percent,
+ mapped_columns,
+ unmapped_non_default_columns,
+ }
}
-/// 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> {
+/// Inspects a `.sut` file buffer and returns a complete coverage report:
+/// `Node` rows, chosen `VariantID` / `DualVariantID`, every `MaterialFile` entry
+/// with decoded `data/*.layer` dimensions and expression color, all mapped `Variant`
+/// columns with parsed Ink Studio values, and all unmapped non-default `Variant` columns.
+pub fn inspect_sut_bytes(
+ bytes: &[u8],
+ file_label: Option<&str>,
+) -> Result<SutInspectionReport, 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 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 sorted_tables: Vec<String> = tables.iter().cloned().collect();
+ sorted_tables.sort();
+
+ let selected = select_sut_nodes_and_variants(&conn, &tables);
+ let nodes: Vec<serde_json::Value> = selected
+ .all_nodes
+ .iter()
+ .map(sql_row_to_debug_json)
+ .collect();
- 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),
- _ => {}
+ let mut materials = Vec::new();
+ let mut embedded_catalog_paths = HashSet::<String>::new();
+ for row in query_table(&conn, &tables, "MaterialFile")
+ .into_iter()
+ .take(MAX_SUT_MATERIALS)
+ {
+ let pw_id = match row.get("_PW_ID") {
+ Some(Value::Integer(i)) => i.to_string(),
+ Some(Value::Text(s)) => s.clone(),
+ _ => String::new(),
+ };
+ let original_path = get_str(&row, &["OriginalPath"], "");
+ let catalog_path = get_str(&row, &["CatalogPath"], "");
+ if !catalog_path.is_empty() {
+ embedded_catalog_paths.insert(catalog_path.clone());
+ }
+ if !original_path.is_empty() {
+ embedded_catalog_paths.insert(original_path.clone());
+ }
+ let file_data = get_bytes(&row, &["FileData"]).unwrap_or(&[]);
+ let decoded = decode_material_file_blob(file_data);
+ materials.push(SutMaterialInspectionEntry {
+ pw_id,
+ original_path,
+ catalog_path,
+ file_data_len: file_data.len(),
+ decoded_source: decoded.source.to_string(),
+ width: decoded.width,
+ height: decoded.height,
+ expression_color: decoded.expression_color,
+ is_paper_texture: decoded.is_paper_texture,
+ has_sub_color: decoded.has_sub_color,
+ tar_entries: decoded.tar_entry_summaries,
+ });
+ }
+
+ let primary_variant = selected
+ .primary_variant
+ .as_ref()
+ .map(|row| build_variant_coverage_report(row, selected.variant_id, false));
+ let dual_variant = selected
+ .dual_variant
+ .as_ref()
+ .map(|row| build_variant_coverage_report(row, selected.dual_variant_id, true));
+
+ // Diagnose missing external material references and unsupported non-brush sub-tools
+ let mut warnings = Vec::new();
+ if let Some(ref pv) = selected.primary_variant {
+ for (col, label) in [
+ ("BrushPatternImageArray", "brush tip"),
+ ("TextureImage", "paper texture"),
+ ("DualPatternImageArray", "dual brush tip"),
+ ] {
+ if let Some(blob) = get_bytes(pv, &[col]) {
+ for cref in extract_catalog_refs_from_blob(blob) {
+ if !embedded_catalog_paths.contains(&cref) {
+ warnings.push(format!(
+ "Unembedded {} material reference ({}) not found in MaterialFile",
+ label, cref
+ ));
}
}
- Ok(())
- });
+ }
+ }
+ let has_liquify = pv.keys().any(|k| k.to_ascii_lowercase().starts_with("liquify"));
+ if has_liquify {
+ warnings.push(
+ "Unsupported non-brush CSP sub-tool detected (Liquify): fallback brush parameters apply".to_string(),
+ );
}
}
- let mut blobs = Vec::<u8>::new();
- let mut variant_scalars = HashMap::new();
- let mut variant_blobs = HashMap::new();
-
- if tables.contains("Variant") {
- let query_variant_by_col = |col: &str, vid: i64| -> rusqlite::Result<(Vec<String>, Vec<Value>)> {
- let sql = format!("SELECT * FROM Variant WHERE {} = ?1 LIMIT 1", col);
- let mut s = conn.prepare(&sql)?;
- 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))
- };
+ Ok(SutInspectionReport {
+ file: file_label.map(String::from),
+ tables: sorted_tables,
+ selected: SutInspectionSelection {
+ node_name: selected.node_name,
+ node_uuid: selected.node_uuid,
+ variant_id: selected.variant_id,
+ dual_variant_id: selected.dual_variant_id,
+ node_init_variant_id: selected.node_init_variant_id,
+ has_dual_variant: selected.dual_variant.is_some(),
+ },
+ nodes,
+ materials,
+ primary_variant,
+ dual_variant,
+ warnings,
+ })
+}
- let query_res: rusqlite::Result<(Vec<String>, Vec<Value>)> = if let Some(vid) = variant_id {
- query_variant_by_col("VariantID", vid)
- .or_else(|_| query_variant_by_col("_PW_ID", vid))
- } 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))
- });
+/// Formats a `SutInspectionReport` as a clean, human-readable CLI coverage summary.
+pub fn format_sut_inspection_human(report: &SutInspectionReport) -> String {
+ let mut out = String::new();
+ let title = report.file.as_deref().unwrap_or("<in-memory .sut>");
+ out.push_str(&format!("=== SUT Inspection: {} ===\n", title));
+ out.push_str(&format!(
+ "Brush Name : {}\n",
+ report.selected.node_name.as_deref().unwrap_or("<unnamed>")
+ ));
+ if let Some(ref uuid) = report.selected.node_uuid {
+ out.push_str(&format!("Node UUID : {}\n", uuid));
+ }
+ out.push_str(&format!(
+ "Chosen VariantID : {:?} (InitVariantID: {:?}, DualVariantID: {:?})\n",
+ report.selected.variant_id,
+ report.selected.node_init_variant_id,
+ report.selected.dual_variant_id
+ ));
+ out.push_str(&format!(
+ "Node Rows : {} | Tables: {}\n",
+ report.nodes.len(),
+ report.tables.join(", ")
+ ));
+ for (idx, n) in report.nodes.iter().enumerate() {
+ out.push_str(&format!(
+ " Node[{}]: name={} variantId={} initVariantId={}\n",
+ idx,
+ n.get("NodeName").unwrap_or(&serde_json::Value::Null),
+ n.get("NodeVariantId").unwrap_or(&serde_json::Value::Null),
+ n.get("NodeInitVariantId").unwrap_or(&serde_json::Value::Null),
+ ));
+ }
- 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 });
- }
- _ => {}
- }
- }
+ out.push_str(&format!("\nMaterialFile Entries ({}):\n", report.materials.len()));
+ if report.materials.is_empty() {
+ out.push_str(" (none)\n");
+ } else {
+ for m in &report.materials {
+ let dims = match (m.width, m.height) {
+ (Some(w), Some(h)) => format!("{}x{}", w, h),
+ _ => "unknown".to_string(),
+ };
+ out.push_str(&format!(
+ " - [PW_ID={}] {} | src={} dims={} expr={} paper={} subColor={} bytes={}\n",
+ m.pw_id,
+ if m.catalog_path.is_empty() { &m.original_path } else { &m.catalog_path },
+ m.decoded_source,
+ dims,
+ m.expression_color.as_deref().unwrap_or("unknown"),
+ m.is_paper_texture,
+ m.has_sub_color,
+ m.file_data_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 fmt_variant = |out: &mut String, label: &str, v: &SutVariantCoverageReport| {
+ out.push_str(&format!(
+ "\n{} Variant (ID={:?}) — Coverage: {:.1}% ({} mapped / {} unmapped non-default / {} default-zero)\n",
+ label,
+ v.variant_id,
+ v.coverage_percent,
+ v.mapped_count,
+ v.unmapped_non_default_count,
+ v.unmapped_default_count
+ ));
+ out.push_str(" Mapped Columns:\n");
+ if v.mapped_columns.is_empty() {
+ out.push_str(" (none)\n");
+ } else {
+ for c in &v.mapped_columns {
+ out.push_str(&format!(
+ " - {} -> {} = {} (raw: {})\n",
+ c.column, c.ink_studio_field, c.parsed_value, c.raw_value
+ ));
}
}
+ out.push_str(" Unmapped Non-Default Columns:\n");
+ if v.unmapped_non_default_columns.is_empty() {
+ out.push_str(" (none — 100% active column coverage!)\n");
+ } else {
+ for u in &v.unmapped_non_default_columns {
+ out.push_str(&format!(" ! {} = {}\n", u.column, u.value));
+ }
+ }
+ };
+
+ if let Some(ref pv) = report.primary_variant {
+ fmt_variant(&mut out, "Primary", pv);
+ }
+ if let Some(ref dv) = report.dual_variant {
+ fmt_variant(&mut out, "Dual", dv);
}
- 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())?;
+ if !report.warnings.is_empty() {
+ out.push_str(&format!("\nWarnings ({}):\n", report.warnings.len()));
+ for w in &report.warnings {
+ out.push_str(&format!(" * {}\n", w));
+ }
+ }
- 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)
+ 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());
@@ -1803,4 +4672,558 @@ mod tests {
assert_eq!(layers[1]["name"], "Paper");
assert_eq!(layers[1]["solidFillHex"], "#ffffff");
}
+
+ fn build_ustar_archive(entries: &[(&str, &[u8])]) -> Vec<u8> {
+ let mut out = Vec::new();
+ for &(name, data) in entries {
+ let mut hdr = [0u8; 512];
+ let nb = name.as_bytes();
+ assert!(nb.len() <= 100);
+ hdr[..nb.len()].copy_from_slice(nb);
+ hdr[100..108].copy_from_slice(b"0000644\0");
+ hdr[108..116].copy_from_slice(b"0000000\0");
+ hdr[116..124].copy_from_slice(b"0000000\0");
+ let size_oct = format!("{:011o}\0", data.len());
+ hdr[124..136].copy_from_slice(size_oct.as_bytes());
+ hdr[136..148].copy_from_slice(b"00000000000\0");
+ hdr[148..156].copy_from_slice(b" ");
+ hdr[156] = b'0';
+ hdr[257..263].copy_from_slice(b"ustar\0");
+ hdr[263..265].copy_from_slice(b"00");
+ let chksum: u32 = hdr.iter().map(|&b| b as u32).sum();
+ let chk_oct = format!("{:06o}\0 ", chksum);
+ hdr[148..156].copy_from_slice(chk_oct.as_bytes());
+
+ out.extend_from_slice(&hdr);
+ out.extend_from_slice(data);
+ let pad = (512 - (data.len() % 512)) % 512;
+ out.extend(std::iter::repeat_n(0u8, pad));
+ }
+ // Two 512-byte zero blocks end-of-archive marker
+ out.extend(std::iter::repeat_n(0u8, 1024));
+ out
+ }
+
+ fn build_multi_block_payload(tiles: &[(u32, &[u8])]) -> Vec<u8> {
+ let mut payload = Vec::new();
+ for &(idx, tile_planes) in tiles {
+ let compressed = zlib_compress(tile_planes);
+ let mut inner = Vec::new();
+ inner.extend_from_slice(&idx.to_be_bytes());
+ inner.extend_from_slice(&[0u8; 12]);
+ inner.extend_from_slice(&1u32.to_be_bytes());
+ inner.extend_from_slice(&((compressed.len() + 4) as u32).to_be_bytes());
+ inner.extend_from_slice(&(compressed.len() as u32).to_le_bytes());
+ inner.extend_from_slice(&compressed);
+
+ payload.extend_from_slice(tag_block_begin());
+ payload.extend_from_slice(&inner);
+ payload.extend_from_slice(tag_block_end());
+ }
+ payload
+ }
+
+ fn build_synthetic_layer_file(w: u32, h: u32, tiles: &[(u32, &[u8])]) -> Vec<u8> {
+ let conn = Connection::open_in_memory().unwrap();
+ conn.execute_batch(
+ "
+ CREATE TABLE Canvas (CanvasWidth REAL, CanvasHeight REAL);
+ CREATE TABLE Layer (
+ MainId INTEGER, LayerName TEXT, LayerFolder INTEGER, LayerFirstChildIndex INTEGER,
+ LayerType INTEGER, LayerVisibility 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);
+ ",
+ )
+ .unwrap();
+ conn.execute("INSERT INTO Canvas VALUES (?1, ?2)", rusqlite::params![w as f64, h as f64])
+ .unwrap();
+ conn.execute(
+ "INSERT INTO Layer VALUES (1, 'MatLayer', 0, 0, 1, 1, 10, 0, 0)",
+ [],
+ )
+ .unwrap();
+ conn.execute("INSERT INTO Mipmap VALUES (10, 20)", []).unwrap();
+ conn.execute("INSERT INTO MipmapInfo VALUES (20, 30, 1.0, 0)", [])
+ .unwrap();
+ conn.execute("INSERT INTO Offscreen VALUES (30, 1, 'extrnlid_mat', NULL)", [])
+ .unwrap();
+
+ let sqlite_bytes = conn.serialize(DatabaseName::Main).unwrap().to_vec();
+ let exta = build_exta("extrnlid_mat", &build_multi_block_payload(tiles));
+ let sqli = build_chunk(b"SQLi", &sqlite_bytes);
+ let foot = build_chunk(b"Foot", &[]);
+
+ let mut layer = Vec::new();
+ layer.extend_from_slice(b"CSFCHUNK");
+ layer.extend_from_slice(&[0u8; 16]);
+ layer.extend_from_slice(&exta);
+ layer.extend_from_slice(&sqli);
+ layer.extend_from_slice(&foot);
+ layer
+ }
+
+ /// Minimal PNG RGBA8 decoder for verifying our encoder output bit-for-bit in tests.
+ fn decode_test_png_rgba(png: &[u8]) -> (u32, u32, Vec<u8>) {
+ assert_eq!(&png[0..8], PNG_SIG);
+ let (w, h) = parse_png_dimensions(png).expect("valid PNG header");
+ let mut idat = Vec::new();
+ let mut off = 8usize;
+ while off + 12 <= png.len() {
+ let len = read_u32_be(png, off).unwrap() as usize;
+ let ctype = &png[off + 4..off + 8];
+ let data = &png[off + 8..off + 8 + len];
+ let crc_stored = read_u32_be(png, off + 8 + len).unwrap();
+ let crc_calc = !crc32_update(crc32_update(!0u32, ctype), data);
+ assert_eq!(crc_stored, crc_calc, "PNG CRC mismatch for {:?}", ctype);
+ if ctype == b"IDAT" {
+ idat.extend_from_slice(data);
+ }
+ off += 12 + len;
+ if ctype == b"IEND" {
+ break;
+ }
+ }
+ let raw = safe_unzlib(&idat, MAX_MATERIAL_RGBA_BYTES).expect("valid PNG IDAT zlib");
+ let stride = (w as usize) * 4;
+ assert_eq!(raw.len(), (h as usize) * (1 + stride));
+ let mut rgba = vec![0u8; (w as usize) * (h as usize) * 4];
+ for y in 0..(h as usize) {
+ let ftype = raw[y * (1 + stride)];
+ let src = &raw[y * (1 + stride) + 1..(y + 1) * (1 + stride)];
+ let dst = &mut rgba[y * stride..(y + 1) * stride];
+ match ftype {
+ 0 => dst.copy_from_slice(src),
+ 1 => {
+ for x in 0..stride {
+ let left = if x >= 4 { dst[x - 4] } else { 0 };
+ dst[x] = src[x].wrapping_add(left);
+ }
+ }
+ other => panic!("unexpected PNG filter {}", other),
+ }
+ }
+ (w, h, rgba)
+ }
+
+ #[test]
+ fn test_extract_multinode_sut_with_512_layer_over_64_thumbnail() {
+ // 1. Build a 512x512 (2x2 grid of 256x256) 2-plane Grayscale brush tip with BOTH
+ // opaque black (Main color) and opaque white (Sub color) pixels alongside transparent background.
+ let mut tile_tl = vec![0u8; TILE_PIXELS * 2];
+ // Opaque black square at (10..50, 10..50)
+ for y in 10..50 {
+ for x in 10..50 {
+ let p = y * TILE_SIZE + x;
+ tile_tl[p] = 255; // alpha
+ tile_tl[TILE_PIXELS + p] = 0; // black (Main color)
+ }
+ }
+ // Opaque white square at (60..100, 10..50) — MUST stay opaque white (255,255,255,255)!
+ for y in 10..50 {
+ for x in 60..100 {
+ let p = y * TILE_SIZE + x;
+ tile_tl[p] = 255; // alpha
+ tile_tl[TILE_PIXELS + p] = 255; // white (Sub color)
+ }
+ }
+ let mut tile_br = vec![0u8; TILE_PIXELS * 2];
+ // Semi-transparent mid-gray pixel at bottom-right tile (500, 500) -> local (244, 244)
+ {
+ let p = 244 * TILE_SIZE + 244;
+ tile_br[p] = 180;
+ tile_br[TILE_PIXELS + p] = 128;
+ }
+ let empty_gray_tile = vec![0u8; TILE_PIXELS * 2];
+
+ let tip_layer_bytes = build_synthetic_layer_file(
+ 512,
+ 512,
+ &[
+ (0, &tile_tl),
+ (1, &empty_gray_tile),
+ (2, &empty_gray_tile),
+ (3, &tile_br),
+ ],
+ );
+
+ let thumb_64_rgba = vec![0u8; 64 * 64 * 4];
+ let thumb_64_png = encode_rgba8_to_png(64, 64, &thumb_64_rgba).unwrap();
+
+ let tip_xml = br#"<?xml version="1.0" encoding="UTF-8"?>
+<infolist>
+ <info uuid="11111111-2222-3333-4444-555555555555">
+ <datalist key="tag"><data>BrushTip</data></datalist>
+ <ExpressionColor>Gray</ExpressionColor>
+ <Width>512</Width>
+ <Height>512</Height>
+ </info>
+</infolist>"#;
+
+ let tip_tar = build_ustar_archive(&[
+ ("thumbnail/thumbnail.png", &thumb_64_png),
+ ("icedata/layerData.xml", tip_xml),
+ ("data/material_0.layer", &tip_layer_bytes),
+ ]);
+
+ // 2. Build a 512x512 PaperTexture TAR (1-plane 8-bit density)
+ let mut paper_tile = vec![0u8; TILE_PIXELS];
+ paper_tile[12 * TILE_SIZE + 34] = 210; // high density valley
+ let paper_layer_bytes = build_synthetic_layer_file(512, 512, &[(0, &paper_tile)]);
+ let paper_xml = br#"<?xml version="1.0" encoding="UTF-8"?>
+<infolist>
+ <info>
+ <datalist key="tag"><data>PaperTexture</data></datalist>
+ <datalist key="color"><data>Gray</data></datalist>
+ </info>
+</infolist>"#;
+ let paper_tar = build_ustar_archive(&[
+ ("thumbnail/thumbnail.png", &thumb_64_png),
+ ("icedata/layerData.xml", paper_xml),
+ ("data/material_0.layer", &paper_layer_bytes),
+ ]);
+
+ // 3. Build a 256x256 Color brush tip TAR
+ let mut color_tile = vec![0u8; TILE_PIXELS * 5];
+ {
+ let p = 7 * TILE_SIZE + 9;
+ color_tile[p] = 200; // alpha
+ let ci = TILE_PIXELS + p * 4;
+ color_tile[ci] = 30; // B
+ color_tile[ci + 1] = 80; // G
+ color_tile[ci + 2] = 240; // R
+ }
+ let color_layer_bytes = build_synthetic_layer_file(256, 256, &[(0, &color_tile)]);
+ let color_xml = br#"<?xml version="1.0" encoding="UTF-8"?>
+<infolist><info><ExpressionColor>Color</ExpressionColor></info></infolist>"#;
+ let color_tar = build_ustar_archive(&[
+ ("thumbnail/thumbnail.png", &thumb_64_png),
+ ("icedata/layerData.xml", color_xml),
+ ("data/material_0.layer", &color_layer_bytes),
+ ]);
+
+ // 4. Build a fallback-only material TAR (no data/*.layer -> must use 64x64 thumbnail.png)
+ let fallback_tar = build_ustar_archive(&[("thumbnail/thumbnail.png", &thumb_64_png)]);
+
+ // 5. Build multi-node .sut SQLite DB where row 1 is a Root container (NodeVariantId = 0)
+ // and row 2 is the actual brush with NodeVariantId = 42, NodeInitVariantId = 43,
+ // plus DualBrushVariantId = 99.
+ let conn = Connection::open_in_memory().unwrap();
+ conn.execute_batch(
+ "
+ CREATE TABLE Node (
+ _PW_ID INTEGER PRIMARY KEY,
+ NodeName TEXT,
+ NodeUuid BLOB,
+ NodeVariantId INTEGER,
+ NodeInitVariantId INTEGER
+ );
+ CREATE TABLE Variant (
+ _PW_ID INTEGER PRIMARY KEY,
+ VariantID INTEGER,
+ BrushSize REAL,
+ UseDualBrush INTEGER,
+ DualBrushVariantId INTEGER,
+ BrushUsePatternImage INTEGER,
+ BrushPatternImageArray BLOB
+ );
+ CREATE TABLE MaterialFile (
+ _PW_ID INTEGER PRIMARY KEY,
+ OriginalPath TEXT,
+ FileData BLOB,
+ CatalogPath TEXT
+ );
+ ",
+ )
+ .unwrap();
+
+ let brush_uuid: [u8; 16] = [
+ 0xaa, 0xbb, 0xcc, 0xdd, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00,
+ 0xab, 0xcd,
+ ];
+ // Root container node first (previously broke LIMIT 1!)
+ conn.execute(
+ "INSERT INTO Node VALUES (1, 'RootGroup', NULL, 0, 0)",
+ [],
+ )
+ .unwrap();
+ // Actual brush child node second
+ conn.execute(
+ "INSERT INTO Node VALUES (2, 'DualTone Ink', ?1, 42, 43)",
+ rusqlite::params![brush_uuid.as_slice()],
+ )
+ .unwrap();
+
+ // Primary variant (42), Init variant (43), Dual variant (99)
+ conn.execute(
+ "INSERT INTO Variant VALUES (1, 42, 28.5, 1, 99, 1, ?1)",
+ rusqlite::params![b".:01:02:tip0000001".as_slice()],
+ )
+ .unwrap();
+ conn.execute(
+ "INSERT INTO Variant VALUES (2, 43, 18.0, 0, 0, 1, NULL)",
+ [],
+ )
+ .unwrap();
+ conn.execute(
+ "INSERT INTO Variant VALUES (3, 99, 14.0, 0, 0, 1, ?1)",
+ rusqlite::params![b".:01:02:dual000001".as_slice()],
+ )
+ .unwrap();
+
+ conn.execute(
+ "INSERT INTO MaterialFile VALUES (1, 'tip.layer', ?1, '.:01:02:tip0000001')",
+ rusqlite::params![tip_tar.as_slice()],
+ )
+ .unwrap();
+ conn.execute(
+ "INSERT INTO MaterialFile VALUES (2, 'paper.layer', ?1, '.:01:02:paper00001')",
+ rusqlite::params![paper_tar.as_slice()],
+ )
+ .unwrap();
+ conn.execute(
+ "INSERT INTO MaterialFile VALUES (3, 'color.layer', ?1, '.:01:02:color00001')",
+ rusqlite::params![color_tar.as_slice()],
+ )
+ .unwrap();
+ conn.execute(
+ "INSERT INTO MaterialFile VALUES (4, 'fallback.layer', ?1, '.:01:02:fallback01')",
+ rusqlite::params![fallback_tar.as_slice()],
+ )
+ .unwrap();
+
+ let sut_bytes = conn.serialize(DatabaseName::Main).unwrap().to_vec();
+
+ // Run native SUT extractor
+ let wire = extract_sut_sqlite_binary(&sut_bytes).expect("extract_sut_sqlite_binary failed");
+ assert_eq!(&wire[0..4], b"SUTD");
+ let meta_len = u32::from_le_bytes(wire[4..8].try_into().unwrap()) as usize;
+ let meta: serde_json::Value = serde_json::from_slice(&wire[8..8 + meta_len]).unwrap();
+ let blob_section = &wire[8 + meta_len..];
+
+ // Multi-node selection assertions
+ assert_eq!(meta["nodeName"], "DualTone Ink");
+ assert_eq!(meta["nodeUuid"], "aabbccdd-1122-3344-5566-77889900abcd");
+ assert_eq!(meta["variantId"], 42);
+ assert_eq!(meta["nodeInitVariantId"], 43);
+ assert_eq!(meta["variantScalars"]["BrushSize"], 28.5);
+ assert_eq!(meta["dualVariantScalars"]["VariantID"], 99);
+ assert_eq!(meta["dualVariantScalars"]["BrushSize"], 14.0);
+ assert!(meta["dualVariantBlobs"]["BrushPatternImageArray"].is_object());
+
+ let mats = meta["materials"].as_array().unwrap();
+ assert_eq!(mats.len(), 4);
+
+ // Material 0: 512x512 Gray dual-tone brush tip (NOT 64x64 thumbnail!)
+ let m0 = &mats[0];
+ assert_eq!(m0["width"], 512);
+ assert_eq!(m0["height"], 512);
+ assert_eq!(m0["expressionColor"], "gray");
+ assert_eq!(m0["isPaperTexture"], false);
+ assert_eq!(m0["hasSubColor"], true);
+ assert_eq!(m0["decodedFromLayer"], true);
+ let m0_off = m0["decodedPngOffset"].as_u64().unwrap() as usize;
+ let m0_len = m0["decodedPngLen"].as_u64().unwrap() as usize;
+ let (w0, h0, rgba0) = decode_test_png_rgba(&blob_section[m0_off..m0_off + m0_len]);
+ assert_eq!((w0, h0), (512, 512));
+ // Transparent background pixel (0, 0)
+ assert_eq!(&rgba0[0..4], &[0, 0, 0, 0]);
+ // Opaque black pixel at (20, 20)
+ let blk_i = (20 * 512 + 20) * 4;
+ assert_eq!(&rgba0[blk_i..blk_i + 4], &[0, 0, 0, 255]);
+ // Opaque white pixel at (70, 20) — preserved opaque white, NOT burned to transparent!
+ let wht_i = (20 * 512 + 70) * 4;
+ assert_eq!(&rgba0[wht_i..wht_i + 4], &[255, 255, 255, 255]);
+ // Bottom-right tile pixel at (500, 500)
+ let br_i = (500 * 512 + 500) * 4;
+ assert_eq!(&rgba0[br_i..br_i + 4], &[128, 128, 128, 180]);
+
+ // Material 1: 512x512 PaperTexture
+ let m1 = &mats[1];
+ assert_eq!(m1["width"], 512);
+ assert_eq!(m1["height"], 512);
+ assert_eq!(m1["expressionColor"], "gray");
+ assert_eq!(m1["isPaperTexture"], true);
+ assert_eq!(m1["hasSubColor"], false);
+ assert_eq!(m1["decodedFromLayer"], true);
+ let m1_off = m1["decodedPngOffset"].as_u64().unwrap() as usize;
+ let m1_len = m1["decodedPngLen"].as_u64().unwrap() as usize;
+ let (w1, h1, rgba1) = decode_test_png_rgba(&blob_section[m1_off..m1_off + m1_len]);
+ assert_eq!((w1, h1), (512, 512));
+ let p_i = (12 * 512 + 34) * 4;
+ assert_eq!(&rgba1[p_i..p_i + 4], &[0, 0, 0, 210]);
+
+ // Material 2: 256x256 Color tip preserved unmodified
+ let m2 = &mats[2];
+ assert_eq!(m2["width"], 256);
+ assert_eq!(m2["height"], 256);
+ assert_eq!(m2["expressionColor"], "color");
+ assert_eq!(m2["isPaperTexture"], false);
+ assert_eq!(m2["hasSubColor"], false);
+ let m2_off = m2["decodedPngOffset"].as_u64().unwrap() as usize;
+ let m2_len = m2["decodedPngLen"].as_u64().unwrap() as usize;
+ let (w2, h2, rgba2) = decode_test_png_rgba(&blob_section[m2_off..m2_off + m2_len]);
+ assert_eq!((w2, h2), (256, 256));
+ let c_i = (7 * 256 + 9) * 4;
+ assert_eq!(&rgba2[c_i..c_i + 4], &[240, 80, 30, 200]);
+
+ // Material 3: Missing data/*.layer falls back strictly to 64x64 thumbnail.png
+ let m3 = &mats[3];
+ assert_eq!(m3["width"], 64);
+ assert_eq!(m3["height"], 64);
+ assert_eq!(m3["decodedFromLayer"], false);
+
+ // Verify metadata dump helper
+ let dump = dump_sut_metadata_json(&sut_bytes).expect("dump_sut_metadata_json failed");
+ assert_eq!(dump["selected"]["nodeName"], "DualTone Ink");
+ assert_eq!(dump["selected"]["hasDualVariant"], true);
+ assert_eq!(dump["nodes"].as_array().unwrap().len(), 2);
+ assert_eq!(dump["variants"].as_array().unwrap().len(), 3);
+ assert_eq!(dump["materials"].as_array().unwrap().len(), 4);
+ assert_eq!(dump["materials"][0]["decoded"]["source"], "layer");
+ assert_eq!(dump["materials"][0]["decoded"]["width"], 512);
+ assert_eq!(dump["materials"][3]["decoded"]["source"], "thumbnail");
+ }
+
+ #[test]
+ fn test_inspect_sut_bytes_reports_mapped_and_unmapped_columns() {
+ let mut tile = vec![0u8; TILE_PIXELS * 2];
+ for y in 10..40 {
+ for x in 10..40 {
+ let p = y * TILE_SIZE + x;
+ tile[p] = 255;
+ tile[TILE_PIXELS + p] = 0; // Main color
+ }
+ for x in 50..80 {
+ let p = y * TILE_SIZE + x;
+ tile[p] = 255;
+ tile[TILE_PIXELS + p] = 255; // Sub color
+ }
+ }
+ let tip_layer = build_synthetic_layer_file(256, 256, &[(0, &tile)]);
+ let tip_xml = b"<?xml version=\"1.0\"?><infolist><data>BrushTip</data><expressionColor>Gray</expressionColor></infolist>";
+ let tip_tar = build_ustar_archive(&[
+ ("icedata/layerData.xml", tip_xml),
+ ("data/material_0.layer", &tip_layer),
+ ]);
+
+ let conn = Connection::open_in_memory().unwrap();
+ conn.execute_batch(
+ "
+ CREATE TABLE Node (
+ _PW_ID INTEGER PRIMARY KEY,
+ NodeName TEXT,
+ NodeVariantId INTEGER,
+ NodeInitVariantId INTEGER
+ );
+ CREATE TABLE Variant (
+ _PW_ID INTEGER PRIMARY KEY,
+ VariantID INTEGER,
+ BrushSize REAL,
+ BrushHardness INTEGER,
+ BrushCombineMode INTEGER,
+ TextureCompositeMode INTEGER,
+ UseDualBrush INTEGER,
+ DualBrushVariantId INTEGER,
+ BrushPatternImageArray BLOB,
+ CustomUnmappedExperimentalFlag INTEGER,
+ ZeroDefaultUnmappedColumn INTEGER
+ );
+ CREATE TABLE MaterialFile (
+ _PW_ID INTEGER PRIMARY KEY,
+ OriginalPath TEXT,
+ FileData BLOB,
+ CatalogPath TEXT
+ );
+ ",
+ )
+ .unwrap();
+
+ conn.execute("INSERT INTO Node VALUES (1, 'Coverage Ink', 10, 11)", []).unwrap();
+ conn.execute(
+ "INSERT INTO Variant VALUES (1, 10, 32.0, 4, 2, 7, 1, 20, ?1, 777, 0)",
+ rusqlite::params![b".:01:02:tip0000001".as_slice()],
+ )
+ .unwrap();
+ conn.execute(
+ "INSERT INTO Variant VALUES (2, 20, 12.0, 5, 0, 0, 0, 0, NULL, 0, 0)",
+ [],
+ )
+ .unwrap();
+ conn.execute(
+ "INSERT INTO MaterialFile VALUES (1, 'tip.layer', ?1, '.:01:02:tip0000001')",
+ rusqlite::params![tip_tar.as_slice()],
+ )
+ .unwrap();
+
+ let sut_bytes = conn.serialize(DatabaseName::Main).unwrap().to_vec();
+ let report = inspect_sut_bytes(&sut_bytes, Some("coverage_ink.sut")).expect("inspect_sut_bytes failed");
+
+ assert_eq!(report.selected.node_name.as_deref(), Some("Coverage Ink"));
+ assert_eq!(report.selected.variant_id, Some(10));
+ assert_eq!(report.selected.dual_variant_id, Some(20));
+ assert!(report.selected.has_dual_variant);
+ assert_eq!(report.materials.len(), 1);
+ assert_eq!(report.materials[0].width, Some(256));
+ assert_eq!(report.materials[0].height, Some(256));
+ assert_eq!(report.materials[0].expression_color.as_deref(), Some("gray"));
+ assert!(report.materials[0].has_sub_color);
+
+ let pv = report.primary_variant.as_ref().expect("primary variant missing");
+ assert!(pv.mapped_columns.iter().any(|c| c.column == "BrushSize" && c.parsed_value == serde_json::json!(32.0)));
+ assert!(pv.mapped_columns.iter().any(|c| c.column == "BrushCombineMode" && c.parsed_value == serde_json::json!("multiply")));
+ assert!(pv.mapped_columns.iter().any(|c| c.column == "TextureCompositeMode" && c.parsed_value == serde_json::json!("height")));
+ assert_eq!(pv.unmapped_non_default_columns.len(), 1);
+ assert_eq!(pv.unmapped_non_default_columns[0].column, "CustomUnmappedExperimentalFlag");
+ assert_eq!(pv.unmapped_non_default_columns[0].value, serde_json::json!(777));
+ assert_eq!(pv.unmapped_default_count, 1);
+
+ let human = format_sut_inspection_human(&report);
+ assert!(human.contains("Coverage Ink"));
+ assert!(human.contains("256x256"));
+ assert!(human.contains("CustomUnmappedExperimentalFlag"));
+ assert!(human.contains("DualVariantID: Some(20)"));
+ }
+
+ #[test]
+ fn test_thumbnail_fallback_detects_gray_dual_tone_and_color_semantics() {
+ // Dual-tone grayscale PNG (black outline + white fill on transparent alpha, like Chain.sut thumbnail)
+ let w = 40u32;
+ let h = 16u32;
+ let mut rgba = vec![0u8; (w * h * 4) as usize];
+ for y in 2..14 {
+ for x in 2..38 {
+ let idx = ((y * w + x) * 4) as usize;
+ let is_border = y == 2 || y == 13 || x == 2 || x == 37;
+ let lum = if is_border { 0u8 } else { 255u8 };
+ rgba[idx] = lum;
+ rgba[idx + 1] = lum;
+ rgba[idx + 2] = lum;
+ rgba[idx + 3] = 255;
+ }
+ }
+ let dual_png = encode_rgba8_to_png(w, h, &rgba).unwrap();
+ let tar = build_ustar_archive(&[("thumbnail/thumbnail.png", &dual_png)]);
+ let decoded = decode_material_file_blob(&tar);
+ assert_eq!(decoded.source, "thumbnail");
+ assert_eq!(decoded.width, Some(w));
+ assert_eq!(decoded.height, Some(h));
+ assert_eq!(decoded.expression_color.as_deref(), Some("gray"));
+ assert!(decoded.has_sub_color);
+
+ // Full-color PNG thumbnail -> expression_color = "color", has_sub_color = false
+ let mut color_rgba = vec![0u8; (16 * 16 * 4) as usize];
+ for px in color_rgba.chunks_exact_mut(4) {
+ px.copy_from_slice(&[240, 40, 20, 255]);
+ }
+ let color_png = encode_rgba8_to_png(16, 16, &color_rgba).unwrap();
+ let color_tar = build_ustar_archive(&[("thumbnail/thumbnail.png", &color_png)]);
+ let decoded_color = decode_material_file_blob(&color_tar);
+ assert_eq!(decoded_color.source, "thumbnail");
+ assert_eq!(decoded_color.expression_color.as_deref(), Some("color"));
+ assert!(!decoded_color.has_sub_color);
+ }
}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 805db7f..5750245 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -1,4 +1,4 @@
-mod clip_parser;
+pub mod clip_parser;
mod doc_wire;
mod psd_parser;
mod raster_ops;
diff --git a/src-tauri/src/server.rs b/src-tauri/src/server.rs
index 7f5305c..68aed04 100644
--- a/src-tauri/src/server.rs
+++ b/src-tauri/src/server.rs
@@ -2063,6 +2063,16 @@ fn is_valid_port_suffix(rest: &str) -> bool {
&& port_str.parse::<u16>().is_ok()
}
+fn is_private_lan_ipv4(host: &str) -> bool {
+ let Ok(ip) = host.parse::<std::net::Ipv4Addr>() else {
+ return false;
+ };
+ let octets = ip.octets();
+ ip.is_private()
+ || ip.is_loopback()
+ || (octets[0] == 100 && (octets[1] & 0b1100_0000) == 64) // Tailscale / CGNAT 100.64.0.0/10
+}
+
fn is_allowed_origin(
origin: &str,
local_ip: &str,
@@ -2089,6 +2099,15 @@ fn is_allowed_origin(
return true;
}
}
+ // Allow local private-network Vite dev origins (:1420) for LAN tablet browser testing
+ // without opening arbitrary LAN ports (e.g. :9999 remains blocked against CSWSH).
+ if let Some(host_and_port) = origin.strip_prefix("http://") {
+ if let Some(host_part) = host_and_port.strip_suffix(":1420") {
+ if is_private_lan_ipv4(host_part) {
+ return true;
+ }
+ }
+ }
let local_origin_with_port = format!("http://{}:{}", local_ip, port);
if origin == local_origin_with_port {
return true;
diff --git a/src-tauri/src/tablet_input.rs b/src-tauri/src/tablet_input.rs
index 6d42691..0bdfb09 100644
--- a/src-tauri/src/tablet_input.rs
+++ b/src-tauri/src/tablet_input.rs
@@ -28,6 +28,369 @@ pub struct TabletSample {
pub const SAMPLE_WIRE_BYTES: usize = 36;
+/// Per-pointer contact & frame deduplication state for Windows Ink WM_POINTER messages.
+/// Prevents child/parent WebView2 HWND message duplication or child-HWND WM_POINTERLEAVE
+/// transitions from prematurely ending an active stroke while the stylus is still in contact.
+#[derive(Default, Clone, Copy, Debug)]
+struct InkPointerState {
+ in_contact: bool,
+ consecutive_no_contact: u8,
+ last_frame_id: u32,
+ last_phase: u8,
+ last_perf_count: u64,
+ last_ts_ms: f64,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct InkPointerDecision {
+ pub emit_phase: u8,
+ pub prev_perf_cutoff: u64,
+ pub prev_ts_ms: f64,
+}
+
+#[derive(Default)]
+pub struct InkStateMachine {
+ pointers: std::collections::HashMap<u32, InkPointerState>,
+}
+
+impl InkStateMachine {
+ pub fn reset(&mut self) {
+ self.pointers.clear();
+ }
+
+ pub fn process_message(
+ &mut self,
+ hwnd: isize,
+ main_hwnd: isize,
+ pointer_id: u32,
+ raw_phase_code: u8,
+ newest_frame_id: u32,
+ newest_in_contact: bool,
+ ) -> Option<InkPointerDecision> {
+ if self.pointers.len() > 16 && !self.pointers.contains_key(&pointer_id) {
+ self.pointers.retain(|_, st| st.in_contact);
+ }
+ let st = self.pointers.entry(pointer_id).or_default();
+
+ // Reject out-of-order or duplicate frames across subclassed parent + child HWNDs
+ if newest_frame_id != 0 && st.last_frame_id != 0 {
+ let frame_delta = newest_frame_id.wrapping_sub(st.last_frame_id) as i32;
+ if frame_delta < 0 {
+ return None;
+ }
+ if frame_delta == 0 {
+ if raw_phase_code == st.last_phase {
+ return None;
+ }
+ if st.in_contact && (raw_phase_code == 4 || raw_phase_code == 0) {
+ return None;
+ }
+ if st.last_phase == 3 && raw_phase_code == 2 {
+ return None;
+ }
+ }
+ }
+
+ let emit_phase = match raw_phase_code {
+ 1 => {
+ // WM_POINTERDOWN: avoid emitting duplicate down if another HWND already started contact
+ let p = if st.in_contact { 2 } else { 1 };
+ st.in_contact = true;
+ st.consecutive_no_contact = 0;
+ p
+ }
+ 2 => {
+ // WM_POINTERUPDATE
+ if newest_in_contact {
+ st.consecutive_no_contact = 0;
+ st.in_contact = true;
+ 2
+ } else if st.in_contact {
+ // Require 2 consecutive !INCONTACT frames before ending stroke on update
+ st.consecutive_no_contact = st.consecutive_no_contact.saturating_add(1);
+ if st.consecutive_no_contact >= 2 {
+ st.in_contact = false;
+ st.consecutive_no_contact = 0;
+ 3
+ } else {
+ if newest_frame_id != 0 {
+ st.last_frame_id = newest_frame_id;
+ }
+ return None;
+ }
+ } else {
+ // Hover update while not in contact
+ 0
+ }
+ }
+ 3 => {
+ // WM_POINTERUP: ignore bogus UP while INCONTACT is still set or duplicate UP
+ if newest_in_contact || !st.in_contact {
+ return None;
+ }
+ st.in_contact = false;
+ st.consecutive_no_contact = 0;
+ 3
+ }
+ 4 => {
+ // WM_POINTERLEAVE: NEVER end a stroke while INCONTACT is set or on child-HWND bounce
+ if newest_in_contact {
+ return None;
+ }
+ if st.in_contact {
+ if hwnd != main_hwnd {
+ return None;
+ }
+ st.consecutive_no_contact = st.consecutive_no_contact.saturating_add(1);
+ if st.consecutive_no_contact >= 2 {
+ st.in_contact = false;
+ st.consecutive_no_contact = 0;
+ 3
+ } else {
+ if newest_frame_id != 0 {
+ st.last_frame_id = newest_frame_id;
+ }
+ return None;
+ }
+ } else {
+ 4
+ }
+ }
+ 0 => {
+ // WM_POINTERENTER: do not disrupt an active stroke on child-HWND enter
+ if st.in_contact {
+ return None;
+ }
+ 0
+ }
+ _ => return None,
+ };
+
+ let prev_perf_cutoff = if emit_phase == 2 {
+ st.last_perf_count
+ } else {
+ 0
+ };
+ let prev_ts_ms = st.last_ts_ms;
+
+ if newest_frame_id != 0 {
+ st.last_frame_id = newest_frame_id;
+ }
+ st.last_phase = emit_phase;
+ if emit_phase == 1 || emit_phase == 3 || emit_phase == 4 {
+ st.last_perf_count = 0;
+ }
+
+ Some(InkPointerDecision {
+ emit_phase,
+ prev_perf_cutoff,
+ prev_ts_ms,
+ })
+ }
+
+ pub fn record_emitted(
+ &mut self,
+ pointer_id: u32,
+ emit_phase: u8,
+ max_perf_count: u64,
+ last_ts_ms: f64,
+ ) {
+ if let Some(st) = self.pointers.get_mut(&pointer_id) {
+ if emit_phase == 1 || emit_phase == 2 {
+ st.last_perf_count = max_perf_count;
+ }
+ st.last_ts_ms = last_ts_ms;
+ }
+ }
+}
+
+/// WinTab tip-contact hysteresis state machine.
+/// Debounces single-packet zero-pressure micro-dips while the stylus remains in proximity
+/// (requiring >= 2 consecutive zero-contact packets or >= 12ms before emitting pen-up phase = 3).
+#[derive(Default, Clone, Copy, Debug)]
+pub struct WintabContactState {
+ pub was_down: bool,
+ zero_contact_streak: u8,
+ zero_contact_start_ms: f64,
+ last_nonzero_pressure: f32,
+}
+
+impl WintabContactState {
+ pub fn reset(&mut self) {
+ self.was_down = false;
+ self.zero_contact_streak = 0;
+ self.zero_contact_start_ms = 0.0;
+ self.last_nonzero_pressure = 0.0;
+ }
+
+ /// Processes a WinTab packet and returns `(phase, effective_pressure, effective_tip_down)`.
+ pub fn step(
+ &mut self,
+ out_of_proximity: bool,
+ raw_pressure: f32,
+ tip_button_down: bool,
+ timestamp_ms: f64,
+ ) -> (u8, f32, bool) {
+ if out_of_proximity {
+ self.reset();
+ return (4, 0.0, false);
+ }
+
+ let raw_tip_down = raw_pressure > 0.0 || tip_button_down;
+ if raw_tip_down {
+ self.zero_contact_streak = 0;
+ self.zero_contact_start_ms = 0.0;
+ if raw_pressure > 0.0 {
+ self.last_nonzero_pressure = raw_pressure;
+ }
+ let eff_p = raw_pressure.max(0.006);
+ if !self.was_down {
+ self.was_down = true;
+ (1, eff_p, true)
+ } else {
+ (2, eff_p, true)
+ }
+ } else if self.was_down {
+ if self.zero_contact_streak == 0 {
+ // First zero-pressure packet while still in proximity: hold stroke active
+ self.zero_contact_streak = 1;
+ self.zero_contact_start_ms = timestamp_ms;
+ let hold_p = self.last_nonzero_pressure.clamp(0.006, 0.03);
+ (2, hold_p, true)
+ } else {
+ self.zero_contact_streak = self.zero_contact_streak.saturating_add(1);
+ let elapsed_ms = (timestamp_ms - self.zero_contact_start_ms).max(0.0);
+ if self.zero_contact_streak >= 2 || elapsed_ms >= 12.0 {
+ self.was_down = false;
+ self.zero_contact_streak = 0;
+ self.zero_contact_start_ms = 0.0;
+ (3, 0.0, false)
+ } else {
+ let hold_p = self.last_nonzero_pressure.clamp(0.006, 0.03);
+ (2, hold_p, true)
+ }
+ }
+ } else {
+ (0, 0.0, false)
+ }
+ }
+}
+
+/// WinTab output-space -> virtual-screen coordinate mapper with automatic Y-orientation
+/// calibration against the Win32 system cursor (CXO_SYSTEM).
+///
+/// In WinTab 1.4, requesting negative `lcOutExtY = -vh * scale` flips the Y axis so
+/// `pk_y` spans `[0, +vh * scale]` (0 = top, +H = bottom). Dividing positive `pk_y` by
+/// the signed negative `lcOutExtY` yields negative off-screen coordinates! Some drivers
+/// also ignore negative `lcOutExtY` or output signed negative `pk_y ∈ [-H, 0]`.
+/// `WintabCoordMapper` defaults to WinTab 1.4 (`StandardPos`: divide by `|out_ext_y|`)
+/// and auto-locks the driver's exact orientation on the first off-center cursor sample.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum WintabYMode {
+ StandardPos,
+ FlippedPos,
+ SignedNeg,
+}
+
+#[derive(Debug, Default, Clone, Copy)]
+pub struct WintabCoordMapper {
+ locked_y_mode: Option<WintabYMode>,
+}
+
+impl WintabCoordMapper {
+ pub fn locked_mode(&self) -> Option<WintabYMode> {
+ self.locked_y_mode
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ pub fn map_to_screen(
+ &mut self,
+ pk_x: i32,
+ pk_y: 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,
+ cursor_pos: Option<(i32, i32)>,
+ ) -> (f64, f64) {
+ let abs_ext_x = (out_ext_x as i64).abs().max(1) as f64;
+ let abs_ext_y = (out_ext_y as i64).abs().max(1) as f64;
+ let nx = (pk_x as i64 - out_org_x as i64) as f64 / abs_ext_x;
+ let sx = sys_org_x as f64 + nx * (sys_ext_x as f64);
+
+ let eval_y = |mode: WintabYMode| -> f64 {
+ let dy = (pk_y as i64 - out_org_y as i64) as f64;
+ let ny = match mode {
+ WintabYMode::StandardPos => dy / abs_ext_y,
+ WintabYMode::FlippedPos => 1.0 - (dy / abs_ext_y),
+ WintabYMode::SignedNeg => dy / (-abs_ext_y),
+ };
+ sys_org_y as f64 + ny * (sys_ext_y as f64)
+ };
+
+ let pick_best_mode = |cur_y: f64| -> (WintabYMode, f64, f64) {
+ let candidates = [
+ WintabYMode::StandardPos,
+ WintabYMode::FlippedPos,
+ WintabYMode::SignedNeg,
+ ];
+ let mut best_mode = WintabYMode::StandardPos;
+ let mut best_sy = eval_y(best_mode);
+ let mut best_err = (best_sy - cur_y).abs();
+ for &m in &candidates[1..] {
+ let sy = eval_y(m);
+ let err = (sy - cur_y).abs();
+ if err < best_err {
+ best_err = err;
+ best_mode = m;
+ best_sy = sy;
+ }
+ }
+ (best_mode, best_sy, best_err)
+ };
+
+ let mut sy = if let Some(mode) = self.locked_y_mode {
+ eval_y(mode)
+ } else if let Some((_, cy)) = cursor_pos {
+ let cur_y = cy as f64;
+ let (best_mode, best_sy, best_err) = pick_best_mode(cur_y);
+ let mid_y = sys_org_y as f64 + (sys_ext_y as f64) * 0.5;
+ let off_center = (cur_y - mid_y).abs() > (sys_ext_y.abs() as f64) * 0.06;
+ if best_err <= 24.0 && (off_center || best_mode == WintabYMode::SignedNeg) {
+ self.locked_y_mode = Some(best_mode);
+ }
+ best_sy
+ } else if out_ext_y < 0 && pk_y < out_org_y - 16 {
+ eval_y(WintabYMode::SignedNeg)
+ } else {
+ eval_y(WintabYMode::StandardPos)
+ };
+
+ // Guard against monitor/DPI layout changes or driver quirks: re-calibrate once,
+ // and fall back to cursor position if WinTab coords diverge > 48px from system cursor.
+ if let Some((cx, cy)) = cursor_pos {
+ let cur_x = cx as f64;
+ let cur_y = cy as f64;
+ if (sy - cur_y).abs() > 48.0 {
+ let (best_mode, best_sy, best_err) = pick_best_mode(cur_y);
+ if best_err <= 24.0 {
+ self.locked_y_mode = Some(best_mode);
+ sy = best_sy;
+ }
+ }
+ if (sx - cur_x).abs() > 48.0 || (sy - cur_y).abs() > 48.0 {
+ return (cur_x, cur_y);
+ }
+ }
+
+ (sx, sy)
+ }
+}
+
/// 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> {
@@ -52,12 +415,12 @@ pub fn pack_tablet_samples(samples: &[TabletSample]) -> Vec<u8> {
mod win_impl {
use super::*;
use std::ffi::c_void;
- use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering};
+ use std::sync::atomic::{AtomicBool, AtomicIsize, AtomicU64, 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::Foundation::{FreeLibrary, BOOL, HANDLE, HWND, LPARAM, LRESULT, POINT, RECT, WPARAM};
use windows_sys::Win32::Graphics::Gdi::ScreenToClient;
- use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW};
+ use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress, LoadLibraryW};
use windows_sys::Win32::System::Performance::{
QueryPerformanceCounter, QueryPerformanceFrequency,
};
@@ -82,12 +445,16 @@ mod win_impl {
};
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,
+ GetCursorPos, GetForegroundWindow, GetMessageW, GetSystemMetrics, PostMessageW,
+ PostThreadMessageW, RegisterClassW, TranslateMessage, HWND_MESSAGE, MSG, PT_PEN,
+ SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN,
+ WM_ACTIVATE, WM_ACTIVATEAPP, WM_APP, WM_NCACTIVATE, WM_POINTERDOWN, WM_POINTERENTER,
+ WM_POINTERLEAVE, WM_POINTERUP, WM_POINTERUPDATE, WM_QUIT, WM_SETFOCUS, WNDCLASSW,
};
+ const WM_APP_WINTAB_FOCUS: u32 = WM_APP + 1;
+ const WINTAB_FOCUS_SUBCLASS_ID: usize = 0x494E_4B57; // "INKW"
+
// --- WinTab ABI constants & types ---
const WTI_INTERFACE: u32 = 1;
const IFC_WINTABID: u32 = 1;
@@ -98,7 +465,6 @@ mod win_impl {
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;
@@ -200,6 +566,7 @@ mod win_impl {
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 FnWTEnable = unsafe extern "system" fn(HCTX, BOOL) -> BOOL;
type FnWTQueueSizeSet = unsafe extern "system" fn(HCTX, i32) -> BOOL;
struct WintabLib {
@@ -209,6 +576,7 @@ mod win_impl {
wt_close: FnWTClose,
wt_packets_get: FnWTPacketsGet,
wt_overlap: Option<FnWTOverlap>,
+ wt_enable: Option<FnWTEnable>,
wt_queue_size_set: Option<FnWTQueueSizeSet>,
}
@@ -227,6 +595,7 @@ mod win_impl {
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_enable = GetProcAddress(module, b"WTEnable\0".as_ptr());
let wt_queue_size_set = GetProcAddress(module, b"WTQueueSizeSet\0".as_ptr());
Some(Self {
@@ -236,6 +605,7 @@ mod win_impl {
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_enable: wt_enable.map(|f| std::mem::transmute(f)),
wt_queue_size_set: wt_queue_size_set.map(|f| std::mem::transmute(f)),
})
}
@@ -251,7 +621,7 @@ mod win_impl {
}
}
- fn qpc_now_ms() -> f64 {
+ fn qpc_freq_per_ms() -> f64 {
static FREQ: LazyLock<f64> = LazyLock::new(|| unsafe {
let mut f = 0i64;
QueryPerformanceFrequency(&mut f);
@@ -261,23 +631,84 @@ mod win_impl {
1.0
}
});
+ *FREQ
+ }
+
+ fn qpc_now_ms() -> f64 {
unsafe {
let mut now = 0i64;
QueryPerformanceCounter(&mut now);
- (now as f64) / *FREQ
+ (now as f64) / qpc_freq_per_ms()
}
}
- fn screen_to_css_client(main_hwnd: HWND, sx: i32, sy: i32) -> (f32, f32) {
+ fn screen_to_css_client_f64(main_hwnd: HWND, sx: f64, sy: f64) -> (f32, f32) {
unsafe {
- let mut pt = POINT { x: sx, y: sy };
+ let ix = sx.floor() as i32;
+ let iy = sy.floor() as i32;
+ let fx = sx - (ix as f64);
+ let fy = sy - (iy as f64);
+ let mut pt = POINT { x: ix, y: iy };
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)
+ let scale = if dpi > 0 { (dpi as f64) / 96.0 } else { 1.0 };
+ (
+ ((pt.x as f64 + fx) / scale) as f32,
+ ((pt.y as f64 + fy) / scale) as f32,
+ )
}
}
+ type FnGetPointerDeviceRects =
+ unsafe extern "system" fn(HANDLE, *mut RECT, *mut RECT) -> BOOL;
+
+ fn try_himetric_to_screen_f64(
+ source_device: HANDLE,
+ himetric_x: i32,
+ himetric_y: i32,
+ pixel_x: i32,
+ pixel_y: i32,
+ ) -> (f64, f64) {
+ static FN_PTR: LazyLock<Option<FnGetPointerDeviceRects>> = LazyLock::new(|| unsafe {
+ let user32: Vec<u16> = "user32.dll\0".encode_utf16().collect();
+ let hmod = GetModuleHandleW(user32.as_ptr());
+ if hmod.is_null() {
+ return None;
+ }
+ let proc = GetProcAddress(hmod, b"GetPointerDeviceRects\0".as_ptr())?;
+ Some(std::mem::transmute(proc))
+ });
+
+ if !source_device.is_null() {
+ if let Some(get_rects) = *FN_PTR {
+ unsafe {
+ let mut dev_rect: RECT = std::mem::zeroed();
+ let mut disp_rect: RECT = std::mem::zeroed();
+ if get_rects(source_device, &mut dev_rect, &mut disp_rect) != 0 {
+ let dev_w = (dev_rect.right - dev_rect.left) as f64;
+ let dev_h = (dev_rect.bottom - dev_rect.top) as f64;
+ let disp_w = (disp_rect.right - disp_rect.left) as f64;
+ let disp_h = (disp_rect.bottom - disp_rect.top) as f64;
+ if dev_w > 0.0 && dev_h > 0.0 && disp_w > 0.0 && disp_h > 0.0 {
+ let sx = disp_rect.left as f64
+ + ((himetric_x - dev_rect.left) as f64 / dev_w) * disp_w;
+ let sy = disp_rect.top as f64
+ + ((himetric_y - dev_rect.top) as f64 / dev_h) * disp_h;
+ // Guard against exotic multi-monitor DPI discrepancies:
+ // accept sub-pixel HIMETRIC only when tightly aligned with ptPixelLocationRaw.
+ if (sx - pixel_x as f64).abs() <= 2.0
+ && (sy - pixel_y as f64).abs() <= 2.0
+ {
+ return (sx, sy);
+ }
+ }
+ }
+ }
+ }
+ }
+ (pixel_x as f64, pixel_y as f64)
+ }
+
fn wintab_orientation_to_tilt(
ori: Orientation,
az_max: i32,
@@ -312,6 +743,9 @@ mod win_impl {
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_MSG_HWND: AtomicIsize = AtomicIsize::new(0);
+ static WINTAB_FOCUS_SUBCLASS_HWND: AtomicIsize = AtomicIsize::new(0);
+ static LAST_WINTAB_PACKET_MS_BITS: AtomicU64 = AtomicU64::new(0);
static WINTAB_THREAD: LazyLock<Mutex<Option<JoinHandle<()>>>> =
LazyLock::new(|| Mutex::new(None));
static CURRENT_STATUS: LazyLock<Mutex<TabletStatus>> = LazyLock::new(|| {
@@ -339,6 +773,9 @@ mod win_impl {
}
}
+ static INK_DEDUP: LazyLock<Mutex<InkStateMachine>> =
+ LazyLock::new(|| Mutex::new(InkStateMachine::default()));
+
// --- Windows Ink WM_POINTER subclass callback ---
unsafe extern "system" fn ink_subclass_proc(
hwnd: HWND,
@@ -358,7 +795,17 @@ mod win_impl {
_ => None,
};
- if let Some(phase_code) = phase {
+ if let Some(raw_phase_code) = phase {
+ // In "auto" dual-hook mode, defer to WinTab whenever WinTab is actively delivering packets.
+ if WINTAB_RUNNING.load(Ordering::Relaxed) {
+ let last_wt_bits = LAST_WINTAB_PACKET_MS_BITS.load(Ordering::Relaxed);
+ if last_wt_bits != 0 {
+ let last_wt_ms = f64::from_bits(last_wt_bits);
+ if qpc_now_ms() - last_wt_ms < 500.0 {
+ return;
+ }
+ }
+ }
let pointer_id = (wparam & 0xFFFF) as u32;
let mut ptype = 0i32;
if GetPointerType(pointer_id, &mut ptype) != 0 && ptype == PT_PEN {
@@ -369,24 +816,80 @@ mod win_impl {
&& count > 0
{
let n = (count as usize).min(64);
+ let newest_frame_id = history[0].pointerInfo.frameId;
+ let newest_in_contact =
+ (history[0].pointerInfo.pointerFlags & POINTER_FLAG_INCONTACT) != 0;
let ts_now = qpc_now_ms();
+ let qpc_ms = qpc_freq_per_ms();
+
+ // Per-pointer contact tracking & cross-HWND frame deduplication so
+ // child/parent WebView2 HWND transitions NEVER emit spurious leave/up mid-stroke.
+ let decision = {
+ let Ok(mut dedup) = INK_DEDUP.lock() else {
+ return;
+ };
+ dedup.process_message(
+ hwnd as isize,
+ main_hwnd as isize,
+ pointer_id,
+ raw_phase_code,
+ newest_frame_id,
+ newest_in_contact,
+ )
+ };
+ let Some(decision) = decision else {
+ return;
+ };
+ let phase_code = decision.emit_phase;
+ let prev_perf_cutoff = decision.prev_perf_cutoff;
+ let prev_ts_ms = decision.prev_ts_ms;
+
let mut samples = Vec::with_capacity(n);
+ let mut max_perf_emitted = prev_perf_cutoff;
+ let mut running_ts = prev_ts_ms;
+
+ // Fallback span when hardware PerformanceCount is unavailable
+ let fallback_span = if prev_ts_ms > 0.0 && ts_now > prev_ts_ms + 0.5 {
+ (ts_now - prev_ts_ms).min(40.0)
+ } else {
+ (n as f64) * 4.0
+ };
+ let fallback_start = ts_now - fallback_span;
// History is reverse chronological (0 = newest), emit oldest -> newest
- for idx in (0..n).rev() {
+ for (emit_pos, idx) in (0..n).rev().enumerate() {
let info = &history[idx];
let pinfo = &info.pointerInfo;
- let (cx, cy) = screen_to_css_client(
- main_hwnd,
+
+ // Skip already-emitted overlapping history samples during drag
+ if phase_code == 2
+ && prev_perf_cutoff > 0
+ && pinfo.PerformanceCount > 0
+ && pinfo.PerformanceCount <= prev_perf_cutoff
+ {
+ continue;
+ }
+ if pinfo.PerformanceCount > max_perf_emitted {
+ max_perf_emitted = pinfo.PerformanceCount;
+ }
+
+ let (sx, sy) = try_himetric_to_screen_f64(
+ pinfo.sourceDevice,
+ pinfo.ptHimetricLocationRaw.x,
+ pinfo.ptHimetricLocationRaw.y,
pinfo.ptPixelLocationRaw.x,
pinfo.ptPixelLocationRaw.y,
);
+ let (cx, cy) = screen_to_css_client_f64(main_hwnd, sx, sy);
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)
+ let p = (info.pressure as f32 / 1024.0).clamp(0.0, 1.0);
+ if in_contact { p.max(0.006) } else { p }
} else if in_contact {
- 0.5
+ // Never fabricate a fake 0.5 pressure spike on initial WM_POINTERDOWN
+ // before the pen digitizer populates PEN_MASK_PRESSURE.
+ if phase_code == 1 { 0.006 } else { 0.5 }
} else {
0.0
};
@@ -428,6 +931,20 @@ mod win_impl {
0
};
+ let raw_sample_ts = if pinfo.PerformanceCount > 0 {
+ (pinfo.PerformanceCount as f64) / qpc_ms
+ } else {
+ fallback_start
+ + fallback_span * ((emit_pos + 1) as f64 / (n as f64))
+ };
+ let sample_ts = if running_ts > 0.0 && raw_sample_ts < running_ts + 0.25
+ {
+ running_ts + 0.5
+ } else {
+ raw_sample_ts
+ };
+ running_ts = sample_ts;
+
samples.push(TabletSample {
client_x: cx,
client_y: cy,
@@ -435,14 +952,24 @@ mod win_impl {
tilt_x,
tilt_y,
twist,
- timestamp_ms: ts_now,
+ timestamp_ms: sample_ts,
buttons,
phase: sample_phase,
backend: 2,
});
}
- send_samples(&samples);
+ if !samples.is_empty() {
+ if let Ok(mut dedup) = INK_DEDUP.lock() {
+ dedup.record_emitted(
+ pointer_id,
+ phase_code,
+ max_perf_emitted,
+ running_ts,
+ );
+ }
+ send_samples(&samples);
+ }
}
}
}
@@ -491,9 +1018,14 @@ mod win_impl {
RemoveWindowSubclass(raw as HWND, Some(ink_subclass_proc), SUBCLASS_ID);
}
}
+ if let Ok(mut dedup) = INK_DEDUP.lock() {
+ dedup.reset();
+ }
}
// --- WinTab dedicated high-priority message-window thread ---
+ const WINTAB_SUBPIXEL_SCALE: i32 = 16;
+
struct WintabRuntime {
lib: WintabLib,
hctx: HCTX,
@@ -510,13 +1042,68 @@ mod win_impl {
sys_org_y: i32,
sys_ext_x: i32,
sys_ext_y: i32,
- was_down: bool,
+ coord_mapper: WintabCoordMapper,
+ contact: WintabContactState,
+ was_foreground: bool,
+ last_ts_ms: f64,
}
thread_local! {
static WT_RT: std::cell::RefCell<Option<WintabRuntime>> = const { std::cell::RefCell::new(None) };
}
+ unsafe extern "system" fn wintab_focus_subclass_proc(
+ hwnd: HWND,
+ msg: u32,
+ wparam: WPARAM,
+ lparam: LPARAM,
+ _uid_subclass: usize,
+ _dw_ref_data: usize,
+ ) -> LRESULT {
+ let should_raise = match msg {
+ WM_ACTIVATE => (wparam & 0xFFFF) != 0,
+ WM_ACTIVATEAPP => wparam != 0,
+ WM_NCACTIVATE => wparam != 0,
+ WM_SETFOCUS => true,
+ _ => false,
+ };
+ if should_raise {
+ let wt_hwnd = WINTAB_MSG_HWND.load(Ordering::Acquire);
+ if wt_hwnd != 0 {
+ PostMessageW(wt_hwnd as HWND, WM_APP_WINTAB_FOCUS, 0, 0);
+ }
+ }
+ DefSubclassProc(hwnd, msg, wparam, lparam)
+ }
+
+ fn install_wintab_focus_hook(main_hwnd: HWND) {
+ uninstall_wintab_focus_hook();
+ unsafe {
+ if SetWindowSubclass(
+ main_hwnd,
+ Some(wintab_focus_subclass_proc),
+ WINTAB_FOCUS_SUBCLASS_ID,
+ 0,
+ ) != 0
+ {
+ WINTAB_FOCUS_SUBCLASS_HWND.store(main_hwnd as isize, Ordering::SeqCst);
+ }
+ }
+ }
+
+ fn uninstall_wintab_focus_hook() {
+ let prev = WINTAB_FOCUS_SUBCLASS_HWND.swap(0, Ordering::SeqCst);
+ if prev != 0 {
+ unsafe {
+ RemoveWindowSubclass(
+ prev as HWND,
+ Some(wintab_focus_subclass_proc),
+ WINTAB_FOCUS_SUBCLASS_ID,
+ );
+ }
+ }
+ }
+
unsafe extern "system" fn wintab_wnd_proc(
hwnd: HWND,
msg: u32,
@@ -524,18 +1111,32 @@ mod win_impl {
lparam: LPARAM,
) -> LRESULT {
let _ = std::panic::catch_unwind(|| {
- if msg == WT_PACKET {
+ if msg == WM_APP_WINTAB_FOCUS {
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(enable) = rt.lib.wt_enable {
+ enable(rt.hctx, 1);
+ }
if let Some(overlap) = rt.lib.wt_overlap {
- let fg = GetForegroundWindow();
- if fg == rt.main_hwnd {
+ overlap(rt.hctx, 1);
+ }
+ rt.was_foreground = true;
+ });
+ } else if msg == WT_PACKET {
+ WT_RT.with(|cell| {
+ let mut borrow = cell.borrow_mut();
+ let Some(rt) = borrow.as_mut() else { return };
+
+ // Only assert WinTab Z-order overlap when foreground transitions to our window
+ // (avoid calling WTOverlap at 250Hz inside every WT_PACKET, which stalls some drivers)
+ let is_fg = GetForegroundWindow() == rt.main_hwnd;
+ if is_fg && !rt.was_foreground {
+ if let Some(overlap) = rt.lib.wt_overlap {
overlap(rt.hctx, 1);
}
}
+ rt.was_foreground = is_fg;
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);
@@ -543,27 +1144,71 @@ mod win_impl {
return;
}
+ let count = n as usize;
let ts_now = qpc_now_ms();
- let mut samples = Vec::with_capacity(n as usize);
+ LAST_WINTAB_PACKET_MS_BITS.store(ts_now.to_bits(), Ordering::Relaxed);
+ let mut samples = Vec::with_capacity(count);
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 mut cur_pt = POINT { x: 0, y: 0 };
+ let cursor_pos = if GetCursorPos(&mut cur_pt) != 0 {
+ Some((cur_pt.x, cur_pt.y))
+ } else {
+ None
+ };
+
+ // Pre-calibrate Y-axis orientation on newest packet (which aligns with GetCursorPos)
+ // before mapping older packets in this burst.
+ if rt.coord_mapper.locked_mode().is_none() {
+ let newest = &buf[count - 1];
+ let _ = rt.coord_mapper.map_to_screen(
+ newest.pk_x,
+ newest.pk_y,
+ rt.out_org_x,
+ rt.out_org_y,
+ rt.out_ext_x,
+ rt.out_ext_y,
+ rt.sys_org_x,
+ rt.sys_org_y,
+ rt.sys_ext_x,
+ rt.sys_ext_y,
+ cursor_pos,
+ );
+ }
- let pressure = (pkt.pk_normal_pressure as f32 / denom_p).clamp(0.0, 1.0);
+ // Resolve true hardware packet timestamps from pk_time (with clean even interpolation fallback)
+ let newest_pk_time = buf[count - 1].pk_time;
+ let oldest_pk_time = buf[0].pk_time;
+ let pk_span = newest_pk_time.wrapping_sub(oldest_pk_time);
+ let has_valid_pk_span = count > 1 && pk_span > 0 && pk_span <= 200;
+ let fallback_span = if rt.last_ts_ms > 0.0 && ts_now > rt.last_ts_ms + 0.5 {
+ (ts_now - rt.last_ts_ms).min(40.0)
+ } else {
+ (count as f64) * 4.0
+ };
+ let fallback_start = ts_now - fallback_span;
+
+ for (idx, pkt) in buf[..count].iter().enumerate() {
+ // Map WinTab high-res output space -> sub-pixel virtual screen -> CSS client pixels.
+ // Pass cursor_pos only for the newest packet in the burst so older history points
+ // preserve exact sub-pixel positions while still guarding against driver quirks.
+ let pkt_cursor = if idx + 1 == count { cursor_pos } else { None };
+ let (sx, sy) = rt.coord_mapper.map_to_screen(
+ pkt.pk_x,
+ pkt.pk_y,
+ rt.out_org_x,
+ rt.out_org_y,
+ rt.out_ext_x,
+ rt.out_ext_y,
+ rt.sys_org_x,
+ rt.sys_org_y,
+ rt.sys_ext_x,
+ rt.sys_ext_y,
+ pkt_cursor,
+ );
+ let (cx, cy) = screen_to_css_client_f64(rt.main_hwnd, sx, sy);
+
+ let raw_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,
@@ -571,9 +1216,33 @@ mod win_impl {
rt.twist_max,
);
- let tip_down = pressure > 0.001 || (pkt.pk_buttons & 1) != 0;
+ let raw_sample_ts = if has_valid_pk_span {
+ let age_ms = newest_pk_time.wrapping_sub(pkt.pk_time).min(200) as f64;
+ ts_now - age_ms
+ } else if count > 1 {
+ fallback_start + fallback_span * ((idx + 1) as f64 / (count as f64))
+ } else {
+ ts_now
+ };
+ let sample_ts = if rt.last_ts_ms > 0.0 && raw_sample_ts < rt.last_ts_ms + 0.25
+ {
+ rt.last_ts_ms + 0.5
+ } else {
+ raw_sample_ts
+ };
+ rt.last_ts_ms = sample_ts;
+
+ let out_of_proximity = (pkt.pk_status & TPS_PROXIMITY) != 0;
+ let tip_button_down = (pkt.pk_buttons & 1) != 0;
+ let (phase, pressure, eff_tip_down) = rt.contact.step(
+ out_of_proximity,
+ raw_pressure,
+ tip_button_down,
+ sample_ts,
+ );
+
let mut buttons: u16 = 0;
- if tip_down {
+ if eff_tip_down {
buttons |= 1;
}
if (pkt.pk_buttons & 2) != 0 {
@@ -586,21 +1255,6 @@ mod win_impl {
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,
@@ -608,7 +1262,7 @@ mod win_impl {
tilt_x,
tilt_y,
twist,
- timestamp_ms: ts_now,
+ timestamp_ms: sample_ts,
buttons,
phase,
backend: 1,
@@ -622,7 +1276,7 @@ mod win_impl {
if !entering {
WT_RT.with(|cell| {
if let Some(rt) = cell.borrow_mut().as_mut() {
- rt.was_down = false;
+ rt.contact.reset();
}
});
send_samples(&[TabletSample {
@@ -761,7 +1415,7 @@ mod win_impl {
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_options |= CXO_SYSTEM | CXO_MESSAGES;
lc.lc_pkt_data = PACKET_DATA_MASK;
lc.lc_pkt_mode = 0;
lc.lc_move_mask = PACKET_DATA_MASK;
@@ -769,8 +1423,8 @@ mod win_impl {
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_out_ext_x = vw.saturating_mul(WINTAB_SUBPIXEL_SCALE);
+ lc.lc_out_ext_y = (-vh).saturating_mul(WINTAB_SUBPIXEL_SCALE); // top-down Y with 1/16px subpixel precision
lc.lc_sys_org_x = vx;
lc.lc_sys_org_y = vy;
lc.lc_sys_ext_x = vw;
@@ -823,6 +1477,13 @@ mod win_impl {
if let Some(qset) = lib.wt_queue_size_set {
qset(hctx, 128);
}
+ if let Some(enable) = lib.wt_enable {
+ enable(hctx, 1);
+ }
+ if let Some(overlap) = lib.wt_overlap {
+ overlap(hctx, 1);
+ }
+ WINTAB_MSG_HWND.store(msg_hwnd as isize, Ordering::Release);
WT_RT.with(|cell| {
*cell.borrow_mut() = Some(WintabRuntime {
@@ -841,7 +1502,10 @@ mod win_impl {
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,
+ coord_mapper: WintabCoordMapper::default(),
+ contact: WintabContactState::default(),
+ was_foreground: GetForegroundWindow() == main_hwnd as HWND,
+ last_ts_ms: 0.0,
});
});
@@ -855,6 +1519,7 @@ mod win_impl {
DispatchMessageW(&msg);
}
+ WINTAB_MSG_HWND.store(0, Ordering::Release);
WT_RT.with(|cell| {
if let Some(rt) = cell.borrow_mut().take() {
(rt.lib.wt_close)(rt.hctx);
@@ -875,6 +1540,7 @@ mod win_impl {
if let Ok(mut guard) = WINTAB_THREAD.lock() {
*guard = Some(handle);
}
+ install_wintab_focus_hook(main_hwnd as HWND);
Ok(info)
}
Err(e) => {
@@ -885,7 +1551,10 @@ mod win_impl {
}
fn stop_wintab_thread() {
+ uninstall_wintab_focus_hook();
WINTAB_RUNNING.store(false, Ordering::SeqCst);
+ WINTAB_MSG_HWND.store(0, Ordering::SeqCst);
+ LAST_WINTAB_PACKET_MS_BITS.store(0, Ordering::Relaxed);
let tid = WINTAB_THREAD_ID.load(Ordering::SeqCst);
if tid != 0 {
unsafe {
@@ -938,10 +1607,15 @@ mod win_impl {
return Ok(get_status());
}
_ => {
- // "auto": prefer WinTab if driver + tablet context opens, else Windows Ink WM_POINTER
+ // "auto": prefer WinTab if driver + tablet context opens, and ALSO install Windows Ink
+ // WM_POINTER hooks as a live fallback (arbitrated by LAST_WINTAB_PACKET_MS_BITS) so
+ // toggling "Windows Ink" ON/OFF in Wacom/XP-Pen/Huion drivers always delivers full pressure.
if wt_avail {
match start_wintab_thread(main_hwnd_raw) {
- Ok((dev, mp)) => ("wintab".to_string(), dev, mp),
+ Ok((dev, mp)) => {
+ let _ = install_windows_ink_hooks(hwnd.0 as HWND);
+ ("wintab".to_string(), dev, mp)
+ }
Err(_) => {
install_windows_ink_hooks(hwnd.0 as HWND)?;
(
@@ -1100,4 +1774,205 @@ mod tests {
assert_eq!(buf[38], 2);
assert_eq!(buf[39], 1);
}
+
+ #[test]
+ fn test_ink_state_machine_ignores_child_hwnd_leave_during_active_contact() {
+ let mut sm = InkStateMachine::default();
+ let main_hwnd: isize = 1000;
+ let child_hwnd: isize = 2000;
+ let pid: u32 = 42;
+
+ // 1. Pen down on child HWND
+ let d1 = sm
+ .process_message(child_hwnd, main_hwnd, pid, 1, 100, true)
+ .expect("pen down should emit");
+ assert_eq!(d1.emit_phase, 1);
+
+ // 2. Duplicate pen down on main HWND with same frameId is dropped
+ assert!(sm
+ .process_message(main_hwnd, main_hwnd, pid, 1, 100, true)
+ .is_none());
+
+ // 3. Normal drag update
+ let d2 = sm
+ .process_message(child_hwnd, main_hwnd, pid, 2, 101, true)
+ .expect("drag should emit");
+ assert_eq!(d2.emit_phase, 2);
+
+ // 4. Spurious WM_POINTERLEAVE from child HWND while INCONTACT is still set -> dropped
+ assert!(sm
+ .process_message(child_hwnd, main_hwnd, pid, 4, 101, true)
+ .is_none());
+
+ // 5. Spurious WM_POINTERLEAVE from child HWND transition even with INCONTACT=false -> dropped
+ assert!(sm
+ .process_message(child_hwnd, main_hwnd, pid, 4, 102, false)
+ .is_none());
+
+ // 6. Out-of-order older frame from parent HWND -> dropped
+ assert!(sm
+ .process_message(main_hwnd, main_hwnd, pid, 2, 100, true)
+ .is_none());
+
+ // 7. Subsequent drag continues uninterrupted
+ let d3 = sm
+ .process_message(main_hwnd, main_hwnd, pid, 2, 103, true)
+ .expect("subsequent drag should continue");
+ assert_eq!(d3.emit_phase, 2);
+
+ // 8. Single !in_contact update glitch does not end stroke
+ assert!(sm
+ .process_message(main_hwnd, main_hwnd, pid, 2, 104, false)
+ .is_none());
+
+ // 9. Recovery frame with in_contact=true resets streak and keeps stroke alive
+ let d4 = sm
+ .process_message(main_hwnd, main_hwnd, pid, 2, 105, true)
+ .expect("recovery drag should emit");
+ assert_eq!(d4.emit_phase, 2);
+
+ // 10. Genuine WM_POINTERUP with in_contact=false cleanly ends stroke
+ let d5 = sm
+ .process_message(child_hwnd, main_hwnd, pid, 3, 106, false)
+ .expect("genuine pen up should emit");
+ assert_eq!(d5.emit_phase, 3);
+
+ // 11. Duplicate WM_POINTERUP from main HWND is dropped
+ assert!(sm
+ .process_message(main_hwnd, main_hwnd, pid, 3, 106, false)
+ .is_none());
+
+ // 12. Consecutive !in_contact updates without WM_POINTERUP cleanly end stroke on 2nd frame
+ let d6 = sm
+ .process_message(main_hwnd, main_hwnd, pid, 1, 200, true)
+ .expect("second stroke down");
+ assert_eq!(d6.emit_phase, 1);
+ assert!(sm
+ .process_message(main_hwnd, main_hwnd, pid, 2, 201, false)
+ .is_none());
+ let d7 = sm
+ .process_message(main_hwnd, main_hwnd, pid, 2, 202, false)
+ .expect("second consecutive !in_contact frame ends stroke");
+ assert_eq!(d7.emit_phase, 3);
+ }
+
+ #[test]
+ fn test_wintab_contact_debounces_single_packet_pressure_dip() {
+ let mut wt = WintabContactState::default();
+
+ // 1. Light pen down (e.g. 4 / 8192 = 0.000488, previously dropped by > 0.001 check!)
+ let (p1, pr1, down1) = wt.step(false, 0.0005, false, 100.0);
+ assert_eq!(p1, 1);
+ assert!(down1);
+ assert!(pr1 >= 0.006);
+
+ // 2. Normal drag
+ let (p2, pr2, down2) = wt.step(false, 0.35, true, 104.0);
+ assert_eq!(p2, 2);
+ assert!(down2);
+ assert!((pr2 - 0.35).abs() < 1e-5);
+
+ // 3. Single-packet zero-pressure micro-dip while still in proximity -> MUST NOT end stroke!
+ let (p3, pr3, down3) = wt.step(false, 0.0, false, 108.0);
+ assert_eq!(p3, 2);
+ assert!(down3);
+ assert!(pr3 >= 0.006);
+
+ // 4. Next packet recovers light pressure -> continues seamlessly as phase=2
+ let (p4, pr4, down4) = wt.step(false, 0.02, false, 112.0);
+ assert_eq!(p4, 2);
+ assert!(down4);
+ assert!((pr4 - 0.02).abs() < 1e-5);
+
+ // 5. Genuine lift: 2 consecutive zero-pressure packets cleanly emit phase=3 on the 2nd packet
+ let (p5, _, down5) = wt.step(false, 0.0, false, 116.0);
+ assert_eq!(p5, 2);
+ assert!(down5);
+ let (p6, pr6, down6) = wt.step(false, 0.0, false, 120.0);
+ assert_eq!(p6, 3);
+ assert!(!down6);
+ assert_eq!(pr6, 0.0);
+
+ // 6. Hover packets stay phase=0
+ let (p7, pr7, down7) = wt.step(false, 0.0, false, 124.0);
+ assert_eq!(p7, 0);
+ assert!(!down7);
+ assert_eq!(pr7, 0.0);
+ }
+
+ #[test]
+ fn test_wintab_coord_mapper_handles_negative_out_ext_y_without_offscreen_y() {
+ // WinTab 1.4 spec: lcOutExtY = -vh * 16 flips Y so pk_y spans [0, +vh * 16] (positive).
+ // Previously dividing positive pk_y by negative out_ext_y yielded negative off-screen sy!
+ let mut mapper = WintabCoordMapper::default();
+ let (sx, sy) = mapper.map_to_screen(
+ 1280 * 16 + 8, // 1280.5px
+ 400 * 16 + 4, // 400.25px (positive!)
+ 0,
+ 0,
+ 2560 * 16,
+ -1600 * 16, // negative lcOutExtY
+ 0,
+ 0,
+ 2560,
+ 1600,
+ Some((1280, 400)),
+ );
+ assert!((sx - 1280.5).abs() < 1e-4, "expected 1280.5, got {}", sx);
+ assert!((sy - 400.25).abs() < 1e-4, "expected +400.25 (not -400.25!), got {}", sy);
+ assert_eq!(mapper.locked_mode(), Some(WintabYMode::StandardPos));
+
+ // Subsequent history samples without cursor_pos preserve exact sub-pixel coordinates
+ let (sx2, sy2) = mapper.map_to_screen(
+ 640 * 16 + 12,
+ 1200 * 16 + 8,
+ 0,
+ 0,
+ 2560 * 16,
+ -1600 * 16,
+ 0,
+ 0,
+ 2560,
+ 1600,
+ None,
+ );
+ assert!((sx2 - 640.75).abs() < 1e-4);
+ assert!((sy2 - 1200.5).abs() < 1e-4);
+
+ // Driver that outputs bottom-up pk_y despite negative lcOutExtY auto-calibrates to FlippedPos
+ let mut flipped = WintabCoordMapper::default();
+ let (_, sy_f) = flipped.map_to_screen(
+ 500 * 16,
+ 1300 * 16, // bottom-up value for screen y=300 on 1600px tall screen
+ 0,
+ 0,
+ 2560 * 16,
+ -1600 * 16,
+ 0,
+ 0,
+ 2560,
+ 1600,
+ Some((500, 300)),
+ );
+ assert!((sy_f - 300.0).abs() < 1e-4);
+ assert_eq!(flipped.locked_mode(), Some(WintabYMode::FlippedPos));
+
+ // Driver that outputs signed-negative pk_y in [-H, 0] auto-calibrates to SignedNeg
+ let mut neg = WintabCoordMapper::default();
+ let (_, sy_n) = neg.map_to_screen(
+ 500 * 16,
+ -300 * 16,
+ 0,
+ 0,
+ 2560 * 16,
+ -1600 * 16,
+ 0,
+ 0,
+ 2560,
+ 1600,
+ Some((500, 300)),
+ );
+ assert!((sy_n - 300.0).abs() < 1e-4);
+ assert_eq!(neg.locked_mode(), Some(WintabYMode::SignedNeg));
+ }
}
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index 0f043a5..ea9d132 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Ink Studio",
- "version": "1.0.3",
+ "version": "1.0.4",
"identifier": "com.inkstudio.app",
"build": {
"beforeDevCommand": "npm run dev",
diff --git a/src/App.tsx b/src/App.tsx
index 1f66bb6..2ad143b 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -339,6 +339,10 @@ export function App() {
flushPendingHistoryTasksRef.current = drawing.flushPendingHistoryTasks;
const handleUndo = useCallback(() => {
+ if ((collab.isConnected || collab.isReconnecting) && collab.myRole === 'viewer') {
+ showToast('Viewers have read-only access');
+ return;
+ }
if (
useUiStore.getState().is3DLayerOpen &&
useToolStore.getState().tool === '3d' &&
@@ -366,9 +370,13 @@ export function App() {
} else {
drawing.undo();
}
- }, [collab.isConnected, collab.myPeer.id, drawing, selectionTools]);
+ }, [collab.isConnected, collab.isReconnecting, collab.myPeer.id, collab.myRole, drawing, selectionTools, showToast]);
const handleRedo = useCallback(() => {
+ if ((collab.isConnected || collab.isReconnecting) && collab.myRole === 'viewer') {
+ showToast('Viewers have read-only access');
+ return;
+ }
if (
useUiStore.getState().is3DLayerOpen &&
useToolStore.getState().tool === '3d' &&
@@ -379,7 +387,7 @@ export function App() {
}
}
drawing.redo();
- }, [drawing]);
+ }, [collab.isConnected, collab.isReconnecting, collab.myRole, drawing, showToast]);
const getCanvasCoords = useCallback(
(e: React.PointerEvent<HTMLElement> | PointerEvent) => {
@@ -572,7 +580,44 @@ export function App() {
[layerMgr.toggleTone, selectionTools]
);
+ const checkCollabLayerEdit = useCallback(
+ (layerId: string): boolean => {
+ if (!collab.isConnected && !collab.isReconnecting) return true;
+ if (collab.myRole === 'viewer') {
+ showToast('Viewers have read-only access');
+ return false;
+ }
+ const perm = collab.canEditLayerById(layerId);
+ if (!perm.allowed) {
+ showToast(perm.reason || 'Layer is locked by its owner');
+ return false;
+ }
+ return true;
+ },
+ [collab.isConnected, collab.isReconnecting, collab.myRole, collab.canEditLayerById, showToast]
+ );
+
const handleMergeDown = useCallback(() => {
+ if (collab.isConnected || collab.isReconnecting) {
+ if (collab.myRole === 'viewer') {
+ showToast('Viewers have read-only access');
+ return;
+ }
+ const delPerm = collab.canDeleteLayerById(layerMgr.activeLayerId);
+ if (!delPerm.allowed) {
+ showToast(delPerm.reason || 'Cannot merge a protected layer');
+ return;
+ }
+ const activeIdx = layerMgr.layers.findIndex((l) => l.id === layerMgr.activeLayerId);
+ const belowLayer = activeIdx >= 0 ? layerMgr.layers[activeIdx + 1] : undefined;
+ if (belowLayer) {
+ const belowPerm = collab.canEditLayerById(belowLayer.id);
+ if (!belowPerm.allowed) {
+ showToast(belowPerm.reason || 'Target layer below is locked by its owner');
+ return;
+ }
+ }
+ }
const res = layerMgr.mergeDown();
if (res) {
documentStoreActions.markDocumentDirty(activeDocumentId, true);
@@ -581,7 +626,18 @@ export function App() {
} else {
showToast('Cannot merge down: need an unlocked raster layer below');
}
- }, [layerMgr.mergeDown, activeDocumentId, showToast]);
+ }, [
+ collab.isConnected,
+ collab.isReconnecting,
+ collab.myRole,
+ collab.canDeleteLayerById,
+ collab.canEditLayerById,
+ layerMgr.activeLayerId,
+ layerMgr.layers,
+ layerMgr.mergeDown,
+ activeDocumentId,
+ showToast,
+ ]);
const handleMergeFolder = useCallback(
(folderId?: string) => {
@@ -653,18 +709,23 @@ export function App() {
const handleRecordedDuplicateLayer = useCallback(
(id: string) => {
+ if ((collab.isConnected || collab.isReconnecting) && collab.myRole === 'viewer') {
+ showToast('Viewers have read-only access');
+ return;
+ }
layerMgr.duplicateLayer(id);
autoActionStoreActions.recordStep('duplicate-layer', 'Duplicate Layer');
},
- [layerMgr.duplicateLayer]
+ [collab.isConnected, collab.isReconnecting, collab.myRole, layerMgr.duplicateLayer, showToast]
);
const handleRecordedSetBlendMode = useCallback(
(id: string, blendMode: BlendMode) => {
+ if (!checkCollabLayerEdit(id)) return;
layerMgr.setBlendMode(id, blendMode);
autoActionStoreActions.recordStep('set-blend-mode', `Blend Mode: ${blendMode}`, { blendMode });
},
- [layerMgr.setBlendMode]
+ [checkCollabLayerEdit, layerMgr.setBlendMode]
);
const handleRecordedSetOpacity = useCallback(
@@ -679,10 +740,83 @@ export function App() {
const handleRecordedToggleClipping = useCallback(
(id: string) => {
+ if (!checkCollabLayerEdit(id)) return;
layerMgr.toggleClipping(id);
autoActionStoreActions.recordStep('toggle-clipping', 'Toggle Clipping Mask');
},
- [layerMgr.toggleClipping]
+ [checkCollabLayerEdit, layerMgr.toggleClipping]
+ );
+
+ const handleGuardedToggleAlphaLock = useCallback(
+ (id: string) => {
+ if (!checkCollabLayerEdit(id)) return;
+ layerMgr.toggleAlphaLock(id);
+ },
+ [checkCollabLayerEdit, layerMgr.toggleAlphaLock]
+ );
+
+ const handleGuardedMoveLayer = useCallback(
+ (id: string, direction: 'up' | 'down') => {
+ if (!checkCollabLayerEdit(id)) return;
+ layerMgr.moveLayer(id, direction);
+ },
+ [checkCollabLayerEdit, layerMgr.moveLayer]
+ );
+
+ const handleGuardedMoveLayerToFolder = useCallback(
+ (layerId: string, targetFolderId: string | null) => {
+ if (!checkCollabLayerEdit(layerId)) return;
+ layerMgr.moveLayerToFolder(layerId, targetFolderId);
+ },
+ [checkCollabLayerEdit, layerMgr.moveLayerToFolder]
+ );
+
+ const handleGuardedReorderLayers = useCallback(
+ (sourceId: string, targetId: string, position: 'above' | 'below' | 'inside') => {
+ if (!checkCollabLayerEdit(sourceId)) return;
+ layerMgr.reorderLayers(sourceId, targetId, position);
+ },
+ [checkCollabLayerEdit, layerMgr.reorderLayers]
+ );
+
+ const handleGuardedToggleLayerColor = useCallback(
+ (id: string) => {
+ if (!checkCollabLayerEdit(id)) return;
+ layerMgr.toggleLayerColor(id);
+ },
+ [checkCollabLayerEdit, layerMgr.toggleLayerColor]
+ );
+
+ const handleGuardedAddLayerMask = useCallback(
+ (...args: Parameters<typeof layerMgr.addLayerMask>) => {
+ if (!checkCollabLayerEdit(args[0])) return;
+ layerMgr.addLayerMask(...args);
+ },
+ [checkCollabLayerEdit, layerMgr.addLayerMask]
+ );
+
+ const handleGuardedRemoveLayerMask = useCallback(
+ (...args: Parameters<typeof layerMgr.removeLayerMask>) => {
+ if (!checkCollabLayerEdit(args[0])) return;
+ layerMgr.removeLayerMask(...args);
+ },
+ [checkCollabLayerEdit, layerMgr.removeLayerMask]
+ );
+
+ const handleGuardedToggleLayerMask = useCallback(
+ (layerId: string) => {
+ if (!checkCollabLayerEdit(layerId)) return;
+ layerMgr.toggleLayerMask(layerId);
+ },
+ [checkCollabLayerEdit, layerMgr.toggleLayerMask]
+ );
+
+ const handleGuardedToggleMaskLinked = useCallback(
+ (layerId: string) => {
+ if (!checkCollabLayerEdit(layerId)) return;
+ layerMgr.toggleMaskLinked(layerId);
+ },
+ [checkCollabLayerEdit, layerMgr.toggleMaskLinked]
);
const handleRecordedApplyFilter = useCallback(
@@ -1377,13 +1511,13 @@ export function App() {
setBlendMode={handleRecordedSetBlendMode}
toggleLock={collab.handleToggleLock}
toggleOwnerLock={collab.handleToggleOwnerLock}
- toggleAlphaLock={layerMgr.toggleAlphaLock}
+ toggleAlphaLock={handleGuardedToggleAlphaLock}
toggleClipping={handleRecordedToggleClipping}
toggleCollapse={layerMgr.toggleCollapse}
handleRenameLayer={collab.handleRenameLayer}
- moveLayer={layerMgr.moveLayer}
- moveLayerToFolder={layerMgr.moveLayerToFolder}
- reorderLayers={layerMgr.reorderLayers}
+ moveLayer={handleGuardedMoveLayer}
+ moveLayerToFolder={handleGuardedMoveLayerToFolder}
+ reorderLayers={handleGuardedReorderLayers}
handleToggleReferenceLayer={handleToggleReferenceLayer}
toggleTone={handleToggleTone}
setToneFrequency={layerMgr.setToneFrequency}
@@ -1391,7 +1525,7 @@ export function App() {
setToneDotShape={layerMgr.setToneDotShape}
setToneDensity={layerMgr.setToneDensity}
setToneDensityType={layerMgr.setToneDensityType}
- toggleLayerColor={layerMgr.toggleLayerColor}
+ toggleLayerColor={handleGuardedToggleLayerColor}
setLayerColor={layerMgr.setLayerColor}
setLayerSubColor={layerMgr.setLayerSubColor}
setLayerExpressionColor={handleRecordedSetExpressionColor}
@@ -1399,10 +1533,10 @@ export function App() {
setLayerMonoExpressMode={layerMgr.setLayerMonoExpressMode}
handleApplyExpressionColor={tonalActions.handleApplyExpressionColor}
handleApplyLayerColor={tonalActions.handleApplyLayerColor}
- addLayerMask={layerMgr.addLayerMask}
- removeLayerMask={layerMgr.removeLayerMask}
- toggleLayerMask={layerMgr.toggleLayerMask}
- toggleMaskLinked={layerMgr.toggleMaskLinked}
+ addLayerMask={handleGuardedAddLayerMask}
+ removeLayerMask={handleGuardedRemoveLayerMask}
+ toggleLayerMask={handleGuardedToggleLayerMask}
+ toggleMaskLinked={handleGuardedToggleMaskLinked}
handleOpenAdjustmentModal={tonalActions.handleOpenAdjustmentModal}
handleOpenLayerStylesModal={tonalActions.handleOpenLayerStylesModal}
onEditVectorLayer={shapeFillTools.openLayerForEditing}
@@ -1505,6 +1639,7 @@ export function App() {
collabMyPeer={collab.myPeer}
updateMyName={collab.updateMyName}
handleStartHosting={collab.handleStartHosting}
+ handleStartWebRtcHosting={collab.handleStartWebRtcHosting}
stopHosting={collab.stopHosting}
joinByInviteUrl={collab.joinByInviteUrl}
leaveRoom={collab.leaveRoom}
diff --git a/src/components/BrushPreview.tsx b/src/components/BrushPreview.tsx
index 3e24327..c00cf4f 100644
--- a/src/components/BrushPreview.tsx
+++ b/src/components/BrushPreview.tsx
@@ -1,5 +1,5 @@
import React, { useRef, useEffect, useState } from 'react';
-import { BrushSettings, BrushPresetId } from '../types/editor';
+import { BrushSettings, BrushPresetId, CspSubTip } from '../types/editor';
import { renderBrushStrokePreview, BrushPreviewOptions } from '../utils/brushPreview';
import { getPreloadedTipImage, preloadTipImage } from '../utils/brushStorage';
import { DEFAULT_BRUSH_PRESET_ID } from '../utils/brushPresetManager';
@@ -9,6 +9,7 @@ interface BrushPreviewProps {
settings?: Partial<BrushSettings>;
tool?: 'brush' | 'eraser';
strokeColor?: string;
+ secondaryColor?: string;
backgroundColor?: string;
className?: string;
width?: number;
@@ -18,11 +19,26 @@ interface BrushPreviewProps {
customTipAngle?: number;
}
+function resolveCachedSubTips(
+ subTips?: CspSubTip[],
+ existing?: HTMLImageElement[]
+): HTMLImageElement[] | undefined {
+ if (existing && existing.length > 0) return existing;
+ if (!subTips || subTips.length === 0) return undefined;
+ const out: HTMLImageElement[] = [];
+ for (const st of subTips) {
+ const img = getPreloadedTipImage(st.dataUrl);
+ if (img) out.push(img);
+ }
+ return out.length > 0 ? out : undefined;
+}
+
export const BrushPreview: React.FC<BrushPreviewProps> = React.memo(({
preset = DEFAULT_BRUSH_PRESET_ID,
settings,
tool = 'brush',
strokeColor = '#ffffff',
+ secondaryColor,
backgroundColor = 'transparent',
className = '',
width: fixedWidth,
@@ -35,32 +51,120 @@ export const BrushPreview: React.FC<BrushPreviewProps> = React.memo(({
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const [measuredWidth, setMeasuredWidth] = useState<number>(fixedWidth || 140);
const rafIdRef = useRef<number | null>(null);
+ const [assetLoadRevision, setAssetLoadRevision] = useState<number>(0);
+
+ const tipUrl =
+ customTipImage?.src ||
+ settings?.customTipDataUrl ||
+ (settings as { tipDataUrl?: string } | undefined)?.tipDataUrl;
+ const dualTipUrl =
+ settings?.dualTipImage?.src ||
+ settings?.dualTipDataUrl ||
+ settings?.dualBrushConfig?.tipDataUrl ||
+ (settings as { secondaryTipDataUrl?: string } | undefined)?.secondaryTipDataUrl;
+ const paperUrl = settings?.paperTextureImage?.src || settings?.paperTexture;
- const tipUrl = customTipImage?.src || settings?.customTipDataUrl || (settings as any)?.tipDataUrl;
const [internalTipImage, setInternalTipImage] = useState<HTMLImageElement | undefined>(() => {
if (customTipImage) return customTipImage;
if (tipUrl) return getPreloadedTipImage(tipUrl) || undefined;
return undefined;
});
+ const [internalDualTipImage, setInternalDualTipImage] = useState<HTMLImageElement | undefined>(() => {
+ if (settings?.dualTipImage) return settings.dualTipImage;
+ if (settings?.dualBrushConfig?.tipImage) return settings.dualBrushConfig.tipImage;
+ if (dualTipUrl) return getPreloadedTipImage(dualTipUrl) || undefined;
+ return undefined;
+ });
+ const [internalPaperImage, setInternalPaperImage] = useState<HTMLImageElement | undefined>(() => {
+ if (settings?.paperTextureImage) return settings.paperTextureImage;
+ if (paperUrl) return getPreloadedTipImage(paperUrl) || undefined;
+ return undefined;
+ });
+ // Preload primary tip, dual tip, paper texture, and sub-tip arrays
useEffect(() => {
+ let cancelled = false;
+ const bump = () => {
+ if (!cancelled) setAssetLoadRevision((r) => r + 1);
+ };
+
if (customTipImage) {
setInternalTipImage(customTipImage);
- return;
- }
- if (tipUrl) {
+ } else if (tipUrl) {
const cached = getPreloadedTipImage(tipUrl);
if (cached) {
setInternalTipImage(cached);
} else {
preloadTipImage(tipUrl)
- .then((img) => setInternalTipImage(img))
+ .then((img) => {
+ if (!cancelled) setInternalTipImage(img);
+ })
.catch(() => {});
}
} else {
setInternalTipImage(undefined);
}
- }, [customTipImage, tipUrl]);
+
+ const explicitDual = settings?.dualTipImage || settings?.dualBrushConfig?.tipImage;
+ if (explicitDual) {
+ setInternalDualTipImage(explicitDual);
+ } else if (dualTipUrl) {
+ const cached = getPreloadedTipImage(dualTipUrl);
+ if (cached) {
+ setInternalDualTipImage(cached);
+ } else {
+ preloadTipImage(dualTipUrl)
+ .then((img) => {
+ if (!cancelled) setInternalDualTipImage(img);
+ })
+ .catch(() => {});
+ }
+ } else {
+ setInternalDualTipImage(undefined);
+ }
+
+ if (settings?.paperTextureImage) {
+ setInternalPaperImage(settings.paperTextureImage);
+ } else if (paperUrl) {
+ const cached = getPreloadedTipImage(paperUrl);
+ if (cached) {
+ setInternalPaperImage(cached);
+ } else {
+ preloadTipImage(paperUrl)
+ .then((img) => {
+ if (!cancelled) setInternalPaperImage(img);
+ })
+ .catch(() => {});
+ }
+ } else {
+ setInternalPaperImage(undefined);
+ }
+
+ const subTipsToLoad = [
+ ...(settings?.subTips || []),
+ ...(settings?.dualSubTips || settings?.dualBrushConfig?.subTips || []),
+ ];
+ for (const st of subTipsToLoad) {
+ if (st.dataUrl && !getPreloadedTipImage(st.dataUrl)) {
+ preloadTipImage(st.dataUrl).then(bump).catch(() => {});
+ }
+ }
+
+ return () => {
+ cancelled = true;
+ };
+ }, [
+ customTipImage,
+ tipUrl,
+ dualTipUrl,
+ paperUrl,
+ settings?.dualTipImage,
+ settings?.dualBrushConfig?.tipImage,
+ settings?.paperTextureImage,
+ settings?.subTips,
+ settings?.dualSubTips,
+ settings?.dualBrushConfig?.subTips,
+ ]);
// ResizeObserver for auto-responsive width when fixedWidth is not supplied
useEffect(() => {
@@ -85,7 +189,7 @@ export const BrushPreview: React.FC<BrushPreviewProps> = React.memo(({
return () => observer.disconnect();
}, [fixedWidth]);
- // Render stroke preview
+ // Render stroke preview through the full unified renderCompleteStroke pipeline
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas || measuredWidth <= 0 || fixedHeight <= 0) return;
@@ -97,37 +201,128 @@ export const BrushPreview: React.FC<BrushPreviewProps> = React.memo(({
rafIdRef.current = requestAnimationFrame(() => {
rafIdRef.current = null;
+ const resolvedDualTipImg =
+ internalDualTipImage || settings?.dualTipImage || settings?.dualBrushConfig?.tipImage;
+ const resolvedSubTipImgs = resolveCachedSubTips(settings?.subTips, settings?.subTipImages);
+ const resolvedDualSubTipImgs = resolveCachedSubTips(
+ settings?.dualSubTips || settings?.dualBrushConfig?.subTips,
+ settings?.dualSubTipImages || settings?.dualBrushConfig?.subTipImages
+ );
+
const opts: BrushPreviewOptions = {
preset,
size: settings?.size,
flow: settings?.flow,
+ brushDensity: settings?.brushDensity,
opacity: settings?.opacity,
- grain: settings?.grain,
+ grain: settings?.grain ?? settings?.textureDensity,
+ textureDensity: settings?.textureDensity,
+ paperTexture: settings?.paperTexture,
+ paperTextureImage: internalPaperImage || settings?.paperTextureImage,
paperTextureMode: settings?.paperTextureMode,
paperTextureScale: settings?.paperTextureScale,
+ paperTextureRotate: settings?.paperTextureRotate,
+ paperTextureOffsetX: settings?.paperTextureOffsetX,
+ paperTextureOffsetY: settings?.paperTextureOffsetY,
paperTextureContrast: settings?.paperTextureContrast,
paperTextureBrightness: settings?.paperTextureBrightness,
+ paperTextureApplyEachPlot: settings?.paperTextureApplyEachPlot,
+ paperTextureEmphasizeDensity: settings?.paperTextureEmphasizeDensity,
paperTextureInverted: settings?.paperTextureInverted,
+ surfaceTextureId: settings?.surfaceTextureId,
+ grainMappingMode: settings?.grainMappingMode,
hardness: settings?.hardness,
spacing: settings?.spacing,
minSizeFactor: settings?.minSizeFactor,
thickness: settings?.thickness,
+ thicknessVertical: settings?.thicknessVertical,
+ thicknessSensor: settings?.thicknessSensor,
+ flipH: settings?.flipH,
+ flipV: settings?.flipV,
+ blendTipsMode: settings?.blendTipsMode,
+ brushCombineMode: settings?.brushCombineMode,
+ adjustDensityByGap: settings?.adjustDensityByGap,
antiAlias: settings?.antiAlias,
pressureCurve: settings?.pressureCurve,
+ velocityCurve: settings?.velocityCurve,
+ sizeSensor: settings?.sizeSensor,
+ opacitySensor: settings?.opacitySensor,
+ densitySensor: settings?.densitySensor,
+ intervalSensor: settings?.intervalSensor,
+ textureDensitySensor: settings?.textureDensitySensor,
+ angleSensor: settings?.angleSensor,
+ scatterSensor: settings?.scatterSensor,
spray: settings?.spray,
+ taper: settings?.taper,
dynamics: settings?.dynamics,
usePressure: settings?.usePressure,
+ useTilt: settings?.useTilt,
+ tiltScale: settings?.tiltScale,
+ useVelocity: settings?.useVelocity,
color: strokeColor,
+ secondaryColor: secondaryColor ?? settings?.secondaryColor,
backgroundColor,
tool,
+ customTipDataUrl: settings?.customTipDataUrl,
customTipImage: customTipImage || internalTipImage || settings?.customTipImage,
customTipAngle: customTipAngle !== undefined ? customTipAngle : settings?.customTipAngle,
customTipAngleDynamics: settings?.customTipAngleDynamics,
+ customTipRotationRandomScale: settings?.customTipRotationRandomScale,
+ isColorTip: settings?.isColorTip,
+ isDualToneTip: settings?.isDualToneTip,
+ isRibbon: settings?.isRibbon,
+ subTips: settings?.subTips,
+ subTipOrder: settings?.subTipOrder,
+ subTipImages: resolvedSubTipImgs,
colorMixing: settings?.colorMixing,
+ perceptualMixing: settings?.perceptualMixing,
amountOfPaint: settings?.amountOfPaint,
densityOfPaint: settings?.densityOfPaint,
colorStretch: settings?.colorStretch,
+ amountOfPaintSensor: settings?.amountOfPaintSensor,
+ densityOfPaintSensor: settings?.densityOfPaintSensor,
+ colorStretchSensor: settings?.colorStretchSensor,
+ mixingMode: settings?.mixingMode,
wetEdge: settings?.wetEdge,
+ wetEdgeRadius: settings?.wetEdgeRadius,
+ wetEdgeAlphaPower: settings?.wetEdgeAlphaPower,
+ wetEdgeValuePower: settings?.wetEdgeValuePower,
+ dualBrush: settings?.dualBrush,
+ dualBrushConfig: settings?.dualBrushConfig
+ ? {
+ ...settings.dualBrushConfig,
+ tipImage: resolvedDualTipImg,
+ subTipImages: resolvedDualSubTipImgs,
+ }
+ : undefined,
+ dualBrushCompositeMode: settings?.dualBrushCompositeMode,
+ dualTipDataUrl: dualTipUrl,
+ dualTipImage: resolvedDualTipImg,
+ dualSize: settings?.dualSize,
+ dualLinkSize: settings?.dualLinkSize,
+ dualSpacing: settings?.dualSpacing,
+ dualScatter: settings?.dualScatter,
+ dualThickness: settings?.dualThickness,
+ dualThicknessVertical: settings?.dualThicknessVertical,
+ dualAngle: settings?.dualAngle,
+ dualAngleDynamics: settings?.dualAngleDynamics,
+ dualAngleSensor: settings?.dualAngleSensor,
+ dualHardness: settings?.dualHardness,
+ dualDensity: settings?.dualDensity,
+ dualSubTips: settings?.dualSubTips,
+ dualSubTipImages: resolvedDualSubTipImgs,
+ dualSubTipOrder: settings?.dualSubTipOrder,
+ dualFlipH: settings?.dualFlipH,
+ dualFlipV: settings?.dualFlipV,
+ dualSpray: settings?.dualSpray,
+ dualIsRibbon: settings?.dualIsRibbon,
+ dualScale: settings?.dualScale,
+ dualSurfaceTextureId: settings?.dualSurfaceTextureId,
+ dualGrainDepth: settings?.dualGrainDepth,
+ renderMode: settings?.renderMode,
+ bristle: settings?.bristle,
+ naturalPaint: settings?.naturalPaint,
+ impasto: settings?.impasto,
};
renderBrushStrokePreview(canvas, measuredWidth, fixedHeight, opts, isLiveCard);
@@ -141,27 +336,17 @@ export const BrushPreview: React.FC<BrushPreviewProps> = React.memo(({
};
}, [
preset,
- settings?.size,
- settings?.flow,
- settings?.opacity,
- settings?.grain,
- settings?.hardness,
- settings?.spacing,
- settings?.minSizeFactor,
- settings?.thickness,
- settings?.usePressure,
- settings?.customTipImage,
- settings?.customTipAngle,
- settings?.colorMixing,
- settings?.amountOfPaint,
- settings?.densityOfPaint,
- settings?.colorStretch,
- settings?.wetEdge,
+ settings,
customTipImage,
internalTipImage,
+ internalDualTipImage,
+ internalPaperImage,
+ dualTipUrl,
customTipAngle,
+ assetLoadRevision,
tool,
strokeColor,
+ secondaryColor,
backgroundColor,
measuredWidth,
fixedHeight,
diff --git a/src/components/BrushStudioModal.tsx b/src/components/BrushStudioModal.tsx
index 65b4a21..d99c436 100644
--- a/src/components/BrushStudioModal.tsx
+++ b/src/components/BrushStudioModal.tsx
@@ -181,7 +181,16 @@ export const BrushStudioModal: React.FC<BrushStudioModalProps> = ({
try {
const parsed = await importBrushFile(file);
saveActivePresetId(parsed.id);
- showToast?.(`Imported "${parsed.name}"`);
+ if (parsed.importWarnings && parsed.importWarnings.length > 0) {
+ const count = parsed.importWarnings.length;
+ showToast?.(
+ count === 1
+ ? `Imported "${parsed.name}" (Notice: ${parsed.importWarnings[0]})`
+ : `Imported "${parsed.name}" with ${count} CSP import notices`
+ );
+ } else {
+ showToast?.(`Imported "${parsed.name}"`);
+ }
} catch (err) {
showToast?.(err instanceof Error ? err.message : 'Import failed');
}
diff --git a/src/components/ClipboardInviteToast.tsx b/src/components/ClipboardInviteToast.tsx
index b8f57b8..794c097 100644
--- a/src/components/ClipboardInviteToast.tsx
+++ b/src/components/ClipboardInviteToast.tsx
@@ -1,9 +1,19 @@
import React from 'react';
import { Users, ArrowRight, X } from 'lucide-react';
-import { ParsedInviteLink } from '../services/multiplayerService';
+import {
+ ParsedCollabTarget,
+ ParsedInviteLink,
+ ParsedP2pInvite,
+} from '../services/multiplayerService';
+
+function isP2pInvite(
+ invite: ParsedCollabTarget | ParsedInviteLink
+): invite is ParsedP2pInvite {
+ return 'kind' in invite && invite.kind === 'p2p';
+}
interface ClipboardInviteToastProps {
- invite: ParsedInviteLink | null;
+ invite: ParsedCollabTarget | ParsedInviteLink | null;
onJoin: (
host: string,
port: number,
@@ -11,16 +21,32 @@ interface ClipboardInviteToastProps {
token?: string,
isSecure?: boolean
) => void;
+ onJoinTarget?: (target: ParsedCollabTarget) => void;
onDismiss: () => void;
}
export const ClipboardInviteToast: React.FC<ClipboardInviteToastProps> = ({
invite,
onJoin,
+ onJoinTarget,
onDismiss,
}) => {
if (!invite) return null;
+ const subtitle = isP2pInvite(invite)
+ ? `WebRTC P2P · ${invite.joinCode}`
+ : `${invite.host}${invite.port && invite.port !== 443 && invite.port !== 80 ? `:${invite.port}` : ''}`;
+
+ const handleConnect = () => {
+ if ('kind' in invite && onJoinTarget) {
+ onJoinTarget(invite);
+ return;
+ }
+ if (!isP2pInvite(invite)) {
+ onJoin(invite.host, invite.port, invite.roomName, invite.token, invite.isSecure);
+ }
+ };
+
return (
<div
role="status"
@@ -41,22 +67,17 @@ export const ClipboardInviteToast: React.FC<ClipboardInviteToastProps> = ({
<div className="text-[11px] text-[#d4d4d4] truncate">
Room: <span className="font-medium text-[#e5e5e5]">"{invite.roomName}"</span>
</div>
- <div className="text-[10px] text-[#8a8a8a] font-mono truncate">
- {invite.host}
- {invite.port && invite.port !== 443 && invite.port !== 80 ? `:${invite.port}` : ''}
- </div>
+ <div className="text-[10px] text-[#8a8a8a] font-mono truncate">{subtitle}</div>
</div>
<div className="flex items-center gap-1.5 pl-1 shrink-0">
<button
type="button"
- onClick={() =>
- onJoin(invite.host, invite.port, invite.roomName, invite.token, invite.isSecure)
- }
- className="flex items-center gap-1 rounded bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 px-2.5 py-1.5 text-[11px] font-medium transition-opacity cursor-pointer"
+ onClick={handleConnect}
+ className="flex items-center justify-center gap-1 min-h-[44px] min-w-[44px] rounded bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 px-3 py-1.5 text-xs font-medium transition-opacity cursor-pointer"
>
<span>Connect</span>
- <ArrowRight className="w-3 h-3" />
+ <ArrowRight className="w-3.5 h-3.5" />
</button>
<button
@@ -64,9 +85,9 @@ export const ClipboardInviteToast: React.FC<ClipboardInviteToastProps> = ({
onClick={onDismiss}
aria-label="Dismiss invitation"
title="Dismiss"
- className="w-6 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:bg-[#2c2c2c] hover:text-[#e5e5e5] transition-colors cursor-pointer"
+ className="w-11 h-11 rounded flex items-center justify-center text-[#8a8a8a] hover:bg-[#2c2c2c] hover:text-[#e5e5e5] transition-colors cursor-pointer"
>
- <X className="w-3.5 h-3.5" />
+ <X className="w-4 h-4" />
</button>
</div>
</div>
diff --git a/src/components/DocumentLifecycleManager.tsx b/src/components/DocumentLifecycleManager.tsx
index e8e4001..397343b 100644
--- a/src/components/DocumentLifecycleManager.tsx
+++ b/src/components/DocumentLifecycleManager.tsx
@@ -436,6 +436,10 @@ export function useDocumentLifecycle({
const handleResizeCanvas = useCallback(
(options: ResizeCanvasOptions) => {
+ if (multiplayerService.isConnected() && multiplayerService.getLocalRole() === 'viewer') {
+ showToast('Viewers have read-only access');
+ return;
+ }
const curDims = useDocumentStore.getState().dimensions;
const newDims: CanvasDimensions = {
width: options.width,
@@ -516,7 +520,16 @@ export function useDocumentLifecycle({
try {
uiStoreActions.setLoading(true, `Importing Brush: ${file.name}...`);
const parsedBrush = await importBrushFile(file);
- showToast(`Imported brush "${parsedBrush.name}"`);
+ if (parsedBrush.importWarnings && parsedBrush.importWarnings.length > 0) {
+ const count = parsedBrush.importWarnings.length;
+ showToast(
+ count === 1
+ ? `Imported "${parsedBrush.name}" (Notice: ${parsedBrush.importWarnings[0]})`
+ : `Imported "${parsedBrush.name}" with ${count} CSP import notices — check inspector`
+ );
+ } else {
+ showToast(`Imported brush "${parsedBrush.name}"`);
+ }
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : 'Failed to import brush file.';
showToast(msg);
diff --git a/src/components/HostModal.tsx b/src/components/HostModal.tsx
index b5f1d2f..d140cab 100644
--- a/src/components/HostModal.tsx
+++ b/src/components/HostModal.tsx
@@ -1,10 +1,12 @@
-import React, { useState, useEffect, useRef } from 'react';
+import React, { useState, useEffect, useMemo, useRef } from 'react';
import {
SessionHostInfo,
CollabPeer,
CollabRole,
ConnectionStatus,
} from '../types/multiplayer';
+import { parseCollabTarget } from '../services/multiplayerService';
+import { MAX_WEBRTC_PEERS } from '../services/webrtcHostHub';
import {
Users,
Copy,
@@ -22,6 +24,7 @@ import {
Ban,
UserX,
RefreshCw,
+ Radio,
} from 'lucide-react';
interface HostModalProps {
@@ -44,8 +47,18 @@ interface HostModalProps {
isGlobal?: boolean,
onStatus?: (status: string) => void
) => Promise<any>;
+ onStartWebRtcHosting?: (
+ roomName: string,
+ hostNickname?: string,
+ onStatus?: (status: string) => void
+ ) => Promise<any>;
onStopHosting: () => void;
- onJoinByInviteUrl: (rawUrl: string, nickname?: string, persistName?: boolean) => Promise<boolean>;
+ onJoinByInviteUrl: (
+ rawUrl: string,
+ nickname?: string,
+ persistName?: boolean,
+ secretOverride?: string
+ ) => Promise<boolean>;
onLeaveRoom: () => void;
onSetPeerRole?: (peerId: string | number, role: 'editor' | 'viewer') => void;
onKickPeer?: (peerId: string | number) => void;
@@ -73,6 +86,7 @@ export const HostModal: React.FC<HostModalProps> = ({
myPeer,
onUpdateMyName,
onStartHosting,
+ onStartWebRtcHosting,
onStopHosting,
onJoinByInviteUrl,
onLeaveRoom,
@@ -86,9 +100,13 @@ export const HostModal: React.FC<HostModalProps> = ({
const [nickname, setNickname] = useState(myPeer.name || 'Artist');
const [roomName, setRoomName] = useState(() => defaultStudioName(myPeer.name));
const [port, setPort] = useState(30303);
- const [isGlobal, setIsGlobal] = useState(true);
+ const [hostMode, setHostMode] = useState<'p2p' | 'tunnel' | 'lan'>(() =>
+ onStartWebRtcHosting ? 'p2p' : 'tunnel'
+ );
const [joinUrl, setJoinUrl] = useState('');
+ const [manualSecret, setManualSecret] = useState('');
const [copied, setCopied] = useState(false);
+ const [copiedCode, setCopiedCode] = useState(false);
const [copiedLocal, setCopiedLocal] = useState(false);
const [isStarting, setIsStarting] = useState(false);
const [isJoining, setIsJoining] = useState(false);
@@ -98,6 +116,14 @@ export const HostModal: React.FC<HostModalProps> = ({
const nicknameEditedRef = useRef(false);
const roomNameEditedRef = useRef(false);
+ const parsedJoinTarget = useMemo(() => {
+ const trimmed = joinUrl.trim();
+ if (!trimmed) return null;
+ return parseCollabTarget(trimmed);
+ }, [joinUrl]);
+
+ const isP2pSession = hostInfo?.transport === 'webrtc';
+
// Sync nickname & default room name when OS username resolves or Preferences changes
useEffect(() => {
if (!nicknameEditedRef.current && myPeer.name) {
@@ -108,12 +134,13 @@ export const HostModal: React.FC<HostModalProps> = ({
}
}, [myPeer.name]);
- // Reset transient error when modal re-opens
+ // Reset transient error and default to P2P mode whenever modal opens
useEffect(() => {
if (isOpen) {
setStartError(null);
+ setHostMode(onStartWebRtcHosting ? 'p2p' : 'tunnel');
}
- }, [isOpen]);
+ }, [isOpen, onStartWebRtcHosting]);
// Escape key closes modal
useEffect(() => {
@@ -143,6 +170,19 @@ export const HostModal: React.FC<HostModalProps> = ({
}
};
+ const handleCopyCode = async () => {
+ const code = hostInfo?.joinCode || hostInfo?.roomCode;
+ if (!code) return;
+ try {
+ await navigator.clipboard.writeText(code);
+ setCopiedCode(true);
+ showToast('Room code copied.');
+ setTimeout(() => setCopiedCode(false), 2000);
+ } catch {
+ showToast('Failed to copy to clipboard.');
+ }
+ };
+
const handleCopyLocalLink = async () => {
if (!hostInfo?.localInviteUrl) return;
try {
@@ -155,20 +195,35 @@ export const HostModal: React.FC<HostModalProps> = ({
}
};
- const handleStart = async (overrideGlobal?: boolean) => {
- const useGlobal = overrideGlobal !== undefined ? overrideGlobal : isGlobal;
+ const handleStart = async (overrideMode?: 'tunnel' | 'p2p' | 'lan') => {
+ const mode = overrideMode ?? hostMode;
setIsStarting(true);
setStartError(null);
- setStartStatus(useGlobal ? 'Starting Worldwide Tunnel...' : 'Starting Local Server...');
+ setStartStatus(
+ mode === 'p2p'
+ ? 'Opening Quick P2P Room...'
+ : mode === 'tunnel'
+ ? 'Starting Worldwide Tunnel...'
+ : 'Starting Local Server...'
+ );
try {
const resolvedName = nickname.trim() || myPeer.name || 'Artist';
if (nicknameEditedRef.current && resolvedName !== myPeer.name) {
onUpdateMyName(resolvedName);
}
const resolvedRoom = roomName.trim() || defaultStudioName(resolvedName);
- await onStartHosting(resolvedRoom, port, resolvedName, useGlobal, (status) => {
- setStartStatus(status);
- });
+ if (mode === 'p2p') {
+ if (!onStartWebRtcHosting) {
+ throw new Error('Quick P2P hosting is unavailable in this context.');
+ }
+ await onStartWebRtcHosting(resolvedRoom, resolvedName, (status) => {
+ setStartStatus(status);
+ });
+ } else {
+ await onStartHosting(resolvedRoom, port, resolvedName, mode === 'tunnel', (status) => {
+ setStartStatus(status);
+ });
+ }
} catch (err: any) {
const msg = err?.message || (typeof err === 'string' ? err : 'Failed to start server');
setStartError(msg);
@@ -182,7 +237,7 @@ export const HostModal: React.FC<HostModalProps> = ({
e.preventDefault();
const trimmedUrl = joinUrl.trim();
if (!trimmedUrl) {
- showToast('Paste a room invite link first.');
+ showToast('Enter a room code (INK-XXXX) or invite link first.');
return;
}
setIsJoining(true);
@@ -191,9 +246,16 @@ export const HostModal: React.FC<HostModalProps> = ({
if (nicknameEditedRef.current && resolvedName !== myPeer.name) {
onUpdateMyName(resolvedName);
}
- const ok = await onJoinByInviteUrl(trimmedUrl, resolvedName, nicknameEditedRef.current);
+ const extraSecret =
+ parsedJoinTarget?.kind === 'p2p' && !parsedJoinTarget.roomSecret
+ ? manualSecret.trim() || undefined
+ : undefined;
+ const ok = extraSecret
+ ? await onJoinByInviteUrl(trimmedUrl, resolvedName, nicknameEditedRef.current, extraSecret)
+ : await onJoinByInviteUrl(trimmedUrl, resolvedName, nicknameEditedRef.current);
if (ok) {
setJoinUrl('');
+ setManualSecret('');
onClose();
}
} finally {
@@ -281,7 +343,21 @@ export const HostModal: React.FC<HostModalProps> = ({
) : isConnected && isHost ? (
// Active Host View
<div className="space-y-4">
- {hostInfo?.isGlobal ? (
+ {isP2pSession ? (
+ <div className="rounded-md border border-emerald-500/30 bg-emerald-500/10 p-3.5 flex items-start gap-3">
+ <Radio className="w-4 h-4 text-emerald-400 shrink-0 mt-0.5" />
+ <div className="flex-1 min-w-0">
+ <div className="text-xs font-medium text-emerald-300">
+ Quick P2P Room Active (WebRTC)
+ </div>
+ <div className="text-[11px] text-[#b5b5b5] mt-0.5">
+ Room: <span className="text-[#e5e5e5] font-medium">{hostInfo?.roomName}</span>{' '}
+ — Android tablets &amp; PCs can join worldwide with the short code below (up to{' '}
+ {MAX_WEBRTC_PEERS} guests).
+ </div>
+ </div>
+ </div>
+ ) : hostInfo?.isGlobal ? (
<div className="rounded-md border border-[var(--accent-border)] bg-[#161616] p-3.5 flex items-start gap-3">
<Globe className="w-4 h-4 text-[var(--accent)] shrink-0 mt-0.5" />
<div className="flex-1 min-w-0">
@@ -309,59 +385,115 @@ export const HostModal: React.FC<HostModalProps> = ({
</div>
)}
- {/* Shareable Link Box */}
- <div>
- <label className="block text-[11px] font-medium text-[#8a8a8a] mb-1.5 flex items-center justify-between">
- <span>
- {hostInfo?.isGlobal
- ? 'Worldwide Invite Link (Browser or Desktop App)'
- : 'Local Wi-Fi Invite Link'}
- </span>
- {hostInfo?.isGlobal && (
- <span className="text-[10px] text-[var(--accent)] font-mono flex items-center gap-1">
- <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" />
- <span>HTTPS + WSS</span>
- </span>
+ {/* Shareable Code / Link Box */}
+ {isP2pSession ? (
+ <div className="space-y-3">
+ <div>
+ <label className="text-[11px] font-medium text-[#8a8a8a] mb-1.5 flex items-center justify-between">
+ <span>Quick P2P Room Code (Android &amp; Desktop)</span>
+ <span className="text-[10px] text-emerald-400 font-mono flex items-center gap-1">
+ <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" />
+ <span>WEBRTC P2P</span>
+ </span>
+ </label>
+ <div className="flex items-center gap-2">
+ <input
+ type="text"
+ readOnly
+ data-testid="host-p2p-join-code"
+ value={hostInfo?.joinCode || hostInfo?.roomCode || ''}
+ className="flex-1 rounded border border-[#2c2c2c] bg-[#161616] px-3 py-1.5 text-sm font-bold tracking-wider text-[#e5e5e5] font-mono select-all focus:outline-hidden"
+ />
+ <button
+ type="button"
+ onClick={handleCopyCode}
+ className="flex items-center gap-1.5 rounded bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 px-3 py-1.5 text-xs font-medium transition-opacity shrink-0 cursor-pointer"
+ >
+ {copiedCode ? (
+ <Check className="w-3.5 h-3.5" />
+ ) : (
+ <Copy className="w-3.5 h-3.5" />
+ )}
+ <span>{copiedCode ? 'Copied' : 'Copy Code'}</span>
+ </button>
+ </div>
+ </div>
+
+ {hostInfo?.inviteUrl && (
+ <div className="pt-2 border-t border-[#2c2c2c] flex items-center justify-between text-[10px] text-[#8a8a8a]">
+ <span className="truncate">
+ Invite Link:{' '}
+ <span className="font-mono text-[#b5b5b5]">{hostInfo.inviteUrl}</span>
+ </span>
+ <button
+ type="button"
+ onClick={handleCopyLink}
+ className="text-[#b5b5b5] hover:text-[#e5e5e5] underline cursor-pointer ml-2 shrink-0"
+ >
+ {copied ? 'Copied' : 'Copy Link'}
+ </button>
+ </div>
)}
- </label>
- <div className="flex items-center gap-2">
- <input
- type="text"
- readOnly
- value={hostInfo?.inviteUrl || ''}
- className="flex-1 rounded border border-[#2c2c2c] bg-[#161616] px-3 py-1.5 text-xs text-[#e5e5e5] font-mono select-all focus:outline-hidden"
- />
- <button
- type="button"
- onClick={handleCopyLink}
- className="flex items-center gap-1.5 rounded bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 px-3 py-1.5 text-xs font-medium transition-opacity shrink-0 cursor-pointer"
- >
- {copied ? <Check className="w-3.5 h-3.5" /> : <Copy className="w-3.5 h-3.5" />}
- <span>{copied ? 'Copied' : 'Copy'}</span>
- </button>
- </div>
- {hostInfo?.isGlobal && hostInfo.localInviteUrl && (
- <div className="mt-2 pt-2 border-t border-[#2c2c2c] flex items-center justify-between text-[10px] text-[#8a8a8a]">
- <span className="truncate">
- Local LAN:{' '}
- <span className="font-mono text-[#b5b5b5]">{hostInfo.localInviteUrl}</span>
+ <p className="text-[10px] text-[#8a8a8a] leading-relaxed">
+ Share this Room Code with Android tablet or desktop users — no cloudflared
+ required. Keep this app open while hosting.
+ </p>
+ </div>
+ ) : (
+ <div>
+ <label className="text-[11px] font-medium text-[#8a8a8a] mb-1.5 flex items-center justify-between">
+ <span>
+ {hostInfo?.isGlobal
+ ? 'Worldwide Invite Link (Browser or Desktop App)'
+ : 'Local Wi-Fi Invite Link'}
</span>
+ {hostInfo?.isGlobal && (
+ <span className="text-[10px] text-[var(--accent)] font-mono flex items-center gap-1">
+ <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" />
+ <span>HTTPS + WSS</span>
+ </span>
+ )}
+ </label>
+ <div className="flex items-center gap-2">
+ <input
+ type="text"
+ readOnly
+ value={hostInfo?.inviteUrl || ''}
+ className="flex-1 rounded border border-[#2c2c2c] bg-[#161616] px-3 py-1.5 text-xs text-[#e5e5e5] font-mono select-all focus:outline-hidden"
+ />
<button
type="button"
- onClick={handleCopyLocalLink}
- className="text-[#b5b5b5] hover:text-[#e5e5e5] underline cursor-pointer ml-2 shrink-0"
+ onClick={handleCopyLink}
+ className="flex items-center gap-1.5 rounded bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 px-3 py-1.5 text-xs font-medium transition-opacity shrink-0 cursor-pointer"
>
- {copiedLocal ? 'Copied' : 'Copy Local'}
+ {copied ? <Check className="w-3.5 h-3.5" /> : <Copy className="w-3.5 h-3.5" />}
+ <span>{copied ? 'Copied' : 'Copy'}</span>
</button>
</div>
- )}
- <p className="text-[10px] text-[#8a8a8a] mt-1.5 leading-relaxed">
- Share this link to open directly in a browser or paste it into the Join tab in the
- desktop app.
- </p>
- </div>
+ {hostInfo?.isGlobal && hostInfo.localInviteUrl && (
+ <div className="mt-2 pt-2 border-t border-[#2c2c2c] flex items-center justify-between text-[10px] text-[#8a8a8a]">
+ <span className="truncate">
+ Local LAN:{' '}
+ <span className="font-mono text-[#b5b5b5]">{hostInfo.localInviteUrl}</span>
+ </span>
+ <button
+ type="button"
+ onClick={handleCopyLocalLink}
+ className="text-[#b5b5b5] hover:text-[#e5e5e5] underline cursor-pointer ml-2 shrink-0"
+ >
+ {copiedLocal ? 'Copied' : 'Copy Local'}
+ </button>
+ </div>
+ )}
+
+ <p className="text-[10px] text-[#8a8a8a] mt-1.5 leading-relaxed">
+ Share this link to open directly in a browser or paste it into the Join tab in the
+ desktop app.
+ </p>
+ </div>
+ )}
{/* Connected Peers List */}
<div>
@@ -490,19 +622,31 @@ export const HostModal: React.FC<HostModalProps> = ({
// Active Guest View
<div className="space-y-4">
<div className="rounded-md border border-[var(--accent-border)] bg-[#161616] p-3.5 flex items-start gap-3">
- <Globe className="w-4 h-4 text-[var(--accent)] shrink-0 mt-0.5" />
+ {isP2pSession ? (
+ <Radio className="w-4 h-4 text-emerald-400 shrink-0 mt-0.5" />
+ ) : (
+ <Globe className="w-4 h-4 text-[var(--accent)] shrink-0 mt-0.5" />
+ )}
<div className="flex-1 min-w-0">
- <div className="text-xs font-medium text-[#e5e5e5]">Connected to Session</div>
+ <div className="text-xs font-medium text-[#e5e5e5]">
+ {isP2pSession ? 'Connected via WebRTC P2P' : 'Connected to Session'}
+ </div>
<div className="text-[11px] text-[#8a8a8a] mt-0.5 truncate">
Room:{' '}
<span className="text-[#e5e5e5] font-medium">
{hostInfo?.roomName || 'Studio'}
</span>
</div>
- {hostInfo?.localIp && (
+ {isP2pSession && hostInfo?.roomCode ? (
<div className="text-[10px] text-[#8a8a8a] font-mono truncate mt-0.5">
- {hostInfo.localIp}
+ Code: {hostInfo.joinCode || hostInfo.roomCode}
</div>
+ ) : (
+ hostInfo?.localIp && (
+ <div className="text-[10px] text-[#8a8a8a] font-mono truncate mt-0.5">
+ {hostInfo.localIp}
+ </div>
+ )
)}
</div>
</div>
@@ -588,7 +732,7 @@ export const HostModal: React.FC<HostModalProps> = ({
: 'text-[#8a8a8a] hover:text-[#e5e5e5]'
}`}
>
- Join via Link
+ Join Room
</button>
</div>
@@ -633,52 +777,98 @@ export const HostModal: React.FC<HostModalProps> = ({
<label className="block text-[11px] font-medium text-[#b5b5b5] mb-1.5">
Connection Mode
</label>
- <div className="grid grid-cols-2 gap-2">
- <button
- type="button"
- onClick={() => {
- setIsGlobal(true);
- setStartError(null);
- }}
- className={`flex items-start gap-2 rounded-md border p-2.5 text-left transition-colors cursor-pointer ${
- isGlobal
- ? 'border-[var(--accent-border)] bg-[var(--accent-subtle)] text-[#e5e5e5]'
- : 'border-[#2c2c2c] bg-[#161616] text-[#8a8a8a] hover:border-[#3a3a3a] hover:text-[#e5e5e5]'
- }`}
- >
- <Globe
- className={`w-4 h-4 shrink-0 mt-0.5 ${isGlobal ? 'text-[var(--accent)]' : 'text-[#8a8a8a]'}`}
- />
- <div>
- <div className="text-xs font-medium">Worldwide (Internet)</div>
- <div className="text-[10px] opacity-75">Cloudflare Tunnel</div>
- </div>
- </button>
+ <div className="space-y-2">
+ {onStartWebRtcHosting && (
+ <button
+ type="button"
+ data-testid="host-mode-p2p-btn"
+ aria-pressed={hostMode === 'p2p'}
+ onClick={() => {
+ setHostMode('p2p');
+ setStartError(null);
+ }}
+ className={`w-full flex items-start gap-2.5 rounded-md border p-2.5 text-left transition-colors cursor-pointer ${
+ hostMode === 'p2p'
+ ? 'border-[var(--accent-border)] bg-[var(--accent-subtle)] text-[#e5e5e5]'
+ : 'border-[#2c2c2c] bg-[#161616] text-[#8a8a8a] hover:border-[#3a3a3a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ <Radio
+ className={`w-4 h-4 shrink-0 mt-0.5 ${hostMode === 'p2p' ? 'text-[var(--accent)]' : 'text-[#8a8a8a]'}`}
+ />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-1.5 flex-wrap">
+ <span className="text-xs font-medium">
+ Worldwide P2P (Room Code)
+ </span>
+ <span className="text-[9px] font-medium px-1.5 py-0.5 rounded bg-emerald-500/15 text-emerald-300 border border-emerald-500/25 leading-none">
+ Recommended
+ </span>
+ </div>
+ <div className="text-[10px] opacity-75 mt-0.5">
+ Fast direct INK-XXXX code for PC &amp; Android tablets · No setup
+ </div>
+ </div>
+ </button>
+ )}
- <button
- type="button"
- onClick={() => {
- setIsGlobal(false);
- setStartError(null);
- }}
- className={`flex items-start gap-2 rounded-md border p-2.5 text-left transition-colors cursor-pointer ${
- !isGlobal
- ? 'border-[var(--accent-border)] bg-[var(--accent-subtle)] text-[#e5e5e5]'
- : 'border-[#2c2c2c] bg-[#161616] text-[#8a8a8a] hover:border-[#3a3a3a] hover:text-[#e5e5e5]'
- }`}
- >
- <Wifi
- className={`w-4 h-4 shrink-0 mt-0.5 ${!isGlobal ? 'text-[var(--accent)]' : 'text-[#8a8a8a]'}`}
- />
- <div>
- <div className="text-xs font-medium">Local Network Only</div>
- <div className="text-[10px] opacity-75">Same Wi-Fi network</div>
- </div>
- </button>
+ <div className="grid grid-cols-2 gap-2">
+ <button
+ type="button"
+ data-testid="host-mode-tunnel-btn"
+ aria-pressed={hostMode === 'tunnel'}
+ onClick={() => {
+ setHostMode('tunnel');
+ setStartError(null);
+ }}
+ className={`flex items-start gap-2 rounded-md border p-2.5 text-left transition-colors cursor-pointer ${
+ hostMode === 'tunnel'
+ ? 'border-[var(--accent-border)] bg-[var(--accent-subtle)] text-[#e5e5e5]'
+ : 'border-[#2c2c2c] bg-[#161616] text-[#8a8a8a] hover:border-[#3a3a3a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ <Globe
+ className={`w-4 h-4 shrink-0 mt-0.5 ${hostMode === 'tunnel' ? 'text-[var(--accent)]' : 'text-[#8a8a8a]'}`}
+ />
+ <div className="min-w-0">
+ <div className="text-xs font-medium leading-tight">
+ Web Link (Cloudflare Tunnel)
+ </div>
+ <div className="text-[10px] opacity-75 mt-0.5">
+ Browser guests &amp; up to 16 peers
+ </div>
+ </div>
+ </button>
+
+ <button
+ type="button"
+ data-testid="host-mode-lan-btn"
+ aria-pressed={hostMode === 'lan'}
+ onClick={() => {
+ setHostMode('lan');
+ setStartError(null);
+ }}
+ className={`flex items-start gap-2 rounded-md border p-2.5 text-left transition-colors cursor-pointer ${
+ hostMode === 'lan'
+ ? 'border-[var(--accent-border)] bg-[var(--accent-subtle)] text-[#e5e5e5]'
+ : 'border-[#2c2c2c] bg-[#161616] text-[#8a8a8a] hover:border-[#3a3a3a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ <Wifi
+ className={`w-4 h-4 shrink-0 mt-0.5 ${hostMode === 'lan' ? 'text-[var(--accent)]' : 'text-[#8a8a8a]'}`}
+ />
+ <div className="min-w-0">
+ <div className="text-xs font-medium leading-tight">
+ Local Network (LAN)
+ </div>
+ <div className="text-[10px] opacity-75 mt-0.5">Same Wi-Fi network</div>
+ </div>
+ </button>
+ </div>
</div>
</div>
- {!isGlobal && (
+ {hostMode === 'lan' && (
<div>
<label className="block text-[11px] font-medium text-[#b5b5b5] mb-1.5">
Local Port
@@ -701,17 +891,31 @@ export const HostModal: React.FC<HostModalProps> = ({
<AlertTriangle className="w-4 h-4 shrink-0 mt-0.5 text-red-400" />
<span className="break-words">{startError}</span>
</div>
- {isGlobal && (
- <button
- type="button"
- onClick={() => {
- setIsGlobal(false);
- void handleStart(false);
- }}
- className="text-[11px] text-[#e5e5e5] underline hover:text-white cursor-pointer"
- >
- Start Local Wi-Fi Server instead
- </button>
+ {hostMode === 'tunnel' && (
+ <div className="flex flex-wrap gap-3">
+ {onStartWebRtcHosting && (
+ <button
+ type="button"
+ onClick={() => {
+ setHostMode('p2p');
+ void handleStart('p2p');
+ }}
+ className="text-[11px] text-[#e5e5e5] underline hover:text-white cursor-pointer"
+ >
+ Start Quick P2P Room instead
+ </button>
+ )}
+ <button
+ type="button"
+ onClick={() => {
+ setHostMode('lan');
+ void handleStart('lan');
+ }}
+ className="text-[11px] text-[#e5e5e5] underline hover:text-white cursor-pointer"
+ >
+ Start Local Wi-Fi Server instead
+ </button>
+ </div>
)}
</div>
)}
@@ -720,18 +924,25 @@ export const HostModal: React.FC<HostModalProps> = ({
<div className="flex items-center gap-1.5 text-[#e5e5e5] font-medium">
<Shield className="w-3.5 h-3.5 text-[#8a8a8a]" />
<span>
- {isGlobal ? 'Encrypted Worldwide Tunnel' : 'Local Wi-Fi Access'}
+ {hostMode === 'p2p'
+ ? 'Direct Encrypted WebRTC P2P'
+ : hostMode === 'tunnel'
+ ? 'Encrypted Worldwide Tunnel'
+ : 'Local Wi-Fi Access'}
</span>
</div>
<p className="leading-relaxed">
- {isGlobal
- ? 'Launches a Cloudflare HTTPS/WSS tunnel (HTTP/2 over port 443) so friends on any network can join in a browser or desktop app.'
- : 'Reachable only by devices on the same Wi-Fi network or virtual LAN (e.g. Tailscale).'}
+ {hostMode === 'p2p'
+ ? `Generates a short Room Code (INK-XXXX-XXXXXX) with zero server setup or cloudflared download. Android tablets and desktop apps connect directly over WebRTC (up to ${MAX_WEBRTC_PEERS} guests).`
+ : hostMode === 'tunnel'
+ ? 'Launches a Cloudflare HTTPS/WSS tunnel (HTTP/2 over port 443) so friends on any network can join in a browser or desktop app.'
+ : 'Reachable only by devices on the same Wi-Fi network or virtual LAN (e.g. Tailscale).'}
</p>
</div>
<button
type="button"
+ data-testid="host-start-btn"
disabled={isStarting}
onClick={() => void handleStart()}
className="w-full flex items-center justify-center gap-2 rounded bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 py-2 text-xs font-medium transition-opacity disabled:opacity-50 cursor-pointer"
@@ -741,17 +952,27 @@ export const HostModal: React.FC<HostModalProps> = ({
<Loader2 className="w-3.5 h-3.5 animate-spin" />
<span>
{startStatus ||
- (isGlobal ? 'Starting Worldwide Tunnel...' : 'Starting Server...')}
+ (hostMode === 'p2p'
+ ? 'Opening P2P Room...'
+ : hostMode === 'tunnel'
+ ? 'Starting Worldwide Tunnel...'
+ : 'Starting Server...')}
</span>
</>
) : (
<>
- {isGlobal ? (
+ {hostMode === 'p2p' ? (
+ <Radio className="w-3.5 h-3.5" />
+ ) : hostMode === 'tunnel' ? (
<Globe className="w-3.5 h-3.5" />
) : (
<Users className="w-3.5 h-3.5" />
)}
- <span>Start Server &amp; Copy Link</span>
+ <span>
+ {hostMode === 'p2p'
+ ? 'Start Room & Copy Code'
+ : 'Start Server & Copy Link'}
+ </span>
</>
)}
</button>
@@ -761,20 +982,62 @@ export const HostModal: React.FC<HostModalProps> = ({
<div>
<label className="text-[11px] font-medium text-[#b5b5b5] mb-1.5 flex items-center gap-1.5">
<Link2 className="w-3.5 h-3.5 text-[#8a8a8a]" />
- <span>Invite Link</span>
+ <span>Room Code (INK-XXXX...) or Invite Link</span>
</label>
<input
type="text"
+ data-testid="join-target-input"
value={joinUrl}
onChange={(e) => setJoinUrl(e.target.value)}
- placeholder="https://....trycloudflare.com/?room=...&token=..."
+ placeholder="INK-7429-K8P2M9 or invite link (ws://, wss://, trycloudflare.com)"
className="w-full rounded border border-[#2c2c2c] bg-[#161616] px-3 py-2 text-xs text-[#e5e5e5] font-mono focus:border-[var(--accent-border)] focus:outline-hidden"
/>
+ {parsedJoinTarget && (
+ <div
+ data-testid="join-target-badge"
+ className="mt-1.5 flex items-center gap-1.5 text-[10px] font-mono text-emerald-400"
+ >
+ {parsedJoinTarget.kind === 'p2p' ? (
+ <>
+ <Radio className="w-3 h-3 shrink-0" />
+ <span>
+ WebRTC P2P Room detected ({parsedJoinTarget.roomCode})
+ </span>
+ </>
+ ) : (
+ <>
+ <Globe className="w-3 h-3 shrink-0" />
+ <span>
+ {parsedJoinTarget.isSecure
+ ? 'Secure WebSocket (WSS)'
+ : 'WebSocket (WS)'}{' '}
+ detected ({parsedJoinTarget.host})
+ </span>
+ </>
+ )}
+ </div>
+ )}
<p className="text-[10px] text-[#8a8a8a] mt-1">
- Paste the full worldwide or LAN invite link shared by the host.
+ Paste an Android/PC P2P Room Code (INK-XXXX-XXXXXX), P2P invite link, or
+ Cloudflare / LAN WebSocket URL.
</p>
</div>
+ {parsedJoinTarget?.kind === 'p2p' && !parsedJoinTarget.roomSecret && (
+ <div>
+ <label className="block text-[11px] font-medium text-[#b5b5b5] mb-1.5">
+ Room Passcode (if separate)
+ </label>
+ <input
+ type="text"
+ value={manualSecret}
+ onChange={(e) => setManualSecret(e.target.value.toUpperCase())}
+ placeholder="e.g. K8P2M9"
+ className="w-full rounded border border-[#2c2c2c] bg-[#161616] px-3 py-2 text-xs text-[#e5e5e5] font-mono focus:border-[var(--accent-border)] focus:outline-hidden"
+ />
+ </div>
+ )}
+
<button
type="submit"
disabled={isJoining || !joinUrl.trim()}
@@ -787,8 +1050,16 @@ export const HostModal: React.FC<HostModalProps> = ({
</>
) : (
<>
- <Link2 className="w-3.5 h-3.5" />
- <span>Join Session</span>
+ {parsedJoinTarget?.kind === 'p2p' ? (
+ <Radio className="w-3.5 h-3.5" />
+ ) : (
+ <Link2 className="w-3.5 h-3.5" />
+ )}
+ <span>
+ {parsedJoinTarget?.kind === 'p2p'
+ ? 'Join P2P Room'
+ : 'Join Session'}
+ </span>
</>
)}
</button>
diff --git a/src/components/ModalHost.tsx b/src/components/ModalHost.tsx
index 8e67af2..3ed8cf2 100644
--- a/src/components/ModalHost.tsx
+++ b/src/components/ModalHost.tsx
@@ -9,7 +9,7 @@ import {
} from '../types/editor';
import { AppSettings, ResizeCanvasOptions } from '../types/settings';
import { CollabPeer, CollabRole, ConnectionStatus, SessionHostInfo } from '../types/multiplayer';
-import { ParsedInviteLink } from '../services/multiplayerService';
+import { ParsedCollabTarget } from '../services/multiplayerService';
import { CrashedSessionInfo } from '../services/recoveryService';
import { TonalCorrectionType } from '../utils/tonalEngine';
import { AnyFilterParams, AnyTonalParams } from '../hooks/useTonalAndFilterActions';
@@ -40,7 +40,7 @@ import { ConfirmDialogModal } from './ConfirmDialogModal';
import { FilterModal } from './FilterModal';
import { SaveDocumentResult } from '../utils/appCloseFlow';
-export type InviteLinkPayload = ParsedInviteLink;
+export type InviteLinkPayload = ParsedCollabTarget;
export interface ModalHostProps {
layers: LayerItem[];
@@ -90,8 +90,18 @@ export interface ModalHostProps {
isGlobal?: boolean,
onStatus?: (status: string) => void
) => Promise<boolean | SessionHostInfo>;
+ handleStartWebRtcHosting?: (
+ roomName: string,
+ hostNickname?: string,
+ onStatus?: (status: string) => void
+ ) => Promise<boolean | SessionHostInfo>;
stopHosting: () => void;
- joinByInviteUrl: (rawUrl: string, nickname?: string, persistName?: boolean) => Promise<boolean>;
+ joinByInviteUrl: (
+ rawUrl: string,
+ nickname?: string,
+ persistName?: boolean,
+ secretOverride?: string
+ ) => Promise<boolean>;
leaveRoom: () => void;
onSetPeerRole?: (peerId: string | number, role: 'editor' | 'viewer') => void;
onKickPeer?: (peerId: string | number) => void;
@@ -108,7 +118,8 @@ export interface ModalHostProps {
name?: string,
token?: string,
isSecureOverride?: boolean,
- persistName?: boolean
+ persistName?: boolean,
+ wsPath?: string
) => Promise<boolean>;
onCaptureTimelapseNow?: () => void;
handleSave?: () => void;
@@ -148,6 +159,7 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(
collabMyPeer,
updateMyName,
handleStartHosting,
+ handleStartWebRtcHosting,
stopHosting,
joinByInviteUrl,
leaveRoom,
@@ -337,6 +349,7 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(
myPeer={collabMyPeer}
onUpdateMyName={updateMyName}
onStartHosting={handleStartHosting}
+ onStartWebRtcHosting={handleStartWebRtcHosting}
onStopHosting={stopHosting}
onJoinByInviteUrl={joinByInviteUrl}
onLeaveRoom={leaveRoom}
@@ -350,8 +363,22 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(
<ClipboardInviteToast
invite={clipboardInvite}
onJoin={(h, p, r, t, isSecure) =>
- void joinRoom(h, p, r, collabMyPeer.name, t, isSecure, false)
+ void joinRoom(
+ h,
+ p,
+ r,
+ collabMyPeer.name,
+ t,
+ isSecure,
+ false,
+ clipboardInvite && (!('kind' in clipboardInvite) || clipboardInvite.kind === 'ws')
+ ? clipboardInvite.wsPath
+ : undefined
+ )
}
+ onJoinTarget={(target) => {
+ void joinByInviteUrl(target.url, collabMyPeer.name, false);
+ }}
onDismiss={() => setClipboardInvite(null)}
/>
@@ -363,6 +390,12 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(
}
void joinRoom(h, p, r, name, t, isSecure, Boolean(persistName));
}}
+ onJoinTargetInBrowser={(name, target, persistName) => {
+ if (persistName) {
+ updateMyName(name);
+ }
+ void joinByInviteUrl(target.url, name, Boolean(persistName));
+ }}
onDismiss={() => setWebLandingInvite(null)}
/>
diff --git a/src/components/PigmentBlendControl.tsx b/src/components/PigmentBlendControl.tsx
index 7583e74..294bf89 100644
--- a/src/components/PigmentBlendControl.tsx
+++ b/src/components/PigmentBlendControl.tsx
@@ -33,16 +33,16 @@ interface SwatchPair {
}
const DEFAULT_PAIRS: readonly SwatchPair[] = [
- { id: 'blue-yellow', label: 'Blue + Yellow', c1: '#0084ff', c2: '#fff000' },
- { id: 'green-magenta', label: 'Green + Magenta', c1: '#28ff00', c2: '#ff00a6' },
- { id: 'sky-cream', label: 'Sky + Cream', c1: '#4fa8ff', c2: '#fffef0' },
+ { id: 'blue-yellow', label: 'Blue + Yellow', c1: '#002185', c2: '#fcd300' },
+ { id: 'navy-white', label: 'Navy + White', c1: '#0d1b44', c2: '#ffffff' },
+ { id: 'crimson-yellow', label: 'Crimson + Yellow', c1: '#80022e', c2: '#fcd300' },
];
const PREVIEW_STEPS = 14;
/**
- * Computes a CSS linear-gradient string directly from Ink Studio's 7-band Kubelka-Munk
- * spectral pigment engine so the UI swatch matches canvas blending 1:1.
+ * Computes a CSS linear-gradient string directly from Ink Studio's physical Kubelka-Munk
+ * pigment engine so the UI swatch matches canvas blending 1:1.
*/
export function buildPigmentPreviewGradient(
colorA: string,
@@ -131,7 +131,7 @@ export const PigmentBlendControl: React.FC<PigmentBlendControlProps> = React.mem
: 'bg-white/[0.04] text-[#7a7a7a] border-white/[0.07]'
}`}
>
- {enabled ? 'Spectral' : 'RGB'}
+ {enabled ? 'Pigment' : 'RGB'}
</span>
</div>
diff --git a/src/components/QuickAccessPanel.tsx b/src/components/QuickAccessPanel.tsx
index 9656d3f..c945525 100644
--- a/src/components/QuickAccessPanel.tsx
+++ b/src/components/QuickAccessPanel.tsx
@@ -28,7 +28,12 @@ import { ToolType } from '../types/editor';
import { ThemePreset } from '../types/settings';
import { COMMAND_CATALOG, CommandActionId, QuickAccessItem } from '../types/workspace';
import { BUILTIN_BRUSHES } from '../utils/presetBrushes';
-import { getEffectiveBrushSettings, saveActivePresetId } from '../utils/brushPresetManager';
+import {
+ NEUTRAL_BRUSH_DEFAULTS,
+ getEffectiveBrushSettings,
+ migrateLegacyPresetId,
+ saveActivePresetId,
+} from '../utils/brushPresetManager';
import {
toolStoreActions,
useToolStore,
@@ -137,10 +142,15 @@ export const QuickAccessPanel: React.FC<QuickAccessPanelProps> = React.memo(({
return;
}
if (item.kind === 'brush' && item.brushPresetId) {
+ const resolvedPresetId = migrateLegacyPresetId(item.brushPresetId);
toolStoreActions.selectTool('brush');
- saveActivePresetId(item.brushPresetId);
- const effective = getEffectiveBrushSettings(item.brushPresetId);
- toolStoreActions.updateBrushSettings({ ...effective, preset: item.brushPresetId });
+ saveActivePresetId(resolvedPresetId);
+ const effective = getEffectiveBrushSettings(resolvedPresetId);
+ toolStoreActions.updateBrushSettings({
+ ...NEUTRAL_BRUSH_DEFAULTS,
+ ...effective,
+ preset: resolvedPresetId,
+ });
}
};
@@ -264,7 +274,10 @@ export const QuickAccessPanel: React.FC<QuickAccessPanelProps> = React.memo(({
item.commandId &&
isCommandActive(item.commandId, handlers, palettesHidden)) ||
(item.kind === 'tool' && item.toolId === activeTool) ||
- (item.kind === 'brush' && item.brushPresetId === activePresetId && activeTool === 'brush') ||
+ (item.kind === 'brush' &&
+ item.brushPresetId &&
+ migrateLegacyPresetId(item.brushPresetId) === activePresetId &&
+ activeTool === 'brush') ||
(item.kind === 'color' && item.color?.toLowerCase() === primaryColor.toLowerCase());
return (
@@ -311,7 +324,10 @@ export const QuickAccessPanel: React.FC<QuickAccessPanelProps> = React.memo(({
item.commandId &&
isCommandActive(item.commandId, handlers, palettesHidden)) ||
(item.kind === 'tool' && item.toolId === activeTool) ||
- (item.kind === 'brush' && item.brushPresetId === activePresetId && activeTool === 'brush') ||
+ (item.kind === 'brush' &&
+ item.brushPresetId &&
+ migrateLegacyPresetId(item.brushPresetId) === activePresetId &&
+ activeTool === 'brush') ||
(item.kind === 'color' && item.color?.toLowerCase() === primaryColor.toLowerCase()));
return (
diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsx
index 6947dbe..88166a5 100644
--- a/src/components/SettingsModal.tsx
+++ b/src/components/SettingsModal.tsx
@@ -9,6 +9,8 @@ import {
Keyboard,
SlidersHorizontal,
Gauge,
+ Users,
+ Shield,
Info,
RotateCcw,
Check,
@@ -64,6 +66,7 @@ type SettingsTab =
| 'canvas'
| 'brush'
| 'performance'
+ | 'collaboration'
| 'shortcuts'
| 'modifiers'
| 'about';
@@ -310,6 +313,19 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
onShowToast('Modifier keys reset to defaults');
};
+ const handleResetCollaboration = () => {
+ const updated: AppSettings = {
+ ...localSettings,
+ collabSignalingUrl: '',
+ collabTurnUrl: '',
+ collabTurnUsername: '',
+ collabTurnCredential: '',
+ };
+ setLocalSettings(updated);
+ onUpdateSettings(updated);
+ onShowToast('Collaboration network settings reset to defaults');
+ };
+
const resolvedAccent = resolveModernAccentColor(
localSettings.modernAccent,
localSettings.modernCustomColor
@@ -320,6 +336,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
{ id: 'canvas', label: 'Canvas', icon: <Layers className="w-3.5 h-3.5" /> },
{ id: 'brush', label: 'Brush & Stylus', icon: <Paintbrush className="w-3.5 h-3.5" /> },
{ id: 'performance', label: 'Performance', icon: <Gauge className="w-3.5 h-3.5" /> },
+ { id: 'collaboration', label: 'Collaboration', icon: <Users className="w-3.5 h-3.5" /> },
{ id: 'shortcuts', label: 'Shortcuts', icon: <Keyboard className="w-3.5 h-3.5" /> },
{
id: 'modifiers',
@@ -662,6 +679,147 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
/>
)}
+ {activeTab === 'collaboration' && (
+ <div className="space-y-5">
+ <div className="flex items-center justify-between gap-3">
+ <div>
+ <h3 className="text-xs font-medium text-[#e5e5e5]">
+ Collaborative Drawing (WebRTC P2P)
+ </h3>
+ <p className="text-[11px] text-[#8a8a8a]">
+ Configure your display nickname and optional custom signaling or TURN relay servers for P2P rooms
+ </p>
+ </div>
+ <button
+ type="button"
+ data-testid="settings-collab-reset-btn"
+ onClick={handleResetCollaboration}
+ className="flex items-center gap-1 px-2.5 py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer shrink-0"
+ >
+ <RotateCcw className="w-3 h-3" />
+ <span>Reset</span>
+ </button>
+ </div>
+
+ <section className="space-y-2">
+ <h4 className="text-xs font-medium text-[#e5e5e5]">Artist Nickname</h4>
+ <input
+ type="text"
+ data-testid="settings-collab-nickname"
+ value={localSettings.userName || ''}
+ onChange={(e) => {
+ const val = e.target.value;
+ handleChange('userName', val);
+ safeLocalStorageSetItem(NICKNAME_STORAGE_KEY, val, 'artist name');
+ safeLocalStorageSetItem(
+ NICKNAME_CUSTOMIZED_STORAGE_KEY,
+ val.trim() ? '1' : '0',
+ 'artist name flag'
+ );
+ }}
+ maxLength={40}
+ placeholder="Artist"
+ className="w-full bg-[#161616] px-3 py-1.5 rounded text-xs text-[#e5e5e5] placeholder-[#8a8a8a]/50"
+ />
+ <p className="text-[10px] text-[#8a8a8a]">
+ Shown to other artists on live cursors, participant lists, and owned layers.
+ </p>
+ </section>
+
+ <section className="space-y-2">
+ <h4 className="text-xs font-medium text-[#e5e5e5]">
+ Custom Signaling Server URL (Optional)
+ </h4>
+ <input
+ type="text"
+ data-testid="settings-collab-signaling-url"
+ value={localSettings.collabSignalingUrl || ''}
+ onChange={(e) => handleChange('collabSignalingUrl', e.target.value)}
+ placeholder="wss://your-worker.workers.dev/signal (leave blank for built-in free relays)"
+ className="w-full bg-[#161616] px-3 py-1.5 rounded font-mono text-xs text-[#e5e5e5] placeholder-[#8a8a8a]/50"
+ />
+ {localSettings.collabSignalingUrl.trim() &&
+ !/^(wss?|https?):\/\//i.test(localSettings.collabSignalingUrl.trim()) && (
+ <p className="text-[10px] text-amber-400">
+ Signaling URL should start with <code className="font-mono">wss://</code> or{' '}
+ <code className="font-mono">https://</code>.
+ </p>
+ )}
+ <p className="text-[10px] text-[#8a8a8a] leading-relaxed">
+ Leave blank to use Ink Studio&apos;s built-in free multi-relay signaling. Only
+ tiny SDP/ICE handshakes pass through signaling — all brush strokes and tiles
+ travel directly peer-to-peer.
+ </p>
+ </section>
+
+ <section className="space-y-2.5">
+ <div>
+ <h4 className="text-xs font-medium text-[#e5e5e5]">
+ Optional TURN Server (Strict NAT / Firewall)
+ </h4>
+ <p className="text-[10px] text-[#8a8a8a] mt-0.5">
+ Only required when direct P2P hole-punching is blocked by symmetric NAT or
+ corporate firewalls.
+ </p>
+ </div>
+
+ <div className="space-y-2 bg-[#161616] rounded p-3">
+ <div className="space-y-1">
+ <label className="text-[11px] text-[#8a8a8a] block">TURN Server URL</label>
+ <input
+ type="text"
+ data-testid="settings-collab-turn-url"
+ value={localSettings.collabTurnUrl || ''}
+ onChange={(e) => handleChange('collabTurnUrl', e.target.value)}
+ placeholder="turns:turn.example.com:5349"
+ className="w-full bg-[#202020] px-2.5 py-1.5 rounded font-mono text-xs text-[#e5e5e5] placeholder-[#8a8a8a]/50"
+ />
+ {localSettings.collabTurnUrl.trim() &&
+ !/^turns?:/i.test(localSettings.collabTurnUrl.trim()) && (
+ <p className="text-[10px] text-amber-400">
+ TURN URL must start with <code className="font-mono">turn:</code> or{' '}
+ <code className="font-mono">turns:</code>.
+ </p>
+ )}
+ </div>
+
+ <div className="grid grid-cols-2 gap-2.5">
+ <div className="space-y-1">
+ <label className="text-[11px] text-[#8a8a8a] block">TURN Username</label>
+ <input
+ type="text"
+ data-testid="settings-collab-turn-username"
+ value={localSettings.collabTurnUsername || ''}
+ onChange={(e) => handleChange('collabTurnUsername', e.target.value)}
+ placeholder="Optional username"
+ className="w-full bg-[#202020] px-2.5 py-1.5 rounded text-xs text-[#e5e5e5] placeholder-[#8a8a8a]/50"
+ />
+ </div>
+ <div className="space-y-1">
+ <label className="text-[11px] text-[#8a8a8a] block">TURN Credential</label>
+ <input
+ type="password"
+ data-testid="settings-collab-turn-credential"
+ value={localSettings.collabTurnCredential || ''}
+ onChange={(e) => handleChange('collabTurnCredential', e.target.value)}
+ placeholder="Optional password / token"
+ className="w-full bg-[#202020] px-2.5 py-1.5 rounded text-xs text-[#e5e5e5] placeholder-[#8a8a8a]/50"
+ />
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <div className="rounded bg-[#161616] p-3 flex items-start gap-2.5 text-[11px] text-[#8a8a8a]">
+ <Shield className="w-3.5 h-3.5 text-[#8a8a8a] shrink-0 mt-0.5" />
+ <p className="leading-relaxed">
+ Free public Google and Cloudflare STUN servers are included automatically for
+ direct WebRTC P2P connections across PC and Android tablets.
+ </p>
+ </div>
+ </div>
+ )}
+
{activeTab === 'brush' && (
<>
<PressureCurveEditor
diff --git a/src/components/SubToolList.tsx b/src/components/SubToolList.tsx
index 790f70f..bcc9ace 100644
--- a/src/components/SubToolList.tsx
+++ b/src/components/SubToolList.tsx
@@ -1,5 +1,6 @@
import React, { useState, useRef } from 'react';
import {
+ Droplets,
Paintbrush,
Palette,
PenTool,
@@ -13,6 +14,7 @@ import {
ChevronDown,
ChevronRight,
Sliders,
+ AlertTriangle,
} from 'lucide-react';
import { BrushCategory, BrushPresetId, CspBrush } from '../types/editor';
import {
@@ -48,6 +50,7 @@ export interface SubToolListProps {
function renderBuiltinIcon(icon: BuiltinBrushDefinition['icon']) {
if (icon === 'pen') return <PenTool className="w-3 h-3 shrink-0 opacity-80" />;
if (icon === 'pencil') return <Pencil className="w-3 h-3 shrink-0 opacity-80" />;
+ if (icon === 'droplets') return <Droplets className="w-3 h-3 shrink-0 text-sky-300/85" />;
if (icon === 'palette') return <Palette className="w-3 h-3 shrink-0 text-rose-300/85" />;
return <Paintbrush className="w-3 h-3 shrink-0 opacity-80" />;
}
@@ -102,6 +105,17 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(
),
]);
saveActivePresetId(parsedBrush.id);
+ if (parsedBrush.importWarnings && parsedBrush.importWarnings.length > 0) {
+ const count = parsedBrush.importWarnings.length;
+ const first = parsedBrush.importWarnings[0];
+ uiStoreActions.showToast(
+ count === 1
+ ? `Imported "${parsedBrush.name}" (Notice: ${first})`
+ : `Imported "${parsedBrush.name}" with ${count} CSP import notices — check inspector`
+ );
+ } else {
+ uiStoreActions.showToast(`Imported brush "${parsedBrush.name}"`);
+ }
} catch (err: unknown) {
const msg =
err instanceof Error ? err.message : 'Failed to import brush file.';
@@ -386,6 +400,15 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(
<Paintbrush className="w-3 h-3 shrink-0 opacity-70" />
)}
<span className="text-[11px] truncate leading-tight">{brush.name}</span>
+ {brush.importWarnings && brush.importWarnings.length > 0 && (
+ <span
+ title={brush.importWarnings.join('\n')}
+ className="text-amber-400 shrink-0"
+ aria-label="Import warning"
+ >
+ <AlertTriangle className="w-2.5 h-2.5" />
+ </span>
+ )}
</div>
<div className="flex items-center gap-1 shrink-0">
<button
diff --git a/src/components/ToolPropertyInspector.tsx b/src/components/ToolPropertyInspector.tsx
index e2c1adb..7737836 100644
--- a/src/components/ToolPropertyInspector.tsx
+++ b/src/components/ToolPropertyInspector.tsx
@@ -14,6 +14,7 @@ import {
Layers,
Trash2,
Crop,
+ AlertTriangle,
} from 'lucide-react';
import {
BrushSettings,
@@ -190,10 +191,15 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React
const isHidden = useUiStore((s) => s.isLeftPanelHidden);
const [openAccordion, setOpenAccordion] = useState<InspectorAccordionId | null>(null);
+ const [warningsExpanded, setWarningsExpanded] = useState<boolean>(false);
const previewCanvasRef = useRef<HTMLCanvasElement>(null);
const isBrushOrEraser = currentTool === 'brush' || currentTool === 'eraser';
+ useEffect(() => {
+ setWarningsExpanded(false);
+ }, [brushSettings.preset]);
+
useEffect(() => {
if (isHidden || !isBrushOrEraser) return;
const canvas = previewCanvasRef.current;
@@ -216,38 +222,104 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React
preset: brushSettings.preset,
size: brushSettings.size,
flow: brushSettings.flow,
+ brushDensity: brushSettings.brushDensity,
opacity: brushSettings.opacity,
grain: brushSettings.grain,
+ textureDensity: brushSettings.textureDensity,
+ paperTexture: brushSettings.paperTexture,
+ paperTextureImage: brushSettings.paperTextureImage,
paperTextureMode: brushSettings.paperTextureMode,
paperTextureScale: brushSettings.paperTextureScale,
+ paperTextureRotate: brushSettings.paperTextureRotate,
+ paperTextureOffsetX: brushSettings.paperTextureOffsetX,
+ paperTextureOffsetY: brushSettings.paperTextureOffsetY,
paperTextureContrast: brushSettings.paperTextureContrast,
paperTextureBrightness: brushSettings.paperTextureBrightness,
+ paperTextureApplyEachPlot: brushSettings.paperTextureApplyEachPlot,
+ paperTextureEmphasizeDensity: brushSettings.paperTextureEmphasizeDensity,
paperTextureInverted: brushSettings.paperTextureInverted,
hardness: brushSettings.hardness,
spacing: brushSettings.spacing,
minSizeFactor: brushSettings.minSizeFactor,
usePressure: brushSettings.usePressure,
+ useTilt: brushSettings.useTilt,
+ tiltScale: brushSettings.tiltScale,
+ useVelocity: brushSettings.useVelocity,
color: currentTool === 'eraser' ? '#e5e5e5' : '#ececec',
+ secondaryColor: secondaryColor || brushSettings.secondaryColor || '#60a5fa',
backgroundColor: '#161616',
tool: currentTool === 'eraser' ? 'eraser' : 'brush',
+ customTipDataUrl: brushSettings.customTipDataUrl,
customTipImage: resolvedTip,
customTipAngle: brushSettings.customTipAngle,
customTipAngleDynamics: brushSettings.customTipAngleDynamics,
+ customTipRotationRandomScale: brushSettings.customTipRotationRandomScale,
+ isColorTip: brushSettings.isColorTip,
+ isDualToneTip: brushSettings.isDualToneTip,
+ isRibbon: brushSettings.isRibbon,
+ subTips: brushSettings.subTips,
+ subTipOrder: brushSettings.subTipOrder,
+ subTipImages: brushSettings.subTipImages,
thickness: brushSettings.thickness,
thicknessVertical: brushSettings.thicknessVertical,
+ thicknessSensor: brushSettings.thicknessSensor,
flipH: brushSettings.flipH,
flipV: brushSettings.flipV,
blendTipsMode: brushSettings.blendTipsMode,
+ brushCombineMode: brushSettings.brushCombineMode,
adjustDensityByGap: brushSettings.adjustDensityByGap,
antiAlias: brushSettings.antiAlias,
pressureCurve: brushSettings.pressureCurve,
+ velocityCurve: brushSettings.velocityCurve,
+ sizeSensor: brushSettings.sizeSensor,
+ opacitySensor: brushSettings.opacitySensor,
+ densitySensor: brushSettings.densitySensor,
+ intervalSensor: brushSettings.intervalSensor,
+ textureDensitySensor: brushSettings.textureDensitySensor,
+ angleSensor: brushSettings.angleSensor,
+ scatterSensor: brushSettings.scatterSensor,
spray: brushSettings.spray,
+ taper: brushSettings.taper,
dynamics: brushSettings.dynamics,
colorMixing: brushSettings.colorMixing,
+ perceptualMixing: brushSettings.perceptualMixing,
amountOfPaint: brushSettings.amountOfPaint,
densityOfPaint: brushSettings.densityOfPaint,
colorStretch: brushSettings.colorStretch,
+ amountOfPaintSensor: brushSettings.amountOfPaintSensor,
+ densityOfPaintSensor: brushSettings.densityOfPaintSensor,
+ colorStretchSensor: brushSettings.colorStretchSensor,
+ useBlur: brushSettings.useBlur,
+ blurStrength: brushSettings.blurStrength,
+ mixingMode: brushSettings.mixingMode,
wetEdge: brushSettings.wetEdge,
+ wetEdgeRadius: brushSettings.wetEdgeRadius,
+ wetEdgeAlphaPower: brushSettings.wetEdgeAlphaPower,
+ wetEdgeValuePower: brushSettings.wetEdgeValuePower,
+ dualBrush: brushSettings.dualBrush,
+ dualBrushConfig: brushSettings.dualBrushConfig,
+ dualBrushCompositeMode: brushSettings.dualBrushCompositeMode,
+ dualTipDataUrl: brushSettings.dualTipDataUrl,
+ dualTipImage: brushSettings.dualTipImage,
+ dualSize: brushSettings.dualSize,
+ dualLinkSize: brushSettings.dualLinkSize,
+ dualSpacing: brushSettings.dualSpacing,
+ dualScatter: brushSettings.dualScatter,
+ dualThickness: brushSettings.dualThickness,
+ dualThicknessVertical: brushSettings.dualThicknessVertical,
+ dualAngle: brushSettings.dualAngle,
+ dualAngleDynamics: brushSettings.dualAngleDynamics,
+ dualAngleSensor: brushSettings.dualAngleSensor,
+ dualHardness: brushSettings.dualHardness,
+ dualDensity: brushSettings.dualDensity,
+ dualSubTips: brushSettings.dualSubTips,
+ dualSubTipImages: brushSettings.dualSubTipImages,
+ dualSubTipOrder: brushSettings.dualSubTipOrder,
+ dualFlipH: brushSettings.dualFlipH,
+ dualFlipV: brushSettings.dualFlipV,
+ dualSpray: brushSettings.dualSpray,
+ dualIsRibbon: brushSettings.dualIsRibbon,
+ dualScale: brushSettings.dualScale,
renderMode: brushSettings.renderMode,
bristle: brushSettings.bristle,
naturalPaint: brushSettings.naturalPaint,
@@ -263,7 +335,7 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React
cancelAnimationFrame(rafId);
loadListenerCleanup?.();
};
- }, [isHidden, isBrushOrEraser, width, currentTool, brushSettings]);
+ }, [isHidden, isBrushOrEraser, width, currentTool, brushSettings, secondaryColor]);
const activePreset: BrushPresetId = brushSettings.preset || DEFAULT_BRUSH_PRESET_ID;
const activeBuiltinBrush = BUILTIN_BRUSHES.find((b) => b.id === activePreset);
@@ -2006,6 +2078,14 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React
}
const currentAntiAlias = brushSettings.antiAlias ?? 2;
+ const activeImportWarnings =
+ currentTool === 'brush'
+ ? activeCustomBrush?.importWarnings?.length
+ ? activeCustomBrush.importWarnings
+ : brushSettings.importWarnings?.length
+ ? brushSettings.importWarnings
+ : []
+ : [];
return (
<>
@@ -2025,6 +2105,40 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React
</button>
)}
</div>
+ {activeImportWarnings.length > 0 && (
+ <div
+ data-testid="brush-import-warnings-badge"
+ className="rounded bg-amber-500/10 border border-amber-400/25 px-1.5 py-1 text-[10px] text-amber-200"
+ >
+ <button
+ type="button"
+ onClick={() => setWarningsExpanded((v) => !v)}
+ className="w-full flex items-center justify-between gap-1 text-left cursor-pointer"
+ title={activeImportWarnings.join('\n')}
+ >
+ <span className="flex items-center gap-1 min-w-0">
+ <AlertTriangle className="w-3 h-3 text-amber-400 shrink-0" />
+ <span className="truncate font-medium">
+ {activeImportWarnings.length === 1
+ ? '1 CSP import notice'
+ : `${activeImportWarnings.length} CSP import notices`}
+ </span>
+ </span>
+ {warningsExpanded ? (
+ <ChevronDown className="w-3 h-3 shrink-0 text-amber-300" />
+ ) : (
+ <ChevronRight className="w-3 h-3 shrink-0 text-amber-300" />
+ )}
+ </button>
+ {warningsExpanded && (
+ <ul className="mt-1 space-y-1 pl-4 list-disc text-[9.5px] leading-snug text-amber-100/90">
+ {activeImportWarnings.map((w, idx) => (
+ <li key={idx}>{w}</li>
+ ))}
+ </ul>
+ )}
+ </div>
+ )}
<CompactSlider
label="Brush Size ([ / ])"
valueLabel={`${brushSettings.size < 10 ? brushSettings.size.toFixed(1) : Math.round(brushSettings.size)}px`}
@@ -2460,17 +2574,15 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React
>
<span>Blending &amp; Mixing</span>
<div className="flex items-center gap-1">
- {brushSettings.colorMixing && (
- <span
- className={`px-1.5 py-[1px] rounded-full text-[9px] font-medium border ${
- (brushSettings.perceptualMixing ?? true)
- ? 'bg-emerald-500/12 text-emerald-300 border-emerald-400/25'
- : 'bg-white/[0.04] text-[#8a8a8a] border-white/[0.08]'
- }`}
- >
- {(brushSettings.perceptualMixing ?? true) ? 'Pigment' : 'Regular'}
- </span>
- )}
+ <span
+ className={`px-1.5 py-[1px] rounded-full text-[9px] font-medium border ${
+ (brushSettings.perceptualMixing ?? true)
+ ? 'bg-emerald-500/12 text-emerald-300 border-emerald-400/25'
+ : 'bg-white/[0.04] text-[#8a8a8a] border-white/[0.08]'
+ }`}
+ >
+ {(brushSettings.perceptualMixing ?? true) ? 'Pigment' : 'Regular'}
+ </span>
{openAccordion === 'mixing' ? (
<ChevronDown className="w-3 h-3" />
) : (
@@ -2481,7 +2593,30 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React
{openAccordion === 'mixing' && (
<div className="px-2.5 pb-2.5 pt-1 space-y-2.5">
- <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <PigmentBlendControl
+ label="Color Blending"
+ strengthLabel="Pigment Strength"
+ enabled={brushSettings.perceptualMixing ?? true}
+ onEnabledChange={(enabled) =>
+ handleUpdateBrushSettings({
+ perceptualMixing: enabled,
+ })
+ }
+ strength={brushSettings.naturalPaint?.pigmentMixingStrength ?? 1.0}
+ onStrengthChange={(s) =>
+ handleUpdateBrushSettings({
+ perceptualMixing: true,
+ naturalPaint: {
+ ...DEFAULT_NATURAL_PAINT_SETTINGS,
+ ...(brushSettings.naturalPaint || {}),
+ pigmentMixingStrength: s,
+ },
+ })
+ }
+ primaryColor={primaryColor}
+ secondaryColor={secondaryColor}
+ />
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer pt-1 border-t border-white/[0.06]">
<span>Color Mixing</span>
<input
type="checkbox"
@@ -2527,29 +2662,6 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React
</button>
))}
</div>
- <PigmentBlendControl
- label="Color Blending"
- strengthLabel="Pigment Strength"
- enabled={brushSettings.perceptualMixing ?? true}
- onEnabledChange={(enabled) =>
- handleUpdateBrushSettings({
- perceptualMixing: enabled,
- })
- }
- strength={brushSettings.naturalPaint?.pigmentMixingStrength ?? 1.0}
- onStrengthChange={(s) =>
- handleUpdateBrushSettings({
- perceptualMixing: true,
- naturalPaint: {
- ...DEFAULT_NATURAL_PAINT_SETTINGS,
- ...(brushSettings.naturalPaint || {}),
- pigmentMixingStrength: s,
- },
- })
- }
- primaryColor={primaryColor}
- secondaryColor={secondaryColor}
- />
<CompactSlider
label="Amount of Paint"
valueLabel={`${Math.round((brushSettings.amountOfPaint ?? brushSettings.naturalPaint?.paintLoad ?? 0.7) * 100)}%`}
@@ -2582,6 +2694,32 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React
value={Math.round((brushSettings.colorStretch ?? 0.6) * 100)}
onChange={(v) => handleUpdateBrushSettings({ colorStretch: v / 100 })}
/>
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Optical Blur</span>
+ <input
+ type="checkbox"
+ checked={Boolean(brushSettings.useBlur)}
+ onChange={(e) => {
+ const enabled = e.target.checked;
+ handleUpdateBrushSettings({
+ useBlur: enabled,
+ ...(enabled && brushSettings.blurStrength === undefined
+ ? { blurStrength: 0.35 }
+ : {}),
+ });
+ }}
+ />
+ </label>
+ {brushSettings.useBlur && (
+ <CompactSlider
+ label="Blur Strength"
+ valueLabel={`${Math.round((brushSettings.blurStrength ?? 0.35) * 100)}%`}
+ min={5}
+ max={100}
+ value={Math.round((brushSettings.blurStrength ?? 0.35) * 100)}
+ onChange={(v) => handleUpdateBrushSettings({ blurStrength: v / 100 })}
+ />
+ )}
</>
)}
<CompactSlider
@@ -2646,10 +2784,14 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React
}
className="w-full h-6 bg-[#161616] text-[#e5e5e5] text-[10px] px-1.5 rounded cursor-pointer"
>
- <option value="subtract">Subtract (Valley Fill)</option>
+ <option value="normal">Normal</option>
<option value="multiply">Multiply</option>
+ <option value="subtract">Subtract (Valley Fill)</option>
<option value="compare">Compare Density</option>
<option value="overlay">Overlay</option>
+ <option value="color-burn">Color Burn</option>
+ <option value="linear-burn">Linear Burn</option>
+ <option value="height">Height</option>
<option value="outline">Outline</option>
</select>
</div>
diff --git a/src/components/WebLandingModal.tsx b/src/components/WebLandingModal.tsx
index cc3d09c..cc17ab6 100644
--- a/src/components/WebLandingModal.tsx
+++ b/src/components/WebLandingModal.tsx
@@ -1,12 +1,23 @@
import React, { useEffect, useState } from 'react';
import { Users, Globe, Monitor, ArrowRight, User, X } from 'lucide-react';
import { isTauriEnvironment } from '../hooks/useMultiplayer';
-import { DEEP_LINK_SCHEME, ParsedInviteLink } from '../services/multiplayerService';
+import {
+ DEEP_LINK_SCHEME,
+ ParsedCollabTarget,
+ ParsedInviteLink,
+ ParsedP2pInvite,
+} from '../services/multiplayerService';
import { NICKNAME_CUSTOMIZED_STORAGE_KEY, NICKNAME_STORAGE_KEY } from '../types/settings';
import { safeLocalStorageSetItem } from '../utils/safeStorage';
+function isP2pInvite(
+ invite: ParsedCollabTarget | ParsedInviteLink
+): invite is ParsedP2pInvite {
+ return 'kind' in invite && invite.kind === 'p2p';
+}
+
interface WebLandingModalProps {
- invite: ParsedInviteLink | null;
+ invite: ParsedCollabTarget | ParsedInviteLink | null;
onJoinInBrowser: (
name: string,
host: string,
@@ -16,12 +27,18 @@ interface WebLandingModalProps {
isSecure?: boolean,
persistName?: boolean
) => void;
+ onJoinTargetInBrowser?: (
+ name: string,
+ target: ParsedCollabTarget,
+ persistName?: boolean
+ ) => void;
onDismiss: () => void;
}
export const WebLandingModal: React.FC<WebLandingModalProps> = ({
invite,
onJoinInBrowser,
+ onJoinTargetInBrowser,
onDismiss,
}) => {
const [userName, setUserName] = useState(() => {
@@ -49,21 +66,54 @@ export const WebLandingModal: React.FC<WebLandingModalProps> = ({
return () => window.removeEventListener('keydown', handleKeyDown);
}, [isVisible, onDismiss]);
- // If running inside desktop Tauri app, don't show the web browser welcome banner
+ // If running inside native Tauri app, don't show the web browser welcome banner
if (!invite || isTauri) return null;
+ const p2pMode = isP2pInvite(invite);
+ const isSecureWs = !isP2pInvite(invite) && invite.isSecure;
const trimmedName = userName.trim();
- const hostDisplay = `${invite.host}${
- invite.port && invite.port !== 443 && invite.port !== 80 ? `:${invite.port}` : ''
- }`;
+ const hostDisplay = isP2pInvite(invite)
+ ? `WebRTC P2P · ${invite.joinCode}`
+ : `${invite.host}${
+ invite.port && invite.port !== 443 && invite.port !== 80 ? `:${invite.port}` : ''
+ }`;
const handleOpenInApp = () => {
+ if (isP2pInvite(invite)) {
+ const params = new URLSearchParams();
+ params.set('code', invite.roomCode);
+ if (invite.roomSecret) params.set('secret', invite.roomSecret);
+ if (invite.roomName && invite.roomName !== invite.roomCode) {
+ params.set('room', invite.roomName);
+ }
+ if (invite.signalingUrl) params.set('sig', invite.signalingUrl);
+ window.location.href = `${DEEP_LINK_SCHEME}//p2p?${params.toString()}`;
+ return;
+ }
const tokenPart = invite.token ? `&token=${encodeURIComponent(invite.token)}` : '';
const protoPart = invite.isSecure ? '&protocol=https' : '';
const deepLink = `${DEEP_LINK_SCHEME}//join?host=${encodeURIComponent(invite.host)}&port=${invite.port}&room=${encodeURIComponent(invite.roomName)}${tokenPart}${protoPart}`;
window.location.href = deepLink;
};
+ const dispatchJoin = (name: string, persistName: boolean) => {
+ if ('kind' in invite && onJoinTargetInBrowser) {
+ onJoinTargetInBrowser(name, invite, persistName);
+ return;
+ }
+ if (!isP2pInvite(invite)) {
+ onJoinInBrowser(
+ name,
+ invite.host,
+ invite.port,
+ invite.roomName,
+ invite.token,
+ invite.isSecure,
+ persistName
+ );
+ }
+ };
+
const handleJoinWithNickname = (e?: React.FormEvent) => {
e?.preventDefault();
if (!trimmedName) {
@@ -72,27 +122,11 @@ export const WebLandingModal: React.FC<WebLandingModalProps> = ({
}
safeLocalStorageSetItem(NICKNAME_STORAGE_KEY, trimmedName, 'artist name');
safeLocalStorageSetItem(NICKNAME_CUSTOMIZED_STORAGE_KEY, '1', 'artist name flag');
- onJoinInBrowser(
- trimmedName,
- invite.host,
- invite.port,
- invite.roomName,
- invite.token,
- invite.isSecure,
- true
- );
+ dispatchJoin(trimmedName, true);
};
const handlePlayAsGuest = () => {
- onJoinInBrowser(
- 'Guest',
- invite.host,
- invite.port,
- invite.roomName,
- invite.token,
- invite.isSecure,
- false
- );
+ dispatchJoin('Guest', false);
};
return (
@@ -134,9 +168,9 @@ export const WebLandingModal: React.FC<WebLandingModalProps> = ({
<span className="text-[10px] uppercase tracking-wider text-[#8a8a8a]">
Connecting to Canvas
</span>
- {invite.isSecure && (
+ {(p2pMode || isSecureWs) && (
<span className="font-mono text-[10px] px-1.5 py-0.5 rounded bg-[#202020] border border-[#2c2c2c] text-[#a0a0a0]">
- HTTPS · WSS
+ {p2pMode ? 'WEBRTC · P2P' : 'HTTPS · WSS'}
</span>
)}
</div>
@@ -203,11 +237,11 @@ export const WebLandingModal: React.FC<WebLandingModalProps> = ({
<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"
+ className="w-full min-h-[44px] 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>Open in Ink Studio App</span>
</span>
<ArrowRight className="w-3.5 h-3.5 text-[#8a8a8a]" />
</button>
diff --git a/src/components/brushStudio/BrushStudioScratchpad.tsx b/src/components/brushStudio/BrushStudioScratchpad.tsx
index 76bdf62..740cc31 100644
--- a/src/components/brushStudio/BrushStudioScratchpad.tsx
+++ b/src/components/brushStudio/BrushStudioScratchpad.tsx
@@ -6,7 +6,14 @@ import {
centripetalCatmullRomToBezier,
drawBrushCubicBezierSegment,
drawBrushDot,
+ renderCompleteStroke,
} from '../../engine/BrushEngine';
+import {
+ buildRibbonRenderOptionsFromBrushSettings,
+ isRibbonBrush,
+ RibbonStrokeSession,
+} from '../../engine/RibbonBrushEngine';
+import { resolveDualBrushConfig } from '../../engine/DualBrushEngine';
import {
isNaturalPaintBrush,
NaturalPaintStrokeSession,
@@ -16,6 +23,10 @@ import {
LayerPixelSampler,
PaintReservoir,
} from '../../utils/colorMixingEngine';
+import {
+ compositePigmentOverPixelInto,
+ isPigmentCompatibleCombineMode,
+} from '../../utils/pigmentEngine';
type ScratchpadBg = 'white' | 'gray' | 'dark';
@@ -53,6 +64,8 @@ export const BrushStudioScratchpad: React.FC<BrushStudioScratchpadProps> = ({
pointerId: number;
points: Point[];
natSession: NaturalPaintStrokeSession | null;
+ ribbonSession: RibbonStrokeSession | null;
+ useCompleteCommit: boolean;
sampler: LayerPixelSampler | null;
reservoir: PaintReservoir | null;
remainderDist: number;
@@ -63,6 +76,8 @@ export const BrushStudioScratchpad: React.FC<BrushStudioScratchpadProps> = ({
pointerId: -1,
points: [],
natSession: null,
+ ribbonSession: null,
+ useCompleteCommit: false,
sampler: null,
reservoir: null,
remainderDist: 0,
@@ -141,6 +156,11 @@ export const BrushStudioScratchpad: React.FC<BrushStudioScratchpadProps> = ({
s.totalDist = 0;
const naturalMode = isNaturalPaintBrush(brushSettings);
+ const hasDualBrush = Boolean(resolveDualBrushConfig(brushSettings));
+ const hasCompareDensity = brushSettings.brushCombineMode === 'compare-density';
+ const ribbonMode = !naturalMode && !hasDualBrush && isRibbonBrush(brushSettings);
+ s.useCompleteCommit = !naturalMode && (hasDualBrush || hasCompareDensity);
+
const needsSampler = Boolean(
brushSettings.colorMixing !== false &&
(brushSettings.colorMixing || (naturalMode && brushSettings.naturalPaint?.spatialMixing))
@@ -149,6 +169,7 @@ export const BrushStudioScratchpad: React.FC<BrushStudioScratchpadProps> = ({
s.reservoir = brushSettings.colorMixing ? new PaintReservoir(activeColor) : null;
if (naturalMode) {
+ s.ribbonSession = null;
strokeSeedRef.current = (strokeSeedRef.current + 7919) & 0x7fffffff;
const previewBs: BrushSettings = {
...brushSettings,
@@ -161,8 +182,12 @@ export const BrushStudioScratchpad: React.FC<BrushStudioScratchpadProps> = ({
strokeSeedRef.current
);
s.natSession.stampInitialPoint(dCtx, pt, s.sampler || undefined, true);
+ } else if (ribbonMode) {
+ s.natSession = null;
+ s.ribbonSession = new RibbonStrokeSession();
} else {
s.natSession = null;
+ s.ribbonSession = null;
const opts = buildBrushRenderOptions(brushSettings, {
size: Math.min(110, Math.max(2, brushSettings.size || 24)),
opacity: 1.0,
@@ -198,6 +223,26 @@ export const BrushStudioScratchpad: React.FC<BrushStudioScratchpadProps> = ({
if (s.natSession) {
s.natSession.drawCubicSegment(dCtx, p1, c1, c2, p2, s.sampler || undefined, true);
+ } else if (s.ribbonSession) {
+ const previewBs: BrushSettings = {
+ ...brushSettings,
+ color: activeColor,
+ size: Math.min(110, Math.max(2, brushSettings.size || 24)),
+ };
+ const ribbonOpts = buildRibbonRenderOptionsFromBrushSettings(
+ previewBs,
+ 'color',
+ false,
+ false,
+ false,
+ false,
+ undefined,
+ {
+ opacity: 1.0,
+ useGpu: false,
+ }
+ );
+ s.ribbonSession.appendCubicSegment(dCtx, { p0: p1, c1, c2, p3: p2 }, ribbonOpts, 'brush');
} else {
const opts = buildBrushRenderOptions(brushSettings, {
size: Math.min(110, Math.max(2, brushSettings.size || 24)),
@@ -239,21 +284,104 @@ export const BrushStudioScratchpad: React.FC<BrushStudioScratchpadProps> = ({
}
if (base && draft) {
- const bCtx = base.getContext('2d');
- const dCtx = draft.getContext('2d');
+ const bCtx = base.getContext('2d', { willReadFrequently: true });
+ const dCtx = draft.getContext('2d', { willReadFrequently: true });
if (bCtx && dCtx) {
- if (s.natSession) {
- s.natSession.flushPendingTapIfNeeded(s.sampler || undefined);
- const tapBounds = s.natSession.getDirtyBounds();
- if (tapBounds && s.points.length <= 1) {
- s.natSession.flushDirtyRectToContext(dCtx, tapBounds, true, 1.0, 'source-over');
+ const pigmentStrength =
+ brushSettings.perceptualMixing === false ||
+ brushSettings.isTransparentInk ||
+ !isPigmentCompatibleCombineMode(brushSettings.brushCombineMode)
+ ? 0
+ : Math.max(
+ 0,
+ Math.min(1, brushSettings.naturalPaint?.pigmentMixingStrength ?? 1.0)
+ );
+ const compositeDraftToBase = () => {
+ const op = Math.max(0.01, Math.min(1, brushSettings.opacity ?? 1.0));
+ if (pigmentStrength > 0.005) {
+ const w = base.width;
+ const h = base.height;
+ const dstImg = bCtx.getImageData(0, 0, w, h);
+ const srcImg = dCtx.getImageData(0, 0, w, h);
+ const dd = dstImg.data;
+ const sd = srcImg.data;
+ const whiteGround = bgMode === 'white';
+ const pxOut: [number, number, number, number] = [0, 0, 0, 0];
+ for (let i = 0; i < dd.length; i += 4) {
+ const sa = sd[i + 3];
+ if (sa === 0) continue;
+ const effA = op >= 0.999 ? sa : Math.round(sa * op);
+ if (effA <= 0) continue;
+ compositePigmentOverPixelInto(
+ dd[i],
+ dd[i + 1],
+ dd[i + 2],
+ dd[i + 3],
+ sd[i],
+ sd[i + 1],
+ sd[i + 2],
+ effA,
+ pigmentStrength,
+ whiteGround,
+ 'source-over',
+ brushSettings.brushCombineMode,
+ pxOut
+ );
+ dd[i] = pxOut[0];
+ dd[i + 1] = pxOut[1];
+ dd[i + 2] = pxOut[2];
+ dd[i + 3] = pxOut[3];
+ }
+ bCtx.putImageData(dstImg, 0, 0);
+ } else {
+ bCtx.save();
+ bCtx.globalAlpha = op;
+ bCtx.drawImage(draft, 0, 0);
+ bCtx.restore();
+ }
+ dCtx.clearRect(0, 0, draft.width, draft.height);
+ };
+
+ if (s.useCompleteCommit && s.points.length > 0) {
+ dCtx.clearRect(0, 0, draft.width, draft.height);
+ const previewBs: BrushSettings = {
+ ...brushSettings,
+ color: activeColor,
+ size: Math.min(110, Math.max(2, brushSettings.size || 24)),
+ useGpu: false,
+ };
+ if (pigmentStrength > 0.005) {
+ renderCompleteStroke(
+ dCtx,
+ s.points,
+ { ...previewBs, opacity: 1.0, brushCombineMode: undefined },
+ 'brush',
+ 'color',
+ false,
+ base,
+ false
+ );
+ compositeDraftToBase();
+ } else {
+ renderCompleteStroke(bCtx, s.points, previewBs, 'brush', 'color', false, base, false);
}
+ } else {
+ if (s.natSession) {
+ s.natSession.flushPendingTapIfNeeded(s.sampler || undefined);
+ const tapBounds = s.natSession.getDirtyBounds();
+ if (tapBounds && s.points.length <= 1) {
+ s.natSession.flushDirtyRectToContext(dCtx, tapBounds, true, 1.0, 'source-over');
+ }
+ } else if (s.ribbonSession && s.points.length === 1) {
+ const opts = buildBrushRenderOptions(brushSettings, {
+ size: Math.min(110, Math.max(2, brushSettings.size || 24)),
+ opacity: 1.0,
+ useGpu: false,
+ });
+ drawBrushDot(dCtx, s.points[0], activeColor, opts);
+ }
+ compositeDraftToBase();
}
- bCtx.save();
- bCtx.globalAlpha = Math.max(0.01, Math.min(1, brushSettings.opacity ?? 1.0));
- bCtx.drawImage(draft, 0, 0);
- bCtx.restore();
- dCtx.clearRect(0, 0, draft.width, draft.height);
}
}
@@ -261,6 +389,11 @@ export const BrushStudioScratchpad: React.FC<BrushStudioScratchpadProps> = ({
s.natSession.finishAndDispose();
s.natSession = null;
}
+ if (s.ribbonSession) {
+ s.ribbonSession.reset();
+ s.ribbonSession = null;
+ }
+ s.useCompleteCommit = false;
s.sampler = null;
s.reservoir = null;
s.points = [];
diff --git a/src/components/brushStudio/BrushStudioTabsPrimary.tsx b/src/components/brushStudio/BrushStudioTabsPrimary.tsx
index 0df28f1..73ade59 100644
--- a/src/components/brushStudio/BrushStudioTabsPrimary.tsx
+++ b/src/components/brushStudio/BrushStudioTabsPrimary.tsx
@@ -7,6 +7,7 @@ import type {
BrushSettings,
CspAngleDynamicsMode,
CspPaperTextureMode,
+ CspSubTipOrder,
CspTaperSettings,
CspTipFlipMode,
GrainMappingMode,
@@ -240,7 +241,7 @@ export const ShapeBristlesTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch })
</div>
))}
</div>
- <StudioSegmented<'random' | 'sequential' | 'direction' | 'reverse'>
+ <StudioSegmented<CspSubTipOrder>
label="Sub-Tip Order"
value={bs.subTipOrder ?? 'sequential'}
options={[
@@ -723,10 +724,31 @@ export const TextureGrainTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch })
export const DualBrushTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch }) => {
const dualInputRef = useRef<HTMLInputElement>(null);
+ const patchDual = (patch: Partial<typeof bs>) => {
+ const baseCfg = bs.dualBrushConfig;
+ const nextEnabled = patch.dualBrush !== undefined ? patch.dualBrush : (baseCfg?.enabled ?? Boolean(bs.dualBrush));
+ const nextCfg = baseCfg
+ ? {
+ ...baseCfg,
+ enabled: nextEnabled,
+ ...(patch.dualBrushCompositeMode !== undefined
+ ? { compositeMode: patch.dualBrushCompositeMode as NonNullable<typeof bs.dualBrushConfig>['compositeMode'] }
+ : {}),
+ ...(patch.dualScale !== undefined ? { sizeRatio: patch.dualScale } : {}),
+ ...(patch.dualAngle !== undefined ? { angle: patch.dualAngle } : {}),
+ ...(patch.dualScatter !== undefined ? { scatter: patch.dualScatter } : {}),
+ ...(patch.dualSpacing !== undefined ? { spacing: patch.dualSpacing } : {}),
+ ...(patch.dualTipDataUrl !== undefined ? { tipDataUrl: patch.dualTipDataUrl } : {}),
+ ...(patch.dualTipImage !== undefined ? { tipImage: patch.dualTipImage } : {}),
+ }
+ : undefined;
+ onPatch(nextCfg ? { ...patch, dualBrushConfig: nextCfg } : patch);
+ };
+
const handleUploadDualTip = async (file: File) => {
try {
const res = await readImageFileAsDataUrl(file);
- onPatch({
+ patchDual({
dualBrush: true,
dualTipDataUrl: res.dataUrl,
dualTipImage: res.image,
@@ -743,7 +765,7 @@ export const DualBrushTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch }) =>
label="Enable Dual Brush Compositing"
description="Modulate primary tip with a secondary tip shape"
checked={Boolean(bs.dualBrush)}
- onChange={(v) => onPatch({ dualBrush: v })}
+ onChange={(v) => patchDual({ dualBrush: v })}
/>
{bs.dualBrush && (
@@ -771,7 +793,7 @@ export const DualBrushTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch }) =>
onClick={() => {
const url = generateNaturalTipByProfile('rake');
const img = url ? getPreloadedBuiltinTipImage(url) : undefined;
- onPatch({ dualTipDataUrl: url, dualTipImage: img });
+ patchDual({ dualTipDataUrl: url, dualTipImage: img });
}}
className="px-2 py-1 rounded bg-[#242424] hover:bg-[#323232] text-[10px] text-[#cccccc] cursor-pointer"
>
@@ -792,13 +814,27 @@ export const DualBrushTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch }) =>
/>
</div>
- <StudioSegmented<'multiply' | 'subtract' | 'darken' | 'overlay' | 'screen'>
+ <StudioSegmented<
+ | 'multiply'
+ | 'subtract'
+ | 'darken'
+ | 'height'
+ | 'linear-burn'
+ | 'color-burn'
+ | 'compare-density'
+ | 'overlay'
+ | 'screen'
+ >
label="Composite Blend Mode"
value={
((bs.dualBrushCompositeMode as
| 'multiply'
| 'subtract'
| 'darken'
+ | 'height'
+ | 'linear-burn'
+ | 'color-burn'
+ | 'compare-density'
| 'overlay'
| 'screen') || 'multiply')
}
@@ -806,10 +842,14 @@ export const DualBrushTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch }) =>
{ id: 'multiply', label: 'Multiply' },
{ id: 'subtract', label: 'Subtract' },
{ id: 'darken', label: 'Darken' },
+ { id: 'height', label: 'Height' },
+ { id: 'linear-burn', label: 'Lin Burn' },
+ { id: 'color-burn', label: 'Col Burn' },
+ { id: 'compare-density', label: 'Compare' },
{ id: 'overlay', label: 'Overlay' },
{ id: 'screen', label: 'Screen' },
]}
- onChange={(v) => onPatch({ dualBrushCompositeMode: v })}
+ onChange={(v) => patchDual({ dualBrushCompositeMode: v })}
/>
<StudioSlider
@@ -818,7 +858,7 @@ export const DualBrushTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch }) =>
min={20}
max={300}
valueLabel={`${Math.round((bs.dualScale ?? 1.0) * 100)}%`}
- onChange={(v) => onPatch({ dualScale: v / 100 })}
+ onChange={(v) => patchDual({ dualScale: v / 100 })}
/>
<StudioSlider
label="Dual Angle"
@@ -826,7 +866,7 @@ export const DualBrushTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch }) =>
min={-180}
max={180}
valueLabel={`${Math.round(bs.dualAngle ?? 0)}°`}
- onChange={(v) => onPatch({ dualAngle: v })}
+ onChange={(v) => patchDual({ dualAngle: v })}
/>
<StudioSlider
label="Dual Scatter"
@@ -834,7 +874,7 @@ export const DualBrushTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch }) =>
min={0}
max={200}
valueLabel={`${Math.round((bs.dualScatter ?? 0) * 100)}%`}
- onChange={(v) => onPatch({ dualScatter: v / 100 })}
+ onChange={(v) => patchDual({ dualScatter: v / 100 })}
/>
<StudioSlider
label="Dual Spacing"
@@ -842,7 +882,7 @@ export const DualBrushTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch }) =>
min={2}
max={100}
valueLabel={`${Math.round((bs.dualSpacing ?? 0.1) * 100)}%`}
- onChange={(v) => onPatch({ dualSpacing: v / 100 })}
+ onChange={(v) => patchDual({ dualSpacing: v / 100 })}
/>
</>
)}
diff --git a/src/components/brushStudio/BrushStudioTabsSecondary.tsx b/src/components/brushStudio/BrushStudioTabsSecondary.tsx
index b7a4e20..e0e5db6 100644
--- a/src/components/brushStudio/BrushStudioTabsSecondary.tsx
+++ b/src/components/brushStudio/BrushStudioTabsSecondary.tsx
@@ -82,7 +82,7 @@ export const NaturalPaintMixingTab: React.FC<BrushStudioTabProps> = ({ bs, onPat
<PigmentBlendControl
variant="studio"
label="Color Blending"
- strengthLabel="Kubelka-Munk Pigment Strength"
+ strengthLabel="Pigment Strength"
enabled={bs.perceptualMixing !== false}
onEnabledChange={(enabled) => onPatch({ perceptualMixing: enabled })}
strength={np.pigmentMixingStrength}
@@ -140,6 +140,27 @@ export const NaturalPaintMixingTab: React.FC<BrushStudioTabProps> = ({ bs, onPat
valueLabel={`${Math.round((bs.colorStretch ?? 0.65) * 100)}%`}
onChange={(v) => onPatch({ colorStretch: v / 100 })}
/>
+ <StudioToggle
+ label="Optical Blend Blur"
+ description="Isotropic smoothing pass on picked-up canvas color for silky blending"
+ checked={Boolean(bs.useBlur)}
+ onChange={(v) =>
+ onPatch({
+ useBlur: v,
+ blurStrength: v ? bs.blurStrength ?? 0.35 : bs.blurStrength,
+ })
+ }
+ />
+ {bs.useBlur && (
+ <StudioSlider
+ label="Blur Strength"
+ value={Math.round((bs.blurStrength ?? 0.35) * 100)}
+ min={5}
+ max={100}
+ valueLabel={`${Math.round((bs.blurStrength ?? 0.35) * 100)}%`}
+ onChange={(v) => onPatch({ blurStrength: v / 100 })}
+ />
+ )}
<StudioSlider
label="Charge per Pressure"
value={Math.round(np.chargePerPressure * 100)}
@@ -527,6 +548,7 @@ export interface AboutPresetsTabProps extends BrushStudioTabProps {
}
export const AboutPresetsTab: React.FC<AboutPresetsTabProps> = ({
+ bs,
brushName,
onBrushNameChange,
category,
@@ -543,6 +565,18 @@ export const AboutPresetsTab: React.FC<AboutPresetsTabProps> = ({
return (
<div className="space-y-4">
+ {bs.importWarnings && bs.importWarnings.length > 0 && (
+ <div className="p-2.5 rounded bg-amber-500/10 border border-amber-400/25 space-y-1.5">
+ <div className="text-[11px] font-medium text-amber-300">
+ CSP Import Notices ({bs.importWarnings.length})
+ </div>
+ <ul className="pl-4 list-disc space-y-1 text-[10.5px] leading-snug text-amber-100/90">
+ {bs.importWarnings.map((w, idx) => (
+ <li key={idx}>{w}</li>
+ ))}
+ </ul>
+ </div>
+ )}
<div className="p-2.5 rounded bg-[#181818] border border-white/[0.06] space-y-3">
<div className="space-y-1">
<label className="text-[11px] text-[#a3a3a3]">Brush Name</label>
@@ -561,10 +595,11 @@ export const AboutPresetsTab: React.FC<AboutPresetsTabProps> = ({
onChange={(e) => onCategoryChange(e.target.value as BrushCategory | 'custom')}
className="w-full px-2.5 py-1.5 rounded bg-[#111111] border border-white/10 text-[12px] text-[#f5f5f5]"
>
- <option value="natural-paint">Natural Paint</option>
- <option value="brush">Brush</option>
- <option value="sketch">Sketch</option>
<option value="pen">Pen</option>
+ <option value="sketch">Sketch</option>
+ <option value="brush">Brush</option>
+ <option value="blend">Blend</option>
+ <option value="natural-paint">Natural Paint</option>
<option value="custom">Custom</option>
</select>
</div>
diff --git a/src/components/canvasArea/useCanvasEffects.ts b/src/components/canvasArea/useCanvasEffects.ts
index d38120a..7be8986 100644
--- a/src/components/canvasArea/useCanvasEffects.ts
+++ b/src/components/canvasArea/useCanvasEffects.ts
@@ -2,6 +2,7 @@ import React, { useEffect, useRef, useState } from 'react';
import { BrushSettings, LiquifySettings, RetouchSettings, ToolType } from '../../types/editor';
import { ModifierAction } from '../../types/settings';
import { getBrushTipOutline, resolveBrushTipImage, TipOutline } from '../../utils/brushOutline';
+import { computeTipStampDimensions } from '../../engine/BrushEngine';
import { preloadTipImage } from '../../utils/brushStorage';
import { subscribeNativeTablet } from '../../utils/nativeTabletInput';
import { CursorConfig, formatCursorRingTransform } from './types';
@@ -110,9 +111,10 @@ export function useCanvasEffects({
setTipOutline(null);
}, [activeTipImage, brushSettings.customTipDataUrl, brushSettings.preset]);
- const isCustomTip = Boolean(tipOutline && (tool === 'brush' || tool === 'eraser'));
+ const isCustomTip = Boolean(
+ tipOutline && !brushSettings.isRibbon && (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
@@ -129,12 +131,17 @@ export function useCanvasEffects({
(brushSettings.customTipAngleDynamics === 'direction' ||
brushSettings.customTipAngleDynamics === 'direction-random');
- const cursorWidth = thicknessVertical
- ? Math.max(2, cursorBaseWidth * thicknessRatio)
- : cursorBaseWidth;
- const cursorHeight = thicknessVertical
- ? Math.max(2, cursorBaseWidth * tipAspect)
- : Math.max(2, cursorBaseWidth * tipAspect * thicknessRatio);
+ const tipAspect =
+ isCustomTip && tipOutline ? tipOutline.height / Math.max(1, tipOutline.width) : 1;
+ const tipCursorDims = computeTipStampDimensions(
+ cursorBaseWidth,
+ thicknessRatio,
+ thicknessVertical,
+ isCustomTip && tipOutline ? tipOutline.width : 1,
+ isCustomTip && tipOutline ? tipOutline.height : 1
+ );
+ const cursorWidth = Math.max(2, tipCursorDims.width);
+ const cursorHeight = Math.max(2, tipCursorDims.height);
// Brush tip rotation: tip angle relative to canvas + viewport canvas rotation
const totalAngleDeg = tipAngleDeg + liveRotation;
diff --git a/src/components/canvasArea/useCanvasPointerHandlers.ts b/src/components/canvasArea/useCanvasPointerHandlers.ts
index 5112415..2f38997 100644
--- a/src/components/canvasArea/useCanvasPointerHandlers.ts
+++ b/src/components/canvasArea/useCanvasPointerHandlers.ts
@@ -10,7 +10,7 @@ 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 { shouldSuppressDomPointerEvent } from '../../utils/nativeTabletInput';
import { artworkTimeTracker } from '../../utils/artworkTimeTracker';
import { toolStoreActions, useToolStore, useUiStore } from '../../stores';
import { extractCoalescedEvents, extractPredictedEvents } from './types';
@@ -290,11 +290,11 @@ export function useCanvasPointerHandlers({
return;
}
- // Native WinTab / Windows Ink channel owns pen brush/eraser strokes; skip duplicate DOM PointerEvent.
+ // Native WinTab / Windows Ink channel owns pen brush/eraser strokes; skip duplicate DOM
+ // pen events AND WinTab CXO_SYSTEM-synthesized mouse events (which carry constant pressure=0.5).
if (
- e.pointerType === 'pen' &&
- isNativePenStreamActive() &&
- (tool === 'brush' || tool === 'eraser')
+ (tool === 'brush' || tool === 'eraser') &&
+ shouldSuppressDomPointerEvent(e.pointerType, e.clientX, e.clientY)
) {
return;
}
@@ -310,9 +310,8 @@ export function useCanvasPointerHandlers({
const handleCanvasPointerMove = (e: React.PointerEvent<HTMLElement>) => {
if (
- e.pointerType === 'pen' &&
- isNativePenStreamActive() &&
- (tool === 'brush' || tool === 'eraser')
+ (tool === 'brush' || tool === 'eraser') &&
+ shouldSuppressDomPointerEvent(e.pointerType, e.clientX, e.clientY)
) {
return;
}
@@ -330,9 +329,8 @@ export function useCanvasPointerHandlers({
const handleCanvasPointerUp = (e: React.PointerEvent<HTMLElement>) => {
if (
!(
- e.pointerType === 'pen' &&
- isNativePenStreamActive() &&
- (tool === 'brush' || tool === 'eraser')
+ (tool === 'brush' || tool === 'eraser') &&
+ shouldSuppressDomPointerEvent(e.pointerType, e.clientX, e.clientY)
)
) {
onPointerUp(e);
diff --git a/src/components/canvasArea/useCompositorViewport.ts b/src/components/canvasArea/useCompositorViewport.ts
index c80042b..b6d0aa0 100644
--- a/src/components/canvasArea/useCompositorViewport.ts
+++ b/src/components/canvasArea/useCompositorViewport.ts
@@ -7,6 +7,7 @@ import {
SoftProofSettings,
} from '../../types/editor';
import { CanvasNavigationHandle } from '../../hooks/useCanvasNavigation';
+import { computeTipStampDimensions } from '../../engine/BrushEngine';
import { ViewportCompositor } from '../../utils/compositor';
import { SparseTileGrid } from '../../utils/tileEngine';
import { getOnionSkinFrames } from '../../utils/animationEngine';
@@ -215,6 +216,9 @@ export function useCompositorViewport({
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);
+ const draftPigmentStrength = Number((draftCanvas as any)?.__draftPigmentStrength ?? 0);
+ const draftPigmentWhiteGround = Boolean((draftCanvas as any)?.__draftPigmentWhiteGround);
+ const draftCombineMode = (draftCanvas as any)?.__draftCombineMode;
return {
dimensions: rp.dimensions,
showCheckerboard: rp.showCheckerboard,
@@ -230,6 +234,9 @@ export function useCompositorViewport({
activeDraftSpace: draftSpace,
activeDraftOpacity: rp.brushOpacity,
activeDraftMonochrome: draftMonochrome,
+ activeDraftPigmentStrength: draftPigmentStrength,
+ activeDraftPigmentWhiteGround: draftPigmentWhiteGround,
+ activeDraftCombineMode: draftCombineMode,
};
};
@@ -264,12 +271,15 @@ export function useCompositorViewport({
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);
+ const dims = computeTipStampDimensions(
+ baseW,
+ cfg.thicknessRatio,
+ cfg.thicknessVertical,
+ 1,
+ cfg.tipAspect
+ );
+ const cW = Math.max(2, dims.width);
+ const cH = Math.max(2, dims.height);
ring.style.width = `${cW}px`;
ring.style.height = `${cH}px`;
const pos = lastPointerPosRef.current;
diff --git a/src/engine/BristleRibbonEngine.ts b/src/engine/BristleRibbonEngine.ts
index 2c9ef5d..838d13a 100644
--- a/src/engine/BristleRibbonEngine.ts
+++ b/src/engine/BristleRibbonEngine.ts
@@ -179,6 +179,12 @@ export class BristleRibbonEngine {
private readonly prevBedA = new Float32Array(7);
private readonly prevBedLoad = new Float32Array(7);
private readonly prevBedRad = new Float32Array(7);
+ private readonly bandR = new Float32Array(7);
+ private readonly bandG = new Float32Array(7);
+ private readonly bandB = new Float32Array(7);
+ private readonly bandLoad = new Float32Array(7);
+ private readonly bandAlpha = new Float32Array(7);
+ private readonly bandCount = new Int32Array(7);
private bedInitialized: boolean = false;
// Reusable segment output buffer
@@ -452,8 +458,8 @@ export class BristleRibbonEngine {
}
const avgW = Math.max(2, (p0.width + p3.width) * 0.5 || this.config.size);
- // Fine high-DPI continuous ribbon stepping: razor-smooth curves even on large 80-120px brushes
- const targetStep = Math.max(1.0, Math.min(3.2, avgW * Math.max(0.035, this.config.spacing * 0.55)));
+ // Continuous capsules connect prev->cur seamlessly, so 1.4..4.8px stepping stays smooth without over-rasterizing
+ const targetStep = Math.max(1.4, Math.min(4.8, avgW * Math.max(0.05, this.config.spacing * 0.85)));
const slices = Math.max(1, Math.min(64, Math.ceil(polyLen / targetStep)));
const n = this.reservoir.count;
@@ -592,12 +598,18 @@ export class BristleRibbonEngine {
if (hasUnderBed) segCount += BED_BANDS;
// Accumulate local spatial color & load per under-bed band so yellow+purple NEVER muddy together!
- const bandR = [0, 0, 0, 0, 0, 0, 0];
- const bandG = [0, 0, 0, 0, 0, 0, 0];
- const bandB = [0, 0, 0, 0, 0, 0, 0];
- const bandLoad = [0, 0, 0, 0, 0, 0, 0];
- const bandAlpha = [0, 0, 0, 0, 0, 0, 0];
- const bandCount = [0, 0, 0, 0, 0, 0, 0];
+ const bandR = this.bandR;
+ const bandG = this.bandG;
+ const bandB = this.bandB;
+ const bandLoad = this.bandLoad;
+ const bandAlpha = this.bandAlpha;
+ const bandCount = this.bandCount;
+ bandR.fill(0);
+ bandG.fill(0);
+ bandB.fill(0);
+ bandLoad.fill(0);
+ bandAlpha.fill(0);
+ bandCount.fill(0);
for (let i = 0; i < n; i++) {
const rawOff = this.reservoir.offsets[i];
@@ -640,8 +652,10 @@ export class BristleRibbonEngine {
this.reservoir.radii[i] * halfW * tuftWidthBoost * rakeCenterBoost * widthBreath
);
+ const pigmentStrength = this.config.naturalPaint.pigmentMixingStrength;
+ const usePigmentSample = pigmentStrength > 0.005;
if (sampler && this.config.naturalPaint.spatialMixing) {
- sampler.samplePointFast(bx, by, strandRad, this.scratchSample);
+ sampler.samplePointFast(bx, by, strandRad, this.scratchSample, usePigmentSample);
} else {
this.scratchSample.a = 0;
}
@@ -756,7 +770,8 @@ export class BristleRibbonEngine {
stepOut.r,
stepOut.g,
stepOut.b,
- effAlpha * 0.35
+ effAlpha * 0.35,
+ pigmentStrength
);
}
}
diff --git a/src/engine/BrushEngine.ts b/src/engine/BrushEngine.ts
index 4773bca..3ba0c44 100644
--- a/src/engine/BrushEngine.ts
+++ b/src/engine/BrushEngine.ts
@@ -22,14 +22,20 @@ import {
CanvasColorMode,
CspSensorConfig,
CspPaperTextureMode,
+ CspSubTipOrder,
CspTipFlipMode,
CspAngleDynamicsMode,
CspBlendTipsMode,
+ CspBrushCombineMode,
CspSpraySettings,
CspTaperSettings,
CspSubTip,
+ CspDualBrushConfig,
+ DualBrushCompositeMode,
} from '../types/editor';
import { enforceColorMode } from '../utils/colorUtils';
+import { getSurfaceTextureHeightField, SURFACE_TEXTURE_SIZE } from '../utils/proceduralBrushTips';
+import { compositeBrushPixelInto, isCustomBrushCombineMode } from '../utils/tileEngine/strokeComposite';
import {
PaintReservoir,
SpatialTipMixer,
@@ -41,6 +47,36 @@ import {
import { GpuDab, WebGlBrushEngine } from './WebGlBrushEngine';
import { performanceManager } from '../utils/performanceManager';
import { isNaturalPaintBrush, renderCompleteNaturalPaintStroke } from './NaturalPaintRenderer';
+import {
+ isRibbonBrush,
+ renderCompleteRibbonStroke,
+ RibbonRepeatMode,
+} from './RibbonBrushEngine';
+import {
+ buildSecondaryBrushSettings,
+ combineDualBrushAlpha,
+ combineDualBrushImageData,
+ computeSecondaryBrushSize,
+ dualBrushCompositeModeToIndex,
+ normalizeDualBrushCompositeMode,
+ resolveDualBrushConfig,
+ scalePointForSecondaryBrush,
+ scalePointsForSecondaryBrush,
+ scaleSegmentForSecondaryBrush,
+} from './DualBrushEngine';
+
+export {
+ buildSecondaryBrushSettings,
+ combineDualBrushAlpha,
+ combineDualBrushImageData,
+ computeSecondaryBrushSize,
+ dualBrushCompositeModeToIndex,
+ normalizeDualBrushCompositeMode,
+ resolveDualBrushConfig,
+ scalePointForSecondaryBrush,
+ scalePointsForSecondaryBrush,
+ scaleSegmentForSecondaryBrush,
+};
// ============================================================================
// 1. Types & Unified Brush Render Options
@@ -54,9 +90,11 @@ export interface BrushRenderOptions {
brushDensity?: number;
adjustDensityByGap?: boolean;
blendTipsMode?: CspBlendTipsMode;
+ brushCombineMode?: CspBrushCombineMode;
spacing?: number;
thickness?: number;
thicknessVertical?: boolean;
+ thicknessSensor?: CspSensorConfig;
flipH?: CspTipFlipMode;
flipV?: CspTipFlipMode;
angle?: number; // degrees
@@ -66,6 +104,9 @@ export interface BrushRenderOptions {
antiAlias?: number;
tipImage?: HTMLImageElement;
isColorTip?: boolean;
+ isDualToneTip?: boolean;
+ isRibbon?: boolean;
+ ribbonRepeatMode?: RibbonRepeatMode;
pressureCurve?: [number, number][];
velocityCurve?: [number, number][];
usePressure?: boolean;
@@ -75,13 +116,15 @@ export interface BrushRenderOptions {
sizeSensor?: CspSensorConfig;
opacitySensor?: CspSensorConfig;
densitySensor?: CspSensorConfig;
+ intervalSensor?: CspSensorConfig;
+ textureDensitySensor?: CspSensorConfig;
bristleSplaySensor?: CspSensorConfig;
paintLoadSensor?: CspSensorConfig;
grainPenetrationSensor?: CspSensorConfig;
angleSensor?: CspSensorConfig;
scatterSensor?: CspSensorConfig;
subTips?: CspSubTip[];
- subTipOrder?: 'random' | 'sequential' | 'direction' | 'reverse';
+ subTipOrder?: CspSubTipOrder;
subTipImages?: HTMLImageElement[];
spray?: CspSpraySettings;
taper?: CspTaperSettings;
@@ -91,6 +134,11 @@ export interface BrushRenderOptions {
amountOfPaint?: number;
densityOfPaint?: number;
colorStretch?: number;
+ amountOfPaintSensor?: CspSensorConfig;
+ densityOfPaintSensor?: CspSensorConfig;
+ colorStretchSensor?: CspSensorConfig;
+ useBlur?: boolean;
+ blurStrength?: number;
mixingMode?: NaturalMixingMode;
wetEdge?: number;
wetEdgeRadius?: number;
@@ -103,15 +151,37 @@ export interface BrushRenderOptions {
paperTextureMode?: CspPaperTextureMode;
paperTextureBrightness?: number;
paperTextureContrast?: number;
+ paperTextureApplyEachPlot?: boolean;
+ paperTextureEmphasizeDensity?: boolean;
paperTextureInverted?: boolean;
paperTextureImage?: HTMLImageElement;
paperTextureScale?: number;
paperTextureRotate?: number;
+ /** Internal flag: skip per-dab paper grain when per-stroke texture pass handles it. */
+ skipPerDabPaperGrain?: boolean;
dualBrush?: boolean;
+ dualBrushConfig?: CspDualBrushConfig;
+ dualTipDataUrl?: string;
dualTipImage?: HTMLImageElement;
- dualBrushCompositeMode?: string;
+ dualBrushCompositeMode?: DualBrushCompositeMode | string;
+ dualSize?: number;
+ dualLinkSize?: boolean;
+ dualSpacing?: number;
dualScale?: number;
+ dualThickness?: number;
+ dualThicknessVertical?: boolean;
dualAngle?: number;
+ dualAngleDynamics?: CspAngleDynamicsMode;
+ dualAngleSensor?: CspSensorConfig;
+ dualHardness?: number;
+ dualDensity?: number;
+ dualSubTips?: CspSubTip[];
+ dualSubTipImages?: HTMLImageElement[];
+ dualSubTipOrder?: CspSubTipOrder;
+ dualFlipH?: CspTipFlipMode;
+ dualFlipV?: CspTipFlipMode;
+ dualSpray?: CspSpraySettings;
+ dualIsRibbon?: boolean;
dualScatter?: number;
dualSurfaceTextureId?: SurfaceTextureId;
dualGrainDepth?: number;
@@ -134,6 +204,7 @@ export interface BrushRenderOptions {
initialAngleRad?: number;
dynamics?: BrushDynamics;
secondaryColor?: string;
+ strokeJitterColor?: { r: number; g: number; b: number; hex: string };
}
export interface EvaluatedBezierSample {
@@ -389,22 +460,56 @@ export function getCompiledCurveLut(curve?: readonly [number, number][]): Float3
}
}
} else {
+ const hArr = new Float64Array(n - 1);
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]);
+ hArr[k] = Math.max(1e-5, dedup[k + 1][0] - dedup[k][0]);
+ deltas[k] = (dedup[k + 1][1] - dedup[k][1]) / hArr[k];
}
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;
+ if (deltas[k - 1] * deltas[k] <= 0) {
+ if (
+ k === 1 &&
+ Math.abs(deltas[0]) < 1e-6 &&
+ hArr[0] < 0.025 &&
+ Math.abs(deltas[1]) > 1e-6
+ ) {
+ // Tiny leading deadzone stub (e.g. (0,0)->(0.0043,0) in CSP effector curves) acts as a
+ // shifted origin rather than a plateau that collapses light-pressure slopes to 0.
+ m[k] = deltas[1];
+ } else if (
+ k === n - 2 &&
+ Math.abs(deltas[n - 2]) < 1e-6 &&
+ hArr[n - 2] < 0.025 &&
+ Math.abs(deltas[n - 3]) > 1e-6
+ ) {
+ m[k] = deltas[n - 3];
+ } else {
+ m[k] = 0;
+ }
+ } else {
+ // Standard Fritsch-Carlson / Brodlie weighted harmonic mean preserves
+ // light-pressure ramps on asymmetric steep-tail CSP effector curves.
+ const w1 = 2 * hArr[k] + hArr[k - 1];
+ const w2 = hArr[k] + 2 * hArr[k - 1];
+ m[k] = (w1 + w2) / (w1 / deltas[k - 1] + w2 / deltas[k]);
+ }
}
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;
+ if (k === 0 && hArr[0] < 0.025) {
+ m[0] = 0;
+ } else if (k === n - 2 && hArr[n - 2] < 0.025) {
+ m[n - 1] = 0;
+ } else {
+ m[k] = 0;
+ m[k + 1] = 0;
+ }
} else {
const alpha = m[k] / dk;
const beta = m[k + 1] / dk;
@@ -501,7 +606,20 @@ export function evaluateCspSensor(
}
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));
+ const tMax =
+ typeof sensor.tiltMax === 'number' && Number.isFinite(sensor.tiltMax) && sensor.tiltMax > tMin
+ ? Math.min(10.0, sensor.tiltMax)
+ : 1.0;
+ const clampedTilt = Math.max(0, Math.min(1, tiltMagnitude));
+ // CSP Tilt curves plot pen altitude on X (0 = flat/tilted, 1 = upright),
+ // whereas tiltMagnitude is 0 (upright) -> 1 (flat).
+ const curveX = sensor.invertTilt ? clampedTilt : 1.0 - clampedTilt;
+ const curvedT = sensor.tiltCurve
+ ? evaluateFastSpline(curveX, sensor.tiltCurve)
+ : sensor.invertTilt
+ ? 1.0 - clampedTilt
+ : clampedTilt;
+ factor *= tMin + (tMax - tMin) * curvedT;
}
if (sensor.useBarrelTwist) {
const twMin = Math.max(0, Math.min(1, sensor.twistMin ?? 0));
@@ -511,7 +629,11 @@ export function evaluateCspSensor(
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;
+ const vVal = sensor.velocityCurve
+ ? evaluateFastSpline(vNorm, sensor.velocityCurve)
+ : sensor.invertVelocity !== false
+ ? 1.0 - vNorm
+ : vNorm;
factor *= vMin + (1.0 - vMin) * vVal;
}
if (sensor.useDistance) {
@@ -524,7 +646,55 @@ export function evaluateCspSensor(
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));
+ const maxFactor =
+ sensor.useTilt && typeof sensor.tiltMax === 'number' && Number.isFinite(sensor.tiltMax) && sensor.tiltMax > 1.0
+ ? Math.min(10.0, sensor.tiltMax)
+ : 1.0;
+ return Math.max(0, Math.min(maxFactor, factor));
+}
+
+/**
+ * Computes normalized linear pen tilt magnitude in [0, 1] from W3C/WinTab (tiltX, tiltY) degrees:
+ * 0.0 = vertical/upright (90° altitude), 1.0 = flat/horizontal (0° altitude).
+ * Uses exact spherical tilt angle `atan(hypot(tan(tx), tan(ty))) / 90°` so CSP tilt curves
+ * (plotted linearly against pen altitude 0..90°) match CSP without sin()-curve distortion.
+ */
+export function computeCspTiltMagnitude(tiltX: number, tiltY: number): number {
+ if (tiltX === 0 && tiltY === 0) return 0;
+ const cx = Math.max(-89.9, Math.min(89.9, tiltX));
+ const cy = Math.max(-89.9, Math.min(89.9, tiltY));
+ const tanX = Math.tan((cx * Math.PI) / 180);
+ const tanY = Math.tan((cy * Math.PI) / 180);
+ const tiltAngleDeg = (Math.atan(Math.hypot(tanX, tanY)) * 180) / Math.PI;
+ return Math.max(0, Math.min(1, tiltAngleDeg / 90));
+}
+
+function resolveTiltBehavior(options: BrushRenderOptions): {
+ readTiltInput: boolean;
+ useSyntheticTiltShading: boolean;
+} {
+ const hasExplicitCspTiltControl = Boolean(
+ options.angleDynamics === 'tilt' ||
+ options.sizeSensor?.useTilt ||
+ options.opacitySensor?.useTilt ||
+ options.densitySensor?.useTilt ||
+ options.intervalSensor?.useTilt ||
+ options.thicknessSensor?.useTilt ||
+ options.textureDensitySensor?.useTilt ||
+ options.amountOfPaintSensor?.useTilt ||
+ options.densityOfPaintSensor?.useTilt ||
+ options.colorStretchSensor?.useTilt
+ );
+ // Built-in pencil/chalk presets opt into synthetic elliptical side-shading via useTilt + tiltScale > 0.
+ // CSP .sut brushes with explicit tilt effectors control size/density/interval/thickness/texture/angle
+ // individually and must NEVER trigger synthetic elliptical stretching even if tiltScale defaults to 1.0.
+ const useSyntheticTiltShading = Boolean(
+ options.useTilt &&
+ !hasExplicitCspTiltControl &&
+ (typeof options.tiltScale === 'number' ? options.tiltScale > 0 : true)
+ );
+ const readTiltInput = Boolean(options.useTilt || hasExplicitCspTiltControl);
+ return { readTiltInput, useSyntheticTiltShading };
}
export function computeEllipticalStepDistance(
@@ -623,6 +793,29 @@ export function resolveTipFlipSigns(
return { signX, signY };
}
+/**
+ * Computes CSP-accurate dab bounding dimensions so BrushSize always represents the
+ * maximum axis of the thickness-scaled tip (preventing tall tips like 56x300 from blowing up).
+ */
+export function computeTipStampDimensions(
+ baseSize: number,
+ thickness: number = 1.0,
+ thicknessVertical: boolean = false,
+ tipW: number = 1,
+ tipH: number = 1
+): { width: number; height: number } {
+ const safeW = tipW > 0 ? tipW : 1;
+ const safeH = tipH > 0 ? tipH : 1;
+ const effThick = Math.max(0.05, Math.min(20.0, thickness || 1.0));
+ const rawW = thicknessVertical ? safeW * effThick : safeW;
+ const rawH = thicknessVertical ? safeH : safeH * effThick;
+ const maxRaw = Math.max(rawW, rawH, 1e-4);
+ return {
+ width: (baseSize * rawW) / maxRaw,
+ height: (baseSize * rawH) / maxRaw,
+ };
+}
+
export function applyCspPaperTextureAlpha(
tipAlpha: number,
grainNorm: number,
@@ -631,14 +824,19 @@ export function applyCspPaperTextureAlpha(
mode: CspPaperTextureMode = 'subtract',
brightness: number = 0,
contrast: number = 0,
- inverted: boolean = false
+ inverted: boolean = false,
+ preserveDensity: boolean = false,
+ emphasizeDensity: boolean = false
): number {
if (textureDensity <= 0.001 || tipAlpha <= 0.001) return tipAlpha;
let g = inverted ? 1.0 - grainNorm : grainNorm;
+ if (emphasizeDensity) {
+ g = Math.max(0, Math.min(1, (g - 0.5) * 2.2 + 0.35));
+ }
if (brightness !== 0) g += brightness / 100.0;
if (contrast !== 0) {
- const cFactor = Math.pow((contrast + 100.0) / 100.0, 2);
+ const cFactor = Math.pow(Math.max(0.05, (contrast + 100.0) / 100.0), 2);
g = (g - 0.5) * cFactor + 0.5;
}
g = Math.max(0, Math.min(1, g));
@@ -646,14 +844,20 @@ export function applyCspPaperTextureAlpha(
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);
+ const effDensity = preserveDensity
+ ? textureDensity
+ : textureDensity * (1.0 - penetration * 0.85);
switch (mode) {
+ case 'normal': {
+ const sil = Math.min(1.0, tipAlpha * 4.0);
+ return Math.max(0, Math.min(1, tipAlpha * (1.0 - effDensity) + g * sil * effDensity));
+ }
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)));
+ return Math.max(0, Math.min(1, tipAlpha - sub * (preserveDensity ? 1.0 : 1.0 - penetration * 0.5)));
}
case 'compare': {
const contactHeight = g * (0.22 + 0.78 * tipAlpha);
@@ -664,9 +868,25 @@ export function applyCspPaperTextureAlpha(
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);
+ // CSP Overlay texture mode: carves valleys strongly at light/medium density
+ // and retains crisp impasto relief even on solid tips (tipAlpha -> 1.0).
+ const dMod = tipAlpha * (1.0 - effDensity * 0.32 * (1.0 - g));
+ const ov = dMod < 0.5 ? 2.0 * dMod * g : 1.0 - 2.0 * (1.0 - dMod) * (1.0 - g);
return Math.max(0, Math.min(1, tipAlpha + (ov - tipAlpha) * effDensity));
}
+ case 'color-burn': {
+ const burned = g <= 0.001 ? 0 : Math.max(0, 1.0 - (1.0 - tipAlpha) / g);
+ return Math.max(0, Math.min(1, tipAlpha + (burned - tipAlpha) * effDensity));
+ }
+ case 'linear-burn': {
+ const burned = Math.max(0, tipAlpha + g - 1.0);
+ return Math.max(0, Math.min(1, tipAlpha + (burned - tipAlpha) * effDensity));
+ }
+ case 'height': {
+ const sil = Math.min(1.0, tipAlpha * 4.0);
+ const relief = Math.max(0, Math.min(1, (tipAlpha + g - 0.5) * 1.6)) * sil;
+ return Math.max(0, Math.min(1, tipAlpha * (1.0 - effDensity) + relief * 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))));
@@ -676,6 +896,142 @@ export function applyCspPaperTextureAlpha(
}
}
+/**
+ * Returns true when a brush should apply its paper texture once at the stroke level
+ * (CSP TextureForPlot = 0) instead of cumulatively per dab.
+ */
+export function needsStrokeLevelPaperTexture(options: {
+ paperTextureApplyEachPlot?: boolean;
+ grain?: number;
+ textureDensity?: number;
+ colorMixing?: boolean;
+ isEraser?: boolean;
+ isBgEraser?: boolean;
+}): boolean {
+ if (options.paperTextureApplyEachPlot !== false) return false;
+ if (options.colorMixing || options.isEraser || options.isBgEraser) return false;
+ const density = options.grain ?? options.textureDensity ?? 0;
+ return density > 0.005;
+}
+
+/**
+ * Applies CSP per-stroke paper texture (TextureForPlot = 0) to a rendered stroke ImageData
+ * anchored at world coordinate (originX, originY) with optional uniform canvas scale.
+ */
+export function applyStrokePaperTextureToImageData(
+ imgData: { data: Uint8ClampedArray; width: number; height: number },
+ originX: number,
+ originY: number,
+ options: {
+ textureDensity?: number;
+ grain?: number;
+ surfaceTextureId?: SurfaceTextureId;
+ paperTextureImage?: HTMLImageElement;
+ paperTextureScale?: number;
+ paperTextureRotate?: number;
+ paperTextureMode?: CspPaperTextureMode;
+ paperTextureBrightness?: number;
+ paperTextureContrast?: number;
+ paperTextureInverted?: boolean;
+ paperTextureEmphasizeDensity?: boolean;
+ paperTextureApplyEachPlot?: boolean;
+ grainPenetrationSensor?: CspSensorConfig;
+ },
+ surfaceScale: number = 1.0
+): void {
+ const density = options.grain ?? options.textureDensity ?? 0;
+ if (density <= 0.005) return;
+
+ const customPaper = options.paperTextureImage
+ ? getCustomPaperLuminance(options.paperTextureImage)
+ : null;
+ const surfacePaper =
+ !customPaper && options.surfaceTextureId
+ ? getSurfaceTextureHeightField(options.surfaceTextureId)
+ : null;
+ const paperData = customPaper ? customPaper.lum : surfacePaper ?? paperGrainTable;
+ const paperW = customPaper ? customPaper.width : surfacePaper ? SURFACE_TEXTURE_SIZE : GRAIN_SIZE;
+ const paperH = customPaper ? customPaper.height : surfacePaper ? SURFACE_TEXTURE_SIZE : GRAIN_SIZE;
+ if (paperW <= 0 || paperH <= 0) return;
+
+ const paperPow2 = (paperW & (paperW - 1)) === 0 && (paperH & (paperH - 1)) === 0;
+ const paperMaskW = paperW - 1;
+ const paperMaskH = paperH - 1;
+ const invScale = 1.0 / Math.max(0.05, options.paperTextureScale ?? 1.0);
+ const rotRad = ((options.paperTextureRotate ?? 0) * Math.PI) / 180;
+ const hasRot = Math.abs(rotRad) > 1e-4;
+ const cosR = hasRot ? Math.cos(rotRad) : 1;
+ const sinR = hasRot ? Math.sin(rotRad) : 0;
+ const mode = options.paperTextureMode ?? 'multiply';
+ const bright = options.paperTextureBrightness ?? 0;
+ const contrast = options.paperTextureContrast ?? 0;
+ const inv = Boolean(options.paperTextureInverted);
+ const emphasize = Boolean(options.paperTextureEmphasizeDensity);
+ const preserveDensity = !options.grainPenetrationSensor?.usePressure;
+ const invSurfScale = surfaceScale > 1e-4 ? 1.0 / surfaceScale : 1.0;
+
+ const { data, width, height } = imgData;
+ const inv255 = 1 / 255;
+
+ for (let y = 0; y < height; y++) {
+ const wy = originY + (y + 0.5) * invSurfScale;
+ const rowOff = y * width;
+ for (let x = 0; x < width; x++) {
+ const pOff = (rowOff + x) << 2;
+ const aByte = data[pOff + 3];
+ if (aByte === 0) continue;
+
+ const wx = originX + (x + 0.5) * invSurfScale;
+ let rotX = wx;
+ let rotY = wy;
+ if (hasRot) {
+ rotX = wx * cosR - wy * sinR;
+ rotY = wx * sinR + wy * cosR;
+ }
+ const psx = rotX * invScale - 0.5;
+ const psy = rotY * invScale - 0.5;
+
+ const pfx = Math.floor(psx);
+ const pfy = Math.floor(psy);
+ const ptx = psx - pfx;
+ const pty = psy - pfy;
+ let px0: number, py0: number, px1: number, py1: number;
+ if (paperPow2) {
+ px0 = pfx & paperMaskW;
+ py0 = pfy & paperMaskH;
+ px1 = (px0 + 1) & paperMaskW;
+ py1 = (py0 + 1) & paperMaskH;
+ } else {
+ px0 = ((pfx % paperW) + paperW) % paperW;
+ py0 = ((pfy % paperH) + paperH) % paperH;
+ px1 = px0 + 1 < paperW ? px0 + 1 : 0;
+ py1 = py0 + 1 < paperH ? py0 + 1 : 0;
+ }
+
+ const pr0 = py0 * paperW;
+ const pr1 = py1 * paperW;
+ const pvTop = paperData[pr0 + px0] + (paperData[pr0 + px1] - paperData[pr0 + px0]) * ptx;
+ const pvBot = paperData[pr1 + px0] + (paperData[pr1 + px1] - paperData[pr1 + px0]) * ptx;
+ const gNorm = (pvTop + (pvBot - pvTop) * pty) * inv255;
+
+ const origAlpha = aByte * inv255;
+ const modAlpha = applyCspPaperTextureAlpha(
+ origAlpha,
+ gNorm,
+ density,
+ 0.5,
+ mode,
+ bright,
+ contrast,
+ inv,
+ preserveDensity,
+ emphasize
+ );
+ data[pOff + 3] = Math.max(0, Math.min(255, Math.round(modAlpha * 255)));
+ }
+ }
+}
+
export function applyCspPostCorrection(
points: Point[],
level: number = 0,
@@ -729,6 +1085,17 @@ export function applyCspPostCorrection(
return current;
}
+/**
+ * Strictly normalizes CSP wet edge alpha/value power into 0..1.
+ * Defensively converts legacy/persisted 0..100 values (> 1.0) by dividing by 100.
+ */
+export function normalizeWetEdgePower01(value: number | undefined, fallback: number = 0): number {
+ const v = value !== undefined && Number.isFinite(value) ? value : fallback;
+ if (!Number.isFinite(v) || v <= 0) return 0;
+ if (v > 1.0) return Math.min(1.0, v / 100.0);
+ return Math.min(1.0, v);
+}
+
export function applyCspWatercolorEdge(
strokeImageData: { data: Uint8ClampedArray; width: number; height: number },
wetEdge: number,
@@ -741,7 +1108,7 @@ export function applyCspWatercolorEdge(
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 r = Math.max(1, Math.min(12, Math.round(radiusPx)));
const totalPixels = width * height;
const alphaOrig = new Float32Array(totalPixels);
@@ -750,41 +1117,84 @@ export function applyCspWatercolorEdge(
alphaOrig[i] = data[i * 4 + 3] / 255.0;
}
- const invKernel = 1.0 / (2 * r + 1);
+ // Clean separable 1D Gaussian blur kernel of exact radius `r` (zero interior pollution beyond `r`)
+ const sigma = Math.max(0.85, radiusPx * 0.72);
+ const twoSigmaSq = 2.0 * sigma * sigma;
+ const kernel = new Float32Array(2 * r + 1);
+ let kSum = 0;
+ for (let k = -r; k <= r; k++) {
+ const w = Math.exp(-(k * k) / twoSigmaSq);
+ kernel[k + r] = w;
+ kSum += w;
+ }
+ const invKSum = 1.0 / kSum;
+ for (let k = 0; k < kernel.length; k++) {
+ kernel[k] *= invKSum;
+ }
+
+ // Horizontal separable pass
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)];
+ let acc = 0;
+ for (let k = -r; k <= r; k++) {
+ const sx = x + k < 0 ? 0 : x + k >= width ? width - 1 : x + k;
+ acc += alphaOrig[row + sx] * kernel[k + r];
+ }
+ alphaTemp[row + x] = acc;
}
}
- const aBoost = strength * (0.45 + alphaPower * 1.15);
- const vDarken = strength * (0.25 + valuePower * 0.55);
+ const normAlphaPower = normalizeWetEdgePower01(alphaPower, 0.25);
+ const normValuePower = normalizeWetEdgePower01(valuePower, 0.15);
+ const aBoost = strength * (0.35 + normAlphaPower * 1.15);
+ const vDarken = strength * (0.18 + normValuePower * 0.55);
+ // Vertical separable pass + smooth inner rim alpha boost & chroma-preserving pigment darkening
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];
+ // Strictly skip transparent pixels to guarantee zero black-fringe halo
+ if (origA <= 0.015) continue;
- 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);
- }
+ let blurredA = 0;
+ for (let k = -r; k <= r; k++) {
+ const sy = y + k < 0 ? 0 : y + k >= height ? height - 1 : y + k;
+ blurredA += alphaTemp[sy * width + x] * kernel[k + r];
}
- sum += alphaTemp[Math.min(height - 1, y + r + 1) * width + x] - alphaTemp[Math.max(0, y - r) * width + x];
+ // Normalize rim gradient by local wash opacity so translucent watercolor washes
+ // form authentic crisp inner drying rims just like Clip Studio Paint.
+ const relDrop = Math.max(0, origA - blurredA) / Math.max(0.22, origA);
+ const rawRim = relDrop * 2.2;
+ if (rawRim > 0.008) {
+ // Smooth edge guard prevents faint antialiased outer pixels from getting dark fringes
+ const alphaMask = Math.min(1.0, (origA - 0.015) / 0.085);
+ const rim = Math.min(1.0, rawRim) * alphaMask;
+ const p = idx * 4;
+
+ const r0 = data[p] / 255.0;
+ const g0 = data[p + 1] / 255.0;
+ const b0 = data[p + 2] / 255.0;
+
+ const darkScale = Math.max(0.28, 1.0 - rim * vDarken);
+ const dr = r0 * darkScale;
+ const dg = g0 * darkScale;
+ const db = b0 * darkScale;
+
+ // Subtle chroma preservation as pigment concentrates along the drying rim
+ const lum = 0.299 * dr + 0.587 * dg + 0.114 * db;
+ const satBoost = 1.0 + Math.min(0.32, rim * vDarken * 0.42);
+ const outR = Math.max(0, Math.min(r0, lum + (dr - lum) * satBoost));
+ const outG = Math.max(0, Math.min(g0, lum + (dg - lum) * satBoost));
+ const outB = Math.max(0, Math.min(b0, lum + (db - lum) * satBoost));
+
+ data[p] = Math.round(outR * 255);
+ data[p + 1] = Math.round(outG * 255);
+ data[p + 2] = Math.round(outB * 255);
+ data[p + 3] = Math.round(Math.min(1.0, origA * (1.0 + rim * aBoost)) * 255);
+ }
}
}
}
@@ -1053,12 +1463,14 @@ export function centripetalCatmullRomToBezier(
p2: Point,
p3: Point
): { c1: Point; c2: Point } {
- const effP0 = p1.isCorner ? p1 : p0;
- const effP3 = p2.isCorner ? p2 : p3;
+ const rawD01 = Math.hypot(p1.x - p0.x, p1.y - p0.y);
+ const rawD23 = Math.hypot(p3.x - p2.x, p3.y - p2.y);
+ const effP0 = p1.isCorner || rawD01 < 1e-3 ? p1 : p0;
+ const effP3 = p2.isCorner || rawD23 < 1e-3 ? p2 : p3;
- const d01 = Math.hypot(p1.x - effP0.x, p1.y - effP0.y);
+ const d01 = p1.isCorner || rawD01 < 1e-3 ? 0 : rawD01;
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 d23 = p2.isCorner || rawD23 < 1e-3 ? 0 : rawD23;
const dt0 = Math.max(1e-4, Math.sqrt(d01));
const dt1 = Math.max(1e-4, Math.sqrt(d12));
@@ -1175,7 +1587,9 @@ export function getTintedMasterCanvas(
color: string,
w: number,
h: number,
- isColorTip: boolean = false
+ isColorTip: boolean = false,
+ isDualToneTip: boolean = false,
+ secondaryColor?: string
): HTMLCanvasElement {
if (isColorTip) {
const key = `color_${sourceKey}_${w}x${h}`;
@@ -1192,6 +1606,42 @@ export function getTintedMasterCanvas(
return canvas;
}
+ if (isDualToneTip) {
+ const primRgb = parseColorToRgb(color);
+ const secRgb = parseColorToRgb(secondaryColor || '#ffffff');
+ const primHex = rgbToHex(primRgb.r, primRgb.g, primRgb.b);
+ const secHex = rgbToHex(secRgb.r, secRgb.g, secRgb.b);
+ const key = `dualtone_${sourceKey}_${primHex}_${secHex}_${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);
+ if (typeof ctx.getImageData === 'function' && typeof ctx.putImageData === 'function') {
+ const img = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ const d = img.data;
+ const dr = secRgb.r - primRgb.r;
+ const dg = secRgb.g - primRgb.g;
+ const db = secRgb.b - primRgb.b;
+ for (let i = 0; i < d.length; i += 4) {
+ if (d[i + 3] === 0) continue;
+ const lum = (0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2]) / 255.0;
+ d[i] = Math.max(0, Math.min(255, Math.round(primRgb.r + dr * lum)));
+ d[i + 1] = Math.max(0, Math.min(255, Math.round(primRgb.g + dg * lum)));
+ d[i + 2] = Math.max(0, Math.min(255, Math.round(primRgb.b + db * lum)));
+ }
+ ctx.putImageData(img, 0, 0);
+ }
+
+ 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}`;
@@ -1216,11 +1666,22 @@ export function getTintedMasterCanvas(
export function getTintedTipMaster(
tipImage: HTMLImageElement,
color: string,
- isColorTip: boolean = false
+ isColorTip: boolean = false,
+ isDualToneTip: boolean = false,
+ secondaryColor?: string
): 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);
+ return getTintedMasterCanvas(
+ tipImage,
+ getUniqueSourceKey(tipImage, 'tip'),
+ color,
+ w,
+ h,
+ isColorTip,
+ isDualToneTip,
+ secondaryColor
+ );
}
export function getRadialDabMaster(
@@ -1314,6 +1775,146 @@ export function getRadialDabMaster(
return getTintedMasterCanvas(maskCanvas, `radial_${maskKey}`, isEraser ? '#000000' : color, size, size);
}
+let _compareScratchCanvas: HTMLCanvasElement | null = null;
+let _compareScratchCtx: CanvasRenderingContext2D | null = null;
+
+function drawCompareDensityStampCpu(
+ ctx: CanvasRenderingContext2D,
+ stampSource: CanvasImageSource,
+ x: number,
+ y: number,
+ renderW: number,
+ renderH: number,
+ angleRad: number,
+ effAlpha: number,
+ flipX: number,
+ flipY: number,
+ antiAlias: number
+): boolean {
+ if (
+ typeof document === 'undefined' ||
+ typeof ctx.getImageData !== 'function' ||
+ typeof ctx.putImageData !== 'function' ||
+ !ctx.canvas ||
+ ctx.canvas.width <= 0 ||
+ ctx.canvas.height <= 0
+ ) {
+ return false;
+ }
+
+ const m =
+ typeof ctx.getTransform === 'function'
+ ? ctx.getTransform()
+ : { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };
+
+ const halfW = renderW * 0.5;
+ const halfH = renderH * 0.5;
+ const cosA = Math.cos(angleRad);
+ const sinA = Math.sin(angleRad);
+ // Compute world-space axis-aligned bounding box of rotated stamp, then map through ctx transform
+ const extX = Math.abs(halfW * cosA) + Math.abs(halfH * sinA);
+ const extY = Math.abs(halfW * sinA) + Math.abs(halfH * cosA);
+ const corners: [number, number][] = [
+ [x - extX, y - extY],
+ [x + extX, y - extY],
+ [x - extX, y + extY],
+ [x + extX, y + extY],
+ ];
+ let dMinX = Infinity;
+ let dMinY = Infinity;
+ let dMaxX = -Infinity;
+ let dMaxY = -Infinity;
+ for (let i = 0; i < 4; i++) {
+ const wx = corners[i][0];
+ const wy = corners[i][1];
+ const dx = m.a * wx + m.c * wy + m.e;
+ const dy = m.b * wx + m.d * wy + m.f;
+ if (dx < dMinX) dMinX = dx;
+ if (dy < dMinY) dMinY = dy;
+ if (dx > dMaxX) dMaxX = dx;
+ if (dy > dMaxY) dMaxY = dy;
+ }
+
+ const bx = Math.max(0, Math.floor(dMinX) - 1);
+ const by = Math.max(0, Math.floor(dMinY) - 1);
+ const ex = Math.min(ctx.canvas.width, Math.ceil(dMaxX) + 1);
+ const ey = Math.min(ctx.canvas.height, Math.ceil(dMaxY) + 1);
+ const bw = ex - bx;
+ const bh = ey - by;
+ if (bw <= 0 || bh <= 0 || bw > 2048 || bh > 2048) return false;
+
+ if (!_compareScratchCanvas) {
+ _compareScratchCanvas = document.createElement('canvas');
+ _compareScratchCanvas.width = Math.max(64, bw);
+ _compareScratchCanvas.height = Math.max(64, bh);
+ _compareScratchCtx = _compareScratchCanvas.getContext('2d', { willReadFrequently: true });
+ } else if (_compareScratchCanvas.width < bw || _compareScratchCanvas.height < bh) {
+ _compareScratchCanvas.width = Math.max(_compareScratchCanvas.width, bw);
+ _compareScratchCanvas.height = Math.max(_compareScratchCanvas.height, bh);
+ _compareScratchCtx = _compareScratchCanvas.getContext('2d', { willReadFrequently: true });
+ }
+ const sCtx = _compareScratchCtx;
+ if (!sCtx || typeof sCtx.getImageData !== 'function') return false;
+
+ sCtx.save();
+ if (typeof sCtx.setTransform === 'function') {
+ sCtx.setTransform(1, 0, 0, 1, 0, 0);
+ }
+ sCtx.clearRect(0, 0, bw, bh);
+ if (typeof sCtx.setTransform === 'function') {
+ sCtx.setTransform(m.a, m.b, m.c, m.d, m.e - bx, m.f - by);
+ } else {
+ sCtx.translate(m.e - bx, m.f - by);
+ }
+ if (antiAlias === 0) sCtx.imageSmoothingEnabled = false;
+ sCtx.globalCompositeOperation = 'source-over';
+ sCtx.globalAlpha = effAlpha;
+ sCtx.translate(x, y);
+ if (Math.abs(angleRad) >= 0.001) sCtx.rotate(angleRad);
+ if ((flipX < 0 || flipY < 0) && typeof sCtx.scale === 'function') {
+ sCtx.scale(flipX < 0 ? -1 : 1, flipY < 0 ? -1 : 1);
+ }
+ sCtx.drawImage(stampSource, -halfW, -halfH, renderW, renderH);
+ sCtx.restore();
+
+ const srcData = sCtx.getImageData(0, 0, bw, bh).data;
+ let hasSrc = false;
+ for (let i = 3; i < srcData.length; i += 4) {
+ if (srcData[i] !== 0) {
+ hasSrc = true;
+ break;
+ }
+ }
+ if (!hasSrc) return false;
+
+ const dstImg = ctx.getImageData(bx, by, bw, bh);
+ const dstData = dstImg.data;
+
+ // CSP Compare Density: alpha = max(dstAlpha, srcAlpha); never accumulates translucent self-overlap
+ for (let i = 0; i < dstData.length; i += 4) {
+ const sa = srcData[i + 3];
+ if (sa === 0) continue;
+ const da = dstData[i + 3];
+ if (sa > da) {
+ if (da === 0) {
+ dstData[i] = srcData[i];
+ dstData[i + 1] = srcData[i + 1];
+ dstData[i + 2] = srcData[i + 2];
+ dstData[i + 3] = sa;
+ } else {
+ const blendT = (sa - da) / sa;
+ dstData[i] = Math.round(dstData[i] + (srcData[i] - dstData[i]) * blendT);
+ dstData[i + 1] = Math.round(dstData[i + 1] + (srcData[i + 1] - dstData[i + 1]) * blendT);
+ dstData[i + 2] = Math.round(dstData[i + 2] + (srcData[i + 2] - dstData[i + 2]) * blendT);
+ dstData[i + 3] = sa;
+ }
+ }
+ }
+
+ ctx.putImageData(dstImg, bx, by);
+ return true;
+}
+
export function drawSingleStamp(
ctx: CanvasRenderingContext2D,
stampSource: CanvasImageSource,
@@ -1330,7 +1931,7 @@ export function drawSingleStamp(
flipX: number = 1,
flipY: number = 1,
antiAlias: number = 2,
- _blendTipsMode?: CspBlendTipsMode
+ blendTipsMode?: CspBlendTipsMode
): void {
if (width < 0.08 || height < 0.08 || alpha <= 0.002) return;
@@ -1341,6 +1942,33 @@ export function drawSingleStamp(
const effAlpha = antiAlias === 0 ? (sub.effAlpha >= 0.45 ? 1.0 : 0) : sub.effAlpha;
if (effAlpha <= 0.002) return;
+ // CSP "Compare density" (blendTipsMode === 'compare'): max(dstAlpha, srcAlpha) inside stroke buffer
+ if (
+ blendTipsMode === 'compare' &&
+ !isEraser &&
+ !isBgEraser &&
+ !isTransparentInk &&
+ !alphaLocked
+ ) {
+ if (
+ drawCompareDensityStampCpu(
+ ctx,
+ stampSource,
+ x,
+ y,
+ renderW,
+ renderH,
+ angleRad,
+ effAlpha,
+ flipX,
+ flipY,
+ antiAlias
+ )
+ ) {
+ return;
+ }
+ }
+
const targetOp: GlobalCompositeOperation = isBgEraser
? 'source-over'
: isTransparentInk || isEraser
@@ -1381,7 +2009,7 @@ export function drawSingleStamp(
function selectTipIndex(
tipImages: HTMLImageElement[] | undefined,
- order: 'random' | 'sequential' | 'direction' | 'reverse' = 'sequential',
+ order: CspSubTipOrder = 'sequential',
dabIndex: number = 0,
tangentAngle: number = 0,
x: number = 0,
@@ -1390,6 +2018,15 @@ function selectTipIndex(
if (!tipImages || tipImages.length <= 1) return 0;
const count = tipImages.length;
if (order === 'random') return Math.floor(dabHashFloat(x, y, dabIndex, 97) * count) % count;
+ if (order === 'random-no-repeat') {
+ const cur = Math.floor(dabHashFloat(x, y, dabIndex, 97) * count) % count;
+ if (dabIndex > 0) {
+ const prev = Math.floor(dabHashFloat(x, y, dabIndex - 1, 97) * count) % count;
+ if (cur === prev) return (cur + 1) % count;
+ }
+ return cur;
+ }
+ if (order === 'once') return Math.min(dabIndex, count - 1);
if (order === 'reverse') return (count - 1 - (dabIndex % count)) % count;
if (order === 'direction') {
const normAngle = ((tangentAngle % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI);
@@ -1401,7 +2038,7 @@ function selectTipIndex(
function selectTipImage(
tipImages: HTMLImageElement[] | undefined,
fallbackTip: HTMLImageElement,
- order: 'random' | 'sequential' | 'direction' | 'reverse' = 'sequential',
+ order: CspSubTipOrder = 'sequential',
dabIndex: number = 0,
tangentAngle: number = 0,
x: number = 0,
@@ -1414,128 +2051,220 @@ function selectTipImage(
return tipImages[idx] ?? fallbackTip;
}
-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 aNorm = d[i + 3] / 255;
- const rgbLum = 0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2];
- // CSP paper textures are black-on-transparent RGBA (RGB=0, A=density); composite over white
- const effLum = rgbLum * aNorm + 255 * (1 - aNorm);
- d[i] = 255;
- d[i + 1] = 255;
- d[i + 2] = 255;
- d[i + 3] = 255 - Math.round(effLum);
- }
- 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;
+interface CpuPaperGrainOptions {
+ paperTextureMode?: CspPaperTextureMode;
+ paperTextureScale?: number;
+ paperTextureRotate?: number;
+ paperTextureBrightness?: number;
+ paperTextureContrast?: number;
+ paperTextureInverted?: boolean;
+ paperTextureEmphasizeDensity?: boolean;
+ preservePaperDensity?: boolean;
+ paperTextureImage?: HTMLImageElement;
+ surfaceTextureId?: SurfaceTextureId;
+ grainMappingMode?: GrainMappingMode;
+ strokeDist?: number;
+ grainRandomOffsetX?: number;
+ grainRandomOffsetY?: number;
+ grainRandomRot?: number;
}
+/**
+ * Exact per-pixel CPU paper grain modulation matching `WebGlBrushEngine.ts` fragment shader
+ * across all 9 CSP `TextureCompositeMode` modes, rotation, scale, brightness, contrast,
+ * invert, emphasizeDensity, preserveDensity, surfaceTextureId, and dab rotation/flip.
+ * Bakes `dabAlpha` before applying non-linear paper modes for <= 3/255 WebGL parity.
+ */
function applyCpuPerPixelPaperGrain(
master: CanvasImageSource,
worldX: number,
worldY: number,
renderW: number,
renderH: number,
+ angleRad: number,
+ flipX: number,
+ flipY: number,
+ dabAlpha: number,
grainAmount: number,
pressure: number,
- paperScale: number = 1.0,
- paperTextureImage?: HTMLImageElement
+ paperOpts: CpuPaperGrainOptions
): HTMLCanvasElement | null {
- if (typeof document === 'undefined' || grainAmount <= 0.005) return null;
+ if (typeof document === 'undefined' || grainAmount <= 0.001 || dabAlpha <= 0.002) return null;
+
+ const bufW = Math.max(2, Math.min(256, Math.ceil(renderW)));
+ const bufH = Math.max(2, Math.min(256, Math.ceil(renderH)));
+
if (!_grainScratchCanvas) {
_grainScratchCanvas = document.createElement('canvas');
- _grainScratchCanvas.width = 128;
- _grainScratchCanvas.height = 128;
- _grainScratchCtx = _grainScratchCanvas.getContext('2d');
+ _grainScratchCanvas.width = bufW;
+ _grainScratchCanvas.height = bufH;
+ _grainScratchCtx = _grainScratchCanvas.getContext('2d', { willReadFrequently: true });
+ } else if (_grainScratchCanvas.width !== bufW || _grainScratchCanvas.height !== bufH) {
+ _grainScratchCanvas.width = bufW;
+ _grainScratchCanvas.height = bufH;
+ _grainScratchCtx = _grainScratchCanvas.getContext('2d', { willReadFrequently: true });
}
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;
+ if (!sCtx || typeof sCtx.getImageData !== 'function' || typeof sCtx.putImageData !== 'function') {
+ 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.clearRect(0, 0, bufW, bufH);
+ if (flipX < 0 || flipY < 0) {
+ sCtx.translate(flipX < 0 ? bufW : 0, flipY < 0 ? bufH : 0);
+ sCtx.scale(flipX < 0 ? -1 : 1, flipY < 0 ? -1 : 1);
+ }
+ sCtx.drawImage(master, 0, 0, bufW, bufH);
sCtx.restore();
+ const imgData = sCtx.getImageData(0, 0, bufW, bufH);
+ const data = imgData.data;
+
+ // Verify the canvas backing store actually rasterized pixels (protects mock Canvas2D unit tests)
+ let hasAnyNonZero = false;
+ for (let i = 3; i < data.length; i += 4) {
+ if (data[i] !== 0) {
+ hasAnyNonZero = true;
+ break;
+ }
+ }
+ if (!hasAnyNonZero) return null;
+
+ const customPaper = paperOpts.paperTextureImage
+ ? getCustomPaperLuminance(paperOpts.paperTextureImage)
+ : null;
+ const surfacePaper =
+ !customPaper && paperOpts.surfaceTextureId
+ ? getSurfaceTextureHeightField(paperOpts.surfaceTextureId)
+ : null;
+ const paperData = customPaper ? customPaper.lum : surfacePaper ?? paperGrainTable;
+ const paperW = customPaper ? customPaper.width : surfacePaper ? SURFACE_TEXTURE_SIZE : GRAIN_SIZE;
+ const paperH = customPaper ? customPaper.height : surfacePaper ? SURFACE_TEXTURE_SIZE : GRAIN_SIZE;
+ if (paperW <= 0 || paperH <= 0) return null;
+
+ const paperPow2 = (paperW & (paperW - 1)) === 0 && (paperH & (paperH - 1)) === 0;
+ const paperMaskW = paperW - 1;
+ const paperMaskH = paperH - 1;
+
+ const invScale = 1.0 / Math.max(0.05, paperOpts.paperTextureScale ?? 1.0);
+ const rotRad = ((paperOpts.paperTextureRotate ?? 0) * Math.PI) / 180;
+ const hasRot = Math.abs(rotRad) > 1e-4;
+ const cosR = hasRot ? Math.cos(rotRad) : 1;
+ const sinR = hasRot ? Math.sin(rotRad) : 0;
+
+ const mode = paperOpts.paperTextureMode ?? 'subtract';
+ const bright = paperOpts.paperTextureBrightness ?? 0;
+ const contrast = paperOpts.paperTextureContrast ?? 0;
+ const inv = Boolean(paperOpts.paperTextureInverted);
+ const emphasize = Boolean(paperOpts.paperTextureEmphasizeDensity);
+ const preserveDensity = Boolean(paperOpts.preservePaperDensity);
+
+ const gmMode = paperOpts.grainMappingMode ?? 'canvas-locked';
+ const strokeDist = paperOpts.strokeDist ?? 0;
+ const randOffX = paperOpts.grainRandomOffsetX ?? 0;
+ const randOffY = paperOpts.grainRandomOffsetY ?? 0;
+ const randRot = paperOpts.grainRandomRot ?? 0;
+ const randCos = gmMode === 'random-per-stroke' ? Math.cos(randRot) : 1;
+ const randSin = gmMode === 'random-per-stroke' ? Math.sin(randRot) : 0;
+
+ const cosA = Math.cos(angleRad);
+ const sinA = Math.sin(angleRad);
+ const maxDim = Math.max(renderW, renderH);
+ const invBufW = 1 / bufW;
+ const invBufH = 1 / bufH;
+ const inv255 = 1 / 255;
+
+ for (let py = 0; py < bufH; py++) {
+ const vNorm = (py + 0.5) * invBufH - 0.5; // [-0.5, 0.5]
+ const localY = vNorm * renderH;
+ const rowOff = py * bufW;
+
+ for (let px = 0; px < bufW; px++) {
+ const pOff = (rowOff + px) << 2;
+ const aByte = data[pOff + 3];
+ if (aByte === 0) continue;
+
+ const uNorm = (px + 0.5) * invBufW - 0.5; // [-0.5, 0.5]
+ const localX = uNorm * renderW;
+
+ let baseX: number;
+ let baseY: number;
+ if (gmMode === 'brush-aligned') {
+ baseX = uNorm * maxDim;
+ baseY = vNorm * maxDim;
+ } else if (gmMode === 'stroke-flow') {
+ baseX = strokeDist + localX;
+ baseY = localY;
+ } else {
+ const wx = worldX + localX * cosA - localY * sinA;
+ const wy = worldY + localX * sinA + localY * cosA;
+ if (gmMode === 'random-per-stroke') {
+ baseX = wx * randCos - wy * randSin + randOffX;
+ baseY = wx * randSin + wy * randCos + randOffY;
+ } else {
+ baseX = wx;
+ baseY = wy;
+ }
+ }
+
+ let rotX = baseX;
+ let rotY = baseY;
+ if (hasRot) {
+ rotX = baseX * cosR - baseY * sinR;
+ rotY = baseX * sinR + baseY * cosR;
+ }
+ const psx = rotX * invScale - 0.5;
+ const psy = rotY * invScale - 0.5;
+
+ const pfx = Math.floor(psx);
+ const pfy = Math.floor(psy);
+ const ptx = psx - pfx;
+ const pty = psy - pfy;
+ let px0: number, py0: number, px1: number, py1: number;
+ if (paperPow2) {
+ px0 = pfx & paperMaskW;
+ py0 = pfy & paperMaskH;
+ px1 = (px0 + 1) & paperMaskW;
+ py1 = (py0 + 1) & paperMaskH;
+ } else {
+ px0 = ((pfx % paperW) + paperW) % paperW;
+ py0 = ((pfy % paperH) + paperH) % paperH;
+ px1 = px0 + 1 < paperW ? px0 + 1 : 0;
+ py1 = py0 + 1 < paperH ? py0 + 1 : 0;
+ }
+
+ const pr0 = py0 * paperW;
+ const pr1 = py1 * paperW;
+ const pvTop = paperData[pr0 + px0] + (paperData[pr0 + px1] - paperData[pr0 + px0]) * ptx;
+ const pvBot = paperData[pr1 + px0] + (paperData[pr1 + px1] - paperData[pr1 + px0]) * ptx;
+ const gNorm = (pvTop + (pvBot - pvTop) * pty) * inv255;
+
+ // Modulate brush tip profile (0..1) BEFORE scaling by per-dab flow (matching CSP TextureForPlot=1 & SpatialTipMixer)
+ const tipAlpha = Math.max(0, Math.min(1, aByte * inv255));
+ const modTipAlpha = applyCspPaperTextureAlpha(
+ tipAlpha,
+ gNorm,
+ grainAmount,
+ pressure,
+ mode,
+ bright,
+ contrast,
+ inv,
+ preserveDensity,
+ emphasize
+ );
+ const modAlpha = Math.max(0, Math.min(1, modTipAlpha * dabAlpha));
+ data[pOff + 3] = modTipAlpha <= 0.002 ? 0 : Math.max(0, Math.min(255, Math.round(modAlpha * 255)));
+ }
+ }
+
+ sCtx.putImageData(imgData, 0, 0);
return _grainScratchCanvas;
}
@@ -1548,7 +2277,8 @@ export function canUseWebGlForBrush(options?: BrushRenderOptions): boolean {
if (perf.renderBackend === 'canvas2d' || !perf.gpuBrushAcceleration) {
return false;
}
- if (!options) return WebGlBrushEngine.getInstance().isAvailable();
+ const gpu = WebGlBrushEngine.getInstance();
+ if (!options) return gpu.isAvailable();
if (options.useGpu === false) return false;
if (options.colorMixing) return false;
if ((options.antiAlias ?? 2) === 0) return false;
@@ -1560,28 +2290,36 @@ export function canUseWebGlForBrush(options?: BrushRenderOptions): boolean {
) {
return false;
}
- return WebGlBrushEngine.getInstance().isAvailable();
+ if (options.blendTipsMode === 'compare') {
+ const isMultiColor = Boolean(
+ options.isColorTip ||
+ options.isDualToneTip ||
+ options.subTips?.[0]?.isColor ||
+ options.subTips?.[0]?.isDualToneTip ||
+ options.dynamics?.colorJitterEnabled
+ );
+ if (isMultiColor || !gpu.supportsBlendMax()) {
+ return false;
+ }
+ }
+ return gpu.isAvailable();
}
-export function flushGpuDabs(
- ctx: CanvasRenderingContext2D,
- dabs: GpuDab[],
+function buildGpuBrushSettingsFromOptions(
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);
+): BrushSettings & { alphaLocked?: boolean; isBgEraser?: boolean } {
const isBgEraser = Boolean(options.isBgEraser);
- const tool: ToolType = isEraser || isBgEraser ? 'eraser' : 'brush';
- const settings: BrushSettings & { alphaLocked?: boolean; isBgEraser?: boolean } = {
+ const grainVal = options.skipPerDabPaperGrain ? 0 : (options.grain ?? options.textureDensity ?? 0);
+ return {
size: options.size ?? 10,
minSizeFactor: options.minSizeFactor ?? 0,
color,
+ secondaryColor: options.secondaryColor,
opacity: options.opacity ?? 1.0,
flow: options.flow ?? 1.0,
+ blendTipsMode: options.blendTipsMode,
+ brushCombineMode: options.brushCombineMode,
spacing: options.spacing ?? 0.08,
usePressure: options.usePressure !== false,
smoothing: false,
@@ -1589,33 +2327,49 @@ export function flushGpuDabs(
hardness: options.hardness ?? 1.0,
antiAlias: options.antiAlias ?? 2,
wetEdge: options.wetEdge ?? 0,
- grain: options.grain ?? options.textureDensity ?? 0,
- textureDensity: options.textureDensity,
+ grain: grainVal,
+ textureDensity: options.skipPerDabPaperGrain ? 0 : options.textureDensity,
+ opacitySensor: options.opacitySensor,
+ textureDensitySensor: options.textureDensitySensor,
+ grainPenetrationSensor: options.grainPenetrationSensor,
surfaceTextureId: options.surfaceTextureId,
grainMappingMode: options.grainMappingMode,
paperTextureMode: options.paperTextureMode,
paperTextureBrightness: options.paperTextureBrightness,
paperTextureContrast: options.paperTextureContrast,
+ paperTextureApplyEachPlot: options.paperTextureApplyEachPlot,
+ paperTextureEmphasizeDensity: options.paperTextureEmphasizeDensity,
paperTextureInverted: options.paperTextureInverted,
paperTextureImage: options.paperTextureImage,
paperTextureScale: options.paperTextureScale,
paperTextureRotate: options.paperTextureRotate,
customTipImage: options.tipImage,
isColorTip: options.isColorTip,
+ isDualToneTip: options.isDualToneTip,
subTips: options.subTips,
subTipImages: options.subTipImages,
- dualBrush: options.dualBrush,
- dualTipImage: options.dualTipImage,
- dualBrushCompositeMode: options.dualBrushCompositeMode as BrushSettings['dualBrushCompositeMode'],
- dualScale: options.dualScale,
- dualAngle: options.dualAngle,
- dualScatter: options.dualScatter,
naturalPaint: options.naturalPaint,
colorMixing: false,
isTransparentInk: Boolean(options.isTransparentInk),
alphaLocked: Boolean(options.alphaLocked),
isBgEraser,
};
+}
+
+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 = buildGpuBrushSettingsFromOptions(color, options);
const docW = options.underlyingCanvas?.width || ctx.canvas?.width || 1024;
const docH = options.underlyingCanvas?.height || ctx.canvas?.height || 1024;
@@ -1631,7 +2385,7 @@ const _customGrainLumCache = new WeakMap<
{ width: number; height: number; lum: Uint8Array }
>();
-function getCustomPaperLuminance(
+export function getCustomPaperLuminance(
img: HTMLImageElement
): { width: number; height: number; lum: Uint8Array } | null {
const cached = _customGrainLumCache.get(img);
@@ -1661,54 +2415,13 @@ function getCustomPaperLuminance(
return entry;
}
-function sampleWorldPaperGrainNorm(
- wx: number,
- wy: number,
- scale: number,
- rotateDeg: number,
- customPaper?: { width: number; height: number; lum: Uint8Array } | null
-): number {
- const invScale = 1.0 / Math.max(0.05, scale);
- let sx = wx * invScale;
- let sy = wy * invScale;
- if (rotateDeg !== 0) {
- const rad = (-rotateDeg * Math.PI) / 180;
- const c = Math.cos(rad);
- const s = Math.sin(rad);
- const rx = sx * c - sy * s;
- const ry = sx * s + sy * c;
- sx = rx;
- sy = ry;
- }
- if (customPaper) {
- const cw = customPaper.width;
- const ch = customPaper.height;
- const fx = Math.floor(sx);
- const fy = Math.floor(sy);
- const tx = sx - fx;
- const ty = sy - fy;
- const x0 = ((fx % cw) + cw) % cw;
- const y0 = ((fy % ch) + ch) % ch;
- const x1 = (x0 + 1) % cw;
- const y1 = (y0 + 1) % ch;
- const v00 = customPaper.lum[y0 * cw + x0];
- const v10 = customPaper.lum[y0 * cw + x1];
- const v01 = customPaper.lum[y1 * cw + x0];
- const v11 = customPaper.lum[y1 * cw + x1];
- const top = v00 + (v10 - v00) * tx;
- const bot = v01 + (v11 - v01) * tx;
- return (top + (bot - top) * ty) / 255.0;
- }
- return getPaperGrain(sx, sy) / 255.0;
-}
-
-function evaluateCspTaperFactors(
+export function evaluateCspTaperFactors(
taper: CspTaperSettings | undefined,
strokeDist: number,
totalLength: number | undefined,
exitSpeed?: number
): { sizeScale: number; alphaScale: number; amountScale: number; paintDensityScale: number } {
- if (!taper || (!taper.useIn && !taper.useOut)) {
+ if (!taper || taper.inOutType === 0 || (!taper.useIn && !taper.useOut)) {
return { sizeScale: 1.0, alphaScale: 1.0, amountScale: 1.0, paintDensityScale: 1.0 };
}
@@ -1830,10 +2543,12 @@ function resolveCpuMaster(
isBgEraser: boolean,
isColorTip: boolean,
targetWidth: number,
- aaMode: number
+ aaMode: number,
+ isDualToneTip: boolean = false,
+ secondaryColor?: string
): HTMLCanvasElement {
if (activeTip) {
- return getTintedTipMaster(activeTip, color, isColorTip);
+ return getTintedTipMaster(activeTip, color, isColorTip, isDualToneTip, secondaryColor);
}
return getRadialDabMaster(hardness, color, isEraser && !isBgEraser, targetWidth, aaMode);
}
@@ -1849,12 +2564,20 @@ function sampleAndMixColor(
options: BrushRenderOptions,
spacingRatio: number = 0.08,
dirX: number = 0,
- dirY: number = 0
+ dirY: number = 0,
+ amountOverride?: number,
+ densityOverride?: number,
+ stretchOverride?: number
): { colorHex: string; alpha: number; r: number; g: number; b: number } {
const reservoir = options.reservoir!;
+ const effPigmentStrength =
+ options.perceptualMixing !== false
+ ? Math.max(0, Math.min(1, options.pigmentMixingStrength ?? 1.0))
+ : 0;
+ const usePigmentSample = effPigmentStrength > 0.005;
let sampled = { r: 255, g: 255, b: 255, a: 0 };
if (options.sampler) {
- sampled = options.sampler.sampleColor(x, y, radius);
+ sampled = options.sampler.sampleColor(x, y, radius, usePigmentSample);
} else {
const sampleCanvas = options.underlyingCanvas || ctx.canvas;
const sampleCtx = sampleCanvas ? sampleCanvas.getContext('2d') : null;
@@ -1864,14 +2587,16 @@ function sampleAndMixColor(
}
const pressureAlreadyApplied = Boolean(
- options.opacitySensor?.usePressure || options.densitySensor?.usePressure
+ options.opacitySensor?.usePressure ||
+ options.densitySensor?.usePressure ||
+ options.densityOfPaintSensor?.usePressure
);
const mixed = reservoir.mixWithCanvas(
sampled,
- options.amountOfPaint ?? 0.65,
- options.densityOfPaint ?? 0.9,
- options.colorStretch ?? 0.75,
+ amountOverride !== undefined ? amountOverride : options.amountOfPaint ?? 0.65,
+ densityOverride !== undefined ? densityOverride : options.densityOfPaint ?? 0.9,
+ stretchOverride !== undefined ? stretchOverride : options.colorStretch ?? 0.75,
options.mixingMode ?? 'blend',
pressure,
flow,
@@ -1896,7 +2621,16 @@ function sampleAndMixColor(
const trailOffset = radius + depRad + 0.5;
const depX = x - dirX * trailOffset;
const depY = y - dirY * trailOffset;
- options.sampler.depositDab(depX, depY, depRad, mixed.r, mixed.g, mixed.b, effectiveAlpha * 0.45);
+ options.sampler.depositDab(
+ depX,
+ depY,
+ depRad,
+ mixed.r,
+ mixed.g,
+ mixed.b,
+ effectiveAlpha * 0.45,
+ effPigmentStrength
+ );
}
return { ...mixed, alpha: effectiveAlpha };
}
@@ -1918,20 +2652,25 @@ export function drawBrushDot(
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;
+ const { readTiltInput, useSyntheticTiltShading } = resolveTiltBehavior(options);
+ const grainAmount = options.skipPerDabPaperGrain ? 0 : (options.grain ?? options.textureDensity ?? 0);
+ const preservePaperDensity =
+ Boolean(options.textureDensitySensor) ||
+ (options.paperTextureApplyEachPlot !== undefined && !options.grainPenetrationSensor?.usePressure);
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;
+ const effPressure = Math.max(0, Math.min(1, point.pressure ?? 1.0));
+ const curvedPressure = options.pressureCurve ? evaluateFastSpline(effPressure, options.pressureCurve) : effPressure;
+ const minFactor = Math.max(0, Math.min(1.0, 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));
+ : options.usePressure !== false
+ ? Math.max(0.5, (options.size ?? 10) * (minFactor + (1.0 - minFactor) * curvedPressure))
+ : Math.max(0.5, options.size ?? 10);
let startAmountScale = 1.0;
let startPaintDensityScale = 1.0;
@@ -1943,13 +2682,25 @@ export function drawBrushDot(
startPaintDensityScale = startTaper.paintDensityScale;
}
- 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 tiltX = readTiltInput ? point.tiltX ?? 0 : 0;
+ const tiltY = readTiltInput ? point.tiltY ?? 0 : 0;
+ const tiltMagnitude = computeCspTiltMagnitude(tiltX, tiltY);
const tiltSpread = tiltMagnitude * (options.tiltScale ?? 1.0);
const grainPressure =
- useTilt && tiltMagnitude > 0.01 ? effPressure * (1.0 - tiltMagnitude * 0.55) : effPressure;
+ useSyntheticTiltShading && tiltMagnitude > 0.01 ? effPressure * (1.0 - tiltMagnitude * 0.55) : effPressure;
+ let effGrainAmount = grainAmount;
+ if (grainAmount > 0.005 && options.textureDensitySensor) {
+ const tdFactor = evaluateCspSensor(
+ options.textureDensitySensor,
+ effPressure,
+ tiltMagnitude,
+ 0,
+ dabHashFloat(point.x, point.y, 0, 58),
+ point.twist ?? 0,
+ 0
+ );
+ effGrainAmount = Math.max(0, Math.min(1, grainAmount * tdFactor));
+ }
if (options.sizeSensor) {
// Avoid double-applying pressure when point.width already has pressure baked from calculateStrokeWidth
@@ -1962,13 +2713,53 @@ export function drawBrushDot(
effWidth * evaluateCspSensor(effectiveSizeSensor, 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));
+ const isColorMixing = Boolean(options.colorMixing) && !isEraser && !isBgEraser;
+ const hasConcurrentDensityAndPaintDensityPressure = Boolean(
+ isColorMixing && options.densitySensor?.usePressure && options.densityOfPaintSensor?.usePressure
+ );
+
+ let effDensityOfPaint = (options.densityOfPaint ?? 0.9) * startPaintDensityScale;
+ let paintDensitySensorFactor = 1.0;
+ if (options.densityOfPaintSensor) {
+ paintDensitySensorFactor = evaluateCspSensor(
+ options.densityOfPaintSensor,
+ effPressure,
+ tiltMagnitude,
+ 0,
+ dabHashFloat(point.x, point.y, 0, 56),
+ point.twist ?? 0,
+ 0
+ );
+ if (!hasConcurrentDensityAndPaintDensityPressure) {
+ effDensityOfPaint *= paintDensitySensorFactor;
+ } else if (paintDensitySensorFactor <= 0.002) {
+ effDensityOfPaint = 0;
+ }
}
- if (options.densitySensor) {
- effectiveFlow *= evaluateCspSensor(options.densitySensor, effPressure, tiltMagnitude, 0, dabHashFloat(point.x, point.y, 0, 52));
+
+ let flowSensorFactor = 1.0;
+ if (hasConcurrentDensityAndPaintDensityPressure) {
+ // In CSP Color Mixing (Blend), BrushFlowEffector drives per-plot brush density while
+ // BrushMixAlphaEffector shapes paint-covering translucency without bottlenecking BrushFlow.
+ const dnF = evaluateCspSensor(options.densitySensor, effPressure, tiltMagnitude, 0, dabHashFloat(point.x, point.y, 0, 52));
+ flowSensorFactor = dnF;
+ if (options.opacitySensor) {
+ flowSensorFactor *= evaluateCspSensor(options.opacitySensor, effPressure, tiltMagnitude, 0, dabHashFloat(point.x, point.y, 0, 51));
+ }
+ } else if (options.opacitySensor && options.densitySensor && (isColorMixing || options.paperTextureApplyEachPlot === false)) {
+ const opF = evaluateCspSensor(options.opacitySensor, effPressure, tiltMagnitude, 0, dabHashFloat(point.x, point.y, 0, 51));
+ const dnF = evaluateCspSensor(options.densitySensor, effPressure, tiltMagnitude, 0, dabHashFloat(point.x, point.y, 0, 52));
+ flowSensorFactor = Math.min(opF, dnF);
+ } else {
+ if (options.opacitySensor) {
+ flowSensorFactor *= evaluateCspSensor(options.opacitySensor, effPressure, tiltMagnitude, 0, dabHashFloat(point.x, point.y, 0, 51));
+ }
+ if (options.densitySensor) {
+ flowSensorFactor *= evaluateCspSensor(options.densitySensor, effPressure, tiltMagnitude, 0, dabHashFloat(point.x, point.y, 0, 52));
+ }
}
- if (useTilt && tiltMagnitude > 0.03 && (options.tipImage || grainAmount > 0.005)) {
+ effectiveFlow = Math.max(0, Math.min(1, effectiveFlow * flowSensorFactor));
+ if (useSyntheticTiltShading && tiltMagnitude > 0.03 && (options.tipImage || grainAmount > 0.005)) {
effectiveFlow *= 1.0 - tiltMagnitude * 0.28;
}
@@ -1977,27 +2768,91 @@ export function drawBrushDot(
? 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;
+ const isDualToneTip = !isColorTip && Boolean(options.isDualToneTip || (options.subTips && options.subTips[0]?.isDualToneTip));
+ const tipNaturalW = activeTip ? (activeTip.naturalWidth || activeTip.width || 1) : 1;
+ const tipNaturalH = activeTip ? (activeTip.naturalHeight || activeTip.height || 1) : 1;
+
+ let effThickness = thickness;
+ if (options.thicknessSensor) {
+ // CSP Brush Thickness minimum is 10% (0.10); never collapse below 0.10 unless base thickness itself is thinner.
+ const minThicknessFloor = Math.min(thickness, 0.1);
+ effThickness = Math.max(
+ minThicknessFloor,
+ thickness *
+ evaluateCspSensor(
+ options.thicknessSensor,
+ effPressure,
+ tiltMagnitude,
+ 0,
+ dabHashFloat(point.x, point.y, 0, 54),
+ point.twist ?? 0,
+ 0
+ )
+ );
+ }
+
+ let effAmountOfPaint = (options.amountOfPaint ?? 0.65) * startAmountScale;
+ if (options.amountOfPaintSensor) {
+ effAmountOfPaint *= evaluateCspSensor(
+ options.amountOfPaintSensor,
+ effPressure,
+ tiltMagnitude,
+ 0,
+ dabHashFloat(point.x, point.y, 0, 55),
+ point.twist ?? 0,
+ 0
+ );
+ }
+ let effColorStretch = options.colorStretch ?? 0.75;
+ if (options.colorStretchSensor) {
+ effColorStretch *= evaluateCspSensor(
+ options.colorStretchSensor,
+ effPressure,
+ tiltMagnitude,
+ 0,
+ dabHashFloat(point.x, point.y, 0, 57),
+ point.twist ?? 0,
+ 0
+ );
+ }
let angleRad =
options.initialAngleRad !== undefined
? options.initialAngleRad
: ((options.angle ?? 0) * Math.PI) / 180;
- if (useTilt && tiltMagnitude > 0.05) {
+ if (options.angleDynamics === 'tilt' && tiltMagnitude > 0.05) {
+ angleRad = Math.atan2(tiltX, -tiltY) + ((options.angle ?? 0) * Math.PI) / 180;
+ } else if (useSyntheticTiltShading && tiltMagnitude > 0.05) {
angleRad = Math.atan2(tiltY, tiltX) + ((options.angle ?? 0) * Math.PI) / 180;
}
- if (point.twist && (options.angleDynamics === 'twist' || useTilt)) {
+ if (point.twist && (options.angleDynamics === 'twist' || useSyntheticTiltShading)) {
angleRad += (point.twist * Math.PI) / 180;
}
- const isColorMixing = Boolean(options.colorMixing) && !isEraser && !isBgEraser;
+ const dynamics = options.dynamics;
+ const colorJitterEnabled = Boolean(dynamics?.colorJitterEnabled);
+ const colorJitterPerStroke = Boolean(colorJitterEnabled && dynamics?.colorJitterPerStroke);
+ if (colorJitterPerStroke && dynamics) {
+ if (!options.strokeJitterColor) {
+ const prim0 = parseColorToRgb(effectiveColor);
+ const sec0 = parseColorToRgb(options.secondaryColor || '#ffffff');
+ let salt = 200;
+ const strokeIdx = options.strokeIndex ?? 0;
+ options.strokeJitterColor = applyColorDynamics(
+ { r: prim0.r / 255, g: prim0.g / 255, b: prim0.b / 255 },
+ { r: sec0.r / 255, g: sec0.g / 255, b: sec0.b / 255 },
+ dynamics,
+ () => dabHashFloat(point.x, point.y, strokeIdx, salt++)
+ );
+ }
+ effectiveColor = options.strokeJitterColor.hex;
+ }
+ const perDabColorJitter = colorJitterEnabled && !colorJitterPerStroke;
+
const useSpatialTipMixing =
isColorMixing &&
!gpuDabs &&
!isColorTip &&
- !options.dynamics?.colorJitterEnabled &&
!options.spray?.enabled;
if (useSpatialTipMixing) {
@@ -2005,17 +2860,35 @@ export function drawBrushDot(
if (!options.reservoir.spatialMixer) {
options.reservoir.spatialMixer = new SpatialTipMixer(effectiveColor);
}
+ let freshColorOverride: { r: number; g: number; b: number } | undefined;
+ if (perDabColorJitter && dynamics) {
+ const prim0 = parseColorToRgb(effectiveColor);
+ const sec0 = parseColorToRgb(options.secondaryColor || '#ffffff');
+ let salt = 20;
+ const cd = applyColorDynamics(
+ { r: prim0.r / 255, g: prim0.g / 255, b: prim0.b / 255 },
+ { r: sec0.r / 255, g: sec0.g / 255, b: sec0.b / 255 },
+ dynamics,
+ () => dabHashFloat(point.x, point.y, 0, salt++)
+ );
+ freshColorOverride = { r: cd.r * 255, g: cd.g * 255, b: cd.b * 255 };
+ }
const pressureAlreadyApplied = Boolean(
- options.opacitySensor?.usePressure || options.densitySensor?.usePressure
+ options.opacitySensor?.usePressure ||
+ options.densitySensor?.usePressure ||
+ options.densityOfPaintSensor?.usePressure
);
- let finalW = isVert ? effWidth * thickness : effWidth;
- let finalH = isVert ? effWidth * aspect : effWidth * aspect * thickness;
- if (useTilt && tiltMagnitude > 0.01) {
+ const tipDims = computeTipStampDimensions(effWidth, effThickness, isVert, tipNaturalW, tipNaturalH);
+ let finalW = tipDims.width;
+ let finalH = tipDims.height;
+ if (useSyntheticTiltShading && 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, 0, point.x, point.y);
const customPaper = options.paperTextureImage ? getCustomPaperLuminance(options.paperTextureImage) : null;
+ const surfacePaper =
+ !customPaper && options.surfaceTextureId ? getSurfaceTextureHeightField(options.surfaceTextureId) : null;
const texScale = options.paperTextureScale ?? 1.0;
const texRot = options.paperTextureRotate ?? 0;
const texMode = options.paperTextureMode ?? 'multiply';
@@ -2041,29 +2914,36 @@ export function drawBrushDot(
flow: effectiveFlow,
pressure: effPressure,
pressureAlreadyApplied,
- amountOfPaint: (options.amountOfPaint ?? 0.65) * startAmountScale,
- densityOfPaint: (options.densityOfPaint ?? 0.9) * startPaintDensityScale,
- colorStretch: options.colorStretch ?? 0.75,
+ amountOfPaint: effAmountOfPaint,
+ densityOfPaint: effDensityOfPaint,
+ colorStretch: effColorStretch,
+ isPureBlender: (options.amountOfPaint ?? 0.65) <= 0.005 || options.mixingMode === 'smear',
mixingMode: options.mixingMode ?? 'blend',
perceptualMixing: options.perceptualMixing !== false,
pigmentMixingStrength: options.pigmentMixingStrength ?? 1.0,
+ useBlur: Boolean(options.useBlur),
+ blurStrength: options.blurStrength,
tipImage: activeTip,
+ isDualToneTip,
+ secondaryColor: options.secondaryColor,
+ freshColor: freshColorOverride,
sampler: options.sampler,
- grainDensity: grainAmount,
- grainModulate:
- grainAmount > 0.005
- ? (wx, wy, tipA) =>
- applyCspPaperTextureAlpha(
- tipA,
- sampleWorldPaperGrainNorm(wx, wy, texScale, texRot, customPaper),
- grainAmount,
- grainPressure,
- texMode,
- texBright,
- texContrast,
- texInv
- )
- : undefined,
+ grainDensity: effGrainAmount,
+ paperTextureMode: texMode,
+ paperLumData:
+ effGrainAmount > 0.005 ? (customPaper ? customPaper.lum : surfacePaper ?? paperGrainTable) : undefined,
+ paperLumWidth:
+ effGrainAmount > 0.005 ? (customPaper ? customPaper.width : surfacePaper ? SURFACE_TEXTURE_SIZE : GRAIN_SIZE) : undefined,
+ paperLumHeight:
+ effGrainAmount > 0.005 ? (customPaper ? customPaper.height : surfacePaper ? SURFACE_TEXTURE_SIZE : GRAIN_SIZE) : undefined,
+ paperTextureScale: texScale,
+ paperTextureRotate: texRot,
+ paperTextureBrightness: texBright,
+ paperTextureContrast: texContrast,
+ paperTextureInverted: texInv,
+ paperTexturePreserveDensity: preservePaperDensity,
+ paperTextureEmphasizeDensity: Boolean(options.paperTextureEmphasizeDensity),
+ grainPressure,
});
if (built) {
options.reservoir.r = built.avgR;
@@ -2097,50 +2977,80 @@ export function drawBrushDot(
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);
+ const mixed = sampleAndMixColor(
+ ctx,
+ point.x,
+ point.y,
+ Math.max(1, effWidth * 0.5),
+ effPressure,
+ effectiveFlow,
+ 0,
+ options,
+ spacing,
+ 0,
+ 0,
+ effAmountOfPaint,
+ effDensityOfPaint,
+ effColorStretch
+ );
effectiveColor = mixed.colorHex;
effectiveFlow = mixed.alpha;
}
if (effectiveFlow <= 0.002) return;
- 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 tryPerPixelCpuGrain = !gpuDabs && effGrainAmount > 0.005 && typeof document !== 'undefined';
+ const dotSeed = Math.abs(Math.sin(point.x * 12.9898 + point.y * 78.233));
+ const dotRandOffX = dotSeed * 256;
+ const dotRandOffY = ((dotSeed * 397) % 1) * 256;
+ const dotRandRot = Math.abs(Math.cos(point.x * 39.346 + point.y * 11.135)) * Math.PI * 2;
+ const dotPaperOpts: CpuPaperGrainOptions = {
+ paperTextureMode: options.paperTextureMode ?? 'subtract',
+ paperTextureScale: options.paperTextureScale ?? 1.0,
+ paperTextureRotate: options.paperTextureRotate ?? 0,
+ paperTextureBrightness: options.paperTextureBrightness ?? 0,
+ paperTextureContrast: options.paperTextureContrast ?? 0,
+ paperTextureInverted: Boolean(options.paperTextureInverted),
+ paperTextureEmphasizeDensity: Boolean(options.paperTextureEmphasizeDensity),
+ preservePaperDensity,
+ paperTextureImage: options.paperTextureImage,
+ surfaceTextureId: options.surfaceTextureId,
+ grainMappingMode: options.grainMappingMode,
+ strokeDist: 0,
+ grainRandomOffsetX: dotRandOffX,
+ grainRandomOffsetY: dotRandOffY,
+ grainRandomRot: dotRandRot,
+ };
const baseMaster = gpuDabs
? null
- : resolveCpuMaster(activeTip, effectiveColor, hardness, isEraser, isBgEraser, isColorTip, effWidth, aaMode);
+ : resolveCpuMaster(
+ activeTip,
+ effectiveColor,
+ hardness,
+ isEraser,
+ isBgEraser,
+ isColorTip,
+ effWidth,
+ aaMode,
+ isDualToneTip,
+ options.secondaryColor
+ );
- 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 primRgb = perDabColorJitter || gpuDabs ? parseColorToRgb(effectiveColor) : null;
+ const secRgb = perDabColorJitter ? 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;
+ let curDabThickness = effThickness;
if (roundnessJitter > 0) curDabThickness *= Math.max(0.05, 1.0 - dabHashFloat(point.x, point.y, k, 2) * roundnessJitter);
let curDabAngle = angleRad;
@@ -2162,7 +3072,7 @@ export function drawBrushDot(
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) {
+ if (perDabColorJitter && primRgb && secRgb && dynamics) {
let salt = 20;
const cd = applyColorDynamics(
{ r: primRgb.r / 255, g: primRgb.g / 255, b: primRgb.b / 255 },
@@ -2174,34 +3084,75 @@ export function drawBrushDot(
dabG = cd.g;
dabB = cd.b;
if (!gpuDabs) {
- curMaster = resolveCpuMaster(activeTip, cd.hex, hardness, isEraser, isBgEraser, isColorTip, curDabW, aaMode);
+ curMaster = resolveCpuMaster(
+ activeTip,
+ cd.hex,
+ hardness,
+ isEraser,
+ isBgEraser,
+ isColorTip,
+ curDabW,
+ aaMode,
+ isDualToneTip,
+ options.secondaryColor
+ );
}
}
- let finalW = isVert ? curDabW * curDabThickness : curDabW;
- let finalH = isVert ? curDabW * aspect : curDabW * aspect * curDabThickness;
- if (useTilt && tiltMagnitude > 0.01) {
+ const dabDims = computeTipStampDimensions(curDabW, curDabThickness, isVert, tipNaturalW, tipNaturalH);
+ let finalW = dabDims.width;
+ let finalH = dabDims.height;
+ if (useSyntheticTiltShading && 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) {
+ let stampAlpha = curDabAlpha;
+ let stampFlipX = flips.signX;
+ let stampFlipY = flips.signY;
+ if (curMaster && tryPerPixelCpuGrain) {
+ const sub = computeSubpixelDabDimensions(finalW, finalH, curDabAlpha, aaMode === 0 ? 1.0 : 0.75);
const grained = applyCpuPerPixelPaperGrain(
curMaster,
curDabX,
curDabY,
- finalW,
- finalH,
- grainAmount,
+ sub.renderW,
+ sub.renderH,
+ curDabAngle,
+ flips.signX,
+ flips.signY,
+ sub.effAlpha,
+ effGrainAmount,
grainPressure,
- options.paperTextureScale ?? 1.0,
- options.paperTextureImage
+ dotPaperOpts
);
- if (grained) curMaster = grained;
+ if (grained) {
+ curMaster = grained;
+ stampAlpha = 1.0;
+ stampFlipX = 1;
+ stampFlipY = 1;
+ } else {
+ const gNorm = sampleScalarPaperGrainNorm(curDabX, curDabY, curDabW, options.paperTextureScale ?? 1.0);
+ const scalarMode = options.paperTextureMode === 'compare' ? 'subtract' : (options.paperTextureMode ?? 'subtract');
+ const modTip = applyCspPaperTextureAlpha(
+ 1.0,
+ gNorm,
+ effGrainAmount,
+ grainPressure,
+ scalarMode,
+ options.paperTextureBrightness ?? 0,
+ options.paperTextureContrast ?? 0,
+ Boolean(options.paperTextureInverted),
+ preservePaperDensity,
+ Boolean(options.paperTextureEmphasizeDensity)
+ );
+ stampAlpha = Math.max(0, Math.min(1, curDabAlpha * modTip));
+ }
}
+ const dabGrainDensity = options.textureDensitySensor ? effGrainAmount : undefined;
if (options.spray?.enabled) {
const pCount = options.spray.density;
const pSize = Math.max(1, options.spray.size);
@@ -2213,19 +3164,21 @@ export function drawBrushDot(
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;
+ const spDims = computeTipStampDimensions(pSize, curDabThickness, isVert, tipNaturalW, tipNaturalH);
+ const spW = spDims.width;
+ const spH = spDims.height;
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,
+ grainDensity: dabGrainDensity,
});
} else if (curMaster) {
drawSingleStamp(
- ctx, curMaster, spX, spY, spW, spH, curDabAngle, curDabAlpha,
+ ctx, curMaster, spX, spY, spW, spH, curDabAngle, stampAlpha,
isEraser, isBgEraser, options.alphaLocked, options.isTransparentInk,
- flips.signX, flips.signY, aaMode, options.blendTipsMode
+ stampFlipX, stampFlipY, aaMode, options.blendTipsMode
);
}
}
@@ -2234,12 +3187,13 @@ export function drawBrushDot(
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,
+ grainDensity: dabGrainDensity,
});
} else if (curMaster) {
drawSingleStamp(
- ctx, curMaster, curDabX, curDabY, finalW, finalH, curDabAngle, curDabAlpha,
+ ctx, curMaster, curDabX, curDabY, finalW, finalH, curDabAngle, stampAlpha,
isEraser, isBgEraser, options.alphaLocked, options.isTransparentInk,
- flips.signX, flips.signY, aaMode, options.blendTipsMode
+ stampFlipX, stampFlipY, aaMode, options.blendTipsMode
);
}
}
@@ -2257,7 +3211,14 @@ export function drawBrushCubicBezierSegment(
color: string,
options: BrushRenderOptions = {},
remainderDist: number = 0,
- dabCounter: { count: number; lastAngle?: number; lastStepDist?: number } = { count: 0 },
+ dabCounter: {
+ count: number;
+ lastAngle?: number;
+ lastStepDist?: number;
+ lockedInitialAngle?: number;
+ initOriginX?: number;
+ initOriginY?: number;
+ } = { count: 0 },
batchGpuDabs?: GpuDab[]
): number {
const { totalLength: totalCurveLength, steps: arcSteps } = buildFastArcLengthScratch(p0, c1, c2, p3);
@@ -2267,7 +3228,27 @@ export function drawBrushCubicBezierSegment(
const isEraser = Boolean(options.isEraser);
const isBgEraser = Boolean(options.isBgEraser);
- const baseColor = isBgEraser ? '#ffffff' : color;
+ const dynamics = options.dynamics;
+ const colorJitterEnabled = Boolean(dynamics?.colorJitterEnabled);
+ const colorJitterPerStroke = Boolean(colorJitterEnabled && dynamics?.colorJitterPerStroke);
+ let baseColor = isBgEraser ? '#ffffff' : color;
+ if (colorJitterPerStroke && dynamics) {
+ if (!options.strokeJitterColor) {
+ const prim0 = parseColorToRgb(baseColor);
+ const sec0 = parseColorToRgb(options.secondaryColor || '#ffffff');
+ let salt = 200;
+ const strokeIdx = options.strokeIndex ?? 0;
+ options.strokeJitterColor = applyColorDynamics(
+ { r: prim0.r / 255, g: prim0.g / 255, b: prim0.b / 255 },
+ { r: sec0.r / 255, g: sec0.g / 255, b: sec0.b / 255 },
+ dynamics,
+ () => dabHashFloat(p0.x, p0.y, strokeIdx, salt++)
+ );
+ }
+ baseColor = options.strokeJitterColor.hex;
+ }
+ const perDabColorJitter = colorJitterEnabled && !colorJitterPerStroke;
+
const hardness = options.hardness ?? 1.0;
const tipImage = options.tipImage;
const isColorMixing = Boolean(options.colorMixing) && !isEraser && !isBgEraser;
@@ -2276,9 +3257,8 @@ export function drawBrushCubicBezierSegment(
options.reservoir = new PaintReservoir(baseColor);
}
- const aspect = tipImage
- ? (tipImage.naturalHeight || tipImage.height || 1) / (tipImage.naturalWidth || tipImage.width || 1)
- : 1.0;
+ const tipNaturalW = tipImage ? (tipImage.naturalWidth || tipImage.width || 1) : 1;
+ const tipNaturalH = tipImage ? (tipImage.naturalHeight || tipImage.height || 1) : 1;
const baseAngleRad = ((options.angle ?? 0) * Math.PI) / 180;
const rawDensity = options.brushDensity ?? options.flow ?? (tipImage ? 0.85 : 1.0);
const spacingRatio = Math.max(0.003, Math.min(2.0, options.spacing ?? (tipImage ? 0.07 : 0.08)));
@@ -2286,15 +3266,18 @@ export function drawBrushCubicBezierSegment(
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 { readTiltInput, useSyntheticTiltShading } = resolveTiltBehavior(options);
const aaMode = options.antiAlias ?? 2;
- const grainAmount = options.grain ?? options.textureDensity ?? 0;
+ const grainAmount = options.skipPerDabPaperGrain ? 0 : (options.grain ?? options.textureDensity ?? 0);
+ const preservePaperDensity =
+ Boolean(options.textureDensitySensor) ||
+ (options.paperTextureApplyEachPlot !== undefined && !options.grainPenetrationSensor?.usePressure);
const isColorTip = Boolean(options.isColorTip || (options.subTips && options.subTips[0]?.isColor));
+ const isDualToneTip = !isColorTip && Boolean(options.isDualToneTip || (options.subTips && options.subTips[0]?.isDualToneTip));
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 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));
@@ -2302,23 +3285,27 @@ export function drawBrushCubicBezierSegment(
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 useSpatialTipMixing =
isColorMixing &&
!gpuDabs &&
!isColorTip &&
- !colorJitterEnabled &&
!options.spray?.enabled;
if (useSpatialTipMixing && options.reservoir && !options.reservoir.spatialMixer) {
options.reservoir.spatialMixer = new SpatialTipMixer(baseColor);
}
const pressureAlreadyAppliedToFlow = Boolean(
- options.opacitySensor?.usePressure || options.densitySensor?.usePressure
+ options.opacitySensor?.usePressure ||
+ options.densitySensor?.usePressure ||
+ options.densityOfPaintSensor?.usePressure
);
const customPaper =
useSpatialTipMixing && grainAmount > 0.005 && options.paperTextureImage
? getCustomPaperLuminance(options.paperTextureImage)
: null;
+ const surfacePaper =
+ useSpatialTipMixing && grainAmount > 0.005 && !customPaper && options.surfaceTextureId
+ ? getSurfaceTextureHeightField(options.surfaceTextureId)
+ : null;
const texScale = options.paperTextureScale ?? 1.0;
const texRot = options.paperTextureRotate ?? 0;
const texMode = options.paperTextureMode ?? 'multiply';
@@ -2329,24 +3316,48 @@ export function drawBrushCubicBezierSegment(
const staticMaster =
isColorMixing || gpuDabs || hasMultiSubTips
? null
- : resolveCpuMaster(tipImage, baseColor, hardness, isEraser, isBgEraser, isColorTip, avgSegWidth, aaMode);
+ : resolveCpuMaster(
+ tipImage,
+ baseColor,
+ hardness,
+ isEraser,
+ isBgEraser,
+ isColorTip,
+ avgSegWidth,
+ aaMode,
+ isDualToneTip,
+ options.secondaryColor
+ );
- const baseRgb = colorJitterEnabled || gpuDabs ? parseColorToRgb(baseColor) : null;
- const secRgb = colorJitterEnabled ? parseColorToRgb(options.secondaryColor || '#ffffff') : null;
+ const baseRgb = perDabColorJitter || gpuDabs ? parseColorToRgb(baseColor) : null;
+ const secRgb = perDabColorJitter ? parseColorToRgb(options.secondaryColor || '#ffffff') : null;
const baseMinStepPx = tipImage ? 0.15 : 0.12;
- const hasPerPixelCpuGrain =
- !gpuDabs && !useSpatialTipMixing && grainAmount > 0.005 && typeof ctx.createPattern === 'function';
+ const tryPerPixelCpuGrain = !gpuDabs && !useSpatialTipMixing && grainAmount > 0.005 && typeof document !== 'undefined';
+ const segSeed = Math.abs(Math.sin(p0.x * 12.9898 + p0.y * 78.233));
+ const segRandOffX = segSeed * 256;
+ const segRandOffY = ((segSeed * 397) % 1) * 256;
+ const segRandRot = Math.abs(Math.cos(p0.x * 39.346 + p0.y * 11.135)) * Math.PI * 2;
+
+ if (options.angleDynamics === 'initial-direction') {
+ if (options.initialAngleRad !== undefined && dabCounter.lockedInitialAngle === undefined) {
+ dabCounter.lockedInitialAngle = options.initialAngleRad;
+ }
+ if (dabCounter.initOriginX === undefined) {
+ dabCounter.initOriginX = p0.x;
+ dabCounter.initOriginY = p0.y;
+ }
+ }
let hasSmoothAngle = dabCounter.lastAngle !== undefined;
let smoothCos = hasSmoothAngle ? Math.cos(dabCounter.lastAngle!) : Math.cos(baseAngleRad);
let smoothSin = hasSmoothAngle ? Math.sin(dabCounter.lastAngle!) : Math.sin(baseAngleRad);
let currentDist = remainderDist > 0 ? remainderDist : 0;
- // Preserve true inter-stamp arc distance across Bezier segment boundaries (never reset to partial remainderDist)
+ // Preserve true inter-stamp arc distance across Bezier segment boundaries.
+ // On Dab 1 (lastStepDist === undefined), use 0 so SpatialTipMixer uses nominal spacing instead of
+ // a tiny post-carryover remainderDist from high-frequency pointer segments.
let prevStepDist =
dabCounter.lastStepDist !== undefined && dabCounter.lastStepDist > 0
? dabCounter.lastStepDist
- : remainderDist > 0
- ? remainderDist
: 0;
while (currentDist <= totalCurveLength) {
@@ -2376,13 +3387,25 @@ export function drawBrushCubicBezierSegment(
const taperPaintDensityScale = taperFactors.paintDensityScale;
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 tiltX = readTiltInput ? pt.tiltX : 0;
+ const tiltY = readTiltInput ? pt.tiltY : 0;
+ const tiltMagnitude = computeCspTiltMagnitude(tiltX, tiltY);
const tiltSpread = tiltMagnitude * (options.tiltScale ?? 1.0);
const grainPressure =
- useTilt && tiltMagnitude > 0.01 ? effPressure * (1.0 - tiltMagnitude * 0.55) : effPressure;
+ useSyntheticTiltShading && tiltMagnitude > 0.01 ? effPressure * (1.0 - tiltMagnitude * 0.55) : effPressure;
+ let effGrainAmount = grainAmount;
+ if (grainAmount > 0.005 && options.textureDensitySensor) {
+ const tdFactor = evaluateCspSensor(
+ options.textureDensitySensor,
+ effPressure,
+ tiltMagnitude,
+ pt.speed * 0.05,
+ dabHashFloat(pt.x, pt.y, dabSeq, 58),
+ pt.twist,
+ strokeDist
+ );
+ effGrainAmount = Math.max(0, Math.min(1, grainAmount * tdFactor));
+ }
if (options.sizeSensor) {
// Avoid double-applying pressure when pt.width already has pressure baked from calculateStrokeWidth
@@ -2395,14 +3418,98 @@ export function drawBrushCubicBezierSegment(
effPressure,
tiltMagnitude,
pt.speed * 0.05,
- dabHashFloat(pt.x, pt.y, dabSeq, 50)
+ dabHashFloat(pt.x, pt.y, dabSeq, 50),
+ pt.twist,
+ strokeDist
);
}
curWidth = Math.max(0.1, curWidth);
+ let effThickness = thickness;
+ if (options.thicknessSensor) {
+ // CSP Brush Thickness minimum is 10% (0.10); never collapse below 0.10 unless base thickness itself is thinner.
+ const minThicknessFloor = Math.min(thickness, 0.1);
+ effThickness = Math.max(
+ minThicknessFloor,
+ thickness *
+ evaluateCspSensor(
+ options.thicknessSensor,
+ effPressure,
+ tiltMagnitude,
+ pt.speed * 0.05,
+ dabHashFloat(pt.x, pt.y, dabSeq, 54),
+ pt.twist,
+ strokeDist
+ )
+ );
+ }
+
+ let effAmountOfPaint = (options.amountOfPaint ?? 0.65) * taperAmountScale;
+ if (options.amountOfPaintSensor) {
+ effAmountOfPaint *= evaluateCspSensor(
+ options.amountOfPaintSensor,
+ effPressure,
+ tiltMagnitude,
+ pt.speed * 0.05,
+ dabHashFloat(pt.x, pt.y, dabSeq, 55),
+ pt.twist,
+ strokeDist
+ );
+ }
+ let effDensityOfPaint = (options.densityOfPaint ?? 0.9) * taperPaintDensityScale;
+ let paintDensitySensorFactor = 1.0;
+ const hasConcurrentDensityAndPaintDensityPressure = Boolean(
+ isColorMixing && options.densitySensor?.usePressure && options.densityOfPaintSensor?.usePressure
+ );
+ if (options.densityOfPaintSensor) {
+ paintDensitySensorFactor = evaluateCspSensor(
+ options.densityOfPaintSensor,
+ effPressure,
+ tiltMagnitude,
+ pt.speed * 0.05,
+ dabHashFloat(pt.x, pt.y, dabSeq, 56),
+ pt.twist,
+ strokeDist
+ );
+ if (!hasConcurrentDensityAndPaintDensityPressure) {
+ effDensityOfPaint *= paintDensitySensorFactor;
+ } else if (paintDensitySensorFactor <= 0.002) {
+ effDensityOfPaint = 0;
+ }
+ }
+ let effColorStretch = options.colorStretch ?? 0.75;
+ if (options.colorStretchSensor) {
+ effColorStretch *= evaluateCspSensor(
+ options.colorStretchSensor,
+ effPressure,
+ tiltMagnitude,
+ pt.speed * 0.05,
+ dabHashFloat(pt.x, pt.y, dabSeq, 57),
+ pt.twist,
+ strokeDist
+ );
+ }
+
let stampAngle = baseAngleRad;
const angleMode = options.angleDynamics;
- if (angleMode === 'direction' || angleMode === 'direction-random') {
+ if (angleMode === 'initial-direction') {
+ if (dabCounter.lockedInitialAngle !== undefined) {
+ stampAngle = dabCounter.lockedInitialAngle;
+ } else {
+ const ox = dabCounter.initOriginX ?? p0.x;
+ const oy = dabCounter.initOriginY ?? p0.y;
+ const cdx = pt.x - ox;
+ const cdy = pt.y - oy;
+ const chordLen = Math.hypot(cdx, cdy);
+ if (chordLen >= 4.0) {
+ dabCounter.lockedInitialAngle = Math.atan2(cdy, cdx) + baseAngleRad;
+ stampAngle = dabCounter.lockedInitialAngle;
+ dabCounter.lastAngle = stampAngle;
+ } else if (pt.speed > 0.2) {
+ stampAngle = Math.atan2(pt.dy, pt.dx) + baseAngleRad;
+ }
+ }
+ } else if (angleMode === 'direction' || angleMode === 'direction-random') {
// Deadzone + arc-length-bounded turn rate prevents micro-jitter / pointer-up hooks
// from spinning flat blades into starbursts while tracking smooth curves faithfully
const minTangentSpeed = hasSmoothAngle ? 1.2 : 0.2;
@@ -2440,10 +3547,12 @@ export function drawBrushCubicBezierSegment(
stampAngle += (dabHashFloat(pt.x, pt.y, dabSeq, 12) - 0.5) * Math.PI * 2 * rotationRandomScale;
}
- if (useTilt && tiltMagnitude > 0.05) {
+ if (angleMode === 'tilt' && tiltMagnitude > 0.05) {
+ stampAngle = Math.atan2(tiltX, -tiltY) + baseAngleRad;
+ } else if (useSyntheticTiltShading && tiltMagnitude > 0.05) {
stampAngle = Math.atan2(tiltY, tiltX) + baseAngleRad;
}
- if (pt.twist && (angleMode === 'twist' || useTilt)) {
+ if (pt.twist && (angleMode === 'twist' || useSyntheticTiltShading)) {
stampAngle += (pt.twist * Math.PI) / 180;
}
@@ -2451,25 +3560,63 @@ export function drawBrushCubicBezierSegment(
let dabAlpha = baseFlow * taperAlphaScale;
let dabRgb = baseRgb;
- if (options.opacitySensor) {
- dabAlpha *= evaluateCspSensor(
+ let flowSensorFactor = 1.0;
+ if (hasConcurrentDensityAndPaintDensityPressure) {
+ const dnF = evaluateCspSensor(
+ options.densitySensor,
+ effPressure,
+ tiltMagnitude,
+ pt.speed * 0.05,
+ dabHashFloat(pt.x, pt.y, dabSeq, 52)
+ );
+ flowSensorFactor = dnF;
+ if (options.opacitySensor) {
+ flowSensorFactor *= evaluateCspSensor(
+ options.opacitySensor,
+ effPressure,
+ tiltMagnitude,
+ pt.speed * 0.05,
+ dabHashFloat(pt.x, pt.y, dabSeq, 51)
+ );
+ }
+ } else if (options.opacitySensor && options.densitySensor && (isColorMixing || options.paperTextureApplyEachPlot === false)) {
+ const opF = evaluateCspSensor(
options.opacitySensor,
effPressure,
tiltMagnitude,
pt.speed * 0.05,
dabHashFloat(pt.x, pt.y, dabSeq, 51)
);
- }
- if (options.densitySensor) {
- dabAlpha *= evaluateCspSensor(
+ const dnF = evaluateCspSensor(
options.densitySensor,
effPressure,
tiltMagnitude,
pt.speed * 0.05,
dabHashFloat(pt.x, pt.y, dabSeq, 52)
);
+ flowSensorFactor = Math.min(opF, dnF);
+ } else {
+ if (options.opacitySensor) {
+ flowSensorFactor *= evaluateCspSensor(
+ options.opacitySensor,
+ effPressure,
+ tiltMagnitude,
+ pt.speed * 0.05,
+ dabHashFloat(pt.x, pt.y, dabSeq, 51)
+ );
+ }
+ if (options.densitySensor) {
+ flowSensorFactor *= 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 = Math.max(0, Math.min(1, dabAlpha * flowSensorFactor));
+ if (useSyntheticTiltShading && tiltMagnitude > 0.03 && (tipImage || grainAmount > 0.005)) {
dabAlpha *= 1.0 - tiltMagnitude * 0.28;
}
@@ -2489,7 +3636,10 @@ export function drawBrushCubicBezierSegment(
options,
spacingRatio,
dirX,
- dirY
+ dirY,
+ effAmountOfPaint,
+ effDensityOfPaint,
+ effColorStretch
);
dabColor = mixed.colorHex;
dabAlpha = mixed.alpha;
@@ -2498,31 +3648,29 @@ export function drawBrushCubicBezierSegment(
}
}
- if (!gpuDabs && !useSpatialTipMixing && 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 activeTipIdx = tipImage
? selectTipIndex(options.subTipImages, options.subTipOrder, dabSeq, stampAngle, pt.x, pt.y)
: 0;
const activeTip = tipImage
? selectTipImage(options.subTipImages, tipImage, options.subTipOrder, dabSeq, stampAngle, pt.x, pt.y)
: undefined;
+ const dabIsDualTone = !isColorTip && Boolean(options.subTips?.[activeTipIdx]?.isDualToneTip ?? isDualToneTip);
const baseMaster =
gpuDabs || useSpatialTipMixing
? null
- : staticMaster ?? resolveCpuMaster(activeTip, dabColor, hardness, isEraser, isBgEraser, isColorTip, curWidth, aaMode);
+ : staticMaster ??
+ resolveCpuMaster(
+ activeTip,
+ dabColor,
+ hardness,
+ isEraser,
+ isBgEraser,
+ isColorTip,
+ curWidth,
+ aaMode,
+ dabIsDualTone,
+ options.secondaryColor
+ );
let tx = 1;
let ty = 0;
@@ -2535,9 +3683,27 @@ export function drawBrushCubicBezierSegment(
ny = tx;
}
- const primRgb = colorJitterEnabled && isColorMixing ? parseColorToRgb(dabColor) : dabRgb;
- let stepRefW = isVert ? curWidth * thickness : curWidth;
- let stepRefH = isVert ? curWidth * aspect : curWidth * aspect * thickness;
+ const primRgb = perDabColorJitter && isColorMixing ? parseColorToRgb(dabColor) : dabRgb;
+ const baseTipDims = computeTipStampDimensions(curWidth, effThickness, isVert, tipNaturalW, tipNaturalH);
+ let stepRefW = baseTipDims.width;
+ let stepRefH = baseTipDims.height;
+
+ const effectiveSpacingRatio = options.intervalSensor
+ ? Math.max(
+ 0.02,
+ Math.min(
+ 2.0,
+ spacingRatio *
+ evaluateCspSensor(
+ options.intervalSensor,
+ effPressure,
+ tiltMagnitude,
+ pt.speed * 0.05,
+ dabHashFloat(pt.x, pt.y, dabSeq, 53)
+ )
+ )
+ )
+ : spacingRatio;
for (let k = 0; k < dabCount; k++) {
const seedIdx = dabSeq * 16 + k;
@@ -2545,7 +3711,7 @@ export function drawBrushCubicBezierSegment(
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;
+ let curDabThickness = effThickness;
if (roundnessJitter > 0) curDabThickness *= Math.max(0.05, 1.0 - dabHashFloat(pt.x, pt.y, seedIdx, 2) * roundnessJitter);
let curDabAngle = stampAngle;
@@ -2569,9 +3735,10 @@ export function drawBrushCubicBezierSegment(
let curDabAlpha = dabAlpha;
if (flowJitter > 0) curDabAlpha *= Math.max(0.005, 1.0 - dabHashFloat(pt.x, pt.y, seedIdx, 6) * flowJitter);
- let finalW = isVert ? curDabW * curDabThickness : curDabW;
- let finalH = isVert ? curDabW * aspect : curDabW * aspect * curDabThickness;
- if (useTilt && tiltMagnitude > 0.01) {
+ const curDims = computeTipStampDimensions(curDabW, curDabThickness, isVert, tipNaturalW, tipNaturalH);
+ let finalW = curDims.width;
+ let finalH = curDims.height;
+ if (useSyntheticTiltShading && tiltMagnitude > 0.01) {
finalW *= 1.0 + tiltSpread * 1.85;
finalH *= Math.max(0.55, 1.0 / (1.0 + tiltMagnitude * 0.45));
}
@@ -2583,8 +3750,19 @@ export function drawBrushCubicBezierSegment(
const flips = resolveTipFlipSigns(options.flipH, options.flipV, seedIdx, curDabX, curDabY);
if (useSpatialTipMixing && options.reservoir?.spatialMixer) {
+ let freshColorOverride: { r: number; g: number; b: number } | undefined;
+ if (perDabColorJitter && 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++)
+ );
+ freshColorOverride = { r: cd.r * 255, g: cd.g * 255, b: cd.b * 255 };
+ }
const effectiveStep =
- prevStepDist > 0 ? prevStepDist : Math.max(0.85, Math.min(finalW, finalH) * Math.max(0.12, spacingRatio));
+ prevStepDist > 0 ? prevStepDist : Math.max(0.75, Math.min(finalW, finalH) * effectiveSpacingRatio);
const built = options.reservoir.spatialMixer.stepAndBuildStamp({
x: curDabX,
y: curDabY,
@@ -2594,7 +3772,7 @@ export function drawBrushCubicBezierSegment(
dirX,
dirY,
stepDist: effectiveStep,
- spacingRatio,
+ spacingRatio: effectiveSpacingRatio,
adjustDensityByGap: Boolean(options.adjustDensityByGap),
dabSeq,
hardness,
@@ -2604,29 +3782,36 @@ export function drawBrushCubicBezierSegment(
flow: curDabAlpha,
pressure: effPressure,
pressureAlreadyApplied: pressureAlreadyAppliedToFlow,
- amountOfPaint: (options.amountOfPaint ?? 0.65) * taperAmountScale,
- densityOfPaint: (options.densityOfPaint ?? 0.9) * taperPaintDensityScale,
- colorStretch: options.colorStretch ?? 0.75,
+ amountOfPaint: effAmountOfPaint,
+ densityOfPaint: effDensityOfPaint,
+ colorStretch: effColorStretch,
+ isPureBlender: (options.amountOfPaint ?? 0.65) <= 0.005 || options.mixingMode === 'smear',
mixingMode: options.mixingMode ?? 'blend',
perceptualMixing: options.perceptualMixing !== false,
pigmentMixingStrength: options.pigmentMixingStrength ?? 1.0,
+ useBlur: Boolean(options.useBlur),
+ blurStrength: options.blurStrength,
tipImage: activeTip,
+ isDualToneTip: dabIsDualTone,
+ secondaryColor: options.secondaryColor,
+ freshColor: freshColorOverride,
sampler: options.sampler,
- grainDensity: grainAmount,
- grainModulate:
- grainAmount > 0.005
- ? (wx, wy, tipA) =>
- applyCspPaperTextureAlpha(
- tipA,
- sampleWorldPaperGrainNorm(wx, wy, texScale, texRot, customPaper),
- grainAmount,
- grainPressure,
- texMode,
- texBright,
- texContrast,
- texInv
- )
- : undefined,
+ grainDensity: effGrainAmount,
+ paperTextureMode: texMode,
+ paperLumData:
+ effGrainAmount > 0.005 ? (customPaper ? customPaper.lum : surfacePaper ?? paperGrainTable) : undefined,
+ paperLumWidth:
+ effGrainAmount > 0.005 ? (customPaper ? customPaper.width : surfacePaper ? SURFACE_TEXTURE_SIZE : GRAIN_SIZE) : undefined,
+ paperLumHeight:
+ effGrainAmount > 0.005 ? (customPaper ? customPaper.height : surfacePaper ? SURFACE_TEXTURE_SIZE : GRAIN_SIZE) : undefined,
+ paperTextureScale: texScale,
+ paperTextureRotate: texRot,
+ paperTextureBrightness: texBright,
+ paperTextureContrast: texContrast,
+ paperTextureInverted: texInv,
+ paperTexturePreserveDensity: preservePaperDensity,
+ paperTextureEmphasizeDensity: Boolean(options.paperTextureEmphasizeDensity),
+ grainPressure,
});
if (built) {
options.reservoir.r = built.avgR;
@@ -2663,7 +3848,7 @@ export function drawBrushCubicBezierSegment(
let dabG = primRgb ? primRgb.g / 255 : 0;
let dabB = primRgb ? primRgb.b / 255 : 0;
- if (colorJitterEnabled && primRgb && secRgb && dynamics) {
+ if (perDabColorJitter && primRgb && secRgb && dynamics) {
let salt = 20;
const cd = applyColorDynamics(
{ r: primRgb.r / 255, g: primRgb.g / 255, b: primRgb.b / 255 },
@@ -2675,25 +3860,81 @@ export function drawBrushCubicBezierSegment(
dabG = cd.g;
dabB = cd.b;
if (!gpuDabs) {
- curMaster = resolveCpuMaster(activeTip, cd.hex, hardness, isEraser, isBgEraser, isColorTip, curDabW, aaMode);
+ curMaster = resolveCpuMaster(
+ activeTip,
+ cd.hex,
+ hardness,
+ isEraser,
+ isBgEraser,
+ isColorTip,
+ curDabW,
+ aaMode,
+ dabIsDualTone,
+ options.secondaryColor
+ );
}
}
- if (curMaster && hasPerPixelCpuGrain) {
+ let stampAlpha = curDabAlpha;
+ let stampFlipX = flips.signX;
+ let stampFlipY = flips.signY;
+ if (curMaster && tryPerPixelCpuGrain) {
+ const sub = computeSubpixelDabDimensions(finalW, finalH, curDabAlpha, aaMode === 0 ? 1.0 : 0.75);
const grained = applyCpuPerPixelPaperGrain(
curMaster,
curDabX,
curDabY,
- finalW,
- finalH,
- grainAmount,
+ sub.renderW,
+ sub.renderH,
+ curDabAngle,
+ flips.signX,
+ flips.signY,
+ sub.effAlpha,
+ effGrainAmount,
grainPressure,
- options.paperTextureScale ?? 1.0,
- options.paperTextureImage
+ {
+ paperTextureMode: options.paperTextureMode ?? 'subtract',
+ paperTextureScale: options.paperTextureScale ?? 1.0,
+ paperTextureRotate: options.paperTextureRotate ?? 0,
+ paperTextureBrightness: options.paperTextureBrightness ?? 0,
+ paperTextureContrast: options.paperTextureContrast ?? 0,
+ paperTextureInverted: Boolean(options.paperTextureInverted),
+ paperTextureEmphasizeDensity: Boolean(options.paperTextureEmphasizeDensity),
+ preservePaperDensity,
+ paperTextureImage: options.paperTextureImage,
+ surfaceTextureId: options.surfaceTextureId,
+ grainMappingMode: options.grainMappingMode,
+ strokeDist,
+ grainRandomOffsetX: segRandOffX,
+ grainRandomOffsetY: segRandOffY,
+ grainRandomRot: segRandRot,
+ }
);
- if (grained) curMaster = grained;
+ if (grained) {
+ curMaster = grained;
+ stampAlpha = 1.0;
+ stampFlipX = 1;
+ stampFlipY = 1;
+ } else {
+ const gNorm = sampleScalarPaperGrainNorm(curDabX, curDabY, curDabW, options.paperTextureScale ?? 1.0);
+ const scalarMode = options.paperTextureMode === 'compare' ? 'subtract' : (options.paperTextureMode ?? 'subtract');
+ const modTip = applyCspPaperTextureAlpha(
+ 1.0,
+ gNorm,
+ effGrainAmount,
+ grainPressure,
+ scalarMode,
+ options.paperTextureBrightness ?? 0,
+ options.paperTextureContrast ?? 0,
+ Boolean(options.paperTextureInverted),
+ preservePaperDensity,
+ Boolean(options.paperTextureEmphasizeDensity)
+ );
+ stampAlpha = Math.max(0, Math.min(1, curDabAlpha * modTip));
+ }
}
+ const dabGrainDensity = options.textureDensitySensor ? effGrainAmount : undefined;
if (options.spray?.enabled) {
const pCount = options.spray.density;
const pSize = Math.max(1, options.spray.size);
@@ -2705,19 +3946,21 @@ export function drawBrushCubicBezierSegment(
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;
+ const spDims = computeTipStampDimensions(pSize, curDabThickness, isVert, tipNaturalW, tipNaturalH);
+ const spW = spDims.width;
+ const spH = spDims.height;
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, tipIndex: activeTipIdx,
+ grainDensity: dabGrainDensity,
});
} else if (curMaster) {
drawSingleStamp(
- ctx, curMaster, spX, spY, spW, spH, curDabAngle, curDabAlpha,
+ ctx, curMaster, spX, spY, spW, spH, curDabAngle, stampAlpha,
isEraser, isBgEraser, options.alphaLocked, options.isTransparentInk,
- flips.signX, flips.signY, aaMode, options.blendTipsMode
+ stampFlipX, stampFlipY, aaMode, options.blendTipsMode
);
}
}
@@ -2726,18 +3969,24 @@ export function drawBrushCubicBezierSegment(
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, tipIndex: activeTipIdx,
+ grainDensity: dabGrainDensity,
});
} else if (curMaster) {
drawSingleStamp(
- ctx, curMaster, curDabX, curDabY, finalW, finalH, curDabAngle, curDabAlpha,
+ ctx, curMaster, curDabX, curDabY, finalW, finalH, curDabAngle, stampAlpha,
isEraser, isBgEraser, options.alphaLocked, options.isTransparentInk,
- flips.signX, flips.signY, aaMode, options.blendTipsMode
+ stampFlipX, stampFlipY, aaMode, options.blendTipsMode
);
}
}
+ const maxAxis = Math.max(stepRefW, stepRefH);
+ const minAxis = Math.max(0.5, Math.min(stepRefW, stepRefH));
+ // SpatialTipMixer normalizes deposition via Beer-Lambert overlapHits, so scaling the floor
+ // smoothly with brush size eliminates 100-300+ redundant CPU dabs per swipe on large oil/blend brushes
+ // while keeping 12+ overlapping hits across the brush chord for silky, zero-scallop strokes.
const effectiveMinStep = useSpatialTipMixing
- ? Math.max(0.55, Math.min(1.05, Math.min(stepRefW, stepRefH) * 0.1))
+ ? Math.max(0.85, Math.min(4.2, minAxis * 0.085))
: baseMinStepPx;
let stepAdvance = computeEllipticalStepDistance(
stepRefW,
@@ -2745,12 +3994,11 @@ export function drawBrushCubicBezierSegment(
stampAngle,
pt.dx,
pt.dy,
- spacingRatio,
+ effectiveSpacingRatio,
effectiveMinStep
);
- // Angular-sweep stepping: tighten step on curves so outer tips of wide flat blades never fan into comb teeth
- const maxAxis = Math.max(stepRefW, stepRefH);
- const minAxis = Math.max(0.5, Math.min(stepRefW, stepRefH));
+ // Angular-sweep stepping: tighten step on curves so outer tips of wide flat blades never fan into comb teeth.
+ // Respect effectiveMinStep for CPU SpatialTipMixer so curves never collapse to 0.2px (10x lag spike).
if (
(angleMode === 'direction' || angleMode === 'direction-random') &&
maxAxis > minAxis * 1.35 &&
@@ -2772,9 +4020,12 @@ export function drawBrushCubicBezierSegment(
while (dTheta > Math.PI) dTheta -= Math.PI * 2;
while (dTheta < -Math.PI) dTheta += Math.PI * 2;
const outerArc = 0.5 * maxAxis * Math.abs(dTheta);
- const maxOuterArc = Math.max(0.75, minAxis * 0.14);
+ const maxOuterArc = useSpatialTipMixing
+ ? Math.max(1.5, minAxis * 0.22)
+ : Math.max(0.75, minAxis * 0.14);
if (outerArc > maxOuterArc) {
- stepAdvance = Math.max(0.2, stepAdvance * (maxOuterArc / outerArc));
+ const curveFloor = useSpatialTipMixing ? effectiveMinStep : 0.2;
+ stepAdvance = Math.max(curveFloor, stepAdvance * (maxOuterArc / outerArc));
}
}
}
@@ -2837,13 +4088,17 @@ export function buildBrushRenderOptions(
brushDensity: bs.brushDensity,
adjustDensityByGap: bs.adjustDensityByGap,
blendTipsMode: bs.blendTipsMode,
+ brushCombineMode: bs.brushCombineMode,
spacing: bs.spacing ?? 0.08,
thickness: bs.thickness,
thicknessVertical: bs.thicknessVertical,
+ thicknessSensor: bs.thicknessSensor,
flipH: bs.flipH,
flipV: bs.flipV,
tipImage: bs.customTipImage,
isColorTip: bs.isColorTip,
+ isDualToneTip: bs.isDualToneTip,
+ isRibbon: bs.isRibbon,
angle: bs.customTipAngle,
angleDynamics: bs.customTipAngleDynamics,
rotationRandomScale: bs.customTipRotationRandomScale,
@@ -2858,6 +4113,8 @@ export function buildBrushRenderOptions(
sizeSensor: bs.sizeSensor,
opacitySensor: bs.opacitySensor,
densitySensor: bs.densitySensor,
+ intervalSensor: bs.intervalSensor,
+ textureDensitySensor: bs.textureDensitySensor,
bristleSplaySensor: bs.bristleSplaySensor,
paintLoadSensor: bs.paintLoadSensor,
grainPenetrationSensor: bs.grainPenetrationSensor,
@@ -2874,6 +4131,11 @@ export function buildBrushRenderOptions(
amountOfPaint: bs.amountOfPaint,
densityOfPaint: bs.densityOfPaint,
colorStretch: bs.colorStretch,
+ amountOfPaintSensor: bs.amountOfPaintSensor,
+ densityOfPaintSensor: bs.densityOfPaintSensor,
+ colorStretchSensor: bs.colorStretchSensor,
+ useBlur: bs.useBlur,
+ blurStrength: bs.blurStrength,
mixingMode: bs.mixingMode,
wetEdge: bs.wetEdge,
wetEdgeRadius: bs.wetEdgeRadius,
@@ -2886,15 +4148,35 @@ export function buildBrushRenderOptions(
paperTextureMode: bs.paperTextureMode,
paperTextureBrightness: bs.paperTextureBrightness,
paperTextureContrast: bs.paperTextureContrast,
+ paperTextureApplyEachPlot: bs.paperTextureApplyEachPlot,
+ paperTextureEmphasizeDensity: bs.paperTextureEmphasizeDensity,
paperTextureInverted: bs.paperTextureInverted,
paperTextureImage: bs.paperTextureImage,
paperTextureScale: bs.paperTextureScale,
paperTextureRotate: bs.paperTextureRotate,
dualBrush: bs.dualBrush,
+ dualBrushConfig: bs.dualBrushConfig,
+ dualTipDataUrl: bs.dualTipDataUrl,
dualTipImage: bs.dualTipImage,
dualBrushCompositeMode: bs.dualBrushCompositeMode,
+ dualSize: bs.dualSize,
+ dualLinkSize: bs.dualLinkSize,
+ dualSpacing: bs.dualSpacing,
dualScale: bs.dualScale,
+ dualThickness: bs.dualThickness,
+ dualThicknessVertical: bs.dualThicknessVertical,
dualAngle: bs.dualAngle,
+ dualAngleDynamics: bs.dualAngleDynamics,
+ dualAngleSensor: bs.dualAngleSensor,
+ dualHardness: bs.dualHardness,
+ dualDensity: bs.dualDensity,
+ dualSubTips: bs.dualSubTips,
+ dualSubTipImages: bs.dualSubTipImages,
+ dualSubTipOrder: bs.dualSubTipOrder,
+ dualFlipH: bs.dualFlipH,
+ dualFlipV: bs.dualFlipV,
+ dualSpray: bs.dualSpray,
+ dualIsRibbon: bs.dualIsRibbon,
dualScatter: bs.dualScatter,
dualSurfaceTextureId: bs.dualSurfaceTextureId,
dualGrainDepth: bs.dualGrainDepth,
@@ -2946,6 +4228,366 @@ export function renderCompleteStroke(
const isEraser = tool === 'eraser';
const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(resolvedSettings.color, colorMode);
+ // True two-pass Clip Studio Paint Dual Brush engine:
+ // Pass 1 renders the full Primary Stroke; Pass 2 renders the independent Secondary Stroke
+ // along the exact same `effectivePoints`; Combine Pass modulates Primary RGBA with Secondary density.
+ const dualCfg = resolveDualBrushConfig(resolvedSettings);
+ if (dualCfg) {
+ const primarySettings: BrushSettings = {
+ ...resolvedSettings,
+ dualBrush: false,
+ dualBrushConfig: undefined,
+ };
+ const secInfo = buildSecondaryBrushSettings(primarySettings, dualCfg);
+ const secondaryPoints = scalePointsForSecondaryBrush(
+ effectivePoints,
+ secInfo.sizeRatio,
+ secInfo.settings.size
+ );
+
+ const strokeHardness = isMono ? 1.0 : primarySettings.hardness ?? 1.0;
+ const strokeFlow = isMono ? 1.0 : primarySettings.flow ?? 1.0;
+ const strokeSpacing = primarySettings.spacing ?? 0.08;
+ const effectiveAntiAlias = isMono
+ ? allowGpuForMonochrome && (primarySettings.antiAlias ?? 2) !== 0 && primarySettings.useGpu !== false
+ ? primarySettings.antiAlias ?? 2
+ : 0
+ : primarySettings.antiAlias;
+
+ const effectiveUnderlying = underlyingCanvas || ctx.canvas;
+
+ const primaryIsNatural =
+ !isEraser && !isBgEraser && !isMono && !primarySettings.isTransparentInk && isNaturalPaintBrush(primarySettings);
+ const primaryIsRibbon = isRibbonBrush(primarySettings);
+ const secondaryIsRibbon = isRibbonBrush(secInfo.settings);
+ const dualHasWetEdge =
+ !isMono && !isEraser && !isBgEraser && !resolvedSettings.isTransparentInk && (resolvedSettings.wetEdge ?? 0) > 0.01;
+ const dualHasCustomCombine =
+ !isEraser && !isBgEraser && !resolvedSettings.isTransparentInk && isCustomBrushCombineMode(resolvedSettings.brushCombineMode);
+ const dualStrokeLevelPaper = needsStrokeLevelPaperTexture({
+ paperTextureApplyEachPlot: primarySettings.paperTextureApplyEachPlot,
+ grain: primarySettings.grain,
+ textureDensity: primarySettings.textureDensity,
+ colorMixing: primarySettings.colorMixing,
+ isEraser: isEraser && !isBgEraser,
+ isBgEraser,
+ });
+
+ // Helper to compute initial lookahead tangent angle for a given brush pass
+ const computePassInitAngle = (pts: Point[], opts: BrushRenderOptions): number | undefined => {
+ if (
+ pts.length < 2 ||
+ (opts.angleDynamics !== 'direction' &&
+ opts.angleDynamics !== 'direction-random' &&
+ opts.angleDynamics !== 'initial-direction')
+ ) {
+ return undefined;
+ }
+ const p0 = pts[0];
+ const minChord =
+ opts.angleDynamics === 'initial-direction'
+ ? Math.max(4.0, Math.min(8.0, (opts.size ?? 10) * 0.25))
+ : Math.max(4.0, (opts.size ?? 10) * 0.12);
+ const minChordSq = minChord * minChord;
+ let fallbackAngle: number | undefined = undefined;
+ for (let i = 1; i < pts.length; i++) {
+ const dx = pts[i].x - p0.x;
+ const dy = pts[i].y - p0.y;
+ const dSq = dx * dx + dy * dy;
+ if (dSq > 0.25 && fallbackAngle === undefined) {
+ fallbackAngle = Math.atan2(dy, dx) + ((opts.angle ?? 0) * Math.PI) / 180;
+ }
+ if (dSq >= minChordSq) {
+ return Math.atan2(dy, dx) + ((opts.angle ?? 0) * Math.PI) / 180;
+ }
+ }
+ return fallbackAngle;
+ };
+
+ const emitPointsIntoDabs = (
+ targetCtx: CanvasRenderingContext2D,
+ pts: Point[],
+ passColor: string,
+ emitOpts: BrushRenderOptions,
+ passSpacing: number,
+ passInitAngle: number | undefined,
+ outDabs: GpuDab[]
+ ) => {
+ emitOpts.currentStrokeDist = 0;
+ drawBrushDot(targetCtx, pts[0], passColor, emitOpts, outDabs);
+ if (pts.length === 1) return;
+
+ const dabCounter: { count: number; lastAngle?: number } = {
+ count: 0,
+ lastAngle: passInitAngle,
+ };
+ const minInitDist = emitOpts.tipImage ? 0.15 : 0.12;
+ let accDist = Math.max(minInitDist, Math.max(0.2, pts[0].width) * passSpacing);
+
+ if (pts.length === 2) {
+ const p0 = pts[0];
+ const p1 = pts[1];
+ const { c1, c2 } = centripetalCatmullRomToBezier(p0, p0, p1, p1);
+ drawBrushCubicBezierSegment(targetCtx, p0, c1, c2, p1, passColor, emitOpts, accDist, dabCounter, outDabs);
+ return;
+ }
+
+ const p0 = pts[0];
+ const p1 = pts[1];
+ const p2 = pts[2];
+ const first = centripetalCatmullRomToBezier(p0, p0, p1, p2);
+ accDist = drawBrushCubicBezierSegment(targetCtx, p0, first.c1, first.c2, p1, passColor, emitOpts, accDist, dabCounter, outDabs);
+ emitOpts.currentStrokeDist = (emitOpts.currentStrokeDist ?? 0) + Math.hypot(p1.x - p0.x, p1.y - p0.y);
+
+ for (let i = 2; i < pts.length - 1; i++) {
+ const seg = centripetalCatmullRomToBezier(pts[i - 2], pts[i - 1], pts[i], pts[i + 1]);
+ accDist = drawBrushCubicBezierSegment(targetCtx, pts[i - 1], seg.c1, seg.c2, pts[i], passColor, emitOpts, accDist, dabCounter, outDabs);
+ emitOpts.currentStrokeDist =
+ (emitOpts.currentStrokeDist ?? 0) + Math.hypot(pts[i].x - pts[i - 1].x, pts[i].y - pts[i - 1].y);
+ }
+
+ const n = pts.length;
+ const last = centripetalCatmullRomToBezier(pts[n - 3], pts[n - 2], pts[n - 1], pts[n - 1]);
+ drawBrushCubicBezierSegment(targetCtx, pts[n - 2], last.c1, last.c2, pts[n - 1], passColor, emitOpts, accDist, dabCounter, outDabs);
+ };
+
+ // Fast GPU two-pass FBO path when both passes are WebGL-eligible (non-mixing, non-ribbon, non-natural)
+ if (!primaryIsNatural && !primaryIsRibbon && !secondaryIsRibbon && !dualStrokeLevelPaper && !dualHasWetEdge && !dualHasCustomCombine) {
+ 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
+ );
+ }
+
+ const primaryOpts = buildBrushRenderOptions(primarySettings, {
+ hardness: strokeHardness,
+ flow: strokeFlow,
+ spacing: strokeSpacing,
+ antiAlias: effectiveAntiAlias,
+ underlyingCanvas: effectiveUnderlying,
+ isEraser: isEraser && !isBgEraser,
+ isBgEraser,
+ alphaLocked,
+ isTransparentInk: Boolean(primarySettings.isTransparentInk),
+ totalLength: totalLen,
+ exitSpeed,
+ });
+ primaryOpts.initialAngleRad = computePassInitAngle(effectivePoints, primaryOpts);
+
+ const secSpacing = secInfo.settings.spacing ?? 0.1;
+ const secondaryOpts = buildBrushRenderOptions(secInfo.settings, {
+ hardness: secInfo.settings.hardness ?? 1.0,
+ flow: secInfo.settings.flow ?? 1.0,
+ spacing: secSpacing,
+ antiAlias: effectiveAntiAlias,
+ isEraser: false,
+ isBgEraser: false,
+ alphaLocked: false,
+ isTransparentInk: false,
+ totalLength: totalLen,
+ exitSpeed,
+ });
+ secondaryOpts.initialAngleRad = computePassInitAngle(secondaryPoints, secondaryOpts);
+
+ if (canUseWebGlForBrush(primaryOpts) && canUseWebGlForBrush(secondaryOpts)) {
+ const primaryDabs: GpuDab[] = [];
+ const secondaryDabs: GpuDab[] = [];
+ emitPointsIntoDabs(
+ ctx,
+ effectivePoints,
+ strokeColor,
+ primaryOpts,
+ strokeSpacing,
+ primaryOpts.initialAngleRad,
+ primaryDabs
+ );
+ emitPointsIntoDabs(
+ ctx,
+ secondaryPoints,
+ '#ffffff',
+ secondaryOpts,
+ secSpacing,
+ secondaryOpts.initialAngleRad,
+ secondaryDabs
+ );
+
+ const gpu = WebGlBrushEngine.getInstance();
+ const docW = effectiveUnderlying?.width || ctx.canvas?.width || 1024;
+ const docH = effectiveUnderlying?.height || ctx.canvas?.height || 1024;
+ const primGpuSettings = buildGpuBrushSettingsFromOptions(strokeColor, primaryOpts);
+ const secGpuSettings = buildGpuBrushSettingsFromOptions('#ffffff', secondaryOpts);
+ if (
+ gpu.renderDualBrushDabsToContext(
+ ctx,
+ primaryDabs,
+ primGpuSettings,
+ secondaryDabs,
+ secGpuSettings,
+ dualCfg.compositeMode,
+ tool,
+ docW,
+ docH,
+ effectiveUnderlying
+ )
+ ) {
+ return;
+ }
+ }
+ }
+
+ // Unified two-pass isolated surface path:
+ // Handles CPU fallback, colorMixing (including SpatialTipMixer), Ribbon, NaturalPaint,
+ // AA=0 monochrome, per-stroke paper texture, or WebGL unavailable.
+ if (typeof document !== 'undefined') {
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+ let maxW = Math.max(primarySettings.size || 10, secInfo.settings.size || 10);
+ for (let i = 0; i < effectivePoints.length; i++) {
+ const p = effectivePoints[i];
+ if (p.x < minX) minX = p.x;
+ if (p.y < minY) minY = p.y;
+ if (p.x > maxX) maxX = p.x;
+ if (p.y > maxY) maxY = p.y;
+ if (p.width > maxW) maxW = p.width;
+ const sw = p.width * secInfo.sizeRatio;
+ if (sw > maxW) maxW = sw;
+ }
+ const maxScatter = Math.max(
+ primarySettings.dynamics?.scatter ?? 0,
+ dualCfg.scatter ?? 0
+ );
+ const sprayPad = Math.max(
+ primarySettings.spray?.enabled ? (primarySettings.spray.size || 0) : 0,
+ secInfo.settings.spray?.enabled ? (secInfo.settings.spray.size || 0) : 0
+ );
+ const pad = Math.ceil(maxW * (1.5 + maxScatter) + sprayPad + 12);
+ const bx = Math.floor(minX - pad);
+ const by = Math.floor(minY - pad);
+ const bw = Math.max(1, Math.ceil(maxX + pad) - bx);
+ const bh = Math.max(1, Math.ceil(maxY + pad) - by);
+
+ if (bw <= 4096 && bh <= 4096) {
+ const primarySurface = document.createElement('canvas');
+ primarySurface.width = bw;
+ primarySurface.height = bh;
+ const pCtx = primarySurface.getContext('2d');
+
+ const secondarySurface = document.createElement('canvas');
+ secondarySurface.width = bw;
+ secondarySurface.height = bh;
+ const sCtx = secondarySurface.getContext('2d');
+
+ if (
+ pCtx &&
+ sCtx &&
+ typeof pCtx.getImageData === 'function' &&
+ typeof pCtx.putImageData === 'function' &&
+ typeof sCtx.getImageData === 'function'
+ ) {
+ // Pass 1 (Primary): render full primary stroke (including colorMixing / SpatialTipMixer / ribbon / taper)
+ const pass1Settings: BrushSettings = {
+ ...primarySettings,
+ opacity: 1.0,
+ postCorrection: 0,
+ isTransparentInk: false,
+ wetEdge: 0,
+ color: isEraser && !isBgEraser ? '#000000' : primarySettings.color,
+ ...(dualStrokeLevelPaper
+ ? { grain: 0, textureDensity: 0, paperTextureApplyEachPlot: undefined }
+ : {}),
+ };
+ pCtx.save();
+ pCtx.translate(-bx, -by);
+ renderCompleteStroke(
+ pCtx,
+ effectivePoints,
+ pass1Settings,
+ isEraser && !isBgEraser ? 'brush' : tool,
+ colorMode,
+ isBgEraser,
+ effectiveUnderlying,
+ false,
+ explicitSampler,
+ allowGpuForMonochrome,
+ exitSpeed
+ );
+ pCtx.restore();
+
+ // Pass 2 (Secondary): render independent secondary brush along exact same trajectory
+ sCtx.save();
+ sCtx.translate(-bx, -by);
+ renderCompleteStroke(
+ sCtx,
+ secondaryPoints,
+ {
+ ...secInfo.settings,
+ opacity: 1.0,
+ postCorrection: 0,
+ },
+ 'brush',
+ 'color',
+ false,
+ undefined,
+ false,
+ undefined,
+ allowGpuForMonochrome,
+ exitSpeed
+ );
+ sCtx.restore();
+
+ // Combine Pass: exact CSP Dual Brush alpha modulation across the tight dirty rect
+ const primaryImg = pCtx.getImageData(0, 0, bw, bh);
+ const secondaryImg = sCtx.getImageData(0, 0, bw, bh);
+ combineDualBrushImageData(
+ primaryImg.data,
+ secondaryImg.data,
+ primaryImg.data,
+ dualCfg.compositeMode
+ );
+
+ if (dualStrokeLevelPaper) {
+ applyStrokePaperTextureToImageData(primaryImg, bx, by, primarySettings, 1.0);
+ }
+
+ if (dualHasWetEdge) {
+ applyCspWatercolorEdge(
+ primaryImg,
+ resolvedSettings.wetEdge ?? 0,
+ resolvedSettings.wetEdgeRadius ?? 3.0,
+ normalizeWetEdgePower01(resolvedSettings.wetEdgeAlphaPower, 0.25),
+ normalizeWetEdgePower01(resolvedSettings.wetEdgeValuePower, 0.15)
+ );
+ }
+
+ pCtx.putImageData(primaryImg, 0, 0);
+
+ const baseCompositeOp: 'source-over' | 'destination-out' | 'source-atop' = isBgEraser
+ ? 'source-over'
+ : isEraser || resolvedSettings.isTransparentInk || resolvedSettings.brushCombineMode === 'clear'
+ ? 'destination-out'
+ : alphaLocked
+ ? 'source-atop'
+ : 'source-over';
+ compositeIsolatedStrokeToCtx(
+ ctx,
+ primarySurface,
+ primaryImg,
+ bx,
+ by,
+ Math.max(0, Math.min(1, resolvedSettings.opacity ?? 1.0)),
+ baseCompositeOp,
+ dualHasCustomCombine ? resolvedSettings.brushCombineMode : undefined
+ );
+ return;
+ }
+ }
+ }
+ }
+
// Route Natural Paint / Bristle Ribbon / Impasto brushes through the dedicated Natural Paint core
if (!isEraser && !isBgEraser && !isMono && !resolvedSettings.isTransparentInk && isNaturalPaintBrush(resolvedSettings)) {
const effectiveUnderlying = underlyingCanvas || ctx.canvas;
@@ -2967,6 +4609,22 @@ export function renderCompleteStroke(
return;
}
+ // Route Clip Studio Paint Ribbon brushes (`BrushRibbon = 1`, non-NaturalPaint, non-Spray)
+ if (isRibbonBrush(resolvedSettings)) {
+ renderCompleteRibbonStroke(
+ ctx,
+ effectivePoints,
+ resolvedSettings,
+ tool,
+ colorMode,
+ isBgEraser,
+ alphaLocked,
+ allowGpuForMonochrome,
+ exitSpeed
+ );
+ return;
+ }
+
const strokeHardness = isMono ? 1.0 : resolvedSettings.hardness ?? 1.0;
const strokeFlow = isMono ? 1.0 : resolvedSettings.flow ?? 1.0;
const strokeSpacing = resolvedSettings.spacing ?? 0.08;
@@ -2977,6 +4635,26 @@ export function renderCompleteStroke(
: resolvedSettings.antiAlias;
const effectiveUnderlying = underlyingCanvas || ctx.canvas;
+ let effectiveStrokeColor = strokeColor;
+ let strokeJitterColor: { r: number; g: number; b: number; hex: string } | undefined = undefined;
+ if (
+ !isEraser &&
+ !isBgEraser &&
+ resolvedSettings.dynamics?.colorJitterEnabled &&
+ resolvedSettings.dynamics?.colorJitterPerStroke
+ ) {
+ const prim0 = parseColorToRgb(strokeColor);
+ const sec0 = parseColorToRgb(resolvedSettings.secondaryColor || '#ffffff');
+ let salt = 200;
+ strokeJitterColor = applyColorDynamics(
+ { r: prim0.r / 255, g: prim0.g / 255, b: prim0.b / 255 },
+ { r: sec0.r / 255, g: sec0.g / 255, b: sec0.b / 255 },
+ resolvedSettings.dynamics,
+ () => dabHashFloat(effectivePoints[0].x, effectivePoints[0].y, 0, salt++)
+ );
+ effectiveStrokeColor = strokeJitterColor.hex;
+ }
+
const options = buildBrushRenderOptions(resolvedSettings, {
hardness: strokeHardness,
flow: strokeFlow,
@@ -2986,11 +4664,12 @@ export function renderCompleteStroke(
sampler: resolvedSettings.colorMixing
? explicitSampler || (effectiveUnderlying ? new LayerPixelSampler(effectiveUnderlying) : undefined)
: undefined,
- reservoir: resolvedSettings.colorMixing && !isEraser && !isBgEraser ? new PaintReservoir(strokeColor) : undefined,
+ reservoir: resolvedSettings.colorMixing && !isEraser && !isBgEraser ? new PaintReservoir(effectiveStrokeColor) : undefined,
isEraser: isEraser && !isBgEraser,
isBgEraser,
alphaLocked,
isTransparentInk: Boolean(resolvedSettings.isTransparentInk),
+ strokeJitterColor,
});
let totalLen = 0;
@@ -3004,10 +4683,15 @@ export function renderCompleteStroke(
let initAngleRad: number | undefined = undefined;
if (
effectivePoints.length >= 2 &&
- (options.angleDynamics === 'direction' || options.angleDynamics === 'direction-random')
+ (options.angleDynamics === 'direction' ||
+ options.angleDynamics === 'direction-random' ||
+ options.angleDynamics === 'initial-direction')
) {
const p0 = effectivePoints[0];
- const minChord = Math.max(4.0, (options.size ?? 10) * 0.12);
+ const minChord =
+ options.angleDynamics === 'initial-direction'
+ ? Math.max(4.0, Math.min(8.0, (options.size ?? 10) * 0.25))
+ : Math.max(4.0, (options.size ?? 10) * 0.12);
const minChordSq = minChord * minChord;
let fallbackAngle: number | undefined = undefined;
for (let i = 1; i < effectivePoints.length; i++) {
@@ -3028,23 +4712,45 @@ export function renderCompleteStroke(
}
options.initialAngleRad = initAngleRad;
- const emitStroke = (batchGpuDabs: GpuDab[] | undefined) => {
- options.currentStrokeDist = 0;
- drawBrushDot(ctx, effectivePoints[0], strokeColor, options, batchGpuDabs);
+ const strokeLevelPaper = needsStrokeLevelPaperTexture(options);
+ const hasWetEdge =
+ !isMono && !isEraser && !isBgEraser && !resolvedSettings.isTransparentInk && (resolvedSettings.wetEdge ?? 0) > 0.01;
+ const needsCompareIsolation =
+ options.blendTipsMode === 'compare' && !isEraser && !isBgEraser && !options.isTransparentInk;
+ const hasCustomCombine =
+ !isEraser && !isBgEraser && !options.isTransparentInk && isCustomBrushCombineMode(resolvedSettings.brushCombineMode);
+
+ const emitStroke = (
+ targetCtx: CanvasRenderingContext2D,
+ emitOpts: BrushRenderOptions,
+ batchGpuDabs: GpuDab[] | undefined
+ ) => {
+ emitOpts.currentStrokeDist = 0;
+ drawBrushDot(targetCtx, effectivePoints[0], effectiveStrokeColor, emitOpts, batchGpuDabs);
if (effectivePoints.length === 1) return;
- const dabCounter: { count: number; lastAngle?: number } = {
+ const dabCounter: {
+ count: number;
+ lastAngle?: number;
+ lastStepDist?: number;
+ lockedInitialAngle?: number;
+ initOriginX?: number;
+ initOriginY?: number;
+ } = {
count: 0,
lastAngle: initAngleRad,
+ lockedInitialAngle: emitOpts.angleDynamics === 'initial-direction' ? initAngleRad : undefined,
+ initOriginX: effectivePoints[0].x,
+ initOriginY: effectivePoints[0].y,
};
- const minInitDist = options.tipImage ? 0.15 : 0.12;
+ const minInitDist = emitOpts.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);
+ drawBrushCubicBezierSegment(targetCtx, p0, c1, c2, p1, effectiveStrokeColor, emitOpts, accDist, dabCounter, batchGpuDabs);
return;
}
@@ -3052,8 +4758,8 @@ export function renderCompleteStroke(
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);
+ accDist = drawBrushCubicBezierSegment(targetCtx, p0, first.c1, first.c2, p1, effectiveStrokeColor, emitOpts, accDist, dabCounter, batchGpuDabs);
+ emitOpts.currentStrokeDist = (emitOpts.currentStrokeDist ?? 0) + Math.hypot(p1.x - p0.x, p1.y - p0.y);
for (let i = 2; i < effectivePoints.length - 1; i++) {
const seg = centripetalCatmullRomToBezier(
@@ -3063,46 +4769,225 @@ export function renderCompleteStroke(
effectivePoints[i + 1]
);
accDist = drawBrushCubicBezierSegment(
- ctx,
+ targetCtx,
effectivePoints[i - 1],
seg.c1,
seg.c2,
effectivePoints[i],
- strokeColor,
- options,
+ effectiveStrokeColor,
+ emitOpts,
accDist,
dabCounter,
batchGpuDabs
);
- options.currentStrokeDist =
- (options.currentStrokeDist ?? 0) +
+ emitOpts.currentStrokeDist =
+ (emitOpts.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,
+ targetCtx,
effectivePoints[n - 2],
last.c1,
last.c2,
effectivePoints[n - 1],
- strokeColor,
- options,
+ effectiveStrokeColor,
+ emitOpts,
accDist,
dabCounter,
batchGpuDabs
);
};
- if (canUseWebGlForBrush(options)) {
- const batchGpuDabs: GpuDab[] = [];
- emitStroke(batchGpuDabs);
- if (flushGpuDabs(ctx, batchGpuDabs, strokeColor, options)) {
- return;
+ const renderIntoContext = (targetCtx: CanvasRenderingContext2D, emitOpts: BrushRenderOptions) => {
+ if (canUseWebGlForBrush(emitOpts)) {
+ const batchGpuDabs: GpuDab[] = [];
+ emitStroke(targetCtx, emitOpts, batchGpuDabs);
+ if (flushGpuDabs(targetCtx, batchGpuDabs, effectiveStrokeColor, emitOpts)) {
+ return;
+ }
+ }
+ // Single general CPU Canvas2D fallback (WebGL unavailable/lost, AA=0, CPU colorMixing, or multi-subTip)
+ emitStroke(targetCtx, emitOpts, undefined);
+ };
+
+ // Isolated stroke accumulation surface for:
+ // - CSP TextureForPlot=0 (per-stroke paper texture)
+ // - CSP Watercolor Edge (works both with and without colorMixing!)
+ // - CSP Compare Density (stroke-level non-accumulating alpha before compositing onto existing pixels)
+ // - CSP BrushCombineMode (all 26+ layer-level brush blend modes including behind/clear/multiply/add-glow)
+ const needsIsolatedSurface = strokeLevelPaper || hasWetEdge || needsCompareIsolation || hasCustomCombine;
+ if (needsIsolatedSurface && typeof document !== 'undefined') {
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+ let maxW = options.size ?? 10;
+ for (let i = 0; i < effectivePoints.length; i++) {
+ const p = effectivePoints[i];
+ if (p.x < minX) minX = p.x;
+ if (p.y < minY) minY = p.y;
+ if (p.x > maxX) maxX = p.x;
+ if (p.y > maxY) maxY = p.y;
+ if (p.width > maxW) maxW = p.width;
+ }
+ const scatterPad = Math.max(0, options.dynamics?.scatter ?? 0) * maxW;
+ const wetPad = hasWetEdge ? Math.ceil((resolvedSettings.wetEdgeRadius ?? 3.0) * 2) + 4 : 0;
+ const pad = Math.ceil(maxW * 1.25 + scatterPad + wetPad + 8);
+ const bx = Math.floor(minX - pad);
+ const by = Math.floor(minY - pad);
+ const bw = Math.max(1, Math.ceil(maxX + pad) - bx);
+ const bh = Math.max(1, Math.ceil(maxY + pad) - by);
+ if (bw <= 4096 && bh <= 4096) {
+ const scratch = document.createElement('canvas');
+ scratch.width = bw;
+ scratch.height = bh;
+ const sCtx = scratch.getContext('2d');
+ if (sCtx && typeof sCtx.getImageData === 'function' && typeof sCtx.putImageData === 'function') {
+ const isolatedOpts: BrushRenderOptions = {
+ ...options,
+ skipPerDabPaperGrain: strokeLevelPaper ? true : options.skipPerDabPaperGrain,
+ wetEdge: 0,
+ alphaLocked: false,
+ isTransparentInk: false,
+ brushCombineMode: undefined,
+ };
+ sCtx.save();
+ sCtx.translate(-bx, -by);
+ renderIntoContext(sCtx, isolatedOpts);
+ sCtx.restore();
+
+ const imgData = sCtx.getImageData(0, 0, bw, bh);
+ if (strokeLevelPaper) {
+ applyStrokePaperTextureToImageData(imgData, bx, by, options, 1.0);
+ }
+ if (hasWetEdge) {
+ applyCspWatercolorEdge(
+ imgData,
+ resolvedSettings.wetEdge ?? 0,
+ resolvedSettings.wetEdgeRadius ?? 3.0,
+ normalizeWetEdgePower01(resolvedSettings.wetEdgeAlphaPower, 0.25),
+ normalizeWetEdgePower01(resolvedSettings.wetEdgeValuePower, 0.15)
+ );
+ }
+ sCtx.putImageData(imgData, 0, 0);
+
+ const baseCompositeOp: 'source-over' | 'destination-out' | 'source-atop' =
+ options.isTransparentInk || resolvedSettings.brushCombineMode === 'clear'
+ ? 'destination-out'
+ : alphaLocked
+ ? 'source-atop'
+ : 'source-over';
+ compositeIsolatedStrokeToCtx(
+ ctx,
+ scratch,
+ imgData,
+ bx,
+ by,
+ Math.max(0, Math.min(1, options.opacity ?? 1.0)),
+ baseCompositeOp,
+ hasCustomCombine ? resolvedSettings.brushCombineMode : undefined
+ );
+ return;
+ }
+ }
+ }
+
+ renderIntoContext(ctx, options);
+}
+
+function compositeIsolatedStrokeToCtx(
+ ctx: CanvasRenderingContext2D,
+ strokeCanvas: HTMLCanvasElement,
+ strokeImg: { data: Uint8ClampedArray; width: number; height: number },
+ bx: number,
+ by: number,
+ opacity: number,
+ compositeOp: 'source-over' | 'destination-out' | 'source-atop',
+ brushCombineMode?: CspBrushCombineMode
+): void {
+ const hasCustom = isCustomBrushCombineMode(brushCombineMode);
+ if (
+ hasCustom &&
+ ctx.canvas &&
+ ctx.canvas.width > 0 &&
+ ctx.canvas.height > 0 &&
+ typeof ctx.getImageData === 'function' &&
+ typeof ctx.putImageData === 'function'
+ ) {
+ const m =
+ typeof ctx.getTransform === 'function'
+ ? ctx.getTransform()
+ : { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };
+ const isTranslationOnly =
+ Math.abs(m.a - 1) < 1e-4 &&
+ Math.abs(m.d - 1) < 1e-4 &&
+ Math.abs(m.b) < 1e-4 &&
+ Math.abs(m.c) < 1e-4;
+ if (isTranslationOnly) {
+ const dx0 = Math.round(bx + m.e);
+ const dy0 = Math.round(by + m.f);
+ const rx0 = Math.max(0, dx0);
+ const ry0 = Math.max(0, dy0);
+ const rx1 = Math.min(ctx.canvas.width, dx0 + strokeImg.width);
+ const ry1 = Math.min(ctx.canvas.height, dy0 + strokeImg.height);
+ const rw = rx1 - rx0;
+ const rh = ry1 - ry0;
+ if (rw > 0 && rh > 0) {
+ const dstImg = ctx.getImageData(rx0, ry0, rw, rh);
+ const dst = dstImg.data;
+ const src = strokeImg.data;
+ const pxOut: [number, number, number, number] = [0, 0, 0, 0];
+ const fullOp = opacity >= 0.999;
+ for (let y = 0; y < rh; y++) {
+ const sy = ry0 - dy0 + y;
+ const sRow = sy * strokeImg.width;
+ const dRow = y * rw;
+ for (let x = 0; x < rw; x++) {
+ const sx = rx0 - dx0 + x;
+ const sOff = (sRow + sx) << 2;
+ const sa = src[sOff + 3];
+ if (sa === 0) continue;
+ const effA = fullOp ? sa : Math.round(sa * opacity);
+ if (effA <= 0) continue;
+ const dOff = (dRow + x) << 2;
+ compositeBrushPixelInto(
+ dst[dOff],
+ dst[dOff + 1],
+ dst[dOff + 2],
+ dst[dOff + 3],
+ src[sOff],
+ src[sOff + 1],
+ src[sOff + 2],
+ effA,
+ compositeOp,
+ brushCombineMode,
+ pxOut
+ );
+ dst[dOff] = pxOut[0];
+ dst[dOff + 1] = pxOut[1];
+ dst[dOff + 2] = pxOut[2];
+ dst[dOff + 3] = pxOut[3];
+ }
+ }
+ ctx.putImageData(dstImg, rx0, ry0);
+ return;
+ }
}
}
- // Single general CPU Canvas2D fallback (WebGL unavailable/lost, AA=0, CPU colorMixing, or multi-subTip)
- emitStroke(undefined);
+ const prevOp = ctx.globalCompositeOperation;
+ const prevAlpha = ctx.globalAlpha;
+ ctx.globalCompositeOperation =
+ brushCombineMode === 'behind'
+ ? 'destination-over'
+ : brushCombineMode === 'clear'
+ ? 'destination-out'
+ : compositeOp;
+ ctx.globalAlpha = opacity;
+ ctx.drawImage(strokeCanvas, bx, by);
+ ctx.globalAlpha = prevAlpha;
+ ctx.globalCompositeOperation = prevOp;
}
diff --git a/src/engine/DualBrushEngine.ts b/src/engine/DualBrushEngine.ts
new file mode 100644
index 0000000..d6b52d6
--- /dev/null
+++ b/src/engine/DualBrushEngine.ts
@@ -0,0 +1,439 @@
+/**
+ * DualBrushEngine.ts
+ * Clip Studio Paint Dual Brush configuration resolver, secondary pass builder,
+ * and exact CPU/GPU-matched Dual Brush combine mathematics.
+ *
+ * Implements CSP's true two-pass Dual Brush model:
+ * Pass 1 (Primary): Full primary stroke (including colorMixing / SpatialTipMixer, subTips, spray, ribbon, taper)
+ * Pass 2 (Secondary): Independent secondary brush along the same trajectory with its own size, spacing,
+ * thickness, angle/angleDynamics, flips, hardness, density, spray, subTips, or ribbon
+ * Combine Pass: Modulates primary RGBA with secondary density a2 using DualBrushCompositeMode.
+ */
+
+import {
+ BrushSettings,
+ CspDualBrushConfig,
+ DEFAULT_BRUSH_DYNAMICS,
+ DualBrushCompositeMode,
+ Point,
+} from '../types/editor';
+import type { CubicBezierSegment } from './SplineGenerator';
+
+export const DUAL_BRUSH_COMPOSITE_MODES: readonly DualBrushCompositeMode[] = [
+ 'multiply',
+ 'darken',
+ 'subtract',
+ 'compare-density',
+ 'linear-burn',
+ 'color-burn',
+ 'height',
+ 'overlay',
+ 'screen',
+ 'lighten',
+ 'hard-mix',
+ 'normal',
+] as const;
+
+const DUAL_MODE_SET = new Set<string>(DUAL_BRUSH_COMPOSITE_MODES);
+
+export function normalizeDualBrushCompositeMode(mode?: string): DualBrushCompositeMode {
+ if (!mode || typeof mode !== 'string') return 'multiply';
+ const cleaned = mode.trim().toLowerCase();
+ if (DUAL_MODE_SET.has(cleaned)) {
+ return cleaned as DualBrushCompositeMode;
+ }
+ if (cleaned === 'compare' || cleaned === 'compare_density') return 'compare-density';
+ if (cleaned === 'linear_burn' || cleaned === 'linearburn') return 'linear-burn';
+ if (cleaned === 'color_burn' || cleaned === 'colorburn') return 'color-burn';
+ if (cleaned === 'hard_mix' || cleaned === 'hardmix') return 'hard-mix';
+ if (cleaned === 'darker-color') return 'darken';
+ if (cleaned === 'lighter-color') return 'lighten';
+ if (cleaned === 'add' || cleaned === 'add-glow' || cleaned === 'color-dodge' || cleaned === 'color-dodge-glow') {
+ return 'screen';
+ }
+ return 'multiply';
+}
+
+/**
+ * Maps DualBrushCompositeMode to integer enum matching WebGlBrushEngine's
+ * DUAL_COMBINE_FRAGMENT_SHADER_SRC `u_combineMode` uniform.
+ */
+export function dualBrushCompositeModeToIndex(mode: DualBrushCompositeMode): number {
+ switch (mode) {
+ case 'multiply':
+ return 0;
+ case 'darken':
+ return 1;
+ case 'subtract':
+ return 2;
+ case 'compare-density':
+ return 3;
+ case 'linear-burn':
+ return 4;
+ case 'color-burn':
+ return 5;
+ case 'height':
+ return 6;
+ case 'overlay':
+ return 7;
+ case 'screen':
+ return 8;
+ case 'lighten':
+ return 9;
+ case 'hard-mix':
+ return 10;
+ case 'normal':
+ return 11;
+ default:
+ return 0;
+ }
+}
+
+/**
+ * Scalar CSP Dual Brush density combination matching the WebGL combine shader bit-for-bit.
+ * `a1` is primary stroke straight alpha in [0, 1]; `a2` is secondary stroke density in [0, 1].
+ */
+export function combineDualBrushAlpha(
+ a1: number,
+ a2: number,
+ mode: DualBrushCompositeMode
+): number {
+ if (a1 <= 1e-4) return 0;
+ const p1 = a1 >= 1 ? 1 : a1;
+ const p2 = a2 <= 0 ? 0 : a2 >= 1 ? 1 : a2;
+
+ switch (mode) {
+ case 'multiply':
+ return p1 * p2;
+ case 'darken':
+ return p1 < p2 ? p1 : p2;
+ case 'subtract': {
+ const v = p1 - p2;
+ return v > 0 ? v : 0;
+ }
+ case 'compare-density': {
+ const sil = p1 * 4.0 < 1.0 ? p1 * 4.0 : 1.0;
+ const eff2 = p2 * sil;
+ return p1 > eff2 ? p1 : eff2;
+ }
+ case 'linear-burn': {
+ const v = p1 + p2 - 1.0;
+ return v > 0 ? v : 0;
+ }
+ case 'color-burn': {
+ if (p2 <= 1e-4) return 0;
+ const v = 1.0 - (1.0 - p1) / p2;
+ return v > 0 ? v : 0;
+ }
+ case 'height': {
+ const h = p1 + p2 - 1.0;
+ if (h <= 0) return 0;
+ if (h >= 0.25) return 1.0;
+ const t = h * 4.0;
+ return t * t * (3.0 - 2.0 * t);
+ }
+ case 'overlay':
+ return p1 < 0.5 ? 2.0 * p1 * p2 : 1.0 - 2.0 * (1.0 - p1) * (1.0 - p2);
+ case 'screen': {
+ const sil = p1 * 4.0 < 1.0 ? p1 * 4.0 : 1.0;
+ const eff2 = p2 * sil;
+ return p1 + eff2 - p1 * eff2;
+ }
+ case 'lighten': {
+ const sil = p1 * 4.0 < 1.0 ? p1 * 4.0 : 1.0;
+ const eff2 = p2 * sil;
+ return p1 > eff2 ? p1 : eff2;
+ }
+ case 'hard-mix':
+ return p1 + p2 >= 1.0 ? 1.0 : 0.0;
+ case 'normal': {
+ const sil = p1 * 4.0 < 1.0 ? p1 * 4.0 : 1.0;
+ const eff2 = p2 * sil;
+ return p1 + eff2 * (1.0 - p1);
+ }
+ default:
+ return p1 * p2;
+ }
+}
+
+/**
+ * Allocation-free tight CPU pixel combine loop.
+ * Works both in-place (`outData === primaryData`) and into a separate output buffer.
+ * `primaryData` contains straight RGBA from Pass 1; `secondaryData` contains Pass 2 density in alpha.
+ */
+export function combineDualBrushImageData(
+ primaryData: Uint8ClampedArray,
+ secondaryData: Uint8ClampedArray,
+ outData: Uint8ClampedArray,
+ mode: DualBrushCompositeMode
+): void {
+ const len = Math.min(primaryData.length, secondaryData.length, outData.length);
+ const inv255 = 1 / 255;
+
+ for (let i = 0; i < len; i += 4) {
+ const a1Byte = primaryData[i + 3];
+ if (a1Byte === 0) {
+ outData[i] = 0;
+ outData[i + 1] = 0;
+ outData[i + 2] = 0;
+ outData[i + 3] = 0;
+ continue;
+ }
+
+ const a1 = a1Byte * inv255;
+ const a2 = secondaryData[i + 3] * inv255;
+ const outA = combineDualBrushAlpha(a1, a2, mode);
+ const outAByte = outA <= 0 ? 0 : outA >= 1 ? 255 : (outA * 255 + 0.5) | 0;
+
+ if (outAByte === 0) {
+ outData[i] = 0;
+ outData[i + 1] = 0;
+ outData[i + 2] = 0;
+ outData[i + 3] = 0;
+ } else {
+ outData[i] = primaryData[i];
+ outData[i + 1] = primaryData[i + 1];
+ outData[i + 2] = primaryData[i + 2];
+ outData[i + 3] = outAByte;
+ }
+ }
+}
+
+export interface DualBrushSourceFields {
+ size?: number;
+ dualBrush?: boolean;
+ dualBrushConfig?: CspDualBrushConfig;
+ dualBrushCompositeMode?: DualBrushCompositeMode | string;
+ dualSize?: number;
+ dualLinkSize?: boolean;
+ dualScale?: number;
+ dualSpacing?: number;
+ dualScatter?: number;
+ dualThickness?: number;
+ dualThicknessVertical?: boolean;
+ dualAngle?: number;
+ dualAngleDynamics?: CspDualBrushConfig['angleDynamics'];
+ dualAngleSensor?: CspDualBrushConfig['angleSensor'];
+ dualHardness?: number;
+ dualDensity?: number;
+ dualSubTips?: CspDualBrushConfig['subTips'];
+ dualSubTipImages?: HTMLImageElement[];
+ dualSubTipOrder?: CspDualBrushConfig['subTipOrder'];
+ dualFlipH?: CspDualBrushConfig['flipH'];
+ dualFlipV?: CspDualBrushConfig['flipV'];
+ dualSpray?: CspDualBrushConfig['spray'];
+ dualIsRibbon?: boolean;
+ dualTipDataUrl?: string;
+ dualTipImage?: HTMLImageElement;
+}
+
+/**
+ * Resolves a unified `CspDualBrushConfig` from either `dualBrushConfig` or legacy flat fields.
+ * Returns `null` when Dual Brush is inactive.
+ */
+export function resolveDualBrushConfig(
+ src?: DualBrushSourceFields | null
+): CspDualBrushConfig | null {
+ if (!src) return null;
+ const cfg = src.dualBrushConfig;
+ const enabled = cfg ? cfg.enabled : Boolean(src.dualBrush);
+ if (!enabled) return null;
+
+ const compositeMode = normalizeDualBrushCompositeMode(
+ cfg?.compositeMode ?? src.dualBrushCompositeMode
+ );
+ const linkSizeWithMain = cfg?.linkSizeWithMain ?? src.dualLinkSize;
+ const size = cfg?.size ?? src.dualSize;
+ const sizeRatio =
+ cfg?.sizeRatio ??
+ (src.dualScale !== undefined && src.dualScale > 0
+ ? src.dualScale
+ : undefined);
+
+ return {
+ enabled: true,
+ compositeMode,
+ linkSizeWithMain,
+ size,
+ sizeRatio,
+ spacing: cfg?.spacing ?? src.dualSpacing,
+ scatter: cfg?.scatter ?? src.dualScatter,
+ thickness: cfg?.thickness ?? src.dualThickness,
+ thicknessVertical: cfg?.thicknessVertical ?? src.dualThicknessVertical,
+ hardness: cfg?.hardness ?? src.dualHardness,
+ density: cfg?.density ?? src.dualDensity,
+ angle: cfg?.angle ?? src.dualAngle,
+ angleDynamics: cfg?.angleDynamics ?? src.dualAngleDynamics,
+ angleSensor: cfg?.angleSensor ?? src.dualAngleSensor,
+ flipH: cfg?.flipH ?? src.dualFlipH,
+ flipV: cfg?.flipV ?? src.dualFlipV,
+ spray: cfg?.spray ?? src.dualSpray,
+ tipDataUrl: cfg?.tipDataUrl ?? src.dualTipDataUrl,
+ tipImage: cfg?.tipImage ?? src.dualTipImage,
+ subTips: cfg?.subTips ?? src.dualSubTips,
+ subTipImages: cfg?.subTipImages ?? src.dualSubTipImages,
+ subTipOrder: cfg?.subTipOrder ?? src.dualSubTipOrder,
+ isRibbon: cfg?.isRibbon ?? src.dualIsRibbon,
+ };
+}
+
+/**
+ * Computes the effective secondary brush diameter in document pixels.
+ */
+export function computeSecondaryBrushSize(
+ primarySize: number,
+ cfg: CspDualBrushConfig,
+ flatScale?: number
+): number {
+ const safeMain = Math.max(0.5, primarySize || 10);
+ const scale = flatScale !== undefined && flatScale > 0 ? flatScale : 1.0;
+
+ if (cfg.linkSizeWithMain) {
+ if (cfg.sizeRatio !== undefined && cfg.sizeRatio > 0) {
+ // When sizeRatio came from flatScale fallback, avoid applying flatScale twice
+ const extraScale = cfg.size !== undefined ? scale : 1.0;
+ return Math.max(0.5, safeMain * cfg.sizeRatio * extraScale);
+ }
+ return Math.max(0.5, safeMain * scale);
+ }
+
+ if (cfg.size !== undefined && cfg.size > 0) {
+ return Math.max(0.5, cfg.size * scale);
+ }
+
+ if (cfg.sizeRatio !== undefined && cfg.sizeRatio > 0) {
+ return Math.max(0.5, safeMain * cfg.sizeRatio);
+ }
+
+ return Math.max(0.5, safeMain * scale);
+}
+
+/**
+ * Constructs a standalone secondary `BrushSettings` for Pass 2 from primary settings + `CspDualBrushConfig`.
+ */
+export function buildSecondaryBrushSettings(
+ primaryBs: BrushSettings,
+ cfg: CspDualBrushConfig
+): { settings: BrushSettings; sizeRatio: number } {
+ const mainSize = Math.max(0.5, primaryBs.size || 10);
+ const secSize = computeSecondaryBrushSize(mainSize, cfg, primaryBs.dualScale);
+ const sizeRatio = secSize / mainSize;
+
+ const secondaryTipImage =
+ cfg.tipImage ?? (cfg.subTipImages && cfg.subTipImages.length > 0 ? cfg.subTipImages[0] : undefined);
+ const secondaryTipDataUrl =
+ cfg.tipDataUrl ?? (cfg.subTips && cfg.subTips.length > 0 ? cfg.subTips[0].dataUrl : undefined);
+ const scatter = cfg.scatter ?? 0;
+
+ const settings: BrushSettings = {
+ size: secSize,
+ minSizeFactor: primaryBs.minSizeFactor,
+ color: '#ffffff',
+ secondaryColor: '#ffffff',
+ opacity: 1.0,
+ flow: cfg.density ?? 1.0,
+ brushDensity: cfg.density ?? 1.0,
+ adjustDensityByGap: false,
+ blendTipsMode: 'normal',
+ spacing: Math.max(0.003, Math.min(2.0, cfg.spacing ?? primaryBs.spacing ?? 0.1)),
+ usePressure: primaryBs.usePressure,
+ useTilt: false,
+ useVelocity: primaryBs.useVelocity,
+ smoothing: primaryBs.smoothing,
+ stabilization: 0,
+ postCorrection: 0,
+ sharpCorners: primaryBs.sharpCorners,
+ hardness: cfg.hardness ?? primaryBs.hardness ?? 1.0,
+ thickness: cfg.thickness ?? 1.0,
+ thicknessVertical: cfg.thicknessVertical ?? false,
+ flipH: cfg.flipH ?? 'none',
+ flipV: cfg.flipV ?? 'none',
+ antiAlias: primaryBs.antiAlias,
+ pressureCurve: primaryBs.pressureCurve,
+ velocityCurve: primaryBs.velocityCurve,
+ angleSensor: cfg.angleSensor,
+ customTipDataUrl: secondaryTipDataUrl,
+ customTipImage: secondaryTipImage,
+ customTipAngle: cfg.angle ?? 0,
+ customTipAngleDynamics: cfg.angleDynamics ?? 'none',
+ isColorTip: false,
+ isDualToneTip: false,
+ subTips: cfg.subTips,
+ subTipOrder: cfg.subTipOrder ?? 'sequential',
+ subTipImages: cfg.subTipImages,
+ spray: cfg.spray?.enabled ? cfg.spray : undefined,
+ taper: undefined,
+ isRibbon: Boolean(cfg.isRibbon),
+ colorMixing: false,
+ wetEdge: 0,
+ grain: 0,
+ textureDensity: 0,
+ dualBrush: false,
+ dualBrushConfig: undefined,
+ useGpu: primaryBs.useGpu,
+ isTransparentInk: false,
+ dynamics:
+ scatter > 0.001
+ ? {
+ ...DEFAULT_BRUSH_DYNAMICS,
+ scatter,
+ scatterBothAxes: true,
+ }
+ : undefined,
+ renderMode: 'stamp',
+ };
+
+ return { settings, sizeRatio };
+}
+
+/**
+ * Rescales stroke points' baked widths from primary brush size to secondary brush size.
+ */
+export function scalePointsForSecondaryBrush(
+ points: Point[],
+ sizeRatio: number,
+ secSize: number
+): Point[] {
+ if (Math.abs(sizeRatio - 1.0) < 1e-4) {
+ return points;
+ }
+ const out = new Array<Point>(points.length);
+ for (let i = 0; i < points.length; i++) {
+ const p = points[i];
+ out[i] = {
+ ...p,
+ width: p.width > 0 ? Math.max(0.2, p.width * sizeRatio) : secSize,
+ };
+ }
+ return out;
+}
+
+export function scalePointForSecondaryBrush(
+ point: Point,
+ sizeRatio: number,
+ secSize: number
+): Point {
+ if (Math.abs(sizeRatio - 1.0) < 1e-4) {
+ return point;
+ }
+ return {
+ ...point,
+ width: point.width > 0 ? Math.max(0.2, point.width * sizeRatio) : secSize,
+ };
+}
+
+export function scaleSegmentForSecondaryBrush(
+ seg: CubicBezierSegment,
+ sizeRatio: number,
+ secSize: number
+): CubicBezierSegment {
+ if (Math.abs(sizeRatio - 1.0) < 1e-4) {
+ return seg;
+ }
+ return {
+ p0: scalePointForSecondaryBrush(seg.p0, sizeRatio, secSize),
+ c1: scalePointForSecondaryBrush(seg.c1, sizeRatio, secSize),
+ c2: scalePointForSecondaryBrush(seg.c2, sizeRatio, secSize),
+ p3: scalePointForSecondaryBrush(seg.p3, sizeRatio, secSize),
+ };
+}
diff --git a/src/engine/InputStabilizer.ts b/src/engine/InputStabilizer.ts
index ff851ee..419ead6 100644
--- a/src/engine/InputStabilizer.ts
+++ b/src/engine/InputStabilizer.ts
@@ -1,35 +1,40 @@
/**
* InputStabilizer.ts
- * Low-latency 1-Euro Filter + Velocity Tracker + Mass-Spring-Damper.
+ * Low-Latency Velocity-Adaptive Isotropic Stabilizer + Velocity Tracker + Glitch Guard.
* Pre-allocated memory structures, zero GC pauses during active drawing.
- * Upgraded with:
- * - Critical Angle Detection (Corner Snapping, DeltaTheta > 45 deg)
- * - Velocity-Adaptive Damping Scaling
+ * Features:
+ * - CSP-calibrated stabilization range (0..50): 0px at level 0, ~3px at level 1,
+ * 6-16px at levels 15-20 (G-Pen / Real G-Pen), up to ~48px max at level 50
+ * - Velocity-adaptive lag tightening so fast strokes feel crisp and real-time
+ * - Rotation-invariant Frenet-frame tremor damping (zero diagonal warping/anisotropy)
+ * - Targeted hardware backtrack glitch rejection that preserves tight curves & waves
+ * - Smooth sub-path corner convergence (never hard-teleports s1/s2/s3 across lag)
+ * - Full-tail catch-up target to the true pen-lift raw coordinate
* - Asymmetric Attack / Decay Pressure Filtering
*/
export interface StabilizerConfig {
- minCutoff: number; // fc_min (Hz): lower = smoother slow movements (default ~1.0)
- beta: number; // beta: speed coefficient; higher = less lag on flicks (default ~0.02)
+ minCutoff: number; // fc_min (Hz): lower = smoother slow movements (default ~1.5)
+ beta: number; // beta: speed coefficient; higher = less lag on flicks (default ~0.012)
dCutoff: number; // d_cutoff (Hz): cutoff for derivative filtering (default ~1.0)
- deadzone: number; // Minimum delta distance (px) to register movement
+ deadzone: number; // Minimum delta distance (px) to register movement when settled
springMass: number; // Mass for virtual pull-string / spring-damper (0 = disabled)
springStiffness: number; // Spring stiffness k
springDamping: number; // Damping coefficient c (critically damped: 2 * sqrt(k * m))
- cornerAngleThreshold: number; // Angular deflection threshold in radians (default 45 deg = 0.785398)
+ cornerAngleThreshold: number; // Angular deflection threshold in radians (default 68 deg = 1.1868)
attackCutoff: number; // Pressure attack cutoff Hz (instant contact)
decayCutoff: number; // Pressure decay cutoff Hz (smooth release)
}
export const DEFAULT_STABILIZER_CONFIG: StabilizerConfig = {
minCutoff: 1.5,
- beta: 0.03,
+ beta: 0.012,
dCutoff: 1.0,
deadzone: 0.1,
springMass: 0,
springStiffness: 180,
springDamping: 26.8,
- cornerAngleThreshold: 0.785398, // 45 degrees
+ cornerAngleThreshold: 1.1868, // 68 degrees: catches deliberate sharp corners without false-snapping smooth waves
attackCutoff: 45.0, // Fast response on pen attack
decayCutoff: 4.0, // Smooth release
};
@@ -54,6 +59,10 @@ export class OneEuroAxis {
this.initialized = true;
}
+ public getValue(): number {
+ return this.xPrev;
+ }
+
private alpha(rate: number, cutoff: number): number {
const tau = 1.0 / (2.0 * Math.PI * cutoff);
const te = 1.0 / Math.max(1e-5, rate);
@@ -70,10 +79,12 @@ export class OneEuroAxis {
}
const rawElapsedMs = timestampMs - this.tPrev;
- // Synthesize monotonic 4ms (250Hz) sub-step when hardware coalesced events share identical timestamps
- const effectiveMs = rawElapsedMs <= 0.5 ? 4.0 : rawElapsedMs;
+ // Use 4ms (250Hz) sub-step when coalesced events share timestamps WITHOUT drifting tPrev ahead of wall time
+ const effectiveMs = rawElapsedMs > 0.5 ? Math.min(50.0, rawElapsedMs) : 4.0;
const dt = Math.max(0.002, effectiveMs * 0.001);
- this.tPrev = rawElapsedMs <= 0.5 ? this.tPrev + 4.0 : Math.max(this.tPrev, timestampMs);
+ if (timestampMs > this.tPrev) {
+ this.tPrev = timestampMs;
+ }
const rate = 1.0 / dt;
// Filter derivative
@@ -103,13 +114,26 @@ export interface StabilizedSample {
isCorner: boolean;
}
+export interface CornerConvergencePlan {
+ startX: number;
+ startY: number;
+ apexX: number;
+ apexY: number;
+ targetX: number;
+ targetY: number;
+ totalDist: number;
+}
+
export class InputStabilizer {
- private filterX = new OneEuroAxis();
- private filterY = new OneEuroAxis();
private filterPressure = new OneEuroAxis();
- // Asymmetric pressure tracker
- private lastRawPressure: number = 0;
+ // 3-stage isotropic cascaded exponential smoother state (zero overshoot, zero diagonal anisotropy)
+ private s1x: number = 0;
+ private s1y: number = 0;
+ private s2x: number = 0;
+ private s2y: number = 0;
+ private s3x: number = 0;
+ private s3y: number = 0;
// Mass-Spring-Damper simulation state
private smX: number = 0;
@@ -117,22 +141,48 @@ export class InputStabilizer {
private smVx: number = 0;
private smVy: number = 0;
- // Velocity tracker state
+ // Velocity & monotonic timing tracker state
private lastX: number = 0;
private lastY: number = 0;
private lastTime: number = 0;
private instantVx: number = 0;
private instantVy: number = 0;
private instantSpeed: number = 0;
+ private smoothedScreenSpeed: number = 0; // screen px / ms
- // Direction vector history for Corner Snapping (Critical Angle Detection)
+ // Direction vector history for Corner Detection, Frenet tremor damping & glitch rejection
private prevDirX: number = 0;
private prevDirY: number = 0;
private hasPrevDir: boolean = false;
+ private lastStepDirX: number = 0;
+ private lastStepDirY: number = 0;
+ private hasLastStepDir: boolean = false;
private rawPrevX: number = 0;
private rawPrevY: number = 0;
private lastRawSampleX: number = 0;
private lastRawSampleY: number = 0;
+ private consecutiveReversals: number = 0;
+
+ // High-frequency lateral twitch energy (decays rapidly; stays ~0 on smooth sine waves)
+ private lateralSpikeEnergy: number = 0;
+ // Short convergence boost after a true deliberate sharp corner (smooth pull instead of teleport)
+ private cornerConvergeBoost: number = 0;
+
+ // Pre-allocated pending corner sub-path plan (consumed by StrokePipeline for smooth convergence)
+ private hasPendingCornerPlan: boolean = false;
+ private pendingCornerPlan: CornerConvergencePlan = {
+ startX: 0,
+ startY: 0,
+ apexX: 0,
+ apexY: 0,
+ targetX: 0,
+ targetY: 0,
+ totalDist: 0,
+ };
+
+ // Stabilizer level and screen-space total smoothing length (px)
+ private stabilizerLevel: number = -1; // -1 = use config fallback
+ private baseLengthPx: number = 0;
// Single pre-allocated sample object for output to eliminate GC allocation
private outputSample: StabilizedSample = {
@@ -167,24 +217,37 @@ export class InputStabilizer {
public setStabilizerLevel(level: number): void {
// level: 0 to 50 (CSP slider equivalent)
- if (level <= 0) {
- this.config.minCutoff = 100.0; // effectively bypassed
+ const clamped = Math.max(0, Math.min(50, level));
+ this.stabilizerLevel = clamped;
+ if (clamped <= 0) {
+ this.config.minCutoff = 100.0; // completely bypassed (0px lag)
this.config.beta = 0.5;
this.config.springMass = 0;
+ this.baseLengthPx = 0;
} else {
- // Pure unconditionally stable 1-Euro adaptive curve (Clip Studio Paint style)
- const t = Math.min(1.0, level / 50.0);
- this.config.minCutoff = Math.max(0.45, 5.0 - t * 4.55); // 5.0 -> 0.45 Hz
- this.config.beta = Math.max(0.005, 0.055 - t * 0.048); // 0.055 -> 0.007
- this.config.springMass = 0; // Pure 1-Euro without oscillating spring artifacts
+ const t = clamped / 50.0;
+ // CSP-calibrated screen-space smoothing length (px):
+ // level 1 -> ~4.0px continuous (~2-3px discrete)
+ // level 10 -> ~9.0px
+ // level 15 -> ~12.4px
+ // level 18 -> ~14.7px (Real G-Pen default; tightens to ~9-11px when fast)
+ // level 20 -> ~16.3px (G-Pen default; tightens to ~10-12px when fast)
+ // level 50 -> 48.0px max (tightens to ~30-34px when fast)
+ this.baseLengthPx = 3.5 + 23.5 * t + 21.0 * t * t;
+ this.config.minCutoff = Math.max(0.8, 5.0 - t * 4.2);
+ this.config.beta = Math.max(0.005, 0.025 - t * 0.018);
+ this.config.springMass = 0;
}
}
public reset(): void {
- this.filterX.reset();
- this.filterY.reset();
this.filterPressure.reset();
- this.lastRawPressure = 0;
+ this.s1x = 0;
+ this.s1y = 0;
+ this.s2x = 0;
+ this.s2y = 0;
+ this.s3x = 0;
+ this.s3y = 0;
this.smX = 0;
this.smY = 0;
this.smVx = 0;
@@ -195,13 +258,21 @@ export class InputStabilizer {
this.instantVx = 0;
this.instantVy = 0;
this.instantSpeed = 0;
+ this.smoothedScreenSpeed = 0;
this.prevDirX = 0;
this.prevDirY = 0;
this.hasPrevDir = false;
+ this.lastStepDirX = 0;
+ this.lastStepDirY = 0;
+ this.hasLastStepDir = false;
this.rawPrevX = 0;
this.rawPrevY = 0;
this.lastRawSampleX = 0;
this.lastRawSampleY = 0;
+ this.consecutiveReversals = 0;
+ this.lateralSpikeEnergy = 0;
+ this.cornerConvergeBoost = 0;
+ this.hasPendingCornerPlan = false;
this.isStarted = false;
}
@@ -209,14 +280,87 @@ export class InputStabilizer {
return this.outputSample;
}
+ public resetPressureState(pressure: number, timestampMs: number): void {
+ const clamped = Math.max(0, Math.min(1, pressure));
+ this.filterPressure.setDirect(clamped, timestampMs);
+ }
+
+ /**
+ * Returns the latest accepted raw pointer coordinate (in document space).
+ */
+ public getRawPosition(): { x: number; y: number } {
+ return { x: this.lastRawSampleX, y: this.lastRawSampleY };
+ }
+
+ /**
+ * Returns the true pen-lift target coordinate (rawX, rawY) plus the 1st-stage guide point (s1)
+ * so StrokePipeline.finalizeStroke can smoothly close residual stabilizer lag all the way to
+ * the true stylus liftoff coordinate without cutting strokes short.
+ */
+ public getCatchUpTarget(): { x: number; y: number; lagDist: number; midX: number; midY: number } {
+ const lagDist = Math.hypot(this.lastRawSampleX - this.s3x, this.lastRawSampleY - this.s3y);
+ return {
+ x: this.lastRawSampleX,
+ y: this.lastRawSampleY,
+ lagDist,
+ midX: this.s1x,
+ midY: this.s1y,
+ };
+ }
+
+ /**
+ * Consumes any pending corner convergence sub-path produced by the latest process() call.
+ * Allows StrokePipeline to emit short smooth sub-steps into a genuine sharp corner vertex
+ * instead of jumping across lag in a single straight segment.
+ */
+ public consumeCornerPlan(): Readonly<CornerConvergencePlan> | null {
+ if (!this.hasPendingCornerPlan) return null;
+ this.hasPendingCornerPlan = false;
+ return this.pendingCornerPlan;
+ }
+
+ /**
+ * Synchronizes internal filter state after StrokePipeline finishes walking a smooth corner sub-path.
+ */
+ public settleAfterCornerSubPath(x: number, y: number): void {
+ this.s1x = x;
+ this.s1y = y;
+ this.s2x = x;
+ this.s2y = y;
+ this.s3x = x;
+ this.s3y = y;
+ this.lastX = x;
+ this.lastY = y;
+ this.smX = x;
+ this.smY = y;
+ this.smVx = 0;
+ this.smVy = 0;
+ this.cornerConvergeBoost = 0;
+ }
+
+ private resolveEffectiveLengthPx(): number {
+ if (this.stabilizerLevel === 0) return 0;
+ if (this.stabilizerLevel > 0) return this.baseLengthPx;
+ if (this.config.minCutoff >= 50.0) return 0;
+ return Math.max(3.0, Math.min(48.0, 20.0 / Math.max(0.4, this.config.minCutoff)));
+ }
+
public process(
rawX: number,
rawY: number,
rawPressure: number,
timestampMs: number
): StabilizedSample {
+ this.hasPendingCornerPlan = false;
+
if (!this.isStarted) {
this.reset();
+ this.s1x = rawX;
+ this.s1y = rawY;
+ this.s2x = rawX;
+ this.s2y = rawY;
+ this.s3x = rawX;
+ this.s3y = rawY;
this.lastX = rawX;
this.lastY = rawY;
this.lastTime = timestampMs;
@@ -228,15 +372,18 @@ export class InputStabilizer {
this.smY = rawY;
this.smVx = 0;
this.smVy = 0;
- this.lastRawPressure = rawPressure;
this.isStarted = true;
- const fX = this.filterX.filter(rawX, timestampMs, this.config.minCutoff, this.config.beta, this.config.dCutoff);
- const fY = this.filterY.filter(rawY, timestampMs, this.config.minCutoff, this.config.beta, this.config.dCutoff);
- const fP = this.filterPressure.filter(rawPressure, timestampMs, this.config.attackCutoff, 0.1, this.config.dCutoff);
+ const fP = this.filterPressure.filter(
+ rawPressure,
+ timestampMs,
+ this.config.attackCutoff,
+ 0.1,
+ this.config.dCutoff
+ );
- this.outputSample.x = fX;
- this.outputSample.y = fY;
+ this.outputSample.x = rawX;
+ this.outputSample.y = rawY;
this.outputSample.pressure = fP;
this.outputSample.vx = 0;
this.outputSample.vy = 0;
@@ -246,42 +393,154 @@ export class InputStabilizer {
return this.outputSample;
}
- const dtMs = Math.max(1, timestampMs - this.lastTime);
- const dtSec = dtMs * 0.001;
+ // 1. Monotonic continuous-time delta without drifting ahead of wall-clock timestamps
+ const rawElapsedMs = timestampMs - this.lastTime;
+ const stepDtMs = rawElapsedMs > 0.5 ? Math.min(50.0, rawElapsedMs) : 4.0;
+ const dtSec = stepDtMs * 0.001;
+ if (timestampMs > this.lastTime) {
+ this.lastTime = timestampMs;
+ }
+ const clampedZoom = Math.max(0.15, Math.min(4.0, this.zoomScale));
const stepRawDx = rawX - this.lastRawSampleX;
const stepRawDy = rawY - this.lastRawSampleY;
const stepRawDist = Math.hypot(stepRawDx, stepRawDy);
+ const stepScreenDist = stepRawDist * clampedZoom;
+
+ // 2. Targeted single-packet hardware backtrack spike guard:
+ // Compares against the immediate previous step direction (NOT a 30px-stale chord) and
+ // requires a large sudden reversal (>123 deg, >= 8 screen px) at high speed (>0.9 px/ms).
+ // Legitimate tight curves and sine waves have smooth per-step turning (<45 deg) and are NEVER dropped.
+ const baseLengthPx = this.resolveEffectiveLengthPx();
+ if (
+ baseLengthPx > 0 &&
+ this.hasLastStepDir &&
+ this.smoothedScreenSpeed > 0.9 &&
+ stepScreenDist >= 8.0
+ ) {
+ const stepDot =
+ (stepRawDx / stepRawDist) * this.lastStepDirX +
+ (stepRawDy / stepRawDist) * this.lastStepDirY;
+ if (stepDot < -0.55) {
+ if (this.consecutiveReversals === 0) {
+ this.consecutiveReversals = 1;
+ const pressureDelta = rawPressure - this.filterPressure.getValue();
+ const pCutoff = pressureDelta > 1e-4 ? this.config.attackCutoff : this.config.decayCutoff;
+ const pBeta = pressureDelta > 1e-4 ? 0.2 : 0.01;
+ const fP = this.filterPressure.filter(
+ rawPressure,
+ timestampMs,
+ pCutoff,
+ pBeta,
+ this.config.dCutoff
+ );
+ this.outputSample.x = this.lastX;
+ this.outputSample.y = this.lastY;
+ this.outputSample.pressure = Math.max(0, Math.min(1, fP));
+ this.outputSample.vx = this.instantVx;
+ this.outputSample.vy = this.instantVy;
+ this.outputSample.speed = this.instantSpeed;
+ this.outputSample.timestamp = timestampMs;
+ this.outputSample.isCorner = false;
+ return this.outputSample;
+ }
+ this.consecutiveReversals++;
+ } else {
+ this.consecutiveReversals = 0;
+ }
+ } else if (stepScreenDist >= 1.0) {
+ this.consecutiveReversals = 0;
+ }
+
+ const prevRawSampleX = this.lastRawSampleX;
+ const prevRawSampleY = this.lastRawSampleY;
this.lastRawSampleX = rawX;
this.lastRawSampleY = rawY;
- // 1. Zoom-Aware Critical Angle Detection (Corner Snapping)
- // Screen-space 6px chord threshold prevents zoomed-out 600 DPI canvases from false-snapping on 1px hand tremor
+ // Smooth raw screen speed with 24ms time constant so packet-cadence jitter never spikes cutoff
+ const instScreenSpeed = stepScreenDist / stepDtMs;
+ const speedEmaAlpha = 1.0 - Math.exp(-stepDtMs / 24.0);
+ this.smoothedScreenSpeed += speedEmaAlpha * (instScreenSpeed - this.smoothedScreenSpeed);
+
+ // Measure instantaneous step direction & angular deflection vs immediately preceding step
+ let stepDirX = this.lastStepDirX;
+ let stepDirY = this.lastStepDirY;
+ let instantStepAngle = 0;
+ if (stepScreenDist >= 0.75) {
+ stepDirX = stepRawDx / stepRawDist;
+ stepDirY = stepRawDy / stepRawDist;
+ if (this.hasLastStepDir) {
+ const sDot = Math.max(
+ -1.0,
+ Math.min(1.0, this.lastStepDirX * stepDirX + this.lastStepDirY * stepDirY)
+ );
+ instantStepAngle = Math.acos(sDot);
+ }
+ }
+
+ // Detect sudden high-speed lateral twitch impulses BEFORE updating prevDir
+ // so a 1-2 sample twitch on a fast swoosh cannot corrupt the established stroke direction.
+ const spikeDecay = Math.exp(-stepDtMs / 20.0);
+ this.lateralSpikeEnergy *= spikeDecay;
+ if (baseLengthPx > 0 && this.hasPrevDir && this.smoothedScreenSpeed > 1.35 && stepScreenDist >= 2.0) {
+ const perpStepScreen = Math.abs(
+ (-this.prevDirY * stepRawDx + this.prevDirX * stepRawDy) * clampedZoom
+ );
+ const perpErrScreen = Math.abs(
+ (-this.prevDirY * (rawX - this.s3x) + this.prevDirX * (rawY - this.s3y)) * clampedZoom
+ );
+ // A smooth sine wave at 250Hz has small per-step lateral deviation (< 3px);
+ // a fast muscle/hardware twitch jumps sharply sideways (> 5.5px) at high speed (> 1.35 px/ms).
+ if (perpStepScreen > 5.5 && instantStepAngle > 0.55) {
+ const impulse = Math.min(1.0, (perpStepScreen - 4.0) / 6.0);
+ if (impulse > this.lateralSpikeEnergy) {
+ this.lateralSpikeEnergy = impulse;
+ }
+ } else if (this.lateralSpikeEnergy > 0.2 && perpErrScreen > 6.5) {
+ // Hold spike energy during a 2-sample twitch plateau while raw stays far off the established ray
+ this.lateralSpikeEnergy = Math.max(this.lateralSpikeEnergy, 0.85);
+ }
+ }
+
+ // 3. Deliberate Sharp Corner Detection (anti-sine-wave gated, NEVER hard-teleports s1/s2/s3):
+ // Requires BOTH a sharp chord deflection (> cornerAngleThreshold) AND a sharp localized
+ // per-step vertex turn (instantStepAngle > 55 deg) at deliberate speed (<= 1.35 px/ms)
+ // so smooth sine waves and fast curves NEVER false-snap.
const rawDx = rawX - this.rawPrevX;
const rawDy = rawY - this.rawPrevY;
const rawDist = Math.hypot(rawDx, rawDy);
- const minCornerChord = 6.0 / Math.max(0.15, Math.min(4.0, this.zoomScale));
+ const minCornerChordScreen =
+ 8.0 + Math.min(20.0, Math.max(0, this.smoothedScreenSpeed - 0.8) * 10.0);
+ const minCornerChord = minCornerChordScreen / clampedZoom;
let isCorner = false;
- if (rawDist >= minCornerChord) {
+ if (rawDist >= minCornerChord && this.lateralSpikeEnergy <= 0.25) {
const curDirX = rawDx / rawDist;
const curDirY = rawDy / rawDist;
- if (this.hasPrevDir && this.sharpCornersEnabled) {
- // Dot product between consecutive motion vectors
+ if (this.hasPrevDir && this.sharpCornersEnabled && baseLengthPx > 0) {
const dot = Math.max(-1.0, Math.min(1.0, this.prevDirX * curDirX + this.prevDirY * curDirY));
- const angle = Math.acos(dot);
+ const chordAngle = Math.acos(dot);
- // If angular deflection exceeds critical angle threshold (default 45 deg)
- if (angle > this.config.cornerAngleThreshold) {
+ const isDeliberateSharpVertex =
+ chordAngle > this.config.cornerAngleThreshold &&
+ this.smoothedScreenSpeed <= 1.35 &&
+ (instantStepAngle > 0.96 || (this.smoothedScreenSpeed <= 0.45 && chordAngle > 1.48 && instantStepAngle > 0.55));
+
+ if (isDeliberateSharpVertex) {
isCorner = true;
- // Immediately reset filter tension and mass-spring inertia to sharp vertex coordinate
- this.filterX.setDirect(rawX, timestampMs);
- this.filterY.setDirect(rawY, timestampMs);
- this.smX = rawX;
- this.smY = rawY;
- this.smVx = 0;
- this.smVy = 0;
+ this.cornerConvergeBoost = 1.0;
+ const totalDist =
+ Math.hypot(prevRawSampleX - this.s3x, prevRawSampleY - this.s3y) +
+ Math.hypot(rawX - prevRawSampleX, rawY - prevRawSampleY);
+ this.pendingCornerPlan.startX = this.s3x;
+ this.pendingCornerPlan.startY = this.s3y;
+ this.pendingCornerPlan.apexX = prevRawSampleX;
+ this.pendingCornerPlan.apexY = prevRawSampleY;
+ this.pendingCornerPlan.targetX = rawX;
+ this.pendingCornerPlan.targetY = rawY;
+ this.pendingCornerPlan.totalDist = totalDist;
+ this.hasPendingCornerPlan = true;
}
}
@@ -292,41 +551,153 @@ export class InputStabilizer {
this.rawPrevY = rawY;
}
- // 2. Velocity-Adaptive Damping Scaling (screen-normalized speed, smooth saturation so fast arcs stay silky)
- const screenSpeed = (stepRawDist * Math.max(0.15, Math.min(4.0, this.zoomScale))) / dtMs; // screen px / ms
- const speedBoost = Math.min(6.0, screenSpeed * 2.2);
- const dynamicMinCutoff = this.config.minCutoff * (1.0 + speedBoost);
- const dynamicBeta = this.config.beta * (1.0 + speedBoost * 0.35);
+ if (stepScreenDist >= 0.75) {
+ this.lastStepDirX = stepDirX;
+ this.lastStepDirY = stepDirY;
+ this.hasLastStepDir = true;
+ }
- // 3. Coordinate Filtering with sub-pixel deadzone suppression
+ // 4. Low-Latency Velocity-Adaptive Isotropic 3-Stage Filtering
let fX: number;
let fY: number;
- if (isCorner) {
+ const residualDist = Math.hypot(rawX - this.s3x, rawY - this.s3y);
+
+ if (baseLengthPx <= 0) {
fX = rawX;
fY = rawY;
- } else if (stepRawDist < this.config.deadzone && this.config.minCutoff < 50.0) {
+ this.s1x = rawX;
+ this.s1y = rawY;
+ this.s2x = rawX;
+ this.s2y = rawY;
+ this.s3x = rawX;
+ this.s3y = rawY;
+ } else if (!isCorner && stepRawDist < this.config.deadzone && residualDist < this.config.deadzone) {
fX = this.lastX;
fY = this.lastY;
+ } else if (isCorner) {
+ // Smoothly pull toward the corner apex and outgoing leg with a bounded per-step distance
+ // (NEVER hard-teleport s1/s2/s3 across arbitrary lag in a single jump!)
+ const maxCornerPullDoc = 12.0 / clampedZoom;
+ const toApexX = prevRawSampleX - this.s3x;
+ const toApexY = prevRawSampleY - this.s3y;
+ const toApexDist = Math.hypot(toApexX, toApexY);
+
+ if (toApexDist >= maxCornerPullDoc) {
+ const frac = maxCornerPullDoc / toApexDist;
+ this.s3x += toApexX * frac;
+ this.s3y += toApexY * frac;
+ } else {
+ // Reach the apex, then spend remaining bounded pull budget along the outgoing leg
+ this.s3x = prevRawSampleX;
+ this.s3y = prevRawSampleY;
+ const remaining = maxCornerPullDoc - toApexDist;
+ const outDx = rawX - prevRawSampleX;
+ const outDy = rawY - prevRawSampleY;
+ const outDist = Math.hypot(outDx, outDy);
+ if (outDist > 1e-4 && remaining > 0) {
+ const outFrac = Math.min(1.0, remaining / outDist);
+ this.s3x += outDx * outFrac;
+ this.s3y += outDy * outFrac;
+ }
+ }
+
+ // Gently align upstream stages between s3 and raw without teleporting past the corner
+ this.s2x = this.s3x + (rawX - this.s3x) * 0.35;
+ this.s2y = this.s3y + (rawY - this.s3y) * 0.35;
+ this.s1x = this.s3x + (rawX - this.s3x) * 0.65;
+ this.s1y = this.s3y + (rawY - this.s3y) * 0.65;
+ this.smX = this.s3x;
+ this.smY = this.s3y;
+ this.smVx = 0;
+ this.smVy = 0;
+ fX = this.s3x;
+ fY = this.s3y;
} else {
- fX = this.filterX.filter(rawX, timestampMs, dynamicMinCutoff, dynamicBeta, this.config.dCutoff);
- fY = this.filterY.filter(rawY, timestampMs, dynamicMinCutoff, dynamicBeta, this.config.dCutoff);
+ // Gently tighten lag on faster strokes for responsive CSP-like real-time feel
+ const speedFactor = Math.max(
+ 0.58,
+ 1.0 / (1.0 + Math.max(0, this.smoothedScreenSpeed - 0.5) * 0.22)
+ );
+ // Smooth convergence boost right after a deliberate corner decays back to normal
+ const cornerFactor = 1.0 - 0.55 * this.cornerConvergeBoost;
+ this.cornerConvergeBoost *= Math.exp(-stepDtMs / 22.0);
+ if (this.cornerConvergeBoost < 0.02) this.cornerConvergeBoost = 0;
+
+ const effectiveLengthPx = baseLengthPx * speedFactor * cornerFactor;
+
+ // Prevent sudden perpendicular twitch spikes from inflating spatial alpha along the stroke
+ let effectiveStepPx = stepScreenDist;
+ if (this.hasPrevDir && stepScreenDist > 0.01) {
+ const dsForward = Math.max(
+ 0,
+ (stepRawDx * this.prevDirX + stepRawDy * this.prevDirY) * clampedZoom
+ );
+ effectiveStepPx = Math.min(
+ stepScreenDist,
+ Math.max(dsForward, 0.35 * stepScreenDist)
+ );
+ }
+
+ const stageLengthPx = Math.max(0.4, effectiveLengthPx / 3.0);
+ const alphaAlong = 1.0 - Math.exp(-effectiveStepPx / stageLengthPx);
+
+ if (this.lateralSpikeEnergy > 0.05 && this.hasPrevDir) {
+ // Rotation-invariant Frenet-frame lateral spike damping:
+ // Keeps tangent lag crisp while strongly attenuating sudden 1-2 packet sideways twitches.
+ const tx = this.prevDirX;
+ const ty = this.prevDirY;
+ const nx = -ty;
+ const ny = tx;
+ const perpStageLen = stageLengthPx * (1.0 + 5.8 * this.lateralSpikeEnergy);
+ const alphaPerp = 1.0 - Math.exp(-effectiveStepPx / perpStageLen);
+
+ const advanceStage = (
+ sx: number,
+ sy: number,
+ targetX: number,
+ targetY: number
+ ): [number, number] => {
+ const ex = targetX - sx;
+ const ey = targetY - sy;
+ const eAlong = ex * tx + ey * ty;
+ const ePerp = ex * nx + ey * ny;
+ const dAlong = alphaAlong * eAlong;
+ const dPerp = alphaPerp * ePerp;
+ return [sx + dAlong * tx + dPerp * nx, sy + dAlong * ty + dPerp * ny];
+ };
+
+ [this.s1x, this.s1y] = advanceStage(this.s1x, this.s1y, rawX, rawY);
+ [this.s2x, this.s2y] = advanceStage(this.s2x, this.s2y, this.s1x, this.s1y);
+ [this.s3x, this.s3y] = advanceStage(this.s3x, this.s3y, this.s2x, this.s2y);
+ } else {
+ // Pure isotropic 3-stage exponential cascade (identical scalar alpha for X and Y)
+ this.s1x += alphaAlong * (rawX - this.s1x);
+ this.s1y += alphaAlong * (rawY - this.s1y);
+ this.s2x += alphaAlong * (this.s1x - this.s2x);
+ this.s2y += alphaAlong * (this.s1y - this.s2y);
+ this.s3x += alphaAlong * (this.s2x - this.s3x);
+ this.s3y += alphaAlong * (this.s2y - this.s3y);
+ }
+
+ fX = this.s3x;
+ fY = this.s3y;
}
- // 4. Asymmetric Pressure Filtering (Fast Attack, Critically Damped Decay)
- const pressureDelta = rawPressure - this.lastRawPressure;
- this.lastRawPressure = rawPressure;
- const pCutoff = pressureDelta > 0 ? this.config.attackCutoff : this.config.decayCutoff;
- const pBeta = pressureDelta > 0 ? 0.2 : 0.01;
+ // 5. Asymmetric Pressure Filtering (Fast Attack, Critically Damped Decay)
+ // Compare target rawPressure against the current filtered pressure (not lastRawPressure)
+ // so constant or plateaued high pressure stays in fast attackCutoff until it converges!
+ const pressureDelta = rawPressure - this.filterPressure.getValue();
+ const pCutoff = pressureDelta > 1e-4 ? this.config.attackCutoff : this.config.decayCutoff;
+ const pBeta = pressureDelta > 1e-4 ? 0.2 : 0.01;
const fP = this.filterPressure.filter(rawPressure, timestampMs, pCutoff, pBeta, this.config.dCutoff);
- // 5. Mass-Spring-Damper Simulation (when enabled for stabilizer > 15)
+ // 6. Optional Mass-Spring-Damper Simulation (only when explicitly configured via configure())
if (this.config.springMass > 0 && !isCorner) {
const k = this.config.springStiffness;
const c = this.config.springDamping;
const m = this.config.springMass;
- // Dynamic damping reduction on fast flicks
- const effectiveDamping = Math.max(c * 0.35, c / (1.0 + screenSpeed * 0.5));
+ const effectiveDamping = Math.max(c * 0.35, c / (1.0 + this.smoothedScreenSpeed * 0.5));
const disX = fX - this.smX;
const disY = fY - this.smY;
@@ -334,7 +705,6 @@ export class InputStabilizer {
const ax = (k * disX - effectiveDamping * this.smVx) / m;
const ay = (k * disY - effectiveDamping * this.smVy) / m;
- // Semi-implicit Euler integration
this.smVx += ax * dtSec;
this.smVy += ay * dtSec;
this.smX += this.smVx * dtSec;
@@ -349,13 +719,12 @@ export class InputStabilizer {
const dy = fY - this.lastY;
const dist = Math.hypot(dx, dy);
- this.instantVx = dx / dtMs;
- this.instantVy = dy / dtMs;
- this.instantSpeed = dist / dtMs;
+ this.instantVx = dx / stepDtMs;
+ this.instantVy = dy / stepDtMs;
+ this.instantSpeed = dist / stepDtMs;
this.lastX = fX;
this.lastY = fY;
- this.lastTime = timestampMs;
this.outputSample.x = fX;
this.outputSample.y = fY;
diff --git a/src/engine/NaturalPaintRenderer.ts b/src/engine/NaturalPaintRenderer.ts
index cb6481b..9cbca86 100644
--- a/src/engine/NaturalPaintRenderer.ts
+++ b/src/engine/NaturalPaintRenderer.ts
@@ -31,6 +31,7 @@ import {
SURFACE_TEXTURE_SIZE,
} from '../utils/proceduralBrushTips';
import { LayerPixelSampler } from '../utils/colorMixingEngine';
+import { PigmentRgb, pigmentMixRgbOut } from '../utils/pigmentEngine';
import {
BRISTLE_SEG_STRIDE,
BristleRibbonEngine,
@@ -95,6 +96,7 @@ export interface GrainSampleParams {
scale: number;
rotateRad: number;
contrast: number;
+ contrastFactor?: number;
brightness: number;
inverted: boolean;
strokeOffsetX: number;
@@ -236,7 +238,7 @@ export function evaluateMappedSurfaceHeight(
if (params.inverted) g = 1.0 - g;
if (params.brightness !== 0) g += params.brightness / 100.0;
if (params.contrast !== 0) {
- const cf = Math.pow(Math.max(0.05, 1.0 + params.contrast / 100.0), 2);
+ const cf = params.contrastFactor ?? Math.pow(Math.max(0.05, 1.0 + params.contrast / 100.0), 2);
g = (g - 0.5) * cf + 0.5;
}
return g <= 0 ? 0 : g >= 1 ? 1 : g;
@@ -315,13 +317,13 @@ function acquireChunk(cx: number, cy: number): PaintChunk {
recycled.b.fill(0);
recycled.a.fill(0);
recycled.height.fill(0);
- recycled.tooth.fill(0.5);
+ recycled.tooth.fill(-1);
recycled.lastArcU.fill(-9999);
recycled.lastBristle.fill(-1);
return recycled;
}
const tooth = new Float32Array(CHUNK_PIXELS);
- tooth.fill(0.5);
+ tooth.fill(-1);
const lastArcU = new Float32Array(CHUNK_PIXELS);
lastArcU.fill(-9999);
const lastBristle = new Int16Array(CHUNK_PIXELS);
@@ -402,6 +404,14 @@ export class NaturalPaintStrokeSession {
private hGridTmp: Float32Array = new Float32Array(0);
private hGridSmooth: Float32Array = new Float32Array(0);
private toothGrid: Float32Array = new Float32Array(0);
+ private rowPaintMinX: Int32Array = new Int32Array(0);
+ private rowPaintMaxX: Int32Array = new Int32Array(0);
+
+ // Per-frame deferred dirty region for batched shading & blit (1 flush per animation frame!)
+ private pendingDirtyMinX: number = Infinity;
+ private pendingDirtyMinY: number = Infinity;
+ private pendingDirtyMaxX: number = -Infinity;
+ private pendingDirtyMaxY: number = -Infinity;
public minX: number = Infinity;
public minY: number = Infinity;
@@ -445,6 +455,10 @@ export class NaturalPaintStrokeSession {
scale: Math.max(0.1, settings.paperTextureScale ?? 1.0),
rotateRad: ((settings.paperTextureRotate ?? 0) * Math.PI) / 180,
contrast: settings.paperTextureContrast ?? 0,
+ contrastFactor:
+ (settings.paperTextureContrast ?? 0) !== 0
+ ? Math.pow(Math.max(0.05, 1.0 + (settings.paperTextureContrast ?? 0) / 100.0), 2)
+ : 1.0,
brightness: settings.paperTextureBrightness ?? 0,
inverted: Boolean(settings.paperTextureInverted),
strokeOffsetX: s1 * SURFACE_TEXTURE_SIZE,
@@ -474,7 +488,8 @@ export class NaturalPaintStrokeSession {
const ch = this.getChunk(cx, cy);
if (!ch) return { hPaint: 0, tooth: 0.5, alpha: 0 };
const idx = ((y & CHUNK_MASK) << CHUNK_SHIFT) + (x & CHUNK_MASK);
- return { hPaint: ch.height[idx], tooth: ch.tooth[idx], alpha: ch.a[idx] };
+ const tVal = ch.tooth[idx];
+ return { hPaint: ch.height[idx], tooth: tVal < 0 ? 0.5 : tVal, alpha: ch.a[idx] };
}
/**
@@ -486,8 +501,20 @@ export class NaturalPaintStrokeSession {
const grainDepth = this.grainParams.grainDepth;
const dryBrush = this.natural.dryBrush;
const penCurve = this.natural.penetrationCurve;
+ const hasGrainOrDry = grainDepth > 0.005 || dryBrush > 0.005;
+ const hasStaticGrain =
+ this.grainParams.mappingMode === 'canvas-locked' ||
+ this.grainParams.mappingMode === 'random-per-stroke';
+ const effectiveDry = Math.max(dryBrush, grainDepth * 0.68);
+ const softnessInv = 1.0 / Math.max(0.06, 0.14 + (1.0 - effectiveDry) * 0.22);
const bristleRelief = this.impasto.enabled ? this.impasto.bristleRelief : 0.4;
+ const edgeSoft = Math.max(1.25, Math.min(2.5, 1.4 + (1.0 - bristleRelief) * 1.0));
+ const halfEdgeSoft = edgeSoft * 0.5;
+ const invEdgeSoft = 1.0 / edgeSoft;
const halfBrushW = Math.max(2, (this.settings.size || 24) * 0.5);
+ const pigmentStrength = this.engine.config.naturalPaint.pigmentMixingStrength;
+ const usePigmentBlend = pigmentStrength > 0.005;
+ const mixScratch: PigmentRgb = { r: 0, g: 0, b: 0 };
let dMinX = Infinity;
let dMinY = Infinity;
@@ -544,11 +571,19 @@ export class NaturalPaintStrokeSession {
const segCos = segLen > 1e-4 ? sdx / segLen : 1;
const segSin = segLen > 1e-4 ? sdy / segLen : 0;
const selfPassWindow = Math.max(14, halfBrushW * 0.9);
+ const curvedP = hasGrainOrDry
+ ? penCurve
+ ? evaluateFastSpline(pressure, penCurve)
+ : Math.max(0, Math.min(1, pressure))
+ : 0;
+ const tiltReduction = 1.0 - Math.max(0, Math.min(1, tiltMag)) * 0.45;
for (let py = by0; py <= by1; py++) {
const cy = py >> CHUNK_SHIFT;
const lyOff = (py & CHUNK_MASK) << CHUNK_SHIFT;
const dy0 = py + 0.5 - y0;
+ let cachedCx = -999999;
+ let cachedCh: PaintChunk | null = null;
for (let px = bx0; px <= bx1; px++) {
const dx0 = px + 0.5 - x0;
@@ -556,13 +591,15 @@ export class NaturalPaintStrokeSession {
if (t < 0) t = 0;
else if (t > 1) t = 1;
- const cxPt = x0 + sdx * t;
- const cyPt = y0 + sdy * t;
- const dist = Math.hypot(px + 0.5 - cxPt, py + 0.5 - cyPt);
+ const ddX = px + 0.5 - (x0 + sdx * t);
+ const ddY = py + 0.5 - (y0 + sdy * t);
const rad = rad0 + (rad1 - rad0) * t;
- if (dist >= rad + 0.85) continue;
+ const maxR = rad + 0.85;
+ const distSq = ddX * ddX + ddY * ddY;
+ if (distSq >= maxR * maxR) continue;
+ const dist = Math.sqrt(distSq);
- const normD = dist / Math.max(0.5, rad);
+ const normD = dist / (rad > 0.5 ? rad : 0.5);
const load = load0 + (load1 - load0) * t;
const arcU = arcU0 + (arcU1 - arcU0) * t;
@@ -573,54 +610,68 @@ export class NaturalPaintStrokeSession {
if (isUnderBed) {
// Cohesive creamy paint cushion: opaque inside core (normD < 0.68), feathered softly across linen flanks
- const flankT = Math.max(0, Math.min(1, (normD - 0.62) / 0.38));
+ const flankRaw = (normD - 0.62) * (1.0 / 0.38);
+ const flankT = flankRaw <= 0 ? 0 : flankRaw >= 1 ? 1 : flankRaw;
const coreEnv = 1.0 - flankT * flankT * (3.0 - 2.0 * flankT);
baseAlpha = (a0 + (a1 - a0) * t) * coreEnv;
grooveCrown = 0.55 + 0.45 * coreEnv;
effLoadForTooth = load * (0.28 + 0.72 * coreEnv);
} else {
// Sculpted rounded cylindrical bristle ridge + recessed outer furrow carving!
- // Low-relief brushes get slightly wider creamy edge feathering for seamless blending
- const edgeSoft = Math.max(1.25, Math.min(2.5, 1.4 + (1.0 - bristleRelief) * 1.0));
- const aaEdge = 1.0 - Math.max(0, Math.min(1, (dist - (rad - edgeSoft * 0.5)) / edgeSoft));
- grooveCrown = Math.pow(Math.max(0, 1.0 - normD * normD), 0.72);
+ const aaRaw = (dist - (rad - halfEdgeSoft)) * invEdgeSoft;
+ const aaEdge = 1.0 - (aaRaw <= 0 ? 0 : aaRaw >= 1 ? 1 : aaRaw);
+ const uCrown = 1.0 - normD * normD;
+ grooveCrown = uCrown > 0 ? Math.sqrt(uCrown) * (0.35 + 0.65 * uCrown) : 0;
// Outer shoulder of a bristle (0.62 < normD < 0.98) gently carves a 3D furrow into the wet paint bed
if (normD > 0.6 && normD < 0.98) {
- const tt = (normD - 0.6) / 0.38;
+ const tt = (normD - 0.6) * (1.0 / 0.38);
troughCarve = Math.sin(tt * Math.PI) * bristleRelief * 0.42;
}
baseAlpha = (a0 + (a1 - a0) * t) * aaEdge;
}
if (baseAlpha <= 0.002) continue;
- // Sample spatial canvas tooth height H_canvas(x, y)
- const hCanvas = evaluateMappedSurfaceHeight(
- this.grainParams,
- px + 0.5,
- py + 0.5,
- arcU,
- acrossV,
- halfBrushW,
- segCos,
- segSin
- );
-
- const toothContact = evaluatePaintCanvasContact(
- hCanvas,
- effLoadForTooth,
- pressure,
- tiltMag,
- grainDepth,
- dryBrush,
- penCurve
- );
+ const cx = px >> CHUNK_SHIFT;
+ if (cx !== cachedCx) {
+ cachedCh = this.getOrCreateChunk(cx, cy);
+ cachedCx = cx;
+ }
+ const ch = cachedCh!;
+ const idx = lyOff + (px & CHUNK_MASK);
+
+ // Sample spatial canvas tooth height H_canvas(x, y) — reuse cached static height across bristle overlaps!
+ let hCanvas = hasStaticGrain ? ch.tooth[idx] : -1;
+ if (hCanvas < 0) {
+ hCanvas = evaluateMappedSurfaceHeight(
+ this.grainParams,
+ px + 0.5,
+ py + 0.5,
+ arcU,
+ acrossV,
+ halfBrushW,
+ segCos,
+ segSin
+ );
+ ch.tooth[idx] = hCanvas;
+ }
+
+ let toothContact = 1.0;
+ if (hasGrainOrDry) {
+ const cLoad = effLoadForTooth <= 0 ? 0 : effLoadForTooth >= 1 ? 1 : effLoadForTooth;
+ const penRaw = (curvedP * 0.5 + cLoad * 0.5) * (0.38 + 0.62 * cLoad) * tiltReduction;
+ const penetration = penRaw <= 0 ? 0 : penRaw >= 1 ? 1 : penRaw;
+ const cutoff = effectiveDry * (1.0 - penetration * 0.84) * 0.76;
+ const ctRaw = (hCanvas - cutoff) * softnessInv;
+ const ct = ctRaw <= 0 ? 0 : ctRaw >= 1 ? 1 : ctRaw;
+ const smooth = ct * ct * (3.0 - 2.0 * ct);
+ const msRaw = grainDepth * (1.0 - penetration * 0.92) + dryBrush * (1.0 - cLoad * 0.94);
+ const maskStrength = msRaw <= 0 ? 0 : msRaw >= 1 ? 1 : msRaw;
+ toothContact = 1.0 - maskStrength + maskStrength * smooth;
+ }
const srcA = baseAlpha * toothContact;
if (srcA <= 0.002) continue;
- const ch = this.getOrCreateChunk(px >> CHUNK_SHIFT, cy);
- const idx = lyOff + (px & CHUNK_MASK);
-
const sr = r0 + (r1 - r0) * t;
const sg = g0 + (g1 - g0) * t;
const sb = b0 + (b1 - b0) * t;
@@ -647,9 +698,19 @@ export class NaturalPaintStrokeSession {
ch.g[idx] = sg;
ch.b[idx] = sb;
} else {
- ch.r[idx] = ch.r[idx] * (1 - fillW) + sr * fillW;
- ch.g[idx] = ch.g[idx] * (1 - fillW) + sg * fillW;
- ch.b[idx] = ch.b[idx] * (1 - fillW) + sb * fillW;
+ const dr = ch.r[idx];
+ const dg = ch.g[idx];
+ const db = ch.b[idx];
+ if (usePigmentBlend && (sr - dr) * (sr - dr) + (sg - dg) * (sg - dg) + (sb - db) * (sb - db) > 16) {
+ pigmentMixRgbOut(dr, dg, db, sr, sg, sb, fillW, pigmentStrength, mixScratch);
+ ch.r[idx] = mixScratch.r;
+ ch.g[idx] = mixScratch.g;
+ ch.b[idx] = mixScratch.b;
+ } else {
+ ch.r[idx] = dr + (sr - dr) * fillW;
+ ch.g[idx] = dg + (sg - dg) * fillW;
+ ch.b[idx] = db + (sb - db) * fillW;
+ }
}
ch.a[idx] = srcA;
}
@@ -661,10 +722,25 @@ export class NaturalPaintStrokeSession {
const depositA = Math.min(1.0, srcA * 0.94);
const outA = depositA + dstA * (1.0 - depositA);
if (outA > 0.0005) {
- const invOut = 1.0 / outA;
- ch.r[idx] = (sr * depositA + ch.r[idx] * dstA * (1.0 - depositA)) * invOut;
- ch.g[idx] = (sg * depositA + ch.g[idx] * dstA * (1.0 - depositA)) * invOut;
- ch.b[idx] = (sb * depositA + ch.b[idx] * dstA * (1.0 - depositA)) * invOut;
+ const dr = ch.r[idx];
+ const dg = ch.g[idx];
+ const db = ch.b[idx];
+ if (
+ usePigmentBlend &&
+ dstA > 0.002 &&
+ (sr - dr) * (sr - dr) + (sg - dg) * (sg - dg) + (sb - db) * (sb - db) > 16
+ ) {
+ pigmentMixRgbOut(dr, dg, db, sr, sg, sb, depositA / outA, pigmentStrength, mixScratch);
+ ch.r[idx] = mixScratch.r;
+ ch.g[idx] = mixScratch.g;
+ ch.b[idx] = mixScratch.b;
+ } else {
+ const invOut = 1.0 / outA;
+ const dstW = dstA * (1.0 - depositA);
+ ch.r[idx] = (sr * depositA + dr * dstW) * invOut;
+ ch.g[idx] = (sg * depositA + dg * dstW) * invOut;
+ ch.b[idx] = (sb * depositA + db * dstW) * invOut;
+ }
ch.a[idx] = outA;
}
ch.height[idx] = ch.height[idx] * (1.0 - depositA * 0.72) + strandH * (0.28 + depositA * 0.72);
@@ -690,9 +766,23 @@ export class NaturalPaintStrokeSession {
const blendW = overBed
? Math.min(0.92, srcA * 1.15)
: srcA / Math.max(0.001, srcA + dstA);
- ch.r[idx] = ch.r[idx] * (1 - blendW) + sr * blendW;
- ch.g[idx] = ch.g[idx] * (1 - blendW) + sg * blendW;
- ch.b[idx] = ch.b[idx] * (1 - blendW) + sb * blendW;
+ const dr = ch.r[idx];
+ const dg = ch.g[idx];
+ const db = ch.b[idx];
+ if (
+ usePigmentBlend &&
+ dstA > 0.002 &&
+ (sr - dr) * (sr - dr) + (sg - dg) * (sg - dg) + (sb - db) * (sb - db) > 16
+ ) {
+ pigmentMixRgbOut(dr, dg, db, sr, sg, sb, blendW, pigmentStrength, mixScratch);
+ ch.r[idx] = mixScratch.r;
+ ch.g[idx] = mixScratch.g;
+ ch.b[idx] = mixScratch.b;
+ } else {
+ ch.r[idx] = dr + (sr - dr) * blendW;
+ ch.g[idx] = dg + (sg - dg) * blendW;
+ ch.b[idx] = db + (sb - db) * blendW;
+ }
ch.a[idx] = targetA;
}
if (overBed) {
@@ -716,10 +806,25 @@ export class NaturalPaintStrokeSession {
const depositA = Math.min(1.0, srcA * 0.94);
const outA = depositA + dstA * (1.0 - depositA);
if (outA > 0.0005) {
- const invOut = 1.0 / outA;
- ch.r[idx] = (sr * depositA + ch.r[idx] * dstA * (1.0 - depositA)) * invOut;
- ch.g[idx] = (sg * depositA + ch.g[idx] * dstA * (1.0 - depositA)) * invOut;
- ch.b[idx] = (sb * depositA + ch.b[idx] * dstA * (1.0 - depositA)) * invOut;
+ const dr = ch.r[idx];
+ const dg = ch.g[idx];
+ const db = ch.b[idx];
+ if (
+ usePigmentBlend &&
+ dstA > 0.002 &&
+ (sr - dr) * (sr - dr) + (sg - dg) * (sg - dg) + (sb - db) * (sb - db) > 16
+ ) {
+ pigmentMixRgbOut(dr, dg, db, sr, sg, sb, depositA / outA, pigmentStrength, mixScratch);
+ ch.r[idx] = mixScratch.r;
+ ch.g[idx] = mixScratch.g;
+ ch.b[idx] = mixScratch.b;
+ } else {
+ const invOut = 1.0 / outA;
+ const dstW = dstA * (1.0 - depositA);
+ ch.r[idx] = (sr * depositA + dr * dstW) * invOut;
+ ch.g[idx] = (sg * depositA + dg * dstW) * invOut;
+ ch.b[idx] = (sb * depositA + db * dstW) * invOut;
+ }
ch.a[idx] = outA;
}
ch.height[idx] = ch.height[idx] * (1.0 - depositA * 0.78) + strandH * (0.22 + depositA * 0.85);
@@ -727,7 +832,6 @@ export class NaturalPaintStrokeSession {
}
ch.lastArcU[idx] = arcU;
- ch.tooth[idx] = hCanvas;
}
}
}
@@ -797,6 +901,10 @@ export class NaturalPaintStrokeSession {
const gh = rh + border * 2;
let smoothPaintH: Float32Array | null = null;
let rawToothGrid: Float32Array | null = null;
+ let minPaintGx = gw;
+ let maxPaintGx = -1;
+ let minPaintGy = gh;
+ let maxPaintGy = -1;
if (impastoOn) {
const needed = gw * gh;
if (this.hGridRaw.length < needed) {
@@ -805,36 +913,57 @@ export class NaturalPaintStrokeSession {
this.hGridSmooth = new Float32Array(needed);
this.toothGrid = new Float32Array(needed);
}
+ if (this.rowPaintMinX.length < gh) {
+ this.rowPaintMinX = new Int32Array(gh);
+ this.rowPaintMaxX = new Int32Array(gh);
+ }
const rawH = this.hGridRaw;
const tmpH = this.hGridTmp;
smoothPaintH = this.hGridSmooth;
rawToothGrid = this.toothGrid;
- // Stage 1: Single-lookup dual-channel extraction:
- // - rawH: pure sculptural paint thickness (zero weave blur contamination!)
- // - rawToothGrid: unblurred high-DPI surface weave fallback
+ // Stage 1: Single-lookup dual-channel extraction with scanline chunk caching
for (let gy = 0; gy < gh; gy++) {
const wy = ry + gy - border;
const cy = wy >> CHUNK_SHIFT;
const lyOff = (wy & CHUNK_MASK) << CHUNK_SHIFT;
const rowOff = gy * gw;
+ let cachedCx = -999999;
+ let cachedCh: PaintChunk | undefined = undefined;
+ let rMin = gw;
+ let rMax = -1;
for (let gx = 0; gx < gw; gx++) {
const wx = rx + gx - border;
- const ch = this.getChunk(wx >> CHUNK_SHIFT, cy);
- if (!ch) {
+ const cx = wx >> CHUNK_SHIFT;
+ if (cx !== cachedCx) {
+ cachedCh = this.getChunk(cx, cy);
+ cachedCx = cx;
+ }
+ if (!cachedCh) {
rawH[rowOff + gx] = 0;
rawToothGrid[rowOff + gx] = 0.5;
continue;
}
const idx = lyOff + (wx & CHUNK_MASK);
- const a = ch.a[idx];
- rawToothGrid[rowOff + gx] = ch.tooth[idx];
+ const a = cachedCh.a[idx];
+ const tVal = cachedCh.tooth[idx];
+ rawToothGrid[rowOff + gx] = tVal < 0 ? 0.5 : tVal;
if (a <= 0.002) {
rawH[rowOff + gx] = 0;
continue;
}
// Pure volumetric paint height (thick oil ridges rise high, edges taper naturally to canvas)
- rawH[rowOff + gx] = ch.height[idx] * impDepth * 1.75 * Math.min(1.0, a * 1.45);
+ rawH[rowOff + gx] = cachedCh.height[idx] * impDepth * 1.75 * (a * 1.45 >= 1.0 ? 1.0 : a * 1.45);
+ if (gx < rMin) rMin = gx;
+ if (gx > rMax) rMax = gx;
+ }
+ this.rowPaintMinX[gy] = rMin;
+ this.rowPaintMaxX[gy] = rMax;
+ if (rMax >= rMin) {
+ if (rMin < minPaintGx) minPaintGx = rMin;
+ if (rMax > maxPaintGx) maxPaintGx = rMax;
+ if (gy < minPaintGy) minPaintGy = gy;
+ if (gy > maxPaintGy) maxPaintGy = gy;
}
}
@@ -863,40 +992,43 @@ export class NaturalPaintStrokeSession {
}
}
- // Fast bilinear height sampler inside smoothPaintH for smooth diagonal directional cast-shadow rays
- const sampleSmoothBilinear = (fx: number, fy: number): number => {
- if (!smoothPaintH) return 0;
- const ix = fx | 0;
- const iy = fy | 0;
- if (ix < 0 || iy < 0 || ix >= gw - 1 || iy >= gh - 1) return 0;
- const tx = fx - ix;
- const ty = fy - iy;
- const r0 = iy * gw + ix;
- const r1 = r0 + gw;
- const v00 = smoothPaintH[r0];
- const v10 = smoothPaintH[r0 + 1];
- const v01 = smoothPaintH[r1];
- const v11 = smoothPaintH[r1 + 1];
- const top = v00 + (v10 - v00) * tx;
- const bot = v01 + (v11 - v01) * tx;
- return top + (bot - top) * ty;
- };
-
+ // 5 adaptive horizon-shadow taps marching toward the directional light source (1.2px .. 7.8px)
+ const shadowScale = 1.55 + impContrast * 1.45;
const marchCastShadow = (gxIdx: number, gyIdx: number, h0: number): number => {
+ if (!smoothPaintH) return 0;
let maxOcc = 0;
- // 8 physical horizon-shadow taps marching toward the directional light source (1.0px .. 8.0px)
- for (let step = 1; step <= 8; step++) {
- const dist = step * 1.0;
- const hS = sampleSmoothBilinear(gxIdx + dlx * dist, gyIdx + dly * dist);
+ const gwM1 = gw - 1;
+ const ghM1 = gh - 1;
+ // Adaptive distances [1.2, 2.5, 4.0, 5.8, 7.8] preserve crisp contact hugs + soft penumbra with 38% fewer taps
+ for (let step = 0; step < 5; step++) {
+ const dist = step === 0 ? 1.2 : step === 1 ? 2.5 : step === 2 ? 4.0 : step === 3 ? 5.8 : 7.8;
+ const fx = gxIdx + dlx * dist;
+ const fy = gyIdx + dly * dist;
+ const ix = fx | 0;
+ const iy = fy | 0;
+ if (ix < 0 || iy < 0 || ix >= gwM1 || iy >= ghM1) continue;
+ const tx = fx - ix;
+ const ty = fy - iy;
+ const r0 = iy * gw + ix;
+ const r1 = r0 + gw;
+ const v00 = smoothPaintH[r0];
+ const v10 = smoothPaintH[r0 + 1];
+ const v01 = smoothPaintH[r1];
+ const v11 = smoothPaintH[r1 + 1];
+ const top = v00 + (v10 - v00) * tx;
+ const bot = v01 + (v11 - v01) * tx;
+ const hS = top + (bot - top) * ty;
const occ = hS - (h0 + raySlope * dist);
if (occ > 0) {
- // Crisp hugging contact shadow near the paint rim, softening naturally into a delicate penumbra
- const distFade = Math.max(0, 1.0 - dist * 0.115);
- const soft = occ * distFade * distFade * 1.25;
- if (soft > maxOcc) maxOcc = soft;
+ const distFade = 1.0 - dist * 0.115;
+ if (distFade > 0) {
+ const soft = occ * distFade * distFade * 1.25;
+ if (soft > maxOcc) maxOcc = soft;
+ }
}
}
- return Math.min(1.0, maxOcc * (1.55 + impContrast * 1.45));
+ const res = maxOcc * shadowScale;
+ return res >= 1.0 ? 1.0 : res;
};
// Use true 2x-DPI analytical surface gradients for built-in canvas-locked / random-per-stroke textures
@@ -905,6 +1037,7 @@ export class NaturalPaintStrokeSession {
(this.grainParams.mappingMode === 'canvas-locked' ||
this.grainParams.mappingMode === 'random-per-stroke');
const gradScratch = { gx: 0, gy: 0 };
+ const hasPaintedBBox = maxPaintGx >= minPaintGx && maxPaintGy >= minPaintGy;
for (let y = 0; y < rh; y++) {
const wy = ry + y;
@@ -915,10 +1048,23 @@ export class NaturalPaintStrokeSession {
const gRowU = (gyIdx - 1) * gw;
const gRowC = gyIdx * gw;
const gRowD = (gyIdx + 1) * gw;
+ const canRowReceiveCast =
+ impastoOn &&
+ impDepth > 0.25 &&
+ hasPaintedBBox &&
+ gyIdx >= minPaintGy - 9 &&
+ gyIdx <= maxPaintGy + 9;
+ let cachedCx = -999999;
+ let cachedCh: PaintChunk | undefined = undefined;
for (let x = 0; x < rw; x++) {
const wx = rx + x;
- const ch = this.getChunk(wx >> CHUNK_SHIFT, cy);
+ const cx = wx >> CHUNK_SHIFT;
+ if (cx !== cachedCx) {
+ cachedCh = this.getChunk(cx, cy);
+ cachedCx = cx;
+ }
+ const ch = cachedCh;
const outIdx = rowOut + x * 4;
const gxIdx = x + border;
@@ -927,7 +1073,12 @@ export class NaturalPaintStrokeSession {
// Bare canvas / lower-layer pixel: check if a genuinely thick impasto ridge casts a subtle shadow
if (alpha <= 0.003) {
- if (impastoOn && impDepth > 0.25 && smoothPaintH) {
+ if (
+ canRowReceiveCast &&
+ smoothPaintH &&
+ gxIdx >= minPaintGx - 9 &&
+ gxIdx <= maxPaintGx + 9
+ ) {
const castS = marchCastShadow(gxIdx, gyIdx, 0);
if (castS > 0.08) {
const shadowAlpha = Math.min(0.18, Math.pow(castS, 1.35) * (0.08 + impDepth * 0.14));
@@ -948,7 +1099,8 @@ export class NaturalPaintStrokeSession {
let r = ch!.r[idx];
let g = ch!.g[idx];
let b = ch!.b[idx];
- const tooth = ch!.tooth[idx];
+ const rawTooth = ch!.tooth[idx];
+ const tooth = rawTooth < 0 ? 0.5 : rawTooth;
const hp = ch!.height[idx];
// Watercolor granulation: pigment particles settle into recessed paper valleys
@@ -1187,22 +1339,69 @@ export class NaturalPaintStrokeSession {
}
}
- public drawCubicSegment(
- ctx: CanvasRenderingContext2D,
+ /**
+ * Rasterizes a cubic segment into sparse RGBA+Height chunks and accumulates its dirty bounds
+ * for deferred single-pass per-frame shading (`flushPendingDirtyToContext`).
+ */
+ public appendCubicSegment(
p0: Point,
c1: Point,
c2: Point,
p3: Point,
- sampler?: LayerPixelSampler,
- replaceRegion: boolean = true
- ): void {
+ sampler?: LayerPixelSampler
+ ): { minX: number; minY: number; maxX: number; maxY: number } | null {
this.hasEmittedSegment = true;
this.pendingTapPoint = null;
const batch = this.engine.emitCubicSegment(p0, c1, c2, p3, sampler);
const dirty = this.rasterizeBatch(batch);
if (dirty) {
- this.flushDirtyRectToContext(ctx, dirty, replaceRegion, 1.0, 'source-over');
+ if (dirty.minX < this.pendingDirtyMinX) this.pendingDirtyMinX = dirty.minX;
+ if (dirty.minY < this.pendingDirtyMinY) this.pendingDirtyMinY = dirty.minY;
+ if (dirty.maxX > this.pendingDirtyMaxX) this.pendingDirtyMaxX = dirty.maxX;
+ if (dirty.maxY > this.pendingDirtyMaxY) this.pendingDirtyMaxY = dirty.maxY;
+ }
+ return dirty;
+ }
+
+ /**
+ * Shades and blits all segments accumulated since the previous frame flush in ONE pass.
+ */
+ public flushPendingDirtyToContext(
+ ctx: CanvasRenderingContext2D,
+ replaceRegion: boolean = true
+ ): { minX: number; minY: number; maxX: number; maxY: number } | null {
+ if (
+ !Number.isFinite(this.pendingDirtyMinX) ||
+ !Number.isFinite(this.pendingDirtyMaxX) ||
+ this.pendingDirtyMaxX < this.pendingDirtyMinX
+ ) {
+ return null;
}
+ const dirty = {
+ minX: this.pendingDirtyMinX,
+ minY: this.pendingDirtyMinY,
+ maxX: this.pendingDirtyMaxX,
+ maxY: this.pendingDirtyMaxY,
+ };
+ this.pendingDirtyMinX = Infinity;
+ this.pendingDirtyMinY = Infinity;
+ this.pendingDirtyMaxX = -Infinity;
+ this.pendingDirtyMaxY = -Infinity;
+ this.flushDirtyRectToContext(ctx, dirty, replaceRegion, 1.0, 'source-over');
+ return dirty;
+ }
+
+ public drawCubicSegment(
+ ctx: CanvasRenderingContext2D,
+ p0: Point,
+ c1: Point,
+ c2: Point,
+ p3: Point,
+ sampler?: LayerPixelSampler,
+ replaceRegion: boolean = true
+ ): void {
+ this.appendCubicSegment(p0, c1, c2, p3, sampler);
+ this.flushPendingDirtyToContext(ctx, replaceRegion);
}
public getDirtyBounds(): { minX: number; minY: number; maxX: number; maxY: number } | null {
diff --git a/src/engine/RibbonBrushEngine.ts b/src/engine/RibbonBrushEngine.ts
new file mode 100644
index 0000000..cbe2406
--- /dev/null
+++ b/src/engine/RibbonBrushEngine.ts
@@ -0,0 +1,2136 @@
+/**
+ * RibbonBrushEngine.ts
+ * Clip Studio Paint Ribbon Brush Engine (`BrushRibbon = 1`).
+ *
+ * Continuously deforms single or multi-subTip brush textures along a stroke's
+ * centripetal Catmull-Rom centerline with:
+ * - Dynamic width w(s) (pressure, sizeSensor, taper), alpha a(s), and pressure p(s)
+ * - Aspect-preserving arc-length UV integration scaled by local width & thickness
+ * - Base angle orientation relative to stroke direction (cardinal & arbitrary angles)
+ * - Miter clamping, bevel corner subdivision, and anti-bowtie winding guard
+ * - Repeat modes: `repeat`, `reverse` (ping-pong), `once` (stretch 0..1 across stroke)
+ * - Multi-subTip selection per tile (`sequential`, `reverse`, `random`, `random-no-repeat`, `once`, `direction`)
+ * - Per-tile `flipH` / `flipV`, `isColorTip`, monochrome tint, and `isDualToneTip`
+ * - World-space `paperTexture` modulation and 4-stage `antiAlias` (0..3)
+ * - Dual backend: WebGL textured triangle mesh shader + exact CPU scanline barycentric fallback
+ */
+
+import {
+ BrushSettings,
+ CanvasColorMode,
+ CspPaperTextureMode,
+ CspSensorConfig,
+ CspSubTip,
+ CspSubTipOrder,
+ CspTaperSettings,
+ CspTipFlipMode,
+ Point,
+ SurfaceTextureId,
+ ToolType,
+} from '../types/editor';
+import { enforceColorMode } from '../utils/colorUtils';
+import { parseColorToRgb } from '../utils/colorMixingEngine';
+import {
+ getSurfaceTextureHeightField,
+ SURFACE_TEXTURE_SIZE,
+} from '../utils/proceduralBrushTips';
+import { performanceManager } from '../utils/performanceManager';
+import {
+ applyCspPaperTextureAlpha,
+ applyCspPostCorrection,
+ buildCubicArcLengthTable,
+ centripetalCatmullRomToBezier,
+ computeCspTiltMagnitude,
+ dabHashFloat,
+ evaluateCspSensor,
+ evaluateCspTaperFactors,
+ evaluateFastSpline,
+ getCubicPointAtArcLength,
+ getCustomPaperLuminance,
+ GRAIN_SIZE,
+ paperGrainTable,
+ resolveBrushPresetSettings,
+ resolveTipFlipSigns,
+} from './BrushEngine';
+import { isNaturalPaintBrush } from './NaturalPaintRenderer';
+import {
+ RIBBON_VERTEX_STRIDE,
+ TexturedRibbonMeshInput,
+ WebGlBrushEngine,
+} from './WebGlBrushEngine';
+import type { CubicBezierSegment } from './SplineGenerator';
+
+export { RIBBON_VERTEX_STRIDE };
+
+export type RibbonRepeatMode = 'repeat' | 'reverse' | 'once';
+
+export interface RibbonBounds {
+ minX: number;
+ minY: number;
+ maxX: number;
+ maxY: number;
+}
+
+export interface RibbonCenterlineSample {
+ x: number;
+ y: number;
+ s: number;
+ sNorm: number;
+ tx: number;
+ ty: number;
+ nx: number;
+ ny: number;
+ width: number;
+ ribbonWidth: number;
+ tilePeriod: number;
+ alpha: number;
+ pressure: number;
+}
+
+export interface RibbonMesh extends TexturedRibbonMeshInput {
+ /** Number of triangles (`vertexCount / 3`). */
+ triangleCount: number;
+ /** Sampled centerline nodes along the stroke. */
+ centerline: RibbonCenterlineSample[];
+ /** Total stroke arc length in pixels. */
+ totalLength: number;
+}
+
+export interface RibbonTipSurface {
+ data: Uint8ClampedArray;
+ width: number;
+ height: number;
+ isColor?: boolean;
+ isDualToneTip?: boolean;
+}
+
+export interface RibbonRenderOptions {
+ size?: number;
+ minSizeFactor?: number;
+ opacity?: number;
+ flow?: number;
+ brushDensity?: number;
+ hardness?: number;
+ thickness?: number;
+ thicknessVertical?: boolean;
+ thicknessSensor?: CspSensorConfig;
+ angle?: number;
+ flipH?: CspTipFlipMode;
+ flipV?: CspTipFlipMode;
+ antiAlias?: number;
+ usePressure?: boolean;
+ pressureCurve?: [number, number][];
+ useTilt?: boolean;
+ tiltScale?: number;
+ sizeSensor?: CspSensorConfig;
+ opacitySensor?: CspSensorConfig;
+ densitySensor?: CspSensorConfig;
+ grainPenetrationSensor?: CspSensorConfig;
+ taper?: CspTaperSettings;
+ tipImage?: HTMLImageElement;
+ subTips?: CspSubTip[];
+ subTipOrder?: CspSubTipOrder;
+ subTipImages?: HTMLImageElement[];
+ /** Optional pre-extracted RGBA tip surfaces (useful for CPU rendering and headless tests). */
+ tipSurfaces?: RibbonTipSurface[];
+ ribbonRepeatMode?: RibbonRepeatMode;
+ isColorTip?: boolean;
+ isDualToneTip?: boolean;
+ primaryColor?: string;
+ secondaryColor?: string;
+ grain?: number;
+ textureDensity?: number;
+ surfaceTextureId?: SurfaceTextureId;
+ paperTextureImage?: HTMLImageElement;
+ paperTextureMode?: CspPaperTextureMode;
+ paperTextureScale?: number;
+ paperTextureRotate?: number;
+ paperTextureBrightness?: number;
+ paperTextureContrast?: number;
+ paperTextureInverted?: boolean;
+ paperTextureApplyEachPlot?: boolean;
+ paperTextureEmphasizeDensity?: boolean;
+ useGpu?: boolean;
+ isEraser?: boolean;
+ isBgEraser?: boolean;
+ alphaLocked?: boolean;
+ isTransparentInk?: boolean;
+ totalLength?: number;
+ exitSpeed?: number;
+ strokeSeed?: number;
+}
+
+interface InternalSlice {
+ lx: number;
+ ly: number;
+ rx: number;
+ ry: number;
+ cx: number;
+ cy: number;
+ s: number;
+ sNorm: number;
+ alpha: number;
+ pressure: number;
+ ribbonWidth: number;
+ tx: number;
+ ty: number;
+}
+
+interface TipMetric {
+ naturalW: number;
+ naturalH: number;
+ rawW: number;
+ rawH: number;
+ maxRaw: number;
+ projAlongNorm: number;
+ projAcrossNorm: number;
+ cosA: number;
+ sinA: number;
+ hasAngle: boolean;
+}
+
+// ============================================================================
+// 1. Predicate, Repeat Mode, and Sub-Tip Selection Helpers
+// ============================================================================
+
+/**
+ * Returns true when a BrushSettings or render options object should route through
+ * the Clip Studio Paint Ribbon brush engine (not Natural Paint and not Spray).
+ */
+export function isRibbonBrush(
+ bs: Partial<BrushSettings> | { isRibbon?: boolean; spray?: { enabled?: boolean }; renderMode?: string; naturalPaint?: { enabled?: boolean }; impasto?: { enabled?: boolean } } | undefined
+): boolean {
+ if (!bs || !bs.isRibbon) return false;
+ if (bs.spray?.enabled) return false;
+ if (isNaturalPaintBrush(bs as Partial<BrushSettings>)) return false;
+ return true;
+}
+
+export function resolveRibbonRepeatMode(
+ subTipOrder?: CspSubTipOrder,
+ explicitMode?: RibbonRepeatMode
+): RibbonRepeatMode {
+ if (explicitMode === 'repeat' || explicitMode === 'reverse' || explicitMode === 'once') {
+ return explicitMode;
+ }
+ if (subTipOrder === 'once') return 'once';
+ if (subTipOrder === 'reverse') return 'reverse';
+ return 'repeat';
+}
+
+export function selectRibbonSubTipIndex(
+ count: number,
+ order: CspSubTipOrder = 'sequential',
+ tileIndex: number = 0,
+ tangentAngle: number = 0,
+ seedX: number = 0,
+ seedY: number = 0
+): number {
+ if (count <= 1) return 0;
+ const safeTile = Math.max(0, Math.floor(tileIndex));
+ if (order === 'random') {
+ return Math.floor(dabHashFloat(seedX, seedY, safeTile, 97) * count) % count;
+ }
+ if (order === 'random-no-repeat') {
+ let idx = Math.floor(dabHashFloat(seedX, seedY, 0, 97) * count) % count;
+ if (count === 2) {
+ return (idx + safeTile) & 1;
+ }
+ const span = count - 1;
+ for (let t = 1; t <= safeTile; t++) {
+ const step = 1 + (Math.floor(dabHashFloat(seedX, seedY, t, 97) * span) % span);
+ idx = (idx + step) % count;
+ }
+ return idx;
+ }
+ if (order === 'once') {
+ return Math.min(safeTile, count - 1);
+ }
+ if (order === 'reverse') {
+ return (count - 1 - (safeTile % count) + count) % count;
+ }
+ if (order === 'direction') {
+ const normAngle = ((tangentAngle % (Math.PI * 2)) + Math.PI * 2) % (Math.PI * 2);
+ return Math.floor((normAngle / (Math.PI * 2)) * count) % count;
+ }
+ return safeTile % count;
+}
+
+// ============================================================================
+// 2. Tip Pixel Extraction & Procedural Fallback Tip Cache
+// ============================================================================
+
+const tipSurfaceCache = new WeakMap<object, RibbonTipSurface>();
+const proceduralRibbonTipCache = new Map<string, RibbonTipSurface>();
+
+function getProceduralRibbonTip(hardness: number = 1.0): RibbonTipSurface {
+ const qH = Math.round(Math.max(0, Math.min(1, hardness)) * 20) / 20;
+ const key = `proc_${qH}`;
+ const cached = proceduralRibbonTipCache.get(key);
+ if (cached) return cached;
+
+ const size = 64;
+ const data = new Uint8ClampedArray(size * size * 4);
+ const cy = (size - 1) * 0.5;
+ const maxDist = size * 0.5;
+ const inner = maxDist * Math.min(0.95, qH);
+
+ for (let y = 0; y < size; y++) {
+ const dy = Math.abs(y - cy);
+ let a = 0;
+ if (dy <= inner) {
+ a = 1;
+ } else if (dy < maxDist) {
+ const t = (dy - inner) / Math.max(1e-4, maxDist - inner);
+ a = qH <= 0.05 ? 0.5 * (1 + Math.cos(t * Math.PI)) : 1 - (3 * t * t - 2 * t * t * t);
+ }
+ const aByte = Math.max(0, Math.min(255, Math.round(a * 255)));
+ for (let x = 0; x < size; x++) {
+ const p = (y * size + x) * 4;
+ data[p] = 255;
+ data[p + 1] = 255;
+ data[p + 2] = 255;
+ data[p + 3] = aByte;
+ }
+ }
+
+ const surf: RibbonTipSurface = { data, width: size, height: size, isColor: false, isDualToneTip: false };
+ proceduralRibbonTipCache.set(key, surf);
+ return surf;
+}
+
+export function extractTipSurface(
+ image: HTMLImageElement | HTMLCanvasElement | undefined,
+ meta?: { isColor?: boolean; isDualToneTip?: boolean }
+): RibbonTipSurface | null {
+ if (!image) return null;
+
+ // Support synthetic test image objects carrying direct RGBA buffers
+ const anyImg = image as unknown as {
+ __rgbaData?: Uint8ClampedArray;
+ data?: Uint8ClampedArray;
+ naturalWidth?: number;
+ naturalHeight?: number;
+ width?: number;
+ height?: number;
+ complete?: boolean;
+ };
+ const directBuf = anyImg.__rgbaData || (anyImg.data instanceof Uint8ClampedArray ? anyImg.data : undefined);
+ if (directBuf) {
+ const w = anyImg.naturalWidth || anyImg.width || 0;
+ const h = anyImg.naturalHeight || anyImg.height || 0;
+ if (w > 0 && h > 0 && directBuf.length >= w * h * 4) {
+ return {
+ data: directBuf,
+ width: w,
+ height: h,
+ isColor: meta?.isColor,
+ isDualToneTip: meta?.isDualToneTip,
+ };
+ }
+ }
+
+ const cached = tipSurfaceCache.get(image);
+ if (cached) {
+ if (meta?.isColor !== undefined || meta?.isDualToneTip !== undefined) {
+ return {
+ ...cached,
+ isColor: meta.isColor ?? cached.isColor,
+ isDualToneTip: meta.isDualToneTip ?? cached.isDualToneTip,
+ };
+ }
+ return cached;
+ }
+
+ if (typeof document === 'undefined') return null;
+ if ('complete' in image && image.complete === false) return null;
+ const w = ('naturalWidth' in image ? image.naturalWidth : 0) || image.width || 0;
+ const h = ('naturalHeight' in image ? image.naturalHeight : 0) || image.height || 0;
+ if (w <= 0 || h <= 0) return null;
+
+ try {
+ const c = document.createElement('canvas');
+ c.width = w;
+ c.height = h;
+ const ctx = c.getContext('2d', { willReadFrequently: true });
+ if (!ctx || typeof ctx.getImageData !== 'function') return null;
+ ctx.clearRect(0, 0, w, h);
+ ctx.drawImage(image, 0, 0, w, h);
+ const imgData = ctx.getImageData(0, 0, w, h);
+ const surf: RibbonTipSurface = {
+ data: imgData.data,
+ width: w,
+ height: h,
+ isColor: meta?.isColor,
+ isDualToneTip: meta?.isDualToneTip,
+ };
+ tipSurfaceCache.set(image, surf);
+ return surf;
+ } catch {
+ return null;
+ }
+}
+
+export function resolveRibbonTipSurfaces(options: RibbonRenderOptions): RibbonTipSurface[] {
+ if (options.tipSurfaces && options.tipSurfaces.length > 0) {
+ return options.tipSurfaces;
+ }
+
+ const surfaces: RibbonTipSurface[] = [];
+ if (options.subTipImages && options.subTipImages.length > 0) {
+ for (let i = 0; i < options.subTipImages.length; i++) {
+ const meta = options.subTips?.[i];
+ const s = extractTipSurface(options.subTipImages[i], {
+ isColor: meta?.isColor ?? options.isColorTip,
+ isDualToneTip: meta?.isDualToneTip ?? options.isDualToneTip,
+ });
+ if (s) surfaces.push(s);
+ }
+ }
+
+ if (surfaces.length === 0 && options.tipImage) {
+ const s = extractTipSurface(options.tipImage, {
+ isColor: options.isColorTip ?? options.subTips?.[0]?.isColor,
+ isDualToneTip: options.isDualToneTip ?? options.subTips?.[0]?.isDualToneTip,
+ });
+ if (s) surfaces.push(s);
+ }
+
+ if (surfaces.length === 0) {
+ surfaces.push(getProceduralRibbonTip(options.hardness ?? 1.0));
+ }
+
+ return surfaces;
+}
+
+function buildTipMetrics(options: RibbonRenderOptions): TipMetric[] {
+ const thickness = Math.max(0.05, Math.min(20.0, options.thickness ?? 1.0));
+ const thicknessVertical = Boolean(options.thicknessVertical);
+ // Clip Studio Paint Ribbon orientation convention (`BrushRibbon = 1`):
+ // At BrushRotation = 0°, the tip image's vertical axis (+Y, top-to-bottom) flows ALONG the
+ // stroke and its horizontal axis (+X, left-to-right) spans ACROSS the stroke width.
+ // Rotating by +90° (e.g. CSP's built-in Chain.sut with a 300x27 horizontal strip and
+ // BrushRotation = 90°) aligns +X along the stroke and +Y across the stroke width.
+ const normDeg = ((((options.angle ?? 0) - 90) % 360) + 360) % 360;
+ const hasAngle = normDeg > 1e-4 && Math.abs(normDeg - 360) > 1e-4;
+ const angleRad = (normDeg * Math.PI) / 180;
+ let cosA = hasAngle ? Math.cos(angleRad) : 1.0;
+ let sinA = hasAngle ? Math.sin(angleRad) : 0.0;
+ if (Math.abs(cosA) < 1e-12) cosA = 0.0;
+ if (Math.abs(sinA) < 1e-12) sinA = 0.0;
+
+ const makeMetric = (w: number, h: number): TipMetric => {
+ const safeW = w > 0 ? w : 64;
+ const safeH = h > 0 ? h : 64;
+ const rawW = thicknessVertical ? safeW * thickness : safeW;
+ const rawH = thicknessVertical ? safeH : safeH * thickness;
+ const maxRaw = Math.max(rawW, rawH, 1e-4);
+ // In CSP Ribbon mode, BrushSize defines the across-stroke ribbon width (at thickness = 100%),
+ // and the along-stroke tile period scales uniformly to preserve the tip's natural aspect ratio.
+ const baseProjAcross = Math.max(1e-4, safeW * Math.abs(sinA) + safeH * Math.abs(cosA));
+ const projAlongRaw = rawW * Math.abs(cosA) + rawH * Math.abs(sinA);
+ const projAcrossRaw = rawW * Math.abs(sinA) + rawH * Math.abs(cosA);
+ const projAlongNorm = projAlongRaw / baseProjAcross;
+ const projAcrossNorm = projAcrossRaw / baseProjAcross;
+ return {
+ naturalW: safeW,
+ naturalH: safeH,
+ rawW,
+ rawH,
+ maxRaw,
+ projAlongNorm: Math.max(0.05, Math.min(64.0, projAlongNorm)),
+ projAcrossNorm: Math.max(0.05, Math.min(20.0, projAcrossNorm)),
+ cosA,
+ sinA,
+ hasAngle,
+ };
+ };
+
+ if (options.tipSurfaces && options.tipSurfaces.length > 0) {
+ return options.tipSurfaces.map((s) => makeMetric(s.width, s.height));
+ }
+ if (options.subTipImages && options.subTipImages.length > 0) {
+ return options.subTipImages.map((img, i) => {
+ const w = img.naturalWidth || img.width || options.subTips?.[i]?.width || 64;
+ const h = img.naturalHeight || img.height || options.subTips?.[i]?.height || 64;
+ return makeMetric(w, h);
+ });
+ }
+ if (options.tipImage) {
+ const w = options.tipImage.naturalWidth || options.tipImage.width || options.subTips?.[0]?.width || 64;
+ const h = options.tipImage.naturalHeight || options.tipImage.height || options.subTips?.[0]?.height || 64;
+ return [makeMetric(w, h)];
+ }
+ if (options.subTips && options.subTips.length > 0) {
+ return options.subTips.map((st) => makeMetric(st.width || 64, st.height || 64));
+ }
+ return [makeMetric(64, 64)];
+}
+
+// ============================================================================
+// 3. Centerline Sampling (Centripetal Catmull-Rom + CSP Dynamics & Taper)
+// ============================================================================
+
+function evaluateSampleDynamics(
+ x: number,
+ y: number,
+ rawWidth: number,
+ rawPressure: number,
+ speedPx: number,
+ tiltX: number,
+ tiltY: number,
+ strokeDist: number,
+ totalLength: number | undefined,
+ sampleIndex: number,
+ options: RibbonRenderOptions
+): { width: number; thicknessScale: number; alpha: number; pressure: number } {
+ const effPressure = Math.max(0, Math.min(1, rawPressure));
+ const curvedPressure = options.pressureCurve
+ ? evaluateFastSpline(effPressure, options.pressureCurve)
+ : effPressure;
+ const minFactor = Math.max(0, Math.min(1.0, options.minSizeFactor ?? 0));
+
+ let curWidth =
+ rawWidth > 0
+ ? rawWidth
+ : options.usePressure !== false
+ ? (options.size ?? 10) * (minFactor + (1.0 - minFactor) * curvedPressure)
+ : options.size ?? 10;
+
+ const taperFactors = evaluateCspTaperFactors(
+ options.taper,
+ strokeDist,
+ totalLength,
+ options.exitSpeed
+ );
+ curWidth *= taperFactors.sizeScale;
+
+ const readTilt = Boolean(
+ options.useTilt ||
+ options.sizeSensor?.useTilt ||
+ options.thicknessSensor?.useTilt ||
+ options.opacitySensor?.useTilt ||
+ options.densitySensor?.useTilt
+ );
+ const tX = readTilt ? tiltX : 0;
+ const tY = readTilt ? tiltY : 0;
+ const tiltMagnitude = computeCspTiltMagnitude(tX, tY);
+
+ if (options.sizeSensor) {
+ const effectiveSizeSensor =
+ rawWidth > 0 && options.usePressure !== false && options.sizeSensor.usePressure
+ ? { ...options.sizeSensor, usePressure: false }
+ : options.sizeSensor;
+ curWidth *= evaluateCspSensor(
+ effectiveSizeSensor,
+ effPressure,
+ tiltMagnitude,
+ speedPx * 0.05,
+ dabHashFloat(x, y, sampleIndex, 50),
+ 0,
+ strokeDist
+ );
+ }
+ curWidth = Math.max(0.2, curWidth);
+
+ let thicknessScale = 1.0;
+ if (options.thicknessSensor) {
+ thicknessScale = Math.max(
+ 0.1,
+ Math.min(
+ 10.0,
+ evaluateCspSensor(
+ options.thicknessSensor,
+ effPressure,
+ tiltMagnitude,
+ speedPx * 0.05,
+ dabHashFloat(x, y, sampleIndex, 54),
+ 0,
+ strokeDist
+ )
+ )
+ );
+ }
+
+ const baseFlow = Math.max(0, Math.min(1, options.brushDensity ?? options.flow ?? 1.0));
+ let curAlpha = baseFlow * taperFactors.alphaScale;
+
+ if (options.opacitySensor) {
+ curAlpha *= evaluateCspSensor(
+ options.opacitySensor,
+ effPressure,
+ tiltMagnitude,
+ speedPx * 0.05,
+ dabHashFloat(x, y, sampleIndex, 51),
+ 0,
+ strokeDist
+ );
+ }
+ if (options.densitySensor) {
+ curAlpha *= evaluateCspSensor(
+ options.densitySensor,
+ effPressure,
+ tiltMagnitude,
+ speedPx * 0.05,
+ dabHashFloat(x, y, sampleIndex, 52),
+ 0,
+ strokeDist
+ );
+ }
+
+ return {
+ width: curWidth,
+ thicknessScale,
+ alpha: Math.max(0, Math.min(1, curAlpha)),
+ pressure: effPressure,
+ };
+}
+
+function sampleCubicSegmentIntoCenterline(
+ out: RibbonCenterlineSample[],
+ p0: Point,
+ c1: Point,
+ c2: Point,
+ p3: Point,
+ options: RibbonRenderOptions,
+ metrics: TipMetric[],
+ state: { s: number; sNorm: number; sampleIdx: number; seedX: number; seedY: number; totalLength?: number }
+): void {
+ const table = buildCubicArcLengthTable(p0, c1, c2, p3);
+ const segLen = table.totalLength;
+ if (segLen < 1e-3) return;
+
+ const avgWidth = Math.max(2, (p0.width + p3.width) * 0.5 || (options.size ?? 12));
+ const baseStep = Math.max(0.85, Math.min(3.5, avgWidth * 0.16));
+ const numSteps = Math.max(2, Math.min(160, Math.ceil(segLen / baseStep)));
+
+ const startI = out.length === 0 ? 0 : 1;
+ const subTipOrder = options.subTipOrder ?? 'sequential';
+ const metricCount = metrics.length;
+
+ for (let i = startI; i <= numSteps; i++) {
+ const distOnSeg = (segLen * i) / numSteps;
+ const pt = getCubicPointAtArcLength(p0, c1, c2, p3, distOnSeg, table);
+
+ if (out.length > 0) {
+ const prev = out[out.length - 1];
+ const stepDx = pt.x - prev.x;
+ const stepDy = pt.y - prev.y;
+ const ds = Math.hypot(stepDx, stepDy);
+ if (ds < 0.12 && i < numSteps) continue;
+
+ let tx = pt.speed > 1e-4 ? pt.dx / pt.speed : ds > 1e-4 ? stepDx / ds : prev.tx;
+ let ty = pt.speed > 1e-4 ? pt.dy / pt.speed : ds > 1e-4 ? stepDy / ds : prev.ty;
+ const tLen = Math.hypot(tx, ty);
+ if (tLen > 1e-5) {
+ tx /= tLen;
+ ty /= tLen;
+ } else {
+ tx = prev.tx;
+ ty = prev.ty;
+ }
+
+ const nextS = state.s + ds;
+ const dyn = evaluateSampleDynamics(
+ pt.x,
+ pt.y,
+ pt.width,
+ pt.pressure,
+ pt.speed,
+ pt.tiltX,
+ pt.tiltY,
+ nextS,
+ state.totalLength,
+ state.sampleIdx++,
+ options
+ );
+
+ // Integrate sNorm with active tile's aspect-preserving tilePeriod
+ const activeTileIdx = Math.floor(state.sNorm);
+ const tipIdx = selectRibbonSubTipIndex(
+ metricCount,
+ subTipOrder,
+ activeTileIdx,
+ Math.atan2(ty, tx),
+ state.seedX,
+ state.seedY
+ );
+ const metric = metrics[tipIdx] ?? metrics[0];
+ const ribbonWidth = Math.max(0.25, dyn.width * metric.projAcrossNorm * dyn.thicknessScale);
+ const tilePeriod = Math.max(0.5, dyn.width * metric.projAlongNorm);
+ const avgPeriod = Math.max(0.5, 0.5 * (prev.tilePeriod + tilePeriod));
+ const nextSNorm = state.sNorm + ds / avgPeriod;
+
+ state.s = nextS;
+ state.sNorm = nextSNorm;
+
+ out.push({
+ x: pt.x,
+ y: pt.y,
+ s: nextS,
+ sNorm: nextSNorm,
+ tx,
+ ty,
+ nx: -ty,
+ ny: tx,
+ width: dyn.width,
+ ribbonWidth,
+ tilePeriod,
+ alpha: dyn.alpha,
+ pressure: dyn.pressure,
+ });
+ } else {
+ let tx = pt.speed > 1e-4 ? pt.dx / pt.speed : 1;
+ let ty = pt.speed > 1e-4 ? pt.dy / pt.speed : 0;
+ if (pt.speed <= 1e-4) {
+ const chDx = p3.x - p0.x;
+ const chDy = p3.y - p0.y;
+ const chL = Math.hypot(chDx, chDy);
+ if (chL > 1e-4) {
+ tx = chDx / chL;
+ ty = chDy / chL;
+ }
+ }
+ const dyn = evaluateSampleDynamics(
+ pt.x,
+ pt.y,
+ pt.width,
+ pt.pressure,
+ pt.speed,
+ pt.tiltX,
+ pt.tiltY,
+ state.s,
+ state.totalLength,
+ state.sampleIdx++,
+ options
+ );
+ const tipIdx = selectRibbonSubTipIndex(
+ metricCount,
+ subTipOrder,
+ Math.floor(state.sNorm),
+ Math.atan2(ty, tx),
+ state.seedX,
+ state.seedY
+ );
+ const metric = metrics[tipIdx] ?? metrics[0];
+ const ribbonWidth = Math.max(0.25, dyn.width * metric.projAcrossNorm * dyn.thicknessScale);
+ const tilePeriod = Math.max(0.5, dyn.width * metric.projAlongNorm);
+ out.push({
+ x: pt.x,
+ y: pt.y,
+ s: state.s,
+ sNorm: state.sNorm,
+ tx,
+ ty,
+ nx: -ty,
+ ny: tx,
+ width: dyn.width,
+ ribbonWidth,
+ tilePeriod,
+ alpha: dyn.alpha,
+ pressure: dyn.pressure,
+ });
+ }
+ }
+}
+
+export function sampleRibbonCenterlineFromPoints(
+ points: Point[],
+ options: RibbonRenderOptions
+): RibbonCenterlineSample[] {
+ if (!points || points.length === 0) return [];
+ const metrics = buildTipMetrics(options);
+ const seedX = points[0].x;
+ const seedY = points[0].y;
+
+ // Estimate total length for taper evaluation
+ let approxTotalLen = options.totalLength;
+ if (approxTotalLen === undefined) {
+ let sum = 0;
+ for (let i = 1; i < points.length; i++) {
+ sum += Math.hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y);
+ }
+ approxTotalLen = sum;
+ }
+
+ // Single-point tap or degenerate zero-length stroke: synthesize a 1-tile horizontal ribbon stamp
+ if (points.length === 1 || approxTotalLen < 0.25) {
+ const p = points[0];
+ const dyn = evaluateSampleDynamics(
+ p.x,
+ p.y,
+ p.width,
+ p.pressure,
+ 0,
+ p.tiltX ?? 0,
+ p.tiltY ?? 0,
+ 0,
+ undefined,
+ 0,
+ options
+ );
+ const m = metrics[0];
+ const ribbonWidth = Math.max(0.5, dyn.width * m.projAcrossNorm * dyn.thicknessScale);
+ const tilePeriod = Math.max(0.5, dyn.width * m.projAlongNorm);
+ const tapLen = Math.min(tilePeriod, Math.max(ribbonWidth, dyn.width));
+ const halfLen = tapLen * 0.5;
+ const tapSNorm = tapLen / tilePeriod;
+ return [
+ {
+ x: p.x - halfLen,
+ y: p.y,
+ s: 0,
+ sNorm: 0,
+ tx: 1,
+ ty: 0,
+ nx: 0,
+ ny: 1,
+ width: dyn.width,
+ ribbonWidth,
+ tilePeriod,
+ alpha: dyn.alpha,
+ pressure: dyn.pressure,
+ },
+ {
+ x: p.x + halfLen,
+ y: p.y,
+ s: tapLen,
+ sNorm: tapSNorm,
+ tx: 1,
+ ty: 0,
+ nx: 0,
+ ny: 1,
+ width: dyn.width,
+ ribbonWidth,
+ tilePeriod,
+ alpha: dyn.alpha,
+ pressure: dyn.pressure,
+ },
+ ];
+ }
+
+ const centerline: RibbonCenterlineSample[] = [];
+ const state = {
+ s: 0,
+ sNorm: 0,
+ sampleIdx: 0,
+ seedX,
+ seedY,
+ totalLength: approxTotalLen,
+ };
+
+ if (points.length === 2) {
+ const { c1, c2 } = centripetalCatmullRomToBezier(points[0], points[0], points[1], points[1]);
+ sampleCubicSegmentIntoCenterline(centerline, points[0], c1, c2, points[1], options, metrics, state);
+ } else {
+ const first = centripetalCatmullRomToBezier(points[0], points[0], points[1], points[2]);
+ sampleCubicSegmentIntoCenterline(centerline, points[0], first.c1, first.c2, points[1], options, metrics, state);
+
+ for (let i = 2; i < points.length - 1; i++) {
+ const seg = centripetalCatmullRomToBezier(
+ points[i - 2],
+ points[i - 1],
+ points[i],
+ points[i + 1]
+ );
+ sampleCubicSegmentIntoCenterline(centerline, points[i - 1], seg.c1, seg.c2, points[i], options, metrics, state);
+ }
+
+ const n = points.length;
+ const last = centripetalCatmullRomToBezier(points[n - 3], points[n - 2], points[n - 1], points[n - 1]);
+ sampleCubicSegmentIntoCenterline(centerline, points[n - 2], last.c1, last.c2, points[n - 1], options, metrics, state);
+ }
+
+ return centerline;
+}
+
+// ============================================================================
+// 4. Deformable Ribbon Mesh Builder (Miter Clamping, Bevel Corners, Anti-Bowtie)
+// ============================================================================
+
+function cross2(ax: number, ay: number, bx: number, by: number): number {
+ return ax * by - ay * bx;
+}
+
+function mapTileUvToTexUv(
+ u: number,
+ v: number,
+ metric: TipMetric,
+ flipX: number,
+ flipY: number
+): { uTex: number; vTex: number } {
+ let uTex: number;
+ let vTex: number;
+
+ if (!metric.hasAngle) {
+ uTex = u;
+ vTex = v;
+ } else {
+ const projAlong = metric.rawW * Math.abs(metric.cosA) + metric.rawH * Math.abs(metric.sinA);
+ const projAcross = metric.rawW * Math.abs(metric.sinA) + metric.rawH * Math.abs(metric.cosA);
+ const pAlong = (u - 0.5) * projAlong;
+ const pAcross = (v - 0.5) * projAcross;
+ const lx = pAlong * metric.cosA + pAcross * metric.sinA;
+ const ly = -pAlong * metric.sinA + pAcross * metric.cosA;
+ uTex = lx / metric.rawW + 0.5;
+ vTex = ly / metric.rawH + 0.5;
+ }
+
+ if (flipX < 0) uTex = 1.0 - uTex;
+ if (flipY < 0) vTex = 1.0 - vTex;
+ return { uTex, vTex };
+}
+
+function buildSlicesFromCenterline(
+ centerline: RibbonCenterlineSample[],
+ options: RibbonRenderOptions,
+ prevEdgeState?: { lx: number; ly: number; rx: number; ry: number; tx: number; ty: number; s: number; sNorm: number; alpha: number; pressure: number; ribbonWidth: number; cx: number; cy: number }
+): InternalSlice[] {
+ if (centerline.length < 2) return [];
+
+ // Deduplicate ultra-close points so segment tangents are always well-conditioned
+ const pts: RibbonCenterlineSample[] = [centerline[0]];
+ for (let i = 1; i < centerline.length; i++) {
+ const prev = pts[pts.length - 1];
+ const cur = centerline[i];
+ if (Math.hypot(cur.x - prev.x, cur.y - prev.y) >= 0.1 || i === centerline.length - 1) {
+ if (Math.hypot(cur.x - prev.x, cur.y - prev.y) >= 1e-4) {
+ pts.push(cur);
+ }
+ }
+ }
+ if (pts.length < 2) return [];
+
+ const m = pts.length;
+ const segTx = new Float64Array(m - 1);
+ const segTy = new Float64Array(m - 1);
+ const segNx = new Float64Array(m - 1);
+ const segNy = new Float64Array(m - 1);
+
+ for (let i = 0; i < m - 1; i++) {
+ const dx = pts[i + 1].x - pts[i].x;
+ const dy = pts[i + 1].y - pts[i].y;
+ const len = Math.hypot(dx, dy) || 1;
+ const tx = dx / len;
+ const ty = dy / len;
+ segTx[i] = tx;
+ segTy[i] = ty;
+ segNx[i] = -ty;
+ segNy[i] = tx;
+ }
+
+ const slices: InternalSlice[] = [];
+ const BEVEL_ANGLE_THRESHOLD = 0.22; // ~12.6 degrees
+ const MAX_MITER_SCALE = 1.45;
+ let extraSNorm = 0;
+
+ // Start slice
+ if (prevEdgeState) {
+ // Seamless stitching from previous live segment with corner bevel if direction turned
+ const t0x = prevEdgeState.tx;
+ const t0y = prevEdgeState.ty;
+ const t1x = segTx[0];
+ const t1y = segTy[0];
+ const dot = Math.max(-1, Math.min(1, t0x * t1x + t0y * t1y));
+ const cr = cross2(t0x, t0y, t1x, t1y);
+ const theta = Math.atan2(cr, dot);
+ slices.push({
+ lx: prevEdgeState.lx,
+ ly: prevEdgeState.ly,
+ rx: prevEdgeState.rx,
+ ry: prevEdgeState.ry,
+ cx: prevEdgeState.cx,
+ cy: prevEdgeState.cy,
+ s: prevEdgeState.s,
+ sNorm: prevEdgeState.sNorm,
+ alpha: prevEdgeState.alpha,
+ pressure: prevEdgeState.pressure,
+ ribbonWidth: prevEdgeState.ribbonWidth,
+ tx: t0x,
+ ty: t0y,
+ });
+ if (Math.abs(theta) >= BEVEL_ANGLE_THRESHOLD) {
+ const h = pts[0].ribbonWidth * 0.5;
+ const steps = Math.max(2, Math.min(8, Math.ceil(Math.abs(theta) / BEVEL_ANGLE_THRESHOLD)));
+ const n0Angle = Math.atan2(t0x, -t0y); // atan2(ny, nx) where nx=-ty, ny=tx
+ const midAngle = n0Angle + theta * 0.5;
+ const mx = Math.cos(midAngle);
+ const my = Math.sin(midAngle);
+ const innerSign = cr >= 0 ? 1 : -1;
+ const innerRad = h * Math.max(0, Math.cos(Math.min(Math.PI * 0.5, Math.abs(theta) * 0.5)));
+ const innerX = pts[0].x + innerSign * mx * innerRad;
+ const innerY = pts[0].y + innerSign * my * innerRad;
+ const cornerDu = (0.5 * Math.abs(theta) * h) / Math.max(0.5, pts[0].tilePeriod);
+ for (let k = 1; k <= steps; k++) {
+ const f = k / steps;
+ const a = n0Angle + theta * f;
+ const nkx = Math.cos(a);
+ const nky = Math.sin(a);
+ const outerX = pts[0].x - innerSign * nkx * h;
+ const outerY = pts[0].y - innerSign * nky * h;
+ const lx = innerSign > 0 ? outerX : innerX;
+ const ly = innerSign > 0 ? outerY : innerY;
+ const rx = innerSign > 0 ? innerX : outerX;
+ const ry = innerSign > 0 ? innerY : outerY;
+ slices.push({
+ lx,
+ ly,
+ rx,
+ ry,
+ cx: pts[0].x,
+ cy: pts[0].y,
+ s: pts[0].s,
+ sNorm: pts[0].sNorm + extraSNorm + cornerDu * f,
+ alpha: pts[0].alpha,
+ pressure: pts[0].pressure,
+ ribbonWidth: pts[0].ribbonWidth,
+ tx: nky,
+ ty: -nkx,
+ });
+ }
+ extraSNorm += cornerDu;
+ }
+ } else {
+ const p0 = pts[0];
+ const h0 = p0.ribbonWidth * 0.5;
+ slices.push({
+ lx: p0.x - segNx[0] * h0,
+ ly: p0.y - segNy[0] * h0,
+ rx: p0.x + segNx[0] * h0,
+ ry: p0.y + segNy[0] * h0,
+ cx: p0.x,
+ cy: p0.y,
+ s: p0.s,
+ sNorm: p0.sNorm,
+ alpha: p0.alpha,
+ pressure: p0.pressure,
+ ribbonWidth: p0.ribbonWidth,
+ tx: segTx[0],
+ ty: segTy[0],
+ });
+ }
+
+ // Interior centerline points
+ for (let i = 1; i < m - 1; i++) {
+ const p = pts[i];
+ const h = p.ribbonWidth * 0.5;
+ const t0x = segTx[i - 1];
+ const t0y = segTy[i - 1];
+ const n0x = segNx[i - 1];
+ const n0y = segNy[i - 1];
+ const t1x = segTx[i];
+ const t1y = segTy[i];
+ const n1x = segNx[i];
+ const n1y = segNy[i];
+
+ const dot = Math.max(-1, Math.min(1, t0x * t1x + t0y * t1y));
+ const cr = cross2(t0x, t0y, t1x, t1y);
+ const theta = Math.atan2(cr, dot);
+
+ if (Math.abs(theta) < BEVEL_ANGLE_THRESHOLD) {
+ let mx = n0x + n1x;
+ let my = n0y + n1y;
+ const mLen = Math.hypot(mx, my);
+ if (mLen > 1e-5) {
+ mx /= mLen;
+ my /= mLen;
+ } else {
+ mx = n0x;
+ my = n0y;
+ }
+ const cosHalf = Math.max(0.5, mx * n0x + my * n0y);
+ const miterLen = Math.min(h * MAX_MITER_SCALE, h / cosHalf);
+ slices.push({
+ lx: p.x - mx * miterLen,
+ ly: p.y - my * miterLen,
+ rx: p.x + mx * miterLen,
+ ry: p.y + my * miterLen,
+ cx: p.x,
+ cy: p.y,
+ s: p.s,
+ sNorm: p.sNorm + extraSNorm,
+ alpha: p.alpha,
+ pressure: p.pressure,
+ ribbonWidth: p.ribbonWidth,
+ tx: (t0x + t1x) * 0.5,
+ ty: (t0y + t1y) * 0.5,
+ });
+ } else {
+ // High-curvature corner: bevel / arc subdivision with pinned safe inner pivot
+ const steps = Math.max(2, Math.min(10, Math.ceil(Math.abs(theta) / BEVEL_ANGLE_THRESHOLD)));
+ const n0Angle = Math.atan2(n0y, n0x);
+ const midAngle = n0Angle + theta * 0.5;
+ const mx = Math.cos(midAngle);
+ const my = Math.sin(midAngle);
+ const innerSign = cr >= 0 ? 1 : -1; // +N (R) is inner when cross > 0; -N (L) is inner when cross < 0
+ const innerRad = h * Math.max(0, Math.cos(Math.min(Math.PI * 0.5, Math.abs(theta) * 0.5)));
+ const innerX = p.x + innerSign * mx * innerRad;
+ const innerY = p.y + innerSign * my * innerRad;
+ const cornerDu = (0.5 * Math.abs(theta) * h) / Math.max(0.5, p.tilePeriod);
+
+ for (let k = 0; k <= steps; k++) {
+ const f = k / steps;
+ const a = n0Angle + theta * f;
+ const nkx = Math.cos(a);
+ const nky = Math.sin(a);
+ const outerX = p.x - innerSign * nkx * h;
+ const outerY = p.y - innerSign * nky * h;
+ const lx = innerSign > 0 ? outerX : innerX;
+ const ly = innerSign > 0 ? outerY : innerY;
+ const rx = innerSign > 0 ? innerX : outerX;
+ const ry = innerSign > 0 ? innerY : outerY;
+
+ slices.push({
+ lx,
+ ly,
+ rx,
+ ry,
+ cx: p.x,
+ cy: p.y,
+ s: p.s,
+ sNorm: p.sNorm + extraSNorm + cornerDu * f,
+ alpha: p.alpha,
+ pressure: p.pressure,
+ ribbonWidth: p.ribbonWidth,
+ tx: nky,
+ ty: -nkx,
+ });
+ }
+ extraSNorm += cornerDu;
+ }
+ }
+
+ // End slice
+ const pLast = pts[m - 1];
+ const hLast = pLast.ribbonWidth * 0.5;
+ slices.push({
+ lx: pLast.x - segNx[m - 2] * hLast,
+ ly: pLast.y - segNy[m - 2] * hLast,
+ rx: pLast.x + segNx[m - 2] * hLast,
+ ry: pLast.y + segNy[m - 2] * hLast,
+ cx: pLast.x,
+ cy: pLast.y,
+ s: pLast.s,
+ sNorm: pLast.sNorm + extraSNorm,
+ alpha: pLast.alpha,
+ pressure: pLast.pressure,
+ ribbonWidth: pLast.ribbonWidth,
+ tx: segTx[m - 2],
+ ty: segTy[m - 2],
+ });
+
+ // In 'once' mode, normalize sNorm strictly across [0, tileSpan] from start to end of stroke
+ const repeatMode = resolveRibbonRepeatMode(options.subTipOrder, options.ribbonRepeatMode);
+ if (repeatMode === 'once' && !prevEdgeState && slices.length >= 2) {
+ const tipCount = Math.max(
+ 1,
+ options.tipSurfaces?.length ??
+ options.subTipImages?.length ??
+ options.subTips?.length ??
+ 1
+ );
+ const tileSpan = options.subTipOrder === 'once' && tipCount > 1 ? tipCount : 1.0;
+ const maxSNorm = Math.max(1e-5, slices[slices.length - 1].sNorm - slices[0].sNorm);
+ const baseSNorm = slices[0].sNorm;
+ for (let i = 0; i < slices.length; i++) {
+ slices[i].sNorm = ((slices[i].sNorm - baseSNorm) / maxSNorm) * tileSpan;
+ }
+ }
+
+ return slices;
+}
+
+export function buildRibbonMeshFromCenterline(
+ centerline: RibbonCenterlineSample[],
+ options: RibbonRenderOptions,
+ prevEdgeState?: { lx: number; ly: number; rx: number; ry: number; tx: number; ty: number; s: number; sNorm: number; alpha: number; pressure: number; ribbonWidth: number; cx: number; cy: number }
+): RibbonMesh {
+ const emptyBounds: RibbonBounds = { minX: 0, minY: 0, maxX: 0, maxY: 0 };
+ if (centerline.length < 2) {
+ return {
+ vertices: new Float32Array(0),
+ vertexCount: 0,
+ triangleCount: 0,
+ bounds: emptyBounds,
+ centerline,
+ totalLength: 0,
+ };
+ }
+
+ const metrics = buildTipMetrics(options);
+ const metricCount = metrics.length;
+ const repeatMode = resolveRibbonRepeatMode(options.subTipOrder, options.ribbonRepeatMode);
+ const subTipOrder = options.subTipOrder ?? 'sequential';
+ const seedX = centerline[0].x;
+ const seedY = centerline[0].y;
+
+ const slices = buildSlicesFromCenterline(centerline, options, prevEdgeState);
+ if (slices.length < 2) {
+ return {
+ vertices: new Float32Array(0),
+ vertexCount: 0,
+ triangleCount: 0,
+ bounds: emptyBounds,
+ centerline,
+ totalLength: centerline[centerline.length - 1].s,
+ };
+ }
+
+ // Dynamic float buffer growth
+ let capacityVerts = Math.max(64, slices.length * 12);
+ let verts = new Float32Array(capacityVerts * RIBBON_VERTEX_STRIDE);
+ let vCount = 0;
+
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+
+ const ensureCapacity = (extraVerts: number) => {
+ if (vCount + extraVerts <= capacityVerts) return;
+ capacityVerts = Math.max(vCount + extraVerts, capacityVerts * 2);
+ const next = new Float32Array(capacityVerts * RIBBON_VERTEX_STRIDE);
+ next.set(verts.subarray(0, vCount * RIBBON_VERTEX_STRIDE));
+ verts = next;
+ };
+
+ const pushVertex = (
+ x: number,
+ y: number,
+ u: number,
+ v: number,
+ alpha: number,
+ pressure: number,
+ tipIndex: number,
+ edgeDist: number,
+ ribbonWidth: number
+ ) => {
+ const off = vCount * RIBBON_VERTEX_STRIDE;
+ verts[off + 0] = x;
+ verts[off + 1] = y;
+ verts[off + 2] = u;
+ verts[off + 3] = v;
+ verts[off + 4] = alpha;
+ verts[off + 5] = pressure;
+ verts[off + 6] = tipIndex;
+ verts[off + 7] = edgeDist;
+ verts[off + 8] = ribbonWidth;
+ vCount++;
+
+ if (x < minX) minX = x;
+ if (y < minY) minY = y;
+ if (x > maxX) maxX = x;
+ if (y > maxY) maxY = y;
+ };
+
+ const emitTileSubQuad = (
+ l0x: number,
+ l0y: number,
+ r0x: number,
+ r0y: number,
+ l1x: number,
+ l1y: number,
+ r1x: number,
+ r1y: number,
+ uRaw0: number,
+ uRaw1: number,
+ a0: number,
+ a1: number,
+ p0: number,
+ p1: number,
+ w0: number,
+ w1: number,
+ tileIdx: number,
+ tangentAngle: number,
+ cx: number,
+ cy: number
+ ) => {
+ const tipIdx = selectRibbonSubTipIndex(
+ metricCount,
+ subTipOrder,
+ tileIdx,
+ tangentAngle,
+ seedX,
+ seedY
+ );
+ const metric = metrics[tipIdx] ?? metrics[0];
+
+ let u0 = uRaw0;
+ let u1 = uRaw1;
+ if (repeatMode === 'reverse' && (tileIdx & 1) === 1) {
+ u0 = 1.0 - u0;
+ u1 = 1.0 - u1;
+ }
+
+ const flips = resolveTipFlipSigns(options.flipH, options.flipV, tileIdx, cx, cy);
+ const uvL0 = mapTileUvToTexUv(u0, 0.0, metric, flips.signX, flips.signY);
+ const uvR0 = mapTileUvToTexUv(u0, 1.0, metric, flips.signX, flips.signY);
+ const uvL1 = mapTileUvToTexUv(u1, 0.0, metric, flips.signX, flips.signY);
+ const uvR1 = mapTileUvToTexUv(u1, 1.0, metric, flips.signX, flips.signY);
+
+ // Emit up to 2 triangles with strict non-inverted winding check (cross2 < -1e-5)
+ const area1 = cross2(r0x - l0x, r0y - l0y, l1x - l0x, l1y - l0y);
+ const area2 = cross2(r1x - r0x, r1y - r0y, l1x - r0x, l1y - r0y);
+
+ ensureCapacity(6);
+ if (area1 < -1e-5) {
+ pushVertex(l0x, l0y, uvL0.uTex, uvL0.vTex, a0, p0, tipIdx, -1.0, w0);
+ pushVertex(r0x, r0y, uvR0.uTex, uvR0.vTex, a0, p0, tipIdx, 1.0, w0);
+ pushVertex(l1x, l1y, uvL1.uTex, uvL1.vTex, a1, p1, tipIdx, -1.0, w1);
+ }
+ if (area2 < -1e-5) {
+ pushVertex(r0x, r0y, uvR0.uTex, uvR0.vTex, a0, p0, tipIdx, 1.0, w0);
+ pushVertex(r1x, r1y, uvR1.uTex, uvR1.vTex, a1, p1, tipIdx, 1.0, w1);
+ pushVertex(l1x, l1y, uvL1.uTex, uvL1.vTex, a1, p1, tipIdx, -1.0, w1);
+ }
+ };
+
+ for (let i = 0; i < slices.length - 1; i++) {
+ const s0 = slices[i];
+ const s1 = slices[i + 1];
+
+ // Anti-bowtie inner-edge guard:
+ // In our frame (L = C - N*h, R = C + N*h), forward motion has cross2(R0 - L0, P1 - L0) <= 0.
+ // If either edge steps backwards across (L0 -> R0) on a tight bend, pin it to the previous edge!
+ const qx = s0.rx - s0.lx;
+ const qy = s0.ry - s0.ly;
+ const lCross = cross2(qx, qy, s1.lx - s0.lx, s1.ly - s0.ly);
+ const rCross = cross2(qx, qy, s1.rx - s0.lx, s1.ry - s0.ly);
+ if (lCross > 1e-4 && rCross <= 1e-4) {
+ s1.lx = s0.lx;
+ s1.ly = s0.ly;
+ } else if (rCross > 1e-4 && lCross <= 1e-4) {
+ s1.rx = s0.rx;
+ s1.ry = s0.ry;
+ } else if (lCross > 1e-4 && rCross > 1e-4) {
+ // Degenerate backward jump; skip without emitting folded geometry
+ continue;
+ }
+
+ const sn0 = s0.sNorm;
+ const sn1 = Math.max(sn0, s1.sNorm);
+ const dSn = sn1 - sn0;
+ const tangentAngle = Math.atan2(s0.ty + s1.ty, s0.tx + s1.tx);
+
+ if (dSn < 1e-6) {
+ const tileIdx = Math.max(0, Math.floor(sn0));
+ const uVal = Math.max(0, Math.min(1, sn0 - tileIdx));
+ emitTileSubQuad(
+ s0.lx, s0.ly, s0.rx, s0.ry,
+ s1.lx, s1.ly, s1.rx, s1.ry,
+ uVal, uVal,
+ s0.alpha, s1.alpha,
+ s0.pressure, s1.pressure,
+ s0.ribbonWidth, s1.ribbonWidth,
+ tileIdx,
+ tangentAngle,
+ s0.cx, s0.cy
+ );
+ continue;
+ }
+
+ // Split quad cleanly at every integer tile boundary so UV never wraps backwards
+ // and sub-tip index / flipH / flipV / reverse seams are razor-sharp with zero bleed!
+ let curSn = sn0;
+ let curF = 0.0;
+ let guard = 0;
+
+ while (curSn < sn1 - 1e-6 && guard++ < 64) {
+ const tileIdx = Math.floor(curSn + 1e-7);
+ const nextBoundary = tileIdx + 1;
+ const segEndSn = Math.min(sn1, nextBoundary);
+ const nextF = Math.min(1.0, (segEndSn - sn0) / dSn);
+
+ const lAx = s0.lx + (s1.lx - s0.lx) * curF;
+ const lAy = s0.ly + (s1.ly - s0.ly) * curF;
+ const rAx = s0.rx + (s1.rx - s0.rx) * curF;
+ const rAy = s0.ry + (s1.ry - s0.ry) * curF;
+
+ const lBx = s0.lx + (s1.lx - s0.lx) * nextF;
+ const lBy = s0.ly + (s1.ly - s0.ly) * nextF;
+ const rBx = s0.rx + (s1.rx - s0.rx) * nextF;
+ const rBy = s0.ry + (s1.ry - s0.ry) * nextF;
+
+ const aA = s0.alpha + (s1.alpha - s0.alpha) * curF;
+ const aB = s0.alpha + (s1.alpha - s0.alpha) * nextF;
+ const pA = s0.pressure + (s1.pressure - s0.pressure) * curF;
+ const pB = s0.pressure + (s1.pressure - s0.pressure) * nextF;
+ const wA = s0.ribbonWidth + (s1.ribbonWidth - s0.ribbonWidth) * curF;
+ const wB = s0.ribbonWidth + (s1.ribbonWidth - s0.ribbonWidth) * nextF;
+ const cAx = s0.cx + (s1.cx - s0.cx) * curF;
+ const cAy = s0.cy + (s1.cy - s0.cy) * curF;
+
+ const uStart = Math.max(0, Math.min(1, curSn - tileIdx));
+ const uEnd = Math.max(0, Math.min(1, segEndSn - tileIdx));
+
+ emitTileSubQuad(
+ lAx, lAy, rAx, rAy,
+ lBx, lBy, rBx, rBy,
+ uStart, uEnd,
+ aA, aB,
+ pA, pB,
+ wA, wB,
+ tileIdx,
+ tangentAngle,
+ cAx, cAy
+ );
+
+ curSn = segEndSn;
+ curF = nextF;
+ }
+ }
+
+ return {
+ vertices: verts.subarray(0, vCount * RIBBON_VERTEX_STRIDE),
+ vertexCount: vCount,
+ triangleCount: Math.floor(vCount / 3),
+ bounds:
+ vCount > 0
+ ? { minX, minY, maxX, maxY }
+ : emptyBounds,
+ centerline,
+ totalLength: centerline[centerline.length - 1].s,
+ };
+}
+
+export function buildRibbonMeshFromPoints(
+ points: Point[],
+ options: RibbonRenderOptions
+): RibbonMesh {
+ const centerline = sampleRibbonCenterlineFromPoints(points, options);
+ return buildRibbonMeshFromCenterline(centerline, options);
+}
+
+// ============================================================================
+// 5. CPU Scanline Barycentric Textured Triangle Rasterizer (WebGL-Parity Fallback)
+// ============================================================================
+
+function sampleSurfaceNearest(
+ surf: RibbonTipSurface,
+ u: number,
+ v: number,
+ out: Float64Array
+): void {
+ const tw = surf.width;
+ const th = surf.height;
+ const ix = Math.max(0, Math.min(tw - 1, Math.floor(u * tw)));
+ const iy = Math.max(0, Math.min(th - 1, Math.floor(v * th)));
+ const idx = (iy * tw + ix) << 2;
+ const d = surf.data;
+ out[0] = d[idx];
+ out[1] = d[idx + 1];
+ out[2] = d[idx + 2];
+ out[3] = d[idx + 3] / 255;
+}
+
+function sampleSurfaceBilinear(
+ surf: RibbonTipSurface,
+ u: number,
+ v: number,
+ needRgb: boolean,
+ out: Float64Array
+): void {
+ const tw = surf.width;
+ const th = surf.height;
+ const fx = u * tw - 0.5;
+ const fy = v * th - 0.5;
+ const x0 = Math.max(0, Math.min(tw - 1, Math.floor(fx)));
+ const y0 = Math.max(0, Math.min(th - 1, Math.floor(fy)));
+ const x1 = Math.min(tw - 1, x0 + 1);
+ const y1 = Math.min(th - 1, y0 + 1);
+ const tx = Math.max(0, Math.min(1, fx - Math.floor(fx)));
+ const ty = Math.max(0, Math.min(1, fy - Math.floor(fy)));
+
+ const w00 = (1 - tx) * (1 - ty);
+ const w10 = tx * (1 - ty);
+ const w01 = (1 - tx) * ty;
+ const w11 = tx * ty;
+
+ const d = surf.data;
+ const i00 = (y0 * tw + x0) << 2;
+ const i10 = (y0 * tw + x1) << 2;
+ const i01 = (y1 * tw + x0) << 2;
+ const i11 = (y1 * tw + x1) << 2;
+
+ const a00 = d[i00 + 3];
+ const a10 = d[i10 + 3];
+ const a01 = d[i01 + 3];
+ const a11 = d[i11 + 3];
+
+ const aSum = w00 * a00 + w10 * a10 + w01 * a01 + w11 * a11;
+ out[3] = aSum / 255;
+
+ if (needRgb) {
+ if (aSum > 1e-4) {
+ const invASum = 1.0 / aSum;
+ out[0] = (w00 * a00 * d[i00] + w10 * a10 * d[i10] + w01 * a01 * d[i01] + w11 * a11 * d[i11]) * invASum;
+ out[1] = (w00 * a00 * d[i00 + 1] + w10 * a10 * d[i10 + 1] + w01 * a01 * d[i01 + 1] + w11 * a11 * d[i11 + 1]) * invASum;
+ out[2] = (w00 * a00 * d[i00 + 2] + w10 * a10 * d[i10 + 2] + w01 * a01 * d[i01 + 2] + w11 * a11 * d[i11 + 2]) * invASum;
+ } else {
+ out[0] = 0;
+ out[1] = 0;
+ out[2] = 0;
+ }
+ }
+}
+
+function resolvePaperLookup(options: RibbonRenderOptions): {
+ data: Uint8Array;
+ width: number;
+ height: number;
+} {
+ if (options.paperTextureImage) {
+ const custom = getCustomPaperLuminance(options.paperTextureImage);
+ if (custom) {
+ return { data: custom.lum, width: custom.width, height: custom.height };
+ }
+ }
+ if (options.surfaceTextureId) {
+ const field = getSurfaceTextureHeightField(options.surfaceTextureId);
+ return { data: field, width: SURFACE_TEXTURE_SIZE, height: SURFACE_TEXTURE_SIZE };
+ }
+ return { data: paperGrainTable, width: GRAIN_SIZE, height: GRAIN_SIZE };
+}
+
+/**
+ * Deterministic CPU scanline barycentric textured triangle rasterizer.
+ * Produces an RGBA pixel buffer matching the WebGL textured ribbon fragment shader.
+ */
+export function rasterizeRibbonMeshCpu(
+ mesh: RibbonMesh,
+ options: RibbonRenderOptions,
+ bufWidth: number,
+ bufHeight: number,
+ originX: number = 0,
+ originY: number = 0
+): { data: Uint8ClampedArray; width: number; height: number } {
+ const width = Math.max(1, Math.round(bufWidth));
+ const height = Math.max(1, Math.round(bufHeight));
+ const out = new Uint8ClampedArray(width * height * 4);
+ if (mesh.vertexCount < 3) return { data: out, width, height };
+
+ const tipSurfaces = resolveRibbonTipSurfaces(options);
+ const isBgEraser = Boolean(options.isBgEraser);
+ const isEraser = Boolean(options.isEraser) && !isBgEraser;
+ const primaryHex = isBgEraser ? '#ffffff' : isEraser ? '#000000' : options.primaryColor ?? '#000000';
+ const secondaryHex = options.secondaryColor ?? '#ffffff';
+ const primRgb = parseColorToRgb(primaryHex);
+ const secRgb = parseColorToRgb(secondaryHex);
+
+ const globalColorTip = Boolean(options.isColorTip);
+ const globalDualTone = !globalColorTip && Boolean(options.isDualToneTip);
+ const aaMode = Math.max(0, Math.min(3, Math.round(options.antiAlias ?? 2)));
+ const edgePx = aaMode === 1 ? 0.65 : aaMode === 3 ? 1.85 : 1.15;
+
+ const grainAmount = Math.max(0, Math.min(1, options.grain ?? options.textureDensity ?? 0));
+ const hasGrain = grainAmount > 0.005;
+ const paper = hasGrain ? resolvePaperLookup(options) : null;
+ const paperW = paper ? paper.width : GRAIN_SIZE;
+ const paperH = paper ? paper.height : GRAIN_SIZE;
+ const paperPow2 = (paperW & (paperW - 1)) === 0 && (paperH & (paperH - 1)) === 0;
+ const paperMaskW = paperW - 1;
+ const paperMaskH = paperH - 1;
+ const invPaperScale = 1.0 / Math.max(0.05, options.paperTextureScale ?? 1.0);
+ const paperRotRad = ((options.paperTextureRotate ?? 0) * Math.PI) / 180;
+ const hasPaperRot = Math.abs(paperRotRad) > 1e-4;
+ const cosPR = hasPaperRot ? Math.cos(paperRotRad) : 1;
+ const sinPR = hasPaperRot ? Math.sin(paperRotRad) : 0;
+ const paperMode: CspPaperTextureMode = options.paperTextureMode ?? 'subtract';
+ const paperBrightness = options.paperTextureBrightness ?? 0;
+ const paperContrast = options.paperTextureContrast ?? 0;
+ const paperInverted = Boolean(options.paperTextureInverted);
+ const preserveDensity =
+ options.paperTextureApplyEachPlot !== undefined && !options.grainPenetrationSensor?.usePressure;
+ const emphasizeDensity = Boolean(options.paperTextureEmphasizeDensity);
+
+ const verts = mesh.vertices;
+ const triCount = Math.floor(mesh.vertexCount / 3);
+ const sampleScratch = new Float64Array(4);
+
+ for (let t = 0; t < triCount; t++) {
+ const base = t * 3 * RIBBON_VERTEX_STRIDE;
+
+ let x0 = verts[base + 0];
+ let y0 = verts[base + 1];
+ let u0 = verts[base + 2];
+ let v0t = verts[base + 3];
+ let a0 = verts[base + 4];
+ let p0 = verts[base + 5];
+ const rawTipIdx = verts[base + 6];
+ let e0 = verts[base + 7];
+ let w0r = verts[base + 8];
+
+ const b1 = base + RIBBON_VERTEX_STRIDE;
+ let x1 = verts[b1 + 0];
+ let y1 = verts[b1 + 1];
+ let u1 = verts[b1 + 2];
+ let v1t = verts[b1 + 3];
+ let a1 = verts[b1 + 4];
+ let p1 = verts[b1 + 5];
+ let e1 = verts[b1 + 7];
+ let w1r = verts[b1 + 8];
+
+ const b2 = base + RIBBON_VERTEX_STRIDE * 2;
+ let x2 = verts[b2 + 0];
+ let y2 = verts[b2 + 1];
+ let u2 = verts[b2 + 2];
+ let v2t = verts[b2 + 3];
+ let a2 = verts[b2 + 4];
+ let p2 = verts[b2 + 5];
+ let e2 = verts[b2 + 7];
+ let w2r = verts[b2 + 8];
+
+ let area = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0);
+ if (Math.abs(area) < 1e-5) continue;
+
+ // Ensure positive area (CW in screen Y-down) for consistent top-left edge fill rule
+ if (area < 0) {
+ area = -area;
+ let tmp = x1; x1 = x2; x2 = tmp;
+ tmp = y1; y1 = y2; y2 = tmp;
+ tmp = u1; u1 = u2; u2 = tmp;
+ tmp = v1t; v1t = v2t; v2t = tmp;
+ tmp = a1; a1 = a2; a2 = tmp;
+ tmp = p1; p1 = p2; p2 = tmp;
+ tmp = e1; e1 = e2; e2 = tmp;
+ tmp = w1r; w1r = w2r; w2r = tmp;
+ }
+
+ const minPx = Math.max(0, Math.floor(Math.min(x0, x1, x2) - originX));
+ const maxPx = Math.min(width - 1, Math.ceil(Math.max(x0, x1, x2) - originX));
+ const minPy = Math.max(0, Math.floor(Math.min(y0, y1, y2) - originY));
+ const maxPy = Math.min(height - 1, Math.ceil(Math.max(y0, y1, y2) - originY));
+ if (minPx > maxPx || minPy > maxPy) continue;
+
+ const tipIdx = Math.max(0, Math.min(tipSurfaces.length - 1, Math.round(rawTipIdx)));
+ const surf = tipSurfaces[tipIdx];
+ const useColorTip = !isEraser && !isBgEraser && Boolean(surf.isColor ?? globalColorTip);
+ const useDualTone = !isEraser && !isBgEraser && !useColorTip && Boolean(surf.isDualToneTip ?? globalDualTone);
+ const needRgb = useColorTip || useDualTone;
+
+ // Top-left edge flags for CW screen-space triangle (area > 0)
+ const tl0 = y2 < y1 || (y2 === y1 && x2 > x1); // edge v1 -> v2
+ const tl1 = y0 < y2 || (y0 === y2 && x0 > x2); // edge v2 -> v0
+ const tl2 = y1 < y0 || (y1 === y0 && x1 > x0); // edge v0 -> v1
+
+ const dx0 = x2 - x1;
+ const dy0 = y2 - y1;
+ const dx1 = x0 - x2;
+ const dy1 = y0 - y2;
+ const dx2 = x1 - x0;
+ const dy2 = y1 - y0;
+ const invArea = 1.0 / area;
+
+ for (let py = minPy; py <= maxPy; py++) {
+ const wy = originY + py + 0.5;
+ const rowOff = py * width;
+ const wxStart = originX + minPx + 0.5;
+
+ let w0 = dx0 * (wy - y1) - dy0 * (wxStart - x1);
+ let w1 = dx1 * (wy - y2) - dy1 * (wxStart - x2);
+ let w2 = dx2 * (wy - y0) - dy2 * (wxStart - x0);
+
+ for (let px = minPx; px <= maxPx; px++) {
+ const inside =
+ (w0 > 0 || (w0 === 0 && tl0)) &&
+ (w1 > 0 || (w1 === 0 && tl1)) &&
+ (w2 > 0 || (w2 === 0 && tl2));
+
+ if (inside) {
+ const bw0 = w0 * invArea;
+ const bw1 = w1 * invArea;
+ const bw2 = w2 * invArea;
+
+ const u = bw0 * u0 + bw1 * u1 + bw2 * u2;
+ const v = bw0 * v0t + bw1 * v1t + bw2 * v2t;
+
+ if (u >= 0 && u <= 1 && v >= 0 && v <= 1) {
+ if (aaMode === 0) {
+ sampleSurfaceNearest(surf, u, v, sampleScratch);
+ } else {
+ sampleSurfaceBilinear(surf, u, v, needRgb, sampleScratch);
+ }
+
+ let tipAlpha = sampleScratch[3];
+ if (aaMode === 0) {
+ tipAlpha = tipAlpha >= 0.5 ? 1.0 : 0.0;
+ } else if (tipAlpha > 0.002) {
+ const edgeDist = bw0 * e0 + bw1 * e1 + bw2 * e2;
+ const ribWidth = bw0 * w0r + bw1 * w1r + bw2 * w2r;
+ const edgeUv = Math.min(0.45, edgePx / Math.max(1.0, ribWidth));
+ const absE = Math.abs(edgeDist);
+ const featherStart = 1.0 - edgeUv * 2.0;
+ if (edgeUv > 1e-4 && absE > featherStart) {
+ const ft = Math.max(0, Math.min(1, (absE - featherStart) / (edgeUv * 2.0)));
+ tipAlpha *= 1.0 - ft * ft * (3.0 - 2.0 * ft);
+ }
+ }
+
+ if (tipAlpha > 0.002) {
+ const vAlpha = bw0 * a0 + bw1 * a1 + bw2 * a2;
+ let finalAlpha = Math.max(0, Math.min(1, tipAlpha * vAlpha));
+
+ if (hasGrain && paper && finalAlpha > 0.002) {
+ const wx = originX + px + 0.5;
+ let psx = wx * invPaperScale;
+ let psy = wy * invPaperScale;
+ if (hasPaperRot) {
+ const rx = psx * cosPR - psy * sinPR;
+ const ry = psx * sinPR + psy * cosPR;
+ psx = rx;
+ psy = ry;
+ }
+ const pfx = Math.floor(psx);
+ const pfy = Math.floor(psy);
+ const ptx = psx - pfx;
+ const pty = psy - pfy;
+ let px0: number, py0: number, px1: number, py1: number;
+ if (paperPow2) {
+ px0 = pfx & paperMaskW;
+ py0 = pfy & paperMaskH;
+ px1 = (px0 + 1) & paperMaskW;
+ py1 = (py0 + 1) & paperMaskH;
+ } else {
+ px0 = ((pfx % paperW) + paperW) % paperW;
+ py0 = ((pfy % paperH) + paperH) % paperH;
+ px1 = px0 + 1 < paperW ? px0 + 1 : 0;
+ py1 = py0 + 1 < paperH ? py0 + 1 : 0;
+ }
+ const pr0 = py0 * paperW;
+ const pr1 = py1 * paperW;
+ const pvTop = paper.data[pr0 + px0] + (paper.data[pr0 + px1] - paper.data[pr0 + px0]) * ptx;
+ const pvBot = paper.data[pr1 + px0] + (paper.data[pr1 + px1] - paper.data[pr1 + px0]) * ptx;
+ const gNorm = (pvTop + (pvBot - pvTop) * pty) / 255;
+ const vPress = bw0 * p0 + bw1 * p1 + bw2 * p2;
+
+ finalAlpha = applyCspPaperTextureAlpha(
+ finalAlpha,
+ gNorm,
+ grainAmount,
+ vPress,
+ paperMode,
+ paperBrightness,
+ paperContrast,
+ paperInverted,
+ preserveDensity,
+ emphasizeDensity
+ );
+ }
+
+ if (aaMode === 0) {
+ finalAlpha = finalAlpha >= 0.5 ? 1.0 : 0.0;
+ }
+
+ if (finalAlpha > 0.002) {
+ let r: number;
+ let g: number;
+ let b: number;
+ if (useColorTip) {
+ r = sampleScratch[0];
+ g = sampleScratch[1];
+ b = sampleScratch[2];
+ } else if (useDualTone) {
+ const lum = (0.299 * sampleScratch[0] + 0.587 * sampleScratch[1] + 0.114 * sampleScratch[2]) / 255;
+ r = primRgb.r + (secRgb.r - primRgb.r) * lum;
+ g = primRgb.g + (secRgb.g - primRgb.g) * lum;
+ b = primRgb.b + (secRgb.b - primRgb.b) * lum;
+ } else {
+ r = primRgb.r;
+ g = primRgb.g;
+ b = primRgb.b;
+ }
+
+ const pOff = (rowOff + px) << 2;
+ const dstA = out[pOff + 3] / 255;
+ if (dstA <= 0.001) {
+ out[pOff + 0] = Math.max(0, Math.min(255, Math.round(r)));
+ out[pOff + 1] = Math.max(0, Math.min(255, Math.round(g)));
+ out[pOff + 2] = Math.max(0, Math.min(255, Math.round(b)));
+ out[pOff + 3] = Math.max(0, Math.min(255, Math.round(finalAlpha * 255)));
+ } else {
+ const outA = finalAlpha + dstA * (1.0 - finalAlpha);
+ const invOutA = 1.0 / Math.max(1e-5, outA);
+ const dstKeep = dstA * (1.0 - finalAlpha);
+ out[pOff + 0] = Math.max(0, Math.min(255, Math.round((r * finalAlpha + out[pOff + 0] * dstKeep) * invOutA)));
+ out[pOff + 1] = Math.max(0, Math.min(255, Math.round((g * finalAlpha + out[pOff + 1] * dstKeep) * invOutA)));
+ out[pOff + 2] = Math.max(0, Math.min(255, Math.round((b * finalAlpha + out[pOff + 2] * dstKeep) * invOutA)));
+ out[pOff + 3] = Math.max(0, Math.min(255, Math.round(outA * 255)));
+ }
+ }
+ }
+ }
+ }
+
+ w0 -= dy0;
+ w1 -= dy1;
+ w2 -= dy2;
+ }
+ }
+ }
+
+ return { data: out, width, height };
+}
+
+// ============================================================================
+// 6. Unified WebGL + CPU Context Dispatcher
+// ============================================================================
+
+let _cpuRibbonScratchCanvas: HTMLCanvasElement | null = null;
+const MAX_CPU_RIBBON_CHUNK = 2048;
+
+export function canUseWebGlForRibbon(options?: RibbonRenderOptions): boolean {
+ const perf = performanceManager.getConfig();
+ if (perf.renderBackend === 'canvas2d' || !perf.gpuBrushAcceleration) {
+ return false;
+ }
+ if (options?.useGpu === false) return false;
+ // When caller supplies raw CPU tipSurfaces without HTMLImageElement, rasterize on CPU
+ if (options?.tipSurfaces && !options.tipImage && !(options.subTipImages && options.subTipImages.length > 0)) {
+ return false;
+ }
+ return WebGlBrushEngine.getInstance().isTexturedRibbonAvailable();
+}
+
+export function renderRibbonMeshToContext(
+ ctx: CanvasRenderingContext2D,
+ mesh: RibbonMesh,
+ options: RibbonRenderOptions,
+ tool: ToolType = 'brush'
+): boolean {
+ if (mesh.vertexCount < 3) return false;
+
+ const isBgEraser = Boolean(options.isBgEraser);
+ const isEraser = (tool === 'eraser' || Boolean(options.isEraser) || Boolean(options.isTransparentInk)) && !isBgEraser;
+ const primaryColor = isBgEraser ? '#ffffff' : isEraser ? '#000000' : options.primaryColor ?? '#000000';
+ const strokeOpacity = Math.max(0, Math.min(1, options.opacity ?? 1.0));
+
+ // 1. Try WebGL textured ribbon pipeline first
+ if (canUseWebGlForRibbon(options)) {
+ const gpu = WebGlBrushEngine.getInstance();
+ const gpuSettings: BrushSettings & { alphaLocked?: boolean; isBgEraser?: boolean } = {
+ size: options.size ?? 10,
+ minSizeFactor: options.minSizeFactor ?? 0,
+ color: primaryColor,
+ secondaryColor: options.secondaryColor ?? '#ffffff',
+ opacity: strokeOpacity,
+ flow: options.flow ?? 1.0,
+ spacing: 0.08,
+ usePressure: options.usePressure !== false,
+ smoothing: false,
+ stabilization: 0,
+ hardness: options.hardness ?? 1.0,
+ antiAlias: options.antiAlias ?? 2,
+ grain: options.grain ?? options.textureDensity ?? 0,
+ textureDensity: options.textureDensity,
+ grainPenetrationSensor: options.grainPenetrationSensor,
+ surfaceTextureId: options.surfaceTextureId,
+ paperTextureMode: options.paperTextureMode,
+ paperTextureBrightness: options.paperTextureBrightness,
+ paperTextureContrast: options.paperTextureContrast,
+ paperTextureApplyEachPlot: options.paperTextureApplyEachPlot,
+ paperTextureEmphasizeDensity: options.paperTextureEmphasizeDensity,
+ paperTextureInverted: options.paperTextureInverted,
+ paperTextureImage: options.paperTextureImage,
+ paperTextureScale: options.paperTextureScale,
+ paperTextureRotate: options.paperTextureRotate,
+ customTipImage: options.tipImage,
+ isColorTip: options.isColorTip,
+ isDualToneTip: options.isDualToneTip,
+ subTips: options.subTips,
+ subTipImages: options.subTipImages,
+ isTransparentInk: Boolean(options.isTransparentInk),
+ alphaLocked: Boolean(options.alphaLocked),
+ isBgEraser,
+ };
+
+ if (gpu.renderTexturedRibbonMesh(ctx, mesh, gpuSettings, primaryColor, isEraser ? 'eraser' : tool)) {
+ return true;
+ }
+ }
+
+ // 2. CPU scanline barycentric fallback
+ if (typeof document === 'undefined') return false;
+
+ const pad = 2;
+ const fullX = Math.floor(mesh.bounds.minX - pad);
+ const fullY = Math.floor(mesh.bounds.minY - pad);
+ const fullMaxX = Math.ceil(mesh.bounds.maxX + pad);
+ const fullMaxY = Math.ceil(mesh.bounds.maxY + pad);
+ const totalW = fullMaxX - fullX;
+ const totalH = fullMaxY - fullY;
+ if (totalW <= 0 || totalH <= 0) return false;
+
+ if (!_cpuRibbonScratchCanvas) {
+ _cpuRibbonScratchCanvas = document.createElement('canvas');
+ }
+ const scratch = _cpuRibbonScratchCanvas;
+
+ const compositeOp: GlobalCompositeOperation = isBgEraser
+ ? 'source-over'
+ : isEraser
+ ? 'destination-out'
+ : options.alphaLocked
+ ? 'source-atop'
+ : 'source-over';
+
+ ctx.save();
+ ctx.globalCompositeOperation = compositeOp;
+ ctx.globalAlpha = strokeOpacity;
+ if ((options.antiAlias ?? 2) === 0) {
+ ctx.imageSmoothingEnabled = false;
+ }
+
+ for (let cy = fullY; cy < fullMaxY; cy += MAX_CPU_RIBBON_CHUNK) {
+ const ch = Math.min(MAX_CPU_RIBBON_CHUNK, fullMaxY - cy);
+ for (let cx = fullX; cx < fullMaxX; cx += MAX_CPU_RIBBON_CHUNK) {
+ const cw = Math.min(MAX_CPU_RIBBON_CHUNK, fullMaxX - cx);
+ const raster = rasterizeRibbonMeshCpu(mesh, options, cw, ch, cx, cy);
+
+ if (scratch.width !== cw || scratch.height !== ch) {
+ scratch.width = cw;
+ scratch.height = ch;
+ }
+ const sCtx = scratch.getContext('2d');
+ if (!sCtx) continue;
+ const imgData =
+ typeof sCtx.createImageData === 'function'
+ ? sCtx.createImageData(cw, ch)
+ : ({ data: new Uint8ClampedArray(cw * ch * 4), width: cw, height: ch } as ImageData);
+ imgData.data.set(raster.data);
+ sCtx.putImageData(imgData, 0, 0);
+ ctx.drawImage(scratch, 0, 0, cw, ch, cx, cy, cw, ch);
+ }
+ }
+
+ ctx.restore();
+ return true;
+}
+
+export function buildRibbonRenderOptionsFromBrushSettings(
+ rawSettings: BrushSettings,
+ colorMode: CanvasColorMode = 'color',
+ isBgEraser: boolean = false,
+ isEraser: boolean = false,
+ alphaLocked: boolean = false,
+ allowGpuForMonochrome: boolean = false,
+ exitSpeed?: number,
+ overrides?: Partial<RibbonRenderOptions>
+): RibbonRenderOptions {
+ const bs = resolveBrushPresetSettings(rawSettings);
+ const isMono = colorMode === 'monochrome';
+ const primaryColor = isBgEraser
+ ? '#ffffff'
+ : isEraser
+ ? '#000000'
+ : enforceColorMode(bs.color, colorMode);
+ const secondaryColor = enforceColorMode(bs.secondaryColor ?? '#ffffff', colorMode);
+
+ const effectiveAntiAlias = isMono
+ ? allowGpuForMonochrome && (bs.antiAlias ?? 2) !== 0 && bs.useGpu !== false
+ ? bs.antiAlias ?? 2
+ : 0
+ : bs.antiAlias ?? 2;
+
+ return {
+ size: bs.size,
+ minSizeFactor: bs.minSizeFactor,
+ opacity: bs.opacity ?? 1.0,
+ flow: isMono ? 1.0 : bs.flow ?? 1.0,
+ brushDensity: isMono ? 1.0 : bs.brushDensity,
+ hardness: isMono ? 1.0 : bs.hardness ?? 1.0,
+ thickness: bs.thickness ?? 1.0,
+ thicknessVertical: Boolean(bs.thicknessVertical),
+ thicknessSensor: bs.thicknessSensor,
+ angle: bs.customTipAngle ?? 0,
+ flipH: bs.flipH,
+ flipV: bs.flipV,
+ antiAlias: effectiveAntiAlias,
+ usePressure: bs.usePressure,
+ pressureCurve: bs.pressureCurve,
+ useTilt: Boolean(bs.useTilt),
+ tiltScale: bs.tiltScale,
+ sizeSensor: bs.sizeSensor,
+ opacitySensor: bs.opacitySensor,
+ densitySensor: bs.densitySensor,
+ grainPenetrationSensor: bs.grainPenetrationSensor,
+ taper: bs.taper,
+ tipImage: bs.customTipImage,
+ subTips: bs.subTips,
+ subTipOrder: bs.subTipOrder,
+ subTipImages: bs.subTipImages,
+ isColorTip: Boolean(bs.isColorTip || bs.subTips?.[0]?.isColor),
+ isDualToneTip: Boolean(bs.isDualToneTip || bs.subTips?.[0]?.isDualToneTip),
+ primaryColor,
+ secondaryColor,
+ grain: bs.grain ?? bs.textureDensity ?? 0,
+ textureDensity: bs.textureDensity,
+ surfaceTextureId: bs.surfaceTextureId,
+ paperTextureImage: bs.paperTextureImage,
+ paperTextureMode: bs.paperTextureMode,
+ paperTextureScale: bs.paperTextureScale,
+ paperTextureRotate: bs.paperTextureRotate,
+ paperTextureBrightness: bs.paperTextureBrightness,
+ paperTextureContrast: bs.paperTextureContrast,
+ paperTextureInverted: bs.paperTextureInverted,
+ paperTextureApplyEachPlot: bs.paperTextureApplyEachPlot,
+ paperTextureEmphasizeDensity: bs.paperTextureEmphasizeDensity,
+ useGpu: bs.useGpu !== false,
+ isEraser: isEraser && !isBgEraser,
+ isBgEraser,
+ alphaLocked,
+ isTransparentInk: Boolean(bs.isTransparentInk),
+ exitSpeed,
+ ...overrides,
+ };
+}
+
+/**
+ * Renders an entire completed ribbon stroke onto `ctx`.
+ */
+export function renderCompleteRibbonStroke(
+ ctx: CanvasRenderingContext2D,
+ points: Point[],
+ brushSettings: BrushSettings,
+ tool: ToolType = 'brush',
+ colorMode: CanvasColorMode = 'color',
+ isBgEraser: boolean = false,
+ alphaLocked: boolean = false,
+ allowGpuForMonochrome: boolean = false,
+ exitSpeed?: number,
+ overrides?: Partial<RibbonRenderOptions>
+): RibbonMesh | null {
+ if (!points || points.length === 0) return null;
+
+ const resolvedSettings = resolveBrushPresetSettings(brushSettings);
+ const postCorrLevel = resolvedSettings.postCorrection ?? 0;
+ const effectivePoints =
+ postCorrLevel > 0 && points.length >= 3
+ ? applyCspPostCorrection(points, postCorrLevel, resolvedSettings.sharpCorners !== false)
+ : points;
+
+ const isEraser = tool === 'eraser';
+ const ribbonOpts = buildRibbonRenderOptionsFromBrushSettings(
+ resolvedSettings,
+ colorMode,
+ isBgEraser,
+ isEraser,
+ alphaLocked,
+ allowGpuForMonochrome,
+ exitSpeed,
+ overrides
+ );
+
+ const mesh = buildRibbonMeshFromPoints(effectivePoints, ribbonOpts);
+ if (mesh.vertexCount < 3) return mesh;
+
+ renderRibbonMeshToContext(ctx, mesh, ribbonOpts, tool);
+ return mesh;
+}
+
+// ============================================================================
+// 7. Live Incremental Ribbon Stroke Session (Draft Canvas Streaming)
+// ============================================================================
+
+export class RibbonStrokeSession {
+ private s = 0;
+ private sNorm = 0;
+ private sampleIdx = 0;
+ private hasSeed = false;
+ private seedX = 0;
+ private seedY = 0;
+ private lastEdgeState: {
+ lx: number;
+ ly: number;
+ rx: number;
+ ry: number;
+ tx: number;
+ ty: number;
+ s: number;
+ sNorm: number;
+ alpha: number;
+ pressure: number;
+ ribbonWidth: number;
+ cx: number;
+ cy: number;
+ } | null = null;
+
+ public reset(): void {
+ this.s = 0;
+ this.sNorm = 0;
+ this.sampleIdx = 0;
+ this.hasSeed = false;
+ this.seedX = 0;
+ this.seedY = 0;
+ this.lastEdgeState = null;
+ }
+
+ public appendCubicSegment(
+ ctx: CanvasRenderingContext2D,
+ seg: CubicBezierSegment,
+ options: RibbonRenderOptions,
+ tool: ToolType = 'brush'
+ ): RibbonMesh | null {
+ if (!this.hasSeed) {
+ this.seedX = seg.p0.x;
+ this.seedY = seg.p0.y;
+ this.hasSeed = true;
+ }
+
+ const metrics = buildTipMetrics(options);
+ const centerline: RibbonCenterlineSample[] = [];
+ const state = {
+ s: this.s,
+ sNorm: this.sNorm,
+ sampleIdx: this.sampleIdx,
+ seedX: this.seedX,
+ seedY: this.seedY,
+ totalLength: options.totalLength,
+ };
+
+ sampleCubicSegmentIntoCenterline(
+ centerline,
+ seg.p0,
+ seg.c1,
+ seg.c2,
+ seg.p3,
+ options,
+ metrics,
+ state
+ );
+
+ if (centerline.length < 2) return null;
+
+ const slices = buildSlicesFromCenterline(centerline, options, this.lastEdgeState ?? undefined);
+ const mesh = buildRibbonMeshFromCenterline(centerline, options, this.lastEdgeState ?? undefined);
+
+ this.s = state.s;
+ this.sampleIdx = state.sampleIdx;
+
+ if (slices.length >= 2) {
+ const endSlice = slices[slices.length - 1];
+ this.sNorm = endSlice.sNorm;
+ this.lastEdgeState = {
+ lx: endSlice.lx,
+ ly: endSlice.ly,
+ rx: endSlice.rx,
+ ry: endSlice.ry,
+ tx: endSlice.tx,
+ ty: endSlice.ty,
+ s: endSlice.s,
+ sNorm: endSlice.sNorm,
+ alpha: endSlice.alpha,
+ pressure: endSlice.pressure,
+ ribbonWidth: endSlice.ribbonWidth,
+ cx: endSlice.cx,
+ cy: endSlice.cy,
+ };
+ } else {
+ this.sNorm = state.sNorm;
+ }
+
+ if (mesh.vertexCount >= 3) {
+ renderRibbonMeshToContext(ctx, mesh, options, tool);
+ }
+ return mesh;
+ }
+}
diff --git a/src/engine/SplineGenerator.ts b/src/engine/SplineGenerator.ts
index 776e956..97a283b 100644
--- a/src/engine/SplineGenerator.ts
+++ b/src/engine/SplineGenerator.ts
@@ -192,18 +192,24 @@ export class SplineGenerator {
const d12 = Math.hypot(p2.x - p1.x, p2.y - p1.y);
const d23 = Math.hypot(p3.x - p2.x, p3.y - p2.y);
+ // Guard degenerate micro-chords (<1e-3 px) so floating-point dust never skews tangent directions
+ const effP0 = d01 < 1e-3 ? p1 : p0;
+ const effP3 = d23 < 1e-3 ? p2 : p3;
+ const effD01 = d01 < 1e-3 ? 0 : d01;
+ const effD23 = d23 < 1e-3 ? 0 : d23;
+
// Centripetal parameterization (alpha = 0.5): dt = sqrt(chord)
- const dt0 = Math.max(1e-4, Math.sqrt(d01));
+ const dt0 = Math.max(1e-4, Math.sqrt(effD01));
const dt1 = Math.max(1e-4, Math.sqrt(d12));
- const dt2 = Math.max(1e-4, Math.sqrt(d23));
+ const dt2 = Math.max(1e-4, Math.sqrt(effD23));
// Non-uniform centripetal Catmull-Rom tangents at P1 and P2:
// m1 = (P1-P0)/dt0 - (P2-P0)/(dt0+dt1) + (P2-P1)/dt1 (reduces to (P2-P0)/2 for uniform knots)
- const t1x = (p1.x - p0.x) / dt0 - (p2.x - p0.x) / (dt0 + dt1) + (p2.x - p1.x) / dt1;
- const t1y = (p1.y - p0.y) / dt0 - (p2.y - p0.y) / (dt0 + dt1) + (p2.y - p1.y) / dt1;
+ const t1x = (p1.x - effP0.x) / dt0 - (p2.x - effP0.x) / (dt0 + dt1) + (p2.x - p1.x) / dt1;
+ const t1y = (p1.y - effP0.y) / dt0 - (p2.y - effP0.y) / (dt0 + dt1) + (p2.y - p1.y) / dt1;
- const t2x = (p2.x - p1.x) / dt1 - (p3.x - p1.x) / (dt1 + dt2) + (p3.x - p2.x) / dt2;
- const t2y = (p2.y - p1.y) / dt1 - (p3.y - p1.y) / (dt1 + dt2) + (p3.y - p2.y) / dt2;
+ const t2x = (p2.x - p1.x) / dt1 - (effP3.x - p1.x) / (dt1 + dt2) + (effP3.x - p2.x) / dt2;
+ const t2y = (p2.y - p1.y) / dt1 - (effP3.y - p1.y) / (dt1 + dt2) + (effP3.y - p2.y) / dt2;
let dx1 = (t1x * dt1) / 3.0;
let dy1 = (t1y * dt1) / 3.0;
diff --git a/src/engine/StrokePipeline.ts b/src/engine/StrokePipeline.ts
index e45aa81..b5554ff 100644
--- a/src/engine/StrokePipeline.ts
+++ b/src/engine/StrokePipeline.ts
@@ -419,6 +419,34 @@ export class StrokePipeline {
this.expandDirtyRect(x, y, width + padExtra);
}
+ /**
+ * Reconciles the initial seeded knot's pressure and width with the first real hardware
+ * pointermove sample when initial pen touchdown was deferred (prevents 0.5 sentinel / click spikes).
+ */
+ public updateSeedKnotPressure(
+ pressure: number,
+ width: number,
+ timestamp: number = 0,
+ tiltX?: number,
+ tiltY?: number
+ ): void {
+ if (this.knotCount === 1) {
+ this.knotP0.pressure = pressure;
+ this.knotP0.width = width;
+ this.knotP1.pressure = pressure;
+ this.knotP1.width = width;
+ if (tiltX !== undefined && tiltY !== undefined) {
+ this.knotP0.tiltX = tiltX;
+ this.knotP0.tiltY = tiltY;
+ this.knotP1.tiltX = tiltX;
+ this.knotP1.tiltY = tiltY;
+ }
+ }
+ if (this.stabilizerLevel > 0) {
+ this.stabilizer.resetPressureState(pressure, timestamp || this.lastRawTime);
+ }
+ }
+
/**
* 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.
@@ -548,6 +576,124 @@ export class StrokePipeline {
isCorner = false;
}
+ const cornerPlan =
+ this.stabilizerLevel > 0 && isCorner ? this.stabilizer.consumeCornerPlan() : null;
+
+ if (cornerPlan) {
+ // Walk a short, smooth sub-path from current stabilized tail -> corner apex -> target
+ // in bounded steps (<= 10 screen px) so sharp corners never jump across lag in one straight line.
+ const clampedZoom = Math.max(0.15, Math.min(4.0, this.zoomScale));
+ const maxStepDoc = 10.0 / clampedZoom;
+ const startX = cornerPlan.startX;
+ const startY = cornerPlan.startY;
+ const apexX = cornerPlan.apexX;
+ const apexY = cornerPlan.apexY;
+ const targetX = cornerPlan.targetX;
+ const targetY = cornerPlan.targetY;
+
+ const leg1Dist = Math.hypot(apexX - startX, apexY - startY);
+ const leg2Dist = Math.hypot(targetX - apexX, targetY - apexY);
+ const leg1Steps = leg1Dist > 1.0 / clampedZoom ? Math.min(6, Math.max(1, Math.ceil(leg1Dist / maxStepDoc))) : 0;
+ const leg2Steps = leg2Dist > 1.0 / clampedZoom ? Math.min(6, Math.max(1, Math.ceil(leg2Dist / maxStepDoc))) : 1;
+ const totalSubSteps = leg1Steps + leg2Steps;
+
+ const calibratedStabPressure = evaluateGlobalPressureCurve(
+ stabPressure,
+ this.globalPressureCurve
+ );
+ const sample = this.scratchSample;
+ sample.tiltX = tiltX;
+ sample.tiltY = tiltY;
+ sample.twist = twist;
+ sample.timestamp = timeMs;
+ sample.vx = vx;
+ sample.vy = vy;
+ sample.pointerType = pointerType;
+
+ if (options?.resolvePoint) {
+ sample.opacity = calibratedStabPressure;
+ options.resolvePoint(
+ rawX,
+ rawY,
+ rawP,
+ calibratedStabPressure,
+ pointerType,
+ vx,
+ vy,
+ dtMs,
+ sample
+ );
+ } else {
+ const hasNonLinearGlobalCurve = Boolean(
+ this.globalPressureCurve &&
+ this.globalPressureCurve.enabled &&
+ !isLinearPressureCurve(this.globalPressureCurve.points)
+ );
+ const mappedPressure = hasNonLinearGlobalCurve
+ ? calibratedStabPressure
+ : this.taperEngine.mapPressure(calibratedStabPressure);
+ const smoothPressure = this.taperEngine.smoothPressure(mappedPressure);
+ sample.pressure = smoothPressure;
+ sample.width = Math.max(0.5, this.baseBrushSize * smoothPressure);
+ sample.opacity = Math.max(0, Math.min(1, smoothPressure));
+ }
+
+ let stepIdx = 0;
+ const emitSubStep = (sx: number, sy: number, markCorner: boolean) => {
+ stepIdx++;
+ sample.x = sx;
+ sample.y = sy;
+ sample.isCorner = markCorner;
+ this.expandDirtyRect(sx, sy, sample.width + padExtra);
+ options?.onPoint?.(sample);
+ this.advanceSplineKnot(
+ sx,
+ sy,
+ sample.pressure,
+ sample.width,
+ sample.tiltX,
+ sample.tiltY,
+ sample.twist,
+ sample.timestamp,
+ sample.vx,
+ sample.vy,
+ markCorner,
+ padExtra,
+ options?.onSegment
+ );
+ };
+
+ for (let k = 1; k <= leg1Steps; k++) {
+ const t = k / leg1Steps;
+ const isFinal = stepIdx + 1 === totalSubSteps;
+ emitSubStep(startX + (apexX - startX) * t, startY + (apexY - startY) * t, isFinal);
+ }
+ for (let k = 1; k <= leg2Steps; k++) {
+ const t = k / leg2Steps;
+ const isFinal = k === leg2Steps;
+ emitSubStep(apexX + (targetX - apexX) * t, apexY + (targetY - apexY) * t, isFinal);
+ }
+
+ this.stabilizer.settleAfterCornerSubPath(targetX, targetY);
+ this.lastRawX = targetX;
+ this.lastRawY = targetY;
+ this.lastRawTime = timeMs;
+ this.lastVx = vx;
+ this.lastVy = vy;
+ this.hasLastRaw = true;
+ continue;
+ }
+
+ // When stabilized, suppress degenerate micro-knots (<0.25 screen px) from deadzone or glitch-hold
+ // so zero-length chords never collapse or skew Catmull-Rom tangents on fast strokes.
+ if (this.stabilizerLevel > 0 && !isCorner && this.knotCount >= 1) {
+ const lastKnot = this.knotCount === 1 ? this.knotP1 : this.knotP2;
+ const minKnotDoc = 0.25 / Math.max(0.15, Math.min(4.0, this.zoomScale));
+ if (Math.hypot(outX - lastKnot.x, outY - lastKnot.y) < minKnotDoc) {
+ continue;
+ }
+ }
+
this.lastRawX = outX;
this.lastRawY = outY;
this.lastRawTime = timeMs;
@@ -645,9 +791,64 @@ export class StrokePipeline {
);
onSegment(bridgeSeg);
- // 2. Speculative lookahead strictly from hardware getPredictedEvents()
+ this.copyKnot(this.scratchPrevPredPt, this.knotP2);
+
+ // 2. Low-latency provisional bridge from stabilized tail toward live raw stylus coordinate
+ if (this.stabilizerLevel > 0) {
+ const catchUp = this.stabilizer.getCatchUpTarget();
+ const clampedZoom = Math.max(0.15, Math.min(4.0, this.zoomScale));
+ const minBridgeDoc = 0.75 / clampedZoom;
+ const maxBridgeDoc = Math.max(maxPredDist * 1.5, 28.0 / clampedZoom);
+ const dxRaw = catchUp.x - this.scratchPrevPredPt.x;
+ const dyRaw = catchUp.y - this.scratchPrevPredPt.y;
+ const distRaw = Math.hypot(dxRaw, dyRaw);
+ if (distRaw >= minBridgeDoc && distRaw <= maxBridgeDoc * 2.5) {
+ const clampScale = distRaw > maxBridgeDoc ? maxBridgeDoc / distRaw : 1.0;
+ const tipX = this.scratchPrevPredPt.x + dxRaw * clampScale;
+ const tipY = this.scratchPrevPredPt.y + dyRaw * clampScale;
+
+ // Curve gently through s1 guide point when lag is notable so provisional bridge follows arcs smoothly
+ const midDx = catchUp.midX - this.scratchPrevPredPt.x;
+ const midDy = catchUp.midY - this.scratchPrevPredPt.y;
+ const midDist = Math.hypot(midDx, midDy);
+ if (midDist >= minBridgeDoc && midDist < distRaw * 0.85) {
+ this.scratchPredPt.x = this.scratchPrevPredPt.x + midDx * clampScale;
+ this.scratchPredPt.y = this.scratchPrevPredPt.y + midDy * clampScale;
+ this.scratchPredPt.pressure = this.scratchPrevPredPt.pressure;
+ this.scratchPredPt.width = this.scratchPrevPredPt.width;
+ this.scratchPredPt.tiltX = this.knotP2.tiltX;
+ this.scratchPredPt.tiltY = this.knotP2.tiltY;
+ this.scratchPredPt.twist = this.knotP2.twist;
+ const midSeg = this.splineGen.generateProvisionalSegment(
+ this.scratchPrevPredPt,
+ this.scratchPredPt,
+ vel.vx,
+ vel.vy
+ );
+ onSegment(midSeg);
+ this.copyKnot(this.scratchPrevPredPt, this.scratchPredPt);
+ }
+
+ this.scratchPredPt.x = tipX;
+ this.scratchPredPt.y = tipY;
+ this.scratchPredPt.pressure = this.scratchPrevPredPt.pressure;
+ this.scratchPredPt.width = this.scratchPrevPredPt.width;
+ this.scratchPredPt.tiltX = this.knotP2.tiltX;
+ this.scratchPredPt.tiltY = this.knotP2.tiltY;
+ this.scratchPredPt.twist = this.knotP2.twist;
+ const rawSeg = this.splineGen.generateProvisionalSegment(
+ this.scratchPrevPredPt,
+ this.scratchPredPt,
+ vel.vx,
+ vel.vy
+ );
+ onSegment(rawSeg);
+ this.copyKnot(this.scratchPrevPredPt, this.scratchPredPt);
+ }
+ }
+
+ // 3. Speculative lookahead strictly from hardware getPredictedEvents()
if (predictedDocCoords && predictedDocCoords.length > 0) {
- this.copyKnot(this.scratchPrevPredPt, this.knotP2);
for (let i = 0; i < predictedDocCoords.length; i++) {
const raw = predictedDocCoords[i];
const dx = raw.x - this.scratchPrevPredPt.x;
@@ -686,6 +887,66 @@ export class StrokePipeline {
const padExtra = options?.dirtyPadExtra ?? 0;
if (this.knotCount >= 2) {
+ // Smoothly catch up residual stabilizer lag all the way to the true pen-lift coordinate (rawX, rawY),
+ // curving gently through the 1st-stage guide point (s1) so curved tails close naturally without cutting short.
+ if (this.stabilizerLevel > 0) {
+ const catchUp = this.stabilizer.getCatchUpTarget();
+ const clampedZoom = Math.max(0.15, Math.min(4.0, this.zoomScale));
+ const minCatchUpDoc = 0.75 / clampedZoom;
+ if (catchUp.lagDist > minCatchUpDoc) {
+ const lagScreen = catchUp.lagDist * clampedZoom;
+ const steps = Math.min(6, Math.max(2, Math.ceil(lagScreen / 5.0)));
+ const startX = this.knotP2.x;
+ const startY = this.knotP2.y;
+ const ctrlX = catchUp.midX;
+ const ctrlY = catchUp.midY;
+ const endX = catchUp.x;
+ const endY = catchUp.y;
+ const startP = this.knotP2.pressure;
+ const startW = this.knotP2.width;
+ const vel = this.getLastVelocity();
+ for (let i = 1; i <= steps; i++) {
+ const frac = i / steps;
+ const inv = 1.0 - frac;
+ // Quadratic Bézier from stabilized tail (s3) through s1 to exact raw pen-lift coordinate
+ const cx = inv * inv * startX + 2.0 * inv * frac * ctrlX + frac * frac * endX;
+ const cy = inv * inv * startY + 2.0 * inv * frac * ctrlY + frac * frac * endY;
+ const sample = this.scratchSample;
+ sample.x = cx;
+ sample.y = cy;
+ sample.pressure = startP;
+ sample.width = startW;
+ sample.opacity = Math.max(0, Math.min(1, startP));
+ sample.tiltX = this.knotP2.tiltX ?? 0;
+ sample.tiltY = this.knotP2.tiltY ?? 0;
+ sample.twist = this.knotP2.twist ?? 0;
+ sample.timestamp = endTimestampMs;
+ sample.isCorner = false;
+ sample.vx = vel.vx;
+ sample.vy = vel.vy;
+ sample.pointerType = 'pen';
+
+ this.expandDirtyRect(cx, cy, startW + padExtra);
+ options?.onPoint?.(sample);
+ this.advanceSplineKnot(
+ cx,
+ cy,
+ startP,
+ startW,
+ sample.tiltX,
+ sample.tiltY,
+ sample.twist,
+ endTimestampMs,
+ vel.vx,
+ vel.vy,
+ false,
+ padExtra,
+ options?.onSegment
+ );
+ }
+ }
+ }
+
let flickCount = 0;
let flickPoints: ReturnType<TaperEngine['computeFlickTaper']>['points'] = [];
let velX = 0;
diff --git a/src/engine/TaperEngine.ts b/src/engine/TaperEngine.ts
index f9c25fd..dac1bde 100644
--- a/src/engine/TaperEngine.ts
+++ b/src/engine/TaperEngine.ts
@@ -20,10 +20,10 @@ export interface FlickConfig {
}
export const DEFAULT_PRESSURE_CONFIG: PressureConfig = {
- deadzone: 0.02,
+ deadzone: 0.005,
gamma: 1.85,
midpoint: 0.45,
- minPressure: 0.005,
+ minPressure: 0.012,
};
export const DEFAULT_FLICK_CONFIG: FlickConfig = {
diff --git a/src/engine/WebGlBrushEngine.ts b/src/engine/WebGlBrushEngine.ts
index ea3b6fd..3e16e95 100644
--- a/src/engine/WebGlBrushEngine.ts
+++ b/src/engine/WebGlBrushEngine.ts
@@ -1,6 +1,44 @@
-import { Point, BrushSettings, ToolType, SurfaceTextureId, ImpastoSettings } from '../types/editor';
+import {
+ Point,
+ BrushSettings,
+ ToolType,
+ SurfaceTextureId,
+ ImpastoSettings,
+ DualBrushCompositeMode,
+ CspPaperTextureMode,
+} from '../types/editor';
import { getSurfaceTextureHeightField, SURFACE_TEXTURE_SIZE } from '../utils/proceduralBrushTips';
import { performanceManager } from '../utils/performanceManager';
+import {
+ PIGMENT_GLSL_WEBGL1,
+ getPigmentLutTexture,
+ invalidatePigmentLutTexture,
+} from '../utils/pigmentEngine';
+import { dualBrushCompositeModeToIndex } from './DualBrushEngine';
+
+export function paperTextureModeToIndex(mode?: CspPaperTextureMode): number {
+ switch (mode) {
+ case 'multiply':
+ return 1;
+ case 'compare':
+ return 2;
+ case 'overlay':
+ return 3;
+ case 'outline':
+ return 4;
+ case 'normal':
+ return 5;
+ case 'color-burn':
+ return 6;
+ case 'linear-burn':
+ return 7;
+ case 'height':
+ return 8;
+ case 'subtract':
+ default:
+ return 0;
+ }
+}
export interface GpuInfo {
isSupported: boolean;
@@ -24,6 +62,16 @@ export interface GpuDab {
flipX?: number;
flipY?: number;
tipIndex?: number;
+ /** Optional per-dab paper texture density override (0..1) from CSP TextureDensityEffector. */
+ grainDensity?: number;
+}
+
+export const RIBBON_VERTEX_STRIDE = 9;
+
+export interface TexturedRibbonMeshInput {
+ vertices: Float32Array;
+ vertexCount: number;
+ bounds: { minX: number; minY: number; maxX: number; maxY: number };
}
const VERTEX_SHADER_SRC = `
@@ -100,16 +148,11 @@ varying float v_tipIndex;
uniform bool u_hasTipTexture;
uniform bool u_isColorTip;
+uniform bool u_isDualToneTip;
+uniform vec3 u_secondaryColor;
uniform sampler2D u_tipTexture;
uniform vec2 u_tipAtlasGrid;
-uniform bool u_hasDualTipTexture;
-uniform sampler2D u_dualTipTexture;
-uniform int u_dualBlendMode;
-uniform float u_dualScale;
-uniform float u_dualRotRad;
-uniform float u_dualScatter;
-
uniform int u_antiAlias;
uniform float u_hardness;
uniform float u_wetEdge;
@@ -125,6 +168,8 @@ uniform int u_paperMode;
uniform float u_paperBrightness;
uniform float u_paperContrast;
uniform bool u_paperInvert;
+uniform bool u_paperPreserveDensity;
+uniform bool u_paperEmphasizeDensity;
uniform bool u_hasPaperTex;
uniform sampler2D u_paperTexture;
uniform vec2 u_paperTexSize;
@@ -132,6 +177,7 @@ uniform vec2 u_paperTexSize;
uniform bool u_colorMixing;
uniform bool u_perceptualMixing;
uniform float u_pigmentStrength;
+uniform sampler2D u_pigmentLut;
uniform bool u_hasCanvasTexture;
uniform sampler2D u_canvasTexture;
uniform vec2 u_canvasResolution;
@@ -167,7 +213,9 @@ float samplePaperTooth(vec2 worldPos) {
vec2 uv = fract(rotP / max(vec2(1.0), u_paperTexSize));
vec4 pSample = texture2D(u_paperTexture, uv);
float lum = dot(pSample.rgb, vec3(0.299, 0.587, 0.114));
- g = pSample.a < 0.98 ? (1.0 - pSample.a) : lum;
+ // Composite over white: handles both CSP black-on-transparent paper textures (RGB=0, A=density)
+ // and opaque grayscale heightmaps seamlessly without alpha-threshold cliffs.
+ g = mix(1.0, lum, pSample.a);
} else {
vec2 coord = rotP * 0.09;
float n1 = sin(coord.x * 3.1415 + coord.y * 1.7) * cos(coord.y * 2.718 - coord.x * 0.9);
@@ -178,6 +226,9 @@ float samplePaperTooth(vec2 worldPos) {
if (u_paperInvert) {
g = 1.0 - g;
}
+ if (u_paperEmphasizeDensity) {
+ g = clamp((g - 0.5) * 2.2 + 0.35, 0.0, 1.0);
+ }
if (abs(u_paperBrightness) > 0.001) {
g += u_paperBrightness;
}
@@ -188,143 +239,7 @@ float samplePaperTooth(vec2 worldPos) {
return clamp(g, 0.0, 1.0);
}
-// 7-band Spectral Kubelka-Munk + OKLab Pigment Mixing (WebGL1-safe unrolled bands)
-float kmReflectanceBand(vec3 c, float bR, float bG, float bB, float bC, float bM, float bY) {
- float rr = 0.025 + c.r * 0.97;
- float gg = 0.025 + c.g * 0.97;
- float bb = 0.025 + c.b * 0.97;
- if (rr <= gg && rr <= bb) {
- if (gg <= bb) {
- return rr + (gg - rr) * bC + (bb - gg) * bB;
- }
- return rr + (bb - rr) * bC + (gg - bb) * bG;
- } else if (gg <= rr && gg <= bb) {
- if (rr <= bb) {
- return gg + (rr - gg) * bM + (bb - rr) * bB;
- }
- return gg + (bb - gg) * bM + (rr - bb) * bR;
- } else {
- if (rr <= gg) {
- return bb + (rr - bb) * bY + (gg - rr) * bG;
- }
- return bb + (gg - bb) * bY + (rr - gg) * bR;
- }
-}
-
-float kmMixBand(float s1, float s2, float w1, float w2) {
- float a = clamp(s1, 0.02, 0.998);
- float b = clamp(s2, 0.02, 0.998);
- float ks1 = pow(((1.0 - a) * (1.0 - a)) / (2.0 * a), 0.72);
- float ks2 = pow(((1.0 - b) * (1.0 - b)) / (2.0 * b), 0.72);
- float ks = pow(max(0.0, ks1 * w1 + ks2 * w2), 1.3888889);
- return 1.0 + ks - sqrt(ks * ks + 2.0 * ks);
-}
-
-vec3 linRgbToOklabGpu(vec3 c) {
- float l = 0.4122214708 * c.r + 0.5363325363 * c.g + 0.0514459929 * c.b;
- float m = 0.2119034982 * c.r + 0.6806995451 * c.g + 0.1073969566 * c.b;
- float s = 0.0883024619 * c.r + 0.2817188376 * c.g + 0.6299787005 * c.b;
- float l_ = pow(max(0.0, l), 0.33333333);
- float m_ = pow(max(0.0, m), 0.33333333);
- float s_ = pow(max(0.0, s), 0.33333333);
- return vec3(
- 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_,
- 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_,
- 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_
- );
-}
-
-vec3 oklabToLinRgbGpu(vec3 lab) {
- float l_ = lab.x + 0.3963377774 * lab.y + 0.2158037573 * lab.z;
- float m_ = lab.x - 0.1055613458 * lab.y - 0.0638541728 * lab.z;
- float s_ = lab.x - 0.0894841775 * lab.y - 1.2914855480 * lab.z;
- float l = l_ * l_ * l_;
- float m = m_ * m_ * m_;
- float s = s_ * s_ * s_;
- return vec3(
- 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
- -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
- -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s
- );
-}
-
-vec3 mixPigmentsGpu(vec3 c1, vec3 c2, float t) {
- float invT = 1.0 - t;
- vec3 l1 = pow(max(c1, vec3(0.0)), vec3(2.2));
- vec3 l2 = pow(max(c2, vec3(0.0)), vec3(2.2));
-
- float Y1 = dot(l1, vec3(0.2126, 0.7152, 0.0722));
- float Y2 = dot(l2, vec3(0.2126, 0.7152, 0.0722));
- float conc1 = pow(0.06 + Y1, 0.36);
- float conc2 = pow(0.06 + Y2, 0.36);
- float w1 = (invT * conc1) / max(1e-5, invT * conc1 + t * conc2);
- float w2 = 1.0 - w1;
-
- vec3 b1 = vec3(0.0);
- vec3 b2 = vec3(0.0);
- vec3 mBase = vec3(0.0);
-
- // Band 0 (420nm)
- float s1 = kmReflectanceBand(l1, 0.025, 0.020, 0.880, 0.720, 0.780, 0.018);
- float s2 = kmReflectanceBand(l2, 0.025, 0.020, 0.880, 0.720, 0.780, 0.018);
- vec3 wv = vec3(0.140, -0.050, 0.340);
- b1 += s1 * wv; b2 += s2 * wv; mBase += kmMixBand(s1, s2, w1, w2) * wv;
-
- // Band 1 (460nm)
- s1 = kmReflectanceBand(l1, 0.018, 0.040, 0.990, 0.980, 0.500, 0.022);
- s2 = kmReflectanceBand(l2, 0.018, 0.040, 0.990, 0.980, 0.500, 0.022);
- wv = vec3(0.030, 0.045, 0.550);
- b1 += s1 * wv; b2 += s2 * wv; mBase += kmMixBand(s1, s2, w1, w2) * wv;
-
- // Band 2 (500nm)
- s1 = kmReflectanceBand(l1, 0.020, 0.420, 0.780, 0.990, 0.055, 0.280);
- s2 = kmReflectanceBand(l2, 0.020, 0.420, 0.780, 0.990, 0.055, 0.280);
- wv = vec3(-0.145, 0.250, 0.145);
- b1 += s1 * wv; b2 += s2 * wv; mBase += kmMixBand(s1, s2, w1, w2) * wv;
-
- // Band 3 (540nm)
- s1 = kmReflectanceBand(l1, 0.035, 0.980, 0.340, 0.840, 0.025, 0.930);
- s2 = kmReflectanceBand(l2, 0.035, 0.980, 0.340, 0.840, 0.025, 0.930);
- wv = vec3(-0.080, 0.500, -0.028);
- b1 += s1 * wv; b2 += s2 * wv; mBase += kmMixBand(s1, s2, w1, w2) * wv;
-
- // Band 4 (580nm)
- s1 = kmReflectanceBand(l1, 0.360, 0.900, 0.025, 0.140, 0.640, 0.995);
- s2 = kmReflectanceBand(l2, 0.360, 0.900, 0.025, 0.140, 0.640, 0.995);
- wv = vec3(0.365, 0.300, -0.007);
- b1 += s1 * wv; b2 += s2 * wv; mBase += kmMixBand(s1, s2, w1, w2) * wv;
-
- // Band 5 (620nm)
- s1 = kmReflectanceBand(l1, 0.965, 0.420, 0.020, 0.025, 0.975, 0.990);
- s2 = kmReflectanceBand(l2, 0.965, 0.420, 0.020, 0.025, 0.975, 0.990);
- wv = vec3(0.465, -0.018, 0.000);
- b1 += s1 * wv; b2 += s2 * wv; mBase += kmMixBand(s1, s2, w1, w2) * wv;
-
- // Band 6 (660nm)
- s1 = kmReflectanceBand(l1, 0.990, 0.060, 0.055, 0.025, 0.990, 0.980);
- s2 = kmReflectanceBand(l2, 0.990, 0.060, 0.055, 0.025, 0.990, 0.980);
- wv = vec3(0.225, -0.027, 0.000);
- b1 += s1 * wv; b2 += s2 * wv; mBase += kmMixBand(s1, s2, w1, w2) * wv;
-
- vec3 res1 = l1 - (b1 - vec3(0.025)) * 1.0309278;
- vec3 res2 = l2 - (b2 - vec3(0.025)) * 1.0309278;
- vec3 mixLin = max(vec3(0.0), (mBase - vec3(0.025)) * 1.0309278 + res1 * invT + res2 * t);
-
- vec3 lab1 = linRgbToOklabGpu(l1);
- vec3 lab2 = linRgbToOklabGpu(l2);
- vec3 labM = linRgbToOklabGpu(mixLin);
-
- float tunedL = clamp(labM.x * 0.40 + (lab1.x * invT + lab2.x * t) * 0.60, 0.0, 1.0);
- float c1Ch = length(lab1.yz);
- float c2Ch = length(lab2.yz);
- float mCh = length(labM.yz);
- float linCh = c1Ch * invT + c2Ch * t;
- float boost = (mCh > 0.008 && linCh > mCh) ? min(1.65, (mCh + (linCh - mCh) * 0.50) / mCh) : 1.0;
- vec2 ab = labM.yz * boost;
-
- vec3 fin = oklabToLinRgbGpu(vec3(tunedL, ab));
- return clamp(pow(max(fin, vec3(0.0)), vec3(1.0 / 2.2)), 0.0, 1.0);
-}
+${PIGMENT_GLSL_WEBGL1}
void main() {
float dist = length(v_localPos);
@@ -347,6 +262,9 @@ void main() {
tipAlpha = tex.a;
if (u_isColorTip) {
rgb = tex.rgb;
+ } else if (u_isDualToneTip) {
+ float lum = dot(tex.rgb, vec3(0.299, 0.587, 0.114));
+ rgb = mix(v_color.rgb, u_secondaryColor, lum);
}
if (u_antiAlias == 0) {
tipAlpha = tipAlpha >= 0.5 ? 1.0 : 0.0;
@@ -371,63 +289,63 @@ void main() {
}
}
- if (u_hasDualTipTexture) {
- vec2 centered = (v_uv - 0.5) / max(0.1, u_dualScale);
- float dc = cos(u_dualRotRad);
- float ds = sin(u_dualRotRad);
- vec2 dRot = vec2(centered.x * dc - centered.y * ds, centered.x * ds + centered.y * dc);
- if (u_dualScatter > 0.001) {
- float sHash = fract(sin(v_strokeDist * 0.137 + v_angle * 12.9898) * 43758.5453);
- float sHash2 = fract(sin(v_strokeDist * 0.271 + v_angle * 78.233) * 24634.6345);
- dRot += (vec2(sHash, sHash2) - 0.5) * u_dualScatter * 0.5;
- }
- vec2 dualUv = dRot + 0.5;
- float dualA = (dualUv.x >= 0.0 && dualUv.x <= 1.0 && dualUv.y >= 0.0 && dualUv.y <= 1.0)
- ? texture2D(u_dualTipTexture, dualUv).a
- : 0.0;
- if (u_dualBlendMode == 1) {
- tipAlpha = max(0.0, tipAlpha - (1.0 - dualA));
- } else if (u_dualBlendMode == 2) {
- tipAlpha = min(tipAlpha, dualA);
- } else if (u_dualBlendMode == 3) {
- tipAlpha = tipAlpha < 0.5 ? (2.0 * tipAlpha * dualA) : (1.0 - 2.0 * (1.0 - tipAlpha) * (1.0 - dualA));
- } else if (u_dualBlendMode == 4) {
- tipAlpha = tipAlpha + dualA - tipAlpha * dualA;
- } else {
- tipAlpha *= dualA;
- }
- }
-
if (tipAlpha <= 0.002) {
discard;
}
- if (u_paperGrain > 0.001 || u_dryBrush > 0.001) {
+ // Modulate brush tip profile (0..1) BEFORE scaling by per-dab flow (matching CSP TextureForPlot=1 & CPU/SpatialTipMixer)
+ float dabPaperGrain = v_color.a >= 0.0 ? v_color.a : u_paperGrain;
+ if (dabPaperGrain > 0.001 || u_dryBrush > 0.001) {
float g = samplePaperTooth(v_worldPos);
float p = clamp(v_pressure, 0.0, 1.0);
float heavyExcess = max(0.0, (p - 0.52) / 0.48);
float penetration = min(0.92, (p * 0.28 + heavyExcess * heavyExcess * 0.64) * (0.45 + 0.55 * clamp(u_paintLoad, 0.0, 1.0)));
- float effDensity = max(u_paperGrain, u_dryBrush * 0.85) * (1.0 - penetration * 0.85);
+ float effDensity = u_paperPreserveDensity
+ ? max(dabPaperGrain, u_dryBrush * 0.85)
+ : max(dabPaperGrain, u_dryBrush * 0.85) * (1.0 - penetration * 0.85);
if (u_dryBrush > 0.01) {
float cutoff = u_dryBrush * (1.0 - penetration * 0.86) * 0.78;
float tooth = smoothstep(cutoff - 0.06, cutoff + 0.14, g);
- tipAlpha *= mix(1.0, tooth, clamp(u_dryBrush + u_paperGrain * 0.5, 0.0, 1.0));
+ tipAlpha *= mix(1.0, tooth, clamp(u_dryBrush + dabPaperGrain * 0.5, 0.0, 1.0));
} else if (u_paperMode == 1) {
+ // multiply
tipAlpha *= (1.0 - effDensity * (1.0 - g));
} else if (u_paperMode == 2) {
+ // compare
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) {
- float ov = tipAlpha < 0.5 ? (2.0 * tipAlpha * g) : (1.0 - 2.0 * (1.0 - tipAlpha) * (1.0 - g));
- tipAlpha = mix(tipAlpha, ov, effDensity);
+ // overlay
+ float dMod = tipAlpha * (1.0 - effDensity * 0.32 * (1.0 - g));
+ float ov = dMod < 0.5 ? (2.0 * dMod * g) : (1.0 - 2.0 * (1.0 - dMod) * (1.0 - g));
+ tipAlpha = clamp(mix(tipAlpha, ov, effDensity), 0.0, 1.0);
} 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 if (u_paperMode == 5) {
+ // normal
+ float sil = min(1.0, tipAlpha * 4.0);
+ tipAlpha = clamp(tipAlpha * (1.0 - effDensity) + g * sil * effDensity, 0.0, 1.0);
+ } else if (u_paperMode == 6) {
+ // color-burn
+ float burned = g <= 0.001 ? 0.0 : max(0.0, 1.0 - (1.0 - tipAlpha) / g);
+ tipAlpha = clamp(mix(tipAlpha, burned, effDensity), 0.0, 1.0);
+ } else if (u_paperMode == 7) {
+ // linear-burn
+ float burned = max(0.0, tipAlpha + g - 1.0);
+ tipAlpha = clamp(mix(tipAlpha, burned, effDensity), 0.0, 1.0);
+ } else if (u_paperMode == 8) {
+ // height
+ float sil = min(1.0, tipAlpha * 4.0);
+ float relief = clamp((tipAlpha + g - 0.5) * 1.6, 0.0, 1.0) * sil;
+ tipAlpha = clamp(tipAlpha * (1.0 - effDensity) + relief * effDensity, 0.0, 1.0);
} else {
- float sub = (1.0 - g) * effDensity * (1.0 - penetration * 0.5);
+ // 0: subtract
+ float sub = (1.0 - g) * effDensity * (u_paperPreserveDensity ? 1.0 : (1.0 - penetration * 0.5));
tipAlpha = max(0.0, tipAlpha - sub);
}
@@ -436,6 +354,8 @@ void main() {
}
}
+ float finalAlpha = clamp(tipAlpha * v_alpha, 0.0, 1.0);
+
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);
@@ -448,17 +368,15 @@ void main() {
? 1.0
: clamp(mix(u_amountOfPaint, 1.0, (1.0 - stretchDecay) * 0.35), 0.02, 1.0);
if (u_perceptualMixing && u_pigmentStrength > 0.005) {
- vec3 pig = mixPigmentsGpu(canvasColor.rgb, rgb, effectiveAmount);
- vec3 lin = mix(canvasColor.rgb, rgb, effectiveAmount);
- rgb = mix(lin, pig, clamp(u_pigmentStrength, 0.0, 1.0));
+ rgb = mixPigmentsGpu(canvasColor.rgb, rgb, effectiveAmount, u_pigmentStrength);
} else {
rgb = mix(canvasColor.rgb, rgb, effectiveAmount);
}
- tipAlpha *= mix(0.65, 1.0, u_densityOfPaint);
+ finalAlpha *= mix(0.65, 1.0, u_densityOfPaint);
}
}
- float finalAlpha = clamp(tipAlpha * v_alpha, 0.0, 1.0);
+ finalAlpha = clamp(finalAlpha, 0.0, 1.0);
if (u_antiAlias == 0) {
finalAlpha = finalAlpha >= 0.5 ? 1.0 : 0.0;
if (finalAlpha <= 0.0) discard;
@@ -484,6 +402,83 @@ void main() {
}
`;
+const DUAL_COMBINE_FRAGMENT_SHADER_SRC = `
+precision highp float;
+
+varying vec2 v_uv;
+
+uniform sampler2D u_primaryTex;
+uniform sampler2D u_secondaryTex;
+uniform vec2 u_uvScale;
+uniform int u_combineMode;
+
+float combineDualAlpha(float a1, float a2, int mode) {
+ if (a1 <= 0.0001) return 0.0;
+ float p1 = clamp(a1, 0.0, 1.0);
+ float p2 = clamp(a2, 0.0, 1.0);
+ if (mode == 0) {
+ // multiply
+ return p1 * p2;
+ } else if (mode == 1) {
+ // darken
+ return min(p1, p2);
+ } else if (mode == 2) {
+ // subtract
+ return max(0.0, p1 - p2);
+ } else if (mode == 3) {
+ // compare-density
+ float sil = min(1.0, p1 * 4.0);
+ return max(p1, p2 * sil);
+ } else if (mode == 4) {
+ // linear-burn
+ return max(0.0, p1 + p2 - 1.0);
+ } else if (mode == 5) {
+ // color-burn
+ return p2 <= 0.0001 ? 0.0 : max(0.0, 1.0 - (1.0 - p1) / p2);
+ } else if (mode == 6) {
+ // height
+ float h = p1 + p2 - 1.0;
+ float t = clamp(h * 4.0, 0.0, 1.0);
+ return t * t * (3.0 - 2.0 * t);
+ } else if (mode == 7) {
+ // overlay
+ return p1 < 0.5 ? (2.0 * p1 * p2) : (1.0 - 2.0 * (1.0 - p1) * (1.0 - p2));
+ } else if (mode == 8) {
+ // screen
+ float sil = min(1.0, p1 * 4.0);
+ float eff2 = p2 * sil;
+ return p1 + eff2 - p1 * eff2;
+ } else if (mode == 9) {
+ // lighten
+ float sil = min(1.0, p1 * 4.0);
+ return max(p1, p2 * sil);
+ } else if (mode == 10) {
+ // hard-mix
+ return (p1 + p2 >= 1.0) ? 1.0 : 0.0;
+ } else if (mode == 11) {
+ // normal
+ float sil = min(1.0, p1 * 4.0);
+ float eff2 = p2 * sil;
+ return p1 + eff2 * (1.0 - p1);
+ }
+ return p1 * p2;
+}
+
+void main() {
+ vec2 uv = v_uv * u_uvScale;
+ vec4 p = texture2D(u_primaryTex, uv);
+ float a1 = clamp(p.a, 0.0, 1.0);
+ if (a1 <= 0.0001) {
+ gl_FragColor = vec4(0.0);
+ return;
+ }
+ vec3 rgb = clamp(p.rgb / a1, 0.0, 1.0);
+ float a2 = clamp(texture2D(u_secondaryTex, uv).a, 0.0, 1.0);
+ float outA = clamp(combineDualAlpha(a1, a2, u_combineMode), 0.0, 1.0);
+ gl_FragColor = vec4(rgb * outA, outA);
+}
+`;
+
const IMPASTO_FRAGMENT_SHADER_SRC = `
precision highp float;
@@ -630,6 +625,225 @@ void main() {
}
`;
+const TEXTURED_RIBBON_VERTEX_SHADER_SRC = `
+precision highp float;
+
+attribute vec2 a_pos;
+attribute vec2 a_uv;
+attribute float a_alpha;
+attribute float a_pressure;
+attribute float a_tipIndex;
+attribute vec2 a_edgeInfo;
+
+uniform vec2 u_canvasResolution;
+uniform vec2 u_dirtyOffset;
+
+varying vec2 v_uv;
+varying float v_alpha;
+varying float v_pressure;
+varying float v_tipIndex;
+varying vec2 v_edgeInfo;
+varying vec2 v_worldPos;
+
+void main() {
+ v_uv = a_uv;
+ v_alpha = a_alpha;
+ v_pressure = a_pressure;
+ v_tipIndex = a_tipIndex;
+ v_edgeInfo = a_edgeInfo;
+ v_worldPos = a_pos;
+
+ vec2 clipPos = ((a_pos - u_dirtyOffset) / u_canvasResolution) * 2.0 - 1.0;
+ clipPos.y = -clipPos.y;
+
+ gl_Position = vec4(clipPos, 0.0, 1.0);
+}
+`;
+
+const TEXTURED_RIBBON_FRAGMENT_SHADER_SRC = `
+precision highp float;
+
+varying vec2 v_uv;
+varying float v_alpha;
+varying float v_pressure;
+varying float v_tipIndex;
+varying vec2 v_edgeInfo;
+varying vec2 v_worldPos;
+
+uniform bool u_hasTipTexture;
+uniform sampler2D u_tipTexture;
+uniform vec2 u_tipAtlasGrid;
+uniform bool u_isColorTip;
+uniform bool u_isDualToneTip;
+uniform vec3 u_primaryColor;
+uniform vec3 u_secondaryColor;
+uniform int u_antiAlias;
+
+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_paperPreserveDensity;
+uniform bool u_paperEmphasizeDensity;
+uniform bool u_hasPaperTex;
+uniform sampler2D u_paperTexture;
+uniform vec2 u_paperTexSize;
+
+uniform bool u_isEraser;
+uniform bool u_isBgEraser;
+
+float sampleRibbonPaperTooth(vec2 worldPos) {
+ float invScale = 1.0 / max(0.05, u_grainScale);
+ float c = cos(u_grainRotateRad);
+ float s = sin(u_grainRotateRad);
+ vec2 rotP = vec2(worldPos.x * c - worldPos.y * s, worldPos.x * s + worldPos.y * c) * invScale;
+
+ float g = 0.5;
+ if (u_hasPaperTex) {
+ vec2 uv = fract(rotP / max(vec2(1.0), u_paperTexSize));
+ vec4 pSample = texture2D(u_paperTexture, uv);
+ float lum = dot(pSample.rgb, vec3(0.299, 0.587, 0.114));
+ g = mix(1.0, lum, pSample.a);
+ } else {
+ vec2 coord = rotP * 0.09;
+ float n1 = sin(coord.x * 3.1415 + coord.y * 1.7) * cos(coord.y * 2.718 - coord.x * 0.9);
+ float n2 = sin(coord.x * 7.3 - coord.y * 5.1) * cos(coord.x * 4.2 + coord.y * 8.3);
+ g = clamp((n1 * 0.6 + n2 * 0.4) * 0.5 + 0.5, 0.0, 1.0);
+ }
+
+ if (u_paperInvert) {
+ g = 1.0 - g;
+ }
+ if (u_paperEmphasizeDensity) {
+ g = clamp((g - 0.5) * 2.2 + 0.35, 0.0, 1.0);
+ }
+ if (abs(u_paperBrightness) > 0.001) {
+ g += u_paperBrightness;
+ }
+ if (abs(u_paperContrast) > 0.001) {
+ float cf = pow(max(0.05, 1.0 + u_paperContrast), 2.0);
+ g = (g - 0.5) * cf + 0.5;
+ }
+ return clamp(g, 0.0, 1.0);
+}
+
+void main() {
+ if (v_uv.x < 0.0 || v_uv.x > 1.0 || v_uv.y < 0.0 || v_uv.y > 1.0) {
+ discard;
+ }
+
+ vec3 rgb = u_primaryColor;
+ float tipAlpha = 1.0;
+
+ if (u_hasTipTexture) {
+ vec2 sampleUv = v_uv;
+ if (u_tipAtlasGrid.x > 1.0 || u_tipAtlasGrid.y > 1.0) {
+ float cols = max(1.0, u_tipAtlasGrid.x);
+ float rows = max(1.0, u_tipAtlasGrid.y);
+ float idx = floor(max(0.0, v_tipIndex) + 0.5);
+ float col = mod(idx, cols);
+ float row = floor(idx / cols);
+ vec2 cellSize = vec2(1.0 / cols, 1.0 / rows);
+ vec2 inset = cellSize * 0.004;
+ sampleUv = vec2(col, row) * cellSize + inset + clamp(v_uv, 0.0, 1.0) * (cellSize - inset * 2.0);
+ }
+ vec4 tex = texture2D(u_tipTexture, sampleUv);
+ tipAlpha = tex.a;
+ if (!u_isEraser && !u_isBgEraser) {
+ if (u_isColorTip) {
+ rgb = tex.rgb;
+ } else if (u_isDualToneTip) {
+ float lum = dot(tex.rgb, vec3(0.299, 0.587, 0.114));
+ rgb = mix(u_primaryColor, u_secondaryColor, lum);
+ }
+ }
+ } else {
+ tipAlpha = 1.0 - smoothstep(0.85, 1.0, abs(v_edgeInfo.x));
+ }
+
+ if (u_antiAlias == 0) {
+ tipAlpha = tipAlpha >= 0.5 ? 1.0 : 0.0;
+ } else {
+ float edgePx = u_antiAlias == 1 ? 0.65 : (u_antiAlias == 3 ? 1.85 : 1.15);
+ float edgeUv = clamp(edgePx / max(1.0, v_edgeInfo.y), 0.0, 0.45);
+ if (edgeUv > 0.0001) {
+ float edgeMask = 1.0 - smoothstep(1.0 - edgeUv * 2.0, 1.0, abs(v_edgeInfo.x));
+ tipAlpha *= edgeMask;
+ }
+ }
+
+ if (tipAlpha <= 0.002) {
+ discard;
+ }
+
+ // Modulate ribbon tip profile (0..1) BEFORE scaling by per-vertex flow (matching CSP TextureForPlot=1 & CPU)
+ if (u_paperGrain > 0.005) {
+ float g = sampleRibbonPaperTooth(v_worldPos);
+ float p = clamp(v_pressure, 0.0, 1.0);
+ float heavyExcess = max(0.0, (p - 0.52) / 0.48);
+ float penetration = min(0.92, p * 0.28 + heavyExcess * heavyExcess * 0.64);
+ float effDensity = u_paperPreserveDensity
+ ? u_paperGrain
+ : u_paperGrain * (1.0 - penetration * 0.85);
+
+ if (u_paperMode == 1) {
+ tipAlpha *= (1.0 - effDensity * (1.0 - g));
+ } else if (u_paperMode == 2) {
+ 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) {
+ float dMod = tipAlpha * (1.0 - effDensity * 0.32 * (1.0 - g));
+ float ov = dMod < 0.5 ? (2.0 * dMod * g) : (1.0 - 2.0 * (1.0 - dMod) * (1.0 - g));
+ tipAlpha = clamp(mix(tipAlpha, ov, effDensity), 0.0, 1.0);
+ } else if (u_paperMode == 4) {
+ float edgeFactor = 4.0 * tipAlpha * (1.0 - tipAlpha);
+ tipAlpha *= (1.0 - effDensity * (1.0 - g) * (0.35 + 0.65 * edgeFactor));
+ } else if (u_paperMode == 5) {
+ float sil = min(1.0, tipAlpha * 4.0);
+ tipAlpha = clamp(tipAlpha * (1.0 - effDensity) + g * sil * effDensity, 0.0, 1.0);
+ } else if (u_paperMode == 6) {
+ float burned = g <= 0.001 ? 0.0 : max(0.0, 1.0 - (1.0 - tipAlpha) / g);
+ tipAlpha = clamp(mix(tipAlpha, burned, effDensity), 0.0, 1.0);
+ } else if (u_paperMode == 7) {
+ float burned = max(0.0, tipAlpha + g - 1.0);
+ tipAlpha = clamp(mix(tipAlpha, burned, effDensity), 0.0, 1.0);
+ } else if (u_paperMode == 8) {
+ float sil = min(1.0, tipAlpha * 4.0);
+ float relief = clamp((tipAlpha + g - 0.5) * 1.6, 0.0, 1.0) * sil;
+ tipAlpha = clamp(tipAlpha * (1.0 - effDensity) + relief * effDensity, 0.0, 1.0);
+ } else {
+ float sub = (1.0 - g) * effDensity * (u_paperPreserveDensity ? 1.0 : (1.0 - penetration * 0.5));
+ tipAlpha = max(0.0, tipAlpha - sub);
+ }
+
+ if (tipAlpha <= 0.002) {
+ discard;
+ }
+ }
+
+ float finalAlpha = clamp(tipAlpha * v_alpha, 0.0, 1.0);
+
+ finalAlpha = clamp(finalAlpha, 0.0, 1.0);
+ if (u_antiAlias == 0) {
+ finalAlpha = finalAlpha >= 0.5 ? 1.0 : 0.0;
+ if (finalAlpha <= 0.0) discard;
+ }
+
+ if (u_isBgEraser) {
+ gl_FragColor = vec4(finalAlpha, finalAlpha, finalAlpha, finalAlpha);
+ } else if (u_isEraser) {
+ gl_FragColor = vec4(0.0, 0.0, 0.0, finalAlpha);
+ } else {
+ gl_FragColor = vec4(rgb * finalAlpha, finalAlpha);
+ }
+}
+`;
+
const MAX_TILE_CHUNK = 2048;
/**
@@ -645,7 +859,9 @@ export class WebGlBrushEngine {
private gl: WebGLRenderingContext | WebGL2RenderingContext | null = null;
private program: WebGLProgram | null = null;
private ribbonProgram: WebGLProgram | null = null;
+ private texturedRibbonProgram: WebGLProgram | null = null;
private impastoProgram: WebGLProgram | null = null;
+ private dualCombineProgram: WebGLProgram | null = null;
private isGpuAvailable = false;
private gpuInfo: GpuInfo = {
isSupported: false,
@@ -670,14 +886,10 @@ export class WebGlBrushEngine {
private uDirtyOffsetLoc: WebGLUniformLocation | null = null;
private uHasTipTextureLoc: WebGLUniformLocation | null = null;
private uIsColorTipLoc: WebGLUniformLocation | null = null;
+ private uIsDualToneTipLoc: WebGLUniformLocation | null = null;
+ private uSecondaryColorLoc: WebGLUniformLocation | null = null;
private uTipTextureLoc: WebGLUniformLocation | null = null;
private uTipAtlasGridLoc: WebGLUniformLocation | null = null;
- private uHasDualTipTextureLoc: WebGLUniformLocation | null = null;
- private uDualTipTextureLoc: WebGLUniformLocation | null = null;
- private uDualBlendModeLoc: WebGLUniformLocation | null = null;
- private uDualScaleLoc: WebGLUniformLocation | null = null;
- private uDualRotRadLoc: WebGLUniformLocation | null = null;
- private uDualScatterLoc: WebGLUniformLocation | null = null;
private uAntiAliasLoc: WebGLUniformLocation | null = null;
private uHardnessLoc: WebGLUniformLocation | null = null;
private uWetEdgeLoc: WebGLUniformLocation | null = null;
@@ -693,12 +905,15 @@ export class WebGlBrushEngine {
private uPaperBrightnessLoc: WebGLUniformLocation | null = null;
private uPaperContrastLoc: WebGLUniformLocation | null = null;
private uPaperInvertLoc: WebGLUniformLocation | null = null;
+ private uPaperPreserveDensityLoc: WebGLUniformLocation | null = null;
+ private uPaperEmphasizeDensityLoc: WebGLUniformLocation | null = null;
private uHasPaperTexLoc: WebGLUniformLocation | null = null;
private uPaperTextureLoc: WebGLUniformLocation | null = null;
private uPaperTexSizeLoc: WebGLUniformLocation | null = null;
private uColorMixingLoc: WebGLUniformLocation | null = null;
private uPerceptualMixingLoc: WebGLUniformLocation | null = null;
private uPigmentStrengthLoc: WebGLUniformLocation | null = null;
+ private uPigmentLutLoc: WebGLUniformLocation | null = null;
private uHasCanvasTextureLoc: WebGLUniformLocation | null = null;
private uCanvasTextureLoc: WebGLUniformLocation | null = null;
private uAmountOfPaintLoc: WebGLUniformLocation | null = null;
@@ -714,6 +929,39 @@ export class WebGlBrushEngine {
private aRibbonColorLoc = -1;
private aRibbonWidthLoc = -1;
+ // Textured CSP Ribbon Program locations & buffer
+ private aTexRibPosLoc = -1;
+ private aTexRibUvLoc = -1;
+ private aTexRibAlphaLoc = -1;
+ private aTexRibPressureLoc = -1;
+ private aTexRibTipIndexLoc = -1;
+ private aTexRibEdgeInfoLoc = -1;
+ private uTexRibCanvasResolutionLoc: WebGLUniformLocation | null = null;
+ private uTexRibDirtyOffsetLoc: WebGLUniformLocation | null = null;
+ private uTexRibHasTipTextureLoc: WebGLUniformLocation | null = null;
+ private uTexRibTipTextureLoc: WebGLUniformLocation | null = null;
+ private uTexRibTipAtlasGridLoc: WebGLUniformLocation | null = null;
+ private uTexRibIsColorTipLoc: WebGLUniformLocation | null = null;
+ private uTexRibIsDualToneTipLoc: WebGLUniformLocation | null = null;
+ private uTexRibPrimaryColorLoc: WebGLUniformLocation | null = null;
+ private uTexRibSecondaryColorLoc: WebGLUniformLocation | null = null;
+ private uTexRibAntiAliasLoc: WebGLUniformLocation | null = null;
+ private uTexRibPaperGrainLoc: WebGLUniformLocation | null = null;
+ private uTexRibGrainScaleLoc: WebGLUniformLocation | null = null;
+ private uTexRibGrainRotateRadLoc: WebGLUniformLocation | null = null;
+ private uTexRibPaperModeLoc: WebGLUniformLocation | null = null;
+ private uTexRibPaperBrightnessLoc: WebGLUniformLocation | null = null;
+ private uTexRibPaperContrastLoc: WebGLUniformLocation | null = null;
+ private uTexRibPaperInvertLoc: WebGLUniformLocation | null = null;
+ private uTexRibPaperPreserveDensityLoc: WebGLUniformLocation | null = null;
+ private uTexRibPaperEmphasizeDensityLoc: WebGLUniformLocation | null = null;
+ private uTexRibHasPaperTexLoc: WebGLUniformLocation | null = null;
+ private uTexRibPaperTextureLoc: WebGLUniformLocation | null = null;
+ private uTexRibPaperTexSizeLoc: WebGLUniformLocation | null = null;
+ private uTexRibIsEraserLoc: WebGLUniformLocation | null = null;
+ private uTexRibIsBgEraserLoc: WebGLUniformLocation | null = null;
+ private texturedRibbonBuffer: WebGLBuffer | null = null;
+
// Impasto Relief Post-Pass locations & resources
private aImpastoPosLoc = -1;
private uImpastoColorTexLoc: WebGLUniformLocation | null = null;
@@ -743,6 +991,19 @@ export class WebGlBrushEngine {
private dabFboWidth = 0;
private dabFboHeight = 0;
+ // Dual Brush two-pass FBO & fullscreen combine shader locations
+ private aDualCombinePosLoc = -1;
+ private uDualCombinePrimaryTexLoc: WebGLUniformLocation | null = null;
+ private uDualCombineSecondaryTexLoc: WebGLUniformLocation | null = null;
+ private uDualCombineUvScaleLoc: WebGLUniformLocation | null = null;
+ private uDualCombineModeLoc: WebGLUniformLocation | null = null;
+ private dualPrimaryFbo: WebGLFramebuffer | null = null;
+ private dualPrimaryTex: WebGLTexture | null = null;
+ private dualSecondaryFbo: WebGLFramebuffer | null = null;
+ private dualSecondaryTex: WebGLTexture | null = null;
+ private dualFboWidth = 0;
+ private dualFboHeight = 0;
+
private quadVertexBuffer: WebGLBuffer | null = null;
private extInstanced: {
drawArraysInstanced: (mode: number, first: number, count: number, instanceCount: number) => void;
@@ -750,6 +1011,9 @@ export class WebGlBrushEngine {
} | null = null;
private instanceBuffer: WebGLBuffer | null = null;
private instanceArray: Float32Array = new Float32Array(4096 * 15);
+ private secondaryInstanceBuffer: WebGLBuffer | null = null;
+ private secondaryInstanceArray: Float32Array = new Float32Array(2048 * 15);
+ private blendMaxEnum: number | null = null;
private ribbonBuffer: WebGLBuffer | null = null;
private ribbonArray: Float32Array = new Float32Array(1024 * 8);
@@ -802,6 +1066,7 @@ export class WebGlBrushEngine {
}
private clearTextureMapsState() {
+ invalidatePigmentLutTexture(this.gl, false);
this.tipTexturesMap.clear();
this.multiTipAtlasCache.clear();
this.surfaceTexturesMap.clear();
@@ -816,6 +1081,12 @@ export class WebGlBrushEngine {
this.dabFboTex = null;
this.dabFboWidth = 0;
this.dabFboHeight = 0;
+ this.dualPrimaryFbo = null;
+ this.dualPrimaryTex = null;
+ this.dualSecondaryFbo = null;
+ this.dualSecondaryTex = null;
+ this.dualFboWidth = 0;
+ this.dualFboHeight = 0;
}
/**
@@ -830,6 +1101,10 @@ export class WebGlBrushEngine {
if (this.canvasLayerTexture) gl.deleteTexture(this.canvasLayerTexture);
if (this.impastoColorTex) gl.deleteTexture(this.impastoColorTex);
if (this.impastoHeightTex) gl.deleteTexture(this.impastoHeightTex);
+ if (this.dualPrimaryTex) gl.deleteTexture(this.dualPrimaryTex);
+ if (this.dualSecondaryTex) gl.deleteTexture(this.dualSecondaryTex);
+ if (this.dualPrimaryFbo) gl.deleteFramebuffer(this.dualPrimaryFbo);
+ if (this.dualSecondaryFbo) gl.deleteFramebuffer(this.dualSecondaryFbo);
}
this.tipTexturesMap.clear();
this.multiTipAtlasCache.clear();
@@ -840,6 +1115,12 @@ export class WebGlBrushEngine {
this.canvasLayerSource = null;
this.impastoColorTex = null;
this.impastoHeightTex = null;
+ this.dualPrimaryTex = null;
+ this.dualSecondaryTex = null;
+ this.dualPrimaryFbo = null;
+ this.dualSecondaryFbo = null;
+ this.dualFboWidth = 0;
+ this.dualFboHeight = 0;
}
/**
@@ -858,7 +1139,10 @@ export class WebGlBrushEngine {
this.gl = null;
this.program = null;
this.ribbonProgram = null;
+ this.texturedRibbonProgram = null;
+ this.texturedRibbonBuffer = null;
this.impastoProgram = null;
+ this.dualCombineProgram = null;
this.canvas = null;
this.isGpuAvailable = false;
this.clearTextureMapsState();
@@ -882,7 +1166,10 @@ export class WebGlBrushEngine {
this.gl = null;
this.program = null;
this.ribbonProgram = null;
+ this.texturedRibbonProgram = null;
+ this.texturedRibbonBuffer = null;
this.impastoProgram = null;
+ this.dualCombineProgram = null;
this.canvas = null;
this.isGpuAvailable = false;
this.clearTextureMapsState();
@@ -964,14 +1251,10 @@ export class WebGlBrushEngine {
this.uDirtyOffsetLoc = gl.getUniformLocation(program, 'u_dirtyOffset');
this.uHasTipTextureLoc = gl.getUniformLocation(program, 'u_hasTipTexture');
this.uIsColorTipLoc = gl.getUniformLocation(program, 'u_isColorTip');
+ this.uIsDualToneTipLoc = gl.getUniformLocation(program, 'u_isDualToneTip');
+ this.uSecondaryColorLoc = gl.getUniformLocation(program, 'u_secondaryColor');
this.uTipTextureLoc = gl.getUniformLocation(program, 'u_tipTexture');
this.uTipAtlasGridLoc = gl.getUniformLocation(program, 'u_tipAtlasGrid');
- this.uHasDualTipTextureLoc = gl.getUniformLocation(program, 'u_hasDualTipTexture');
- this.uDualTipTextureLoc = gl.getUniformLocation(program, 'u_dualTipTexture');
- this.uDualBlendModeLoc = gl.getUniformLocation(program, 'u_dualBlendMode');
- this.uDualScaleLoc = gl.getUniformLocation(program, 'u_dualScale');
- this.uDualRotRadLoc = gl.getUniformLocation(program, 'u_dualRotRad');
- this.uDualScatterLoc = gl.getUniformLocation(program, 'u_dualScatter');
this.uAntiAliasLoc = gl.getUniformLocation(program, 'u_antiAlias');
this.uHardnessLoc = gl.getUniformLocation(program, 'u_hardness');
this.uWetEdgeLoc = gl.getUniformLocation(program, 'u_wetEdge');
@@ -987,12 +1270,15 @@ export class WebGlBrushEngine {
this.uPaperBrightnessLoc = gl.getUniformLocation(program, 'u_paperBrightness');
this.uPaperContrastLoc = gl.getUniformLocation(program, 'u_paperContrast');
this.uPaperInvertLoc = gl.getUniformLocation(program, 'u_paperInvert');
+ this.uPaperPreserveDensityLoc = gl.getUniformLocation(program, 'u_paperPreserveDensity');
+ this.uPaperEmphasizeDensityLoc = gl.getUniformLocation(program, 'u_paperEmphasizeDensity');
this.uHasPaperTexLoc = gl.getUniformLocation(program, 'u_hasPaperTex');
this.uPaperTextureLoc = gl.getUniformLocation(program, 'u_paperTexture');
this.uPaperTexSizeLoc = gl.getUniformLocation(program, 'u_paperTexSize');
this.uColorMixingLoc = gl.getUniformLocation(program, 'u_colorMixing');
this.uPerceptualMixingLoc = gl.getUniformLocation(program, 'u_perceptualMixing');
this.uPigmentStrengthLoc = gl.getUniformLocation(program, 'u_pigmentStrength');
+ this.uPigmentLutLoc = gl.getUniformLocation(program, 'u_pigmentLut');
this.uHasCanvasTextureLoc = gl.getUniformLocation(program, 'u_hasCanvasTexture');
this.uCanvasTextureLoc = gl.getUniformLocation(program, 'u_canvasTexture');
this.uAmountOfPaintLoc = gl.getUniformLocation(program, 'u_amountOfPaint');
@@ -1024,6 +1310,51 @@ export class WebGlBrushEngine {
}
}
+ const trVs = this.compileShader(gl.VERTEX_SHADER, TEXTURED_RIBBON_VERTEX_SHADER_SRC);
+ const trFs = this.compileShader(gl.FRAGMENT_SHADER, TEXTURED_RIBBON_FRAGMENT_SHADER_SRC);
+ if (trVs && trFs) {
+ const trProgram = gl.createProgram();
+ if (trProgram) {
+ gl.attachShader(trProgram, trVs);
+ gl.attachShader(trProgram, trFs);
+ gl.linkProgram(trProgram);
+ if (gl.getProgramParameter(trProgram, gl.LINK_STATUS)) {
+ this.texturedRibbonProgram = trProgram;
+ this.aTexRibPosLoc = gl.getAttribLocation(trProgram, 'a_pos');
+ this.aTexRibUvLoc = gl.getAttribLocation(trProgram, 'a_uv');
+ this.aTexRibAlphaLoc = gl.getAttribLocation(trProgram, 'a_alpha');
+ this.aTexRibPressureLoc = gl.getAttribLocation(trProgram, 'a_pressure');
+ this.aTexRibTipIndexLoc = gl.getAttribLocation(trProgram, 'a_tipIndex');
+ this.aTexRibEdgeInfoLoc = gl.getAttribLocation(trProgram, 'a_edgeInfo');
+
+ this.uTexRibCanvasResolutionLoc = gl.getUniformLocation(trProgram, 'u_canvasResolution');
+ this.uTexRibDirtyOffsetLoc = gl.getUniformLocation(trProgram, 'u_dirtyOffset');
+ this.uTexRibHasTipTextureLoc = gl.getUniformLocation(trProgram, 'u_hasTipTexture');
+ this.uTexRibTipTextureLoc = gl.getUniformLocation(trProgram, 'u_tipTexture');
+ this.uTexRibTipAtlasGridLoc = gl.getUniformLocation(trProgram, 'u_tipAtlasGrid');
+ this.uTexRibIsColorTipLoc = gl.getUniformLocation(trProgram, 'u_isColorTip');
+ this.uTexRibIsDualToneTipLoc = gl.getUniformLocation(trProgram, 'u_isDualToneTip');
+ this.uTexRibPrimaryColorLoc = gl.getUniformLocation(trProgram, 'u_primaryColor');
+ this.uTexRibSecondaryColorLoc = gl.getUniformLocation(trProgram, 'u_secondaryColor');
+ this.uTexRibAntiAliasLoc = gl.getUniformLocation(trProgram, 'u_antiAlias');
+ this.uTexRibPaperGrainLoc = gl.getUniformLocation(trProgram, 'u_paperGrain');
+ this.uTexRibGrainScaleLoc = gl.getUniformLocation(trProgram, 'u_grainScale');
+ this.uTexRibGrainRotateRadLoc = gl.getUniformLocation(trProgram, 'u_grainRotateRad');
+ this.uTexRibPaperModeLoc = gl.getUniformLocation(trProgram, 'u_paperMode');
+ this.uTexRibPaperBrightnessLoc = gl.getUniformLocation(trProgram, 'u_paperBrightness');
+ this.uTexRibPaperContrastLoc = gl.getUniformLocation(trProgram, 'u_paperContrast');
+ this.uTexRibPaperInvertLoc = gl.getUniformLocation(trProgram, 'u_paperInvert');
+ this.uTexRibPaperPreserveDensityLoc = gl.getUniformLocation(trProgram, 'u_paperPreserveDensity');
+ this.uTexRibPaperEmphasizeDensityLoc = gl.getUniformLocation(trProgram, 'u_paperEmphasizeDensity');
+ this.uTexRibHasPaperTexLoc = gl.getUniformLocation(trProgram, 'u_hasPaperTex');
+ this.uTexRibPaperTextureLoc = gl.getUniformLocation(trProgram, 'u_paperTexture');
+ this.uTexRibPaperTexSizeLoc = gl.getUniformLocation(trProgram, 'u_paperTexSize');
+ this.uTexRibIsEraserLoc = gl.getUniformLocation(trProgram, 'u_isEraser');
+ this.uTexRibIsBgEraserLoc = gl.getUniformLocation(trProgram, 'u_isBgEraser');
+ }
+ }
+ }
+
const quadVertices = new Float32Array([
-0.5, -0.5,
0.5, -0.5,
@@ -1068,7 +1399,27 @@ export class WebGlBrushEngine {
gl.STATIC_DRAW
);
+ const dcVs = this.compileShader(gl.VERTEX_SHADER, IMPASTO_VERTEX_SHADER_SRC);
+ const dcFs = this.compileShader(gl.FRAGMENT_SHADER, DUAL_COMBINE_FRAGMENT_SHADER_SRC);
+ if (dcVs && dcFs) {
+ const dcProgram = gl.createProgram();
+ if (dcProgram) {
+ gl.attachShader(dcProgram, dcVs);
+ gl.attachShader(dcProgram, dcFs);
+ gl.linkProgram(dcProgram);
+ if (gl.getProgramParameter(dcProgram, gl.LINK_STATUS)) {
+ this.dualCombineProgram = dcProgram;
+ this.aDualCombinePosLoc = gl.getAttribLocation(dcProgram, 'a_pos');
+ this.uDualCombinePrimaryTexLoc = gl.getUniformLocation(dcProgram, 'u_primaryTex');
+ this.uDualCombineSecondaryTexLoc = gl.getUniformLocation(dcProgram, 'u_secondaryTex');
+ this.uDualCombineUvScaleLoc = gl.getUniformLocation(dcProgram, 'u_uvScale');
+ this.uDualCombineModeLoc = gl.getUniformLocation(dcProgram, 'u_combineMode');
+ }
+ }
+ }
+
this.ribbonBuffer = gl.createBuffer();
+ this.texturedRibbonBuffer = gl.createBuffer();
if ('drawArraysInstanced' in gl) {
this.extInstanced = {
@@ -1093,15 +1444,27 @@ export class WebGlBrushEngine {
}
}
this.instanceBuffer = gl.createBuffer();
+ this.secondaryInstanceBuffer = gl.createBuffer();
if (WebGlBrushEngine.builtinGrainTable) {
this.uploadBuiltinPaperTexture(gl);
}
+ this.blendMaxEnum = null;
+ if ('MAX' in gl && typeof (gl as WebGL2RenderingContext).MAX === 'number') {
+ this.blendMaxEnum = (gl as WebGL2RenderingContext).MAX;
+ } else if (typeof gl.getExtension === 'function') {
+ const minMaxExt = gl.getExtension('EXT_blend_minmax');
+ if (minMaxExt && typeof minMaxExt.MAX_EXT === 'number') {
+ this.blendMaxEnum = minMaxExt.MAX_EXT;
+ }
+ }
+
gl.enable(gl.BLEND);
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
- this.isGpuAvailable = this.program !== null || this.ribbonProgram !== null;
+ this.isGpuAvailable =
+ this.program !== null || this.ribbonProgram !== null || this.texturedRibbonProgram !== null;
} catch {
this.isGpuAvailable = false;
}
@@ -1155,6 +1518,14 @@ export class WebGlBrushEngine {
return true;
}
+ public isTexturedRibbonAvailable(): boolean {
+ return this.isAvailable() && this.texturedRibbonProgram !== null && this.texturedRibbonBuffer !== null;
+ }
+
+ public supportsBlendMax(): boolean {
+ return this.isAvailable() && this.blendMaxEnum !== null;
+ }
+
private ensureDabFbo(width: number, height: number): boolean {
const gl = this.gl;
if (!gl || !('blitFramebuffer' in gl)) return false;
@@ -1189,6 +1560,64 @@ export class WebGlBrushEngine {
return true;
}
+ private ensureDualFbos(width: number, height: number): boolean {
+ const gl = this.gl;
+ if (!gl || !this.dualCombineProgram || !this.fullQuadBuffer) return false;
+ if (
+ this.dualPrimaryFbo &&
+ this.dualPrimaryTex &&
+ this.dualSecondaryFbo &&
+ this.dualSecondaryTex &&
+ this.dualFboWidth >= width &&
+ this.dualFboHeight >= height
+ ) {
+ return true;
+ }
+
+ const targetW = Math.max(width, this.dualFboWidth, 256);
+ const targetH = Math.max(height, this.dualFboHeight, 256);
+
+ if (!this.dualPrimaryFbo) this.dualPrimaryFbo = gl.createFramebuffer();
+ if (!this.dualPrimaryTex) this.dualPrimaryTex = gl.createTexture();
+ if (!this.dualSecondaryFbo) this.dualSecondaryFbo = gl.createFramebuffer();
+ if (!this.dualSecondaryTex) this.dualSecondaryTex = gl.createTexture();
+ if (
+ !this.dualPrimaryFbo ||
+ !this.dualPrimaryTex ||
+ !this.dualSecondaryFbo ||
+ !this.dualSecondaryTex
+ ) {
+ return false;
+ }
+
+ const setupTarget = (fbo: WebGLFramebuffer, tex: WebGLTexture): boolean => {
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, tex);
+ 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.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, targetW, targetH, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
+ return gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE;
+ };
+
+ const ok1 = setupTarget(this.dualPrimaryFbo, this.dualPrimaryTex);
+ const ok2 = ok1 && setupTarget(this.dualSecondaryFbo, this.dualSecondaryTex);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+
+ if (!ok2) {
+ this.dualFboWidth = 0;
+ this.dualFboHeight = 0;
+ return false;
+ }
+ this.dualFboWidth = targetW;
+ this.dualFboHeight = targetH;
+ return true;
+ }
+
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;
@@ -1212,12 +1641,13 @@ export class WebGlBrushEngine {
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
- const wrap = repeatWrap ? gl.REPEAT : gl.CLAMP_TO_EDGE;
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap);
const texW = image.naturalWidth || image.width || 0;
const texH = image.naturalHeight || image.height || 0;
const isPow2 = texW > 0 && texH > 0 && (texW & (texW - 1)) === 0 && (texH & (texH - 1)) === 0;
+ const isWebGL2 = 'blitFramebuffer' in gl;
+ const wrap = repeatWrap && (isPow2 || isWebGL2) ? gl.REPEAT : gl.CLAMP_TO_EDGE;
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap);
if (!repeatWrap && isPow2 && typeof gl.generateMipmap === 'function') {
gl.generateMipmap(gl.TEXTURE_2D);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
@@ -1684,17 +2114,282 @@ export class WebGlBrushEngine {
return true;
}
- public renderDabsToContext(
+ /**
+ * Renders a CSP textured ribbon triangle mesh (`BrushRibbon = 1`) via the dedicated
+ * textured ribbon WebGL program with multi-tip atlas, dual-tone tinting, world-space
+ * paper grain modulation, and tiled chunking for arbitrarily large canvases.
+ */
+ public renderTexturedRibbonMesh(
targetCtx: CanvasRenderingContext2D,
- dabs: GpuDab[],
+ mesh: TexturedRibbonMeshInput,
settings: BrushSettings & { alphaLocked?: boolean; isBgEraser?: boolean },
- tool: ToolType,
- _canvasWidth: number,
- _canvasHeight: number,
- underlyingCanvas?: HTMLCanvasElement
+ primaryColor: string,
+ tool: ToolType
): boolean {
const canvas = this.canvas;
- if (!this.isAvailable() || !this.gl || !canvas || !this.program || dabs.length === 0) {
+ const gl = this.gl;
+ if (
+ !this.isTexturedRibbonAvailable() ||
+ !gl ||
+ !canvas ||
+ !this.texturedRibbonProgram ||
+ !this.texturedRibbonBuffer ||
+ mesh.vertexCount < 3
+ ) {
+ return false;
+ }
+
+ const pad = 2;
+ const fullDirtyX = Math.floor(mesh.bounds.minX - pad);
+ const fullDirtyY = Math.floor(mesh.bounds.minY - pad);
+ const fullDirtyMaxX = Math.ceil(mesh.bounds.maxX + pad);
+ const fullDirtyMaxY = Math.ceil(mesh.bounds.maxY + pad);
+ const totalW = Math.max(0, fullDirtyMaxX - fullDirtyX);
+ const totalH = Math.max(0, fullDirtyMaxY - fullDirtyY);
+ if (totalW <= 0 || totalH <= 0) return false;
+
+ const chunkWMax = Math.min(MAX_TILE_CHUNK, totalW);
+ const chunkHMax = Math.min(MAX_TILE_CHUNK, totalH);
+ if (canvas.width < chunkWMax || canvas.height < chunkHMax) {
+ canvas.width = Math.max(canvas.width, chunkWMax, 512);
+ canvas.height = Math.max(canvas.height, chunkHMax, 512);
+ }
+
+ const useOffscreenFbo = this.ensureDabFbo(canvas.width, canvas.height);
+
+ const isTransparentInk = Boolean(settings.isTransparentInk);
+ const isBgEraser = Boolean(settings.isBgEraser);
+ const isEraser = (tool === 'eraser' || isTransparentInk) && !isBgEraser;
+ const isAlphaLocked = Boolean(settings.alphaLocked);
+ const aaMode = Math.max(0, Math.min(3, Math.round(settings.antiAlias ?? 2)));
+
+ const primRgb = this.parseColor(isBgEraser ? '#ffffff' : primaryColor);
+ const secRgb = this.parseColor(settings.secondaryColor ?? '#ffffff');
+
+ gl.useProgram(this.texturedRibbonProgram);
+ gl.blendEquation(gl.FUNC_ADD);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+
+ gl.uniform3f(this.uTexRibPrimaryColorLoc, primRgb.r, primRgb.g, primRgb.b);
+ gl.uniform3f(this.uTexRibSecondaryColorLoc, secRgb.r, secRgb.g, secRgb.b);
+ gl.uniform1i(this.uTexRibAntiAliasLoc, aaMode);
+ gl.uniform1i(this.uTexRibIsEraserLoc, isEraser ? 1 : 0);
+ gl.uniform1i(this.uTexRibIsBgEraserLoc, isBgEraser ? 1 : 0);
+
+ // Bind tip texture or multi-tip atlas
+ let tipTex: WebGLTexture | null = null;
+ let atlasCols = 1;
+ let atlasRows = 1;
+ if (settings.subTipImages && settings.subTipImages.length > 1) {
+ const atlas = this.getOrCreateMultiTipAtlas(settings.subTipImages);
+ if (atlas) {
+ tipTex = atlas.tex;
+ atlasCols = atlas.cols;
+ atlasRows = atlas.rows;
+ }
+ }
+ if (!tipTex && settings.customTipImage) {
+ tipTex = this.getOrCreateTipTexture(settings.customTipImage, false);
+ }
+ const isColorTip = Boolean(settings.isColorTip || settings.subTips?.[0]?.isColor);
+ const isDualToneTip = !isColorTip && Boolean(settings.isDualToneTip || settings.subTips?.[0]?.isDualToneTip);
+
+ gl.uniform2f(this.uTexRibTipAtlasGridLoc, atlasCols, atlasRows);
+ if (tipTex) {
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, tipTex);
+ if (aaMode === 0) {
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
+ } else {
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ }
+ gl.uniform1i(this.uTexRibTipTextureLoc, 0);
+ gl.uniform1i(this.uTexRibHasTipTextureLoc, 1);
+ gl.uniform1i(this.uTexRibIsColorTipLoc, isColorTip ? 1 : 0);
+ gl.uniform1i(this.uTexRibIsDualToneTipLoc, isDualToneTip ? 1 : 0);
+ } else {
+ gl.uniform1i(this.uTexRibHasTipTextureLoc, 0);
+ gl.uniform1i(this.uTexRibIsColorTipLoc, 0);
+ gl.uniform1i(this.uTexRibIsDualToneTipLoc, 0);
+ }
+
+ // Paper texture uniforms
+ const paperDensity = Math.max(0, Math.min(1, settings.grain ?? settings.textureDensity ?? 0));
+ gl.uniform1f(this.uTexRibPaperGrainLoc, paperDensity);
+ gl.uniform1f(this.uTexRibGrainScaleLoc, settings.paperTextureScale ?? 1.0);
+ gl.uniform1f(this.uTexRibGrainRotateRadLoc, ((settings.paperTextureRotate ?? 0) * Math.PI) / 180);
+
+ const pMode = paperTextureModeToIndex(settings.paperTextureMode);
+ gl.uniform1i(this.uTexRibPaperModeLoc, pMode);
+ gl.uniform1f(this.uTexRibPaperBrightnessLoc, (settings.paperTextureBrightness ?? 0) / 100.0);
+ gl.uniform1f(this.uTexRibPaperContrastLoc, (settings.paperTextureContrast ?? 0) / 100.0);
+ gl.uniform1i(this.uTexRibPaperInvertLoc, settings.paperTextureInverted ? 1 : 0);
+ const preserveDensity =
+ settings.paperTextureApplyEachPlot !== undefined && !settings.grainPenetrationSensor?.usePressure;
+ gl.uniform1i(this.uTexRibPaperPreserveDensityLoc, preserveDensity ? 1 : 0);
+ gl.uniform1i(this.uTexRibPaperEmphasizeDensityLoc, settings.paperTextureEmphasizeDensity ? 1 : 0);
+
+ if (paperDensity > 0.005) {
+ if (!this.builtinPaperTexture && WebGlBrushEngine.builtinGrainTable) {
+ this.uploadBuiltinPaperTexture(gl);
+ }
+ let paperTex: WebGLTexture | null = null;
+ 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 || paperW;
+ paperH = settings.paperTextureImage.naturalHeight || settings.paperTextureImage.height || paperH;
+ } else if (settings.surfaceTextureId) {
+ paperTex = this.getOrCreateSurfaceTexture(settings.surfaceTextureId);
+ paperW = SURFACE_TEXTURE_SIZE;
+ paperH = SURFACE_TEXTURE_SIZE;
+ } else {
+ paperTex = this.builtinPaperTexture;
+ }
+ if (paperTex) {
+ gl.activeTexture(gl.TEXTURE3);
+ gl.bindTexture(gl.TEXTURE_2D, paperTex);
+ gl.uniform1i(this.uTexRibPaperTextureLoc, 3);
+ gl.uniform1i(this.uTexRibHasPaperTexLoc, 1);
+ gl.uniform2f(this.uTexRibPaperTexSizeLoc, paperW, paperH);
+ } else {
+ gl.uniform1i(this.uTexRibHasPaperTexLoc, 0);
+ }
+ } else {
+ gl.uniform1i(this.uTexRibHasPaperTexLoc, 0);
+ }
+
+ // Upload triangle mesh vertices
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.texturedRibbonBuffer);
+ gl.bufferData(
+ gl.ARRAY_BUFFER,
+ mesh.vertices.subarray(0, mesh.vertexCount * RIBBON_VERTEX_STRIDE),
+ gl.DYNAMIC_DRAW
+ );
+
+ const byteStride = RIBBON_VERTEX_STRIDE * 4;
+ if (this.aTexRibPosLoc >= 0) {
+ gl.enableVertexAttribArray(this.aTexRibPosLoc);
+ gl.vertexAttribPointer(this.aTexRibPosLoc, 2, gl.FLOAT, false, byteStride, 0);
+ }
+ if (this.aTexRibUvLoc >= 0) {
+ gl.enableVertexAttribArray(this.aTexRibUvLoc);
+ gl.vertexAttribPointer(this.aTexRibUvLoc, 2, gl.FLOAT, false, byteStride, 2 * 4);
+ }
+ if (this.aTexRibAlphaLoc >= 0) {
+ gl.enableVertexAttribArray(this.aTexRibAlphaLoc);
+ gl.vertexAttribPointer(this.aTexRibAlphaLoc, 1, gl.FLOAT, false, byteStride, 4 * 4);
+ }
+ if (this.aTexRibPressureLoc >= 0) {
+ gl.enableVertexAttribArray(this.aTexRibPressureLoc);
+ gl.vertexAttribPointer(this.aTexRibPressureLoc, 1, gl.FLOAT, false, byteStride, 5 * 4);
+ }
+ if (this.aTexRibTipIndexLoc >= 0) {
+ gl.enableVertexAttribArray(this.aTexRibTipIndexLoc);
+ gl.vertexAttribPointer(this.aTexRibTipIndexLoc, 1, gl.FLOAT, false, byteStride, 6 * 4);
+ }
+ if (this.aTexRibEdgeInfoLoc >= 0) {
+ gl.enableVertexAttribArray(this.aTexRibEdgeInfoLoc);
+ gl.vertexAttribPointer(this.aTexRibEdgeInfoLoc, 2, gl.FLOAT, false, byteStride, 7 * 4);
+ }
+
+ const compositeOp: GlobalCompositeOperation = isBgEraser
+ ? 'source-over'
+ : isEraser
+ ? 'destination-out'
+ : isAlphaLocked
+ ? 'source-atop'
+ : 'source-over';
+
+ targetCtx.save();
+ targetCtx.globalCompositeOperation = compositeOp;
+ targetCtx.globalAlpha = Math.max(0, Math.min(1, settings.opacity ?? 1.0));
+ if (aaMode === 0) {
+ targetCtx.imageSmoothingEnabled = false;
+ }
+
+ const chunkCols = Math.ceil(totalW / MAX_TILE_CHUNK);
+ const chunkRows = Math.ceil(totalH / MAX_TILE_CHUNK);
+
+ for (let row = 0; row < chunkRows; row++) {
+ const cy = fullDirtyY + row * MAX_TILE_CHUNK;
+ const dh = Math.min(MAX_TILE_CHUNK, fullDirtyMaxY - cy);
+ if (dh <= 0) continue;
+ for (let col = 0; col < chunkCols; col++) {
+ const cx = fullDirtyX + col * MAX_TILE_CHUNK;
+ const dw = Math.min(MAX_TILE_CHUNK, fullDirtyMaxX - cx);
+ if (dw <= 0) continue;
+
+ const viewY = Math.max(0, canvas.height - dh);
+
+ if (useOffscreenFbo && this.dabFbo) {
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.dabFbo);
+ }
+
+ gl.viewport(0, viewY, dw, dh);
+ if (typeof gl.scissor === 'function') {
+ gl.enable(gl.SCISSOR_TEST);
+ gl.scissor(0, viewY, dw, dh);
+ }
+ gl.clearColor(0, 0, 0, 0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+
+ gl.uniform2f(this.uTexRibCanvasResolutionLoc, dw, dh);
+ if (this.uTexRibDirtyOffsetLoc) {
+ gl.uniform2f(this.uTexRibDirtyOffsetLoc, cx, cy);
+ }
+
+ gl.drawArrays(gl.TRIANGLES, 0, mesh.vertexCount);
+
+ if (typeof gl.scissor === 'function') {
+ gl.disable(gl.SCISSOR_TEST);
+ }
+
+ if (useOffscreenFbo && this.dabFbo) {
+ 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.bindFramebuffer(gl2.FRAMEBUFFER, null);
+ }
+
+ targetCtx.drawImage(canvas, 0, 0, dw, dh, cx, cy, dw, dh);
+ }
+ }
+
+ targetCtx.restore();
+
+ if (this.aTexRibPosLoc >= 0) gl.disableVertexAttribArray(this.aTexRibPosLoc);
+ if (this.aTexRibUvLoc >= 0) gl.disableVertexAttribArray(this.aTexRibUvLoc);
+ if (this.aTexRibAlphaLoc >= 0) gl.disableVertexAttribArray(this.aTexRibAlphaLoc);
+ if (this.aTexRibPressureLoc >= 0) gl.disableVertexAttribArray(this.aTexRibPressureLoc);
+ if (this.aTexRibTipIndexLoc >= 0) gl.disableVertexAttribArray(this.aTexRibTipIndexLoc);
+ if (this.aTexRibEdgeInfoLoc >= 0) gl.disableVertexAttribArray(this.aTexRibEdgeInfoLoc);
+
+ if (tipTex && aaMode === 0) {
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, tipTex);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ }
+
+ return true;
+ }
+
+ public renderDabsToContext(
+ targetCtx: CanvasRenderingContext2D,
+ dabs: GpuDab[],
+ settings: BrushSettings & { alphaLocked?: boolean; isBgEraser?: boolean },
+ tool: ToolType,
+ _canvasWidth: number,
+ _canvasHeight: number,
+ underlyingCanvas?: HTMLCanvasElement
+ ): boolean {
+ const canvas = this.canvas;
+ if (!this.isAvailable() || !this.gl || !canvas || !this.program || dabs.length === 0) {
return false;
}
@@ -1767,7 +2462,7 @@ export class WebGlBrushEngine {
arr[offset + 5] = d.r;
arr[offset + 6] = d.g;
arr[offset + 7] = d.b;
- arr[offset + 8] = 1.0;
+ arr[offset + 8] = d.grainDensity !== undefined ? d.grainDensity : -1.0;
arr[offset + 9] = effAlpha;
arr[offset + 10] = d.pressure;
arr[offset + 11] = d.strokeDist;
@@ -1782,8 +2477,25 @@ export class WebGlBrushEngine {
}
gl.useProgram(this.program);
- gl.blendEquation(gl.FUNC_ADD);
- gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ const isColorTip = Boolean(settings.isColorTip || (settings.subTips && settings.subTips[0]?.isColor));
+ const isDualToneTip = !isColorTip && Boolean(settings.isDualToneTip || (settings.subTips && settings.subTips[0]?.isDualToneTip));
+ const useMaxBlend =
+ this.blendMaxEnum !== null &&
+ !isEraser &&
+ !isBgEraser &&
+ !settings.colorMixing &&
+ !isColorTip &&
+ !isDualToneTip &&
+ !settings.dynamics?.colorJitterEnabled &&
+ (settings.blendTipsMode === 'compare' ||
+ (settings.paperTextureApplyEachPlot === false && Boolean(settings.opacitySensor?.usePressure)));
+ if (useMaxBlend && this.blendMaxEnum !== null) {
+ gl.blendEquation(this.blendMaxEnum);
+ gl.blendFunc(gl.ONE, gl.ONE);
+ } else {
+ gl.blendEquation(gl.FUNC_ADD);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ }
if (this.uDocResolutionLoc) {
const docW = underlyingCanvas ? underlyingCanvas.width : Math.max(1, _canvasWidth);
@@ -1821,24 +2533,24 @@ export class WebGlBrushEngine {
if (this.uDryBrushLoc) gl.uniform1f(this.uDryBrushLoc, dryBrush);
if (this.uPaintLoadLoc) gl.uniform1f(this.uPaintLoadLoc, paintLoad);
- const pMode =
- settings.paperTextureMode === 'multiply'
- ? 1
- : settings.paperTextureMode === 'compare'
- ? 2
- : settings.paperTextureMode === 'overlay'
- ? 3
- : settings.paperTextureMode === 'outline'
- ? 4
- : 0;
+ const pMode = paperTextureModeToIndex(settings.paperTextureMode);
gl.uniform1i(this.uPaperModeLoc, pMode);
gl.uniform1f(this.uPaperBrightnessLoc, (settings.paperTextureBrightness ?? 0) / 100.0);
gl.uniform1f(this.uPaperContrastLoc, (settings.paperTextureContrast ?? 0) / 100.0);
gl.uniform1i(this.uPaperInvertLoc, settings.paperTextureInverted ? 1 : 0);
+ const preserveDensity =
+ Boolean(settings.textureDensitySensor) ||
+ (settings.paperTextureApplyEachPlot !== undefined && !settings.grainPenetrationSensor?.usePressure);
+ if (this.uPaperPreserveDensityLoc) {
+ gl.uniform1i(this.uPaperPreserveDensityLoc, preserveDensity ? 1 : 0);
+ }
+ if (this.uPaperEmphasizeDensityLoc) {
+ gl.uniform1i(this.uPaperEmphasizeDensityLoc, settings.paperTextureEmphasizeDensity ? 1 : 0);
+ }
gl.uniform1i(this.uIsEraserLoc, isEraser ? 1 : 0);
gl.uniform1i(this.uIsBgEraserLoc, isBgEraser ? 1 : 0);
- if (paperDensity > 0.001 || dryBrush > 0.001) {
+ if (paperDensity > 0.001 || dryBrush > 0.001 || Boolean(settings.textureDensitySensor)) {
if (!this.builtinPaperTexture && WebGlBrushEngine.builtinGrainTable) {
this.uploadBuiltinPaperTexture(gl);
}
@@ -1883,7 +2595,10 @@ export class WebGlBrushEngine {
if (!tipTex && settings.customTipImage) {
tipTex = this.getOrCreateTipTexture(settings.customTipImage, false);
}
- const isColorTip = Boolean(settings.isColorTip || (settings.subTips && settings.subTips[0]?.isColor));
+ const secRgb = this.parseColor(settings.secondaryColor ?? '#ffffff');
+ if (this.uSecondaryColorLoc) {
+ gl.uniform3f(this.uSecondaryColorLoc, secRgb.r, secRgb.g, secRgb.b);
+ }
if (this.uTipAtlasGridLoc) {
gl.uniform2f(this.uTipAtlasGridLoc, atlasCols, atlasRows);
}
@@ -1893,36 +2608,15 @@ export class WebGlBrushEngine {
gl.uniform1i(this.uTipTextureLoc, 0);
gl.uniform1i(this.uHasTipTextureLoc, 1);
gl.uniform1i(this.uIsColorTipLoc, isColorTip ? 1 : 0);
+ if (this.uIsDualToneTipLoc) {
+ gl.uniform1i(this.uIsDualToneTipLoc, isDualToneTip ? 1 : 0);
+ }
} else {
gl.uniform1i(this.uHasTipTextureLoc, 0);
gl.uniform1i(this.uIsColorTipLoc, 0);
- }
-
- let dualTipTex: WebGLTexture | null = null;
- if (settings.dualBrush && settings.dualTipImage) {
- dualTipTex = this.getOrCreateTipTexture(settings.dualTipImage, false);
- }
- if (dualTipTex) {
- gl.activeTexture(gl.TEXTURE2);
- gl.bindTexture(gl.TEXTURE_2D, dualTipTex);
- gl.uniform1i(this.uDualTipTextureLoc, 2);
- gl.uniform1i(this.uHasDualTipTextureLoc, 1);
- const dualMode =
- settings.dualBrushCompositeMode === 'subtract'
- ? 1
- : settings.dualBrushCompositeMode === 'darken'
- ? 2
- : settings.dualBrushCompositeMode === 'overlay'
- ? 3
- : settings.dualBrushCompositeMode === 'screen'
- ? 4
- : 0;
- gl.uniform1i(this.uDualBlendModeLoc, dualMode);
- if (this.uDualScaleLoc) gl.uniform1f(this.uDualScaleLoc, settings.dualScale ?? 1.0);
- if (this.uDualRotRadLoc) gl.uniform1f(this.uDualRotRadLoc, ((settings.dualAngle ?? 0) * Math.PI) / 180);
- if (this.uDualScatterLoc) gl.uniform1f(this.uDualScatterLoc, settings.dualScatter ?? 0.0);
- } else {
- gl.uniform1i(this.uHasDualTipTextureLoc, 0);
+ if (this.uIsDualToneTipLoc) {
+ gl.uniform1i(this.uIsDualToneTipLoc, 0);
+ }
}
const enableColorMix = Boolean(settings.colorMixing) && underlyingCanvas !== undefined;
@@ -1932,6 +2626,14 @@ export class WebGlBrushEngine {
const pStr = settings.perceptualMixing === false ? 0.0 : (settings.naturalPaint?.pigmentMixingStrength ?? 1.0);
gl.uniform1f(this.uPigmentStrengthLoc, Math.max(0, Math.min(1, pStr)));
}
+ if (this.uPigmentLutLoc) {
+ const lutTex = getPigmentLutTexture(gl);
+ if (lutTex) {
+ gl.activeTexture(gl.TEXTURE2);
+ gl.bindTexture(gl.TEXTURE_2D, lutTex);
+ gl.uniform1i(this.uPigmentLutLoc, 2);
+ }
+ }
if (enableColorMix && underlyingCanvas) {
const canvasTex = this.uploadCanvasTexture(underlyingCanvas, {
@@ -2113,7 +2815,7 @@ export class WebGlBrushEngine {
gl.vertexAttrib2f(this.aCenterLoc, arr[offset], arr[offset + 1]);
gl.vertexAttrib2f(this.aSizeLoc, arr[offset + 2], arr[offset + 3]);
gl.vertexAttrib1f(this.aAngleLoc, arr[offset + 4]);
- gl.vertexAttrib4f(this.aColorLoc, arr[offset + 5], arr[offset + 6], arr[offset + 7], 1.0);
+ gl.vertexAttrib4f(this.aColorLoc, arr[offset + 5], arr[offset + 6], arr[offset + 7], arr[offset + 8]);
gl.vertexAttrib1f(this.aAlphaLoc, arr[offset + 9]);
gl.vertexAttrib1f(this.aPressureLoc, arr[offset + 10]);
gl.vertexAttrib1f(this.aStrokeDistLoc, arr[offset + 11]);
@@ -2170,6 +2872,614 @@ export class WebGlBrushEngine {
gl.disableVertexAttribArray(this.aStrokeDistLoc);
}
+ if (useMaxBlend) {
+ gl.blendEquation(gl.FUNC_ADD);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ }
+
+ return true;
+ }
+
+ private packDabsIntoFloatArray(
+ dabs: GpuDab[],
+ aaMode: number,
+ existing: Float32Array
+ ): { array: Float32Array; floatCount: number } {
+ const stride = 15;
+ const requiredFloats = dabs.length * stride;
+ let arr = existing;
+ if (arr.length < requiredFloats) {
+ arr = new Float32Array(Math.max(requiredFloats, arr.length * 2));
+ }
+ const minRenderDim = aaMode === 0 ? 1.0 : 0.75;
+ for (let i = 0; i < dabs.length; i++) {
+ const d = dabs[i];
+ 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] = 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] = d.grainDensity !== undefined ? d.grainDensity : -1.0;
+ arr[offset + 9] = effAlpha;
+ arr[offset + 10] = d.pressure;
+ arr[offset + 11] = d.strokeDist;
+ arr[offset + 12] = d.flipX ?? 1.0;
+ arr[offset + 13] = d.flipY ?? 1.0;
+ arr[offset + 14] = d.tipIndex ?? 0.0;
+ }
+ return { array: arr, floatCount: requiredFloats };
+ }
+
+ private configureDabPassUniforms(
+ gl: WebGLRenderingContext | WebGL2RenderingContext,
+ dabs: GpuDab[],
+ settings: BrushSettings & { alphaLocked?: boolean; isBgEraser?: boolean },
+ isEraser: boolean,
+ isBgEraser: boolean,
+ canvasWidth: number,
+ canvasHeight: number,
+ fullDirtyX: number,
+ fullDirtyY: number,
+ totalW: number,
+ totalH: number,
+ underlyingCanvas?: HTMLCanvasElement
+ ): boolean {
+ const aaMode = settings.antiAlias ?? 2;
+ const isColorTip = Boolean(settings.isColorTip || (settings.subTips && settings.subTips[0]?.isColor));
+ const isDualToneTip = !isColorTip && Boolean(settings.isDualToneTip || (settings.subTips && settings.subTips[0]?.isDualToneTip));
+ const useMaxBlend =
+ this.blendMaxEnum !== null &&
+ !isEraser &&
+ !isBgEraser &&
+ !settings.colorMixing &&
+ !isColorTip &&
+ !isDualToneTip &&
+ !settings.dynamics?.colorJitterEnabled &&
+ (settings.blendTipsMode === 'compare' ||
+ (settings.paperTextureApplyEachPlot === false && Boolean(settings.opacitySensor?.usePressure)));
+ gl.enable(gl.BLEND);
+ if (useMaxBlend && this.blendMaxEnum !== null) {
+ gl.blendEquation(this.blendMaxEnum);
+ gl.blendFunc(gl.ONE, gl.ONE);
+ } else {
+ gl.blendEquation(gl.FUNC_ADD);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ }
+
+ if (this.uDocResolutionLoc) {
+ const docW = underlyingCanvas ? underlyingCanvas.width : Math.max(1, canvasWidth);
+ const docH = underlyingCanvas ? underlyingCanvas.height : Math.max(1, canvasHeight);
+ gl.uniform2f(this.uDocResolutionLoc, docW, docH);
+ }
+
+ gl.uniform1i(this.uAntiAliasLoc, aaMode);
+ gl.uniform1f(this.uHardnessLoc, settings.hardness ?? 1.0);
+ gl.uniform1f(this.uWetEdgeLoc, settings.wetEdge ?? 0.0);
+
+ const paperDensity = settings.grain ?? (settings.textureDensity ?? 0.0);
+ const dryBrush = settings.naturalPaint?.dryBrush ?? 0.0;
+ const paintLoad = settings.naturalPaint?.paintLoad ?? 1.0;
+ gl.uniform1f(this.uPaperGrainLoc, paperDensity);
+ gl.uniform1f(this.uGrainScaleLoc, settings.paperTextureScale ?? 1.0);
+ gl.uniform1f(this.uGrainRotateRadLoc, ((settings.paperTextureRotate ?? 0) * Math.PI) / 180);
+ const gmMode =
+ settings.grainMappingMode === 'brush-aligned'
+ ? 1
+ : settings.grainMappingMode === 'stroke-flow'
+ ? 2
+ : settings.grainMappingMode === 'random-per-stroke'
+ ? 3
+ : 0;
+ if (this.uGrainMappingModeLoc) gl.uniform1i(this.uGrainMappingModeLoc, gmMode);
+ if (this.uGrainRandomOffsetLoc) {
+ const seed = dabs.length > 0 ? Math.abs(Math.sin(dabs[0].x * 12.9898 + dabs[0].y * 78.233)) : 0;
+ gl.uniform2f(this.uGrainRandomOffsetLoc, seed * 256, ((seed * 397) % 1) * 256);
+ }
+ if (this.uGrainRandomRotLoc) {
+ const seedR = dabs.length > 0 ? Math.abs(Math.cos(dabs[0].x * 39.346 + dabs[0].y * 11.135)) * Math.PI * 2 : 0;
+ gl.uniform1f(this.uGrainRandomRotLoc, seedR);
+ }
+ if (this.uDryBrushLoc) gl.uniform1f(this.uDryBrushLoc, dryBrush);
+ if (this.uPaintLoadLoc) gl.uniform1f(this.uPaintLoadLoc, paintLoad);
+
+ const pMode = paperTextureModeToIndex(settings.paperTextureMode);
+ gl.uniform1i(this.uPaperModeLoc, pMode);
+ gl.uniform1f(this.uPaperBrightnessLoc, (settings.paperTextureBrightness ?? 0) / 100.0);
+ gl.uniform1f(this.uPaperContrastLoc, (settings.paperTextureContrast ?? 0) / 100.0);
+ gl.uniform1i(this.uPaperInvertLoc, settings.paperTextureInverted ? 1 : 0);
+ const preserveDensity =
+ Boolean(settings.textureDensitySensor) ||
+ (settings.paperTextureApplyEachPlot !== undefined && !settings.grainPenetrationSensor?.usePressure);
+ if (this.uPaperPreserveDensityLoc) {
+ gl.uniform1i(this.uPaperPreserveDensityLoc, preserveDensity ? 1 : 0);
+ }
+ if (this.uPaperEmphasizeDensityLoc) {
+ gl.uniform1i(this.uPaperEmphasizeDensityLoc, settings.paperTextureEmphasizeDensity ? 1 : 0);
+ }
+ gl.uniform1i(this.uIsEraserLoc, isEraser ? 1 : 0);
+ gl.uniform1i(this.uIsBgEraserLoc, isBgEraser ? 1 : 0);
+
+ if (paperDensity > 0.001 || dryBrush > 0.001 || Boolean(settings.textureDensitySensor)) {
+ if (!this.builtinPaperTexture && WebGlBrushEngine.builtinGrainTable) {
+ this.uploadBuiltinPaperTexture(gl);
+ }
+ let paperTex: WebGLTexture | null = null;
+ 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 || paperW;
+ paperH = settings.paperTextureImage.naturalHeight || settings.paperTextureImage.height || paperH;
+ } else if (settings.surfaceTextureId) {
+ paperTex = this.getOrCreateSurfaceTexture(settings.surfaceTextureId);
+ paperW = SURFACE_TEXTURE_SIZE;
+ paperH = SURFACE_TEXTURE_SIZE;
+ } else {
+ paperTex = this.builtinPaperTexture;
+ }
+ if (paperTex) {
+ gl.activeTexture(gl.TEXTURE3);
+ gl.bindTexture(gl.TEXTURE_2D, paperTex);
+ gl.uniform1i(this.uPaperTextureLoc, 3);
+ gl.uniform1i(this.uHasPaperTexLoc, 1);
+ gl.uniform2f(this.uPaperTexSizeLoc, paperW, paperH);
+ } else {
+ gl.uniform1i(this.uHasPaperTexLoc, 0);
+ }
+ } else {
+ gl.uniform1i(this.uHasPaperTexLoc, 0);
+ }
+
+ let tipTex: WebGLTexture | null = null;
+ let atlasCols = 1;
+ let atlasRows = 1;
+ if (settings.subTipImages && settings.subTipImages.length > 1) {
+ const atlas = this.getOrCreateMultiTipAtlas(settings.subTipImages);
+ if (atlas) {
+ tipTex = atlas.tex;
+ atlasCols = atlas.cols;
+ atlasRows = atlas.rows;
+ }
+ }
+ if (!tipTex && settings.customTipImage) {
+ tipTex = this.getOrCreateTipTexture(settings.customTipImage, false);
+ }
+ const secRgb = this.parseColor(settings.secondaryColor ?? '#ffffff');
+ if (this.uSecondaryColorLoc) {
+ gl.uniform3f(this.uSecondaryColorLoc, secRgb.r, secRgb.g, secRgb.b);
+ }
+ if (this.uTipAtlasGridLoc) {
+ gl.uniform2f(this.uTipAtlasGridLoc, atlasCols, atlasRows);
+ }
+ if (tipTex) {
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, tipTex);
+ gl.uniform1i(this.uTipTextureLoc, 0);
+ gl.uniform1i(this.uHasTipTextureLoc, 1);
+ gl.uniform1i(this.uIsColorTipLoc, isColorTip ? 1 : 0);
+ if (this.uIsDualToneTipLoc) {
+ gl.uniform1i(this.uIsDualToneTipLoc, isDualToneTip ? 1 : 0);
+ }
+ } else {
+ gl.uniform1i(this.uHasTipTextureLoc, 0);
+ gl.uniform1i(this.uIsColorTipLoc, 0);
+ if (this.uIsDualToneTipLoc) {
+ gl.uniform1i(this.uIsDualToneTipLoc, 0);
+ }
+ }
+
+ const enableColorMix = Boolean(settings.colorMixing) && underlyingCanvas !== undefined;
+ gl.uniform1i(this.uColorMixingLoc, enableColorMix ? 1 : 0);
+ gl.uniform1i(this.uPerceptualMixingLoc, settings.perceptualMixing !== false ? 1 : 0);
+ if (this.uPigmentStrengthLoc) {
+ const pStr = settings.perceptualMixing === false ? 0.0 : (settings.naturalPaint?.pigmentMixingStrength ?? 1.0);
+ gl.uniform1f(this.uPigmentStrengthLoc, Math.max(0, Math.min(1, pStr)));
+ }
+ if (this.uPigmentLutLoc) {
+ const lutTex = getPigmentLutTexture(gl);
+ if (lutTex) {
+ gl.activeTexture(gl.TEXTURE2);
+ gl.bindTexture(gl.TEXTURE_2D, lutTex);
+ gl.uniform1i(this.uPigmentLutLoc, 2);
+ }
+ }
+
+ if (enableColorMix && underlyingCanvas) {
+ const canvasTex = this.uploadCanvasTexture(underlyingCanvas, {
+ x: fullDirtyX,
+ y: fullDirtyY,
+ width: totalW,
+ height: totalH,
+ });
+ if (canvasTex) {
+ gl.activeTexture(gl.TEXTURE1);
+ gl.bindTexture(gl.TEXTURE_2D, canvasTex);
+ gl.uniform1i(this.uCanvasTextureLoc, 1);
+ gl.uniform1i(this.uHasCanvasTextureLoc, 1);
+ gl.uniform1f(this.uAmountOfPaintLoc, settings.amountOfPaint ?? 0.7);
+ gl.uniform1f(this.uDensityOfPaintLoc, settings.densityOfPaint ?? 0.8);
+ gl.uniform1f(this.uColorStretchLoc, settings.colorStretch ?? 0.6);
+ } else {
+ gl.uniform1i(this.uHasCanvasTextureLoc, 0);
+ }
+ } else {
+ gl.uniform1i(this.uHasCanvasTextureLoc, 0);
+ }
+
+ return useMaxBlend;
+ }
+
+ private bindDabAttributes(
+ gl: WebGLRenderingContext | WebGL2RenderingContext,
+ instanceBuf: WebGLBuffer | null,
+ useInstanced: boolean
+ ): void {
+ const stride = 15;
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.quadVertexBuffer);
+ gl.enableVertexAttribArray(this.aQuadVertexLoc);
+ gl.vertexAttribPointer(this.aQuadVertexLoc, 2, gl.FLOAT, false, 0, 0);
+
+ if (useInstanced && this.extInstanced && instanceBuf) {
+ gl.bindBuffer(gl.ARRAY_BUFFER, instanceBuf);
+ const byteStride = stride * 4;
+
+ gl.enableVertexAttribArray(this.aCenterLoc);
+ gl.vertexAttribPointer(this.aCenterLoc, 2, gl.FLOAT, false, byteStride, 0);
+ this.extInstanced.vertexAttribDivisor(this.aCenterLoc, 1);
+
+ gl.enableVertexAttribArray(this.aSizeLoc);
+ gl.vertexAttribPointer(this.aSizeLoc, 2, gl.FLOAT, false, byteStride, 2 * 4);
+ this.extInstanced.vertexAttribDivisor(this.aSizeLoc, 1);
+
+ gl.enableVertexAttribArray(this.aAngleLoc);
+ gl.vertexAttribPointer(this.aAngleLoc, 1, gl.FLOAT, false, byteStride, 4 * 4);
+ this.extInstanced.vertexAttribDivisor(this.aAngleLoc, 1);
+
+ gl.enableVertexAttribArray(this.aColorLoc);
+ gl.vertexAttribPointer(this.aColorLoc, 4, gl.FLOAT, false, byteStride, 5 * 4);
+ this.extInstanced.vertexAttribDivisor(this.aColorLoc, 1);
+
+ gl.enableVertexAttribArray(this.aAlphaLoc);
+ gl.vertexAttribPointer(this.aAlphaLoc, 1, gl.FLOAT, false, byteStride, 9 * 4);
+ this.extInstanced.vertexAttribDivisor(this.aAlphaLoc, 1);
+
+ gl.enableVertexAttribArray(this.aPressureLoc);
+ gl.vertexAttribPointer(this.aPressureLoc, 1, gl.FLOAT, false, byteStride, 10 * 4);
+ this.extInstanced.vertexAttribDivisor(this.aPressureLoc, 1);
+
+ gl.enableVertexAttribArray(this.aStrokeDistLoc);
+ gl.vertexAttribPointer(this.aStrokeDistLoc, 1, gl.FLOAT, false, byteStride, 11 * 4);
+ this.extInstanced.vertexAttribDivisor(this.aStrokeDistLoc, 1);
+
+ if (this.aFlipLoc >= 0) {
+ gl.enableVertexAttribArray(this.aFlipLoc);
+ gl.vertexAttribPointer(this.aFlipLoc, 2, gl.FLOAT, false, byteStride, 12 * 4);
+ this.extInstanced.vertexAttribDivisor(this.aFlipLoc, 1);
+ }
+ if (this.aTipIndexLoc >= 0) {
+ gl.enableVertexAttribArray(this.aTipIndexLoc);
+ gl.vertexAttribPointer(this.aTipIndexLoc, 1, gl.FLOAT, false, byteStride, 14 * 4);
+ this.extInstanced.vertexAttribDivisor(this.aTipIndexLoc, 1);
+ }
+ }
+ }
+
+ private unbindDabAttributes(
+ gl: WebGLRenderingContext | WebGL2RenderingContext,
+ useInstanced: boolean
+ ): void {
+ gl.disableVertexAttribArray(this.aQuadVertexLoc);
+ if (useInstanced && this.extInstanced) {
+ this.extInstanced.vertexAttribDivisor(this.aCenterLoc, 0);
+ this.extInstanced.vertexAttribDivisor(this.aSizeLoc, 0);
+ this.extInstanced.vertexAttribDivisor(this.aAngleLoc, 0);
+ this.extInstanced.vertexAttribDivisor(this.aColorLoc, 0);
+ this.extInstanced.vertexAttribDivisor(this.aAlphaLoc, 0);
+ this.extInstanced.vertexAttribDivisor(this.aPressureLoc, 0);
+ this.extInstanced.vertexAttribDivisor(this.aStrokeDistLoc, 0);
+ if (this.aFlipLoc >= 0) {
+ this.extInstanced.vertexAttribDivisor(this.aFlipLoc, 0);
+ gl.disableVertexAttribArray(this.aFlipLoc);
+ }
+ if (this.aTipIndexLoc >= 0) {
+ this.extInstanced.vertexAttribDivisor(this.aTipIndexLoc, 0);
+ gl.disableVertexAttribArray(this.aTipIndexLoc);
+ }
+ gl.disableVertexAttribArray(this.aCenterLoc);
+ gl.disableVertexAttribArray(this.aSizeLoc);
+ gl.disableVertexAttribArray(this.aAngleLoc);
+ gl.disableVertexAttribArray(this.aColorLoc);
+ gl.disableVertexAttribArray(this.aAlphaLoc);
+ gl.disableVertexAttribArray(this.aPressureLoc);
+ gl.disableVertexAttribArray(this.aStrokeDistLoc);
+ }
+ }
+
+ private drawBoundDabs(
+ gl: WebGLRenderingContext | WebGL2RenderingContext,
+ dabCount: number,
+ arr: Float32Array,
+ useInstanced: boolean
+ ): void {
+ if (dabCount <= 0) return;
+ if (useInstanced && this.extInstanced) {
+ this.extInstanced.drawArraysInstanced(gl.TRIANGLES, 0, 6, dabCount);
+ return;
+ }
+ const stride = 15;
+ for (let i = 0; i < dabCount; i++) {
+ const offset = i * stride;
+ gl.vertexAttrib2f(this.aCenterLoc, arr[offset], arr[offset + 1]);
+ gl.vertexAttrib2f(this.aSizeLoc, arr[offset + 2], arr[offset + 3]);
+ gl.vertexAttrib1f(this.aAngleLoc, arr[offset + 4]);
+ gl.vertexAttrib4f(this.aColorLoc, arr[offset + 5], arr[offset + 6], arr[offset + 7], arr[offset + 8]);
+ gl.vertexAttrib1f(this.aAlphaLoc, arr[offset + 9]);
+ gl.vertexAttrib1f(this.aPressureLoc, arr[offset + 10]);
+ gl.vertexAttrib1f(this.aStrokeDistLoc, arr[offset + 11]);
+ if (this.aFlipLoc >= 0) {
+ gl.vertexAttrib2f(this.aFlipLoc, arr[offset + 12], arr[offset + 13]);
+ }
+ if (this.aTipIndexLoc >= 0) {
+ gl.vertexAttrib1f(this.aTipIndexLoc, arr[offset + 14]);
+ }
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+ }
+ }
+
+ /**
+ * True two-pass Clip Studio Paint Dual Brush GPU renderer:
+ * - Pass 1 renders `primaryDabs` into `dualPrimaryFbo`
+ * - Pass 2 renders `secondaryDabs` into `dualSecondaryFbo`
+ * - Combine Pass executes a single fullscreen FBO shader combining primary RGBA
+ * and secondary density `a2` with `compositeMode` and composites onto `targetCtx`.
+ */
+ public renderDualBrushDabsToContext(
+ targetCtx: CanvasRenderingContext2D,
+ primaryDabs: GpuDab[],
+ primarySettings: BrushSettings & { alphaLocked?: boolean; isBgEraser?: boolean },
+ secondaryDabs: GpuDab[],
+ secondarySettings: BrushSettings,
+ compositeMode: DualBrushCompositeMode,
+ tool: ToolType,
+ canvasWidth: number,
+ canvasHeight: number,
+ underlyingCanvas?: HTMLCanvasElement
+ ): boolean {
+ const canvas = this.canvas;
+ const gl = this.gl;
+ if (
+ !this.isAvailable() ||
+ !gl ||
+ !canvas ||
+ !this.program ||
+ !this.dualCombineProgram ||
+ !this.fullQuadBuffer ||
+ primaryDabs.length === 0
+ ) {
+ return false;
+ }
+
+ const isTransparentInk = Boolean(primarySettings.isTransparentInk);
+ const isEraser = tool === 'eraser' || isTransparentInk;
+ const isBgEraser =
+ Boolean(primarySettings.isBgEraser) || (tool === 'eraser' && targetCtx.fillStyle === '#ffffff');
+ const isAlphaLocked = Boolean(primarySettings.alphaLocked);
+
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+ for (let i = 0; i < primaryDabs.length; i++) {
+ const d = primaryDabs[i];
+ const rad = Math.max(d.width, d.height) * 0.75 + 4;
+ if (d.x - rad < minX) minX = d.x - rad;
+ if (d.y - rad < minY) minY = d.y - rad;
+ if (d.x + rad > maxX) maxX = d.x + rad;
+ if (d.y + rad > maxY) maxY = d.y + rad;
+ }
+
+ const fullDirtyX = Math.floor(minX);
+ const fullDirtyY = Math.floor(minY);
+ const fullDirtyMaxX = Math.ceil(maxX);
+ const fullDirtyMaxY = Math.ceil(maxY);
+ const totalW = Math.max(0, fullDirtyMaxX - fullDirtyX);
+ const totalH = Math.max(0, fullDirtyMaxY - fullDirtyY);
+ if (totalW <= 0 || totalH <= 0) return false;
+
+ const chunkWMax = Math.min(MAX_TILE_CHUNK, totalW);
+ const chunkHMax = Math.min(MAX_TILE_CHUNK, totalH);
+ if (canvas.width < chunkWMax || canvas.height < chunkHMax) {
+ canvas.width = Math.max(canvas.width, chunkWMax, 512);
+ canvas.height = Math.max(canvas.height, chunkHMax, 512);
+ }
+
+ if (!this.ensureDualFbos(chunkWMax, chunkHMax)) {
+ return false;
+ }
+
+ const aaMode = primarySettings.antiAlias ?? 2;
+ const packedPrimary = this.packDabsIntoFloatArray(primaryDabs, aaMode, this.instanceArray);
+ this.instanceArray = packedPrimary.array;
+ if (this.instanceBuffer) {
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.instanceBuffer);
+ gl.bufferData(gl.ARRAY_BUFFER, this.instanceArray.subarray(0, packedPrimary.floatCount), gl.DYNAMIC_DRAW);
+ }
+
+ const secAaMode = secondarySettings.antiAlias ?? aaMode;
+ const packedSecondary = this.packDabsIntoFloatArray(
+ secondaryDabs,
+ secAaMode,
+ this.secondaryInstanceArray
+ );
+ this.secondaryInstanceArray = packedSecondary.array;
+ if (this.secondaryInstanceBuffer && secondaryDabs.length > 0) {
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.secondaryInstanceBuffer);
+ gl.bufferData(
+ gl.ARRAY_BUFFER,
+ this.secondaryInstanceArray.subarray(0, packedSecondary.floatCount),
+ gl.DYNAMIC_DRAW
+ );
+ }
+
+ const useInstancedPrimary = Boolean(this.extInstanced && this.instanceBuffer);
+ const useInstancedSecondary = Boolean(this.extInstanced && this.secondaryInstanceBuffer);
+ const modeIdx = dualBrushCompositeModeToIndex(compositeMode);
+
+ const compositeOp: GlobalCompositeOperation = isBgEraser
+ ? 'source-over'
+ : isEraser
+ ? 'destination-out'
+ : isAlphaLocked
+ ? 'source-atop'
+ : 'source-over';
+
+ targetCtx.save();
+ targetCtx.globalCompositeOperation = compositeOp;
+ targetCtx.globalAlpha = Math.max(0, Math.min(1, primarySettings.opacity ?? 1.0));
+ if (aaMode === 0) {
+ targetCtx.imageSmoothingEnabled = false;
+ }
+
+ const chunkCols = Math.ceil(totalW / MAX_TILE_CHUNK);
+ const chunkRows = Math.ceil(totalH / MAX_TILE_CHUNK);
+
+ for (let row = 0; row < chunkRows; row++) {
+ const cy = fullDirtyY + row * MAX_TILE_CHUNK;
+ const dh = Math.min(MAX_TILE_CHUNK, fullDirtyMaxY - cy);
+ if (dh <= 0) continue;
+ for (let col = 0; col < chunkCols; col++) {
+ const cx = fullDirtyX + col * MAX_TILE_CHUNK;
+ const dw = Math.min(MAX_TILE_CHUNK, fullDirtyMaxX - cx);
+ if (dw <= 0) continue;
+
+ // Pass 1: Primary stroke into dualPrimaryFbo at (0, 0, dw, dh)
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.dualPrimaryFbo);
+ gl.viewport(0, 0, dw, dh);
+ if (typeof gl.scissor === 'function') {
+ gl.enable(gl.SCISSOR_TEST);
+ gl.scissor(0, 0, dw, dh);
+ }
+ gl.clearColor(0, 0, 0, 0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+
+ gl.useProgram(this.program);
+ this.configureDabPassUniforms(
+ gl,
+ primaryDabs,
+ primarySettings,
+ isEraser,
+ isBgEraser,
+ canvasWidth,
+ canvasHeight,
+ fullDirtyX,
+ fullDirtyY,
+ totalW,
+ totalH,
+ underlyingCanvas
+ );
+ gl.uniform2f(this.uCanvasResolutionLoc, dw, dh);
+ if (this.uDirtyOffsetLoc) {
+ gl.uniform2f(this.uDirtyOffsetLoc, cx, cy);
+ }
+ this.bindDabAttributes(gl, this.instanceBuffer, useInstancedPrimary);
+ this.drawBoundDabs(gl, primaryDabs.length, this.instanceArray, useInstancedPrimary);
+ this.unbindDabAttributes(gl, useInstancedPrimary);
+
+ // Pass 2: Secondary stroke into dualSecondaryFbo at (0, 0, dw, dh)
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.dualSecondaryFbo);
+ gl.viewport(0, 0, dw, dh);
+ if (typeof gl.scissor === 'function') {
+ gl.scissor(0, 0, dw, dh);
+ }
+ gl.clearColor(0, 0, 0, 0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+
+ if (secondaryDabs.length > 0) {
+ gl.useProgram(this.program);
+ this.configureDabPassUniforms(
+ gl,
+ secondaryDabs,
+ secondarySettings,
+ false,
+ false,
+ canvasWidth,
+ canvasHeight,
+ fullDirtyX,
+ fullDirtyY,
+ totalW,
+ totalH,
+ undefined
+ );
+ gl.uniform2f(this.uCanvasResolutionLoc, dw, dh);
+ if (this.uDirtyOffsetLoc) {
+ gl.uniform2f(this.uDirtyOffsetLoc, cx, cy);
+ }
+ this.bindDabAttributes(gl, this.secondaryInstanceBuffer, useInstancedSecondary);
+ this.drawBoundDabs(
+ gl,
+ secondaryDabs.length,
+ this.secondaryInstanceArray,
+ useInstancedSecondary
+ );
+ this.unbindDabAttributes(gl, useInstancedSecondary);
+ }
+
+ // Combine Pass: single fullscreen quad shader combining dualPrimaryTex + dualSecondaryTex
+ const viewY = Math.max(0, canvas.height - dh);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.viewport(0, viewY, dw, dh);
+ if (typeof gl.scissor === 'function') {
+ gl.scissor(0, viewY, dw, dh);
+ }
+ gl.clearColor(0, 0, 0, 0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+
+ gl.disable(gl.BLEND);
+ gl.useProgram(this.dualCombineProgram);
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, this.dualPrimaryTex);
+ gl.uniform1i(this.uDualCombinePrimaryTexLoc, 0);
+ gl.activeTexture(gl.TEXTURE1);
+ gl.bindTexture(gl.TEXTURE_2D, this.dualSecondaryTex);
+ gl.uniform1i(this.uDualCombineSecondaryTexLoc, 1);
+ gl.uniform2f(
+ this.uDualCombineUvScaleLoc,
+ dw / Math.max(1, this.dualFboWidth),
+ dh / Math.max(1, this.dualFboHeight)
+ );
+ gl.uniform1i(this.uDualCombineModeLoc, modeIdx);
+
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.fullQuadBuffer);
+ gl.enableVertexAttribArray(this.aDualCombinePosLoc);
+ gl.vertexAttribPointer(this.aDualCombinePosLoc, 2, gl.FLOAT, false, 0, 0);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+ gl.disableVertexAttribArray(this.aDualCombinePosLoc);
+
+ if (typeof gl.scissor === 'function') {
+ gl.disable(gl.SCISSOR_TEST);
+ }
+ gl.enable(gl.BLEND);
+ gl.blendEquation(gl.FUNC_ADD);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+
+ targetCtx.drawImage(canvas, 0, 0, dw, dh, cx, cy, dw, dh);
+ }
+ }
+
+ targetCtx.restore();
return true;
}
}
diff --git a/src/hooks/drawing/brushStrokeSession/flushPendingPoints.ts b/src/hooks/drawing/brushStrokeSession/flushPendingPoints.ts
index ef5fbba..a18f3a9 100644
--- a/src/hooks/drawing/brushStrokeSession/flushPendingPoints.ts
+++ b/src/hooks/drawing/brushStrokeSession/flushPendingPoints.ts
@@ -1,8 +1,18 @@
import { Point } from '../../../types/editor';
import { calculateStrokeWidth, get2DContext } from '../../../utils/canvasUtils';
-import { canUseWebGlForBrush, flushGpuDabs } from '../../../engine/BrushEngine';
-import { isLinearPressureCurve } from '../../../utils/pressureCurve';
+import {
+ buildSecondaryBrushSettings,
+ canUseWebGlForBrush,
+ flushGpuDabs,
+ resolveDualBrushConfig,
+} from '../../../engine/BrushEngine';
+import { evaluateGlobalPressureCurve, isLinearPressureCurve } from '../../../utils/pressureCurve';
import { DraftCanvasElement, isBackgroundLayerId } from '../types';
+import {
+ syncDualBrushRegionToDraft,
+ syncStrokePaperTextureRegionToDraft,
+} from './strokeHelpers';
+import { flushLiveDualSecondaryGpuBatch } from './liveSegmentEmitter';
import {
StrokeSessionHelpers,
StrokeSessionState,
@@ -68,9 +78,12 @@ export function runFlushPendingPoints(
const hasCustomCurve =
hasCustomGlobalCurve || Boolean(bs.pressureCurve && bs.pressureCurve.length > 0);
const taperEngine = pipeline.getTaperEngine();
- const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
+ const dualCfg = state.isDualBrushStroke ? resolveDualBrushConfig(bs) : null;
+ const dualSecSize = dualCfg ? buildSecondaryBrushSettings(bs, dualCfg).settings.size : 0;
+ const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0, dualCfg?.scatter ?? 0);
+ const maxBrushDim = Math.max(bs.size || 10, dualSecSize);
const blurMargin = (1 - strokeHardness) * ((bs.size || 10) * 1.5);
- const dirtyPadExtra = Math.ceil((bs.size || 10) * (1.8 + scatterFactor * 2) + blurMargin + 24);
+ const dirtyPadExtra = Math.ceil(maxBrushDim * (1.8 + scatterFactor * 2) + blurMargin + 24);
const draftScale = draftCanvas.__draftScale ?? 1.0;
const liveAA = helpers.resolveLiveAntiAlias(bs, isMonochrome, draftScale);
@@ -91,10 +104,21 @@ export function runFlushPendingPoints(
const gpuBatch = state.frameGpuDabs;
gpuBatch.length = 0;
+ state.dualFrameSecondaryGpuDabs.length = 0;
const collabActive = Boolean(state.currentStrokeId && params.onCollabStrokeChunkRef.current);
const chunkPts: Point[] | null = collabActive ? [] : null;
let drewAnySegment = false;
+ const activeDrawCtx =
+ state.isDualBrushStroke && state.dualPrimaryCanvas
+ ? get2DContext(state.dualPrimaryCanvas) || draftCtx
+ : state.isStrokePaperTextureActive && state.rawDraftCanvas
+ ? get2DContext(state.rawDraftCanvas) || draftCtx
+ : draftCtx;
+ let frameMinX = Infinity;
+ let frameMinY = Infinity;
+ let frameMaxX = -Infinity;
+ let frameMaxY = -Infinity;
pipeline.drain({
dirtyPadExtra,
@@ -109,17 +133,39 @@ export function runFlushPendingPoints(
velocityScale = Math.max(0.65, Math.min(1.0, 1.0 - Math.max(0, speed - 0.5) * 0.12));
}
- const baseP = bs.usePressure
+ let effectiveStabP = stabPressure;
+ const isPlaceholderDown =
+ Math.abs(state.deferredStartRawPressure - 0.5) < 1e-4 ||
+ (state.deferredStartRawPressure <= 0.015 && rawPressure > 0.015);
+ if (
+ state.deferredInitialDot &&
+ state.allStrokePoints.length === 1 &&
+ (rawPressure < state.deferredStartRawPressure - 0.01 || isPlaceholderDown)
+ ) {
+ // Clear any sentinel / unpopulated WM_POINTERDOWN (0.006) / click-impulse pressure
+ // seeded on pointerdown so neither InputStabilizer nor TaperEngine's 8-sample
+ // smoother drags the opening samples of a firm or light stroke off hardware pressure.
+ pipeline.getStabilizer().resetPressureState(rawPressure, state.lastPointTime);
+ taperEngine.reset();
+ effectiveStabP = evaluateGlobalPressureCurve(rawPressure, globalCurve);
+ }
+
+ const rawBaseP = bs.usePressure
? hasCustomCurve
- ? stabPressure
- : taperEngine.mapPressure(stabPressure)
+ ? effectiveStabP
+ : taperEngine.mapPressure(effectiveStabP)
: rawPressure > 0
? 1.0
: 0;
+ // Preserve light continuous stylus contact (> 0.005) above zero collapse mid-stroke
+ const baseP =
+ bs.usePressure && rawPressure > 0.005 ? Math.max(0.015, rawBaseP) : rawBaseP;
const mappedP = bs.usePressure ? taperEngine.smoothPressure(baseP) : baseP;
+ const effectiveP =
+ bs.usePressure && rawPressure > 0.005 ? Math.max(0.015, mappedP) : mappedP;
let width = calculateStrokeWidth(
bs.size,
- mappedP,
+ effectiveP,
bs.minSizeFactor,
bs.usePressure,
pointerType,
@@ -130,7 +176,7 @@ export function runFlushPendingPoints(
if (isMonochrome && !hasTaper && width < 1.25) {
width = 1.25;
}
- out.pressure = mappedP;
+ out.pressure = effectiveP;
out.width = width;
},
onPoint: (sample) => {
@@ -145,6 +191,32 @@ export function runFlushPendingPoints(
timestamp: sample.timestamp,
isCorner: sample.isCorner,
};
+ if (state.deferredInitialDot) {
+ state.deferredInitialDot = false;
+ if (state.allStrokePoints.length === 1) {
+ const p0 = state.allStrokePoints[0];
+ const wasSentinel =
+ Math.abs(state.deferredStartRawPressure - 0.5) < 1e-4 ||
+ (state.deferredStartRawPressure <= 0.015 && pt.pressure > 0.015);
+ if (wasSentinel || pt.pressure < p0.pressure) {
+ p0.pressure = pt.pressure;
+ p0.width = pt.width;
+ const p0HadNoTilt = (p0.tiltX ?? 0) === 0 && (p0.tiltY ?? 0) === 0;
+ const ptHasTilt = (pt.tiltX ?? 0) !== 0 || (pt.tiltY ?? 0) !== 0;
+ if (p0HadNoTilt && ptHasTilt) {
+ p0.tiltX = pt.tiltX;
+ p0.tiltY = pt.tiltY;
+ }
+ pipeline.updateSeedKnotPressure(
+ pt.pressure,
+ pt.width,
+ sample.timestamp,
+ p0.tiltX,
+ p0.tiltY
+ );
+ }
+ }
+ }
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);
@@ -168,8 +240,19 @@ export function runFlushPendingPoints(
},
onSegment: (seg) => {
drewAnySegment = true;
+ const segPad = Math.ceil(
+ Math.max(seg.p0.width, seg.p3.width, maxBrushDim) * (2.2 + scatterFactor * 2) + 16
+ );
+ const sMinX = Math.min(seg.p0.x, seg.c1.x, seg.c2.x, seg.p3.x) - segPad;
+ const sMinY = Math.min(seg.p0.y, seg.c1.y, seg.c2.y, seg.p3.y) - segPad;
+ const sMaxX = Math.max(seg.p0.x, seg.c1.x, seg.c2.x, seg.p3.x) + segPad;
+ const sMaxY = Math.max(seg.p0.y, seg.c1.y, seg.c2.y, seg.p3.y) + segPad;
+ if (sMinX < frameMinX) frameMinX = sMinX;
+ if (sMinY < frameMinY) frameMinY = sMinY;
+ if (sMaxX > frameMaxX) frameMaxX = sMaxX;
+ if (sMaxY > frameMaxY) frameMaxY = sMaxY;
helpers.emitLiveSegment(
- draftCtx,
+ activeDrawCtx,
seg,
bs,
strokeColor,
@@ -182,15 +265,27 @@ export function runFlushPendingPoints(
useWireframeEraser,
canvas,
activeLayer,
- useGpuBatch ? gpuBatch : undefined
+ useGpuBatch ? gpuBatch : undefined,
+ liveBrushOpts
);
},
});
+ if (state.naturalPaintSession) {
+ const natDirty = state.naturalPaintSession.flushPendingDirtyToContext(activeDrawCtx, true);
+ if (natDirty) {
+ const natPad = 14;
+ if (natDirty.minX - natPad < frameMinX) frameMinX = natDirty.minX - natPad;
+ if (natDirty.minY - natPad < frameMinY) frameMinY = natDirty.minY - natPad;
+ if (natDirty.maxX + natPad > frameMaxX) frameMaxX = natDirty.maxX + natPad;
+ if (natDirty.maxY + natPad > frameMaxY) frameMaxY = natDirty.maxY + natPad;
+ }
+ }
+
if (useGpuBatch && gpuBatch.length > 0) {
const liveColor =
(isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
- const flushed = flushGpuDabs(draftCtx, gpuBatch, liveColor, liveBrushOpts);
+ const flushed = flushGpuDabs(activeDrawCtx, gpuBatch, liveColor, liveBrushOpts);
if (!flushed) {
const pts = state.allStrokePoints;
if (pts.length >= 2) {
@@ -198,7 +293,7 @@ export function runFlushPendingPoints(
const pB = pts[pts.length - 1];
const fallbackSeg = pipeline.getSplineGenerator().generateCornerSegment(pA, pB);
helpers.emitLiveSegment(
- draftCtx,
+ activeDrawCtx,
fallbackSeg,
bs,
strokeColor,
@@ -218,6 +313,33 @@ export function runFlushPendingPoints(
gpuBatch.length = 0;
}
+ if (state.isDualBrushStroke) {
+ flushLiveDualSecondaryGpuBatch(state, helpers, bs, isMonochrome, draftScale);
+ if (drewAnySegment && Number.isFinite(frameMinX)) {
+ syncDualBrushRegionToDraft(
+ state,
+ draftCanvas,
+ draftCtx,
+ bs,
+ frameMinX,
+ frameMinY,
+ frameMaxX,
+ frameMaxY
+ );
+ }
+ } else if (state.isStrokePaperTextureActive && drewAnySegment && Number.isFinite(frameMinX)) {
+ syncStrokePaperTextureRegionToDraft(
+ state,
+ draftCanvas,
+ draftCtx,
+ bs,
+ frameMinX,
+ frameMinY,
+ frameMaxX,
+ frameMaxY
+ );
+ }
+
const pDirty = pipeline.dirtyRect;
if (Number.isFinite(pDirty.minX) && Number.isFinite(pDirty.maxX)) {
const dims = params.dimensionsRef.current;
@@ -239,6 +361,28 @@ export function runFlushPendingPoints(
if (drewAnySegment) {
draftCanvas.__draftHasContent = true;
draftCanvas.__draftVersion = (draftCanvas.__draftVersion || 0) + 1;
+ // Record pixel-space dirty sub-rect on draftCanvas so WebGL2 compositor uploads ONLY
+ // the freshly painted region instead of the entire 38MB draft texture every animation frame.
+ if (Number.isFinite(frameMinX) && Number.isFinite(frameMaxX) && draftCanvas.__draftDocRect) {
+ const docRect = draftCanvas.__draftDocRect;
+ const scale = draftCanvas.__draftScale ?? 1.0;
+ const px0 = Math.max(0, Math.floor((frameMinX - docRect.x) * scale) - 4);
+ const py0 = Math.max(0, Math.floor((frameMinY - docRect.y) * scale) - 4);
+ const px1 = Math.min(draftCanvas.width, Math.ceil((frameMaxX - docRect.x) * scale) + 4);
+ const py1 = Math.min(draftCanvas.height, Math.ceil((frameMaxY - docRect.y) * scale) + 4);
+ if (px1 > px0 && py1 > py0) {
+ const prevDirty = draftCanvas.__draftFrameDirtyRect;
+ if (prevDirty) {
+ const ux0 = Math.min(prevDirty.x, px0);
+ const uy0 = Math.min(prevDirty.y, py0);
+ const ux1 = Math.max(prevDirty.x + prevDirty.width, px1);
+ const uy1 = Math.max(prevDirty.y + prevDirty.height, py1);
+ draftCanvas.__draftFrameDirtyRect = { x: ux0, y: uy0, width: ux1 - ux0, height: uy1 - uy0 };
+ } else {
+ draftCanvas.__draftFrameDirtyRect = { x: px0, y: py0, width: px1 - px0, height: py1 - py0 };
+ }
+ }
+ }
state.liveNeedsNotify = true;
}
diff --git a/src/hooks/drawing/brushStrokeSession/liveSegmentEmitter.ts b/src/hooks/drawing/brushStrokeSession/liveSegmentEmitter.ts
index e525210..466ea3d 100644
--- a/src/hooks/drawing/brushStrokeSession/liveSegmentEmitter.ts
+++ b/src/hooks/drawing/brushStrokeSession/liveSegmentEmitter.ts
@@ -10,15 +10,177 @@ import {
canUseWebGlForBrush,
flushGpuDabs,
buildBrushRenderOptions,
+ buildSecondaryBrushSettings,
+ resolveDualBrushConfig,
+ scalePointsForSecondaryBrush,
+ scaleSegmentForSecondaryBrush,
} from '../../../engine/BrushEngine';
+import {
+ buildRibbonRenderOptionsFromBrushSettings,
+ isRibbonBrush,
+ renderCompleteRibbonStroke,
+ resolveRibbonRepeatMode,
+ RibbonStrokeSession,
+} from '../../../engine/RibbonBrushEngine';
import { GpuDab } from '../../../engine/WebGlBrushEngine';
import { DraftCanvasElement, applySelectionCanvasClip } from '../types';
+import { buildLiveSecondaryBrushOptions } from './strokeHelpers';
import {
StrokeSessionHelpers,
StrokeSessionState,
UseBrushStrokeSessionParams,
} from './types';
+function emitLiveDualSecondarySegment(
+ state: StrokeSessionState,
+ params: UseBrushStrokeSessionParams,
+ helpers: Pick<StrokeSessionHelpers, 'resolveLiveAntiAlias' | 'markTouchedTiles'>,
+ seg: CubicBezierSegment,
+ bs: BrushSettings,
+ isMonochrome: boolean
+): void {
+ const dualCfg = resolveDualBrushConfig(bs);
+ if (!dualCfg || !state.dualSecondaryCanvas) return;
+ const secCtx = get2DContext(state.dualSecondaryCanvas);
+ if (!secCtx) return;
+
+ const secInfo = buildSecondaryBrushSettings(bs, dualCfg);
+ const secBs = secInfo.settings;
+ const secSeg = scaleSegmentForSecondaryBrush(seg, secInfo.sizeRatio, secBs.size);
+
+ const secScatter = Math.max(0, dualCfg.scatter ?? 0);
+ const secPad = Math.ceil(
+ Math.max(secSeg.p0.width, secSeg.p3.width, secBs.size || 10) * (2.8 + secScatter * 2) + 32
+ );
+ const sMinX = Math.min(secSeg.p0.x, secSeg.c1.x, secSeg.c2.x, secSeg.p3.x) - secPad;
+ const sMinY = Math.min(secSeg.p0.y, secSeg.c1.y, secSeg.c2.y, secSeg.p3.y) - secPad;
+ const sMaxX = Math.max(secSeg.p0.x, secSeg.c1.x, secSeg.c2.x, secSeg.p3.x) + secPad;
+ const sMaxY = Math.max(secSeg.p0.y, secSeg.c1.y, secSeg.c2.y, secSeg.p3.y) + secPad;
+ state.strokePipeline.expandDirtyRectBounds(sMinX, sMinY, sMaxX, sMaxY);
+ helpers.markTouchedTiles(sMinX, sMinY, sMaxX, sMaxY);
+
+ const draftCanvas = params.effectiveDraftCanvasRef?.current as
+ | DraftCanvasElement
+ | null
+ | undefined;
+ const draftScale = draftCanvas?.__draftScale ?? 1.0;
+ const liveAA = helpers.resolveLiveAntiAlias(secBs, isMonochrome, draftScale);
+
+ if (isRibbonBrush(secBs)) {
+ const repeatMode = resolveRibbonRepeatMode(secBs.subTipOrder);
+ const ribbonOpts = buildRibbonRenderOptionsFromBrushSettings(
+ secBs,
+ 'color',
+ false,
+ false,
+ false,
+ false,
+ undefined,
+ {
+ opacity: 1.0,
+ flow: secBs.flow ?? 1.0,
+ hardness: secBs.hardness ?? 1.0,
+ antiAlias: liveAA ?? secBs.antiAlias ?? 2,
+ primaryColor: '#ffffff',
+ isEraser: false,
+ isBgEraser: false,
+ alphaLocked: false,
+ isTransparentInk: false,
+ }
+ );
+
+ if (repeatMode === 'once' && state.allStrokePoints.length >= 2 && draftCanvas) {
+ const docRect = draftCanvas.__draftDocRect;
+ if (docRect) {
+ secCtx.clearRect(docRect.x, docRect.y, docRect.width, docRect.height);
+ } else {
+ secCtx.clearRect(0, 0, state.dualSecondaryCanvas.width, state.dualSecondaryCanvas.height);
+ }
+ const scaledPts = scalePointsForSecondaryBrush(
+ state.allStrokePoints,
+ secInfo.sizeRatio,
+ secBs.size
+ );
+ renderCompleteRibbonStroke(
+ secCtx,
+ scaledPts,
+ {
+ ...secBs,
+ opacity: 1.0,
+ antiAlias: liveAA ?? secBs.antiAlias,
+ color: '#ffffff',
+ isTransparentInk: false,
+ },
+ 'brush',
+ 'color',
+ false,
+ false,
+ false,
+ undefined,
+ ribbonOpts
+ );
+ return;
+ }
+
+ if (!state.dualSecondaryRibbonSession) {
+ state.dualSecondaryRibbonSession = new RibbonStrokeSession();
+ }
+ state.dualSecondaryRibbonSession.appendCubicSegment(secCtx, secSeg, ribbonOpts, 'brush');
+ return;
+ }
+
+ const secOpts = buildLiveSecondaryBrushOptions(
+ secBs,
+ isMonochrome,
+ liveAA,
+ state.strokeTotalDistance
+ );
+ const useSecGpu = canUseWebGlForBrush(secOpts);
+
+ state.dualSecondaryRemainderDist = drawBrushCubicBezierSegment(
+ secCtx,
+ secSeg.p0,
+ secSeg.c1,
+ secSeg.c2,
+ secSeg.p3,
+ '#ffffff',
+ secOpts,
+ state.dualSecondaryRemainderDist,
+ state.dualSecondaryDabCounter,
+ useSecGpu ? state.dualFrameSecondaryGpuDabs : undefined
+ );
+}
+
+export function flushLiveDualSecondaryGpuBatch(
+ state: StrokeSessionState,
+ helpers: Pick<StrokeSessionHelpers, 'resolveLiveAntiAlias'>,
+ bs: BrushSettings,
+ isMonochrome: boolean,
+ draftScale: number
+): void {
+ if (!state.isDualBrushStroke || state.dualFrameSecondaryGpuDabs.length === 0) return;
+ const dualCfg = resolveDualBrushConfig(bs);
+ if (!dualCfg || !state.dualSecondaryCanvas) {
+ state.dualFrameSecondaryGpuDabs.length = 0;
+ return;
+ }
+ const secCtx = get2DContext(state.dualSecondaryCanvas);
+ if (!secCtx) {
+ state.dualFrameSecondaryGpuDabs.length = 0;
+ return;
+ }
+ const secInfo = buildSecondaryBrushSettings(bs, dualCfg);
+ const liveAA = helpers.resolveLiveAntiAlias(secInfo.settings, isMonochrome, draftScale);
+ const secOpts = buildLiveSecondaryBrushOptions(
+ secInfo.settings,
+ isMonochrome,
+ liveAA,
+ state.strokeTotalDistance
+ );
+ flushGpuDabs(secCtx, state.dualFrameSecondaryGpuDabs, '#ffffff', secOpts);
+ state.dualFrameSecondaryGpuDabs.length = 0;
+}
+
export function emitLiveSegmentToDraft(
state: StrokeSessionState,
params: UseBrushStrokeSessionParams,
@@ -36,7 +198,8 @@ export function emitLiveSegmentToDraft(
useWireframeEraser: boolean,
canvas: HTMLCanvasElement | null,
activeLayer: LayerItem | undefined,
- gpuBatch: GpuDab[] | undefined
+ gpuBatch: GpuDab[] | undefined,
+ precomputedBrushOpts?: import('../../../engine/BrushEngine').BrushRenderOptions
): void {
const sStart = seg.p0;
const c1Pt = seg.c1;
@@ -70,40 +233,120 @@ export function emitLiveSegmentToDraft(
}
if (state.naturalPaintSession) {
- state.naturalPaintSession.drawCubicSegment(
- draftCtx,
+ state.naturalPaintSession.appendCubicSegment(
sStart,
c1Pt,
c2Pt,
sEnd,
- state.layerPixelSampler || undefined,
- true
+ state.layerPixelSampler || undefined
);
return;
}
+ if (isRibbonBrush(bs)) {
+ 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 repeatMode = resolveRibbonRepeatMode(bs.subTipOrder);
+
+ const ribbonOpts = buildRibbonRenderOptionsFromBrushSettings(
+ bs,
+ isMonochrome ? 'monochrome' : params.colorModeRef.current,
+ isBgEraser,
+ false,
+ false,
+ isMonochrome && (liveAA ?? bs.antiAlias ?? 2) !== 0 && bs.useGpu !== false,
+ undefined,
+ {
+ opacity: 1.0,
+ flow: strokeFlow,
+ hardness: strokeHardness,
+ antiAlias: liveAA ?? (isMonochrome ? 0 : bs.antiAlias ?? 2),
+ opacitySensor: helpers.resolveEffectiveOpacitySensor(bs, isMonochrome, isEraser),
+ primaryColor: liveColor,
+ isEraser: false,
+ isBgEraser: false,
+ alphaLocked: false,
+ isTransparentInk: false,
+ }
+ );
+
+ if (repeatMode === 'once' && state.allStrokePoints.length >= 2 && draftCanvas) {
+ const docRect = draftCanvas.__draftDocRect;
+ if (docRect) {
+ draftCtx.clearRect(docRect.x, docRect.y, docRect.width, docRect.height);
+ } else {
+ draftCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
+ }
+ renderCompleteRibbonStroke(
+ draftCtx,
+ state.allStrokePoints,
+ {
+ ...bs,
+ opacity: 1.0,
+ flow: strokeFlow,
+ hardness: strokeHardness,
+ antiAlias: liveAA ?? bs.antiAlias,
+ color: liveColor,
+ isTransparentInk: false,
+ },
+ 'brush',
+ isMonochrome ? 'monochrome' : params.colorModeRef.current,
+ false,
+ false,
+ isMonochrome && (liveAA ?? bs.antiAlias ?? 2) !== 0 && bs.useGpu !== false,
+ undefined,
+ ribbonOpts
+ );
+ if (state.isDualBrushStroke) {
+ emitLiveDualSecondarySegment(state, params, helpers, seg, bs, isMonochrome);
+ }
+ return;
+ }
+
+ if (!state.ribbonSession) {
+ state.ribbonSession = new RibbonStrokeSession();
+ }
+ state.ribbonSession.appendCubicSegment(draftCtx, seg, ribbonOpts, 'brush');
+ if (state.isDualBrushStroke) {
+ emitLiveDualSecondarySegment(state, params, helpers, seg, bs, isMonochrome);
+ }
+ 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
- );
+ let brushOpts = precomputedBrushOpts;
+ if (brushOpts) {
+ brushOpts.currentStrokeDist = state.strokeTotalDistance;
+ } else {
+ const draftCanvas = params.effectiveDraftCanvasRef?.current as
+ | DraftCanvasElement
+ | null
+ | undefined;
+ const draftScale = draftCanvas?.__draftScale ?? 1.0;
+ const liveAA = helpers.resolveLiveAntiAlias(bs, isMonochrome, draftScale);
+
+ brushOpts = helpers.buildLiveBrushOptions(
+ bs,
+ strokeFlow,
+ strokeSpacing,
+ strokeHardness,
+ isMonochrome,
+ canvas,
+ activeLayer,
+ isEraser,
+ isBgEraser,
+ true,
+ liveAA
+ );
+ }
state.stampRemainderDist = drawBrushCubicBezierSegment(
draftCtx,
@@ -117,6 +360,10 @@ export function emitLiveSegmentToDraft(
state.liveDabCounter,
gpuBatch
);
+
+ if (state.isDualBrushStroke) {
+ emitLiveDualSecondarySegment(state, params, helpers, seg, bs, isMonochrome);
+ }
}
export function renderPredictedStrokeOverlay(
@@ -128,11 +375,24 @@ export function renderPredictedStrokeOverlay(
): void {
helpers.clearPredictedCanvas();
const bs = helpers.getBrushSettings();
+ const draftCanvas = params.effectiveDraftCanvasRef?.current as
+ | DraftCanvasElement
+ | null
+ | undefined;
+ const isTranslucentPigment =
+ (draftCanvas?.__draftPigmentStrength ?? 0) > 0.005 &&
+ ((bs.opacity ?? 1) < 0.995 ||
+ (bs.flow ?? 1) < 0.995 ||
+ (bs.hardness ?? 1) < 0.98 ||
+ Boolean(bs.opacitySensor?.usePressure));
if (
helpers.getTool() === 'eraser' ||
bs.isTransparentInk ||
bs.colorMixing ||
- state.naturalPaintSession
+ isTranslucentPigment ||
+ state.naturalPaintSession ||
+ isRibbonBrush(bs) ||
+ Boolean(resolveDualBrushConfig(bs))
) {
return;
}
@@ -154,7 +414,8 @@ export function renderPredictedStrokeOverlay(
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 safeZoom = Math.max(0.15, params.zoomRef.current || 1.0);
+ const maxPredDist = Math.min(24 / safeZoom, Math.max(6 / safeZoom, (bs.size || 10) * 1.25));
const predCoords = state.predDocCoords;
predCoords.length = 0;
@@ -227,20 +488,24 @@ export function renderPredictedStrokeOverlay(
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
- );
- });
+ const drew = pipeline.buildPredictedSegments(
+ predCoords.length > 0 ? predCoords : 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);
diff --git a/src/hooks/drawing/brushStrokeSession/nativeTabletBridge.ts b/src/hooks/drawing/brushStrokeSession/nativeTabletBridge.ts
new file mode 100644
index 0000000..679fbbb
--- /dev/null
+++ b/src/hooks/drawing/brushStrokeSession/nativeTabletBridge.ts
@@ -0,0 +1,159 @@
+import React from 'react';
+import { ToolType } from '../../../types/editor';
+import { NativeTabletSample } from '../../../utils/nativeTabletInput';
+
+export const NATIVE_PEN_POINTER_ID = -1001;
+
+export interface NativeTabletBridgeState {
+ nativeStrokeActive: boolean;
+ prevToolBeforeEraserFlip: ToolType | null;
+}
+
+export interface NativeTabletBridgeCallbacks {
+ getTool: () => ToolType;
+ selectTool: (tool: ToolType) => void;
+ isDisabled: () => boolean;
+ isStrokeActive?: () => boolean;
+ isPointOverCanvasViewport: (x: number, y: number) => boolean;
+ onPointerDown: (e: React.PointerEvent<HTMLElement>) => void;
+ onPointerMove: (
+ e: React.PointerEvent<HTMLElement>,
+ coalesced: PointerEvent[]
+ ) => void;
+ onPointerUp: (e: React.PointerEvent<HTMLElement>) => void;
+ onHover: (e: React.PointerEvent<HTMLElement>) => void;
+}
+
+export function createSyntheticNativePenEvent(
+ s: NativeTabletSample,
+ modKeys: { shift: boolean; alt: boolean }
+): React.PointerEvent<HTMLElement> {
+ const evt: Record<string, unknown> = {
+ 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 unknown as React.PointerEvent<HTMLElement>;
+}
+
+/**
+ * Processes a batch of native WinTab / Windows Ink samples into pointer lifecycle callbacks.
+ * Resilient against:
+ * - Spurious child-HWND phase=4 (leave) events while tip contact (buttons & 1) or pressure is still active
+ * - Missed phase=1 (down) events: cleanly recovers and starts a stroke when phase=2 arrives in-contact over canvas
+ */
+export function processNativeTabletBatch(
+ batch: ReadonlyArray<NativeTabletSample>,
+ bridge: NativeTabletBridgeState,
+ modKeys: { shift: boolean; alt: boolean },
+ cb: NativeTabletBridgeCallbacks
+): void {
+ const curTool = cb.getTool();
+ const isBrushOrEraser = curTool === 'brush' || curTool === 'eraser';
+
+ const startStrokeFromSample = (s: NativeTabletSample): boolean => {
+ if (
+ cb.isDisabled() ||
+ !isBrushOrEraser ||
+ !cb.isPointOverCanvasViewport(s.clientX, s.clientY)
+ ) {
+ return false;
+ }
+ const isTailEraser = (s.buttons & 8) !== 0;
+ if (isTailEraser && curTool !== 'eraser') {
+ bridge.prevToolBeforeEraserFlip = curTool;
+ cb.selectTool('eraser');
+ }
+ bridge.nativeStrokeActive = true;
+ cb.onPointerDown(createSyntheticNativePenEvent(s, modKeys));
+ return true;
+ };
+
+ const endActiveStroke = (s: NativeTabletSample): void => {
+ bridge.nativeStrokeActive = false;
+ cb.onPointerUp(createSyntheticNativePenEvent(s, modKeys));
+ if (bridge.prevToolBeforeEraserFlip !== null) {
+ const prev = bridge.prevToolBeforeEraserFlip;
+ bridge.prevToolBeforeEraserFlip = null;
+ cb.selectTool(prev);
+ }
+ };
+
+ let i = 0;
+ while (i < batch.length) {
+ const s = batch[i];
+
+ if (s.phase === 1) {
+ // Pen down: if the drawing session was externally aborted (e.g. Ctrl+Z during WinTab
+ // pen-up hysteresis), resync bridge.nativeStrokeActive so the next pen-down starts cleanly.
+ if (bridge.nativeStrokeActive && cb.isStrokeActive && !cb.isStrokeActive()) {
+ bridge.nativeStrokeActive = false;
+ if (bridge.prevToolBeforeEraserFlip !== null) {
+ const prev = bridge.prevToolBeforeEraserFlip;
+ bridge.prevToolBeforeEraserFlip = null;
+ cb.selectTool(prev);
+ }
+ }
+ if (!bridge.nativeStrokeActive) {
+ startStrokeFromSample(s);
+ } else {
+ // Already active (e.g. duplicate down): treat as drag point so we don't abort mid-stroke
+ const evt = createSyntheticNativePenEvent(s, modKeys);
+ cb.onPointerMove(evt, [evt as unknown as PointerEvent]);
+ }
+ i++;
+ } else if (s.phase === 2) {
+ // If a phase=1 was missed or dropped, cleanly recover on in-contact drag over the canvas viewport
+ if (!bridge.nativeStrokeActive && (s.buttons & 1) !== 0) {
+ if (startStrokeFromSample(s)) {
+ i++;
+ }
+ }
+
+ // Batch all contiguous drag samples in this hardware burst
+ const coalesced: PointerEvent[] = [];
+ while (i < batch.length && batch[i].phase === 2) {
+ coalesced.push(createSyntheticNativePenEvent(batch[i], modKeys) as unknown as PointerEvent);
+ i++;
+ }
+ if (bridge.nativeStrokeActive && coalesced.length > 0) {
+ const last = coalesced[coalesced.length - 1] as unknown as React.PointerEvent<HTMLElement>;
+ cb.onPointerMove(last, coalesced);
+ }
+ } else if (s.phase === 3) {
+ // Genuine pen up
+ if (bridge.nativeStrokeActive) {
+ endActiveStroke(s);
+ }
+ i++;
+ } else if (s.phase === 4) {
+ // Leave: ONLY end stroke if the pen truly lost contact (not a child-HWND hover bounce!)
+ const stillInContact = (s.buttons & 1) !== 0 || s.pressure > 0.001;
+ if (bridge.nativeStrokeActive && !stillInContact) {
+ endActiveStroke(s);
+ }
+ i++;
+ } else {
+ // Hover (phase 0)
+ if (!bridge.nativeStrokeActive && cb.isPointOverCanvasViewport(s.clientX, s.clientY)) {
+ cb.onHover(createSyntheticNativePenEvent(s, modKeys));
+ }
+ i++;
+ }
+ }
+}
diff --git a/src/hooks/drawing/brushStrokeSession/pointerDownHandler.ts b/src/hooks/drawing/brushStrokeSession/pointerDownHandler.ts
index 1f35be0..c94f8b3 100644
--- a/src/hooks/drawing/brushStrokeSession/pointerDownHandler.ts
+++ b/src/hooks/drawing/brushStrokeSession/pointerDownHandler.ts
@@ -2,10 +2,24 @@ import React from 'react';
import { Point } from '../../../types/editor';
import { calculateStrokeWidth, get2DContext } from '../../../utils/canvasUtils';
import { PaintReservoir, LayerPixelSampler } from '../../../utils/colorMixingEngine';
+import { detectWhitePaperGround } from '../../../utils/pigmentEngine';
import {
isNaturalPaintBrush,
NaturalPaintStrokeSession,
} from '../../../engine/NaturalPaintRenderer';
+import { isRibbonBrush, RibbonStrokeSession } from '../../../engine/RibbonBrushEngine';
+import {
+ buildSecondaryBrushSettings,
+ needsStrokeLevelPaperTexture,
+ resolveDualBrushConfig,
+} from '../../../engine/BrushEngine';
+import {
+ prepareDualDraftCanvases,
+ prepareRawDraftCanvasForStrokeTexture,
+ resolveStrokePigmentStrength,
+ syncDualBrushRegionToDraft,
+ syncStrokePaperTextureRegionToDraft,
+} from './strokeHelpers';
import { useUiStore } from '../../../stores';
import { recoveryService } from '../../../services/recoveryService';
import { isLinearPressureCurve } from '../../../utils/pressureCurve';
@@ -20,6 +34,7 @@ import {
renderShiftLineInitialSegment,
setupDraftCanvasSurface,
} from './pointerDownInitialStamp';
+import { NATIVE_PEN_POINTER_ID } from './nativeTabletBridge';
export function runPointerDown(
state: StrokeSessionState,
@@ -41,6 +56,14 @@ export function runPointerDown(
}
e.preventDefault();
if (params.isDrawingRef.current) {
+ // Defense-in-depth: never let a WinTab CXO_SYSTEM-synthesized DOM mouse pointerdown
+ // abort an active native pen stroke that carries true hardware pressure.
+ if (
+ state.activePointerId === NATIVE_PEN_POINTER_ID &&
+ e.pointerId !== NATIVE_PEN_POINTER_ID
+ ) {
+ return;
+ }
helpers.abortActiveStroke();
}
@@ -48,9 +71,12 @@ export function runPointerDown(
const currentLayerIdCheck = params.activeLayerIdRef.current;
if (!currentLayerIdCheck || dims.width <= 0 || dims.height <= 0) return;
+ // Flush any deferred idle history tasks from previous strokes before starting a new stroke
+ // so undo/redo order and tile deltas stay strictly consistent during rapid sketching.
+ params.flushPendingHistoryTasks();
+
const maskCanvas = params.getActiveMaskCanvas();
if (params.isMaskModeRef.current) {
- params.flushPendingHistoryTasks();
if (!maskCanvas) return;
}
@@ -90,12 +116,18 @@ export function runPointerDown(
const draftCompositeOp: GlobalCompositeOperation =
isVectorOrMask || isBgEraser
? 'source-over'
- : isEraser || bs.isTransparentInk
+ : isEraser || bs.isTransparentInk || bs.brushCombineMode === 'clear'
? 'destination-out'
+ : bs.brushCombineMode === 'behind'
+ ? 'destination-over'
: activeLayer?.alphaLocked
? 'source-atop'
: 'source-over';
+ const preferNativeDraftScale = Boolean(
+ !isVectorOrMask &&
+ (bs.colorMixing || bs.customTipImage || bs.paperTextureImage)
+ );
const draftScale = setupDraftCanvasSurface(
params,
draftCanvas,
@@ -103,9 +135,21 @@ export function runPointerDown(
vRect,
dims,
draftCompositeOp,
- isMonochrome
+ isMonochrome,
+ preferNativeDraftScale
);
+ const draftPigmentStrength = isVectorOrMask
+ ? 0
+ : resolveStrokePigmentStrength(bs, isEraser, isBgEraser, isMonochrome);
+ draftCanvas.__draftPigmentStrength = draftPigmentStrength;
+ draftCanvas.__draftPigmentWhiteGround =
+ draftPigmentStrength > 0.005
+ ? detectWhitePaperGround(allLayers, currentLayerId, params.activeTileGridRef.current)
+ : false;
+ draftCanvas.__draftCombineMode =
+ (isEraser && !isBgEraser) || bs.isTransparentInk ? undefined : bs.brushCombineMode;
+
helpers.clearPredictedCanvas();
if (params.interactionRef.current) {
@@ -172,14 +216,17 @@ export function runPointerDown(
hasCustomGlobalCurve || Boolean(bs.pressureCurve && bs.pressureCurve.length > 0);
const taperEngine = pipeline.getTaperEngine();
if (bs.usePressure) {
- const baseStartP = hasCustomCurve
+ const rawStartP = firstEvent.pointerType === 'mouse' ? 0.5 : firstEvent.pressure ?? 0;
+ const rawBaseStartP = hasCustomCurve
? startPoint.pressure
: taperEngine.mapPressure(startPoint.pressure);
+ const baseStartP = rawStartP > 0.005 ? Math.max(0.015, rawBaseStartP) : rawBaseStartP;
const smoothStartP = taperEngine.smoothPressure(baseStartP);
- startPoint.pressure = smoothStartP;
+ const effectiveStartP = rawStartP > 0.005 ? Math.max(0.015, smoothStartP) : smoothStartP;
+ startPoint.pressure = effectiveStartP;
startPoint.width = calculateStrokeWidth(
bs.size,
- smoothStartP,
+ effectiveStartP,
bs.minSizeFactor,
bs.usePressure,
firstEvent.pointerType,
@@ -193,13 +240,14 @@ export function runPointerDown(
startPoint.width = 1.25;
}
- const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
+ const dualCfg = resolveDualBrushConfig(bs);
+ const dualSecInfo = dualCfg ? buildSecondaryBrushSettings(bs, dualCfg) : null;
+ const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0, dualCfg?.scatter ?? 0);
+ const maxBrushDim = Math.max(startPoint.width, bs.size || 10, dualSecInfo?.settings.size || 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
- )
+ Math.ceil(maxBrushDim * (2.8 + scatterFactor * 2) + blurMargin + 32)
);
const shiftAction = useUiStore.getState().appSettings.modifierKeys.shift;
@@ -361,6 +409,61 @@ export function runPointerDown(
);
}
+ const isRibbonStroke =
+ !useWireframeEraser &&
+ !state.naturalPaintSession &&
+ isRibbonBrush(bs);
+ state.ribbonSession = isRibbonStroke ? new RibbonStrokeSession() : null;
+
+ state.isStrokePaperTextureActive =
+ !isEraser &&
+ !isBgEraser &&
+ !isMonochrome &&
+ !isVectorOrMask &&
+ !state.naturalPaintSession &&
+ !isRibbonStroke &&
+ needsStrokeLevelPaperTexture(bs);
+
+ state.isDualBrushStroke = Boolean(
+ dualCfg && !useWireframeEraser && !isVectorOrMask && !state.naturalPaintSession
+ );
+ state.dualSecondaryDabCounter.count = 0;
+ state.dualSecondaryDabCounter.lastAngle = undefined;
+ state.dualSecondaryDabCounter.lastStepDist = undefined;
+ state.dualFrameSecondaryGpuDabs.length = 0;
+ state.dualSecondaryRibbonSession =
+ state.isDualBrushStroke && dualSecInfo && isRibbonBrush(dualSecInfo.settings)
+ ? new RibbonStrokeSession()
+ : null;
+
+ let activeDrawCtx: CanvasRenderingContext2D = draftCtx;
+ if (state.isDualBrushStroke) {
+ const dualPair = prepareDualDraftCanvases(
+ state,
+ draftCanvas,
+ dims,
+ params.selectionRef.current
+ );
+ if (dualPair) {
+ activeDrawCtx = dualPair.primaryCtx;
+ } else {
+ state.isDualBrushStroke = false;
+ }
+ }
+ if (!state.isDualBrushStroke && state.isStrokePaperTextureActive) {
+ const rawCtx = prepareRawDraftCanvasForStrokeTexture(
+ state,
+ draftCanvas,
+ dims,
+ params.selectionRef.current
+ );
+ if (rawCtx) {
+ activeDrawCtx = rawCtx;
+ } else {
+ state.isStrokePaperTextureActive = false;
+ }
+ }
+
const strokeId = `stroke-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`;
state.currentStrokeId = strokeId;
params.onCollabStrokeStartRef.current?.(strokeId, currentLayerId, bs, currentTool, startPoint);
@@ -368,9 +471,24 @@ export function runPointerDown(
state.liveDabCounter.count = 0;
state.liveDabCounter.lastAngle = undefined;
state.liveDabCounter.lastStepDist = undefined;
+ state.liveDabCounter.lockedInitialAngle = undefined;
+ state.liveDabCounter.initOriginX = undefined;
+ state.liveDabCounter.initOriginY = undefined;
+ state.dualSecondaryDabCounter.lockedInitialAngle = undefined;
+ state.dualSecondaryDabCounter.initOriginX = undefined;
+ state.dualSecondaryDabCounter.initOriginY = undefined;
state.stampRemainderDist = bs.customTipImage
? Math.max(0.15, startPoint.width * (bs.spacing ?? 0.07))
: Math.max(0.12, startPoint.width * (bs.spacing ?? 0.08));
+ if (state.isDualBrushStroke && dualSecInfo) {
+ const secStartW = Math.max(0.2, startPoint.width * dualSecInfo.sizeRatio);
+ const secSpacing = dualSecInfo.settings.spacing ?? 0.1;
+ state.dualSecondaryRemainderDist = dualSecInfo.settings.customTipImage
+ ? Math.max(0.15, secStartW * secSpacing)
+ : Math.max(0.12, secStartW * secSpacing);
+ } else {
+ state.dualSecondaryRemainderDist = 0;
+ }
const firstDotPoint = state.allStrokePoints[0];
@@ -380,13 +498,38 @@ export function runPointerDown(
!isShiftLine &&
!state.naturalPaintSession &&
!useWireframeEraser &&
- (bs.customTipAngleDynamics === 'direction' ||
- bs.customTipAngleDynamics === 'direction-random') &&
- (bs.thickness ?? 1.0) < 0.85;
+ (isRibbonStroke ||
+ ((bs.customTipAngleDynamics === 'direction' ||
+ bs.customTipAngleDynamics === 'direction-random' ||
+ bs.customTipAngleDynamics === 'initial-direction') &&
+ (bs.thickness ?? 1.0) < 0.85));
+
+ // For stylus strokes with pressure-sensitive opacity/density/curve or an unpopulated 0.5
+ // Windows Ink / W3C pointerdown sentinel, defer the initial dot until the first real
+ // pointermove delivers confirmed hardware pressure (single taps still stamp cleanly on pointerup).
+ const isPenDown = firstEvent.pointerType === 'pen';
+ const rawPenDownP = firstEvent.pressure ?? 0;
+ const isSentinelPenDown = isPenDown && Math.abs(rawPenDownP - 0.5) < 1e-4;
+ const hasPressureDensityOrCurve = Boolean(
+ bs.usePressure &&
+ (bs.densitySensor?.usePressure ||
+ bs.opacitySensor?.usePressure ||
+ bs.densityOfPaintSensor?.usePressure ||
+ (bs.pressureCurve && bs.pressureCurve.length > 0))
+ );
+ const deferPenInitialDot =
+ !isShiftLine &&
+ !state.naturalPaintSession &&
+ !useWireframeEraser &&
+ isPenDown &&
+ (hasPressureDensityOrCurve || isSentinelPenDown);
+
+ state.deferredInitialDot = deferPenInitialDot;
+ state.deferredStartRawPressure = rawPenDownP;
- if (!deferDirectionInitialDot) {
+ if (!deferDirectionInitialDot && !deferPenInitialDot) {
renderInitialStrokeDot(state, helpers, {
- draftCtx,
+ draftCtx: activeDrawCtx,
firstDotPoint,
bs,
strokeColor,
@@ -405,11 +548,14 @@ export function runPointerDown(
} else {
// Start stamping right at distance 0 on the first movement segment so there is no gap at stroke start
state.stampRemainderDist = 0;
+ if (state.isDualBrushStroke) {
+ state.dualSecondaryRemainderDist = 0;
+ }
}
if (isShiftLine && prevStrokeEnd) {
renderShiftLineInitialSegment(state, helpers, {
- draftCtx,
+ draftCtx: activeDrawCtx,
startPoint,
startNow,
dirtyRadius: r,
@@ -428,9 +574,39 @@ export function runPointerDown(
});
}
- draftCanvas.__draftHasContent = true;
- draftCanvas.__draftVersion = (draftCanvas.__draftVersion || 0) + 1;
- params.activeTileGridRef.current.notifyChange(true);
+ if (state.isDualBrushStroke && state.dirtyRect) {
+ syncDualBrushRegionToDraft(
+ state,
+ draftCanvas,
+ draftCtx,
+ bs,
+ state.dirtyRect.minX,
+ state.dirtyRect.minY,
+ state.dirtyRect.maxX,
+ state.dirtyRect.maxY
+ );
+ } else if (state.isStrokePaperTextureActive && state.dirtyRect) {
+ syncStrokePaperTextureRegionToDraft(
+ state,
+ draftCanvas,
+ draftCtx,
+ bs,
+ state.dirtyRect.minX,
+ state.dirtyRect.minY,
+ state.dirtyRect.maxX,
+ state.dirtyRect.maxY
+ );
+ }
+
+ const hasInitialVisualContent =
+ (!deferDirectionInitialDot && !deferPenInitialDot) || (isShiftLine && Boolean(prevStrokeEnd));
+ if (hasInitialVisualContent) {
+ draftCanvas.__draftHasContent = true;
+ draftCanvas.__draftVersion = (draftCanvas.__draftVersion || 0) + 1;
+ params.activeTileGridRef.current.notifyChange(true);
+ } else {
+ draftCanvas.__draftHasContent = false;
+ }
state.liveNeedsNotify = false;
if (pipeline.getPendingCount() > 0 && state.drawRafId === null) {
diff --git a/src/hooks/drawing/brushStrokeSession/pointerDownInitialStamp.ts b/src/hooks/drawing/brushStrokeSession/pointerDownInitialStamp.ts
index bcf07de..c2b0a05 100644
--- a/src/hooks/drawing/brushStrokeSession/pointerDownInitialStamp.ts
+++ b/src/hooks/drawing/brushStrokeSession/pointerDownInitialStamp.ts
@@ -1,11 +1,17 @@
import { BrushSettings, CanvasDimensions, LayerItem, Point } from '../../../types/editor';
-import { getVisibleCanvasBounds } from '../../../utils/canvasUtils';
+import { get2DContext, getVisibleCanvasBounds } from '../../../utils/canvasUtils';
import {
drawBrushDot,
canUseWebGlForBrush,
flushGpuDabs,
+ buildSecondaryBrushSettings,
+ resolveDualBrushConfig,
+ scalePointForSecondaryBrush,
} from '../../../engine/BrushEngine';
+import { isRibbonBrush } from '../../../engine/RibbonBrushEngine';
import { DraftCanvasElement, applySelectionCanvasClip } from '../types';
+import { buildLiveSecondaryBrushOptions } from './strokeHelpers';
+import { flushLiveDualSecondaryGpuBatch } from './liveSegmentEmitter';
import {
StrokeSessionHelpers,
StrokeSessionState,
@@ -19,7 +25,8 @@ export function setupDraftCanvasSurface(
vRect: DOMRect,
dims: CanvasDimensions,
draftCompositeOp: GlobalCompositeOperation,
- isMonochrome: boolean
+ isMonochrome: boolean,
+ preferNativeScale: boolean = false
): number {
const rawVis = getVisibleCanvasBounds(
vRect,
@@ -31,19 +38,34 @@ export function setupDraftCanvasSurface(
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 visMinX = rawVis.maxX > rawVis.minX ? Math.floor(rawVis.minX) : 0;
+ const visMinY = rawVis.maxY > rawVis.minY ? Math.floor(rawVis.minY) : 0;
+ const visW = Math.max(1, rawVis.maxX > rawVis.minX ? Math.ceil(rawVis.maxX) - visMinX : dims.width);
+ const visH = Math.max(1, rawVis.maxY > rawVis.minY ? Math.ceil(rawVis.maxY) - visMinY : 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 maxDimScale = MAX_DRAFT_DIM / Math.max(visW, visH);
+ // Keep 1:1 native document resolution for textured custom tips and SpatialTipMixer color-mixing
+ // brushes whenever the visible canvas fits within MAX_DRAFT_DIM, avoiding bilinear dilution of
+ // porous 1px tip pores during live drawing and enabling zero-pop direct draft commit on pointerUp.
+ const draftScale = preferNativeScale
+ ? Math.min(1.0, maxDimScale)
+ : Math.min(1.0, screenMatchedScale, maxDimScale);
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) {
+ const resized = draftCanvas.width !== surfaceW || draftCanvas.height !== surfaceH;
+ if (resized) {
draftCanvas.width = surfaceW;
draftCanvas.height = surfaceH;
+ draftCanvas.__clipSaved = false;
+ } else if (draftCanvas.__clipSaved) {
+ try {
+ draftCtx.restore();
+ } catch {
+ // Ignore restore underflow
+ }
+ draftCanvas.__clipSaved = false;
}
draftCtx.resetTransform();
@@ -60,6 +82,8 @@ export function setupDraftCanvasSurface(
draftCanvas.__draftScale = draftScale;
draftCanvas.__draftMonochrome = isMonochrome;
draftCanvas.__draftVersion = (draftCanvas.__draftVersion || 0) + 1;
+ draftCanvas.__draftFrameDirtyRect = null;
+ draftCanvas.__draftForceFullUpload = true;
draftCtx.setTransform(
draftScale,
@@ -70,6 +94,7 @@ export function setupDraftCanvasSurface(
-visMinY * draftScale
);
draftCtx.save();
+ draftCanvas.__clipSaved = true;
draftCtx.beginPath();
draftCtx.rect(0, 0, dims.width, dims.height);
draftCtx.clip();
@@ -180,6 +205,33 @@ export function renderInitialStrokeDot(
}
gpuBatch.length = 0;
}
+
+ if (state.isDualBrushStroke && state.dualSecondaryCanvas) {
+ const dualCfg = resolveDualBrushConfig(bs);
+ const secCtx = get2DContext(state.dualSecondaryCanvas);
+ if (dualCfg && secCtx) {
+ const secInfo = buildSecondaryBrushSettings(bs, dualCfg);
+ if (!isRibbonBrush(secInfo.settings)) {
+ const secPt = scalePointForSecondaryBrush(
+ firstDotPoint,
+ secInfo.sizeRatio,
+ secInfo.settings.size
+ );
+ const secAA = helpers.resolveLiveAntiAlias(secInfo.settings, isMonochrome, draftScale);
+ const secOpts = buildLiveSecondaryBrushOptions(secInfo.settings, isMonochrome, secAA, 0);
+ const useSecGpu = canUseWebGlForBrush(secOpts);
+ const secBatch = state.dualFrameSecondaryGpuDabs;
+ secBatch.length = 0;
+ drawBrushDot(secCtx, secPt, '#ffffff', secOpts, useSecGpu ? secBatch : undefined);
+ if (useSecGpu && secBatch.length > 0) {
+ if (!flushGpuDabs(secCtx, secBatch, '#ffffff', secOpts)) {
+ drawBrushDot(secCtx, secPt, '#ffffff', secOpts);
+ }
+ secBatch.length = 0;
+ }
+ }
+ }
+ }
}
export interface ShiftLineSegmentParams extends Omit<InitialStampParams, 'firstDotPoint' | 'zoom'> {
@@ -257,6 +309,9 @@ export function renderShiftLineInitialSegment(
flushGpuDabs(draftCtx, gpuBatch, liveColor, liveOpts);
gpuBatch.length = 0;
}
+ if (state.isDualBrushStroke) {
+ flushLiveDualSecondaryGpuBatch(state, helpers, bs, isMonochrome, draftScale);
+ }
pipeline.seedKnot(
startPoint.x,
diff --git a/src/hooks/drawing/brushStrokeSession/pointerMoveHandler.ts b/src/hooks/drawing/brushStrokeSession/pointerMoveHandler.ts
index 733d50c..c64b624 100644
--- a/src/hooks/drawing/brushStrokeSession/pointerMoveHandler.ts
+++ b/src/hooks/drawing/brushStrokeSession/pointerMoveHandler.ts
@@ -72,8 +72,37 @@ export function runPointerMove(
let lastQueuedPressure = state.lastQueuedPressure;
let hasQueued = false;
+ // Ensure monotonic, evenly spaced timestamps across same-timestamp coalesced hardware bursts
+ // (common in WebView2 / Chromium getCoalescedEvents and Windows Ink / WinTab bursts).
+ const batchEndTs =
+ (rawCoalesced && rawCoalesced.length > 0
+ ? rawCoalesced[rawCoalesced.length - 1].timeStamp
+ : e.nativeEvent.timeStamp) || performance.now();
+ const prevTs = state.lastPointTime || 0;
+ let allSameTs = count > 1;
+ if (allSameTs && rawCoalesced) {
+ const firstTs = rawCoalesced[0].timeStamp;
+ for (let k = 1; k < count; k++) {
+ if (Math.abs(rawCoalesced[k].timeStamp - firstTs) > 0.25) {
+ allSameTs = false;
+ break;
+ }
+ }
+ }
+ const syntheticSpanMs =
+ allSameTs && count > 1
+ ? prevTs > 0 && batchEndTs > prevTs + 0.5
+ ? Math.min(40, batchEndTs - prevTs)
+ : count * 4.0
+ : 0;
+ const syntheticStartTs = batchEndTs - syntheticSpanMs;
+
for (let i = 0; i < count; i++) {
const cEvent = rawCoalesced && rawCoalesced.length > 0 ? rawCoalesced[i] : e.nativeEvent;
+ const sampleTs =
+ allSameTs && count > 1
+ ? syntheticStartTs + (syntheticSpanMs * (i + 1)) / count
+ : cEvent.timeStamp;
screenToCanvasInto(
cEvent.clientX,
cEvent.clientY,
@@ -150,7 +179,7 @@ export function runPointerMove(
cEvent.tiltX ?? 0,
cEvent.tiltY ?? 0,
cEvent.twist ?? 0,
- cEvent.timeStamp,
+ sampleTs,
encodePointerType(cEvent.pointerType)
);
lastQueuedX = cx;
diff --git a/src/hooks/drawing/brushStrokeSession/pointerUpDirectCommit.ts b/src/hooks/drawing/brushStrokeSession/pointerUpDirectCommit.ts
index 6cff849..c28cd68 100644
--- a/src/hooks/drawing/brushStrokeSession/pointerUpDirectCommit.ts
+++ b/src/hooks/drawing/brushStrokeSession/pointerUpDirectCommit.ts
@@ -1,6 +1,7 @@
import {
BrushSettings,
CanvasSelection,
+ CspBrushCombineMode,
DirtyRect,
LayerItem,
} from '../../../types/editor';
@@ -8,7 +9,13 @@ 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 { get2DContext } from '../../../utils/canvasUtils';
+import { DraftCanvasElement, PushHistoryStepFn } from '../types';
+import {
+ syncDualBrushRegionToDraft,
+ syncStrokePaperTextureRegionToDraft,
+} from './strokeHelpers';
+import { flushLiveDualSecondaryGpuBatch } from './liveSegmentEmitter';
import { StrokeSessionHelpers, StrokeSessionState } from './types';
import { StrokeHistoryToolType } from './pointerUpSpecialCommit';
@@ -66,6 +73,9 @@ export interface DirectDraftCommitParams {
activeLayer: LayerItem | undefined;
targetFormat: TileFormat;
compositeOp: 'source-over' | 'destination-out' | 'source-atop';
+ brushCombineMode?: CspBrushCombineMode;
+ pigmentStrength?: number;
+ pigmentWhiteGround?: boolean;
monoOpts?: {
threshold: number;
expressBlack: boolean;
@@ -102,6 +112,9 @@ export function commitDirectDraftToTiles(opts: DirectDraftCommitParams): () => v
activeLayer,
targetFormat,
compositeOp,
+ brushCombineMode,
+ pigmentStrength,
+ pigmentWhiteGround,
monoOpts,
selMaskOpts,
isEraser,
@@ -140,10 +153,17 @@ export function commitDirectDraftToTiles(opts: DirectDraftCommitParams): () => v
const useGpuTail = canUseWebGlForBrush(liveBrushOpts);
const gpuBatch = state.frameGpuDabs;
gpuBatch.length = 0;
+ state.dualFrameSecondaryGpuDabs.length = 0;
+ const tailDrawCtx =
+ state.isDualBrushStroke && state.dualPrimaryCanvas
+ ? get2DContext(state.dualPrimaryCanvas) || draftCtx
+ : state.isStrokePaperTextureActive && state.rawDraftCanvas
+ ? get2DContext(state.rawDraftCanvas) || draftCtx
+ : draftCtx;
for (let i = 0; i < tailSegments.length; i++) {
helpers.emitLiveSegment(
- draftCtx,
+ tailDrawCtx,
tailSegments[i],
bs,
strokeColor,
@@ -163,11 +183,11 @@ export function commitDirectDraftToTiles(opts: DirectDraftCommitParams): () => v
if (useGpuTail && gpuBatch.length > 0) {
const liveColor =
(isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
- const flushed = flushGpuDabs(draftCtx, gpuBatch, liveColor, liveBrushOpts);
+ const flushed = flushGpuDabs(tailDrawCtx, gpuBatch, liveColor, liveBrushOpts);
if (!flushed) {
for (let i = 0; i < tailSegments.length; i++) {
helpers.emitLiveSegment(
- draftCtx,
+ tailDrawCtx,
tailSegments[i],
bs,
strokeColor,
@@ -186,6 +206,31 @@ export function commitDirectDraftToTiles(opts: DirectDraftCommitParams): () => v
}
gpuBatch.length = 0;
}
+
+ if (state.isDualBrushStroke && draftCtx.canvas) {
+ flushLiveDualSecondaryGpuBatch(state, helpers, bs, isMonochrome, draftScale);
+ syncDualBrushRegionToDraft(
+ state,
+ draftCtx.canvas as DraftCanvasElement,
+ draftCtx,
+ bs,
+ sx,
+ sy,
+ sx + dw,
+ sy + dh
+ );
+ } else if (state.isStrokePaperTextureActive && draftCtx.canvas) {
+ syncStrokePaperTextureRegionToDraft(
+ state,
+ draftCtx.canvas as DraftCanvasElement,
+ draftCtx,
+ bs,
+ sx,
+ sy,
+ sx + dw,
+ sy + dh
+ );
+ }
}
const beforeSnapshot = new Map<
@@ -208,7 +253,10 @@ export function commitDirectDraftToTiles(opts: DirectDraftCommitParams): () => v
destY: sp.y,
format: targetFormat,
compositeOp,
+ brushCombineMode,
opacity: bs.opacity ?? 1.0,
+ pigmentStrength,
+ pigmentWhiteGround,
monochrome: monoOpts,
selectionMask: selMaskOpts,
snapshotOut: beforeSnapshot,
diff --git a/src/hooks/drawing/brushStrokeSession/pointerUpHandler.ts b/src/hooks/drawing/brushStrokeSession/pointerUpHandler.ts
index 74c0aaa..494482f 100644
--- a/src/hooks/drawing/brushStrokeSession/pointerUpHandler.ts
+++ b/src/hooks/drawing/brushStrokeSession/pointerUpHandler.ts
@@ -18,6 +18,12 @@ import {
resolveStrokeHistoryLabel,
} from './pointerUpSpecialCommit';
import { commitRasterStrokeToTiles } from './pointerUpRasterCommit';
+import { renderInitialStrokeDot } from './pointerDownInitialStamp';
+import {
+ resetAndClearOffscreenDraftCanvas,
+ syncDualBrushRegionToDraft,
+ syncStrokePaperTextureRegionToDraft,
+} from './strokeHelpers';
export function runPointerUp(
state: StrokeSessionState,
@@ -152,15 +158,19 @@ export function runPointerUp(
exitSpeed = Math.hypot(pB.x - pA.x, pB.y - pA.y) / dt;
}
+ const hasActiveTaper = Boolean(bs.taper && bs.taper.inOutType !== 0);
const hasCspArcLengthTaper = Boolean(
- bs.taper &&
+ hasActiveTaper &&
+ bs.taper &&
(bs.taper.inOutType !== undefined ||
bs.taper.affectDensity ||
bs.taper.affectOpacity ||
bs.taper.minSizeRatio !== undefined)
);
const shouldTaper =
- Boolean(bs.taper?.useIn) || (Boolean(bs.taper?.useOut) && (!addedFlickPoints || hasCspArcLengthTaper));
+ hasActiveTaper &&
+ (Boolean(bs.taper?.useIn) ||
+ (Boolean(bs.taper?.useOut) && (!addedFlickPoints || hasCspArcLengthTaper)));
if (shouldTaper && !hasCspArcLengthTaper && state.allStrokePoints.length >= 3) {
applyParametricTaper(state.allStrokePoints, {
useIn: Boolean(bs.taper?.useIn),
@@ -171,6 +181,67 @@ export function runPointerUp(
}
const allPoints = state.allStrokePoints;
+ if (
+ state.deferredInitialDot &&
+ allPoints.length === 1 &&
+ tailSegments.length === 0 &&
+ draftCanvas
+ ) {
+ state.deferredInitialDot = false;
+ const dCtx = get2DContext(draftCanvas);
+ if (dCtx) {
+ const activeDrawCtx =
+ state.isDualBrushStroke && state.dualPrimaryCanvas
+ ? get2DContext(state.dualPrimaryCanvas) || dCtx
+ : state.isStrokePaperTextureActive && state.rawDraftCanvas
+ ? get2DContext(state.rawDraftCanvas) || dCtx
+ : dCtx;
+ const isVectorOrMask =
+ activeLayer?.type === 'vector' || params.isMaskModeRef.current;
+ const useWireframeEraser = isVectorOrMask && isEraser && !isBgEraser;
+ renderInitialStrokeDot(state, helpers, {
+ draftCtx: activeDrawCtx,
+ firstDotPoint: allPoints[0],
+ bs,
+ strokeColor,
+ strokeHardness: isMonochrome ? 1.0 : bs.hardness ?? 1.0,
+ strokeFlow: isMonochrome ? 1.0 : bs.flow ?? 1.0,
+ strokeSpacing: bs.spacing ?? 0.08,
+ isMonochrome,
+ isEraser,
+ isBgEraser,
+ useWireframeEraser,
+ draftScale: draftCanvas.__draftScale ?? 1.0,
+ zoom: params.zoomRef.current,
+ canvas: maskCanvas,
+ activeLayer,
+ });
+ if (state.isDualBrushStroke && mergedDirty) {
+ syncDualBrushRegionToDraft(
+ state,
+ draftCanvas,
+ dCtx,
+ bs,
+ mergedDirty.minX,
+ mergedDirty.minY,
+ mergedDirty.maxX,
+ mergedDirty.maxY
+ );
+ } else if (state.isStrokePaperTextureActive && mergedDirty) {
+ syncStrokePaperTextureRegionToDraft(
+ state,
+ draftCanvas,
+ dCtx,
+ bs,
+ mergedDirty.minX,
+ mergedDirty.minY,
+ mergedDirty.maxX,
+ mergedDirty.maxY
+ );
+ }
+ draftCanvas.__draftHasContent = true;
+ }
+ }
let createdVectorStroke: VectorStroke | undefined;
let postPresentWork: (() => void) | null = null;
@@ -258,6 +329,7 @@ export function runPointerUp(
currentTool,
currentLayerId,
activeLayer,
+ allLayers: params.layersRef.current,
activeSelection,
effectiveMode,
targetFormat,
@@ -287,19 +359,32 @@ export function runPointerUp(
if (draftCanvas) {
const dCtx = get2DContext(draftCanvas);
if (dCtx) {
- try {
- dCtx.restore();
- } catch {
- // Ignore restore underflow
+ if (draftCanvas.__clipSaved) {
+ try {
+ dCtx.restore();
+ } catch {
+ // Ignore restore underflow
+ }
+ draftCanvas.__clipSaved = false;
}
dCtx.resetTransform();
dCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
+ } else {
+ draftCanvas.__clipSaved = false;
}
draftCanvas.__draftHasContent = false;
draftCanvas.__draftCompositeOp = 'source-over';
draftCanvas.__draftMonochrome = false;
+ draftCanvas.__draftPigmentStrength = 0;
+ draftCanvas.__draftPigmentWhiteGround = false;
+ draftCanvas.__draftCombineMode = undefined;
+ draftCanvas.__draftFrameDirtyRect = null;
+ draftCanvas.__draftForceFullUpload = true;
draftCanvas.__draftVersion = (draftCanvas.__draftVersion || 0) + 1;
}
+ resetAndClearOffscreenDraftCanvas(state.rawDraftCanvas as DraftCanvasElement | null);
+ resetAndClearOffscreenDraftCanvas(state.dualPrimaryCanvas as DraftCanvasElement | null);
+ resetAndClearOffscreenDraftCanvas(state.dualSecondaryCanvas as DraftCanvasElement | null);
helpers.clearPredictedCanvas();
grid.notifyChange(true);
@@ -341,12 +426,23 @@ export function runPointerUp(
state.touchedTiles.clear();
state.liveNeedsNotify = false;
state.isShiftLineStroke = false;
+ state.deferredInitialDot = false;
+ state.deferredStartRawPressure = 0;
state.layerPixelSampler = null;
state.activeReservoir = null;
+ state.isStrokePaperTextureActive = false;
+ state.isDualBrushStroke = false;
+ state.dualSecondaryRemainderDist = 0;
+ state.dualSecondaryDabCounter.count = 0;
+ state.dualSecondaryDabCounter.lastAngle = undefined;
+ state.dualSecondaryDabCounter.lastStepDist = undefined;
+ state.dualSecondaryRibbonSession = null;
+ state.dualFrameSecondaryGpuDabs.length = 0;
if (state.naturalPaintSession) {
state.naturalPaintSession.finishAndDispose();
state.naturalPaintSession = null;
}
+ state.ribbonSession = null;
state.snapSession.endStroke();
state.straightSnapSession.endStroke();
helpers.emitConstraintAxisChange(null);
diff --git a/src/hooks/drawing/brushStrokeSession/pointerUpRasterCommit.ts b/src/hooks/drawing/brushStrokeSession/pointerUpRasterCommit.ts
index fad1d9d..ee2ec47 100644
--- a/src/hooks/drawing/brushStrokeSession/pointerUpRasterCommit.ts
+++ b/src/hooks/drawing/brushStrokeSession/pointerUpRasterCommit.ts
@@ -12,19 +12,24 @@ 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 {
+ applyCspWatercolorEdge,
+ normalizeWetEdgePower01,
+ renderCompleteStroke,
+ resolveDualBrushConfig,
+} from '../../../engine/BrushEngine';
+import { isRibbonBrush } from '../../../engine/RibbonBrushEngine';
import { LayerPixelSampler } from '../../../utils/colorMixingEngine';
+import { detectWhitePaperGround } from '../../../utils/pigmentEngine';
import {
DraftCanvasElement,
PushHistoryStepFn,
applySelectionCanvasClip,
- applySelectionMaskToImageData,
} from '../types';
+import { resolveStrokePigmentStrength } from './strokeHelpers';
import { StrokeSessionHelpers, StrokeSessionState } from './types';
import { StrokeHistoryToolType } from './pointerUpSpecialCommit';
import {
@@ -51,6 +56,7 @@ export interface CommitRasterStrokeParams {
currentTool: ToolType;
currentLayerId: string;
activeLayer: LayerItem | undefined;
+ allLayers?: LayerItem[];
activeSelection: CanvasSelection | null;
effectiveMode: CanvasColorMode;
targetFormat: TileFormat;
@@ -84,6 +90,7 @@ export function commitRasterStrokeToTiles(
currentTool,
currentLayerId,
activeLayer,
+ allLayers,
activeSelection,
effectiveMode,
targetFormat,
@@ -107,12 +114,16 @@ export function commitRasterStrokeToTiles(
const draftCtx = draftCanvas ? get2DContext(draftCanvas) : null;
const draftScale = draftCanvas?.__draftScale ?? 0;
const draftDocRect = draftCanvas?.__draftDocRect;
+ const effectiveBrushCombineMode =
+ (isEraser && !isBgEraser) || bs.isTransparentInk ? undefined : bs.brushCombineMode;
const compositeOp: 'source-over' | 'destination-out' | 'source-atop' =
- (isEraser && !isBgEraser) || bs.isTransparentInk
+ (isEraser && !isBgEraser) || bs.isTransparentInk || effectiveBrushCombineMode === 'clear'
? 'destination-out'
: activeLayer?.alphaLocked
? 'source-atop'
: 'source-over';
+ const normWetAlphaPower = normalizeWetEdgePower01(bs.wetEdgeAlphaPower, 0.25);
+ const normWetValuePower = normalizeWetEdgePower01(bs.wetEdgeValuePower, 0.15);
const monoOpts =
targetFormat === 'monochrome-1bit'
? {
@@ -124,6 +135,17 @@ export function commitRasterStrokeToTiles(
const selMaskOpts = activeSelection?.mask
? { mask: activeSelection.mask, bounds: activeSelection.bounds }
: null;
+ const pigmentStrength = resolveStrokePigmentStrength(
+ bs,
+ isEraser,
+ isBgEraser,
+ isMonochrome
+ );
+ const pigmentWhiteGround =
+ pigmentStrength > 0.005
+ ? draftCanvas?.__draftPigmentWhiteGround ??
+ detectWhitePaperGround(allLayers, currentLayerId, grid)
+ : false;
const draftOriginX = draftDocRect ? Math.round(draftDocRect.x) : 0;
const draftOriginY = draftDocRect ? Math.round(draftDocRect.y) : 0;
@@ -135,7 +157,9 @@ export function commitRasterStrokeToTiles(
Math.abs(draftDocRect.x - draftOriginX) < 1e-6 &&
Math.abs(draftDocRect.y - draftOriginY) < 1e-6 &&
!hasWetEdge &&
- !bs.colorMixing &&
+ !isRibbonBrush(bs) &&
+ !(state.isDualBrushStroke && Boolean(resolveDualBrushConfig(bs)?.isRibbon)) &&
+ !(state.isStrokePaperTextureActive && Boolean(bs.opacitySensor?.usePressure)) &&
(bs.postCorrection ?? 0) === 0 &&
!shouldTaper &&
sx >= draftOriginX &&
@@ -190,7 +214,10 @@ export function commitRasterStrokeToTiles(
destY: sp.y,
format: targetFormat,
compositeOp,
+ brushCombineMode: effectiveBrushCombineMode,
opacity: bs.opacity ?? 1.0,
+ pigmentStrength,
+ pigmentWhiteGround,
monochrome: monoOpts,
selectionMask: selMaskOpts,
snapshotOut: beforeSnapshot,
@@ -228,6 +255,9 @@ export function commitRasterStrokeToTiles(
activeLayer,
targetFormat,
compositeOp,
+ brushCombineMode: effectiveBrushCombineMode,
+ pigmentStrength,
+ pigmentWhiteGround,
monoOpts,
selMaskOpts,
isEraser,
@@ -243,123 +273,23 @@ export function commitRasterStrokeToTiles(
});
}
- 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,
- exitSpeed
- );
- 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;
+ // Isolated 1:1 re-bake onto a clean transparent surface for BOTH standard and color-mixing brushes.
+ // Accumulating low-alpha dabs on a transparent bakeCanvas (matching live draftCanvas) and
+ // compositing once via grid.compositeStrokeToTiles avoids 8-bit rounding wipeout of faint strokes
+ // over opaque backgrounds/paint, skips unpacking existing tiles via createRegionCanvas, and
+ // supports Watercolor Edge, BrushCombineMode, Alpha Lock, Selection Masks, and 1-bit monochrome.
+ const bakeCanvas = getReusableBakeCanvas(dw, dh);
+ const bCtx = get2DContext(bakeCanvas);
+ if (!bCtx) return null;
- rCtx.save();
- rCtx.translate(-sx, -sy);
- rCtx.beginPath();
- rCtx.rect(sx, sy, dw, dh);
- rCtx.clip();
- applySelectionCanvasClip(rCtx, activeSelection);
+ 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,
@@ -370,108 +300,71 @@ export function commitRasterStrokeToTiles(
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,
- exitSpeed
- );
- } 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,
- exitSpeed
- );
- 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);
- }
- }
+ const bakeSampler =
+ bs.colorMixing && !isEraser
+ ? new LayerPixelSampler(dims, currentLayerId, grid)
+ : undefined;
- rCtx.restore();
+ renderCompleteStroke(
+ bCtx,
+ allPoints,
+ {
+ ...bakeBs,
+ opacity: 1.0,
+ isTransparentInk: false,
+ wetEdge: 0,
+ brushCombineMode: undefined,
+ color: isEraser && !isBgEraser ? '#000000' : bakeBs.color,
+ },
+ isEraser && !isBgEraser ? 'brush' : currentTool,
+ effectiveMode,
+ isBgEraser,
+ undefined,
+ false,
+ bakeSampler,
+ allowGpuMonoBake,
+ exitSpeed
+ );
+ bCtx.restore();
- if (beforeSelectionData && activeSelection?.mask) {
- const fullAfter = rCtx.getImageData(0, 0, dw, dh);
- applySelectionMaskToImageData(beforeSelectionData, fullAfter, sx, sy, activeSelection);
- rCtx.putImageData(fullAfter, 0, 0);
+ if (hasWetEdge) {
+ const bakeImg = bCtx.getImageData(0, 0, dw, dh);
+ applyCspWatercolorEdge(
+ bakeImg,
+ bs.wetEdge ?? 0,
+ bs.wetEdgeRadius ?? 3.0,
+ normWetAlphaPower,
+ normWetValuePower
+ );
+ bCtx.putImageData(bakeImg, 0, 0);
}
- const spans = helpers.buildTouchedTileSpans(sx, sy, dw, dh);
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 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);
+ 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,
+ brushCombineMode: effectiveBrushCombineMode,
+ opacity: bakeBs.opacity ?? 1.0,
+ pigmentStrength,
+ pigmentWhiteGround,
+ monochrome: monoOpts,
+ selectionMask: selMaskOpts,
+ snapshotOut: beforeSnapshot,
+ suppressNotify: true,
+ });
}
return createRasterPostPresentWork(
diff --git a/src/hooks/drawing/brushStrokeSession/strokeHelpers.ts b/src/hooks/drawing/brushStrokeSession/strokeHelpers.ts
index cd3fb31..ea3d24f 100644
--- a/src/hooks/drawing/brushStrokeSession/strokeHelpers.ts
+++ b/src/hooks/drawing/brushStrokeSession/strokeHelpers.ts
@@ -9,12 +9,19 @@ import {
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 {
+ BrushRenderOptions,
+ applyStrokePaperTextureToImageData,
+ buildBrushRenderOptions,
+ combineDualBrushImageData,
+ resolveDualBrushConfig,
+} 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 { isPigmentCompatibleCombineMode } from '../../../utils/pigmentEngine';
+import { DraftCanvasElement, applySelectionCanvasClip } from '../types';
import { StrokeSessionState, TouchedTileSpan, UseBrushStrokeSessionParams } from './types';
export function getPredictedCanvasElement(
@@ -130,6 +137,27 @@ export function dispatchPointerStatThrottled(
}
}
+export function resetAndClearOffscreenDraftCanvas(
+ canvas: DraftCanvasElement | null | undefined
+): void {
+ if (!canvas) return;
+ const ctx = get2DContext(canvas);
+ if (ctx) {
+ if (canvas.__clipSaved) {
+ try {
+ ctx.restore();
+ } catch {
+ // Ignore restore underflow
+ }
+ canvas.__clipSaved = false;
+ }
+ ctx.resetTransform();
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ } else {
+ canvas.__clipSaved = false;
+ }
+}
+
export function abortActiveStrokeSession(
params: Pick<
UseBrushStrokeSessionParams,
@@ -152,13 +180,18 @@ export function abortActiveStrokeSession(
if (draftCanvas) {
const dCtx = get2DContext(draftCanvas);
if (dCtx) {
- try {
- dCtx.restore();
- } catch {
- // Ignore restore underflow
+ if (draftCanvas.__clipSaved) {
+ try {
+ dCtx.restore();
+ } catch {
+ // Ignore restore underflow
+ }
+ draftCanvas.__clipSaved = false;
}
dCtx.resetTransform();
dCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
+ } else {
+ draftCanvas.__clipSaved = false;
}
if (draftCanvas.__draftHasContent) {
clearedActiveDraft = true;
@@ -166,8 +199,16 @@ export function abortActiveStrokeSession(
draftCanvas.__draftHasContent = false;
draftCanvas.__draftCompositeOp = 'source-over';
draftCanvas.__draftMonochrome = false;
+ draftCanvas.__draftPigmentStrength = 0;
+ draftCanvas.__draftPigmentWhiteGround = false;
+ draftCanvas.__draftCombineMode = undefined;
+ draftCanvas.__draftFrameDirtyRect = null;
+ draftCanvas.__draftForceFullUpload = true;
draftCanvas.__draftVersion = (draftCanvas.__draftVersion || 0) + 1;
}
+ resetAndClearOffscreenDraftCanvas(state.rawDraftCanvas as DraftCanvasElement | null);
+ resetAndClearOffscreenDraftCanvas(state.dualPrimaryCanvas as DraftCanvasElement | null);
+ resetAndClearOffscreenDraftCanvas(state.dualSecondaryCanvas as DraftCanvasElement | null);
clearPredictedCanvas();
if (clearedActiveDraft) {
params.activeTileGridRef.current.notifyChange(true);
@@ -191,12 +232,23 @@ export function abortActiveStrokeSession(
state.touchedTiles.clear();
state.liveNeedsNotify = false;
state.isShiftLineStroke = false;
+ state.deferredInitialDot = false;
+ state.deferredStartRawPressure = 0;
state.layerPixelSampler = null;
state.activeReservoir = null;
+ state.isStrokePaperTextureActive = false;
+ state.isDualBrushStroke = false;
+ state.dualSecondaryRemainderDist = 0;
+ state.dualSecondaryDabCounter.count = 0;
+ state.dualSecondaryDabCounter.lastAngle = undefined;
+ state.dualSecondaryDabCounter.lastStepDist = undefined;
+ state.dualSecondaryRibbonSession = null;
+ state.dualFrameSecondaryGpuDabs.length = 0;
if (state.naturalPaintSession) {
state.naturalPaintSession.finishAndDispose();
state.naturalPaintSession = null;
}
+ state.ribbonSession = null;
state.snapSession.endStroke();
state.straightSnapSession.endStroke();
emitConstraintAxisChange(null);
@@ -261,6 +313,26 @@ export function computeCanvasPoint(
};
}
+export function resolveStrokePigmentStrength(
+ bs: BrushSettings,
+ isEraser: boolean,
+ isBgEraser: boolean,
+ isMonochrome: boolean
+): number {
+ if (
+ isEraser ||
+ isBgEraser ||
+ isMonochrome ||
+ bs.isTransparentInk ||
+ bs.perceptualMixing === false ||
+ !isPigmentCompatibleCombineMode(bs.brushCombineMode)
+ ) {
+ return 0;
+ }
+ const raw = bs.naturalPaint?.pigmentMixingStrength ?? 1.0;
+ return raw <= 0.005 ? 0 : raw >= 1 ? 1 : raw;
+}
+
export function resolveEffectiveOpacitySensorValue(
bs: BrushSettings,
isMonochrome: boolean,
@@ -372,9 +444,248 @@ export function createLiveBrushOptions(
alphaLocked: isolatedPass ? false : Boolean(activeLayer?.alphaLocked),
isTransparentInk: isolatedPass ? false : Boolean(bs.isTransparentInk),
currentStrokeDist: state.strokeTotalDistance,
+ skipPerDabPaperGrain: state.isStrokePaperTextureActive ? true : undefined,
+ ...(state.isDualBrushStroke ? { dualBrush: false, dualBrushConfig: undefined } : {}),
});
}
+function configureMatchedOffscreenCanvas(
+ canvas: DraftCanvasElement,
+ draftCanvas: DraftCanvasElement,
+ dims: CanvasDimensions,
+ selection: UseBrushStrokeSessionParams['selectionRef']['current']
+): CanvasRenderingContext2D | null {
+ const resized = canvas.width !== draftCanvas.width || canvas.height !== draftCanvas.height;
+ if (resized) {
+ canvas.width = draftCanvas.width;
+ canvas.height = draftCanvas.height;
+ canvas.__clipSaved = false;
+ }
+ const ctx = get2DContext(canvas);
+ if (!ctx) return null;
+
+ if (!resized && canvas.__clipSaved) {
+ try {
+ ctx.restore();
+ } catch {
+ // Ignore restore underflow
+ }
+ canvas.__clipSaved = false;
+ }
+
+ const draftScale = draftCanvas.__draftScale ?? 1.0;
+ const docRect = draftCanvas.__draftDocRect;
+ const visMinX = docRect ? docRect.x : 0;
+ const visMinY = docRect ? docRect.y : 0;
+
+ ctx.resetTransform();
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ ctx.setTransform(
+ draftScale,
+ 0,
+ 0,
+ draftScale,
+ -visMinX * draftScale,
+ -visMinY * draftScale
+ );
+ ctx.save();
+ canvas.__clipSaved = true;
+ ctx.beginPath();
+ ctx.rect(0, 0, dims.width, dims.height);
+ ctx.clip();
+ applySelectionCanvasClip(ctx, selection);
+ return ctx;
+}
+
+/**
+ * Prepares paired primary and secondary draft surfaces for live two-pass Dual Brush rendering,
+ * matching draftCanvas's exact dimensions, transform, and selection clip.
+ */
+export function prepareDualDraftCanvases(
+ state: StrokeSessionState,
+ draftCanvas: DraftCanvasElement,
+ dims: CanvasDimensions,
+ selection: UseBrushStrokeSessionParams['selectionRef']['current']
+): { primaryCtx: CanvasRenderingContext2D; secondaryCtx: CanvasRenderingContext2D } | null {
+ if (typeof document === 'undefined') return null;
+ if (!state.dualPrimaryCanvas) {
+ state.dualPrimaryCanvas = document.createElement('canvas');
+ }
+ if (!state.dualSecondaryCanvas) {
+ state.dualSecondaryCanvas = document.createElement('canvas');
+ }
+ const primaryCtx = configureMatchedOffscreenCanvas(
+ state.dualPrimaryCanvas,
+ draftCanvas,
+ dims,
+ selection
+ );
+ const secondaryCtx = configureMatchedOffscreenCanvas(
+ state.dualSecondaryCanvas,
+ draftCanvas,
+ dims,
+ selection
+ );
+ if (!primaryCtx || !secondaryCtx) return null;
+ return { primaryCtx, secondaryCtx };
+}
+
+/**
+ * Builds BrushRenderOptions for the live secondary Dual Brush pass.
+ */
+export function buildLiveSecondaryBrushOptions(
+ secSettings: BrushSettings,
+ isMonochrome: boolean,
+ effectiveAntiAlias: number | undefined,
+ currentStrokeDist: number
+): BrushRenderOptions {
+ return buildBrushRenderOptions(secSettings, {
+ opacity: 1.0,
+ flow: secSettings.flow ?? 1.0,
+ spacing: secSettings.spacing ?? 0.1,
+ hardness: secSettings.hardness ?? 1.0,
+ antiAlias:
+ effectiveAntiAlias !== undefined ? effectiveAntiAlias : isMonochrome ? 0 : secSettings.antiAlias,
+ wetEdge: 0,
+ grain: 0,
+ textureDensity: 0,
+ colorMixing: false,
+ dualBrush: false,
+ dualBrushConfig: undefined,
+ isEraser: false,
+ isBgEraser: false,
+ alphaLocked: false,
+ isTransparentInk: false,
+ currentStrokeDist,
+ });
+}
+
+/**
+ * Combines the newly-updated document-space dirty rect from paired
+ * (dualPrimaryCanvas, dualSecondaryCanvas) -> draftCanvas using CSP Dual Brush semantics
+ * (plus per-stroke paper texture if active).
+ */
+export function syncDualBrushRegionToDraft(
+ state: StrokeSessionState,
+ draftCanvas: DraftCanvasElement,
+ draftCtx: CanvasRenderingContext2D,
+ bs: BrushSettings,
+ minDocX: number,
+ minDocY: number,
+ maxDocX: number,
+ maxDocY: number
+): void {
+ const dualCfg = resolveDualBrushConfig(bs);
+ if (!dualCfg) return;
+ const primary = state.dualPrimaryCanvas;
+ const secondary = state.dualSecondaryCanvas;
+ if (!primary || !secondary || primary.width <= 0 || primary.height <= 0) return;
+ const pCtx = get2DContext(primary);
+ const sCtx = get2DContext(secondary);
+ if (
+ !pCtx ||
+ !sCtx ||
+ typeof pCtx.getImageData !== 'function' ||
+ typeof sCtx.getImageData !== 'function' ||
+ typeof draftCtx.putImageData !== 'function'
+ ) {
+ return;
+ }
+
+ const draftScale = draftCanvas.__draftScale ?? 1.0;
+ const docRect = draftCanvas.__draftDocRect;
+ const originX = docRect ? docRect.x : 0;
+ const originY = docRect ? docRect.y : 0;
+
+ const px0 = Math.max(0, Math.floor((minDocX - originX) * draftScale));
+ const py0 = Math.max(0, Math.floor((minDocY - originY) * draftScale));
+ const px1 = Math.min(primary.width, Math.ceil((maxDocX - originX) * draftScale));
+ const py1 = Math.min(primary.height, Math.ceil((maxDocY - originY) * draftScale));
+ const pw = px1 - px0;
+ const ph = py1 - py0;
+ if (pw <= 0 || ph <= 0) return;
+
+ const primaryImg = pCtx.getImageData(px0, py0, pw, ph);
+ const secondaryImg = sCtx.getImageData(px0, py0, pw, ph);
+ combineDualBrushImageData(
+ primaryImg.data,
+ secondaryImg.data,
+ primaryImg.data,
+ dualCfg.compositeMode
+ );
+
+ if (state.isStrokePaperTextureActive) {
+ const worldStartX = originX + px0 / Math.max(1e-4, draftScale);
+ const worldStartY = originY + py0 / Math.max(1e-4, draftScale);
+ applyStrokePaperTextureToImageData(primaryImg, worldStartX, worldStartY, bs, draftScale);
+ }
+
+ draftCtx.putImageData(primaryImg, px0, py0);
+}
+
+/**
+ * Prepares the untextured raw stroke accumulation canvas for CSP per-stroke paper texture
+ * (TextureForPlot = 0), matching draftCanvas's exact dimensions, transform, and clip.
+ */
+export function prepareRawDraftCanvasForStrokeTexture(
+ state: StrokeSessionState,
+ draftCanvas: DraftCanvasElement,
+ dims: CanvasDimensions,
+ selection: UseBrushStrokeSessionParams['selectionRef']['current']
+): CanvasRenderingContext2D | null {
+ if (typeof document === 'undefined') return null;
+ if (!state.rawDraftCanvas) {
+ state.rawDraftCanvas = document.createElement('canvas');
+ }
+ return configureMatchedOffscreenCanvas(
+ state.rawDraftCanvas as DraftCanvasElement,
+ draftCanvas,
+ dims,
+ selection
+ );
+}
+
+/**
+ * Copies a newly-updated document-space dirty rect from rawDraftCanvas -> draftCanvas
+ * while applying CSP per-stroke paper texture ONCE over the accumulated stroke alpha.
+ */
+export function syncStrokePaperTextureRegionToDraft(
+ state: StrokeSessionState,
+ draftCanvas: DraftCanvasElement,
+ draftCtx: CanvasRenderingContext2D,
+ bs: BrushSettings,
+ minDocX: number,
+ minDocY: number,
+ maxDocX: number,
+ maxDocY: number
+): void {
+ const raw = state.rawDraftCanvas;
+ if (!raw || raw.width <= 0 || raw.height <= 0) return;
+ const rCtx = get2DContext(raw);
+ if (!rCtx || typeof rCtx.getImageData !== 'function' || typeof draftCtx.putImageData !== 'function') {
+ return;
+ }
+
+ const draftScale = draftCanvas.__draftScale ?? 1.0;
+ const docRect = draftCanvas.__draftDocRect;
+ const originX = docRect ? docRect.x : 0;
+ const originY = docRect ? docRect.y : 0;
+
+ const px0 = Math.max(0, Math.floor((minDocX - originX) * draftScale));
+ const py0 = Math.max(0, Math.floor((minDocY - originY) * draftScale));
+ const px1 = Math.min(raw.width, Math.ceil((maxDocX - originX) * draftScale));
+ const py1 = Math.min(raw.height, Math.ceil((maxDocY - originY) * draftScale));
+ const pw = px1 - px0;
+ const ph = py1 - py0;
+ if (pw <= 0 || ph <= 0) return;
+
+ const imgData = rCtx.getImageData(px0, py0, pw, ph);
+ const worldStartX = originX + px0 / Math.max(1e-4, draftScale);
+ const worldStartY = originY + py0 / Math.max(1e-4, draftScale);
+ applyStrokePaperTextureToImageData(imgData, worldStartX, worldStartY, bs, draftScale);
+ draftCtx.putImageData(imgData, px0, py0);
+}
+
export function resolveStrokeColorValue(
isMaskMode: boolean,
bs: BrushSettings,
diff --git a/src/hooks/drawing/brushStrokeSession/types.ts b/src/hooks/drawing/brushStrokeSession/types.ts
index ad8def5..12dee21 100644
--- a/src/hooks/drawing/brushStrokeSession/types.ts
+++ b/src/hooks/drawing/brushStrokeSession/types.ts
@@ -16,6 +16,7 @@ import { CubicBezierSegment } from '../../../engine/SplineGenerator';
import { BrushRenderOptions } from '../../../engine/BrushEngine';
import { GpuDab } from '../../../engine/WebGlBrushEngine';
import { NaturalPaintStrokeSession } from '../../../engine/NaturalPaintRenderer';
+import { RibbonStrokeSession } from '../../../engine/RibbonBrushEngine';
import { PaintReservoir, LayerPixelSampler } from '../../../utils/colorMixingEngine';
import { PerspectiveRuler, StraightRuler, ConstraintAxis } from '../../../types/perspective';
import { PerspectiveSnapSession } from '../../../utils/perspectiveSnapping';
@@ -138,6 +139,22 @@ export interface StrokeSessionState {
strokePipeline: StrokePipeline;
frameGpuDabs: GpuDab[];
reusableRegionCanvas: HTMLCanvasElement | null;
+ rawDraftCanvas: HTMLCanvasElement | null;
+ isStrokePaperTextureActive: boolean;
+ isDualBrushStroke: boolean;
+ dualPrimaryCanvas: HTMLCanvasElement | null;
+ dualSecondaryCanvas: HTMLCanvasElement | null;
+ dualSecondaryRemainderDist: number;
+ dualSecondaryDabCounter: {
+ count: number;
+ lastAngle?: number;
+ lastStepDist?: number;
+ lockedInitialAngle?: number;
+ initOriginX?: number;
+ initOriginY?: number;
+ };
+ dualSecondaryRibbonSession: RibbonStrokeSession | null;
+ dualFrameSecondaryGpuDabs: GpuDab[];
scratchDocCoord: { x: number; y: number };
predCoordPool: Array<{ x: number; y: number; pressure?: number }>;
predDocCoords: Array<{ x: number; y: number; pressure?: number }>;
@@ -145,14 +162,24 @@ export interface StrokeSessionState {
lastQueuedPressure: number;
stabilizedPoint: Point | null;
stampRemainderDist: number;
- liveDabCounter: { count: number; lastAngle?: number; lastStepDist?: number };
+ liveDabCounter: {
+ count: number;
+ lastAngle?: number;
+ lastStepDist?: number;
+ lockedInitialAngle?: number;
+ initOriginX?: number;
+ initOriginY?: number;
+ };
activeReservoir: PaintReservoir | null;
layerPixelSampler: LayerPixelSampler | null;
naturalPaintSession: NaturalPaintStrokeSession | null;
+ ribbonSession: RibbonStrokeSession | null;
naturalStrokeSeed: number;
isWetColorStroke: boolean;
liveNeedsNotify: boolean;
isShiftLineStroke: boolean;
+ deferredInitialDot: boolean;
+ deferredStartRawPressure: number;
lastPointTime: number;
recentPointsTrail: RecentPointSample[];
strokeTotalDistance: number;
@@ -180,6 +207,15 @@ export function createInitialStrokeSessionState(): StrokeSessionState {
strokePipeline: new StrokePipeline(),
frameGpuDabs: [],
reusableRegionCanvas: null,
+ rawDraftCanvas: null,
+ isStrokePaperTextureActive: false,
+ isDualBrushStroke: false,
+ dualPrimaryCanvas: null,
+ dualSecondaryCanvas: null,
+ dualSecondaryRemainderDist: 0,
+ dualSecondaryDabCounter: { count: 0 },
+ dualSecondaryRibbonSession: null,
+ dualFrameSecondaryGpuDabs: [],
scratchDocCoord: { x: 0, y: 0 },
predCoordPool: [
{ x: 0, y: 0, pressure: 0.5 },
@@ -196,10 +232,13 @@ export function createInitialStrokeSessionState(): StrokeSessionState {
activeReservoir: null,
layerPixelSampler: null,
naturalPaintSession: null,
+ ribbonSession: null,
naturalStrokeSeed: 1337,
isWetColorStroke: false,
liveNeedsNotify: false,
isShiftLineStroke: false,
+ deferredInitialDot: false,
+ deferredStartRawPressure: 0,
lastPointTime: 0,
recentPointsTrail: [],
strokeTotalDistance: 0,
@@ -229,7 +268,8 @@ export type EmitLiveSegmentFn = (
useWireframeEraser: boolean,
canvas: HTMLCanvasElement | null,
activeLayer: LayerItem | undefined,
- gpuBatch: GpuDab[] | undefined
+ gpuBatch: GpuDab[] | undefined,
+ precomputedBrushOpts?: BrushRenderOptions
) => void;
export type BuildLiveBrushOptionsFn = (
diff --git a/src/hooks/drawing/types.ts b/src/hooks/drawing/types.ts
index bfa39a0..91ce758 100644
--- a/src/hooks/drawing/types.ts
+++ b/src/hooks/drawing/types.ts
@@ -2,6 +2,7 @@ import React from 'react';
import {
ToolType,
BrushSettings,
+ CspBrushCombineMode,
Point,
CanvasDimensions,
CanvasSelection,
@@ -24,7 +25,13 @@ export interface DraftCanvasElement extends HTMLCanvasElement {
__draftDocRect?: { x: number; y: number; width: number; height: number };
__draftScale?: number;
__draftMonochrome?: boolean;
+ __draftPigmentStrength?: number;
+ __draftPigmentWhiteGround?: boolean;
+ __draftCombineMode?: CspBrushCombineMode;
__draftVersion?: number;
+ __draftFrameDirtyRect?: { x: number; y: number; width: number; height: number } | null;
+ __draftForceFullUpload?: boolean;
+ __clipSaved?: boolean;
__isBlank?: boolean;
__isSolidWhite?: boolean;
}
diff --git a/src/hooks/drawing/useBrushStrokeSession.ts b/src/hooks/drawing/useBrushStrokeSession.ts
index 892dc48..a071fe8 100644
--- a/src/hooks/drawing/useBrushStrokeSession.ts
+++ b/src/hooks/drawing/useBrushStrokeSession.ts
@@ -14,10 +14,13 @@ import { useToolStore, toolStoreActions } from '../../stores';
import { recoveryService } from '../../services/recoveryService';
import { isNativeRustAvailable } from '../../utils/nativeBackend';
import {
- NativeTabletSample,
startNativeTablet,
subscribeNativeTablet,
} from '../../utils/nativeTabletInput';
+import {
+ NativeTabletBridgeState,
+ processNativeTabletBatch,
+} from './brushStrokeSession/nativeTabletBridge';
import {
StrokeSessionHelpers,
StrokeSessionState,
@@ -174,6 +177,11 @@ export function useBrushStrokeSession(
[]
);
+ const nativeBridgeStateRef = useRef<NativeTabletBridgeState>({
+ nativeStrokeActive: false,
+ prevToolBeforeEraserFlip: null,
+ });
+
const abortActiveStroke = useCallback(() => {
abortActiveStrokeSession(
{ isDrawingRef, effectiveDraftCanvasRef, activeTileGridRef, interactionRef },
@@ -181,6 +189,13 @@ export function useBrushStrokeSession(
clearPredictedCanvas,
emitConstraintAxisChange
);
+ const bridge = nativeBridgeStateRef.current;
+ bridge.nativeStrokeActive = false;
+ if (bridge.prevToolBeforeEraserFlip !== null) {
+ const prev = bridge.prevToolBeforeEraserFlip;
+ bridge.prevToolBeforeEraserFlip = null;
+ toolStoreActions.selectTool(prev);
+ }
}, [
activeTileGridRef,
clearPredictedCanvas,
@@ -279,7 +294,8 @@ export function useBrushStrokeSession(
useWireframeEraser: boolean,
canvas: HTMLCanvasElement | null,
activeLayer: LayerItem | undefined,
- gpuBatch: GpuDab[] | undefined
+ gpuBatch: GpuDab[] | undefined,
+ precomputedBrushOpts?: BrushRenderOptions
) => {
emitLiveSegmentToDraft(
sessionStateRef.current!,
@@ -298,7 +314,8 @@ export function useBrushStrokeSession(
useWireframeEraser,
canvas,
activeLayer,
- gpuBatch
+ gpuBatch,
+ precomputedBrushOpts
);
},
[]
@@ -392,9 +409,9 @@ export function useBrushStrokeSession(
useEffect(() => {
if (!isNativeRustAvailable()) return;
- const NATIVE_PEN_POINTER_ID = -1001;
- let nativeStrokeActive = false;
- let prevToolBeforeEraserFlip: ToolType | null = null;
+ const bridgeState = nativeBridgeStateRef.current;
+ bridgeState.nativeStrokeActive = false;
+ bridgeState.prevToolBeforeEraserFlip = null;
const modKeys = { shift: false, alt: false };
const onKeyDown = (ev: KeyboardEvent) => {
@@ -408,30 +425,6 @@ export function useBrushStrokeSession(
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 isPointOverCanvasViewport = (x: number, y: number): boolean => {
const vp = viewportRef.current;
if (!vp) return false;
@@ -452,61 +445,21 @@ export function useBrushStrokeSession(
const helpers = helpersRef.current;
if (!state || !helpers) return;
- const curTool = helpers.getTool();
- const isBrushOrEraser = curTool === 'brush' || curTool === 'eraser';
-
- let i = 0;
- while (i < batch.length) {
- const s = batch[i];
-
- if (s.phase === 1) {
- // Pen down
- if (
- !paramsRef.current.disabled &&
- isBrushOrEraser &&
- isPointOverCanvasViewport(s.clientX, s.clientY)
- ) {
- const isTailEraser = (s.buttons & 8) !== 0;
- if (isTailEraser && curTool !== 'eraser') {
- prevToolBeforeEraserFlip = curTool;
- toolStoreActions.selectTool('eraser');
- }
- 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);
- }
- }
- 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);
- }
- i++;
- }
- }
+ processNativeTabletBatch(batch, bridgeState, modKeys, {
+ getTool: helpers.getTool,
+ selectTool: (tool) => toolStoreActions.selectTool(tool),
+ isDisabled: () => paramsRef.current.disabled,
+ isStrokeActive: () => paramsRef.current.isDrawingRef.current,
+ isPointOverCanvasViewport,
+ onPointerDown: (evt) => runPointerDown(state, paramsRef.current, helpers, evt),
+ onPointerMove: (lastEvt, coalesced) =>
+ runPointerMove(state, paramsRef.current, helpers, lastEvt, coalesced),
+ onPointerUp: (evt) => runPointerUp(state, paramsRef.current, helpers, evt),
+ onHover: (evt) => {
+ const pt = helpers.getCanvasPoint(evt);
+ helpers.dispatchPointerStat(pt.x, pt.y, pt.pressure);
+ },
+ });
});
return () => {
diff --git a/src/hooks/drawing/useDrawingHistory.ts b/src/hooks/drawing/useDrawingHistory.ts
index 0698d6d..0379293 100644
--- a/src/hooks/drawing/useDrawingHistory.ts
+++ b/src/hooks/drawing/useDrawingHistory.ts
@@ -119,6 +119,8 @@ export function useDrawingHistory({
const historyRef = useRef<HistoryItem[]>(initialSession ? initialSession.history : []);
const historyIndexRef = useRef<number>(initialSession ? initialSession.historyIndex : -1);
const historyQueueRef = useRef<Promise<void>>(Promise.resolve());
+ const inFlightHistoryOpsRef = useRef<number>(0);
+ const pendingTargetIndexRef = useRef<number | null>(null);
const [historyList, setHistoryList] = useState<HistoryItemMeta[]>([]);
const [historyIndex, setHistoryIndex] = useState<number>(-1);
@@ -337,6 +339,7 @@ export function useDrawingHistory({
historyRef.current = newHistory;
historyIndexRef.current = newHistory.length - 1;
+ pendingTargetIndexRef.current = null;
persistSessionHistory(docId);
if (dims.width > 0 && dims.height > 0) {
@@ -457,12 +460,251 @@ export function useDrawingHistory({
[isDrawingRef]
);
+ const applySingleHistoryStep = useCallback(
+ (
+ item: HistoryItem,
+ deltas: TileDelta[] | null,
+ direction: 'undo' | 'redo',
+ grid: SparseTileGrid,
+ dims: CanvasDimensions
+ ) => {
+ const targetLayerId = item.layerId || activeLayerId;
+ const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);
+ const dataToApply =
+ direction === 'undo' ? item.beforeImageData : item.afterImageData || item.imageData;
+
+ if (item.layerTreeDelta) {
+ const applied = onApplyLayerTreeDeltaRef?.current?.(item.layerTreeDelta, direction);
+ if (applied) {
+ layersRef.current = applied.nextLayers;
+ if (applied.nextActiveLayerId !== null) {
+ activeLayerIdRef.current = applied.nextActiveLayerId;
+ }
+ }
+ if (deltas && deltas.length > 0) {
+ grid.applyTileDeltas(deltas, direction);
+ if (multiplayerService.isConnected()) {
+ multiplayerService.sendTileDeltas(deltas, grid, { force: true });
+ }
+ }
+ const liveLayerIds = new Set((layersRef.current ?? []).map((l) => l.id));
+ const affectedLayerIds = new Set<string>();
+ if (deltas) {
+ for (const d of deltas) {
+ affectedLayerIds.add(parseTileKey(d.key).layerId);
+ }
+ }
+ if (applied) {
+ for (const added of applied.addedLayers) {
+ affectedLayerIds.add(added.id);
+ }
+ }
+ for (const lid of affectedLayerIds) {
+ if (lid !== targetLayerId && liveLayerIds.has(lid)) {
+ onUpdateLayerThumbnail(lid, true);
+ }
+ }
+ grid.notifyChange(true);
+ } else if (item.isMaskEdit && targetLayer?.maskCanvas) {
+ const mCtx = get2DContext(targetLayer.maskCanvas);
+ if (mCtx && dataToApply) {
+ const mx =
+ item.dirtyRect && dataToApply.width === item.dirtyRect.width ? item.dirtyRect.x : 0;
+ const my =
+ item.dirtyRect && dataToApply.height === item.dirtyRect.height ? item.dirtyRect.y : 0;
+ 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 =
+ direction === 'undo' ? item.vectorStrokesDelta.before : item.vectorStrokesDelta.after;
+ 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);
+ }
+ }
+ if (multiplayerService.isConnected()) {
+ multiplayerService.sendLayerUpdate(targetLayerId, {
+ vectorStrokes: targetLayer.vectorStrokes,
+ });
+ }
+ } else if (deltas && deltas.length > 0) {
+ grid.applyTileDeltas(deltas, direction);
+ 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);
+ }
+ for (const lid of affectedLayerIds) {
+ if (lid !== targetLayerId) {
+ onUpdateLayerThumbnail(lid, true);
+ }
+ }
+ } else {
+ const isMono =
+ !isBackgroundLayerId(targetLayerId) &&
+ (targetLayer?.expressionColor === 'monochrome' ||
+ colorModeRef.current === 'monochrome');
+ const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
+
+ if (dataToApply) {
+ const ax =
+ item.dirtyRect &&
+ dataToApply.width === item.dirtyRect.width &&
+ dataToApply.height === item.dirtyRect.height
+ ? item.dirtyRect.x
+ : 0;
+ const ay =
+ item.dirtyRect &&
+ dataToApply.width === item.dirtyRect.width &&
+ dataToApply.height === item.dirtyRect.height
+ ? item.dirtyRect.y
+ : 0;
+ grid.writeImageData(targetLayerId, dataToApply, ax, ay, targetFormat);
+ } else if (item.type === 'initial') {
+ if (isBackgroundLayerId(targetLayerId)) {
+ grid.fillLayerSolidWhite(targetLayerId, dims.width, dims.height, 'color-32bit');
+ } else {
+ grid.clearLayer(targetLayerId);
+ }
+ }
+ }
+
+ if (
+ !item.layerTreeDelta ||
+ (layersRef.current ?? []).some((l) => l.id === targetLayerId)
+ ) {
+ onUpdateLayerThumbnail(targetLayerId, true);
+ }
+ },
+ [
+ activeLayerId,
+ activeLayerIdRef,
+ colorModeRef,
+ layersRef,
+ onApplyLayerTreeDeltaRef,
+ onUpdateLayerThumbnail,
+ onUpdateMaskThumbnailRef,
+ ]
+ );
+
const jumpToHistoryIndex = useCallback(
(targetIndex: number): Promise<void> => {
flushPendingHistoryTasks();
if (isDrawingRef.current) {
abortActiveStrokeRef.current();
}
+ lastStrokeEndRef.current = null;
+
+ // Fast synchronous path when no async history job is in flight and every touched step is
+ // already resident in RAM (eliminates Ctrl+Z -> quick-draw race conditions).
+ if (inFlightHistoryOpsRef.current === 0) {
+ if (targetIndex < 0 || targetIndex >= historyRef.current.length) {
+ return Promise.resolve();
+ }
+ const currentIndex = historyIndexRef.current;
+ if (targetIndex === currentIndex) {
+ return Promise.resolve();
+ }
+
+ const undoCache = activeUndoCacheRef.current;
+ let canRunSync = true;
+ if (targetIndex < currentIndex) {
+ for (let i = currentIndex; i > targetIndex; i--) {
+ const item = historyRef.current[i];
+ if (item && !undoCache.canResolveDeltasSync(item)) {
+ canRunSync = false;
+ break;
+ }
+ }
+ } else {
+ for (let i = currentIndex + 1; i <= targetIndex; i++) {
+ const item = historyRef.current[i];
+ if (item && !undoCache.canResolveDeltasSync(item)) {
+ canRunSync = false;
+ break;
+ }
+ }
+ }
+
+ if (canRunSync) {
+ const grid = activeTileGridRef.current;
+ const dims = dimensionsRef.current;
+ if (targetIndex < currentIndex) {
+ for (let i = currentIndex; i > targetIndex; i--) {
+ const item = historyRef.current[i];
+ if (item) {
+ const deltas = undoCache.resolveDeltasSync(item);
+ applySingleHistoryStep(item, deltas, 'undo', grid, dims);
+ }
+ }
+ } else {
+ for (let i = currentIndex + 1; i <= targetIndex; i++) {
+ const item = historyRef.current[i];
+ if (item) {
+ const deltas = undoCache.resolveDeltasSync(item);
+ applySingleHistoryStep(item, deltas, 'redo', grid, dims);
+ }
+ }
+ }
+ historyIndexRef.current = targetIndex;
+ pendingTargetIndexRef.current = null;
+ persistSessionHistory();
+ syncHistoryState();
+ grid.notifyChange(true);
+ return Promise.resolve();
+ }
+ }
+
+ pendingTargetIndexRef.current = targetIndex;
+ inFlightHistoryOpsRef.current++;
const nextOp = historyQueueRef.current.then(async () => {
if (targetIndex < 0 || targetIndex >= historyRef.current.length) return;
const currentIndex = historyIndexRef.current;
@@ -476,337 +718,16 @@ export function useDrawingHistory({
for (let i = currentIndex; i > targetIndex; i--) {
const item = historyRef.current[i];
if (item) {
- const targetLayerId = item.layerId || activeLayerId;
- const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);
const deltas = await undoCache.resolveDeltas(item);
-
- if (item.layerTreeDelta) {
- const applied = onApplyLayerTreeDeltaRef?.current?.(item.layerTreeDelta, 'undo');
- if (applied) {
- layersRef.current = applied.nextLayers;
- if (applied.nextActiveLayerId !== null) {
- activeLayerIdRef.current = applied.nextActiveLayerId;
- }
- }
- if (deltas && deltas.length > 0) {
- grid.applyTileDeltas(deltas, 'undo');
- if (multiplayerService.isConnected()) {
- multiplayerService.sendTileDeltas(deltas, grid, { force: true });
- }
- }
- const liveLayerIds = new Set((layersRef.current ?? []).map((l) => l.id));
- const affectedLayerIds = new Set<string>();
- if (deltas) {
- for (const d of deltas) {
- affectedLayerIds.add(parseTileKey(d.key).layerId);
- }
- }
- if (applied) {
- for (const added of applied.addedLayers) {
- affectedLayerIds.add(added.id);
- }
- }
- for (const lid of affectedLayerIds) {
- if (lid !== targetLayerId && liveLayerIds.has(lid)) {
- onUpdateLayerThumbnail(lid, true);
- }
- }
- grid.notifyChange(true);
- } else if (item.isMaskEdit && targetLayer?.maskCanvas) {
- const mCtx = get2DContext(targetLayer.maskCanvas);
- if (mCtx && item.beforeImageData) {
- const mx =
- item.dirtyRect && item.beforeImageData.width === item.dirtyRect.width
- ? item.dirtyRect.x
- : 0;
- const my =
- item.dirtyRect && item.beforeImageData.height === item.dirtyRect.height
- ? item.dirtyRect.y
- : 0;
- 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 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);
- }
- }
- if (multiplayerService.isConnected()) {
- multiplayerService.sendLayerUpdate(targetLayerId, {
- vectorStrokes: targetLayer.vectorStrokes,
- });
- }
- } 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);
- }
- for (const lid of affectedLayerIds) {
- if (lid !== targetLayerId) {
- onUpdateLayerThumbnail(lid, true);
- }
- }
- } else {
- const isMono =
- !isBackgroundLayerId(targetLayerId) &&
- (targetLayer?.expressionColor === 'monochrome' ||
- colorModeRef.current === 'monochrome');
- const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
-
- if (item.beforeImageData) {
- const bx =
- item.dirtyRect &&
- item.beforeImageData.width === item.dirtyRect.width &&
- item.beforeImageData.height === item.dirtyRect.height
- ? item.dirtyRect.x
- : 0;
- const by =
- item.dirtyRect &&
- item.beforeImageData.width === item.dirtyRect.width &&
- item.beforeImageData.height === item.dirtyRect.height
- ? item.dirtyRect.y
- : 0;
- grid.writeImageData(targetLayerId, item.beforeImageData, bx, by, targetFormat);
- } else if (item.type === 'initial') {
- if (isBackgroundLayerId(targetLayerId)) {
- grid.fillLayerSolidWhite(
- targetLayerId,
- dims.width,
- dims.height,
- 'color-32bit'
- );
- } else {
- grid.clearLayer(targetLayerId);
- }
- }
- }
-
- if (
- !item.layerTreeDelta ||
- (layersRef.current ?? []).some((l) => l.id === targetLayerId)
- ) {
- onUpdateLayerThumbnail(targetLayerId, true);
- }
+ applySingleHistoryStep(item, deltas, 'undo', grid, dims);
}
}
} else {
for (let i = currentIndex + 1; i <= targetIndex; i++) {
const item = historyRef.current[i];
- const dataToApply = item?.afterImageData || item?.imageData;
if (item) {
- const targetLayerId = item.layerId || activeLayerId;
- const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);
const deltas = await undoCache.resolveDeltas(item);
-
- if (item.layerTreeDelta) {
- const applied = onApplyLayerTreeDeltaRef?.current?.(item.layerTreeDelta, 'redo');
- if (applied) {
- layersRef.current = applied.nextLayers;
- if (applied.nextActiveLayerId !== null) {
- activeLayerIdRef.current = applied.nextActiveLayerId;
- }
- }
- if (deltas && deltas.length > 0) {
- grid.applyTileDeltas(deltas, 'redo');
- if (multiplayerService.isConnected()) {
- multiplayerService.sendTileDeltas(deltas, grid, { force: true });
- }
- }
- const liveLayerIds = new Set((layersRef.current ?? []).map((l) => l.id));
- const affectedLayerIds = new Set<string>();
- if (deltas) {
- for (const d of deltas) {
- affectedLayerIds.add(parseTileKey(d.key).layerId);
- }
- }
- if (applied) {
- for (const added of applied.addedLayers) {
- affectedLayerIds.add(added.id);
- }
- }
- for (const lid of affectedLayerIds) {
- if (lid !== targetLayerId && liveLayerIds.has(lid)) {
- onUpdateLayerThumbnail(lid, true);
- }
- }
- grid.notifyChange(true);
- } else if (item.isMaskEdit && targetLayer?.maskCanvas) {
- const mCtx = get2DContext(targetLayer.maskCanvas);
- if (mCtx && dataToApply) {
- const mx =
- item.dirtyRect && dataToApply.width === item.dirtyRect.width
- ? item.dirtyRect.x
- : 0;
- const my =
- item.dirtyRect && dataToApply.height === item.dirtyRect.height
- ? item.dirtyRect.y
- : 0;
- 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 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);
- }
- }
- if (multiplayerService.isConnected()) {
- multiplayerService.sendLayerUpdate(targetLayerId, {
- vectorStrokes: targetLayer.vectorStrokes,
- });
- }
- } 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);
- }
- for (const lid of affectedLayerIds) {
- if (lid !== targetLayerId) {
- onUpdateLayerThumbnail(lid, true);
- }
- }
- } else {
- const isMono =
- !isBackgroundLayerId(targetLayerId) &&
- (targetLayer?.expressionColor === 'monochrome' ||
- colorModeRef.current === 'monochrome');
- const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
-
- if (dataToApply) {
- const ax =
- item.dirtyRect &&
- dataToApply.width === item.dirtyRect.width &&
- dataToApply.height === item.dirtyRect.height
- ? item.dirtyRect.x
- : 0;
- const ay =
- item.dirtyRect &&
- dataToApply.width === item.dirtyRect.width &&
- dataToApply.height === item.dirtyRect.height
- ? item.dirtyRect.y
- : 0;
- grid.writeImageData(targetLayerId, dataToApply, ax, ay, targetFormat);
- } else if (item.type === 'initial') {
- if (isBackgroundLayerId(targetLayerId)) {
- grid.fillLayerSolidWhite(
- targetLayerId,
- dims.width,
- dims.height,
- 'color-32bit'
- );
- } else {
- grid.clearLayer(targetLayerId);
- }
- }
- }
-
- if (
- !item.layerTreeDelta ||
- (layersRef.current ?? []).some((l) => l.id === targetLayerId)
- ) {
- onUpdateLayerThumbnail(targetLayerId, true);
- }
+ applySingleHistoryStep(item, deltas, 'redo', grid, dims);
}
}
}
@@ -816,44 +737,64 @@ export function useDrawingHistory({
syncHistoryState();
grid.notifyChange(true);
});
- historyQueueRef.current = nextOp.catch((err) => {
- console.warn('[History] Error during jumpToHistoryIndex:', err);
- });
+ historyQueueRef.current = nextOp
+ .catch((err) => {
+ console.warn('[History] Error during jumpToHistoryIndex:', err);
+ })
+ .finally(() => {
+ inFlightHistoryOpsRef.current = Math.max(0, inFlightHistoryOpsRef.current - 1);
+ if (inFlightHistoryOpsRef.current === 0) {
+ pendingTargetIndexRef.current = null;
+ }
+ });
return historyQueueRef.current;
},
[
abortActiveStrokeRef,
- activeLayerId,
- activeLayerIdRef,
- colorModeRef,
+ applySingleHistoryStep,
dimensionsRef,
flushPendingHistoryTasks,
isDrawingRef,
- layersRef,
- onApplyLayerTreeDeltaRef,
- onUpdateLayerThumbnail,
- onUpdateMaskThumbnailRef,
+ lastStrokeEndRef,
persistSessionHistory,
syncHistoryState,
]
);
const undo = useCallback(() => {
+ if (multiplayerService.isConnected() && multiplayerService.getLocalRole() === 'viewer') return;
flushPendingHistoryTasks();
if (isDrawingRef.current) {
abortActiveStrokeRef.current();
}
- if (historyIndexRef.current <= 0) return;
- jumpToHistoryIndex(historyIndexRef.current - 1);
+ const baseIndex =
+ pendingTargetIndexRef.current !== null
+ ? pendingTargetIndexRef.current
+ : historyIndexRef.current;
+ if (baseIndex <= 0) return;
+ jumpToHistoryIndex(baseIndex - 1);
}, [abortActiveStrokeRef, flushPendingHistoryTasks, isDrawingRef, jumpToHistoryIndex]);
const redo = useCallback(() => {
+ if (multiplayerService.isConnected() && multiplayerService.getLocalRole() === 'viewer') return;
flushPendingHistoryTasks();
if (isDrawingRef.current) {
abortActiveStrokeRef.current();
}
- if (historyIndexRef.current >= historyRef.current.length - 1) return;
- jumpToHistoryIndex(historyIndexRef.current + 1);
+ const baseIndex =
+ pendingTargetIndexRef.current !== null
+ ? pendingTargetIndexRef.current
+ : historyIndexRef.current;
+ if (baseIndex >= historyRef.current.length - 1) return;
+ const nextItem = historyRef.current[baseIndex + 1];
+ if (
+ multiplayerService.isConnected() &&
+ nextItem?.peerId !== undefined &&
+ nextItem.peerId !== 'local'
+ ) {
+ return;
+ }
+ jumpToHistoryIndex(baseIndex + 1);
}, [abortActiveStrokeRef, flushPendingHistoryTasks, isDrawingRef, jumpToHistoryIndex]);
const selectiveUndo = useCallback(
@@ -1146,6 +1087,7 @@ export function useDrawingHistory({
if (!targetDocumentId || targetDocumentId === activeSessionIdRef.current) {
historyRef.current = [];
historyIndexRef.current = -1;
+ pendingTargetIndexRef.current = null;
lastStrokeEndRef.current = null;
setHistoryList([]);
setHistoryIndex(-1);
@@ -1211,6 +1153,7 @@ export function useDrawingHistory({
}
activeSessionIdRef.current = nextDocId;
+ pendingTargetIndexRef.current = null;
lastStrokeEndRef.current = null;
if (nextDocId) {
diff --git a/src/hooks/drawing/useRetouchTool.ts b/src/hooks/drawing/useRetouchTool.ts
index c1a14ef..f5b871b 100644
--- a/src/hooks/drawing/useRetouchTool.ts
+++ b/src/hooks/drawing/useRetouchTool.ts
@@ -11,6 +11,7 @@ import {
applyRetouchStrokeSegment,
createRetouchStrokeSession,
} from '../../utils/retouchEngine';
+import { detectWhitePaperGround } from '../../utils/pigmentEngine';
import { createSelectionMask } from '../../utils/tonalEngine';
import { documentStore } from '../../utils/documentStore';
import { TileFormat } from '../../utils/tileEngine';
@@ -167,6 +168,7 @@ export function useRetouchTool({
layerId: activeLayerId,
targetFormat,
alphaLock: Boolean(activeLayer.alphaLocked),
+ pigmentWhiteGround: detectWhitePaperGround(layers, activeLayerId, grid),
dimensions,
selectionMask: selMask,
cloneOffset,
diff --git a/src/hooks/useCollabSync.ts b/src/hooks/useCollabSync.ts
index 4d9e812..2442fea 100644
--- a/src/hooks/useCollabSync.ts
+++ b/src/hooks/useCollabSync.ts
@@ -770,19 +770,8 @@ export function useCollabSync({
? true
: canEditLayer(activeLayerObj, mp.myPeer.id, mp.myRole).allowed;
- const handleStartHosting = useCallback(
- async (
- roomName: string,
- port: number,
- hostNickname?: string,
- isGlobal?: boolean,
- onStatus?: (status: string) => void
- ) => {
- if (!hasOpenDocument) {
- showToast('Please create or open a canvas before hosting a session.');
- return false;
- }
- const finalHostName = (hostNickname || mp.myPeer.name || 'Artist').trim();
+ const prepareHostLayers = useCallback(
+ (finalHostName: string) => {
const hostPeerId = mp.myPeer.id;
// Stamp ownership on host's existing non-background layers to protect them from accidental guest deletion
@@ -812,18 +801,44 @@ export function useCollabSync({
);
renameLayer(defaultLayer.id, hostLayerName);
}
+ },
+ [mp.myPeer.id, activeLayerId, renameLayer, setLayers]
+ );
+
+ const handleStartHosting = useCallback(
+ async (
+ roomName: string,
+ port: number,
+ hostNickname?: string,
+ isGlobal?: boolean,
+ onStatus?: (status: string) => void
+ ) => {
+ if (!hasOpenDocument) {
+ showToast('Please create or open a canvas before hosting a session.');
+ return false;
+ }
+ const finalHostName = (hostNickname || mp.myPeer.name || 'Artist').trim();
+ prepareHostLayers(finalHostName);
return await mp.startHosting(roomName, port, finalHostName, isGlobal, onStatus);
},
- [
- hasOpenDocument,
- showToast,
- mp.myPeer.id,
- mp.myPeer.name,
- activeLayerId,
- renameLayer,
- setLayers,
- mp.startHosting,
- ]
+ [hasOpenDocument, showToast, mp.myPeer.name, prepareHostLayers, mp.startHosting]
+ );
+
+ const handleStartWebRtcHosting = useCallback(
+ async (
+ roomName: string,
+ hostNickname?: string,
+ onStatus?: (status: string) => void
+ ) => {
+ if (!hasOpenDocument) {
+ showToast('Please create or open a canvas before hosting a session.');
+ return false;
+ }
+ const finalHostName = (hostNickname || mp.myPeer.name || 'Artist').trim();
+ prepareHostLayers(finalHostName);
+ return await mp.startWebRtcHosting(roomName, finalHostName, onStatus);
+ },
+ [hasOpenDocument, showToast, mp.myPeer.name, prepareHostLayers, mp.startWebRtcHosting]
);
const handleAddLayer = useCallback(
@@ -1052,6 +1067,7 @@ export function useCollabSync({
canDeleteLayerById,
canToggleOwnerLockById,
handleStartHosting,
+ handleStartWebRtcHosting,
handleAddLayer,
handleDeleteLayer,
handleDeleteSelectedLayers,
diff --git a/src/hooks/useMultiplayer.ts b/src/hooks/useMultiplayer.ts
index 7ad3c29..8897795 100644
--- a/src/hooks/useMultiplayer.ts
+++ b/src/hooks/useMultiplayer.ts
@@ -24,10 +24,19 @@ import {
WireLayerItem,
} from '../types/multiplayer';
import {
+ buildP2pShareUrl,
multiplayerService,
- ParsedInviteLink,
- parseInviteUrl,
+ parseCollabTarget,
+ ParsedCollabTarget,
} from '../services/multiplayerService';
+import { WebRtcHostHub, WebRtcTurnConfig } from '../services/webrtcHostHub';
+import { WebRtcGuestClient } from '../services/webrtcGuestClient';
+import {
+ computeRoomTopicHash,
+ generateP2pRoomCredentials,
+ normalizeRoomCode,
+ normalizeRoomSecret,
+} from '../services/webrtcSignaling';
import {
getBrushAssetRecord,
registerRemoteBrushAsset,
@@ -112,14 +121,42 @@ function getInitialPeerName(): string {
}
}
-interface ActiveSessionParams {
- wsUrl: string;
- token?: string;
- roomName: string;
- host: string;
- port: number;
- isSecure: boolean;
- isHost: boolean;
+type ActiveSessionParams =
+ | {
+ kind: 'ws';
+ wsUrl: string;
+ token?: string;
+ roomName: string;
+ host: string;
+ port: number;
+ isSecure: boolean;
+ isHost: boolean;
+ }
+ | {
+ kind: 'webrtc-guest';
+ roomCode: string;
+ roomSecret: string;
+ roomHash: string;
+ roomName: string;
+ customSignalingUrl?: string;
+ isHost: false;
+ };
+
+function getWebRtcNetworkConfigFromSettings(signalingOverride?: string): {
+ customSignalingUrl?: string;
+ turnConfig?: WebRtcTurnConfig;
+} {
+ const settings = useUiStore.getState().appSettings;
+ const customSignalingUrl = (signalingOverride || settings.collabSignalingUrl || '').trim() || undefined;
+ const turnUrl = (settings.collabTurnUrl || '').trim();
+ const turnConfig: WebRtcTurnConfig | undefined = turnUrl
+ ? {
+ turnUrl,
+ turnUsername: settings.collabTurnUsername || undefined,
+ turnCredential: settings.collabTurnCredential || undefined,
+ }
+ : undefined;
+ return { customSignalingUrl, turnConfig };
}
export interface UseMultiplayerProps {
@@ -210,12 +247,12 @@ export function useMultiplayer({
>([]);
const [isHostModalOpen, setIsHostModalOpen] = useState(false);
- // Smart Clipboard Invitation Prompt
- const [clipboardInvite, setClipboardInvite] = useState<ParsedInviteLink | null>(null);
+ // Smart Clipboard Invitation Prompt (supports WS links, P2P links, and INK-XXXX room codes)
+ const [clipboardInvite, setClipboardInvite] = useState<ParsedCollabTarget | null>(null);
const lastProcessedClipboardUrlRef = useRef<string | null>(null);
- // Web Landing modal for browser guests visiting via ?room=...
- const [webLandingInvite, setWebLandingInvite] = useState<ParsedInviteLink | null>(null);
+ // Web Landing modal for browser guests visiting via ?room=... or ?p2p=...
+ const [webLandingInvite, setWebLandingInvite] = useState<ParsedCollabTarget | null>(null);
// Auto-reconnect & seq/version tracking refs
const sessionParamsRef = useRef<ActiveSessionParams | null>(null);
@@ -405,41 +442,44 @@ export function useMultiplayer({
}, []);
// Paced async tile streaming so large canvases never saturate WS or server mpsc buffers
- const streamTilesPaced = useCallback((layersToStream: LayerItem[]) => {
- const activeGrid = documentStore.getActiveTileGrid();
- const queue: Array<{ layerId: string; tile: TileBuffer }> = [];
- for (const layer of layersToStream) {
- const tiles = activeGrid.getLayerTiles(layer.id);
- for (const tile of tiles) {
- if (tile.data && tile.data.byteLength > 0) {
- queue.push({ layerId: layer.id, tile });
+ const streamTilesPaced = useCallback(
+ (layersToStream: LayerItem[], targetPeerId?: string | number) => {
+ const activeGrid = documentStore.getActiveTileGrid();
+ const queue: Array<{ layerId: string; tile: TileBuffer }> = [];
+ for (const layer of layersToStream) {
+ const tiles = activeGrid.getLayerTiles(layer.id);
+ for (const tile of tiles) {
+ if (tile.data && tile.data.byteLength > 0) {
+ queue.push({ layerId: layer.id, tile });
+ }
}
}
- }
- if (queue.length === 0) return;
+ if (queue.length === 0) return;
- let idx = 0;
- const BATCH_SIZE = 16;
- const MAX_BUFFERED_BYTES = 2 * 1024 * 1024;
+ let idx = 0;
+ const BATCH_SIZE = 16;
+ const MAX_BUFFERED_BYTES = 2 * 1024 * 1024;
- const pump = () => {
- if (!multiplayerService.isConnected()) return;
- if (multiplayerService.getBufferedAmount() > MAX_BUFFERED_BYTES) {
- setTimeout(pump, 20);
- return;
- }
- const end = Math.min(idx + BATCH_SIZE, queue.length);
- for (; idx < end; idx++) {
- const entry = queue[idx];
- multiplayerService.sendTileDelta(entry.layerId, entry.tile);
- }
- if (idx < queue.length) {
- setTimeout(pump, 4);
- }
- };
+ const pump = () => {
+ if (!multiplayerService.isConnected()) return;
+ if (multiplayerService.getBufferedAmount() > MAX_BUFFERED_BYTES) {
+ setTimeout(pump, 20);
+ return;
+ }
+ const end = Math.min(idx + BATCH_SIZE, queue.length);
+ for (; idx < end; idx++) {
+ const entry = queue[idx];
+ multiplayerService.sendTileDelta(entry.layerId, entry.tile, targetPeerId);
+ }
+ if (idx < queue.length) {
+ setTimeout(pump, 4);
+ }
+ };
- pump();
- }, []);
+ pump();
+ },
+ []
+ );
// Auto-reconnect scheduler with exponential backoff and missed seq/tile catch-up
const scheduleReconnectRef = useRef<(immediate?: boolean) => void>(() => {});
@@ -454,8 +494,13 @@ export function useMultiplayer({
const nextAttempt = reconnectAttemptRef.current + 1;
if (nextAttempt > RECONNECT_MAX_ATTEMPTS) {
+ const wasWebRtcGuest = params.kind === 'webrtc-guest';
resetSessionState();
- showToastRef.current('Unable to reconnect to collaborative session');
+ showToastRef.current(
+ wasWebRtcGuest
+ ? 'Host disconnected — the P2P room has ended. Your canvas remains open locally.'
+ : 'Unable to reconnect to collaborative session'
+ );
return;
}
@@ -485,11 +530,31 @@ export function useMultiplayer({
isReconnectingInFlightRef.current = true;
pendingReconnectCatchUpRef.current = true;
- multiplayerService
- .connect(targetParams.wsUrl, reconnectPeer, targetParams.token, {
- isReconnect: true,
- sinceSeq,
- })
+ const attemptConnect =
+ targetParams.kind === 'ws'
+ ? multiplayerService.connect(targetParams.wsUrl, reconnectPeer, targetParams.token, {
+ isReconnect: true,
+ sinceSeq,
+ })
+ : (async () => {
+ const { customSignalingUrl, turnConfig } = getWebRtcNetworkConfigFromSettings(
+ targetParams.customSignalingUrl
+ );
+ const guestClient = new WebRtcGuestClient({
+ roomHash: targetParams.roomHash,
+ peerId: String(reconnectPeer.id),
+ customSignalingUrl,
+ turnConfig,
+ });
+ await guestClient.connect();
+ multiplayerService.attachTransport(guestClient, reconnectPeer, {
+ isReconnect: true,
+ sinceSeq,
+ sendJoinRequest: true,
+ });
+ })();
+
+ attemptConnect
.then(() => {
isReconnectingInFlightRef.current = false;
if (intentionalDisconnectRef.current || !sessionParamsRef.current) {
@@ -768,11 +833,16 @@ export function useMultiplayer({
animationTimeline: wireAnim,
});
- streamTilesPaced(effectiveLayers);
+ streamTilesPaced(effectiveLayers, guestPeer.id);
for (const layer of effectiveLayers) {
if (layer.maskCanvas) {
- multiplayerService.sendLayerMaskData(layer.id, layer.maskCanvas);
+ multiplayerService.sendLayerMaskData(
+ layer.id,
+ layer.maskCanvas,
+ undefined,
+ guestPeer.id
+ );
}
}
@@ -1123,16 +1193,32 @@ export function useMultiplayer({
});
// Unexpected close: keep session state & seq cursors, reconnect with exponential backoff
- const unsubClose = multiplayerService.onClose(() => {
+ const unsubClose = multiplayerService.onClose((reason?: string) => {
if (intentionalDisconnectRef.current || !sessionParamsRef.current) {
resetSessionState();
return;
}
+ // If the P2P host explicitly closed the room, notify cleanly without endless retries
+ if (
+ sessionParamsRef.current.kind === 'webrtc-guest' &&
+ reason &&
+ /host closed/i.test(reason)
+ ) {
+ intentionalDisconnectRef.current = true;
+ resetSessionState();
+ showToastRef.current('Host ended the P2P room. Your canvas remains open locally.');
+ return;
+ }
+
setIsConnected(false);
setConnectionStatus('reconnecting');
if (reconnectAttemptRef.current === 0) {
- showToastRef.current('Connection lost. Reconnecting...');
+ showToastRef.current(
+ sessionParamsRef.current.kind === 'webrtc-guest'
+ ? 'Host connection interrupted. Reconnecting to P2P room...'
+ : 'Connection lost. Reconnecting...'
+ );
}
scheduleReconnectRef.current(false);
});
@@ -1153,7 +1239,7 @@ export function useMultiplayer({
const text = await navigator.clipboard.readText();
if (!text || text === lastProcessedClipboardUrlRef.current) return;
- const parsed = parseInviteUrl(text);
+ const parsed = parseCollabTarget(text);
if (parsed) {
lastProcessedClipboardUrlRef.current = text;
setClipboardInvite(parsed);
@@ -1170,7 +1256,7 @@ export function useMultiplayer({
// Check URL query parameters on initial page load (for Web Browser joins)
useEffect(() => {
if (typeof window === 'undefined') return;
- const parsed = parseInviteUrl(window.location.href);
+ const parsed = parseCollabTarget(window.location.href);
if (parsed) {
setWebLandingInvite(parsed);
}
@@ -1253,6 +1339,7 @@ export function useMultiplayer({
peerCount: serverInfo.peerCount || 1,
isGlobal: isGlobalServer,
localInviteUrl,
+ transport: 'ws',
};
setHostInfo(normalizedServerInfo);
@@ -1283,6 +1370,7 @@ export function useMultiplayer({
// Host connects locally via 127.0.0.1 with the room token
const wsUrl = `ws://127.0.0.1:${resolvedPort}/ws`;
sessionParamsRef.current = {
+ kind: 'ws',
wsUrl,
token: resolvedRoomToken || undefined,
roomName: resolvedRoomName,
@@ -1345,13 +1433,127 @@ export function useMultiplayer({
[clearReconnectTimer, resetSessionState, showToast, streamTilesPaced]
);
+ // START QUICK P2P HOSTING (SERVERLESS WEBRTC STAR HUB, NO CLOUDFLARED REQUIRED)
+ const startWebRtcHosting = useCallback(
+ async (
+ roomName: string = 'Ink Studio Session',
+ hostNickname?: string,
+ onStatus?: (status: string) => void
+ ): Promise<SessionHostInfo> => {
+ try {
+ clearReconnectTimer();
+ intentionalDisconnectRef.current = false;
+ reconnectAttemptRef.current = 0;
+ setReconnectAttempt(0);
+ setConnectionStatus('connecting');
+
+ let currentName = myPeerRef.current.name;
+ if (hostNickname && hostNickname.trim()) {
+ currentName = hostNickname.trim();
+ }
+
+ const resolvedRoomName = roomName.trim() || 'Ink Studio Session';
+ const creds = generateP2pRoomCredentials();
+ const { customSignalingUrl, turnConfig } = getWebRtcNetworkConfigFromSettings();
+
+ onStatus?.('Connecting to P2P signaling...');
+
+ const hostPeer: CollabPeer = {
+ ...myPeerRef.current,
+ name: currentName,
+ isHost: true,
+ role: 'host',
+ };
+
+ const hub = new WebRtcHostHub({
+ roomHash: creds.roomHash,
+ hostPeerId: String(hostPeer.id),
+ customSignalingUrl,
+ turnConfig,
+ });
+
+ await hub.start();
+
+ const shareUrl = buildP2pShareUrl(
+ creds.roomCode,
+ creds.roomSecret,
+ resolvedRoomName,
+ customSignalingUrl
+ );
+
+ const normalizedServerInfo: SessionHostInfo = {
+ isRunning: true,
+ port: 0,
+ localIp: 'WebRTC P2P',
+ roomName: resolvedRoomName,
+ roomToken: creds.roomSecret,
+ inviteUrl: shareUrl,
+ peerCount: 1,
+ isGlobal: true,
+ transport: 'webrtc',
+ roomCode: creds.roomCode,
+ roomSecret: creds.roomSecret,
+ joinCode: creds.joinCode,
+ };
+
+ setHostInfo(normalizedServerInfo);
+ setIsHost(true);
+ 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;
+
+ setMyPeer(hostPeer);
+ myPeerRef.current = hostPeer;
+ myRoleRef.current = 'host';
+ setMyRole('host');
+ multiplayerService.setLocalRole('host');
+
+ sessionParamsRef.current = null;
+ multiplayerService.attachTransport(hub, hostPeer, { sendJoinRequest: false });
+
+ setIsConnected(true);
+ setConnectionStatus('connected');
+
+ // Auto-copy short join code (graceful fallback if clipboard blocked)
+ try {
+ if (navigator.clipboard && navigator.clipboard.writeText) {
+ await navigator.clipboard.writeText(creds.joinCode);
+ lastProcessedClipboardUrlRef.current = creds.joinCode;
+ showToast(`Quick P2P room ready! Code ${creds.joinCode} copied.`);
+ } else {
+ showToast(`Quick P2P room ready: ${creds.joinCode}`);
+ }
+ } catch {
+ showToast(`Quick P2P room ready: ${creds.joinCode}`);
+ }
+
+ return normalizedServerInfo;
+ } catch (err: any) {
+ console.error('Failed to start WebRTC P2P host session:', err);
+ resetSessionState();
+ const errMsg = err?.message || (typeof err === 'string' ? err : 'P2P connection error');
+ showToast(`Failed to start P2P room: ${errMsg}`);
+ throw err;
+ }
+ },
+ [clearReconnectTimer, resetSessionState, showToast]
+ );
+
// STOP HOSTING
const stopHosting = useCallback(async () => {
try {
+ const wasWebRtc = hostInfoRef.current?.transport === 'webrtc';
intentionalDisconnectRef.current = true;
clearReconnectTimer();
multiplayerService.disconnect();
- if (isTauriEnvironment()) {
+ if (!wasWebRtc && isTauriEnvironment()) {
const { invoke } = await import('@tauri-apps/api/core');
await invoke('stop_collab_server');
}
@@ -1371,7 +1573,8 @@ export function useMultiplayer({
guestNickname?: string,
token?: string,
isSecureOverride?: boolean,
- persistName: boolean = false
+ persistName: boolean = false,
+ wsPath?: string
): Promise<boolean> => {
try {
clearReconnectTimer();
@@ -1396,7 +1599,8 @@ export function useMultiplayer({
: isHttps || port === 443 || host.toLowerCase().endsWith('.trycloudflare.com');
const proto = isSecure ? 'wss' : 'ws';
const portPart = port === 80 || port === 443 || !port ? '' : `:${port}`;
- const wsUrl = `${proto}://${host}${portPart}/ws`;
+ const normalizedPath = wsPath && wsPath.startsWith('/') ? wsPath : '/ws';
+ const wsUrl = `${proto}://${host}${portPart}${normalizedPath}`;
const guestPeer: CollabPeer = {
...myPeerRef.current,
@@ -1416,6 +1620,7 @@ export function useMultiplayer({
pendingReconnectCatchUpRef.current = false;
sessionParamsRef.current = {
+ kind: 'ws',
wsUrl,
token,
roomName,
@@ -1442,6 +1647,7 @@ export function useMultiplayer({
inviteUrl: `${inviteProto}://${host}${portPart}/?room=${encodeURIComponent(roomName)}${tokenQuery}`,
peerCount: 1,
isGlobal: isSecure,
+ transport: 'ws',
};
setHostInfo(nextHostInfo);
hostInfoRef.current = nextHostInfo;
@@ -1457,24 +1663,153 @@ export function useMultiplayer({
[clearReconnectTimer, resetSessionState, showToast]
);
+ // JOIN WORLDWIDE P2P ROOM (WEBRTC GUEST)
+ const joinWebRtcRoom = useCallback(
+ async (
+ rawRoomCode: string,
+ rawRoomSecret: string = '',
+ guestNickname?: string,
+ signalingUrlOverride?: string,
+ persistName: boolean = false,
+ roomNameOverride?: string
+ ): Promise<boolean> => {
+ try {
+ clearReconnectTimer();
+ intentionalDisconnectRef.current = false;
+ reconnectAttemptRef.current = 0;
+ setReconnectAttempt(0);
+ setConnectionStatus('connecting');
+
+ const roomCode = normalizeRoomCode(rawRoomCode);
+ const roomSecret = normalizeRoomSecret(rawRoomSecret);
+ const roomHash = computeRoomTopicHash(roomCode, roomSecret);
+ const joinCode = roomSecret ? `${roomCode}-${roomSecret}` : roomCode;
+ const resolvedRoomName = (roomNameOverride || roomCode).trim() || roomCode;
+
+ let currentName = myPeerRef.current.name;
+ if (guestNickname && guestNickname.trim()) {
+ currentName = guestNickname.trim();
+ if (persistName) {
+ safeLocalStorageSetItem(NICKNAME_KEY, currentName, 'artist name');
+ safeLocalStorageSetItem(NICKNAME_CUSTOMIZED_KEY, '1', 'artist name flag');
+ }
+ }
+
+ const guestPeer: CollabPeer = {
+ ...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;
+
+ const { customSignalingUrl, turnConfig } =
+ getWebRtcNetworkConfigFromSettings(signalingUrlOverride);
+
+ sessionParamsRef.current = {
+ kind: 'webrtc-guest',
+ roomCode,
+ roomSecret,
+ roomHash,
+ roomName: resolvedRoomName,
+ customSignalingUrl,
+ isHost: false,
+ };
+
+ const guestClient = new WebRtcGuestClient({
+ roomHash,
+ peerId: String(guestPeer.id),
+ customSignalingUrl,
+ turnConfig,
+ });
+
+ await guestClient.connect();
+ multiplayerService.attachTransport(guestClient, guestPeer, {
+ sendJoinRequest: true,
+ });
+
+ setIsConnected(true);
+ setConnectionStatus('connected');
+ setIsHost(false);
+ isHostRef.current = false;
+
+ const nextHostInfo: SessionHostInfo = {
+ isRunning: true,
+ port: 0,
+ localIp: 'WebRTC P2P',
+ roomName: resolvedRoomName,
+ roomToken: roomSecret || undefined,
+ inviteUrl: buildP2pShareUrl(roomCode, roomSecret, resolvedRoomName, customSignalingUrl),
+ peerCount: 1,
+ isGlobal: true,
+ transport: 'webrtc',
+ roomCode,
+ roomSecret: roomSecret || undefined,
+ joinCode,
+ };
+ setHostInfo(nextHostInfo);
+ hostInfoRef.current = nextHostInfo;
+ setClipboardInvite(null);
+ setWebLandingInvite(null);
+ return true;
+ } catch (err: any) {
+ resetSessionState();
+ showToast(`Failed to join P2P room: ${err?.message || err}`);
+ return false;
+ }
+ },
+ [clearReconnectTimer, resetSessionState, showToast]
+ );
+
const joinByInviteUrl = useCallback(
- async (rawUrl: string, nickname?: string, persistName: boolean = false): Promise<boolean> => {
- const parsed = parseInviteUrl(rawUrl);
- if (!parsed) {
- showToast('Invalid invite link. Paste the full room URL.');
+ async (
+ rawUrl: string,
+ nickname?: string,
+ persistName: boolean = false,
+ secretOverride?: string
+ ): Promise<boolean> => {
+ const target = parseCollabTarget(rawUrl);
+ if (!target) {
+ showToast(
+ 'Invalid room code or link. Enter an INK-XXXX code, P2P link, or wss:// / ws:// URL.'
+ );
return false;
}
+ if (target.kind === 'p2p') {
+ const effectiveSecret =
+ secretOverride !== undefined && secretOverride.trim()
+ ? secretOverride.trim()
+ : target.roomSecret;
+ return joinWebRtcRoom(
+ target.roomCode,
+ effectiveSecret,
+ nickname,
+ target.signalingUrl,
+ persistName,
+ target.roomName
+ );
+ }
return joinRoom(
- parsed.host,
- parsed.port,
- parsed.roomName,
+ target.host,
+ target.port,
+ target.roomName,
nickname,
- parsed.token,
- parsed.isSecure,
- persistName
+ target.token,
+ target.isSecure,
+ persistName,
+ target.wsPath
);
},
- [joinRoom, showToast]
+ [joinRoom, joinWebRtcRoom, showToast]
);
const leaveRoom = useCallback(() => {
@@ -1620,8 +1955,10 @@ export function useMultiplayer({
isHostModalOpen,
setIsHostModalOpen,
startHosting,
+ startWebRtcHosting,
stopHosting,
joinRoom,
+ joinWebRtcRoom,
joinByInviteUrl,
leaveRoom,
setPeerRole,
diff --git a/src/services/collabTransport.ts b/src/services/collabTransport.ts
new file mode 100644
index 0000000..fd6dbdc
--- /dev/null
+++ b/src/services/collabTransport.ts
@@ -0,0 +1,276 @@
+export type CollabTransportKind = 'ws' | 'webrtc-host' | 'webrtc-guest';
+
+export interface ICollabTransport {
+ readonly kind: CollabTransportKind;
+ isOpen(): boolean;
+ getBufferedAmount(): number;
+ sendText(text: string): void;
+ sendBinary(data: ArrayBuffer | Uint8Array): void;
+ sendBinaryTo?(targetPeerId: string | number, data: ArrayBuffer | Uint8Array): void;
+ close(): void;
+ onTextMessage(handler: (text: string) => void): () => void;
+ onBinaryMessage(handler: (data: ArrayBuffer) => void): () => void;
+ onClose(handler: (reason?: string) => void): () => void;
+ onError(handler: (err: Error | Event) => void): () => void;
+}
+
+/**
+ * Lightweight binary framing/chunking header for RTCDataChannel transport.
+ *
+ * Frame layout (16 bytes header + payload slice):
+ * [0..1] Magic bytes: 'I' (0x49), 'C' (0x43) (distinct from 'I','N' wire packets)
+ * [2] Payload kind: 0x01 = UTF-8 JSON text, 0x02 = raw binary ArrayBuffer
+ * [3] Flags (reserved, 0x00)
+ * [4..7] messageId (Uint32 LE)
+ * [8..11] chunkIndex (Uint32 LE, 0 .. totalChunks - 1)
+ * [12..15] totalChunks (Uint32 LE, 1 .. MAX_CHUNKS_PER_MESSAGE)
+ * [16..] Chunk payload bytes (<= maxChunkPayloadBytes, default 48 KB)
+ */
+export const CHUNK_MAGIC_0 = 0x49; // 'I'
+export const CHUNK_MAGIC_1 = 0x43; // 'C'
+export const CHUNK_KIND_TEXT = 0x01;
+export const CHUNK_KIND_BINARY = 0x02;
+export const CHUNK_HEADER_BYTES = 16;
+
+/** Safe default chunk payload size (48 KB) well below Android WebView / browser SCTP limits. */
+export const DEFAULT_CHUNK_PAYLOAD_BYTES = 48 * 1024;
+/** Maximum reassembled message size (16 MB, matching multiplayerService binary ceiling). */
+export const MAX_REASSEMBLED_MESSAGE_BYTES = 16 * 1024 * 1024;
+/** Safety cap on chunk count per message. */
+export const MAX_CHUNKS_PER_MESSAGE = 1024;
+/** Maximum concurrent incomplete reassembly buffers per peer. */
+export const MAX_INFLIGHT_REASSEMBLY = 64;
+/** Timeout before stale incomplete chunk buffers are evicted. */
+export const REASSEMBLY_TIMEOUT_MS = 30_000;
+
+export type ReassembledTransportMessage =
+ | { kind: 'text'; text: string }
+ | { kind: 'binary'; data: ArrayBuffer };
+
+const sharedTextEncoder = new TextEncoder();
+const sharedTextDecoder = new TextDecoder();
+
+export function toUint8Array(data: ArrayBuffer | Uint8Array): Uint8Array {
+ return data instanceof Uint8Array ? data : new Uint8Array(data);
+}
+
+/**
+ * Splits a text (JSON) or binary ('IN...') payload into 1 or more framed chunks
+ * sized <= `maxChunkPayloadBytes` (+ 16 byte header).
+ */
+export function encodeTransportFrames(
+ kind: 'text' | 'binary',
+ payload: string | ArrayBuffer | Uint8Array,
+ messageId: number,
+ maxChunkPayloadBytes: number = DEFAULT_CHUNK_PAYLOAD_BYTES
+): Uint8Array[] {
+ const safeChunkSize = Math.max(256, Math.min(256 * 1024, Math.floor(maxChunkPayloadBytes)));
+ const rawBytes =
+ kind === 'text'
+ ? sharedTextEncoder.encode(typeof payload === 'string' ? payload : '')
+ : toUint8Array(payload as ArrayBuffer | Uint8Array);
+
+ if (rawBytes.byteLength > MAX_REASSEMBLED_MESSAGE_BYTES) {
+ throw new Error(
+ `Transport payload exceeds ${MAX_REASSEMBLED_MESSAGE_BYTES} byte safety ceiling`
+ );
+ }
+
+ const totalChunks = Math.max(1, Math.ceil(rawBytes.byteLength / safeChunkSize));
+ if (totalChunks > MAX_CHUNKS_PER_MESSAGE) {
+ throw new Error(`Transport payload requires too many chunks (${totalChunks})`);
+ }
+
+ const kindByte = kind === 'text' ? CHUNK_KIND_TEXT : CHUNK_KIND_BINARY;
+ const msgIdU32 = messageId >>> 0;
+ const frames: Uint8Array[] = new Array(totalChunks);
+
+ for (let i = 0; i < totalChunks; i++) {
+ const start = i * safeChunkSize;
+ const end = Math.min(rawBytes.byteLength, start + safeChunkSize);
+ const sliceLen = end - start;
+ const frame = new Uint8Array(CHUNK_HEADER_BYTES + sliceLen);
+ const view = new DataView(frame.buffer, frame.byteOffset, frame.byteLength);
+
+ frame[0] = CHUNK_MAGIC_0;
+ frame[1] = CHUNK_MAGIC_1;
+ frame[2] = kindByte;
+ frame[3] = 0;
+ view.setUint32(4, msgIdU32, true);
+ view.setUint32(8, i >>> 0, true);
+ view.setUint32(12, totalChunks >>> 0, true);
+
+ if (sliceLen > 0) {
+ frame.set(rawBytes.subarray(start, end), CHUNK_HEADER_BYTES);
+ }
+ frames[i] = frame;
+ }
+
+ return frames;
+}
+
+interface PendingAssembly {
+ kindByte: number;
+ totalChunks: number;
+ receivedCount: number;
+ totalBytes: number;
+ chunks: Array<Uint8Array | undefined>;
+ createdAt: number;
+}
+
+/**
+ * Stateful per-peer chunk reassembler with bounds, duplicate, and timeout protection.
+ */
+export class ChunkReassembler {
+ private pending = new Map<number, PendingAssembly>();
+ private readonly maxMessageBytes: number;
+ private readonly maxInflight: number;
+ private readonly timeoutMs: number;
+
+ constructor(options?: {
+ maxMessageBytes?: number;
+ maxInflight?: number;
+ timeoutMs?: number;
+ }) {
+ this.maxMessageBytes = options?.maxMessageBytes ?? MAX_REASSEMBLED_MESSAGE_BYTES;
+ this.maxInflight = options?.maxInflight ?? MAX_INFLIGHT_REASSEMBLY;
+ this.timeoutMs = options?.timeoutMs ?? REASSEMBLY_TIMEOUT_MS;
+ }
+
+ public getPendingCount(): number {
+ return this.pending.size;
+ }
+
+ public clear(): void {
+ this.pending.clear();
+ }
+
+ public pruneExpired(nowMs: number = Date.now()): void {
+ for (const [id, entry] of this.pending.entries()) {
+ if (nowMs - entry.createdAt > this.timeoutMs) {
+ this.pending.delete(id);
+ }
+ }
+ }
+
+ public pushFrame(
+ frameData: ArrayBuffer | Uint8Array,
+ nowMs: number = Date.now()
+ ): ReassembledTransportMessage | null {
+ const bytes = toUint8Array(frameData);
+ if (bytes.byteLength < CHUNK_HEADER_BYTES) return null;
+ if (bytes[0] !== CHUNK_MAGIC_0 || bytes[1] !== CHUNK_MAGIC_1) return null;
+
+ const kindByte = bytes[2];
+ if (kindByte !== CHUNK_KIND_TEXT && kindByte !== CHUNK_KIND_BINARY) return null;
+
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ const messageId = view.getUint32(4, true);
+ const chunkIndex = view.getUint32(8, true);
+ const totalChunks = view.getUint32(12, true);
+
+ if (
+ totalChunks === 0 ||
+ totalChunks > MAX_CHUNKS_PER_MESSAGE ||
+ chunkIndex >= totalChunks
+ ) {
+ return null;
+ }
+
+ const payloadSlice = bytes.subarray(CHUNK_HEADER_BYTES);
+ if (payloadSlice.byteLength > this.maxMessageBytes) {
+ this.pending.delete(messageId);
+ return null;
+ }
+
+ // Fast path for single-chunk messages (avoids pending map overhead for strokes/cursors)
+ if (totalChunks === 1) {
+ this.pending.delete(messageId);
+ if (kindByte === CHUNK_KIND_TEXT) {
+ return { kind: 'text', text: sharedTextDecoder.decode(payloadSlice) };
+ }
+ const copy = new Uint8Array(payloadSlice.byteLength);
+ copy.set(payloadSlice);
+ return { kind: 'binary', data: copy.buffer };
+ }
+
+ let entry = this.pending.get(messageId);
+ if (!entry) {
+ this.pruneExpired(nowMs);
+ if (this.pending.size >= this.maxInflight) {
+ const oldestKey = this.pending.keys().next().value;
+ if (oldestKey !== undefined) {
+ this.pending.delete(oldestKey);
+ }
+ }
+ entry = {
+ kindByte,
+ totalChunks,
+ receivedCount: 0,
+ totalBytes: 0,
+ chunks: new Array<Uint8Array | undefined>(totalChunks),
+ createdAt: nowMs,
+ };
+ this.pending.set(messageId, entry);
+ } else if (entry.totalChunks !== totalChunks || entry.kindByte !== kindByte) {
+ // Mismatched header for an in-flight messageId — discard corrupt buffer
+ this.pending.delete(messageId);
+ return null;
+ }
+
+ // Ignore duplicate chunk indices safely
+ if (entry.chunks[chunkIndex] !== undefined) {
+ return null;
+ }
+
+ const nextTotalBytes = entry.totalBytes + payloadSlice.byteLength;
+ if (nextTotalBytes > this.maxMessageBytes) {
+ this.pending.delete(messageId);
+ return null;
+ }
+
+ const chunkCopy = new Uint8Array(payloadSlice.byteLength);
+ chunkCopy.set(payloadSlice);
+ entry.chunks[chunkIndex] = chunkCopy;
+ entry.receivedCount += 1;
+ entry.totalBytes = nextTotalBytes;
+
+ if (entry.receivedCount < entry.totalChunks) {
+ return null;
+ }
+
+ this.pending.delete(messageId);
+
+ const combined = new Uint8Array(entry.totalBytes);
+ let offset = 0;
+ for (let i = 0; i < entry.totalChunks; i++) {
+ const part = entry.chunks[i];
+ if (!part) return null;
+ combined.set(part, offset);
+ offset += part.byteLength;
+ }
+
+ if (entry.kindByte === CHUNK_KIND_TEXT) {
+ return { kind: 'text', text: sharedTextDecoder.decode(combined) };
+ }
+ return { kind: 'binary', data: combined.buffer };
+ }
+}
+
+/**
+ * Helper to send a framed text or binary payload over an open RTCDataChannel.
+ */
+export function sendFramedOverDataChannel(
+ dc: Pick<RTCDataChannel, 'readyState' | 'send'>,
+ kind: 'text' | 'binary',
+ payload: string | ArrayBuffer | Uint8Array,
+ nextMessageId: () => number,
+ maxChunkPayloadBytes: number = DEFAULT_CHUNK_PAYLOAD_BYTES
+): boolean {
+ if (dc.readyState !== 'open') return false;
+ const frames = encodeTransportFrames(kind, payload, nextMessageId(), maxChunkPayloadBytes);
+ for (const frame of frames) {
+ dc.send(frame as unknown as ArrayBuffer);
+ }
+ return true;
+}
diff --git a/src/services/multiplayerService.ts b/src/services/multiplayerService.ts
index 208445f..25b249e 100644
--- a/src/services/multiplayerService.ts
+++ b/src/services/multiplayerService.ts
@@ -70,6 +70,8 @@ import {
sanitizeWireLayerTree,
serializeLayerForWire,
} from '../utils/collabSyncUtils';
+import { CollabTransportKind, ICollabTransport } from './collabTransport';
+import { normalizeRoomCode, normalizeRoomSecret } from './webrtcSignaling';
type MessageHandler = (msg: MultiplayerMessage) => void;
@@ -120,6 +122,9 @@ const TOOL_TYPES_LIST: ToolType[] = [
'shape',
'object',
'3d',
+ 'gradient',
+ 'retouch',
+ 'pen',
];
export const DEEP_LINK_SCHEME = 'inkstudio:';
@@ -131,6 +136,8 @@ export interface ParsedInviteLink {
url: string;
token?: string;
isSecure: boolean;
+ /** Optional custom WebSocket path (defaults to "/ws" when omitted). */
+ wsPath?: string;
}
export function parseInviteUrl(raw: string): ParsedInviteLink | null {
@@ -145,15 +152,19 @@ export function parseInviteUrl(raw: string): ParsedInviteLink | null {
}
if (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') {
+ const hostname = parsedUrl.hostname.trim();
+ if (!hostname) return null;
+ const isTryCloudflare =
+ parsedUrl.protocol === 'https:' && hostname.toLowerCase().endsWith('.trycloudflare.com');
const roomParam = parsedUrl.searchParams.get('room');
- if (!roomParam) return null;
+ if (!roomParam && !isTryCloudflare) return null;
const isSecure = parsedUrl.protocol === 'https:';
const port = parsedUrl.port ? parseInt(parsedUrl.port, 10) : isSecure ? 443 : 80;
if (!Number.isFinite(port) || port <= 0 || port > 65535) return null;
const token = parsedUrl.searchParams.get('token') || undefined;
return {
- roomName: roomParam,
- host: parsedUrl.hostname,
+ roomName: (roomParam || 'Studio').trim() || 'Studio',
+ host: hostname,
port,
url: trimmed,
token,
@@ -161,6 +172,27 @@ export function parseInviteUrl(raw: string): ParsedInviteLink | null {
};
}
+ if (parsedUrl.protocol === 'ws:' || parsedUrl.protocol === 'wss:') {
+ const hostname = parsedUrl.hostname.trim();
+ if (!hostname) return null;
+ const isSecure = parsedUrl.protocol === 'wss:';
+ const port = parsedUrl.port ? parseInt(parsedUrl.port, 10) : isSecure ? 443 : 80;
+ if (!Number.isFinite(port) || port <= 0 || port > 65535) return null;
+ const roomName = (parsedUrl.searchParams.get('room') || 'Studio').trim() || 'Studio';
+ const token = parsedUrl.searchParams.get('token') || undefined;
+ const pathname = parsedUrl.pathname;
+ const wsPath = pathname && pathname !== '/' && pathname !== '/ws' ? pathname : undefined;
+ return {
+ roomName,
+ host: hostname,
+ port,
+ url: trimmed,
+ token,
+ isSecure,
+ ...(wsPath ? { wsPath } : {}),
+ };
+ }
+
if (parsedUrl.protocol === DEEP_LINK_SCHEME) {
const host = parsedUrl.searchParams.get('host');
const portParam = parsedUrl.searchParams.get('port');
@@ -187,6 +219,176 @@ export function parseInviteUrl(raw: string): ParsedInviteLink | null {
return null;
}
+export interface ParsedP2pInvite {
+ kind: 'p2p';
+ roomCode: string;
+ roomSecret: string;
+ joinCode: string;
+ roomName: string;
+ signalingUrl?: string;
+ url: string;
+}
+
+export interface ParsedWsInvite extends ParsedInviteLink {
+ kind: 'ws';
+}
+
+export type ParsedCollabTarget = ParsedP2pInvite | ParsedWsInvite;
+
+const P2P_SHORT_CODE_REGEX = /^INK-([A-Z0-9]{4,8})(?:[-:\s]+([A-Z0-9]{4,16}))?$/i;
+
+function sanitizeSignalingUrlParam(raw: string | null): string | undefined {
+ if (!raw) return undefined;
+ const trimmed = raw.trim();
+ if (!trimmed) return undefined;
+ try {
+ const parsed = new URL(trimmed);
+ if (
+ parsed.protocol === 'wss:' ||
+ parsed.protocol === 'ws:' ||
+ parsed.protocol === 'https:' ||
+ parsed.protocol === 'http:'
+ ) {
+ return trimmed;
+ }
+ } catch {
+ // ignore invalid signaling URL param
+ }
+ return undefined;
+}
+
+function splitEmbeddedP2pCode(rawCode: string, explicitSecret?: string | null): {
+ roomCode: string;
+ roomSecret: string;
+} | null {
+ const match = rawCode.trim().match(P2P_SHORT_CODE_REGEX);
+ if (!match) return null;
+ const roomCode = normalizeRoomCode(`INK-${match[1]}`);
+ const roomSecret = normalizeRoomSecret(explicitSecret || match[2] || '');
+ return { roomCode, roomSecret };
+}
+
+/**
+ * Auto-detects whether user input is:
+ * - a short P2P room code (`INK-7429` or `INK-7429-K8P2M9`)
+ * - a P2P invite link (`https://.../?p2p=INK-7429&secret=...` or `inkstudio://p2p?code=...`)
+ * - a WebSocket / Cloudflare / LAN invite link (`wss://...`, `ws://...`, `https://...trycloudflare.com`, `http://.../?room=...`)
+ */
+export function parseCollabTarget(raw: string): ParsedCollabTarget | null {
+ const trimmed = raw.trim();
+ if (!trimmed) return null;
+
+ // 1. Bare or combined short P2P room code (e.g. INK-7429 or INK-7429-K8P2M9)
+ const directCode = splitEmbeddedP2pCode(trimmed);
+ if (directCode) {
+ const joinCode = directCode.roomSecret
+ ? `${directCode.roomCode}-${directCode.roomSecret}`
+ : directCode.roomCode;
+ return {
+ kind: 'p2p',
+ roomCode: directCode.roomCode,
+ roomSecret: directCode.roomSecret,
+ joinCode,
+ roomName: directCode.roomCode,
+ url: trimmed,
+ };
+ }
+
+ // 2. P2P URL (`https://.../?p2p=INK-7429&secret=...` or `inkstudio://p2p?code=INK-7429&secret=...`)
+ try {
+ const parsedUrl = new URL(trimmed);
+ if (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') {
+ const p2pParam = parsedUrl.searchParams.get('p2p');
+ if (p2pParam) {
+ const split = splitEmbeddedP2pCode(
+ p2pParam,
+ parsedUrl.searchParams.get('secret') || parsedUrl.searchParams.get('token')
+ );
+ if (split) {
+ const roomName =
+ (parsedUrl.searchParams.get('room') || split.roomCode).trim() || split.roomCode;
+ const signalingUrl = sanitizeSignalingUrlParam(parsedUrl.searchParams.get('sig'));
+ return {
+ kind: 'p2p',
+ roomCode: split.roomCode,
+ roomSecret: split.roomSecret,
+ joinCode: split.roomSecret ? `${split.roomCode}-${split.roomSecret}` : split.roomCode,
+ roomName,
+ ...(signalingUrl ? { signalingUrl } : {}),
+ url: trimmed,
+ };
+ }
+ }
+ } else if (parsedUrl.protocol === DEEP_LINK_SCHEME) {
+ const hostOrPath = `${parsedUrl.hostname}${parsedUrl.pathname}`.toLowerCase();
+ const codeParam = parsedUrl.searchParams.get('code') || parsedUrl.searchParams.get('p2p');
+ if (codeParam && (hostOrPath.includes('p2p') || parsedUrl.searchParams.has('code'))) {
+ const split = splitEmbeddedP2pCode(
+ codeParam,
+ parsedUrl.searchParams.get('secret') || parsedUrl.searchParams.get('token')
+ );
+ if (split) {
+ const roomName =
+ (parsedUrl.searchParams.get('room') || split.roomCode).trim() || split.roomCode;
+ const signalingUrl = sanitizeSignalingUrlParam(parsedUrl.searchParams.get('sig'));
+ return {
+ kind: 'p2p',
+ roomCode: split.roomCode,
+ roomSecret: split.roomSecret,
+ joinCode: split.roomSecret ? `${split.roomCode}-${split.roomSecret}` : split.roomCode,
+ roomName,
+ ...(signalingUrl ? { signalingUrl } : {}),
+ url: trimmed,
+ };
+ }
+ }
+ }
+ } catch {
+ // Not a URL — fall through
+ }
+
+ // 3. WebSocket / Cloudflare / LAN / inkstudio://join invite URL
+ const wsInvite = parseInviteUrl(trimmed);
+ if (wsInvite) {
+ return {
+ kind: 'ws',
+ ...wsInvite,
+ };
+ }
+
+ return null;
+}
+
+export function buildP2pShareUrl(
+ roomCode: string,
+ roomSecret: string,
+ roomName: string,
+ customSignalingUrl?: string
+): string {
+ const params = new URLSearchParams();
+ const sig = sanitizeSignalingUrlParam(customSignalingUrl || null);
+
+ const isWebHttpOrigin =
+ typeof window !== 'undefined' &&
+ (window.location.protocol === 'http:' || window.location.protocol === 'https:') &&
+ window.location.hostname !== 'tauri.localhost' &&
+ window.location.hostname !== '';
+
+ if (isWebHttpOrigin) {
+ params.set('p2p', normalizeRoomCode(roomCode));
+ if (roomSecret) params.set('secret', normalizeRoomSecret(roomSecret));
+ if (roomName) params.set('room', roomName);
+ if (sig) params.set('sig', sig);
+ return `${window.location.origin}/?${params.toString()}`;
+ }
+
+ params.set('code', normalizeRoomCode(roomCode));
+ if (roomSecret) params.set('secret', normalizeRoomSecret(roomSecret));
+ if (roomName) params.set('room', roomName);
+ if (sig) params.set('sig', sig);
+ return `${DEEP_LINK_SCHEME}//p2p?${params.toString()}`;
+}
+
function sanitizeRemoteBrushSettings(raw: unknown): BrushSettings | null {
if (!raw || typeof raw !== 'object') return null;
const bs = raw as BrushSettings;
@@ -586,9 +788,11 @@ export interface ConnectOptions {
class MultiplayerService {
private ws: WebSocket | null = null;
+ private transport: ICollabTransport | null = null;
+ private transportUnsubs: Array<() => void> = [];
private messageHandlers: Set<MessageHandler> = new Set();
- private closeHandlers: Set<() => void> = new Set();
- private errorHandlers: Set<(err: Event) => void> = new Set();
+ private closeHandlers: Set<(reason?: string) => void> = new Set();
+ private errorHandlers: Set<(err: Event | Error) => void> = new Set();
private currentPeer: CollabPeer | null = null;
private localRole: CollabRole = 'editor';
@@ -653,7 +857,16 @@ class MultiplayerService {
}
public isConnected(): boolean {
- return this.ws !== null && this.ws.readyState === WebSocket.OPEN;
+ return (
+ (this.ws !== null && this.ws.readyState === WebSocket.OPEN) ||
+ (this.transport !== null && this.transport.isOpen())
+ );
+ }
+
+ public getTransportKind(): CollabTransportKind | null {
+ if (this.transport && this.transport.isOpen()) return this.transport.kind;
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) return 'ws';
+ return null;
}
public getPeer(): CollabPeer | null {
@@ -680,10 +893,60 @@ class MultiplayerService {
}
public getBufferedAmount(): number {
+ if (this.transport) return this.transport.getBufferedAmount();
return this.ws ? this.ws.bufferedAmount : 0;
}
+ private handleIncomingBinaryPayload(buf: ArrayBuffer): void {
+ const parsed = this.decodeBinaryPacket(buf);
+ if (!parsed) return;
+ if (buf.byteLength >= 7) {
+ const serverSeq = new DataView(buf).getUint32(3, true);
+ if (serverSeq > 0) {
+ parsed.seq = serverSeq;
+ this.updateServerSeq(serverSeq);
+ }
+ }
+ this.notifyHandlers(parsed);
+ }
+
+ private handleIncomingTextPayload(rawText: string): void {
+ if (rawText.length > MAX_JSON_MESSAGE_CHARS) return;
+ const raw = JSON.parse(rawText) as unknown;
+ const sanitized = sanitizeIncomingJsonMessage(raw);
+ if (!sanitized) return;
+ 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);
+ }
+
+ private detachTransportQuietly(): void {
+ for (const unsub of this.transportUnsubs) {
+ try {
+ unsub();
+ } catch {
+ // ignore
+ }
+ }
+ this.transportUnsubs = [];
+ if (this.transport) {
+ const closing = this.transport;
+ this.transport = null;
+ try {
+ closing.close();
+ } catch {
+ // ignore
+ }
+ }
+ }
+
private closeSocketQuietly(): void {
+ this.detachTransportQuietly();
if (!this.ws) return;
const closingWs = this.ws;
this.ws = null;
@@ -698,6 +961,84 @@ class MultiplayerService {
}
}
+ /**
+ * Attaches a custom `ICollabTransport` (e.g., WebRtcHostHub or WebRtcGuestClient)
+ * so the entire existing binary (`IN...`) & JSON protocol works identically over WebRTC.
+ */
+ public attachTransport(
+ transport: ICollabTransport,
+ peer: CollabPeer,
+ options?: ConnectOptions & { sendJoinRequest?: boolean }
+ ): void {
+ const isReconnect = Boolean(options?.isReconnect);
+ if (isReconnect) {
+ this.closeSocketQuietly();
+ } else {
+ this.disconnect();
+ }
+
+ this.transport = transport;
+ this.currentPeer = peer;
+ this.localRole = peer.isHost ? 'host' : peer.role ?? (isReconnect ? this.localRole : 'editor');
+
+ const unsubText = transport.onTextMessage((text) => {
+ if (this.transport !== transport) return;
+ try {
+ this.handleIncomingTextPayload(text);
+ } catch (err) {
+ console.error('[Multiplayer] Failed to parse transport JSON:', err);
+ }
+ });
+
+ const unsubBin = transport.onBinaryMessage((buf) => {
+ if (this.transport !== transport) return;
+ try {
+ this.handleIncomingBinaryPayload(buf);
+ } catch (err) {
+ console.error('[Multiplayer] Failed to parse transport binary:', err);
+ }
+ });
+
+ const unsubClose = transport.onClose((reason) => {
+ if (this.transport === transport) {
+ this.transport = null;
+ this.transportUnsubs = [];
+ this.closeHandlers.forEach((h) => h(reason));
+ }
+ });
+
+ const unsubErr = transport.onError((err) => {
+ if (this.transport !== transport) return;
+ this.errorHandlers.forEach((h) => h(err));
+ });
+
+ this.transportUnsubs = [unsubText, unsubBin, unsubClose, unsubErr];
+
+ const shouldSendJoin =
+ options?.sendJoinRequest !== undefined
+ ? options.sendJoinRequest
+ : transport.kind === 'webrtc-guest';
+
+ if (shouldSendJoin && transport.isOpen()) {
+ const resumeSeq =
+ isReconnect &&
+ typeof options?.sinceSeq === 'number' &&
+ Number.isSafeInteger(options.sinceSeq) &&
+ options.sinceSeq >= 0
+ ? options.sinceSeq
+ : isReconnect
+ ? this.lastServerSeq
+ : undefined;
+
+ this.sendMessage({
+ type: 'JOIN_REQUEST',
+ peer: this.currentPeer,
+ ...(isReconnect ? { isReconnect: true } : {}),
+ ...(resumeSeq !== undefined ? { sinceSeq: resumeSeq } : {}),
+ });
+ }
+ }
+
public connect(
url: string,
peer: CollabPeer,
@@ -852,6 +1193,19 @@ class MultiplayerService {
}
public disconnect() {
+ if (this.transport) {
+ if (
+ this.currentPeer &&
+ this.transport.isOpen() &&
+ this.transport.kind !== 'webrtc-host'
+ ) {
+ this.sendMessage({
+ type: 'PEER_LEFT',
+ peerId: this.currentPeer.id,
+ });
+ }
+ this.detachTransportQuietly();
+ }
if (this.ws) {
const closingWs = this.ws;
if (this.currentPeer && closingWs.readyState === WebSocket.OPEN) {
@@ -902,17 +1256,24 @@ class MultiplayerService {
return () => this.messageHandlers.delete(handler);
}
- public onClose(handler: () => void): () => void {
+ public onClose(handler: (reason?: string) => void): () => void {
this.closeHandlers.add(handler);
return () => this.closeHandlers.delete(handler);
}
- public onError(handler: (err: Event) => void): () => void {
+ public onError(handler: (err: Event | Error) => void): () => void {
this.errorHandlers.add(handler);
return () => this.errorHandlers.delete(handler);
}
public sendMessage(msg: MultiplayerMessage) {
+ if (this.transport && this.transport.isOpen()) {
+ if (!msg.senderId && this.currentPeer) {
+ msg.senderId = this.currentPeer.id;
+ }
+ this.transport.sendText(JSON.stringify(msg));
+ return;
+ }
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
if (!msg.senderId && this.currentPeer) {
msg.senderId = this.currentPeer.id;
@@ -921,7 +1282,15 @@ class MultiplayerService {
}
}
- public sendBinary(buffer: ArrayBuffer | Uint8Array) {
+ public sendBinary(buffer: ArrayBuffer | Uint8Array, targetPeerId?: string | number) {
+ if (this.transport && this.transport.isOpen()) {
+ if (targetPeerId !== undefined && this.transport.sendBinaryTo) {
+ this.transport.sendBinaryTo(targetPeerId, buffer);
+ return;
+ }
+ this.transport.sendBinary(buffer);
+ return;
+ }
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(buffer as any);
}
@@ -959,6 +1328,7 @@ class MultiplayerService {
if (!safeSettings || !isValidRemotePoint(data?.startPoint)) return null;
return {
type: 'STROKE_START',
+ senderId: data.peerId,
strokeId: String(data.strokeId || '').slice(0, 128),
peerId: data.peerId,
peerName: String(data.peerName || 'Peer').slice(0, 64),
@@ -1034,6 +1404,7 @@ class MultiplayerService {
return {
type: 'STROKE_CHUNK',
+ senderId: peerId,
strokeId,
peerId,
points,
@@ -1045,6 +1416,7 @@ class MultiplayerService {
const data = JSON.parse(jsonStr);
return {
type: 'STROKE_FINISH',
+ senderId: data.peerId,
strokeId: String(data.strokeId || '').slice(0, 128),
peerId: data.peerId,
layerId: String(data.layerId || '').slice(0, 256),
@@ -1158,6 +1530,7 @@ class MultiplayerService {
return {
type: 'CURSOR_MOVE',
+ senderId: peerId,
peerId,
x,
y,
@@ -1171,6 +1544,7 @@ class MultiplayerService {
const data = JSON.parse(jsonStr);
return {
type: 'SELECTIVE_UNDO',
+ senderId: data.peerId,
strokeId: data.strokeId,
peerId: data.peerId,
lamport: data.lamport,
@@ -1445,14 +1819,16 @@ class MultiplayerService {
/**
* Stream a single LZ4-compressed binary tile (or 14-byte deletion tombstone when tile.data === null).
*/
- public sendTileDelta(layerId: string, tile: TileBuffer) {
+ public sendTileDelta(layerId: string, tile: TileBuffer, targetPeerId?: string | number) {
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);
+ if (targetPeerId === undefined) {
+ if (tile.data === null) {
+ this.sentTileVersions.delete(tileKey);
+ } else if (tile.version > 0) {
+ this.sentTileVersions.set(tileKey, tile.version);
+ }
}
const encoder = new TextEncoder();
@@ -1476,7 +1852,7 @@ class MultiplayerService {
offset += layerIdBytes.length;
packet.set(tileBytes, offset);
- this.sendBinary(packet);
+ this.sendBinary(packet, targetPeerId);
}
/**
@@ -1775,7 +2151,8 @@ class MultiplayerService {
height: number,
isFullReplace: boolean,
solidValue: number | null,
- pixels: Uint8Array | null
+ pixels: Uint8Array | null,
+ targetPeerId?: string | number
) {
if (!this.isConnected() || !this.canSendMutation() || !layerId || width <= 0 || height <= 0) return;
@@ -1825,7 +2202,7 @@ class MultiplayerService {
offset += 16;
packet.set(body, offset);
- this.sendBinary(packet);
+ this.sendBinary(packet, targetPeerId);
}
public sendLayerMaskSolid(
@@ -1833,13 +2210,19 @@ class MultiplayerService {
width: number,
height: number,
value: number = 255,
- isFullReplace: boolean = true
+ isFullReplace: boolean = true,
+ targetPeerId?: string | number
) {
if (!this.isConnected() || width <= 0 || height <= 0) return;
- this.sendMaskPacket(layerId, 0, 0, width, height, isFullReplace, value, null);
+ this.sendMaskPacket(layerId, 0, 0, width, height, isFullReplace, value, null, targetPeerId);
}
- public sendLayerMaskData(layerId: string, maskCanvas: HTMLCanvasElement, rect?: DirtyRect) {
+ public sendLayerMaskData(
+ layerId: string,
+ maskCanvas: HTMLCanvasElement,
+ rect?: DirtyRect,
+ targetPeerId?: string | number
+ ) {
if (!this.isConnected() || !maskCanvas || maskCanvas.width <= 0 || maskCanvas.height <= 0) {
return;
}
@@ -1874,7 +2257,8 @@ class MultiplayerService {
extracted.height,
isFull,
extracted.solidValue,
- extracted.solidValue === null ? extracted.pixels : null
+ extracted.solidValue === null ? extracted.pixels : null,
+ targetPeerId
);
return;
}
@@ -1915,7 +2299,7 @@ class MultiplayerService {
// 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);
+ this.sendMaskPacket(layerId, x0, y0, totalW, totalH, isFull, firstSolid, null, targetPeerId);
return;
}
@@ -1930,7 +2314,17 @@ class MultiplayerService {
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);
+ this.sendMaskPacket(
+ layerId,
+ c.x,
+ c.y,
+ c.width,
+ c.height,
+ false,
+ c.solidValue,
+ c.pixels,
+ targetPeerId
+ );
}
if (idx < chunks.length) {
setTimeout(pump, 4);
diff --git a/src/services/webrtcGuestClient.ts b/src/services/webrtcGuestClient.ts
new file mode 100644
index 0000000..69309ad
--- /dev/null
+++ b/src/services/webrtcGuestClient.ts
@@ -0,0 +1,447 @@
+import {
+ ChunkReassembler,
+ ICollabTransport,
+ sendFramedOverDataChannel,
+} from './collabTransport';
+import {
+ buildIceServers,
+ WEBRTC_DATACHANNEL_LABEL,
+ WebRtcTurnConfig,
+} from './webrtcHostHub';
+import {
+ createSignalingClient,
+ ISignalingClient,
+ SignalingEnvelope,
+} from './webrtcSignaling';
+
+export interface WebRtcGuestClientOptions {
+ roomHash: string;
+ peerId: string;
+ turnConfig?: WebRtcTurnConfig;
+ customSignalingUrl?: string;
+ signalingClient?: ISignalingClient;
+ connectTimeoutMs?: number;
+}
+
+/**
+ * WebRTC Star-Topology Guest Client.
+ *
+ * Exchanges SDP offer/answer & ICE via the pluggable zero-cost signaling client,
+ * then opens a reliable ordered RTCDataChannel carrying 48 KB framed JSON + binary
+ * packets directly to/from the Host Hub.
+ */
+export class WebRtcGuestClient implements ICollabTransport {
+ public readonly kind = 'webrtc-guest' as const;
+
+ public readonly roomHash: string;
+ private readonly peerId: string;
+ private readonly iceServers: RTCIceServer[];
+ private readonly connectTimeoutMs: number;
+ private readonly signaling: ISignalingClient;
+
+ private pc: RTCPeerConnection | null = null;
+ private dc: RTCDataChannel | null = null;
+ private reassembler = new ChunkReassembler();
+ private remoteDescSet = false;
+ private pendingIce: RTCIceCandidateInit[] = [];
+ private localIceCandidates: NonNullable<SignalingEnvelope['candidate']>[] = [];
+ private hostSignalingPeerId: string | null = null;
+
+ private textHandlers = new Set<(text: string) => void>();
+ private binaryHandlers = new Set<(data: ArrayBuffer) => void>();
+ private closeHandlers = new Set<(reason?: string) => void>();
+ private errorHandlers = new Set<(err: Error | Event) => void>();
+
+ private unsubSignaling: (() => void) | null = null;
+ private offerRetryTimer: ReturnType<typeof setInterval> | null = null;
+ private signalingCloseTimer: ReturnType<typeof setTimeout> | null = null;
+ private disconnectTimer: ReturnType<typeof setTimeout> | null = null;
+ private nextMsgId = 1;
+ private closed = false;
+ private hasNotifiedClose = false;
+
+ constructor(options: WebRtcGuestClientOptions) {
+ this.roomHash = options.roomHash;
+ this.peerId = options.peerId;
+ this.iceServers = buildIceServers(options.turnConfig);
+ this.connectTimeoutMs = options.connectTimeoutMs ?? 20_000;
+ this.signaling =
+ options.signalingClient ??
+ createSignalingClient({
+ roomHash: options.roomHash,
+ peerId: options.peerId,
+ customSignalingUrl: options.customSignalingUrl,
+ });
+ }
+
+ private allocMessageId = (): number => {
+ this.nextMsgId = (this.nextMsgId + 1) >>> 0;
+ if (this.nextMsgId === 0) this.nextMsgId = 1;
+ return this.nextMsgId;
+ };
+
+ public async connect(): Promise<void> {
+ if (this.closed) {
+ throw new Error('WebRTC Guest Client already closed');
+ }
+ if (typeof RTCPeerConnection === 'undefined') {
+ throw new Error('WebRTC is not supported in this browser/WebView');
+ }
+
+ await this.signaling.connect();
+
+ return new Promise<void>((resolve, reject) => {
+ let settled = false;
+
+ const clearTimers = () => {
+ if (timeoutId !== null) {
+ clearTimeout(timeoutId);
+ timeoutId = null;
+ }
+ if (this.offerRetryTimer !== null) {
+ clearInterval(this.offerRetryTimer);
+ this.offerRetryTimer = null;
+ }
+ };
+
+ const settleResolve = () => {
+ if (settled) return;
+ settled = true;
+ clearTimers();
+ // Close signaling shortly after DataChannel opens (zero ongoing signaling traffic)
+ this.signalingCloseTimer = setTimeout(() => {
+ this.unsubSignaling?.();
+ this.unsubSignaling = null;
+ this.signaling.close();
+ }, 3_000);
+ resolve();
+ };
+
+ const settleReject = (err: Error) => {
+ if (settled) return;
+ settled = true;
+ clearTimers();
+ this.closeInternal(false);
+ reject(err);
+ };
+
+ let timeoutId: ReturnType<typeof setTimeout> | null = setTimeout(() => {
+ settleReject(
+ new Error(
+ 'Could not reach the room host. Verify the Room Code/Secret and ensure the host tablet is online.'
+ )
+ );
+ }, this.connectTimeoutMs);
+
+ const pc = new RTCPeerConnection({ iceServers: this.iceServers });
+ this.pc = pc;
+
+ const dc = pc.createDataChannel(WEBRTC_DATACHANNEL_LABEL, { ordered: true });
+ dc.binaryType = 'arraybuffer';
+ this.dc = dc;
+
+ dc.onopen = () => {
+ settleResolve();
+ };
+
+ dc.onmessage = async (msgEv) => {
+ if (this.closed) return;
+ try {
+ const rawBuf =
+ msgEv.data instanceof ArrayBuffer
+ ? msgEv.data
+ : msgEv.data instanceof Blob
+ ? await msgEv.data.arrayBuffer()
+ : null;
+ if (!rawBuf) return;
+
+ const assembled = this.reassembler.pushFrame(rawBuf);
+ if (!assembled) return;
+
+ if (assembled.kind === 'text') {
+ this.textHandlers.forEach((h) => h(assembled.text));
+ } else {
+ this.binaryHandlers.forEach((h) => h(assembled.data));
+ }
+ } catch {
+ // drop malformed frame
+ }
+ };
+
+ dc.onclose = () => {
+ if (!settled) {
+ settleReject(new Error('Host closed the connection before handshake completed'));
+ } else {
+ this.emitCloseOnce('Host disconnected from the P2P room');
+ }
+ };
+
+ dc.onerror = (ev) => {
+ this.errorHandlers.forEach((h) => h(ev));
+ };
+
+ pc.onicecandidate = (ev) => {
+ if (this.closed || !ev.candidate) return;
+ const json = ev.candidate.toJSON ? ev.candidate.toJSON() : undefined;
+ const candidateStr = json?.candidate ?? ev.candidate.candidate ?? '';
+ if (!candidateStr) return;
+ const candidateInit: NonNullable<SignalingEnvelope['candidate']> = {
+ candidate: candidateStr,
+ sdpMid: json?.sdpMid ?? ev.candidate.sdpMid ?? null,
+ sdpMLineIndex: json?.sdpMLineIndex ?? ev.candidate.sdpMLineIndex ?? null,
+ ...(json?.usernameFragment != null ? { usernameFragment: json.usernameFragment } : {}),
+ };
+ if (this.localIceCandidates.length < 64) {
+ this.localIceCandidates.push(candidateInit);
+ }
+ this.signaling.send({
+ type: 'ice',
+ fromPeerId: this.peerId,
+ ...(this.hostSignalingPeerId ? { toPeerId: this.hostSignalingPeerId } : {}),
+ candidate: candidateInit,
+ });
+ };
+
+ pc.onconnectionstatechange = () => {
+ if (pc.connectionState === 'connected') {
+ if (this.disconnectTimer !== null) {
+ clearTimeout(this.disconnectTimer);
+ this.disconnectTimer = null;
+ }
+ return;
+ }
+ if (pc.connectionState === 'failed' || pc.connectionState === 'closed') {
+ if (!settled) {
+ settleReject(
+ new Error(
+ 'WebRTC peer connection failed (strict firewall/NAT). Try configuring an optional TURN server in Settings.'
+ )
+ );
+ } else {
+ this.emitCloseOnce('Host disconnected from the P2P room');
+ }
+ } else if (pc.connectionState === 'disconnected' && settled) {
+ if (this.disconnectTimer === null) {
+ this.disconnectTimer = setTimeout(() => {
+ this.disconnectTimer = null;
+ if (!this.closed && this.pc?.connectionState === 'disconnected') {
+ this.emitCloseOnce('Host disconnected from the P2P room');
+ }
+ }, 5_000);
+ }
+ }
+ };
+
+ this.unsubSignaling = this.signaling.onMessage((env: SignalingEnvelope) => {
+ void this.handleSignalingEnvelope(env, settleReject);
+ });
+
+ // Create & broadcast offer (with periodic retry carrying live gathered SDP & ICE until answer arrives)
+ pc.createOffer()
+ .then(async (offer) => {
+ if (this.closed) return;
+ await pc.setLocalDescription(offer);
+ const initialSdp = pc.localDescription?.sdp || offer.sdp;
+ if (!initialSdp) {
+ settleReject(new Error('Failed to generate WebRTC SDP offer'));
+ return;
+ }
+
+ const sendOffer = () => {
+ if (this.closed || this.remoteDescSet) return;
+ const liveSdp = pc.localDescription?.sdp || initialSdp;
+ this.signaling.send({
+ type: 'offer',
+ fromPeerId: this.peerId,
+ sdp: liveSdp,
+ sdpType: 'offer',
+ });
+ for (const cand of this.localIceCandidates) {
+ this.signaling.send({
+ type: 'ice',
+ fromPeerId: this.peerId,
+ candidate: cand,
+ });
+ }
+ };
+
+ sendOffer();
+ this.offerRetryTimer = setInterval(sendOffer, 2_500);
+ })
+ .catch((err) => {
+ settleReject(err instanceof Error ? err : new Error('Failed to create WebRTC offer'));
+ });
+ });
+ }
+
+ private async handleSignalingEnvelope(
+ env: SignalingEnvelope,
+ onFatalError: (err: Error) => void
+ ): Promise<void> {
+ if (this.closed || !this.pc) return;
+
+ if (env.type === 'room-full') {
+ onFatalError(new Error(env.reason || 'Room is full (maximum 8 guests)'));
+ return;
+ }
+
+ if (env.type === 'bye' && env.fromPeerId === this.hostSignalingPeerId) {
+ this.emitCloseOnce(env.reason || 'Host closed the P2P room');
+ return;
+ }
+
+ if (env.type === 'answer' && env.sdp && !this.remoteDescSet) {
+ this.hostSignalingPeerId = env.fromPeerId;
+ if (this.offerRetryTimer !== null) {
+ clearInterval(this.offerRetryTimer);
+ this.offerRetryTimer = null;
+ }
+ try {
+ await this.pc.setRemoteDescription({ type: 'answer', sdp: env.sdp });
+ this.remoteDescSet = true;
+ for (const cand of this.pendingIce.splice(0)) {
+ try {
+ await this.pc.addIceCandidate(cand);
+ } catch {
+ // ignore stale candidate
+ }
+ }
+ // Replay any local ICE candidates gathered before we knew hostSignalingPeerId
+ for (const localCand of this.localIceCandidates) {
+ this.signaling.send({
+ type: 'ice',
+ fromPeerId: this.peerId,
+ toPeerId: this.hostSignalingPeerId,
+ candidate: localCand,
+ });
+ }
+ } catch (err) {
+ onFatalError(
+ err instanceof Error ? err : new Error('Failed to apply WebRTC answer from host')
+ );
+ }
+ return;
+ }
+
+ if (env.type === 'ice' && env.candidate) {
+ if (!this.remoteDescSet) {
+ if (this.pendingIce.length < 64) {
+ this.pendingIce.push(env.candidate);
+ }
+ return;
+ }
+ try {
+ await this.pc.addIceCandidate(env.candidate);
+ } catch {
+ // ignore invalid candidate
+ }
+ }
+ }
+
+ private emitCloseOnce(reason?: string): void {
+ if (this.hasNotifiedClose) return;
+ this.hasNotifiedClose = true;
+ this.closeInternal(false);
+ this.closeHandlers.forEach((h) => h(reason));
+ }
+
+ public isOpen(): boolean {
+ return !this.closed && this.dc !== null && this.dc.readyState === 'open';
+ }
+
+ public getBufferedAmount(): number {
+ return this.dc && this.dc.readyState === 'open' ? this.dc.bufferedAmount || 0 : 0;
+ }
+
+ public sendText(text: string): void {
+ if (!this.dc || this.dc.readyState !== 'open') return;
+ sendFramedOverDataChannel(this.dc, 'text', text, this.allocMessageId);
+ }
+
+ public sendBinary(data: ArrayBuffer | Uint8Array): void {
+ if (!this.dc || this.dc.readyState !== 'open') return;
+ sendFramedOverDataChannel(this.dc, 'binary', data, this.allocMessageId);
+ }
+
+ public onTextMessage(handler: (text: string) => void): () => void {
+ this.textHandlers.add(handler);
+ return () => this.textHandlers.delete(handler);
+ }
+
+ public onBinaryMessage(handler: (data: ArrayBuffer) => void): () => void {
+ this.binaryHandlers.add(handler);
+ return () => this.binaryHandlers.delete(handler);
+ }
+
+ public onClose(handler: (reason?: string) => void): () => void {
+ this.closeHandlers.add(handler);
+ return () => this.closeHandlers.delete(handler);
+ }
+
+ public onError(handler: (err: Error | Event) => void): () => void {
+ this.errorHandlers.add(handler);
+ return () => this.errorHandlers.delete(handler);
+ }
+
+ private closeInternal(sendBye: boolean): void {
+ if (this.closed) return;
+ this.closed = true;
+
+ if (this.offerRetryTimer !== null) {
+ clearInterval(this.offerRetryTimer);
+ this.offerRetryTimer = null;
+ }
+ if (this.signalingCloseTimer !== null) {
+ clearTimeout(this.signalingCloseTimer);
+ this.signalingCloseTimer = null;
+ }
+ if (this.disconnectTimer !== null) {
+ clearTimeout(this.disconnectTimer);
+ this.disconnectTimer = null;
+ }
+ if (sendBye) {
+ try {
+ this.signaling.send({
+ type: 'bye',
+ fromPeerId: this.peerId,
+ ...(this.hostSignalingPeerId ? { toPeerId: this.hostSignalingPeerId } : {}),
+ });
+ } catch {
+ // ignore
+ }
+ }
+
+ this.unsubSignaling?.();
+ this.unsubSignaling = null;
+ this.signaling.close();
+ this.reassembler.clear();
+
+ try {
+ if (this.dc) {
+ this.dc.onopen = null;
+ this.dc.onmessage = null;
+ this.dc.onclose = null;
+ this.dc.onerror = null;
+ this.dc.close();
+ }
+ } catch {
+ // ignore
+ }
+ this.dc = null;
+
+ try {
+ if (this.pc) {
+ this.pc.onicecandidate = null;
+ this.pc.onconnectionstatechange = null;
+ this.pc.close();
+ }
+ } catch {
+ // ignore
+ }
+ this.pc = null;
+ }
+
+ public close(): void {
+ this.closeInternal(true);
+ }
+}
diff --git a/src/services/webrtcHostHub.ts b/src/services/webrtcHostHub.ts
new file mode 100644
index 0000000..6ba33ae
--- /dev/null
+++ b/src/services/webrtcHostHub.ts
@@ -0,0 +1,940 @@
+import { CollabRole } from '../types/multiplayer';
+import {
+ ChunkReassembler,
+ ICollabTransport,
+ sendFramedOverDataChannel,
+ toUint8Array,
+} from './collabTransport';
+import {
+ createSignalingClient,
+ ISignalingClient,
+ SignalingEnvelope,
+} from './webrtcSignaling';
+
+export const WEBRTC_DATACHANNEL_LABEL = 'inkstudio-collab';
+export const MAX_WEBRTC_PEERS = 8;
+
+export const DEFAULT_WEBRTC_ICE_SERVERS: RTCIceServer[] = [
+ { urls: 'stun:stun.l.google.com:19302' },
+ { urls: 'stun:stun1.l.google.com:19302' },
+ { urls: 'stun:stun.cloudflare.com:3478' },
+];
+
+export interface WebRtcTurnConfig {
+ turnUrl?: string;
+ turnUsername?: string;
+ turnCredential?: string;
+}
+
+export function buildIceServers(turn?: WebRtcTurnConfig): RTCIceServer[] {
+ const servers: RTCIceServer[] = DEFAULT_WEBRTC_ICE_SERVERS.map((s) => ({ ...s }));
+ const url = (turn?.turnUrl || '').trim();
+ if (url && /^(turns?:)/i.test(url)) {
+ const entry: RTCIceServer = { urls: url };
+ if (turn?.turnUsername?.trim()) entry.username = turn.turnUsername.trim();
+ if (turn?.turnCredential?.trim()) entry.credential = turn.turnCredential.trim();
+ servers.push(entry);
+ }
+ return servers;
+}
+
+const BINARY_MAGIC_0 = 0x49; // 'I'
+const BINARY_MAGIC_1 = 0x4e; // 'N'
+const CODE_STROKE_START = 0x01;
+const CODE_STROKE_FINISH = 0x03;
+const CODE_TILE_DELTA = 0x04;
+const CODE_CURSOR_MOVE = 0x05;
+const CODE_BRUSH_ASSET_REQUEST = 0x08;
+const CODE_LAYER_MASK_DATA = 0x09;
+
+const DISCONNECTED_GRACE_MS = 5_000;
+const sharedTextDecoder = new TextDecoder();
+
+interface LayerLockMeta {
+ ownerPeerId?: string;
+ reservedByPeerId?: string;
+}
+
+type SignalingIceCandidate = NonNullable<SignalingEnvelope['candidate']>;
+
+const VIEWER_ALLOWED_JSON_TYPES = new Set<string>([
+ 'JOIN_REQUEST',
+ 'DOC_SYNC_REQUEST',
+ 'CURSOR_MOVE',
+ 'CANVAS_PING',
+ 'BRUSH_ASSET_REQUEST',
+ 'PEER_LEFT',
+]);
+
+const HOST_ONLY_MODERATION_TYPES = new Set<string>([
+ 'PEER_ROLE_UPDATE',
+ 'PEER_KICK',
+ 'PEER_BAN',
+ 'PEER_UNBAN',
+]);
+
+const HOST_ONLY_CONSUME_TYPES = new Set<string>(['JOIN_REQUEST', 'DOC_SYNC_REQUEST']);
+
+const UNICAST_FROM_HOST_TYPES = new Set<string>([
+ 'JOIN_ACCEPTED',
+ 'DOC_SYNC_RESPONSE',
+ 'ACCESS_DENIED',
+ 'BRUSH_ASSET_REQUEST',
+]);
+
+interface GuestConnection {
+ signalingPeerId: string;
+ appPeerId: string | null;
+ joined: boolean;
+ role: Exclude<CollabRole, 'host'>;
+ pc: RTCPeerConnection;
+ dc: RTCDataChannel | null;
+ reassembler: ChunkReassembler;
+ remoteDescSet: boolean;
+ pendingIce: RTCIceCandidateInit[];
+ localIceCandidates: SignalingIceCandidate[];
+ lastAnswerSdp: string | null;
+ disconnectTimer: ReturnType<typeof setTimeout> | null;
+ closed: boolean;
+}
+
+export interface WebRtcHostHubOptions {
+ roomHash: string;
+ hostPeerId: string;
+ turnConfig?: WebRtcTurnConfig;
+ customSignalingUrl?: string;
+ signalingClient?: ISignalingClient;
+ maxPeers?: number;
+}
+
+/**
+ * Authoritative Star-Topology WebRTC Host Hub.
+ *
+ * The Host tablet/browser accepts up to 8 concurrent RTCDataChannel guest connections,
+ * enforces Host / Editor / Viewer roles, relays live strokes/tiles/layers/cursors across peers,
+ * and plugs directly into `multiplayerService` via `ICollabTransport`.
+ */
+export class WebRtcHostHub implements ICollabTransport {
+ public readonly kind = 'webrtc-host' as const;
+
+ public readonly roomHash: string;
+ private readonly hostPeerId: string;
+ private readonly iceServers: RTCIceServer[];
+ private readonly maxPeers: number;
+ private readonly signaling: ISignalingClient;
+
+ private guests = new Map<string, GuestConnection>();
+ private layerLocks = new Map<string, LayerLockMeta>();
+ private textHandlers = new Set<(text: string) => void>();
+ private binaryHandlers = new Set<(data: ArrayBuffer) => void>();
+ private closeHandlers = new Set<(reason?: string) => void>();
+ private errorHandlers = new Set<(err: Error | Event) => void>();
+
+ private unsubSignaling: (() => void) | null = null;
+ private nextMsgId = 1;
+ private seq = 0;
+ private open = false;
+ private closed = false;
+
+ constructor(options: WebRtcHostHubOptions) {
+ this.roomHash = options.roomHash;
+ this.hostPeerId = options.hostPeerId;
+ this.iceServers = buildIceServers(options.turnConfig);
+ this.maxPeers = Math.max(1, Math.min(MAX_WEBRTC_PEERS, options.maxPeers ?? MAX_WEBRTC_PEERS));
+ this.signaling =
+ options.signalingClient ??
+ createSignalingClient({
+ roomHash: options.roomHash,
+ peerId: options.hostPeerId,
+ customSignalingUrl: options.customSignalingUrl,
+ });
+ }
+
+ public async start(): Promise<void> {
+ if (this.closed) {
+ throw new Error('WebRTC Host Hub has already been closed');
+ }
+ if (typeof RTCPeerConnection === 'undefined') {
+ throw new Error('WebRTC is not supported in this browser/WebView');
+ }
+
+ this.unsubSignaling = this.signaling.onMessage((env) => {
+ void this.handleSignalingEnvelope(env);
+ });
+
+ await this.signaling.connect();
+ this.open = true;
+ }
+
+ public isOpen(): boolean {
+ return this.open && !this.closed;
+ }
+
+ public getConnectedGuestCount(): number {
+ let count = 0;
+ for (const g of this.guests.values()) {
+ if (!g.closed && g.dc?.readyState === 'open') count += 1;
+ }
+ return count;
+ }
+
+ public getBufferedAmount(): number {
+ let maxBuffered = 0;
+ for (const g of this.guests.values()) {
+ if (g.dc && g.dc.readyState === 'open') {
+ maxBuffered = Math.max(maxBuffered, g.dc.bufferedAmount || 0);
+ }
+ }
+ return maxBuffered;
+ }
+
+ private allocMessageId = (): number => {
+ this.nextMsgId = (this.nextMsgId + 1) >>> 0;
+ if (this.nextMsgId === 0) this.nextMsgId = 1;
+ return this.nextMsgId;
+ };
+
+ private findGuestByAppOrSignalingId(peerId: string | number | undefined): GuestConnection | null {
+ if (peerId === undefined || peerId === null) return null;
+ const target = String(peerId);
+ for (const guest of this.guests.values()) {
+ if (guest.appPeerId === target || guest.signalingPeerId === target) {
+ return guest;
+ }
+ }
+ return null;
+ }
+
+ private sendTextToGuest(guest: GuestConnection, text: string): void {
+ if (guest.closed || !guest.dc || guest.dc.readyState !== 'open') return;
+ try {
+ sendFramedOverDataChannel(guest.dc, 'text', text, this.allocMessageId);
+ } catch {
+ // ignore send failure on closing channel
+ }
+ }
+
+ private sendBinaryToGuest(guest: GuestConnection, data: ArrayBuffer | Uint8Array): void {
+ if (guest.closed || !guest.dc || guest.dc.readyState !== 'open') return;
+ try {
+ sendFramedOverDataChannel(guest.dc, 'binary', data, this.allocMessageId);
+ } catch {
+ // ignore send failure on closing channel
+ }
+ }
+
+ private sendAccessDeniedToGuest(
+ guest: GuestConnection,
+ code: 'VIEWER_READONLY' | 'FORBIDDEN' | 'LAYER_LOCKED' | 'NOT_OWNER',
+ reason: string
+ ): void {
+ const payload = JSON.stringify({
+ type: 'ACCESS_DENIED',
+ senderId: this.hostPeerId,
+ targetPeerId: guest.appPeerId || guest.signalingPeerId,
+ code,
+ reason,
+ });
+ this.sendTextToGuest(guest, payload);
+ }
+
+ private stampBinarySeq(data: ArrayBuffer | Uint8Array): Uint8Array {
+ const src = toUint8Array(data);
+ const out = new Uint8Array(src.byteLength);
+ out.set(src);
+ if (out.byteLength >= 11 && out[0] === BINARY_MAGIC_0 && out[1] === BINARY_MAGIC_1) {
+ const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
+ view.setUint32(3, ++this.seq, true);
+ }
+ return out;
+ }
+
+ private syncLayerLocksFromWireList(layersRaw: unknown): void {
+ if (!Array.isArray(layersRaw)) return;
+ const next = new Map<string, LayerLockMeta>();
+ for (const item of layersRaw) {
+ if (!item || typeof item !== 'object') continue;
+ const obj = item as Record<string, unknown>;
+ if (typeof obj.id !== 'string' || !obj.id) continue;
+ const ownerPeerId =
+ obj.ownerPeerId !== undefined && obj.ownerPeerId !== null && obj.ownerPeerId !== ''
+ ? String(obj.ownerPeerId)
+ : undefined;
+ const reservedByPeerId =
+ obj.reservedByPeerId !== undefined &&
+ obj.reservedByPeerId !== null &&
+ obj.reservedByPeerId !== ''
+ ? String(obj.reservedByPeerId)
+ : undefined;
+ next.set(obj.id, { ownerPeerId, reservedByPeerId });
+ }
+ this.layerLocks = next;
+ }
+
+ private applyLayerLockMutation(parsed: Record<string, unknown>): void {
+ const type = typeof parsed.type === 'string' ? parsed.type : '';
+ if (type === 'DOC_SYNC_RESPONSE' || type === 'LAYER_TREE_SYNC') {
+ this.syncLayerLocksFromWireList(parsed.layers);
+ return;
+ }
+ if (type === 'LAYER_ADD' && parsed.layerItem && typeof parsed.layerItem === 'object') {
+ const item = parsed.layerItem as Record<string, unknown>;
+ if (typeof item.id === 'string' && item.id) {
+ this.layerLocks.set(item.id, {
+ ownerPeerId:
+ item.ownerPeerId !== undefined && item.ownerPeerId !== null && item.ownerPeerId !== ''
+ ? String(item.ownerPeerId)
+ : undefined,
+ reservedByPeerId:
+ item.reservedByPeerId !== undefined &&
+ item.reservedByPeerId !== null &&
+ item.reservedByPeerId !== ''
+ ? String(item.reservedByPeerId)
+ : undefined,
+ });
+ }
+ return;
+ }
+ if (type === 'LAYER_DELETE' && typeof parsed.layerId === 'string') {
+ this.layerLocks.delete(parsed.layerId);
+ return;
+ }
+ if (type === 'LAYER_UPDATE' && typeof parsed.layerId === 'string') {
+ const existing = this.layerLocks.get(parsed.layerId) || {};
+ const next: LayerLockMeta = { ...existing };
+ const patch =
+ parsed.patch && typeof parsed.patch === 'object'
+ ? (parsed.patch as Record<string, unknown>)
+ : null;
+ const cleared = Array.isArray(parsed.clearedFields) ? parsed.clearedFields : [];
+ if (patch) {
+ if (patch.ownerPeerId !== undefined && patch.ownerPeerId !== null && patch.ownerPeerId !== '') {
+ next.ownerPeerId = String(patch.ownerPeerId);
+ }
+ if (
+ patch.reservedByPeerId !== undefined &&
+ patch.reservedByPeerId !== null &&
+ patch.reservedByPeerId !== ''
+ ) {
+ next.reservedByPeerId = String(patch.reservedByPeerId);
+ }
+ }
+ if (cleared.includes('ownerPeerId')) delete next.ownerPeerId;
+ if (cleared.includes('reservedByPeerId')) delete next.reservedByPeerId;
+ this.layerLocks.set(parsed.layerId, next);
+ return;
+ }
+ if (type === 'PEER_BAN' && parsed.targetPeerId !== undefined && parsed.targetPeerId !== null) {
+ const bannedId = String(parsed.targetPeerId);
+ for (const meta of this.layerLocks.values()) {
+ if (meta.reservedByPeerId === bannedId) {
+ delete meta.reservedByPeerId;
+ }
+ }
+ }
+ }
+
+ private isLayerLockedForGuest(layerId: string, guestPeerId: string): boolean {
+ const meta = this.layerLocks.get(layerId);
+ return Boolean(meta?.reservedByPeerId && meta.reservedByPeerId !== guestPeerId);
+ }
+
+ private extractBinaryLayerId(bytes: Uint8Array, opcode: number): string | null {
+ if (bytes.byteLength < 11) return null;
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ const payloadLen = view.getUint32(7, true);
+ if (11 + payloadLen > bytes.byteLength) return null;
+
+ if (opcode === CODE_TILE_DELTA || opcode === CODE_LAYER_MASK_DATA) {
+ if (payloadLen < 2) return null;
+ const layerIdLen = view.getUint16(11, true);
+ if (layerIdLen === 0 || layerIdLen > 256 || 13 + layerIdLen > 11 + payloadLen) return null;
+ return sharedTextDecoder.decode(bytes.subarray(13, 13 + layerIdLen));
+ }
+
+ if (opcode === CODE_STROKE_START || opcode === CODE_STROKE_FINISH) {
+ try {
+ const jsonStr = sharedTextDecoder.decode(bytes.subarray(11, 11 + payloadLen));
+ const parsed = JSON.parse(jsonStr) as { layerId?: unknown };
+ return typeof parsed?.layerId === 'string' ? parsed.layerId : null;
+ } catch {
+ return null;
+ }
+ }
+
+ return null;
+ }
+
+ private broadcastText(text: string, excludeSignalingId?: string): void {
+ for (const guest of this.guests.values()) {
+ if (excludeSignalingId && guest.signalingPeerId === excludeSignalingId) continue;
+ this.sendTextToGuest(guest, text);
+ }
+ }
+
+ private broadcastBinary(data: ArrayBuffer | Uint8Array, excludeSignalingId?: string): void {
+ for (const guest of this.guests.values()) {
+ if (excludeSignalingId && guest.signalingPeerId === excludeSignalingId) continue;
+ this.sendBinaryToGuest(guest, data);
+ }
+ }
+
+ public sendText(text: string): void {
+ if (!this.isOpen()) return;
+
+ let parsed: Record<string, unknown> | null = null;
+ try {
+ const raw = JSON.parse(text) as unknown;
+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
+ parsed = raw as Record<string, unknown>;
+ }
+ } catch {
+ // send raw
+ }
+
+ if (parsed) {
+ const type = typeof parsed.type === 'string' ? parsed.type : '';
+ const targetPeerId =
+ typeof parsed.targetPeerId === 'string' || typeof parsed.targetPeerId === 'number'
+ ? String(parsed.targetPeerId)
+ : undefined;
+
+ // Stateful Rust server seed is unnecessary in P2P host hub (Host is already live)
+ if (targetPeerId === '__server__') {
+ return;
+ }
+
+ if (type === 'PEER_ROLE_UPDATE' && targetPeerId) {
+ const guest = this.findGuestByAppOrSignalingId(targetPeerId);
+ if (guest) {
+ guest.role = parsed.role === 'viewer' ? 'viewer' : 'editor';
+ }
+ } else if (type === 'JOIN_ACCEPTED' && targetPeerId) {
+ const guest = this.findGuestByAppOrSignalingId(targetPeerId);
+ if (guest && (parsed.assignedRole === 'viewer' || parsed.assignedRole === 'editor')) {
+ guest.role = parsed.assignedRole;
+ }
+ }
+
+ this.applyLayerLockMutation(parsed);
+
+ const sequenced =
+ typeof parsed.seq === 'number'
+ ? text
+ : JSON.stringify({ ...parsed, seq: ++this.seq });
+
+ if (
+ type === 'PEER_KICK' ||
+ type === 'PEER_BAN' ||
+ (type === 'ACCESS_DENIED' && (parsed.code === 'BANNED' || parsed.code === 'KICKED'))
+ ) {
+ const guest = this.findGuestByAppOrSignalingId(targetPeerId);
+ if (type === 'ACCESS_DENIED') {
+ if (guest) this.sendTextToGuest(guest, sequenced);
+ } else {
+ this.broadcastText(sequenced);
+ }
+ if (guest) {
+ setTimeout(() => this.removeGuest(guest.signalingPeerId, false), 80);
+ }
+ return;
+ }
+
+ if (targetPeerId && UNICAST_FROM_HOST_TYPES.has(type)) {
+ const targetGuest = this.findGuestByAppOrSignalingId(targetPeerId);
+ if (targetGuest) {
+ this.sendTextToGuest(targetGuest, sequenced);
+ }
+ return;
+ }
+
+ this.broadcastText(sequenced);
+ return;
+ }
+
+ this.broadcastText(text);
+ }
+
+ public sendBinary(data: ArrayBuffer | Uint8Array): void {
+ if (!this.isOpen()) return;
+ this.broadcastBinary(this.stampBinarySeq(data));
+ }
+
+ public sendBinaryTo(targetPeerId: string | number, data: ArrayBuffer | Uint8Array): void {
+ if (!this.isOpen()) return;
+ const guest = this.findGuestByAppOrSignalingId(targetPeerId);
+ if (!guest) return;
+ this.sendBinaryToGuest(guest, this.stampBinarySeq(data));
+ }
+
+ private async handleSignalingEnvelope(env: SignalingEnvelope): Promise<void> {
+ if (this.closed) return;
+
+ if (env.type === 'offer' && env.sdp) {
+ const existing = this.guests.get(env.fromPeerId);
+ if (existing) {
+ if (!existing.closed) {
+ if (existing.pc.connectionState === 'connected' || existing.dc?.readyState === 'open') {
+ return;
+ }
+ // Resend answer + gathered host ICE candidates on duplicate offer retries while connecting/new
+ if (
+ existing.lastAnswerSdp &&
+ (existing.pc.connectionState === 'connecting' || existing.pc.connectionState === 'new')
+ ) {
+ const latestAnswerSdp = existing.pc.localDescription?.sdp || existing.lastAnswerSdp;
+ this.signaling.send({
+ type: 'answer',
+ fromPeerId: this.hostPeerId,
+ toPeerId: existing.signalingPeerId,
+ sdp: latestAnswerSdp,
+ sdpType: 'answer',
+ });
+ for (const cand of existing.localIceCandidates) {
+ this.signaling.send({
+ type: 'ice',
+ fromPeerId: this.hostPeerId,
+ toPeerId: existing.signalingPeerId,
+ candidate: cand,
+ });
+ }
+ return;
+ }
+ }
+ this.removeGuest(env.fromPeerId, false);
+ }
+
+ if (this.guests.size >= this.maxPeers) {
+ this.signaling.send({
+ type: 'room-full',
+ fromPeerId: this.hostPeerId,
+ toPeerId: env.fromPeerId,
+ reason: `Room is full (maximum ${this.maxPeers} guests)`,
+ });
+ return;
+ }
+
+ const pc = new RTCPeerConnection({ iceServers: this.iceServers });
+ const guest: GuestConnection = {
+ signalingPeerId: env.fromPeerId,
+ appPeerId: null,
+ joined: false,
+ role: 'editor',
+ pc,
+ dc: null,
+ reassembler: new ChunkReassembler(),
+ remoteDescSet: false,
+ pendingIce: [],
+ localIceCandidates: [],
+ lastAnswerSdp: null,
+ disconnectTimer: null,
+ closed: false,
+ };
+ this.guests.set(env.fromPeerId, guest);
+
+ pc.onicecandidate = (ev) => {
+ if (guest.closed || !ev.candidate) return;
+ const json = ev.candidate.toJSON ? ev.candidate.toJSON() : undefined;
+ const candidateStr = json?.candidate ?? ev.candidate.candidate ?? '';
+ if (!candidateStr) return;
+ const candidateInit: SignalingIceCandidate = {
+ candidate: candidateStr,
+ sdpMid: json?.sdpMid ?? ev.candidate.sdpMid ?? null,
+ sdpMLineIndex: json?.sdpMLineIndex ?? ev.candidate.sdpMLineIndex ?? null,
+ ...(json?.usernameFragment != null ? { usernameFragment: json.usernameFragment } : {}),
+ };
+ if (guest.localIceCandidates.length < 64) {
+ guest.localIceCandidates.push(candidateInit);
+ }
+ this.signaling.send({
+ type: 'ice',
+ fromPeerId: this.hostPeerId,
+ toPeerId: guest.signalingPeerId,
+ candidate: candidateInit,
+ });
+ };
+
+ pc.onconnectionstatechange = () => {
+ if (guest.closed) return;
+ if (pc.connectionState === 'connected') {
+ if (guest.disconnectTimer !== null) {
+ clearTimeout(guest.disconnectTimer);
+ guest.disconnectTimer = null;
+ }
+ return;
+ }
+ if (pc.connectionState === 'failed' || pc.connectionState === 'closed') {
+ this.removeGuest(guest.signalingPeerId, true);
+ } else if (pc.connectionState === 'disconnected') {
+ if (guest.disconnectTimer === null) {
+ guest.disconnectTimer = setTimeout(() => {
+ guest.disconnectTimer = null;
+ if (!guest.closed && pc.connectionState === 'disconnected') {
+ this.removeGuest(guest.signalingPeerId, true);
+ }
+ }, DISCONNECTED_GRACE_MS);
+ }
+ }
+ };
+
+ pc.ondatachannel = (ev) => {
+ if (guest.closed) return;
+ const dc = ev.channel;
+ dc.binaryType = 'arraybuffer';
+ guest.dc = dc;
+
+ dc.onmessage = async (msgEv) => {
+ if (guest.closed) return;
+ try {
+ const rawBuf =
+ msgEv.data instanceof ArrayBuffer
+ ? msgEv.data
+ : msgEv.data instanceof Blob
+ ? await msgEv.data.arrayBuffer()
+ : null;
+ if (!rawBuf) return;
+
+ const assembled = guest.reassembler.pushFrame(rawBuf);
+ if (!assembled) return;
+
+ if (assembled.kind === 'text') {
+ this.handleGuestTextMessage(guest, assembled.text);
+ } else {
+ this.handleGuestBinaryMessage(guest, assembled.data);
+ }
+ } catch {
+ // drop malformed frame
+ }
+ };
+
+ dc.onclose = () => {
+ this.removeGuest(guest.signalingPeerId, true);
+ };
+
+ dc.onerror = () => {
+ this.removeGuest(guest.signalingPeerId, true);
+ };
+ };
+
+ try {
+ await pc.setRemoteDescription({ type: 'offer', sdp: env.sdp });
+ guest.remoteDescSet = true;
+ for (const cand of guest.pendingIce.splice(0)) {
+ try {
+ await pc.addIceCandidate(cand);
+ } catch {
+ // ignore stale candidate
+ }
+ }
+ const answer = await pc.createAnswer();
+ await pc.setLocalDescription(answer);
+ const answerSdp = pc.localDescription?.sdp || answer.sdp;
+ if (answerSdp) {
+ guest.lastAnswerSdp = answerSdp;
+ this.signaling.send({
+ type: 'answer',
+ fromPeerId: this.hostPeerId,
+ toPeerId: guest.signalingPeerId,
+ sdp: answerSdp,
+ sdpType: 'answer',
+ });
+ }
+ } catch (err) {
+ this.errorHandlers.forEach((h) =>
+ h(err instanceof Error ? err : new Error('Failed to answer WebRTC peer'))
+ );
+ this.removeGuest(guest.signalingPeerId, false);
+ }
+ return;
+ }
+
+ if (env.type === 'ice' && env.candidate) {
+ const guest = this.guests.get(env.fromPeerId);
+ if (!guest || guest.closed) return;
+ if (!guest.remoteDescSet) {
+ if (guest.pendingIce.length < 64) {
+ guest.pendingIce.push(env.candidate);
+ }
+ return;
+ }
+ try {
+ await guest.pc.addIceCandidate(env.candidate);
+ } catch {
+ // ignore invalid candidate
+ }
+ return;
+ }
+
+ if (env.type === 'bye') {
+ this.removeGuest(env.fromPeerId, true);
+ }
+ }
+
+ private handleGuestTextMessage(guest: GuestConnection, rawText: string): void {
+ let parsed: Record<string, unknown>;
+ try {
+ const raw = JSON.parse(rawText) as unknown;
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return;
+ parsed = raw as Record<string, unknown>;
+ } catch {
+ return;
+ }
+
+ const type = typeof parsed.type === 'string' ? parsed.type : '';
+ if (!type) return;
+
+ if (type === 'JOIN_REQUEST' && parsed.peer && typeof parsed.peer === 'object') {
+ const peerObj = parsed.peer as Record<string, unknown>;
+ if (typeof peerObj.id === 'string' || typeof peerObj.id === 'number') {
+ guest.appPeerId = String(peerObj.id);
+ }
+ guest.joined = true;
+ }
+
+ // Strict pre-join & role enforcement on the authoritative Host Hub
+ if (!guest.joined && type !== 'JOIN_REQUEST' && type !== 'PEER_LEFT') {
+ this.sendAccessDeniedToGuest(guest, 'FORBIDDEN', 'Must join room before sending actions');
+ return;
+ }
+
+ if (HOST_ONLY_MODERATION_TYPES.has(type)) {
+ this.sendAccessDeniedToGuest(guest, 'FORBIDDEN', 'Only the Host can moderate participants');
+ return;
+ }
+
+ if (guest.role === 'viewer' && !VIEWER_ALLOWED_JSON_TYPES.has(type)) {
+ this.sendAccessDeniedToGuest(guest, 'VIEWER_READONLY', 'Viewers have read-only access');
+ return;
+ }
+
+ const guestPeerId = guest.appPeerId || guest.signalingPeerId;
+
+ // Layer ownership & lock enforcement matching stateful Rust server
+ if (type === 'LAYER_DELETE' && typeof parsed.layerId === 'string') {
+ const meta = this.layerLocks.get(parsed.layerId);
+ if (meta?.reservedByPeerId && meta.reservedByPeerId !== guestPeerId) {
+ this.sendAccessDeniedToGuest(guest, 'LAYER_LOCKED', 'Layer is locked by its owner');
+ return;
+ }
+ if (meta?.ownerPeerId && meta.ownerPeerId !== guestPeerId) {
+ this.sendAccessDeniedToGuest(guest, 'NOT_OWNER', 'Only the layer owner or Host can delete this layer');
+ return;
+ }
+ } else if (
+ (type === 'LAYER_CLEAR' ||
+ type === 'LAYER_RENAME' ||
+ type === 'LAYER_VISIBILITY' ||
+ type === 'LAYER_OPACITY' ||
+ type === 'LAYER_UPDATE') &&
+ typeof parsed.layerId === 'string'
+ ) {
+ if (this.isLayerLockedForGuest(parsed.layerId, guestPeerId)) {
+ this.sendAccessDeniedToGuest(guest, 'LAYER_LOCKED', 'Layer is locked by its owner');
+ return;
+ }
+ if (type === 'LAYER_UPDATE') {
+ const meta = this.layerLocks.get(parsed.layerId);
+ const patch =
+ parsed.patch && typeof parsed.patch === 'object'
+ ? (parsed.patch as Record<string, unknown>)
+ : null;
+ if (
+ patch?.reservedByPeerId !== undefined &&
+ patch.reservedByPeerId !== null &&
+ patch.reservedByPeerId !== '' &&
+ String(patch.reservedByPeerId) !== guestPeerId
+ ) {
+ this.sendAccessDeniedToGuest(guest, 'FORBIDDEN', 'Cannot lock layer under another peer ID');
+ return;
+ }
+ if (
+ meta?.ownerPeerId &&
+ meta.ownerPeerId !== guestPeerId &&
+ (patch?.ownerPeerId !== undefined ||
+ (Array.isArray(parsed.clearedFields) && parsed.clearedFields.includes('ownerPeerId')))
+ ) {
+ this.sendAccessDeniedToGuest(guest, 'NOT_OWNER', 'Cannot reassign layer ownership');
+ return;
+ }
+ }
+ } else if (type === 'LAYER_TREE_SYNC' && Array.isArray(parsed.layers)) {
+ const incomingById = new Map<string, Record<string, unknown>>();
+ for (const rawItem of parsed.layers) {
+ if (rawItem && typeof rawItem === 'object') {
+ const item = rawItem as Record<string, unknown>;
+ if (typeof item.id === 'string') incomingById.set(item.id, item);
+ }
+ }
+ for (const [layerId, meta] of this.layerLocks.entries()) {
+ const nextItem = incomingById.get(layerId);
+ if (!nextItem) {
+ if (meta.reservedByPeerId && meta.reservedByPeerId !== guestPeerId) {
+ this.sendAccessDeniedToGuest(guest, 'LAYER_LOCKED', 'Cannot delete a locked layer');
+ return;
+ }
+ if (meta.ownerPeerId && meta.ownerPeerId !== guestPeerId) {
+ this.sendAccessDeniedToGuest(guest, 'NOT_OWNER', 'Cannot delete another user layer');
+ return;
+ }
+ } else if (meta.reservedByPeerId && meta.reservedByPeerId !== guestPeerId) {
+ const nextReserved =
+ nextItem.reservedByPeerId !== undefined &&
+ nextItem.reservedByPeerId !== null &&
+ nextItem.reservedByPeerId !== ''
+ ? String(nextItem.reservedByPeerId)
+ : undefined;
+ if (nextReserved !== meta.reservedByPeerId) {
+ this.sendAccessDeniedToGuest(guest, 'LAYER_LOCKED', 'Cannot unlock another user layer');
+ return;
+ }
+ }
+ }
+ }
+
+ this.applyLayerLockMutation(parsed);
+
+ const sequenced = JSON.stringify({
+ ...parsed,
+ senderId: guest.appPeerId || parsed.senderId || guest.signalingPeerId,
+ seq: ++this.seq,
+ });
+
+ // Deliver locally to the Host's multiplayerService
+ this.textHandlers.forEach((h) => h(sequenced));
+
+ // Relay to all other guests unless this is a Host-consumed handshake message
+ if (!HOST_ONLY_CONSUME_TYPES.has(type)) {
+ this.broadcastText(sequenced, guest.signalingPeerId);
+ }
+ }
+
+ private handleGuestBinaryMessage(guest: GuestConnection, buf: ArrayBuffer): void {
+ const bytes = toUint8Array(buf);
+ if (bytes.byteLength < 11 || bytes[0] !== BINARY_MAGIC_0 || bytes[1] !== BINARY_MAGIC_1) {
+ return;
+ }
+
+ const opcode = bytes[2];
+ const isReadOnlyBinary = opcode === CODE_CURSOR_MOVE || opcode === CODE_BRUSH_ASSET_REQUEST;
+
+ if (!guest.joined && !isReadOnlyBinary) {
+ this.sendAccessDeniedToGuest(guest, 'FORBIDDEN', 'Must join room before drawing');
+ return;
+ }
+
+ if (guest.role === 'viewer' && !isReadOnlyBinary) {
+ this.sendAccessDeniedToGuest(guest, 'VIEWER_READONLY', 'Viewers have read-only access');
+ return;
+ }
+
+ if (
+ opcode === CODE_STROKE_START ||
+ opcode === CODE_STROKE_FINISH ||
+ opcode === CODE_TILE_DELTA ||
+ opcode === CODE_LAYER_MASK_DATA
+ ) {
+ const layerId = this.extractBinaryLayerId(bytes, opcode);
+ const guestPeerId = guest.appPeerId || guest.signalingPeerId;
+ if (layerId && this.isLayerLockedForGuest(layerId, guestPeerId)) {
+ this.sendAccessDeniedToGuest(guest, 'LAYER_LOCKED', 'Layer is locked by its owner');
+ return;
+ }
+ }
+
+ const stamped = this.stampBinarySeq(bytes);
+ const stampedBuf = new ArrayBuffer(stamped.byteLength);
+ new Uint8Array(stampedBuf).set(stamped);
+
+ // Deliver locally to the Host's multiplayerService
+ this.binaryHandlers.forEach((h) => h(stampedBuf));
+
+ // Relay to all other connected guests (star topology)
+ this.broadcastBinary(stamped, guest.signalingPeerId);
+ }
+
+ private removeGuest(signalingPeerId: string, notifyDisconnect: boolean): void {
+ const guest = this.guests.get(signalingPeerId);
+ if (!guest || guest.closed) return;
+ guest.closed = true;
+ if (guest.disconnectTimer !== null) {
+ clearTimeout(guest.disconnectTimer);
+ guest.disconnectTimer = null;
+ }
+ this.guests.delete(signalingPeerId);
+ guest.reassembler.clear();
+
+ try {
+ if (guest.dc) {
+ guest.dc.onmessage = null;
+ guest.dc.onclose = null;
+ guest.dc.onerror = null;
+ guest.dc.close();
+ }
+ } catch {
+ // ignore
+ }
+ try {
+ guest.pc.onicecandidate = null;
+ guest.pc.ondatachannel = null;
+ guest.pc.onconnectionstatechange = null;
+ guest.pc.close();
+ } catch {
+ // ignore
+ }
+
+ if (notifyDisconnect && guest.appPeerId && !this.closed) {
+ const discJson = JSON.stringify({
+ type: 'PEER_DISCONNECTED',
+ peerId: guest.appPeerId,
+ seq: ++this.seq,
+ });
+ this.textHandlers.forEach((h) => h(discJson));
+ this.broadcastText(discJson);
+ }
+ }
+
+ public onTextMessage(handler: (text: string) => void): () => void {
+ this.textHandlers.add(handler);
+ return () => this.textHandlers.delete(handler);
+ }
+
+ public onBinaryMessage(handler: (data: ArrayBuffer) => void): () => void {
+ this.binaryHandlers.add(handler);
+ return () => this.binaryHandlers.delete(handler);
+ }
+
+ public onClose(handler: (reason?: string) => void): () => void {
+ this.closeHandlers.add(handler);
+ return () => this.closeHandlers.delete(handler);
+ }
+
+ public onError(handler: (err: Error | Event) => void): () => void {
+ this.errorHandlers.add(handler);
+ return () => this.errorHandlers.delete(handler);
+ }
+
+ public close(): void {
+ if (this.closed) return;
+ this.closed = true;
+ this.open = false;
+
+ try {
+ this.signaling.send({
+ type: 'bye',
+ fromPeerId: this.hostPeerId,
+ reason: 'Host closed the room',
+ });
+ } catch {
+ // ignore
+ }
+
+ for (const id of Array.from(this.guests.keys())) {
+ this.removeGuest(id, false);
+ }
+
+ this.unsubSignaling?.();
+ this.unsubSignaling = null;
+ this.signaling.close();
+ this.closeHandlers.forEach((h) => h('Host closed the P2P room'));
+ }
+}
diff --git a/src/services/webrtcSignaling.ts b/src/services/webrtcSignaling.ts
new file mode 100644
index 0000000..2d76e43
--- /dev/null
+++ b/src/services/webrtcSignaling.ts
@@ -0,0 +1,897 @@
+/**
+ * Zero-Cost Pluggable WebRTC Signaling Client.
+ *
+ * Exchanges ONLY small SDP offer/answer and ICE candidate envelopes (zero drawing traffic).
+ * Every room channel is scoped and authenticated by a SHA-256 hash of
+ * `"inkstudio-p2p-v1:" + roomCode + ":" + roomSecret` so unrelated peers cannot hijack a room.
+ */
+
+export type SignalingMessageType = 'offer' | 'answer' | 'ice' | 'room-full' | 'bye';
+
+export interface SignalingEnvelope {
+ v: 1;
+ type: SignalingMessageType;
+ roomHash: string;
+ mid: string;
+ fromPeerId: string;
+ toPeerId?: string;
+ sdp?: string;
+ sdpType?: 'offer' | 'answer';
+ candidate?: {
+ candidate: string;
+ sdpMid?: string | null;
+ sdpMLineIndex?: number | null;
+ usernameFragment?: string | null;
+ };
+ reason?: string;
+ ts: number;
+}
+
+export interface P2pRoomCredentials {
+ roomCode: string; // e.g. "INK-7429"
+ roomSecret: string; // e.g. "K8P2M9"
+ joinCode: string; // e.g. "INK-7429-K8P2M9"
+ roomHash: string; // 64-char SHA-256 hex
+}
+
+export interface ISignalingClient {
+ connect(): Promise<void>;
+ send(msg: Omit<SignalingEnvelope, 'v' | 'roomHash' | 'mid' | 'ts'>): void;
+ onMessage(handler: (msg: SignalingEnvelope) => void): () => void;
+ onError(handler: (err: Error) => void): () => void;
+ close(): void;
+}
+
+export interface SignalingClientOptions {
+ roomHash: string;
+ peerId: string;
+ customSignalingUrl?: string;
+ relayUrls?: string[];
+ connectTimeoutMs?: number;
+}
+
+export const DEFAULT_PUBLIC_SIGNALING_RELAYS: readonly string[] = [
+ 'wss://broker.emqx.io:8084/mqtt',
+ 'wss://broker.hivemq.com:8884/mqtt',
+ 'wss://test.mosquitto.org:8081/mqtt',
+];
+
+const MAX_SIGNALING_JSON_CHARS = 64 * 1024;
+const MAX_SDP_CHARS = 48 * 1024;
+const MAX_CANDIDATE_CHARS = 4 * 1024;
+const MAX_PEER_ID_CHARS = 128;
+const ALLOWED_SIGNALING_TYPES = new Set<SignalingMessageType>([
+ 'offer',
+ 'answer',
+ 'ice',
+ 'room-full',
+ 'bye',
+]);
+
+const SECRET_ALPHABET = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
+
+function randomBytes(length: number): Uint8Array {
+ const out = new Uint8Array(length);
+ if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {
+ crypto.getRandomValues(out);
+ } else {
+ for (let i = 0; i < length; i++) {
+ out[i] = Math.floor(Math.random() * 256);
+ }
+ }
+ return out;
+}
+
+export function normalizeRoomCode(raw: string): string {
+ return raw.trim().toUpperCase();
+}
+
+export function normalizeRoomSecret(raw: string | undefined): string {
+ return (raw || '').trim().toUpperCase();
+}
+
+/**
+ * Pure TypeScript synchronous SHA-256 returning 64-char lowercase hex.
+ * Works identically in Tauri WebView, insecure HTTP LAN dev origins, and Node/Vitest.
+ */
+const SHA256_K = new Uint32Array([
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
+]);
+
+export function sha256HexSync(input: string): string {
+ const bytes = new TextEncoder().encode(input);
+ const bitLen = bytes.length * 8;
+ const paddedLen = Math.ceil((bytes.length + 9) / 64) * 64;
+ const padded = new Uint8Array(paddedLen);
+ padded.set(bytes);
+ padded[bytes.length] = 0x80;
+ const view = new DataView(padded.buffer);
+ const hiBits = Math.floor(bitLen / 0x100000000);
+ const loBits = bitLen >>> 0;
+ view.setUint32(paddedLen - 8, hiBits, false);
+ view.setUint32(paddedLen - 4, loBits, false);
+
+ let h0 = 0x6a09e667;
+ let h1 = 0xbb67ae85;
+ let h2 = 0x3c6ef372;
+ let h3 = 0xa54ff53a;
+ let h4 = 0x510e527f;
+ let h5 = 0x9b05688c;
+ let h6 = 0x1f83d9ab;
+ let h7 = 0x5be0cd19;
+
+ const w = new Uint32Array(64);
+
+ for (let offset = 0; offset < paddedLen; offset += 64) {
+ for (let i = 0; i < 16; i++) {
+ w[i] = view.getUint32(offset + i * 4, false);
+ }
+ for (let i = 16; i < 64; i++) {
+ const s0 =
+ ((w[i - 15] >>> 7) | (w[i - 15] << 25)) ^
+ ((w[i - 15] >>> 18) | (w[i - 15] << 14)) ^
+ (w[i - 15] >>> 3);
+ const s1 =
+ ((w[i - 2] >>> 17) | (w[i - 2] << 15)) ^
+ ((w[i - 2] >>> 19) | (w[i - 2] << 13)) ^
+ (w[i - 2] >>> 10);
+ w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
+ }
+
+ let a = h0;
+ let b = h1;
+ let c = h2;
+ let d = h3;
+ let e = h4;
+ let f = h5;
+ let g = h6;
+ let h = h7;
+
+ for (let i = 0; i < 64; i++) {
+ const S1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
+ const ch = (e & f) ^ (~e & g);
+ const temp1 = (h + S1 + ch + SHA256_K[i] + w[i]) >>> 0;
+ const S0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
+ const maj = (a & b) ^ (a & c) ^ (b & c);
+ const temp2 = (S0 + maj) >>> 0;
+
+ h = g;
+ g = f;
+ f = e;
+ e = (d + temp1) >>> 0;
+ d = c;
+ c = b;
+ b = a;
+ a = (temp1 + temp2) >>> 0;
+ }
+
+ h0 = (h0 + a) >>> 0;
+ h1 = (h1 + b) >>> 0;
+ h2 = (h2 + c) >>> 0;
+ h3 = (h3 + d) >>> 0;
+ h4 = (h4 + e) >>> 0;
+ h5 = (h5 + f) >>> 0;
+ h6 = (h6 + g) >>> 0;
+ h7 = (h7 + h) >>> 0;
+ }
+
+ return [h0, h1, h2, h3, h4, h5, h6, h7]
+ .map((n) => n.toString(16).padStart(8, '0'))
+ .join('');
+}
+
+export function computeRoomTopicHash(roomCode: string, roomSecret: string = ''): string {
+ const normalizedCode = normalizeRoomCode(roomCode);
+ const normalizedSecret = normalizeRoomSecret(roomSecret);
+ return sha256HexSync(`inkstudio-p2p-v1:${normalizedCode}:${normalizedSecret}`);
+}
+
+export function generateP2pRoomCredentials(): P2pRoomCredentials {
+ const rb = randomBytes(10);
+ // 4-digit human-friendly code: INK-1000 .. INK-9999
+ const num = 1000 + (((rb[0] << 8) | rb[1]) % 9000);
+ const roomCode = `INK-${num}`;
+ // 6-char unambiguous room secret
+ let roomSecret = '';
+ for (let i = 0; i < 6; i++) {
+ roomSecret += SECRET_ALPHABET[rb[2 + i] % SECRET_ALPHABET.length];
+ }
+ const joinCode = `${roomCode}-${roomSecret}`;
+ const roomHash = computeRoomTopicHash(roomCode, roomSecret);
+ return { roomCode, roomSecret, joinCode, roomHash };
+}
+
+function constantTimeStrEqual(a: string, b: string): boolean {
+ if (a.length !== b.length) return false;
+ let diff = 0;
+ for (let i = 0; i < a.length; i++) {
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
+ }
+ return diff === 0;
+}
+
+/**
+ * Strictly validates an untrusted signaling JSON payload against the expected roomHash.
+ * Drops malformed, oversized, or cross-room payloads.
+ */
+export function validateSignalingMessage(
+ raw: unknown,
+ expectedRoomHash: string
+): SignalingEnvelope | null {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const obj = raw as Record<string, unknown>;
+
+ if (obj.v !== 1) return null;
+ if (typeof obj.type !== 'string' || !ALLOWED_SIGNALING_TYPES.has(obj.type as SignalingMessageType)) {
+ return null;
+ }
+ if (
+ typeof obj.roomHash !== 'string' ||
+ !/^[0-9a-f]{64}$/.test(obj.roomHash) ||
+ !constantTimeStrEqual(obj.roomHash, expectedRoomHash)
+ ) {
+ return null;
+ }
+ if (
+ typeof obj.fromPeerId !== 'string' ||
+ obj.fromPeerId.trim().length === 0 ||
+ obj.fromPeerId.length > MAX_PEER_ID_CHARS
+ ) {
+ return null;
+ }
+ if (
+ obj.toPeerId !== undefined &&
+ (typeof obj.toPeerId !== 'string' || obj.toPeerId.length > MAX_PEER_ID_CHARS)
+ ) {
+ return null;
+ }
+ if (typeof obj.mid !== 'string' || obj.mid.length === 0 || obj.mid.length > 64) {
+ return null;
+ }
+ if (typeof obj.ts !== 'number' || !Number.isFinite(obj.ts)) {
+ return null;
+ }
+
+ const type = obj.type as SignalingMessageType;
+ const out: SignalingEnvelope = {
+ v: 1,
+ type,
+ roomHash: obj.roomHash,
+ mid: obj.mid,
+ fromPeerId: obj.fromPeerId,
+ ...(obj.toPeerId ? { toPeerId: obj.toPeerId } : {}),
+ ts: obj.ts,
+ };
+
+ if (type === 'offer' || type === 'answer') {
+ if (
+ typeof obj.sdp !== 'string' ||
+ obj.sdp.length === 0 ||
+ obj.sdp.length > MAX_SDP_CHARS
+ ) {
+ return null;
+ }
+ out.sdp = obj.sdp;
+ out.sdpType = type;
+ } else if (type === 'ice') {
+ if (!obj.candidate || typeof obj.candidate !== 'object' || Array.isArray(obj.candidate)) {
+ return null;
+ }
+ const cand = obj.candidate as Record<string, unknown>;
+ if (typeof cand.candidate !== 'string' || cand.candidate.length > MAX_CANDIDATE_CHARS) {
+ return null;
+ }
+ out.candidate = {
+ candidate: cand.candidate,
+ sdpMid: typeof cand.sdpMid === 'string' || cand.sdpMid === null ? cand.sdpMid : undefined,
+ sdpMLineIndex:
+ typeof cand.sdpMLineIndex === 'number' || cand.sdpMLineIndex === null
+ ? cand.sdpMLineIndex
+ : undefined,
+ usernameFragment:
+ typeof cand.usernameFragment === 'string' || cand.usernameFragment === null
+ ? cand.usernameFragment
+ : undefined,
+ };
+ } else if (type === 'room-full' || type === 'bye') {
+ if (typeof obj.reason === 'string') {
+ out.reason = obj.reason.slice(0, 200);
+ }
+ }
+
+ return out;
+}
+
+function makeMessageId(): string {
+ const b = randomBytes(6);
+ let hex = '';
+ for (let i = 0; i < b.length; i++) {
+ hex += b[i].toString(16).padStart(2, '0');
+ }
+ return `${Date.now().toString(36)}-${hex}`;
+}
+
+// --- Minimal dependency-free MQTT v3.1.1 over WebSocket codec (QoS 0 pub/sub) ---
+
+const mqttEncoder = new TextEncoder();
+const mqttDecoder = new TextDecoder();
+
+function encodeMqttRemainingLength(len: number): number[] {
+ const out: number[] = [];
+ let x = len;
+ do {
+ let encodedByte = x % 128;
+ x = Math.floor(x / 128);
+ if (x > 0) encodedByte |= 0x80;
+ out.push(encodedByte);
+ } while (x > 0);
+ return out;
+}
+
+function encodeMqttString(str: string): Uint8Array {
+ const utf8 = mqttEncoder.encode(str);
+ const out = new Uint8Array(2 + utf8.length);
+ out[0] = (utf8.length >>> 8) & 0xff;
+ out[1] = utf8.length & 0xff;
+ out.set(utf8, 2);
+ return out;
+}
+
+function concatBytes(parts: Uint8Array[]): Uint8Array {
+ let total = 0;
+ for (const p of parts) total += p.length;
+ const out = new Uint8Array(total);
+ let offset = 0;
+ for (const p of parts) {
+ out.set(p, offset);
+ offset += p.length;
+ }
+ return out;
+}
+
+export function encodeMqttConnect(clientId: string, keepAliveSec = 30): Uint8Array {
+ const protoName = encodeMqttString('MQTT');
+ const varHeader = concatBytes([
+ protoName,
+ new Uint8Array([0x04, 0x02, (keepAliveSec >>> 8) & 0xff, keepAliveSec & 0xff]),
+ ]);
+ const payload = encodeMqttString(clientId);
+ const remLen = encodeMqttRemainingLength(varHeader.length + payload.length);
+ return concatBytes([new Uint8Array([0x10, ...remLen]), varHeader, payload]);
+}
+
+export function encodeMqttSubscribe(packetId: number, topic: string): Uint8Array {
+ const topicBytes = encodeMqttString(topic);
+ const body = concatBytes([
+ new Uint8Array([(packetId >>> 8) & 0xff, packetId & 0xff]),
+ topicBytes,
+ new Uint8Array([0x00]), // QoS 0
+ ]);
+ const remLen = encodeMqttRemainingLength(body.length);
+ return concatBytes([new Uint8Array([0x82, ...remLen]), body]);
+}
+
+export function encodeMqttPublish(topic: string, textPayload: string): Uint8Array {
+ const topicBytes = encodeMqttString(topic);
+ const payloadBytes = mqttEncoder.encode(textPayload);
+ const remLen = encodeMqttRemainingLength(topicBytes.length + payloadBytes.length);
+ return concatBytes([new Uint8Array([0x30, ...remLen]), topicBytes, payloadBytes]);
+}
+
+export function decodeMqttPackets(
+ buf: Uint8Array
+): Array<{ packetType: number; topic?: string; payload?: string }> {
+ const results: Array<{ packetType: number; topic?: string; payload?: string }> = [];
+ let offset = 0;
+
+ while (offset + 2 <= buf.length) {
+ const headerByte = buf[offset];
+ const packetType = (headerByte >>> 4) & 0x0f;
+ const qos = (headerByte >>> 1) & 0x03;
+
+ let multiplier = 1;
+ let remLen = 0;
+ let idx = offset + 1;
+ let digit = 0;
+ let validVarInt = false;
+
+ while (idx < buf.length && multiplier <= 128 * 128 * 128) {
+ digit = buf[idx++];
+ remLen += (digit & 0x7f) * multiplier;
+ if ((digit & 0x80) === 0) {
+ validVarInt = true;
+ break;
+ }
+ multiplier *= 128;
+ }
+ if (!validVarInt || idx + remLen > buf.length) break;
+
+ const packetEnd = idx + remLen;
+ if (packetType === 3) {
+ // PUBLISH
+ if (idx + 2 <= packetEnd) {
+ const topicLen = (buf[idx] << 8) | buf[idx + 1];
+ idx += 2;
+ if (idx + topicLen <= packetEnd) {
+ const topic = mqttDecoder.decode(buf.subarray(idx, idx + topicLen));
+ idx += topicLen;
+ if (qos > 0) idx += 2; // skip packetId for QoS 1/2
+ if (idx <= packetEnd) {
+ const payload = mqttDecoder.decode(buf.subarray(idx, packetEnd));
+ results.push({ packetType, topic, payload });
+ }
+ }
+ }
+ } else {
+ results.push({ packetType });
+ }
+
+ offset = packetEnd;
+ }
+
+ return results;
+}
+
+/**
+ * Default zero-setup public multi-relay WSS signaling adapter.
+ * Connects to free public MQTT-over-WSS brokers in parallel for automatic failover
+ * and deduplicates envelopes by `mid`.
+ */
+export class PublicMultiRelaySignalingClient implements ISignalingClient {
+ private readonly roomHash: string;
+ private readonly peerId: string;
+ private readonly relayUrls: readonly string[];
+ private readonly connectTimeoutMs: number;
+ private readonly topic: string;
+
+ private sockets = new Map<string, WebSocket>();
+ private readyRelays = new Set<string>();
+ private reconnectTimers = new Map<string, ReturnType<typeof setTimeout>>();
+ private reconnectAttempts = new Map<string, number>();
+ private pingTimer: ReturnType<typeof setInterval> | null = null;
+ private messageHandlers = new Set<(msg: SignalingEnvelope) => void>();
+ private errorHandlers = new Set<(err: Error) => void>();
+ private seenMids = new Set<string>();
+ private pendingOutgoing: string[] = [];
+ private hasEverConnected = false;
+ private closed = false;
+
+ constructor(options: SignalingClientOptions) {
+ this.roomHash = options.roomHash;
+ this.peerId = options.peerId;
+ this.relayUrls =
+ options.relayUrls && options.relayUrls.length > 0
+ ? options.relayUrls
+ : DEFAULT_PUBLIC_SIGNALING_RELAYS;
+ this.connectTimeoutMs = options.connectTimeoutMs ?? 12_000;
+ this.topic = `inkstudio/sig/v1/${this.roomHash}`;
+ }
+
+ private scheduleRelayReconnect(relayUrl: string): void {
+ if (this.closed || !this.hasEverConnected) return;
+ if (this.reconnectTimers.has(relayUrl) || this.sockets.has(relayUrl)) return;
+
+ const attempt = (this.reconnectAttempts.get(relayUrl) ?? 0) + 1;
+ this.reconnectAttempts.set(relayUrl, attempt);
+ const delayMs = Math.min(30_000, 2_000 * Math.pow(2, Math.min(attempt - 1, 4)));
+
+ const timer = setTimeout(() => {
+ this.reconnectTimers.delete(relayUrl);
+ if (this.closed) return;
+ this.openRelaySocket(relayUrl);
+ }, delayMs);
+ this.reconnectTimers.set(relayUrl, timer);
+ }
+
+ private openRelaySocket(
+ relayUrl: string,
+ onInitialReady?: (url: string) => void,
+ onInitialFailed?: (url: string) => void
+ ): void {
+ if (this.closed) return;
+ const prevTimer = this.reconnectTimers.get(relayUrl);
+ if (prevTimer) {
+ clearTimeout(prevTimer);
+ this.reconnectTimers.delete(relayUrl);
+ }
+
+ try {
+ const ws = new WebSocket(relayUrl, 'mqtt');
+ ws.binaryType = 'arraybuffer';
+ this.sockets.set(relayUrl, ws);
+
+ ws.onopen = () => {
+ if (this.closed) {
+ ws.close();
+ return;
+ }
+ const clientId = `ink-${this.peerId.replace(/[^a-zA-Z0-9]/g, '').slice(-12)}-${Math.random()
+ .toString(36)
+ .slice(2, 6)}`;
+ ws.send(encodeMqttConnect(clientId, 30) as unknown as ArrayBuffer);
+ };
+
+ ws.onmessage = async (ev) => {
+ if (this.closed) return;
+ try {
+ const rawBuf =
+ ev.data instanceof ArrayBuffer
+ ? new Uint8Array(ev.data)
+ : ev.data instanceof Blob
+ ? new Uint8Array(await ev.data.arrayBuffer())
+ : null;
+ if (!rawBuf) return;
+
+ const packets = decodeMqttPackets(rawBuf);
+ for (const pkt of packets) {
+ if (pkt.packetType === 2) {
+ // CONNACK -> subscribe to roomHash topic
+ if (ws.readyState === WebSocket.OPEN) {
+ ws.send(encodeMqttSubscribe(1, this.topic) as unknown as ArrayBuffer);
+ }
+ } else if (pkt.packetType === 9) {
+ // SUBACK -> relay ready
+ this.reconnectAttempts.delete(relayUrl);
+ this.readyRelays.add(relayUrl);
+ this.flushPending();
+ onInitialReady?.(relayUrl);
+ } else if (pkt.packetType === 3 && pkt.topic === this.topic && pkt.payload) {
+ this.handleIncomingPayload(pkt.payload);
+ }
+ }
+ } catch {
+ // ignore malformed relay frames
+ }
+ };
+
+ ws.onerror = () => {
+ if (!this.readyRelays.has(relayUrl)) {
+ onInitialFailed?.(relayUrl);
+ }
+ };
+
+ ws.onclose = () => {
+ const wasCurrent = this.sockets.get(relayUrl) === ws;
+ if (wasCurrent) {
+ this.readyRelays.delete(relayUrl);
+ this.sockets.delete(relayUrl);
+ }
+ onInitialFailed?.(relayUrl);
+ if (!this.closed && this.hasEverConnected) {
+ this.scheduleRelayReconnect(relayUrl);
+ }
+ };
+ } catch {
+ onInitialFailed?.(relayUrl);
+ if (!this.closed && this.hasEverConnected) {
+ this.scheduleRelayReconnect(relayUrl);
+ }
+ }
+ }
+
+ public connect(): Promise<void> {
+ if (this.closed) {
+ return Promise.reject(new Error('Signaling client already closed'));
+ }
+
+ return new Promise((resolve, reject) => {
+ let settled = false;
+ const failedRelays = new Set<string>();
+
+ const timeoutId = setTimeout(() => {
+ if (!settled) {
+ settled = true;
+ reject(
+ new Error(
+ 'Could not reach public WebRTC signaling relays. Check your internet connection or configure a custom signaling Worker URL.'
+ )
+ );
+ }
+ }, this.connectTimeoutMs);
+
+ const markReady = (relayUrl: string) => {
+ this.hasEverConnected = true;
+ this.readyRelays.add(relayUrl);
+ this.flushPending();
+ if (!settled) {
+ settled = true;
+ clearTimeout(timeoutId);
+ this.startKeepAlive();
+ resolve();
+ }
+ };
+
+ const markFailed = (relayUrl: string) => {
+ if (settled) return;
+ failedRelays.add(relayUrl);
+ if (failedRelays.size >= this.relayUrls.length) {
+ settled = true;
+ clearTimeout(timeoutId);
+ reject(new Error('All public WebRTC signaling relays failed to connect.'));
+ }
+ };
+
+ for (const relayUrl of this.relayUrls) {
+ this.openRelaySocket(relayUrl, markReady, markFailed);
+ }
+ });
+ }
+
+ private startKeepAlive(): void {
+ if (this.pingTimer) return;
+ this.pingTimer = setInterval(() => {
+ if (this.closed) return;
+ const ping = new Uint8Array([0xc0, 0x00]);
+ for (const [url, ws] of this.sockets.entries()) {
+ if (this.readyRelays.has(url) && ws.readyState === WebSocket.OPEN) {
+ try {
+ ws.send(ping as unknown as ArrayBuffer);
+ } catch {
+ // ignore
+ }
+ }
+ }
+ }, 20_000);
+ }
+
+ private flushPending(): void {
+ if (this.pendingOutgoing.length === 0 || this.readyRelays.size === 0) return;
+ const queued = this.pendingOutgoing.splice(0, this.pendingOutgoing.length);
+ for (const json of queued) {
+ this.publishRaw(json);
+ }
+ }
+
+ private publishRaw(json: string): void {
+ const packet = encodeMqttPublish(this.topic, json);
+ for (const [url, ws] of this.sockets.entries()) {
+ if (this.readyRelays.has(url) && ws.readyState === WebSocket.OPEN) {
+ try {
+ ws.send(packet as unknown as ArrayBuffer);
+ } catch {
+ // ignore single relay failure
+ }
+ }
+ }
+ }
+
+ private handleIncomingPayload(rawText: string): void {
+ if (rawText.length > MAX_SIGNALING_JSON_CHARS) return;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(rawText);
+ } catch {
+ return;
+ }
+ const env = validateSignalingMessage(parsed, this.roomHash);
+ if (!env) return;
+ if (env.fromPeerId === this.peerId) return;
+ if (env.toPeerId && env.toPeerId !== this.peerId) return;
+ if (this.seenMids.has(env.mid)) return;
+
+ this.seenMids.add(env.mid);
+ if (this.seenMids.size > 512) {
+ const oldest = this.seenMids.values().next().value;
+ if (oldest !== undefined) this.seenMids.delete(oldest);
+ }
+
+ this.messageHandlers.forEach((h) => h(env));
+ }
+
+ public send(msg: Omit<SignalingEnvelope, 'v' | 'roomHash' | 'mid' | 'ts'>): void {
+ if (this.closed) return;
+ const full: SignalingEnvelope = {
+ ...msg,
+ v: 1,
+ roomHash: this.roomHash,
+ mid: makeMessageId(),
+ ts: Date.now(),
+ };
+ const json = JSON.stringify(full);
+ if (json.length > MAX_SIGNALING_JSON_CHARS) return;
+ if (this.readyRelays.size === 0) {
+ if (this.pendingOutgoing.length < 64) {
+ this.pendingOutgoing.push(json);
+ }
+ return;
+ }
+ this.publishRaw(json);
+ }
+
+ public onMessage(handler: (msg: SignalingEnvelope) => void): () => void {
+ this.messageHandlers.add(handler);
+ return () => this.messageHandlers.delete(handler);
+ }
+
+ public onError(handler: (err: Error) => void): () => void {
+ this.errorHandlers.add(handler);
+ return () => this.errorHandlers.delete(handler);
+ }
+
+ public close(): void {
+ this.closed = true;
+ for (const timer of this.reconnectTimers.values()) {
+ clearTimeout(timer);
+ }
+ this.reconnectTimers.clear();
+ this.reconnectAttempts.clear();
+ if (this.pingTimer) {
+ clearInterval(this.pingTimer);
+ this.pingTimer = null;
+ }
+ for (const ws of this.sockets.values()) {
+ try {
+ ws.onopen = null;
+ ws.onmessage = null;
+ ws.onclose = null;
+ ws.onerror = null;
+ ws.close();
+ } catch {
+ // ignore
+ }
+ }
+ this.sockets.clear();
+ this.readyRelays.clear();
+ this.pendingOutgoing = [];
+ }
+}
+
+/**
+ * Custom Cloudflare Worker WebSocket signaling adapter.
+ * Connects to `wss://<worker-domain>/signal?roomHash=<64-hex>&peerId=<peerId>`
+ * matching `docs/cloudflare-signaling-worker.js`.
+ */
+export class CustomWorkerSignalingClient implements ISignalingClient {
+ private readonly roomHash: string;
+ private readonly peerId: string;
+ private readonly workerUrl: string;
+ private readonly connectTimeoutMs: number;
+ private ws: WebSocket | null = null;
+ private messageHandlers = new Set<(msg: SignalingEnvelope) => void>();
+ private errorHandlers = new Set<(err: Error) => void>();
+ private closed = false;
+
+ constructor(options: SignalingClientOptions & { customSignalingUrl: string }) {
+ this.roomHash = options.roomHash;
+ this.peerId = options.peerId;
+ this.workerUrl = options.customSignalingUrl.trim();
+ this.connectTimeoutMs = options.connectTimeoutMs ?? 12_000;
+ }
+
+ public connect(): Promise<void> {
+ if (this.closed) {
+ return Promise.reject(new Error('Signaling client already closed'));
+ }
+
+ let finalUrl: string;
+ try {
+ const parsed = new URL(this.workerUrl);
+ if (parsed.protocol === 'https:') parsed.protocol = 'wss:';
+ if (parsed.protocol === 'http:') parsed.protocol = 'ws:';
+ if (parsed.protocol !== 'wss:' && parsed.protocol !== 'ws:') {
+ return Promise.reject(new Error('Custom signaling URL must use wss:// or https://'));
+ }
+ parsed.searchParams.set('roomHash', this.roomHash);
+ parsed.searchParams.set('peerId', this.peerId);
+ finalUrl = parsed.toString();
+ } catch {
+ return Promise.reject(new Error('Invalid custom signaling Worker URL'));
+ }
+
+ return new Promise((resolve, reject) => {
+ let settled = false;
+ const timeoutId = setTimeout(() => {
+ if (!settled) {
+ settled = true;
+ this.ws?.close();
+ reject(new Error('Timed out connecting to custom signaling server'));
+ }
+ }, this.connectTimeoutMs);
+
+ try {
+ const ws = new WebSocket(finalUrl);
+ this.ws = ws;
+
+ ws.onopen = () => {
+ if (!settled) {
+ settled = true;
+ clearTimeout(timeoutId);
+ resolve();
+ }
+ };
+
+ ws.onmessage = (ev) => {
+ if (this.closed || typeof ev.data !== 'string') return;
+ if (ev.data.length > MAX_SIGNALING_JSON_CHARS) return;
+ try {
+ const raw = JSON.parse(ev.data) as unknown;
+ const env = validateSignalingMessage(raw, this.roomHash);
+ if (!env) return;
+ if (env.fromPeerId === this.peerId) return;
+ if (env.toPeerId && env.toPeerId !== this.peerId) return;
+ this.messageHandlers.forEach((h) => h(env));
+ } catch {
+ // ignore
+ }
+ };
+
+ ws.onerror = () => {
+ const err = new Error('Custom signaling server connection error');
+ this.errorHandlers.forEach((h) => h(err));
+ if (!settled) {
+ settled = true;
+ clearTimeout(timeoutId);
+ reject(err);
+ }
+ };
+
+ ws.onclose = () => {
+ if (this.ws === ws) this.ws = null;
+ if (!settled) {
+ settled = true;
+ clearTimeout(timeoutId);
+ reject(new Error('Custom signaling server closed before ready'));
+ }
+ };
+ } catch (err: unknown) {
+ clearTimeout(timeoutId);
+ reject(err instanceof Error ? err : new Error('Failed to open signaling WebSocket'));
+ }
+ });
+ }
+
+ public send(msg: Omit<SignalingEnvelope, 'v' | 'roomHash' | 'mid' | 'ts'>): void {
+ if (this.closed || !this.ws || this.ws.readyState !== WebSocket.OPEN) return;
+ const full: SignalingEnvelope = {
+ ...msg,
+ v: 1,
+ roomHash: this.roomHash,
+ mid: makeMessageId(),
+ ts: Date.now(),
+ };
+ const json = JSON.stringify(full);
+ if (json.length > MAX_SIGNALING_JSON_CHARS) return;
+ this.ws.send(json);
+ }
+
+ public onMessage(handler: (msg: SignalingEnvelope) => void): () => void {
+ this.messageHandlers.add(handler);
+ return () => this.messageHandlers.delete(handler);
+ }
+
+ public onError(handler: (err: Error) => void): () => void {
+ this.errorHandlers.add(handler);
+ return () => this.errorHandlers.delete(handler);
+ }
+
+ public close(): void {
+ this.closed = true;
+ if (this.ws) {
+ try {
+ this.ws.onopen = null;
+ this.ws.onmessage = null;
+ this.ws.onclose = null;
+ this.ws.onerror = null;
+ this.ws.close();
+ } catch {
+ // ignore
+ }
+ this.ws = null;
+ }
+ }
+}
+
+export function createSignalingClient(options: SignalingClientOptions): ISignalingClient {
+ const customUrl = (options.customSignalingUrl || '').trim();
+ if (customUrl) {
+ return new CustomWorkerSignalingClient({ ...options, customSignalingUrl: customUrl });
+ }
+ return new PublicMultiRelaySignalingClient(options);
+}
diff --git a/src/types/editor.ts b/src/types/editor.ts
index d24167e..754c6bd 100644
--- a/src/types/editor.ts
+++ b/src/types/editor.ts
@@ -60,7 +60,7 @@ export interface Point {
isCorner?: boolean;
}
-export type BrushCategory = 'pen' | 'sketch' | 'brush' | 'natural-paint';
+export type BrushCategory = 'pen' | 'sketch' | 'brush' | 'blend' | 'natural-paint';
export type BrushRenderMode = 'stamp' | 'bristle-ribbon' | 'bristle-hybrid';
@@ -130,7 +130,7 @@ export interface NaturalPaintSettings {
export const DEFAULT_NATURAL_PAINT_SETTINGS: NaturalPaintSettings = {
enabled: false,
spatialMixing: false,
- pigmentMixingStrength: 0.85,
+ pigmentMixingStrength: 1.0,
paintLoad: 0.85,
depletionRate: 0.25,
wetness: 0.5,
@@ -166,6 +166,7 @@ export type BrushPresetId =
| 'g-pen'
| 'real-g-pen'
| 'textured-pen'
+ | 'rough-pen'
| 'dot-pen'
| 'calligraphy'
// Sketch section
@@ -174,14 +175,23 @@ export type BrushPresetId =
| 'pencil-6b-8b'
| 'charcoal-pencil'
| 'standard-chalk'
- // Brush section
- | 'oil-painting'
- | 'thick-oil-painting'
- | 'chalk-painting'
- | 'blend-brush'
- | 'blend-chalk-brush'
- | 'soft-round'
- | 'noise-shader'
+ // Brush section (Painterly Coloring & Illustration)
+ | 'oil-flat-alla-prima'
+ | 'thick-oil-impasto'
+ | 'dry-bristle-rake-paint'
+ | 'concept-matte-chalk'
+ | 'silky-portrait-round'
+ | 'canvas-scumble-oil'
+ | 'soft-glaze-airbrush'
+ | 'atmospheric-grain-shader'
+ | 'fine-detail-filbert'
+ // Blend section (Dedicated Pure Blenders)
+ | 'blend-velvet-soft'
+ | 'blend-oil-bristle'
+ | 'blend-matte-chalk'
+ | 'blend-rake-hair'
+ | 'blend-canvas-scumble'
+ | 'blend-fingertip'
// Natural Paint section
| 'impasto-bristle-oil'
| 'wet-mixing-filbert'
@@ -204,6 +214,7 @@ export interface CspSubTip {
width: number;
height: number;
isColor?: boolean;
+ isDualToneTip?: boolean;
}
export interface CspSpraySettings {
@@ -211,6 +222,14 @@ export interface CspSpraySettings {
size: number;
density: number;
bias: number;
+ particleSize?: number; // CSP BrushSprayParticleSize
+ linkSize?: boolean; // CSP BrushSprayLinkSize
+ sizeSensor?: CspSensorConfig; // CSP BrushSpraySizeEffector
+ densitySensor?: CspSensorConfig; // CSP BrushSprayDensityEffector
+ direction?: number; // CSP BrushSprayDirection (degrees 0..360)
+ directionDynamics?: CspAngleDynamicsMode; // CSP BrushSprayDirectionEffector mode
+ directionSensor?: CspSensorConfig; // CSP BrushSprayDirectionEffector BLOB
+ deviation?: number; // CSP BrushSprayDeviation (-1..1)
}
export interface CspTaperSettings {
@@ -239,35 +258,99 @@ export interface CspTaperSettings {
export type CspAntiAliasLevel = 0 | 1 | 2 | 3; // 0: None (Binary), 1: Weak, 2: Medium, 3: Strong
export type CspPaperTextureMode =
+ | 'normal'
| 'multiply'
| 'subtract'
| 'compare'
| 'overlay'
+ | 'color-burn'
+ | 'linear-burn'
+ | 'height'
| 'outline';
export type CspBlendTipsMode = 'normal' | 'darken' | 'compare';
+export type CspBrushCombineMode =
+ | BlendMode
+ | 'add'
+ | 'behind'
+ | 'clear'
+ | 'compare-density';
+
+export type CspSubTipOrder =
+ | 'sequential'
+ | 'reverse'
+ | 'random'
+ | 'random-no-repeat'
+ | 'once'
+ | 'direction';
+
export type CspTipFlipMode = 'none' | 'random' | 'alternate';
export type CspAngleDynamicsMode =
| 'none'
+ | 'initial-direction'
| 'direction'
| 'tilt'
| 'twist'
| 'random'
| 'direction-random';
+export type DualBrushCompositeMode =
+ | 'multiply'
+ | 'darken'
+ | 'subtract'
+ | 'compare-density'
+ | 'linear-burn'
+ | 'color-burn'
+ | 'height'
+ | 'overlay'
+ | 'screen'
+ | 'lighten'
+ | 'hard-mix'
+ | 'normal';
+
+export interface CspDualBrushConfig {
+ enabled: boolean;
+ compositeMode: DualBrushCompositeMode;
+ linkSizeWithMain?: boolean;
+ size?: number;
+ sizeRatio?: number;
+ spacing?: number;
+ scatter?: number;
+ thickness?: number;
+ thicknessVertical?: boolean;
+ hardness?: number;
+ density?: number;
+ angle?: number;
+ angleDynamics?: CspAngleDynamicsMode;
+ angleSensor?: CspSensorConfig;
+ flipH?: CspTipFlipMode;
+ flipV?: CspTipFlipMode;
+ spray?: CspSpraySettings;
+ tipDataUrl?: string;
+ tipImage?: HTMLImageElement;
+ subTips?: CspSubTip[];
+ subTipImages?: HTMLImageElement[];
+ subTipOrder?: CspSubTipOrder;
+ isRibbon?: boolean;
+}
+
export interface CspSensorConfig {
usePressure?: boolean;
pressureMin?: number; // 0.0 to 1.0
pressureCurve?: [number, number][];
useTilt?: boolean;
tiltMin?: number; // 0.0 to 1.0
+ tiltMax?: number; // 1.0 to 10.0 (CSP Tilt enlargement ceiling, e.g. 1.75 for 175%)
+ tiltCurve?: [number, number][];
+ invertTilt?: boolean;
useTiltAzimuth?: boolean;
useBarrelTwist?: boolean;
twistMin?: number; // 0.0 to 1.0
useVelocity?: boolean;
velocityMin?: number; // 0.0 to 1.0
+ velocityCurve?: [number, number][];
invertVelocity?: boolean;
useDistance?: boolean;
distanceMin?: number; // 0.0 to 1.0
@@ -286,11 +369,16 @@ export interface BrushDynamics {
flowJitter: number; // 0.0 to 1.0
// Color Dynamics
colorJitterEnabled: boolean;
+ colorJitterPerStroke?: boolean; // CSP BrushChangeColorPerStroke (true = per stroke, false = per dab)
hueJitter: number; // 0.0 to 1.0
saturationJitter: number; // 0.0 to 1.0
brightnessJitter: number; // 0.0 to 1.0
temperatureJitter?: number; // 0.0 to 1.0 (warm-cool pigment shift)
foregroundBackgroundJitter: number; // 0.0 to 1.0 (mix with secondary color)
+ subColorMixSensor?: CspSensorConfig;
+ hueJitterSensor?: CspSensorConfig;
+ saturationJitterSensor?: CspSensorConfig;
+ luminanceJitterSensor?: CspSensorConfig;
}
export const DEFAULT_BRUSH_DYNAMICS: BrushDynamics = {
@@ -322,15 +410,18 @@ export interface CspBrush {
secondaryTipWidth?: number;
secondaryTipHeight?: number;
subTips?: CspSubTip[]; // Multiple tip array for patterned brushes
- subTipOrder?: 'random' | 'sequential' | 'direction' | 'reverse';
+ subTipOrder?: CspSubTipOrder;
size: number;
+ brushSizeUnit?: number; // CSP BrushSizeUnit (0=px, 1=mm, etc.)
+ brushSizeSpecifiedByScreen?: boolean; // CSP BrushSizeSpecifiedByScreen
minSizeFactor: number;
opacity: number;
flow: number;
spacing: number;
hardness: number;
- thickness: number; // 0.05 to 1.0 (elliptical aspect ratio)
+ thickness: number; // 0.05 to 20.0 (elliptical aspect ratio)
thicknessVertical?: boolean;
+ thicknessSensor?: CspSensorConfig;
angle: number;
angleDynamics?: CspAngleDynamicsMode;
rotationRandomScale?: number; // 0.0 to 1.0
@@ -351,10 +442,12 @@ export interface CspBrush {
brushDensity?: number; // 0.0 to 1.0 (CSP Brush Density)
adjustDensityByGap?: boolean; // CSP Adjust brush density by gap
blendTipsMode?: CspBlendTipsMode; // normal | darken | compare
- brushCombineMode?: BlendMode;
+ brushCombineMode?: CspBrushCombineMode;
sizeSensor?: CspSensorConfig;
opacitySensor?: CspSensorConfig;
densitySensor?: CspSensorConfig;
+ intervalSensor?: CspSensorConfig;
+ textureDensitySensor?: CspSensorConfig;
bristleSplaySensor?: CspSensorConfig;
paintLoadSensor?: CspSensorConfig;
grainPenetrationSensor?: CspSensorConfig;
@@ -366,11 +459,17 @@ export interface CspBrush {
amountOfPaint?: number; // 0.0 to 1.0 (CSP: Amount of Paint)
densityOfPaint?: number; // 0.0 to 1.0 (CSP: Density of Paint)
colorStretch?: number; // 0.0 to 1.0 (CSP: Color Stretch along stroke length)
+ amountOfPaintSensor?: CspSensorConfig; // CSP BrushMixColorEffector
+ densityOfPaintSensor?: CspSensorConfig; // CSP BrushMixAlphaEffector
+ colorStretchSensor?: CspSensorConfig; // CSP BrushMixColorExtensionEffector
+ mixGroundColor?: boolean; // CSP BrushMixGroundColor (mix with underlying visible layers)
+ useBlur?: boolean; // CSP BrushUseBlur
+ blurStrength?: number; // 0.0 to 1.0 (CSP BrushBlur)
mixingMode?: NaturalMixingMode; // CSP / Natural Paint mixing mode
wetEdge?: number; // 0.0 to 1.0 (CSP: Watercolor Wet / Water Edge)
wetEdgeRadius?: number;
- wetEdgeAlphaPower?: number;
- wetEdgeValuePower?: number;
+ wetEdgeAlphaPower?: number; // Normalized 0.0 to 1.0
+ wetEdgeValuePower?: number; // Normalized 0.0 to 1.0
paperTexture?: string; // Paper grain texture data URL
surfaceTextureId?: SurfaceTextureId; // Built-in 512x512 seamless surface texture ID
grainMappingMode?: GrainMappingMode; // Spatial grain mapping mode
@@ -379,15 +478,32 @@ export interface CspBrush {
paperTextureBrightness?: number; // -100 to 100
paperTextureContrast?: number; // -100 to 100
paperTextureApplyEachPlot?: boolean;
+ paperTextureEmphasizeDensity?: boolean;
paperTextureScale?: number;
paperTextureRotate?: number;
+ paperTextureOffsetX?: number;
+ paperTextureOffsetY?: number;
paperTextureInverted?: boolean;
dualBrush?: boolean; // CSP Dual Brush compositing
- dualBrushCompositeMode?: string;
+ dualBrushConfig?: CspDualBrushConfig;
+ dualBrushCompositeMode?: DualBrushCompositeMode | string;
dualSize?: number;
+ dualLinkSize?: boolean;
dualSpacing?: number;
dualScatter?: number;
+ dualThickness?: number;
+ dualThicknessVertical?: boolean;
dualAngle?: number;
+ dualAngleDynamics?: CspAngleDynamicsMode;
+ dualAngleSensor?: CspSensorConfig;
+ dualHardness?: number;
+ dualDensity?: number;
+ dualSubTips?: CspSubTip[];
+ dualSubTipOrder?: CspSubTipOrder;
+ dualFlipH?: CspTipFlipMode;
+ dualFlipV?: CspTipFlipMode;
+ dualSpray?: CspSpraySettings;
+ dualIsRibbon?: boolean;
dualScale?: number;
dualSurfaceTextureId?: SurfaceTextureId;
dualGrainDepth?: number;
@@ -395,6 +511,7 @@ export interface CspBrush {
taper?: CspTaperSettings;
isRibbon?: boolean;
isColorTip?: boolean;
+ isDualToneTip?: boolean;
pressureCurveGamma?: number; // CSP Pressure response curve gamma
velocityDynamics?: boolean; // Velocity-based taper
dynamics?: BrushDynamics; // Multi-axis jitter matrix
@@ -403,11 +520,14 @@ export interface CspBrush {
bristle?: BristleSettings;
naturalPaint?: NaturalPaintSettings;
impasto?: ImpastoSettings;
+ importWarnings?: string[]; // Non-fatal diagnostics (e.g., missing external CSP CatalogPath materials)
importedAt: number;
}
export interface BrushSettings {
size: number;
+ brushSizeUnit?: number;
+ brushSizeSpecifiedByScreen?: boolean;
minSizeFactor: number; // minimum width ratio at lowest pressure (e.g. 0.2)
color: string;
secondaryColor?: string; // Secondary / background color for color dynamics
@@ -416,7 +536,7 @@ export interface BrushSettings {
brushDensity?: number; // Explicit CSP Brush Density alias (0.0 to 1.0)
adjustDensityByGap?: boolean; // CSP Adjust brush density by gap
blendTipsMode?: CspBlendTipsMode; // CSP Blend brush tips with darken / compare
- brushCombineMode?: BlendMode;
+ brushCombineMode?: CspBrushCombineMode;
spacing: number; // Spacing between stamps (0.01 to 1.0)
usePressure: boolean;
useTilt?: boolean; // Explicit pen tilt sensitivity toggle (default false except pencils/tilt brushes)
@@ -427,8 +547,9 @@ export interface BrushSettings {
postCorrection?: number; // 0 to 5 (CSP Post-correction spline refinement)
sharpCorners?: boolean; // CSP Sharp angles corner-snapping toggle
hardness: number; // Brush hardness (0.0 to 1.0)
- thickness?: number; // Elliptical thickness ratio (0.05 to 1.0)
+ thickness?: number; // Elliptical thickness ratio (0.05 to 20.0)
thicknessVertical?: boolean;
+ thicknessSensor?: CspSensorConfig;
flipH?: CspTipFlipMode;
flipV?: CspTipFlipMode;
antiAlias?: number; // 0: none, 1: low, 2: mid, 3: high
@@ -438,6 +559,8 @@ export interface BrushSettings {
sizeSensor?: CspSensorConfig;
opacitySensor?: CspSensorConfig;
densitySensor?: CspSensorConfig;
+ intervalSensor?: CspSensorConfig;
+ textureDensitySensor?: CspSensorConfig;
bristleSplaySensor?: CspSensorConfig;
paintLoadSensor?: CspSensorConfig;
grainPenetrationSensor?: CspSensorConfig;
@@ -450,9 +573,10 @@ export interface BrushSettings {
customTipAngleDynamics?: CspAngleDynamicsMode;
customTipRotationRandomScale?: number;
isColorTip?: boolean;
+ isDualToneTip?: boolean;
brushName?: string; // Custom display name
subTips?: CspSubTip[];
- subTipOrder?: 'random' | 'sequential' | 'direction' | 'reverse';
+ subTipOrder?: CspSubTipOrder;
subTipImages?: HTMLImageElement[];
pressureCurve?: [number, number][];
velocityCurve?: [number, number][];
@@ -465,11 +589,17 @@ export interface BrushSettings {
amountOfPaint?: number; // 0.0 to 1.0 (default 0.7)
densityOfPaint?: number; // 0.0 to 1.0 (default 0.8)
colorStretch?: number; // 0.0 to 1.0 (default 0.6)
+ amountOfPaintSensor?: CspSensorConfig;
+ densityOfPaintSensor?: CspSensorConfig;
+ colorStretchSensor?: CspSensorConfig;
+ mixGroundColor?: boolean;
+ useBlur?: boolean;
+ blurStrength?: number;
mixingMode?: NaturalMixingMode; // 'blend', 'running_color', 'smear', or 'impasto_mix'
wetEdge?: number; // 0.0 to 1.0 (CSP Water Edge rim density)
wetEdgeRadius?: number;
- wetEdgeAlphaPower?: number;
- wetEdgeValuePower?: number;
+ wetEdgeAlphaPower?: number; // Normalized 0.0 to 1.0
+ wetEdgeValuePower?: number; // Normalized 0.0 to 1.0
paperTexture?: string; // Optional paper texture data URL
paperTextureImage?: HTMLImageElement; // Preloaded paper grain image
surfaceTextureId?: SurfaceTextureId; // Built-in 512x512 seamless surface texture ID
@@ -479,15 +609,33 @@ export interface BrushSettings {
paperTextureBrightness?: number;
paperTextureContrast?: number;
paperTextureApplyEachPlot?: boolean;
+ paperTextureEmphasizeDensity?: boolean;
paperTextureInverted?: boolean;
paperTextureScale?: number;
paperTextureRotate?: number;
+ paperTextureOffsetX?: number;
+ paperTextureOffsetY?: number;
dualBrush?: boolean;
- dualBrushCompositeMode?: 'multiply' | 'subtract' | 'darken' | 'overlay' | 'screen' | string;
+ dualBrushConfig?: CspDualBrushConfig;
+ dualBrushCompositeMode?: DualBrushCompositeMode | string;
dualSize?: number;
+ dualLinkSize?: boolean;
dualSpacing?: number;
dualScatter?: number;
+ dualThickness?: number;
+ dualThicknessVertical?: boolean;
dualAngle?: number;
+ dualAngleDynamics?: CspAngleDynamicsMode;
+ dualAngleSensor?: CspSensorConfig;
+ dualHardness?: number;
+ dualDensity?: number;
+ dualSubTips?: CspSubTip[];
+ dualSubTipImages?: HTMLImageElement[];
+ dualSubTipOrder?: CspSubTipOrder;
+ dualFlipH?: CspTipFlipMode;
+ dualFlipV?: CspTipFlipMode;
+ dualSpray?: CspSpraySettings;
+ dualIsRibbon?: boolean;
dualScale?: number;
dualSurfaceTextureId?: SurfaceTextureId;
dualGrainDepth?: number;
@@ -503,6 +651,7 @@ export interface BrushSettings {
bristle?: BristleSettings;
naturalPaint?: NaturalPaintSettings;
impasto?: ImpastoSettings;
+ importWarnings?: string[];
}
export interface OnionSkinSettings {
diff --git a/src/types/multiplayer.ts b/src/types/multiplayer.ts
index bfdc3b0..b780a72 100644
--- a/src/types/multiplayer.ts
+++ b/src/types/multiplayer.ts
@@ -422,4 +422,12 @@ export interface SessionHostInfo {
peerCount: number;
isGlobal?: boolean;
localInviteUrl?: string;
+ /** Underlying room transport ('ws' for LAN/Relay WebSocket, 'webrtc' for serverless P2P). */
+ transport?: 'ws' | 'webrtc';
+ /** Short human-friendly P2P room code (e.g. "INK-7429"). */
+ roomCode?: string;
+ /** Room authentication secret paired with roomCode. */
+ roomSecret?: string;
+ /** Combined copyable join code (e.g. "INK-7429-K8P2M9"). */
+ joinCode?: string;
}
diff --git a/src/types/settings.ts b/src/types/settings.ts
index 7f656b0..f779d1f 100644
--- a/src/types/settings.ts
+++ b/src/types/settings.ts
@@ -247,6 +247,12 @@ export interface AppSettings {
// Auto-Updater (Desktop)
autoCheckUpdates: boolean;
skippedUpdateVersion: string;
+
+ // Collaborative Drawing (Optional WebRTC Signaling & TURN)
+ collabSignalingUrl: string;
+ collabTurnUrl: string;
+ collabTurnUsername: string;
+ collabTurnCredential: string;
}
export const DEFAULT_APP_SETTINGS: AppSettings = {
@@ -302,6 +308,11 @@ export const DEFAULT_APP_SETTINGS: AppSettings = {
autoCheckUpdates: true,
skippedUpdateVersion: '',
+
+ collabSignalingUrl: '',
+ collabTurnUrl: '',
+ collabTurnUsername: '',
+ collabTurnCredential: '',
};
const VALID_MODIFIER_ACTIONS = new Set<ModifierAction>([
@@ -565,6 +576,22 @@ export function loadAppSettings(): AppSettings {
typeof parsed.skippedUpdateVersion === 'string'
? parsed.skippedUpdateVersion.trim()
: DEFAULT_APP_SETTINGS.skippedUpdateVersion;
+ const validCollabSignalingUrl: string =
+ typeof parsed.collabSignalingUrl === 'string' && !parsed.collabSignalingUrl.includes('\0')
+ ? parsed.collabSignalingUrl.trim().slice(0, 512)
+ : DEFAULT_APP_SETTINGS.collabSignalingUrl;
+ const validCollabTurnUrl: string =
+ typeof parsed.collabTurnUrl === 'string' && !parsed.collabTurnUrl.includes('\0')
+ ? parsed.collabTurnUrl.trim().slice(0, 512)
+ : DEFAULT_APP_SETTINGS.collabTurnUrl;
+ const validCollabTurnUsername: string =
+ typeof parsed.collabTurnUsername === 'string' && !parsed.collabTurnUsername.includes('\0')
+ ? parsed.collabTurnUsername.trim().slice(0, 256)
+ : DEFAULT_APP_SETTINGS.collabTurnUsername;
+ const validCollabTurnCredential: string =
+ typeof parsed.collabTurnCredential === 'string' && !parsed.collabTurnCredential.includes('\0')
+ ? parsed.collabTurnCredential.trim().slice(0, 256)
+ : DEFAULT_APP_SETTINGS.collabTurnCredential;
return {
...DEFAULT_APP_SETTINGS,
...parsed,
@@ -575,6 +602,10 @@ export function loadAppSettings(): AppSettings {
modernCustomColor: validCustomColor,
uiTone: validTone,
maxHistorySteps: validMaxHistorySteps,
+ collabSignalingUrl: validCollabSignalingUrl,
+ collabTurnUrl: validCollabTurnUrl,
+ collabTurnUsername: validCollabTurnUsername,
+ collabTurnCredential: validCollabTurnCredential,
autoOptimizePerformance: validAutoOptimizePerformance,
tileMemoryBudgetMb: validBudget,
memoryAllocationPercent: validMemoryPercent,
diff --git a/src/utils/__tests__/brushResponsiveness.test.ts b/src/utils/__tests__/brushResponsiveness.test.ts
new file mode 100644
index 0000000..5e3f2c8
--- /dev/null
+++ b/src/utils/__tests__/brushResponsiveness.test.ts
@@ -0,0 +1,257 @@
+import { describe, it, expect } from 'vitest';
+import { getEffectiveBrushSettings } from '../brushPresetManager';
+import { drawBrushCubicBezierSegment, buildBrushRenderOptions } from '../../engine/BrushEngine';
+import { LayerPixelSampler, PaintReservoir } from '../colorMixingEngine';
+import { NaturalPaintStrokeSession } from '../../engine/NaturalPaintRenderer';
+import { uploadActiveDraftTexture } from '../compositor/tileDraw';
+import { BrushPresetId, BrushSettings, Point } from '../../types/editor';
+
+function makeBenchCanvas(w = 512, h = 512) {
+ let width = w;
+ let height = h;
+ let buf = new Uint8ClampedArray(width * height * 4);
+ let resizes = 0;
+ let createImgDataCalls = 0;
+ let putImgDataCalls = 0;
+ const canvas: any = {
+ get width() { return width; },
+ set width(v: number) { if (v !== width) resizes++; width = v; buf = new Uint8ClampedArray(Math.max(1, width * height * 4)); },
+ get height() { return height; },
+ set height(v: number) { if (v !== height) resizes++; height = v; buf = new Uint8ClampedArray(Math.max(1, width * height * 4)); },
+ get __resizes() { return resizes; },
+ get __createImgDataCalls() { return createImgDataCalls; },
+ get __putImgDataCalls() { return putImgDataCalls; },
+ __buf: buf,
+ getContext: () => ctx,
+ toDataURL: () => 'data:image/png;base64,MOCK',
+ };
+ const ctx: any = {
+ canvas,
+ globalAlpha: 1,
+ globalCompositeOperation: 'source-over',
+ imageSmoothingEnabled: true,
+ save: () => {},
+ restore: () => {},
+ translate: () => {},
+ rotate: () => {},
+ scale: () => {},
+ clearRect: () => {},
+ createImageData: (iw: number, ih: number) => {
+ createImgDataCalls++;
+ return { width: iw, height: ih, data: new Uint8ClampedArray(iw * ih * 4) };
+ },
+ putImageData: () => { putImgDataCalls++; },
+ getImageData: (sx = 0, sy = 0, sw = width, sh = height) => {
+ const out = new Uint8ClampedArray(sw * sh * 4);
+ for (let row = 0; row < sh; row++) {
+ const srcY = sy + row;
+ if (srcY < 0 || srcY >= height) continue;
+ const srcStart = (srcY * width + Math.max(0, sx)) * 4;
+ const dstStart = (row * sw + Math.max(0, -sx)) * 4;
+ const copyCols = Math.min(sw - Math.max(0, -sx), width - Math.max(0, sx));
+ if (copyCols > 0) {
+ out.set(buf.subarray(srcStart, srcStart + copyCols * 4), dstStart);
+ }
+ }
+ return { width: sw, height: sh, data: out };
+ },
+ drawImage: () => {},
+ };
+ return canvas;
+}
+
+describe('Brush Responsiveness & Blend Performance', () => {
+ it('benchmarks curved 320px multi-color swipes for Loaded Impasto Oil, Dry Bristle Rake, Blend, and Natural Paint brushes', () => {
+ const store = new Map<string, string>();
+ (globalThis as any).localStorage = {
+ getItem: (k: string) => store.get(k) ?? null,
+ setItem: (k: string, v: string) => store.set(k, String(v)),
+ removeItem: (k: string) => store.delete(k),
+ clear: () => store.clear(),
+ };
+ const createdCanvases: any[] = [];
+ (globalThis as any).document = {
+ createElement: () => {
+ const c = makeBenchCanvas(256, 256);
+ createdCanvases.push(c);
+ return c;
+ },
+ };
+ (globalThis as any).Image = class {
+ src = ''; complete = true; naturalWidth = 256; naturalHeight = 256; width = 256; height = 256;
+ decode() { return Promise.resolve(); }
+ };
+
+ // Painted canvas with smooth multi-color gradient (worst-case pigment mixing!)
+ const srcCanvas = makeBenchCanvas(512, 512);
+ const sbuf = srcCanvas.__buf;
+ for (let y = 0; y < 512; y++) {
+ for (let x = 0; x < 512; x++) {
+ const i = (y * 512 + x) << 2;
+ sbuf[i] = ((x * 255) / 512) | 0;
+ sbuf[i + 1] = ((y * 255) / 512) | 0;
+ sbuf[i + 2] = 255 - (((x * 255) / 512) | 0);
+ sbuf[i + 3] = 255;
+ }
+ }
+
+ const segs: Array<[Point, Point, Point, Point]> = [];
+ for (let k = 0; k < 8; k++) {
+ const t0 = k / 8;
+ const t1 = (k + 1) / 8;
+ const x0 = 60 + t0 * 320;
+ const y0 = 256 + Math.sin(t0 * Math.PI * 2) * 90;
+ const x3 = 60 + t1 * 320;
+ const y3 = 256 + Math.sin(t1 * Math.PI * 2) * 90;
+ const p0Val = 0.45 + 0.45 * Math.sin(t0 * Math.PI);
+ const p3Val = 0.45 + 0.45 * Math.sin(t1 * Math.PI);
+ segs.push([
+ { x: x0, y: y0, pressure: p0Val, width: 0 },
+ { x: x0 + (x3 - x0) * 0.33, y: y0 + (y3 - y0) * 0.6, pressure: (p0Val + p3Val) * 0.5, width: 0 },
+ { x: x0 + (x3 - x0) * 0.66, y: y0 + (y3 - y0) * 0.4, pressure: (p0Val + p3Val) * 0.5, width: 0 },
+ { x: x3, y: y3, pressure: p3Val, width: 0 },
+ ]);
+ }
+
+ const spatialPresets: BrushPresetId[] = [
+ 'thick-oil-impasto',
+ 'dry-bristle-rake-paint',
+ 'blend-velvet-soft',
+ 'blend-oil-bristle',
+ 'blend-matte-chalk',
+ 'blend-rake-hair',
+ 'blend-canvas-scumble',
+ 'blend-fingertip',
+ ];
+
+ const draft = makeBenchCanvas(512, 512);
+ const draftCtx = draft.getContext('2d');
+
+ for (const id of spatialPresets) {
+ const bs = getEffectiveBrushSettings(id) as BrushSettings;
+ const size = Math.max(bs.size, 64);
+ const bsRun: BrushSettings = { ...bs, size, color: '#facc15', useGpu: false };
+ const sampler = new LayerPixelSampler(srcCanvas);
+ const reservoir = new PaintReservoir('#facc15');
+ const opts = buildBrushRenderOptions(bsRun, { sampler, reservoir, useGpu: false });
+ const counter = { count: 0 };
+ let rem = 0;
+ const canvasCountBefore = createdCanvases.length;
+
+ const t0 = performance.now();
+ for (const [p0, c1, c2, p3] of segs) {
+ rem = drawBrushCubicBezierSegment(
+ draftCtx,
+ { ...p0, width: size * (0.4 + 0.6 * p0.pressure) },
+ { ...c1, width: size * (0.4 + 0.6 * c1.pressure) },
+ { ...c2, width: size * (0.4 + 0.6 * c2.pressure) },
+ { ...p3, width: size * (0.4 + 0.6 * p3.pressure) },
+ '#facc15',
+ opts,
+ rem,
+ counter
+ );
+ }
+ const ms = performance.now() - t0;
+ const newCanvases = createdCanvases.slice(canvasCountBefore);
+ // After initial creation (width+height set once), pooled surfaces must NEVER resize again!
+ const extraResizes = newCanvases.reduce((s, c) => s + Math.max(0, c.__resizes - 2), 0);
+ const totalCreateImg = newCanvases.reduce((s, c) => s + c.__createImgDataCalls, 0);
+ console.log(
+ `[BENCH] ${id.padEnd(24)} dabs=${String(counter.count).padStart(4)} extraResizes=${String(extraResizes).padStart(3)} createImg=${String(totalCreateImg).padStart(4)} time=${ms.toFixed(1)}ms`
+ );
+ expect(counter.count).toBeGreaterThan(10);
+ // Exact-size surface pool never resizes an existing canvas across pressure changes
+ expect(extraResizes).toBe(0);
+ }
+
+ const naturalPresets: BrushPresetId[] = ['impasto-bristle-oil', 'dry-bristle-rake', 'oil-bristle-blender'];
+ for (const id of naturalPresets) {
+ const bs = getEffectiveBrushSettings(id) as BrushSettings;
+ const size = Math.max(bs.size, 64);
+ const bsRun: BrushSettings = { ...bs, size, color: '#facc15' };
+ const sampler = new LayerPixelSampler(srcCanvas);
+ const session = new NaturalPaintStrokeSession(bsRun, '#facc15', undefined, 1337);
+ const t0 = performance.now();
+ session.stampInitialPoint(draftCtx, { ...segs[0][0], width: size * 0.6 }, sampler, true);
+ // Simulate real animation-frame batching (2 coalesced Bezier segments per frame -> 1 flush/frame)
+ for (let i = 0; i < segs.length; i++) {
+ const [p0, c1, c2, p3] = segs[i];
+ session.appendCubicSegment(
+ { ...p0, width: size * (0.4 + 0.6 * p0.pressure) },
+ { ...c1, width: size * (0.4 + 0.6 * c1.pressure) },
+ { ...c2, width: size * (0.4 + 0.6 * c2.pressure) },
+ { ...p3, width: size * (0.4 + 0.6 * p3.pressure) },
+ sampler
+ );
+ if ((i & 1) === 1 || i === segs.length - 1) {
+ session.flushPendingDirtyToContext(draftCtx, true);
+ }
+ }
+ const ms = performance.now() - t0;
+ expect(session.getDirtyBounds()).not.toBeNull();
+ session.finishAndDispose();
+ console.log(`[BENCH-NAT] ${id.padEnd(20)} time=${ms.toFixed(1)}ms`);
+ }
+ });
+
+ it('uploads only the dirty sub-rect of large draft canvases and skips mipmaps at 50%-99% zoom', () => {
+ (globalThis as any).document = {
+ createElement: () => makeBenchCanvas(16, 16),
+ };
+ const subCalls: any[] = [];
+ let mipmapCalls = 0;
+ const mockGl: any = {
+ TEXTURE0: 0x84c0,
+ TEXTURE_2D: 0x0de1,
+ TEXTURE_WRAP_S: 0x2802,
+ TEXTURE_WRAP_T: 0x2803,
+ TEXTURE_MIN_FILTER: 0x2801,
+ TEXTURE_MAG_FILTER: 0x2800,
+ CLAMP_TO_EDGE: 0x812f,
+ LINEAR: 0x2601,
+ NEAREST: 0x2600,
+ LINEAR_MIPMAP_LINEAR: 0x2703,
+ UNPACK_ALIGNMENT: 0x0cf5,
+ UNPACK_FLIP_Y_WEBGL: 0x9240,
+ UNPACK_PREMULTIPLY_ALPHA_WEBGL: 0x9241,
+ RGBA: 0x1908,
+ UNSIGNED_BYTE: 0x1401,
+ createTexture: () => ({ id: 'tex' }),
+ activeTexture: () => {},
+ bindTexture: () => {},
+ texParameteri: () => {},
+ pixelStorei: () => {},
+ texImage2D: () => {},
+ texSubImage2D: (...args: any[]) => subCalls.push(args),
+ generateMipmap: () => { mipmapCalls++; },
+ };
+ const state: any = {
+ draftTexture: null,
+ draftTexWidth: 0,
+ draftTexHeight: 0,
+ lastDraftVersion: -1,
+ draftHasMipmap: false,
+ draftUploadCanvas: null,
+ currentZoom: 0.75,
+ filteringQuality: 'auto',
+ };
+ const draft: any = makeBenchCanvas(2048, 2048);
+ draft.__draftHasContent = true;
+
+ // Frame 1: initial full allocation
+ uploadActiveDraftTexture(state, mockGl, draft, 1, 'document');
+ expect(mipmapCalls).toBe(0);
+
+ // Frame 2: small 120x90 stroke dirty sub-rect -> must upload only (100, 200, 120x90)
+ draft.__draftFrameDirtyRect = { x: 100, y: 200, width: 120, height: 90 };
+ uploadActiveDraftTexture(state, mockGl, draft, 2, 'document');
+ expect(subCalls.length).toBe(1);
+ expect(subCalls[0][2]).toBe(100);
+ expect(subCalls[0][3]).toBe(200);
+ expect(subCalls[0][6].width).toBe(120);
+ expect(subCalls[0][6].height).toBe(90);
+ expect(draft.__draftFrameDirtyRect).toBeNull();
+ expect(mipmapCalls).toBe(0);
+ });
+});
diff --git a/src/utils/__tests__/builtinBrushes.test.ts b/src/utils/__tests__/builtinBrushes.test.ts
index 1bd38ae..f208015 100644
--- a/src/utils/__tests__/builtinBrushes.test.ts
+++ b/src/utils/__tests__/builtinBrushes.test.ts
@@ -3,18 +3,43 @@ import {
BUILTIN_BRUSHES,
BUILTIN_BRUSH_SECTIONS,
getBuiltinBrushConfig,
+ prewarmBuiltinBrushAssets,
} from '../presetBrushes';
-import { getEffectiveBrushSettings } from '../brushPresetManager';
+import {
+ BUILTIN_PRESET_SCHEMA_VERSION,
+ LEGACY_PRESET_ID_MAP,
+ STORAGE_KEY_ACTIVE_PRESET,
+ STORAGE_KEY_SETTINGS,
+ getActivePresetId,
+ getEffectiveBrushSettings,
+ loadAllSavedBrushSettings,
+ migrateLegacyPresetId,
+ resetBrushSettingsCache,
+ saveBrushSettingsImmediately,
+} from '../brushPresetManager';
import {
applyCspPaperTextureAlpha,
drawBrushCubicBezierSegment,
BrushRenderOptions,
} from '../../engine/BrushEngine';
-import { PaintReservoir } from '../colorMixingEngine';
-import { Point } from '../../types/editor';
+import {
+ buildRibbonMeshFromPoints,
+ buildRibbonRenderOptionsFromBrushSettings,
+ isRibbonBrush,
+} from '../../engine/RibbonBrushEngine';
+import { resolveDualBrushConfig } from '../../engine/DualBrushEngine';
+import {
+ LayerPixelSampler,
+ PaintReservoir,
+ SpatialTipMixer,
+} from '../colorMixingEngine';
+import { compositeBrushPixelInto } from '../tileEngine/strokeComposite';
+import { BrushSettings, Point } from '../../types/editor';
-function createMockCanvas(width: number = 128, height: number = 128) {
- const pixelBuffer = new Uint8ClampedArray(width * height * 4);
+function createMockCanvas(initWidth: number = 128, initHeight: number = 128) {
+ let width = initWidth;
+ let height = initHeight;
+ let pixelBuffer = new Uint8ClampedArray(width * height * 4);
const drawnDabs: {
x: number;
y: number;
@@ -23,8 +48,37 @@ function createMockCanvas(width: number = 128, height: number = 128) {
alpha: number;
}[] = [];
+ const ensureSize = () => {
+ const needed = Math.max(1, width) * Math.max(1, height) * 4;
+ if (pixelBuffer.length !== needed) {
+ pixelBuffer = new Uint8ClampedArray(needed);
+ }
+ };
+
+ const canvasObj: any = {
+ get width() {
+ return width;
+ },
+ set width(v: number) {
+ width = v;
+ ensureSize();
+ },
+ get height() {
+ return height;
+ },
+ set height(v: number) {
+ height = v;
+ ensureSize();
+ },
+ get pixelBuffer() {
+ return pixelBuffer;
+ },
+ drawnDabs,
+ lastImageData: null as { width: number; height: number; data: Uint8ClampedArray } | null,
+ };
+
const ctx: any = {
- canvas: { width, height },
+ canvas: canvasObj,
globalAlpha: 1.0,
globalCompositeOperation: 'source-over',
imageSmoothingEnabled: true,
@@ -36,11 +90,35 @@ function createMockCanvas(width: number = 128, height: number = 128) {
data: new Uint8ClampedArray(w * h * 4),
}),
putImageData: (imgData: any) => {
+ canvasObj.lastImageData = {
+ width: imgData.width,
+ height: imgData.height,
+ data: new Uint8ClampedArray(imgData.data),
+ };
if (imgData.data.length === pixelBuffer.length) {
pixelBuffer.set(imgData.data);
+ } else {
+ pixelBuffer = new Uint8ClampedArray(imgData.data);
+ }
+ },
+ getImageData: (sx: number = 0, sy: number = 0, sw: number = width, sh: number = height) => {
+ const out = new Uint8ClampedArray(sw * sh * 4);
+ for (let y = 0; y < sh; y++) {
+ const srcY = sy + y;
+ if (srcY < 0 || srcY >= height) continue;
+ for (let x = 0; x < sw; x++) {
+ const srcX = sx + x;
+ if (srcX < 0 || srcX >= width) continue;
+ const sIdx = (srcY * width + srcX) << 2;
+ const dIdx = (y * sw + x) << 2;
+ out[dIdx] = pixelBuffer[sIdx];
+ out[dIdx + 1] = pixelBuffer[sIdx + 1];
+ out[dIdx + 2] = pixelBuffer[sIdx + 2];
+ out[dIdx + 3] = pixelBuffer[sIdx + 3];
+ }
}
+ return { width: sw, height: sh, data: out };
},
- getImageData: () => ({ width, height, data: pixelBuffer }),
drawImage: (_src: any, dx: number, dy: number, dw?: number, dh?: number) => {
drawnDabs.push({
x: dx + (dw ? dw / 2 : 0),
@@ -57,18 +135,32 @@ function createMockCanvas(width: number = 128, height: number = 128) {
scale: () => {},
};
+ canvasObj.getContext = (type: string) => (type === '2d' ? ctx : null);
+ canvasObj.toDataURL = () =>
+ `data:image/png;base64,MOCK_${width}x${height}_${pixelBuffer.reduce((a, b) => (a + b) & 0xffff, 0)}`;
+
+ return canvasObj;
+}
+
+function createMemoryStorage() {
+ const store = new Map<string, string>();
return {
- width,
- height,
- getContext: (type: string) => (type === '2d' ? ctx : null),
- toDataURL: () => `data:image/png;base64,MOCK_${width}x${height}_${pixelBuffer.reduce((a, b) => (a + b) & 0xffff, 0)}`,
- pixelBuffer,
- drawnDabs,
+ getItem: (k: string) => (store.has(k) ? store.get(k)! : null),
+ setItem: (k: string, v: string) => {
+ store.set(k, String(v));
+ },
+ removeItem: (k: string) => {
+ store.delete(k);
+ },
+ clear: () => store.clear(),
};
}
-describe('Pre-Installed Standard Brushes & Realistic Physics', () => {
+describe('Pre-Installed Standard Brushes, CSP Pen Port & Pro Painting/Blending Physics', () => {
beforeEach(() => {
+ (globalThis as any).localStorage = createMemoryStorage();
+ resetBrushSettingsCache();
+
(globalThis as any).document = {
createElement: (tag: string) => {
if (tag === 'canvas') return createMockCanvas();
@@ -78,30 +170,39 @@ describe('Pre-Installed Standard Brushes & Realistic Physics', () => {
(globalThis as any).Image = class MockImage {
src = '';
complete = true;
- naturalWidth = 128;
- naturalHeight = 128;
- width = 128;
- height = 128;
+ naturalWidth = 256;
+ naturalHeight = 256;
+ width = 256;
+ height = 256;
decode() {
return Promise.resolve();
}
};
});
- it('registers all 26 brushes cleanly across Pen (5), Sketch (5), Brush (7), and Natural Paint (9) sections', () => {
+ it('registers all 35 built-in brushes cleanly across Pen (6), Sketch (5), Brush (9), Blend (6), and Natural Paint (9)', () => {
expect(BUILTIN_BRUSH_SECTIONS.map((s) => s.id)).toEqual([
'pen',
'sketch',
'brush',
+ 'blend',
'natural-paint',
]);
const penIds = BUILTIN_BRUSHES.filter((b) => b.category === 'pen').map((b) => b.id);
const sketchIds = BUILTIN_BRUSHES.filter((b) => b.category === 'sketch').map((b) => b.id);
const brushIds = BUILTIN_BRUSHES.filter((b) => b.category === 'brush').map((b) => b.id);
+ const blendIds = BUILTIN_BRUSHES.filter((b) => b.category === 'blend').map((b) => b.id);
const naturalIds = BUILTIN_BRUSHES.filter((b) => b.category === 'natural-paint').map((b) => b.id);
- expect(penIds).toEqual(['g-pen', 'real-g-pen', 'textured-pen', 'dot-pen', 'calligraphy']);
+ expect(penIds).toEqual([
+ 'g-pen',
+ 'real-g-pen',
+ 'textured-pen',
+ 'rough-pen',
+ 'dot-pen',
+ 'calligraphy',
+ ]);
expect(sketchIds).toEqual([
'mechanical-pencil',
'pencil-hb-2b',
@@ -110,13 +211,23 @@ describe('Pre-Installed Standard Brushes & Realistic Physics', () => {
'standard-chalk',
]);
expect(brushIds).toEqual([
- 'oil-painting',
- 'thick-oil-painting',
- 'chalk-painting',
- 'blend-brush',
- 'blend-chalk-brush',
- 'soft-round',
- 'noise-shader',
+ 'oil-flat-alla-prima',
+ 'thick-oil-impasto',
+ 'dry-bristle-rake-paint',
+ 'concept-matte-chalk',
+ 'silky-portrait-round',
+ 'canvas-scumble-oil',
+ 'soft-glaze-airbrush',
+ 'atmospheric-grain-shader',
+ 'fine-detail-filbert',
+ ]);
+ expect(blendIds).toEqual([
+ 'blend-velvet-soft',
+ 'blend-oil-bristle',
+ 'blend-matte-chalk',
+ 'blend-rake-hair',
+ 'blend-canvas-scumble',
+ 'blend-fingertip',
]);
expect(naturalIds).toEqual([
'impasto-bristle-oil',
@@ -129,9 +240,11 @@ describe('Pre-Installed Standard Brushes & Realistic Physics', () => {
'oil-bristle-blender',
'pastel-stick-canvas',
]);
+ expect(BUILTIN_BRUSHES).toHaveLength(35);
});
- it('generates deterministic non-empty procedural tip and paper PNG data URLs for every configured brush', () => {
+ it('generates deterministic non-empty PNG assets for tips, sub-tips, dual tips, and paper textures across all 35 presets', () => {
+ prewarmBuiltinBrushAssets();
for (const def of BUILTIN_BRUSHES) {
const cfg = getBuiltinBrushConfig(def.id);
expect(cfg).not.toBeNull();
@@ -140,6 +253,19 @@ describe('Pre-Installed Standard Brushes & Realistic Physics', () => {
expect(cfg?.customTipDataUrl).toMatch(/^data:image\/png;base64,/);
expect(cfg?.customTipImage).toBeDefined();
}
+ if (def.subTipGenerators && def.subTipGenerators.length > 0) {
+ expect(cfg?.subTips).toHaveLength(def.subTipGenerators.length);
+ expect(cfg?.subTipImages).toHaveLength(def.subTipGenerators.length);
+ for (const st of cfg!.subTips!) {
+ expect(st.dataUrl).toMatch(/^data:image\/png;base64,/);
+ }
+ }
+ if (def.dualTipGenerator) {
+ expect(cfg?.dualTipDataUrl).toMatch(/^data:image\/png;base64,/);
+ expect(cfg?.dualTipImage).toBeDefined();
+ expect(cfg?.dualBrushConfig?.tipDataUrl).toMatch(/^data:image\/png;base64,/);
+ expect(cfg?.dualBrushConfig?.tipImage).toBeDefined();
+ }
if (def.paperTextureGenerator) {
expect(cfg?.paperTexture).toMatch(/^data:image\/png;base64,/);
expect(cfg?.paperTextureImage).toBeDefined();
@@ -147,20 +273,170 @@ describe('Pre-Installed Standard Brushes & Realistic Physics', () => {
}
});
- it('enforces authentic Sketch pencil physics contracts across grades', () => {
+ it('enforces official CSP Pen contracts for G-Pen, Real G-Pen, Textured Pen, and Rough Pen (Ribbon)', () => {
+ // 1. G-Pen: analytical circular tip, linear pressure + exact CSP tilt swell (1.0..1.5)
+ const gPen = getBuiltinBrushConfig('g-pen')!;
+ expect(gPen.customTipDataUrl).toBeUndefined();
+ expect(gPen.size).toBe(12);
+ expect(gPen.hardness).toBe(1.0);
+ expect(gPen.antiAlias).toBe(2);
+ expect(gPen.sharpCorners).toBe(true);
+ expect(gPen.sizeSensor?.usePressure).toBe(true);
+ expect(gPen.sizeSensor?.useTilt).toBe(true);
+ expect(gPen.sizeSensor?.tiltMin).toBe(1.0);
+ expect(gPen.sizeSensor?.tiltMax).toBe(1.5);
+ expect(gPen.sizeSensor?.tiltCurve).toEqual([
+ [0.0, 1.0],
+ [0.2455, 0.9273],
+ [0.3909, 0.4],
+ [0.6545, 0.0],
+ [1.0, 0.0],
+ ]);
+
+ // 2. Real G-Pen: custom jagged porous tip, concave J-curve + tilt + pressure nib spread, no artificial grain
+ const realG = getBuiltinBrushConfig('real-g-pen')!;
+ expect(realG.customTipDataUrl).toMatch(/^data:image\/png;base64,/);
+ expect(realG.size).toBe(10);
+ expect(realG.thickness).toBe(0.85);
+ expect(realG.thicknessVertical).toBe(false);
+ expect(realG.grain ?? 0).toBe(0);
+ expect(realG.customTipAngleDynamics).toBe('random');
+ expect(realG.sizeSensor?.pressureCurve).toEqual([
+ [0.0, 0.0],
+ [0.7455, 0.2545],
+ [1.0, 1.0],
+ ]);
+ expect(realG.sizeSensor?.tiltMin).toBe(1.0);
+ expect(realG.sizeSensor?.tiltMax).toBe(1.5);
+ expect(realG.thicknessSensor?.usePressure).toBe(true);
+ expect(realG.thicknessSensor?.pressureMin).toBe(0.5);
+
+ // 3. Textured Pen: analytical ellipse, NO raster tip, compare-density combine mode, antiAlias=1
+ const texPen = getBuiltinBrushConfig('textured-pen')!;
+ expect(texPen.customTipDataUrl).toBeUndefined();
+ expect(texPen.size).toBe(12);
+ expect(texPen.thickness).toBe(0.6);
+ expect(texPen.thicknessVertical).toBe(true);
+ expect(texPen.hardness).toBe(0.6);
+ expect(texPen.spacing).toBe(0.1);
+ expect(texPen.antiAlias).toBe(1);
+ expect(texPen.brushCombineMode).toBe('compare-density');
+ expect(texPen.customTipAngleDynamics).toBe('random');
+ expect(texPen.useTilt).toBe(false);
+
+ // Verify compare-density compositing prevents semi-transparent alpha stacking on transparent layers
+ // while still drawing solid/anti-aliased dark ink cleanly over opaque filled layers (da === 255).
+ const pxOut: [number, number, number, number] = [0, 0, 0, 0];
+ // Same-color semi-transparent overlap: alpha stays max(140, 140) = 140
+ compositeBrushPixelInto(10, 10, 10, 140, 10, 10, 10, 140, 'source-over', 'compare-density', pxOut);
+ expect(pxOut[3]).toBe(140);
+ // Solid black ink over opaque cream paper (da = 255): must draw solid black, never invisible!
+ compositeBrushPixelInto(248, 245, 238, 255, 12, 12, 16, 255, 'source-over', 'compare-density', pxOut);
+ expect(pxOut[0]).toBe(12);
+ expect(pxOut[1]).toBe(12);
+ expect(pxOut[2]).toBe(16);
+ expect(pxOut[3]).toBe(255);
+ // Semi-transparent feathered ink edge (effA = 128) over opaque cream paper: blends cleanly
+ compositeBrushPixelInto(248, 245, 238, 255, 0, 0, 0, 128, 'source-over', 'compare-density', pxOut);
+ expect(pxOut[0]).toBeLessThan(140);
+ expect(pxOut[3]).toBe(255);
+
+ // 4. Rough Pen: Ribbon brush, adapted comfortable pixel size (not raw 1.2mm), 4-source sizeSensor & 2-source thicknessSensor
+ const roughPen = getBuiltinBrushConfig('rough-pen')!;
+ expect(roughPen.isRibbon).toBe(true);
+ expect(roughPen.size!).toBeGreaterThanOrEqual(10);
+ expect(roughPen.antiAlias).toBe(1);
+ expect(roughPen.thickness).toBe(1.5);
+ expect(roughPen.thicknessVertical).toBe(true);
+ expect(roughPen.subTips?.length).toBe(3);
+ expect(roughPen.subTips?.[0].width).toBe(64);
+ expect(roughPen.subTips?.[0].height).toBe(512);
+ expect(roughPen.subTipOrder).toBe('random');
+ expect(roughPen.flipH).toBe('alternate');
+ expect(roughPen.flipV).toBe('alternate');
+ expect(roughPen.sizeSensor?.usePressure).toBe(true);
+ expect(roughPen.sizeSensor?.useTilt).toBe(true);
+ expect(roughPen.sizeSensor?.tiltMax).toBe(2.0);
+ expect(roughPen.sizeSensor?.useVelocity).toBe(true);
+ expect(roughPen.sizeSensor?.velocityMin).toBe(0.5);
+ expect(roughPen.sizeSensor?.useRandom).toBe(true);
+ expect(roughPen.sizeSensor?.randomMin).toBe(0.8);
+ expect(roughPen.thicknessSensor?.useVelocity).toBe(true);
+ expect(roughPen.thicknessSensor?.useRandom).toBe(true);
+ });
+
+ it('orients Rough Pen ribbon UVs strictly along the stroke path (vertical strip Y maps along stroke, X across width)', () => {
+ const roughEffective = getEffectiveBrushSettings('rough-pen') as BrushSettings;
+ // Override mock image dimensions to match real 64x512 vertical ribbon tip
+ const verticalTipImg: any = {
+ src: roughEffective.customTipDataUrl,
+ complete: true,
+ naturalWidth: 64,
+ naturalHeight: 512,
+ width: 64,
+ height: 512,
+ };
+ const ribbonBs: BrushSettings = {
+ ...roughEffective,
+ color: '#111111',
+ customTipImage: verticalTipImg,
+ subTipImages: [verticalTipImg],
+ };
+ expect(isRibbonBrush(ribbonBs)).toBe(true);
+
+ const ribbonOpts = buildRibbonRenderOptionsFromBrushSettings(
+ ribbonBs,
+ 'color',
+ false,
+ false,
+ false,
+ false,
+ undefined,
+ { useGpu: false }
+ );
+ const pts: Point[] = [
+ { x: 20, y: 100, pressure: 0.85, width: 11, timestamp: 0 },
+ { x: 100, y: 100, pressure: 0.85, width: 11, timestamp: 50 },
+ { x: 200, y: 100, pressure: 0.85, width: 11, timestamp: 100 },
+ ];
+ const mesh = buildRibbonMeshFromPoints(pts, ribbonOpts);
+ expect(mesh.triangleCount).toBeGreaterThan(8);
+
+ // Vertex stride = 9: [x, y, u, v, alpha, pressure, tipIndex, edgeDist, ribbonWidth]
+ // First triangle vertices are (L0, R0, L1):
+ // L0 -> R0 must span texture X (uTex) across width, while L0 -> L1 must advance texture Y (vTex) along stroke.
+ const stride = 9;
+ const verts = mesh.vertices;
+ const uL0 = verts[0 * stride + 2];
+ const vL0 = verts[0 * stride + 3];
+ const uR0 = verts[1 * stride + 2];
+ const vR0 = verts[1 * stride + 3];
+ const uL1 = verts[2 * stride + 2];
+ const vL1 = verts[2 * stride + 3];
+
+ const dUAcross = Math.abs(uR0 - uL0);
+ const dVAcross = Math.abs(vR0 - vL0);
+ const dUAlong = Math.abs(uL1 - uL0);
+ const dVAlong = Math.abs(vL1 - vL0);
+
+ expect(dUAcross).toBeGreaterThan(0.9);
+ expect(dVAcross).toBeLessThan(0.05);
+ expect(dVAlong).toBeGreaterThan(0.01);
+ expect(dUAlong).toBeLessThan(0.05);
+ });
+
+ it('enforces authentic Sketch pencil physics contracts across grades (untouched)', () => {
const mech = getBuiltinBrushConfig('mechanical-pencil')!;
const hb2b = getBuiltinBrushConfig('pencil-hb-2b')!;
const b68 = getBuiltinBrushConfig('pencil-6b-8b')!;
const charcoal = getBuiltinBrushConfig('charcoal-pencil')!;
- // Mechanical pencil: firm, thin, tilt-independent, minimal grain, crisp edge
expect(mech.useTilt).toBe(false);
expect(mech.size).toBeLessThanOrEqual(3);
expect(mech.grain).toBeLessThan(0.4);
expect(mech.hardness).toBeGreaterThanOrEqual(0.9);
expect(mech.paperTextureMode).toBe('compare');
- // HB/2B: moderate grain, pressure opacity/flow modulation, gentle tilt
expect(hb2b.useTilt).toBe(true);
expect(hb2b.tiltScale!).toBeGreaterThan(0.5);
expect(hb2b.tiltScale!).toBeLessThan(1.2);
@@ -169,13 +445,11 @@ describe('Pre-Installed Standard Brushes & Realistic Physics', () => {
expect(hb2b.opacitySensor?.usePressure).toBe(true);
expect(hb2b.paperTextureMode).toBe('compare');
- // 6B/8B: rich dark, strong grain that clogs under heavy pressure, wide tilt hatching edge
expect(b68.useTilt).toBe(true);
expect(b68.tiltScale!).toBeGreaterThanOrEqual(1.8);
expect(b68.grain!).toBeGreaterThanOrEqual(0.8);
expect(b68.paperTextureMode).toBe('compare');
- // Charcoal: dry jagged aggressive texture, edge crumbs (halo + scatter), max tilt response
expect(charcoal.useTilt).toBe(true);
expect(charcoal.tiltScale!).toBeGreaterThanOrEqual(2.0);
expect(charcoal.grain!).toBeGreaterThanOrEqual(0.88);
@@ -184,18 +458,16 @@ describe('Pre-Installed Standard Brushes & Realistic Physics', () => {
});
it('cuts recessed paper valleys to exact zero at light/medium pressure and clogs only under heavy pressure (compare mode)', () => {
- const valleyHeight = 0.22; // Deep paper valley
- const ridgeHeight = 0.82; // High cotton paper peak
+ const valleyHeight = 0.22;
+ const ridgeHeight = 0.82;
- // At light & medium pressure, recessed valleys MUST cut to 0.0 so multi-dab overlap never fills them in
const valleyLight = applyCspPaperTextureAlpha(0.9, valleyHeight, 0.86, 0.25, 'compare');
- const valleyMed = applyCspPaperTextureAlpha(0.9, valleyHeight, 0.86, 0.50, 'compare');
- const ridgeMed = applyCspPaperTextureAlpha(0.9, ridgeHeight, 0.86, 0.50, 'compare');
+ const valleyMed = applyCspPaperTextureAlpha(0.9, valleyHeight, 0.86, 0.5, 'compare');
+ const ridgeMed = applyCspPaperTextureAlpha(0.9, ridgeHeight, 0.86, 0.5, 'compare');
expect(valleyLight).toBe(0);
expect(valleyMed).toBe(0);
expect(ridgeMed).toBeGreaterThan(0.8);
- // Under heavy pressure (6B/8B clogging), soft lead compresses into mid-valleys
const midValleyMed = applyCspPaperTextureAlpha(0.9, 0.42, 0.86, 0.45, 'compare');
const midValleyHeavy = applyCspPaperTextureAlpha(0.9, 0.42, 0.86, 0.96, 'compare');
expect(midValleyMed).toBe(0);
@@ -216,7 +488,6 @@ describe('Pre-Installed Standard Brushes & Realistic Physics', () => {
tiltY: 0,
})) as [Point, Point, Point, Point];
- // 1. 6B/8B widens dramatically and softens when tilted
const b68 = getBuiltinBrushConfig('pencil-6b-8b')!;
const cUp = createMockCanvas(200, 200);
const cTilt = createMockCanvas(200, 200);
@@ -233,14 +504,13 @@ describe('Pre-Installed Standard Brushes & Realistic Physics', () => {
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;
- const avgUpA = cUp.drawnDabs.reduce((s, d) => s + d.alpha, 0) / cUp.drawnDabs.length;
- const avgTiltA = cTilt.drawnDabs.reduce((s, d) => s + d.alpha, 0) / cTilt.drawnDabs.length;
+ const avgUpW = cUp.drawnDabs.reduce((s: number, d: any) => s + d.width, 0) / cUp.drawnDabs.length;
+ const avgTiltW = cTilt.drawnDabs.reduce((s: number, d: any) => s + d.width, 0) / cTilt.drawnDabs.length;
+ const avgUpA = cUp.drawnDabs.reduce((s: number, d: any) => s + d.alpha, 0) / cUp.drawnDabs.length;
+ const avgTiltA = cTilt.drawnDabs.reduce((s: number, d: any) => s + d.alpha, 0) / cTilt.drawnDabs.length;
expect(avgTiltW).toBeGreaterThan(avgUpW * 2.5);
expect(avgTiltA).toBeLessThan(avgUpA);
- // 2. Mechanical Pencil ignores tilt completely
const mech = getBuiltinBrushConfig('mechanical-pencil')!;
const mUp = createMockCanvas(200, 200);
const mTilt = createMockCanvas(200, 200);
@@ -256,69 +526,362 @@ describe('Pre-Installed Standard Brushes & Realistic Physics', () => {
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;
+ const mUpW = mUp.drawnDabs.reduce((s: number, d: any) => s + d.width, 0) / mUp.drawnDabs.length;
+ const mTiltW = mTilt.drawnDabs.reduce((s: number, d: any) => s + d.width, 0) / mTilt.drawnDabs.length;
expect(mTiltW).toBeCloseTo(mUpW, 4);
});
- it('prevents pure Blend / Blend Chalk brushes from emitting foreground color onto blank canvas or contaminating first contact', () => {
- const blend = getBuiltinBrushConfig('blend-brush')!;
- const blendChalk = getBuiltinBrushConfig('blend-chalk-brush')!;
- expect(blend.colorMixing).toBe(true);
- expect(blend.amountOfPaint).toBe(0);
- expect(blend.mixingMode).toBe('smear');
- expect(blendChalk.amountOfPaint).toBe(0);
- expect(blendChalk.mixingMode).toBe('smear');
- expect(blendChalk.grain).toBeGreaterThan(0.4);
-
- // Touching blank canvas with red foreground selected must output alpha === 0
- const resBlank = new PaintReservoir('#ff0000');
- const blankOut = resBlank.mixWithCanvas(
- { r: 255, g: 255, b: 255, a: 0 },
- 0,
- 0.75,
- 0.74,
- 'smear',
- 0.8,
- 0.7,
- 0,
- true
- );
- expect(blankOut.alpha).toBe(0);
-
- // First contact with pure blue paint on canvas must pick up pure blue, NOT mix in red foreground!
- const resPaint = new PaintReservoir('#ff0000');
- const firstContact = resPaint.mixWithCanvas(
- { r: 0, g: 40, b: 220, a: 1.0 },
- 0,
- 0.75,
- 0.74,
- 'smear',
- 0.8,
- 0.7,
- 0,
- true
+ it('configures the upgraded 9-brush painterly Brush suite with high-res tips, Dual Brush tooth, multi-tip scumble, and perceptual pigment mixing', () => {
+ const oilFlat = getBuiltinBrushConfig('oil-flat-alla-prima')!;
+ expect(oilFlat.colorMixing).toBe(true);
+ expect(oilFlat.perceptualMixing).toBe(true);
+ expect(oilFlat.customTipAngle).toBe(-22);
+ expect(oilFlat.customTipAngleDynamics).toBe('none');
+ expect(oilFlat.thickness).toBe(0.72);
+
+ const thickImpasto = getBuiltinBrushConfig('thick-oil-impasto')!;
+ expect(thickImpasto.mixingMode).toBe('running_color');
+ expect(thickImpasto.amountOfPaint!).toBeGreaterThanOrEqual(0.8);
+
+ const rakePaint = getBuiltinBrushConfig('dry-bristle-rake-paint')!;
+ expect(rakePaint.mixingMode).toBe('running_color');
+ expect(rakePaint.customTipAngleDynamics).toBe('direction');
+ expect(rakePaint.surfaceTextureId).toBe('linen-canvas');
+
+ const matteChalk = getBuiltinBrushConfig('concept-matte-chalk')!;
+ expect(matteChalk.dualBrush).toBe(true);
+ expect(matteChalk.dualBrushConfig?.enabled).toBe(true);
+ expect(matteChalk.dualBrushConfig?.tipImage).toBeDefined();
+ expect(resolveDualBrushConfig(matteChalk as BrushSettings)).not.toBeNull();
+ expect(matteChalk.customTipAngleDynamics).toBe('none');
+ expect(matteChalk.paperTextureMode).toBe('compare');
+ expect(matteChalk.amountOfPaint!).toBeGreaterThanOrEqual(0.8);
+
+ const scumble = getBuiltinBrushConfig('canvas-scumble-oil')!;
+ expect(scumble.subTips?.length).toBe(4);
+ expect(scumble.surfaceTextureId).toBe('linen-canvas');
+ expect(scumble.dynamics?.colorJitterEnabled).toBe(true);
+ expect(scumble.dynamics?.temperatureJitter!).toBeGreaterThan(0);
+
+ const airbrush = getBuiltinBrushConfig('soft-glaze-airbrush')!;
+ expect(airbrush.customTipDataUrl).toBeUndefined();
+ expect(airbrush.hardness).toBe(0.0);
+ expect(airbrush.flow!).toBeLessThanOrEqual(0.3);
+ expect(airbrush.adjustDensityByGap).toBe(true);
+ expect(airbrush.opacitySensor?.usePressure).toBe(true);
+
+ const fineDetail = getBuiltinBrushConfig('fine-detail-filbert')!;
+ expect(fineDetail.size!).toBeLessThanOrEqual(12);
+ expect(fineDetail.amountOfPaint!).toBeGreaterThanOrEqual(0.9);
+ });
+
+ it('enforces pure-smear invariants across all 6 Blend brushes (zero blank deposition, zero first-contact foreground contamination)', () => {
+ const blendDefs = BUILTIN_BRUSHES.filter((b) => b.category === 'blend');
+ expect(blendDefs).toHaveLength(6);
+
+ const blankCanvas = createMockCanvas(64, 64);
+ const blankSampler = new LayerPixelSampler(blankCanvas);
+
+ for (const def of blendDefs) {
+ const cfg = getBuiltinBrushConfig(def.id)!;
+ expect(cfg.colorMixing).toBe(true);
+ expect(cfg.perceptualMixing).toBe(true);
+ expect(cfg.amountOfPaint).toBe(0);
+ expect(cfg.mixingMode).toBe('smear');
+
+ // 1. PaintReservoir on blank canvas emits alpha === 0
+ const resBlank = new PaintReservoir('#ff0000');
+ const blankOut = resBlank.mixWithCanvas(
+ { r: 255, g: 255, b: 255, a: 0 },
+ cfg.amountOfPaint!,
+ cfg.densityOfPaint ?? 0.85,
+ cfg.colorStretch ?? 0.78,
+ 'smear',
+ 0.8,
+ 0.8,
+ 0,
+ true
+ );
+ expect(blankOut.alpha).toBe(0);
+
+ // 2. SpatialTipMixer on blank canvas with bright red foreground emits zero visible pixels
+ const spatialBlank = new SpatialTipMixer('#ff0000');
+ const stampBlank = spatialBlank.stepAndBuildStamp({
+ sampler: blankSampler,
+ x: 32,
+ y: 32,
+ width: 24,
+ height: 24,
+ angleRad: 0,
+ dirX: 1,
+ dirY: 0,
+ stepDist: 2,
+ hardness: cfg.hardness ?? 0.5,
+ antiAlias: 2,
+ flipX: 1,
+ flipY: 1,
+ flow: cfg.flow ?? 0.6,
+ pressure: 0.7,
+ pressureAlreadyApplied: false,
+ amountOfPaint: cfg.amountOfPaint!,
+ densityOfPaint: cfg.densityOfPaint ?? 0.85,
+ colorStretch: cfg.colorStretch ?? 0.78,
+ mixingMode: 'smear',
+ isPureBlender: true,
+ perceptualMixing: true,
+ useBlur: Boolean(cfg.useBlur),
+ blurStrength: cfg.blurStrength,
+ });
+ expect(!stampBlank || !stampBlank.hasVisiblePixels).toBe(true);
+
+ // 3. First contact with pure blue canvas paint must never mix in red foreground
+ const resBlue = new PaintReservoir('#ff0000');
+ const firstContact = resBlue.mixWithCanvas(
+ { r: 0, g: 40, b: 220, a: 1.0 },
+ cfg.amountOfPaint!,
+ cfg.densityOfPaint ?? 0.85,
+ cfg.colorStretch ?? 0.78,
+ 'smear',
+ 0.8,
+ 0.8,
+ 0,
+ true
+ );
+ expect(firstContact.r).toBe(0);
+ expect(firstContact.g).toBe(40);
+ expect(firstContact.b).toBe(220);
+ expect(firstContact.alpha).toBeGreaterThan(0.1);
+ }
+
+ // Specific Blend brush character contracts
+ expect(getBuiltinBrushConfig('blend-velvet-soft')!.useBlur).toBe(true);
+ expect(getBuiltinBrushConfig('blend-velvet-soft')!.blurStrength!).toBeGreaterThanOrEqual(0.3);
+ expect(getBuiltinBrushConfig('blend-oil-bristle')!.useBlur).toBe(false);
+ expect(getBuiltinBrushConfig('blend-rake-hair')!.useBlur).toBe(false);
+ expect(getBuiltinBrushConfig('blend-fingertip')!.useBlur).toBe(false);
+ expect(getBuiltinBrushConfig('blend-matte-chalk')!.paperTextureMode).toBe('compare');
+ expect(getBuiltinBrushConfig('blend-canvas-scumble')!.surfaceTextureId).toBe('linen-canvas');
+ });
+
+ it('produces measurably smoother transitions across a hard color seam in SpatialTipMixer when useBlur is enabled', () => {
+ // Build a 64x64 canvas with a razor-sharp vertical seam at x = 32: left = pure red, right = pure blue
+ const seamCanvas = createMockCanvas(64, 64);
+ const buf = seamCanvas.pixelBuffer as Uint8ClampedArray;
+ for (let y = 0; y < 64; y++) {
+ for (let x = 0; x < 64; x++) {
+ const idx = (y * 64 + x) << 2;
+ if (x < 32) {
+ buf[idx] = 230;
+ buf[idx + 1] = 25;
+ buf[idx + 2] = 25;
+ buf[idx + 3] = 255;
+ } else {
+ buf[idx] = 25;
+ buf[idx + 1] = 45;
+ buf[idx + 2] = 230;
+ buf[idx + 3] = 255;
+ }
+ }
+ }
+
+ const samplerSharp = new LayerPixelSampler(seamCanvas);
+ const samplerBlur = new LayerPixelSampler(seamCanvas);
+
+ const sharpMixer = new SpatialTipMixer('#00ff00');
+ const blurMixer = new SpatialTipMixer('#00ff00');
+
+ const baseParams = {
+ x: 32,
+ y: 32,
+ width: 32,
+ height: 32,
+ angleRad: 0,
+ dirX: 1,
+ dirY: 0,
+ stepDist: 2,
+ hardness: 0.9,
+ antiAlias: 2,
+ flipX: 1,
+ flipY: 1,
+ flow: 0.85,
+ pressure: 0.8,
+ pressureAlreadyApplied: false,
+ amountOfPaint: 0,
+ densityOfPaint: 0.9,
+ colorStretch: 0.85,
+ mixingMode: 'smear' as const,
+ isPureBlender: true,
+ perceptualMixing: true,
+ };
+
+ const sharpStamp = sharpMixer.stepAndBuildStamp({
+ ...baseParams,
+ sampler: samplerSharp,
+ useBlur: false,
+ })!;
+ const blurStamp = blurMixer.stepAndBuildStamp({
+ ...baseParams,
+ sampler: samplerBlur,
+ useBlur: true,
+ blurStrength: 0.6,
+ })!;
+
+ expect(sharpStamp.hasVisiblePixels).toBe(true);
+ expect(blurStamp.hasVisiblePixels).toBe(true);
+
+ const sharpData = (sharpStamp.canvas as any).lastImageData as {
+ width: number;
+ height: number;
+ data: Uint8ClampedArray;
+ };
+ const blurData = (blurStamp.canvas as any).lastImageData as {
+ width: number;
+ height: number;
+ data: Uint8ClampedArray;
+ };
+
+ // Measure maximum horizontal step delta across the middle row (y = height / 2)
+ // and count intermediate mixed pixels (both R > 60 and B > 60)
+ const measureRow = (img: { width: number; height: number; data: Uint8ClampedArray }) => {
+ const midY = Math.floor(img.height / 2);
+ let maxDelta = 0;
+ let mixedPxCount = 0;
+ let sampleCount = 0;
+ for (let x = 4; x < img.width - 5; x++) {
+ const i0 = (midY * img.width + x) << 2;
+ const i1 = (midY * img.width + x + 1) << 2;
+ if (img.data[i0 + 3] < 20 || img.data[i1 + 3] < 20) continue;
+ sampleCount++;
+ const dr = Math.abs(img.data[i1] - img.data[i0]);
+ const db = Math.abs(img.data[i1 + 2] - img.data[i0 + 2]);
+ maxDelta = Math.max(maxDelta, dr + db);
+ if (img.data[i0] > 60 && img.data[i0 + 2] > 60) {
+ mixedPxCount++;
+ }
+ }
+ return { maxDelta, mixedPxCount, sampleCount };
+ };
+
+ const sharpMetrics = measureRow(sharpData);
+ const blurMetrics = measureRow(blurData);
+
+ // Ensure real visible pixels were sampled, and optical blur measurably softens the seam gradient
+ expect(sharpMetrics.sampleCount).toBeGreaterThan(10);
+ expect(blurMetrics.sampleCount).toBeGreaterThan(10);
+ expect(sharpMetrics.maxDelta).toBeGreaterThan(120);
+ expect(blurMetrics.maxDelta).toBeLessThan(sharpMetrics.maxDelta * 0.72);
+ expect(blurMetrics.mixedPxCount).toBeGreaterThan(sharpMetrics.mixedPxCount);
+ });
+
+ it('migrates schema v3 -> v4 cleanly, maps all legacy preset IDs, preserves Sketch/Natural Paint overrides, and retains built-in dual tips on reload', () => {
+ expect(BUILTIN_PRESET_SCHEMA_VERSION).toBe(4);
+
+ // Seed v3 localStorage with stale Pen/Brush/Blend overrides AND preserved Sketch/Natural Paint overrides
+ localStorage.setItem('ink_studio_brush_preset_schema_v', '3');
+ localStorage.setItem(
+ STORAGE_KEY_SETTINGS,
+ JSON.stringify({
+ 'g-pen': { size: 99 },
+ 'oil-painting': { size: 77 },
+ 'blend-brush': { size: 66 },
+ 'pencil-hb-2b': { size: 7.5 },
+ 'impasto-bristle-oil': { size: 62 },
+ })
);
- expect(firstContact.r).toBe(0);
- expect(firstContact.g).toBe(40);
- expect(firstContact.b).toBe(220);
- expect(firstContact.alpha).toBeGreaterThan(0.1);
+ localStorage.setItem(STORAGE_KEY_ACTIVE_PRESET, 'chalk-painting');
+ resetBrushSettingsCache();
+
+ const loaded = loadAllSavedBrushSettings();
+ expect(localStorage.getItem('ink_studio_brush_preset_schema_v')).toBe('4');
+ // Stale v3 upgraded/replaced IDs cleared
+ expect(loaded['g-pen']).toBeUndefined();
+ expect(loaded['oil-painting']).toBeUndefined();
+ expect(loaded['blend-brush']).toBeUndefined();
+ // Sketch & Natural Paint overrides strictly preserved
+ expect(loaded['pencil-hb-2b']?.size).toBe(7.5);
+ expect(loaded['impasto-bristle-oil']?.size).toBe(62);
+
+ // Active preset migrated cleanly from legacy ID
+ const active = getActivePresetId();
+ expect(active).toBe('concept-matte-chalk');
+ expect(localStorage.getItem(STORAGE_KEY_ACTIVE_PRESET)).toBe('concept-matte-chalk');
+
+ // Every legacy mapping resolves to a valid built-in brush
+ for (const [oldId, newId] of Object.entries(LEGACY_PRESET_ID_MAP)) {
+ expect(migrateLegacyPresetId(oldId)).toBe(newId);
+ expect(getBuiltinBrushConfig(newId)).not.toBeNull();
+ expect(getEffectiveBrushSettings(oldId).preset).toBe(newId);
+ }
+
+ // Saving a user tweak to Concept Matte Chalk (Dual Brush) must NOT wipe procedural dual tipImage on reload
+ const chalk = getEffectiveBrushSettings('concept-matte-chalk');
+ saveBrushSettingsImmediately('concept-matte-chalk', {
+ ...chalk,
+ size: 55,
+ dualBrushConfig: {
+ ...chalk.dualBrushConfig!,
+ size: 36,
+ },
+ });
+ resetBrushSettingsCache();
+ const reloadedChalk = getEffectiveBrushSettings('concept-matte-chalk');
+ expect(reloadedChalk.size).toBe(55);
+ expect(reloadedChalk.dualBrushConfig?.size).toBe(36);
+ expect(reloadedChalk.dualBrushConfig?.tipDataUrl).toMatch(/^data:image\/png;base64,/);
+ expect(reloadedChalk.dualBrushConfig?.tipImage).toBeDefined();
});
- it('resets dynamics, sensors, paper grain, tilt, and colorMixing cleanly when switching presets (zero state leakage)', () => {
+ it('resets ribbon, dual brush, compare-density, blur, sub-tips, dynamics, grain, and colorMixing cleanly when switching presets (zero state leakage)', () => {
+ const rough = getEffectiveBrushSettings('rough-pen');
+ expect(rough.isRibbon).toBe(true);
+ expect(rough.subTips?.length).toBeGreaterThan(0);
+ expect(rough.thicknessSensor?.useVelocity).toBe(true);
+
+ const chalk = getEffectiveBrushSettings('concept-matte-chalk');
+ expect(chalk.dualBrush).toBe(true);
+ expect(chalk.dualBrushConfig?.enabled).toBe(true);
+
+ const tex = getEffectiveBrushSettings('textured-pen');
+ expect(tex.brushCombineMode).toBe('compare-density');
+
+ const velvetBlend = getEffectiveBrushSettings('blend-velvet-soft');
+ expect(velvetBlend.useBlur).toBe(true);
+ expect(velvetBlend.blurStrength).toBeGreaterThan(0);
+ expect(velvetBlend.mixingMode).toBe('smear');
+
+ const scumble = getEffectiveBrushSettings('canvas-scumble-oil');
+ expect(scumble.dynamics?.colorJitterEnabled).toBe(true);
+
const charcoal = getEffectiveBrushSettings('charcoal-pencil');
expect(charcoal.dynamics?.scatter).toBeGreaterThan(0);
- expect(charcoal.useTilt).toBe(true);
expect(charcoal.grain).toBeGreaterThan(0.8);
+ // Switching to G-Pen resets every specialized feature cleanly (while keeping G-Pen's CSP tilt curve)
const gPen = getEffectiveBrushSettings('g-pen');
+ expect(gPen.isRibbon).toBe(false);
+ expect(gPen.dualBrush).toBe(false);
+ expect(gPen.dualBrushConfig).toBeUndefined();
+ expect(gPen.brushCombineMode).toBeUndefined();
+ expect(gPen.useBlur).toBe(false);
+ expect(gPen.blurStrength).toBeUndefined();
+ expect(gPen.thicknessSensor).toBeUndefined();
+ expect(gPen.subTips).toBeUndefined();
+ expect(gPen.subTipImages).toBeUndefined();
expect(gPen.dynamics).toBeUndefined();
- expect(gPen.useTilt).toBe(false);
expect(gPen.grain).toBe(0);
expect(gPen.colorMixing).toBe(false);
expect(gPen.opacitySensor).toBeUndefined();
expect(gPen.densitySensor).toBeUndefined();
expect(gPen.customTipImage).toBeUndefined();
expect(gPen.paperTextureImage).toBeUndefined();
+ expect(gPen.useTilt).toBe(true);
+
+ // Switching to Dot Pen also clears tilt completely
+ const dotPen = getEffectiveBrushSettings('dot-pen');
+ expect(dotPen.useTilt).toBe(false);
+ expect(dotPen.sizeSensor).toBeUndefined();
+ expect(dotPen.isRibbon).toBe(false);
+ expect(dotPen.dualBrush).toBe(false);
+ expect(dotPen.useBlur).toBe(false);
});
});
diff --git a/src/utils/__tests__/changelog.test.ts b/src/utils/__tests__/changelog.test.ts
index a7f596c..db5321d 100644
--- a/src/utils/__tests__/changelog.test.ts
+++ b/src/utils/__tests__/changelog.test.ts
@@ -8,12 +8,30 @@ import {
} from '../changelog';
describe('changelog parser', () => {
- it('parses bundled CHANGELOG.md including v1.0.3, v1.0.2, and v1.0.1 sections', () => {
+ it('parses bundled CHANGELOG.md including v1.0.4, v1.0.3, v1.0.2, and v1.0.1 sections', () => {
const entries = getChangelogEntries();
- expect(entries.length).toBeGreaterThanOrEqual(3);
+ expect(entries.length).toBeGreaterThanOrEqual(4);
const latest = getChangelogForVersion();
- expect(latest?.version).toBe('1.0.3');
+ expect(latest?.version).toBe('1.0.4');
+
+ const v104 = getChangelogForVersion('1.0.4');
+ expect(v104).toBeDefined();
+ expect(v104?.version).toBe('1.0.4');
+ expect(v104?.sections.map((s) => s.title)).toEqual([
+ 'New',
+ 'Improvements',
+ 'Bug Fixes',
+ ]);
+ expect(v104?.sections[0].items).toContain(
+ 'Added full Dual Brush support'
+ );
+ expect(v104?.sections[1].items).toContain(
+ 'Improved paper texture effects and brush color mixing to feel closer to Clip Studio Paint'
+ );
+ expect(v104?.sections[2].items).toContain(
+ 'Fixed ghost strokes briefly reappearing on the canvas when drawing right after pressing `Ctrl+Z`'
+ );
const v103 = getChangelogForVersion('1.0.3');
expect(v103).toBeDefined();
diff --git a/src/utils/__tests__/compositor.test.ts b/src/utils/__tests__/compositor.test.ts
index 512b079..1a5ed47 100644
--- a/src/utils/__tests__/compositor.test.ts
+++ b/src/utils/__tests__/compositor.test.ts
@@ -1550,6 +1550,136 @@ describe('Unified GPU Viewport Compositor', () => {
expect(t00.dirty).toBe(true);
expect(glSpecErrors).toEqual([]);
});
+
+ it('forces full texImage2D upload on first frame after stroke end / undo even with small __draftFrameDirtyRect (no ghost stroke in draftTexture)', () => {
+ const { canvas, calls, glSpecErrors } = createMockWebGL2Context();
+ const compositor = new ViewportCompositor(canvas);
+ const grid = new SparseTileGrid();
+ const dims = { width: 1024, height: 1024, dpi: 300 };
+
+ const layers: LayerItem[] = [
+ {
+ id: 'layer-1',
+ name: 'Sketch',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ },
+ ];
+
+ const mockDraftCanvas = {
+ width: 1024,
+ height: 1024,
+ __draftHasContent: true,
+ __draftVersion: 1,
+ __draftSpace: 'document',
+ __draftDocRect: { x: 0, y: 0, width: 1024, height: 1024 },
+ __draftFrameDirtyRect: null as { x: number; y: number; width: number; height: number } | null,
+ __draftForceFullUpload: true,
+ } as unknown as HTMLCanvasElement;
+
+ const transform: ViewportTransform = { pan: { x: 400, y: 300 }, zoom: 1.0, rotation: 0 };
+
+ // 1. Stroke 1 live render (populates state.draftTexture)
+ compositor.render(layers, transform, dims, grid, {
+ dimensions: dims,
+ devicePixelRatio: 1,
+ activeLayerId: 'layer-1',
+ activeDraftLayerId: 'layer-1',
+ activeDraftCanvas: mockDraftCanvas,
+ activeDraftVersion: 1,
+ activeDraftSpace: 'document',
+ activeDraftOpacity: 1.0,
+ });
+ expect((mockDraftCanvas as any).__draftForceFullUpload).toBe(false);
+
+ // 2. PointerUp + Ctrl+Z: draft becomes inactive (state.draftTexture still holds Stroke 1 on GPU)
+ (mockDraftCanvas as any).__draftHasContent = false;
+ (mockDraftCanvas as any).__draftVersion = 2;
+ compositor.render(layers, transform, dims, grid, {
+ dimensions: dims,
+ devicePixelRatio: 1,
+ activeLayerId: 'layer-1',
+ activeDraftLayerId: 'layer-1',
+ activeDraftCanvas: mockDraftCanvas,
+ activeDraftVersion: 2,
+ activeDraftSpace: 'document',
+ activeDraftOpacity: 1.0,
+ });
+
+ // 3. Stroke 2 starts with deferred pen initial dot -> first rendered frame ALREADY has a small __draftFrameDirtyRect!
+ // Must bypass partial texSubImage2D and perform a full texImage2D replacement so Stroke 1 cannot ghost.
+ calls.length = 0;
+ (mockDraftCanvas as any).__draftHasContent = true;
+ (mockDraftCanvas as any).__draftVersion = 3;
+ (mockDraftCanvas as any).__draftFrameDirtyRect = { x: 100, y: 100, width: 48, height: 48 };
+ compositor.render(layers, transform, dims, grid, {
+ dimensions: dims,
+ devicePixelRatio: 1,
+ activeLayerId: 'layer-1',
+ activeDraftLayerId: 'layer-1',
+ activeDraftCanvas: mockDraftCanvas,
+ activeDraftVersion: 3,
+ activeDraftSpace: 'document',
+ activeDraftOpacity: 1.0,
+ });
+
+ const fullUploadsOnStroke2Start = calls.filter(
+ (c) => c.name === 'texImage2D' && c.args[c.args.length - 1] === mockDraftCanvas
+ );
+ const subUploadsOnStroke2Start = calls.filter((c) => c.name === 'texSubImage2D');
+ expect(fullUploadsOnStroke2Start.length).toBe(1);
+ expect(subUploadsOnStroke2Start.length).toBe(0);
+ expect((mockDraftCanvas as any).__draftFrameDirtyRect).toBeNull();
+
+ // 4. Subsequent live frame within Stroke 2 uses fast texSubImage2D (zero texImage2D reallocation)
+ calls.length = 0;
+ (mockDraftCanvas as any).__draftVersion = 4;
+ (mockDraftCanvas as any).__draftFrameDirtyRect = { x: 120, y: 120, width: 32, height: 32 };
+ compositor.render(layers, transform, dims, grid, {
+ dimensions: dims,
+ devicePixelRatio: 1,
+ activeLayerId: 'layer-1',
+ activeDraftLayerId: 'layer-1',
+ activeDraftCanvas: mockDraftCanvas,
+ activeDraftVersion: 4,
+ activeDraftSpace: 'document',
+ activeDraftOpacity: 1.0,
+ });
+
+ expect(
+ calls.filter((c) => c.name === 'texImage2D' && c.args[c.args.length - 1] === mockDraftCanvas)
+ .length
+ ).toBe(0);
+ expect(calls.filter((c) => c.name === 'texSubImage2D').length).toBe(1);
+
+ // 5. Explicit __draftForceFullUpload flag forces full texImage2D even without an intermediate inactive frame
+ calls.length = 0;
+ (mockDraftCanvas as any).__draftVersion = 5;
+ (mockDraftCanvas as any).__draftForceFullUpload = true;
+ (mockDraftCanvas as any).__draftFrameDirtyRect = { x: 200, y: 200, width: 24, height: 24 };
+ compositor.render(layers, transform, dims, grid, {
+ dimensions: dims,
+ devicePixelRatio: 1,
+ activeLayerId: 'layer-1',
+ activeDraftLayerId: 'layer-1',
+ activeDraftCanvas: mockDraftCanvas,
+ activeDraftVersion: 5,
+ activeDraftSpace: 'document',
+ activeDraftOpacity: 1.0,
+ });
+
+ expect(
+ calls.filter((c) => c.name === 'texImage2D' && c.args[c.args.length - 1] === mockDraftCanvas)
+ .length
+ ).toBe(1);
+ expect(calls.filter((c) => c.name === 'texSubImage2D').length).toBe(0);
+ expect((mockDraftCanvas as any).__draftForceFullUpload).toBe(false);
+ expect(glSpecErrors).toEqual([]);
+ });
});
});
diff --git a/src/utils/__tests__/cspBrushEngineV2.test.ts b/src/utils/__tests__/cspBrushEngineV2.test.ts
index 2f3768e..8b7510b 100644
--- a/src/utils/__tests__/cspBrushEngineV2.test.ts
+++ b/src/utils/__tests__/cspBrushEngineV2.test.ts
@@ -168,7 +168,9 @@ describe('CSP Brush Engine V2 - Mathematics, Sensors & Post-Processing', () => {
expect(stepBrushSizePreset(0.5, -1)).toBe(0.5);
expect(stepBrushSizePreset(2000, 1)).toBe(2000);
expect(BUILTIN_BRUSHES.map((b) => b.id)).toContain('g-pen');
+ expect(BUILTIN_BRUSHES.map((b) => b.id)).toContain('rough-pen');
+ expect(BUILTIN_BRUSHES.map((b) => b.id)).toContain('blend-velvet-soft');
expect(BUILTIN_BRUSHES.map((b) => b.id)).toContain('impasto-bristle-oil');
- expect(BUILTIN_BRUSHES.length).toBe(26);
+ expect(BUILTIN_BRUSHES.length).toBe(35);
});
});
diff --git a/src/utils/__tests__/cspEngineRefactor.test.ts b/src/utils/__tests__/cspEngineRefactor.test.ts
index a2d3688..11c467f 100644
--- a/src/utils/__tests__/cspEngineRefactor.test.ts
+++ b/src/utils/__tests__/cspEngineRefactor.test.ts
@@ -29,9 +29,16 @@ describe('Clip Studio Paint Drawing Engine Refactor Tests', () => {
const cornerSample = stabilizer.process(30, 20, 0.5, t);
expect(cornerSample.isCorner).toBe(true);
- // Coordinates should snap sharply to raw corner coordinate rather than lagging behind
+ // Smoothly pulls toward the corner vertex without hard-teleporting across large lag
expect(cornerSample.x).toBeCloseTo(30, 0);
- expect(cornerSample.y).toBeCloseTo(20, 0);
+ expect(cornerSample.y).toBeGreaterThan(0);
+ expect(cornerSample.y).toBeLessThanOrEqual(20);
+ const plan = stabilizer.consumeCornerPlan();
+ expect(plan).not.toBeNull();
+ expect(plan!.apexX).toBeCloseTo(30, 0);
+ expect(plan!.apexY).toBeCloseTo(0, 0);
+ expect(plan!.targetX).toBeCloseTo(30, 0);
+ expect(plan!.targetY).toBeCloseTo(20, 0);
});
it('maintains continuous smoothing for gentle curves (< 45 deg deflection)', () => {
diff --git a/src/utils/__tests__/cspRenderingParity.test.ts b/src/utils/__tests__/cspRenderingParity.test.ts
new file mode 100644
index 0000000..bcf8e94
--- /dev/null
+++ b/src/utils/__tests__/cspRenderingParity.test.ts
@@ -0,0 +1,1422 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import {
+ applyCspPaperTextureAlpha,
+ applyCspWatercolorEdge,
+ applyStrokePaperTextureToImageData,
+ buildBrushRenderOptions,
+ centripetalCatmullRomToBezier,
+ drawBrushCubicBezierSegment,
+ drawBrushDot,
+ getTintedMasterCanvas,
+ normalizeWetEdgePower01,
+ renderCompleteStroke,
+ type BrushRenderOptions,
+} from '../../engine/BrushEngine';
+import {
+ paperTextureModeToIndex,
+ type GpuDab,
+} from '../../engine/WebGlBrushEngine';
+import {
+ LayerPixelSampler,
+ PaintReservoir,
+ SpatialTipMixer,
+ parseColorToRgb,
+} from '../colorMixingEngine';
+import { SparseTileGrid } from '../tileEngine';
+import { evaluateCpuBlendModeInto } from '../tileEngine/strokeComposite';
+import { commitRasterStrokeToTiles } from '../../hooks/drawing/brushStrokeSession/pointerUpRasterCommit';
+import { createInitialStrokeSessionState } from '../../hooks/drawing/brushStrokeSession/types';
+import {
+ BrushSettings,
+ CspBrushCombineMode,
+ CspPaperTextureMode,
+ DEFAULT_BRUSH_DYNAMICS,
+ Point,
+} from '../../types/editor';
+
+// ============================================================================
+// Pixel-exact software Canvas2D rasterizer for headless parity verification
+// ============================================================================
+
+function createSoftwareCanvas(initW: number, initH: number) {
+ let width = initW;
+ let height = initH;
+ let buf = new Uint8ClampedArray(width * height * 4);
+ type State = {
+ a: number;
+ b: number;
+ c: number;
+ d: number;
+ e: number;
+ f: number;
+ alpha: number;
+ op: string;
+ fillStyle: string;
+ };
+ const stack: State[] = [];
+ let st: State = {
+ a: 1,
+ b: 0,
+ c: 0,
+ d: 1,
+ e: 0,
+ f: 0,
+ alpha: 1,
+ op: 'source-over',
+ fillStyle: '#000000',
+ };
+
+ const ctx: any = {
+ get canvas() {
+ return surfaceObj;
+ },
+ get globalAlpha() {
+ return st.alpha;
+ },
+ set globalAlpha(v: number) {
+ st.alpha = v;
+ },
+ get globalCompositeOperation() {
+ return st.op;
+ },
+ set globalCompositeOperation(v: string) {
+ st.op = v;
+ },
+ get fillStyle() {
+ return st.fillStyle;
+ },
+ set fillStyle(v: string) {
+ st.fillStyle = v;
+ },
+ imageSmoothingEnabled: true,
+ save: () => stack.push({ ...st }),
+ restore: () => {
+ const p = stack.pop();
+ if (p) st = p;
+ },
+ getTransform: () => ({ a: st.a, b: st.b, c: st.c, d: st.d, e: st.e, f: st.f }),
+ setTransform: (a: number, b: number, c: number, d: number, e: number, f: number) => {
+ st.a = a;
+ st.b = b;
+ st.c = c;
+ st.d = d;
+ st.e = e;
+ st.f = f;
+ },
+ resetTransform: () => {
+ st.a = 1;
+ st.b = 0;
+ st.c = 0;
+ st.d = 1;
+ st.e = 0;
+ st.f = 0;
+ },
+ translate: (x: number, y: number) => {
+ st.e += st.a * x + st.c * y;
+ st.f += st.b * x + st.d * y;
+ },
+ rotate: (rad: number) => {
+ const cos = Math.cos(rad);
+ const sin = Math.sin(rad);
+ const na = st.a * cos + st.c * sin;
+ const nb = st.b * cos + st.d * sin;
+ const nc = -st.a * sin + st.c * cos;
+ const nd = -st.b * sin + st.d * cos;
+ st.a = na;
+ st.b = nb;
+ st.c = nc;
+ st.d = nd;
+ },
+ scale: (sx: number, sy: number) => {
+ st.a *= sx;
+ st.b *= sx;
+ st.c *= sy;
+ st.d *= sy;
+ },
+ beginPath: () => {},
+ rect: () => {},
+ clip: () => {},
+ clearRect: (x = 0, y = 0, w = width, h = height) => {
+ const x0 = Math.max(0, Math.floor(x));
+ const y0 = Math.max(0, Math.floor(y));
+ const x1 = Math.min(width, Math.ceil(x + w));
+ const y1 = Math.min(height, Math.ceil(y + h));
+ for (let py = y0; py < y1; py++) {
+ buf.fill(0, (py * width + x0) * 4, (py * width + x1) * 4);
+ }
+ },
+ fillRect: (x: number, y: number, w: number, h: number) => {
+ const rgb = parseColorToRgb(st.fillStyle);
+ const x0 = Math.max(0, Math.floor(x));
+ const y0 = Math.max(0, Math.floor(y));
+ const x1 = Math.min(width, Math.ceil(x + w));
+ const y1 = Math.min(height, Math.ceil(y + h));
+ for (let py = y0; py < y1; py++) {
+ for (let px = x0; px < x1; px++) {
+ const i = (py * width + px) * 4;
+ if (st.op === 'source-in') {
+ if (buf[i + 3] > 0) {
+ buf[i] = rgb.r;
+ buf[i + 1] = rgb.g;
+ buf[i + 2] = rgb.b;
+ }
+ } else {
+ buf[i] = rgb.r;
+ buf[i + 1] = rgb.g;
+ buf[i + 2] = rgb.b;
+ buf[i + 3] = Math.round(st.alpha * 255);
+ }
+ }
+ }
+ },
+ createImageData: (w: number, h: number) => ({
+ width: w,
+ height: h,
+ data: new Uint8ClampedArray(w * h * 4),
+ }),
+ putImageData: (
+ img: { width: number; height: number; data: Uint8ClampedArray },
+ dx = 0,
+ dy = 0
+ ) => {
+ for (let y = 0; y < img.height; y++) {
+ const ty = dy + y;
+ if (ty < 0 || ty >= height) continue;
+ for (let x = 0; x < img.width; x++) {
+ const tx = dx + x;
+ if (tx < 0 || tx >= width) continue;
+ const si = (y * img.width + x) * 4;
+ const di = (ty * width + tx) * 4;
+ buf[di] = img.data[si];
+ buf[di + 1] = img.data[si + 1];
+ buf[di + 2] = img.data[si + 2];
+ buf[di + 3] = img.data[si + 3];
+ }
+ }
+ },
+ getImageData: (sx: number, sy: number, sw: number, sh: number) => {
+ const data = new Uint8ClampedArray(sw * sh * 4);
+ for (let y = 0; y < sh; y++) {
+ const py = sy + y;
+ if (py < 0 || py >= height) continue;
+ for (let x = 0; x < sw; x++) {
+ const px = sx + x;
+ if (px < 0 || px >= width) continue;
+ const si = (py * width + px) * 4;
+ const di = (y * sw + x) * 4;
+ data[di] = buf[si];
+ data[di + 1] = buf[si + 1];
+ data[di + 2] = buf[si + 2];
+ data[di + 3] = buf[si + 3];
+ }
+ }
+ return { width: sw, height: sh, data };
+ },
+ drawImage: (
+ src: any,
+ a1: number,
+ a2: number,
+ a3?: number,
+ a4?: number,
+ a5?: number,
+ a6?: number,
+ a7?: number,
+ a8?: number
+ ) => {
+ const srcBuf: Uint8ClampedArray | undefined = src?.buf;
+ if (!srcBuf) return;
+ const fullSw = src.width;
+ const fullSh = src.height;
+
+ let sx = 0,
+ sy = 0,
+ sw = fullSw,
+ sh = fullSh,
+ dx = a1,
+ dy = a2,
+ dw = a3 ?? fullSw,
+ dh = a4 ?? fullSh;
+ if (a8 !== undefined && a7 !== undefined && a6 !== undefined && a5 !== undefined) {
+ sx = a1;
+ sy = a2;
+ sw = a3!;
+ sh = a4!;
+ dx = a5;
+ dy = a6;
+ dw = a7;
+ dh = a8;
+ }
+ if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0) return;
+
+ const det = st.a * st.d - st.b * st.c;
+ if (Math.abs(det) < 1e-8) return;
+ const invDet = 1 / det;
+
+ const corners = [
+ [dx, dy],
+ [dx + dw, dy],
+ [dx, dy + dh],
+ [dx + dw, dy + dh],
+ ];
+ let minX = width,
+ minY = height,
+ maxX = -1,
+ maxY = -1;
+ for (const [lx, ly] of corners) {
+ const wx = st.a * lx + st.c * ly + st.e;
+ const wy = st.b * lx + st.d * ly + st.f;
+ if (wx < minX) minX = wx;
+ if (wy < minY) minY = wy;
+ if (wx > maxX) maxX = wx;
+ if (wy > maxY) maxY = wy;
+ }
+ const ix0 = Math.max(0, Math.floor(minX));
+ const iy0 = Math.max(0, Math.floor(minY));
+ const ix1 = Math.min(width - 1, Math.ceil(maxX));
+ const iy1 = Math.min(height - 1, Math.ceil(maxY));
+
+ for (let py = iy0; py <= iy1; py++) {
+ for (let px = ix0; px <= ix1; px++) {
+ const rx = px + 0.5 - st.e;
+ const ry = py + 0.5 - st.f;
+ const lx = (st.d * rx - st.c * ry) * invDet;
+ const ly = (-st.b * rx + st.a * ry) * invDet;
+ const u = (lx - dx) / dw;
+ const v = (ly - dy) / dh;
+ if (u < 0 || u > 1 || v < 0 || v > 1) continue;
+
+ const fx = sx + u * sw - 0.5;
+ const fy = sy + v * sh - 0.5;
+ const x0 = Math.max(0, Math.min(fullSw - 1, Math.floor(fx)));
+ const y0 = Math.max(0, Math.min(fullSh - 1, Math.floor(fy)));
+ const x1 = Math.min(fullSw - 1, x0 + 1);
+ const y1 = Math.min(fullSh - 1, y0 + 1);
+ const tx = Math.max(0, Math.min(1, fx - x0));
+ const ty = Math.max(0, Math.min(1, fy - y0));
+
+ const i00 = (y0 * fullSw + x0) * 4;
+ const i10 = (y0 * fullSw + x1) * 4;
+ const i01 = (y1 * fullSw + x0) * 4;
+ const i11 = (y1 * fullSw + x1) * 4;
+
+ const w00 = (1 - tx) * (1 - ty);
+ const w10 = tx * (1 - ty);
+ const w01 = (1 - tx) * ty;
+ const w11 = tx * ty;
+
+ const sa00 = srcBuf[i00 + 3] / 255;
+ const sa10 = srcBuf[i10 + 3] / 255;
+ const sa01 = srcBuf[i01 + 3] / 255;
+ const sa11 = srcBuf[i11 + 3] / 255;
+ const aInterp = sa00 * w00 + sa10 * w10 + sa01 * w01 + sa11 * w11;
+ const sa = aInterp * st.alpha;
+ if (sa <= 0.001) continue;
+
+ const premulR =
+ srcBuf[i00] * sa00 * w00 +
+ srcBuf[i10] * sa10 * w10 +
+ srcBuf[i01] * sa01 * w01 +
+ srcBuf[i11] * sa11 * w11;
+ const premulG =
+ srcBuf[i00 + 1] * sa00 * w00 +
+ srcBuf[i10 + 1] * sa10 * w10 +
+ srcBuf[i01 + 1] * sa01 * w01 +
+ srcBuf[i11 + 1] * sa11 * w11;
+ const premulB =
+ srcBuf[i00 + 2] * sa00 * w00 +
+ srcBuf[i10 + 2] * sa10 * w10 +
+ srcBuf[i01 + 2] * sa01 * w01 +
+ srcBuf[i11 + 2] * sa11 * w11;
+ const invA = aInterp > 1e-5 ? 1 / aInterp : 0;
+ const sr = premulR * invA;
+ const sg = premulG * invA;
+ const sb = premulB * invA;
+
+ const di = (py * width + px) * 4;
+ const da = buf[di + 3] / 255;
+ if (st.op === 'destination-out') {
+ const outA = da * (1 - sa);
+ buf[di + 3] = Math.round(outA * 255);
+ } else if (st.op === 'destination-over') {
+ const outA = da + sa * (1 - da);
+ if (outA > 0) {
+ const inv = 1 / outA;
+ buf[di] = Math.round((buf[di] * da + sr * sa * (1 - da)) * inv);
+ buf[di + 1] = Math.round((buf[di + 1] * da + sg * sa * (1 - da)) * inv);
+ buf[di + 2] = Math.round((buf[di + 2] * da + sb * sa * (1 - da)) * inv);
+ buf[di + 3] = Math.round(outA * 255);
+ }
+ } else {
+ const outA = sa + da * (1 - sa);
+ if (outA > 0) {
+ const inv = 1 / outA;
+ buf[di] = Math.round((sr * sa + buf[di] * da * (1 - sa)) * inv);
+ buf[di + 1] = Math.round((sg * sa + buf[di + 1] * da * (1 - sa)) * inv);
+ buf[di + 2] = Math.round((sb * sa + buf[di + 2] * da * (1 - sa)) * inv);
+ buf[di + 3] = Math.round(outA * 255);
+ }
+ }
+ }
+ }
+ },
+ };
+
+ const surfaceObj: any = {
+ get width() {
+ return width;
+ },
+ set width(v: number) {
+ width = Math.max(1, v | 0);
+ buf = new Uint8ClampedArray(width * height * 4);
+ },
+ get height() {
+ return height;
+ },
+ set height(v: number) {
+ height = Math.max(1, v | 0);
+ buf = new Uint8ClampedArray(width * height * 4);
+ },
+ get naturalWidth() {
+ return width;
+ },
+ get naturalHeight() {
+ return height;
+ },
+ complete: true,
+ get buf() {
+ return buf;
+ },
+ getContext: () => ctx,
+ };
+
+ return surfaceObj;
+}
+
+/**
+ * Exact reference mirror of `WebGlBrushEngine.ts` `FRAGMENT_SHADER_SRC` paper texture math
+ * for verifying WebGL vs CPU parity within <= 3/255 across all 9 modes.
+ */
+function simulateWebGlFragmentPaperAlpha(
+ tipAlpha: number,
+ vAlpha: number,
+ gRaw: number,
+ paperGrain: number,
+ pressure: number,
+ mode: CspPaperTextureMode,
+ brightness: number,
+ contrast: number,
+ invert: boolean,
+ preserveDensity: boolean,
+ emphasizeDensity: boolean
+): number {
+ let g = gRaw;
+ if (invert) g = 1.0 - g;
+ if (emphasizeDensity) g = Math.max(0, Math.min(1, (g - 0.5) * 2.2 + 0.35));
+ const brightNorm = brightness / 100.0;
+ const contrastNorm = contrast / 100.0;
+ if (Math.abs(brightNorm) > 0.001) g += brightNorm;
+ if (Math.abs(contrastNorm) > 0.001) {
+ const cf = Math.pow(Math.max(0.05, 1.0 + contrastNorm), 2.0);
+ g = (g - 0.5) * cf + 0.5;
+ }
+ g = Math.max(0, Math.min(1, g));
+
+ let modTip = Math.max(0, Math.min(1, tipAlpha));
+ 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 = preserveDensity ? paperGrain : paperGrain * (1.0 - penetration * 0.85);
+ const modeIdx = paperTextureModeToIndex(mode);
+
+ const smoothstep = (e0: number, e1: number, x: number) => {
+ const t = Math.max(0, Math.min(1, (x - e0) / (e1 - e0)));
+ return t * t * (3.0 - 2.0 * t);
+ };
+
+ if (modeIdx === 1) {
+ modTip *= 1.0 - effDensity * (1.0 - g);
+ } else if (modeIdx === 2) {
+ const contactHeight = g * (0.22 + 0.78 * modTip);
+ const cutoff = effDensity * 0.68;
+ modTip *= smoothstep(cutoff - 0.05, cutoff + 0.16, contactHeight);
+ } else if (modeIdx === 3) {
+ const dMod = modTip * (1.0 - effDensity * 0.32 * (1.0 - g));
+ const ov = dMod < 0.5 ? 2.0 * dMod * g : 1.0 - 2.0 * (1.0 - dMod) * (1.0 - g);
+ modTip = Math.max(0, Math.min(1, modTip + (ov - modTip) * effDensity));
+ } else if (modeIdx === 4) {
+ const edgeFactor = 4.0 * modTip * (1.0 - modTip);
+ modTip *= 1.0 - effDensity * (1.0 - g) * (0.35 + 0.65 * edgeFactor);
+ } else if (modeIdx === 5) {
+ const sil = Math.min(1.0, modTip * 4.0);
+ modTip = Math.max(0, Math.min(1, modTip * (1.0 - effDensity) + g * sil * effDensity));
+ } else if (modeIdx === 6) {
+ const burned = g <= 0.001 ? 0.0 : Math.max(0.0, 1.0 - (1.0 - modTip) / g);
+ modTip = Math.max(0, Math.min(1, modTip + (burned - modTip) * effDensity));
+ } else if (modeIdx === 7) {
+ const burned = Math.max(0.0, modTip + g - 1.0);
+ modTip = Math.max(0, Math.min(1, modTip + (burned - modTip) * effDensity));
+ } else if (modeIdx === 8) {
+ const sil = Math.min(1.0, modTip * 4.0);
+ const relief = Math.max(0, Math.min(1, (modTip + g - 0.5) * 1.6)) * sil;
+ modTip = Math.max(0, Math.min(1, modTip * (1.0 - effDensity) + relief * effDensity));
+ } else {
+ const sub = (1.0 - g) * effDensity * (preserveDensity ? 1.0 : 1.0 - penetration * 0.5);
+ modTip = Math.max(0.0, modTip - sub);
+ }
+
+ if (modTip <= 0.002) return 0;
+ return Math.max(0, Math.min(1, modTip * vAlpha));
+}
+
+describe('CSP Rendering Math Parity (GPU / CPU / SpatialTipMixer / Tile Commit)', () => {
+ const origDocument = (globalThis as any).document;
+
+ beforeEach(() => {
+ (globalThis as any).document = {
+ createElement: () => createSoftwareCanvas(64, 64),
+ };
+ });
+
+ afterEach(() => {
+ (globalThis as any).document = origDocument;
+ });
+
+ // ==========================================================================
+ // 1. All 9 CSP TextureCompositeMode modes: WebGL vs CPU vs SpatialTipMixer
+ // ==========================================================================
+
+ it('matches WebGL vs CPU paper texture alpha within <= 3/255 across all 9 CSP TextureCompositeMode modes', () => {
+ const allModes: CspPaperTextureMode[] = [
+ 'normal',
+ 'multiply',
+ 'subtract',
+ 'compare',
+ 'overlay',
+ 'color-burn',
+ 'linear-burn',
+ 'height',
+ 'outline',
+ ];
+
+ // Verify every mode has a unique WebGL uniform index (0..8)
+ const indices = new Set(allModes.map((m) => paperTextureModeToIndex(m)));
+ expect(indices.size).toBe(9);
+
+ // Deterministic gradient paper texture (32x32)
+ const paperImg = createSoftwareCanvas(32, 32);
+ for (let y = 0; y < 32; y++) {
+ for (let x = 0; x < 32; x++) {
+ const i = (y * 32 + x) * 4;
+ const lum = Math.round(((x * 7 + y * 5) % 32) * (255 / 31));
+ paperImg.buf[i] = lum;
+ paperImg.buf[i + 1] = lum;
+ paperImg.buf[i + 2] = lum;
+ paperImg.buf[i + 3] = 255;
+ }
+ }
+
+ // Solid 16x16 square brush tip at alpha = 0.72 so non-linear modes & normal vs multiply are exercised
+ const solidTip = createSoftwareCanvas(16, 16);
+ for (let i = 0; i < solidTip.buf.length; i += 4) {
+ solidTip.buf[i] = 255;
+ solidTip.buf[i + 1] = 255;
+ solidTip.buf[i + 2] = 255;
+ solidTip.buf[i + 3] = 255;
+ }
+
+ for (const mode of allModes) {
+ // 1A. Analytical parity across alpha/grain/pressure/brightness/contrast/invert/emphasize sweeps
+ for (const tipA of [0.2, 0.55, 0.85, 1.0]) {
+ for (const g of [0.1, 0.45, 0.85]) {
+ const modTip = applyCspPaperTextureAlpha(tipA, g, 0.75, 0.4, mode, 10, 15, false, true, true);
+ const cpuA = modTip <= 0.002 ? 0 : modTip * 0.8;
+ const gpuA = simulateWebGlFragmentPaperAlpha(tipA, 0.8, g, 0.75, 0.4, mode, 10, 15, false, true, true);
+ expect(Math.abs(cpuA - gpuA) * 255).toBeLessThanOrEqual(1);
+ }
+ }
+
+ // 1B. Per-dab CPU pixel rasterization (`applyCpuPerPixelPaperGrain`) vs WebGL fragment shader
+ const cpuSurf = createSoftwareCanvas(48, 48);
+ const cpuCtx = cpuSurf.getContext('2d');
+ drawBrushDot(
+ cpuCtx,
+ { x: 24, y: 24, pressure: 0.45, width: 16 },
+ '#cc4422',
+ {
+ size: 16,
+ flow: 0.75,
+ hardness: 1.0,
+ tipImage: solidTip,
+ grain: 0.72,
+ textureDensity: 0.72,
+ paperTextureMode: mode,
+ paperTextureImage: paperImg,
+ paperTextureScale: 1.0,
+ paperTextureRotate: 0,
+ paperTextureBrightness: 5,
+ paperTextureContrast: 10,
+ paperTextureInverted: false,
+ paperTextureEmphasizeDensity: true,
+ paperTextureApplyEachPlot: true,
+ useGpu: false,
+ }
+ );
+
+ let maxDiffBytes = 0;
+ for (let py = 17; py <= 30; py++) {
+ for (let px = 17; px <= 30; px++) {
+ const cpuAlphaByte = cpuSurf.buf[(py * 48 + px) * 4 + 3];
+ const paperLum = paperImg.buf[((py & 31) * 32 + (px & 31)) * 4] / 255;
+ const gpuAlpha = simulateWebGlFragmentPaperAlpha(
+ 1.0,
+ 0.75,
+ paperLum,
+ 0.72,
+ 0.45,
+ mode,
+ 5,
+ 10,
+ false,
+ true,
+ true
+ );
+ const gpuAlphaByte = Math.round(gpuAlpha * 255);
+ const diff = Math.abs(cpuAlphaByte - gpuAlphaByte);
+ if (diff > maxDiffBytes) maxDiffBytes = diff;
+ }
+ }
+ expect(maxDiffBytes).toBeLessThanOrEqual(3);
+ }
+
+ // 1B-2. Light-pressure low-flow Subtract paper texture MUST modulate tipAlpha BEFORE v_alpha/dabAlpha
+ // so light-pressure textured strokes (e.g. Oil Pastel at p=0.25 -> flow=0.06, grain=0.52, lum=60/255)
+ // stay visible instead of collapsing to 0 when (1 - g) * grain > flow!
+ const darkPaper = createSoftwareCanvas(16, 16);
+ for (let i = 0; i < darkPaper.buf.length; i += 4) {
+ darkPaper.buf[i] = 60;
+ darkPaper.buf[i + 1] = 60;
+ darkPaper.buf[i + 2] = 60;
+ darkPaper.buf[i + 3] = 255;
+ }
+ const lowFlowSurf = createSoftwareCanvas(32, 32);
+ drawBrushDot(
+ lowFlowSurf.getContext('2d'),
+ { x: 16, y: 16, pressure: 0.25, width: 14 },
+ '#ff2000',
+ {
+ size: 14,
+ flow: 0.08,
+ hardness: 1.0,
+ tipImage: solidTip,
+ grain: 0.52,
+ textureDensity: 0.52,
+ paperTextureMode: 'subtract',
+ paperTextureImage: darkPaper,
+ paperTextureScale: 1.0,
+ paperTextureApplyEachPlot: true,
+ useGpu: false,
+ }
+ );
+ const lowFlowCpuA = lowFlowSurf.buf[(16 * 32 + 16) * 4 + 3];
+ const lowFlowGpuA = Math.round(
+ simulateWebGlFragmentPaperAlpha(1.0, 0.08, 60 / 255, 0.52, 0.25, 'subtract', 0, 0, false, true, false) * 255
+ );
+ expect(lowFlowCpuA).toBeGreaterThanOrEqual(10);
+ expect(Math.abs(lowFlowCpuA - lowFlowGpuA)).toBeLessThanOrEqual(2);
+
+ // 1C. Verify `applyCpuPerPixelPaperGrain` responds to rotation, invert, brightness, contrast, emphasizeDensity
+ const renderDotWith = (overrides: Partial<BrushRenderOptions>) => {
+ const s = createSoftwareCanvas(48, 48);
+ drawBrushDot(
+ s.getContext('2d'),
+ { x: 24, y: 24, pressure: 0.5, width: 20 },
+ '#3366aa',
+ {
+ size: 20,
+ flow: 0.85,
+ tipImage: solidTip,
+ grain: 0.8,
+ paperTextureMode: 'multiply',
+ paperTextureImage: paperImg,
+ paperTextureApplyEachPlot: true,
+ useGpu: false,
+ ...overrides,
+ }
+ );
+ return Array.from(s.buf);
+ };
+ const baseBytes = renderDotWith({});
+ expect(renderDotWith({ paperTextureRotate: 45 })).not.toEqual(baseBytes);
+ expect(renderDotWith({ paperTextureInverted: true })).not.toEqual(baseBytes);
+ expect(renderDotWith({ paperTextureBrightness: 35 })).not.toEqual(baseBytes);
+ expect(renderDotWith({ paperTextureContrast: 45 })).not.toEqual(baseBytes);
+ expect(renderDotWith({ paperTextureEmphasizeDensity: true })).not.toEqual(baseBytes);
+
+ // 1C-2. Verify per-stroke `applyStrokePaperTextureToImageData` matches WebGL within <= 3/255 across all 9 modes
+ for (const mode of allModes) {
+ const strokeBuf = new Uint8ClampedArray(16 * 16 * 4);
+ for (let i = 0; i < 16 * 16; i++) {
+ strokeBuf[i * 4] = 180;
+ strokeBuf[i * 4 + 1] = 80;
+ strokeBuf[i * 4 + 2] = 60;
+ strokeBuf[i * 4 + 3] = 204; // 0.8
+ }
+ applyStrokePaperTextureToImageData(
+ { data: strokeBuf, width: 16, height: 16 },
+ 4,
+ 6,
+ {
+ grain: 0.7,
+ paperTextureMode: mode,
+ paperTextureImage: paperImg,
+ paperTextureScale: 1.0,
+ paperTextureRotate: 0,
+ },
+ 1.0
+ );
+ for (let y = 0; y < 16; y++) {
+ for (let x = 0; x < 16; x++) {
+ const gotA = strokeBuf[(y * 16 + x) * 4 + 3];
+ const pLum = paperImg.buf[(((y + 6) & 31) * 32 + ((x + 4) & 31)) * 4] / 255;
+ const expA = Math.round(
+ simulateWebGlFragmentPaperAlpha(204 / 255, 1.0, pLum, 0.7, 0.5, mode, 0, 0, false, true, false) * 255
+ );
+ expect(Math.abs(gotA - expA)).toBeLessThanOrEqual(3);
+ }
+ }
+ }
+
+ // 1D. Verify SpatialTipMixer executes all 9 modes cleanly with distinct modulation
+ const paperLum = new Uint8Array(32 * 32);
+ for (let i = 0; i < 32 * 32; i++) paperLum[i] = paperImg.buf[i * 4];
+
+ const modeSums = new Map<CspPaperTextureMode, number>();
+ for (const mode of allModes) {
+ const mixer = new SpatialTipMixer('#3355cc');
+ const built = mixer.stepAndBuildStamp({
+ x: 24,
+ y: 24,
+ width: 16,
+ height: 16,
+ angleRad: 0,
+ dirX: 1,
+ dirY: 0,
+ stepDist: 4,
+ hardness: 1.0,
+ antiAlias: 2,
+ flipX: 1,
+ flipY: 1,
+ flow: 0.75,
+ pressure: 0.5,
+ pressureAlreadyApplied: true,
+ amountOfPaint: 1.0,
+ densityOfPaint: 0.75,
+ colorStretch: 0.5,
+ mixingMode: 'blend',
+ perceptualMixing: true,
+ tipImage: solidTip,
+ grainDensity: 0.78,
+ paperTextureMode: mode,
+ paperLumData: paperLum,
+ paperLumWidth: 32,
+ paperLumHeight: 32,
+ paperTextureScale: 1.0,
+ paperTextureRotate: 0,
+ paperTexturePreserveDensity: true,
+ });
+ expect(built).not.toBeNull();
+ expect(built!.hasVisiblePixels).toBe(true);
+ const data = (built!.canvas as any).buf as Uint8ClampedArray;
+ let alphaSum = 0;
+ for (let i = 3; i < data.length; i += 4) alphaSum += data[i];
+ expect(alphaSum).toBeGreaterThan(0);
+ modeSums.set(mode, alphaSum);
+ }
+ // Compare/color-burn/linear-burn/overlay/subtract/multiply should not collapse to identical values
+ expect(modeSums.get('compare')).not.toBe(modeSums.get('multiply'));
+ expect(modeSums.get('color-burn')).not.toBe(modeSums.get('multiply'));
+ expect(modeSums.get('outline')).not.toBe(modeSums.get('subtract'));
+ });
+
+ // ==========================================================================
+ // 2. Watercolor Edge scale fix & enabled with colorMixing
+ // ==========================================================================
+
+ it('normalizes Watercolor Edge 0..100 vs 0..1 cleanly, prevents black-fringe halos, and applies with colorMixing', () => {
+ expect(normalizeWetEdgePower01(0.25)).toBeCloseTo(0.25, 5);
+ expect(normalizeWetEdgePower01(25)).toBeCloseTo(0.25, 5);
+ expect(normalizeWetEdgePower01(15)).toBeCloseTo(0.15, 5);
+ expect(normalizeWetEdgePower01(100)).toBeCloseTo(1.0, 5);
+ expect(normalizeWetEdgePower01(0)).toBe(0);
+
+ // Direct applyCspWatercolorEdge: (25, 15) must equal (0.25, 0.15) and never blow out to black
+ const makeWash = () => {
+ const w = 28,
+ h = 28;
+ const data = new Uint8ClampedArray(w * h * 4);
+ for (let y = 6; y < 22; y++) {
+ for (let x = 6; x < 22; x++) {
+ const i = (y * w + x) * 4;
+ data[i] = 220;
+ data[i + 1] = 110;
+ data[i + 2] = 80;
+ data[i + 3] = 150;
+ }
+ }
+ return { data, width: w, height: h };
+ };
+ const img01 = makeWash();
+ const img100 = makeWash();
+ applyCspWatercolorEdge(img01, 0.75, 3, 0.25, 0.15);
+ applyCspWatercolorEdge(img100, 0.75, 3, 25, 15);
+ expect(Array.from(img100.data)).toEqual(Array.from(img01.data));
+
+ // Rim darkens smoothly (not blown out to near-zero black) and concentrates alpha
+ const rimOff = (6 * 28 + 14) * 4;
+ const centerOff = (14 * 28 + 14) * 4;
+ const transparentOff = (1 * 28 + 1) * 4;
+ expect(img01.data[rimOff]).toBeLessThan(220);
+ expect(img01.data[rimOff]).toBeGreaterThan(100);
+ expect(img01.data[rimOff + 3]).toBeGreaterThan(150);
+ expect(img01.data[centerOff]).toBe(220);
+ expect(img01.data[centerOff + 3]).toBe(150);
+ // Transparent pixels outside stroke have zero black-fringe halo
+ expect(img01.data[transparentOff]).toBe(0);
+ expect(img01.data[transparentOff + 1]).toBe(0);
+ expect(img01.data[transparentOff + 2]).toBe(0);
+ expect(img01.data[transparentOff + 3]).toBe(0);
+
+ // renderCompleteStroke MUST apply watercolor edge even when colorMixing === true
+ const pts: Point[] = [
+ { x: 24, y: 32, pressure: 0.65, width: 22 },
+ { x: 56, y: 32, pressure: 0.65, width: 22 },
+ { x: 88, y: 32, pressure: 0.65, width: 22 },
+ ];
+ const baseMixBs: BrushSettings = {
+ size: 22,
+ minSizeFactor: 0.2,
+ color: '#d87050',
+ opacity: 1.0,
+ flow: 0.65,
+ spacing: 0.1,
+ usePressure: true,
+ smoothing: false,
+ stabilization: 0,
+ hardness: 0.85,
+ colorMixing: true,
+ amountOfPaint: 0.85,
+ densityOfPaint: 0.55,
+ colorStretch: 0.4,
+ useGpu: false,
+ };
+
+ const surfNoWet = createSoftwareCanvas(120, 64);
+ renderCompleteStroke(surfNoWet.getContext('2d'), pts, { ...baseMixBs, wetEdge: 0 }, 'brush', 'color');
+
+ const surfWithWet = createSoftwareCanvas(120, 64);
+ renderCompleteStroke(
+ surfWithWet.getContext('2d'),
+ pts,
+ { ...baseMixBs, wetEdge: 0.85, wetEdgeRadius: 3, wetEdgeAlphaPower: 35, wetEdgeValuePower: 30 },
+ 'brush',
+ 'color'
+ );
+
+ // Find rim pixels where watercolor edge darkened and concentrated alpha relative to no-wetEdge
+ let darkenedRimPixels = 0;
+ let boostedAlphaRimPixels = 0;
+ for (let i = 0; i < surfNoWet.buf.length; i += 4) {
+ if (surfNoWet.buf[i + 3] > 30) {
+ if (surfWithWet.buf[i] < surfNoWet.buf[i] - 5) darkenedRimPixels++;
+ if (surfWithWet.buf[i + 3] > surfNoWet.buf[i + 3] + 5) boostedAlphaRimPixels++;
+ }
+ }
+ expect(darkenedRimPixels).toBeGreaterThan(20);
+ expect(boostedAlphaRimPixels).toBeGreaterThan(20);
+
+ // pointerUpRasterCommit with colorMixing === true + wetEdge + legacy 0..100 powers
+ const gridNoWet = new SparseTileGrid();
+ const gridWithWet = new SparseTileGrid();
+ const runCommit = (grid: SparseTileGrid, wetEdge: number) => {
+ const state = createInitialStrokeSessionState();
+ commitRasterStrokeToTiles({
+ state,
+ helpers: {
+ markTouchedTiles: () => {},
+ resolveLiveAntiAlias: () => 2,
+ buildLiveBrushOptions: () => ({}),
+ emitLiveSegment: () => {},
+ buildTouchedTileSpans: (x, y, w, h) => [{ x, y, width: w, height: h }],
+ resolveEffectiveOpacitySensor: () => undefined,
+ },
+ grid,
+ draftCanvas: null,
+ dirtyRect: { x: 0, y: 0, width: 120, height: 64 },
+ dims: { width: 120, height: 64 },
+ bs: {
+ ...baseMixBs,
+ wetEdge,
+ wetEdgeRadius: 3,
+ wetEdgeAlphaPower: 35,
+ wetEdgeValuePower: 30,
+ },
+ currentTool: 'brush',
+ currentLayerId: 'layer-wc',
+ activeLayer: undefined,
+ activeSelection: null,
+ effectiveMode: 'color',
+ targetFormat: 'color-32bit',
+ isEraser: false,
+ isBgEraser: false,
+ isMonochrome: false,
+ hasWetEdge: wetEdge > 0.01,
+ shouldTaper: false,
+ strokeColor: '#d87050',
+ allPoints: pts,
+ tailSegments: [],
+ toolForHistory: 'brush',
+ label: 'Watercolor',
+ strokeIdForHistory: undefined,
+ enqueueHistoryTask: () => {},
+ pushHistoryStep: () => {},
+ });
+ };
+
+ runCommit(gridNoWet, 0);
+ runCommit(gridWithWet, 0.85);
+ const readNoWet = gridNoWet.readImageData('layer-wc', 0, 0, 120, 64).data;
+ const readWithWet = gridWithWet.readImageData('layer-wc', 0, 0, 120, 64).data;
+ let commitDarkened = 0;
+ for (let i = 0; i < readNoWet.length; i += 4) {
+ if (readNoWet[i + 3] > 30 && readWithWet[i] < readNoWet[i] - 5) {
+ commitDarkened++;
+ }
+ }
+ expect(commitDarkened).toBeGreaterThan(20);
+ });
+
+ // ==========================================================================
+ // 3A. Compare density (blendTipsMode === 'compare') non-accumulation
+ // ==========================================================================
+
+ it('prevents translucent alpha accumulation over 10 overlapping dabs when blendTipsMode === "compare"', () => {
+ const compareSurf = createSoftwareCanvas(64, 64);
+ const compareCtx = compareSurf.getContext('2d');
+ const normalSurf = createSoftwareCanvas(64, 64);
+ const normalCtx = normalSurf.getContext('2d');
+
+ const dotPt: Point = { x: 32, y: 32, pressure: 1.0, width: 24 };
+ const sharedOpts: BrushRenderOptions = {
+ size: 24,
+ flow: 0.4,
+ hardness: 1.0,
+ useGpu: false,
+ };
+
+ // Stamp 10 completely overlapping 40%-alpha dabs at (32, 32)
+ for (let i = 0; i < 10; i++) {
+ drawBrushDot(compareCtx, dotPt, '#2060e0', { ...sharedOpts, blendTipsMode: 'compare' });
+ drawBrushDot(normalCtx, dotPt, '#2060e0', { ...sharedOpts, blendTipsMode: 'normal' });
+ }
+
+ const centerIdx = (32 * 64 + 32) * 4;
+ const compareAlpha = compareSurf.buf[centerIdx + 3];
+ const normalAlpha = normalSurf.buf[centerIdx + 3];
+
+ // Normal builds up: 1 - (1 - 0.4)^10 = 0.994 (~253/255)
+ expect(normalAlpha).toBeGreaterThanOrEqual(248);
+ // Compare density MUST NOT accumulate above single-dab 0.4 (~102/255)
+ expect(compareAlpha).toBeGreaterThanOrEqual(98);
+ expect(compareAlpha).toBeLessThanOrEqual(106);
+
+ // Also verify renderCompleteStroke with blendTipsMode === 'compare' over an existing background
+ const strokeSurf = createSoftwareCanvas(96, 64);
+ const sCtx = strokeSurf.getContext('2d');
+ // Fill opaque green background first
+ sCtx.fillStyle = '#00cc00';
+ sCtx.fillRect(0, 0, 96, 64);
+
+ renderCompleteStroke(
+ sCtx,
+ [
+ { x: 20, y: 32, pressure: 1.0, width: 20 },
+ { x: 40, y: 32, pressure: 1.0, width: 20 },
+ { x: 60, y: 32, pressure: 1.0, width: 20 },
+ { x: 40, y: 32, pressure: 1.0, width: 20 }, // fold back over itself!
+ ],
+ {
+ size: 20,
+ minSizeFactor: 1.0,
+ color: '#ff0000',
+ opacity: 1.0,
+ flow: 0.4,
+ spacing: 0.08,
+ usePressure: false,
+ smoothing: false,
+ stabilization: 0,
+ hardness: 1.0,
+ blendTipsMode: 'compare',
+ useGpu: false,
+ },
+ 'brush',
+ 'color'
+ );
+
+ // At (40, 32): 40% red over 100% green -> R ~ 0.4 * 255 = 102, G ~ 0.6 * 204 = 122 (NOT 255 red!)
+ const midIdx = (32 * 96 + 40) * 4;
+ expect(strokeSurf.buf[midIdx]).toBeGreaterThanOrEqual(90);
+ expect(strokeSurf.buf[midIdx]).toBeLessThanOrEqual(115);
+ expect(strokeSurf.buf[midIdx + 1]).toBeGreaterThanOrEqual(110);
+ });
+
+ // ==========================================================================
+ // 3B. BrushCombineMode (multiply, behind, add-glow, clear + all 26+ modes)
+ // ==========================================================================
+
+ it('blends strokes onto existing tiles with exact CSP BrushCombineMode semantics (multiply, behind, add-glow, clear, etc.)', () => {
+ const layerId = 'combine-layer';
+
+ const makeSolid = (w: number, h: number, r: number, g: number, b: number, a: number) => {
+ const data = new Uint8ClampedArray(w * h * 4);
+ for (let i = 0; i < w * h; i++) {
+ data[i * 4] = r;
+ data[i * 4 + 1] = g;
+ data[i * 4 + 2] = b;
+ data[i * 4 + 3] = a;
+ }
+ return { data, width: w, height: h };
+ };
+
+ // 1. Multiply: (128, 255, 200) * (200, 100, 50) / 255 = (100, 100, 39)
+ const gridMul = new SparseTileGrid();
+ gridMul.writeImageData(layerId, makeSolid(16, 16, 128, 255, 200, 255), 0, 0, 'color-32bit');
+ gridMul.compositeStrokeToTiles({
+ layerId,
+ strokeData: makeSolid(16, 16, 200, 100, 50, 255),
+ destX: 0,
+ destY: 0,
+ format: 'color-32bit',
+ compositeOp: 'source-over',
+ brushCombineMode: 'multiply',
+ opacity: 1.0,
+ });
+ const mulPx = gridMul.readImageData(layerId, 8, 8, 1, 1).data;
+ expect(Math.abs(mulPx[0] - 100)).toBeLessThanOrEqual(1);
+ expect(Math.abs(mulPx[1] - 100)).toBeLessThanOrEqual(1);
+ expect(Math.abs(mulPx[2] - 39)).toBeLessThanOrEqual(1);
+ expect(mulPx[3]).toBe(255);
+
+ // 2. Behind (destination-over): opaque front stays untouched, transparent fills behind
+ const gridBehind = new SparseTileGrid();
+ // Left half opaque blue (0..7), right half transparent (8..15)
+ gridBehind.writeImageData(layerId, makeSolid(8, 16, 20, 40, 220, 255), 0, 0, 'color-32bit');
+ gridBehind.compositeStrokeToTiles({
+ layerId,
+ strokeData: makeSolid(16, 16, 240, 30, 30, 255),
+ destX: 0,
+ destY: 0,
+ format: 'color-32bit',
+ compositeOp: 'source-over',
+ brushCombineMode: 'behind',
+ opacity: 1.0,
+ });
+ const behindFrontPx = gridBehind.readImageData(layerId, 4, 8, 1, 1).data;
+ const behindEmptyPx = gridBehind.readImageData(layerId, 12, 8, 1, 1).data;
+ expect(behindFrontPx[0]).toBe(20);
+ expect(behindFrontPx[2]).toBe(220);
+ expect(behindEmptyPx[0]).toBe(240);
+ expect(behindEmptyPx[2]).toBe(30);
+ expect(behindEmptyPx[3]).toBe(255);
+
+ // 3. Add (Glow): (120, 180, 90) + (100, 120, 200) -> (220, 255, 255)
+ const gridGlow = new SparseTileGrid();
+ gridGlow.writeImageData(layerId, makeSolid(16, 16, 120, 180, 90, 255), 0, 0, 'color-32bit');
+ gridGlow.compositeStrokeToTiles({
+ layerId,
+ strokeData: makeSolid(16, 16, 100, 120, 200, 255),
+ destX: 0,
+ destY: 0,
+ format: 'color-32bit',
+ compositeOp: 'source-over',
+ brushCombineMode: 'add-glow',
+ opacity: 1.0,
+ });
+ const glowPx = gridGlow.readImageData(layerId, 8, 8, 1, 1).data;
+ expect(glowPx[0]).toBe(220);
+ expect(glowPx[1]).toBe(255);
+ expect(glowPx[2]).toBe(255);
+
+ // 4. Clear (destination-out): erases existing opaque pixels
+ const gridClear = new SparseTileGrid();
+ gridClear.writeImageData(layerId, makeSolid(16, 16, 200, 100, 50, 255), 0, 0, 'color-32bit');
+ gridClear.compositeStrokeToTiles({
+ layerId,
+ strokeData: makeSolid(16, 16, 255, 0, 0, 255),
+ destX: 0,
+ destY: 0,
+ format: 'color-32bit',
+ compositeOp: 'source-over',
+ brushCombineMode: 'clear',
+ opacity: 1.0,
+ });
+ const clearPx = gridClear.readImageData(layerId, 8, 8, 1, 1).data;
+ expect(clearPx[3]).toBe(0);
+
+ // 5. All 26+ CSP blend modes produce valid finite [0..1] RGB
+ const allCombineModes: CspBrushCombineMode[] = [
+ 'normal',
+ 'multiply',
+ 'screen',
+ 'overlay',
+ 'darken',
+ 'lighten',
+ 'color-dodge',
+ 'color-burn',
+ 'hard-light',
+ 'soft-light',
+ 'difference',
+ 'exclusion',
+ 'linear-burn',
+ 'add',
+ 'add-glow',
+ 'color-dodge-glow',
+ 'divide',
+ 'vivid-light',
+ 'linear-light',
+ 'pin-light',
+ 'hard-mix',
+ 'subtract',
+ 'darker-color',
+ 'lighter-color',
+ 'hue',
+ 'saturation',
+ 'color',
+ 'luminosity',
+ ];
+ const out: [number, number, number] = [0, 0, 0];
+ for (const mode of allCombineModes) {
+ evaluateCpuBlendModeInto(0.6, 0.35, 0.8, 0.4, 0.7, 0.25, mode, out);
+ expect(Number.isFinite(out[0]) && out[0] >= 0 && out[0] <= 1).toBe(true);
+ expect(Number.isFinite(out[1]) && out[1] >= 0 && out[1] <= 1).toBe(true);
+ expect(Number.isFinite(out[2]) && out[2] >= 0 && out[2] <= 1).toBe(true);
+ }
+
+ // 6. Wire brushCombineMode through commitRasterStrokeToTiles
+ const commitGrid = new SparseTileGrid();
+ commitGrid.writeImageData(layerId, makeSolid(64, 64, 160, 200, 120, 255), 0, 0, 'color-32bit');
+ commitRasterStrokeToTiles({
+ state: createInitialStrokeSessionState(),
+ helpers: {
+ markTouchedTiles: () => {},
+ resolveLiveAntiAlias: () => 2,
+ buildLiveBrushOptions: () => ({}),
+ emitLiveSegment: () => {},
+ buildTouchedTileSpans: (x, y, w, h) => [{ x, y, width: w, height: h }],
+ resolveEffectiveOpacitySensor: () => undefined,
+ },
+ grid: commitGrid,
+ draftCanvas: null,
+ dirtyRect: { x: 0, y: 0, width: 64, height: 64 },
+ dims: { width: 64, height: 64 },
+ bs: {
+ size: 24,
+ minSizeFactor: 1.0,
+ color: '#808080',
+ opacity: 1.0,
+ flow: 1.0,
+ spacing: 0.1,
+ usePressure: false,
+ smoothing: false,
+ stabilization: 0,
+ hardness: 1.0,
+ brushCombineMode: 'multiply',
+ useGpu: false,
+ },
+ currentTool: 'brush',
+ currentLayerId: layerId,
+ activeLayer: undefined,
+ activeSelection: null,
+ effectiveMode: 'color',
+ targetFormat: 'color-32bit',
+ isEraser: false,
+ isBgEraser: false,
+ isMonochrome: false,
+ hasWetEdge: false,
+ shouldTaper: false,
+ strokeColor: '#808080',
+ allPoints: [{ x: 32, y: 32, pressure: 1.0, width: 24 }],
+ tailSegments: [],
+ toolForHistory: 'brush',
+ label: 'Multiply Brush',
+ strokeIdForHistory: undefined,
+ enqueueHistoryTask: () => {},
+ pushHistoryStep: () => {},
+ });
+ const committedMulPx = commitGrid.readImageData(layerId, 32, 32, 1, 1).data;
+ // Multiply by #808080 (~0.502): (160, 200, 120) -> ~(80, 100, 60)
+ expect(Math.abs(committedMulPx[0] - 80)).toBeLessThanOrEqual(2);
+ expect(Math.abs(committedMulPx[1] - 100)).toBeLessThanOrEqual(2);
+ expect(Math.abs(committedMulPx[2] - 60)).toBeLessThanOrEqual(2);
+ });
+
+ // ==========================================================================
+ // 4. Dual-tone tips (Main + Sub Color) across CPU, WebGL math, SpatialTipMixer
+ // ==========================================================================
+
+ it('renders dual-tone grayscale tips (isDualToneTip) identically across CPU, WebGL math, and SpatialTipMixer within <= 3/255', () => {
+ // 4x1 tip: black (lum 0), dark gray (lum ~0.25), light gray (lum ~0.75), white (lum 1) with distinct alphas
+ const tip = createSoftwareCanvas(4, 1);
+ const samples = [
+ [0, 0, 0, 255],
+ [64, 64, 64, 210],
+ [192, 192, 192, 175],
+ [255, 255, 255, 140],
+ ];
+ for (let x = 0; x < 4; x++) {
+ tip.buf[x * 4] = samples[x][0];
+ tip.buf[x * 4 + 1] = samples[x][1];
+ tip.buf[x * 4 + 2] = samples[x][2];
+ tip.buf[x * 4 + 3] = samples[x][3];
+ }
+
+ const primary = '#e02040'; // (224, 32, 64)
+ const secondaryA = '#20a0f0'; // (32, 160, 240)
+ const secondaryB = '#40e040'; // (64, 224, 64)
+
+ const masterA = getTintedMasterCanvas(tip, 'dualtone_test_tip', primary, 4, 1, false, true, secondaryA);
+ const masterB = getTintedMasterCanvas(tip, 'dualtone_test_tip', primary, 4, 1, false, true, secondaryB);
+
+ // Cache key MUST include secondaryColor (different sub-colors return distinct canvases)
+ expect(masterA).not.toBe(masterB);
+
+ const bufA = (masterA as any).buf as Uint8ClampedArray;
+ const pRgb = parseColorToRgb(primary);
+ const sRgb = parseColorToRgb(secondaryA);
+
+ for (let x = 0; x < 4; x++) {
+ const lum = (0.299 * samples[x][0] + 0.587 * samples[x][1] + 0.114 * samples[x][2]) / 255;
+ // WebGL fragment shader exact formula: mix(v_color.rgb, u_secondaryColor, lum)
+ const glR = Math.round((pRgb.r / 255 + ((sRgb.r - pRgb.r) / 255) * lum) * 255);
+ const glG = Math.round((pRgb.g / 255 + ((sRgb.g - pRgb.g) / 255) * lum) * 255);
+ const glB = Math.round((pRgb.b / 255 + ((sRgb.b - pRgb.b) / 255) * lum) * 255);
+
+ expect(Math.abs(bufA[x * 4] - glR)).toBeLessThanOrEqual(1);
+ expect(Math.abs(bufA[x * 4 + 1] - glG)).toBeLessThanOrEqual(1);
+ expect(Math.abs(bufA[x * 4 + 2] - glB)).toBeLessThanOrEqual(1);
+ // Preserves exact tip alpha
+ expect(bufA[x * 4 + 3]).toBe(samples[x][3]);
+ }
+
+ // SpatialTipMixer dual-tone mapping: left half black (primary), right half white (secondary)
+ const dualTipSquare = createSoftwareCanvas(16, 16);
+ for (let y = 0; y < 16; y++) {
+ for (let x = 0; x < 16; x++) {
+ const i = (y * 16 + x) * 4;
+ const v = x < 8 ? 0 : 255;
+ dualTipSquare.buf[i] = v;
+ dualTipSquare.buf[i + 1] = v;
+ dualTipSquare.buf[i + 2] = v;
+ dualTipSquare.buf[i + 3] = 255;
+ }
+ }
+ const mixer = new SpatialTipMixer(primary);
+ const built = mixer.stepAndBuildStamp({
+ x: 16,
+ y: 16,
+ width: 16,
+ height: 16,
+ angleRad: 0,
+ dirX: 1,
+ dirY: 0,
+ stepDist: 0,
+ hardness: 1.0,
+ antiAlias: 2,
+ flipX: 1,
+ flipY: 1,
+ flow: 1.0,
+ pressure: 1.0,
+ pressureAlreadyApplied: true,
+ amountOfPaint: 1.0,
+ densityOfPaint: 1.0,
+ colorStretch: 0.5,
+ mixingMode: 'blend',
+ perceptualMixing: false,
+ tipImage: dualTipSquare,
+ isDualToneTip: true,
+ secondaryColor: secondaryA,
+ });
+ expect(built).not.toBeNull();
+ const mBuf = (built!.canvas as any).buf as Uint8ClampedArray;
+ const w = built!.srcW;
+ // Inner left pixel (x=3, y=9) -> primaryColor; inner right pixel (x=14, y=9) -> secondaryA
+ const leftOff = (9 * w + 3) * 4;
+ const rightOff = (9 * w + 14) * 4;
+ expect(Math.abs(mBuf[leftOff] - pRgb.r)).toBeLessThanOrEqual(3);
+ expect(Math.abs(mBuf[leftOff + 1] - pRgb.g)).toBeLessThanOrEqual(3);
+ expect(Math.abs(mBuf[leftOff + 2] - pRgb.b)).toBeLessThanOrEqual(3);
+ expect(Math.abs(mBuf[rightOff] - sRgb.r)).toBeLessThanOrEqual(3);
+ expect(Math.abs(mBuf[rightOff + 1] - sRgb.g)).toBeLessThanOrEqual(3);
+ expect(Math.abs(mBuf[rightOff + 2] - sRgb.b)).toBeLessThanOrEqual(3);
+ });
+
+ // ==========================================================================
+ // 5. Dynamic effectors (thicknessSensor, amountOfPaintSensor, initial-direction, colorJitter)
+ // ==========================================================================
+
+ it('wires thicknessSensor, amountOfPaintSensor, angleDynamics="initial-direction", and colorJitter with SpatialTipMixer', () => {
+ // 5A. thicknessSensor modulates dab height on GPU batch
+ const gpuDabs: GpuDab[] = [];
+ const dummyCtx = createSoftwareCanvas(128, 128).getContext('2d');
+ const pLow: Point = { x: 10, y: 20, pressure: 0.1, width: 20 };
+ const pHigh: Point = { x: 90, y: 20, pressure: 1.0, width: 20 };
+ const { c1, c2 } = centripetalCatmullRomToBezier(pLow, pLow, pHigh, pHigh);
+ drawBrushCubicBezierSegment(
+ dummyCtx,
+ pLow,
+ c1,
+ c2,
+ pHigh,
+ '#000000',
+ {
+ size: 20,
+ spacing: 0.25,
+ thickness: 1.0,
+ thicknessSensor: { usePressure: true, pressureMin: 0.2 },
+ },
+ 0,
+ { count: 0 },
+ gpuDabs
+ );
+ expect(gpuDabs.length).toBeGreaterThan(5);
+ // Low-pressure start dab should be much flatter (smaller height) than high-pressure end dab
+ expect(gpuDabs[0].height).toBeLessThan(gpuDabs[gpuDabs.length - 1].height * 0.5);
+
+ // 5B. amountOfPaintSensor: light pressure blends underlying canvas paint; heavy pressure covers with fresh foreground!
+ const bgCanvas = createSoftwareCanvas(120, 64);
+ const bgCtx = bgCanvas.getContext('2d');
+ bgCtx.fillStyle = '#0020ff'; // Pure blue underlying layer
+ bgCtx.fillRect(0, 0, 120, 64);
+ const sampler = new LayerPixelSampler(bgCanvas);
+
+ const runMixingStroke = (pressure: number) => {
+ const outSurf = createSoftwareCanvas(120, 64);
+ const pts: Point[] = [
+ { x: 20, y: 32, pressure, width: 16 },
+ { x: 50, y: 32, pressure, width: 16 },
+ { x: 80, y: 32, pressure, width: 16 },
+ ];
+ const opts = buildBrushRenderOptions(
+ {
+ size: 16,
+ minSizeFactor: 1.0,
+ color: '#ff2000', // Fresh red foreground
+ opacity: 1.0,
+ flow: 1.0,
+ spacing: 0.12,
+ usePressure: false,
+ smoothing: false,
+ stabilization: 0,
+ hardness: 1.0,
+ colorMixing: true,
+ perceptualMixing: false,
+ amountOfPaint: 0.9,
+ densityOfPaint: 0.9,
+ colorStretch: 0.5,
+ amountOfPaintSensor: { usePressure: true, pressureMin: 0.02 },
+ useGpu: false,
+ },
+ {
+ sampler: new LayerPixelSampler(bgCanvas),
+ reservoir: new PaintReservoir('#ff2000'),
+ }
+ );
+ drawBrushDot(outSurf.getContext('2d'), pts[0], '#ff2000', opts);
+ const seg = centripetalCatmullRomToBezier(pts[0], pts[0], pts[1], pts[2]);
+ drawBrushCubicBezierSegment(outSurf.getContext('2d'), pts[0], seg.c1, seg.c2, pts[1], '#ff2000', opts, 0, { count: 0 });
+ return outSurf.buf[(32 * 120 + 48) * 4]; // Red channel
+ };
+
+ const lightPressureRed = runMixingStroke(0.05); // Blends blue canvas -> low Red!
+ const heavyPressureRed = runMixingStroke(1.0); // Covers with fresh red -> high Red!
+ expect(heavyPressureRed).toBeGreaterThan(lightPressureRed + 80);
+
+ // 5C. angleDynamics === 'initial-direction': locks angle to initial 4-8px chord even through a 90° bend
+ const lockedDabs: GpuDab[] = [];
+ const bendPts: Point[] = [
+ { x: 10, y: 10, pressure: 1, width: 12 },
+ { x: 30, y: 10, pressure: 1, width: 12 }, // moving right (angle 0)
+ { x: 30, y: 60, pressure: 1, width: 12 }, // turning 90° down (angle +PI/2)
+ ];
+ const segA = centripetalCatmullRomToBezier(bendPts[0], bendPts[0], bendPts[1], bendPts[2]);
+ const segB = centripetalCatmullRomToBezier(bendPts[0], bendPts[1], bendPts[2], bendPts[2]);
+ const lockCounter: any = { count: 0 };
+ const lockOpts: BrushRenderOptions = {
+ size: 12,
+ spacing: 0.25,
+ thickness: 0.35,
+ angleDynamics: 'initial-direction',
+ };
+ const rem = drawBrushCubicBezierSegment(dummyCtx, bendPts[0], segA.c1, segA.c2, bendPts[1], '#000', lockOpts, 0, lockCounter, lockedDabs);
+ drawBrushCubicBezierSegment(dummyCtx, bendPts[1], segB.c1, segB.c2, bendPts[2], '#000', lockOpts, rem, lockCounter, lockedDabs);
+ expect(lockedDabs.length).toBeGreaterThan(8);
+ expect(lockCounter.lockedInitialAngle).toBeDefined();
+ // Final vertical segment dabs MUST stay locked near 0 rad (horizontal), NOT turn to PI/2 (~1.57 rad)!
+ const lastAngle = lockedDabs[lockedDabs.length - 1].angle;
+ expect(Math.abs(lastAngle)).toBeLessThan(0.25);
+
+ // 5D. colorJitter (perDab AND colorJitterPerStroke) works seamlessly WITH SpatialTipMixer
+ const perDabReservoir = new PaintReservoir('#cc3333');
+ const perDabSurf = createSoftwareCanvas(120, 48);
+ const perDabOpts: BrushRenderOptions = {
+ size: 14,
+ flow: 1.0,
+ spacing: 0.4,
+ hardness: 1.0,
+ colorMixing: true,
+ amountOfPaint: 1.0,
+ densityOfPaint: 1.0,
+ colorStretch: 0.2,
+ secondaryColor: '#20c0f0',
+ dynamics: {
+ ...DEFAULT_BRUSH_DYNAMICS,
+ colorJitterEnabled: true,
+ colorJitterPerStroke: false,
+ hueJitter: 0.8,
+ foregroundBackgroundJitter: 0.5,
+ },
+ reservoir: perDabReservoir,
+ sampler,
+ useGpu: false,
+ };
+ const jP0: Point = { x: 15, y: 24, pressure: 1, width: 14 };
+ const jP1: Point = { x: 105, y: 24, pressure: 1, width: 14 };
+ const jSeg = centripetalCatmullRomToBezier(jP0, jP0, jP1, jP1);
+ drawBrushCubicBezierSegment(perDabSurf.getContext('2d'), jP0, jSeg.c1, jSeg.c2, jP1, '#cc3333', perDabOpts, 0, { count: 0 });
+ // MUST stay inside SpatialTipMixer (never fall back out of SpatialTipMixer!)
+ expect(perDabReservoir.spatialMixer).toBeDefined();
+ // Different x positions along the stroke should exhibit distinct jittered colors
+ const sample1 = [perDabSurf.buf[(24 * 120 + 20) * 4], perDabSurf.buf[(24 * 120 + 20) * 4 + 1], perDabSurf.buf[(24 * 120 + 20) * 4 + 2]];
+ const sample2 = [perDabSurf.buf[(24 * 120 + 85) * 4], perDabSurf.buf[(24 * 120 + 85) * 4 + 1], perDabSurf.buf[(24 * 120 + 85) * 4 + 2]];
+ expect(sample1).not.toEqual(sample2);
+
+ // colorJitterPerStroke: constant jittered color across entire stroke, still using SpatialTipMixer
+ const perStrokeReservoir = new PaintReservoir('#cc3333');
+ const perStrokeSurf = createSoftwareCanvas(120, 48);
+ const perStrokeOpts: BrushRenderOptions = {
+ ...perDabOpts,
+ dynamics: {
+ ...DEFAULT_BRUSH_DYNAMICS,
+ colorJitterEnabled: true,
+ colorJitterPerStroke: true,
+ hueJitter: 0.8,
+ foregroundBackgroundJitter: 0.5,
+ },
+ reservoir: perStrokeReservoir,
+ };
+ drawBrushCubicBezierSegment(perStrokeSurf.getContext('2d'), jP0, jSeg.c1, jSeg.c2, jP1, '#cc3333', perStrokeOpts, 0, { count: 0 });
+ expect(perStrokeReservoir.spatialMixer).toBeDefined();
+ const ps1 = [perStrokeSurf.buf[(24 * 120 + 20) * 4], perStrokeSurf.buf[(24 * 120 + 20) * 4 + 1], perStrokeSurf.buf[(24 * 120 + 20) * 4 + 2]];
+ const ps2 = [perStrokeSurf.buf[(24 * 120 + 85) * 4], perStrokeSurf.buf[(24 * 120 + 85) * 4 + 1], perStrokeSurf.buf[(24 * 120 + 85) * 4 + 2]];
+ expect(ps1).toEqual(ps2);
+ });
+});
diff --git a/src/utils/__tests__/dualBrushParity.test.ts b/src/utils/__tests__/dualBrushParity.test.ts
new file mode 100644
index 0000000..101bd2b
--- /dev/null
+++ b/src/utils/__tests__/dualBrushParity.test.ts
@@ -0,0 +1,854 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import {
+ renderCompleteStroke,
+ resolveDualBrushConfig,
+ buildSecondaryBrushSettings,
+ combineDualBrushAlpha,
+ combineDualBrushImageData,
+ dualBrushCompositeModeToIndex,
+ computeSecondaryBrushSize,
+ scalePointsForSecondaryBrush,
+} from '../../engine/BrushEngine';
+import { DUAL_BRUSH_COMPOSITE_MODES } from '../../engine/DualBrushEngine';
+import { WebGlBrushEngine, GpuDab } from '../../engine/WebGlBrushEngine';
+import { LayerPixelSampler } from '../colorMixingEngine';
+import { parseSutExtractedData } from '../sutParser';
+import {
+ createInitialStrokeSessionState,
+} from '../../hooks/drawing/brushStrokeSession/types';
+import {
+ prepareDualDraftCanvases,
+ syncDualBrushRegionToDraft,
+} from '../../hooks/drawing/brushStrokeSession/strokeHelpers';
+import { DraftCanvasElement } from '../../hooks/drawing/types';
+import { BrushSettings, DualBrushCompositeMode, Point } from '../../types/editor';
+
+/**
+ * Software-compositing mock Canvas2D with accurate scaling, translation, source-in tinting,
+ * and source-over / destination-out compositing for headless Vitest raster parity tests.
+ */
+function createRasterMockCanvas(width: number = 256, height: number = 128) {
+ let curW = width;
+ let curH = height;
+ let buf = new Uint8ClampedArray(curW * curH * 4);
+
+ const resize = (nw: number, nh: number) => {
+ curW = Math.max(1, Math.round(nw));
+ curH = Math.max(1, Math.round(nh));
+ buf = new Uint8ClampedArray(curW * curH * 4);
+ mockObj.pixelBuffer = buf;
+ };
+
+ let tx = 0;
+ let ty = 0;
+ let sxScale = 1;
+ let syScale = 1;
+ let rotRad = 0;
+ const stack: Array<{
+ tx: number;
+ ty: number;
+ sx: number;
+ sy: number;
+ rot: number;
+ alpha: number;
+ op: string;
+ fill: string;
+ }> = [];
+
+ const parseHex = (color: string): [number, number, number] => {
+ if (color.startsWith('#')) {
+ let hex = color.slice(1);
+ if (hex.length === 3) {
+ hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
+ }
+ const n = parseInt(hex, 16);
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
+ }
+ return [0, 0, 0];
+ };
+
+ const ctx: any = {
+ canvas: null as any,
+ globalAlpha: 1.0,
+ globalCompositeOperation: 'source-over',
+ fillStyle: '#000000',
+ imageSmoothingEnabled: true,
+ save() {
+ stack.push({
+ tx,
+ ty,
+ sx: sxScale,
+ sy: syScale,
+ rot: rotRad,
+ alpha: ctx.globalAlpha,
+ op: ctx.globalCompositeOperation,
+ fill: ctx.fillStyle,
+ });
+ },
+ restore() {
+ const s = stack.pop();
+ if (s) {
+ tx = s.tx;
+ ty = s.ty;
+ sxScale = s.sx;
+ syScale = s.sy;
+ rotRad = s.rot;
+ ctx.globalAlpha = s.alpha;
+ ctx.globalCompositeOperation = s.op;
+ ctx.fillStyle = s.fill;
+ }
+ },
+ translate(dx: number, dy: number) {
+ tx += dx * sxScale;
+ ty += dy * syScale;
+ },
+ scale(x: number, y: number) {
+ sxScale *= x;
+ syScale *= y;
+ },
+ rotate(rad: number) {
+ rotRad += rad;
+ },
+ setTransform(a: number, _b: number, _c: number, d: number, e: number, f: number) {
+ sxScale = a;
+ syScale = d;
+ tx = e;
+ ty = f;
+ rotRad = 0;
+ },
+ resetTransform() {
+ tx = 0;
+ ty = 0;
+ sxScale = 1;
+ syScale = 1;
+ rotRad = 0;
+ },
+ beginPath() {},
+ rect() {},
+ clip() {},
+ clearRect(x = 0, y = 0, w = curW, h = curH) {
+ const x0 = Math.max(0, Math.floor(x));
+ const y0 = Math.max(0, Math.floor(y));
+ const x1 = Math.min(curW, Math.ceil(x + w));
+ const y1 = Math.min(curH, Math.ceil(y + h));
+ for (let py = y0; py < y1; py++) {
+ for (let px = x0; px < x1; px++) {
+ const i = (py * curW + px) * 4;
+ buf[i] = 0;
+ buf[i + 1] = 0;
+ buf[i + 2] = 0;
+ buf[i + 3] = 0;
+ }
+ }
+ },
+ fillRect(x: number, y: number, w: number, h: number) {
+ const [fr, fg, fb] = parseHex(String(ctx.fillStyle));
+ const x0 = Math.max(0, Math.floor(x + tx));
+ const y0 = Math.max(0, Math.floor(y + ty));
+ const x1 = Math.min(curW, Math.ceil(x + w + tx));
+ const y1 = Math.min(curH, Math.ceil(y + h + ty));
+ const aScale = Math.max(0, Math.min(1, ctx.globalAlpha));
+ for (let py = y0; py < y1; py++) {
+ for (let px = x0; px < x1; px++) {
+ const i = (py * curW + px) * 4;
+ if (ctx.globalCompositeOperation === 'source-in') {
+ if (buf[i + 3] > 0) {
+ buf[i] = fr;
+ buf[i + 1] = fg;
+ buf[i + 2] = fb;
+ buf[i + 3] = Math.round(buf[i + 3] * aScale);
+ }
+ } else {
+ buf[i] = fr;
+ buf[i + 1] = fg;
+ buf[i + 2] = fb;
+ buf[i + 3] = Math.round(255 * aScale);
+ }
+ }
+ }
+ },
+ createImageData(w: number, h: number) {
+ return { width: w, height: h, data: new Uint8ClampedArray(w * h * 4) };
+ },
+ putImageData(imgData: { width: number; height: number; data: Uint8ClampedArray }, dx = 0, dy = 0) {
+ for (let y = 0; y < imgData.height; y++) {
+ const destY = dy + y;
+ if (destY < 0 || destY >= curH) continue;
+ for (let x = 0; x < imgData.width; x++) {
+ const destX = dx + x;
+ if (destX < 0 || destX >= curW) continue;
+ const si = (y * imgData.width + x) * 4;
+ const di = (destY * curW + destX) * 4;
+ buf[di] = imgData.data[si];
+ buf[di + 1] = imgData.data[si + 1];
+ buf[di + 2] = imgData.data[si + 2];
+ buf[di + 3] = imgData.data[si + 3];
+ }
+ }
+ },
+ getImageData(sx: number, sy: number, sw: number, sh: number) {
+ const data = new Uint8ClampedArray(sw * sh * 4);
+ for (let y = 0; y < sh; y++) {
+ const srcY = sy + y;
+ if (srcY < 0 || srcY >= curH) continue;
+ for (let x = 0; x < sw; x++) {
+ const srcX = sx + x;
+ if (srcX < 0 || srcX >= curW) continue;
+ const si = (srcY * curW + srcX) * 4;
+ const di = (y * sw + x) * 4;
+ data[di] = buf[si];
+ data[di + 1] = buf[si + 1];
+ data[di + 2] = buf[si + 2];
+ data[di + 3] = buf[si + 3];
+ }
+ }
+ return { width: sw, height: sh, data };
+ },
+ drawImage(
+ source: any,
+ sx: number,
+ sy: number,
+ sw?: number,
+ sh?: number,
+ dx?: number,
+ dy?: number,
+ dw?: number,
+ dh?: number
+ ) {
+ const srcBuf: Uint8ClampedArray | undefined = source?.pixelBuffer || source?.__rgbaData;
+ const srcW: number = source?.width || source?.naturalWidth || 0;
+ const srcH: number = source?.height || source?.naturalHeight || 0;
+ if (!srcBuf || srcW <= 0 || srcH <= 0) return;
+
+ const useSub = dx !== undefined && dy !== undefined && dw !== undefined && dh !== undefined;
+ const srcX0 = useSub ? sx : 0;
+ const srcY0 = useSub ? sy : 0;
+ const srcCopyW = useSub ? sw! : srcW;
+ const srcCopyH = useSub ? sh! : srcH;
+ const rawDstX = useSub ? dx! : sx;
+ const rawDstY = useSub ? dy! : sy;
+ const rawDstW = useSub ? dw! : sw ?? srcW;
+ const rawDstH = useSub ? dh! : sh ?? srcH;
+
+ const dstX0 = rawDstX * sxScale + tx;
+ const dstY0 = rawDstY * syScale + ty;
+ const dstW = rawDstW * Math.abs(sxScale);
+ const dstH = rawDstH * Math.abs(syScale);
+ if (dstW <= 0 || dstH <= 0) return;
+
+ const alphaScale = Math.max(0, Math.min(1, ctx.globalAlpha));
+ const xStart = Math.max(0, Math.floor(dstX0));
+ const yStart = Math.max(0, Math.floor(dstY0));
+ const xEnd = Math.min(curW, Math.ceil(dstX0 + dstW));
+ const yEnd = Math.min(curH, Math.ceil(dstY0 + dstH));
+
+ for (let py = yStart; py < yEnd; py++) {
+ const v = (py + 0.5 - dstY0) / dstH;
+ if (v < 0 || v >= 1) continue;
+ const syi = Math.min(srcH - 1, Math.max(0, Math.floor(srcY0 + v * srcCopyH)));
+ for (let px = xStart; px < xEnd; px++) {
+ const u = (px + 0.5 - dstX0) / dstW;
+ if (u < 0 || u >= 1) continue;
+ const sxi = Math.min(srcW - 1, Math.max(0, Math.floor(srcX0 + u * srcCopyW)));
+ const si = (syi * srcW + sxi) * 4;
+ const srcA = (srcBuf[si + 3] / 255) * alphaScale;
+ if (srcA <= 0.001) continue;
+ const di = (py * curW + px) * 4;
+ const dstA = buf[di + 3] / 255;
+
+ if (ctx.globalCompositeOperation === 'destination-out') {
+ buf[di + 3] = Math.round(dstA * (1 - srcA) * 255);
+ } else if (ctx.globalCompositeOperation === 'source-atop') {
+ if (dstA <= 0.001) continue;
+ buf[di] = Math.round(srcBuf[si] * srcA + buf[di] * (1 - srcA));
+ buf[di + 1] = Math.round(srcBuf[si + 1] * srcA + buf[di + 1] * (1 - srcA));
+ buf[di + 2] = Math.round(srcBuf[si + 2] * srcA + buf[di + 2] * (1 - srcA));
+ } else {
+ const outA = srcA + dstA * (1 - srcA);
+ const inv = outA > 1e-5 ? 1 / outA : 0;
+ buf[di] = Math.round((srcBuf[si] * srcA + buf[di] * dstA * (1 - srcA)) * inv);
+ buf[di + 1] = Math.round((srcBuf[si + 1] * srcA + buf[di + 1] * dstA * (1 - srcA)) * inv);
+ buf[di + 2] = Math.round((srcBuf[si + 2] * srcA + buf[di + 2] * dstA * (1 - srcA)) * inv);
+ buf[di + 3] = Math.round(outA * 255);
+ }
+ }
+ }
+ },
+ };
+
+ const mockObj: any = {
+ get width() {
+ return curW;
+ },
+ set width(v: number) {
+ if (v !== curW) resize(v, curH);
+ },
+ get height() {
+ return curH;
+ },
+ set height(v: number) {
+ if (v !== curH) resize(curW, v);
+ },
+ pixelBuffer: buf,
+ getContext(type: string) {
+ return type === '2d' ? ctx : null;
+ },
+ };
+ ctx.canvas = mockObj;
+ return mockObj;
+}
+
+function makeBaseBrushSettings(overrides: Partial<BrushSettings> = {}): BrushSettings {
+ return {
+ size: 20,
+ minSizeFactor: 1.0,
+ color: '#ff2222',
+ opacity: 1.0,
+ flow: 1.0,
+ spacing: 0.05,
+ hardness: 1.0,
+ usePressure: false,
+ smoothing: false,
+ stabilization: 0,
+ useGpu: false,
+ ...overrides,
+ };
+}
+
+function makeHorizontalStrokePoints(
+ x0: number,
+ x1: number,
+ y: number,
+ width: number,
+ count: number = 12
+): Point[] {
+ const pts: Point[] = [];
+ for (let i = 0; i < count; i++) {
+ const t = i / (count - 1);
+ pts.push({
+ x: x0 + (x1 - x0) * t,
+ y,
+ pressure: 1.0,
+ width,
+ });
+ }
+ return pts;
+}
+
+describe('CSP True Two-Pass Dual Brush Engine Parity', () => {
+ beforeEach(() => {
+ (globalThis as any).document = {
+ createElement: (tag: string) => {
+ if (tag === 'canvas') {
+ return createRasterMockCanvas(128, 128);
+ }
+ return {};
+ },
+ };
+ });
+
+ describe('1. CspDualBrushConfig Resolution, Link Size & SUT Parser Population', () => {
+ it('populates dualBrushConfig from SUT Dual* columns and dualVariantValues while keeping flat fields', async () => {
+ const brush = await parseSutExtractedData({
+ nodeName: 'CSP Dual Textured Charcoal',
+ variantId: 42,
+ variantValues: new Map<string, unknown>([
+ ['brushsize', 50],
+ ['usedualbrush', 1],
+ ['dualbrushcompositemode', 28], // height
+ ['dualbrushlinksize', 1],
+ ['dualbrushhardness', 3], // 0.6
+ ['dualbrushdensity', 70], // 0.7
+ ['dualbrushfliph', 3], // random
+ ['dualbrushflipv', 1], // alternate
+ ['dualbrushpatternordertype', 4], // random-no-repeat
+ ['dualbrushribbon', 1],
+ ]),
+ dualVariantValues: new Map<string, unknown>([
+ ['brushsize', 25],
+ ['brushinterval', 40], // 0.40
+ ['brushthickness', 60], // 0.6
+ ['brushverticalthicknes', 0], // horizontal -> thicknessVertical = true
+ ['brushrotation', 45],
+ ['brushrotationeffector', 67], // 0x43 = direction of line
+ ]),
+ materials: [],
+ });
+
+ expect(brush.dualBrush).toBe(true);
+ expect(brush.dualBrushConfig).toBeDefined();
+ expect(brush.dualBrushConfig!.enabled).toBe(true);
+ expect(brush.dualBrushConfig!.compositeMode).toBe('height');
+ expect(brush.dualBrushConfig!.linkSizeWithMain).toBe(true);
+ expect(brush.dualBrushConfig!.size).toBe(25);
+ expect(brush.dualBrushConfig!.sizeRatio).toBeCloseTo(0.5, 4);
+ expect(brush.dualBrushConfig!.spacing).toBeCloseTo(0.4, 4);
+ expect(brush.dualBrushConfig!.thickness).toBeCloseTo(0.6, 4);
+ expect(brush.dualBrushConfig!.thicknessVertical).toBe(true);
+ expect(brush.dualBrushConfig!.hardness).toBeCloseTo(0.6, 4);
+ expect(brush.dualBrushConfig!.density).toBeCloseTo(0.7, 4);
+ expect(brush.dualBrushConfig!.angle).toBe(45);
+ expect(brush.dualBrushConfig!.angleDynamics).toBe('direction');
+ expect(brush.dualBrushConfig!.flipH).toBe('random');
+ expect(brush.dualBrushConfig!.flipV).toBe('alternate');
+ expect(brush.dualBrushConfig!.subTipOrder).toBe('random-no-repeat');
+ expect(brush.dualBrushConfig!.isRibbon).toBe(true);
+ });
+
+ it('resolves legacy flat dual* fields cleanly and respects linkSizeWithMain', () => {
+ const legacyBs = makeBaseBrushSettings({
+ size: 40,
+ dualBrush: true,
+ dualBrushCompositeMode: 'subtract',
+ dualSize: 16,
+ dualSpacing: 0.75,
+ dualAngle: 30,
+ dualScatter: 0.4,
+ });
+
+ const cfg = resolveDualBrushConfig(legacyBs);
+ expect(cfg).not.toBeNull();
+ expect(cfg!.compositeMode).toBe('subtract');
+ expect(cfg!.size).toBe(16);
+ expect(cfg!.spacing).toBe(0.75);
+ expect(cfg!.angle).toBe(30);
+ expect(cfg!.scatter).toBe(0.4);
+
+ const unlinkedSize = computeSecondaryBrushSize(80, {
+ enabled: true,
+ compositeMode: 'multiply',
+ linkSizeWithMain: false,
+ size: 16,
+ sizeRatio: 0.4,
+ });
+ expect(unlinkedSize).toBeCloseTo(16, 4);
+
+ const linkedSize = computeSecondaryBrushSize(80, {
+ enabled: true,
+ compositeMode: 'multiply',
+ linkSizeWithMain: true,
+ size: 16,
+ sizeRatio: 0.4,
+ });
+ expect(linkedSize).toBeCloseTo(32, 4);
+
+ const scaled = scalePointsForSecondaryBrush(
+ [{ x: 10, y: 10, pressure: 1, width: 40 }],
+ 0.4,
+ 16
+ );
+ expect(scaled[0].width).toBeCloseTo(16, 4);
+ });
+ });
+
+ describe('2. Exact CSP Dual Brush Combine Modes (Math & Raster)', () => {
+ it('assigns unique GPU shader indices 0..11 to all 12 CSP Dual Brush composite modes', () => {
+ const indices = DUAL_BRUSH_COMPOSITE_MODES.map((m) => dualBrushCompositeModeToIndex(m));
+ expect(indices).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
+ });
+
+ it('evaluates exact combine semantics for every DualBrushCompositeMode', () => {
+ // Zero primary silhouette always produces 0 across every mode
+ for (const mode of DUAL_BRUSH_COMPOSITE_MODES) {
+ expect(combineDualBrushAlpha(0, 1.0, mode)).toBe(0);
+ }
+
+ // Exact algebraic checks at (a1=0.8, a2=0.5)
+ expect(combineDualBrushAlpha(0.8, 0.5, 'multiply')).toBeCloseTo(0.4, 5);
+ expect(combineDualBrushAlpha(0.8, 0.5, 'darken')).toBeCloseTo(0.5, 5);
+ expect(combineDualBrushAlpha(0.8, 0.5, 'subtract')).toBeCloseTo(0.3, 5);
+ expect(combineDualBrushAlpha(0.8, 0.5, 'compare-density')).toBeCloseTo(0.8, 5);
+ expect(combineDualBrushAlpha(0.5, 0.8, 'compare-density')).toBeCloseTo(0.8, 5);
+ expect(combineDualBrushAlpha(0.8, 0.5, 'linear-burn')).toBeCloseTo(0.3, 5);
+ expect(combineDualBrushAlpha(0.8, 0.5, 'color-burn')).toBeCloseTo(0.6, 5);
+ expect(combineDualBrushAlpha(0.8, 0.0, 'color-burn')).toBe(0);
+ expect(combineDualBrushAlpha(0.8, 0.5, 'overlay')).toBeCloseTo(0.8, 5);
+ expect(combineDualBrushAlpha(0.4, 0.5, 'overlay')).toBeCloseTo(0.4, 5);
+ expect(combineDualBrushAlpha(0.4, 0.2, 'overlay')).toBeCloseTo(0.16, 5);
+ expect(combineDualBrushAlpha(0.8, 0.5, 'screen')).toBeCloseTo(0.9, 5);
+ expect(combineDualBrushAlpha(0.5, 0.8, 'lighten')).toBeCloseTo(0.8, 5);
+ expect(combineDualBrushAlpha(0.6, 0.5, 'hard-mix')).toBe(1.0);
+ expect(combineDualBrushAlpha(0.4, 0.5, 'hard-mix')).toBe(0.0);
+ expect(combineDualBrushAlpha(0.8, 0.5, 'normal')).toBeCloseTo(0.9, 5);
+
+ // Height mode: smooth carving threshold around a1 + a2 = 1.0
+ expect(combineDualBrushAlpha(0.4, 0.5, 'height')).toBe(0);
+ expect(combineDualBrushAlpha(1.0, 0.0, 'height')).toBe(0);
+ const heightMid = combineDualBrushAlpha(0.6, 0.5, 'height');
+ expect(heightMid).toBeGreaterThan(0.1);
+ expect(heightMid).toBeLessThan(0.9);
+ expect(combineDualBrushAlpha(0.8, 0.6, 'height')).toBe(1.0);
+ });
+
+ it('renders distinct raster pixel outputs for multiply, subtract, darken, height, linear-burn, color-burn, and overlay', () => {
+ const renderModeWithPartialDensity = (mode: DualBrushCompositeMode) => {
+ const w = 64;
+ const h = 64;
+ const pData = new Uint8ClampedArray(w * h * 4);
+ const sData = new Uint8ClampedArray(w * h * 4);
+ const out = new Uint8ClampedArray(w * h * 4);
+
+ // Primary horizontal ramp: a1 = 0.65 across interior
+ // Secondary vertical ramp: a2 = 0.45 in top half, 0.90 in bottom half
+ for (let y = 10; y < 54; y++) {
+ for (let x = 10; x < 54; x++) {
+ const i = (y * w + x) * 4;
+ pData[i] = 220;
+ pData[i + 1] = 40;
+ pData[i + 2] = 60;
+ pData[i + 3] = Math.round(0.65 * 255);
+
+ sData[i] = 255;
+ sData[i + 1] = 255;
+ sData[i + 2] = 255;
+ sData[i + 3] = Math.round((y < 32 ? 0.45 : 0.9) * 255);
+ }
+ }
+ combineDualBrushImageData(pData, sData, out, mode);
+ const topAlpha = out[(20 * w + 32) * 4 + 3] / 255;
+ const botAlpha = out[(42 * w + 32) * 4 + 3] / 255;
+ const outsideAlpha = out[(2 * w + 2) * 4 + 3] / 255;
+ return { topAlpha, botAlpha, outsideAlpha };
+ };
+
+ const mult = renderModeWithPartialDensity('multiply');
+ const sub = renderModeWithPartialDensity('subtract');
+ const dark = renderModeWithPartialDensity('darken');
+ const height = renderModeWithPartialDensity('height');
+ const linBurn = renderModeWithPartialDensity('linear-burn');
+ const colBurn = renderModeWithPartialDensity('color-burn');
+ const ov = renderModeWithPartialDensity('overlay');
+
+ // No mode ever leaks outside primary silhouette
+ for (const r of [mult, sub, dark, height, linBurn, colBurn, ov]) {
+ expect(r.outsideAlpha).toBe(0);
+ }
+
+ // Multiply: 0.65*0.45 ≈ 0.2925, 0.65*0.90 ≈ 0.585
+ expect(mult.topAlpha).toBeCloseTo(0.65 * 0.45, 1);
+ expect(mult.botAlpha).toBeCloseTo(0.65 * 0.9, 1);
+
+ // Subtract: max(0, 0.65-0.45) = 0.20, max(0, 0.65-0.90) = 0 (stronger secondary carves deeper!)
+ expect(sub.topAlpha).toBeCloseTo(0.2, 1);
+ expect(sub.botAlpha).toBeCloseTo(0.0, 2);
+
+ // Darken: min(0.65, 0.45) = 0.45, min(0.65, 0.90) = 0.65
+ expect(dark.topAlpha).toBeCloseTo(0.45, 1);
+ expect(dark.botAlpha).toBeCloseTo(0.65, 1);
+
+ // Linear burn: max(0, 0.65+0.45-1) = 0.10, max(0, 0.65+0.90-1) = 0.55
+ expect(linBurn.topAlpha).toBeCloseTo(0.1, 1);
+ expect(linBurn.botAlpha).toBeCloseTo(0.55, 1);
+
+ // Color burn: 1-(0.35/0.45) ≈ 0.222, 1-(0.35/0.90) ≈ 0.611
+ expect(colBurn.topAlpha).toBeCloseTo(1 - 0.35 / 0.45, 1);
+ expect(colBurn.botAlpha).toBeCloseTo(1 - 0.35 / 0.9, 1);
+
+ // Height: steeper/crisper than linear-burn (0.65+0.45-1=0.10 -> smoothstep ≈ 0.352; 0.65+0.90-1=0.55 -> 1.0)
+ expect(height.topAlpha).toBeGreaterThan(linBurn.topAlpha + 0.1);
+ expect(height.botAlpha).toBeCloseTo(1.0, 2);
+
+ // Overlay: 1 - 2*(0.35)*(0.55) = 0.615, 1 - 2*(0.35)*(0.10) = 0.93
+ expect(ov.topAlpha).toBeCloseTo(1 - 2 * 0.35 * 0.55, 1);
+ expect(ov.botAlpha).toBeCloseTo(1 - 2 * 0.35 * 0.1, 1);
+ });
+ });
+
+ describe('3. Independent Secondary Spacing & Size Cadence', () => {
+ it('stamps an independent secondary bead cadence inside a continuous primary stroke (multiply & subtract)', () => {
+ const pts = makeHorizontalStrokePoints(20, 220, 48, 22, 16);
+
+ // Primary stroke alone: solid continuous bar along y=48
+ const primaryOnlyCanvas = createRasterMockCanvas(256, 96);
+ renderCompleteStroke(
+ primaryOnlyCanvas.getContext('2d'),
+ pts,
+ makeBaseBrushSettings({ size: 22, spacing: 0.08, hardness: 1.0, flow: 1.0 }),
+ 'brush'
+ );
+ let solidCount = 0;
+ for (let x = 25; x <= 215; x++) {
+ if (primaryOnlyCanvas.pixelBuffer[(48 * 256 + x) * 4 + 3] > 200) solidCount++;
+ }
+ expect(solidCount).toBeGreaterThan(185); // Nearly 100% solid bar
+
+ // Dual Brush (multiply) with independent secondary size=10, spacing=2.0 (~20px between 10px beads -> ~10px gaps!)
+ const dualMultCanvas = createRasterMockCanvas(256, 96);
+ renderCompleteStroke(
+ dualMultCanvas.getContext('2d'),
+ pts,
+ makeBaseBrushSettings({
+ size: 22,
+ spacing: 0.08,
+ hardness: 1.0,
+ flow: 1.0,
+ dualBrush: true,
+ dualBrushConfig: {
+ enabled: true,
+ compositeMode: 'multiply',
+ size: 10,
+ spacing: 2.0,
+ hardness: 1.0,
+ density: 1.0,
+ },
+ }),
+ 'brush'
+ );
+
+ // Count transitions between inked (alpha > 150) and carved gap (alpha < 20) along centerline y=48
+ let inkedPx = 0;
+ let gapPx = 0;
+ let transitions = 0;
+ let prevInked = false;
+ for (let x = 25; x <= 215; x++) {
+ const a = dualMultCanvas.pixelBuffer[(48 * 256 + x) * 4 + 3];
+ const isInked = a > 150;
+ if (isInked) inkedPx++;
+ else if (a < 20) gapPx++;
+ if (x > 25 && isInked !== prevInked) transitions++;
+ prevInked = isInked;
+ }
+
+ // Independent secondary cadence must produce multiple alternating inked beads and empty gaps!
+ expect(inkedPx).toBeGreaterThan(35);
+ expect(gapPx).toBeGreaterThan(35);
+ expect(transitions).toBeGreaterThanOrEqual(8);
+
+ // Verify secondary size=10 is narrower than primary size=22:
+ // At y=48+9=57 (inside primary radius 11, outside secondary radius 5), multiply must be 0!
+ let outerPrimaryAlpha = 0;
+ let outerDualAlpha = 0;
+ for (let x = 30; x <= 210; x += 2) {
+ outerPrimaryAlpha += primaryOnlyCanvas.pixelBuffer[(57 * 256 + x) * 4 + 3];
+ outerDualAlpha += dualMultCanvas.pixelBuffer[(57 * 256 + x) * 4 + 3];
+ }
+ expect(outerPrimaryAlpha).toBeGreaterThan(10000);
+ expect(outerDualAlpha).toBe(0);
+
+ // Dual Brush (subtract) with the exact same secondary cadence carves alternating holes along centerline
+ const dualSubCanvas = createRasterMockCanvas(256, 96);
+ renderCompleteStroke(
+ dualSubCanvas.getContext('2d'),
+ pts,
+ makeBaseBrushSettings({
+ size: 22,
+ spacing: 0.08,
+ hardness: 1.0,
+ flow: 1.0,
+ dualBrush: true,
+ dualBrushConfig: {
+ enabled: true,
+ compositeMode: 'subtract',
+ size: 10,
+ spacing: 2.0,
+ hardness: 1.0,
+ density: 1.0,
+ },
+ }),
+ 'brush'
+ );
+
+ let subInked = 0;
+ let subCarved = 0;
+ for (let x = 25; x <= 215; x++) {
+ const a = dualSubCanvas.pixelBuffer[(48 * 256 + x) * 4 + 3];
+ if (a > 150) subInked++;
+ else if (a < 20) subCarved++;
+ }
+ expect(subInked).toBeGreaterThan(35);
+ expect(subCarved).toBeGreaterThan(35);
+ });
+ });
+
+ describe('4. Dual Brush + colorMixing (SpatialTipMixer Parity)', () => {
+ it('executes both pigment mixing and two-pass Dual Brush modulation without silently dropping dualBrush', () => {
+ const w = 220;
+ const h = 96;
+ const bgCanvas = createRasterMockCanvas(w, h);
+ const bgCtx = bgCanvas.getContext('2d');
+ bgCtx.fillStyle = '#0000ff';
+ bgCtx.fillRect(0, 0, w, h);
+
+ // Stroke red (#ff0000) across blue background with colorMixing=true AND dualBrush=true (multiply, spaced beads)
+ const strokeCanvas = createRasterMockCanvas(w, h);
+ const pts = makeHorizontalStrokePoints(20, 200, 48, 20, 14);
+ const sampler = new LayerPixelSampler(bgCanvas);
+
+ renderCompleteStroke(
+ strokeCanvas.getContext('2d'),
+ pts,
+ makeBaseBrushSettings({
+ size: 20,
+ color: '#ff0000',
+ spacing: 0.1,
+ hardness: 1.0,
+ flow: 1.0,
+ colorMixing: true,
+ amountOfPaint: 0.55,
+ densityOfPaint: 0.9,
+ colorStretch: 0.7,
+ dualBrush: true,
+ dualBrushConfig: {
+ enabled: true,
+ compositeMode: 'multiply',
+ size: 10,
+ spacing: 2.0,
+ hardness: 1.0,
+ density: 1.0,
+ },
+ }),
+ 'brush',
+ 'color',
+ false,
+ bgCanvas,
+ false,
+ sampler
+ );
+
+ let mixedInkedCount = 0;
+ let carvedGapCount = 0;
+ let pickedUpBlueSum = 0;
+ for (let x = 25; x <= 195; x++) {
+ const i = (48 * w + x) * 4;
+ const r = strokeCanvas.pixelBuffer[i];
+ const b = strokeCanvas.pixelBuffer[i + 2];
+ const a = strokeCanvas.pixelBuffer[i + 3];
+ if (a > 100) {
+ mixedInkedCount++;
+ // Mixed red + blue canvas pigment must contain both red and blue channels!
+ if (r > 30 && b > 20) {
+ pickedUpBlueSum += b;
+ }
+ } else if (a < 15) {
+ carvedGapCount++;
+ }
+ }
+
+ // Dual Brush did NOT get dropped: alternating inked beads AND carved gaps exist
+ expect(mixedInkedCount).toBeGreaterThan(25);
+ expect(carvedGapCount).toBeGreaterThan(25);
+ // Color mixing actually mixed underlying blue canvas into the red brush pigment
+ expect(pickedUpBlueSum).toBeGreaterThan(500);
+ });
+ });
+
+ describe('5. WebGL Two-Pass Dispatch & Live Paired-Buffer Zero-Pop Parity', () => {
+ it('dispatches independent primaryDabs and secondaryDabs to WebGlBrushEngine.renderDualBrushDabsToContext', () => {
+ const gpu = WebGlBrushEngine.getInstance();
+ const availSpy = vi.spyOn(gpu, 'isAvailable').mockReturnValue(true);
+ let capturedPrimary: GpuDab[] = [];
+ let capturedSecondary: GpuDab[] = [];
+ let capturedMode: DualBrushCompositeMode | null = null;
+
+ const dualSpy = vi
+ .spyOn(gpu, 'renderDualBrushDabsToContext')
+ .mockImplementation(
+ (_ctx, primaryDabs, _pSettings, secondaryDabs, _sSettings, mode) => {
+ capturedPrimary = primaryDabs.slice();
+ capturedSecondary = secondaryDabs.slice();
+ capturedMode = mode;
+ return true;
+ }
+ );
+
+ try {
+ const targetCanvas = createRasterMockCanvas(256, 96);
+ const pts = makeHorizontalStrokePoints(20, 220, 48, 24, 12);
+ renderCompleteStroke(
+ targetCanvas.getContext('2d'),
+ pts,
+ makeBaseBrushSettings({
+ size: 24,
+ spacing: 0.1,
+ useGpu: true,
+ dualBrush: true,
+ dualBrushConfig: {
+ enabled: true,
+ compositeMode: 'height',
+ size: 12,
+ spacing: 1.5,
+ hardness: 0.8,
+ density: 0.9,
+ },
+ }),
+ 'brush'
+ );
+
+ expect(dualSpy).toHaveBeenCalledTimes(1);
+ expect(capturedMode).toBe('height');
+ // Primary spacing 0.1 on 24px over 200px (~83 dabs) vs secondary spacing 1.5 on 12px (~12 dabs)
+ expect(capturedPrimary.length).toBeGreaterThan(50);
+ expect(capturedSecondary.length).toBeGreaterThan(5);
+ expect(capturedSecondary.length).toBeLessThan(capturedPrimary.length * 0.3);
+ expect(capturedPrimary[0].width).toBeCloseTo(24, 1);
+ expect(capturedSecondary[0].width).toBeCloseTo(12, 1);
+ } finally {
+ availSpy.mockRestore();
+ dualSpy.mockRestore();
+ }
+ });
+
+ it('matches live paired draft buffers (syncDualBrushRegionToDraft) pixel-for-pixel with renderCompleteStroke', () => {
+ const w = 160;
+ const h = 80;
+ const bs = makeBaseBrushSettings({
+ size: 18,
+ spacing: 0.1,
+ hardness: 0.9,
+ flow: 0.9,
+ dualBrush: true,
+ dualBrushConfig: {
+ enabled: true,
+ compositeMode: 'linear-burn',
+ size: 12,
+ spacing: 1.4,
+ hardness: 0.8,
+ density: 0.85,
+ },
+ });
+ const pts = makeHorizontalStrokePoints(20, 140, 40, 18, 10);
+
+ // Reference: full two-pass renderCompleteStroke
+ const refCanvas = createRasterMockCanvas(w, h);
+ renderCompleteStroke(refCanvas.getContext('2d'), pts, bs, 'brush');
+
+ // Live paired buffers: Pass 1 -> dualPrimaryCanvas, Pass 2 -> dualSecondaryCanvas, sync -> draftCanvas
+ const draftCanvas = createRasterMockCanvas(w, h) as DraftCanvasElement;
+ draftCanvas.__draftScale = 1.0;
+ draftCanvas.__draftDocRect = { x: 0, y: 0, width: w, height: h };
+ const draftCtx = draftCanvas.getContext('2d')!;
+ const state = createInitialStrokeSessionState();
+ state.isDualBrushStroke = true;
+
+ const pair = prepareDualDraftCanvases(state, draftCanvas, { width: w, height: h }, null);
+ expect(pair).not.toBeNull();
+
+ const dualCfg = resolveDualBrushConfig(bs)!;
+ const secInfo = buildSecondaryBrushSettings(bs, dualCfg);
+ const secPts = scalePointsForSecondaryBrush(pts, secInfo.sizeRatio, secInfo.settings.size);
+
+ renderCompleteStroke(
+ pair!.primaryCtx,
+ pts,
+ { ...bs, dualBrush: false, dualBrushConfig: undefined },
+ 'brush'
+ );
+ renderCompleteStroke(pair!.secondaryCtx, secPts, secInfo.settings, 'brush');
+
+ syncDualBrushRegionToDraft(state, draftCanvas, draftCtx, bs, 0, 0, w, h);
+
+ // Zero visual pop: combined live draft matches renderCompleteStroke pixel-for-pixel!
+ let maxDiff = 0;
+ let nonZeroCount = 0;
+ for (let i = 0; i < refCanvas.pixelBuffer.length; i += 4) {
+ if (refCanvas.pixelBuffer[i + 3] > 0) nonZeroCount++;
+ for (let c = 0; c < 4; c++) {
+ const diff = Math.abs(refCanvas.pixelBuffer[i + c] - (draftCanvas as any).pixelBuffer[i + c]);
+ if (diff > maxDiff) maxDiff = diff;
+ }
+ }
+ expect(nonZeroCount).toBeGreaterThan(100);
+ expect(maxDiff).toBeLessThanOrEqual(1);
+ });
+ });
+});
diff --git a/src/utils/__tests__/hostModal.test.tsx b/src/utils/__tests__/hostModal.test.tsx
new file mode 100644
index 0000000..efbaa44
--- /dev/null
+++ b/src/utils/__tests__/hostModal.test.tsx
@@ -0,0 +1,429 @@
+import { act } from 'react';
+import { createRoot, Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { HostModal } from '../../components/HostModal';
+import { SettingsModal } from '../../components/SettingsModal';
+import { DEFAULT_APP_SETTINGS } from '../../types/settings';
+import type { CollabPeer } from '../../types/multiplayer';
+
+class TestTextNode {
+ public nodeType = 3;
+ public nodeName = '#text';
+ public parentNode: TestElement | null = null;
+ constructor(
+ public nodeValue: string,
+ public ownerDocument: TestDocument
+ ) {}
+}
+
+class TestElement extends EventTarget {
+ public nodeType = 1;
+ public nodeName: string;
+ public tagName: string;
+ public namespaceURI = 'http://www.w3.org/1999/xhtml';
+ public parentNode: TestElement | null = null;
+ public childNodes: Array<TestElement | TestTextNode> = [];
+ public style: Record<string, string> = {};
+ public attributes = new Map<string, string>();
+ public value = '';
+ public disabled = false;
+ public type = '';
+ public placeholder = '';
+ public className = '';
+
+ constructor(
+ tag: string,
+ public ownerDocument: TestDocument
+ ) {
+ super();
+ this.nodeName = tag.toUpperCase();
+ this.tagName = this.nodeName;
+ }
+
+ appendChild<T extends TestElement | TestTextNode>(child: T): T {
+ child.parentNode = this;
+ this.childNodes.push(child);
+ return child;
+ }
+
+ removeChild<T extends TestElement | TestTextNode>(child: T): T {
+ const idx = this.childNodes.indexOf(child);
+ if (idx >= 0) this.childNodes.splice(idx, 1);
+ child.parentNode = null;
+ return child;
+ }
+
+ insertBefore<T extends TestElement | TestTextNode>(child: T, ref: TestElement | TestTextNode | null): T {
+ child.parentNode = this;
+ const idx = ref ? this.childNodes.indexOf(ref) : -1;
+ if (idx >= 0) this.childNodes.splice(idx, 0, child);
+ else this.childNodes.push(child);
+ return child;
+ }
+
+ setAttribute(name: string, val: string) {
+ this.attributes.set(name, String(val));
+ if (name === 'placeholder') this.placeholder = String(val);
+ if (name === 'type') this.type = String(val);
+ if (name === 'value') this.value = String(val);
+ }
+
+ removeAttribute(name: string) {
+ this.attributes.delete(name);
+ }
+
+ getAttribute(name: string): string | null {
+ return this.attributes.has(name) ? this.attributes.get(name)! : null;
+ }
+
+ get textContent(): string {
+ return this.childNodes
+ .map((c) => (c instanceof TestTextNode ? c.nodeValue : c.textContent))
+ .join('');
+ }
+
+ set textContent(v: string) {
+ this.childNodes = [];
+ if (v) this.appendChild(new TestTextNode(v, this.ownerDocument));
+ }
+
+ override dispatchEvent(event: Event): boolean {
+ const path: EventTarget[] = [];
+ let cur: TestElement | null = this;
+ while (cur) {
+ path.push(cur);
+ cur = cur.parentNode;
+ }
+ path.push(this.ownerDocument);
+ if (this.ownerDocument.defaultView && this.ownerDocument.defaultView instanceof EventTarget) {
+ path.push(this.ownerDocument.defaultView);
+ }
+
+ Object.defineProperty(event, 'target', { value: this, configurable: true });
+ for (const node of path) {
+ Object.defineProperty(event, 'currentTarget', { value: node, configurable: true });
+ EventTarget.prototype.dispatchEvent.call(node, event);
+ if (event.cancelBubble) break;
+ }
+ return !event.defaultPrevented;
+ }
+}
+
+class TestDocument extends EventTarget {
+ public nodeType = 9;
+ public activeElement: TestElement | null = null;
+ public defaultView: unknown = null;
+ public documentElement: TestElement;
+ public body: TestElement;
+
+ constructor() {
+ super();
+ this.documentElement = new TestElement('html', this);
+ this.body = new TestElement('body', this);
+ this.documentElement.appendChild(this.body);
+ }
+
+ createElement(tag: string): TestElement {
+ return new TestElement(tag, this);
+ }
+
+ createElementNS(_ns: string, tag: string): TestElement {
+ return new TestElement(tag, this);
+ }
+
+ createTextNode(text: string): TestTextNode {
+ return new TestTextNode(text, this);
+ }
+
+ createComment(): TestTextNode {
+ return new TestTextNode('', this);
+ }
+}
+
+function findAll(root: TestElement, pred: (el: TestElement) => boolean): TestElement[] {
+ const out: TestElement[] = [];
+ const walk = (node: TestElement | TestTextNode) => {
+ if (node instanceof TestElement) {
+ if (pred(node)) out.push(node);
+ for (const child of node.childNodes) walk(child);
+ }
+ };
+ walk(root);
+ return out;
+}
+
+function findByTestId(root: TestElement, testId: string): TestElement | undefined {
+ return findAll(root, (el) => el.getAttribute('data-testid') === testId)[0];
+}
+
+function clickElement(el: TestElement) {
+ const ev = new Event('click', { bubbles: true, cancelable: true });
+ el.dispatchEvent(ev);
+}
+
+describe('HostModal WebRTC P2P default & hierarchy', () => {
+ const origWindow = (globalThis as any).window;
+ const origDocument = (globalThis as any).document;
+ const origHTMLElement = (globalThis as any).HTMLElement;
+ const origElement = (globalThis as any).Element;
+ const origNode = (globalThis as any).Node;
+ const origActEnv = (globalThis as any).IS_REACT_ACT_ENVIRONMENT;
+
+ let doc: TestDocument;
+ let container: TestElement;
+ let root: Root;
+
+ const basePeer: CollabPeer = {
+ id: 'peer-host-1',
+ name: 'Sora',
+ color: '#3b82f6',
+ role: 'host',
+ };
+
+ beforeEach(() => {
+ doc = new TestDocument();
+ const win: any = new EventTarget();
+ win.document = doc;
+ doc.defaultView = win;
+ class HTMLIFrameElementShim extends TestElement {}
+ win.HTMLElement = TestElement;
+ win.HTMLIFrameElement = HTMLIFrameElementShim;
+ win.Element = TestElement;
+ win.Node = TestElement;
+ win.navigator = {};
+ (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+ (globalThis as any).window = win;
+ (globalThis as any).document = doc;
+ (globalThis as any).HTMLElement = TestElement;
+ (globalThis as any).HTMLIFrameElement = HTMLIFrameElementShim;
+ (globalThis as any).Element = TestElement;
+ (globalThis as any).Node = TestElement;
+
+ container = doc.createElement('div');
+ doc.body.appendChild(container);
+ root = createRoot(container as unknown as HTMLElement);
+ });
+
+ afterEach(async () => {
+ await act(async () => {
+ root.unmount();
+ });
+ (globalThis as any).window = origWindow;
+ (globalThis as any).document = origDocument;
+ (globalThis as any).HTMLElement = origHTMLElement;
+ (globalThis as any).Element = origElement;
+ (globalThis as any).Node = origNode;
+ (globalThis as any).IS_REACT_ACT_ENVIRONMENT = origActEnv;
+ });
+
+ it('defaults to Worldwide P2P (Room Code) on open, orders cards P2P-first, and calls onStartWebRtcHosting', async () => {
+ const onStartHosting = vi.fn().mockResolvedValue({});
+ const onStartWebRtcHosting = vi.fn().mockResolvedValue({});
+
+ await act(async () => {
+ root.render(
+ <HostModal
+ isOpen={true}
+ onClose={vi.fn()}
+ isHost={false}
+ isConnected={false}
+ hostInfo={null}
+ peers={[]}
+ myPeer={basePeer}
+ onUpdateMyName={vi.fn()}
+ onStartHosting={onStartHosting}
+ onStartWebRtcHosting={onStartWebRtcHosting}
+ onStopHosting={vi.fn()}
+ onJoinByInviteUrl={vi.fn().mockResolvedValue(true)}
+ onLeaveRoom={vi.fn()}
+ showToast={vi.fn()}
+ />
+ );
+ });
+
+ const p2pBtn = findByTestId(container, 'host-mode-p2p-btn');
+ const tunnelBtn = findByTestId(container, 'host-mode-tunnel-btn');
+ const lanBtn = findByTestId(container, 'host-mode-lan-btn');
+ const startBtn = findByTestId(container, 'host-start-btn');
+
+ expect(p2pBtn).toBeDefined();
+ expect(tunnelBtn).toBeDefined();
+ expect(lanBtn).toBeDefined();
+ expect(startBtn).toBeDefined();
+
+ // P2P is selected by default
+ expect(p2pBtn!.getAttribute('aria-pressed')).toBe('true');
+ expect(tunnelBtn!.getAttribute('aria-pressed')).toBe('false');
+ expect(lanBtn!.getAttribute('aria-pressed')).toBe('false');
+
+ // Hierarchy & labels
+ expect(p2pBtn!.textContent).toContain('Worldwide P2P (Room Code)');
+ expect(p2pBtn!.textContent).toContain('Recommended');
+ expect(p2pBtn!.textContent).toContain(
+ 'Fast direct INK-XXXX code for PC & Android tablets · No setup'
+ );
+ expect(tunnelBtn!.textContent).toContain('Web Link (Cloudflare Tunnel)');
+ expect(tunnelBtn!.textContent).toContain('Browser guests & up to 16 peers');
+ expect(lanBtn!.textContent).toContain('Local Network (LAN)');
+ expect(lanBtn!.textContent).toContain('Same Wi-Fi network');
+
+ // Full text ordering: P2P card comes above Tunnel and LAN
+ const fullText = container.textContent;
+ expect(fullText.indexOf('Worldwide P2P (Room Code)')).toBeLessThan(
+ fullText.indexOf('Web Link (Cloudflare Tunnel)')
+ );
+ expect(fullText.indexOf('Web Link (Cloudflare Tunnel)')).toBeLessThan(
+ fullText.indexOf('Local Network (LAN)')
+ );
+
+ // Primary CTA for P2P
+ expect(startBtn!.textContent).toContain('Start Room & Copy Code');
+
+ // Clicking CTA triggers WebRTC P2P hosting, not Cloudflare Tunnel
+ await act(async () => {
+ clickElement(startBtn!);
+ });
+ expect(onStartWebRtcHosting).toHaveBeenCalledTimes(1);
+ expect(onStartHosting).not.toHaveBeenCalled();
+ });
+
+ it('switches CTA when choosing Cloudflare Tunnel and resets back to P2P whenever re-opened', async () => {
+ const props = {
+ onClose: vi.fn(),
+ isHost: false,
+ isConnected: false,
+ hostInfo: null,
+ peers: [],
+ myPeer: basePeer,
+ onUpdateMyName: vi.fn(),
+ onStartHosting: vi.fn().mockResolvedValue({}),
+ onStartWebRtcHosting: vi.fn().mockResolvedValue({}),
+ onStopHosting: vi.fn(),
+ onJoinByInviteUrl: vi.fn().mockResolvedValue(true),
+ onLeaveRoom: vi.fn(),
+ showToast: vi.fn(),
+ };
+
+ await act(async () => {
+ root.render(<HostModal {...props} isOpen={true} />);
+ });
+
+ // Switch to Cloudflare Tunnel
+ const tunnelBtn = findByTestId(container, 'host-mode-tunnel-btn')!;
+ await act(async () => {
+ clickElement(tunnelBtn);
+ });
+ expect(findByTestId(container, 'host-mode-tunnel-btn')!.getAttribute('aria-pressed')).toBe('true');
+ expect(findByTestId(container, 'host-start-btn')!.textContent).toContain(
+ 'Start Server & Copy Link'
+ );
+
+ // Close and re-open -> resets to P2P default
+ await act(async () => {
+ root.render(<HostModal {...props} isOpen={false} />);
+ });
+ await act(async () => {
+ root.render(<HostModal {...props} isOpen={true} />);
+ });
+ expect(findByTestId(container, 'host-mode-p2p-btn')!.getAttribute('aria-pressed')).toBe('true');
+ expect(findByTestId(container, 'host-start-btn')!.textContent).toContain(
+ 'Start Room & Copy Code'
+ );
+ });
+
+ it('prioritizes Room Code label and placeholder in the Join Room tab', async () => {
+ await act(async () => {
+ root.render(
+ <HostModal
+ isOpen={true}
+ onClose={vi.fn()}
+ isHost={false}
+ isConnected={false}
+ hostInfo={null}
+ peers={[]}
+ myPeer={basePeer}
+ onUpdateMyName={vi.fn()}
+ onStartHosting={vi.fn().mockResolvedValue({})}
+ onStartWebRtcHosting={vi.fn().mockResolvedValue({})}
+ onStopHosting={vi.fn()}
+ onJoinByInviteUrl={vi.fn().mockResolvedValue(true)}
+ onLeaveRoom={vi.fn()}
+ showToast={vi.fn()}
+ />
+ );
+ });
+
+ const joinTabBtn = findAll(
+ container,
+ (el) => el.tagName === 'BUTTON' && el.textContent.trim() === 'Join Room'
+ )[0];
+ expect(joinTabBtn).toBeDefined();
+
+ await act(async () => {
+ clickElement(joinTabBtn);
+ });
+
+ expect(container.textContent).toContain('Room Code (INK-XXXX...) or Invite Link');
+ const input = findByTestId(container, 'join-target-input');
+ expect(input).toBeDefined();
+ expect(input!.placeholder).toContain('INK-7429-K8P2M9');
+ expect(input!.placeholder).toContain('trycloudflare.com');
+ });
+
+ it('exposes Collaboration settings tab in SettingsModal with signaling & TURN controls and Reset', async () => {
+ const onUpdateSettings = vi.fn();
+ const onShowToast = vi.fn();
+
+ await act(async () => {
+ root.render(
+ <SettingsModal
+ isOpen={true}
+ onClose={vi.fn()}
+ settings={{
+ ...DEFAULT_APP_SETTINGS,
+ collabSignalingUrl: 'wss://sig.example.workers.dev/signal',
+ collabTurnUrl: 'turns:turn.example.com:5349',
+ collabTurnUsername: 'sora',
+ collabTurnCredential: 'pw',
+ }}
+ onUpdateSettings={onUpdateSettings}
+ onShowToast={onShowToast}
+ />
+ );
+ });
+
+ const collabTabBtn = findAll(
+ container,
+ (el) => el.tagName === 'BUTTON' && el.textContent.trim() === 'Collaboration'
+ )[0];
+ expect(collabTabBtn).toBeDefined();
+
+ await act(async () => {
+ clickElement(collabTabBtn);
+ });
+
+ expect(findByTestId(container, 'settings-collab-nickname')).toBeDefined();
+ expect(findByTestId(container, 'settings-collab-signaling-url')?.value).toBe(
+ 'wss://sig.example.workers.dev/signal'
+ );
+ expect(findByTestId(container, 'settings-collab-turn-url')?.value).toBe(
+ 'turns:turn.example.com:5349'
+ );
+ expect(findByTestId(container, 'settings-collab-turn-username')?.value).toBe('sora');
+ expect(findByTestId(container, 'settings-collab-turn-credential')?.value).toBe('pw');
+
+ const resetBtn = findByTestId(container, 'settings-collab-reset-btn')!;
+ await act(async () => {
+ clickElement(resetBtn);
+ });
+
+ expect(onUpdateSettings).toHaveBeenCalledWith(
+ expect.objectContaining({
+ collabSignalingUrl: '',
+ collabTurnUrl: '',
+ collabTurnUsername: '',
+ collabTurnCredential: '',
+ })
+ );
+ });
+});
diff --git a/src/utils/__tests__/naturalPaintEngine.test.ts b/src/utils/__tests__/naturalPaintEngine.test.ts
index 4bcf6e3..4d6f041 100644
--- a/src/utils/__tests__/naturalPaintEngine.test.ts
+++ b/src/utils/__tests__/naturalPaintEngine.test.ts
@@ -690,7 +690,9 @@ describe('Natural Paint Engine — Bristles, Spatial Mixing, Surface Textures &
engineMid.emitCubicSegment(strokePts[0], strokePts[1], strokePts[2], strokePts[3], samplerMid);
// Green dominates both red and blue (subtractive Yellow+Blue = Green, not swallowed into pure blue)
- expect(engineMid.reservoir.g[midBristle]).toBeGreaterThan(120);
+ expect(engineMid.reservoir.g[midBristle]).toBeGreaterThan(100);
+ expect(engineMid.reservoir.g[midBristle]).toBeGreaterThan(engineMid.reservoir.r[midBristle] + 35);
+ expect(engineMid.reservoir.g[midBristle]).toBeGreaterThan(engineMid.reservoir.b[midBristle] + 10);
expect(engineMid.reservoir.b[midBristle]).toBeLessThan(150);
});
});
diff --git a/src/utils/__tests__/pigmentBlending.test.ts b/src/utils/__tests__/pigmentBlending.test.ts
index da6637c..d941018 100644
--- a/src/utils/__tests__/pigmentBlending.test.ts
+++ b/src/utils/__tests__/pigmentBlending.test.ts
@@ -1,10 +1,16 @@
import { describe, it, expect } from 'vitest';
import {
+ LayerPixelSampler,
+ PaintReservoir,
mixSubtractivePigments,
mixPigmentsWithStrength,
mixPigmentRgbOut,
parseColorToRgb,
} from '../colorMixingEngine';
+import {
+ buildPigmentLutRgba,
+ encodePigmentOverWhiteOut,
+} from '../pigmentEngine';
import {
DEFAULT_RETOUCH_SETTINGS,
applyRetouchStrokeSegment,
@@ -38,59 +44,106 @@ function fillRectRgba(
grid.writeImageData(layerId, { data, width: w, height: h }, x, y, 'color-32bit', true);
}
-describe('7-Band Spectral Kubelka-Munk Pigment Blending', () => {
- it('mixes Blue + Yellow into vibrant Green (vs dull gray in Regular RGB)', () => {
- const blue = { r: 0, g: 136, b: 255 };
- const yellow = { r: 255, g: 244, b: 0 };
+function compositeOverWhite(px: readonly [number, number, number, number]): [number, number, number] {
+ const a = px[3] / 255;
+ const inv = 1 - a;
+ return [
+ Math.round(px[0] * a + 255 * inv),
+ Math.round(px[1] * a + 255 * inv),
+ Math.round(px[2] * a + 255 * inv),
+ ];
+}
- const pigment = mixSubtractivePigments(blue, yellow, 0.5);
- const regular = mixPigmentsWithStrength(blue, yellow, 0.5, 0);
+describe('Physical Kubelka-Munk Pigment Blending Engine', () => {
+ it('mixes Cobalt Blue + Hansa Yellow and Cyan-Blue + Yellow into vibrant Green (vs muddy gray/olive in Regular RGB)', () => {
+ const pairs = [
+ { blue: { r: 0, g: 33, b: 133 }, yellow: { r: 252, g: 211, b: 0 } },
+ { blue: { r: 0, g: 136, b: 255 }, yellow: { r: 255, g: 244, b: 0 } },
+ ];
- // Regular RGB collapses toward gray-olive (r ≈ b ≈ 128)
- expect(Math.abs(regular.r - regular.b)).toBeLessThan(2);
+ for (const { blue, yellow } of pairs) {
+ const pigment = mixSubtractivePigments(blue, yellow, 0.5);
+ const regular = mixPigmentsWithStrength(blue, yellow, 0.5, 0);
- // Spectral pigment produces clearly green-dominant emerald hue
- expect(pigment.g).toBeGreaterThan(pigment.r + 50);
- expect(pigment.g).toBeGreaterThan(pigment.b + 50);
+ const pigGreenDom = pigment.g - Math.max(pigment.r, pigment.b);
+ const regGreenDom = regular.g - Math.max(regular.r, regular.b);
+ expect(pigGreenDom).toBeGreaterThan(55);
+ expect(pigGreenDom).toBeGreaterThan(regGreenDom + 45);
+ }
});
- it('mixes Green + Magenta into warm golden-amber instead of muddy gray', () => {
- const green = { r: 40, g: 255, b: 0 };
- const magenta = { r: 255, g: 0, b: 170 };
+ it('dilutes dark pigments over white into luminous cerulean, rose-magenta, turquoise, royal blue & violet (vs dull slate/gray in Regular RGB)', () => {
+ const white = { r: 255, g: 255, b: 255 };
+
+ // Phthalo Blue + White -> electric cerulean blue
+ const phthaloBlue = { r: 13, g: 27, b: 68 };
+ const pbPig = mixSubtractivePigments(phthaloBlue, white, 0.5);
+ const pbReg = mixPigmentsWithStrength(phthaloBlue, white, 0.5, 0);
+ expect(pbPig.b - pbPig.r).toBeGreaterThan(130);
+ expect(pbPig.g - pbPig.r).toBeGreaterThan(60);
+ expect(pbReg.b - pbReg.r).toBeLessThan(35);
+
+ // Quinacridone Magenta + White -> vivid rose-magenta
+ const quinMagenta = { r: 128, g: 2, b: 46 };
+ const qmPig = mixSubtractivePigments(quinMagenta, white, 0.5);
+ const qmReg = mixPigmentsWithStrength(quinMagenta, white, 0.5, 0);
+ expect(qmPig.r - qmPig.g).toBeGreaterThan(100);
+ expect(qmPig.b - qmPig.g).toBeGreaterThan(55);
+ expect(qmReg.b - qmReg.g).toBeLessThan(30);
+
+ // Phthalo Green + White -> vibrant turquoise-teal
+ const phthaloGreen = { r: 0, g: 60, b: 50 };
+ const pgPig = mixSubtractivePigments(phthaloGreen, white, 0.5);
+ const pgReg = mixPigmentsWithStrength(phthaloGreen, white, 0.5, 0);
+ expect(pgPig.g - pgPig.r).toBeGreaterThan(65);
+ expect(pgPig.b - pgPig.r).toBeGreaterThan(60);
+ expect(pgReg.g - pgReg.r).toBeLessThan(35);
- const pigment = mixSubtractivePigments(green, magenta, 0.5);
+ // Ultramarine + White -> electric royal blue
+ const ultramarine = { r: 25, g: 0, b: 89 };
+ const umPig = mixSubtractivePigments(ultramarine, white, 0.5);
+ expect(umPig.b - umPig.r).toBeGreaterThan(110);
- // Warm golden-amber: red & green strongly exceed blue
- expect(pigment.r).toBeGreaterThan(pigment.b + 70);
- expect(pigment.g).toBeGreaterThan(pigment.b + 50);
+ // Cobalt Violet + White -> vibrant magenta-violet
+ const cobaltViolet = { r: 78, g: 0, b: 66 };
+ const cvPig = mixSubtractivePigments(cobaltViolet, white, 0.5);
+ expect(cvPig.r - cvPig.g).toBeGreaterThan(75);
+ expect(cvPig.b - cvPig.g).toBeGreaterThan(75);
});
- it('mixes Red + Yellow into vibrant Orange and Red + Blue into rich Violet', () => {
+ it('mixes Green + Magenta into warm amber-ochre and Red + Yellow/Blue into Orange and Violet', () => {
+ const green = { r: 40, g: 255, b: 0 };
+ const magenta = { r: 255, g: 0, b: 170 };
+ const amber = mixSubtractivePigments(green, magenta, 0.5);
+ expect(amber.r).toBeGreaterThan(amber.b + 70);
+ expect(amber.g).toBeGreaterThan(amber.b + 35);
+
const red = { r: 235, g: 20, b: 20 };
const yellow = { r: 255, g: 240, b: 0 };
const blue = { r: 15, g: 60, b: 240 };
const orange = mixSubtractivePigments(red, yellow, 0.5);
expect(orange.r).toBeGreaterThan(220);
- expect(orange.g).toBeGreaterThan(110);
- expect(orange.b).toBeLessThan(30);
+ expect(orange.g).toBeGreaterThan(100);
+ expect(orange.g).toBeGreaterThan(orange.b + 55);
+ expect(orange.b).toBeLessThan(45);
const violet = mixSubtractivePigments(red, blue, 0.5);
- expect(violet.r).toBeGreaterThan(violet.g + 60);
- expect(violet.b).toBeGreaterThan(violet.g + 60);
+ expect(violet.r).toBeGreaterThan(violet.g + 55);
+ expect(violet.b).toBeGreaterThan(violet.g + 55);
});
- it('keeps Black + White strictly neutral gray and preserves exact self-mix invariance', () => {
+ it('keeps Black + White strictly neutral gray, preserves self-mix invariance, and returns exact RGB at strength=0', () => {
const gray50 = mixSubtractivePigments({ r: 0, g: 0, b: 0 }, { r: 255, g: 255, b: 255 }, 0.5);
expect(Math.abs(gray50.r - gray50.g)).toBeLessThan(1.5);
expect(Math.abs(gray50.g - gray50.b)).toBeLessThan(1.5);
const testColors = [
- { r: 0, g: 136, b: 255 },
- { r: 255, g: 244, b: 0 },
- { r: 40, g: 255, b: 0 },
- { r: 255, g: 0, b: 170 },
- { r: 155, g: 0, b: 255 },
+ { r: 0, g: 33, b: 133 },
+ { r: 252, g: 211, b: 0 },
+ { r: 13, g: 27, b: 68 },
+ { r: 128, g: 2, b: 46 },
+ { r: 0, g: 60, b: 50 },
{ r: 0, g: 0, b: 0 },
{ r: 255, g: 255, b: 255 },
];
@@ -101,14 +154,186 @@ describe('7-Band Spectral Kubelka-Munk Pigment Blending', () => {
expect(Math.abs(out.g - c.g)).toBeLessThan(1.5);
expect(Math.abs(out.b - c.b)).toBeLessThan(1.5);
}
+
+ // Strength 0 reproduces exact linear RGB
+ mixPigmentRgbOut(0, 33, 133, 252, 211, 0, 0.5, 0, out);
+ expect(out.r).toBeCloseTo(126, 0);
+ expect(out.g).toBeCloseTo(122, 0);
+ expect(out.b).toBeCloseTo(66.5, 0);
+ });
+
+ it('encodePigmentOverWhiteOut reconstructs exact physical pigment dilution over white across alphas', () => {
+ const darkPigments = [
+ [13, 27, 68],
+ [128, 2, 46],
+ [0, 60, 50],
+ [25, 0, 89],
+ ] as const;
+ const enc: [number, number, number, number] = [0, 0, 0, 0];
+
+ for (const [r, g, b] of darkPigments) {
+ for (const alpha of [0.15, 0.35, 0.5, 0.75]) {
+ const expected = mixSubtractivePigments({ r: 255, g: 255, b: 255 }, { r, g, b }, alpha);
+ encodePigmentOverWhiteOut(r, g, b, alpha, 1.0, enc);
+ const [vr, vg, vb] = compositeOverWhite(enc);
+ expect(Math.abs(vr - expected.r)).toBeLessThanOrEqual(2);
+ expect(Math.abs(vg - expected.g)).toBeLessThanOrEqual(2);
+ expect(Math.abs(vb - expected.b)).toBeLessThanOrEqual(2);
+ }
+ }
+ });
+
+ it('buildPigmentLutRgba generates a valid 512x512 RGBA8 GPU concentration lookup table', () => {
+ const rgba = buildPigmentLutRgba();
+ expect(rgba.length).toBe(512 * 512 * 4);
+ // Blue corner (r=0, g=0, b=63) sits at slice 63 (tile x=7*64, y=7*64)
+ const blueCornerIdx = ((7 * 64 + 0) * 512 + (7 * 64 + 0)) * 4;
+ expect(rgba[blueCornerIdx]).toBeGreaterThan(150); // high c0 (blue pigment)
+ expect(rgba[blueCornerIdx + 3]).toBe(255);
+ });
+
+ it('compositeStrokeToTiles blends glazing strokes in pigment space and supports Regular vs Pigment on the same layer', () => {
+ const grid = new SparseTileGrid();
+ const layerId = 'layer-glaze';
+
+ // 1. Opaque Cobalt Blue base on left & right; glaze 50% Hansa Yellow over both
+ fillRectRgba(grid, layerId, 0, 0, 64, 32, 0, 33, 133, 255);
+ const yellowDab = new Uint8ClampedArray(20 * 20 * 4);
+ for (let i = 0; i < yellowDab.length; i += 4) {
+ yellowDab[i] = 252;
+ yellowDab[i + 1] = 211;
+ yellowDab[i + 2] = 0;
+ yellowDab[i + 3] = 255;
+ }
+
+ // Left: Regular RGB (pigmentStrength = 0)
+ grid.compositeStrokeToTiles({
+ layerId,
+ strokeData: { data: yellowDab, width: 20, height: 20 },
+ destX: 4,
+ destY: 4,
+ format: 'color-32bit',
+ compositeOp: 'source-over',
+ opacity: 0.5,
+ pigmentStrength: 0,
+ pigmentWhiteGround: true,
+ });
+ // Right: Pigment (pigmentStrength = 1.0)
+ grid.compositeStrokeToTiles({
+ layerId,
+ strokeData: { data: yellowDab, width: 20, height: 20 },
+ destX: 36,
+ destY: 4,
+ format: 'color-32bit',
+ compositeOp: 'source-over',
+ opacity: 0.5,
+ pigmentStrength: 1.0,
+ pigmentWhiteGround: true,
+ });
+
+ const regPx = grid.getPixelRGBA(layerId, 12, 12);
+ const pigPx = grid.getPixelRGBA(layerId, 44, 12);
+ const regGreenDom = regPx[1] - Math.max(regPx[0], regPx[2]);
+ const pigGreenDom = pigPx[1] - Math.max(pigPx[0], pigPx[2]);
+ expect(regGreenDom).toBeLessThan(10); // muddy olive-gray in regular RGB
+ expect(pigGreenDom).toBeGreaterThan(60); // vibrant green in pigment mode
+
+ // 2. Transparent region over white paper: 50% Phthalo Blue (Regular left vs Pigment right)
+ const navyDab = new Uint8ClampedArray(20 * 20 * 4);
+ for (let i = 0; i < navyDab.length; i += 4) {
+ navyDab[i] = 13;
+ navyDab[i + 1] = 27;
+ navyDab[i + 2] = 68;
+ navyDab[i + 3] = 255;
+ }
+ grid.compositeStrokeToTiles({
+ layerId,
+ strokeData: { data: navyDab, width: 20, height: 20 },
+ destX: 4,
+ destY: 60,
+ format: 'color-32bit',
+ compositeOp: 'source-over',
+ opacity: 0.5,
+ pigmentStrength: 0,
+ pigmentWhiteGround: true,
+ });
+ grid.compositeStrokeToTiles({
+ layerId,
+ strokeData: { data: navyDab, width: 20, height: 20 },
+ destX: 36,
+ destY: 60,
+ format: 'color-32bit',
+ compositeOp: 'source-over',
+ opacity: 0.5,
+ pigmentStrength: 1.0,
+ pigmentWhiteGround: true,
+ });
+
+ const regOverWhite = compositeOverWhite(grid.getPixelRGBA(layerId, 12, 68));
+ const pigOverWhite = compositeOverWhite(grid.getPixelRGBA(layerId, 44, 68));
+ expect(regOverWhite[2] - regOverWhite[0]).toBeLessThan(35); // slate gray
+ expect(pigOverWhite[2] - pigOverWhite[0]).toBeGreaterThan(130); // luminous cerulean
+
+ // 3. Multi-pass translucent layering over transparent white paper (two 25% passes of Phthalo Blue)
+ for (let pass = 0; pass < 2; pass++) {
+ grid.compositeStrokeToTiles({
+ layerId,
+ strokeData: { data: navyDab, width: 20, height: 20 },
+ destX: 36,
+ destY: 96,
+ format: 'color-32bit',
+ compositeOp: 'source-over',
+ opacity: 0.25,
+ pigmentStrength: 1.0,
+ pigmentWhiteGround: true,
+ });
+ }
+ const twoPassOverWhite = compositeOverWhite(grid.getPixelRGBA(layerId, 44, 104));
+ expect(twoPassOverWhite[2] - twoPassOverWhite[0]).toBeGreaterThan(130); // stays electric cerulean across passes
});
- it('Retouch Smudge produces vibrant Green when blending Blue into Yellow with Pigment Blending enabled', () => {
+ it('LayerPixelSampler and PaintReservoir average and mix Blue | Yellow in pigment latent space (vs muddy gray in Regular mode)', () => {
+ const grid = new SparseTileGrid();
+ const layerId = 'layer-sampler-pigment';
+ fillRectRgba(grid, layerId, 0, 0, 64, 128, 0, 33, 133, 255);
+ fillRectRgba(grid, layerId, 64, 0, 64, 128, 252, 211, 0, 255);
+
+ const sampler = new LayerPixelSampler({ width: 128, height: 128 }, layerId, grid);
+
+ // 1. Neighborhood sampling across the Blue | Yellow seam
+ const pigSample = sampler.sampleColor(64, 64, 16, true);
+ const regSample = sampler.sampleColor(64, 64, 16, false);
+ const pigSampleGreen = pigSample.g - Math.max(pigSample.r, pigSample.b);
+ const regSampleGreen = regSample.g - Math.max(regSample.r, regSample.b);
+ expect(pigSampleGreen).toBeGreaterThan(50);
+ expect(pigSampleGreen).toBeGreaterThan(regSampleGreen + 40);
+
+ // 2. PaintReservoir mixing Yellow brush over Blue canvas across stroke travel
+ const pigRes = new PaintReservoir('#fcd300');
+ const regRes = new PaintReservoir('#fcd300');
+ const blueCanvas = { r: 0, g: 33, b: 133, a: 1 };
+ let pigMixed = pigRes.mixWithCanvas(blueCanvas, 0.35, 0.7, 0.7, 'blend', 0.6, 0.85, 8, true, false, 1.0);
+ let regMixed = regRes.mixWithCanvas(blueCanvas, 0.35, 0.7, 0.7, 'blend', 0.6, 0.85, 8, false, false, 0.0);
+ for (let step = 0; step < 5; step++) {
+ pigMixed = pigRes.mixWithCanvas(blueCanvas, 0.35, 0.7, 0.7, 'blend', 0.6, 0.85, 8, true, false, 1.0);
+ regMixed = regRes.mixWithCanvas(blueCanvas, 0.35, 0.7, 0.7, 'blend', 0.6, 0.85, 8, false, false, 0.0);
+ }
+ const pigResGreen = pigMixed.g - Math.max(pigMixed.r, pigMixed.b);
+ const regResGreen = regMixed.g - Math.max(regMixed.r, regMixed.b);
+ expect(pigResGreen).toBeGreaterThan(55);
+ expect(pigResGreen).toBeGreaterThan(regResGreen + 45);
+
+ // 3. depositDab updates in-memory sampler in pigment space
+ sampler.depositDab(20, 20, 8, 252, 211, 0, 0.5, 1.0);
+ const deposited = sampler.sampleColor(20, 20, 2, true);
+ expect(deposited.g - Math.max(deposited.r, deposited.b)).toBeGreaterThan(45);
+ });
+
+ it('Retouch Smudge produces vibrant Green across Blue|Yellow and luminous Cerulean when dragging Phthalo Blue onto transparent white paper', () => {
const runSmudge = (pigmentBlending: boolean) => {
const grid = new SparseTileGrid();
const dims = { width: 128, height: 128 };
const layerId = 'layer-pigment-smudge';
- // Left half: Blue, Right half: Yellow
fillRectRgba(grid, layerId, 0, 0, 64, 128, 0, 120, 255, 255);
fillRectRgba(grid, layerId, 64, 0, 64, 128, 255, 240, 0, 255);
@@ -134,7 +359,6 @@ describe('7-Band Spectral Kubelka-Munk Pigment Blending', () => {
applyRetouchStrokeSegment({ grid, session, pt: { x: 48, y: 64 }, pressure: 1, settings, primaryColor: '#000000' });
applyRetouchStrokeSegment({ grid, session, pt: { x: 76, y: 64 }, pressure: 1, settings, primaryColor: '#000000' });
- // Peak green dominance across the smudged Blue -> Yellow transition zone (x = 64..90)
let maxGreenDom = -999;
for (let x = 64; x <= 90; x++) {
const px = grid.getPixelRGBA(layerId, x, 64);
@@ -146,13 +370,57 @@ describe('7-Band Spectral Kubelka-Munk Pigment Blending', () => {
const pigGreenDom = runSmudge(true);
const regGreenDom = runSmudge(false);
-
- // Pigment smudge pushes vibrant green well above regular RGB smudge
expect(pigGreenDom).toBeGreaterThan(40);
expect(pigGreenDom).toBeGreaterThan(regGreenDom + 25);
+
+ // Dragging dark Phthalo Blue into empty transparent pixels over white ground
+ const runDarkSmudgeToWhite = (pigmentBlending: boolean) => {
+ const grid = new SparseTileGrid();
+ const dims = { width: 128, height: 128 };
+ const layerId = 'layer-navy-smudge';
+ fillRectRgba(grid, layerId, 0, 0, 48, 128, 13, 27, 68, 255);
+
+ const session = createRetouchStrokeSession({
+ mode: 'smudge',
+ layerId,
+ targetFormat: 'color-32bit',
+ alphaLock: false,
+ pigmentWhiteGround: true,
+ dimensions: dims,
+ selectionMask: null,
+ });
+ const settings = {
+ ...DEFAULT_RETOUCH_SETTINGS,
+ mode: 'smudge' as const,
+ size: 30,
+ strength: 65,
+ hardness: 60,
+ usePressure: false,
+ pigmentBlending,
+ pigmentStrength: 100,
+ };
+
+ applyRetouchStrokeSegment({ grid, session, pt: { x: 32, y: 64 }, pressure: 1, settings, primaryColor: '#000000' });
+ applyRetouchStrokeSegment({ grid, session, pt: { x: 74, y: 64 }, pressure: 1, settings, primaryColor: '#000000' });
+
+ let maxBlueChroma = 0;
+ for (let x = 50; x <= 74; x++) {
+ const px = grid.getPixelRGBA(layerId, x, 64);
+ if (px[3] > 20 && px[3] < 240) {
+ const [vr, , vb] = compositeOverWhite(px);
+ maxBlueChroma = Math.max(maxBlueChroma, vb - vr);
+ }
+ }
+ return maxBlueChroma;
+ };
+
+ const pigCerulean = runDarkSmudgeToWhite(true);
+ const regSlate = runDarkSmudgeToWhite(false);
+ expect(pigCerulean).toBeGreaterThan(100);
+ expect(pigCerulean).toBeGreaterThan(regSlate + 60);
});
- it('Retouch Blur produces Green across a Blue | Yellow seam when Pigment Blending is enabled', () => {
+ it('Retouch Blur produces vibrant Green across a Blue | Yellow seam via 7-channel pigment latent convolution', () => {
const runBlur = (pigmentBlending: boolean) => {
const grid = new SparseTileGrid();
const dims = { width: 128, height: 128 };
@@ -188,8 +456,8 @@ describe('7-Band Spectral Kubelka-Munk Pigment Blending', () => {
const pigGreenDom = pigPx[1] - Math.max(pigPx[0], pigPx[2]);
const regGreenDom = regPx[1] - Math.max(regPx[0], regPx[2]);
- expect(pigGreenDom).toBeGreaterThan(35);
- expect(pigGreenDom).toBeGreaterThan(regGreenDom + 25);
+ expect(pigGreenDom).toBeGreaterThan(45);
+ expect(pigGreenDom).toBeGreaterThan(regGreenDom + 35);
});
it('Gradient stop sampling blends Blue -> Yellow through Green when pigmentBlending is enabled', () => {
@@ -209,11 +477,10 @@ describe('7-Band Spectral Kubelka-Munk Pigment Blending', () => {
});
it('PigmentBlendControl preview gradient visually distinguishes Regular vs Pigment midpoints', () => {
- const regGrad = buildPigmentPreviewGradient('#0084ff', '#fff000', false, 1.0);
- const pigGrad = buildPigmentPreviewGradient('#0084ff', '#fff000', true, 1.0);
+ const regGrad = buildPigmentPreviewGradient('#002185', '#fcd300', false, 1.0);
+ const pigGrad = buildPigmentPreviewGradient('#002185', '#fcd300', true, 1.0);
expect(regGrad).not.toBe(pigGrad);
- // Extract the 50% stop hex from both CSS gradients
const regMidMatch = regGrad.match(/(#[0-9a-f]{6}) 50%/i);
const pigMidMatch = pigGrad.match(/(#[0-9a-f]{6}) 50%/i);
expect(regMidMatch).toBeTruthy();
@@ -222,7 +489,7 @@ describe('7-Band Spectral Kubelka-Munk Pigment Blending', () => {
const regMid = parseColorToRgb(regMidMatch![1]);
const pigMid = parseColorToRgb(pigMidMatch![1]);
expect(pigMid.g - Math.max(pigMid.r, pigMid.b)).toBeGreaterThan(
- regMid.g - Math.max(regMid.r, regMid.b) + 30
+ regMid.g - Math.max(regMid.r, regMid.b) + 45
);
});
});
diff --git a/src/utils/__tests__/ribbonBrushEngine.test.ts b/src/utils/__tests__/ribbonBrushEngine.test.ts
new file mode 100644
index 0000000..014783f
--- /dev/null
+++ b/src/utils/__tests__/ribbonBrushEngine.test.ts
@@ -0,0 +1,1037 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import {
+ buildRibbonMeshFromPoints,
+ isRibbonBrush,
+ rasterizeRibbonMeshCpu,
+ renderCompleteRibbonStroke,
+ resolveRibbonRepeatMode,
+ RIBBON_VERTEX_STRIDE,
+ RibbonRenderOptions,
+ RibbonStrokeSession,
+ RibbonTipSurface,
+ selectRibbonSubTipIndex,
+} from '../../engine/RibbonBrushEngine';
+import { centripetalCatmullRomToBezier, renderCompleteStroke } from '../../engine/BrushEngine';
+import { WebGlBrushEngine } from '../../engine/WebGlBrushEngine';
+import { BrushSettings, Point } from '../../types/editor';
+
+/**
+ * Software-compositing mock Canvas2D for deterministic headless raster verification.
+ */
+function createRasterMockCanvas(width: number, height: number) {
+ const pixelBuffer = new Uint8ClampedArray(width * height * 4);
+ let curW = width;
+ let curH = height;
+ let buf = pixelBuffer;
+
+ const resize = (nw: number, nh: number) => {
+ curW = Math.max(1, Math.round(nw));
+ curH = Math.max(1, Math.round(nh));
+ buf = new Uint8ClampedArray(curW * curH * 4);
+ mockObj.pixelBuffer = buf;
+ };
+
+ let tx = 0;
+ let ty = 0;
+ const stack: Array<{ tx: number; ty: number; alpha: number; op: string }> = [];
+
+ const ctx: any = {
+ canvas: {
+ get width() {
+ return curW;
+ },
+ set width(v: number) {
+ if (v !== curW) resize(v, curH);
+ },
+ get height() {
+ return curH;
+ },
+ set height(v: number) {
+ if (v !== curH) resize(curW, v);
+ },
+ },
+ globalAlpha: 1.0,
+ globalCompositeOperation: 'source-over',
+ imageSmoothingEnabled: true,
+ save() {
+ stack.push({ tx, ty, alpha: ctx.globalAlpha, op: ctx.globalCompositeOperation });
+ },
+ restore() {
+ const s = stack.pop();
+ if (s) {
+ tx = s.tx;
+ ty = s.ty;
+ ctx.globalAlpha = s.alpha;
+ ctx.globalCompositeOperation = s.op;
+ }
+ },
+ translate(dx: number, dy: number) {
+ tx += dx;
+ ty += dy;
+ },
+ resetTransform() {
+ tx = 0;
+ ty = 0;
+ },
+ clearRect() {
+ buf.fill(0);
+ },
+ createImageData(w: number, h: number) {
+ return { width: w, height: h, data: new Uint8ClampedArray(w * h * 4) };
+ },
+ putImageData(imgData: { width: number; height: number; data: Uint8ClampedArray }, dx = 0, dy = 0) {
+ for (let y = 0; y < imgData.height; y++) {
+ const destY = dy + y;
+ if (destY < 0 || destY >= curH) continue;
+ for (let x = 0; x < imgData.width; x++) {
+ const destX = dx + x;
+ if (destX < 0 || destX >= curW) continue;
+ const si = (y * imgData.width + x) * 4;
+ const di = (destY * curW + destX) * 4;
+ buf[di] = imgData.data[si];
+ buf[di + 1] = imgData.data[si + 1];
+ buf[di + 2] = imgData.data[si + 2];
+ buf[di + 3] = imgData.data[si + 3];
+ }
+ }
+ },
+ getImageData(sx: number, sy: number, sw: number, sh: number) {
+ const data = new Uint8ClampedArray(sw * sh * 4);
+ for (let y = 0; y < sh; y++) {
+ const srcY = sy + y;
+ if (srcY < 0 || srcY >= curH) continue;
+ for (let x = 0; x < sw; x++) {
+ const srcX = sx + x;
+ if (srcX < 0 || srcX >= curW) continue;
+ const si = (srcY * curW + srcX) * 4;
+ const di = (y * sw + x) * 4;
+ data[di] = buf[si];
+ data[di + 1] = buf[si + 1];
+ data[di + 2] = buf[si + 2];
+ data[di + 3] = buf[si + 3];
+ }
+ }
+ return { width: sw, height: sh, data };
+ },
+ drawImage(
+ source: any,
+ sx: number,
+ sy: number,
+ sw?: number,
+ sh?: number,
+ dx?: number,
+ dy?: number,
+ dw?: number,
+ dh?: number
+ ) {
+ const srcBuf: Uint8ClampedArray | undefined = source?.pixelBuffer || source?.__rgbaData;
+ const srcW: number = source?.width || source?.naturalWidth || 0;
+ const srcH: number = source?.height || source?.naturalHeight || 0;
+ if (!srcBuf || srcW <= 0 || srcH <= 0) return;
+
+ const useSub = dx !== undefined && dy !== undefined && dw !== undefined && dh !== undefined;
+ const srcX0 = useSub ? sx : 0;
+ const srcY0 = useSub ? sy : 0;
+ const copyW = useSub ? sw! : sw ?? srcW;
+ const copyH = useSub ? sh! : sh ?? srcH;
+ const dstX0 = Math.round((useSub ? dx! : sx) + tx);
+ const dstY0 = Math.round((useSub ? dy! : sy) + ty);
+ const alphaScale = Math.max(0, Math.min(1, ctx.globalAlpha));
+
+ for (let y = 0; y < copyH; y++) {
+ const py = dstY0 + y;
+ const syi = srcY0 + y;
+ if (py < 0 || py >= curH || syi < 0 || syi >= srcH) continue;
+ for (let x = 0; x < copyW; x++) {
+ const px = dstX0 + x;
+ const sxi = srcX0 + x;
+ if (px < 0 || px >= curW || sxi < 0 || sxi >= srcW) continue;
+ const si = (syi * srcW + sxi) * 4;
+ const srcA = (srcBuf[si + 3] / 255) * alphaScale;
+ if (srcA <= 0.001) continue;
+ const di = (py * curW + px) * 4;
+ const dstA = buf[di + 3] / 255;
+ if (ctx.globalCompositeOperation === 'destination-out') {
+ buf[di + 3] = Math.round(dstA * (1 - srcA) * 255);
+ } else {
+ const outA = srcA + dstA * (1 - srcA);
+ const inv = outA > 1e-5 ? 1 / outA : 0;
+ buf[di] = Math.round((srcBuf[si] * srcA + buf[di] * dstA * (1 - srcA)) * inv);
+ buf[di + 1] = Math.round((srcBuf[si + 1] * srcA + buf[di + 1] * dstA * (1 - srcA)) * inv);
+ buf[di + 2] = Math.round((srcBuf[si + 2] * srcA + buf[di + 2] * dstA * (1 - srcA)) * inv);
+ buf[di + 3] = Math.round(outA * 255);
+ }
+ }
+ }
+ },
+ };
+
+ const mockObj = {
+ get width() {
+ return curW;
+ },
+ set width(v: number) {
+ if (v !== curW) resize(v, curH);
+ },
+ get height() {
+ return curH;
+ },
+ set height(v: number) {
+ if (v !== curH) resize(curW, v);
+ },
+ pixelBuffer: buf,
+ getContext(type: string) {
+ return type === '2d' ? ctx : null;
+ },
+ };
+ return mockObj;
+}
+
+function makeSolidColorTip(
+ width: number,
+ height: number,
+ r: number,
+ g: number,
+ b: number,
+ a: number = 255
+): RibbonTipSurface {
+ const data = new Uint8ClampedArray(width * height * 4);
+ for (let i = 0; i < width * height; i++) {
+ const p = i * 4;
+ data[p] = r;
+ data[p + 1] = g;
+ data[p + 2] = b;
+ data[p + 3] = a;
+ }
+ return { data, width, height, isColor: true };
+}
+
+function makeDirectionalGradientColorTip(width: number = 32, height: number = 16): RibbonTipSurface {
+ // u = 0 -> pure Red (255, 0, 0), u = 1 -> pure Blue (0, 0, 255)
+ const data = new Uint8ClampedArray(width * height * 4);
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const t = x / Math.max(1, width - 1);
+ const p = (y * width + x) * 4;
+ data[p] = Math.round(255 * (1 - t));
+ data[p + 1] = 0;
+ data[p + 2] = Math.round(255 * t);
+ data[p + 3] = 255;
+ }
+ }
+ return { data, width, height, isColor: true };
+}
+
+function makeChainStripedTip(width: number = 32, height: number = 16): RibbonTipSurface {
+ // Continuous chain-stripe along v in [0.25, 0.75] with bright outer rails
+ const data = new Uint8ClampedArray(width * height * 4);
+ for (let y = 0; y < height; y++) {
+ const v = (y + 0.5) / height;
+ const inBand = v >= 0.2 && v <= 0.8;
+ for (let x = 0; x < width; x++) {
+ const p = (y * width + x) * 4;
+ if (inBand) {
+ data[p] = 255;
+ data[p + 1] = 255;
+ data[p + 2] = 255;
+ data[p + 3] = 255;
+ }
+ }
+ }
+ return { data, width, height, isColor: false };
+}
+
+function makeDualToneTip(width: number = 32, height: number = 16): RibbonTipSurface {
+ // Top half (v < 0.5): black (lum = 0 -> primaryColor)
+ // Bottom half (v >= 0.5): white (lum = 1 -> secondaryColor)
+ const data = new Uint8ClampedArray(width * height * 4);
+ for (let y = 0; y < height; y++) {
+ const lum = y < height / 2 ? 0 : 255;
+ for (let x = 0; x < width; x++) {
+ const p = (y * width + x) * 4;
+ data[p] = lum;
+ data[p + 1] = lum;
+ data[p + 2] = lum;
+ data[p + 3] = 255;
+ }
+ }
+ return { data, width, height, isColor: false, isDualToneTip: true };
+}
+
+function readPixel(buf: Uint8ClampedArray, width: number, x: number, y: number) {
+ const ix = Math.round(x);
+ const iy = Math.round(y);
+ const p = (iy * width + ix) * 4;
+ return { r: buf[p], g: buf[p + 1], b: buf[p + 2], a: buf[p + 3] };
+}
+
+function createFakeTipImage(surface: RibbonTipSurface): HTMLImageElement {
+ return {
+ width: surface.width,
+ height: surface.height,
+ naturalWidth: surface.width,
+ naturalHeight: surface.height,
+ complete: true,
+ src: `data:image/png;base64,test_${surface.width}x${surface.height}`,
+ __rgbaData: surface.data,
+ } as unknown as HTMLImageElement;
+}
+
+describe('Clip Studio Paint Ribbon Brush Engine (BrushRibbon = 1)', () => {
+ beforeEach(() => {
+ (globalThis as any).document = {
+ createElement(tag: string) {
+ if (tag === 'canvas') {
+ return createRasterMockCanvas(64, 64);
+ }
+ return {};
+ },
+ };
+ });
+
+ describe('1. Predicate & Routing Rules', () => {
+ it('routes isRibbon=true brushes unless NaturalPaint or Spray is active', () => {
+ expect(isRibbonBrush({ isRibbon: true })).toBe(true);
+ expect(isRibbonBrush({ isRibbon: false })).toBe(false);
+ expect(isRibbonBrush({})).toBe(false);
+ expect(isRibbonBrush({ isRibbon: true, spray: { enabled: true, size: 4, density: 4, bias: 0 } })).toBe(false);
+ expect(isRibbonBrush({ isRibbon: true, renderMode: 'bristle-ribbon' })).toBe(false);
+ expect(isRibbonBrush({ isRibbon: true, naturalPaint: { enabled: true } as any })).toBe(false);
+ expect(isRibbonBrush({ isRibbon: true, impasto: { enabled: true } as any })).toBe(false);
+ });
+
+ it('resolves repeat modes cleanly from subTipOrder and explicit overrides', () => {
+ expect(resolveRibbonRepeatMode(undefined)).toBe('repeat');
+ expect(resolveRibbonRepeatMode('sequential')).toBe('repeat');
+ expect(resolveRibbonRepeatMode('reverse')).toBe('reverse');
+ expect(resolveRibbonRepeatMode('once')).toBe('once');
+ expect(resolveRibbonRepeatMode('sequential', 'reverse')).toBe('reverse');
+ expect(resolveRibbonRepeatMode('sequential', 'once')).toBe('once');
+ });
+ });
+
+ describe('2. S-Curve Continuity & Anti-Bowtie Corner Geometry', () => {
+ it('bends a striped chain tip continuously along an S-curve with zero stepping gaps and zero bowties', () => {
+ const sCurvePoints: Point[] = [];
+ for (let i = 0; i <= 24; i++) {
+ const t = i / 24;
+ const x = 20 + t * 220;
+ const y = 90 + Math.sin(t * Math.PI * 2) * 45;
+ sCurvePoints.push({ x, y, pressure: 0.8, width: 24 });
+ }
+
+ const tip = makeChainStripedTip(32, 16);
+ const opts: RibbonRenderOptions = {
+ size: 24,
+ angle: 90,
+ primaryColor: '#1144cc',
+ tipSurfaces: [tip],
+ antiAlias: 2,
+ };
+
+ const mesh = buildRibbonMeshFromPoints(sCurvePoints, opts);
+ expect(mesh.triangleCount).toBeGreaterThan(40);
+
+ // Every single triangle must have consistent non-inverted winding (signedArea < 0 => zero bowties)
+ for (let t = 0; t < mesh.triangleCount; t++) {
+ const b = t * 3 * RIBBON_VERTEX_STRIDE;
+ const x0 = mesh.vertices[b];
+ const y0 = mesh.vertices[b + 1];
+ const x1 = mesh.vertices[b + RIBBON_VERTEX_STRIDE];
+ const y1 = mesh.vertices[b + RIBBON_VERTEX_STRIDE + 1];
+ const x2 = mesh.vertices[b + RIBBON_VERTEX_STRIDE * 2];
+ const y2 = mesh.vertices[b + RIBBON_VERTEX_STRIDE * 2 + 1];
+ const signedArea = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0);
+ expect(signedArea).toBeLessThan(0);
+ }
+
+ const raster = rasterizeRibbonMeshCpu(mesh, opts, 260, 180, 0, 0);
+
+ // Verify every centerline sample along the entire S-curve is continuously painted (zero discrete gaps)
+ let coveredSamples = 0;
+ for (let i = 1; i < mesh.centerline.length - 1; i++) {
+ const c = mesh.centerline[i];
+ const px = readPixel(raster.data, raster.width, c.x, c.y);
+ if (px.a > 180) coveredSamples++;
+ }
+ expect(coveredSamples).toBe(mesh.centerline.length - 2);
+ });
+
+ it('prevents bowtie fold-overs on sharp 90-degree, 150-degree, and 180-degree hairpin bends', () => {
+ const sharpPoints: Point[] = [
+ { x: 20, y: 80, pressure: 1.0, width: 32 },
+ { x: 100, y: 80, pressure: 1.0, width: 32, isCorner: true },
+ { x: 100, y: 160, pressure: 1.0, width: 32, isCorner: true }, // 90 deg
+ { x: 50, y: 95, pressure: 1.0, width: 32, isCorner: true }, // ~140 deg
+ { x: 52, y: 170, pressure: 1.0, width: 32 }, // hairpin turn
+ ];
+
+ const mesh = buildRibbonMeshFromPoints(sharpPoints, {
+ size: 32,
+ tipSurfaces: [makeSolidColorTip(32, 32, 200, 50, 50)],
+ });
+
+ expect(mesh.triangleCount).toBeGreaterThan(20);
+ for (let t = 0; t < mesh.triangleCount; t++) {
+ const b = t * 3 * RIBBON_VERTEX_STRIDE;
+ const x0 = mesh.vertices[b];
+ const y0 = mesh.vertices[b + 1];
+ const x1 = mesh.vertices[b + RIBBON_VERTEX_STRIDE];
+ const y1 = mesh.vertices[b + RIBBON_VERTEX_STRIDE + 1];
+ const x2 = mesh.vertices[b + RIBBON_VERTEX_STRIDE * 2];
+ const y2 = mesh.vertices[b + RIBBON_VERTEX_STRIDE * 2 + 1];
+ const signedArea = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0);
+ expect(signedArea).toBeLessThan(0);
+ expect(Number.isFinite(x0) && Number.isFinite(y0)).toBe(true);
+ }
+
+ // Miter clamping prevents runaway spikes far outside the stroke hull
+ expect(mesh.bounds.maxX).toBeLessThan(140);
+ expect(mesh.bounds.minX).toBeGreaterThan(0);
+ });
+ });
+
+ describe('3. Aspect-Preserving UV Scaling, Thickness, and Base Angle', () => {
+ it('scales tile period proportionally with local width under varying pen pressure', () => {
+ const narrowPts: Point[] = [
+ { x: 10, y: 40, pressure: 0.5, width: 20 },
+ { x: 110, y: 40, pressure: 0.5, width: 20 },
+ ];
+ const widePts: Point[] = [
+ { x: 10, y: 40, pressure: 1.0, width: 40 },
+ { x: 110, y: 40, pressure: 1.0, width: 40 },
+ ];
+
+ const tip = makeSolidColorTip(32, 32, 255, 0, 0);
+ const narrowMesh = buildRibbonMeshFromPoints(narrowPts, { size: 40, tipSurfaces: [tip] });
+ const wideMesh = buildRibbonMeshFromPoints(widePts, { size: 40, tipSurfaces: [tip] });
+
+ const narrowTiles = narrowMesh.centerline[narrowMesh.centerline.length - 1].sNorm;
+ const wideTiles = wideMesh.centerline[wideMesh.centerline.length - 1].sNorm;
+
+ // 100px at width 20 => 5.0 tiles; 100px at width 40 => 2.5 tiles
+ expect(narrowTiles).toBeCloseTo(5.0, 1);
+ expect(wideTiles).toBeCloseTo(2.5, 1);
+ expect(narrowTiles / wideTiles).toBeCloseTo(2.0, 1);
+ });
+
+ it('respects CSP ribbon orientation (0 deg vertical, 90 deg horizontal), width scaling, and thickness', () => {
+ const pts: Point[] = [
+ { x: 20, y: 50, pressure: 1, width: 40 },
+ { x: 140, y: 50, pressure: 1, width: 40 },
+ ];
+ const gradTip = makeDirectionalGradientColorTip(32, 32);
+
+ // CSP Ribbon convention: at angle = 90°, tip +X (Red->Blue) flows ALONG the stroke
+ const opts90: RibbonRenderOptions = {
+ size: 40,
+ angle: 90,
+ tipSurfaces: [gradTip],
+ ribbonRepeatMode: 'once',
+ isColorTip: true,
+ antiAlias: 1,
+ };
+ const r90 = rasterizeRibbonMeshCpu(buildRibbonMeshFromPoints(pts, opts90), opts90, 160, 100, 0, 0);
+ const startPx90 = readPixel(r90.data, r90.width, 30, 50);
+ const endPx90 = readPixel(r90.data, r90.width, 130, 50);
+ expect(startPx90.r).toBeGreaterThan(200);
+ expect(endPx90.b).toBeGreaterThan(200);
+
+ // At angle = 0°, tip +Y flows ALONG the stroke and tip +X (Red->Blue) runs ACROSS the stroke
+ const opts0: RibbonRenderOptions = { ...opts90, angle: 0 };
+ const r0 = rasterizeRibbonMeshCpu(buildRibbonMeshFromPoints(pts, opts0), opts0, 160, 100, 0, 0);
+ const topPx0 = readPixel(r0.data, r0.width, 80, 36);
+ const botPx0 = readPixel(r0.data, r0.width, 80, 64);
+ expect(topPx0.b).toBeGreaterThan(topPx0.r);
+ expect(botPx0.r).toBeGreaterThan(botPx0.b);
+
+ // At angle = 0°, tip X is across-stroke and tip Y is along-stroke:
+ // thicknessVertical=true (CSP BrushVerticalThicknes=0) scales X (across-stroke width);
+ // thicknessVertical=false (CSP BrushVerticalThicknes=1) scales Y (along-stroke period).
+ const thinAlongMesh = buildRibbonMeshFromPoints(pts, {
+ size: 40,
+ angle: 0,
+ thickness: 0.5,
+ thicknessVertical: false,
+ tipSurfaces: [gradTip],
+ });
+ const thinAcrossMesh = buildRibbonMeshFromPoints(pts, {
+ size: 40,
+ angle: 0,
+ thickness: 0.5,
+ thicknessVertical: true,
+ tipSurfaces: [gradTip],
+ });
+ expect(thinAcrossMesh.centerline[0].ribbonWidth).toBeCloseTo(20, 1);
+ expect(thinAcrossMesh.centerline[0].tilePeriod).toBeCloseTo(40, 1);
+ expect(thinAlongMesh.centerline[0].ribbonWidth).toBeCloseTo(40, 1);
+ expect(thinAlongMesh.centerline[0].tilePeriod).toBeCloseTo(20, 1);
+
+ // Elongated ribbon tips (e.g. CSP Chain.sut 300x27 at angle=90° and vertical 27x300 at angle=0°)
+ // must keep ribbonWidth == BrushSize and preserve the natural aspect ratio along the stroke!
+ const horizChainMesh = buildRibbonMeshFromPoints(pts, {
+ size: 40,
+ angle: 90,
+ tipSurfaces: [makeSolidColorTip(300, 27, 255, 0, 0)],
+ });
+ expect(horizChainMesh.centerline[0].ribbonWidth).toBeCloseTo(40, 1);
+ expect(horizChainMesh.centerline[0].tilePeriod).toBeCloseTo((40 * 300) / 27, 1);
+
+ const vertChainMesh = buildRibbonMeshFromPoints(pts, {
+ size: 40,
+ angle: 0,
+ tipSurfaces: [makeSolidColorTip(27, 300, 255, 0, 0)],
+ });
+ expect(vertChainMesh.centerline[0].ribbonWidth).toBeCloseTo(40, 1);
+ expect(vertChainMesh.centerline[0].tilePeriod).toBeCloseTo((40 * 300) / 27, 1);
+ });
+ });
+
+ describe('4. Repeat Modes (repeat, reverse, once) & Multi-SubTip Arrays', () => {
+ it('renders repeat, reverse (ping-pong mirror), and once (full-stroke stretch) accurately', () => {
+ // 120px stroke with 40px square tip => 3 tiles in repeat/reverse, 1 stretched tile in once
+ const pts: Point[] = [
+ { x: 10, y: 40, pressure: 1, width: 40 },
+ { x: 130, y: 40, pressure: 1, width: 40 },
+ ];
+ const gradTip = makeDirectionalGradientColorTip(32, 32);
+
+ // REPEAT: tile 0 [10..50] R->B, tile 1 [50..90] R->B, tile 2 [90..130] R->B
+ const optsRep: RibbonRenderOptions = {
+ size: 40,
+ angle: 90,
+ tipSurfaces: [gradTip],
+ ribbonRepeatMode: 'repeat',
+ isColorTip: true,
+ antiAlias: 1,
+ };
+ const rRep = rasterizeRibbonMeshCpu(buildRibbonMeshFromPoints(pts, optsRep), optsRep, 150, 80, 0, 0);
+ expect(readPixel(rRep.data, 150, 14, 40).r).toBeGreaterThan(200); // start of tile 0 = Red
+ expect(readPixel(rRep.data, 150, 54, 40).r).toBeGreaterThan(200); // start of tile 1 = Red
+ expect(readPixel(rRep.data, 150, 86, 40).b).toBeGreaterThan(200); // end of tile 1 = Blue
+
+ // REVERSE: tile 0 [10..50] R->B, tile 1 [50..90] B->R (mirrored!), tile 2 [90..130] R->B
+ const optsRev: RibbonRenderOptions = { ...optsRep, ribbonRepeatMode: 'reverse' };
+ const rRev = rasterizeRibbonMeshCpu(buildRibbonMeshFromPoints(pts, optsRev), optsRev, 150, 80, 0, 0);
+ expect(readPixel(rRev.data, 150, 14, 40).r).toBeGreaterThan(200); // start of tile 0 = Red
+ expect(readPixel(rRev.data, 150, 46, 40).b).toBeGreaterThan(200); // end of tile 0 = Blue
+ expect(readPixel(rRev.data, 150, 54, 40).b).toBeGreaterThan(200); // start of tile 1 = Blue (seamless!)
+ expect(readPixel(rRev.data, 150, 86, 40).r).toBeGreaterThan(200); // end of tile 1 = Red
+
+ // ONCE: u stretches 0..1 across entire [10..130], so midpoint x=70 is ~50% purple (R~127, B~127)
+ const optsOnce: RibbonRenderOptions = { ...optsRep, ribbonRepeatMode: 'once' };
+ const rOnce = rasterizeRibbonMeshCpu(buildRibbonMeshFromPoints(pts, optsOnce), optsOnce, 150, 80, 0, 0);
+ const midPx = readPixel(rOnce.data, 150, 70, 40);
+ expect(midPx.r).toBeGreaterThan(100);
+ expect(midPx.r).toBeLessThan(155);
+ expect(midPx.b).toBeGreaterThan(100);
+ expect(midPx.b).toBeLessThan(155);
+ });
+
+ it('cycles multi-subTip arrays sequentially, reversed, and deterministically random', () => {
+ const tipR = makeSolidColorTip(32, 32, 240, 20, 20);
+ const tipG = makeSolidColorTip(32, 32, 20, 240, 20);
+ const tipB = makeSolidColorTip(32, 32, 20, 20, 240);
+ const pts: Point[] = [
+ { x: 10, y: 40, pressure: 1, width: 30 },
+ { x: 190, y: 40, pressure: 1, width: 30 }, // 180px => 6 tiles of 30px
+ ];
+
+ // Sequential: [R, G, B, R, G, B]
+ const seqOpts: RibbonRenderOptions = {
+ size: 30,
+ tipSurfaces: [tipR, tipG, tipB],
+ subTipOrder: 'sequential',
+ isColorTip: true,
+ antiAlias: 1,
+ };
+ const rSeq = rasterizeRibbonMeshCpu(buildRibbonMeshFromPoints(pts, seqOpts), seqOpts, 210, 80, 0, 0);
+ expect(readPixel(rSeq.data, 210, 25, 40).r).toBeGreaterThan(200); // tile 0 = R
+ expect(readPixel(rSeq.data, 210, 55, 40).g).toBeGreaterThan(200); // tile 1 = G
+ expect(readPixel(rSeq.data, 210, 85, 40).b).toBeGreaterThan(200); // tile 2 = B
+ expect(readPixel(rSeq.data, 210, 115, 40).r).toBeGreaterThan(200); // tile 3 = R
+
+ // Reversed: [B, G, R, B, G, R]
+ const revOpts: RibbonRenderOptions = { ...seqOpts, subTipOrder: 'reverse' };
+ const rRev = rasterizeRibbonMeshCpu(buildRibbonMeshFromPoints(pts, revOpts), revOpts, 210, 80, 0, 0);
+ expect(readPixel(rRev.data, 210, 25, 40).b).toBeGreaterThan(200); // tile 0 = B
+ expect(readPixel(rRev.data, 210, 55, 40).g).toBeGreaterThan(200); // tile 1 = G
+ expect(readPixel(rRev.data, 210, 85, 40).r).toBeGreaterThan(200); // tile 2 = R
+
+ // Deterministic random & random-no-repeat
+ const seqA = Array.from({ length: 12 }, (_, k) =>
+ selectRibbonSubTipIndex(3, 'random', k, 0, 10, 40)
+ );
+ const seqB = Array.from({ length: 12 }, (_, k) =>
+ selectRibbonSubTipIndex(3, 'random', k, 0, 10, 40)
+ );
+ expect(seqA).toEqual(seqB);
+
+ const noRep = Array.from({ length: 12 }, (_, k) =>
+ selectRibbonSubTipIndex(3, 'random-no-repeat', k, 0, 10, 40)
+ );
+ for (let i = 1; i < noRep.length; i++) {
+ expect(noRep[i]).not.toBe(noRep[i - 1]);
+ }
+ });
+ });
+
+ describe('5. Dual-Tone Tips, FlipH/FlipV, Taper, Anti-Aliasing & Paper Texture', () => {
+ it('renders isDualToneTip blending primaryColor (black) and secondaryColor (white)', () => {
+ const pts: Point[] = [
+ { x: 10, y: 40, pressure: 1, width: 32 },
+ { x: 110, y: 40, pressure: 1, width: 32 },
+ ];
+ const dualTip = makeDualToneTip(32, 32);
+ const opts: RibbonRenderOptions = {
+ size: 32,
+ angle: 90,
+ tipSurfaces: [dualTip],
+ isDualToneTip: true,
+ primaryColor: '#e02020',
+ secondaryColor: '#20d040',
+ antiAlias: 1,
+ };
+
+ const raster = rasterizeRibbonMeshCpu(buildRibbonMeshFromPoints(pts, opts), opts, 130, 80, 0, 0);
+ const topHalf = readPixel(raster.data, 130, 60, 32); // v < 0.5 -> black -> primaryColor (#e02020)
+ const botHalf = readPixel(raster.data, 130, 60, 48); // v > 0.5 -> white -> secondaryColor (#20d040)
+
+ expect(topHalf.r).toBeGreaterThan(200);
+ expect(topHalf.g).toBeLessThan(60);
+ expect(botHalf.g).toBeGreaterThan(180);
+ expect(botHalf.r).toBeLessThan(60);
+ });
+
+ it('supports per-tile flipH and flipV alternation', () => {
+ const pts: Point[] = [
+ { x: 10, y: 40, pressure: 1, width: 40 },
+ { x: 90, y: 40, pressure: 1, width: 40 }, // 2 tiles: [10..50] and [50..90]
+ ];
+ const gradTip = makeDirectionalGradientColorTip(32, 32);
+ const optsFlipH: RibbonRenderOptions = {
+ size: 40,
+ angle: 90,
+ tipSurfaces: [gradTip],
+ isColorTip: true,
+ flipH: 'alternate',
+ antiAlias: 1,
+ };
+ const rH = rasterizeRibbonMeshCpu(buildRibbonMeshFromPoints(pts, optsFlipH), optsFlipH, 110, 80, 0, 0);
+ // Tile 0 not flipped: start is Red; Tile 1 flipped horizontally: start is Blue!
+ expect(readPixel(rH.data, 110, 14, 40).r).toBeGreaterThan(200);
+ expect(readPixel(rH.data, 110, 54, 40).b).toBeGreaterThan(200);
+
+ const dualTip = makeDualToneTip(32, 32);
+ const optsFlipV: RibbonRenderOptions = {
+ size: 40,
+ angle: 90,
+ tipSurfaces: [dualTip],
+ isDualToneTip: true,
+ primaryColor: '#ff0000',
+ secondaryColor: '#0000ff',
+ flipV: 'alternate',
+ antiAlias: 1,
+ };
+ const rV = rasterizeRibbonMeshCpu(buildRibbonMeshFromPoints(pts, optsFlipV), optsFlipV, 110, 80, 0, 0);
+ // Tile 0 top is Red, Tile 1 is flipped vertically so top is Blue!
+ expect(readPixel(rV.data, 110, 30, 30).r).toBeGreaterThan(200);
+ expect(readPixel(rV.data, 110, 70, 30).b).toBeGreaterThan(200);
+ });
+
+ it('applies CSP taper (in & out) to ribbon width and alpha', () => {
+ const pts: Point[] = [
+ { x: 10, y: 40, pressure: 1, width: 30 },
+ { x: 110, y: 40, pressure: 1, width: 30 },
+ { x: 210, y: 40, pressure: 1, width: 30 },
+ ];
+ const mesh = buildRibbonMeshFromPoints(pts, {
+ size: 30,
+ tipSurfaces: [makeSolidColorTip(32, 32, 0, 0, 0)],
+ taper: {
+ useIn: true,
+ inLength: 50,
+ inRatio: 0.25,
+ useOut: true,
+ outLength: 50,
+ outRatio: 0.25,
+ inOutType: 2,
+ affectSize: true,
+ affectOpacity: true,
+ minSizeRatio: 0.1,
+ minDensityRatio: 0.1,
+ },
+ });
+
+ const first = mesh.centerline[0];
+ const mid = mesh.centerline[Math.floor(mesh.centerline.length / 2)];
+ const last = mesh.centerline[mesh.centerline.length - 1];
+
+ expect(first.ribbonWidth).toBeLessThan(mid.ribbonWidth * 0.5);
+ expect(last.ribbonWidth).toBeLessThan(mid.ribbonWidth * 0.5);
+ expect(first.alpha).toBeLessThan(mid.alpha * 0.6);
+ expect(last.alpha).toBeLessThan(mid.alpha * 0.6);
+ });
+
+ it('enforces binary alpha at antiAlias=0 and modulates alpha with world-space paperTexture', () => {
+ const pts: Point[] = [
+ { x: 10, y: 40, pressure: 0.35, width: 26 },
+ { x: 130, y: 55, pressure: 0.35, width: 26 }, // slight slope to test AA edges
+ ];
+ const solidTip = makeSolidColorTip(32, 32, 20, 20, 20);
+
+ // AA = 0 -> strictly binary alpha (0 or 255)
+ const optsAA0: RibbonRenderOptions = { size: 26, tipSurfaces: [solidTip], antiAlias: 0 };
+ const rAA0 = rasterizeRibbonMeshCpu(buildRibbonMeshFromPoints(pts, optsAA0), optsAA0, 150, 90, 0, 0);
+ let intermediateAA0 = 0;
+ for (let i = 3; i < rAA0.data.length; i += 4) {
+ if (rAA0.data[i] > 0 && rAA0.data[i] < 255) intermediateAA0++;
+ }
+ expect(intermediateAA0).toBe(0);
+
+ // AA = 2 -> smooth edge pixels have intermediate alpha
+ const optsAA2: RibbonRenderOptions = { size: 26, tipSurfaces: [solidTip], antiAlias: 2 };
+ const rAA2 = rasterizeRibbonMeshCpu(buildRibbonMeshFromPoints(pts, optsAA2), optsAA2, 150, 90, 0, 0);
+ let intermediateAA2 = 0;
+ for (let i = 3; i < rAA2.data.length; i += 4) {
+ if (rAA2.data[i] > 0 && rAA2.data[i] < 255) intermediateAA2++;
+ }
+ expect(intermediateAA2).toBeGreaterThan(20);
+
+ // Paper texture modulation reduces alpha in paper valleys and introduces spatial grain variance
+ const optsPaper: RibbonRenderOptions = {
+ size: 26,
+ tipSurfaces: [solidTip],
+ grain: 0.85,
+ paperTextureMode: 'subtract',
+ paperTextureApplyEachPlot: true,
+ antiAlias: 2,
+ };
+ const rPaper = rasterizeRibbonMeshCpu(buildRibbonMeshFromPoints(pts, optsPaper), optsPaper, 150, 90, 0, 0);
+ let sumPlain = 0;
+ let sumPaper = 0;
+ let diffPixels = 0;
+ for (let i = 3; i < rAA2.data.length; i += 4) {
+ sumPlain += rAA2.data[i];
+ sumPaper += rPaper.data[i];
+ if (rAA2.data[i] > 200 && Math.abs(rAA2.data[i] - rPaper.data[i]) > 15) {
+ diffPixels++;
+ }
+ }
+ expect(sumPaper).toBeLessThan(sumPlain * 0.92);
+ expect(diffPixels).toBeGreaterThan(100);
+ });
+ });
+
+ describe('6. End-to-End Integration (renderCompleteStroke & Live RibbonStrokeSession)', () => {
+ it('routes renderCompleteStroke with isRibbon=true into RibbonBrushEngine CPU fallback', () => {
+ const target = createRasterMockCanvas(180, 100);
+ const ctx = target.getContext('2d') as unknown as CanvasRenderingContext2D;
+ const dualTipImg = createFakeTipImage(makeDualToneTip(32, 32));
+
+ const bs: BrushSettings = {
+ size: 28,
+ minSizeFactor: 0.2,
+ color: '#d81b60',
+ secondaryColor: '#00acc1',
+ opacity: 1.0,
+ flow: 1.0,
+ spacing: 0.1,
+ usePressure: true,
+ smoothing: false,
+ stabilization: 0,
+ hardness: 1.0,
+ isRibbon: true,
+ isDualToneTip: true,
+ customTipImage: dualTipImg,
+ useGpu: false,
+ };
+
+ const pts: Point[] = [
+ { x: 20, y: 50, pressure: 1, width: 28 },
+ { x: 80, y: 35, pressure: 1, width: 28 },
+ { x: 150, y: 60, pressure: 1, width: 28 },
+ ];
+
+ renderCompleteStroke(ctx, pts, bs, 'brush', 'color');
+
+ // Check that pixels along the curved stroke were actually painted with both dual-tone colors
+ let primaryHits = 0;
+ let secondaryHits = 0;
+ for (let i = 0; i < target.pixelBuffer.length; i += 4) {
+ if (target.pixelBuffer[i + 3] < 200) continue;
+ const r = target.pixelBuffer[i];
+ const g = target.pixelBuffer[i + 1];
+ const b = target.pixelBuffer[i + 2];
+ if (r > 180 && g < 60) primaryHits++;
+ if (g > 140 && b > 150 && r < 60) secondaryHits++;
+ }
+ expect(primaryHits).toBeGreaterThan(200);
+ expect(secondaryHits).toBeGreaterThan(200);
+ });
+
+ it('stitches consecutive live CubicBezierSegments seamlessly via RibbonStrokeSession', () => {
+ const target = createRasterMockCanvas(200, 100);
+ const ctx = target.getContext('2d') as unknown as CanvasRenderingContext2D;
+ const tip = makeChainStripedTip(32, 16);
+ const opts: RibbonRenderOptions = {
+ size: 24,
+ angle: 90,
+ primaryColor: '#228833',
+ tipSurfaces: [tip],
+ useGpu: false,
+ };
+
+ const p0: Point = { x: 15, y: 50, pressure: 1, width: 24 };
+ const p1: Point = { x: 75, y: 30, pressure: 1, width: 24 };
+ const p2: Point = { x: 135, y: 70, pressure: 1, width: 24 };
+ const p3: Point = { x: 185, y: 45, pressure: 1, width: 24 };
+
+ const s1 = centripetalCatmullRomToBezier(p0, p0, p1, p2);
+ const s2 = centripetalCatmullRomToBezier(p0, p1, p2, p3);
+ const s3 = centripetalCatmullRomToBezier(p1, p2, p3, p3);
+
+ const session = new RibbonStrokeSession();
+ const m1 = session.appendCubicSegment(ctx, { p0, c1: s1.c1, c2: s1.c2, p3: p1 }, opts);
+ const m2 = session.appendCubicSegment(ctx, { p0: p1, c1: s2.c1, c2: s2.c2, p3: p2 }, opts);
+ const m3 = session.appendCubicSegment(ctx, { p0: p2, c1: s3.c1, c2: s3.c2, p3 }, opts);
+
+ expect(m1 && m1.triangleCount).toBeGreaterThan(4);
+ expect(m2 && m2.triangleCount).toBeGreaterThan(4);
+ expect(m3 && m3.triangleCount).toBeGreaterThan(4);
+
+ // Verify both join knots (p1 and p2) are solidly painted with zero seam crack
+ expect(readPixel(target.pixelBuffer, 200, p1.x, p1.y).a).toBeGreaterThan(200);
+ expect(readPixel(target.pixelBuffer, 200, p2.x, p2.y).a).toBeGreaterThan(200);
+
+ // Verify single-tap renderCompleteRibbonStroke renders cleanly
+ const tapCanvas = createRasterMockCanvas(80, 80);
+ const tapCtx = tapCanvas.getContext('2d') as unknown as CanvasRenderingContext2D;
+ const tapMesh = renderCompleteRibbonStroke(
+ tapCtx,
+ [{ x: 40, y: 40, pressure: 1, width: 24 }],
+ {
+ size: 24,
+ minSizeFactor: 0.2,
+ color: '#000000',
+ opacity: 1,
+ flow: 1,
+ spacing: 0.1,
+ usePressure: true,
+ smoothing: false,
+ stabilization: 0,
+ hardness: 1,
+ customTipAngle: 90,
+ isRibbon: true,
+ useGpu: false,
+ },
+ 'brush',
+ 'color',
+ false,
+ false,
+ false,
+ undefined,
+ { tipSurfaces: [tip] }
+ );
+ expect(tapMesh && tapMesh.triangleCount).toBeGreaterThanOrEqual(2);
+ expect(readPixel(tapCanvas.pixelBuffer, 80, 40, 40).a).toBeGreaterThan(200);
+ });
+
+ it('compiles and dispatches the WebGL textured ribbon shader with all attributes and uniforms', () => {
+ const compiledSources: string[] = [];
+ const setUniforms = new Map<string, any>();
+ const boundAttribs = new Set<string>();
+ const drawCalls: Array<{ mode: number; first: number; count: number }> = [];
+ let nextLocId = 1;
+ const attribLocMap = new Map<string, number>();
+
+ const mockGl: any = {
+ VERTEX_SHADER: 35633,
+ FRAGMENT_SHADER: 35632,
+ COMPILE_STATUS: 35713,
+ LINK_STATUS: 35714,
+ ARRAY_BUFFER: 34962,
+ STATIC_DRAW: 35044,
+ DYNAMIC_DRAW: 35048,
+ TEXTURE_2D: 3553,
+ TEXTURE0: 33984,
+ TEXTURE3: 33987,
+ RGBA: 6408,
+ LUMINANCE: 6409,
+ UNSIGNED_BYTE: 5121,
+ UNPACK_ALIGNMENT: 3317,
+ UNPACK_PREMULTIPLY_ALPHA_WEBGL: 37441,
+ TEXTURE_WRAP_S: 10242,
+ TEXTURE_WRAP_T: 10243,
+ TEXTURE_MIN_FILTER: 10241,
+ TEXTURE_MAG_FILTER: 10240,
+ REPEAT: 10497,
+ CLAMP_TO_EDGE: 33071,
+ LINEAR: 9729,
+ NEAREST: 9728,
+ LINEAR_MIPMAP_LINEAR: 9987,
+ BLEND: 3042,
+ ONE: 1,
+ ONE_MINUS_SRC_ALPHA: 771,
+ FUNC_ADD: 32774,
+ COLOR_BUFFER_BIT: 16384,
+ SCISSOR_TEST: 3089,
+ FLOAT: 5126,
+ TRIANGLES: 4,
+ VERSION: 7938,
+ getExtension: () => null,
+ getParameter: () => 'WebGL 1.0 Mock',
+ isContextLost: () => false,
+ createShader: (type: number) => ({ type }),
+ shaderSource: (_shader: any, src: string) => {
+ compiledSources.push(src);
+ },
+ compileShader: () => {},
+ getShaderParameter: () => true,
+ deleteShader: () => {},
+ createProgram: () => ({ id: nextLocId++ }),
+ attachShader: () => {},
+ linkProgram: () => {},
+ getProgramParameter: () => true,
+ getAttribLocation: (_prog: any, name: string) => {
+ if (!attribLocMap.has(name)) attribLocMap.set(name, attribLocMap.size);
+ return attribLocMap.get(name)!;
+ },
+ getUniformLocation: (_prog: any, name: string) => ({ name }),
+ createBuffer: () => ({ id: nextLocId++ }),
+ bindBuffer: () => {},
+ bufferData: () => {},
+ createTexture: () => ({ id: nextLocId++ }),
+ deleteTexture: () => {},
+ activeTexture: () => {},
+ bindTexture: () => {},
+ pixelStorei: () => {},
+ texImage2D: () => {},
+ texParameteri: () => {},
+ generateMipmap: () => {},
+ enable: () => {},
+ disable: () => {},
+ blendFunc: () => {},
+ blendEquation: () => {},
+ viewport: () => {},
+ scissor: () => {},
+ clearColor: () => {},
+ clear: () => {},
+ useProgram: () => {},
+ uniform1i: (loc: any, v: number) => {
+ if (loc?.name) setUniforms.set(loc.name, v);
+ },
+ uniform1f: (loc: any, v: number) => {
+ if (loc?.name) setUniforms.set(loc.name, v);
+ },
+ uniform2f: (loc: any, a: number, b: number) => {
+ if (loc?.name) setUniforms.set(loc.name, [a, b]);
+ },
+ uniform3f: (loc: any, a: number, b: number, c: number) => {
+ if (loc?.name) setUniforms.set(loc.name, [a, b, c]);
+ },
+ enableVertexAttribArray: (loc: number) => {
+ for (const [k, v] of attribLocMap.entries()) {
+ if (v === loc) boundAttribs.add(k);
+ }
+ },
+ disableVertexAttribArray: () => {},
+ vertexAttribPointer: () => {},
+ drawArrays: (mode: number, first: number, count: number) => {
+ drawCalls.push({ mode, first, count });
+ },
+ };
+
+ const prevDoc = (globalThis as any).document;
+ (globalThis as any).document = {
+ createElement(tag: string) {
+ if (tag === 'canvas') {
+ const c = createRasterMockCanvas(256, 256);
+ const origGetContext = c.getContext.bind(c);
+ c.getContext = (type: string) => (type === 'webgl' || type === 'webgl2' ? mockGl : origGetContext(type));
+ return c;
+ }
+ return {};
+ },
+ };
+
+ // Reset singleton so WebGlBrushEngine initializes against mockGl
+ const prevInst = (WebGlBrushEngine as any).instance;
+ (WebGlBrushEngine as any).instance = null;
+
+ try {
+ const gpu = WebGlBrushEngine.getInstance();
+ expect(gpu.isTexturedRibbonAvailable()).toBe(true);
+
+ const joinedShaders = compiledSources.join('\n');
+ expect(joinedShaders).toContain('attribute vec2 a_pos');
+ expect(joinedShaders).toContain('attribute vec2 a_uv');
+ expect(joinedShaders).toContain('attribute float a_alpha');
+ expect(joinedShaders).toContain('attribute float a_pressure');
+ expect(joinedShaders).toContain('attribute float a_tipIndex');
+ expect(joinedShaders).toContain('uniform bool u_isColorTip');
+ expect(joinedShaders).toContain('uniform bool u_isDualToneTip');
+ expect(joinedShaders).toContain('uniform vec3 u_primaryColor');
+ expect(joinedShaders).toContain('uniform vec3 u_secondaryColor');
+
+ const pts: Point[] = [
+ { x: 10, y: 40, pressure: 0.7, width: 24 },
+ { x: 90, y: 60, pressure: 0.9, width: 24 },
+ { x: 170, y: 30, pressure: 0.8, width: 24 },
+ ];
+ const tipImg = createFakeTipImage(makeDualToneTip(32, 32));
+ const mesh = buildRibbonMeshFromPoints(pts, {
+ size: 24,
+ tipImage: tipImg,
+ isDualToneTip: true,
+ });
+
+ const target = createRasterMockCanvas(200, 120);
+ const targetCtx = target.getContext('2d') as unknown as CanvasRenderingContext2D;
+ const ok = gpu.renderTexturedRibbonMesh(
+ targetCtx,
+ mesh,
+ {
+ size: 24,
+ minSizeFactor: 0.2,
+ color: '#ff0000',
+ secondaryColor: '#00ff00',
+ opacity: 1,
+ flow: 1,
+ spacing: 0.1,
+ usePressure: true,
+ smoothing: false,
+ stabilization: 0,
+ hardness: 1,
+ isRibbon: true,
+ isDualToneTip: true,
+ customTipImage: tipImg,
+ grain: 0.6,
+ paperTextureMode: 'subtract',
+ antiAlias: 2,
+ },
+ '#ff0000',
+ 'brush'
+ );
+
+ expect(ok).toBe(true);
+ expect(drawCalls.length).toBeGreaterThanOrEqual(1);
+ expect(drawCalls[0].mode).toBe(mockGl.TRIANGLES);
+ expect(drawCalls[0].count).toBe(mesh.vertexCount);
+ expect(boundAttribs.has('a_pos')).toBe(true);
+ expect(boundAttribs.has('a_uv')).toBe(true);
+ expect(boundAttribs.has('a_alpha')).toBe(true);
+ expect(boundAttribs.has('a_pressure')).toBe(true);
+ expect(boundAttribs.has('a_tipIndex')).toBe(true);
+ expect(setUniforms.get('u_isDualToneTip')).toBe(1);
+ expect(setUniforms.get('u_isColorTip')).toBe(0);
+ expect(setUniforms.get('u_primaryColor')).toEqual([1, 0, 0]);
+ expect(setUniforms.get('u_secondaryColor')).toEqual([0, 1, 0]);
+ expect(setUniforms.get('u_paperGrain')).toBeCloseTo(0.6, 4);
+ } finally {
+ (WebGlBrushEngine as any).instance = prevInst;
+ (globalThis as any).document = prevDoc;
+ }
+ });
+ });
+});
diff --git a/src/utils/__tests__/settings.test.ts b/src/utils/__tests__/settings.test.ts
index 991e96f..8663373 100644
--- a/src/utils/__tests__/settings.test.ts
+++ b/src/utils/__tests__/settings.test.ts
@@ -142,4 +142,37 @@ describe('settings theme & accent system', () => {
expect(NICKNAME_STORAGE_KEY).toBe('ink_studio_nickname');
expect(loadAppSettings().userName).toBe('InkArtist');
});
+
+ it('persists and sanitizes WebRTC collaboration signaling and TURN settings', () => {
+ const defaults = loadAppSettings();
+ expect(defaults.collabSignalingUrl).toBe('');
+ expect(defaults.collabTurnUrl).toBe('');
+ expect(defaults.collabTurnUsername).toBe('');
+ expect(defaults.collabTurnCredential).toBe('');
+
+ saveAppSettings({
+ ...DEFAULT_APP_SETTINGS,
+ collabSignalingUrl: ' wss://sig.example.workers.dev/signal ',
+ collabTurnUrl: ' turns:turn.example.com:5349 ',
+ collabTurnUsername: ' artist ',
+ collabTurnCredential: ' secret-token ',
+ });
+ const loaded = loadAppSettings();
+ expect(loaded.collabSignalingUrl).toBe('wss://sig.example.workers.dev/signal');
+ expect(loaded.collabTurnUrl).toBe('turns:turn.example.com:5349');
+ expect(loaded.collabTurnUsername).toBe('artist');
+ expect(loaded.collabTurnCredential).toBe('secret-token');
+
+ // Null-byte / non-string corruption falls back safely
+ localStorage.setItem(
+ 'ink_studio_app_settings',
+ JSON.stringify({
+ collabSignalingUrl: 'wss://bad\0url',
+ collabTurnUrl: 12345,
+ })
+ );
+ const sanitized = loadAppSettings();
+ expect(sanitized.collabSignalingUrl).toBe('');
+ expect(sanitized.collabTurnUrl).toBe('');
+ });
});
diff --git a/src/utils/__tests__/strokePipelineIntegration.test.ts b/src/utils/__tests__/strokePipelineIntegration.test.ts
index 1939c6e..271abe8 100644
--- a/src/utils/__tests__/strokePipelineIntegration.test.ts
+++ b/src/utils/__tests__/strokePipelineIntegration.test.ts
@@ -312,6 +312,100 @@ describe('StrokePipeline: Ring Buffer, Stabilization, Taper, Prediction & Bake D
expect(encodePointerType('mouse')).toBe(POINTER_TYPE_MOUSE);
expect(encodePointerType('touch')).toBe(POINTER_TYPE_TOUCH);
});
+
+ it('keeps fast diagonal lines straight with zero anisotropy and suppresses mid-stroke twitches at stabilization 20', () => {
+ // 1. Asymmetric fast diagonal line (dx:dy = 4:3, ~2.5 px/ms = 2500 px/s) with coalesced identical timestamps
+ pipeline.beginStroke({ stabilizerLevel: 20, zoom: 1.0, sharpCorners: true, brushSize: 6 });
+ const dirX = 0.8;
+ const dirY = 0.6;
+ const normX = -dirY;
+ const normY = dirX;
+
+ let t = 1000;
+ for (let i = 0; i <= 40; i++) {
+ const dist = i * 10; // 400px total at 2.5 px/ms (4ms per step)
+ // Simulate realistic 4-packet coalesced bursts sharing identical frame timestamps
+ if (i > 0 && i % 4 === 0) t += 16;
+ pipeline.enqueueSample(dist * dirX, dist * dirY, 0.7, 0, 0, 0, t, POINTER_TYPE_PEN);
+ }
+
+ const straightPts: Array<{ x: number; y: number; isCorner: boolean }> = [];
+ pipeline.drain({
+ onPoint: (pt) => straightPts.push({ x: pt.x, y: pt.y, isCorner: pt.isCorner }),
+ });
+
+ expect(straightPts.length).toBeGreaterThan(20);
+ for (const pt of straightPts) {
+ // Strictly collinear (isotropic 2D smoothing -> zero perpendicular warp on diagonal lines!)
+ const perpErr = Math.abs(pt.x * normX + pt.y * normY);
+ expect(perpErr).toBeLessThan(1e-6);
+ expect(pt.isCorner).toBe(false);
+ }
+
+ // 2. Fast diagonal line with a 1-sample 12px twitch, a 2-sample 12px twitch, AND a 15px backtrack glitch
+ const runFastTwitchStroke = (
+ inject: (i: number, dist: number) => { x: number; y: number }
+ ) => {
+ pipeline.beginStroke({ stabilizerLevel: 20, zoom: 1.0, sharpCorners: true, brushSize: 6 });
+ let ts = 2000;
+ for (let i = 0; i <= 50; i++) {
+ ts += 4;
+ const pos = inject(i, i * 10);
+ pipeline.enqueueSample(pos.x, pos.y, 0.7, 0, 0, 0, ts, POINTER_TYPE_PEN);
+ }
+ const pts: Array<{ x: number; y: number; isCorner: boolean }> = [];
+ pipeline.drain({
+ onPoint: (pt) => pts.push({ x: pt.x, y: pt.y, isCorner: pt.isCorner }),
+ });
+ let maxPerp = 0;
+ let corners = 0;
+ for (const pt of pts) {
+ const perp = Math.abs(pt.x * normX + pt.y * normY);
+ if (perp > maxPerp) maxPerp = perp;
+ if (pt.isCorner) corners++;
+ }
+ return { pts, maxPerp, corners, endTs: ts };
+ };
+
+ // 2a. 1-sample 12px lateral twitch -> attenuated by >85% (< 1.8px) with zero false corners
+ const oneSampleTwitch = runFastTwitchStroke((i, dist) => ({
+ x: dist * dirX + (i === 20 ? normX * 12 : 0),
+ y: dist * dirY + (i === 20 ? normY * 12 : 0),
+ }));
+ expect(oneSampleTwitch.corners).toBe(0);
+ expect(oneSampleTwitch.maxPerp).toBeLessThan(1.8);
+
+ // 2b. 2-sample (20px wide) 12px lateral twitch -> attenuated by >75% (< 3.0px) with zero false corners
+ const twoSampleTwitch = runFastTwitchStroke((i, dist) => ({
+ x: dist * dirX + (i === 20 || i === 21 ? normX * 12 : 0),
+ y: dist * dirY + (i === 20 || i === 21 ? normY * 12 : 0),
+ }));
+ expect(twoSampleTwitch.corners).toBe(0);
+ expect(twoSampleTwitch.maxPerp).toBeLessThan(3.0);
+
+ // 2c. 1-sample backwards hardware glitch (-30px along stroke, +15px lateral) -> completely rejected (< 0.25px)
+ const backtrackGlitch = runFastTwitchStroke((i, dist) =>
+ i === 25
+ ? { x: (dist - 30) * dirX + normX * 15, y: (dist - 30) * dirY + normY * 15 }
+ : { x: dist * dirX, y: dist * dirY }
+ );
+ expect(backtrackGlitch.corners).toBe(0);
+ expect(backtrackGlitch.maxPerp).toBeLessThan(0.25);
+
+ // 3. Finalize smoothly catches up residual stabilizer lag along the exact diagonal line
+ const catchUpPts: Array<{ x: number; y: number }> = [];
+ pipeline.finalizeStroke(backtrackGlitch.endTs + 4, {
+ enableFlickTaper: false,
+ onPoint: (pt) => catchUpPts.push({ x: pt.x, y: pt.y }),
+ });
+ expect(catchUpPts.length).toBeGreaterThanOrEqual(2);
+ const lastBeforeFinalize = backtrackGlitch.pts[backtrackGlitch.pts.length - 1];
+ const lastAfterFinalize = catchUpPts[catchUpPts.length - 1];
+ expect(Math.hypot(lastAfterFinalize.x, lastAfterFinalize.y)).toBeGreaterThan(
+ Math.hypot(lastBeforeFinalize.x, lastBeforeFinalize.y)
+ );
+ expect(Math.abs(lastAfterFinalize.x * normX + lastAfterFinalize.y * normY)).toBeLessThan(0.25);
+ });
});
describe('WebGlBrushEngine Integration & Canvas 2D Fallback in stampEngine', () => {
diff --git a/src/utils/__tests__/strokeStabilizerAndTabletResilience.test.ts b/src/utils/__tests__/strokeStabilizerAndTabletResilience.test.ts
new file mode 100644
index 0000000..a232661
--- /dev/null
+++ b/src/utils/__tests__/strokeStabilizerAndTabletResilience.test.ts
@@ -0,0 +1,328 @@
+import { describe, it, expect, vi } from 'vitest';
+import { InputStabilizer } from '../../engine/InputStabilizer';
+import { StrokePipeline, POINTER_TYPE_PEN } from '../../engine/StrokePipeline';
+import { TaperEngine } from '../../engine/TaperEngine';
+import { calculateStrokeWidth } from '../canvasUtils';
+import {
+ NativeTabletBridgeState,
+ processNativeTabletBatch,
+} from '../../hooks/drawing/brushStrokeSession/nativeTabletBridge';
+import {
+ NativeTabletSample,
+ recordNativeTabletBatchForSuppression,
+ resetNativeTabletSuppressionState,
+ shouldSuppressDomPointerEvent,
+} from '../nativeTabletInput';
+
+describe('InputStabilizer CSP-Calibrated Lag Bounds & Smooth Sine Wave Tracking', () => {
+ it('bypasses completely at level 0 and scales lag cleanly from level 1 (~3px) to level 50 (<=48px)', () => {
+ const stab0 = new InputStabilizer();
+ stab0.setStabilizerLevel(0);
+ stab0.setZoomScale(1.0);
+ for (let i = 0; i <= 30; i++) {
+ const s = stab0.process(i * 6, i * 3, 0.6, 1000 + i * 4);
+ expect(s.x).toBe(i * 6);
+ expect(s.y).toBe(i * 3);
+ }
+
+ const measureSteadyLag = (level: number, stepPx: number, dtMs: number) => {
+ const stab = new InputStabilizer();
+ stab.setStabilizerLevel(level);
+ stab.setZoomScale(1.0);
+ let maxLag = 0;
+ let lastLag = 0;
+ for (let i = 0; i <= 80; i++) {
+ const rx = i * stepPx;
+ const ry = 0;
+ const s = stab.process(rx, ry, 0.7, 1000 + i * dtMs);
+ lastLag = Math.hypot(rx - s.x, ry - s.y);
+ if (i >= 20 && lastLag > maxLag) maxLag = lastLag;
+ }
+ return { maxLag, lastLag };
+ };
+
+ const lag1 = measureSteadyLag(1, 2, 8);
+ expect(lag1.lastLag).toBeGreaterThan(1.5);
+ expect(lag1.lastLag).toBeLessThan(5.0);
+
+ // G-Pen default (level 20): strictly <= 18 screen px across slow, medium, and fast speeds
+ const lag20Slow = measureSteadyLag(20, 2.5, 8); // 0.31 px/ms
+ const lag20Med = measureSteadyLag(20, 5.0, 4); // 1.25 px/ms
+ const lag20Fast = measureSteadyLag(20, 10.0, 4); // 2.50 px/ms
+
+ expect(lag20Slow.maxLag).toBeLessThanOrEqual(18.0);
+ expect(lag20Slow.lastLag).toBeGreaterThanOrEqual(6.0);
+ expect(lag20Med.maxLag).toBeLessThanOrEqual(18.0);
+ expect(lag20Fast.maxLag).toBeLessThanOrEqual(18.0);
+ // Velocity-adaptive tightening: faster strokes tighten lag compared to slow strokes
+ expect(lag20Fast.lastLag).toBeLessThan(lag20Slow.lastLag);
+
+ // Real G-Pen default (level 18): strictly <= 16 screen px
+ const lag18 = measureSteadyLag(18, 4.0, 4);
+ expect(lag18.maxLag).toBeLessThanOrEqual(16.5);
+
+ // Max stabilization (level 50): bounded <= 48 screen px
+ const lag50Slow = measureSteadyLag(50, 3.0, 8);
+ expect(lag50Slow.maxLag).toBeLessThanOrEqual(48.5);
+ expect(lag50Slow.lastLag).toBeGreaterThan(30.0);
+ });
+
+ it('tracks slow and fast sine waves at level 20 with <= 18px lag and ZERO >15px single-step corner teleports', () => {
+ const testWave = (level: number, stepX: number, dtMs: number, amp: number, wavelength: number) => {
+ const stab = new InputStabilizer();
+ stab.setStabilizerLevel(level);
+ stab.setZoomScale(1.0);
+ stab.setSharpCorners(true);
+
+ let prevX = 0;
+ let prevY = 0;
+ let maxLag = 0;
+ let maxStepJump = 0;
+ let cornerCount = 0;
+ let droppedBacktrackSteps = 0;
+
+ const totalSteps = 200;
+ for (let i = 0; i <= totalSteps; i++) {
+ const rx = i * stepX;
+ const ry = amp * Math.sin((rx / wavelength) * Math.PI * 2);
+ const s = stab.process(rx, ry, 0.65, 1000 + i * dtMs);
+ const lag = Math.hypot(rx - s.x, ry - s.y);
+ if (lag > maxLag) maxLag = lag;
+ if (s.isCorner) cornerCount++;
+ if (i > 0) {
+ const jump = Math.hypot(s.x - prevX, s.y - prevY);
+ if (jump > maxStepJump) maxStepJump = jump;
+ if (jump < 1e-4) droppedBacktrackSteps++;
+ }
+ prevX = s.x;
+ prevY = s.y;
+ }
+
+ return { maxLag, maxStepJump, cornerCount, droppedBacktrackSteps };
+ };
+
+ // Slow smooth sine wave (G-Pen level 20)
+ const slowWave = testWave(20, 2.0, 8, 45, 140);
+ expect(slowWave.cornerCount).toBe(0);
+ expect(slowWave.maxLag).toBeLessThanOrEqual(18.0);
+ expect(slowWave.maxStepJump).toBeLessThanOrEqual(15.0);
+ expect(slowWave.droppedBacktrackSteps).toBe(0);
+
+ // Fast smooth sine wave (G-Pen level 20)
+ const fastWave = testWave(20, 4.5, 4, 55, 160);
+ expect(fastWave.cornerCount).toBe(0);
+ expect(fastWave.maxLag).toBeLessThanOrEqual(18.0);
+ expect(fastWave.maxStepJump).toBeLessThanOrEqual(15.0);
+ expect(fastWave.droppedBacktrackSteps).toBe(0);
+
+ // Tight high-curvature wave (Real G-Pen level 18)
+ const tightWave = testWave(18, 2.5, 4, 40, 90);
+ expect(tightWave.cornerCount).toBe(0);
+ expect(tightWave.maxLag).toBeLessThanOrEqual(18.0);
+ expect(tightWave.maxStepJump).toBeLessThanOrEqual(15.0);
+ expect(tightWave.droppedBacktrackSteps).toBe(0);
+ });
+
+ it('closes stroke tails cleanly all the way to the true pen-lift coordinate on finalizeStroke', () => {
+ const pipeline = new StrokePipeline();
+ pipeline.beginStroke({ stabilizerLevel: 20, zoom: 1.0, sharpCorners: true, brushSize: 8 });
+
+ const endX = 320;
+ const endY = 85;
+ for (let i = 0; i <= 40; i++) {
+ const frac = i / 40;
+ const x = frac * endX;
+ const y = frac * endY + Math.sin(frac * Math.PI) * 30;
+ pipeline.enqueueSample(x, y, 0.65, 0, 0, 0, 1000 + i * 4, POINTER_TYPE_PEN);
+ }
+ pipeline.drain();
+
+ const catchUp = pipeline.getStabilizer().getCatchUpTarget();
+ expect(catchUp.x).toBeCloseTo(endX, 4);
+ expect(catchUp.y).toBeCloseTo(endY, 4);
+
+ const tailPts: Array<{ x: number; y: number }> = [];
+ pipeline.finalizeStroke(1200, {
+ enableFlickTaper: false,
+ onPoint: (pt) => tailPts.push({ x: pt.x, y: pt.y }),
+ });
+
+ expect(tailPts.length).toBeGreaterThanOrEqual(2);
+ const finalPt = tailPts[tailPts.length - 1];
+ expect(Math.hypot(finalPt.x - endX, finalPt.y - endY)).toBeLessThan(0.05);
+ });
+
+ it('bridges predicted segments toward live raw stylus coordinate when stabilized without mutating dirtyRect', () => {
+ const pipeline = new StrokePipeline();
+ pipeline.beginStroke({ stabilizerLevel: 20, zoom: 1.0, sharpCorners: true, brushSize: 8 });
+ for (let i = 0; i <= 15; i++) {
+ pipeline.enqueueSample(i * 6, 100, 0.7, 0, 0, 0, 1000 + i * 4, POINTER_TYPE_PEN);
+ }
+ pipeline.drain();
+
+ const dirtyBefore = { ...pipeline.dirtyRect };
+ const knotsBefore = pipeline.getKnotCount();
+ const segEnds: Array<{ x: number; y: number }> = [];
+ const drew = pipeline.buildPredictedSegments(
+ [{ x: 96, y: 100, pressure: 0.7 }],
+ 20,
+ (seg) => segEnds.push({ x: seg.p3.x, y: seg.p3.y })
+ );
+
+ expect(drew).toBe(true);
+ // Includes bridge + stabilizer-to-raw catch-up + hardware predicted event
+ expect(segEnds.length).toBeGreaterThanOrEqual(3);
+ expect(segEnds[segEnds.length - 1].x).toBeCloseTo(96, 1);
+ expect(pipeline.dirtyRect).toEqual(dirtyBefore);
+ expect(pipeline.getKnotCount()).toBe(knotsBefore);
+ });
+});
+
+describe('Native Tablet Bridge Resilience & Light-Pressure Anti-Collapse', () => {
+ const makeSample = (overrides: Partial<NativeTabletSample>): NativeTabletSample => ({
+ clientX: 200,
+ clientY: 200,
+ pressure: 0.5,
+ tiltX: 0,
+ tiltY: 0,
+ twist: 0,
+ timestamp: 1000,
+ buttons: 1,
+ phase: 2,
+ backend: 2,
+ ...overrides,
+ });
+
+ it('ignores spurious child-HWND phase=4 (leave) while in-contact and recovers if phase=1 was missed', () => {
+ const bridge: NativeTabletBridgeState = {
+ nativeStrokeActive: false,
+ prevToolBeforeEraserFlip: null,
+ };
+ const modKeys = { shift: false, alt: false };
+ const onPointerDown = vi.fn();
+ const onPointerMove = vi.fn();
+ const onPointerUp = vi.fn();
+ const onHover = vi.fn();
+
+ const cb = {
+ getTool: () => 'brush' as const,
+ selectTool: vi.fn(),
+ isDisabled: () => false,
+ isPointOverCanvasViewport: () => true,
+ onPointerDown,
+ onPointerMove,
+ onPointerUp,
+ onHover,
+ };
+
+ // 1. Start stroke (phase 1) -> drag (phase 2) -> spurious phase 4 while buttons & 1 is set -> more drag
+ processNativeTabletBatch(
+ [
+ makeSample({ phase: 1, clientX: 100, clientY: 100, pressure: 0.4, buttons: 1, timestamp: 100 }),
+ makeSample({ phase: 2, clientX: 110, clientY: 100, pressure: 0.4, buttons: 1, timestamp: 104 }),
+ // Spurious child-HWND WM_POINTERLEAVE with tip still contacting
+ makeSample({ phase: 4, clientX: 112, clientY: 100, pressure: 0.35, buttons: 1, timestamp: 106 }),
+ makeSample({ phase: 2, clientX: 120, clientY: 100, pressure: 0.45, buttons: 1, timestamp: 108 }),
+ ],
+ bridge,
+ modKeys,
+ cb
+ );
+
+ expect(bridge.nativeStrokeActive).toBe(true);
+ expect(onPointerDown).toHaveBeenCalledTimes(1);
+ expect(onPointerUp).not.toHaveBeenCalled();
+ expect(onPointerMove).toHaveBeenCalledTimes(2);
+
+ // 2. Genuine pen up (phase 3) ends stroke cleanly
+ processNativeTabletBatch(
+ [makeSample({ phase: 3, clientX: 125, clientY: 100, pressure: 0, buttons: 0, timestamp: 112 })],
+ bridge,
+ modKeys,
+ cb
+ );
+ expect(bridge.nativeStrokeActive).toBe(false);
+ expect(onPointerUp).toHaveBeenCalledTimes(1);
+
+ // 3. Recovery when phase=1 was missed and phase=2 arrives in-contact over canvas viewport
+ processNativeTabletBatch(
+ [
+ makeSample({ phase: 2, clientX: 200, clientY: 200, pressure: 0.3, buttons: 1, timestamp: 200 }),
+ makeSample({ phase: 2, clientX: 210, clientY: 205, pressure: 0.35, buttons: 1, timestamp: 204 }),
+ makeSample({ phase: 2, clientX: 220, clientY: 210, pressure: 0.4, buttons: 1, timestamp: 208 }),
+ ],
+ bridge,
+ modKeys,
+ cb
+ );
+
+ expect(bridge.nativeStrokeActive).toBe(true);
+ expect(onPointerDown).toHaveBeenCalledTimes(2);
+ expect(onPointerMove).toHaveBeenCalledTimes(3);
+
+ // 4. True out-of-proximity phase=4 (buttons=0, pressure=0) ends stroke cleanly
+ processNativeTabletBatch(
+ [makeSample({ phase: 4, clientX: 220, clientY: 210, pressure: 0, buttons: 0, timestamp: 212 })],
+ bridge,
+ modKeys,
+ cb
+ );
+ expect(bridge.nativeStrokeActive).toBe(false);
+ expect(onPointerUp).toHaveBeenCalledTimes(2);
+ });
+
+ it('prevents light continuous pen contact (> 0.005) from collapsing to zero pressure or invisible 0.1px width', () => {
+ const taper = new TaperEngine();
+
+ // True zero remains zero
+ expect(taper.mapPressure(0)).toBe(0);
+ // Light continuous pen contact (> 0.005) produces positive pressure instead of 0
+ const pLight = taper.mapPressure(0.01);
+ expect(pLight).toBeGreaterThan(0.01);
+
+ // G-Pen (size 8, minSizeFactor 0.04) at light continuous contact never collapses to width=0.1
+ const wLight = calculateStrokeWidth(8, pLight, 0.04, true, 'pen');
+ expect(wLight).toBeGreaterThanOrEqual(0.35);
+
+ // Flick taper / zero pressure still tapers down to 0.1px
+ const wZero = calculateStrokeWidth(8, 0.0, 0.0, true, 'pen');
+ expect(wZero).toBeCloseTo(0.1, 4);
+ });
+
+ it('suppresses WinTab CXO_SYSTEM synthetic mouse events during native pen strokes while preserving real mouse after pen leaves', () => {
+ resetNativeTabletSuppressionState(true);
+
+ // 1. Stylus hovering in proximity (phase=0) via WinTab -> suppress both DOM pen & synthetic mouse
+ recordNativeTabletBatchForSuppression(
+ [makeSample({ phase: 0, clientX: 300, clientY: 220, pressure: 0, buttons: 0, backend: 1 })],
+ 1000
+ );
+ expect(shouldSuppressDomPointerEvent('pen', 300, 220, 1005)).toBe(true);
+ expect(shouldSuppressDomPointerEvent('mouse', 300, 220, 1005)).toBe(true);
+
+ // 2. Stylus touches down (phase=1) with heavy pressure -> WinTab CXO_SYSTEM fires DOM mouse pointerdown (pressure=0.5)
+ // Must be suppressed so it NEVER aborts/hijacks the active native pen stroke!
+ recordNativeTabletBatchForSuppression(
+ [makeSample({ phase: 1, clientX: 302, clientY: 225, pressure: 0.92, buttons: 1, backend: 1 })],
+ 1010
+ );
+ expect(shouldSuppressDomPointerEvent('mouse', 302, 225, 1012)).toBe(true);
+ expect(shouldSuppressDomPointerEvent('mouse', 310, 240, 1100)).toBe(true);
+
+ // 3. Stylus lifts (phase=3) and leaves proximity (phase=4)
+ recordNativeTabletBatchForSuppression(
+ [
+ makeSample({ phase: 3, clientX: 305, clientY: 320, pressure: 0, buttons: 0, backend: 1 }),
+ makeSample({ phase: 4, clientX: 305, clientY: 320, pressure: 0, buttons: 0, backend: 1 }),
+ ],
+ 1120
+ );
+ // Immediate stray mouse up at the exact lift position within 250ms is still suppressed
+ expect(shouldSuppressDomPointerEvent('mouse', 306, 321, 1130)).toBe(true);
+ // Physical mouse used elsewhere (>24px away) or after 250ms works immediately
+ expect(shouldSuppressDomPointerEvent('mouse', 600, 400, 1135)).toBe(false);
+ expect(shouldSuppressDomPointerEvent('mouse', 306, 321, 1400)).toBe(false);
+
+ resetNativeTabletSuppressionState(false);
+ });
+});
diff --git a/src/utils/__tests__/sutGoldenParity.test.ts b/src/utils/__tests__/sutGoldenParity.test.ts
new file mode 100644
index 0000000..168d95e
--- /dev/null
+++ b/src/utils/__tests__/sutGoldenParity.test.ts
@@ -0,0 +1,2278 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import {
+ buildRibbonMeshFromPoints,
+ rasterizeRibbonMeshCpu,
+} from '../../engine/RibbonBrushEngine';
+import {
+ buildBrushRenderOptions,
+ centripetalCatmullRomToBezier,
+ drawBrushCubicBezierSegment,
+ drawBrushDot,
+ renderCompleteStroke,
+} from '../../engine/BrushEngine';
+import { LayerPixelSampler, parseColorToRgb } from '../colorMixingEngine';
+import { renderBrushStrokePreview, clearBrushPreviewCache } from '../brushPreview';
+import {
+ BRUSH_INDEX_LS_KEY,
+ prepareBrushSettingsForCsp,
+ resetBrushStorageCache,
+ saveCustomBrush,
+} from '../brushStorage';
+import {
+ getEffectiveBrushSettings,
+ saveBrushSettingsImmediately,
+} from '../brushPresetManager';
+import {
+ buildExportableBrush,
+ parseInkbFile,
+ serializeInkbBrush,
+} from '../inkbBrushFormat';
+import { parseSutExtractedData } from '../sutParser';
+import type { NativeSutExtract } from '../nativeBackend';
+import {
+ BrushSettings,
+ CspBrush,
+ CspPaperTextureMode,
+ CspSubTipOrder,
+ DEFAULT_BRUSH_DYNAMICS,
+ Point,
+} from '../../types/editor';
+
+// ============================================================================
+// Pixel-exact software Canvas2D rasterizer for deterministic golden parity tests
+// ============================================================================
+
+function createSoftwareCanvas(initW: number, initH: number) {
+ let width = Math.max(1, Math.round(initW));
+ let height = Math.max(1, Math.round(initH));
+ let buf = new Uint8ClampedArray(width * height * 4);
+
+ type State = {
+ a: number;
+ b: number;
+ c: number;
+ d: number;
+ e: number;
+ f: number;
+ alpha: number;
+ op: string;
+ fillStyle: string;
+ };
+ const stack: State[] = [];
+ let st: State = {
+ a: 1,
+ b: 0,
+ c: 0,
+ d: 1,
+ e: 0,
+ f: 0,
+ alpha: 1,
+ op: 'source-over',
+ fillStyle: '#000000',
+ };
+
+ const compositePixel = (di: number, sr: number, sg: number, sb: number, srcA: number) => {
+ const sa = Math.max(0, Math.min(1, srcA));
+ if (sa <= 1e-4) return;
+ const dr = buf[di];
+ const dg = buf[di + 1];
+ const db = buf[di + 2];
+ const da = buf[di + 3] / 255;
+
+ if (st.op === 'destination-out') {
+ const outA = da * (1 - sa);
+ buf[di + 3] = Math.round(Math.max(0, Math.min(255, outA * 255)));
+ if (buf[di + 3] === 0) {
+ buf[di] = 0;
+ buf[di + 1] = 0;
+ buf[di + 2] = 0;
+ }
+ return;
+ }
+
+ if (st.op === 'destination-over') {
+ const outA = da + sa * (1 - da);
+ if (outA <= 1e-4) return;
+ const inv = 1 / outA;
+ buf[di] = Math.round((dr * da + sr * sa * (1 - da)) * inv);
+ buf[di + 1] = Math.round((dg * da + sg * sa * (1 - da)) * inv);
+ buf[di + 2] = Math.round((db * da + sb * sa * (1 - da)) * inv);
+ buf[di + 3] = Math.round(Math.min(255, outA * 255));
+ return;
+ }
+
+ if (st.op === 'source-atop') {
+ if (da <= 1e-4) return;
+ buf[di] = Math.round(sr * sa + dr * (1 - sa));
+ buf[di + 1] = Math.round(sg * sa + dg * (1 - sa));
+ buf[di + 2] = Math.round(sb * sa + db * (1 - sa));
+ return;
+ }
+
+ // Standard source-over (and fallback)
+ const outA = sa + da * (1 - sa);
+ if (outA <= 1e-4) return;
+ const inv = 1 / outA;
+ buf[di] = Math.round((sr * sa + dr * da * (1 - sa)) * inv);
+ buf[di + 1] = Math.round((sg * sa + dg * da * (1 - sa)) * inv);
+ buf[di + 2] = Math.round((sb * sa + db * da * (1 - sa)) * inv);
+ buf[di + 3] = Math.round(Math.min(255, outA * 255));
+ };
+
+ const ctx: any = {
+ get canvas() {
+ return surfaceObj;
+ },
+ get globalAlpha() {
+ return st.alpha;
+ },
+ set globalAlpha(v: number) {
+ st.alpha = v;
+ },
+ get globalCompositeOperation() {
+ return st.op;
+ },
+ set globalCompositeOperation(v: string) {
+ st.op = v;
+ },
+ get fillStyle() {
+ return st.fillStyle;
+ },
+ set fillStyle(v: string) {
+ st.fillStyle = v;
+ },
+ imageSmoothingEnabled: true,
+ save: () => stack.push({ ...st }),
+ restore: () => {
+ const p = stack.pop();
+ if (p) st = p;
+ },
+ getTransform: () => ({ a: st.a, b: st.b, c: st.c, d: st.d, e: st.e, f: st.f }),
+ setTransform: (a: number, b: number, c: number, d: number, e: number, f: number) => {
+ st.a = a;
+ st.b = b;
+ st.c = c;
+ st.d = d;
+ st.e = e;
+ st.f = f;
+ },
+ resetTransform: () => {
+ st.a = 1;
+ st.b = 0;
+ st.c = 0;
+ st.d = 1;
+ st.e = 0;
+ st.f = 0;
+ },
+ translate: (x: number, y: number) => {
+ st.e += st.a * x + st.c * y;
+ st.f += st.b * x + st.d * y;
+ },
+ rotate: (rad: number) => {
+ const cos = Math.cos(rad);
+ const sin = Math.sin(rad);
+ const na = st.a * cos + st.c * sin;
+ const nb = st.b * cos + st.d * sin;
+ const nc = -st.a * sin + st.c * cos;
+ const nd = -st.b * sin + st.d * cos;
+ st.a = na;
+ st.b = nb;
+ st.c = nc;
+ st.d = nd;
+ },
+ scale: (sx: number, sy: number) => {
+ st.a *= sx;
+ st.b *= sx;
+ st.c *= sy;
+ st.d *= sy;
+ },
+ beginPath: () => {},
+ rect: () => {},
+ clip: () => {},
+ clearRect: (x = 0, y = 0, w = width, h = height) => {
+ const x0 = Math.max(0, Math.floor(x));
+ const y0 = Math.max(0, Math.floor(y));
+ const x1 = Math.min(width, Math.ceil(x + w));
+ const y1 = Math.min(height, Math.ceil(y + h));
+ for (let py = y0; py < y1; py++) {
+ buf.fill(0, (py * width + x0) * 4, (py * width + x1) * 4);
+ }
+ },
+ fillRect: (x: number, y: number, w: number, h: number) => {
+ const rgb = parseColorToRgb(st.fillStyle);
+ const x0 = Math.max(0, Math.floor(x + st.e));
+ const y0 = Math.max(0, Math.floor(y + st.f));
+ const x1 = Math.min(width, Math.ceil(x + w + st.e));
+ const y1 = Math.min(height, Math.ceil(y + h + st.f));
+ for (let py = y0; py < y1; py++) {
+ for (let px = x0; px < x1; px++) {
+ const i = (py * width + px) * 4;
+ if (st.op === 'source-in') {
+ if (buf[i + 3] > 0) {
+ buf[i] = rgb.r;
+ buf[i + 1] = rgb.g;
+ buf[i + 2] = rgb.b;
+ }
+ } else {
+ buf[i] = rgb.r;
+ buf[i + 1] = rgb.g;
+ buf[i + 2] = rgb.b;
+ buf[i + 3] = Math.round(st.alpha * 255);
+ }
+ }
+ }
+ },
+ createImageData: (w: number, h: number) => ({
+ width: w,
+ height: h,
+ data: new Uint8ClampedArray(w * h * 4),
+ }),
+ putImageData: (
+ img: { width: number; height: number; data: Uint8ClampedArray },
+ dx = 0,
+ dy = 0
+ ) => {
+ for (let y = 0; y < img.height; y++) {
+ const ty = dy + y;
+ if (ty < 0 || ty >= height) continue;
+ for (let x = 0; x < img.width; x++) {
+ const tx = dx + x;
+ if (tx < 0 || tx >= width) continue;
+ const si = (y * img.width + x) * 4;
+ const di = (ty * width + tx) * 4;
+ buf[di] = img.data[si];
+ buf[di + 1] = img.data[si + 1];
+ buf[di + 2] = img.data[si + 2];
+ buf[di + 3] = img.data[si + 3];
+ }
+ }
+ },
+ getImageData: (sx: number, sy: number, sw: number, sh: number) => {
+ const data = new Uint8ClampedArray(sw * sh * 4);
+ for (let y = 0; y < sh; y++) {
+ const py = sy + y;
+ if (py < 0 || py >= height) continue;
+ for (let x = 0; x < sw; x++) {
+ const px = sx + x;
+ if (px < 0 || px >= width) continue;
+ const si = (py * width + px) * 4;
+ const di = (y * sw + x) * 4;
+ data[di] = buf[si];
+ data[di + 1] = buf[si + 1];
+ data[di + 2] = buf[si + 2];
+ data[di + 3] = buf[si + 3];
+ }
+ }
+ return { width: sw, height: sh, data };
+ },
+ drawImage: (
+ src: any,
+ a1: number,
+ a2: number,
+ a3?: number,
+ a4?: number,
+ a5?: number,
+ a6?: number,
+ a7?: number,
+ a8?: number
+ ) => {
+ const srcBuf: Uint8ClampedArray | undefined = src?.buf;
+ if (!srcBuf) return;
+ const fullSw = src.width || src.naturalWidth || 0;
+ const fullSh = src.height || src.naturalHeight || 0;
+ if (fullSw <= 0 || fullSh <= 0) return;
+
+ let sx = 0,
+ sy = 0,
+ sw = fullSw,
+ sh = fullSh,
+ dx = a1,
+ dy = a2,
+ dw = a3 ?? fullSw,
+ dh = a4 ?? fullSh;
+ if (a8 !== undefined && a7 !== undefined && a6 !== undefined && a5 !== undefined) {
+ sx = a1;
+ sy = a2;
+ sw = a3!;
+ sh = a4!;
+ dx = a5;
+ dy = a6;
+ dw = a7;
+ dh = a8;
+ }
+ if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0) return;
+
+ const det = st.a * st.d - st.b * st.c;
+ if (Math.abs(det) < 1e-8) return;
+ const invDet = 1 / det;
+
+ const corners = [
+ [dx, dy],
+ [dx + dw, dy],
+ [dx, dy + dh],
+ [dx + dw, dy + dh],
+ ];
+ let minX = width,
+ minY = height,
+ maxX = -1,
+ maxY = -1;
+ for (const [lx, ly] of corners) {
+ const wx = st.a * lx + st.c * ly + st.e;
+ const wy = st.b * lx + st.d * ly + st.f;
+ if (wx < minX) minX = wx;
+ if (wy < minY) minY = wy;
+ if (wx > maxX) maxX = wx;
+ if (wy > maxY) maxY = wy;
+ }
+ const ix0 = Math.max(0, Math.floor(minX));
+ const iy0 = Math.max(0, Math.floor(minY));
+ const ix1 = Math.min(width - 1, Math.ceil(maxX));
+ const iy1 = Math.min(height - 1, Math.ceil(maxY));
+
+ for (let py = iy0; py <= iy1; py++) {
+ for (let px = ix0; px <= ix1; px++) {
+ const rx = px + 0.5 - st.e;
+ const ry = py + 0.5 - st.f;
+ const lx = (st.d * rx - st.c * ry) * invDet;
+ const ly = (-st.b * rx + st.a * ry) * invDet;
+ const u = (lx - dx) / dw;
+ const v = (ly - dy) / dh;
+ if (u < 0 || u > 1 || v < 0 || v > 1) continue;
+
+ const fx = sx + u * sw - 0.5;
+ const fy = sy + v * sh - 0.5;
+
+ if (!ctx.imageSmoothingEnabled) {
+ const nx = Math.max(0, Math.min(fullSw - 1, Math.floor(sx + u * sw)));
+ const ny = Math.max(0, Math.min(fullSh - 1, Math.floor(sy + v * sh)));
+ const ni = (ny * fullSw + nx) * 4;
+ const srcA = (srcBuf[ni + 3] / 255) * st.alpha;
+ if (srcA <= 1e-4) continue;
+ compositePixel((py * width + px) * 4, srcBuf[ni], srcBuf[ni + 1], srcBuf[ni + 2], srcA);
+ continue;
+ }
+
+ const x0 = Math.max(0, Math.min(fullSw - 1, Math.floor(fx)));
+ const y0 = Math.max(0, Math.min(fullSh - 1, Math.floor(fy)));
+ const x1 = Math.min(fullSw - 1, x0 + 1);
+ const y1 = Math.min(fullSh - 1, y0 + 1);
+ const tx = Math.max(0, Math.min(1, fx - x0));
+ const ty = Math.max(0, Math.min(1, fy - y0));
+
+ const i00 = (y0 * fullSw + x0) * 4;
+ const i10 = (y0 * fullSw + x1) * 4;
+ const i01 = (y1 * fullSw + x0) * 4;
+ const i11 = (y1 * fullSw + x1) * 4;
+ const w00 = (1 - tx) * (1 - ty);
+ const w10 = tx * (1 - ty);
+ const w01 = (1 - tx) * ty;
+ const w11 = tx * ty;
+
+ const a00 = (srcBuf[i00 + 3] / 255) * w00;
+ const a10 = (srcBuf[i10 + 3] / 255) * w10;
+ const a01 = (srcBuf[i01 + 3] / 255) * w01;
+ const a11 = (srcBuf[i11 + 3] / 255) * w11;
+ const aSum = a00 + a10 + a01 + a11;
+ const srcA = aSum * st.alpha;
+ if (srcA <= 1e-4) continue;
+
+ const sr =
+ (srcBuf[i00] * a00 + srcBuf[i10] * a10 + srcBuf[i01] * a01 + srcBuf[i11] * a11) / aSum;
+ const sg =
+ (srcBuf[i00 + 1] * a00 +
+ srcBuf[i10 + 1] * a10 +
+ srcBuf[i01 + 1] * a01 +
+ srcBuf[i11 + 1] * a11) /
+ aSum;
+ const sb =
+ (srcBuf[i00 + 2] * a00 +
+ srcBuf[i10 + 2] * a10 +
+ srcBuf[i01 + 2] * a01 +
+ srcBuf[i11 + 2] * a11) /
+ aSum;
+
+ compositePixel((py * width + px) * 4, sr, sg, sb, srcA);
+ }
+ }
+ },
+ };
+
+ const surfaceObj: any = {
+ get width() {
+ return width;
+ },
+ set width(v: number) {
+ width = Math.max(1, Math.round(v));
+ buf = new Uint8ClampedArray(width * height * 4);
+ },
+ get height() {
+ return height;
+ },
+ set height(v: number) {
+ height = Math.max(1, Math.round(v));
+ buf = new Uint8ClampedArray(width * height * 4);
+ },
+ get naturalWidth() {
+ return width;
+ },
+ get naturalHeight() {
+ return height;
+ },
+ complete: true,
+ src: `memory://canvas-${width}x${height}`,
+ get buf() {
+ return buf;
+ },
+ getContext: (type: string) => (type === '2d' ? ctx : null),
+ ctx,
+ };
+ return surfaceObj;
+}
+
+// ============================================================================
+// Deterministic Synthetic Stylus Trajectory Generator
+// Smooth pressure ramp (0 -> 1 -> 0), tilt sweep, curved S-stroke + sharp corner
+// ============================================================================
+
+interface TrajectoryOptions {
+ startX?: number;
+ startY?: number;
+ width?: number;
+ baseBrushSize?: number;
+ minSizeFactor?: number;
+ stepsS?: number;
+ stepsCornerLeg?: number;
+ includeSharpCorner?: boolean;
+ tiltSweep?: boolean;
+ constantPressure?: number;
+}
+
+function generateSyntheticStylusTrajectory(opts: TrajectoryOptions = {}): {
+ points: Point[];
+ cornerIndex: number;
+ cornerPoint: { x: number; y: number };
+} {
+ const startX = opts.startX ?? 28;
+ const startY = opts.startY ?? 96;
+ const spanX = opts.width ?? 176;
+ const baseSize = opts.baseBrushSize ?? 16;
+ const minFactor = opts.minSizeFactor ?? 0.12;
+ const stepsS = opts.stepsS ?? 32;
+ const stepsCornerLeg = opts.stepsCornerLeg ?? 12;
+ const includeCorner = opts.includeSharpCorner ?? true;
+ const tiltSweep = opts.tiltSweep ?? true;
+
+ const totalSteps = includeCorner ? stepsS + stepsCornerLeg : stepsS;
+ const points: Point[] = [];
+
+ for (let i = 0; i <= stepsS; i++) {
+ const u = i / stepsS;
+ const tGlobal = i / totalSteps;
+ const x = startX + u * spanX;
+ const y = startY - Math.sin(u * Math.PI * 2) * 34;
+
+ // Smooth pressure ramp 0 -> 1 -> 0
+ const rawP =
+ opts.constantPressure !== undefined
+ ? opts.constantPressure
+ : Math.max(0.02, Math.sin(tGlobal * Math.PI));
+ const width = Math.max(1.0, baseSize * (minFactor + (1 - minFactor) * rawP));
+
+ // Tilt sweep from upright (5 deg) to heavily tilted (68 deg)
+ const tiltX = tiltSweep ? Math.round(5 + 63 * tGlobal) : 0;
+ const tiltY = tiltSweep ? Math.round(18 * Math.sin(tGlobal * Math.PI)) : 0;
+
+ points.push({
+ x,
+ y,
+ pressure: rawP,
+ width,
+ tiltX,
+ tiltY,
+ twist: Math.round(u * 90),
+ timestamp: i * 10,
+ isCorner: includeCorner && i === stepsS,
+ });
+ }
+
+ const cornerIndex = points.length - 1;
+ const cornerPt = { x: points[cornerIndex].x, y: points[cornerIndex].y };
+
+ if (includeCorner) {
+ // Sharp ~125-degree reversal down-left to stress corner snapping & miter guards
+ const endX = cornerPt.x - 42;
+ const endY = cornerPt.y + 46;
+ for (let j = 1; j <= stepsCornerLeg; j++) {
+ const v = j / stepsCornerLeg;
+ const tGlobal = (stepsS + j) / totalSteps;
+ const x = cornerPt.x + (endX - cornerPt.x) * v;
+ const y = cornerPt.y + (endY - cornerPt.y) * v;
+ const rawP =
+ opts.constantPressure !== undefined
+ ? opts.constantPressure
+ : Math.max(0.02, Math.sin(tGlobal * Math.PI));
+ const width = Math.max(1.0, baseSize * (minFactor + (1 - minFactor) * rawP));
+ const tiltX = tiltSweep ? Math.round(5 + 63 * tGlobal) : 0;
+ const tiltY = tiltSweep ? Math.round(18 * Math.sin(tGlobal * Math.PI)) : 0;
+
+ points.push({
+ x,
+ y,
+ pressure: rawP,
+ width,
+ tiltX,
+ tiltY,
+ twist: Math.round(90 + v * 45),
+ timestamp: (stepsS + j) * 10,
+ isCorner: false,
+ });
+ }
+ }
+
+ return { points, cornerIndex, cornerPoint: cornerPt };
+}
+
+function generateHorizontalStroke(
+ x0: number,
+ x1: number,
+ y: number,
+ baseSize: number,
+ steps: number = 32,
+ pressureFn?: (u: number) => number,
+ tiltFn?: (u: number) => { tiltX: number; tiltY: number }
+): Point[] {
+ const pts: Point[] = [];
+ for (let i = 0; i <= steps; i++) {
+ const u = i / steps;
+ const p = pressureFn ? pressureFn(u) : 0.85;
+ const tilt = tiltFn ? tiltFn(u) : { tiltX: 0, tiltY: 0 };
+ pts.push({
+ x: x0 + (x1 - x0) * u,
+ y,
+ pressure: p,
+ width: Math.max(1, baseSize * p),
+ tiltX: tilt.tiltX,
+ tiltY: tilt.tiltY,
+ timestamp: i * 10,
+ });
+ }
+ return pts;
+}
+
+// ============================================================================
+// Procedural Tip & Texture Helpers for Headless Raster Verification
+// ============================================================================
+
+function makeFlatBristleTip(size: number = 32, tufts: number = 6) {
+ const c = createSoftwareCanvas(size, size);
+ c.src = `memory://bristle-${size}-${tufts}`;
+ const data = c.buf;
+ for (let y = 0; y < size; y++) {
+ const ny = (y / (size - 1)) * 2 - 1;
+ for (let x = 0; x < size; x++) {
+ const nx = (x / (size - 1)) * 2 - 1;
+ // Flat elliptical envelope with discrete bristle ridges
+ const env = 1 - (nx * nx * 1.15 + ny * ny * 3.2);
+ if (env <= 0) continue;
+ const ridge = 0.5 + 0.5 * Math.cos(nx * Math.PI * tufts);
+ const a = Math.max(0, Math.min(1, env * (0.35 + 0.65 * ridge)));
+ const i = (y * size + x) * 4;
+ data[i] = 255;
+ data[i + 1] = 255;
+ data[i + 2] = 255;
+ data[i + 3] = Math.round(a * 255);
+ }
+ }
+ return c as unknown as HTMLImageElement;
+}
+
+function makeColorRibbonTip(size: number = 32) {
+ const c = createSoftwareCanvas(size, size);
+ c.src = `memory://color-ribbon-${size}`;
+ const data = c.buf;
+ for (let y = 0; y < size; y++) {
+ const edgeFade = Math.min(1, Math.min(y + 1, size - y) / 3);
+ for (let x = 0; x < size; x++) {
+ const i = (y * size + x) * 4;
+ const frac = x / size;
+ // Asymmetric directional RGB pattern so Repeat vs Reverse differ clearly
+ if (frac < 0.35) {
+ data[i] = 240;
+ data[i + 1] = 35;
+ data[i + 2] = 35;
+ } else if (frac < 0.7) {
+ data[i] = 35;
+ data[i + 1] = 225;
+ data[i + 2] = 55;
+ } else {
+ data[i] = 35;
+ data[i + 1] = 70;
+ data[i + 2] = 245;
+ }
+ data[i + 3] = Math.round(255 * edgeFade);
+ }
+ }
+ return c as unknown as HTMLImageElement;
+}
+
+function makeDualToneGrayTip(size: number = 32) {
+ const c = createSoftwareCanvas(size, size);
+ c.src = `memory://dual-tone-gray-${size}`;
+ const data = c.buf;
+ const half = (size - 1) * 0.5;
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const dist = Math.hypot(x - half, y - half) / half;
+ if (dist > 1.0) continue;
+ const i = (y * size + x) * 4;
+ // Dark center (gray=0 -> Main Color), bright outer ring (gray=255 -> Sub Color)
+ const gray = dist < 0.52 ? 0 : 255;
+ data[i] = gray;
+ data[i + 1] = gray;
+ data[i + 2] = gray;
+ data[i + 3] = 255;
+ }
+ }
+ return c as unknown as HTMLImageElement;
+}
+
+function makeCheckerGrainTexture(size: number = 32) {
+ const c = createSoftwareCanvas(size, size);
+ c.src = `memory://checker-grain-${size}`;
+ const data = c.buf;
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const i = (y * size + x) * 4;
+ const v = ((Math.floor(x / 3) + Math.floor(y / 3)) & 1) === 0 ? 235 : 30;
+ data[i] = v;
+ data[i + 1] = v;
+ data[i + 2] = v;
+ data[i + 3] = 255;
+ }
+ }
+ return c as unknown as HTMLImageElement;
+}
+
+function makeDualPatternTip(size: number = 24) {
+ const c = createSoftwareCanvas(size, size);
+ c.src = `memory://dual-pattern-${size}`;
+ const data = c.buf;
+ const half = (size - 1) * 0.5;
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const d = Math.hypot(x - half, y - half) / half;
+ if (d > 1) continue;
+ // Ring + core pattern so multiply/subtract/height show rich texture modulation
+ const a = d < 0.45 ? 1.0 : d < 0.72 ? 0.25 : 0.85;
+ const i = (y * size + x) * 4;
+ data[i] = 255;
+ data[i + 1] = 255;
+ data[i + 2] = 255;
+ data[i + 3] = Math.round(a * 255);
+ }
+ }
+ return c as unknown as HTMLImageElement;
+}
+
+// ============================================================================
+// Quantitative Raster Metric Helpers
+// ============================================================================
+
+interface RasterMetrics {
+ litPixels: number;
+ opaquePixels: number;
+ semiTransparentPixels: number;
+ alphaSum: number;
+ meanLitAlpha: number;
+ alphaVariance: number;
+ minX: number;
+ maxX: number;
+ minY: number;
+ maxY: number;
+ hasInvalidValues: boolean;
+}
+
+function analyzeRaster(buf: Uint8ClampedArray, width: number, height: number): RasterMetrics {
+ let litPixels = 0;
+ let opaquePixels = 0;
+ let semiTransparentPixels = 0;
+ let alphaSum = 0;
+ let minX = width;
+ let maxX = -1;
+ let minY = height;
+ let maxY = -1;
+ let hasInvalidValues = false;
+
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const i = (y * width + x) * 4;
+ const r = buf[i];
+ const g = buf[i + 1];
+ const b = buf[i + 2];
+ const a = buf[i + 3];
+ if (!Number.isFinite(r) || !Number.isFinite(g) || !Number.isFinite(b) || !Number.isFinite(a)) {
+ hasInvalidValues = true;
+ }
+ if (a > 0) {
+ litPixels++;
+ alphaSum += a;
+ if (a === 255) opaquePixels++;
+ else semiTransparentPixels++;
+ if (x < minX) minX = x;
+ if (x > maxX) maxX = x;
+ if (y < minY) minY = y;
+ if (y > maxY) maxY = y;
+ }
+ }
+ }
+
+ const meanLitAlpha = litPixels > 0 ? alphaSum / litPixels : 0;
+ let sqDiff = 0;
+ if (litPixels > 0) {
+ for (let i = 3; i < buf.length; i += 4) {
+ if (buf[i] > 0) {
+ const d = buf[i] - meanLitAlpha;
+ sqDiff += d * d;
+ }
+ }
+ }
+
+ return {
+ litPixels,
+ opaquePixels,
+ semiTransparentPixels,
+ alphaSum,
+ meanLitAlpha,
+ alphaVariance: litPixels > 0 ? sqDiff / litPixels : 0,
+ minX,
+ maxX,
+ minY,
+ maxY,
+ hasInvalidValues,
+ };
+}
+
+function measureVerticalExtentAtX(
+ buf: Uint8ClampedArray,
+ width: number,
+ height: number,
+ xCenter: number,
+ halfWindow: number = 2,
+ alphaThreshold: number = 20
+): number {
+ let minY = height;
+ let maxY = -1;
+ const x0 = Math.max(0, Math.round(xCenter - halfWindow));
+ const x1 = Math.min(width - 1, Math.round(xCenter + halfWindow));
+ for (let y = 0; y < height; y++) {
+ for (let x = x0; x <= x1; x++) {
+ if (buf[(y * width + x) * 4 + 3] >= alphaThreshold) {
+ if (y < minY) minY = y;
+ if (y > maxY) maxY = y;
+ }
+ }
+ }
+ return maxY >= minY ? maxY - minY + 1 : 0;
+}
+
+function countUnbrokenCenterlineCoverage(
+ buf: Uint8ClampedArray,
+ width: number,
+ height: number,
+ points: Point[],
+ radius: number = 2
+): { covered: number; total: number } {
+ let covered = 0;
+ for (const pt of points) {
+ const cx = Math.round(pt.x);
+ const cy = Math.round(pt.y);
+ let maxA = 0;
+ for (let dy = -radius; dy <= radius; dy++) {
+ for (let dx = -radius; dx <= radius; dx++) {
+ const px = cx + dx;
+ const py = cy + dy;
+ if (px >= 0 && px < width && py >= 0 && py < height) {
+ const a = buf[(py * width + px) * 4 + 3];
+ if (a > maxA) maxA = a;
+ }
+ }
+ }
+ if (maxA > 10) covered++;
+ }
+ return { covered, total: points.length };
+}
+
+function baseBrushSettings(overrides: Partial<BrushSettings> = {}): BrushSettings {
+ return {
+ size: 16,
+ minSizeFactor: 0.12,
+ color: '#181818',
+ secondaryColor: '#2563eb',
+ opacity: 1.0,
+ flow: 1.0,
+ spacing: 0.06,
+ hardness: 1.0,
+ thickness: 1.0,
+ antiAlias: 2,
+ usePressure: true,
+ useTilt: false,
+ smoothing: true,
+ stabilization: 0,
+ sharpCorners: true,
+ useGpu: false,
+ ...overrides,
+ };
+}
+
+// ============================================================================
+// Golden Parity Test Suite
+// ============================================================================
+
+describe('CSP .sut Golden Parity Suite (9 Canonical Archetypes + Preview + Persistence)', () => {
+ const prevDoc = (globalThis as any).document;
+ const prevWindow = (globalThis as any).window;
+ const prevLocalStorage = (globalThis as any).localStorage;
+ let lsStore: Map<string, string>;
+
+ beforeEach(() => {
+ clearBrushPreviewCache();
+ resetBrushStorageCache();
+ lsStore = new Map<string, string>();
+ (globalThis as any).document = {
+ createElement: (tag: string) => {
+ if (tag === 'canvas') return createSoftwareCanvas(64, 64);
+ return {};
+ },
+ };
+ (globalThis as any).window = {
+ devicePixelRatio: 1,
+ dispatchEvent: () => true,
+ };
+ (globalThis as any).localStorage = {
+ getItem: (k: string) => (lsStore.has(k) ? lsStore.get(k)! : null),
+ setItem: (k: string, v: string) => {
+ lsStore.set(k, String(v));
+ },
+ removeItem: (k: string) => {
+ lsStore.delete(k);
+ },
+ clear: () => lsStore.clear(),
+ };
+ });
+
+ afterEach(() => {
+ (globalThis as any).document = prevDoc;
+ (globalThis as any).window = prevWindow;
+ (globalThis as any).localStorage = prevLocalStorage;
+ });
+
+ // --------------------------------------------------------------------------
+ // Archetype 1: Hard Inker / G-Pen
+ // --------------------------------------------------------------------------
+ it('Archetype 1: Hard Inker / G-Pen preserves S-curve pressure, sharp corners, and crisp AA', () => {
+ const W = 256;
+ const H = 192;
+ const traj = generateSyntheticStylusTrajectory({
+ baseBrushSize: 16,
+ minSizeFactor: 0.08,
+ includeSharpCorner: true,
+ tiltSweep: false,
+ });
+
+ const sCurve: [number, number][] = [
+ [0, 0],
+ [0.25, 0.08],
+ [0.5, 0.48],
+ [0.75, 0.9],
+ [1, 1],
+ ];
+
+ const cBinary = createSoftwareCanvas(W, H);
+ renderCompleteStroke(
+ cBinary.ctx,
+ traj.points,
+ baseBrushSettings({
+ size: 16,
+ minSizeFactor: 0.08,
+ hardness: 1.0,
+ spacing: 0.04,
+ antiAlias: 0,
+ sharpCorners: true,
+ pressureCurve: sCurve,
+ }),
+ 'brush',
+ 'color'
+ );
+
+ const cSmooth = createSoftwareCanvas(W, H);
+ renderCompleteStroke(
+ cSmooth.ctx,
+ traj.points,
+ baseBrushSettings({
+ size: 16,
+ minSizeFactor: 0.08,
+ hardness: 1.0,
+ spacing: 0.04,
+ antiAlias: 2,
+ sharpCorners: true,
+ pressureCurve: sCurve,
+ }),
+ 'brush',
+ 'color'
+ );
+
+ const mBin = analyzeRaster(cBinary.buf, W, H);
+ const mSmooth = analyzeRaster(cSmooth.buf, W, H);
+
+ expect(mBin.hasInvalidValues).toBe(false);
+ expect(mSmooth.hasInvalidValues).toBe(false);
+ expect(mBin.litPixels).toBeGreaterThan(800);
+ expect(mSmooth.litPixels).toBeGreaterThan(800);
+
+ // Binary AA=0 invariant: strictly crisp 0/255 alpha histogram
+ expect(mBin.semiTransparentPixels).toBe(0);
+ expect(mBin.opaquePixels).toBe(mBin.litPixels);
+
+ // Smooth AA=2 invariant: crisp opaque interior + narrow anti-aliased edge band
+ expect(mSmooth.opaquePixels).toBeGreaterThan(mSmooth.litPixels * 0.55);
+ expect(mSmooth.semiTransparentPixels).toBeGreaterThan(20);
+ expect(mSmooth.semiTransparentPixels / mSmooth.litPixels).toBeLessThan(0.45);
+
+ // Sharp corner apex inked solidly with zero dropouts
+ const cov = countUnbrokenCenterlineCoverage(cSmooth.buf, W, H, traj.points, 2);
+ expect(cov.covered).toBe(cov.total);
+ const cx = Math.round(traj.cornerPoint.x);
+ const cy = Math.round(traj.cornerPoint.y);
+ expect(cSmooth.buf[(cy * W + cx) * 4 + 3]).toBeGreaterThan(200);
+
+ // Pressure ramp width invariant: peak mid-stroke clearly thicker than start tip
+ const startExtent = measureVerticalExtentAtX(cSmooth.buf, W, H, traj.points[1].x, 1);
+ const peakExtent = measureVerticalExtentAtX(cSmooth.buf, W, H, traj.points[22].x, 2);
+ expect(peakExtent).toBeGreaterThan(startExtent);
+ });
+
+ // --------------------------------------------------------------------------
+ // Archetype 2: Textured Pencil
+ // --------------------------------------------------------------------------
+ it('Archetype 2: Textured Pencil applies tilt spread, opacity/density sensors, and height vs compare grain', () => {
+ const W = 256;
+ const H = 128;
+ const grainTex = makeCheckerGrainTexture(32);
+
+ const pts = generateHorizontalStroke(
+ 24,
+ 232,
+ 64,
+ 14,
+ 36,
+ (u) => 0.35 + 0.6 * Math.sin(u * Math.PI),
+ (u) => ({ tiltX: Math.round(5 + 65 * u), tiltY: 0 })
+ );
+
+ const makePencil = (mode: CspPaperTextureMode): BrushSettings =>
+ baseBrushSettings({
+ size: 14,
+ minSizeFactor: 0.2,
+ hardness: 0.78,
+ flow: 0.75,
+ spacing: 0.08,
+ usePressure: true,
+ useTilt: true,
+ tiltScale: 1.6,
+ sizeSensor: { usePressure: true, pressureMin: 0.25, useTilt: true, tiltMin: 0.4 },
+ opacitySensor: { usePressure: true, pressureMin: 0.25 },
+ densitySensor: { usePressure: true, pressureMin: 0.3 },
+ grain: 0.85,
+ textureDensity: 0.85,
+ paperTextureImage: grainTex,
+ paperTextureMode: mode,
+ paperTextureScale: 1.0,
+ paperTextureApplyEachPlot: false,
+ });
+
+ const cHeight = createSoftwareCanvas(W, H);
+ renderCompleteStroke(cHeight.ctx, pts, makePencil('height'), 'brush', 'color');
+
+ const cCompare = createSoftwareCanvas(W, H);
+ renderCompleteStroke(cCompare.ctx, pts, makePencil('compare'), 'brush', 'color');
+
+ const mHeight = analyzeRaster(cHeight.buf, W, H);
+ const mCompare = analyzeRaster(cCompare.buf, W, H);
+
+ expect(mHeight.hasInvalidValues).toBe(false);
+ expect(mCompare.hasInvalidValues).toBe(false);
+ expect(mHeight.litPixels).toBeGreaterThan(400);
+ expect(mCompare.litPixels).toBeGreaterThan(400);
+
+ // Grain texture contrast invariant: measurable variance in alpha across the textured stroke
+ expect(mHeight.alphaVariance).toBeGreaterThan(150);
+ expect(mCompare.alphaVariance).toBeGreaterThan(80);
+
+ // Distinct alpha histogram between 'height' and 'compare'
+ let pixelDiffCount = 0;
+ for (let i = 3; i < cHeight.buf.length; i += 4) {
+ if (Math.abs(cHeight.buf[i] - cCompare.buf[i]) > 8) pixelDiffCount++;
+ }
+ expect(pixelDiffCount).toBeGreaterThan(80);
+
+ // Tilt spread invariant: later high-tilt region should be wider than early low-tilt region at comparable pressure
+ const cTilt = createSoftwareCanvas(W, H);
+ const constPressTiltPts = generateHorizontalStroke(
+ 24,
+ 232,
+ 64,
+ 14,
+ 36,
+ () => 0.75,
+ (u) => ({ tiltX: Math.round(5 + 70 * u), tiltY: 0 })
+ );
+ renderCompleteStroke(
+ cTilt.ctx,
+ constPressTiltPts,
+ baseBrushSettings({
+ size: 14,
+ hardness: 0.85,
+ flow: 0.9,
+ spacing: 0.06,
+ useTilt: true,
+ tiltScale: 1.8,
+ sizeSensor: { useTilt: true, tiltMin: 0.35 },
+ }),
+ 'brush',
+ 'color'
+ );
+ const lowTiltW = measureVerticalExtentAtX(cTilt.buf, W, H, 45, 3);
+ const highTiltW = measureVerticalExtentAtX(cTilt.buf, W, H, 210, 3);
+ expect(highTiltW).toBeGreaterThan(lowTiltW);
+ });
+
+ // --------------------------------------------------------------------------
+ // Archetype 3: Flat Oil Paint
+ // --------------------------------------------------------------------------
+ it('Archetype 3: Flat Oil Paint produces spatial color mixing gradient, per-plot grain, and taper', () => {
+ const W = 256;
+ const H = 128;
+ const flatTip = makeFlatBristleTip(32, 5);
+ const grainTex = makeCheckerGrainTexture(32);
+
+ const prepareSplitCanvas = () => {
+ const c = createSoftwareCanvas(W, H);
+ c.ctx.fillStyle = '#dc2626';
+ c.ctx.fillRect(0, 0, W / 2, H);
+ c.ctx.fillStyle = '#2563eb';
+ c.ctx.fillRect(W / 2, 0, W / 2, H);
+ return c;
+ };
+
+ const pts = generateHorizontalStroke(24, 232, 64, 24, 40, (u) =>
+ Math.max(0.15, Math.sin(u * Math.PI))
+ );
+
+ const oilSettings = baseBrushSettings({
+ size: 24,
+ color: '#facc15',
+ flow: 0.9,
+ spacing: 0.08,
+ customTipImage: flatTip,
+ customTipAngleDynamics: 'direction',
+ colorMixing: true,
+ perceptualMixing: true,
+ amountOfPaint: 0.55,
+ densityOfPaint: 0.85,
+ colorStretch: 0.8,
+ amountOfPaintSensor: { usePressure: true, pressureMin: 0.15 },
+ grain: 0.65,
+ textureDensity: 0.65,
+ paperTextureImage: grainTex,
+ paperTextureMode: 'multiply',
+ paperTextureApplyEachPlot: true, // TextureForPlot=1
+ taper: {
+ useIn: true,
+ inLength: 44,
+ inRatio: 0.9,
+ useOut: true,
+ outLength: 44,
+ outRatio: 0.9,
+ affectSize: true,
+ affectAmountOfPaint: true,
+ minSizeRatio: 0.1,
+ minAmountRatio: 0.1,
+ },
+ });
+
+ const cOil = prepareSplitCanvas();
+ const sampler = new LayerPixelSampler(cOil);
+ renderCompleteStroke(cOil.ctx, pts, oilSettings, 'brush', 'color', false, cOil, false, sampler);
+
+ const mOil = analyzeRaster(cOil.buf, W, H);
+ expect(mOil.hasInvalidValues).toBe(false);
+
+ // Color mixing gradient invariant: crossing from red half into blue half with yellow paint
+ // produces warm orange-ish pixels on the red side and greenish/blended pixels past x=128
+ const sampleBandAvg = (x0: number, x1: number, y0: number, y1: number) => {
+ let r = 0,
+ g = 0,
+ b = 0,
+ n = 0;
+ for (let y = y0; y <= y1; y++) {
+ for (let x = x0; x <= x1; x++) {
+ const i = (y * W + x) * 4;
+ r += cOil.buf[i];
+ g += cOil.buf[i + 1];
+ b += cOil.buf[i + 2];
+ n++;
+ }
+ }
+ return { r: r / n, g: g / n, b: b / n };
+ };
+ const leftSide = sampleBandAvg(72, 104, 62, 66);
+ const untouchedLeft = sampleBandAvg(72, 104, 8, 12);
+ const rightSide = sampleBandAvg(140, 172, 62, 66);
+ const untouchedRight = sampleBandAvg(140, 172, 8, 12);
+
+ // Stroke visibly altered both halves and carried mixed pigment across the boundary
+ expect(leftSide.g).toBeGreaterThan(untouchedLeft.g + 25); // Yellow mixed with red increases G
+ expect(
+ Math.abs(rightSide.g - untouchedRight.g) +
+ Math.abs(rightSide.r - untouchedRight.r) +
+ Math.abs(rightSide.b - untouchedRight.b)
+ ).toBeGreaterThan(25);
+ expect(leftSide.r).toBeGreaterThan(rightSide.r); // Gradient preserves underlying red->blue shift
+
+ // TextureForPlot=1 creates measurable spatial texture variance along the stroke
+ const cNoGrainOil = prepareSplitCanvas();
+ renderCompleteStroke(
+ cNoGrainOil.ctx,
+ pts,
+ { ...oilSettings, grain: 0, textureDensity: 0, paperTextureImage: undefined },
+ 'brush',
+ 'color',
+ false,
+ cNoGrainOil,
+ false,
+ new LayerPixelSampler(cNoGrainOil)
+ );
+ let grainDiffSum = 0;
+ for (let x = 60; x <= 190; x++) {
+ const i = (64 * W + x) * 4;
+ grainDiffSum +=
+ Math.abs(cOil.buf[i] - cNoGrainOil.buf[i]) +
+ Math.abs(cOil.buf[i + 1] - cNoGrainOil.buf[i + 1]) +
+ Math.abs(cOil.buf[i + 2] - cNoGrainOil.buf[i + 2]);
+ }
+ expect(grainDiffSum).toBeGreaterThan(200);
+
+ // Compare against untapered stroke on blank canvas to confirm taper narrows endpoints
+ const cTapered = createSoftwareCanvas(W, H);
+ renderCompleteStroke(
+ cTapered.ctx,
+ generateHorizontalStroke(24, 232, 64, 24, 40, () => 0.9),
+ { ...oilSettings, colorMixing: false, grain: 0, textureDensity: 0 },
+ 'brush',
+ 'color'
+ );
+ const cUntapered = createSoftwareCanvas(W, H);
+ renderCompleteStroke(
+ cUntapered.ctx,
+ generateHorizontalStroke(24, 232, 64, 24, 40, () => 0.9),
+ { ...oilSettings, colorMixing: false, grain: 0, textureDensity: 0, taper: undefined },
+ 'brush',
+ 'color'
+ );
+ const taperedEndW = measureVerticalExtentAtX(cTapered.buf, W, H, 28, 2);
+ const untaperedEndW = measureVerticalExtentAtX(cUntapered.buf, W, H, 28, 2);
+ expect(taperedEndW).toBeLessThan(untaperedEndW);
+ });
+
+ // --------------------------------------------------------------------------
+ // Archetype 4: Pure Blender / Fur Blend
+ // --------------------------------------------------------------------------
+ it('Archetype 4: Pure Blender (Amount=0, Density=0, Stretch=100%) blends canvas colors without injecting foreground pigment', () => {
+ const W = 256;
+ const H = 128;
+ const bristleTip = makeFlatBristleTip(32, 7);
+
+ const cBase = createSoftwareCanvas(W, H);
+ cBase.ctx.fillStyle = '#e11d48'; // Crimson left
+ cBase.ctx.fillRect(0, 0, 120, H);
+ cBase.ctx.fillStyle = '#1d4ed8'; // Royal blue right
+ cBase.ctx.fillRect(120, 0, W - 120, H);
+
+ const pts = generateHorizontalStroke(48, 210, 64, 24, 36, () => 0.9);
+ const blenderSettings = baseBrushSettings({
+ size: 24,
+ color: '#00ff00', // Bright green foreground MUST NOT be injected!
+ flow: 0.9,
+ spacing: 0.08,
+ customTipImage: bristleTip,
+ customTipAngleDynamics: 'direction',
+ colorMixing: true,
+ perceptualMixing: true,
+ amountOfPaint: 0,
+ densityOfPaint: 0,
+ colorStretch: 1.0,
+ mixingMode: 'blend',
+ });
+
+ const sampler = new LayerPixelSampler(cBase);
+ renderCompleteStroke(cBase.ctx, pts, blenderSettings, 'brush', 'color', false, cBase, false, sampler);
+
+ const mBlend = analyzeRaster(cBase.buf, W, H);
+ expect(mBlend.hasInvalidValues).toBe(false);
+
+ // Downstream of x=120 along y=64, crimson pigment was stretched into blue without green injection
+ let stretchedRedIntoBluePixels = 0;
+ let maxGreenSpill = 0;
+ for (let x = 124; x <= 170; x++) {
+ const i = (64 * W + x) * 4;
+ const r = cBase.buf[i];
+ const g = cBase.buf[i + 1];
+ const b = cBase.buf[i + 2];
+ if (r > 55 && b > 90) stretchedRedIntoBluePixels++;
+ if (g > maxGreenSpill) maxGreenSpill = g;
+ }
+ expect(stretchedRedIntoBluePixels).toBeGreaterThan(10);
+ // Bright green (#00ff00) foreground must never contaminate pure blender
+ expect(maxGreenSpill).toBeLessThan(120);
+
+ // On a blank transparent canvas, pure blender (Amount=0, Density=0) does not drop opaque green blobs
+ const cEmpty = createSoftwareCanvas(W, H);
+ renderCompleteStroke(
+ cEmpty.ctx,
+ pts,
+ blenderSettings,
+ 'brush',
+ 'color',
+ false,
+ cEmpty,
+ false,
+ new LayerPixelSampler(cEmpty)
+ );
+ const mEmpty = analyzeRaster(cEmpty.buf, W, H);
+ expect(mEmpty.opaquePixels).toBe(0);
+ });
+
+ // --------------------------------------------------------------------------
+ // Archetype 5: Watercolor
+ // --------------------------------------------------------------------------
+ it('Archetype 5: Watercolor creates wet-edge rim, perceptual blue+yellow green shift, and bounded compare tip blend', () => {
+ const W = 256;
+ const H = 128;
+ const pts = generateHorizontalStroke(32, 224, 64, 28, 32, () => 0.9);
+
+ const commonWc: Partial<BrushSettings> = {
+ size: 28,
+ color: '#2563eb',
+ flow: 0.45,
+ opacity: 1.0,
+ spacing: 0.06,
+ hardness: 0.7,
+ blendTipsMode: 'compare',
+ };
+
+ const cNoWet = createSoftwareCanvas(W, H);
+ renderCompleteStroke(
+ cNoWet.ctx,
+ pts,
+ baseBrushSettings({ ...commonWc, wetEdge: 0 }),
+ 'brush',
+ 'color'
+ );
+
+ const cWet = createSoftwareCanvas(W, H);
+ renderCompleteStroke(
+ cWet.ctx,
+ pts,
+ baseBrushSettings({
+ ...commonWc,
+ wetEdge: 0.9,
+ wetEdgeRadius: 4,
+ wetEdgeAlphaPower: 0.7,
+ wetEdgeValuePower: 0.5,
+ }),
+ 'brush',
+ 'color'
+ );
+
+ const mNoWet = analyzeRaster(cNoWet.buf, W, H);
+ const mWet = analyzeRaster(cWet.buf, W, H);
+ expect(mNoWet.hasInvalidValues).toBe(false);
+ expect(mWet.hasInvalidValues).toBe(false);
+ expect(mWet.litPixels).toBeGreaterThan(1000);
+
+ // Compare tip blend invariant: interior alpha stays bounded below 255 even with tight 6% overlap
+ const centerIdx = (64 * W + 128) * 4;
+ expect(cNoWet.buf[centerIdx + 3]).toBeGreaterThan(70);
+ expect(cNoWet.buf[centerIdx + 3]).toBeLessThan(200);
+
+ // Wet Edge rim invariant: border band has darker value & elevated alpha rim compared to non-wet
+ let rimDarkerCount = 0;
+ let rimAlphaBoostCount = 0;
+ for (let y = 44; y <= 84; y++) {
+ const i = (y * W + 128) * 4;
+ const wetA = cWet.buf[i + 3];
+ const baseA = cNoWet.buf[i + 3];
+ if (wetA > baseA + 6) rimAlphaBoostCount++;
+ if (wetA > 40 && baseA > 40) {
+ const wetLum = 0.299 * cWet.buf[i] + 0.587 * cWet.buf[i + 1] + 0.114 * cWet.buf[i + 2];
+ const baseLum = 0.299 * cNoWet.buf[i] + 0.587 * cNoWet.buf[i + 1] + 0.114 * cNoWet.buf[i + 2];
+ if (wetLum < baseLum - 3) rimDarkerCount++;
+ }
+ }
+ expect(rimAlphaBoostCount + rimDarkerCount).toBeGreaterThan(2);
+
+ // Perceptual mixing invariant: blue paint over yellow canvas yields greener mix than linear RGB
+ const paintBlueOverYellow = (perceptual: boolean) => {
+ const c = createSoftwareCanvas(W, H);
+ c.ctx.fillStyle = '#fde047';
+ c.ctx.fillRect(0, 0, W, H);
+ renderCompleteStroke(
+ c.ctx,
+ pts,
+ baseBrushSettings({
+ size: 24,
+ color: '#1d4ed8',
+ flow: 0.7,
+ spacing: 0.08,
+ colorMixing: true,
+ perceptualMixing: perceptual,
+ amountOfPaint: 0.5,
+ densityOfPaint: 0.65,
+ colorStretch: 0.5,
+ }),
+ 'brush',
+ 'color',
+ false,
+ c,
+ false,
+ new LayerPixelSampler(c)
+ );
+ let greenness = 0;
+ let n = 0;
+ for (let x = 70; x <= 180; x += 2) {
+ const i = (64 * W + x) * 4;
+ greenness += c.buf[i + 1] - (c.buf[i] + c.buf[i + 2]) * 0.5;
+ n++;
+ }
+ return greenness / n;
+ };
+
+ const perceptualGreen = paintBlueOverYellow(true);
+ const linearGreen = paintBlueOverYellow(false);
+ expect(perceptualGreen).toBeGreaterThan(linearGreen + 5);
+ });
+
+ // --------------------------------------------------------------------------
+ // Archetype 6: Decorative Ribbon
+ // --------------------------------------------------------------------------
+ it('Archetype 6: Decorative Ribbon deforms color tip continuously across S-stroke + corner in repeat and reverse modes', () => {
+ const W = 256;
+ const H = 192;
+ const ribbonTip = makeColorRibbonTip(32);
+ const traj = generateSyntheticStylusTrajectory({
+ baseBrushSize: 18,
+ minSizeFactor: 0.45,
+ includeSharpCorner: true,
+ tiltSweep: false,
+ });
+
+ const cRepeat = createSoftwareCanvas(W, H);
+ renderCompleteStroke(
+ cRepeat.ctx,
+ traj.points,
+ baseBrushSettings({
+ size: 18,
+ minSizeFactor: 0.45,
+ isRibbon: true,
+ isColorTip: true,
+ customTipAngle: 90,
+ customTipImage: ribbonTip,
+ subTipOrder: 'sequential',
+ }),
+ 'brush',
+ 'color'
+ );
+
+ const cReverse = createSoftwareCanvas(W, H);
+ renderCompleteStroke(
+ cReverse.ctx,
+ traj.points,
+ baseBrushSettings({
+ size: 18,
+ minSizeFactor: 0.45,
+ isRibbon: true,
+ isColorTip: true,
+ customTipAngle: 90,
+ customTipImage: ribbonTip,
+ subTipOrder: 'reverse',
+ }),
+ 'brush',
+ 'color'
+ );
+
+ const mRep = analyzeRaster(cRepeat.buf, W, H);
+ const mRev = analyzeRaster(cReverse.buf, W, H);
+ expect(mRep.hasInvalidValues).toBe(false);
+ expect(mRev.hasInvalidValues).toBe(false);
+ expect(mRep.litPixels).toBeGreaterThan(1000);
+
+ // Zero dropouts along the S-stroke + sharp corner
+ const cov = countUnbrokenCenterlineCoverage(cRepeat.buf, W, H, traj.points, 3);
+ expect(cov.covered).toBeGreaterThanOrEqual(cov.total - 1);
+
+ // Full color preservation from color tip (red, green, and blue pixels all present)
+ let redPx = 0;
+ let greenPx = 0;
+ let bluePx = 0;
+ let diffRepeatVsReverse = 0;
+ for (let i = 0; i < cRepeat.buf.length; i += 4) {
+ if (cRepeat.buf[i + 3] > 120) {
+ const r = cRepeat.buf[i];
+ const g = cRepeat.buf[i + 1];
+ const b = cRepeat.buf[i + 2];
+ if (r > g + 60 && r > b + 60) redPx++;
+ if (g > r + 60 && g > b + 60) greenPx++;
+ if (b > r + 60 && b > g + 60) bluePx++;
+ }
+ if (
+ cRepeat.buf[i + 3] > 100 &&
+ cReverse.buf[i + 3] > 100 &&
+ (Math.abs(cRepeat.buf[i] - cReverse.buf[i]) > 40 ||
+ Math.abs(cRepeat.buf[i + 2] - cReverse.buf[i + 2]) > 40)
+ ) {
+ diffRepeatVsReverse++;
+ }
+ }
+ expect(redPx).toBeGreaterThan(100);
+ expect(greenPx).toBeGreaterThan(100);
+ expect(bluePx).toBeGreaterThan(100);
+ expect(diffRepeatVsReverse).toBeGreaterThan(100);
+ });
+
+ // --------------------------------------------------------------------------
+ // Archetype 7: Dual Brush (multiply, subtract, height)
+ // --------------------------------------------------------------------------
+ it('Archetype 7: Dual Brush applies independent secondary spacing/size across multiply, subtract, and height modes', () => {
+ const W = 256;
+ const H = 128;
+ const secTip = makeDualPatternTip(24);
+ const pts = generateHorizontalStroke(28, 228, 64, 26, 36, () => 0.9);
+
+ const cPrimaryOnly = createSoftwareCanvas(W, H);
+ renderCompleteStroke(
+ cPrimaryOnly.ctx,
+ pts,
+ baseBrushSettings({
+ size: 26,
+ flow: 0.85,
+ spacing: 0.06,
+ hardness: 0.85,
+ dualBrush: false,
+ }),
+ 'brush',
+ 'color'
+ );
+
+ const renderDual = (mode: 'multiply' | 'subtract' | 'height') => {
+ const c = createSoftwareCanvas(W, H);
+ renderCompleteStroke(
+ c.ctx,
+ pts,
+ baseBrushSettings({
+ size: 26,
+ flow: 0.85,
+ spacing: 0.06,
+ hardness: 0.85,
+ dualBrush: true,
+ dualBrushConfig: {
+ enabled: true,
+ compositeMode: mode,
+ linkSizeWithMain: false,
+ size: 18,
+ spacing: 0.42, // Independent wide secondary spacing creates visible rhythmic modulation
+ hardness: 0.9,
+ density: 0.85,
+ tipImage: secTip,
+ },
+ }),
+ 'brush',
+ 'color'
+ );
+ return c;
+ };
+
+ const cMul = renderDual('multiply');
+ const cSub = renderDual('subtract');
+ const cHeight = renderDual('height');
+
+ const mPrim = analyzeRaster(cPrimaryOnly.buf, W, H);
+ const mMul = analyzeRaster(cMul.buf, W, H);
+ const mSub = analyzeRaster(cSub.buf, W, H);
+ const mHeight = analyzeRaster(cHeight.buf, W, H);
+
+ expect(mMul.hasInvalidValues).toBe(false);
+ expect(mSub.hasInvalidValues).toBe(false);
+ expect(mHeight.hasInvalidValues).toBe(false);
+
+ // Multiply and Subtract strictly reduce total alpha mass compared to unmodulated primary
+ expect(mMul.alphaSum).toBeGreaterThan(0);
+ expect(mMul.alphaSum).toBeLessThan(mPrim.alphaSum * 0.92);
+ expect(mSub.alphaSum).toBeGreaterThan(0);
+ expect(mSub.alphaSum).toBeLessThan(mPrim.alphaSum * 0.92);
+ expect(mHeight.alphaSum).toBeGreaterThan(0);
+
+ // All three dual combine modes produce mutually distinct alpha distributions
+ const l1DiffAlpha = (a: Uint8ClampedArray, b: Uint8ClampedArray) => {
+ let sum = 0;
+ for (let i = 3; i < a.length; i += 4) sum += Math.abs(a[i] - b[i]);
+ return sum;
+ };
+ expect(l1DiffAlpha(cMul.buf, cSub.buf)).toBeGreaterThan(5000);
+ expect(l1DiffAlpha(cMul.buf, cHeight.buf)).toBeGreaterThan(5000);
+ expect(l1DiffAlpha(cSub.buf, cHeight.buf)).toBeGreaterThan(5000);
+ });
+
+ // --------------------------------------------------------------------------
+ // Archetype 8: Spray + Color Jitter (per-dab & per-stroke)
+ // --------------------------------------------------------------------------
+ it('Archetype 8: Spray scatters particles and Color Jitter differentiates per-dab vs per-stroke variance', () => {
+ const W = 256;
+ const H = 160;
+ const pts = generateHorizontalStroke(32, 224, 80, 34, 24, () => 0.9);
+
+ const makeSpraySettings = (perStroke: boolean): BrushSettings =>
+ baseBrushSettings({
+ size: 34,
+ color: '#e11d48',
+ secondaryColor: '#0284c7',
+ flow: 0.95,
+ spacing: 0.25,
+ hardness: 0.9,
+ spray: {
+ enabled: true,
+ size: 30,
+ particleSize: 6,
+ density: 8,
+ bias: 0,
+ },
+ dynamics: {
+ ...DEFAULT_BRUSH_DYNAMICS,
+ colorJitterEnabled: true,
+ colorJitterPerStroke: perStroke,
+ hueJitter: 0.9,
+ saturationJitter: 0.5,
+ brightnessJitter: 0.4,
+ foregroundBackgroundJitter: 0.35,
+ },
+ });
+
+ const cPerDab = createSoftwareCanvas(W, H);
+ renderCompleteStroke(cPerDab.ctx, pts, makeSpraySettings(false), 'brush', 'color');
+
+ const cPerStroke = createSoftwareCanvas(W, H);
+ renderCompleteStroke(cPerStroke.ctx, pts, makeSpraySettings(true), 'brush', 'color');
+
+ const mDab = analyzeRaster(cPerDab.buf, W, H);
+ const mStroke = analyzeRaster(cPerStroke.buf, W, H);
+
+ expect(mDab.hasInvalidValues).toBe(false);
+ expect(mStroke.hasInvalidValues).toBe(false);
+ expect(mDab.litPixels).toBeGreaterThan(250);
+ expect(mStroke.litPixels).toBeGreaterThan(250);
+
+ // Spray bounding box spreads well beyond a thin centerline
+ expect(mDab.maxY - mDab.minY).toBeGreaterThan(20);
+
+ // Count distinct quantized RGB buckets among strongly opaque pixels
+ const countDistinctColors = (buf: Uint8ClampedArray) => {
+ const buckets = new Set<string>();
+ for (let i = 0; i < buf.length; i += 4) {
+ if (buf[i + 3] >= 180) {
+ buckets.add(`${buf[i] >> 4},${buf[i + 1] >> 4},${buf[i + 2] >> 4}`);
+ }
+ }
+ return buckets.size;
+ };
+
+ const perDabColorCount = countDistinctColors(cPerDab.buf);
+ const perStrokeColorCount = countDistinctColors(cPerStroke.buf);
+
+ // Per-dab jitter creates many distinct colors within a single stroke;
+ // per-stroke jitter locks all dabs in the stroke to one uniform shifted color!
+ expect(perDabColorCount).toBeGreaterThanOrEqual(6);
+ expect(perStrokeColorCount).toBeLessThanOrEqual(2);
+ });
+
+ // --------------------------------------------------------------------------
+ // Archetype 9: Dual-Tone Grayscale Tip (Main + Sub Color) + BrushCombineMode
+ // --------------------------------------------------------------------------
+ it('Archetype 9: Dual-Tone Grayscale Tip blends Main+Sub colors and honors multiply, add-glow, and behind combine modes', () => {
+ const W = 220;
+ const H = 128;
+ const dualToneTip = makeDualToneGrayTip(32);
+ const pts = generateHorizontalStroke(30, 190, 64, 28, 28, () => 0.9);
+
+ // 1. Clean canvas: verify Main (#e02020) and Sub (#2040f0) colors both appear
+ const cClean = createSoftwareCanvas(W, H);
+ renderCompleteStroke(
+ cClean.ctx,
+ pts,
+ baseBrushSettings({
+ size: 28,
+ color: '#e02020',
+ secondaryColor: '#2040f0',
+ customTipImage: dualToneTip,
+ isDualToneTip: true,
+ spacing: 0.22,
+ flow: 1.0,
+ }),
+ 'brush',
+ 'color'
+ );
+ let mainRedPx = 0;
+ let subBluePx = 0;
+ for (let i = 0; i < cClean.buf.length; i += 4) {
+ if (cClean.buf[i + 3] > 180) {
+ if (cClean.buf[i] > 170 && cClean.buf[i + 2] < 80) mainRedPx++;
+ if (cClean.buf[i + 2] > 170 && cClean.buf[i] < 80) subBluePx++;
+ }
+ }
+ expect(mainRedPx).toBeGreaterThan(80);
+ expect(subBluePx).toBeGreaterThan(80);
+
+ // 2. BrushCombineMode: multiply (darkens), add-glow (brightens), behind (preserves opaque, paints transparent)
+ const makeMidtoneLeftCanvas = () => {
+ const c = createSoftwareCanvas(W, H);
+ c.ctx.fillStyle = '#808080';
+ c.ctx.fillRect(0, 0, 110, H);
+ return c;
+ };
+
+ const runCombine = (mode: 'multiply' | 'add-glow' | 'behind') => {
+ const c = makeMidtoneLeftCanvas();
+ renderCompleteStroke(
+ c.ctx,
+ pts,
+ baseBrushSettings({
+ size: 26,
+ color: '#c06040',
+ secondaryColor: '#4080e0',
+ customTipImage: dualToneTip,
+ isDualToneTip: true,
+ spacing: 0.14,
+ flow: 0.9,
+ brushCombineMode: mode,
+ }),
+ 'brush',
+ 'color'
+ );
+ return c;
+ };
+
+ const cMul = runCombine('multiply');
+ const cAddGlow = runCombine('add-glow');
+ const cBehind = runCombine('behind');
+
+ const midLeftIdx = (64 * W + 70) * 4; // Over opaque #808080 region
+ const transRightIdx = (64 * W + 150) * 4; // Over transparent region
+
+ // Multiply darkens mid-tone gray (#80=128)
+ const mulLum = (cMul.buf[midLeftIdx] + cMul.buf[midLeftIdx + 1] + cMul.buf[midLeftIdx + 2]) / 3;
+ expect(mulLum).toBeLessThan(115);
+
+ // Add-Glow brightens mid-tone gray strictly above 128
+ const addLum =
+ (cAddGlow.buf[midLeftIdx] + cAddGlow.buf[midLeftIdx + 1] + cAddGlow.buf[midLeftIdx + 2]) / 3;
+ expect(addLum).toBeGreaterThan(150);
+
+ // Behind preserves opaque left pixel (#808080) untouched while painting into transparent right half
+ expect(cBehind.buf[midLeftIdx]).toBe(128);
+ expect(cBehind.buf[midLeftIdx + 1]).toBe(128);
+ expect(cBehind.buf[midLeftIdx + 2]).toBe(128);
+ expect(cBehind.buf[transRightIdx + 3]).toBeGreaterThan(180);
+ });
+
+ // --------------------------------------------------------------------------
+ // Live-vs-Commit Equivalence
+ // --------------------------------------------------------------------------
+ it('Live incremental segment emission matches committed renderCompleteStroke pixel-for-pixel', () => {
+ const W = 256;
+ const H = 192;
+ const traj = generateSyntheticStylusTrajectory({
+ baseBrushSize: 14,
+ minSizeFactor: 0.15,
+ includeSharpCorner: true,
+ tiltSweep: false,
+ });
+
+ const settings = baseBrushSettings({
+ size: 14,
+ minSizeFactor: 0.15,
+ color: '#1e293b',
+ flow: 0.85,
+ spacing: 0.08,
+ hardness: 0.85,
+ antiAlias: 2,
+ useGpu: false,
+ });
+
+ // Committed path
+ const cCommit = createSoftwareCanvas(W, H);
+ renderCompleteStroke(cCommit.ctx, traj.points, settings, 'brush', 'color');
+
+ // Live incremental segment path (mirrors liveSegmentEmitter.ts + pointerDownInitialStamp.ts)
+ const cLive = createSoftwareCanvas(W, H);
+ const liveOpts = buildBrushRenderOptions(settings, {
+ hardness: settings.hardness,
+ flow: settings.flow,
+ spacing: settings.spacing,
+ antiAlias: settings.antiAlias,
+ isEraser: false,
+ isBgEraser: false,
+ alphaLocked: false,
+ isTransparentInk: false,
+ });
+ const pts = traj.points;
+ liveOpts.currentStrokeDist = 0;
+ drawBrushDot(cLive.ctx, pts[0], settings.color, liveOpts, undefined);
+ const dabCounter = { count: 0 };
+ let accDist = Math.max(0.12, Math.max(0.2, pts[0].width) * settings.spacing);
+
+ const first = centripetalCatmullRomToBezier(pts[0], pts[0], pts[1], pts[2]);
+ accDist = drawBrushCubicBezierSegment(
+ cLive.ctx,
+ pts[0],
+ first.c1,
+ first.c2,
+ pts[1],
+ settings.color,
+ liveOpts,
+ accDist,
+ dabCounter,
+ undefined
+ );
+ liveOpts.currentStrokeDist += Math.hypot(pts[1].x - pts[0].x, pts[1].y - pts[0].y);
+
+ for (let i = 2; i < pts.length - 1; i++) {
+ const seg = centripetalCatmullRomToBezier(pts[i - 2], pts[i - 1], pts[i], pts[i + 1]);
+ accDist = drawBrushCubicBezierSegment(
+ cLive.ctx,
+ pts[i - 1],
+ seg.c1,
+ seg.c2,
+ pts[i],
+ settings.color,
+ liveOpts,
+ accDist,
+ dabCounter,
+ undefined
+ );
+ liveOpts.currentStrokeDist += Math.hypot(pts[i].x - pts[i - 1].x, pts[i].y - pts[i - 1].y);
+ }
+
+ const n = pts.length;
+ const last = centripetalCatmullRomToBezier(pts[n - 3], pts[n - 2], pts[n - 1], pts[n - 1]);
+ drawBrushCubicBezierSegment(
+ cLive.ctx,
+ pts[n - 2],
+ last.c1,
+ last.c2,
+ pts[n - 1],
+ settings.color,
+ liveOpts,
+ accDist,
+ dabCounter,
+ undefined
+ );
+
+ let maxDiff = 0;
+ let totalDiff = 0;
+ let litCount = 0;
+ for (let i = 0; i < cCommit.buf.length; i += 4) {
+ if (cCommit.buf[i + 3] > 0 || cLive.buf[i + 3] > 0) {
+ litCount++;
+ for (let c = 0; c < 4; c++) {
+ const d = Math.abs(cCommit.buf[i + c] - cLive.buf[i + c]);
+ if (d > maxDiff) maxDiff = d;
+ totalDiff += d;
+ }
+ }
+ }
+ expect(litCount).toBeGreaterThan(500);
+ expect(maxDiff).toBeLessThanOrEqual(1);
+ expect(totalDiff / (litCount * 4)).toBeLessThan(0.05);
+ });
+
+ // --------------------------------------------------------------------------
+ // Unified BrushPreview Pipeline Verification
+ // --------------------------------------------------------------------------
+ it('renderBrushStrokePreview renders authentic non-empty previews for ribbon, dualBrush, wetEdge, all 9 paperTextureModes, dualTone, colorJitter, and taper', () => {
+ const ribbonTip = makeColorRibbonTip(24);
+ const dualToneTip = makeDualToneGrayTip(24);
+ const dualPatternTip = makeDualPatternTip(20);
+ const grainTex = makeCheckerGrainTexture(24);
+
+ const previewCases: Array<{ name: string; opts: Parameters<typeof renderBrushStrokePreview>[3] }> = [
+ {
+ name: 'isRibbon',
+ opts: { isRibbon: true, isColorTip: true, customTipImage: ribbonTip, size: 16 },
+ },
+ {
+ name: 'dualBrush',
+ opts: {
+ size: 18,
+ dualBrush: true,
+ dualBrushConfig: {
+ enabled: true,
+ compositeMode: 'multiply',
+ size: 12,
+ spacing: 0.3,
+ tipImage: dualPatternTip,
+ },
+ },
+ },
+ {
+ name: 'wetEdge',
+ opts: { size: 18, flow: 0.55, wetEdge: 0.85, wetEdgeRadius: 3, blendTipsMode: 'compare' },
+ },
+ {
+ name: 'isDualToneTip',
+ opts: {
+ size: 18,
+ customTipImage: dualToneTip,
+ isDualToneTip: true,
+ color: '#ef4444',
+ secondaryColor: '#3b82f6',
+ },
+ },
+ {
+ name: 'colorJitter',
+ opts: {
+ size: 16,
+ color: '#ef4444',
+ secondaryColor: '#22c55e',
+ dynamics: {
+ ...DEFAULT_BRUSH_DYNAMICS,
+ colorJitterEnabled: true,
+ colorJitterPerStroke: false,
+ hueJitter: 0.85,
+ saturationJitter: 0.5,
+ },
+ },
+ },
+ {
+ name: 'taper',
+ opts: {
+ size: 18,
+ taper: { useIn: true, inLength: 24, inRatio: 0.9, useOut: true, outLength: 24, outRatio: 0.9, affectSize: true },
+ },
+ },
+ ];
+
+ const allPaperModes: CspPaperTextureMode[] = [
+ 'normal',
+ 'multiply',
+ 'subtract',
+ 'compare',
+ 'overlay',
+ 'color-burn',
+ 'linear-burn',
+ 'height',
+ 'outline',
+ ];
+ for (const mode of allPaperModes) {
+ previewCases.push({
+ name: `paperTextureMode:${mode}`,
+ opts: {
+ size: 18,
+ grain: 0.8,
+ paperTextureImage: grainTex,
+ paperTextureMode: mode,
+ },
+ });
+ }
+
+ for (const tc of previewCases) {
+ const canvas = createSoftwareCanvas(140, 34);
+ renderBrushStrokePreview(canvas, 140, 34, { ...tc.opts, color: tc.opts?.color ?? '#ffffff' }, true);
+ const m = analyzeRaster(canvas.buf, 140, 34);
+ expect(m.hasInvalidValues, `${tc.name} produced NaN/invalid pixel`).toBe(false);
+ expect(m.litPixels, `${tc.name} produced blank preview`).toBeGreaterThan(60);
+ }
+ });
+
+ // --------------------------------------------------------------------------
+ // Lossless Persistence & Round-Trip Serialization Verification
+ // --------------------------------------------------------------------------
+ it('preserves every new CSP field losslessly across brushStorage, brushPresetManager, inkbBrushFormat, and non-brush .sut importWarnings', async () => {
+ const samplePng =
+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==';
+
+ const allSubTipOrders: CspSubTipOrder[] = [
+ 'sequential',
+ 'reverse',
+ 'random',
+ 'random-no-repeat',
+ 'once',
+ 'direction',
+ ];
+ const allPaperModes: CspPaperTextureMode[] = [
+ 'normal',
+ 'multiply',
+ 'subtract',
+ 'compare',
+ 'overlay',
+ 'color-burn',
+ 'linear-burn',
+ 'height',
+ 'outline',
+ ];
+
+ const fullBrush: CspBrush = {
+ id: 'csp-golden-roundtrip-1',
+ name: 'Golden Master Brush',
+ badge: 'CSP',
+ tipDataUrl: samplePng,
+ tipWidth: 1,
+ tipHeight: 1,
+ isDualToneTip: true,
+ secondaryTipDataUrl: samplePng,
+ subTips: [{ dataUrl: samplePng, width: 1, height: 1, isColor: false, isDualToneTip: true }],
+ subTipOrder: 'random-no-repeat',
+ size: 28,
+ minSizeFactor: 0.15,
+ opacity: 0.92,
+ flow: 0.78,
+ spacing: 0.09,
+ hardness: 0.85,
+ thickness: 0.65,
+ thicknessVertical: true,
+ thicknessSensor: { usePressure: true, pressureMin: 0.25, useTilt: true, tiltMin: 0.4 },
+ angle: 35,
+ angleDynamics: 'direction',
+ brushCombineMode: 'add-glow',
+ blendTipsMode: 'compare',
+ usePressure: true,
+ useTilt: true,
+ smoothing: true,
+ stabilization: 12,
+ colorMixing: true,
+ perceptualMixing: true,
+ amountOfPaint: 0.5,
+ densityOfPaint: 0.6,
+ colorStretch: 0.85,
+ amountOfPaintSensor: { usePressure: true, pressureMin: 0.1 },
+ densityOfPaintSensor: { useVelocity: true, velocityMin: 0.2, invertVelocity: true },
+ colorStretchSensor: { useTilt: true, tiltMin: 0.3 },
+ paperTexture: samplePng,
+ textureDensity: 0.72,
+ paperTextureMode: 'linear-burn',
+ paperTextureApplyEachPlot: true,
+ dualBrush: true,
+ dualBrushCompositeMode: 'height',
+ dualBrushConfig: {
+ enabled: true,
+ compositeMode: 'height',
+ linkSizeWithMain: false,
+ size: 18,
+ sizeRatio: 0.64,
+ spacing: 0.25,
+ scatter: 0.4,
+ thickness: 0.7,
+ thicknessVertical: true,
+ hardness: 0.8,
+ density: 0.9,
+ angle: 45,
+ angleDynamics: 'random',
+ flipH: 'alternate',
+ flipV: 'random',
+ tipDataUrl: samplePng,
+ subTips: [{ dataUrl: samplePng, width: 1, height: 1, isDualToneTip: true }],
+ subTipOrder: 'direction',
+ isRibbon: false,
+ },
+ dynamics: {
+ ...DEFAULT_BRUSH_DYNAMICS,
+ colorJitterEnabled: true,
+ colorJitterPerStroke: true,
+ hueJitter: 0.4,
+ saturationJitter: 0.3,
+ brightnessJitter: 0.2,
+ },
+ importWarnings: [
+ 'Missing external paper texture material (.:Install:01:02): not embedded in MaterialFile.',
+ ],
+ importedAt: Date.now(),
+ };
+
+ // 1. brushStorage.ts: save -> verify lightweight localStorage index strips heavy data URLs
+ // even inside dualBrushConfig, while keeping all settings & importWarnings intact
+ await saveCustomBrush(fullBrush);
+ const lsRaw = lsStore.get(BRUSH_INDEX_LS_KEY);
+ expect(lsRaw).toBeTruthy();
+ expect(lsRaw!).not.toContain('data:image/png;base64');
+ const lsParsed = JSON.parse(lsRaw!) as CspBrush[];
+ expect(lsParsed[0].isDualToneTip).toBe(true);
+ expect(lsParsed[0].dualBrushConfig?.compositeMode).toBe('height');
+ expect(lsParsed[0].dualBrushConfig?.spacing).toBe(0.25);
+ expect(lsParsed[0].dualBrushConfig?.tipDataUrl).toBeUndefined();
+ expect(lsParsed[0].importWarnings).toEqual(fullBrush.importWarnings);
+
+ const prepared = await prepareBrushSettingsForCsp(fullBrush);
+ expect(prepared.isDualToneTip).toBe(true);
+ expect(prepared.thicknessSensor).toEqual(fullBrush.thicknessSensor);
+ expect(prepared.amountOfPaintSensor).toEqual(fullBrush.amountOfPaintSensor);
+ expect(prepared.densityOfPaintSensor).toEqual(fullBrush.densityOfPaintSensor);
+ expect(prepared.colorStretchSensor).toEqual(fullBrush.colorStretchSensor);
+ expect(prepared.dualBrushConfig?.compositeMode).toBe('height');
+ expect(prepared.brushCombineMode).toBe('add-glow');
+ expect(prepared.paperTextureMode).toBe('linear-burn');
+ expect(prepared.dynamics?.colorJitterPerStroke).toBe(true);
+ expect(prepared.importWarnings).toEqual(fullBrush.importWarnings);
+
+ // 2. brushPresetManager.ts: saveBrushSettingsImmediately + getEffectiveBrushSettings
+ saveBrushSettingsImmediately(fullBrush.id, {
+ isDualToneTip: true,
+ thicknessSensor: fullBrush.thicknessSensor,
+ amountOfPaintSensor: fullBrush.amountOfPaintSensor,
+ densityOfPaintSensor: fullBrush.densityOfPaintSensor,
+ colorStretchSensor: fullBrush.colorStretchSensor,
+ subTipOrder: 'once',
+ paperTextureMode: 'color-burn',
+ brushCombineMode: 'behind',
+ dynamics: fullBrush.dynamics,
+ dualBrushConfig: {
+ ...fullBrush.dualBrushConfig!,
+ spacing: 0.33,
+ },
+ });
+ const effective = getEffectiveBrushSettings(fullBrush.id, [fullBrush]);
+ expect(effective.isDualToneTip).toBe(true);
+ expect(effective.thicknessSensor).toEqual(fullBrush.thicknessSensor);
+ expect(effective.amountOfPaintSensor).toEqual(fullBrush.amountOfPaintSensor);
+ expect(effective.densityOfPaintSensor).toEqual(fullBrush.densityOfPaintSensor);
+ expect(effective.colorStretchSensor).toEqual(fullBrush.colorStretchSensor);
+ expect(effective.subTipOrder).toBe('once');
+ expect(effective.paperTextureMode).toBe('color-burn');
+ expect(effective.brushCombineMode).toBe('behind');
+ expect(effective.dynamics?.colorJitterPerStroke).toBe(true);
+ expect(effective.dualBrushConfig?.spacing).toBe(0.33);
+ // Preserved tipDataUrl from CspBrush even though localStorage stripped it
+ expect(effective.dualBrushConfig?.tipDataUrl).toBe(samplePng);
+ expect(effective.importWarnings).toEqual(fullBrush.importWarnings);
+
+ // 3. inkbBrushFormat.ts: buildExportableBrush -> serializeInkbBrush -> parseInkbFile
+ const exportable = buildExportableBrush(fullBrush.id, [fullBrush]);
+ const bytes = serializeInkbBrush(exportable);
+ const roundTripped = parseInkbFile(
+ bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer,
+ 'Golden.inkb'
+ );
+ expect(roundTripped.isDualToneTip).toBe(true);
+ expect(roundTripped.subTips?.[0]?.isDualToneTip).toBe(true);
+ expect(roundTripped.thicknessSensor).toEqual(fullBrush.thicknessSensor);
+ expect(roundTripped.amountOfPaintSensor).toEqual(fullBrush.amountOfPaintSensor);
+ expect(roundTripped.densityOfPaintSensor).toEqual(fullBrush.densityOfPaintSensor);
+ expect(roundTripped.colorStretchSensor).toEqual(fullBrush.colorStretchSensor);
+ expect(roundTripped.dualBrushConfig?.compositeMode).toBe('height');
+ expect(roundTripped.dualBrushConfig?.spacing).toBe(0.33);
+ expect(roundTripped.dualBrushConfig?.tipDataUrl).toBe(samplePng);
+ expect(roundTripped.dualBrushConfig?.subTipOrder).toBe('direction');
+ expect(roundTripped.dynamics?.colorJitterPerStroke).toBe(true);
+ expect(roundTripped.brushCombineMode).toBe('behind');
+ expect(roundTripped.paperTextureMode).toBe('color-burn');
+ expect(roundTripped.importWarnings).toEqual(fullBrush.importWarnings);
+
+ // Exhaustive enum round-trip check for all 6 subTipOrders and all 9 paperTextureModes
+ for (const order of allSubTipOrders) {
+ const bBytes = serializeInkbBrush({ ...fullBrush, subTipOrder: order });
+ const parsed = parseInkbFile(
+ bBytes.buffer.slice(bBytes.byteOffset, bBytes.byteOffset + bBytes.byteLength) as ArrayBuffer
+ );
+ expect(parsed.subTipOrder).toBe(order);
+ }
+ for (const mode of allPaperModes) {
+ const bBytes = serializeInkbBrush({ ...fullBrush, paperTextureMode: mode });
+ const parsed = parseInkbFile(
+ bBytes.buffer.slice(bBytes.byteOffset, bBytes.byteOffset + bBytes.byteLength) as ArrayBuffer
+ );
+ expect(parsed.paperTextureMode).toBe(mode);
+ }
+
+ // 4. Unsupported non-brush .sut sub-tool (Liquify) surfaces clean importWarnings
+ const liquifyExtract: NativeSutExtract = {
+ nodeName: 'CSP Liquify Push',
+ variantId: 1,
+ variantValues: new Map<string, unknown>([
+ ['liquifymode', 0],
+ ['liquifystrength', 50],
+ ['liquifysize', 80],
+ ]),
+ materials: [],
+ };
+ const parsedLiquify = await parseSutExtractedData(liquifyExtract, 'liquify.sut');
+ expect(parsedLiquify.importWarnings?.length).toBeGreaterThan(0);
+ expect(parsedLiquify.importWarnings![0]).toMatch(/Liquify/i);
+ });
+
+ // --------------------------------------------------------------------------
+ // Regression: CSP Built-in Chain.sut (BrushRibbon=1, BrushRotation=90°, 300x27 dual-tone strip)
+ // --------------------------------------------------------------------------
+ it('Chain.sut regression: horizontal 300x27 ribbon tip at BrushRotation=90° flows along horizontal & vertical strokes at full BrushSize width with dual-tone coloring', async () => {
+ const chainCat = '.:Install:Paint110:45db3581c6-9246-6887-2a7a-c9454ab8be';
+ const pngSig = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
+
+ // 1. Verify exact Chain.sut Variant column parsing
+ const chainExtract: NativeSutExtract = {
+ nodeName: 'Chain',
+ nodeUuid: '2fde90e0-fb6a-4092-9e8c-6f7d23d80e7f',
+ variantId: 685,
+ variantValues: new Map<string, unknown>([
+ ['brushsize', 219.0],
+ ['brushsizeunit', 0],
+ ['brushribbon', 1],
+ ['brushrotation', 90.0],
+ ['brushrotationeffector', 3],
+ ['brushthickness', 100],
+ ['brushverticalthicknes', 0],
+ ['brushpatternordertype', 0],
+ ['brushusepatternimage', 1],
+ ['brushpatternimagearray', new TextEncoder().encode(chainCat)],
+ ['brushflow', 100],
+ ['opacity', 100],
+ ['brushhardness', 100],
+ ['antialias', 2],
+ ['usedualbrush', 0],
+ ]),
+ materials: [
+ {
+ pwId: '1',
+ originalPath: '.:Paint110:45db3581c6-9246-6887-2a7a-c9454ab8be:data:material_0.layer',
+ catalogPath: chainCat,
+ fileData: pngSig,
+ decodedPng: pngSig,
+ width: 300,
+ height: 27,
+ expressionColor: 'gray',
+ isPaperTexture: false,
+ hasSubColor: true,
+ decodedFromLayer: false,
+ },
+ ],
+ };
+
+ const parsed = await parseSutExtractedData(chainExtract, 'Chain.sut');
+ expect(parsed.isRibbon).toBe(true);
+ expect(parsed.angle).toBe(90);
+ expect(parsed.angleDynamics).toBe('none');
+ expect(parsed.size).toBe(219);
+ expect(parsed.thickness).toBe(1);
+ expect(parsed.thicknessVertical).toBe(true);
+ expect(parsed.isDualToneTip).toBe(true);
+ expect(parsed.isColorTip).toBe(false);
+ expect(parsed.dualBrush).toBe(false);
+
+ // 2. Build a synthetic 300x27 horizontal dual-tone chain strip:
+ // 8 discrete links along X (each with black outline lum=0 and white interior lum=255),
+ // transparent gaps between link holes and above/below the links.
+ const tipW = 300;
+ const tipH = 27;
+ const tipData = new Uint8ClampedArray(tipW * tipH * 4);
+ for (let y = 0; y < tipH; y++) {
+ for (let x = 0; x < tipW; x++) {
+ // Horizontal link centered vertically y in [5..21], repeating every 37.5px with a 5px gap
+ const inLinkX = (x % 37) >= 2 && (x % 37) <= 32;
+ const inLinkY = y >= 5 && y <= 21;
+ if (!inLinkX || !inLinkY) continue;
+ const isBorder = (x % 37) <= 4 || (x % 37) >= 30 || y <= 7 || y >= 19;
+ const idx = (y * tipW + x) * 4;
+ const lum = isBorder ? 0 : 255;
+ tipData[idx] = lum;
+ tipData[idx + 1] = lum;
+ tipData[idx + 2] = lum;
+ tipData[idx + 3] = 255;
+ }
+ }
+ const chainSurface = {
+ data: tipData,
+ width: tipW,
+ height: tipH,
+ isColor: false,
+ isDualToneTip: true,
+ };
+
+ // 3. Verify geometry: ribbonWidth == BrushSize (54px) and tilePeriod == 54 * (300/27) == 600px
+ const brushSize = 54;
+ const horizPts: Point[] = [
+ { x: 20, y: 80, pressure: 1, width: brushSize },
+ { x: 260, y: 80, pressure: 1, width: brushSize },
+ ];
+ const ribbonOpts = {
+ size: brushSize,
+ angle: parsed.angle,
+ thickness: parsed.thickness,
+ thicknessVertical: parsed.thicknessVertical,
+ tipSurfaces: [chainSurface],
+ isDualToneTip: true,
+ primaryColor: '#ff3000',
+ secondaryColor: '#3f2e1f',
+ antiAlias: 1,
+ };
+
+ const horizMesh = buildRibbonMeshFromPoints(horizPts, ribbonOpts);
+ expect(horizMesh.centerline[0].ribbonWidth).toBeCloseTo(brushSize, 1);
+ expect(horizMesh.centerline[0].tilePeriod).toBeCloseTo((brushSize * tipW) / tipH, 1);
+ // Stroke is 240px long out of 600px tile period -> sNorm reaches ~0.4 (NOT 240/4.86 = 49 sideways strips!)
+ const endSNorm = horizMesh.centerline[horizMesh.centerline.length - 1].sNorm;
+ expect(endSNorm).toBeGreaterThan(0.35);
+ expect(endSNorm).toBeLessThan(0.45);
+
+ // 4. Rasterize horizontal stroke and verify dual-tone colors + link orientation along X
+ const horizRaster = rasterizeRibbonMeshCpu(horizMesh, ribbonOpts, 280, 160, 0, 0);
+ let outlineRedHits = 0;
+ let fillBrownHits = 0;
+ let paintedRows = 0;
+ for (let y = 0; y < 160; y++) {
+ let rowLit = false;
+ for (let x = 30; x < 250; x++) {
+ const p = (y * 280 + x) * 4;
+ if (horizRaster.data[p + 3] < 200) continue;
+ rowLit = true;
+ const r = horizRaster.data[p];
+ const g = horizRaster.data[p + 1];
+ const b = horizRaster.data[p + 2];
+ if (r > 210 && g < 80 && b < 40) outlineRedHits++;
+ if (r > 40 && r < 95 && g > 25 && g < 70 && b > 15 && b < 55) fillBrownHits++;
+ }
+ if (rowLit) paintedRows++;
+ }
+ expect(outlineRedHits).toBeGreaterThan(400);
+ expect(fillBrownHits).toBeGreaterThan(600);
+ // Chain links occupy rows 5..21 of 27 -> ~17/27 * 54px = ~34px tall (NOT 54*27/300 = 4.8px!)
+ expect(paintedRows).toBeGreaterThan(26);
+ expect(paintedRows).toBeLessThan(44);
+
+ // 5. Verify vertical stroke rotates chain links smoothly to flow along Y
+ const vertPts: Point[] = [
+ { x: 80, y: 20, pressure: 1, width: brushSize },
+ { x: 80, y: 260, pressure: 1, width: brushSize },
+ ];
+ const vertMesh = buildRibbonMeshFromPoints(vertPts, ribbonOpts);
+ expect(vertMesh.centerline[0].ribbonWidth).toBeCloseTo(brushSize, 1);
+ expect(vertMesh.centerline[0].tilePeriod).toBeCloseTo((brushSize * tipW) / tipH, 1);
+ const vertRaster = rasterizeRibbonMeshCpu(vertMesh, ribbonOpts, 160, 280, 0, 0);
+ let paintedCols = 0;
+ for (let x = 0; x < 160; x++) {
+ let colLit = false;
+ for (let y = 30; y < 250; y++) {
+ if (vertRaster.data[(y * 160 + x) * 4 + 3] >= 200) {
+ colLit = true;
+ break;
+ }
+ }
+ if (colLit) paintedCols++;
+ }
+ expect(paintedCols).toBeGreaterThan(26);
+ expect(paintedCols).toBeLessThan(44);
+ });
+});
diff --git a/src/utils/__tests__/sutImportParity.test.ts b/src/utils/__tests__/sutImportParity.test.ts
index 4cfc559..08a60f2 100644
--- a/src/utils/__tests__/sutImportParity.test.ts
+++ b/src/utils/__tests__/sutImportParity.test.ts
@@ -1,18 +1,60 @@
import { describe, it, expect, beforeEach } from 'vitest';
import {
+ decodeCspBrushSize,
+ decodeCspHardness,
+ mapCspBrushCombineMode,
parseCspEffector,
parseCspInOutTarget,
parseSutExtractedData,
} from '../sutParser';
+import {
+ getEffectiveBrushSettings,
+ saveBrushSettingsImmediately,
+} from '../brushPresetManager';
+import { prepareBrushSettingsForCsp } from '../brushStorage';
import { NativeSutExtract } from '../nativeBackend';
import {
centripetalCatmullRomToBezier,
buildCubicArcLengthTable,
getCubicPointAtArcLength,
+ drawBrushDot,
+ drawBrushCubicBezierSegment,
+ evaluateCspSensor,
+ evaluateFastSpline,
renderCompleteStroke,
+ computeTipStampDimensions,
+ applyCspPaperTextureAlpha,
+ applyCspWatercolorEdge,
+ evaluateCspTaperFactors,
+ computeCspTiltMagnitude,
} from '../../engine/BrushEngine';
+import type { GpuDab } from '../../engine/WebGlBrushEngine';
+import { InputStabilizer } from '../../engine/InputStabilizer';
import { LayerPixelSampler } from '../colorMixingEngine';
-import { BrushSettings, Point } from '../../types/editor';
+import { BrushSettings, CspPaperTextureMode, LayerItem, Point } from '../../types/editor';
+import { SparseTileGrid } from '../tileEngine';
+import { downsample2x2ToParentTile } from '../tileEngine/mipmap';
+import { createTileBuffer } from '../tileEngine/types';
+import { createInitialStrokeSessionState } from '../../hooks/drawing/brushStrokeSession/types';
+import { runPointerDown } from '../../hooks/drawing/brushStrokeSession/pointerDownHandler';
+import { runPointerMove } from '../../hooks/drawing/brushStrokeSession/pointerMoveHandler';
+import { runFlushPendingPoints } from '../../hooks/drawing/brushStrokeSession/flushPendingPoints';
+import { runPointerUp } from '../../hooks/drawing/brushStrokeSession/pointerUpHandler';
+import {
+ abortActiveStrokeSession,
+ buildTouchedTileSpansFromSet,
+ clearPredictedCanvasSurface,
+ computeCanvasPoint,
+ createLiveBrushOptions,
+ emitConstraintAxisChangeIfNeeded,
+ getPredictedCanvasElement,
+ getViewportRectCached,
+ markTouchedTilesInRect,
+ resolveEffectiveOpacitySensorValue,
+ resolveLiveAntiAliasValue,
+ resolveStrokeColorValue,
+} from '../../hooks/drawing/brushStrokeSession/strokeHelpers';
+import { emitLiveSegmentToDraft } from '../../hooks/drawing/brushStrokeSession/liveSegmentEmitter';
/**
* Software Canvas2D rasterizer with accurate affine translate/rotate + bilinear drawImage
@@ -35,6 +77,18 @@ function createSoftwareCanvas(initW: number, initH: number) {
imageSmoothingEnabled: true,
save: () => stack.push({ ...st }),
restore: () => { const p = stack.pop(); if (p) st = p; },
+ resetTransform: () => { st.tx = 0; st.ty = 0; st.rot = 0; st.sx = 1; st.sy = 1; },
+ setTransform: (a: number, _b: number, _c: number, d: number, e: number, f: number) => {
+ st.sx = a;
+ st.sy = d;
+ st.tx = e;
+ st.ty = f;
+ st.rot = 0;
+ },
+ getTransform: () => ({ a: st.sx, b: 0, c: 0, d: st.sy, e: st.tx, f: st.ty }),
+ beginPath: () => {},
+ rect: () => {},
+ clip: () => {},
translate: (x: number, y: number) => {
const c = Math.cos(st.rot), s = Math.sin(st.rot);
st.tx += (x * c - y * s) * st.sx;
@@ -49,14 +103,22 @@ function createSoftwareCanvas(initW: number, initH: number) {
height: h,
data: new Uint8ClampedArray(w * h * 4),
}),
- putImageData: (img: { width: number; height: number; data: Uint8ClampedArray }, dx = 0, dy = 0) => {
- for (let y = 0; y < img.height; y++) {
- const ty = dy + y;
+ putImageData: (
+ img: { width: number; height: number; data: Uint8ClampedArray },
+ dx = 0,
+ dy = 0,
+ dirtyX = 0,
+ dirtyY = 0,
+ dirtyW = img.width,
+ dirtyH = img.height
+ ) => {
+ for (let row = 0; row < dirtyH; row++) {
+ const ty = dy + dirtyY + row;
if (ty < 0 || ty >= height) continue;
- for (let x = 0; x < img.width; x++) {
- const tx = dx + x;
+ for (let col = 0; col < dirtyW; col++) {
+ const tx = dx + dirtyX + col;
if (tx < 0 || tx >= width) continue;
- const si = (y * img.width + x) * 4;
+ const si = ((dirtyY + row) * img.width + (dirtyX + col)) * 4;
const di = (ty * width + tx) * 4;
buf[di] = img.data[si];
buf[di + 1] = img.data[si + 1];
@@ -326,13 +388,14 @@ describe('CSP .sut Import & Oil Paint Parity', () => {
expect(brush.name).toBe('Oil Paint Brush');
expect(brush.tipDataUrl).toBeUndefined(); // Circle tip, NOT paper texture!
expect(brush.paperTexture).toBeDefined();
- expect(brush.paperTextureMode).toBe('multiply');
+ expect(brush.paperTextureMode).toBe('normal');
expect(brush.paperTextureApplyEachPlot).toBe(true);
expect(brush.textureDensity).toBeCloseTo(0.62, 4);
expect(brush.spacing).toBeCloseTo(0.003, 5); // 0.3% = 0.003, NOT 30%!
expect(brush.thickness).toBeCloseTo(0.17, 4);
+ expect(brush.thicknessVertical).toBe(true); // CSP Horizontal (BrushVerticalThicknes=0) scales local X
expect(brush.angleDynamics).toBe('direction');
- expect(brush.angle).toBe(90); // CSP 12-o'clock forward -> +90 deg
+ expect(brush.angle).toBe(0); // CSP Direction of line aligns local +X directly with atan2(dy, dx)
expect(brush.rotationRandomScale).toBe(0); // Random is OFF!
expect(brush.wetEdge).toBe(0); // BrushUseWaterEdge=0!
expect(brush.colorMixing).toBe(true);
@@ -590,4 +653,3074 @@ describe('CSP .sut Import & Oil Paint Parity', () => {
expect(aMidTail).toBeLessThan(aPast381 - 15);
expect(aEndTail).toBeLessThan(aMidTail - 40);
});
+
+ it('parses ◇スケッチ.sut (AutoIntervalType=1 Narrow, Overlay texture, TextureForPlot=0) and renders rich per-stroke texture on solid square tips', async () => {
+ const tinyPng = new Uint8Array([
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
+ 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
+ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
+ 0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53,
+ 0xde, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e,
+ 0x44, 0xae, 0x42, 0x60, 0x82,
+ ]);
+ const texCat = '.:Install:Paint001:4abe2a6fb7-9a42-c98b-2492-2b41211e8c';
+ const extracted: NativeSutExtract = {
+ nodeName: '◇スケッチ',
+ variantId: 913,
+ variantValues: new Map<string, unknown>([
+ ['brushsize', 30],
+ ['opacity', 90],
+ ['brushflow', 100],
+ ['brushadjustflowbyinterval', 1],
+ ['brushautointervaltype', 1], // Narrow!
+ ['brushinterval', 1.0],
+ ['brushthickness', 51],
+ ['brushverticalthicknes', 0],
+ ['brushrotation', 0],
+ ['brushrotationeffector', 67],
+ ['brushusepatternimage', 0],
+ ['textureimage', new TextEncoder().encode(texCat)],
+ ['texturecompositemode', 4], // Overlay
+ ['texturedensity', 89],
+ ['texturescale2', 70],
+ ['textureforplot', 0], // Per-stroke!
+ ['brushusewatercolor', 0],
+ ['brushopacityeffector', makeFakeEffector(0x10, 0, 100, [[0, 0], [0.59, 0.655], [1, 1]])],
+ ['brushfloweffector', makeFakeEffector(0x10, 0, 100, [[0, 0], [0.54, 0.79], [1, 1]])],
+ ]),
+ materials: [
+ {
+ pwId: '1',
+ originalPath: `${texCat}:data:material.layer`,
+ catalogPath: texCat,
+ fileData: tinyPng,
+ },
+ ],
+ };
+
+ const brush = await parseSutExtractedData(extracted, '◇スケッチ.sut');
+ expect(brush.spacing).toBeCloseTo(0.04, 4); // Narrow (NOT 0.25!)
+ expect(brush.paperTextureMode).toBe('overlay');
+ expect(brush.paperTextureApplyEachPlot).toBe(false);
+ expect(brush.textureDensity).toBeCloseTo(0.89, 4);
+ expect(brush.paperTextureScale).toBeCloseTo(0.7, 4);
+ expect(brush.thickness).toBeCloseTo(0.51, 4);
+ expect(brush.thicknessVertical).toBe(true);
+
+ // Overlay texture mode MUST modulate even solid 1.0 alpha tips (previously overlay(1, g) === 1!)
+ const valleyA = applyCspPaperTextureAlpha(1.0, 0.05, 0.89, 1.0, 'overlay', 0, 0, false, true);
+ const peakA = applyCspPaperTextureAlpha(1.0, 0.95, 0.89, 1.0, 'overlay', 0, 0, false, true);
+ expect(peakA - valleyA).toBeGreaterThan(0.45);
+
+ // Render a real per-stroke textured stroke (TextureForPlot=0) with a solid square tip & checkerboard paper texture
+ const paperImg = createSoftwareCanvas(16, 16);
+ for (let y = 0; y < 16; y++) {
+ for (let x = 0; x < 16; x++) {
+ const i = (y * 16 + x) * 4;
+ // CSP paper texture format: RGB=0, alpha encodes darkness (0=peak, 255=valley)
+ const isValley = ((x >> 1) + (y >> 1)) % 2 === 0;
+ paperImg.buf[i] = 0;
+ paperImg.buf[i + 1] = 0;
+ paperImg.buf[i + 2] = 0;
+ paperImg.buf[i + 3] = isValley ? 245 : 10;
+ }
+ }
+ const solidSquareTip = createSoftwareCanvas(16, 16);
+ for (let i = 0; i < solidSquareTip.buf.length; i += 4) {
+ solidSquareTip.buf[i] = 255;
+ solidSquareTip.buf[i + 1] = 255;
+ solidSquareTip.buf[i + 2] = 255;
+ solidSquareTip.buf[i + 3] = 255;
+ }
+
+ const surf = createSoftwareCanvas(140, 80);
+ const pts: Point[] = [];
+ for (let i = 0; i <= 10; i++) {
+ pts.push({ x: 20 + i * 10, y: 40, pressure: 0.6, width: 30 });
+ }
+ renderCompleteStroke(
+ surf.ctx,
+ pts,
+ {
+ size: 30,
+ minSizeFactor: 0,
+ color: '#e89040',
+ opacity: 0.9,
+ flow: 1.0,
+ spacing: 0.04,
+ adjustDensityByGap: true,
+ hardness: 1.0,
+ thickness: 0.51,
+ thicknessVertical: true,
+ customTipImage: solidSquareTip as unknown as HTMLImageElement,
+ customTipAngle: 0,
+ customTipAngleDynamics: 'direction',
+ antiAlias: 1,
+ usePressure: false,
+ smoothing: true,
+ stabilization: 0,
+ grain: 0.89,
+ textureDensity: 0.89,
+ paperTextureImage: paperImg as unknown as HTMLImageElement,
+ paperTextureMode: 'overlay',
+ paperTextureScale: 1.0,
+ paperTextureApplyEachPlot: false,
+ useGpu: false,
+ },
+ 'brush',
+ 'color'
+ );
+
+ // Sample alphas inside the stroke body: per-stroke texture MUST produce clear valley vs peak contrast
+ let minBodyA = 255;
+ let maxBodyA = 0;
+ for (let y = 32; y <= 48; y++) {
+ for (let x = 35; x <= 105; x++) {
+ const a = surf.buf[(y * 140 + x) * 4 + 3];
+ if (a < minBodyA) minBodyA = a;
+ if (a > maxBodyA) maxBodyA = a;
+ }
+ }
+ expect(maxBodyA).toBeGreaterThan(200);
+ expect(maxBodyA - minBodyA).toBeGreaterThan(95);
+ });
+
+ it('parses fur blend.sut (Amount=0, Density=0, Stretch=100%, Thickness=135%, IntervalEffector) and visibly blends contrasting colors', async () => {
+ const extracted: NativeSutExtract = {
+ nodeName: 'fur blend',
+ variantId: 856,
+ variantValues: new Map<string, unknown>([
+ ['brushsize', 36.2],
+ ['opacity', 100],
+ ['brushflow', 100],
+ ['brushinterval', 30.9],
+ ['brushautointervaltype', 0],
+ ['brushintervaleffector', makeFakeEffector(0x10, 0, 100, [[0, 0.62], [1, 0]])],
+ ['brushthickness', 135],
+ ['brushverticalthicknes', 0],
+ ['brushrotation', 0],
+ ['brushrotationeffector', 67],
+ ['brushusepatternimage', 0],
+ ['brushusewatercolor', 1],
+ ['brushwatercolor', 0],
+ ['brushmixcolor', 0],
+ ['brushmixalpha', 0],
+ ['brushmixcolorextension', 100],
+ ['brushopacityeffector', makeFakeEffector(0x10, 0, 100, [[0, 0], [1, 1]])],
+ ['brushfloweffector', makeFakeEffector(0x10, 0, 100, [[0, 0.368], [0.3, 0.75], [1, 1]])],
+ ]),
+ materials: [],
+ };
+
+ const brush = await parseSutExtractedData(extracted, 'fur blend.sut');
+ expect(brush.colorMixing).toBe(true);
+ expect(brush.amountOfPaint).toBe(0);
+ expect(brush.densityOfPaint).toBe(0);
+ expect(brush.colorStretch).toBeCloseTo(1.0, 4);
+ expect(brush.thickness).toBeCloseTo(1.35, 4);
+ expect(brush.thicknessVertical).toBe(true);
+ expect(brush.angle).toBe(0);
+ expect(brush.intervalSensor?.usePressure).toBe(true);
+
+ // Tall 56x300 tip with thickness=1.35 & thicknessVertical=true MUST fit inside BrushSize=36.2 (NOT 194px!)
+ const dims = computeTipStampDimensions(36.2, 1.35, true, 56, 300);
+ expect(dims.height).toBeCloseTo(36.2, 2);
+ expect(dims.width).toBeCloseTo(36.2 * ((56 * 1.35) / 300), 2);
+
+ // Multi-bristle tall rake tip (12x60 with 3 separated bristles)
+ const rakeTip = createSoftwareCanvas(12, 60);
+ for (let y = 0; y < 60; y++) {
+ const inBristle = (y >= 4 && y <= 14) || (y >= 24 && y <= 34) || (y >= 44 && y <= 54);
+ if (!inBristle) continue;
+ for (let x = 1; x < 11; x++) {
+ const i = (y * 12 + x) * 4;
+ rakeTip.buf[i] = 255;
+ rakeTip.buf[i + 1] = 255;
+ rakeTip.buf[i + 2] = 255;
+ rakeTip.buf[i + 3] = 255;
+ }
+ }
+
+ // Paint left half BLACK (x < 90) and right half ORANGE (90 <= x < 180), blank canvas (x >= 180)
+ const surf = createSoftwareCanvas(240, 100);
+ for (let y = 0; y < 100; y++) {
+ for (let x = 0; x < 180; x++) {
+ const i = (y * 240 + x) * 4;
+ if (x < 90) {
+ surf.buf[i] = 15;
+ surf.buf[i + 1] = 15;
+ surf.buf[i + 2] = 15;
+ surf.buf[i + 3] = 255;
+ } else {
+ surf.buf[i] = 240;
+ surf.buf[i + 1] = 150;
+ surf.buf[i + 2] = 70;
+ surf.buf[i + 3] = 255;
+ }
+ }
+ }
+
+ const sampler = new LayerPixelSampler(surf as unknown as HTMLCanvasElement);
+ const pts: Point[] = [];
+ for (let i = 0; i <= 18; i++) {
+ pts.push({ x: 30 + i * 10, y: 50, pressure: 0.65, width: 42 });
+ }
+ renderCompleteStroke(
+ surf.ctx,
+ pts,
+ {
+ size: 42,
+ minSizeFactor: 0,
+ color: '#0000ff', // Foreground color MUST NOT leak when Amount=0!
+ opacity: 1.0,
+ flow: 1.0,
+ spacing: 0.309,
+ intervalSensor: { usePressure: true, pressureMin: 0, pressureCurve: [[0, 0.62], [1, 0]] },
+ opacitySensor: { usePressure: true, pressureMin: 0, pressureCurve: [[0, 0], [1, 1]] },
+ densitySensor: { usePressure: true, pressureMin: 0, pressureCurve: [[0, 0.368], [0.3, 0.75], [1, 1]] },
+ hardness: 1.0,
+ thickness: 1.35,
+ thicknessVertical: true,
+ customTipImage: rakeTip as unknown as HTMLImageElement,
+ customTipAngle: 0,
+ customTipAngleDynamics: 'direction',
+ antiAlias: 1,
+ usePressure: true,
+ smoothing: true,
+ stabilization: 0,
+ colorMixing: true,
+ perceptualMixing: false,
+ amountOfPaint: 0,
+ densityOfPaint: 0,
+ colorStretch: 1.0,
+ mixingMode: 'blend',
+ useGpu: false,
+ },
+ 'brush',
+ 'color',
+ false,
+ surf as unknown as HTMLCanvasElement,
+ false,
+ sampler
+ );
+
+ // 1. Inside orange region (x=115, y=50 center bristle), black MUST be visibly dragged into orange!
+ const blendIdx = (50 * 240 + 115) * 4;
+ expect(surf.buf[blendIdx]).toBeLessThan(185); // Visibly darkened from 240 orange (NOT imperceptible!)
+ expect(surf.buf[blendIdx + 2]).toBeLessThan(120); // Zero blue foreground contamination!
+
+ // 2. Out onto blank canvas (x=196, y=50), orange/blended paint MUST be visibly stretched onto blank area!
+ const stretchIdx = (50 * 240 + 196) * 4;
+ expect(surf.buf[stretchIdx + 3]).toBeGreaterThan(75);
+ });
+
+ it('prefers Rust-decoded full-resolution data/*.layer PNG over thumbnail.png and propagates isDualToneTip & dualVariantValues', async () => {
+ const makeHeaderPng = (w: number, h: number) => {
+ const buf = new Uint8Array([
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
+ 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
+ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
+ 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4,
+ 0x89, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e,
+ 0x44, 0xae, 0x42, 0x60, 0x82,
+ ]);
+ const dv = new DataView(buf.buffer);
+ dv.setUint32(16, w, false);
+ dv.setUint32(20, h, false);
+ return buf;
+ };
+
+ const thumb64 = makeHeaderPng(64, 64);
+ const full512Tip1 = makeHeaderPng(512, 512);
+ const full512Tip2 = makeHeaderPng(512, 512);
+ const full256Dual = makeHeaderPng(256, 256);
+
+ const tip1Cat = '.:01:02:1111111111-2222-3333-4444-5555555555';
+ const tip2Cat = '.:01:02:aaaaaaaaaa-bbbb-cccc-dddd-eeeeeeeeee';
+ const dualCat = '.:01:02:9999999999-8888-7777-6666-5555555555';
+
+ const extracted: NativeSutExtract = {
+ nodeName: 'DualTone Ribbon',
+ nodeUuid: 'aabbccdd-1122-3344-5566-77889900abcd',
+ variantId: 42,
+ nodeInitVariantId: 43,
+ variantValues: new Map<string, unknown>([
+ ['brushsize', 28],
+ ['brushusepatternimage', 1],
+ ['brushpatternimagearray', new TextEncoder().encode(`${tip1Cat} ${tip2Cat}`)],
+ ['usedualbrush', 1],
+ ['dualbrushcompositemode', 2],
+ ]),
+ dualVariantValues: new Map<string, unknown>([
+ ['brushsize', 14],
+ ['brushinterval', 12],
+ ['brushrotation', 45],
+ ['brushpatternimagearray', new TextEncoder().encode(dualCat)],
+ ]),
+ materials: [
+ {
+ pwId: '1',
+ originalPath: 'tip1.layer',
+ catalogPath: tip1Cat,
+ fileData: thumb64, // lower-res fallback blob
+ decodedPng: full512Tip1, // full-res Rust decoded data/*.layer
+ width: 512,
+ height: 512,
+ expressionColor: 'gray',
+ isPaperTexture: false,
+ hasSubColor: true,
+ decodedFromLayer: true,
+ },
+ {
+ pwId: '2',
+ originalPath: 'tip2.layer',
+ catalogPath: tip2Cat,
+ fileData: thumb64,
+ decodedPng: full512Tip2,
+ width: 512,
+ height: 512,
+ expressionColor: 'color',
+ isPaperTexture: false,
+ hasSubColor: false,
+ decodedFromLayer: true,
+ },
+ {
+ pwId: '3',
+ originalPath: 'dual.layer',
+ catalogPath: dualCat,
+ fileData: thumb64,
+ decodedPng: full256Dual,
+ width: 256,
+ height: 256,
+ expressionColor: 'monochrome',
+ isPaperTexture: false,
+ hasSubColor: false,
+ decodedFromLayer: true,
+ },
+ ],
+ };
+
+ const brush = await parseSutExtractedData(extracted, 'DualTone Ribbon.sut');
+ expect(brush.name).toBe('DualTone Ribbon');
+ expect(brush.tipWidth).toBe(512);
+ expect(brush.tipHeight).toBe(512);
+ expect(brush.isColorTip).toBe(false);
+ expect(brush.isDualToneTip).toBe(true);
+ expect(brush.subTips).toHaveLength(2);
+ expect(brush.subTips![0].width).toBe(512);
+ expect(brush.subTips![0].isDualToneTip).toBe(true);
+ expect(brush.subTips![0].isColor).toBe(false);
+ expect(brush.subTips![1].width).toBe(512);
+ expect(brush.subTips![1].isColor).toBe(true);
+ expect(brush.subTips![1].isDualToneTip).toBe(false);
+ expect(brush.dualBrush).toBe(true);
+ expect(brush.dualBrushCompositeMode).toBe('darken');
+ expect(brush.dualSize).toBe(14);
+ expect(brush.dualSpacing).toBeCloseTo(0.12, 4);
+ expect(brush.dualAngle).toBe(45);
+ expect(brush.secondaryTipWidth).toBe(256);
+ expect(brush.secondaryTipHeight).toBe(256);
+ });
+
+ it('decodes large BrushSize values accurately using BrushSizeUnit / BrushSizeSpecifiedByScreen without dividing >250px by 10', async () => {
+ expect(decodeCspBrushSize(300, 0, 0)).toBe(300);
+ expect(decodeCspBrushSize(1200, 0, 0)).toBe(1200);
+ expect(decodeCspBrushSize(2000, 0, 0)).toBe(2000);
+ expect(decodeCspBrushSize(3500, 0, 0)).toBe(350); // legacy tenth-px overflow (>2000)
+ expect(decodeCspBrushSize(3000, 10, 0)).toBe(300); // explicit tenth-px unit
+
+ const airbrush = await parseSutExtractedData(
+ {
+ nodeName: '300px Soft Airbrush',
+ variantId: 1,
+ variantValues: new Map<string, unknown>([
+ ['brushsize', 300],
+ ['brushsizeunit', 0],
+ ['brushsizespecifiedbyscreen', 1],
+ ]),
+ materials: [],
+ },
+ 'Airbrush.sut'
+ );
+ expect(airbrush.size).toBe(300);
+ expect(airbrush.brushSizeUnit).toBe(0);
+ expect(airbrush.brushSizeSpecifiedByScreen).toBe(true);
+ });
+
+ it('strictly separates BrushCombineMode (layer blend) from BlendBrushTips (within-stroke dab combine)', async () => {
+ expect(mapCspBrushCombineMode(0)).toBe('normal');
+ expect(mapCspBrushCombineMode(2)).toBe('multiply');
+ expect(mapCspBrushCombineMode(10)).toBe('color-dodge-glow');
+ expect(mapCspBrushCombineMode(11)).toBe('add');
+ expect(mapCspBrushCombineMode(12)).toBe('add-glow');
+ expect(mapCspBrushCombineMode(20)).toBe('hard-mix');
+ expect(mapCspBrushCombineMode(26)).toBe('luminosity');
+ expect(mapCspBrushCombineMode(27)).toBe('behind');
+ expect(mapCspBrushCombineMode(28)).toBe('clear');
+ expect(mapCspBrushCombineMode(29)).toBe('compare-density');
+ expect(mapCspBrushCombineMode(36)).toBe('divide');
+
+ const brush = await parseSutExtractedData(
+ {
+ nodeName: 'Multiply Behind Brush',
+ variantId: 2,
+ variantValues: new Map<string, unknown>([
+ ['brushsize', 40],
+ ['brushcombinemode', 2], // Multiply against layer
+ ['blendbrushtips', 0], // Normal within-stroke dab accumulation
+ ]),
+ materials: [],
+ },
+ 'Multiply.sut'
+ );
+ expect(brush.brushCombineMode).toBe('multiply');
+ expect(brush.blendTipsMode).toBe('normal');
+
+ const behindCompare = await parseSutExtractedData(
+ {
+ nodeName: 'Behind Compare Brush',
+ variantId: 3,
+ variantValues: new Map<string, unknown>([
+ ['brushsize', 40],
+ ['brushcombinemode', 27], // Behind
+ ['blendbrushtips', 1], // Compare density within stroke
+ ]),
+ materials: [],
+ },
+ 'Behind.sut'
+ );
+ expect(behindCompare.brushCombineMode).toBe('behind');
+ expect(behindCompare.blendTipsMode).toBe('compare');
+ });
+
+ it('decodes per-source minimums, real CSP curve-length slots, and source bitmasks in parseCspEffector (44 & 48 byte headers)', () => {
+ const makeRealCspEffector = (opts: {
+ headerLen?: 44 | 48;
+ supportedMask?: number;
+ flags: number;
+ pressureMin?: number;
+ tiltMin?: number;
+ velocityMin?: number;
+ randomMin?: number;
+ maxScale?: number;
+ pressureCurve?: [number, number][];
+ tiltCurve?: [number, number][];
+ velocityCurve?: [number, number][];
+ }) => {
+ const headerLen = opts.headerLen ?? 48;
+ const pBytes = opts.pressureCurve ? 12 + opts.pressureCurve.length * 16 : 0;
+ const tBytes = opts.tiltCurve ? 12 + opts.tiltCurve.length * 16 : 0;
+ const vBytes = opts.velocityCurve ? 12 + opts.velocityCurve.length * 16 : 0;
+ const buf = new Uint8Array(headerLen + pBytes + tBytes + vBytes);
+ const v = new DataView(buf.buffer);
+ v.setUint32(0, headerLen, false);
+ v.setUint32(4, opts.supportedMask ?? 0x1f0, false);
+ v.setUint32(8, opts.flags, false);
+ v.setInt32(12, opts.pressureMin ?? 0, false);
+ v.setInt32(16, opts.tiltMin ?? 0, false);
+ v.setInt32(20, opts.velocityMin ?? 0, false);
+ v.setInt32(24, opts.randomMin ?? 0, false);
+ v.setUint32(28, 0, false);
+ if (headerLen >= 48) {
+ v.setUint32(32, pBytes, false);
+ v.setUint32(36, tBytes, false);
+ v.setUint32(40, opts.maxScale ?? 100, false);
+ v.setUint32(44, vBytes, false);
+ }
+ let off = headerLen;
+ for (const pts of [opts.pressureCurve, opts.tiltCurve, opts.velocityCurve]) {
+ if (!pts) continue;
+ v.setUint32(off, 12, false);
+ v.setUint32(off + 4, pts.length, false);
+ v.setUint32(off + 8, 16, false);
+ off += 12;
+ for (const [x, y] of pts) {
+ v.setFloat64(off, x, false);
+ v.setFloat64(off + 8, y, false);
+ off += 16;
+ }
+ }
+ return buf;
+ };
+
+ const pCurve: [number, number][] = [[0, 0.1], [1, 1]];
+ const tCurve: [number, number][] = [[0, 0.2], [0.5, 0.8], [1, 1]];
+ const vCurve: [number, number][] = [[0, 1], [1, 0.3]];
+
+ const fullBlob = makeRealCspEffector({
+ headerLen: 48,
+ flags: 0x10 | 0x20 | 0x40 | 0x80,
+ pressureMin: 25,
+ tiltMin: 40,
+ velocityMin: 60,
+ randomMin: 15,
+ maxScale: 500, // 0x1f4 must NEVER trigger false invertTilt / invertVelocity!
+ pressureCurve: pCurve,
+ tiltCurve: tCurve,
+ velocityCurve: vCurve,
+ });
+
+ const eff = parseCspEffector(fullBlob);
+ expect(eff).not.toBeNull();
+ expect(eff!.usePressure).toBe(true);
+ expect(eff!.useTilt).toBe(true);
+ expect(eff!.useVelocity).toBe(true);
+ expect(eff!.useRandom).toBe(true);
+ expect(eff!.pressureMin).toBeCloseTo(0.25, 4);
+ expect(eff!.tiltMin).toBeCloseTo(0.4, 4);
+ expect(eff!.velocityMin).toBeCloseTo(0.6, 4);
+ expect(eff!.randomMin).toBeCloseTo(0.15, 4);
+ expect(eff!.invertTilt).toBe(false);
+ expect(eff!.invertVelocity).toBe(false);
+ expect(eff!.pressureCurve).toEqual(pCurve);
+ expect(eff!.tiltCurve).toEqual(tCurve);
+ expect(eff!.velocityCurve).toEqual(vCurve);
+
+ // Real CSP Tilt-only effector that still retains a disabled Pressure curve before the Tilt curve
+ const tiltOnlyWithSavedP = makeRealCspEffector({
+ headerLen: 48,
+ flags: 0x20,
+ pressureMin: 50,
+ tiltMin: 35,
+ maxScale: 150,
+ pressureCurve: pCurve,
+ tiltCurve: tCurve,
+ });
+ const effTilt = parseCspEffector(tiltOnlyWithSavedP);
+ expect(effTilt).not.toBeNull();
+ expect(effTilt!.usePressure).toBe(false);
+ expect(effTilt!.useTilt).toBe(true);
+ expect(effTilt!.tiltMin).toBeCloseTo(0.35, 4);
+ expect(effTilt!.pressureCurve).toBeUndefined();
+ expect(effTilt!.tiltCurve).toEqual(tCurve);
+
+ // 44-byte compact header with Tilt + Velocity + explicit invertVelocity flag bit
+ const compact44 = makeRealCspEffector({
+ headerLen: 44,
+ flags: 0x20 | 0x40 | 0x8000,
+ tiltMin: 30,
+ velocityMin: 50,
+ tiltCurve: tCurve,
+ velocityCurve: vCurve,
+ });
+ const eff44 = parseCspEffector(compact44);
+ expect(eff44).not.toBeNull();
+ expect(eff44!.usePressure).toBe(false);
+ expect(eff44!.useTilt).toBe(true);
+ expect(eff44!.useVelocity).toBe(true);
+ expect(eff44!.tiltMin).toBeCloseTo(0.3, 4);
+ expect(eff44!.velocityMin).toBeCloseTo(0.5, 4);
+ expect(eff44!.invertTilt).toBe(false);
+ expect(eff44!.invertVelocity).toBe(true);
+ expect(eff44!.pressureCurve).toBeUndefined();
+ expect(eff44!.tiltCurve).toEqual(tCurve);
+ expect(eff44!.velocityCurve).toEqual(vCurve);
+ });
+
+ it('maps sub-tip order, thickness dynamics, and complete angle dynamics (integer bitmask + BLOB effector)', async () => {
+ const orderCases: Array<[number, string]> = [
+ [0, 'sequential'],
+ [1, 'reverse'],
+ [2, 'once'],
+ [3, 'random'],
+ [4, 'random-no-repeat'],
+ [5, 'direction'],
+ ];
+ for (const [code, expected] of orderCases) {
+ const b = await parseSutExtractedData({
+ nodeName: `Order ${code}`,
+ variantId: 10 + code,
+ variantValues: new Map<string, unknown>([['brushpatternordertype', code]]),
+ materials: [],
+ });
+ expect(b.subTipOrder).toBe(expected);
+ }
+
+ const angleBlob = makeFakeEffector(0x40 | 0x80, 20, 100, [[0, 0], [1, 1]]);
+ const thickBlob = makeFakeEffector(0x10, 35, 100, [[0, 0.35], [1, 1]]);
+ const blobBrush = await parseSutExtractedData({
+ nodeName: 'Blob Angle & Thickness',
+ variantId: 20,
+ variantValues: new Map<string, unknown>([
+ ['brushthicknesseffector', thickBlob],
+ ['brushrotationeffector', angleBlob],
+ ['brushrotationrandomscale', 65],
+ ]),
+ materials: [],
+ });
+ expect(blobBrush.thicknessSensor?.usePressure).toBe(true);
+ expect(blobBrush.thicknessSensor?.pressureMin).toBeCloseTo(0.35, 4);
+ expect(blobBrush.angleDynamics).toBe('direction-random');
+ expect(blobBrush.angleSensor?.useVelocity).toBe(true);
+ expect(blobBrush.angleSensor?.useRandom).toBe(true);
+ expect(blobBrush.rotationRandomScale).toBeCloseTo(0.65, 4);
+
+ // Real CSP integer BrushRotationEffector bitmask codes (low nibble 0x03)
+ const rotCases: Array<[number, string]> = [
+ [3, 'none'], // 0x03 = Fixed angle
+ [19, 'tilt'], // 0x13 = Direction of pen (Tilt)
+ [35, 'twist'], // 0x23 = Rotation of pen axis
+ [67, 'direction'], // 0x43 = Direction of line
+ [131, 'random'], // 0x83 = Random
+ [195, 'direction-random'], // 0xc3 = Direction + Random
+ [259, 'initial-direction'],// 0x103 = Initial direction
+ [6, 'initial-direction'], // Legacy direct enum code
+ ];
+ for (const [code, expected] of rotCases) {
+ const rb = await parseSutExtractedData({
+ nodeName: `Rot ${code}`,
+ variantId: 21 + code,
+ variantValues: new Map<string, unknown>([['brushrotationeffector', code]]),
+ materials: [],
+ });
+ expect(rb.angleDynamics).toBe(expected);
+ }
+ });
+
+ it('maps Color Jitter, Color Mixing effectors, Ground Mixing, Blur, all 9 TextureCompositeMode values, and Extended Spray', async () => {
+ const effP = makeFakeEffector(0x10, 15, 100, [[0, 0], [1, 1]]);
+ const effV = makeFakeEffector(0x40, 25, 100, [[0, 0], [1, 1]]);
+ const tinyPng = new Uint8Array([
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
+ 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
+ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
+ 0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53,
+ 0xde, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e,
+ 0x44, 0xae, 0x42, 0x60, 0x82,
+ ]);
+ const texCat = '.:09:11:1111111111-aaaa-bbbb-cccc-2222222222';
+
+ const brush = await parseSutExtractedData({
+ nodeName: 'Painterly Jitter Spray',
+ variantId: 30,
+ variantValues: new Map<string, unknown>([
+ ['brushsize', 64],
+ // Color Jitter
+ ['brushchangebrushcolor', 1],
+ ['brushchangecolorperstroke', 1],
+ ['brushsubcolormix', 45],
+ ['brushsubcolormixeffector', effP],
+ ['brushrandomhue', 18],
+ ['brushrandomhueeffector', effP],
+ ['brushrandomsaturation', 30],
+ ['brushrandomsaturationeffector', effV],
+ ['brushrandomluminance', 22],
+ ['brushrandomluminanceeffector', effP],
+ // Color Mixing Effectors + Ground Mixing + Blur
+ ['brushusewatercolor', 1],
+ ['brushwatercolor', 3],
+ ['brushmixcoloreffector', effP],
+ ['brushmixalphaeffector', effP],
+ ['brushmixcolorextensioneffector', effV],
+ ['brushmixgroundcolor', 1],
+ ['brushuseblur', 1],
+ ['brushblur', 70],
+ // Paper Texture Position + Offset + Mode
+ ['textureimage', new TextEncoder().encode(texCat)],
+ ['texturedensity', 80],
+ ['texturecompositemode', 7], // height
+ ['textureposition', 2], // stroke-flow
+ ['textureoffsetx', 12],
+ ['textureoffsety', -8],
+ // Extended Spray
+ ['brushusespray', 1],
+ ['brushspraysize', 120],
+ ['brushspraydensity', 18],
+ ['brushsprayparticlesize', 14],
+ ['brushspraylinksize', 1],
+ ['brushspraysizeeffector', effP],
+ ['brushspraydensityeffector', effV],
+ ['brushspraydirection', 135],
+ ['brushspraydirectioneffector', 67], // 0x43 = direction of line
+ ['brushspraydeviation', -35],
+ ]),
+ materials: [
+ { pwId: '1', originalPath: 'tex.layer', catalogPath: texCat, fileData: tinyPng },
+ ],
+ });
+
+ // Color Jitter
+ expect(brush.dynamics?.colorJitterEnabled).toBe(true);
+ expect(brush.dynamics?.colorJitterPerStroke).toBe(true);
+ expect(brush.dynamics?.foregroundBackgroundJitter).toBeCloseTo(0.45, 4);
+ expect(brush.dynamics?.hueJitter).toBeCloseTo(0.18, 4);
+ expect(brush.dynamics?.saturationJitter).toBeCloseTo(0.3, 4);
+ expect(brush.dynamics?.brightnessJitter).toBeCloseTo(0.22, 4);
+ expect(brush.dynamics?.subColorMixSensor?.usePressure).toBe(true);
+ expect(brush.dynamics?.hueJitterSensor?.usePressure).toBe(true);
+ expect(brush.dynamics?.saturationJitterSensor?.useVelocity).toBe(true);
+ expect(brush.dynamics?.luminanceJitterSensor?.usePressure).toBe(true);
+
+ // Color Mixing Effectors + Ground Mixing + Blur
+ expect(brush.amountOfPaintSensor?.usePressure).toBe(true);
+ expect(brush.densityOfPaintSensor?.usePressure).toBe(true);
+ expect(brush.colorStretchSensor?.useVelocity).toBe(true);
+ expect(brush.mixGroundColor).toBe(true);
+ expect(brush.useBlur).toBe(true);
+ expect(brush.blurStrength).toBeCloseTo(0.7, 4);
+ expect(brush.mixingMode).toBe('smear');
+
+ // Texture mode + position + offsets
+ expect(brush.paperTextureMode).toBe('height');
+ expect(brush.grainMappingMode).toBe('stroke-flow');
+ expect(brush.paperTextureOffsetX).toBe(12);
+ expect(brush.paperTextureOffsetY).toBe(-8);
+
+ // Verify all 9 TextureCompositeMode enum values & alpha evaluation
+ const allTexModes: Array<[number, CspPaperTextureMode]> = [
+ [0, 'normal'],
+ [1, 'multiply'],
+ [2, 'subtract'],
+ [3, 'compare'],
+ [4, 'overlay'],
+ [5, 'color-burn'],
+ [6, 'linear-burn'],
+ [7, 'height'],
+ [8, 'outline'],
+ ];
+ for (const [idx, expectedMode] of allTexModes) {
+ const tb = await parseSutExtractedData({
+ nodeName: `Tex ${idx}`,
+ variantId: 40 + idx,
+ variantValues: new Map<string, unknown>([['texturecompositemode', idx]]),
+ materials: [],
+ });
+ expect(tb.paperTextureMode).toBe(expectedMode);
+ const a = applyCspPaperTextureAlpha(0.8, 0.4, 0.75, 0.5, expectedMode);
+ expect(a).toBeGreaterThanOrEqual(0);
+ expect(a).toBeLessThanOrEqual(1);
+ }
+
+ // Extended Spray
+ expect(brush.spray?.enabled).toBe(true);
+ expect(brush.spray?.size).toBe(120);
+ expect(brush.spray?.density).toBe(18);
+ expect(brush.spray?.particleSize).toBe(14);
+ expect(brush.spray?.linkSize).toBe(true);
+ expect(brush.spray?.sizeSensor?.usePressure).toBe(true);
+ expect(brush.spray?.densitySensor?.useVelocity).toBe(true);
+ expect(brush.spray?.direction).toBe(135);
+ expect(brush.spray?.directionDynamics).toBe('direction');
+ expect(brush.spray?.deviation).toBeCloseTo(-0.35, 4);
+ expect(brush.spray?.bias).toBeCloseTo(-0.35, 4);
+ });
+
+ it('parses full Dual Brush configuration merged from primary DualBrush* columns and dualVariantValues', async () => {
+ const tinyPng = new Uint8Array([
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
+ 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
+ 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02,
+ 0x08, 0x02, 0x00, 0x00, 0x00, 0xfd, 0xd4, 0x9a,
+ 0x73, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e,
+ 0x44, 0xae, 0x42, 0x60, 0x82,
+ ]);
+ const dualTipA = '.:01:02:1111111111-1111-1111-1111-1111111111';
+ const dualTipB = '.:01:02:2222222222-2222-2222-2222-2222222222';
+
+ const brush = await parseSutExtractedData({
+ nodeName: 'Full Dual Brush',
+ variantId: 50,
+ variantValues: new Map<string, unknown>([
+ ['brushsize', 80],
+ ['usedualbrush', 1],
+ ['dualbrushcompositemode', 11], // overlay
+ ['dualbrushlinksize', 1],
+ ['dualbrushhardness', 3], // discrete 3 -> 0.6
+ ['dualbrushdensity', 65],
+ ['dualbrushpatternordertype', 4], // random-no-repeat
+ ['dualbrushfliph', 3], // random
+ ['dualbrushflipv', 1], // alternate
+ ['dualbrushribbon', 1],
+ ['dualbrushusespray', 1],
+ ['dualbrushspraysize', 45],
+ ['dualbrushspraydensity', 12],
+ ['dualbrushsprayparticlesize', 8],
+ ]),
+ dualVariantValues: new Map<string, unknown>([
+ ['brushsize', 320], // >250px must remain 320px!
+ ['brushautointervaltype', 3], // Wide -> 0.22
+ ['brushthickness', 60],
+ ['brushverticalthicknes', 1], // Vertical -> thicknessVertical=false
+ ['brushrotation', 25],
+ ['brushrotationeffector', 5], // twist
+ ['brushpatternimagearray', new TextEncoder().encode(`${dualTipA} ${dualTipB}`)],
+ ]),
+ materials: [
+ { pwId: '1', originalPath: 'a.layer', catalogPath: dualTipA, fileData: tinyPng },
+ { pwId: '2', originalPath: 'b.layer', catalogPath: dualTipB, fileData: tinyPng },
+ ],
+ });
+
+ expect(brush.dualBrush).toBe(true);
+ expect(brush.dualBrushCompositeMode).toBe('overlay');
+ expect(brush.dualSize).toBe(320);
+ expect(brush.dualLinkSize).toBe(true);
+ expect(brush.dualSpacing).toBeCloseTo(0.22, 4);
+ expect(brush.dualThickness).toBeCloseTo(0.6, 4);
+ expect(brush.dualThicknessVertical).toBe(false);
+ expect(brush.dualAngle).toBe(25);
+ expect(brush.dualAngleDynamics).toBe('twist');
+ expect(brush.dualHardness).toBeCloseTo(0.6, 4);
+ expect(brush.dualDensity).toBeCloseTo(0.65, 4);
+ expect(brush.dualSubTipOrder).toBe('random-no-repeat');
+ expect(brush.dualFlipH).toBe('random');
+ expect(brush.dualFlipV).toBe('alternate');
+ expect(brush.dualIsRibbon).toBe(true);
+ expect(brush.dualSpray?.enabled).toBe(true);
+ expect(brush.dualSpray?.size).toBe(45);
+ expect(brush.dualSpray?.density).toBe(12);
+ expect(brush.dualSpray?.particleSize).toBe(8);
+ expect(brush.dualSubTips).toHaveLength(2);
+ expect(brush.secondaryTipDataUrl).toBeDefined();
+ });
+
+ it('distinguishes discrete 1..5 hardness vs 0..100% and normalizes wetEdgeAlphaPower/wetEdgeValuePower to 0..1 across parser and renderer', async () => {
+ expect(decodeCspHardness(1)).toBeCloseTo(0.2, 4);
+ expect(decodeCspHardness(3)).toBeCloseTo(0.6, 4);
+ expect(decodeCspHardness(5)).toBeCloseTo(1.0, 4);
+ expect(decodeCspHardness(50)).toBeCloseTo(0.5, 4);
+ expect(decodeCspHardness(100)).toBeCloseTo(1.0, 4);
+ expect(decodeCspHardness(0.75)).toBeCloseTo(0.75, 4);
+
+ const brush = await parseSutExtractedData({
+ nodeName: 'Watercolor Rim Brush',
+ variantId: 60,
+ variantValues: new Map<string, unknown>([
+ ['brushhardness', 4], // discrete 4 -> 0.8
+ ['brushusewateredge', 1],
+ ['brushwateredgeradius', 4.5],
+ ['brushwateredgealphapower', 40],
+ ['brushwateredgevaluepower', 25],
+ ]),
+ materials: [],
+ });
+
+ expect(brush.hardness).toBeCloseTo(0.8, 4);
+ expect(brush.wetEdgeRadius).toBeCloseTo(4.5, 4);
+ expect(brush.wetEdgeAlphaPower).toBeCloseTo(0.4, 4);
+ expect(brush.wetEdgeValuePower).toBeCloseTo(0.25, 4);
+ expect(brush.wetEdge).toBeCloseTo(0.4, 4);
+
+ // Defensive normalization in applyCspWatercolorEdge: legacy 0..100 values produce identical pixels to 0..1
+ const makeImg = () => {
+ const w = 16, h = 16;
+ const data = new Uint8ClampedArray(w * h * 4);
+ for (let y = 3; y < 13; y++) {
+ for (let x = 3; x < 13; x++) {
+ const i = (y * w + x) * 4;
+ data[i] = 180;
+ data[i + 1] = 120;
+ data[i + 2] = 90;
+ data[i + 3] = 170;
+ }
+ }
+ return { data, width: w, height: h };
+ };
+ const imgNorm = makeImg();
+ const imgLegacy = makeImg();
+ applyCspWatercolorEdge(imgNorm, 0.8, 2, 0.4, 0.25);
+ applyCspWatercolorEdge(imgLegacy, 0.8, 2, 40, 25);
+ expect(Array.from(imgLegacy.data)).toEqual(Array.from(imgNorm.data));
+ });
+
+ it('records clear importWarnings for missing external CatalogPath materials without crashing or hijacking paper texture as tip', async () => {
+ const tinyPng = new Uint8Array([
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
+ 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
+ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
+ 0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53,
+ 0xde, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e,
+ 0x44, 0xae, 0x42, 0x60, 0x82,
+ ]);
+ const embeddedPaperCat = '.:Install:Paper:embedded-paper-001';
+ const missingTipCat = '.:Install:BrushTip:external-missing-nib';
+ const missingTexCat = '.:Install:PaperTexture:external-missing-grain';
+
+ const brushWithEmbeddedPaper = await parseSutExtractedData({
+ nodeName: 'External Tip With Embedded Paper',
+ variantId: 70,
+ variantValues: new Map<string, unknown>([
+ ['brushusepatternimage', 1],
+ ['brushpatternimagearray', new TextEncoder().encode(missingTipCat)],
+ ['textureimage', new TextEncoder().encode(embeddedPaperCat)],
+ ['texturedensity', 55],
+ ]),
+ materials: [
+ {
+ pwId: '1',
+ originalPath: 'paper.layer',
+ catalogPath: embeddedPaperCat,
+ fileData: tinyPng,
+ isPaperTexture: true,
+ },
+ ],
+ });
+ expect(brushWithEmbeddedPaper.tipDataUrl).toBeUndefined(); // Clean procedural fallback, NEVER paper texture!
+ expect(brushWithEmbeddedPaper.paperTexture).toBeDefined();
+ expect(brushWithEmbeddedPaper.importWarnings).toBeDefined();
+ expect(brushWithEmbeddedPaper.importWarnings!.some((w) => w.includes(missingTipCat))).toBe(true);
+
+ const brushMissingTex = await parseSutExtractedData({
+ nodeName: 'External Texture Missing',
+ variantId: 71,
+ variantValues: new Map<string, unknown>([
+ ['brushusepatternimage', 0],
+ ['textureimage', new TextEncoder().encode(missingTexCat)],
+ ['texturedensity', 70],
+ ]),
+ materials: [],
+ });
+ expect(brushMissingTex.paperTexture).toBeUndefined();
+ expect(brushMissingTex.textureDensity).toBe(0);
+ expect(brushMissingTex.importWarnings).toBeDefined();
+ expect(brushMissingTex.importWarnings!.some((w) => w.includes(missingTexCat))).toBe(true);
+ });
+
+ it('persists all newly mapped CSP brush fields across preset switches and brushStorage hydration', async () => {
+ const effP = makeFakeEffector(0x10, 20, 100, [[0, 0], [1, 1]]);
+ const imported = await parseSutExtractedData({
+ nodeName: 'Full Parity Persistence Brush',
+ variantId: 80,
+ variantValues: new Map<string, unknown>([
+ ['brushsize', 310],
+ ['brushsizeunit', 0],
+ ['brushsizespecifiedbyscreen', 1],
+ ['brushcombinemode', 29], // compare-density
+ ['blendbrushtips', 0], // normal
+ ['brushpatternordertype', 4], // random-no-repeat
+ ['brushthicknesseffector', effP],
+ ['brushmixcoloreffector', effP],
+ ['brushmixalphaeffector', effP],
+ ['brushmixcolorextensioneffector', effP],
+ ['brushmixgroundcolor', 1],
+ ['brushuseblur', 1],
+ ['brushblur', 45],
+ ['texturecompositemode', 5], // color-burn
+ ['textureposition', 3], // random-per-stroke
+ ['textureoffsetx', 24],
+ ['textureoffsety', -16],
+ ['brushchangebrushcolor', 1],
+ ['brushchangecolorperstroke', 1],
+ ['brushrandomhue', 30],
+ ['usedualbrush', 1],
+ ['dualbrushcompositemode', 11],
+ ['dualbrushsize', 180],
+ ['dualbrushlinksize', 1],
+ ['dualbrushhardness', 4],
+ ['dualbrushdensity', 75],
+ ['dualbrushpatternordertype', 2], // once
+ ['dualbrushfliph', 3],
+ ['dualbrushflipv', 1],
+ ['dualbrushribbon', 1],
+ ]),
+ materials: [],
+ });
+
+ const hydrated = await prepareBrushSettingsForCsp(imported);
+ expect(hydrated.size).toBe(310);
+ expect(hydrated.brushSizeSpecifiedByScreen).toBe(true);
+ expect(hydrated.brushCombineMode).toBe('compare-density');
+ expect(hydrated.blendTipsMode).toBe('normal');
+ expect(hydrated.subTipOrder).toBe('random-no-repeat');
+ expect(hydrated.thicknessSensor?.usePressure).toBe(true);
+ expect(hydrated.amountOfPaintSensor?.usePressure).toBe(true);
+ expect(hydrated.densityOfPaintSensor?.usePressure).toBe(true);
+ expect(hydrated.colorStretchSensor?.usePressure).toBe(true);
+ expect(hydrated.mixGroundColor).toBe(true);
+ expect(hydrated.useBlur).toBe(true);
+ expect(hydrated.blurStrength).toBeCloseTo(0.45, 4);
+ expect(hydrated.paperTextureMode).toBe('color-burn');
+ expect(hydrated.grainMappingMode).toBe('random-per-stroke');
+ expect(hydrated.paperTextureOffsetX).toBe(24);
+ expect(hydrated.paperTextureOffsetY).toBe(-16);
+ expect(hydrated.dynamics?.colorJitterPerStroke).toBe(true);
+ expect(hydrated.dualSize).toBe(180);
+ expect(hydrated.dualLinkSize).toBe(true);
+ expect(hydrated.dualHardness).toBeCloseTo(0.8, 4);
+ expect(hydrated.dualDensity).toBeCloseTo(0.75, 4);
+ expect(hydrated.dualSubTipOrder).toBe('once');
+ expect(hydrated.dualFlipH).toBe('random');
+ expect(hydrated.dualFlipV).toBe('alternate');
+ expect(hydrated.dualIsRibbon).toBe(true);
+
+ // Save overridden values through brushPresetManager and read back via getEffectiveBrushSettings
+ saveBrushSettingsImmediately(imported.id, {
+ ...hydrated,
+ brushCombineMode: 'behind',
+ subTipOrder: 'once',
+ mixGroundColor: false,
+ paperTextureOffsetX: 99,
+ dualLinkSize: false,
+ });
+ const reloaded = getEffectiveBrushSettings(imported.id, [imported]);
+ expect(reloaded.brushCombineMode).toBe('behind');
+ expect(reloaded.subTipOrder).toBe('once');
+ expect(reloaded.mixGroundColor).toBe(false);
+ expect(reloaded.paperTextureOffsetX).toBe(99);
+ expect(reloaded.dualLinkSize).toBe(false);
+ expect(reloaded.thicknessSensor?.usePressure).toBe(true);
+ expect(reloaded.amountOfPaintSensor?.usePressure).toBe(true);
+ expect(reloaded.dualIsRibbon).toBe(true);
+ });
+
+ it('parses ザッサラ絵筆油彩風.sut (0x90=Pressure+Random opacity, RotEff=3 fixed 218° angle, ThicknessEffector) with CSP width/opacity/angle parity on CPU & GPU', async () => {
+ const buildCspEffector = (opts: {
+ supportedMask: number;
+ flags: number;
+ pMin?: number;
+ tMin?: number;
+ vMin?: number;
+ rMin?: number;
+ maxScale?: number;
+ pCurve?: [number, number][];
+ tCurve?: [number, number][];
+ vCurve?: [number, number][];
+ }) => {
+ const pBytes = opts.pCurve ? 12 + opts.pCurve.length * 16 : 0;
+ const tBytes = opts.tCurve ? 12 + opts.tCurve.length * 16 : 0;
+ const vBytes = opts.vCurve ? 12 + opts.vCurve.length * 16 : 0;
+ const buf = new Uint8Array(48 + pBytes + tBytes + vBytes);
+ const v = new DataView(buf.buffer);
+ v.setUint32(0, 48, false);
+ v.setUint32(4, opts.supportedMask, false);
+ v.setUint32(8, opts.flags, false);
+ v.setInt32(12, opts.pMin ?? 0, false);
+ v.setInt32(16, opts.tMin ?? 0, false);
+ v.setInt32(20, opts.vMin ?? 0, false);
+ v.setInt32(24, opts.rMin ?? 0, false);
+ v.setUint32(28, 0, false);
+ v.setUint32(32, pBytes, false);
+ v.setUint32(36, tBytes, false);
+ v.setUint32(40, opts.maxScale ?? 100, false);
+ v.setUint32(44, vBytes, false);
+ let off = 48;
+ for (const pts of [opts.pCurve, opts.tCurve, opts.vCurve]) {
+ if (!pts) continue;
+ v.setUint32(off, 12, false);
+ v.setUint32(off + 4, pts.length, false);
+ v.setUint32(off + 8, 16, false);
+ off += 12;
+ for (const [x, y] of pts) {
+ v.setFloat64(off, x, false);
+ v.setFloat64(off + 8, y, false);
+ off += 16;
+ }
+ }
+ return buf;
+ };
+
+ // Exact Variant 800 blobs from ザッサラ絵筆油彩風.sut
+ const sizeEff = buildCspEffector({
+ supportedMask: 0x1f0,
+ flags: 0x10,
+ pMin: 0,
+ vMin: 60,
+ rMin: 67,
+ pCurve: [[0, 0], [1, 1]],
+ });
+ const opacityEff = buildCspEffector({
+ supportedMask: 0x0f0,
+ flags: 0x90, // 0x10 (Pressure) | 0x80 (Random) — NOT Velocity!
+ pMin: 0,
+ rMin: 90,
+ pCurve: [[0, 0], [0.5182, 0.6909], [1, 1]],
+ });
+ const flowEff = buildCspEffector({
+ supportedMask: 0x1f0,
+ flags: 0x10, // Pressure only, with a saved inactive Tilt curve
+ pMin: 20,
+ tMin: 100,
+ vMin: 90,
+ maxScale: 500,
+ pCurve: [[0, 0], [1, 1]],
+ tCurve: [[0, 1], [0.5, 1], [0.8, 0], [1, 0]],
+ });
+ const thicknessEff = buildCspEffector({
+ supportedMask: 0x1f0,
+ flags: 0x10,
+ pMin: 0,
+ pCurve: [[0, 0], [0.9909, 0], [1, 1]],
+ });
+ const mixAlphaEff = buildCspEffector({
+ supportedMask: 0x1f0,
+ flags: 0x10,
+ pMin: 0,
+ pCurve: [[0, 0], [1, 1]],
+ });
+
+ const brush = await parseSutExtractedData({
+ nodeName: 'ザッサラ絵筆油彩風',
+ variantId: 800,
+ variantValues: new Map<string, unknown>([
+ ['brushsize', 66.7],
+ ['brushsizeeffector', sizeEff],
+ ['opacity', 100],
+ ['brushopacityeffector', opacityEff],
+ ['brushflow', 100],
+ ['brushfloweffector', flowEff],
+ ['brushadjustflowbyinterval', 0],
+ ['brushinterval', 1.8],
+ ['brushautointervaltype', 0],
+ ['brushhardness', 95],
+ ['brushthickness', 100],
+ ['brushverticalthicknes', 1],
+ ['brushthicknesseffector', thicknessEff],
+ ['brushrotation', 218.0],
+ ['brushrotationeffector', 3], // 0x03 = Fixed angle (None), NOT direction!
+ ['brushrotationrandomscale', 100],
+ ['brushusepatternimage', 0],
+ ['brushusewatercolor', 1],
+ ['brushwatercolor', 0],
+ ['brushmixcolor', 55],
+ ['brushmixalpha', 100],
+ ['brushmixalphaeffector', mixAlphaEff],
+ ['brushmixcolorextension', 35],
+ ['brushusewateredge', 1],
+ ['brushwateredgeradius', 1.8],
+ ['brushwateredgealphapower', 8],
+ ['brushwateredgevaluepower', 25],
+ ]),
+ materials: [],
+ });
+
+ // 1. Verify exact CSP sensor & rotation decoding
+ expect(brush.opacitySensor?.usePressure).toBe(true);
+ expect(brush.opacitySensor?.useRandom).toBe(true);
+ expect(brush.opacitySensor?.randomMin).toBeCloseTo(0.9, 4);
+ expect(brush.opacitySensor?.useVelocity).toBe(false);
+ expect(brush.opacitySensor?.pressureCurve).toEqual([[0, 0], [0.5182, 0.6909], [1, 1]]);
+ expect(brush.densitySensor?.usePressure).toBe(true);
+ expect(brush.densitySensor?.pressureMin).toBeCloseTo(0.2, 4);
+ expect(brush.densitySensor?.useTilt).toBe(false);
+ expect(brush.densitySensor?.tiltCurve).toBeUndefined();
+ expect(brush.angle).toBe(218);
+ expect(brush.angleDynamics).toBe('none');
+ expect(brush.rotationRandomScale).toBe(0);
+ expect(brush.thickness).toBeCloseTo(1.0, 4);
+ expect(brush.thicknessVertical).toBe(false);
+ expect(brush.thicknessSensor?.usePressure).toBe(true);
+
+ // 2. Render light vs heavy vertical strokes (matching CSP Photo 1 Strokes 1 & 2) with vertical bristle tip
+ const bristleTip = createSoftwareCanvas(64, 64);
+ for (let y = 0; y < 64; y++) {
+ for (let x = 2; x < 62; x++) {
+ // Dense vertical bristles across the tip width
+ const ridge = 0.55 + 0.45 * Math.cos((x / 64) * Math.PI * 14);
+ const i = (y * 64 + x) * 4;
+ bristleTip.buf[i] = 255;
+ bristleTip.buf[i + 1] = 255;
+ bristleTip.buf[i + 2] = 255;
+ bristleTip.buf[i + 3] = Math.round(ridge * 255);
+ }
+ }
+
+ const baseSettings: BrushSettings = {
+ size: brush.size,
+ minSizeFactor: brush.minSizeFactor,
+ color: '#ff2400',
+ opacity: brush.opacity,
+ flow: brush.flow,
+ adjustDensityByGap: brush.adjustDensityByGap,
+ spacing: brush.spacing,
+ hardness: brush.hardness,
+ thickness: brush.thickness,
+ thicknessVertical: brush.thicknessVertical,
+ thicknessSensor: brush.thicknessSensor,
+ customTipImage: bristleTip as unknown as HTMLImageElement,
+ customTipAngle: brush.angle,
+ customTipAngleDynamics: brush.angleDynamics,
+ customTipRotationRandomScale: brush.rotationRandomScale,
+ antiAlias: 1,
+ usePressure: brush.usePressure,
+ pressureCurve: brush.pressureCurve,
+ sizeSensor: brush.sizeSensor,
+ opacitySensor: brush.opacitySensor,
+ densitySensor: brush.densitySensor,
+ densityOfPaintSensor: brush.densityOfPaintSensor,
+ smoothing: true,
+ stabilization: 0,
+ colorMixing: true,
+ perceptualMixing: false,
+ amountOfPaint: brush.amountOfPaint,
+ densityOfPaint: brush.densityOfPaint,
+ colorStretch: brush.colorStretch,
+ mixingMode: brush.mixingMode,
+ useGpu: false,
+ };
+
+ const surf = createSoftwareCanvas(240, 220);
+ const sampler = new LayerPixelSampler(surf as unknown as HTMLCanvasElement);
+ // Stroke 1: Light pressure vertical stroke (x=60)
+ const lightPts: Point[] = [];
+ for (let i = 0; i <= 14; i++) {
+ lightPts.push({ x: 60, y: 30 + i * 10, pressure: 0.25, width: 66.7 * 0.25 });
+ }
+ renderCompleteStroke(surf.ctx, lightPts, baseSettings, 'brush', 'color', false, surf as unknown as HTMLCanvasElement, false, sampler);
+
+ // Stroke 2: Heavy pressure vertical stroke (x=160), ending with a longer catch-up segment (must NOT create a dark end-dot!)
+ const heavyPts: Point[] = [];
+ for (let i = 0; i <= 12; i++) {
+ heavyPts.push({ x: 160, y: 30 + i * 10, pressure: 0.85, width: 66.7 * 0.85 });
+ }
+ heavyPts.push({ x: 160, y: 175, pressure: 0.85, width: 66.7 * 0.85 }); // Longer final segment simulating stabilizer catch-up
+ renderCompleteStroke(surf.ctx, heavyPts, baseSettings, 'brush', 'color', false, surf as unknown as HTMLCanvasElement, false, sampler);
+
+ const measureRowWidth = (y: number, xStart: number, xEnd: number, thresh = 30) => {
+ let minX = xEnd;
+ let maxX = xStart;
+ let maxA = 0;
+ for (let x = xStart; x <= xEnd; x++) {
+ const a = surf.buf[(y * 240 + x) * 4 + 3];
+ if (a > maxA) maxA = a;
+ if (a >= thresh) {
+ if (x < minX) minX = x;
+ if (x > maxX) maxX = x;
+ }
+ }
+ return { width: maxX >= minX ? maxX - minX + 1 : 0, maxA };
+ };
+
+ const lightMid = measureRowWidth(100, 20, 100);
+ const heavyMid = measureRowWidth(100, 110, 210);
+ const heavyEnd = measureRowWidth(160, 110, 210);
+
+ // Heavy vertical stroke must be wide (~42-50px) and bold/opaque (>220), far wider & denser than light stroke!
+ expect(heavyMid.width).toBeGreaterThan(38);
+ expect(heavyMid.width).toBeGreaterThan(lightMid.width * 2.2);
+ expect(heavyMid.maxA).toBeGreaterThan(220);
+ expect(lightMid.maxA).toBeGreaterThan(40);
+ expect(lightMid.maxA).toBeLessThan(heavyMid.maxA - 30);
+ // Mid-stroke must already be fully dense (no washed-out body + dark end-dot!)
+ expect(Math.abs(heavyMid.maxA - heavyEnd.maxA)).toBeLessThan(25);
+
+ // 3. Fixed 218° angle chisel anisotropy: `/` stroke (perpendicular to 218°) is wider than `\` stroke (parallel to 218°)
+ const diagSurf = createSoftwareCanvas(220, 140);
+ const diagSampler = new LayerPixelSampler(diagSurf as unknown as HTMLCanvasElement);
+ const slashPts: Point[] = []; // top-right to bottom-left `/` (~125°)
+ const backslashPts: Point[] = []; // top-left to bottom-right `\` (~38°)
+ for (let i = 0; i <= 10; i++) {
+ const u = i / 10;
+ slashPts.push({ x: 85 - u * 45, y: 25 + u * 85, pressure: 0.8, width: 66.7 * 0.8 });
+ backslashPts.push({ x: 130 + u * 65, y: 35 + u * 50, pressure: 0.8, width: 66.7 * 0.8 });
+ }
+ renderCompleteStroke(diagSurf.ctx, slashPts, baseSettings, 'brush', 'color', false, diagSurf as unknown as HTMLCanvasElement, false, diagSampler);
+ renderCompleteStroke(diagSurf.ctx, backslashPts, baseSettings, 'brush', 'color', false, diagSurf as unknown as HTMLCanvasElement, false, diagSampler);
+
+ let slashLit = 0;
+ let backslashLit = 0;
+ for (let y = 0; y < 140; y++) {
+ for (let x = 0; x < 110; x++) {
+ if (diagSurf.buf[(y * 220 + x) * 4 + 3] > 60) slashLit++;
+ }
+ for (let x = 110; x < 220; x++) {
+ if (diagSurf.buf[(y * 220 + x) * 4 + 3] > 60) backslashLit++;
+ }
+ }
+ expect(slashLit).toBeGreaterThan(backslashLit * 1.5);
+
+ // 4. GPU dab emission parity: thicknessSensor floor (0.10), fixed 218° angle, and velocity-free opacity match CPU path
+ const gpuDabs: GpuDab[] = [];
+ const p0: Point = { x: 20, y: 20, pressure: 0.8, width: 66.7 * 0.8 };
+ const p3: Point = { x: 20, y: 120, pressure: 0.8, width: 66.7 * 0.8 };
+ const c1: Point = { x: 20, y: 53, pressure: 0.8, width: 66.7 * 0.8 };
+ const c2: Point = { x: 20, y: 86, pressure: 0.8, width: 66.7 * 0.8 };
+ drawBrushCubicBezierSegment(
+ surf.ctx,
+ p0,
+ c1,
+ c2,
+ p3,
+ '#ff2400',
+ {
+ size: brush.size,
+ minSizeFactor: brush.minSizeFactor,
+ opacity: 1.0,
+ flow: 1.0,
+ spacing: 0.1,
+ thickness: brush.thickness,
+ thicknessVertical: brush.thicknessVertical,
+ thicknessSensor: brush.thicknessSensor,
+ angle: brush.angle,
+ angleDynamics: brush.angleDynamics,
+ opacitySensor: brush.opacitySensor,
+ densitySensor: brush.densitySensor,
+ colorMixing: false,
+ },
+ 0,
+ { count: 0 },
+ gpuDabs
+ );
+ expect(gpuDabs.length).toBeGreaterThan(5);
+ const sampleDab = gpuDabs[Math.floor(gpuDabs.length / 2)];
+ // Fixed 218° angle in radians
+ expect(sampleDab.angle).toBeCloseTo((218 * Math.PI) / 180, 4);
+ // CSP 10% thickness floor on height (not 5%!)
+ expect(sampleDab.height / sampleDab.width).toBeCloseTo(0.1, 2);
+ // Opacity driven by Pressure + Random(0.9..1.0), NOT crushed by fake velocity!
+ expect(sampleDab.alpha).toBeGreaterThan(0.65);
+ });
+
+ it('calibrates Oil Pastel (오일 파스텔.sut): steep BrushSizeEffector never causes detached start dots on CPU or GPU, and asymmetric flow/density curves ramp smoothly', async () => {
+ const tinyPng = new Uint8Array([
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
+ 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
+ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
+ 0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53,
+ 0xde, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e,
+ 0x44, 0xae, 0x42, 0x60, 0x82,
+ ]);
+ const tipCat = '.:07:55:10fc7c53ef-f34e-a4a3-6239-75669202b9';
+ const texCat = '.:10:41:0871fa2caf-d14c-e5b9-c3a7-d1a5d077a2';
+
+ const sizeCurve: [number, number][] = [[0, 0], [0.0043, 1.0], [1.0, 1.0]];
+ const flowCurve: [number, number][] = [[0, 0], [0.0043, 0], [0.6379, 0.1928], [1.0, 1.0]];
+ const mixColorCurve: [number, number][] = [[0, 0], [1.0, 1.0]];
+ const mixAlphaCurve: [number, number][] = [[0, 0], [0.8491, 0.1285], [1.0, 1.0]];
+
+ const extracted: NativeSutExtract = {
+ nodeName: '오일 파스텔',
+ variantId: 840,
+ variantValues: new Map<string, unknown>([
+ ['brushsize', 149.8],
+ ['brushsizeunit', 0],
+ ['brushsizeeffector', makeFakeEffector(0x10, 0, 100, sizeCurve)],
+ ['opacity', 100],
+ ['brushflow', 100],
+ ['brushfloweffector', makeFakeEffector(0x10, 0, 100, flowCurve)],
+ ['brushadjustflowbyinterval', 0],
+ ['brushautointervaltype', 0],
+ ['brushinterval', 7.0],
+ ['brushhardness', 100],
+ ['brushthickness', 100],
+ ['brushverticalthicknes', 0],
+ ['brushrotation', 0],
+ ['brushrotationeffector', 3],
+ ['antialias', 1],
+ ['brushusepatternimage', 1],
+ ['brushpatternimagearray', new TextEncoder().encode(tipCat)],
+ ['textureimage', new TextEncoder().encode(texCat)],
+ ['texturedensity', 52],
+ ['texturecompositemode', 2], // Subtract
+ ['textureforplot', 1],
+ ['texturescale2', 100.0],
+ ['brushusewatercolor', 1],
+ ['brushusewatercolor2', 1],
+ ['brushwatercolor', 0], // Blend
+ ['brushcolormixingmode', 0], // Standard RGB
+ ['brushmixcolor', 30],
+ ['brushmixcoloreffector', makeFakeEffector(0x10, 0, 100, mixColorCurve)],
+ ['brushmixalpha', 100],
+ ['brushmixalphaeffector', makeFakeEffector(0x10, 0, 100, mixAlphaCurve)],
+ ['brushmixcolorextension', 10],
+ ['brushusein', 1],
+ ['brushuseout', 1],
+ ['brushinouttype', 0], // Taper OFF
+ ]),
+ materials: [
+ { pwId: '1', originalPath: `${texCat}:data:material_0.layer`, catalogPath: texCat, fileData: tinyPng, isPaperTexture: true },
+ { pwId: '2', originalPath: `${tipCat}:data:material_0.layer`, catalogPath: tipCat, fileData: tinyPng, isPaperTexture: false },
+ ],
+ };
+
+ const brush = await parseSutExtractedData(extracted, '오일 파스텔.sut');
+ expect(brush.size).toBeCloseTo(149.8, 2);
+ expect(brush.spacing).toBeCloseTo(0.07, 4);
+ expect(brush.adjustDensityByGap).toBe(false);
+ expect(brush.colorMixing).toBe(true);
+ expect(brush.perceptualMixing).toBe(false);
+ expect(brush.amountOfPaint).toBeCloseTo(0.3, 4);
+ expect(brush.densityOfPaint).toBeCloseTo(1.0, 4);
+ expect(brush.colorStretch).toBeCloseTo(0.1, 4);
+ expect(brush.paperTextureMode).toBe('subtract');
+ expect(brush.paperTextureApplyEachPlot).toBe(true);
+ expect(brush.taper).toBeUndefined();
+ expect(brush.pressureCurve).toEqual(sizeCurve);
+ expect(brush.densitySensor?.pressureCurve).toEqual(flowCurve);
+ expect(brush.densityOfPaintSensor?.pressureCurve).toEqual(mixAlphaCurve);
+
+ // 1. Weighted harmonic mean PCHIP preserves smooth light-pressure ramps on asymmetric steep-tail curves
+ // (previously arithmetic mean + clamping crushed y(0.25) to ~0.006 on BrushMixAlphaEffector!)
+ const mixAlphaAt25 = evaluateFastSpline(0.25, mixAlphaCurve);
+ const flowAt30 = evaluateFastSpline(0.3, flowCurve);
+ expect(mixAlphaAt25).toBeGreaterThan(0.02);
+ expect(mixAlphaAt25).toBeLessThan(0.12);
+ expect(flowAt30).toBeGreaterThan(0.035);
+ expect(flowAt30).toBeLessThan(0.15);
+ // Strict monotonicity across full [0, 1] range
+ let prevY = 0;
+ for (let i = 0; i <= 100; i++) {
+ const y = evaluateFastSpline(i / 100, mixAlphaCurve);
+ expect(y).toBeGreaterThanOrEqual(prevY - 1e-6);
+ prevY = y;
+ }
+
+ // 2. Regression check for detached start dot (CPU SpatialTipMixer + GPU drawBrushDot parity):
+ // Even though BrushSizeEffector(0.05) === 1.0, drawBrushDot MUST pass raw pressure (0.05) — NOT 1.0 —
+ // to densitySensor / densityOfPaintSensor / amountOfPaintSensor!
+ const surf = createSoftwareCanvas(160, 220);
+ const sampler = new LayerPixelSampler(surf as unknown as HTMLCanvasElement);
+ const pastelSettings: BrushSettings = {
+ size: 36,
+ minSizeFactor: 0,
+ color: '#ff1800',
+ opacity: 1.0,
+ flow: 1.0,
+ spacing: 0.07,
+ adjustDensityByGap: false,
+ hardness: 1.0,
+ thickness: 1.0,
+ thicknessVertical: true,
+ customTipAngle: 0,
+ customTipAngleDynamics: 'none',
+ antiAlias: 1,
+ usePressure: true,
+ smoothing: true,
+ stabilization: 0,
+ pressureCurve: sizeCurve,
+ densitySensor: brush.densitySensor,
+ amountOfPaintSensor: brush.amountOfPaintSensor,
+ densityOfPaintSensor: brush.densityOfPaintSensor,
+ colorMixing: true,
+ perceptualMixing: false,
+ amountOfPaint: 0.3,
+ densityOfPaint: 1.0,
+ colorStretch: 0.1,
+ mixingMode: 'blend',
+ useGpu: false,
+ };
+
+ // Pressure-ramping stroke starting at very light touchdown (p=0.05) -> ramping up to max (p=0.98)
+ const rampPts: Point[] = [];
+ for (let i = 0; i <= 16; i++) {
+ const u = i / 16;
+ const p = 0.05 + 0.93 * u;
+ rampPts.push({ x: 80, y: 24 + i * 11, pressure: p, width: 36 });
+ }
+ renderCompleteStroke(
+ surf.ctx,
+ rampPts,
+ pastelSettings,
+ 'brush',
+ 'color',
+ false,
+ surf as unknown as HTMLCanvasElement,
+ false,
+ sampler
+ );
+
+ const startDotA = surf.buf[(24 * 160 + 80) * 4 + 3];
+ const earlyA = surf.buf[(57 * 160 + 80) * 4 + 3];
+ const midA = surf.buf[(123 * 160 + 80) * 4 + 3];
+ const maxA = surf.buf[(189 * 160 + 80) * 4 + 3];
+
+ // Standalone single touchdown dot at p=0.05 must be virtually invisible (<= 6/255)
+ const dotSurf = createSoftwareCanvas(96, 96);
+ renderCompleteStroke(
+ dotSurf.ctx,
+ [{ x: 48, y: 48, pressure: 0.05, width: 36 }],
+ pastelSettings,
+ 'brush',
+ 'color',
+ false,
+ dotSurf as unknown as HTMLCanvasElement,
+ false,
+ new LayerPixelSampler(dotSurf as unknown as HTMLCanvasElement)
+ );
+ expect(dotSurf.buf[(48 * 96 + 48) * 4 + 3]).toBeLessThanOrEqual(6);
+
+ // Zero detached dot at stroke start: touchdown alpha at p=0.05 stays a smooth fade-in (never a blotch!)
+ expect(startDotA).toBeLessThanOrEqual(60);
+ expect(startDotA).toBeLessThan(earlyA);
+ // Smooth monotonic buildup into full opaque max pressure
+ expect(midA).toBeGreaterThan(startDotA + 40);
+ expect(maxA).toBeGreaterThan(220);
+
+ // 2b. Constant-pressure strokes verify CSP-calibrated pressure response (BrushFlowEffector drives
+ // per-plot density without BrushMixAlphaEffector's low curve bottlenecking light/medium pressure!)
+ const measureConstantPressureAlpha = (pVal: number, extra?: Partial<BrushSettings>): number => {
+ const c = createSoftwareCanvas(120, 160);
+ const s = new LayerPixelSampler(c as unknown as HTMLCanvasElement);
+ const linePts: Point[] = [];
+ for (let i = 0; i <= 14; i++) {
+ linePts.push({ x: 60, y: 20 + i * 8, pressure: pVal, width: 36 });
+ }
+ renderCompleteStroke(
+ c.ctx,
+ linePts,
+ { ...pastelSettings, ...extra },
+ 'brush',
+ 'color',
+ false,
+ c as unknown as HTMLCanvasElement,
+ false,
+ s
+ );
+ return c.buf[(80 * 120 + 60) * 4 + 3];
+ };
+ const lightStrokeA = measureConstantPressureAlpha(0.35);
+ const medStrokeA = measureConstantPressureAlpha(0.65);
+ const heavyStrokeA = measureConstantPressureAlpha(0.95);
+ // Light pressure (p=0.35) must be clearly visible pastel (~25-70% alpha), NOT invisible dead zone
+ expect(lightStrokeA).toBeGreaterThan(60);
+ expect(lightStrokeA).toBeLessThan(190);
+ // Medium pressure (p=0.65) builds rich oil-pastel coverage (~60-95%), matching CSP Stroke 1 & Stroke 4 mid
+ expect(medStrokeA).toBeGreaterThan(Math.max(150, lightStrokeA + 30));
+ expect(medStrokeA).toBeLessThan(248);
+ // Max pressure (p=0.95) reaches solid opaque pastel
+ expect(heavyStrokeA).toBeGreaterThan(240);
+
+ // With per-plot Subtract paper texture (TextureDensity=52%), light & medium strokes remain
+ // rich and match CSP (never collapsing to <15% faint washes when BrushMixAlphaEffector is active!)
+ const texturedLightA = measureConstantPressureAlpha(0.35, {
+ grain: 0.52,
+ textureDensity: 0.52,
+ paperTextureMode: 'subtract',
+ paperTextureApplyEachPlot: true,
+ });
+ const texturedMedA = measureConstantPressureAlpha(0.65, {
+ grain: 0.52,
+ textureDensity: 0.52,
+ paperTextureMode: 'subtract',
+ paperTextureApplyEachPlot: true,
+ });
+ expect(texturedLightA).toBeGreaterThan(45);
+ expect(texturedMedA).toBeGreaterThan(120);
+
+ // 2d. Deferred-initial-dot live incremental segment emission must match renderCompleteStroke on pointerup
+ // (no first-dab stepDist=0.12 vs 0.07 pop between live draft and committed stroke!)
+ const liveSurf = createSoftwareCanvas(120, 160);
+ const bakeSurf = createSoftwareCanvas(120, 160);
+ const parityPts: Point[] = [];
+ for (let i = 0; i <= 14; i++) {
+ parityPts.push({ x: 60, y: 20 + i * 8, pressure: 0.55, width: 36 });
+ }
+ const liveOpts = {
+ ...pastelSettings,
+ sampler: new LayerPixelSampler(liveSurf as unknown as HTMLCanvasElement),
+ reservoir: undefined as any,
+ };
+ let rem = 0;
+ const liveCounter: { count: number; lastStepDist?: number } = { count: 0 };
+ for (let i = 1; i < parityPts.length; i++) {
+ const pA = parityPts[i - 1];
+ const pB = parityPts[i];
+ const pPrev = parityPts[Math.max(0, i - 2)];
+ const pNext = parityPts[Math.min(parityPts.length - 1, i + 1)];
+ const { c1, c2 } = centripetalCatmullRomToBezier(pPrev, pA, pB, pNext);
+ rem = drawBrushCubicBezierSegment(liveSurf.ctx, pA, c1, c2, pB, pastelSettings.color, liveOpts, rem, liveCounter);
+ }
+ renderCompleteStroke(
+ bakeSurf.ctx,
+ parityPts,
+ pastelSettings,
+ 'brush',
+ 'color',
+ false,
+ bakeSurf as unknown as HTMLCanvasElement,
+ false,
+ new LayerPixelSampler(bakeSurf as unknown as HTMLCanvasElement)
+ );
+ const liveBodyA = liveSurf.buf[(80 * 120 + 60) * 4 + 3];
+ const bakeBodyA = bakeSurf.buf[(80 * 120 + 60) * 4 + 3];
+ expect(Math.abs(liveBodyA - bakeBodyA)).toBeLessThanOrEqual(8);
+
+ // 2c. CSP Blend (BrushWaterColor=0) uniform tip color mixing on Point 1:
+ // Drawing green (#66ff00) partially overlapping red (#fe2501) shifts the ENTIRE green stroke
+ // toward warm olive (matching CSP Blend), rather than leaving the outer left half pure neon green!
+ const blendSurf = createSoftwareCanvas(160, 160);
+ const redPts: Point[] = [];
+ for (let i = 0; i <= 12; i++) {
+ redPts.push({ x: 96, y: 20 + i * 10, pressure: 0.85, width: 36 });
+ }
+ renderCompleteStroke(
+ blendSurf.ctx,
+ redPts,
+ { ...pastelSettings, color: '#fe2501' },
+ 'brush',
+ 'color',
+ false,
+ blendSurf as unknown as HTMLCanvasElement,
+ false,
+ new LayerPixelSampler(blendSurf as unknown as HTMLCanvasElement)
+ );
+ const greenPts: Point[] = [];
+ for (let i = 0; i <= 12; i++) {
+ // Center at x=72 so right ~30% of the 36px green stroke overlaps the red stroke at x=78..114
+ greenPts.push({ x: 72, y: 20 + i * 10, pressure: 0.8, width: 36 });
+ }
+ renderCompleteStroke(
+ blendSurf.ctx,
+ greenPts,
+ { ...pastelSettings, color: '#66ff00' },
+ 'brush',
+ 'color',
+ false,
+ blendSurf as unknown as HTMLCanvasElement,
+ false,
+ new LayerPixelSampler(blendSurf as unknown as HTMLCanvasElement)
+ );
+ // Outer left side of green stroke (x=64, y=80 — over blank canvas, NOT over red!)
+ // must still have visibly picked up red into olive (R significantly above pure green's 102, G < 235)
+ const leftGreenIdx = (80 * 160 + 64) * 4;
+ expect(blendSurf.buf[leftGreenIdx + 3]).toBeGreaterThan(100);
+ expect(blendSurf.buf[leftGreenIdx]).toBeGreaterThan(135);
+ expect(blendSurf.buf[leftGreenIdx + 1]).toBeLessThan(225);
+
+ // 3. GPU path parity: drawBrushDot with batchGpuDabs must ALSO use uncurved raw pressure for densitySensor
+ const gpuDotDabs: GpuDab[] = [];
+ drawBrushDot(
+ surf.ctx,
+ { x: 80, y: 24, pressure: 0.05, width: 36 },
+ '#ff1800',
+ {
+ size: 36,
+ minSizeFactor: 0,
+ opacity: 1.0,
+ flow: 1.0,
+ spacing: 0.07,
+ usePressure: true,
+ pressureCurve: sizeCurve,
+ densitySensor: brush.densitySensor,
+ colorMixing: false,
+ },
+ gpuDotDabs
+ );
+ // At raw pressure 0.05, flowCurve(0.05) <= 0.002 -> dot must NOT emit a high-alpha GPU dab!
+ expect(gpuDotDabs.length === 0 || gpuDotDabs[0].alpha < 0.02).toBe(true);
+ });
+
+ it('InputStabilizer stays in fast attackCutoff on constant high pressure after light touchdown (no 4Hz decay lockout)', () => {
+ const stab = new InputStabilizer();
+ stab.setStabilizerLevel(6);
+ stab.setZoomScale(1.0);
+ stab.process(100, 100, 0.006, 0);
+
+ const pressures: number[] = [];
+ for (let i = 1; i <= 10; i++) {
+ const s = stab.process(100, 100 + i * 10, 0.95, i * 4);
+ pressures.push(s.pressure);
+ }
+
+ // Must converge quickly to constant 0.95 within 5 samples (20ms) instead of stalling at ~0.55..0.77 in 4Hz decay
+ expect(pressures[4]).toBeGreaterThanOrEqual(0.9);
+ expect(pressures[9]).toBeGreaterThanOrEqual(0.94);
+
+ // Smooth decay on release still works cleanly
+ const drop1 = stab.process(100, 210, 0.1, 44).pressure;
+ expect(drop1).toBeLessThan(0.95);
+ expect(drop1).toBeGreaterThan(0.5);
+ });
+
+ it('reconciles 0.006 WM_POINTERDOWN placeholder for firm and light Oil Pastel strokes with zero live-vs-pointerup pop', () => {
+ const origDoc = (globalThis as any).document;
+ const origImgData = (globalThis as any).ImageData;
+ const origRaf = (globalThis as any).requestAnimationFrame;
+ const origCancelRaf = (globalThis as any).cancelAnimationFrame;
+
+ (globalThis as any).requestAnimationFrame = () => 1;
+ (globalThis as any).cancelAnimationFrame = () => {};
+ (globalThis as any).ImageData = class {
+ data: Uint8ClampedArray;
+ width: number;
+ height: number;
+ constructor(d: Uint8ClampedArray, w: number, h: number) {
+ this.data = d;
+ this.width = w;
+ this.height = h;
+ }
+ };
+ (globalThis as any).document = {
+ createElement: () => createSoftwareCanvas(1, 1),
+ };
+
+ try {
+ const dims = { width: 512, height: 512 };
+ const grid = new SparseTileGrid();
+ const draftCanvas: any = createSoftwareCanvas(512, 512);
+ const state = createInitialStrokeSessionState();
+ const layer: LayerItem = {
+ id: 'layer-1',
+ name: 'Layer 1',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ type: 'raster',
+ } as any;
+
+ const oilPastelBs: BrushSettings = {
+ size: 64,
+ minSizeFactor: 0,
+ color: '#ff0000',
+ opacity: 1.0,
+ flow: 1.0,
+ spacing: 0.07,
+ adjustDensityByGap: false,
+ usePressure: true,
+ smoothing: true,
+ stabilization: 6,
+ postCorrection: 0,
+ sharpCorners: false,
+ hardness: 1.0,
+ antiAlias: 1,
+ thickness: 1.0,
+ thicknessVertical: true,
+ pressureCurve: [
+ [0, 0],
+ [0.00431, 1],
+ [1, 1],
+ ],
+ sizeSensor: {
+ usePressure: true,
+ pressureMin: 0,
+ pressureCurve: [
+ [0, 0],
+ [0.00431, 1],
+ [1, 1],
+ ],
+ },
+ densitySensor: {
+ usePressure: true,
+ pressureMin: 0,
+ pressureCurve: [
+ [0, 0],
+ [0.00431, 0],
+ [0.6379, 0.1928],
+ [1, 1],
+ ],
+ },
+ amountOfPaint: 0.3,
+ amountOfPaintSensor: {
+ usePressure: true,
+ pressureMin: 0,
+ pressureCurve: [
+ [0, 0],
+ [1, 1],
+ ],
+ },
+ densityOfPaint: 1.0,
+ densityOfPaintSensor: {
+ usePressure: true,
+ pressureMin: 0,
+ pressureCurve: [
+ [0, 0],
+ [0.8491, 0.1285],
+ [1, 1],
+ ],
+ },
+ colorStretch: 0.1,
+ colorMixing: true,
+ mixingMode: 'blend',
+ perceptualMixing: false,
+ grain: 0.52,
+ textureDensity: 0.52,
+ paperTextureMode: 'subtract',
+ paperTextureApplyEachPlot: true,
+ paperTextureScale: 1.0,
+ // Also verify CSP BrushInOutType=0 ("Off") never triggers taper on pointerup
+ taper: {
+ useIn: true,
+ useOut: true,
+ inOutType: 0,
+ inLength: 20,
+ inRatio: 0.3,
+ outLength: 20,
+ outRatio: 0.3,
+ } as any,
+ useGpu: false,
+ };
+
+ const zoom = 0.4; // Forces draftScale < 1.0 so pointerup runs renderCompleteStroke
+ const params: any = {
+ disabled: false,
+ viewportRef: {
+ current: {
+ getBoundingClientRect: () => ({
+ left: 0,
+ top: 0,
+ width: 512,
+ height: 512,
+ right: 512,
+ bottom: 512,
+ }),
+ },
+ },
+ interactionRef: { current: null },
+ isDrawingRef: { current: false },
+ panRef: { current: { x: 256, y: 256 } },
+ zoomRef: { current: zoom },
+ rotationRef: { current: 0 },
+ flipXRef: { current: false },
+ flipYRef: { current: false },
+ dimensionsRef: { current: dims },
+ layersRef: { current: [layer] },
+ activeLayerIdRef: { current: 'layer-1' },
+ activeLayerLockedRef: { current: false },
+ activeLayerVisibleRef: { current: true },
+ colorModeRef: { current: 'color' },
+ isMaskModeRef: { current: false },
+ getActiveMaskCanvas: () => null,
+ effectiveDraftCanvasRef: { current: draftCanvas },
+ activeTileGridRef: { current: grid },
+ selectionRef: { current: null },
+ rulerRef: { current: null },
+ straightRulerRef: { current: null },
+ lastStrokeEndRef: { current: null },
+ onActiveConstraintAxisChangeRef: { current: undefined },
+ onCollabStrokeStartRef: { current: undefined },
+ onCollabStrokeChunkRef: { current: undefined },
+ onCollabStrokeFinishRef: { current: undefined },
+ onCollabCursorMoveRef: { current: undefined },
+ onUpdateMaskThumbnailRef: { current: undefined },
+ enqueueHistoryTask: () => {},
+ pushHistoryStep: () => {},
+ flushPendingHistoryTasks: () => {},
+ onUpdateLayerThumbnail: () => {},
+ };
+
+ const helpers: any = {
+ getTool: () => 'brush',
+ getBrushSettings: () => oilPastelBs,
+ getPredictedCanvas: () => getPredictedCanvasElement(undefined),
+ clearPredictedCanvas: () => clearPredictedCanvasSurface(state, () => null),
+ emitConstraintAxisChange: (a: any) =>
+ emitConstraintAxisChangeIfNeeded(state, params.onActiveConstraintAxisChangeRef, a),
+ markTouchedTiles: (x0: number, y0: number, x1: number, y1: number) =>
+ markTouchedTilesInRect(dims, state.touchedTiles, x0, y0, x1, y1),
+ getViewportRect: () => getViewportRectCached(state, params.viewportRef),
+ dispatchPointerStat: () => {},
+ abortActiveStroke: () =>
+ abortActiveStrokeSession(
+ params,
+ state,
+ helpers.clearPredictedCanvas,
+ helpers.emitConstraintAxisChange
+ ),
+ getCanvasPoint: (e: any) =>
+ computeCanvasPoint(e, params, helpers.getViewportRect, helpers.getBrushSettings),
+ resolveEffectiveOpacitySensor: resolveEffectiveOpacitySensorValue,
+ resolveLiveAntiAlias: resolveLiveAntiAliasValue,
+ buildTouchedTileSpans: (sx: number, sy: number, dw: number, dh: number) =>
+ buildTouchedTileSpansFromSet(state.touchedTiles, sx, sy, dw, dh),
+ buildLiveBrushOptions: (...a: any[]) => (createLiveBrushOptions as any)(state, ...a),
+ resolveStrokeColor: (...a: any[]) => (resolveStrokeColorValue as any)(false, ...a),
+ emitLiveSegment: (...a: any[]) => (emitLiveSegmentToDraft as any)(state, params, helpers, ...a),
+ renderPredictedStroke: () => {},
+ flushPendingPoints: (skip?: any) => runFlushPendingPoints(state, params, helpers, skip),
+ };
+
+ const mkEvt = (dx: number, dy: number, p: number, ts: number) => {
+ const e: any = {
+ pointerId: -1001,
+ pointerType: 'pen',
+ button: 0,
+ buttons: 1,
+ clientX: 256 + (dx - 256) * zoom,
+ clientY: 256 + (dy - 256) * zoom,
+ pressure: p,
+ tiltX: 0,
+ tiltY: 0,
+ twist: 0,
+ timeStamp: ts,
+ shiftKey: false,
+ altKey: false,
+ preventDefault() {},
+ };
+ e.nativeEvent = e;
+ return e;
+ };
+
+ // 1. Firm max-pressure stroke (0.006 placeholder down -> 0.95 constant move)
+ runPointerDown(state, params, helpers, mkEvt(140, 100, 0.006, 100));
+ for (let i = 1; i <= 15; i++) {
+ runPointerMove(state, params, helpers, mkEvt(140, 100 + i * 20, 0.95, 100 + i * 4));
+ if (i % 3 === 0 || i === 15) runFlushPendingPoints(state, params, helpers, false);
+ }
+ const ds = draftCanvas.__draftScale ?? 1;
+ const dr = draftCanvas.__draftDocRect ?? { x: 0, y: 0 };
+ const livePxX = Math.round((140 - dr.x) * ds);
+ const livePxY = Math.round((250 - dr.y) * ds);
+ const liveFirmA = draftCanvas.buf[(livePxY * draftCanvas.width + livePxX) * 4 + 3];
+ runPointerUp(state, params, helpers, mkEvt(140, 400, 0, 170));
+
+ const pxOut: [number, number, number, number] = [0, 0, 0, 0];
+ grid.getPixelRGBA('layer-1', 140, 250, pxOut);
+ const tileFirmA = pxOut[3];
+ expect(liveFirmA).toBeGreaterThanOrEqual(235);
+ expect(tileFirmA).toBeGreaterThanOrEqual(235);
+ expect(Math.abs(liveFirmA - tileFirmA)).toBeLessThanOrEqual(12);
+
+ // 2. Light-pressure stroke (0.006 placeholder down -> 0.25 constant move)
+ runPointerDown(state, params, helpers, mkEvt(320, 100, 0.006, 200));
+ for (let i = 1; i <= 15; i++) {
+ runPointerMove(state, params, helpers, mkEvt(320, 100 + i * 20, 0.25, 200 + i * 4));
+ if (i % 3 === 0 || i === 15) runFlushPendingPoints(state, params, helpers, false);
+ }
+ const lightLivePxX = Math.round((320 - dr.x) * ds);
+ const lightLivePxY = Math.round((250 - dr.y) * ds);
+ const liveLightA = draftCanvas.buf[(lightLivePxY * draftCanvas.width + lightLivePxX) * 4 + 3];
+ runPointerUp(state, params, helpers, mkEvt(320, 400, 0, 270));
+
+ grid.getPixelRGBA('layer-1', 320, 250, pxOut);
+ const tileLightA = pxOut[3];
+ expect(tileLightA).toBeGreaterThan(25);
+ expect(tileLightA).toBeLessThan(150);
+ expect(tileFirmA - tileLightA).toBeGreaterThan(100);
+ expect(Math.abs(liveLightA - tileLightA)).toBeLessThanOrEqual(12);
+ } finally {
+ (globalThis as any).document = origDoc;
+ (globalThis as any).ImageData = origImgData;
+ (globalThis as any).requestAnimationFrame = origRaf;
+ (globalThis as any).cancelAnimationFrame = origCancelRaf;
+ }
+ });
+
+ it('preserves light-pressure Oil Pastel strokes on pen-lift over OPAQUE backgrounds (no 8-bit regionCanvas wipeout), guards inOutType=0 taper, and rounds LOD mipmap alpha unbiasedly', () => {
+ const origDoc = (globalThis as any).document;
+ const origImgData = (globalThis as any).ImageData;
+ const origRaf = (globalThis as any).requestAnimationFrame;
+ const origCancelRaf = (globalThis as any).cancelAnimationFrame;
+
+ (globalThis as any).requestAnimationFrame = () => 1;
+ (globalThis as any).cancelAnimationFrame = () => {};
+ (globalThis as any).ImageData = class {
+ data: Uint8ClampedArray;
+ width: number;
+ height: number;
+ constructor(d: Uint8ClampedArray, w: number, h: number) {
+ this.data = d;
+ this.width = w;
+ this.height = h;
+ }
+ };
+ (globalThis as any).document = {
+ createElement: () => createSoftwareCanvas(1, 1),
+ };
+
+ try {
+ // 1. CSP BrushInOutType=0 ("Off") must ALWAYS return identity taper factors even when useIn/useOut=true
+ const offTaper = {
+ useIn: true,
+ useOut: true,
+ inOutType: 0,
+ inLength: 40,
+ inRatio: 0.4,
+ outLength: 40,
+ outRatio: 0.4,
+ affectSize: true,
+ affectDensity: true,
+ affectOpacity: true,
+ affectAmountOfPaint: true,
+ affectDensityOfPaint: true,
+ } as any;
+ for (const dist of [0, 10, 100, 195, 200]) {
+ expect(evaluateCspTaperFactors(offTaper, dist, 200, 1.0)).toEqual({
+ sizeScale: 1.0,
+ alphaScale: 1.0,
+ amountScale: 1.0,
+ paintDensityScale: 1.0,
+ });
+ }
+
+ // 2. Light-pressure Oil Pastel stroke drawn on an OPAQUE WHITE layer (e.g. Background layer)
+ // at zoom=0.4 (forcing pointerUpRasterCommit re-bake):
+ // Previously, compositing low-alpha (1..5/255) color-mixing dabs directly onto an opaque
+ // regionCanvas snapped every dab back to RGB=(255,255,255) on pen lift!
+ const dims = { width: 512, height: 512 };
+ const grid = new SparseTileGrid();
+ const whiteData = new Uint8ClampedArray(512 * 512 * 4);
+ whiteData.fill(255);
+ grid.writeImageData('layer-bg', { data: whiteData, width: 512, height: 512 } as any, 0, 0, 'color-32bit', true);
+
+ const draftCanvas: any = createSoftwareCanvas(512, 512);
+ const state = createInitialStrokeSessionState();
+ const bgLayer: LayerItem = {
+ id: 'layer-bg',
+ name: 'Paper',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ type: 'raster',
+ } as any;
+
+ const oilPastelBs: BrushSettings = {
+ size: 64,
+ minSizeFactor: 0,
+ color: '#fe2501',
+ opacity: 1.0,
+ flow: 1.0,
+ spacing: 0.07,
+ adjustDensityByGap: false,
+ usePressure: true,
+ smoothing: true,
+ stabilization: 6,
+ postCorrection: 0,
+ sharpCorners: false,
+ hardness: 1.0,
+ antiAlias: 1,
+ thickness: 1.0,
+ thicknessVertical: true,
+ pressureCurve: [
+ [0, 0],
+ [0.00431, 1],
+ [1, 1],
+ ],
+ sizeSensor: {
+ usePressure: true,
+ pressureMin: 0,
+ pressureCurve: [
+ [0, 0],
+ [0.00431, 1],
+ [1, 1],
+ ],
+ },
+ densitySensor: {
+ usePressure: true,
+ pressureMin: 0,
+ pressureCurve: [
+ [0, 0],
+ [0.00431, 0],
+ [0.63793, 0.19277],
+ [1, 1],
+ ],
+ },
+ amountOfPaint: 0.3,
+ amountOfPaintSensor: {
+ usePressure: true,
+ pressureMin: 0,
+ pressureCurve: [
+ [0, 0],
+ [1, 1],
+ ],
+ },
+ densityOfPaint: 1.0,
+ densityOfPaintSensor: {
+ usePressure: true,
+ pressureMin: 0,
+ pressureCurve: [
+ [0, 0],
+ [0.84914, 0.12851],
+ [1, 1],
+ ],
+ },
+ colorStretch: 0.1,
+ colorMixing: true,
+ mixingMode: 'blend',
+ perceptualMixing: false,
+ grain: 0.52,
+ textureDensity: 0.52,
+ paperTextureMode: 'subtract',
+ paperTextureApplyEachPlot: true,
+ paperTextureScale: 1.0,
+ taper: offTaper,
+ useGpu: false,
+ };
+
+ const zoom = 0.4;
+ const params: any = {
+ disabled: false,
+ viewportRef: {
+ current: {
+ getBoundingClientRect: () => ({
+ left: 0,
+ top: 0,
+ width: 512,
+ height: 512,
+ right: 512,
+ bottom: 512,
+ }),
+ },
+ },
+ interactionRef: { current: null },
+ isDrawingRef: { current: false },
+ panRef: { current: { x: 256, y: 256 } },
+ zoomRef: { current: zoom },
+ rotationRef: { current: 0 },
+ flipXRef: { current: false },
+ flipYRef: { current: false },
+ dimensionsRef: { current: dims },
+ layersRef: { current: [bgLayer] },
+ activeLayerIdRef: { current: 'layer-bg' },
+ activeLayerLockedRef: { current: false },
+ activeLayerVisibleRef: { current: true },
+ colorModeRef: { current: 'color' },
+ isMaskModeRef: { current: false },
+ getActiveMaskCanvas: () => null,
+ effectiveDraftCanvasRef: { current: draftCanvas },
+ activeTileGridRef: { current: grid },
+ selectionRef: { current: null },
+ rulerRef: { current: null },
+ straightRulerRef: { current: null },
+ lastStrokeEndRef: { current: null },
+ onActiveConstraintAxisChangeRef: { current: undefined },
+ onCollabStrokeStartRef: { current: undefined },
+ onCollabStrokeChunkRef: { current: undefined },
+ onCollabStrokeFinishRef: { current: undefined },
+ onCollabCursorMoveRef: { current: undefined },
+ onUpdateMaskThumbnailRef: { current: undefined },
+ enqueueHistoryTask: () => {},
+ pushHistoryStep: () => {},
+ flushPendingHistoryTasks: () => {},
+ onUpdateLayerThumbnail: () => {},
+ };
+
+ const helpers: any = {
+ getTool: () => 'brush',
+ getBrushSettings: () => oilPastelBs,
+ getPredictedCanvas: () => getPredictedCanvasElement(undefined),
+ clearPredictedCanvas: () => clearPredictedCanvasSurface(state, () => null),
+ emitConstraintAxisChange: (a: any) =>
+ emitConstraintAxisChangeIfNeeded(state, params.onActiveConstraintAxisChangeRef, a),
+ markTouchedTiles: (x0: number, y0: number, x1: number, y1: number) =>
+ markTouchedTilesInRect(dims, state.touchedTiles, x0, y0, x1, y1),
+ getViewportRect: () => getViewportRectCached(state, params.viewportRef),
+ dispatchPointerStat: () => {},
+ abortActiveStroke: () =>
+ abortActiveStrokeSession(
+ params,
+ state,
+ helpers.clearPredictedCanvas,
+ helpers.emitConstraintAxisChange
+ ),
+ getCanvasPoint: (e: any) =>
+ computeCanvasPoint(e, params, helpers.getViewportRect, helpers.getBrushSettings),
+ resolveEffectiveOpacitySensor: resolveEffectiveOpacitySensorValue,
+ resolveLiveAntiAlias: resolveLiveAntiAliasValue,
+ buildTouchedTileSpans: (sx: number, sy: number, dw: number, dh: number) =>
+ buildTouchedTileSpansFromSet(state.touchedTiles, sx, sy, dw, dh),
+ buildLiveBrushOptions: (...a: any[]) => (createLiveBrushOptions as any)(state, ...a),
+ resolveStrokeColor: (...a: any[]) => (resolveStrokeColorValue as any)(false, ...a),
+ emitLiveSegment: (...a: any[]) => (emitLiveSegmentToDraft as any)(state, params, helpers, ...a),
+ renderPredictedStroke: () => {},
+ flushPendingPoints: (skip?: any) => runFlushPendingPoints(state, params, helpers, skip),
+ };
+
+ const mkEvt = (dx: number, dy: number, p: number, ts: number) => {
+ const e: any = {
+ pointerId: -2002,
+ pointerType: 'pen',
+ button: 0,
+ buttons: 1,
+ clientX: 256 + (dx - 256) * zoom,
+ clientY: 256 + (dy - 256) * zoom,
+ pressure: p,
+ tiltX: 0,
+ tiltY: 0,
+ twist: 0,
+ timeStamp: ts,
+ shiftKey: false,
+ altKey: false,
+ preventDefault() {},
+ };
+ e.nativeEvent = e;
+ return e;
+ };
+
+ runPointerDown(state, params, helpers, mkEvt(256, 100, 0.25, 100));
+ for (let i = 1; i <= 15; i++) {
+ runPointerMove(state, params, helpers, mkEvt(256, 100 + i * 20, 0.25, 100 + i * 4));
+ if (i % 3 === 0 || i === 15) runFlushPendingPoints(state, params, helpers, false);
+ }
+
+ const ds = draftCanvas.__draftScale ?? 1;
+ const dr = draftCanvas.__draftDocRect ?? { x: 0, y: 0 };
+ const livePxX = Math.round((256 - dr.x) * ds);
+ const livePxY = Math.round((250 - dr.y) * ds);
+ const liveOff = (livePxY * draftCanvas.width + livePxX) * 4;
+ const liveA = draftCanvas.buf[liveOff + 3] / 255;
+ const liveCompositeG = Math.round(draftCanvas.buf[liveOff + 1] * liveA + 255 * (1 - liveA));
+ const liveColorShift = 255 - liveCompositeG;
+
+ // Lift pen -> triggers isolated color-mixing raster commit
+ runPointerUp(state, params, helpers, mkEvt(256, 400, 0, 170));
+
+ const pxOut: [number, number, number, number] = [0, 0, 0, 0];
+ grid.getPixelRGBA('layer-bg', 256, 250, pxOut);
+ const tileColorShift = 255 - pxOut[1];
+
+ // Must remain clearly visible on white (not vanished to 255,255,255!) and match live preview
+ expect(liveColorShift).toBeGreaterThanOrEqual(4);
+ expect(tileColorShift).toBeGreaterThanOrEqual(4);
+ expect(Math.abs(liveColorShift - tileColorShift)).toBeLessThanOrEqual(4);
+
+ // 3. LOD mipmap unbiased alpha rounding: sparse faint alpha (sumA=2 across 2x2) rounds to 1 instead of 0
+ const child = createTileBuffer('layer-lod', 0, 0, 'color-32bit', 0);
+ child.data![0] = 255;
+ child.data![1] = 30;
+ child.data![2] = 0;
+ child.data![3] = 2; // top-left pixel of 2x2 block has alpha=2, other 3 are 0 -> sumA=2
+ const parent = createTileBuffer('layer-lod', 0, 0, 'color-32bit', 1);
+ expect(downsample2x2ToParentTile([child, null, null, null], parent)).toBe(true);
+ expect(parent.data![3]).toBe(1);
+ } finally {
+ (globalThis as any).document = origDoc;
+ (globalThis as any).ImageData = origImgData;
+ (globalThis as any).requestAnimationFrame = origRaf;
+ (globalThis as any).cancelAnimationFrame = origCancelRaf;
+ }
+ });
+
+ it('parses Cross-hatching (for tone scraping).sut with empty CatalogPath via OriginalPath and renders 1:1 cross-hatch without synthetic ellipse distortion on GPU & CPU', async () => {
+ const buildEffector = (
+ flags: number,
+ tMin: number,
+ tiltMaxPct: number,
+ tiltCurve?: [number, number][]
+ ) => {
+ const tBytes = tiltCurve ? 12 + tiltCurve.length * 16 : 0;
+ const buf = new Uint8Array(48 + tBytes);
+ const v = new DataView(buf.buffer);
+ v.setUint32(0, 48, false);
+ v.setUint32(4, 0xf0, false);
+ v.setUint32(8, flags, false);
+ v.setInt32(12, 0, false);
+ v.setInt32(16, tMin, false);
+ v.setInt32(20, 0, false);
+ v.setInt32(24, 0, false);
+ v.setUint32(28, 0, false);
+ v.setUint32(32, 0, false);
+ v.setUint32(36, tBytes, false);
+ v.setUint32(40, tiltMaxPct, false);
+ v.setUint32(44, 0, false);
+ if (tiltCurve) {
+ v.setUint32(48, 12, false);
+ v.setUint32(52, tiltCurve.length, false);
+ v.setUint32(56, 16, false);
+ for (let i = 0; i < tiltCurve.length; i++) {
+ v.setFloat64(60 + i * 16, tiltCurve[i][0], false);
+ v.setFloat64(68 + i * 16, tiltCurve[i][1], false);
+ }
+ }
+ return buf;
+ };
+
+ // Encode UTF-16LE BrushPatternImageArray matching real CSP Paint003 .sut format
+ const origPath = '.:Paint003:7951fc496f-c44a-3ea9-ee5f-d870cf0454:data:material.layer';
+ const utf16Bytes = new Uint8Array(16 + origPath.length * 2);
+ for (let i = 0; i < origPath.length; i++) {
+ const code = origPath.charCodeAt(i);
+ utf16Bytes[16 + i * 2] = code & 0xff;
+ utf16Bytes[16 + i * 2 + 1] = (code >> 8) & 0xff;
+ }
+
+ const tinyPng = new Uint8Array([
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
+ 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
+ 0x00, 0x00, 0x01, 0x2c, 0x00, 0x00, 0x01, 0x2b, // 300x299
+ 0x08, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e,
+ 0x44, 0xae, 0x42, 0x60, 0x82,
+ ]);
+
+ const sizeTiltCurve: [number, number][] = [
+ [0.0, 1.0],
+ [0.2, 1.0],
+ [0.4, 0.5273],
+ [0.4273, 0.0091],
+ [0.6091, 0.0],
+ [1.0, 0.0],
+ ];
+ const intervalTiltCurve: [number, number][] = [
+ [0.0, 1.0],
+ [0.2364, 1.0],
+ [0.4, 0.0],
+ [0.5727, 0.0],
+ [1.0, 0.0],
+ ];
+
+ const extracted: NativeSutExtract = {
+ nodeName: 'Cross-hatching (for tone scraping)',
+ variantId: 343,
+ variantValues: new Map<string, unknown>([
+ ['antialias', 0],
+ ['brushsize', 200.0],
+ ['brushsizeunit', 0],
+ ['brushsizeeffector', buildEffector(0x20, 100, 175, sizeTiltCurve)],
+ ['brushinterval', 31.0],
+ ['brushautointervaltype', 0],
+ ['brushintervaleffector', buildEffector(0x20, 100, 150, intervalTiltCurve)],
+ ['brushflow', 100],
+ ['opacity', 100],
+ ['brushhardness', 100],
+ ['brushthickness', 100],
+ ['brushverticalthicknes', 0],
+ ['brushrotation', 0.0],
+ ['brushrotationeffector', 3], // 0x03 = None
+ ['brushrotationrandomscale', 100],
+ ['brushusepatternimage', 1],
+ ['brushpatternimagearray', utf16Bytes],
+ ['brushinouttype', 0],
+ ['brushusein', 1],
+ ['brushuseout', 1],
+ ]),
+ materials: [
+ {
+ pwId: '1',
+ originalPath: origPath,
+ catalogPath: '', // Real CSP Paint003 MaterialFile leaves CatalogPath empty!
+ fileData: new Uint8Array(0),
+ decodedPng: tinyPng,
+ width: 300,
+ height: 299,
+ expressionColor: 'gray',
+ isPaperTexture: false,
+ hasSubColor: false,
+ decodedFromLayer: false,
+ },
+ ],
+ };
+
+ const brush = await parseSutExtractedData(extracted, 'Cross-hatching (for tone scraping).sut');
+
+ // 1. Material must resolve via OriginalPath with ZERO missing-material warnings
+ expect(brush.importWarnings).toBeUndefined();
+ expect(brush.tipDataUrl).toBeDefined();
+ expect(brush.tipWidth).toBe(300);
+ expect(brush.tipHeight).toBe(299);
+ expect(brush.antiAlias).toBe(0);
+ expect(brush.spacing).toBeCloseTo(0.31, 4);
+ expect(brush.thickness).toBeCloseTo(1.0, 4);
+ expect(brush.angle).toBe(0);
+ expect(brush.angleDynamics).toBe('none');
+ expect(brush.usePressure).toBe(false);
+ expect(brush.useTilt).toBe(true);
+ expect(brush.taper).toBeUndefined();
+
+ // 2. Tilt expansion ceilings (175% size, 150% interval) must decode & evaluate faithfully
+ expect(brush.sizeSensor?.useTilt).toBe(true);
+ expect(brush.sizeSensor?.tiltMin).toBeCloseTo(1.0, 4);
+ expect(brush.sizeSensor?.tiltMax).toBeCloseTo(1.75, 4);
+ expect(brush.intervalSensor?.useTilt).toBe(true);
+ expect(brush.intervalSensor?.tiltMin).toBeCloseTo(1.0, 4);
+ expect(brush.intervalSensor?.tiltMax).toBeCloseTo(1.5, 4);
+
+ // Upright pen (tiltMagnitude=0 -> altitude=1.0 -> curve y=0.0) stays at 1.0x
+ expect(evaluateCspSensor(brush.sizeSensor, 0.5, 0.0, 0, 0.5)).toBeCloseTo(1.0, 4);
+ expect(evaluateCspSensor(brush.intervalSensor, 0.5, 0.0, 0, 0.5)).toBeCloseTo(1.0, 4);
+ // Flat-tilted pen (tiltMagnitude=0.95 -> altitude=0.05 -> curve y=1.0) expands to 1.75x / 1.5x
+ expect(evaluateCspSensor(brush.sizeSensor, 0.5, 0.95, 0, 0.5)).toBeCloseTo(1.75, 3);
+ expect(evaluateCspSensor(brush.intervalSensor, 0.5, 0.95, 0, 0.5)).toBeCloseTo(1.5, 3);
+
+ // 3. Build a cross-hatching tip canvas (criss-cross lines, NOT a solid ellipse)
+ const hatchTip = createSoftwareCanvas(64, 64);
+ for (let y = 0; y < 64; y++) {
+ for (let x = 0; x < 64; x++) {
+ const onVertical = x >= 22 && x <= 42 && (x % 4 === 0);
+ const onHorizontal = y >= 22 && y <= 42 && (y % 4 === 0);
+ if (onVertical || onHorizontal) {
+ const i = (y * 64 + x) * 4;
+ hatchTip.buf[i] = 255;
+ hatchTip.buf[i + 1] = 255;
+ hatchTip.buf[i + 2] = 255;
+ hatchTip.buf[i + 3] = 255;
+ }
+ }
+ }
+
+ const commonOpts = {
+ size: 60,
+ minSizeFactor: 1.0,
+ flow: 1.0,
+ spacing: brush.spacing,
+ hardness: 1.0,
+ thickness: brush.thickness,
+ thicknessVertical: brush.thicknessVertical,
+ angle: brush.angle,
+ angleDynamics: brush.angleDynamics,
+ antiAlias: 0,
+ usePressure: false,
+ useTilt: brush.useTilt,
+ sizeSensor: brush.sizeSensor,
+ intervalSensor: brush.intervalSensor,
+ tipImage: hatchTip as unknown as HTMLImageElement,
+ useGpu: false,
+ };
+
+ // 4. GPU dab batch parity under typical 35° stylus tilt:
+ // MUST stay 1:1 square (no 3:1 horizontal ellipse squishing!), angle=0, alpha=1.0
+ const gpuDotNormalTilt: GpuDab[] = [];
+ const surfDummy = createSoftwareCanvas(200, 200);
+ drawBrushDot(
+ surfDummy.ctx,
+ { x: 100, y: 100, pressure: 0.7, width: 60, tiltX: 30, tiltY: 18 },
+ '#000000',
+ commonOpts,
+ gpuDotNormalTilt
+ );
+ expect(gpuDotNormalTilt.length).toBe(1);
+ expect(gpuDotNormalTilt[0].width).toBeCloseTo(gpuDotNormalTilt[0].height, 2);
+ expect(gpuDotNormalTilt[0].width).toBeGreaterThanOrEqual(59.5);
+ expect(gpuDotNormalTilt[0].width).toBeLessThan(70);
+ expect(Math.abs(gpuDotNormalTilt[0].angle)).toBeLessThan(1e-4);
+ expect(gpuDotNormalTilt[0].alpha).toBeCloseTo(1.0, 4);
+
+ // Heavy 75° tilt expands size toward 1.75x uniformly while STILL preserving 1:1 aspect ratio & angle=0
+ const gpuDotHeavyTilt: GpuDab[] = [];
+ drawBrushDot(
+ surfDummy.ctx,
+ { x: 100, y: 100, pressure: 0.7, width: 60, tiltX: 75, tiltY: 0 },
+ '#000000',
+ commonOpts,
+ gpuDotHeavyTilt
+ );
+ expect(gpuDotHeavyTilt.length).toBe(1);
+ expect(gpuDotHeavyTilt[0].width).toBeCloseTo(gpuDotHeavyTilt[0].height, 2);
+ expect(gpuDotHeavyTilt[0].width).toBeCloseTo(60 * 1.75, 0);
+ expect(Math.abs(gpuDotHeavyTilt[0].angle)).toBeLessThan(1e-4);
+
+ // 5. GPU vs CPU vertical stroke parity under 35° stylus tilt
+ const strokePts: Point[] = [
+ { x: 100, y: 30, pressure: 0.8, width: 60, tiltX: 30, tiltY: 18 },
+ { x: 100, y: 70, pressure: 0.8, width: 60, tiltX: 30, tiltY: 18 },
+ { x: 100, y: 110, pressure: 0.8, width: 60, tiltX: 30, tiltY: 18 },
+ { x: 100, y: 150, pressure: 0.8, width: 60, tiltX: 30, tiltY: 18 },
+ ];
+ const gpuStrokeDabs: GpuDab[] = [];
+ drawBrushCubicBezierSegment(
+ surfDummy.ctx,
+ strokePts[0],
+ strokePts[1],
+ strokePts[2],
+ strokePts[3],
+ '#000000',
+ commonOpts,
+ 0,
+ { count: 0 },
+ gpuStrokeDabs
+ );
+ expect(gpuStrokeDabs.length).toBeGreaterThanOrEqual(4);
+ for (const d of gpuStrokeDabs) {
+ expect(d.width).toBeCloseTo(d.height, 2);
+ expect(Math.abs(d.angle)).toBeLessThan(1e-4);
+ expect(d.alpha).toBeCloseTo(1.0, 4);
+ }
+
+ // CPU single dot must render a square hatched bounding box (aspect ratio ~1:1, NOT ~3:1 ellipse)
+ const cpuDotSurf = createSoftwareCanvas(160, 160);
+ drawBrushDot(
+ cpuDotSurf.ctx,
+ { x: 80, y: 80, pressure: 0.8, width: 60, tiltX: 30, tiltY: 18 },
+ '#000000',
+ commonOpts
+ );
+ let minX = 160, maxX = -1, minY = 160, maxY = -1, lit = 0;
+ for (let y = 0; y < 160; y++) {
+ for (let x = 0; x < 160; x++) {
+ if (cpuDotSurf.buf[(y * 160 + x) * 4 + 3] > 20) {
+ lit++;
+ if (x < minX) minX = x;
+ if (x > maxX) maxX = x;
+ if (y < minY) minY = y;
+ if (y > maxY) maxY = y;
+ }
+ }
+ }
+ const bboxW = maxX - minX + 1;
+ const bboxH = maxY - minY + 1;
+ expect(bboxW).toBeGreaterThan(40);
+ expect(bboxH).toBeGreaterThan(40);
+ expect(Math.abs(bboxW - bboxH)).toBeLessThanOrEqual(4);
+ // Hatched pattern has transparent gaps inside its bounding box (unlike a solid filled ellipse!)
+ expect(lit).toBeLessThan(bboxW * bboxH * 0.7);
+ });
+
+ it('calibrates Chalk.sut: TextureDensityEffector (CPU+GPU), linear spherical tilt altitude, pen-direction azimuth, C2F paper thumbnail scale, porous tip box-filtering, and 1:1 live-vs-commit parity', async () => {
+ const buildEffectorBlob = (cfg: {
+ flags: number;
+ pressureMin?: number;
+ tiltMin?: number;
+ tiltMax?: number;
+ velocityMin?: number;
+ randomMin?: number;
+ pressureCurve?: [number, number][];
+ tiltCurve?: [number, number][];
+ velocityCurve?: [number, number][];
+ }): Uint8Array => {
+ const encodeCurve = (pts?: [number, number][]): Uint8Array => {
+ if (!pts || pts.length === 0) return new Uint8Array(0);
+ const out = new Uint8Array(12 + pts.length * 16);
+ const dv = new DataView(out.buffer);
+ dv.setUint32(0, 12, false);
+ dv.setUint32(4, pts.length, false);
+ dv.setUint32(8, 16, false);
+ let off = 12;
+ for (const [x, y] of pts) {
+ dv.setFloat64(off, x, false);
+ dv.setFloat64(off + 8, y, false);
+ off += 16;
+ }
+ return out;
+ };
+ const pBytes = encodeCurve(cfg.pressureCurve);
+ const tBytes = encodeCurve(cfg.tiltCurve);
+ const vBytes = encodeCurve(cfg.velocityCurve);
+ const total = 48 + pBytes.length + tBytes.length + vBytes.length;
+ const buf = new Uint8Array(total);
+ const dv = new DataView(buf.buffer);
+ dv.setUint32(0, 48, false);
+ dv.setUint32(4, 0xf0, false);
+ dv.setUint32(8, cfg.flags, false);
+ dv.setInt32(12, cfg.pressureMin ?? 0, false);
+ dv.setInt32(16, cfg.tiltMin ?? 0, false);
+ dv.setInt32(20, cfg.velocityMin ?? 0, false);
+ dv.setInt32(24, cfg.randomMin ?? 0, false);
+ dv.setUint32(32, pBytes.length, false);
+ dv.setUint32(36, tBytes.length, false);
+ dv.setUint32(40, cfg.tiltMax ?? 100, false);
+ dv.setUint32(44, vBytes.length, false);
+ let cursor = 48;
+ buf.set(pBytes, cursor);
+ cursor += pBytes.length;
+ buf.set(tBytes, cursor);
+ cursor += tBytes.length;
+ buf.set(vBytes, cursor);
+ return buf;
+ };
+
+ const buildTarArchive = (files: Array<{ name: string; data: Uint8Array }>): Uint8Array => {
+ const blocks: Uint8Array[] = [];
+ for (const f of files) {
+ const header = new Uint8Array(512);
+ const nameBytes = new TextEncoder().encode(f.name);
+ header.set(nameBytes.subarray(0, 100), 0);
+ const sizeOct = f.data.length.toString(8).padStart(11, '0') + '\0';
+ header.set(new TextEncoder().encode(sizeOct), 124);
+ blocks.push(header);
+ const paddedLen = Math.ceil(f.data.length / 512) * 512;
+ const body = new Uint8Array(paddedLen);
+ body.set(f.data, 0);
+ blocks.push(body);
+ }
+ blocks.push(new Uint8Array(1024));
+ const total = blocks.reduce((acc, b) => acc + b.length, 0);
+ const out = new Uint8Array(total);
+ let pos = 0;
+ for (const b of blocks) {
+ out.set(b, pos);
+ pos += b.length;
+ }
+ return out;
+ };
+
+ // 1. Build exact Chalk.sut VariantID=731 effectors & C2F paper-texture thumbnail TAR
+ const sizeEff = buildEffectorBlob({
+ flags: 0x30,
+ pressureMin: 50,
+ tiltMin: 100,
+ tiltMax: 350,
+ pressureCurve: [
+ [0, 0],
+ [0.1364, 0.6909],
+ [0.75, 1],
+ [1, 1],
+ ],
+ tiltCurve: [
+ [0, 1],
+ [0.2325, 0.864],
+ [0.2895, 0.4561],
+ [0.5175, 0.0833],
+ [0.7632, 0],
+ [1, 0],
+ ],
+ });
+ const flowEff = buildEffectorBlob({
+ flags: 0x30,
+ pressureMin: 50,
+ tiltMin: 0,
+ tiltMax: 300,
+ pressureCurve: [
+ [0, 0],
+ [0.6, 0],
+ [0.693, 1],
+ [0.8772, 1],
+ [1, 1],
+ ],
+ tiltCurve: [
+ [0, 0],
+ [0.2061, 0.1623],
+ [0.6273, 0.5636],
+ [0.7585, 0.7727],
+ [0.7675, 0.9868],
+ [0.7719, 1],
+ [1, 1],
+ ],
+ });
+ const thickEff = buildEffectorBlob({
+ flags: 0x10,
+ pressureMin: 70,
+ pressureCurve: [
+ [0, 0],
+ [1, 1],
+ ],
+ });
+ const texDensityEff = buildEffectorBlob({
+ flags: 0xb0,
+ pressureMin: 30,
+ tiltMin: 100,
+ tiltMax: 350,
+ randomMin: 40,
+ pressureCurve: [
+ [0, 1],
+ [1, 0],
+ ],
+ tiltCurve: [
+ [0, 1],
+ [1, 0],
+ ],
+ });
+
+ // Synthetic 300x300 thumbnail PNG header + large encrypted C2F data/material_0.layer (~14x thumb bytes)
+ const makePngStub = (w: number, h: number, payloadBytes: number): Uint8Array => {
+ const buf = new Uint8Array(Math.max(45, payloadBytes));
+ buf.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], 0);
+ const dv = new DataView(buf.buffer);
+ dv.setUint32(8, 13, false);
+ buf.set([0x49, 0x48, 0x44, 0x52], 12); // IHDR
+ dv.setUint32(16, w, false);
+ dv.setUint32(20, h, false);
+ buf[24] = 8;
+ buf[25] = 6;
+ // Place IEND at the very end
+ const iend = buf.length - 12;
+ dv.setUint32(iend, 0, false);
+ buf.set([0x49, 0x45, 0x4e, 0x44], iend + 4);
+ return buf;
+ };
+
+ const paperThumb = makePngStub(300, 300, 4096);
+ const fakeC2fLayer = new Uint8Array(4096 * 14);
+ fakeC2fLayer.set([0x89, 0x43, 0x32, 0x46, 0x0d, 0x0a, 0x1a, 0x0a], 0);
+ const paperXml = new TextEncoder().encode(
+ '<infolist><info><datalist key="systemtag"><data>PaperTexture</data></datalist></info></infolist>'
+ );
+ const paperTar = buildTarArchive([
+ { name: 'thumbnail/thumbnail.png', data: paperThumb },
+ { name: 'data/material_0.layer', data: fakeC2fLayer },
+ { name: 'icedata/layerData.xml', data: paperXml },
+ ]);
+
+ const tipThumb = makePngStub(126, 125, 1024);
+ const tipXml = new TextEncoder().encode(
+ '<infolist><info><datalist key="systemtag"><data>BrushPattern</data></datalist></info></infolist>'
+ );
+ const tipTar = buildTarArchive([
+ { name: 'thumbnail/thumbnail.png', data: tipThumb },
+ { name: 'icedata/layerData.xml', data: tipXml },
+ ]);
+
+ const texRefBlob = new TextEncoder().encode('.:Paint003:ad7fdd790c-fe42-c8ba-764e-c82c927efc:data');
+ const patRefBlob = new TextEncoder().encode('.:Paint003:e445940a71-e74e-8b94-f05d-5fb23e6f53:data');
+
+ const variantValues = new Map<string, unknown>([
+ ['brushsize', 52.1],
+ ['brushsizeunit', 0],
+ ['brushthickness', 50],
+ ['brushverticalthicknes', 0],
+ ['brushhardness', 81],
+ ['antialias', 1],
+ ['brushinterval', 10.0],
+ ['brushautointervaltype', 1],
+ ['brushflow', 100],
+ ['brushadjustflowbyinterval', 0],
+ ['opacity', 100],
+ ['brushpatternreversehorizontal', 2],
+ ['brushpatternreversevertical', 0],
+ ['brushrotation', 0],
+ ['brushrotationeffector', 19],
+ ['brushusepatternimage', 1],
+ ['brushpatternimagearray', patRefBlob],
+ ['brushsizeeffector', sizeEff],
+ ['brushfloweffector', flowEff],
+ ['brushthicknesseffector', thickEff],
+ ['texturedensityeffector', texDensityEff],
+ ['brushusewatercolor', 1],
+ ['brushusewatercolor2', 1],
+ ['brushwatercolor', 0],
+ ['brushcolormixingmode', 1],
+ ['brushmixcolor', 70],
+ ['brushmixalpha', 100],
+ ['brushmixcolorextension', 10],
+ ['textureimage', texRefBlob],
+ ['texturecompositemode', 2],
+ ['texturedensity', 80],
+ ['textureforplot', 1],
+ ['texturescale2', 20.0],
+ ['texturerotate', 90.0],
+ ]);
+
+ const extract: NativeSutExtract = {
+ nodeName: 'Chalk',
+ variantId: 731,
+ variantValues,
+ materials: [
+ {
+ pwId: '1',
+ originalPath: '.:Paint003:ad7fdd790c-fe42-c8ba-764e-c82c927efc:data:material_0.layer',
+ catalogPath: '',
+ fileData: paperTar,
+ decodedFromLayer: false,
+ isPaperTexture: true,
+ },
+ {
+ pwId: '2',
+ originalPath: '.:Paint003:e445940a71-e74e-8b94-f05d-5fb23e6f53:data:material_0.layer',
+ catalogPath: '',
+ fileData: tipTar,
+ decodedFromLayer: false,
+ isPaperTexture: false,
+ },
+ ],
+ };
+
+ const brush = await parseSutExtractedData(extract, 'Chalk.sut');
+ expect(brush.size).toBeCloseTo(52.1, 2);
+ expect(brush.spacing).toBeCloseTo(0.04, 4);
+ expect(brush.thickness).toBeCloseTo(0.5, 4);
+ expect(brush.thicknessVertical).toBe(true);
+ expect(brush.flipH).toBe('alternate');
+ expect(brush.angleDynamics).toBe('tilt');
+ expect(brush.colorMixing).toBe(true);
+ expect(brush.perceptualMixing).toBe(true);
+ expect(brush.amountOfPaint).toBeCloseTo(0.7, 4);
+ expect(brush.densityOfPaint).toBeCloseTo(1.0, 4);
+ expect(brush.colorStretch).toBeCloseTo(0.1, 4);
+ expect(brush.paperTextureMode).toBe('subtract');
+ expect(brush.textureDensity).toBeCloseTo(0.8, 4);
+ expect(brush.paperTextureApplyEachPlot).toBe(true);
+
+ // Effector tilt ceilings & TextureDensityEffector inverted pressure curve must survive parsing
+ expect(brush.sizeSensor?.tiltMax).toBeCloseTo(3.5, 3);
+ expect(brush.densitySensor?.tiltMax).toBeCloseTo(3.0, 3);
+ expect(brush.textureDensitySensor?.usePressure).toBe(true);
+ expect(brush.textureDensitySensor?.useTilt).toBe(true);
+ expect(brush.textureDensitySensor?.useRandom).toBe(true);
+ expect(brush.textureDensitySensor?.tiltMax).toBeCloseTo(3.5, 3);
+
+ // C2F paper texture thumbnail fallback compensates TextureScale2=20% by sqrt(layerBytes/thumbBytes) (~3.74x -> ~0.75)
+ expect(brush.paperTextureScale).toBeGreaterThan(0.6);
+ expect(brush.paperTextureScale).toBeLessThan(0.95);
+
+ // 2. Linear spherical tilt altitude: normal 35° pen tilt must NOT blow up width or collapse flow
+ expect(computeCspTiltMagnitude(0, 0)).toBe(0);
+ expect(computeCspTiltMagnitude(45, 0)).toBeCloseTo(0.5, 4);
+ expect(computeCspTiltMagnitude(30, 18)).toBeCloseTo(33.53 / 90, 2);
+
+ // 3. GPU dab parity: TextureDensityEffector lowers per-dab grainDensity at heavy pressure,
+ // pen-direction tilt azimuth uses atan2(tiltX, -tiltY), and tiltScale=1.0 never inflates CSP tilt brushes
+ const dummySurf = createSoftwareCanvas(200, 200);
+ const gpuCommonOpts = {
+ size: brush.size,
+ minSizeFactor: brush.minSizeFactor,
+ flow: brush.flow,
+ spacing: brush.spacing,
+ hardness: brush.hardness,
+ thickness: brush.thickness,
+ thicknessVertical: brush.thicknessVertical,
+ thicknessSensor: brush.thicknessSensor,
+ angle: 0,
+ angleDynamics: brush.angleDynamics,
+ usePressure: true,
+ useTilt: true,
+ tiltScale: 1.0, // simulate NEUTRAL_BRUSH_DEFAULTS leakage; must NOT trigger synthetic side-shading!
+ sizeSensor: brush.sizeSensor,
+ densitySensor: brush.densitySensor,
+ textureDensitySensor: brush.textureDensitySensor,
+ grain: brush.textureDensity,
+ textureDensity: brush.textureDensity,
+ paperTextureMode: brush.paperTextureMode,
+ paperTextureApplyEachPlot: brush.paperTextureApplyEachPlot,
+ colorMixing: false,
+ useGpu: true,
+ };
+
+ const lightGpuDabs: GpuDab[] = [];
+ drawBrushDot(
+ dummySurf.ctx,
+ { x: 100, y: 100, pressure: 0.15, width: 45, tiltX: 28, tiltY: 12 },
+ '#e82c20',
+ gpuCommonOpts,
+ lightGpuDabs
+ );
+ const heavyGpuDabs: GpuDab[] = [];
+ drawBrushDot(
+ dummySurf.ctx,
+ { x: 100, y: 100, pressure: 0.95, width: 52.1, tiltX: 28, tiltY: 12 },
+ '#e82c20',
+ gpuCommonOpts,
+ heavyGpuDabs
+ );
+ expect(lightGpuDabs.length).toBe(1);
+ expect(heavyGpuDabs.length).toBe(1);
+ // CSP pen-direction azimuth: atan2(28, -12) ≈ +1.976 rad (NOT atan2(12, 28) ≈ +0.405 rad)
+ expect(heavyGpuDabs[0].angle).toBeCloseTo(Math.atan2(28, -12), 3);
+ // Width at 30° normal tilt stays near nominal 52px (no 2x+ sin-curve or synthetic tiltScale blowup!)
+ expect(heavyGpuDabs[0].height).toBeGreaterThan(48);
+ expect(heavyGpuDabs[0].height).toBeLessThan(65);
+ expect(heavyGpuDabs[0].width).toBeCloseTo(heavyGpuDabs[0].height * 0.5 * (0.7 + 0.3 * 0.95), 2);
+ // Full flow preserved at normal 30° tilt thanks to BrushFlowEffector tiltMax=3.0 + linear altitude
+ expect(heavyGpuDabs[0].alpha).toBeGreaterThan(0.95);
+ // Inverted TextureDensityEffector: light pressure keeps high grainDensity, heavy pressure drops grainDensity sharply
+ expect(lightGpuDabs[0].grainDensity).toBeDefined();
+ expect(heavyGpuDabs[0].grainDensity).toBeDefined();
+ expect(lightGpuDabs[0].grainDensity!).toBeGreaterThan(heavyGpuDabs[0].grainDensity! * 1.8);
+
+ // 4. CPU SpatialTipMixer porous tip + subtract paper grain + live-vs-commit 1:1 draft parity
+ // Build a deterministic 22%-porous 126x125 sponge tip & 128x128 black-on-transparent paper grain
+ const porousTip = createSoftwareCanvas(126, 125);
+ for (let y = 0; y < 125; y++) {
+ for (let x = 0; x < 126; x++) {
+ const nx = (x - 63) / 62;
+ const ny = (y - 62.5) / 62;
+ if (nx * nx + ny * ny > 1.08) continue;
+ const h = ((Math.imul(x + 7, 73856093) ^ Math.imul(y + 13, 19349663)) >>> 0) % 100;
+ if (h < 23) {
+ const o = (y * 126 + x) << 2;
+ porousTip.buf[o] = 255;
+ porousTip.buf[o + 1] = 255;
+ porousTip.buf[o + 2] = 255;
+ porousTip.buf[o + 3] = 255;
+ }
+ }
+ }
+ const paperTex = createSoftwareCanvas(128, 128);
+ for (let y = 0; y < 128; y++) {
+ for (let x = 0; x < 128; x++) {
+ // Multi-scale paper tooth with dark valleys (alpha ~0.85) and bright peaks (alpha ~0.35)
+ const v =
+ 0.5 +
+ 0.28 * Math.sin(x * 0.45 + Math.cos(y * 0.35)) +
+ 0.22 * Math.cos(y * 0.52 - x * 0.25);
+ const a = Math.max(0, Math.min(255, Math.round((1 - Math.max(0, Math.min(1, v))) * 220)));
+ const o = (y * 128 + x) << 2;
+ paperTex.buf[o] = 0;
+ paperTex.buf[o + 1] = 0;
+ paperTex.buf[o + 2] = 0;
+ paperTex.buf[o + 3] = a;
+ }
+ }
+
+ const origDoc = (globalThis as any).document;
+ const origRaf = (globalThis as any).requestAnimationFrame;
+ const origCancelRaf = (globalThis as any).cancelAnimationFrame;
+ (globalThis as any).requestAnimationFrame = () => 1;
+ (globalThis as any).cancelAnimationFrame = () => {};
+ (globalThis as any).document = {
+ createElement: (tag: string) => {
+ if (tag === 'canvas') {
+ return createSoftwareCanvas(1, 1);
+ }
+ return {};
+ },
+ };
+ try {
+ const chalkSettings: BrushSettings = {
+ size: brush.size,
+ minSizeFactor: brush.minSizeFactor,
+ color: '#e82c20',
+ opacity: 1.0,
+ flow: brush.flow,
+ spacing: brush.spacing,
+ hardness: brush.hardness,
+ thickness: brush.thickness,
+ thicknessVertical: brush.thicknessVertical,
+ thicknessSensor: brush.thicknessSensor,
+ flipH: brush.flipH,
+ flipV: brush.flipV,
+ customTipAngle: 0,
+ customTipAngleDynamics: brush.angleDynamics,
+ customTipImage: porousTip as unknown as HTMLImageElement,
+ antiAlias: 1,
+ usePressure: true,
+ useTilt: true,
+ tiltScale: 1.0,
+ smoothing: true,
+ stabilization: 0,
+ pressureCurve: brush.pressureCurve,
+ sizeSensor: brush.sizeSensor,
+ densitySensor: brush.densitySensor,
+ textureDensitySensor: brush.textureDensitySensor,
+ colorMixing: true,
+ perceptualMixing: true,
+ amountOfPaint: brush.amountOfPaint,
+ densityOfPaint: brush.densityOfPaint,
+ colorStretch: brush.colorStretch,
+ mixingMode: 'blend',
+ grain: brush.textureDensity,
+ textureDensity: brush.textureDensity,
+ paperTextureImage: paperTex as unknown as HTMLImageElement,
+ paperTextureScale: brush.paperTextureScale,
+ paperTextureRotate: brush.paperTextureRotate,
+ paperTextureMode: 'subtract',
+ paperTextureApplyEachPlot: true,
+ useGpu: false,
+ };
+
+ const renderStrokeStats = (pressure: number) => {
+ const s = createSoftwareCanvas(220, 260);
+ const pts: Point[] = Array.from({ length: 16 }, (_, i) => ({
+ x: 110,
+ y: 40 + i * 12,
+ pressure,
+ width: brush.size * (0.5 + 0.5 * pressure),
+ tiltX: 28,
+ tiltY: 12,
+ twist: 0,
+ timestamp: i * 10,
+ }));
+ renderCompleteStroke(s.ctx, pts, chalkSettings, 'brush');
+ let sumA = 0, maxA = 0, litCnt = 0;
+ for (let y = 80; y <= 180; y++) {
+ for (let x = 70; x <= 150; x++) {
+ const a = s.buf[(y * 220 + x) * 4 + 3];
+ if (a > 10) {
+ sumA += a;
+ if (a > maxA) maxA = a;
+ litCnt++;
+ }
+ }
+ }
+ return { meanA: litCnt > 0 ? sumA / litCnt : 0, maxA, litCnt };
+ };
+
+ const lightStats = renderStrokeStats(0.2);
+ const heavyStats = renderStrokeStats(0.95);
+ // Heavy pressure produces rich solid opaque red chalk core; light pressure stays airy & grainy
+ expect(heavyStats.maxA).toBeGreaterThan(220);
+ expect(heavyStats.meanA).toBeGreaterThan(145);
+ expect(lightStats.meanA).toBeGreaterThan(15);
+ expect(heavyStats.meanA).toBeGreaterThan(lightStats.meanA * 1.45);
+
+ // Live drawing on a zoomed-out 1600x1200 canvas (zoom=0.4) must keep 1:1 draftScale for
+ // colorMixing/customTipImage brushes so live canvas == committed tiles with ZERO pointer-up pop!
+ const dims = { width: 1600, height: 1200 };
+ const grid = new SparseTileGrid();
+ const layerId = 'chalk-live-layer';
+ const layers: LayerItem[] = [
+ {
+ id: layerId,
+ name: 'Layer 1',
+ type: 'raster',
+ parentId: null,
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ alphaLocked: false,
+ },
+ ];
+ const draftCanvas = createSoftwareCanvas(1600, 1200) as any;
+ const state = createInitialStrokeSessionState();
+ const params: any = {
+ disabled: false,
+ activeSessionId: 'chalk-live-test',
+ viewportRef: { current: { getBoundingClientRect: () => ({ left: 0, top: 0, width: 640, height: 480, right: 640, bottom: 480 }) } },
+ interactionRef: { current: null },
+ isDrawingRef: { current: false },
+ panRef: { current: { x: 0, y: 0 } },
+ zoomRef: { current: 0.4 },
+ rotationRef: { current: 0 },
+ flipXRef: { current: false },
+ flipYRef: { current: false },
+ toolOverrideRef: { current: 'brush' },
+ brushSettingsOverrideRef: { current: chalkSettings },
+ dimensionsRef: { current: dims },
+ colorModeRef: { current: 'color' },
+ activeLayerIdRef: { current: layerId },
+ activeLayerLockedRef: { current: false },
+ activeLayerVisibleRef: { current: true },
+ layersRef: { current: layers },
+ isMaskModeRef: { current: false },
+ selectionRef: { current: null },
+ effectiveDraftCanvasRef: { current: draftCanvas },
+ predictedCanvasRef: { current: null },
+ activeTileGridRef: { current: grid },
+ lastStrokeEndRef: { current: null },
+ rulerRef: { current: null },
+ straightRulerRef: { current: null },
+ getActiveMaskCanvas: () => null,
+ flushPendingHistoryTasks: () => {},
+ enqueueHistoryTask: () => {},
+ pushHistoryStep: () => {},
+ onUpdateLayerThumbnail: () => {},
+ onUpdateMaskThumbnailRef: { current: null },
+ onCollabStrokeStartRef: { current: null },
+ onCollabStrokeChunkRef: { current: null },
+ onCollabStrokeFinishRef: { current: null },
+ onCollabCursorMoveRef: { current: null },
+ onActiveConstraintAxisChangeRef: { current: undefined },
+ };
+
+ const helpers: any = {
+ getTool: () => 'brush',
+ getBrushSettings: () => chalkSettings,
+ getPredictedCanvas: () => getPredictedCanvasElement(params.predictedCanvasRef),
+ clearPredictedCanvas: () => clearPredictedCanvasSurface(state, () => null),
+ emitConstraintAxisChange: (ax: any) => emitConstraintAxisChangeIfNeeded(state, params.onActiveConstraintAxisChangeRef, ax),
+ markTouchedTiles: (x0: number, y0: number, x1: number, y1: number) => markTouchedTilesInRect(dims, state.touchedTiles, x0, y0, x1, y1),
+ getViewportRect: () => getViewportRectCached(state, params.viewportRef),
+ dispatchPointerStat: () => {},
+ abortActiveStroke: () => abortActiveStrokeSession(params, state, () => {}, () => {}),
+ getCanvasPoint: (ev: any) => computeCanvasPoint(ev, params, helpers.getViewportRect, helpers.getBrushSettings),
+ resolveEffectiveOpacitySensor: resolveEffectiveOpacitySensorValue,
+ resolveLiveAntiAlias: resolveLiveAntiAliasValue,
+ buildTouchedTileSpans: (sx: number, sy: number, dw: number, dh: number) => buildTouchedTileSpansFromSet(state.touchedTiles, sx, sy, dw, dh),
+ buildLiveBrushOptions: (...args: any[]) => (createLiveBrushOptions as any)(state, ...args),
+ resolveStrokeColor: (bs: BrushSettings, isE: boolean, isBg: boolean, isM: boolean, m: any) => resolveStrokeColorValue(false, bs, isE, isBg, isM, m),
+ emitLiveSegment: (...args: any[]) => (emitLiveSegmentToDraft as any)(state, params, helpers, ...args),
+ renderPredictedStroke: () => {},
+ flushPendingPoints: (skip?: boolean) => runFlushPendingPoints(state, params, helpers, skip),
+ };
+
+ const mkEv = (clientX: number, clientY: number, pressure: number, ts: number) => {
+ const ev: any = {
+ pointerId: 1,
+ pointerType: 'pen',
+ button: 0,
+ buttons: 1,
+ clientX,
+ clientY,
+ pressure,
+ tiltX: 28,
+ tiltY: 12,
+ twist: 0,
+ timeStamp: ts,
+ shiftKey: false,
+ altKey: false,
+ preventDefault() {},
+ };
+ ev.nativeEvent = ev;
+ return ev;
+ };
+
+ runPointerDown(state, params, helpers, mkEv(200, 140, 0.75, 0));
+ // Must stay 1:1 native scale at zoom=0.4 so porous tip is never bilinearly diluted
+ expect(draftCanvas.__draftScale).toBeCloseTo(1.0, 5);
+
+ for (let i = 1; i <= 10; i++) {
+ const ev = mkEv(200, 140 + i * 10, 0.85, i * 16);
+ runPointerMove(state, params, helpers, ev, [ev]);
+ }
+ runFlushPendingPoints(state, params, helpers, true);
+
+ // Snapshot live draft alpha BEFORE pointerUp
+ let liveAlphaSum = 0;
+ for (let i = 3; i < draftCanvas.buf.length; i += 4) liveAlphaSum += draftCanvas.buf[i];
+ expect(liveAlphaSum).toBeGreaterThan(50000);
+
+ runPointerUp(state, params, helpers, mkEv(200, 240, 0, 180));
+
+ // Compare committed tile alpha against live draft alpha: direct 1:1 commit means zero pop!
+ const committedImg = grid.readImageData(layerId, 0, 0, 1600, 1200);
+ let committedAlphaSum = 0;
+ for (let i = 3; i < committedImg.data.length; i += 4) committedAlphaSum += committedImg.data[i];
+ const ratio = committedAlphaSum / Math.max(1, liveAlphaSum);
+ expect(ratio).toBeGreaterThan(0.95);
+ expect(ratio).toBeLessThan(1.25);
+ } finally {
+ (globalThis as any).document = origDoc;
+ (globalThis as any).requestAnimationFrame = origRaf;
+ (globalThis as any).cancelAnimationFrame = origCancelRaf;
+ }
+ });
});
diff --git a/src/utils/__tests__/undoGhostStrokeRegression.test.tsx b/src/utils/__tests__/undoGhostStrokeRegression.test.tsx
new file mode 100644
index 0000000..49e605f
--- /dev/null
+++ b/src/utils/__tests__/undoGhostStrokeRegression.test.tsx
@@ -0,0 +1,409 @@
+import React, { act } from 'react';
+import { createRoot, Root } from 'react-dom/client';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { SparseTileGrid, TILE_SIZE } from '../tileEngine';
+import { documentStore } from '../documentStore';
+import {
+ useDrawingHistory,
+ UseDrawingHistoryResult,
+} from '../../hooks/drawing/useDrawingHistory';
+import {
+ DraftCanvasElement,
+ LastStrokeEndState,
+} from '../../hooks/drawing/types';
+import {
+ prepareRawDraftCanvasForStrokeTexture,
+ resetAndClearOffscreenDraftCanvas,
+} from '../../hooks/drawing/brushStrokeSession/strokeHelpers';
+import { createInitialStrokeSessionState } from '../../hooks/drawing/brushStrokeSession/types';
+import {
+ NativeTabletBridgeState,
+ processNativeTabletBatch,
+} from '../../hooks/drawing/brushStrokeSession/nativeTabletBridge';
+import type { LayerItem } from '../../types/editor';
+
+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;
+ }
+ getContext() {
+ return null;
+ }
+}
+
+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.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;
+}
+
+function paintPixelAndCaptureDeltas(
+ grid: SparseTileGrid,
+ layerId: string,
+ x: number,
+ y: number,
+ rgba: [number, number, number, number]
+) {
+ const dirty = { x, y, width: 4, height: 4 };
+ const before = grid.snapshotTilesInRect(layerId, dirty);
+ const data = new Uint8ClampedArray(4 * 4 * 4);
+ for (let i = 0; i < data.length; i += 4) {
+ data[i] = rgba[0];
+ data[i + 1] = rgba[1];
+ data[i + 2] = rgba[2];
+ data[i + 3] = rgba[3];
+ }
+ grid.writeImageData(layerId, { data, width: 4, height: 4 }, x, y, 'color-32bit');
+ const deltas = grid.computeDeltasFromSnapshot(before, layerId);
+ return { dirty, deltas };
+}
+
+function readPixel(grid: SparseTileGrid, layerId: string, x: number, y: number): [number, number, number, number] {
+ const tile = grid.getTile(layerId, Math.floor(x / TILE_SIZE), Math.floor(y / TILE_SIZE), 0);
+ if (!tile) return [0, 0, 0, 0];
+ const rgba = grid.getTileAsRGBA(tile);
+ const lx = x % TILE_SIZE;
+ const ly = y % TILE_SIZE;
+ const idx = (ly * TILE_SIZE + lx) * 4;
+ return [rgba[idx], rgba[idx + 1], rgba[idx + 2], rgba[idx + 3]];
+}
+
+describe('Ctrl+Z Ghost Stroke & Rapid-Draw Regression Suite', () => {
+ let root: Root | null = null;
+ let container: any = null;
+
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ const doc = installDomShim();
+ container = doc.createElement('div');
+ doc.body.appendChild(container);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ if (root) {
+ act(() => {
+ root!.unmount();
+ });
+ root = null;
+ }
+ });
+
+ it('applies in-RAM Ctrl+Z undo/redo synchronously, clears lastStrokeEndRef, and handles rapid double Ctrl+Z without dropping presses', () => {
+ const sessionId = `sync-undo-test-${Date.now()}`;
+ const sess = documentStore.getOrCreateSession(sessionId);
+ const grid = sess.tileGrid;
+ const dims = { width: 512, height: 512, dpi: 300 };
+ const layer: LayerItem = {
+ id: 'layer-1',
+ name: 'Sketch',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ };
+
+ const dimsRef = { current: dims };
+ const activeLayerIdRef = { current: 'layer-1' };
+ const colorModeRef = { current: 'color' as const };
+ const layersRef = { current: [layer] as LayerItem[] | undefined };
+ const onUpdateMaskThumbnailRef = { current: undefined };
+ const isDrawingRef = { current: false };
+ const lastStrokeEndRef = {
+ current: { x: 100, y: 100, pressure: 0.5, width: 6, layerId: 'layer-1' } as LastStrokeEndState | null,
+ };
+ const abortActiveStrokeRef = { current: vi.fn() };
+ const onUpdateLayerThumbnail = vi.fn();
+
+ let hookApi: UseDrawingHistoryResult | null = null;
+ const Harness: React.FC = () => {
+ hookApi = useDrawingHistory({
+ activeSessionId: sessionId,
+ tileGrid: grid,
+ activeLayerId: 'layer-1',
+ activeLayerLocked: false,
+ dimensions: dims,
+ dimensionsRef: dimsRef,
+ activeLayerIdRef,
+ colorModeRef,
+ layersRef,
+ onUpdateLayerThumbnail,
+ onUpdateMaskThumbnailRef,
+ isDrawingRef,
+ lastStrokeEndRef,
+ abortActiveStrokeRef,
+ });
+ return null;
+ };
+
+ act(() => {
+ root!.render(<Harness />);
+ });
+ expect(hookApi).not.toBeNull();
+
+ act(() => {
+ const s1 = paintPixelAndCaptureDeltas(grid, 'layer-1', 10, 10, [255, 0, 0, 255]);
+ hookApi!.pushHistoryStep('brush', 'Stroke 1', null, null, 'layer-1', s1.dirty, s1.deltas);
+ const s2 = paintPixelAndCaptureDeltas(grid, 'layer-1', 40, 40, [0, 0, 255, 255]);
+ hookApi!.pushHistoryStep('brush', 'Stroke 2', null, null, 'layer-1', s2.dirty, s2.deltas);
+ });
+
+ expect(readPixel(grid, 'layer-1', 10, 10)).toEqual([255, 0, 0, 255]);
+ expect(readPixel(grid, 'layer-1', 40, 40)).toEqual([0, 0, 255, 255]);
+
+ // Single synchronous undo — MUST take effect immediately without awaiting any microtask!
+ act(() => {
+ hookApi!.undo();
+ expect(readPixel(grid, 'layer-1', 40, 40)).toEqual([0, 0, 0, 0]);
+ expect(readPixel(grid, 'layer-1', 10, 10)).toEqual([255, 0, 0, 255]);
+ expect(lastStrokeEndRef.current).toBeNull();
+ });
+
+ // Redo then rapid double Ctrl+Z in the exact same synchronous tick — neither press may be dropped!
+ act(() => {
+ hookApi!.redo();
+ expect(readPixel(grid, 'layer-1', 40, 40)).toEqual([0, 0, 255, 255]);
+
+ hookApi!.undo();
+ hookApi!.undo();
+ expect(readPixel(grid, 'layer-1', 40, 40)).toEqual([0, 0, 0, 0]);
+ expect(readPixel(grid, 'layer-1', 10, 10)).toEqual([0, 0, 0, 0]);
+ });
+
+ void sess.resetHistory();
+ });
+
+ it('tracks pendingTargetIndex for rapid double Ctrl+Z even when history steps are offloaded to compressed RAM', async () => {
+ const sessionId = `async-undo-test-${Date.now()}`;
+ const sess = documentStore.getOrCreateSession(sessionId);
+ const grid = sess.tileGrid;
+ const dims = { width: 512, height: 512, dpi: 300 };
+ const layer: LayerItem = {
+ id: 'layer-1',
+ name: 'Sketch',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ };
+
+ const dimsRef = { current: dims };
+ const activeLayerIdRef = { current: 'layer-1' };
+ const colorModeRef = { current: 'color' as const };
+ const layersRef = { current: [layer] as LayerItem[] | undefined };
+ const onUpdateMaskThumbnailRef = { current: undefined };
+ const isDrawingRef = { current: false };
+ const lastStrokeEndRef = { current: null as LastStrokeEndState | null };
+ const abortActiveStrokeRef = { current: vi.fn() };
+
+ let hookApi: UseDrawingHistoryResult | null = null;
+ const Harness: React.FC = () => {
+ hookApi = useDrawingHistory({
+ activeSessionId: sessionId,
+ tileGrid: grid,
+ activeLayerId: 'layer-1',
+ activeLayerLocked: false,
+ dimensions: dims,
+ dimensionsRef: dimsRef,
+ activeLayerIdRef,
+ colorModeRef,
+ layersRef,
+ onUpdateLayerThumbnail: vi.fn(),
+ onUpdateMaskThumbnailRef,
+ isDrawingRef,
+ lastStrokeEndRef,
+ abortActiveStrokeRef,
+ });
+ return null;
+ };
+
+ act(() => {
+ root!.render(<Harness />);
+ });
+
+ act(() => {
+ const s1 = paintPixelAndCaptureDeltas(grid, 'layer-1', 10, 10, [10, 20, 30, 255]);
+ hookApi!.pushHistoryStep('brush', 'Stroke 1', null, null, 'layer-1', s1.dirty, s1.deltas);
+ const s2 = paintPixelAndCaptureDeltas(grid, 'layer-1', 50, 50, [40, 50, 60, 255]);
+ hookApi!.pushHistoryStep('brush', 'Stroke 2', null, null, 'layer-1', s2.dirty, s2.deltas);
+ });
+
+ // Force-offload both steps so jumpToHistoryIndex must take the async decompression path
+ await sess.undoCache.offloadAllToDisk(sess.history);
+ expect(sess.history[1].tileDeltas).toBeUndefined();
+ expect(sess.history[2].tileDeltas).toBeUndefined();
+
+ // Fire two Ctrl+Z presses back-to-back before the first async decompression finishes
+ await act(async () => {
+ hookApi!.undo();
+ hookApi!.undo();
+ await new Promise((r) => setTimeout(r, 30));
+ });
+
+ expect(readPixel(grid, 'layer-1', 50, 50)).toEqual([0, 0, 0, 0]);
+ expect(readPixel(grid, 'layer-1', 10, 10)).toEqual([0, 0, 0, 0]);
+
+ void sess.resetHistory();
+ });
+
+ it('keeps save/restore clip stack balanced on rawDraftCanvas across strokes so clearRect is never clipped', () => {
+ const state = createInitialStrokeSessionState();
+ const ops: string[] = [];
+ let saveDepth = 0;
+
+ const mockCtx = {
+ save: () => {
+ saveDepth++;
+ ops.push(`save:${saveDepth}`);
+ },
+ restore: () => {
+ saveDepth = Math.max(0, saveDepth - 1);
+ ops.push(`restore:${saveDepth}`);
+ },
+ resetTransform: () => ops.push('resetTransform'),
+ clearRect: () => ops.push(`clearRect@depth:${saveDepth}`),
+ setTransform: () => ops.push('setTransform'),
+ beginPath: () => {},
+ rect: () => {},
+ clip: () => {},
+ } as unknown as CanvasRenderingContext2D;
+
+ const rawCanvas = {
+ width: 512,
+ height: 512,
+ getContext: () => mockCtx,
+ } as unknown as DraftCanvasElement;
+ state.rawDraftCanvas = rawCanvas;
+
+ const draftCanvas = {
+ width: 512,
+ height: 512,
+ __draftScale: 1,
+ __draftDocRect: { x: 0, y: 0, width: 512, height: 512 },
+ } as unknown as DraftCanvasElement;
+
+ // Stroke 1 start -> clearRect runs at depth 0, then clip saved at depth 1
+ prepareRawDraftCanvasForStrokeTexture(state, draftCanvas, { width: 512, height: 512 }, null);
+ expect(saveDepth).toBe(1);
+ expect(ops).toContain('clearRect@depth:0');
+
+ // Stroke 1 end -> restore runs before clearRect (back to depth 0)
+ ops.length = 0;
+ resetAndClearOffscreenDraftCanvas(state.rawDraftCanvas as DraftCanvasElement);
+ expect(saveDepth).toBe(0);
+ expect(ops).toContain('clearRect@depth:0');
+
+ // Stroke 2 start -> even if pointerUp was bypassed, preparing again restores before clearing
+ prepareRawDraftCanvasForStrokeTexture(state, draftCanvas, { width: 512, height: 512 }, null);
+ ops.length = 0;
+ prepareRawDraftCanvasForStrokeTexture(state, draftCanvas, { width: 512, height: 512 }, null);
+ expect(saveDepth).toBe(1);
+ expect(ops).toContain('clearRect@depth:0');
+ });
+
+ it('resyncs nativeTabletBridge on next phase=1 pen-down after an external Ctrl+Z stroke abort', () => {
+ const bridge: NativeTabletBridgeState = {
+ nativeStrokeActive: true, // Simulates WinTab stroke aborted externally by Ctrl+Z before phase=3 arrived
+ prevToolBeforeEraserFlip: null,
+ };
+ const onPointerDown = vi.fn();
+ const onPointerMove = vi.fn();
+ const onPointerUp = vi.fn();
+ const onHover = vi.fn();
+
+ processNativeTabletBatch(
+ [
+ {
+ clientX: 200,
+ clientY: 200,
+ pressure: 0.4,
+ tiltX: 0,
+ tiltY: 0,
+ twist: 0,
+ buttons: 1,
+ phase: 1,
+ timestamp: 100,
+ backend: 1,
+ },
+ ],
+ bridge,
+ { shift: false, alt: false },
+ {
+ getTool: () => 'brush',
+ selectTool: vi.fn(),
+ isDisabled: () => false,
+ isStrokeActive: () => false, // Session was aborted by Ctrl+Z
+ isPointOverCanvasViewport: () => true,
+ onPointerDown,
+ onPointerMove,
+ onPointerUp,
+ onHover,
+ }
+ );
+
+ expect(onPointerDown).toHaveBeenCalledTimes(1);
+ expect(onPointerMove).toHaveBeenCalledTimes(0);
+ expect(bridge.nativeStrokeActive).toBe(true);
+ });
+});
diff --git a/src/utils/__tests__/webrtcCollab.test.ts b/src/utils/__tests__/webrtcCollab.test.ts
new file mode 100644
index 0000000..45ac148
--- /dev/null
+++ b/src/utils/__tests__/webrtcCollab.test.ts
@@ -0,0 +1,883 @@
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import {
+ CHUNK_HEADER_BYTES,
+ ChunkReassembler,
+ DEFAULT_CHUNK_PAYLOAD_BYTES,
+ ICollabTransport,
+ encodeTransportFrames,
+} from '../../services/collabTransport';
+import {
+ computeRoomTopicHash,
+ decodeMqttPackets,
+ encodeMqttConnect,
+ encodeMqttPublish,
+ encodeMqttSubscribe,
+ generateP2pRoomCredentials,
+ sha256HexSync,
+ validateSignalingMessage,
+ ISignalingClient,
+ SignalingEnvelope,
+} from '../../services/webrtcSignaling';
+import {
+ BINARY_MAGIC_0,
+ BINARY_MAGIC_1,
+ buildP2pShareUrl,
+ multiplayerService,
+ parseCollabTarget,
+ parseInviteUrl,
+} from '../../services/multiplayerService';
+import {
+ DEFAULT_WEBRTC_ICE_SERVERS,
+ WebRtcHostHub,
+ buildIceServers,
+} from '../../services/webrtcHostHub';
+import { WebRtcGuestClient } from '../../services/webrtcGuestClient';
+import type { CollabPeer, MultiplayerMessage } from '../../types/multiplayer';
+import type { TileBuffer } from '../tileEngine';
+
+describe('WebRTC Framing & Chunking (collabTransport.ts)', () => {
+ it('round-trips small text and binary messages in a single frame', () => {
+ const reassembler = new ChunkReassembler();
+
+ const text = JSON.stringify({ type: 'CURSOR_MOVE', peerId: 'p1', x: 120, y: 240 });
+ const textFrames = encodeTransportFrames('text', text, 1);
+ expect(textFrames).toHaveLength(1);
+ expect(textFrames[0].byteLength).toBeGreaterThan(CHUNK_HEADER_BYTES);
+
+ const decodedText = reassembler.pushFrame(textFrames[0]);
+ expect(decodedText).toEqual({ kind: 'text', text });
+
+ // Binary Ink Studio packet ('I', 'N', ...)
+ const binPayload = new Uint8Array([BINARY_MAGIC_0, BINARY_MAGIC_1, 0x01, 0x02, 0x03, 0xfe, 0xff]);
+ const binFrames = encodeTransportFrames('binary', binPayload, 2);
+ expect(binFrames).toHaveLength(1);
+
+ const decodedBin = reassembler.pushFrame(binFrames[0]);
+ expect(decodedBin?.kind).toBe('binary');
+ if (decodedBin?.kind === 'binary') {
+ expect(Array.from(new Uint8Array(decodedBin.data))).toEqual(Array.from(binPayload));
+ }
+ });
+
+ it('splits large multi-MB binary snapshots into 48 KB chunks and reassembles cleanly', () => {
+ const size = 1_250_000; // ~1.25 MB LZ4 canvas snapshot
+ const payload = new Uint8Array(size);
+ payload[0] = BINARY_MAGIC_0; // 'I'
+ payload[1] = BINARY_MAGIC_1; // 'N'
+ for (let i = 2; i < size; i++) {
+ payload[i] = (i * 31 + 7) & 0xff;
+ }
+
+ const frames = encodeTransportFrames('binary', payload, 42);
+ const expectedChunks = Math.ceil(size / DEFAULT_CHUNK_PAYLOAD_BYTES);
+ expect(frames).toHaveLength(expectedChunks);
+ expect(expectedChunks).toBeGreaterThan(20);
+
+ for (const f of frames) {
+ expect(f.byteLength).toBeLessThanOrEqual(CHUNK_HEADER_BYTES + DEFAULT_CHUNK_PAYLOAD_BYTES);
+ }
+
+ const reassembler = new ChunkReassembler();
+ let result = null;
+ for (let i = 0; i < frames.length; i++) {
+ result = reassembler.pushFrame(frames[i]);
+ if (i < frames.length - 1) {
+ expect(result).toBeNull();
+ }
+ }
+
+ expect(result?.kind).toBe('binary');
+ if (result?.kind === 'binary') {
+ const out = new Uint8Array(result.data);
+ expect(out.byteLength).toBe(size);
+ expect(out[0]).toBe(BINARY_MAGIC_0);
+ expect(out[1]).toBe(BINARY_MAGIC_1);
+ expect(out[123456]).toBe(payload[123456]);
+ expect(out[size - 1]).toBe(payload[size - 1]);
+ }
+ expect(reassembler.getPendingCount()).toBe(0);
+ });
+
+ it('handles out-of-order, interleaved messageIds, duplicate chunks, and UTF-8 JSON', () => {
+ const bigJson = JSON.stringify({
+ type: 'DOC_SYNC_RESPONSE',
+ name: 'Ink Studio — 世界',
+ blob: 'あいうえお-'.repeat(4000),
+ });
+ const framesA = encodeTransportFrames('text', bigJson, 100, 1024);
+ const framesB = encodeTransportFrames('text', 'hello-'.repeat(500), 200, 1024);
+ expect(framesA.length).toBeGreaterThan(3);
+ expect(framesB.length).toBeGreaterThan(2);
+
+ const reassembler = new ChunkReassembler();
+ expect(reassembler.pushFrame(framesA[2])).toBeNull();
+ expect(reassembler.pushFrame(framesB[1])).toBeNull();
+ expect(reassembler.pushFrame(framesA[2])).toBeNull(); // duplicate
+ expect(reassembler.pushFrame(framesA[0])).toBeNull();
+
+ let completedB: ReturnType<ChunkReassembler['pushFrame']> = null;
+ for (let i = 0; i < framesB.length; i++) {
+ if (i === 1) continue;
+ completedB = reassembler.pushFrame(framesB[i]);
+ }
+ expect(completedB).toEqual({ kind: 'text', text: 'hello-'.repeat(500) });
+
+ let completedA: ReturnType<ChunkReassembler['pushFrame']> = null;
+ for (let i = 1; i < framesA.length; i++) {
+ if (i === 2) continue;
+ completedA = reassembler.pushFrame(framesA[i]);
+ }
+ expect(completedA).toEqual({ kind: 'text', text: bigJson });
+ expect(reassembler.getPendingCount()).toBe(0);
+ });
+
+ it('rejects malformed headers and prunes expired partial messages', () => {
+ const reassembler = new ChunkReassembler();
+
+ expect(reassembler.pushFrame(new Uint8Array([0x49, 0x43]))).toBeNull();
+ const badMagic = new Uint8Array(CHUNK_HEADER_BYTES + 4);
+ badMagic[0] = 0x00;
+ badMagic[1] = 0x00;
+ expect(reassembler.pushFrame(badMagic)).toBeNull();
+
+ const partialFrames = encodeTransportFrames('text', 'x'.repeat(2500), 99, 1024);
+ expect(partialFrames.length).toBe(3);
+ expect(reassembler.pushFrame(partialFrames[0], 1000)).toBeNull();
+ expect(reassembler.getPendingCount()).toBe(1);
+
+ reassembler.pruneExpired(10_000);
+ expect(reassembler.getPendingCount()).toBe(1);
+
+ reassembler.pruneExpired(40_000);
+ expect(reassembler.getPendingCount()).toBe(0);
+ });
+});
+
+describe('WebRTC Signaling Crypto, Validation & MQTT Codec (webrtcSignaling.ts)', () => {
+ it('computes RFC-compliant SHA-256 hex digests and deterministic room topic hashes', () => {
+ expect(sha256HexSync('')).toBe(
+ 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
+ );
+ expect(sha256HexSync('abc')).toBe(
+ 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'
+ );
+
+ const h1 = computeRoomTopicHash('INK-7429', 'K8P2M9');
+ const h2 = computeRoomTopicHash(' ink-7429 ', 'k8p2m9');
+ const hDiffSecret = computeRoomTopicHash('INK-7429', 'XXXXXX');
+ const hDiffCode = computeRoomTopicHash('INK-7430', 'K8P2M9');
+
+ expect(h1).toHaveLength(64);
+ expect(h1).toBe(h2);
+ expect(h1).not.toBe(hDiffSecret);
+ expect(h1).not.toBe(hDiffCode);
+ });
+
+ it('generates human-friendly INK-XXXX credentials and join codes', () => {
+ const creds = generateP2pRoomCredentials();
+ expect(creds.roomCode).toMatch(/^INK-\d{4}$/);
+ expect(creds.roomSecret).toMatch(/^[A-Z2-9]{6}$/);
+ expect(creds.joinCode).toBe(`${creds.roomCode}-${creds.roomSecret}`);
+ expect(creds.roomHash).toBe(computeRoomTopicHash(creds.roomCode, creds.roomSecret));
+ });
+
+ it('validates signaling envelopes strictly against roomHash and schema constraints', () => {
+ const roomHash = computeRoomTopicHash('INK-7429', 'K8P2M9');
+ const wrongHash = computeRoomTopicHash('INK-7429', 'WRONG1');
+
+ const validOffer = {
+ v: 1,
+ roomHash,
+ mid: 'msg-1',
+ type: 'offer',
+ fromPeerId: 'guest-1',
+ sdp: 'v=0\r\no=- 123 2 IN IP4 127.0.0.1\r\n',
+ ts: Date.now(),
+ };
+ expect(validateSignalingMessage(validOffer, roomHash)).toMatchObject({
+ v: 1,
+ type: 'offer',
+ roomHash,
+ fromPeerId: 'guest-1',
+ sdpType: 'offer',
+ });
+
+ // Cross-room hijack attempt
+ expect(
+ validateSignalingMessage(
+ {
+ v: 1,
+ roomHash: wrongHash,
+ mid: 'msg-2',
+ type: 'offer',
+ fromPeerId: 'attacker',
+ sdp: 'v=0\r\n',
+ ts: Date.now(),
+ },
+ roomHash
+ )
+ ).toBeNull();
+
+ // Oversized SDP rejected
+ expect(
+ validateSignalingMessage(
+ { v: 1, roomHash, mid: 'm6', type: 'offer', fromPeerId: 'g1', sdp: 'a'.repeat(70_000), ts: 1 },
+ roomHash
+ )
+ ).toBeNull();
+
+ // Unknown message type rejected
+ expect(
+ validateSignalingMessage(
+ { v: 1, roomHash, mid: 'm5', type: 'eval', fromPeerId: 'g1', ts: 1 },
+ roomHash
+ )
+ ).toBeNull();
+ });
+
+ it('encodes and decodes MQTT v3.1.1 CONNECT, SUBSCRIBE, and PUBLISH packets cleanly', () => {
+ const connectPkt = encodeMqttConnect('ink-desktop-client');
+ expect(connectPkt[0]).toBe(0x10);
+
+ const subPkt = encodeMqttSubscribe(1, 'inkstudio/sig/v1/abcdef');
+ expect(subPkt[0]).toBe(0x82);
+
+ const topic = 'inkstudio/sig/v1/0123456789abcdef';
+ const largePayload = JSON.stringify({ sdp: 'v=0\r\n' + 'a=candidate:'.repeat(40) });
+ const pubPkt = encodeMqttPublish(topic, largePayload);
+ const pubPkt2 = encodeMqttPublish(topic, '{"type":"bye"}');
+
+ const combined = new Uint8Array(pubPkt.length + pubPkt2.length);
+ combined.set(pubPkt, 0);
+ combined.set(pubPkt2, pubPkt.length);
+
+ const packets = decodeMqttPackets(combined);
+ expect(packets).toHaveLength(2);
+ expect(packets[0]).toEqual({ packetType: 3, topic, payload: largePayload });
+ expect(packets[1]).toEqual({ packetType: 3, topic, payload: '{"type":"bye"}' });
+ expect(decodeMqttPackets(pubPkt.slice(0, 10))).toEqual([]);
+ });
+});
+
+describe('Room-Code & Invite-Link Routing (parseCollabTarget & parseInviteUrl)', () => {
+ it('routes short P2P room codes and tablet P2P invite links to WebRTC P2P', () => {
+ // Combined code (case-insensitive)
+ expect(parseCollabTarget('ink-7429-k8p2m9')).toMatchObject({
+ kind: 'p2p',
+ roomCode: 'INK-7429',
+ roomSecret: 'K8P2M9',
+ joinCode: 'INK-7429-K8P2M9',
+ roomName: 'INK-7429',
+ });
+
+ // Bare code (separate passcode)
+ expect(parseCollabTarget('INK-7429')).toMatchObject({
+ kind: 'p2p',
+ roomCode: 'INK-7429',
+ roomSecret: '',
+ joinCode: 'INK-7429',
+ roomName: 'INK-7429',
+ });
+
+ // Tablet deep-link P2P invite
+ expect(
+ parseCollabTarget('inkstudio://p2p?code=INK-5511&secret=ABC234&room=Tablet%20Canvas')
+ ).toMatchObject({
+ kind: 'p2p',
+ roomCode: 'INK-5511',
+ roomSecret: 'ABC234',
+ joinCode: 'INK-5511-ABC234',
+ roomName: 'Tablet Canvas',
+ });
+
+ // HTTPS web P2P invite with custom signaling URL
+ expect(
+ parseCollabTarget(
+ 'https://inkstudio.app/?p2p=INK-4400&secret=Q7R8S9&room=Collab&sig=wss%3A%2F%2Fsig.example.workers.dev%2Fsignal'
+ )
+ ).toMatchObject({
+ kind: 'p2p',
+ roomCode: 'INK-4400',
+ roomSecret: 'Q7R8S9',
+ joinCode: 'INK-4400-Q7R8S9',
+ roomName: 'Collab',
+ signalingUrl: 'wss://sig.example.workers.dev/signal',
+ });
+
+ // buildP2pShareUrl round-trip
+ const shareUrl = buildP2pShareUrl(
+ 'INK-8123',
+ 'M4N5P6',
+ 'PC Studio',
+ 'wss://sig.example.workers.dev/signal'
+ );
+ expect(parseCollabTarget(shareUrl)).toMatchObject({
+ kind: 'p2p',
+ roomCode: 'INK-8123',
+ roomSecret: 'M4N5P6',
+ joinCode: 'INK-8123-M4N5P6',
+ roomName: 'PC Studio',
+ signalingUrl: 'wss://sig.example.workers.dev/signal',
+ });
+ });
+
+ it('continues routing ws://, wss://, trycloudflare.com, and LAN HTTP links to WebSocket', () => {
+ const cfHttp = parseCollabTarget(
+ 'https://warm-ink-1234.trycloudflare.com/?room=Studio&token=tok1'
+ );
+ expect(cfHttp).toMatchObject({
+ kind: 'ws',
+ host: 'warm-ink-1234.trycloudflare.com',
+ port: 443,
+ roomName: 'Studio',
+ token: 'tok1',
+ isSecure: true,
+ });
+
+ // Bare trycloudflare.com URL without ?room=
+ const cfBare = parseCollabTarget('https://quick-room.trycloudflare.com/');
+ expect(cfBare).toMatchObject({
+ kind: 'ws',
+ host: 'quick-room.trycloudflare.com',
+ port: 443,
+ isSecure: true,
+ });
+
+ // Direct wss:// URL with custom path
+ const directWss = parseCollabTarget('wss://relay.example.com:8443/custom/ws?room=Art&token=abc');
+ expect(directWss).toMatchObject({
+ kind: 'ws',
+ host: 'relay.example.com',
+ port: 8443,
+ roomName: 'Art',
+ token: 'abc',
+ isSecure: true,
+ wsPath: '/custom/ws',
+ });
+
+ // Local LAN ws:// and http:// URLs
+ const lanWs = parseCollabTarget('ws://192.168.1.40:30303/ws?token=lan1');
+ expect(lanWs).toMatchObject({
+ kind: 'ws',
+ host: '192.168.1.40',
+ port: 30303,
+ token: 'lan1',
+ isSecure: false,
+ });
+
+ const lanHttp = parseInviteUrl('http://192.168.1.40:30303/?room=LAN&token=lan2');
+ expect(lanHttp).toMatchObject({
+ host: '192.168.1.40',
+ port: 30303,
+ roomName: 'LAN',
+ token: 'lan2',
+ isSecure: false,
+ });
+
+ // Invalid inputs
+ expect(parseCollabTarget('not a room code')).toBeNull();
+ expect(parseCollabTarget('')).toBeNull();
+ });
+});
+
+describe('Binary & JSON Wire Compatibility over ICollabTransport & WebRTC Hub/Guest', () => {
+ const origRTCPeerConnection = globalThis.RTCPeerConnection;
+
+ afterEach(() => {
+ multiplayerService.disconnect();
+ if (origRTCPeerConnection === undefined) {
+ delete (globalThis as Record<string, unknown>).RTCPeerConnection;
+ } else {
+ globalThis.RTCPeerConnection = origRTCPeerConnection;
+ }
+ });
+
+ it('includes public Google + Cloudflare STUN servers and optional TURN config', () => {
+ const defaultIce = buildIceServers();
+ expect(defaultIce).toEqual(DEFAULT_WEBRTC_ICE_SERVERS);
+
+ const withTurn = buildIceServers({
+ turnUrl: 'turns:turn.example.com:5349',
+ turnUsername: 'ink',
+ turnCredential: 'secret',
+ });
+ expect(withTurn).toHaveLength(DEFAULT_WEBRTC_ICE_SERVERS.length + 1);
+ expect(withTurn[withTurn.length - 1]).toEqual({
+ urls: 'turns:turn.example.com:5349',
+ username: 'ink',
+ credential: 'secret',
+ });
+ });
+
+ it('round-trips JSON and binary (LZ4 tile delta + stroke + cursor) packets via multiplayerService.attachTransport', () => {
+ const sentTexts: string[] = [];
+ const sentBinaries: Uint8Array[] = [];
+ const textListeners = new Set<(text: string) => void>();
+ const binaryListeners = new Set<(data: ArrayBuffer) => void>();
+ const closeListeners = new Set<(reason?: string) => void>();
+ let open = true;
+
+ const loopbackTransport: ICollabTransport = {
+ kind: 'webrtc-guest',
+ isOpen: () => open,
+ getBufferedAmount: () => 0,
+ sendText: (text: string) => {
+ sentTexts.push(text);
+ // Loop back through ChunkReassembler to simulate real WebRTC DataChannel framing
+ const frames = encodeTransportFrames('text', text, sentTexts.length);
+ const reassembler = new ChunkReassembler();
+ for (const frame of frames) {
+ const out = reassembler.pushFrame(frame);
+ if (out?.kind === 'text') {
+ textListeners.forEach((h) => h(out.text));
+ }
+ }
+ },
+ sendBinary: (data: ArrayBuffer | Uint8Array) => {
+ const bytes = data instanceof Uint8Array ? new Uint8Array(data) : new Uint8Array(data);
+ sentBinaries.push(bytes);
+ const frames = encodeTransportFrames('binary', bytes, 1000 + sentBinaries.length);
+ const reassembler = new ChunkReassembler();
+ for (const frame of frames) {
+ const out = reassembler.pushFrame(frame);
+ if (out?.kind === 'binary') {
+ binaryListeners.forEach((h) => h(out.data));
+ }
+ }
+ },
+ close: () => {
+ if (!open) return;
+ open = false;
+ closeListeners.forEach((h) => h('closed'));
+ },
+ onTextMessage: (h) => {
+ textListeners.add(h);
+ return () => textListeners.delete(h);
+ },
+ onBinaryMessage: (h) => {
+ binaryListeners.add(h);
+ return () => binaryListeners.delete(h);
+ },
+ onClose: (h) => {
+ closeListeners.add(h);
+ return () => closeListeners.delete(h);
+ },
+ onError: () => () => {},
+ };
+
+ const received: MultiplayerMessage[] = [];
+ const unsub = multiplayerService.onMessage((msg) => received.push(msg));
+
+ const peer: CollabPeer = {
+ id: 'desktop-peer-1',
+ name: 'DesktopArtist',
+ color: '#3b82f6',
+ role: 'editor',
+ };
+
+ multiplayerService.attachTransport(loopbackTransport, peer, { sendJoinRequest: true });
+ expect(multiplayerService.isConnected()).toBe(true);
+ expect(multiplayerService.getTransportKind()).toBe('webrtc-guest');
+
+ // Verify automatic JOIN_REQUEST over WebRTC text frame
+ expect(received.some((m) => m.type === 'JOIN_REQUEST')).toBe(true);
+
+ // Send JSON layer rename
+ multiplayerService.sendLayerRename('layer-1', 'Lineart');
+ const renameMsg = received.find((m) => m.type === 'LAYER_RENAME');
+ expect(renameMsg).toMatchObject({
+ type: 'LAYER_RENAME',
+ layerId: 'layer-1',
+ newName: 'Lineart',
+ });
+
+ // Send binary stroke chunk ('I','N', CODE_STROKE_CHUNK)
+ multiplayerService.sendStrokeChunk('stroke-abc', [
+ { x: 10, y: 20, pressure: 0.75, width: 12, timestamp: 1000 },
+ { x: 25.5, y: 40.25, pressure: 0.9, width: 14, timestamp: 1016 },
+ ]);
+ const chunkMsg = received.find((m) => m.type === 'STROKE_CHUNK');
+ expect(chunkMsg).toBeDefined();
+ if (chunkMsg?.type === 'STROKE_CHUNK') {
+ expect(chunkMsg.strokeId).toBe('stroke-abc');
+ expect(chunkMsg.points).toHaveLength(2);
+ expect(chunkMsg.points[0].x).toBeCloseTo(10, 3);
+ expect(chunkMsg.points[1].pressure).toBeCloseTo(0.9, 3);
+ }
+
+ // Send binary LZ4 tile delta ('I','N', CODE_TILE_DELTA) — full 256x256 RGBA tile (262,144 bytes)
+ const tileBytes = new Uint8Array(256 * 256 * 4);
+ for (let i = 0; i < tileBytes.length; i += 4) {
+ tileBytes[i] = 255;
+ tileBytes[i + 1] = 128;
+ tileBytes[i + 2] = 64;
+ tileBytes[i + 3] = 255;
+ }
+ const tile: TileBuffer = {
+ layerId: 'layer-1',
+ tileX: 2,
+ tileY: 3,
+ format: 'color-32bit',
+ version: 5,
+ data: tileBytes,
+ dirty: true,
+ isPagedToDisk: false,
+ lastAccessTimestamp: 0,
+ lod: 0,
+ };
+ multiplayerService.sendTileDelta('layer-1', tile);
+ const tileMsg = received.find((m) => m.type === 'BINARY_TILE');
+ expect(tileMsg).toBeDefined();
+ if (tileMsg?.type === 'BINARY_TILE') {
+ expect(tileMsg.layerId).toBe('layer-1');
+ expect(tileMsg.tileX).toBe(2);
+ expect(tileMsg.tileY).toBe(3);
+ expect(tileMsg.version).toBe(5);
+ expect(tileMsg.data?.byteLength).toBe(tileBytes.byteLength);
+ expect(tileMsg.data?.[0]).toBe(255);
+ expect(tileMsg.data?.[1]).toBe(128);
+ }
+
+ unsub();
+ });
+
+ it('connects WebRtcHostHub and WebRtcGuestClient end-to-end and enforces roles on binary & JSON traffic', async () => {
+ const roomHash = computeRoomTopicHash('INK-9001', 'XYZ234');
+
+ // In-memory signaling bus linking Host Hub and Guest Client
+ const signalingBus = new Set<{ peerId: string; cb: (env: SignalingEnvelope) => void }>();
+ const createMockSignaling = (peerId: string): ISignalingClient => ({
+ connect: vi.fn().mockResolvedValue(undefined),
+ send: (env) => {
+ const full: SignalingEnvelope = {
+ ...env,
+ v: 1,
+ roomHash,
+ mid: `m-${Math.random().toString(36).slice(2)}`,
+ ts: Date.now(),
+ };
+ queueMicrotask(() => {
+ for (const sub of signalingBus) {
+ if (sub.peerId === full.fromPeerId) continue;
+ if (full.toPeerId && full.toPeerId !== sub.peerId) continue;
+ sub.cb(full);
+ }
+ });
+ },
+ onMessage: (cb) => {
+ const entry = { peerId, cb };
+ signalingBus.add(entry);
+ return () => signalingBus.delete(entry);
+ },
+ onError: () => () => {},
+ close: vi.fn(),
+ });
+
+ // Paired FakeDataChannel / FakeRTCPeerConnection wiring Guest <-> Host
+ class PairedDataChannel {
+ readyState: RTCDataChannelState = 'connecting';
+ binaryType: BinaryType = 'arraybuffer';
+ bufferedAmount = 0;
+ peerChannel: PairedDataChannel | null = null;
+ onopen: (() => void) | null = null;
+ onmessage: ((ev: { data: ArrayBuffer }) => void) | null = null;
+ onclose: (() => void) | null = null;
+ onerror: ((ev: Event) => void) | null = null;
+
+ open() {
+ this.readyState = 'open';
+ this.onopen?.();
+ }
+ send(data: ArrayBuffer | Uint8Array) {
+ if (this.readyState !== 'open' || !this.peerChannel || this.peerChannel.readyState !== 'open') {
+ return;
+ }
+ const copy =
+ data instanceof Uint8Array
+ ? new Uint8Array(data)
+ : new Uint8Array(data.slice(0));
+ this.peerChannel.onmessage?.({ data: copy.buffer });
+ }
+ close() {
+ this.readyState = 'closed';
+ this.onclose?.();
+ }
+ }
+
+ let guestPcRef: FakePeerConnection | null = null;
+ class FakePeerConnection {
+ connectionState: RTCPeerConnectionState = 'new';
+ localDescription: RTCSessionDescriptionInit | null = null;
+ onicecandidate: ((ev: { candidate: null }) => void) | null = null;
+ onconnectionstatechange: (() => void) | null = null;
+ ondatachannel: ((ev: { channel: PairedDataChannel }) => void) | null = null;
+ dc: PairedDataChannel | null = null;
+
+ createDataChannel() {
+ const dc = new PairedDataChannel();
+ this.dc = dc;
+ guestPcRef = this;
+ return dc;
+ }
+ async createOffer() {
+ return { type: 'offer' as const, sdp: 'v=0\r\noffer\r\n' };
+ }
+ async setLocalDescription(desc: RTCSessionDescriptionInit) {
+ this.localDescription = desc;
+ }
+ async setRemoteDescription(desc: RTCSessionDescriptionInit) {
+ if (desc.type === 'answer' && this.dc) {
+ this.connectionState = 'connected';
+ this.dc.open();
+ }
+ }
+ async createAnswer() {
+ // Pair host DC with guest DC
+ const hostDc = new PairedDataChannel();
+ if (guestPcRef?.dc) {
+ hostDc.peerChannel = guestPcRef.dc;
+ guestPcRef.dc.peerChannel = hostDc;
+ }
+ hostDc.readyState = 'open';
+ this.connectionState = 'connected';
+ this.ondatachannel?.({ channel: hostDc });
+ return { type: 'answer' as const, sdp: 'v=0\r\nanswer\r\n' };
+ }
+ async addIceCandidate() {}
+ close() {
+ this.connectionState = 'closed';
+ }
+ }
+
+ (globalThis as Record<string, unknown>).RTCPeerConnection = FakePeerConnection;
+
+ const hub = new WebRtcHostHub({
+ roomHash,
+ hostPeerId: 'android-host',
+ signalingClient: createMockSignaling('android-host'),
+ });
+ const hostReceivedTexts: string[] = [];
+ const hostReceivedBinaries: ArrayBuffer[] = [];
+ hub.onTextMessage((t) => hostReceivedTexts.push(t));
+ hub.onBinaryMessage((b) => hostReceivedBinaries.push(b));
+ await hub.start();
+
+ const guest = new WebRtcGuestClient({
+ roomHash,
+ peerId: 'desktop-guest',
+ signalingClient: createMockSignaling('desktop-guest'),
+ });
+ const guestReceivedTexts: string[] = [];
+ guest.onTextMessage((t) => guestReceivedTexts.push(t));
+ await guest.connect();
+
+ expect(guest.isOpen()).toBe(true);
+ expect(hub.getConnectedGuestCount()).toBe(1);
+
+ // Guest sends JOIN_REQUEST -> received by Host with authoritative seq
+ guest.sendText(
+ JSON.stringify({
+ type: 'JOIN_REQUEST',
+ senderId: 'desktop-guest',
+ peer: { id: 'desktop-guest', name: 'DesktopGuest', color: '#10b981' },
+ })
+ );
+ expect(hostReceivedTexts).toHaveLength(1);
+ expect(JSON.parse(hostReceivedTexts[0])).toMatchObject({
+ type: 'JOIN_REQUEST',
+ senderId: 'desktop-guest',
+ seq: 1,
+ });
+
+ // Guest sends binary packet (CODE_STROKE_START) -> accepted while editor
+ const strokeBin = new Uint8Array([BINARY_MAGIC_0, BINARY_MAGIC_1, 0x01, 0, 0, 0, 0, 0, 0, 0, 0]);
+ guest.sendBinary(strokeBin);
+ expect(hostReceivedBinaries).toHaveLength(1);
+
+ // Host demotes guest to viewer
+ hub.sendText(
+ JSON.stringify({
+ type: 'PEER_ROLE_UPDATE',
+ senderId: 'android-host',
+ targetPeerId: 'desktop-guest',
+ role: 'viewer',
+ })
+ );
+
+ // Viewer tries to send binary stroke -> blocked with ACCESS_DENIED (VIEWER_READONLY)
+ hostReceivedBinaries.length = 0;
+ guestReceivedTexts.length = 0;
+ guest.sendBinary(strokeBin);
+ expect(hostReceivedBinaries).toHaveLength(0);
+ expect(guestReceivedTexts).toHaveLength(1);
+ expect(JSON.parse(guestReceivedTexts[0])).toMatchObject({
+ type: 'ACCESS_DENIED',
+ code: 'VIEWER_READONLY',
+ });
+
+ guest.close();
+ hub.close();
+ });
+
+ it('stamps authoritative monotonic seq on binary packets, unicasts via sendBinaryTo, and enforces layer locks', async () => {
+ const roomHash = computeRoomTopicHash('INK-9002', 'ABC345');
+ const signalingListeners = new Set<(env: SignalingEnvelope) => void>();
+ const mockSignaling: ISignalingClient = {
+ connect: vi.fn().mockResolvedValue(undefined),
+ send: vi.fn(),
+ onMessage: (cb) => {
+ signalingListeners.add(cb);
+ return () => signalingListeners.delete(cb);
+ },
+ onError: () => () => {},
+ close: vi.fn(),
+ };
+
+ class FakeDataChannel {
+ readyState: RTCDataChannelState = 'open';
+ binaryType: BinaryType = 'arraybuffer';
+ bufferedAmount = 0;
+ sent: ArrayBuffer[] = [];
+ onopen: (() => void) | null = null;
+ onmessage: ((ev: { data: unknown }) => void) | null = null;
+ onclose: (() => void) | null = null;
+ onerror: ((ev: Event) => void) | null = null;
+ send(data: ArrayBuffer) {
+ this.sent.push(data);
+ }
+ close() {
+ this.readyState = 'closed';
+ }
+ }
+
+ const createdPcs: Array<{
+ dc: FakeDataChannel;
+ ondatachannel: ((ev: { channel: FakeDataChannel }) => void) | null;
+ }> = [];
+ class FakePeerConnection {
+ connectionState: RTCPeerConnectionState = 'connected';
+ onicecandidate: ((ev: { candidate: null }) => void) | null = null;
+ onconnectionstatechange: (() => void) | null = null;
+ ondatachannel: ((ev: { channel: FakeDataChannel }) => void) | null = null;
+ dc = new FakeDataChannel();
+ constructor() {
+ createdPcs.push(this);
+ }
+ async setRemoteDescription() {}
+ async createAnswer() {
+ return { type: 'answer', sdp: 'v=0\r\nanswer\r\n' };
+ }
+ async setLocalDescription() {}
+ async addIceCandidate() {}
+ close() {
+ this.connectionState = 'closed';
+ }
+ }
+
+ (globalThis as Record<string, unknown>).RTCPeerConnection = FakePeerConnection;
+
+ const hub = new WebRtcHostHub({
+ roomHash,
+ hostPeerId: 'host-1',
+ signalingClient: mockSignaling,
+ });
+ const hostBinaries: ArrayBuffer[] = [];
+ hub.onBinaryMessage((b) => hostBinaries.push(b));
+ await hub.start();
+
+ for (const gid of ['guest-a', 'guest-b']) {
+ for (const listener of signalingListeners) {
+ listener({
+ v: 1,
+ mid: `offer-${gid}`,
+ roomHash,
+ type: 'offer',
+ fromPeerId: gid,
+ sdp: 'v=0\r\noffer\r\n',
+ ts: Date.now(),
+ });
+ }
+ }
+ await new Promise((r) => setTimeout(r, 0));
+
+ const dcA = createdPcs[0].dc;
+ const dcB = createdPcs[1].dc;
+ createdPcs[0].ondatachannel?.({ channel: dcA });
+ createdPcs[1].ondatachannel?.({ channel: dcB });
+
+ const sendText = (dc: FakeDataChannel, id: number, payload: object) => {
+ for (const f of encodeTransportFrames('text', JSON.stringify(payload), id)) {
+ dc.onmessage?.({ data: f.buffer.slice(f.byteOffset, f.byteOffset + f.byteLength) });
+ }
+ };
+ const sendBin = (dc: FakeDataChannel, id: number, bytes: Uint8Array) => {
+ for (const f of encodeTransportFrames('binary', bytes, id)) {
+ dc.onmessage?.({ data: f.buffer.slice(f.byteOffset, f.byteOffset + f.byteLength) });
+ }
+ };
+ const makeTileBin = (layerId: string, clientLamport: number): Uint8Array => {
+ const lid = new TextEncoder().encode(layerId);
+ const payloadLen = 2 + lid.length + 4;
+ const pkt = new Uint8Array(11 + payloadLen);
+ const v = new DataView(pkt.buffer);
+ pkt[0] = 0x49;
+ pkt[1] = 0x4e;
+ pkt[2] = 0x04; // CODE_TILE_DELTA
+ v.setUint32(3, clientLamport, true);
+ v.setUint32(7, payloadLen, true);
+ v.setUint16(11, lid.length, true);
+ pkt.set(lid, 13);
+ return pkt;
+ };
+
+ // 1. Pre-join binary tile is rejected before JOIN_REQUEST
+ sendBin(dcA, 1, makeTileBin('layer-1', 50));
+ expect(hostBinaries).toHaveLength(0);
+
+ // Join both guests
+ sendText(dcA, 2, { type: 'JOIN_REQUEST', peer: { id: 'guest-a', name: 'A', color: '#111' } });
+ sendText(dcB, 3, { type: 'JOIN_REQUEST', peer: { id: 'guest-b', name: 'B', color: '#222' } });
+ dcA.sent.length = 0;
+ dcB.sent.length = 0;
+
+ // 2. Host unicasts binary tile to guest-b only -> guest-a receives nothing, guest-b gets stamped seq
+ hub.sendBinaryTo('guest-b', makeTileBin('layer-1', 999));
+ expect(dcA.sent).toHaveLength(0);
+ expect(dcB.sent).toHaveLength(1);
+ const reB = new ChunkReassembler();
+ const msgB = reB.pushFrame(dcB.sent[0]);
+ expect(msgB?.kind).toBe('binary');
+ const hostUnicastSeq =
+ msgB?.kind === 'binary' ? new DataView(msgB.data).getUint32(3, true) : 0;
+ expect(hostUnicastSeq).toBeGreaterThan(0);
+ expect(hostUnicastSeq).not.toBe(999);
+
+ // 3. Guest A sends binary tile with low Lamport (1) -> Hub stamps monotonic seq > hostUnicastSeq
+ dcB.sent.length = 0;
+ sendBin(dcA, 4, makeTileBin('layer-1', 1));
+ expect(hostBinaries).toHaveLength(1);
+ const stampedSeq = new DataView(hostBinaries[0]).getUint32(3, true);
+ expect(stampedSeq).toBeGreaterThan(hostUnicastSeq);
+
+ // 4. Host locks layer-1 to guest-a -> guest-b binary tile on layer-1 is rejected with LAYER_LOCKED
+ hub.sendText(
+ JSON.stringify({
+ type: 'LAYER_UPDATE',
+ layerId: 'layer-1',
+ patch: { reservedByPeerId: 'guest-a' },
+ })
+ );
+ hostBinaries.length = 0;
+ dcB.sent.length = 0;
+ sendBin(dcB, 5, makeTileBin('layer-1', 100));
+ expect(hostBinaries).toHaveLength(0);
+ expect(dcB.sent.length).toBeGreaterThan(0);
+ const denied = new ChunkReassembler().pushFrame(dcB.sent[0]);
+ expect(denied?.kind).toBe('text');
+ if (denied?.kind === 'text') {
+ expect(JSON.parse(denied.text).code).toBe('LAYER_LOCKED');
+ }
+
+ hub.close();
+ });
+});
diff --git a/src/utils/brushAssetSync.ts b/src/utils/brushAssetSync.ts
index 3c1f1cc..5c22351 100644
--- a/src/utils/brushAssetSync.ts
+++ b/src/utils/brushAssetSync.ts
@@ -275,6 +275,9 @@ export function prepareBrushSettingsForWire(bs: BrushSettings): {
customTipImage: _tipImg,
dualTipDataUrl: _dualUrl,
dualTipImage: _dualImg,
+ dualSubTips: _dualSubTips,
+ dualSubTipImages: _dualSubImgs,
+ dualBrushConfig: rawDualCfg,
paperTexture: _paperUrl,
paperTextureImage: _paperImg,
subTips: _subTips,
@@ -282,6 +285,17 @@ export function prepareBrushSettingsForWire(bs: BrushSettings): {
...clean
} = bs;
+ if (rawDualCfg) {
+ const {
+ tipDataUrl: _dUrl,
+ tipImage: _dImg,
+ subTips: _dSubTips,
+ subTipImages: _dSubImgs,
+ ...cleanDualCfg
+ } = rawDualCfg;
+ (clean as BrushSettings).dualBrushConfig = cleanDualCfg;
+ }
+
const hasRefs = Boolean(
refs.tipHash || refs.dualTipHash || refs.paperTextureHash || refs.subTipHashes?.length
);
diff --git a/src/utils/brushPresetManager.ts b/src/utils/brushPresetManager.ts
index 8b52c49..0a2a407 100644
--- a/src/utils/brushPresetManager.ts
+++ b/src/utils/brushPresetManager.ts
@@ -7,9 +7,12 @@ import {
BrushDynamics,
CspAngleDynamicsMode,
CspBlendTipsMode,
+ CspBrushCombineMode,
+ CspDualBrushConfig,
CspPaperTextureMode,
CspSensorConfig,
CspSpraySettings,
+ CspSubTipOrder,
CspTaperSettings,
CspTipFlipMode,
GrainMappingMode,
@@ -58,7 +61,7 @@ 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;
+export const BUILTIN_PRESET_SCHEMA_VERSION = 4;
const SKETCH_PRESET_IDS = [
'mechanical-pencil',
'pencil-hb-2b',
@@ -66,17 +69,79 @@ const SKETCH_PRESET_IDS = [
'charcoal-pencil',
'standard-chalk',
];
+const CHALK_REWORK_PRESET_IDS = [
+ 'oil-painting',
+ 'thick-oil-painting',
+ 'chalk-painting',
+ 'blend-brush',
+ 'blend-chalk-brush',
+];
+
+/**
+ * Maps legacy built-in brush preset IDs (removed/upgraded in schema v4)
+ * to their direct modern equivalents so saved active presets and Quick Access
+ * shortcuts migrate seamlessly.
+ */
+export const LEGACY_PRESET_ID_MAP: Readonly<Record<string, BrushPresetId>> = {
+ 'oil-painting': 'oil-flat-alla-prima',
+ 'thick-oil-painting': 'thick-oil-impasto',
+ 'chalk-painting': 'concept-matte-chalk',
+ 'blend-brush': 'blend-velvet-soft',
+ 'blend-chalk-brush': 'blend-matte-chalk',
+ 'soft-round': 'soft-glaze-airbrush',
+ 'noise-shader': 'atmospheric-grain-shader',
+};
+
+const V4_UPGRADED_PRESET_IDS = [
+ // Upgraded CSP Pen presets
+ 'g-pen',
+ 'real-g-pen',
+ 'textured-pen',
+ 'rough-pen',
+ // Legacy Brush/Blend IDs replaced in v4
+ 'oil-painting',
+ 'thick-oil-painting',
+ 'chalk-painting',
+ 'blend-brush',
+ 'blend-chalk-brush',
+ 'soft-round',
+ 'noise-shader',
+ // New v4 Brush & Blend IDs (clear any stale cached entries on v3 -> v4 upgrade)
+ 'oil-flat-alla-prima',
+ 'thick-oil-impasto',
+ 'dry-bristle-rake-paint',
+ 'concept-matte-chalk',
+ 'silky-portrait-round',
+ 'canvas-scumble-oil',
+ 'soft-glaze-airbrush',
+ 'atmospheric-grain-shader',
+ 'fine-detail-filbert',
+ 'blend-velvet-soft',
+ 'blend-oil-bristle',
+ 'blend-matte-chalk',
+ 'blend-rake-hair',
+ 'blend-canvas-scumble',
+ 'blend-fingertip',
+];
+
+export function migrateLegacyPresetId(presetId: string): string {
+ return LEGACY_PRESET_ID_MAP[presetId] ?? presetId;
+}
+
export const ERASER_PRESET_ID = 'tool-eraser';
export const DEFAULT_BRUSH_PRESET_ID = 'g-pen';
export interface BrushPersistentSettings {
size?: number;
+ brushSizeUnit?: number;
+ brushSizeSpecifiedByScreen?: boolean;
minSizeFactor?: number;
opacity?: number;
flow?: number;
brushDensity?: number;
adjustDensityByGap?: boolean;
blendTipsMode?: CspBlendTipsMode;
+ brushCombineMode?: CspBrushCombineMode;
spacing?: number;
hardness?: number;
grain?: number;
@@ -90,10 +155,13 @@ export interface BrushPersistentSettings {
smoothing?: boolean;
thickness?: number;
thicknessVertical?: boolean;
+ thicknessSensor?: CspSensorConfig;
antiAlias?: number;
flipH?: CspTipFlipMode;
flipV?: CspTipFlipMode;
+ subTipOrder?: CspSubTipOrder;
isRibbon?: boolean;
+ isDualToneTip?: boolean;
customTipAngle?: number;
customTipAngleDynamics?: CspAngleDynamicsMode;
customTipRotationRandomScale?: number;
@@ -102,6 +170,12 @@ export interface BrushPersistentSettings {
amountOfPaint?: number;
densityOfPaint?: number;
colorStretch?: number;
+ amountOfPaintSensor?: CspSensorConfig;
+ densityOfPaintSensor?: CspSensorConfig;
+ colorStretchSensor?: CspSensorConfig;
+ mixGroundColor?: boolean;
+ useBlur?: boolean;
+ blurStrength?: number;
mixingMode?: NaturalMixingMode;
wetEdge?: number;
wetEdgeRadius?: number;
@@ -112,15 +186,21 @@ export interface BrushPersistentSettings {
grainMappingMode?: GrainMappingMode;
paperTextureScale?: number;
paperTextureRotate?: number;
+ paperTextureOffsetX?: number;
+ paperTextureOffsetY?: number;
paperTextureMode?: CspPaperTextureMode;
paperTextureBrightness?: number;
paperTextureContrast?: number;
+ paperTextureApplyEachPlot?: boolean;
+ paperTextureEmphasizeDensity?: boolean;
paperTextureInverted?: boolean;
pressureCurve?: [number, number][];
velocityCurve?: [number, number][];
sizeSensor?: CspSensorConfig;
opacitySensor?: CspSensorConfig;
densitySensor?: CspSensorConfig;
+ intervalSensor?: CspSensorConfig;
+ textureDensitySensor?: CspSensorConfig;
bristleSplaySensor?: CspSensorConfig;
paintLoadSensor?: CspSensorConfig;
grainPenetrationSensor?: CspSensorConfig;
@@ -130,11 +210,24 @@ export interface BrushPersistentSettings {
taper?: CspTaperSettings;
dynamics?: BrushDynamics;
dualBrush?: boolean;
+ dualBrushConfig?: CspDualBrushConfig;
dualBrushCompositeMode?: string;
dualSize?: number;
+ dualLinkSize?: boolean;
dualSpacing?: number;
dualScatter?: number;
+ dualThickness?: number;
+ dualThicknessVertical?: boolean;
dualAngle?: number;
+ dualAngleDynamics?: CspAngleDynamicsMode;
+ dualAngleSensor?: CspSensorConfig;
+ dualHardness?: number;
+ dualDensity?: number;
+ dualSubTipOrder?: CspSubTipOrder;
+ dualFlipH?: CspTipFlipMode;
+ dualFlipV?: CspTipFlipMode;
+ dualSpray?: CspSpraySettings;
+ dualIsRibbon?: boolean;
dualScale?: number;
dualSurfaceTextureId?: SurfaceTextureId;
dualGrainDepth?: number;
@@ -145,6 +238,8 @@ export interface BrushPersistentSettings {
}
export const NEUTRAL_BRUSH_DEFAULTS: Partial<BrushSettings> = {
+ brushSizeUnit: undefined,
+ brushSizeSpecifiedByScreen: undefined,
brushDensity: undefined,
adjustDensityByGap: false,
blendTipsMode: 'darken',
@@ -157,6 +252,7 @@ export const NEUTRAL_BRUSH_DEFAULTS: Partial<BrushSettings> = {
sharpCorners: true,
thickness: 1.0,
thicknessVertical: false,
+ thicknessSensor: undefined,
flipH: 'none',
flipV: 'none',
antiAlias: 2,
@@ -165,6 +261,8 @@ export const NEUTRAL_BRUSH_DEFAULTS: Partial<BrushSettings> = {
sizeSensor: undefined,
opacitySensor: undefined,
densitySensor: undefined,
+ intervalSensor: undefined,
+ textureDensitySensor: undefined,
bristleSplaySensor: undefined,
paintLoadSensor: undefined,
grainPenetrationSensor: undefined,
@@ -176,6 +274,7 @@ export const NEUTRAL_BRUSH_DEFAULTS: Partial<BrushSettings> = {
customTipAngleDynamics: 'none',
customTipRotationRandomScale: 0,
isColorTip: false,
+ isDualToneTip: false,
subTips: undefined,
subTipOrder: undefined,
subTipImages: undefined,
@@ -190,6 +289,12 @@ export const NEUTRAL_BRUSH_DEFAULTS: Partial<BrushSettings> = {
amountOfPaint: 0.7,
densityOfPaint: 0.8,
colorStretch: 0.6,
+ amountOfPaintSensor: undefined,
+ densityOfPaintSensor: undefined,
+ colorStretchSensor: undefined,
+ mixGroundColor: false,
+ useBlur: false,
+ blurStrength: undefined,
mixingMode: 'blend',
wetEdge: 0,
wetEdgeRadius: undefined,
@@ -202,16 +307,34 @@ export const NEUTRAL_BRUSH_DEFAULTS: Partial<BrushSettings> = {
paperTextureMode: 'subtract',
paperTextureBrightness: 0,
paperTextureContrast: 0,
- paperTextureApplyEachPlot: false,
+ paperTextureApplyEachPlot: undefined,
+ paperTextureEmphasizeDensity: false,
paperTextureInverted: false,
paperTextureScale: 1.0,
paperTextureRotate: 0,
+ paperTextureOffsetX: 0,
+ paperTextureOffsetY: 0,
dualBrush: false,
+ dualBrushConfig: undefined,
dualBrushCompositeMode: 'multiply',
dualSize: undefined,
+ dualLinkSize: undefined,
dualSpacing: undefined,
dualScatter: 0,
+ dualThickness: undefined,
+ dualThicknessVertical: undefined,
dualAngle: 0,
+ dualAngleDynamics: undefined,
+ dualAngleSensor: undefined,
+ dualHardness: undefined,
+ dualDensity: undefined,
+ dualSubTips: undefined,
+ dualSubTipImages: undefined,
+ dualSubTipOrder: undefined,
+ dualFlipH: undefined,
+ dualFlipV: undefined,
+ dualSpray: undefined,
+ dualIsRibbon: undefined,
dualScale: 1.0,
dualSurfaceTextureId: undefined,
dualGrainDepth: 0,
@@ -222,6 +345,7 @@ export const NEUTRAL_BRUSH_DEFAULTS: Partial<BrushSettings> = {
bristle: undefined,
naturalPaint: undefined,
impasto: undefined,
+ importWarnings: undefined,
useGpu: true,
};
@@ -247,6 +371,18 @@ export const DEFAULT_ERASER_SETTINGS: Partial<BrushSettings> = {
let _memorySettingsCache: Record<string, BrushPersistentSettings> | null = null;
let _saveDebounceTimer: ReturnType<typeof setTimeout> | null = null;
+/**
+ * Clears the in-memory settings cache so subsequent reads re-load from localStorage.
+ * Primarily used by schema-migration tests.
+ */
+export function resetBrushSettingsCache(): void {
+ if (_saveDebounceTimer) {
+ clearTimeout(_saveDebounceTimer);
+ _saveDebounceTimer = null;
+ }
+ _memorySettingsCache = null;
+}
+
export function loadAllSavedBrushSettings(): Record<string, BrushPersistentSettings> {
if (_memorySettingsCache) return _memorySettingsCache;
try {
@@ -256,10 +392,28 @@ export function loadAllSavedBrushSettings(): Record<string, BrushPersistentSetti
const storedVer = Number(localStorage.getItem(STORAGE_KEY_PRESET_SCHEMA) || '0');
if (storedVer < BUILTIN_PRESET_SCHEMA_VERSION) {
let mutated = false;
- for (const id of SKETCH_PRESET_IDS) {
- if (parsed[id]) {
- delete parsed[id];
- mutated = true;
+ if (storedVer < 2) {
+ for (const id of SKETCH_PRESET_IDS) {
+ if (parsed[id]) {
+ delete parsed[id];
+ mutated = true;
+ }
+ }
+ }
+ if (storedVer < 3) {
+ for (const id of CHALK_REWORK_PRESET_IDS) {
+ if (parsed[id]) {
+ delete parsed[id];
+ mutated = true;
+ }
+ }
+ }
+ if (storedVer < 4) {
+ for (const id of V4_UPGRADED_PRESET_IDS) {
+ if (parsed[id]) {
+ delete parsed[id];
+ mutated = true;
+ }
}
}
if (mutated) {
@@ -282,12 +436,15 @@ export function getSavedBrushSettings(presetId: string): BrushPersistentSettings
const PERSISTENT_KEYS: (keyof BrushPersistentSettings)[] = [
'size',
+ 'brushSizeUnit',
+ 'brushSizeSpecifiedByScreen',
'minSizeFactor',
'opacity',
'flow',
'brushDensity',
'adjustDensityByGap',
'blendTipsMode',
+ 'brushCombineMode',
'spacing',
'hardness',
'grain',
@@ -301,10 +458,13 @@ const PERSISTENT_KEYS: (keyof BrushPersistentSettings)[] = [
'smoothing',
'thickness',
'thicknessVertical',
+ 'thicknessSensor',
'antiAlias',
'flipH',
'flipV',
+ 'subTipOrder',
'isRibbon',
+ 'isDualToneTip',
'customTipAngle',
'customTipAngleDynamics',
'customTipRotationRandomScale',
@@ -313,6 +473,12 @@ const PERSISTENT_KEYS: (keyof BrushPersistentSettings)[] = [
'amountOfPaint',
'densityOfPaint',
'colorStretch',
+ 'amountOfPaintSensor',
+ 'densityOfPaintSensor',
+ 'colorStretchSensor',
+ 'mixGroundColor',
+ 'useBlur',
+ 'blurStrength',
'mixingMode',
'wetEdge',
'wetEdgeRadius',
@@ -323,15 +489,21 @@ const PERSISTENT_KEYS: (keyof BrushPersistentSettings)[] = [
'grainMappingMode',
'paperTextureScale',
'paperTextureRotate',
+ 'paperTextureOffsetX',
+ 'paperTextureOffsetY',
'paperTextureMode',
'paperTextureBrightness',
'paperTextureContrast',
+ 'paperTextureApplyEachPlot',
+ 'paperTextureEmphasizeDensity',
'paperTextureInverted',
'pressureCurve',
'velocityCurve',
'sizeSensor',
'opacitySensor',
'densitySensor',
+ 'intervalSensor',
+ 'textureDensitySensor',
'bristleSplaySensor',
'paintLoadSensor',
'grainPenetrationSensor',
@@ -341,11 +513,24 @@ const PERSISTENT_KEYS: (keyof BrushPersistentSettings)[] = [
'taper',
'dynamics',
'dualBrush',
+ 'dualBrushConfig',
'dualBrushCompositeMode',
'dualSize',
+ 'dualLinkSize',
'dualSpacing',
'dualScatter',
+ 'dualThickness',
+ 'dualThicknessVertical',
'dualAngle',
+ 'dualAngleDynamics',
+ 'dualAngleSensor',
+ 'dualHardness',
+ 'dualDensity',
+ 'dualSubTipOrder',
+ 'dualFlipH',
+ 'dualFlipV',
+ 'dualSpray',
+ 'dualIsRibbon',
'dualScale',
'dualSurfaceTextureId',
'dualGrainDepth',
@@ -355,6 +540,19 @@ const PERSISTENT_KEYS: (keyof BrushPersistentSettings)[] = [
'impasto',
];
+function sanitizeDualBrushConfigForPresetStorage(
+ cfg: CspDualBrushConfig
+): CspDualBrushConfig {
+ const {
+ tipImage: _tipImg,
+ subTipImages: _subImgs,
+ tipDataUrl: _tipUrl,
+ subTips: _subTips,
+ ...lightweight
+ } = cfg;
+ return lightweight;
+}
+
function mergeIntoMemoryCache(presetId: string, settings: Partial<BrushSettings>): Record<string, BrushPersistentSettings> {
const all = loadAllSavedBrushSettings();
const persistent: BrushPersistentSettings = { ...(all[presetId] || {}) };
@@ -363,7 +561,13 @@ function mergeIntoMemoryCache(presetId: string, settings: Partial<BrushSettings>
const key = PERSISTENT_KEYS[i];
const val = settings[key];
if (val !== undefined) {
- (persistent as Record<string, unknown>)[key] = val;
+ if (key === 'dualBrushConfig' && val && typeof val === 'object') {
+ persistent.dualBrushConfig = sanitizeDualBrushConfigForPresetStorage(
+ val as CspDualBrushConfig
+ );
+ } else {
+ (persistent as Record<string, unknown>)[key] = val;
+ }
}
}
@@ -434,6 +638,11 @@ export function getActivePresetId(): string {
if (typeof localStorage === 'undefined') return DEFAULT_BRUSH_PRESET_ID;
const saved = localStorage.getItem(STORAGE_KEY_ACTIVE_PRESET);
if (!saved) return DEFAULT_BRUSH_PRESET_ID;
+ const migrated = migrateLegacyPresetId(saved);
+ if (migrated !== saved && getBuiltinBrushConfig(migrated)) {
+ safeLocalStorageSetItem(STORAGE_KEY_ACTIVE_PRESET, migrated, 'active brush preset');
+ return migrated;
+ }
if (saved.startsWith('csp-') || saved.startsWith('inkb-') || getBuiltinBrushConfig(saved)) return saved;
return DEFAULT_BRUSH_PRESET_ID;
} catch {
@@ -450,10 +659,11 @@ export function getEffectiveBrushSettings(
presetId: string,
customBrushes?: CspBrush[]
): Partial<BrushSettings> {
- const saved = getSavedBrushSettings(presetId);
+ const resolvedPresetId = migrateLegacyPresetId(presetId);
+ const saved = getSavedBrushSettings(resolvedPresetId);
// 1. Eraser
- if (presetId === ERASER_PRESET_ID || presetId === 'eraser') {
+ if (resolvedPresetId === ERASER_PRESET_ID || resolvedPresetId === 'eraser') {
return {
...DEFAULT_ERASER_SETTINGS,
preset: ERASER_PRESET_ID,
@@ -471,8 +681,9 @@ export function getEffectiveBrushSettings(
const tipImg = cspMatch.tipDataUrl
? getPreloadedTipImage(cspMatch.tipDataUrl) || undefined
: undefined;
- const dualTipImg = cspMatch.secondaryTipDataUrl
- ? getPreloadedTipImage(cspMatch.secondaryTipDataUrl) || undefined
+ const dualTipUrl = cspMatch.secondaryTipDataUrl || cspMatch.dualBrushConfig?.tipDataUrl;
+ const dualTipImg = dualTipUrl
+ ? getPreloadedTipImage(dualTipUrl) || undefined
: undefined;
const paperTextureImage = cspMatch.paperTexture
? getPreloadedTipImage(cspMatch.paperTexture) || undefined
@@ -486,12 +697,42 @@ export function getEffectiveBrushSettings(
}
if (imgs.length > 0) subTipImages = imgs;
}
+ const resolvedDualSubTips = cspMatch.dualSubTips || cspMatch.dualBrushConfig?.subTips;
+ let dualSubTipImages: HTMLImageElement[] | undefined = undefined;
+ if (resolvedDualSubTips && resolvedDualSubTips.length > 0) {
+ const imgs: HTMLImageElement[] = [];
+ for (const dst of resolvedDualSubTips) {
+ const im = getPreloadedTipImage(dst.dataUrl);
+ if (im) imgs.push(im);
+ }
+ if (imgs.length > 0) dualSubTipImages = imgs;
+ }
+
+ const baseDualBrushConfig = cspMatch.dualBrushConfig
+ ? {
+ ...cspMatch.dualBrushConfig,
+ tipImage: dualTipImg ?? cspMatch.dualBrushConfig.tipImage,
+ subTipImages: dualSubTipImages ?? cspMatch.dualBrushConfig.subTipImages,
+ }
+ : undefined;
+ const mergedDualBrushConfig = saved?.dualBrushConfig
+ ? {
+ ...baseDualBrushConfig,
+ ...saved.dualBrushConfig,
+ tipDataUrl: saved.dualBrushConfig.tipDataUrl ?? baseDualBrushConfig?.tipDataUrl,
+ tipImage: baseDualBrushConfig?.tipImage,
+ subTips: saved.dualBrushConfig.subTips ?? baseDualBrushConfig?.subTips,
+ subTipImages: baseDualBrushConfig?.subTipImages,
+ }
+ : baseDualBrushConfig;
return {
...NEUTRAL_BRUSH_DEFAULTS,
preset: cspMatch.id,
brushName: cspMatch.name,
size: cspMatch.size,
+ brushSizeUnit: cspMatch.brushSizeUnit,
+ brushSizeSpecifiedByScreen: cspMatch.brushSizeSpecifiedByScreen,
minSizeFactor: cspMatch.minSizeFactor,
flow: cspMatch.flow,
brushDensity: cspMatch.brushDensity,
@@ -503,6 +744,7 @@ export function getEffectiveBrushSettings(
hardness: cspMatch.hardness,
thickness: cspMatch.thickness,
thicknessVertical: cspMatch.thicknessVertical,
+ thicknessSensor: cspMatch.thicknessSensor,
antiAlias: cspMatch.antiAlias,
stabilization: cspMatch.stabilization,
postCorrection: cspMatch.postCorrection,
@@ -510,6 +752,7 @@ export function getEffectiveBrushSettings(
customTipDataUrl: cspMatch.tipDataUrl,
customTipImage: tipImg,
isColorTip: cspMatch.isColorTip,
+ isDualToneTip: cspMatch.isDualToneTip,
flipH: cspMatch.flipH,
flipV: cspMatch.flipV,
customTipAngle: cspMatch.angle,
@@ -527,6 +770,8 @@ export function getEffectiveBrushSettings(
sizeSensor: cspMatch.sizeSensor,
opacitySensor: cspMatch.opacitySensor,
densitySensor: cspMatch.densitySensor,
+ intervalSensor: cspMatch.intervalSensor,
+ textureDensitySensor: cspMatch.textureDensitySensor,
bristleSplaySensor: cspMatch.bristleSplaySensor,
paintLoadSensor: cspMatch.paintLoadSensor,
grainPenetrationSensor: cspMatch.grainPenetrationSensor,
@@ -541,6 +786,12 @@ export function getEffectiveBrushSettings(
amountOfPaint: cspMatch.amountOfPaint ?? 0.7,
densityOfPaint: cspMatch.densityOfPaint ?? 0.8,
colorStretch: cspMatch.colorStretch ?? 0.6,
+ amountOfPaintSensor: cspMatch.amountOfPaintSensor,
+ densityOfPaintSensor: cspMatch.densityOfPaintSensor,
+ colorStretchSensor: cspMatch.colorStretchSensor,
+ mixGroundColor: cspMatch.mixGroundColor,
+ useBlur: cspMatch.useBlur,
+ blurStrength: cspMatch.blurStrength,
mixingMode: cspMatch.mixingMode ?? 'blend',
wetEdge: cspMatch.wetEdge ?? 0,
wetEdgeRadius: cspMatch.wetEdgeRadius,
@@ -554,19 +805,37 @@ export function getEffectiveBrushSettings(
grainMappingMode: cspMatch.grainMappingMode,
paperTextureScale: cspMatch.paperTextureScale,
paperTextureRotate: cspMatch.paperTextureRotate,
+ paperTextureOffsetX: cspMatch.paperTextureOffsetX,
+ paperTextureOffsetY: cspMatch.paperTextureOffsetY,
paperTextureMode: cspMatch.paperTextureMode,
paperTextureBrightness: cspMatch.paperTextureBrightness,
paperTextureContrast: cspMatch.paperTextureContrast,
paperTextureApplyEachPlot: cspMatch.paperTextureApplyEachPlot,
+ paperTextureEmphasizeDensity: cspMatch.paperTextureEmphasizeDensity,
paperTextureInverted: cspMatch.paperTextureInverted,
dualBrush: cspMatch.dualBrush,
- dualTipDataUrl: cspMatch.secondaryTipDataUrl,
+ dualBrushConfig: baseDualBrushConfig,
+ dualTipDataUrl: dualTipUrl,
dualTipImage: dualTipImg,
dualBrushCompositeMode: (cspMatch.dualBrushCompositeMode as BrushSettings['dualBrushCompositeMode']) || 'multiply',
dualSize: cspMatch.dualSize,
+ dualLinkSize: cspMatch.dualLinkSize,
dualSpacing: cspMatch.dualSpacing,
dualScatter: cspMatch.dualScatter,
+ dualThickness: cspMatch.dualThickness,
+ dualThicknessVertical: cspMatch.dualThicknessVertical,
dualAngle: cspMatch.dualAngle,
+ dualAngleDynamics: cspMatch.dualAngleDynamics,
+ dualAngleSensor: cspMatch.dualAngleSensor,
+ dualHardness: cspMatch.dualHardness,
+ dualDensity: cspMatch.dualDensity,
+ dualSubTips: resolvedDualSubTips,
+ dualSubTipImages,
+ dualSubTipOrder: cspMatch.dualSubTipOrder,
+ dualFlipH: cspMatch.dualFlipH,
+ dualFlipV: cspMatch.dualFlipV,
+ dualSpray: cspMatch.dualSpray,
+ dualIsRibbon: cspMatch.dualIsRibbon,
dualScale: cspMatch.dualScale,
dualSurfaceTextureId: cspMatch.dualSurfaceTextureId,
dualGrainDepth: cspMatch.dualGrainDepth,
@@ -575,20 +844,33 @@ export function getEffectiveBrushSettings(
bristle: cspMatch.bristle,
naturalPaint: cspMatch.naturalPaint,
impasto: cspMatch.impasto,
+ importWarnings: cspMatch.importWarnings,
useGpu: true,
...saved,
+ ...(mergedDualBrushConfig ? { dualBrushConfig: mergedDualBrushConfig } : {}),
};
}
}
// 3. Builtin brush
- const builtinCfg = getBuiltinBrushConfig(presetId as BrushPresetId);
+ const builtinCfg = getBuiltinBrushConfig(resolvedPresetId as BrushPresetId);
if (builtinCfg) {
+ const mergedDualBrushConfig = saved?.dualBrushConfig
+ ? {
+ ...builtinCfg.dualBrushConfig,
+ ...saved.dualBrushConfig,
+ tipDataUrl: saved.dualBrushConfig.tipDataUrl ?? builtinCfg.dualBrushConfig?.tipDataUrl,
+ tipImage: builtinCfg.dualBrushConfig?.tipImage,
+ subTips: saved.dualBrushConfig.subTips ?? builtinCfg.dualBrushConfig?.subTips,
+ subTipImages: builtinCfg.dualBrushConfig?.subTipImages,
+ }
+ : builtinCfg.dualBrushConfig;
return {
...NEUTRAL_BRUSH_DEFAULTS,
- preset: presetId,
+ preset: resolvedPresetId,
...builtinCfg,
...saved,
+ ...(mergedDualBrushConfig ? { dualBrushConfig: mergedDualBrushConfig } : {}),
};
}
@@ -599,13 +881,13 @@ export function getEffectiveBrushSettings(
...NEUTRAL_BRUSH_DEFAULTS,
preset: DEFAULT_BRUSH_PRESET_ID,
brushName: 'G-Pen',
- size: 8,
- minSizeFactor: 0.04,
+ size: 12,
+ minSizeFactor: 0.03,
flow: 1.0,
opacity: 1.0,
hardness: 1.0,
- spacing: 0.04,
- stabilization: 20,
+ spacing: 0.05,
+ stabilization: 10,
usePressure: true,
smoothing: true,
useGpu: true,
diff --git a/src/utils/brushPreview.ts b/src/utils/brushPreview.ts
index 1d11b28..ac4b9b4 100644
--- a/src/utils/brushPreview.ts
+++ b/src/utils/brushPreview.ts
@@ -7,11 +7,19 @@ import {
CspAngleDynamicsMode,
CspAntiAliasLevel,
CspBlendTipsMode,
+ CspBrushCombineMode,
+ CspDualBrushConfig,
CspPaperTextureMode,
+ CspSensorConfig,
CspSpraySettings,
+ CspSubTip,
+ CspSubTipOrder,
+ CspTaperSettings,
CspTipFlipMode,
+ DualBrushCompositeMode,
GrainMappingMode,
ImpastoSettings,
+ NaturalMixingMode,
NaturalPaintSettings,
Point,
SurfaceTextureId,
@@ -19,58 +27,116 @@ import {
import { getBuiltinBrushConfig } from './presetBrushes';
import {
getLegacyPencilPresetDefaults,
- getPaperGrain,
- getTintedTipMaster,
- getRadialDabMaster,
- drawSingleStamp,
evaluateFastSpline,
- dabHashFloat,
- computeGapAdjustedAlpha,
- resolveTipFlipSigns,
- applyCspPaperTextureAlpha,
+ renderCompleteStroke,
} from '../engine/BrushEngine';
-import {
- isNaturalPaintBrush,
- renderCompleteNaturalPaintStroke,
-} from '../engine/NaturalPaintRenderer';
+import { resolveDualBrushConfig } from '../engine/DualBrushEngine';
export interface BrushPreviewOptions {
preset?: BrushPresetId;
size?: number;
flow?: number;
+ brushDensity?: number;
opacity?: number;
grain?: number;
+ textureDensity?: number;
+ paperTexture?: string;
+ paperTextureImage?: HTMLImageElement;
paperTextureMode?: CspPaperTextureMode;
paperTextureScale?: number;
+ paperTextureRotate?: number;
+ paperTextureOffsetX?: number;
+ paperTextureOffsetY?: number;
paperTextureContrast?: number;
paperTextureBrightness?: number;
+ paperTextureApplyEachPlot?: boolean;
+ paperTextureEmphasizeDensity?: boolean;
paperTextureInverted?: boolean;
hardness?: number;
spacing?: number;
minSizeFactor?: number;
usePressure?: boolean;
+ useTilt?: boolean;
+ tiltScale?: number;
+ useVelocity?: boolean;
color?: string;
+ secondaryColor?: string;
backgroundColor?: string;
isSelected?: boolean;
tool?: 'brush' | 'eraser';
+ customTipDataUrl?: string;
customTipImage?: HTMLImageElement;
customTipAngle?: number;
customTipAngleDynamics?: CspAngleDynamicsMode;
+ customTipRotationRandomScale?: number;
+ isColorTip?: boolean;
+ isDualToneTip?: boolean;
+ isRibbon?: boolean;
+ subTips?: CspSubTip[];
+ subTipOrder?: CspSubTipOrder;
+ subTipImages?: HTMLImageElement[];
thickness?: number;
thicknessVertical?: boolean;
+ thicknessSensor?: CspSensorConfig;
flipH?: CspTipFlipMode;
flipV?: CspTipFlipMode;
blendTipsMode?: CspBlendTipsMode;
+ brushCombineMode?: CspBrushCombineMode;
adjustDensityByGap?: boolean;
antiAlias?: number;
pressureCurve?: [number, number][];
+ velocityCurve?: [number, number][];
+ sizeSensor?: CspSensorConfig;
+ opacitySensor?: CspSensorConfig;
+ densitySensor?: CspSensorConfig;
+ intervalSensor?: CspSensorConfig;
+ textureDensitySensor?: CspSensorConfig;
+ angleSensor?: CspSensorConfig;
+ scatterSensor?: CspSensorConfig;
spray?: CspSpraySettings;
+ taper?: CspTaperSettings;
dynamics?: BrushDynamics;
colorMixing?: boolean;
+ perceptualMixing?: boolean;
amountOfPaint?: number;
densityOfPaint?: number;
colorStretch?: number;
+ amountOfPaintSensor?: CspSensorConfig;
+ densityOfPaintSensor?: CspSensorConfig;
+ colorStretchSensor?: CspSensorConfig;
+ useBlur?: boolean;
+ blurStrength?: number;
+ mixingMode?: NaturalMixingMode;
wetEdge?: number;
+ wetEdgeRadius?: number;
+ wetEdgeAlphaPower?: number;
+ wetEdgeValuePower?: number;
+ dualBrush?: boolean;
+ dualBrushConfig?: CspDualBrushConfig;
+ dualBrushCompositeMode?: DualBrushCompositeMode | string;
+ dualTipDataUrl?: string;
+ dualTipImage?: HTMLImageElement;
+ dualSize?: number;
+ dualLinkSize?: boolean;
+ dualSpacing?: number;
+ dualScatter?: number;
+ dualThickness?: number;
+ dualThicknessVertical?: boolean;
+ dualAngle?: number;
+ dualAngleDynamics?: CspAngleDynamicsMode;
+ dualAngleSensor?: CspSensorConfig;
+ dualHardness?: number;
+ dualDensity?: number;
+ dualSubTips?: CspSubTip[];
+ dualSubTipImages?: HTMLImageElement[];
+ dualSubTipOrder?: CspSubTipOrder;
+ dualFlipH?: CspTipFlipMode;
+ dualFlipV?: CspTipFlipMode;
+ dualSpray?: CspSpraySettings;
+ dualIsRibbon?: boolean;
+ dualScale?: number;
+ dualSurfaceTextureId?: SurfaceTextureId;
+ dualGrainDepth?: number;
renderMode?: BrushRenderMode;
bristle?: BristleSettings;
naturalPaint?: NaturalPaintSettings;
@@ -111,7 +177,8 @@ export function calculatePreviewWidth(
}
/**
- * Renders an optimized Clip Studio Paint style S-curve brush preview.
+ * Renders an authentic Clip Studio Paint style S-curve stroke preview
+ * directly through the unified `renderCompleteStroke` pipeline.
*/
export function renderBrushStrokePreview(
canvas: HTMLCanvasElement,
@@ -123,8 +190,8 @@ export function renderBrushStrokePreview(
if (!canvas || cssWidth <= 0 || cssHeight <= 0) return;
const dpr = typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1;
- const targetWidth = Math.round(cssWidth * dpr);
- const targetHeight = Math.round(cssHeight * dpr);
+ const targetWidth = Math.max(1, Math.round(cssWidth * dpr));
+ const targetHeight = Math.max(1, Math.round(cssHeight * dpr));
if (canvas.width !== targetWidth || canvas.height !== targetHeight) {
canvas.width = targetWidth;
@@ -139,12 +206,12 @@ export function renderBrushStrokePreview(
!options.customTipImage && options.preset
? getBuiltinBrushConfig(options.preset) || getLegacyPencilPresetDefaults(options.preset)
: null;
- const tipImage = options.customTipImage || builtinCfg?.customTipImage;
+ const tipImage = options.customTipImage || builtinCfg?.customTipImage;
const size = options.size ?? builtinCfg?.size ?? 14;
- const flow = options.flow ?? builtinCfg?.flow ?? 0.85;
+ const flow = options.flow ?? options.brushDensity ?? builtinCfg?.flow ?? 0.85;
const opacity = options.opacity ?? builtinCfg?.opacity ?? 1.0;
- const grain = options.grain ?? builtinCfg?.grain ?? 0;
+ const grain = options.grain ?? options.textureDensity ?? builtinCfg?.grain ?? builtinCfg?.textureDensity ?? 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;
@@ -152,21 +219,27 @@ export function renderBrushStrokePreview(
const customTipAngle = options.customTipAngle ?? builtinCfg?.customTipAngle ?? 0;
const angleDynamics = options.customTipAngleDynamics ?? builtinCfg?.customTipAngleDynamics ?? 'none';
const dynamics = options.dynamics ?? builtinCfg?.dynamics;
+ const paperTextureImage = options.paperTextureImage ?? builtinCfg?.paperTextureImage;
const paperMode = options.paperTextureMode ?? builtinCfg?.paperTextureMode ?? 'subtract';
const paperScale = options.paperTextureScale ?? builtinCfg?.paperTextureScale ?? 1.0;
+ const paperRotate = options.paperTextureRotate ?? builtinCfg?.paperTextureRotate ?? 0;
const paperContrast = options.paperTextureContrast ?? builtinCfg?.paperTextureContrast ?? 0;
const paperBrightness = options.paperTextureBrightness ?? builtinCfg?.paperTextureBrightness ?? 0;
+ const paperApplyEachPlot = options.paperTextureApplyEachPlot ?? builtinCfg?.paperTextureApplyEachPlot;
+ const paperEmphasizeDensity = options.paperTextureEmphasizeDensity ?? builtinCfg?.paperTextureEmphasizeDensity;
const paperInverted = Boolean(options.paperTextureInverted ?? builtinCfg?.paperTextureInverted);
- const spacing = options.spacing ?? builtinCfg?.spacing ?? 0.045;
+ const spacing = options.spacing ?? builtinCfg?.spacing ?? 0.05;
const blendTipsMode = options.blendTipsMode ?? builtinCfg?.blendTipsMode ?? 'darken';
+ const brushCombineMode = options.brushCombineMode ?? builtinCfg?.brushCombineMode;
const adjustByGap = Boolean(options.adjustDensityByGap ?? builtinCfg?.adjustDensityByGap);
const aaLevel = clamp(
Math.round(options.antiAlias ?? builtinCfg?.antiAlias ?? 2),
0,
3
) as CspAntiAliasLevel;
- const isEraser = options.tool === 'eraser';
+ const isEraser = options.tool === 'eraser' || brushCombineMode === 'clear';
const strokeColor = options.color || '#ffffff';
+ const secondaryColor = options.secondaryColor || '#60a5fa';
const bgColor = options.backgroundColor || 'transparent';
const renderMode = options.renderMode ?? builtinCfg?.renderMode;
const bristleCfg = options.bristle ?? builtinCfg?.bristle;
@@ -174,10 +247,67 @@ export function renderBrushStrokePreview(
const impastoCfg = options.impasto ?? builtinCfg?.impasto;
const surfaceTextureId = options.surfaceTextureId ?? builtinCfg?.surfaceTextureId;
const grainMappingMode = options.grainMappingMode ?? builtinCfg?.grainMappingMode;
+ const isRibbon = Boolean(options.isRibbon ?? builtinCfg?.isRibbon);
+ const isColorTip = Boolean(options.isColorTip ?? builtinCfg?.isColorTip);
+ const isDualToneTip = Boolean(options.isDualToneTip ?? builtinCfg?.isDualToneTip);
+ const subTips = options.subTips ?? builtinCfg?.subTips;
+ const subTipOrder = options.subTipOrder ?? builtinCfg?.subTipOrder;
+ const subTipImages = options.subTipImages ?? builtinCfg?.subTipImages;
+ const taper = options.taper ?? builtinCfg?.taper;
+ const spray = options.spray ?? builtinCfg?.spray;
+ const wetEdge = options.wetEdge ?? builtinCfg?.wetEdge ?? 0;
+ const wetEdgeRadius = options.wetEdgeRadius ?? builtinCfg?.wetEdgeRadius;
+ const wetEdgeAlphaPower = options.wetEdgeAlphaPower ?? builtinCfg?.wetEdgeAlphaPower;
+ const wetEdgeValuePower = options.wetEdgeValuePower ?? builtinCfg?.wetEdgeValuePower;
+ const colorMixing = Boolean(options.colorMixing ?? builtinCfg?.colorMixing);
+ const perceptualMixing = options.perceptualMixing ?? builtinCfg?.perceptualMixing;
+ const amountOfPaint = options.amountOfPaint ?? builtinCfg?.amountOfPaint;
+ const densityOfPaint = options.densityOfPaint ?? builtinCfg?.densityOfPaint;
+ const colorStretch = options.colorStretch ?? builtinCfg?.colorStretch;
+ const mixingMode = options.mixingMode ?? builtinCfg?.mixingMode;
+ const usePressure = options.usePressure ?? builtinCfg?.usePressure ?? true;
+ const useTilt = Boolean(options.useTilt ?? builtinCfg?.useTilt);
+
+ const dualCfg = resolveDualBrushConfig({
+ size,
+ dualBrush: options.dualBrush ?? builtinCfg?.dualBrush,
+ dualBrushConfig: options.dualBrushConfig ?? builtinCfg?.dualBrushConfig,
+ dualBrushCompositeMode: options.dualBrushCompositeMode ?? builtinCfg?.dualBrushCompositeMode,
+ dualSize: options.dualSize ?? builtinCfg?.dualSize,
+ dualLinkSize: options.dualLinkSize ?? builtinCfg?.dualLinkSize,
+ dualScale: options.dualScale ?? builtinCfg?.dualScale,
+ dualSpacing: options.dualSpacing ?? builtinCfg?.dualSpacing,
+ dualScatter: options.dualScatter ?? builtinCfg?.dualScatter,
+ dualThickness: options.dualThickness ?? builtinCfg?.dualThickness,
+ dualThicknessVertical: options.dualThicknessVertical ?? builtinCfg?.dualThicknessVertical,
+ dualAngle: options.dualAngle ?? builtinCfg?.dualAngle,
+ dualAngleDynamics: options.dualAngleDynamics ?? builtinCfg?.dualAngleDynamics,
+ dualAngleSensor: options.dualAngleSensor ?? builtinCfg?.dualAngleSensor,
+ dualHardness: options.dualHardness ?? builtinCfg?.dualHardness,
+ dualDensity: options.dualDensity ?? builtinCfg?.dualDensity,
+ dualSubTips: options.dualSubTips ?? builtinCfg?.dualSubTips,
+ dualSubTipImages: options.dualSubTipImages ?? builtinCfg?.dualSubTipImages,
+ dualSubTipOrder: options.dualSubTipOrder ?? builtinCfg?.dualSubTipOrder,
+ dualFlipH: options.dualFlipH ?? builtinCfg?.dualFlipH,
+ dualFlipV: options.dualFlipV ?? builtinCfg?.dualFlipV,
+ dualSpray: options.dualSpray ?? builtinCfg?.dualSpray,
+ dualIsRibbon: options.dualIsRibbon ?? builtinCfg?.dualIsRibbon,
+ dualTipDataUrl: options.dualTipDataUrl ?? builtinCfg?.dualTipDataUrl,
+ dualTipImage: options.dualTipImage ?? builtinCfg?.dualTipImage,
+ });
const curveSig = options.pressureCurve
? options.pressureCurve.map((p) => `${p[0].toFixed(2)},${p[1].toFixed(2)}`).join(';')
: 'lin';
+ const taperSig = taper
+ ? `${taper.useIn ? 1 : 0}:${taper.inLength}:${taper.useOut ? 1 : 0}:${taper.outLength}:${taper.affectSize ? 1 : 0}:${taper.affectOpacity ? 1 : 0}`
+ : 'nt';
+ const dynSig = dynamics
+ ? `${dynamics.sizeJitter.toFixed(2)}:${dynamics.angleJitter.toFixed(2)}:${dynamics.scatter.toFixed(2)}:${dynamics.count}:${dynamics.colorJitterEnabled ? 1 : 0}:${dynamics.colorJitterPerStroke ? 1 : 0}:${dynamics.hueJitter.toFixed(2)}:${dynamics.saturationJitter.toFixed(2)}:${dynamics.brightnessJitter.toFixed(2)}:${dynamics.foregroundBackgroundJitter.toFixed(2)}`
+ : 'nd';
+ const dualSig = dualCfg
+ ? `d:${dualCfg.compositeMode}:${dualCfg.size ?? ''}:${dualCfg.sizeRatio ?? ''}:${dualCfg.spacing ?? ''}:${dualCfg.isRibbon ? 1 : 0}:${getTipCacheIdentity(dualCfg.tipImage)}`
+ : 'ndual';
const cacheKey = [
preset,
@@ -185,29 +315,53 @@ export function renderBrushStrokePreview(
flow.toFixed(2),
opacity.toFixed(2),
grain.toFixed(2),
+ paperMode,
+ paperScale.toFixed(2),
+ paperRotate.toFixed(1),
+ paperContrast.toFixed(1),
+ paperBrightness.toFixed(1),
+ paperApplyEachPlot ? 'p1' : 'p0',
+ paperInverted ? 'inv1' : 'inv0',
+ getTipCacheIdentity(paperTextureImage),
hardness.toFixed(2),
minSizeFactor.toFixed(2),
thickness.toFixed(2),
thicknessVertical ? 'tv' : 'th',
customTipAngle.toFixed(1),
+ angleDynamics,
spacing.toFixed(3),
String(aaLevel),
blendTipsMode,
+ brushCombineMode || 'normal',
adjustByGap ? 'gap1' : 'gap0',
options.flipH || 'n',
options.flipV || 'n',
- options.spray?.enabled ? `sp:${options.spray.size}:${options.spray.density}` : 'dab',
+ isRibbon ? 'rib1' : 'rib0',
+ isColorTip ? 'ct1' : 'ct0',
+ isDualToneTip ? 'dt1' : 'dt0',
+ subTipOrder || 'seq',
+ String(subTipImages?.length ?? subTips?.length ?? 0),
+ spray?.enabled ? `sp:${spray.size}:${spray.density}:${spray.particleSize ?? ''}` : 'dab',
+ taperSig,
+ dynSig,
+ dualSig,
getTipCacheIdentity(tipImage),
curveSig,
+ usePressure ? 'up1' : 'up0',
+ useTilt ? 'ut1' : 'ut0',
isEraser ? '1' : '0',
- options.wetEdge?.toFixed(2) || '0',
- options.colorMixing ? '1' : '0',
+ wetEdge.toFixed(2),
+ String(wetEdgeRadius ?? ''),
+ String(wetEdgeAlphaPower ?? ''),
+ String(wetEdgeValuePower ?? ''),
+ colorMixing ? `cm:${amountOfPaint ?? ''}:${densityOfPaint ?? ''}:${colorStretch ?? ''}` : 'cm0',
renderMode || 'stamp',
bristleCfg ? `${bristleCfg.profile}:${bristleCfg.count}:${bristleCfg.clumping.toFixed(2)}` : 'nb',
impastoCfg?.enabled ? `imp:${impastoCfg.depth.toFixed(2)}:${impastoCfg.gloss.toFixed(2)}` : 'ni',
naturalCfg?.enabled ? `np:${naturalCfg.paintLoad.toFixed(2)}:${naturalCfg.dryBrush.toFixed(2)}:${naturalCfg.depletionRate.toFixed(2)}` : 'nn',
surfaceTextureId || 'std',
strokeColor,
+ secondaryColor,
bgColor,
cssWidth,
cssHeight,
@@ -228,419 +382,253 @@ export function renderBrushStrokePreview(
const offCtx = offscreen.getContext('2d');
if (!offCtx) return;
- offCtx.save();
- offCtx.scale(dpr, dpr);
-
if (bgColor !== 'transparent') {
offCtx.fillStyle = bgColor;
- offCtx.fillRect(0, 0, cssWidth, cssHeight);
+ offCtx.fillRect(0, 0, targetWidth, targetHeight);
} else {
- offCtx.clearRect(0, 0, cssWidth, cssHeight);
+ offCtx.clearRect(0, 0, targetWidth, targetHeight);
}
- const padX = Math.max(12, Math.round(cssWidth * 0.1));
- const strokeLength = cssWidth - 2 * padX;
- const centerY = cssHeight / 2;
- const maxAmp = Math.min(cssHeight * 0.28, isLiveCard ? 14 : 9);
- const amp = Math.max(4, maxAmp);
- const displayWidth = calculatePreviewWidth(size, cssHeight, isLiveCard);
-
- const numSteps = Math.min(120, Math.max(60, Math.round(cssWidth * 0.65)));
- const pts: { x: number; y: number; width: number; pressure: number; tipAlpha: number }[] = [];
+ // Render in native DPR pixel space (identity transform) so isolated surface passes
+ // (wetEdge, stroke-level paper texture, dualBrush, brushCombineMode) stay crisp and pixel-exact.
+ const padX = Math.max(12, Math.round(cssWidth * 0.1)) * dpr;
+ const strokeLength = Math.max(8, targetWidth - 2 * padX);
+ const centerY = targetHeight / 2;
+ const maxAmp = Math.min(cssHeight * 0.28, isLiveCard ? 14 : 9) * dpr;
+ const amp = Math.max(4 * dpr, maxAmp);
+ const displayWidth = calculatePreviewWidth(size, cssHeight, isLiveCard) * dpr;
+ const previewScale = displayWidth / Math.max(1, size);
+
+ if (isEraser) {
+ offCtx.save();
+ offCtx.fillStyle = 'rgba(255, 255, 255, 0.22)';
+ offCtx.fillRect(padX - 4 * dpr, centerY - amp - 4 * dpr, strokeLength + 8 * dpr, (amp + 4 * dpr) * 2);
+ offCtx.restore();
+ }
+ const numSteps = Math.min(64, Math.max(28, Math.round(cssWidth * 0.35)));
+ const previewPts: Point[] = [];
for (let i = 0; i <= numSteps; i++) {
const u = i / numSteps;
const x = padX + u * strokeLength;
const y = centerY - Math.sin(2 * Math.PI * u) * amp;
const sineEnv = Math.sin(Math.PI * u);
- let pressure = Math.pow(Math.max(0, sineEnv), 0.75);
- if (options.pressureCurve) {
- pressure = evaluateFastSpline(pressure, options.pressureCurve);
- }
-
- const tipFactor = Math.min(1.0, sineEnv * 2.8);
- const effMinSize = Math.max(0.02, minSizeFactor * tipFactor);
- const tipAlpha = Math.min(1.0, sineEnv * 4.2);
- const w = Math.max(0.7, displayWidth * (effMinSize + (1 - effMinSize) * pressure));
-
- pts.push({ x, y, width: w, pressure, tipAlpha });
- }
-
- const isNaturalPreview =
- !isEraser &&
- isNaturalPaintBrush({
- renderMode,
- naturalPaint: naturalCfg,
- impasto: impastoCfg,
+ const rawPressure = usePressure ? Math.pow(Math.max(0, sineEnv), 0.75) : 1.0;
+ const sizePressure =
+ usePressure && options.pressureCurve
+ ? evaluateFastSpline(rawPressure, options.pressureCurve)
+ : rawPressure;
+
+ const effMinSize = usePressure ? Math.max(0.02, minSizeFactor) : 1.0;
+ const w = Math.max(0.75 * dpr, displayWidth * (effMinSize + (1 - effMinSize) * sizePressure));
+ const tiltX = useTilt ? Math.round(15 + 35 * u) : 0;
+ const tiltY = useTilt ? Math.round(10 * Math.sin(Math.PI * u)) : 0;
+
+ previewPts.push({
+ x,
+ y,
+ width: w,
+ pressure: rawPressure,
+ tiltX,
+ tiltY,
+ timestamp: i * 8,
});
+ }
- if (isNaturalPreview) {
- // Render authentic Natural Paint bristle-ribbon + impasto S-curve preview
- const previewPts: Point[] = pts.map((p) => ({
- x: p.x,
- y: p.y,
- width: Math.max(3, p.width),
- pressure: p.pressure,
- }));
- const previewNatural: NaturalPaintSettings = {
- enabled: true,
- spatialMixing: false, // Preview on clean swatch uses visible pigment even for zero-load blender
- pigmentMixingStrength: naturalCfg?.pigmentMixingStrength ?? 0.85,
- paintLoad: (naturalCfg?.paintLoad ?? 0.85) <= 0.05 ? 0.55 : (naturalCfg?.paintLoad ?? 0.85),
- depletionRate: naturalCfg?.depletionRate ?? 0.25,
- wetness: naturalCfg?.wetness ?? 0.5,
- viscosity: naturalCfg?.viscosity ?? 0.5,
- autoClean: true,
- chargePerPressure: naturalCfg?.chargePerPressure ?? 0.45,
- dryBrush: naturalCfg?.dryBrush ?? 0.3,
- granulation: naturalCfg?.granulation ?? 0,
- };
- const previewSettings: BrushSettings = {
- size: displayWidth,
- minSizeFactor,
- color: strokeColor,
- opacity,
- flow,
- spacing: Math.max(0.05, spacing),
- usePressure: true,
- smoothing: true,
- stabilization: 0,
- hardness,
- grain,
- textureDensity: grain,
- paperTextureScale: Math.max(0.35, paperScale * 0.65),
- paperTextureContrast: paperContrast,
- paperTextureBrightness: paperBrightness,
- paperTextureInverted: paperInverted,
- wetEdge: options.wetEdge ?? builtinCfg?.wetEdge ?? 0,
- renderMode: renderMode ?? 'bristle-ribbon',
- bristle: bristleCfg
- ? { ...bristleCfg, count: Math.min(24, Math.max(8, bristleCfg.count)) }
- : undefined,
- naturalPaint: previewNatural,
- impasto: impastoCfg,
- surfaceTextureId: surfaceTextureId ?? 'linen-canvas',
- grainMappingMode: grainMappingMode ?? 'canvas-locked',
- useGpu: false, // Deterministic fast CPU shading for tiny preview cards
- };
- renderCompleteNaturalPaintStroke(
- offCtx,
- previewPts,
- previewSettings,
- strokeColor,
- undefined,
- opacity,
- 'source-over',
- 1337
- );
- } else if (isEraser) {
- offCtx.save();
- offCtx.fillStyle = 'rgba(255, 255, 255, 0.18)';
- offCtx.fillRect(padX - 4, centerY - amp - 4, strokeLength + 8, (amp + 4) * 2);
-
- const eraserMaster = getRadialDabMaster(hardness, '#000000', true, displayWidth, aaLevel);
- const baseAngleRad = (customTipAngle * Math.PI) / 180;
- const effSpacing = clamp(spacing, 0.02, 0.25);
-
- 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.5));
- 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 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 stampW = thicknessVertical ? Math.max(1.0, curW * thickness) : Math.max(1.0, curW);
- const stampH = thicknessVertical ? Math.max(1.0, curW) : Math.max(1.0, curW * thickness);
- const alpha = clamp(opacity * flow * curTipAlpha, 0.05, 1.0);
- drawSingleStamp(
- offCtx,
- eraserMaster,
- curX,
- curY,
- stampW,
- stampH,
- baseAngleRad,
- alpha,
- true,
- false,
- false,
- false,
- 1,
- 1,
- aaLevel
- );
- }
+ // Scale taper lengths to fit the preview curve cleanly when taper is enabled
+ const scaledTaper: CspTaperSettings | undefined = taper
+ ? {
+ ...taper,
+ inLength: taper.inLength
+ ? Math.max(4 * dpr, Math.min(strokeLength * 0.38, taper.inLength * Math.min(1, previewScale * 1.4)))
+ : 0,
+ outLength: taper.outLength
+ ? Math.max(4 * dpr, Math.min(strokeLength * 0.38, taper.outLength * Math.min(1, previewScale * 1.4)))
+ : 0,
}
- }
- offCtx.restore();
- } else if (tipImage && tipImage.complete !== false && (tipImage.naturalWidth || tipImage.width) > 0) {
- const tip = tipImage;
- const rawAspect = (tip.naturalHeight || tip.height || 1) / (tip.naturalWidth || tip.width || 1);
- const baseAngleRad = (customTipAngle * Math.PI) / 180;
- const master = getTintedTipMaster(tip, strokeColor);
- const effSpacing = clamp(spacing, 0.02, 0.25);
- const baseFlow = computeGapAdjustedAlpha(flow, effSpacing, adjustByGap);
- const scatterAmt = clamp(dynamics?.scatter ?? 0, 0, 1.5);
- const sizeJit = clamp(dynamics?.sizeJitter ?? 0, 0, 1);
- const flowJit = clamp(dynamics?.flowJitter ?? 0, 0, 1);
- const angleJit = clamp(dynamics?.angleJitter ?? 0, 0, 1);
- const dabCount = Math.max(1, Math.min(3, Math.round(dynamics?.count ?? 1)));
-
- offCtx.save();
- let distanceAcc = 0;
- let dabIdx = 0;
- for (let i = 0; i < pts.length - 1; i++) {
- const p1 = pts[i];
- const p2 = pts[i + 1];
- const segDx = p2.x - p1.x;
- const segDy = p2.y - p1.y;
- const segDist = Math.hypot(segDx, segDy);
- const tangentAngle = Math.atan2(segDy, segDx);
- const nx = segDist > 1e-4 ? -segDy / segDist : 0;
- const ny = segDist > 1e-4 ? segDx / segDist : 1;
- 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 * segDx;
- const curY = p1.y + t * segDy;
- 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.5, curW * effSpacing);
- distanceAcc += segDist / stepCount;
- if (distanceAcc >= requiredStep) {
- distanceAcc = 0;
- dabIdx++;
-
- for (let k = 0; k < dabCount; k++) {
- const seq = dabIdx * 8 + k;
- let baseW = Math.max(1.2, curW);
- if (sizeJit > 0) {
- baseW *= Math.max(0.2, 1.0 - dabHashFloat(curX, curY, seq, 1) * sizeJit);
- }
- const stampW = thicknessVertical ? baseW * thickness : baseW;
- const stampH = thicknessVertical ? baseW * rawAspect : baseW * rawAspect * thickness;
-
- let alpha = clamp(opacity * baseFlow * curTipAlpha, 0.03, 1.0);
- if (flowJit > 0) {
- alpha *= Math.max(0.1, 1.0 - dabHashFloat(curX, curY, seq, 6) * flowJit);
- }
- if (grain > 0.01) {
- 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;
-
- let dabAngle = baseAngleRad;
- if (angleDynamics === 'direction' || angleDynamics === 'direction-random') {
- dabAngle += tangentAngle;
- }
- if (angleDynamics === 'random' || angleDynamics === 'direction-random' || angleJit > 0) {
- const jScale = angleDynamics === 'random' ? 1.0 : Math.max(angleJit, 0.3);
- dabAngle += (dabHashFloat(curX, curY, seq, 3) - 0.5) * Math.PI * 2 * jScale;
- }
-
- let drawX = curX;
- let drawY = curY;
- if (scatterAmt > 0) {
- const off = (dabHashFloat(curX, curY, seq, 4) * 2 - 1) * baseW * scatterAmt;
- drawX += nx * off;
- drawY += ny * off;
- }
-
- const flips = resolveTipFlipSigns(options.flipH, options.flipV, seq, drawX, drawY);
-
- if (options.spray?.enabled) {
- const pSize = Math.max(1, options.spray.size || 2);
- const radius = baseW * 0.5;
- const count = Math.max(1, options.spray.density || 4);
- for (let sp = 0; sp < count; sp++) {
- const r = radius * Math.sqrt(dabHashFloat(drawX, drawY, seq * 32 + sp, 91));
- const th = dabHashFloat(drawX, drawY, seq * 32 + sp, 92) * Math.PI * 2;
- drawSingleStamp(
- offCtx,
- master,
- drawX + r * Math.cos(th),
- drawY + r * Math.sin(th),
- pSize,
- pSize * rawAspect,
- dabAngle,
- alpha,
- false,
- false,
- false,
- false,
- flips.signX,
- flips.signY,
- aaLevel,
- blendTipsMode
- );
- }
- } else {
- drawSingleStamp(
- offCtx,
- master,
- drawX,
- drawY,
- stampW,
- stampH,
- dabAngle,
- alpha,
- false,
- false,
- false,
- false,
- flips.signX,
- flips.signY,
- aaLevel,
- blendTipsMode
- );
- }
- }
- }
+ : undefined;
+
+ // Scale spray particle size gently to fit thumbnail dimensions
+ const scaledSpray: CspSpraySettings | undefined = spray?.enabled
+ ? {
+ ...spray,
+ size: Math.max(1.2 * dpr, Math.min(displayWidth * 0.65, (spray.size || 2) * Math.min(1, previewScale * 1.25))),
+ particleSize: spray.particleSize
+ ? Math.max(1.0 * dpr, Math.min(displayWidth * 0.5, spray.particleSize * Math.min(1, previewScale * 1.25)))
+ : undefined,
}
- }
- offCtx.restore();
- } else {
- offCtx.save();
- const effHardness = clamp(hardness, 0.0, 1.0);
- const effSpacing = clamp(spacing, 0.02, 0.25);
- const effFlow = computeGapAdjustedAlpha(clamp(flow, 0.01, 1.0), effSpacing, adjustByGap);
- const master = getRadialDabMaster(effHardness, strokeColor, false, displayWidth, aaLevel);
- const baseAngleRad = (customTipAngle * Math.PI) / 180;
-
- if (options.wetEdge && options.wetEdge > 0.05) {
- const rimMaster = getRadialDabMaster(Math.min(1.0, effHardness + 0.12), strokeColor, false, displayWidth, aaLevel);
- let wetAcc = 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)) * (1.0 + options.wetEdge * 0.2);
- const curTipAlpha = p1.tipAlpha + t * (p2.tipAlpha - p1.tipAlpha);
-
- const requiredStep = Math.max(0.6, curW * effSpacing * 1.4);
- wetAcc += segDist / stepCount;
- if (wetAcc >= requiredStep) {
- wetAcc = 0;
- const baseW = Math.max(1.1, curW);
- const stampW = thicknessVertical ? baseW * thickness : baseW;
- const stampH = thicknessVertical ? baseW : baseW * thickness;
- const rimAlpha = clamp(
- opacity * effFlow * curTipAlpha * (0.2 + options.wetEdge * 0.4),
- 0.02,
- 1.0
- );
- drawSingleStamp(
- offCtx,
- rimMaster,
- curX,
- curY,
- stampW,
- stampH,
- baseAngleRad,
- rimAlpha,
- false,
- false,
- false,
- false,
- 1,
- 1,
- aaLevel,
- blendTipsMode
- );
- }
- }
+ : spray;
+
+ // Scale Dual Brush config proportionally to preview brush width
+ const scaledDualConfig: CspDualBrushConfig | undefined = dualCfg
+ ? {
+ ...dualCfg,
+ size:
+ dualCfg.size !== undefined
+ ? Math.max(1.0 * dpr, dualCfg.size * previewScale)
+ : undefined,
+ sizeRatio:
+ dualCfg.sizeRatio ??
+ (dualCfg.size !== undefined && size > 0 ? dualCfg.size / size : undefined),
}
- }
-
- 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 curTipAlpha = p1.tipAlpha + t * (p2.tipAlpha - p1.tipAlpha);
-
- const requiredStep = Math.max(0.45, curW * effSpacing);
- distanceAcc += segDist / stepCount;
- if (distanceAcc >= requiredStep) {
- distanceAcc = 0;
- const baseW = Math.max(0.7, curW);
- const stampW = thicknessVertical ? baseW * thickness : baseW;
- const stampH = thicknessVertical ? baseW : baseW * thickness;
- 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,
- curX,
- curY,
- stampW,
- stampH,
- baseAngleRad,
- alpha,
- false,
- false,
- false,
- false,
- 1,
- 1,
- aaLevel,
- blendTipsMode
- );
- }
+ : undefined;
+
+ // Natural paint preview adjustment: ensure zero-load blenders remain visible on clean swatch
+ const previewNatural: NaturalPaintSettings | undefined = naturalCfg?.enabled
+ ? {
+ ...naturalCfg,
+ spatialMixing: false,
+ paintLoad: naturalCfg.paintLoad <= 0.05 ? 0.55 : naturalCfg.paintLoad,
}
- }
- offCtx.restore();
- }
-
- offCtx.restore();
+ : naturalCfg;
+
+ // Pure CSP blender adjustment: ensure Amount=0 or mixingMode='smear' still shows a clear stroke on clean swatch
+ const isPureCspBlender =
+ colorMixing && ((amountOfPaint ?? 0.7) <= 0.05 || mixingMode === 'smear');
+ const previewAmountOfPaint = isPureCspBlender ? 0.55 : amountOfPaint;
+ const previewDensityOfPaint = isPureCspBlender ? Math.max(0.6, densityOfPaint ?? 0.6) : densityOfPaint;
+ const previewMixingMode = isPureCspBlender ? 'blend' : mixingMode;
+
+ const previewWetRadius =
+ wetEdge > 0.01
+ ? Math.max(1.2 * dpr, Math.min(4.5 * dpr, (wetEdgeRadius ?? 3.0) * Math.max(0.45, Math.min(1.0, previewScale)) * dpr))
+ : wetEdgeRadius;
+
+ // Avoid invisible preview if brushCombineMode is 'behind' over an opaque background fill
+ const previewCombineMode =
+ brushCombineMode === 'behind' && bgColor !== 'transparent'
+ ? undefined
+ : brushCombineMode === 'clear'
+ ? undefined
+ : brushCombineMode;
+
+ const previewSettings: BrushSettings = {
+ size: displayWidth,
+ minSizeFactor,
+ color: strokeColor,
+ secondaryColor,
+ opacity,
+ flow,
+ brushDensity: options.brushDensity ?? flow,
+ adjustDensityByGap: adjustByGap,
+ blendTipsMode,
+ brushCombineMode: previewCombineMode,
+ spacing: clamp(spacing, 0.02, 0.65),
+ hardness,
+ thickness,
+ thicknessVertical,
+ thicknessSensor: options.thicknessSensor ?? builtinCfg?.thicknessSensor,
+ flipH: options.flipH ?? builtinCfg?.flipH,
+ flipV: options.flipV ?? builtinCfg?.flipV,
+ antiAlias: aaLevel,
+ usePressure,
+ useTilt,
+ tiltScale: options.tiltScale ?? builtinCfg?.tiltScale,
+ useVelocity: options.useVelocity ?? builtinCfg?.useVelocity,
+ smoothing: true,
+ stabilization: 0,
+ postCorrection: 0,
+ sharpCorners: true,
+ pressureCurve: options.pressureCurve ?? builtinCfg?.pressureCurve,
+ velocityCurve: options.velocityCurve ?? builtinCfg?.velocityCurve,
+ sizeSensor: options.sizeSensor ?? builtinCfg?.sizeSensor,
+ opacitySensor: options.opacitySensor ?? builtinCfg?.opacitySensor,
+ densitySensor: options.densitySensor ?? builtinCfg?.densitySensor,
+ intervalSensor: options.intervalSensor ?? builtinCfg?.intervalSensor,
+ textureDensitySensor: options.textureDensitySensor ?? builtinCfg?.textureDensitySensor,
+ angleSensor: options.angleSensor ?? builtinCfg?.angleSensor,
+ scatterSensor: options.scatterSensor ?? builtinCfg?.scatterSensor,
+ customTipDataUrl: options.customTipDataUrl,
+ customTipImage: tipImage,
+ customTipAngle,
+ customTipAngleDynamics: angleDynamics,
+ customTipRotationRandomScale:
+ options.customTipRotationRandomScale ?? builtinCfg?.customTipRotationRandomScale,
+ isColorTip,
+ isDualToneTip,
+ isRibbon,
+ subTips,
+ subTipOrder,
+ subTipImages,
+ spray: scaledSpray,
+ taper: scaledTaper,
+ dynamics,
+ colorMixing,
+ perceptualMixing: perceptualMixing ?? true,
+ amountOfPaint: previewAmountOfPaint,
+ densityOfPaint: previewDensityOfPaint,
+ colorStretch,
+ amountOfPaintSensor: options.amountOfPaintSensor ?? builtinCfg?.amountOfPaintSensor,
+ densityOfPaintSensor: options.densityOfPaintSensor ?? builtinCfg?.densityOfPaintSensor,
+ colorStretchSensor: options.colorStretchSensor ?? builtinCfg?.colorStretchSensor,
+ useBlur: options.useBlur ?? builtinCfg?.useBlur,
+ blurStrength: options.blurStrength ?? builtinCfg?.blurStrength,
+ mixingMode: previewMixingMode,
+ wetEdge,
+ wetEdgeRadius: previewWetRadius,
+ wetEdgeAlphaPower,
+ wetEdgeValuePower,
+ grain,
+ textureDensity: grain,
+ paperTexture: options.paperTexture ?? builtinCfg?.paperTexture,
+ paperTextureImage,
+ surfaceTextureId,
+ grainMappingMode,
+ paperTextureMode: paperMode,
+ paperTextureScale: Math.max(0.25, paperScale * 0.75),
+ paperTextureRotate: paperRotate,
+ paperTextureOffsetX: options.paperTextureOffsetX ?? builtinCfg?.paperTextureOffsetX,
+ paperTextureOffsetY: options.paperTextureOffsetY ?? builtinCfg?.paperTextureOffsetY,
+ paperTextureBrightness: paperBrightness,
+ paperTextureContrast: paperContrast,
+ paperTextureApplyEachPlot: paperApplyEachPlot,
+ paperTextureEmphasizeDensity: paperEmphasizeDensity,
+ paperTextureInverted: paperInverted,
+ dualBrush: Boolean(scaledDualConfig?.enabled),
+ dualBrushConfig: scaledDualConfig,
+ dualBrushCompositeMode: scaledDualConfig?.compositeMode,
+ dualTipDataUrl: scaledDualConfig?.tipDataUrl,
+ dualTipImage: scaledDualConfig?.tipImage,
+ dualSize: scaledDualConfig?.size,
+ dualLinkSize: scaledDualConfig?.linkSizeWithMain,
+ dualSpacing: scaledDualConfig?.spacing,
+ dualScatter: scaledDualConfig?.scatter,
+ dualThickness: scaledDualConfig?.thickness,
+ dualThicknessVertical: scaledDualConfig?.thicknessVertical,
+ dualAngle: scaledDualConfig?.angle,
+ dualAngleDynamics: scaledDualConfig?.angleDynamics,
+ dualAngleSensor: scaledDualConfig?.angleSensor,
+ dualHardness: scaledDualConfig?.hardness,
+ dualDensity: scaledDualConfig?.density,
+ dualSubTips: scaledDualConfig?.subTips,
+ dualSubTipImages: scaledDualConfig?.subTipImages,
+ dualSubTipOrder: scaledDualConfig?.subTipOrder,
+ dualFlipH: scaledDualConfig?.flipH,
+ dualFlipV: scaledDualConfig?.flipV,
+ dualSpray: scaledDualConfig?.spray,
+ dualIsRibbon: scaledDualConfig?.isRibbon,
+ dualScale: options.dualScale ?? builtinCfg?.dualScale,
+ dualSurfaceTextureId: options.dualSurfaceTextureId ?? builtinCfg?.dualSurfaceTextureId,
+ dualGrainDepth: options.dualGrainDepth ?? builtinCfg?.dualGrainDepth,
+ renderMode,
+ bristle: bristleCfg
+ ? { ...bristleCfg, count: Math.min(24, Math.max(8, bristleCfg.count)) }
+ : undefined,
+ naturalPaint: previewNatural,
+ impasto: impastoCfg,
+ useGpu: false, // Deterministic fast CPU rendering for thumbnails & preview cards
+ };
+
+ renderCompleteStroke(
+ offCtx,
+ previewPts,
+ previewSettings,
+ isEraser ? 'eraser' : 'brush',
+ 'color',
+ false,
+ offscreen
+ );
ctx.clearRect(0, 0, targetWidth, targetHeight);
ctx.drawImage(offscreen, 0, 0);
diff --git a/src/utils/brushStorage.ts b/src/utils/brushStorage.ts
index 4135317..f93a897 100644
--- a/src/utils/brushStorage.ts
+++ b/src/utils/brushStorage.ts
@@ -1,4 +1,4 @@
-import { CspBrush, BrushSettings } from '../types/editor';
+import { CspBrush, BrushSettings, CspDualBrushConfig } from '../types/editor';
import {
handleIndexedDbError,
safeLocalStorageGetItem,
@@ -26,12 +26,45 @@ function emitCustomBrushesChanged(): void {
}
}
+function sanitizeDualBrushConfigForStorage(
+ cfg: CspDualBrushConfig | undefined,
+ stripHeavyDataUrls: boolean
+): CspDualBrushConfig | undefined {
+ if (!cfg) return undefined;
+ const {
+ tipImage: _tipImg,
+ subTipImages: _subImgs,
+ tipDataUrl,
+ subTips,
+ ...rest
+ } = cfg;
+ if (stripHeavyDataUrls) {
+ return rest;
+ }
+ return {
+ ...rest,
+ ...(tipDataUrl !== undefined ? { tipDataUrl } : {}),
+ ...(subTips !== undefined ? { subTips } : {}),
+ };
+}
+
+function sanitizeBrushForIndexedDb(brush: CspBrush): CspBrush {
+ if (!brush.dualBrushConfig) return brush;
+ return {
+ ...brush,
+ dualBrushConfig: sanitizeDualBrushConfigForStorage(brush.dualBrushConfig, false),
+ };
+}
+
function hasHeavyBrushAssets(brush: CspBrush): boolean {
return Boolean(
brush.tipDataUrl ||
brush.secondaryTipDataUrl ||
brush.paperTexture ||
- (brush.subTips && brush.subTips.length > 0)
+ (brush.subTips && brush.subTips.length > 0) ||
+ (brush.dualSubTips && brush.dualSubTips.length > 0) ||
+ brush.dualBrushConfig?.tipDataUrl ||
+ (brush.dualBrushConfig?.subTips && brush.dualBrushConfig.subTips.length > 0)
);
}
@@ -43,24 +76,34 @@ function stripHeavyBrushAssets(brush: CspBrush): CspBrush {
tipDataUrl: _tip,
secondaryTipDataUrl: _sec,
subTips: _subs,
+ dualSubTips: _dualSubs,
paperTexture: _tex,
+ dualBrushConfig,
...lightweight
} = brush;
- return lightweight;
+ const lightDual = sanitizeDualBrushConfigForStorage(dualBrushConfig, true);
+ return lightDual ? { ...lightweight, dualBrushConfig: lightDual } : lightweight;
}
function preloadAllBrushAssets(brush: CspBrush): void {
if (brush.tipDataUrl) {
preloadTipImage(brush.tipDataUrl).catch(() => {});
}
- if (brush.secondaryTipDataUrl) {
- preloadTipImage(brush.secondaryTipDataUrl).catch(() => {});
+ const dualTipUrl = brush.secondaryTipDataUrl || brush.dualBrushConfig?.tipDataUrl;
+ if (dualTipUrl) {
+ preloadTipImage(dualTipUrl).catch(() => {});
}
if (brush.subTips) {
for (const st of brush.subTips) {
if (st.dataUrl) preloadTipImage(st.dataUrl).catch(() => {});
}
}
+ const dualSubTipList = brush.dualSubTips || brush.dualBrushConfig?.subTips;
+ if (dualSubTipList) {
+ for (const dst of dualSubTipList) {
+ if (dst.dataUrl) preloadTipImage(dst.dataUrl).catch(() => {});
+ }
+ }
if (brush.paperTexture) {
preloadTipImage(brush.paperTexture).catch(() => {});
}
@@ -234,16 +277,17 @@ export async function loadCustomBrushes(): Promise<CspBrush[]> {
* Only lightweight metadata/IDs are mirrored to localStorage (never tip/texture data URLs).
*/
export async function saveCustomBrush(brush: CspBrush): Promise<void> {
- preloadAllBrushAssets(brush);
- const existingIdx = _cachedCustomBrushes.findIndex((b) => b.id === brush.id);
+ const cleanBrush = sanitizeBrushForIndexedDb(brush);
+ preloadAllBrushAssets(cleanBrush);
+ const existingIdx = _cachedCustomBrushes.findIndex((b) => b.id === cleanBrush.id);
if (existingIdx >= 0) {
_cachedCustomBrushes = [
..._cachedCustomBrushes.slice(0, existingIdx),
- brush,
+ cleanBrush,
..._cachedCustomBrushes.slice(existingIdx + 1),
];
} else {
- _cachedCustomBrushes = [..._cachedCustomBrushes, brush];
+ _cachedCustomBrushes = [..._cachedCustomBrushes, cleanBrush];
}
_hasLoadedCustomBrushes = true;
@@ -252,16 +296,16 @@ export async function saveCustomBrush(brush: CspBrush): Promise<void> {
await new Promise<void>((resolve, reject) => {
const transaction = db.transaction([STORE_NAME], 'readwrite');
const store = transaction.objectStore(STORE_NAME);
- const request = store.put(brush);
+ const request = store.put(cleanBrush);
request.onsuccess = () => resolve();
request.onerror = () => reject(request.error);
transaction.onerror = () => reject(transaction.error);
});
} catch (err) {
- handleIndexedDbError(err, `custom brush "${brush.name}"`);
+ handleIndexedDbError(err, `custom brush "${cleanBrush.name}"`);
}
- syncLightweightIndexToLocalStorage(brush);
+ syncLightweightIndexToLocalStorage(cleanBrush);
emitCustomBrushesChanged();
}
@@ -358,10 +402,11 @@ export async function prepareBrushSettingsForCsp(brush: CspBrush): Promise<Parti
}
let dualTipImg: HTMLImageElement | undefined = undefined;
- if (brush.secondaryTipDataUrl) {
+ const dualTipUrl = brush.secondaryTipDataUrl || brush.dualBrushConfig?.tipDataUrl;
+ if (dualTipUrl) {
dualTipImg =
- getPreloadedTipImage(brush.secondaryTipDataUrl) ||
- (await preloadTipImage(brush.secondaryTipDataUrl).catch(() => undefined));
+ getPreloadedTipImage(dualTipUrl) ||
+ (await preloadTipImage(dualTipUrl).catch(() => undefined));
}
let subTipImages: HTMLImageElement[] | undefined = undefined;
@@ -375,6 +420,18 @@ export async function prepareBrushSettingsForCsp(brush: CspBrush): Promise<Parti
}
}
+ let dualSubTipImages: HTMLImageElement[] | undefined = undefined;
+ const resolvedDualSubTips = brush.dualSubTips || brush.dualBrushConfig?.subTips;
+ if (resolvedDualSubTips && resolvedDualSubTips.length > 0) {
+ dualSubTipImages = [];
+ for (const dst of resolvedDualSubTips) {
+ const img =
+ getPreloadedTipImage(dst.dataUrl) ||
+ (await preloadTipImage(dst.dataUrl).catch(() => undefined));
+ if (img) dualSubTipImages.push(img);
+ }
+ }
+
let paperTextureImage: HTMLImageElement | undefined = undefined;
if (brush.paperTexture) {
paperTextureImage =
@@ -386,6 +443,8 @@ export async function prepareBrushSettingsForCsp(brush: CspBrush): Promise<Parti
preset: brush.id,
brushName: brush.name,
size: brush.size,
+ brushSizeUnit: brush.brushSizeUnit,
+ brushSizeSpecifiedByScreen: brush.brushSizeSpecifiedByScreen,
minSizeFactor: brush.minSizeFactor,
flow: brush.flow,
brushDensity: brush.brushDensity,
@@ -397,6 +456,7 @@ export async function prepareBrushSettingsForCsp(brush: CspBrush): Promise<Parti
hardness: brush.hardness,
thickness: brush.thickness,
thicknessVertical: brush.thicknessVertical,
+ thicknessSensor: brush.thicknessSensor,
antiAlias: brush.antiAlias,
stabilization: brush.stabilization,
postCorrection: brush.postCorrection,
@@ -405,6 +465,7 @@ export async function prepareBrushSettingsForCsp(brush: CspBrush): Promise<Parti
customTipDataUrl: brush.tipDataUrl,
customTipImage: tipImg,
isColorTip: brush.isColorTip,
+ isDualToneTip: brush.isDualToneTip,
flipH: brush.flipH,
flipV: brush.flipV,
customTipAngle: brush.angle,
@@ -422,6 +483,8 @@ export async function prepareBrushSettingsForCsp(brush: CspBrush): Promise<Parti
sizeSensor: brush.sizeSensor,
opacitySensor: brush.opacitySensor,
densitySensor: brush.densitySensor,
+ intervalSensor: brush.intervalSensor,
+ textureDensitySensor: brush.textureDensitySensor,
bristleSplaySensor: brush.bristleSplaySensor,
paintLoadSensor: brush.paintLoadSensor,
grainPenetrationSensor: brush.grainPenetrationSensor,
@@ -435,6 +498,12 @@ export async function prepareBrushSettingsForCsp(brush: CspBrush): Promise<Parti
amountOfPaint: brush.amountOfPaint ?? 0.7,
densityOfPaint: brush.densityOfPaint ?? 0.8,
colorStretch: brush.colorStretch ?? 0.6,
+ amountOfPaintSensor: brush.amountOfPaintSensor,
+ densityOfPaintSensor: brush.densityOfPaintSensor,
+ colorStretchSensor: brush.colorStretchSensor,
+ mixGroundColor: brush.mixGroundColor,
+ useBlur: brush.useBlur,
+ blurStrength: brush.blurStrength,
mixingMode: brush.mixingMode ?? 'blend',
wetEdge: brush.wetEdge ?? 0,
wetEdgeRadius: brush.wetEdgeRadius,
@@ -448,19 +517,43 @@ export async function prepareBrushSettingsForCsp(brush: CspBrush): Promise<Parti
grainMappingMode: brush.grainMappingMode,
paperTextureScale: brush.paperTextureScale,
paperTextureRotate: brush.paperTextureRotate,
+ paperTextureOffsetX: brush.paperTextureOffsetX,
+ paperTextureOffsetY: brush.paperTextureOffsetY,
paperTextureMode: brush.paperTextureMode,
paperTextureBrightness: brush.paperTextureBrightness,
paperTextureContrast: brush.paperTextureContrast,
paperTextureApplyEachPlot: brush.paperTextureApplyEachPlot,
+ paperTextureEmphasizeDensity: brush.paperTextureEmphasizeDensity,
paperTextureInverted: brush.paperTextureInverted,
dualBrush: brush.dualBrush,
- dualTipDataUrl: brush.secondaryTipDataUrl,
+ dualBrushConfig: brush.dualBrushConfig
+ ? {
+ ...brush.dualBrushConfig,
+ tipImage: dualTipImg ?? brush.dualBrushConfig.tipImage,
+ subTipImages: dualSubTipImages ?? brush.dualBrushConfig.subTipImages,
+ }
+ : undefined,
+ dualTipDataUrl: dualTipUrl,
dualTipImage: dualTipImg,
dualBrushCompositeMode: (brush.dualBrushCompositeMode as BrushSettings['dualBrushCompositeMode']) || 'multiply',
dualSize: brush.dualSize,
+ dualLinkSize: brush.dualLinkSize,
dualSpacing: brush.dualSpacing,
dualScatter: brush.dualScatter,
+ dualThickness: brush.dualThickness,
+ dualThicknessVertical: brush.dualThicknessVertical,
dualAngle: brush.dualAngle,
+ dualAngleDynamics: brush.dualAngleDynamics,
+ dualAngleSensor: brush.dualAngleSensor,
+ dualHardness: brush.dualHardness,
+ dualDensity: brush.dualDensity,
+ dualSubTips: resolvedDualSubTips,
+ dualSubTipImages,
+ dualSubTipOrder: brush.dualSubTipOrder,
+ dualFlipH: brush.dualFlipH,
+ dualFlipV: brush.dualFlipV,
+ dualSpray: brush.dualSpray,
+ dualIsRibbon: brush.dualIsRibbon,
dualScale: brush.dualScale,
dualSurfaceTextureId: brush.dualSurfaceTextureId,
dualGrainDepth: brush.dualGrainDepth,
@@ -469,6 +562,7 @@ export async function prepareBrushSettingsForCsp(brush: CspBrush): Promise<Parti
bristle: brush.bristle,
naturalPaint: brush.naturalPaint,
impasto: brush.impasto,
+ importWarnings: brush.importWarnings,
useGpu: true,
};
}
diff --git a/src/utils/canvasUtils.ts b/src/utils/canvasUtils.ts
index 93da23b..96c80e1 100644
--- a/src/utils/canvasUtils.ts
+++ b/src/utils/canvasUtils.ts
@@ -54,7 +54,11 @@ export function calculateStrokeWidth(
const minRatio = Math.max(0, Math.min(1.0, minSizeFactor ?? 0));
const dynamicWidth = baseSize * (minRatio + (1.0 - minRatio) * curvePressure) * velocityScale;
- return Math.max(0.1, dynamicWidth);
+ // Keep light continuous pen contact (> 0.005) above sub-pixel invisible collapse (width = 0.1),
+ // while still allowing flick taper tails (pressure <= 0.005) to razor-taper down to 0.1px.
+ const contactFloor =
+ effectivePressure > 0.005 ? Math.min(baseSize, Math.max(0.35, baseSize * minRatio)) : 0.1;
+ return Math.max(contactFloor, dynamicWidth);
}
/**
diff --git a/src/utils/colorMixingEngine.ts b/src/utils/colorMixingEngine.ts
index 97d439a..0d5d31a 100644
--- a/src/utils/colorMixingEngine.ts
+++ b/src/utils/colorMixingEngine.ts
@@ -81,29 +81,24 @@ export function rgbToHex(r: number, g: number, b: number): string {
}
// -------------------------------------------------------------
-// Color Science: sRGB <-> Linear RGB <-> OKLab (Fast LUT + Float Precision)
+// Color Science: Linear RGB <-> OKLab (Fast LUT + Float Precision)
// -------------------------------------------------------------
-const SRGB_TO_LINEAR_LUT = new Float32Array(256);
-for (let i = 0; i < 256; i++) {
- const v = i / 255;
- SRGB_TO_LINEAR_LUT[i] = v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
+const CBRT_LUT_SIZE = 2048;
+const CBRT_LUT_MAX = 1.05;
+const CBRT_LUT_SCALE = CBRT_LUT_SIZE / CBRT_LUT_MAX;
+const CBRT_LUT = new Float32Array(CBRT_LUT_SIZE + 1);
+for (let i = 0; i <= CBRT_LUT_SIZE; i++) {
+ CBRT_LUT[i] = Math.cbrt((i / CBRT_LUT_SIZE) * CBRT_LUT_MAX);
}
-function srgbToLinear(c: number): number {
- if (c <= 0) return 0;
- if (c >= 255) return 1;
- const idx = c | 0;
- const frac = c - idx;
- if (idx >= 255) return 1;
- const v0 = SRGB_TO_LINEAR_LUT[idx];
- return frac > 0 ? v0 + (SRGB_TO_LINEAR_LUT[idx + 1] - v0) * frac : v0;
-}
-
-function linearToSrgbFloat(c: number): number {
- const clamped = c <= 0 ? 0 : c >= 1 ? 1 : c;
- const v = clamped <= 0.0031308 ? 12.92 * clamped : 1.055 * Math.pow(clamped, 1 / 2.4) - 0.055;
- return v <= 0 ? 0 : v >= 1 ? 255 : v * 255;
+function fastCbrtPos(x: number): number {
+ if (x <= 0) return 0;
+ if (x >= CBRT_LUT_MAX) return Math.cbrt(x);
+ const pos = x * CBRT_LUT_SCALE;
+ const idx = pos | 0;
+ const v0 = CBRT_LUT[idx];
+ return v0 + (CBRT_LUT[idx + 1] - v0) * (pos - idx);
}
/**
@@ -114,9 +109,9 @@ export function linearRgbToOklab(r: number, g: number, b: number): OklabColor {
const m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b;
const s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b;
- const l_ = Math.cbrt(l);
- const m_ = Math.cbrt(m);
- const s_ = Math.cbrt(s);
+ const l_ = fastCbrtPos(l);
+ const m_ = fastCbrtPos(m);
+ const s_ = fastCbrtPos(s);
return {
L: 0.2104542553 * l_ + 0.793617785 * m_ - 0.0040720468 * s_,
@@ -146,163 +141,81 @@ export function oklabToLinearRgb(L: number, a: number, b: number): { r: number;
import { SparseTileGrid, TILE_SIZE, globalTileGrid } from './tileEngine';
import type { BristleProfilePreset, BristleSettings, NaturalMixingMode, NaturalPaintSettings } from '../types/editor';
+import {
+ PIGMENT_LATENT_SIZE,
+ pigmentLatentToSrgbOut,
+ pigmentMixRgbOut,
+ srgbToPigmentLatentOut,
+} from './pigmentEngine';
// -------------------------------------------------------------
-// 7-Band Spectral Kubelka-Munk Pigment Engine (420–660nm, CIE 1931 D65)
-// Closed-form physical pigment reflectance decomposition + Kubelka-Munk K/S
-// absorption/scattering blending + OKLab perceptual lightness/chroma polish.
+// Physical Kubelka-Munk 4-Pigment + Residual Latent Space Engine
+// Uses a calibrated 64x64x64 3D pigment concentration LUT + 20-term cubic
+// Bernstein polynomial (7-float latent space: 4 physical pigment concentrations
+// + 3 linear sRGB residuals).
// Guarantees:
-// - Blue + Yellow -> vibrant emerald/leaf green (no gray mud)
-// - Green + Magenta -> warm golden-amber / coral (no dead olive-gray)
-// - Red + Blue -> rich royal violet; Red + Yellow -> luminous orange
+// - Blue + Yellow -> vibrant natural Green (no muddy gray)
+// - Dark Navy / Crimson / Emerald + White -> luminous Cerulean / Magenta / Teal
+// - Red + Blue -> rich Violet; Red + Yellow -> luminous Orange
// - Exact self-mix invariance: mix(c, c, t) === c
-// - Exact neutral-gray invariance: Black + White stays pure neutral gray
+// - Exact neutral-gray invariance: Black + White stays strictly neutral gray
// -------------------------------------------------------------
-const KM_LO = 0.025;
-const KM_SPAN = 0.97;
-const KM_INV_SPAN = 1.0 / KM_SPAN;
-const KM_EXP = 0.72;
-const KM_INV_EXP = 1.0 / KM_EXP;
-
-// Normalized CIE 1931 D65 band-to-Linear-sRGB weights (columns sum to 1.0)
-const SPEC_W_R = new Float32Array([0.140, 0.030, -0.145, -0.080, 0.365, 0.465, 0.225]);
-const SPEC_W_G = new Float32Array([-0.050, 0.045, 0.250, 0.500, 0.300, -0.018, -0.027]);
-const SPEC_W_B = new Float32Array([0.340, 0.550, 0.145, -0.028, -0.007, 0.000, 0.000]);
-{
- let sr = 0;
- let sg = 0;
- let sb = 0;
- for (let i = 0; i < 7; i++) {
- sr += SPEC_W_R[i];
- sg += SPEC_W_G[i];
- sb += SPEC_W_B[i];
- }
- for (let i = 0; i < 7; i++) {
- SPEC_W_R[i] /= sr;
- SPEC_W_G[i] /= sg;
- SPEC_W_B[i] /= sb;
- }
+const EXP_NEG_LUT_SIZE = 512;
+const EXP_NEG_LUT_MAX = 8.0;
+const EXP_NEG_LUT_SCALE = EXP_NEG_LUT_SIZE / EXP_NEG_LUT_MAX;
+const ONE_MINUS_EXP_NEG_LUT = new Float32Array(EXP_NEG_LUT_SIZE + 1);
+for (let i = 0; i <= EXP_NEG_LUT_SIZE; i++) {
+ ONE_MINUS_EXP_NEG_LUT[i] = 1.0 - Math.exp(-(i / EXP_NEG_LUT_SIZE) * EXP_NEG_LUT_MAX);
}
-// Calibrated physical artist-pigment reflectance curves across 7 bands (420..660nm)
-const BASIS_R = new Float32Array([0.025, 0.018, 0.020, 0.035, 0.360, 0.965, 0.990]);
-const BASIS_G = new Float32Array([0.020, 0.040, 0.420, 0.980, 0.900, 0.420, 0.060]);
-const BASIS_B = new Float32Array([0.880, 0.990, 0.780, 0.340, 0.025, 0.020, 0.055]);
-const BASIS_C = new Float32Array([0.720, 0.980, 0.990, 0.840, 0.140, 0.025, 0.025]);
-const BASIS_M = new Float32Array([0.780, 0.500, 0.055, 0.025, 0.640, 0.975, 0.990]);
-const BASIS_Y = new Float32Array([0.018, 0.022, 0.280, 0.930, 0.995, 0.990, 0.980]);
-
-// Module-level scratch buffers for zero-allocation hot-loop pigment mixing
-const _kmSp1 = new Float32Array(7);
-const _kmSp2 = new Float32Array(7);
-const _kmSpM = new Float32Array(7);
-
-function linearRgbToReflectance(r: number, g: number, b: number, out: Float32Array): void {
- const rr = KM_LO + r * KM_SPAN;
- const gg = KM_LO + g * KM_SPAN;
- const bb = KM_LO + b * KM_SPAN;
-
- if (rr <= gg && rr <= bb) {
- const w = rr;
- if (gg <= bb) {
- const c = gg - rr;
- const p = bb - gg;
- for (let i = 0; i < 7; i++) out[i] = w + c * BASIS_C[i] + p * BASIS_B[i];
- } else {
- const c = bb - rr;
- const p = gg - bb;
- for (let i = 0; i < 7; i++) out[i] = w + c * BASIS_C[i] + p * BASIS_G[i];
- }
- } else if (gg <= rr && gg <= bb) {
- const w = gg;
- if (rr <= bb) {
- const c = rr - gg;
- const p = bb - rr;
- for (let i = 0; i < 7; i++) out[i] = w + c * BASIS_M[i] + p * BASIS_B[i];
- } else {
- const c = bb - gg;
- const p = rr - bb;
- for (let i = 0; i < 7; i++) out[i] = w + c * BASIS_M[i] + p * BASIS_R[i];
- }
- } else {
- const w = bb;
- if (rr <= gg) {
- const c = rr - bb;
- const p = gg - rr;
- for (let i = 0; i < 7; i++) out[i] = w + c * BASIS_Y[i] + p * BASIS_G[i];
- } else {
- const c = gg - bb;
- const p = rr - gg;
- for (let i = 0; i < 7; i++) out[i] = w + c * BASIS_Y[i] + p * BASIS_R[i];
- }
- }
+function fastOneMinusExpNeg(x: number): number {
+ if (x <= 0) return 0;
+ if (x >= EXP_NEG_LUT_MAX) return 1.0;
+ const pos = x * EXP_NEG_LUT_SCALE;
+ const idx = pos | 0;
+ const v0 = ONE_MINUS_EXP_NEG_LUT[idx];
+ return v0 + (ONE_MINUS_EXP_NEG_LUT[idx + 1] - v0) * (pos - idx);
}
/**
- * Encodes an sRGB color [0..255] into 7-band compressed Kubelka-Munk K/S + 3 linear residual channels
- * (10 floats written starting at `offset`). Useful for fast separable spectral convolution (Pigment Blur).
+ * Encodes an sRGB color [0..255] into 7 Kubelka-Munk pigment latent components
+ * written starting at `offset`. Useful for separable pigment convolution (Pigment Blur).
*/
-export function encodeSrgbToSpectralKS(
+export function encodeSrgbToPigmentLatent(
r: number,
g: number,
b: number,
out: Float32Array,
offset: number
): void {
- const lr = srgbToLinear(r);
- const lg = srgbToLinear(g);
- const lb = srgbToLinear(b);
- linearRgbToReflectance(lr, lg, lb, _kmSp1);
-
- let br = 0;
- let bg = 0;
- let bb = 0;
- for (let i = 0; i < 7; i++) {
- const sp = _kmSp1[i];
- br += sp * SPEC_W_R[i];
- bg += sp * SPEC_W_G[i];
- bb += sp * SPEC_W_B[i];
- const rc = sp < 0.02 ? 0.02 : sp > 0.998 ? 0.998 : sp;
- const ks = ((1 - rc) * (1 - rc)) / (2 * rc);
- out[offset + i] = Math.pow(ks, KM_EXP);
- }
- out[offset + 7] = lr - (br - KM_LO) * KM_INV_SPAN;
- out[offset + 8] = lg - (bg - KM_LO) * KM_INV_SPAN;
- out[offset + 9] = lb - (bb - KM_LO) * KM_INV_SPAN;
+ srgbToPigmentLatentOut(r, g, b, out, offset);
}
/**
- * Decodes 7-band compressed Kubelka-Munk K/S + 3 linear residual channels back to sRGB [0..255].
+ * Decodes 7 Kubelka-Munk pigment latent components back to sRGB [0..255].
*/
-export function decodeSpectralKSToSrgb(
+export function decodePigmentLatentToSrgb(
buf: Float32Array,
offset: number,
out: RgbColor
): RgbColor {
- let mr = 0;
- let mg = 0;
- let mb = 0;
- for (let i = 0; i < 7; i++) {
- const cks = buf[offset + i];
- const ks = cks > 0 ? Math.pow(cks, KM_INV_EXP) : 0;
- const ref = 1 + ks - Math.sqrt(ks * ks + 2 * ks);
- mr += ref * SPEC_W_R[i];
- mg += ref * SPEC_W_G[i];
- mb += ref * SPEC_W_B[i];
- }
- const lr = (mr - KM_LO) * KM_INV_SPAN + buf[offset + 7];
- const lg = (mg - KM_LO) * KM_INV_SPAN + buf[offset + 8];
- const lb = (mb - KM_LO) * KM_INV_SPAN + buf[offset + 9];
- out.r = linearToSrgbFloat(lr);
- out.g = linearToSrgbFloat(lg);
- out.b = linearToSrgbFloat(lb);
- return out;
+ return pigmentLatentToSrgbOut(buf, offset, out);
}
/**
- * Zero-allocation 7-Band Spectral Kubelka-Munk pigment mixer writing directly into `out`.
- * `pigmentStrength` in [0..1]: 0.0 = regular sRGB blend, 1.0 = full physical Kubelka-Munk pigment blend.
+ * Backward-compatible alias for encoding sRGB into 7-channel pigment latent space.
+ */
+export const encodeSrgbToSpectralKS = encodeSrgbToPigmentLatent;
+
+/**
+ * Backward-compatible alias for decoding 7-channel pigment latent space to sRGB.
+ */
+export const decodeSpectralKSToSrgb = decodePigmentLatentToSrgb;
+
+/**
+ * Zero-allocation physical Kubelka-Munk pigment mixer writing directly into `out`.
+ * `pigmentStrength` in [0..1]: 0.0 = regular sRGB blend, 1.0 = full physical pigment blend.
*/
export function mixPigmentRgbOut(
r1In: number,
@@ -315,157 +228,23 @@ export function mixPigmentRgbOut(
pigmentStrength: number,
out: RgbColor
): RgbColor {
- const t = weight2 <= 0 ? 0 : weight2 >= 1 ? 1 : weight2;
- if (t <= 0.0001) {
- out.r = r1In;
- out.g = g1In;
- out.b = b1In;
- return out;
- }
- if (t >= 0.9999) {
- out.r = r2In;
- out.g = g2In;
- out.b = b2In;
- return out;
- }
-
- const strength = pigmentStrength <= 0 ? 0 : pigmentStrength >= 1 ? 1 : pigmentStrength;
- if (strength <= 0.005) {
- out.r = r1In + (r2In - r1In) * t;
- out.g = g1In + (g2In - g1In) * t;
- out.b = b1In + (b2In - b1In) * t;
- return out;
- }
-
- const invT = 1 - t;
- const r1 = srgbToLinear(r1In);
- const g1 = srgbToLinear(g1In);
- const b1 = srgbToLinear(b1In);
-
- const r2 = srgbToLinear(r2In);
- const g2 = srgbToLinear(g2In);
- const b2 = srgbToLinear(b2In);
-
- // 1. Decompose into 7-band physical reflectance spectra + exact linear RGB residuals
- linearRgbToReflectance(r1, g1, b1, _kmSp1);
- linearRgbToReflectance(r2, g2, b2, _kmSp2);
-
- let b1r = 0;
- let b1g = 0;
- let b1b = 0;
- let b2r = 0;
- let b2g = 0;
- let b2b = 0;
- for (let i = 0; i < 7; i++) {
- const s1 = _kmSp1[i];
- const s2 = _kmSp2[i];
- const wr = SPEC_W_R[i];
- const wg = SPEC_W_G[i];
- const wb = SPEC_W_B[i];
- b1r += s1 * wr;
- b1g += s1 * wg;
- b1b += s1 * wb;
- b2r += s2 * wr;
- b2g += s2 * wg;
- b2b += s2 * wb;
- }
- const res1r = r1 - (b1r - KM_LO) * KM_INV_SPAN;
- const res1g = g1 - (b1g - KM_LO) * KM_INV_SPAN;
- const res1b = b1 - (b1b - KM_LO) * KM_INV_SPAN;
- const res2r = r2 - (b2r - KM_LO) * KM_INV_SPAN;
- const res2g = g2 - (b2g - KM_LO) * KM_INV_SPAN;
- const res2b = b2 - (b2b - KM_LO) * KM_INV_SPAN;
-
- // 2. Perceptual luminance concentration (physical tinting strength balance)
- const Y1 = 0.2126 * r1 + 0.7152 * g1 + 0.0722 * b1;
- const Y2 = 0.2126 * r2 + 0.7152 * g2 + 0.0722 * b2;
- const conc1 = Math.pow(0.06 + Y1, 0.36);
- const conc2 = Math.pow(0.06 + Y2, 0.36);
- const w1Raw = invT * conc1;
- const w1 = w1Raw / (w1Raw + t * conc2);
- const w2 = 1 - w1;
-
- // 3. Mix in Kubelka-Munk K/S absorption-scattering space and reconstruct Linear RGB
- let mr = 0;
- let mg = 0;
- let mb = 0;
- for (let i = 0; i < 7; i++) {
- const a = _kmSp1[i] < 0.02 ? 0.02 : _kmSp1[i] > 0.998 ? 0.998 : _kmSp1[i];
- const b = _kmSp2[i] < 0.02 ? 0.02 : _kmSp2[i] > 0.998 ? 0.998 : _kmSp2[i];
- const ks1 = Math.pow(((1 - a) * (1 - a)) / (2 * a), KM_EXP);
- const ks2 = Math.pow(((1 - b) * (1 - b)) / (2 * b), KM_EXP);
- const ks = Math.pow(ks1 * w1 + ks2 * w2, KM_INV_EXP);
- const ref = 1 + ks - Math.sqrt(ks * ks + 2 * ks);
- _kmSpM[i] = ref;
- mr += ref * SPEC_W_R[i];
- mg += ref * SPEC_W_G[i];
- mb += ref * SPEC_W_B[i];
- }
-
- const mixR = Math.max(0, (mr - KM_LO) * KM_INV_SPAN + res1r * invT + res2r * t);
- const mixG = Math.max(0, (mg - KM_LO) * KM_INV_SPAN + res1g * invT + res2g * t);
- const mixB = Math.max(0, (mb - KM_LO) * KM_INV_SPAN + res1b * invT + res2b * t);
-
- // 4. OKLab perceptual lightness & chroma polish with hue-safe gamut clamping
- const lab1 = linearRgbToOklab(r1, g1, b1);
- const lab2 = linearRgbToOklab(r2, g2, b2);
- const labM = linearRgbToOklab(mixR, mixG, mixB);
-
- const targetL = lab1.L * invT + lab2.L * t;
- const tunedL = Math.max(0, Math.min(1, labM.L * 0.40 + targetL * 0.60));
-
- const c1Chroma = Math.hypot(lab1.a, lab1.b);
- const c2Chroma = Math.hypot(lab2.a, lab2.b);
- const mChroma = Math.hypot(labM.a, labM.b);
- const linChroma = c1Chroma * invT + c2Chroma * t;
- let chromaBoost = 1.0;
- if (mChroma > 0.008 && linChroma > mChroma) {
- const targetC = mChroma + (linChroma - mChroma) * 0.50;
- chromaBoost = Math.min(1.65, targetC / mChroma);
- }
- const aM = labM.a * chromaBoost;
- const bM = labM.b * chromaBoost;
-
- let finalLinear = oklabToLinearRgb(tunedL, aM, bM);
- const minCh = Math.min(finalLinear.r, finalLinear.g, finalLinear.b);
- const maxCh = Math.max(finalLinear.r, finalLinear.g, finalLinear.b);
- if (minCh < 0 || maxCh > 1) {
- const lGray = oklabToLinearRgb(tunedL, 0, 0).r;
- let scale = 1.0;
- if (minCh < 0 && lGray > minCh) {
- scale = Math.min(scale, lGray / (lGray - minCh));
- }
- if (maxCh > 1 && maxCh > lGray) {
- scale = Math.min(scale, (1 - lGray) / (maxCh - lGray));
- }
- scale = Math.max(0, Math.min(1, scale));
- finalLinear = oklabToLinearRgb(tunedL, aM * scale, bM * scale);
- }
-
- const subR = linearToSrgbFloat(finalLinear.r);
- const subG = linearToSrgbFloat(finalLinear.g);
- const subB = linearToSrgbFloat(finalLinear.b);
-
- if (strength >= 0.995) {
- out.r = subR;
- out.g = subG;
- out.b = subB;
- return out;
- }
-
- const linR = r1In + (r2In - r1In) * t;
- const linG = g1In + (g2In - g1In) * t;
- const linB = b1In + (b2In - b1In) * t;
- out.r = linR + (subR - linR) * strength;
- out.g = linG + (subG - linG) * strength;
- out.b = linB + (subB - linB) * strength;
- return out;
+ return pigmentMixRgbOut(r1In, g1In, b1In, r2In, g2In, b2In, weight2, pigmentStrength, out);
}
+// Reusable scratch buffers for zero-allocation pigment sampling & deposit in LayerPixelSampler
+const _samplerLatTmp = new Float32Array(PIGMENT_LATENT_SIZE);
+const _samplerLatAcc = new Float32Array(PIGMENT_LATENT_SIZE);
+const _samplerRgbScratch: RgbColor = { r: 0, g: 0, b: 0 };
+const _sample5TapR = new Uint8Array(5);
+const _sample5TapG = new Uint8Array(5);
+const _sample5TapB = new Uint8Array(5);
+const _sample5TapW = new Float32Array(5);
+
/**
- * Subtractive Pigment Mixing (Physical Paint Simulation — 7-Band Spectral Kubelka-Munk + OKLab).
- * Simulates real-world physical absorption and spectral overlap where Blue + Yellow = vibrant Green,
- * Green + Magenta = warm golden-amber/coral, Red + Blue = Violet, Red + Yellow = Orange.
+ * Subtractive Pigment Mixing (Physical Kubelka-Munk 4-Pigment Latent Engine).
+ * Simulates real-world paint absorption and scattering where Blue + Yellow = vibrant Green,
+ * Dark Navy / Crimson / Emerald + White = luminous Cerulean / Magenta / Teal,
+ * Red + Blue = Violet, Red + Yellow = Orange.
*/
export function mixSubtractivePigments(
c1: RgbColor,
@@ -477,8 +256,8 @@ export function mixSubtractivePigments(
}
/**
- * Blends two colors with configurable subtractive pigment mixing strength [0..1].
- * 0.0 = standard linear RGB interpolation; 1.0 = full 7-band Kubelka-Munk + OKLab pigment mixing.
+ * Blends two colors with configurable physical pigment mixing strength [0..1].
+ * 0.0 = standard linear RGB interpolation; 1.0 = full Kubelka-Munk pigment mixing.
*/
export function mixPigmentsWithStrength(
c1: RgbColor,
@@ -505,6 +284,8 @@ export class LayerPixelSampler {
private layerId: string | null = null;
private useLazyTiles: boolean = false;
private lazyTiles: Map<number, Uint8ClampedArray> = new Map();
+ private lastTileKey: number = -1;
+ private lastTileBuf: Uint8ClampedArray | null = null;
private origTilesMap: Map<number, ImageData> | null = null;
private tilesX: number = 1;
@@ -556,8 +337,13 @@ export class LayerPixelSampler {
*/
private getOrLoadTile(tx: number, ty: number): Uint8ClampedArray {
const key = ty * this.tilesX + tx;
+ if (key === this.lastTileKey && this.lastTileBuf) return this.lastTileBuf;
let buf = this.lazyTiles.get(key);
- if (buf) return buf;
+ if (buf) {
+ this.lastTileKey = key;
+ this.lastTileBuf = buf;
+ return buf;
+ }
if (this.origTilesMap) {
const origImg = this.origTilesMap.get(ty * 65536 + tx);
@@ -622,8 +408,15 @@ export class LayerPixelSampler {
/**
* Samples average color and opacity in microseconds with ZERO full-canvas GPU pipeline flushes!
+ * When `usePigment` is true, averages multi-color neighborhoods in 7-channel Kubelka-Munk
+ * pigment latent space so crossing Blue|Yellow yields vibrant Green instead of RGB gray.
*/
- public sampleColor(cx: number, cy: number, radius: number): RgbaColor {
+ public sampleColor(
+ cx: number,
+ cy: number,
+ radius: number,
+ usePigment: boolean = false
+ ): RgbaColor {
const r = Math.max(1, Math.min(64, Math.round(radius)));
const ix = Math.round(cx);
const iy = Math.round(cy);
@@ -661,6 +454,7 @@ export class LayerPixelSampler {
let weightSum = 0;
let radialAreaSum = 0;
const rSq = r * r;
+ if (usePigment) _samplerLatAcc.fill(0);
for (let y = y0; y <= y1; y += step) {
const dy = y - iy;
@@ -678,9 +472,14 @@ export class LayerPixelSampler {
const alpha = tile[idx + 3];
if (alpha > 4) {
const radialWeight = geomWeight * (alpha / 255);
- sumR += tile[idx] * radialWeight;
- sumG += tile[idx + 1] * radialWeight;
- sumB += tile[idx + 2] * radialWeight;
+ if (usePigment) {
+ srgbToPigmentLatentOut(tile[idx], tile[idx + 1], tile[idx + 2], _samplerLatTmp, 0);
+ for (let c = 0; c < 7; c++) _samplerLatAcc[c] += _samplerLatTmp[c] * radialWeight;
+ } else {
+ sumR += tile[idx] * radialWeight;
+ sumG += tile[idx + 1] * radialWeight;
+ sumB += tile[idx + 2] * radialWeight;
+ }
weightSum += radialWeight;
}
}
@@ -688,6 +487,17 @@ export class LayerPixelSampler {
}
if (weightSum > 0.001 && radialAreaSum > 0) {
+ if (usePigment) {
+ const invW = 1 / weightSum;
+ for (let c = 0; c < 7; c++) _samplerLatAcc[c] *= invW;
+ pigmentLatentToSrgbOut(_samplerLatAcc, 0, _samplerRgbScratch);
+ return {
+ r: _samplerRgbScratch.r,
+ g: _samplerRgbScratch.g,
+ b: _samplerRgbScratch.b,
+ a: Math.min(1.0, weightSum / radialAreaSum),
+ };
+ }
return {
r: sumR / weightSum,
g: sumG / weightSum,
@@ -724,6 +534,7 @@ export class LayerPixelSampler {
let weightSum = 0;
let radialAreaSum = 0;
const rSq = r * r;
+ if (usePigment) _samplerLatAcc.fill(0);
for (let y = y0; y <= y1; y += step) {
const dy = y - iy;
@@ -738,11 +549,15 @@ export class LayerPixelSampler {
const idx = (rowOffset + x) * 4;
const alpha = this.data[idx + 3];
if (alpha > 4) {
- // Inverse-distance radial weight
const radialWeight = geomWeight * (alpha / 255);
- sumR += this.data[idx] * radialWeight;
- sumG += this.data[idx + 1] * radialWeight;
- sumB += this.data[idx + 2] * radialWeight;
+ if (usePigment) {
+ srgbToPigmentLatentOut(this.data[idx], this.data[idx + 1], this.data[idx + 2], _samplerLatTmp, 0);
+ for (let c = 0; c < 7; c++) _samplerLatAcc[c] += _samplerLatTmp[c] * radialWeight;
+ } else {
+ sumR += this.data[idx] * radialWeight;
+ sumG += this.data[idx + 1] * radialWeight;
+ sumB += this.data[idx + 2] * radialWeight;
+ }
weightSum += radialWeight;
}
}
@@ -750,6 +565,17 @@ export class LayerPixelSampler {
}
if (weightSum > 0.001 && radialAreaSum > 0) {
+ if (usePigment) {
+ const invW = 1 / weightSum;
+ for (let c = 0; c < 7; c++) _samplerLatAcc[c] *= invW;
+ pigmentLatentToSrgbOut(_samplerLatAcc, 0, _samplerRgbScratch);
+ return {
+ r: _samplerRgbScratch.r,
+ g: _samplerRgbScratch.g,
+ b: _samplerRgbScratch.b,
+ a: Math.min(1.0, weightSum / radialAreaSum),
+ };
+ }
return {
r: sumR / weightSum,
g: sumG / weightSum,
@@ -772,7 +598,8 @@ export class LayerPixelSampler {
r: number,
g: number,
b: number,
- a: number
+ a: number,
+ pigmentStrength: number = 0
): void {
if (a <= 0.002 || this.width <= 0 || this.height <= 0) return;
const rad = Math.max(1, Math.min(64, Math.round(radius)));
@@ -789,8 +616,8 @@ export class LayerPixelSampler {
const radSq = rad * rad;
const invRadSq = 1 / radSq;
- // Contiguous pixel fill for <= 14px, dense 2x2 block fill for larger brushes (zero Swiss-cheese gaps!)
const step = rad > 14 ? 2 : 1;
+ const usePigment = pigmentStrength > 0.005;
const blendPixel = (px: number, py: number, effAlpha: number) => {
if (this.useLazyTiles) {
@@ -799,10 +626,17 @@ export class LayerPixelSampler {
const dstA = tile[idx + 3] / 255;
const outA = effAlpha + dstA * (1 - effAlpha);
if (outA > 0.001) {
- const inv = 1 / outA;
- tile[idx] = Math.round((r * effAlpha + tile[idx] * dstA * (1 - effAlpha)) * inv);
- tile[idx + 1] = Math.round((g * effAlpha + tile[idx + 1] * dstA * (1 - effAlpha)) * inv);
- tile[idx + 2] = Math.round((b * effAlpha + tile[idx + 2] * dstA * (1 - effAlpha)) * inv);
+ if (usePigment && dstA > 0.002) {
+ pigmentMixRgbOut(tile[idx], tile[idx + 1], tile[idx + 2], r, g, b, effAlpha / outA, pigmentStrength, _samplerRgbScratch);
+ tile[idx] = Math.round(_samplerRgbScratch.r);
+ tile[idx + 1] = Math.round(_samplerRgbScratch.g);
+ tile[idx + 2] = Math.round(_samplerRgbScratch.b);
+ } else {
+ const inv = 1 / outA;
+ tile[idx] = Math.round((r * effAlpha + tile[idx] * dstA * (1 - effAlpha)) * inv);
+ tile[idx + 1] = Math.round((g * effAlpha + tile[idx + 1] * dstA * (1 - effAlpha)) * inv);
+ tile[idx + 2] = Math.round((b * effAlpha + tile[idx + 2] * dstA * (1 - effAlpha)) * inv);
+ }
tile[idx + 3] = Math.round(Math.min(255, outA * 255));
}
} else {
@@ -810,10 +644,17 @@ export class LayerPixelSampler {
const dstA = this.data[idx + 3] / 255;
const outA = effAlpha + dstA * (1 - effAlpha);
if (outA > 0.001) {
- const inv = 1 / outA;
- this.data[idx] = Math.round((r * effAlpha + this.data[idx] * dstA * (1 - effAlpha)) * inv);
- this.data[idx + 1] = Math.round((g * effAlpha + this.data[idx + 1] * dstA * (1 - effAlpha)) * inv);
- this.data[idx + 2] = Math.round((b * effAlpha + this.data[idx + 2] * dstA * (1 - effAlpha)) * inv);
+ if (usePigment && dstA > 0.002) {
+ pigmentMixRgbOut(this.data[idx], this.data[idx + 1], this.data[idx + 2], r, g, b, effAlpha / outA, pigmentStrength, _samplerRgbScratch);
+ this.data[idx] = Math.round(_samplerRgbScratch.r);
+ this.data[idx + 1] = Math.round(_samplerRgbScratch.g);
+ this.data[idx + 2] = Math.round(_samplerRgbScratch.b);
+ } else {
+ const inv = 1 / outA;
+ this.data[idx] = Math.round((r * effAlpha + this.data[idx] * dstA * (1 - effAlpha)) * inv);
+ this.data[idx + 1] = Math.round((g * effAlpha + this.data[idx + 1] * dstA * (1 - effAlpha)) * inv);
+ this.data[idx + 2] = Math.round((b * effAlpha + this.data[idx + 2] * dstA * (1 - effAlpha)) * inv);
+ }
this.data[idx + 3] = Math.round(Math.min(255, outA * 255));
}
}
@@ -846,7 +687,13 @@ export class LayerPixelSampler {
* Zero-allocation O(1) per-bristle color sample (5-tap cross when radius >= 2, 1-tap otherwise).
* Writes directly into `out` to eliminate GC churn across 32-64 bristles per step.
*/
- public samplePointFast(cx: number, cy: number, radius: number, out: RgbaColor): RgbaColor {
+ public samplePointFast(
+ cx: number,
+ cy: number,
+ radius: number,
+ out: RgbaColor,
+ usePigment: boolean = false
+ ): RgbaColor {
const w = this.width;
const h = this.height;
const ix = Math.round(cx);
@@ -861,11 +708,54 @@ export class LayerPixelSampler {
}
const rOff = radius >= 2.2 ? Math.min(6, Math.round(radius * 0.6)) : 0;
+ if (rOff === 0) {
+ let alpha = 0;
+ let tr = 0;
+ let tg = 0;
+ let tb = 0;
+ if (this.useLazyTiles) {
+ const tile = this.getOrLoadTile(ix >> 8, iy >> 8);
+ const idx = (((iy & 255) << 8) + (ix & 255)) << 2;
+ tr = tile[idx];
+ tg = tile[idx + 1];
+ tb = tile[idx + 2];
+ alpha = tile[idx + 3];
+ } else {
+ const idx = (iy * w + ix) << 2;
+ tr = this.data[idx];
+ tg = this.data[idx + 1];
+ tb = this.data[idx + 2];
+ alpha = this.data[idx + 3];
+ }
+ if (alpha > 4) {
+ out.r = tr;
+ out.g = tg;
+ out.b = tb;
+ out.a = alpha * (1 / 255);
+ } else {
+ out.r = 255;
+ out.g = 255;
+ out.b = 255;
+ out.a = 0;
+ }
+ return out;
+ }
+
+ // Collect 5-tap cross into local scalars so we only pay 7-channel pigment encoding when taps truly differ in color
+ const tapR = _sample5TapR;
+ const tapG = _sample5TapG;
+ const tapB = _sample5TapB;
+ const tapW = _sample5TapW;
+ let tapCount = 0;
let sumR = 0;
let sumG = 0;
let sumB = 0;
let weightSum = 0;
let totalSamples = 0;
+ let refR = -1;
+ let refG = 0;
+ let refB = 0;
+ let differs = false;
const readTap = (px: number, py: number, geomW: number) => {
if (px < 0 || px >= w || py < 0 || py >= h) return;
@@ -889,26 +779,63 @@ export class LayerPixelSampler {
alpha = this.data[idx + 3];
}
if (alpha > 4) {
- const aw = geomW * (alpha / 255);
+ const aw = geomW * (alpha * (1 / 255));
sumR += tr * aw;
sumG += tg * aw;
sumB += tb * aw;
weightSum += aw;
+ if (usePigment) {
+ tapR[tapCount] = tr;
+ tapG[tapCount] = tg;
+ tapB[tapCount] = tb;
+ tapW[tapCount] = aw;
+ if (refR < 0) {
+ refR = tr;
+ refG = tg;
+ refB = tb;
+ } else if (!differs) {
+ const l1 = Math.abs(tr - refR) + Math.abs(tg - refG) + Math.abs(tb - refB);
+ if (l1 > 12) differs = true;
+ }
+ tapCount++;
+ }
}
};
readTap(ix, iy, 2.0);
- if (rOff > 0) {
- readTap(ix - rOff, iy, 1.0);
- readTap(ix + rOff, iy, 1.0);
- readTap(ix, iy - rOff, 1.0);
- readTap(ix, iy + rOff, 1.0);
- }
+ readTap(ix - rOff, iy, 1.0);
+ readTap(ix + rOff, iy, 1.0);
+ readTap(ix, iy - rOff, 1.0);
+ readTap(ix, iy + rOff, 1.0);
if (weightSum > 0.001 && totalSamples > 0) {
- out.r = sumR / weightSum;
- out.g = sumG / weightSum;
- out.b = sumB / weightSum;
+ const invW = 1 / weightSum;
+ if (usePigment && differs && tapCount > 1) {
+ _samplerLatAcc.fill(0);
+ for (let k = 0; k < tapCount; k++) {
+ const tw = tapW[k];
+ srgbToPigmentLatentOut(tapR[k], tapG[k], tapB[k], _samplerLatTmp, 0);
+ _samplerLatAcc[0] += _samplerLatTmp[0] * tw;
+ _samplerLatAcc[1] += _samplerLatTmp[1] * tw;
+ _samplerLatAcc[2] += _samplerLatTmp[2] * tw;
+ _samplerLatAcc[3] += _samplerLatTmp[3] * tw;
+ _samplerLatAcc[4] += _samplerLatTmp[4] * tw;
+ _samplerLatAcc[5] += _samplerLatTmp[5] * tw;
+ _samplerLatAcc[6] += _samplerLatTmp[6] * tw;
+ }
+ _samplerLatAcc[0] *= invW;
+ _samplerLatAcc[1] *= invW;
+ _samplerLatAcc[2] *= invW;
+ _samplerLatAcc[3] *= invW;
+ _samplerLatAcc[4] *= invW;
+ _samplerLatAcc[5] *= invW;
+ _samplerLatAcc[6] *= invW;
+ pigmentLatentToSrgbOut(_samplerLatAcc, 0, out);
+ } else {
+ out.r = sumR * invW;
+ out.g = sumG * invW;
+ out.b = sumB * invW;
+ }
out.a = Math.min(1.0, weightSum / totalSamples);
} else {
out.r = 255;
@@ -922,7 +849,12 @@ export class LayerPixelSampler {
/**
* Zero-allocation O(1) bilinear single-pixel sample for 2D SpatialTipMixer.
*/
- public sampleBilinearFast(cx: number, cy: number, out: RgbaColor): RgbaColor {
+ public sampleBilinearFast(
+ cx: number,
+ cy: number,
+ out: RgbaColor,
+ usePigment: boolean = false
+ ): RgbaColor {
const w = this.width;
const h = this.height;
if (w <= 0 || h <= 0 || cx < -0.5 || cy < -0.5 || cx >= w - 0.5 || cy >= h - 0.5) {
@@ -945,10 +877,88 @@ export class LayerPixelSampler {
const w01 = (1 - fx) * fy;
const w11 = fx * fy;
+ // Fast path: all 4 bilinear corners inside the same 256x256 tile (99%+ of samples -> 1 cached tile hit)
+ if (this.useLazyTiles && (x0 >> 8) === (x1 >> 8) && (y0 >> 8) === (y1 >> 8)) {
+ const tile = this.getOrLoadTile(x0 >> 8, y0 >> 8);
+ const r0 = (y0 & 255) << 8;
+ const r1 = (y1 & 255) << 8;
+ const c0 = x0 & 255;
+ const c1 = x1 & 255;
+ const i00 = (r0 + c0) << 2;
+ const i10 = (r0 + c1) << 2;
+ const i01 = (r1 + c0) << 2;
+ const i11 = (r1 + c1) << 2;
+ const a00 = tile[i00 + 3];
+ const a10 = tile[i10 + 3];
+ const a01 = tile[i01 + 3];
+ const a11 = tile[i11 + 3];
+ if ((a00 | a10 | a01 | a11) === 0) {
+ out.r = 255;
+ out.g = 255;
+ out.b = 255;
+ out.a = 0;
+ return out;
+ }
+ const aw00 = w00 * (a00 * (1 / 255));
+ const aw10 = w10 * (a10 * (1 / 255));
+ const aw01 = w01 * (a01 * (1 / 255));
+ const aw11 = w11 * (a11 * (1 / 255));
+ const sumA = aw00 + aw10 + aw01 + aw11;
+ if (sumA > 0.002) {
+ const inv = 1 / sumA;
+ if (usePigment) {
+ // Only pay 4-corner latent interpolation when neighboring corners differ meaningfully (> 12 L1);
+ // on smooth gradients (<= 4 per channel) linear bilinear matches Kubelka-Munk to < 0.02/255.
+ const r00 = tile[i00], g00 = tile[i00 + 1], b00 = tile[i00 + 2];
+ const r10 = tile[i10], g10 = tile[i10 + 1], b10 = tile[i10 + 2];
+ const r01 = tile[i01], g01 = tile[i01 + 1], b01 = tile[i01 + 2];
+ const r11 = tile[i11], g11 = tile[i11 + 1], b11 = tile[i11 + 2];
+ const differs =
+ (aw10 > 0 && Math.abs(r10 - r00) + Math.abs(g10 - g00) + Math.abs(b10 - b00) > 12) ||
+ (aw01 > 0 && Math.abs(r01 - r00) + Math.abs(g01 - g00) + Math.abs(b01 - b00) > 12) ||
+ (aw11 > 0 && Math.abs(r11 - r00) + Math.abs(g11 - g00) + Math.abs(b11 - b00) > 12);
+ if (differs) {
+ _samplerLatAcc.fill(0);
+ if (aw00 > 0) {
+ srgbToPigmentLatentOut(r00, g00, b00, _samplerLatTmp, 0);
+ for (let c = 0; c < 7; c++) _samplerLatAcc[c] += _samplerLatTmp[c] * aw00;
+ }
+ if (aw10 > 0) {
+ srgbToPigmentLatentOut(r10, g10, b10, _samplerLatTmp, 0);
+ for (let c = 0; c < 7; c++) _samplerLatAcc[c] += _samplerLatTmp[c] * aw10;
+ }
+ if (aw01 > 0) {
+ srgbToPigmentLatentOut(r01, g01, b01, _samplerLatTmp, 0);
+ for (let c = 0; c < 7; c++) _samplerLatAcc[c] += _samplerLatTmp[c] * aw01;
+ }
+ if (aw11 > 0) {
+ srgbToPigmentLatentOut(r11, g11, b11, _samplerLatTmp, 0);
+ for (let c = 0; c < 7; c++) _samplerLatAcc[c] += _samplerLatTmp[c] * aw11;
+ }
+ for (let c = 0; c < 7; c++) _samplerLatAcc[c] *= inv;
+ pigmentLatentToSrgbOut(_samplerLatAcc, 0, out);
+ out.a = sumA > 1 ? 1 : sumA;
+ return out;
+ }
+ }
+ out.r = (tile[i00] * aw00 + tile[i10] * aw10 + tile[i01] * aw01 + tile[i11] * aw11) * inv;
+ out.g = (tile[i00 + 1] * aw00 + tile[i10 + 1] * aw10 + tile[i01 + 1] * aw01 + tile[i11 + 1] * aw11) * inv;
+ out.b = (tile[i00 + 2] * aw00 + tile[i10 + 2] * aw10 + tile[i01 + 2] * aw01 + tile[i11 + 2] * aw11) * inv;
+ out.a = sumA > 1 ? 1 : sumA;
+ } else {
+ out.r = 255;
+ out.g = 255;
+ out.b = 255;
+ out.a = 0;
+ }
+ return out;
+ }
+
let sumR = 0;
let sumG = 0;
let sumB = 0;
let sumA = 0;
+ if (usePigment) _samplerLatAcc.fill(0);
const accum = (px: number, py: number, wt: number) => {
if (wt <= 1e-4) return;
@@ -969,9 +979,14 @@ export class LayerPixelSampler {
}
if (ta > 0.002) {
const aw = wt * ta;
- sumR += tr * aw;
- sumG += tg * aw;
- sumB += tb * aw;
+ if (usePigment) {
+ srgbToPigmentLatentOut(tr, tg, tb, _samplerLatTmp, 0);
+ for (let c = 0; c < 7; c++) _samplerLatAcc[c] += _samplerLatTmp[c] * aw;
+ } else {
+ sumR += tr * aw;
+ sumG += tg * aw;
+ sumB += tb * aw;
+ }
sumA += aw;
}
};
@@ -983,9 +998,14 @@ export class LayerPixelSampler {
if (sumA > 0.002) {
const inv = 1 / sumA;
- out.r = sumR * inv;
- out.g = sumG * inv;
- out.b = sumB * inv;
+ if (usePigment) {
+ for (let c = 0; c < 7; c++) _samplerLatAcc[c] *= inv;
+ pigmentLatentToSrgbOut(_samplerLatAcc, 0, out);
+ } else {
+ out.r = sumR * inv;
+ out.g = sumG * inv;
+ out.b = sumB * inv;
+ }
out.a = Math.min(1, sumA);
} else {
out.r = 255;
@@ -996,6 +1016,171 @@ export class LayerPixelSampler {
return out;
}
+ /**
+ * Zero-allocation O(1) bilinear sample directly into 7-channel Kubelka-Munk latent space
+ * for SpatialTipMixer: eliminates redundant encode/decode roundtrips per texel!
+ * Writes linear RGB into `out` (and 7 latent floats into `outLat[outLatOff..+6]` when `out.a > 0.002`).
+ */
+ public sampleBilinearLatentFast(
+ cx: number,
+ cy: number,
+ out: RgbaColor,
+ outLat: Float32Array,
+ outLatOff: number
+ ): RgbaColor {
+ const w = this.width;
+ const h = this.height;
+ if (w <= 0 || h <= 0 || cx < -0.5 || cy < -0.5 || cx >= w - 0.5 || cy >= h - 0.5) {
+ out.r = 255;
+ out.g = 255;
+ out.b = 255;
+ out.a = 0;
+ return out;
+ }
+
+ const x0 = cx <= 0 ? 0 : cx >= w - 1 ? w - 1 : cx | 0;
+ const y0 = cy <= 0 ? 0 : cy >= h - 1 ? h - 1 : cy | 0;
+ const x1 = x0 + 1 < w ? x0 + 1 : w - 1;
+ const y1 = y0 + 1 < h ? y0 + 1 : h - 1;
+ const fx = cx <= x0 ? 0 : cx >= x0 + 1 ? 1 : cx - x0;
+ const fy = cy <= y0 ? 0 : cy >= y0 + 1 ? 1 : cy - y0;
+
+ const w00 = (1 - fx) * (1 - fy);
+ const w10 = fx * (1 - fy);
+ const w01 = (1 - fx) * fy;
+ const w11 = fx * fy;
+
+ let r00 = 0, g00 = 0, b00 = 0, a00 = 0;
+ let r10 = 0, g10 = 0, b10 = 0, a10 = 0;
+ let r01 = 0, g01 = 0, b01 = 0, a01 = 0;
+ let r11 = 0, g11 = 0, b11 = 0, a11 = 0;
+
+ if (this.useLazyTiles) {
+ const tx0 = x0 >> 8;
+ const ty0 = y0 >> 8;
+ if (tx0 === (x1 >> 8) && ty0 === (y1 >> 8)) {
+ const tile = this.getOrLoadTile(tx0, ty0);
+ const row0 = (y0 & 255) << 8;
+ const row1 = (y1 & 255) << 8;
+ const c0 = x0 & 255;
+ const c1 = x1 & 255;
+ const i00 = (row0 + c0) << 2;
+ const i10 = (row0 + c1) << 2;
+ const i01 = (row1 + c0) << 2;
+ const i11 = (row1 + c1) << 2;
+ a00 = tile[i00 + 3];
+ a10 = tile[i10 + 3];
+ a01 = tile[i01 + 3];
+ a11 = tile[i11 + 3];
+ if ((a00 | a10 | a01 | a11) === 0) {
+ out.r = 255; out.g = 255; out.b = 255; out.a = 0;
+ return out;
+ }
+ r00 = tile[i00]; g00 = tile[i00 + 1]; b00 = tile[i00 + 2];
+ r10 = tile[i10]; g10 = tile[i10 + 1]; b10 = tile[i10 + 2];
+ r01 = tile[i01]; g01 = tile[i01 + 1]; b01 = tile[i01 + 2];
+ r11 = tile[i11]; g11 = tile[i11 + 1]; b11 = tile[i11 + 2];
+ } else {
+ const t00 = this.getOrLoadTile(tx0, ty0);
+ const i00 = (((y0 & 255) << 8) + (x0 & 255)) << 2;
+ r00 = t00[i00]; g00 = t00[i00 + 1]; b00 = t00[i00 + 2]; a00 = t00[i00 + 3];
+ const t10 = this.getOrLoadTile(x1 >> 8, ty0);
+ const i10 = (((y0 & 255) << 8) + (x1 & 255)) << 2;
+ r10 = t10[i10]; g10 = t10[i10 + 1]; b10 = t10[i10 + 2]; a10 = t10[i10 + 3];
+ const t01 = this.getOrLoadTile(tx0, y1 >> 8);
+ const i01 = (((y1 & 255) << 8) + (x0 & 255)) << 2;
+ r01 = t01[i01]; g01 = t01[i01 + 1]; b01 = t01[i01 + 2]; a01 = t01[i01 + 3];
+ const t11 = this.getOrLoadTile(x1 >> 8, y1 >> 8);
+ const i11 = (((y1 & 255) << 8) + (x1 & 255)) << 2;
+ r11 = t11[i11]; g11 = t11[i11 + 1]; b11 = t11[i11 + 2]; a11 = t11[i11 + 3];
+ if ((a00 | a10 | a01 | a11) === 0) {
+ out.r = 255; out.g = 255; out.b = 255; out.a = 0;
+ return out;
+ }
+ }
+ } else {
+ const data = this.data;
+ const r0 = y0 * w;
+ const r1 = y1 * w;
+ const i00 = (r0 + x0) << 2;
+ const i10 = (r0 + x1) << 2;
+ const i01 = (r1 + x0) << 2;
+ const i11 = (r1 + x1) << 2;
+ a00 = data[i00 + 3];
+ a10 = data[i10 + 3];
+ a01 = data[i01 + 3];
+ a11 = data[i11 + 3];
+ if ((a00 | a10 | a01 | a11) === 0) {
+ out.r = 255; out.g = 255; out.b = 255; out.a = 0;
+ return out;
+ }
+ r00 = data[i00]; g00 = data[i00 + 1]; b00 = data[i00 + 2];
+ r10 = data[i10]; g10 = data[i10 + 1]; b10 = data[i10 + 2];
+ r01 = data[i01]; g01 = data[i01 + 1]; b01 = data[i01 + 2];
+ r11 = data[i11]; g11 = data[i11 + 1]; b11 = data[i11 + 2];
+ }
+
+ const inv255 = 1 / 255;
+ const aw00 = w00 * (a00 * inv255);
+ const aw10 = w10 * (a10 * inv255);
+ const aw01 = w01 * (a01 * inv255);
+ const aw11 = w11 * (a11 * inv255);
+ const sumA = aw00 + aw10 + aw01 + aw11;
+ if (sumA <= 0.002) {
+ out.r = 255; out.g = 255; out.b = 255; out.a = 0;
+ return out;
+ }
+
+ const inv = 1 / sumA;
+ const linR = (r00 * aw00 + r10 * aw10 + r01 * aw01 + r11 * aw11) * inv;
+ const linG = (g00 * aw00 + g10 * aw10 + g01 * aw01 + g11 * aw11) * inv;
+ const linB = (b00 * aw00 + b10 * aw10 + b01 * aw01 + b11 * aw11) * inv;
+ out.r = linR;
+ out.g = linG;
+ out.b = linB;
+ out.a = sumA > 1 ? 1 : sumA;
+
+ const differs =
+ (aw10 > 0 && Math.abs(r10 - r00) + Math.abs(g10 - g00) + Math.abs(b10 - b00) > 12) ||
+ (aw01 > 0 && Math.abs(r01 - r00) + Math.abs(g01 - g00) + Math.abs(b01 - b00) > 12) ||
+ (aw11 > 0 && Math.abs(r11 - r00) + Math.abs(g11 - g00) + Math.abs(b11 - b00) > 12);
+
+ if (!differs) {
+ srgbToPigmentLatentOut(linR, linG, linB, outLat, outLatOff);
+ return out;
+ }
+
+ let l0 = 0, l1 = 0, l2 = 0, l3 = 0, l4 = 0, l5 = 0, l6 = 0;
+ if (aw00 > 0) {
+ srgbToPigmentLatentOut(r00, g00, b00, _samplerLatTmp, 0);
+ l0 += _samplerLatTmp[0] * aw00; l1 += _samplerLatTmp[1] * aw00; l2 += _samplerLatTmp[2] * aw00;
+ l3 += _samplerLatTmp[3] * aw00; l4 += _samplerLatTmp[4] * aw00; l5 += _samplerLatTmp[5] * aw00; l6 += _samplerLatTmp[6] * aw00;
+ }
+ if (aw10 > 0) {
+ srgbToPigmentLatentOut(r10, g10, b10, _samplerLatTmp, 0);
+ l0 += _samplerLatTmp[0] * aw10; l1 += _samplerLatTmp[1] * aw10; l2 += _samplerLatTmp[2] * aw10;
+ l3 += _samplerLatTmp[3] * aw10; l4 += _samplerLatTmp[4] * aw10; l5 += _samplerLatTmp[5] * aw10; l6 += _samplerLatTmp[6] * aw10;
+ }
+ if (aw01 > 0) {
+ srgbToPigmentLatentOut(r01, g01, b01, _samplerLatTmp, 0);
+ l0 += _samplerLatTmp[0] * aw01; l1 += _samplerLatTmp[1] * aw01; l2 += _samplerLatTmp[2] * aw01;
+ l3 += _samplerLatTmp[3] * aw01; l4 += _samplerLatTmp[4] * aw01; l5 += _samplerLatTmp[5] * aw01; l6 += _samplerLatTmp[6] * aw01;
+ }
+ if (aw11 > 0) {
+ srgbToPigmentLatentOut(r11, g11, b11, _samplerLatTmp, 0);
+ l0 += _samplerLatTmp[0] * aw11; l1 += _samplerLatTmp[1] * aw11; l2 += _samplerLatTmp[2] * aw11;
+ l3 += _samplerLatTmp[3] * aw11; l4 += _samplerLatTmp[4] * aw11; l5 += _samplerLatTmp[5] * aw11; l6 += _samplerLatTmp[6] * aw11;
+ }
+ outLat[outLatOff] = l0 * inv;
+ outLat[outLatOff + 1] = l1 * inv;
+ outLat[outLatOff + 2] = l2 * inv;
+ outLat[outLatOff + 3] = l3 * inv;
+ outLat[outLatOff + 4] = l4 * inv;
+ outLat[outLatOff + 5] = l5 * inv;
+ outLat[outLatOff + 6] = l6 * inv;
+ return out;
+ }
+
/**
* Lightweight per-bristle pixel deposit so overlapping turns immediately pick up
* freshly mixed multi-colored streaks laid down earlier in the same stroke.
@@ -1007,7 +1192,8 @@ export class LayerPixelSampler {
r: number,
g: number,
b: number,
- a: number
+ a: number,
+ pigmentStrength: number = 0
): void {
if (a <= 0.005 || this.width <= 0 || this.height <= 0) return;
const w = this.width;
@@ -1022,39 +1208,72 @@ export class LayerPixelSampler {
if (x0 > x1 || y0 > y1) return;
const radSq = Math.max(1, rad * rad);
+ const invRadSqP1 = 0.65 / (radSq + 1);
+ const usePigment = pigmentStrength > 0.005;
for (let y = y0; y <= y1; y++) {
const dy = y - iy;
const dySq = dy * dy;
const ty = y >> 8;
const lyOff = (y & 255) << 8;
const rowOff = y * w;
+ let cachedTx = -1;
+ let cachedTile: Uint8ClampedArray | null = null;
for (let x = x0; x <= x1; x++) {
const dx = x - ix;
const dSq = dx * dx + dySq;
if (dSq > radSq) continue;
- const effA = Math.min(1.0, a * (rad === 0 ? 1.0 : 1.0 - (dSq / (radSq + 1)) * 0.65));
+ const effA = Math.min(1.0, a * (rad === 0 ? 1.0 : 1.0 - dSq * invRadSqP1));
if (this.useLazyTiles) {
- const tile = this.getOrLoadTile(x >> 8, ty);
+ const tx = x >> 8;
+ if (tx !== cachedTx) {
+ cachedTile = this.getOrLoadTile(tx, ty);
+ cachedTx = tx;
+ }
+ const tile = cachedTile!;
const idx = (lyOff + (x & 255)) << 2;
- const dstA = tile[idx + 3] / 255;
+ const dstA = tile[idx + 3] * (1 / 255);
const outA = effA + dstA * (1 - effA);
if (outA > 0.001) {
- const inv = 1 / outA;
- tile[idx] = Math.round((r * effA + tile[idx] * dstA * (1 - effA)) * inv);
- tile[idx + 1] = Math.round((g * effA + tile[idx + 1] * dstA * (1 - effA)) * inv);
- tile[idx + 2] = Math.round((b * effA + tile[idx + 2] * dstA * (1 - effA)) * inv);
- tile[idx + 3] = Math.round(Math.min(255, outA * 255));
+ const dr = tile[idx];
+ const dg = tile[idx + 1];
+ const db = tile[idx + 2];
+ const diffSq = (r - dr) * (r - dr) + (g - dg) * (g - dg) + (b - db) * (b - db);
+ if (usePigment && dstA > 0.002 && diffSq > 64) {
+ pigmentMixRgbOut(dr, dg, db, r, g, b, effA / outA, pigmentStrength, _samplerRgbScratch);
+ tile[idx] = (_samplerRgbScratch.r + 0.5) | 0;
+ tile[idx + 1] = (_samplerRgbScratch.g + 0.5) | 0;
+ tile[idx + 2] = (_samplerRgbScratch.b + 0.5) | 0;
+ } else {
+ const inv = 1 / outA;
+ const dstW = dstA * (1 - effA);
+ tile[idx] = ((r * effA + dr * dstW) * inv + 0.5) | 0;
+ tile[idx + 1] = ((g * effA + dg * dstW) * inv + 0.5) | 0;
+ tile[idx + 2] = ((b * effA + db * dstW) * inv + 0.5) | 0;
+ }
+ tile[idx + 3] = outA >= 1 ? 255 : (outA * 255 + 0.5) | 0;
}
} else {
const idx = (rowOff + x) << 2;
- const dstA = this.data[idx + 3] / 255;
+ const dstA = this.data[idx + 3] * (1 / 255);
const outA = effA + dstA * (1 - effA);
if (outA > 0.001) {
- const inv = 1 / outA;
- this.data[idx] = Math.round((r * effA + this.data[idx] * dstA * (1 - effA)) * inv);
- this.data[idx + 1] = Math.round((g * effA + this.data[idx + 1] * dstA * (1 - effA)) * inv);
- this.data[idx + 2] = Math.round((b * effA + this.data[idx + 2] * dstA * (1 - effA)) * inv);
- this.data[idx + 3] = Math.round(Math.min(255, outA * 255));
+ const dr = this.data[idx];
+ const dg = this.data[idx + 1];
+ const db = this.data[idx + 2];
+ const diffSq = (r - dr) * (r - dr) + (g - dg) * (g - dg) + (b - db) * (b - db);
+ if (usePigment && dstA > 0.002 && diffSq > 64) {
+ pigmentMixRgbOut(dr, dg, db, r, g, b, effA / outA, pigmentStrength, _samplerRgbScratch);
+ this.data[idx] = (_samplerRgbScratch.r + 0.5) | 0;
+ this.data[idx + 1] = (_samplerRgbScratch.g + 0.5) | 0;
+ this.data[idx + 2] = (_samplerRgbScratch.b + 0.5) | 0;
+ } else {
+ const inv = 1 / outA;
+ const dstW = dstA * (1 - effA);
+ this.data[idx] = ((r * effA + dr * dstW) * inv + 0.5) | 0;
+ this.data[idx + 1] = ((g * effA + dg * dstW) * inv + 0.5) | 0;
+ this.data[idx + 2] = ((b * effA + db * dstW) * inv + 0.5) | 0;
+ }
+ this.data[idx + 3] = outA >= 1 ? 255 : (outA * 255 + 0.5) | 0;
}
}
}
@@ -1302,8 +1521,11 @@ export class PaintReservoir {
// Output dab opacity based on Density of Paint, Flow, and Pressure (avoid double-applying pressure)
const effPressure = Math.min(1.0, Math.max(0.05, pressure));
const pressureMod = pressureAlreadyAppliedToFlow ? 1.0 : effPressure * 0.65 + 0.35;
+ const effectiveSmudgeDensity = isPureSmudge
+ ? Math.max(densityOfPaint, clampedStretch)
+ : densityOfPaint;
const dabAlpha = isPureSmudge
- ? flow * pressureMod * densityOfPaint * this.a
+ ? flow * pressureMod * effectiveSmudgeDensity * this.a
: flow * pressureMod * densityOfPaint;
const finalR = Math.round(Math.max(0, Math.min(255, this.r)));
@@ -1415,7 +1637,8 @@ export class SpatialBristleReservoir {
private readonly scratchC1: RgbColor = { r: 0, g: 0, b: 0 };
private readonly scratchC2: RgbColor = { r: 0, g: 0, b: 0 };
- private readonly scratchOrig: RgbColor = { r: 0, g: 0, b: 0 };
+ private readonly scratchEqOut: RgbColor = { r: 0, g: 0, b: 0 };
+ private readonly scratchMixOut: RgbColor = { r: 0, g: 0, b: 0 };
constructor(
baseColorHex: string = '#000000',
@@ -1671,7 +1894,11 @@ export class SpatialBristleReservoir {
stepDist > 0
? 1.0 - Math.exp(-(stepDist * canvasAlpha * viscosityResist * (0.55 + 0.45 * effPressure)) / smudgeDist)
: Math.min(0.75, canvasAlpha * viscosityResist * 0.45);
- const mixed = mixPigmentsWithStrength(this.scratchC1, this.scratchC2, pickup, pigmentStrength);
+ const mixed = mixPigmentRgbOut(
+ this.scratchC1.r, this.scratchC1.g, this.scratchC1.b,
+ this.scratchC2.r, this.scratchC2.g, this.scratchC2.b,
+ pickup, pigmentStrength, this.scratchMixOut
+ );
this.r[i] = mixed.r;
this.g[i] = mixed.g;
this.b[i] = mixed.b;
@@ -1703,14 +1930,10 @@ export class SpatialBristleReservoir {
const eqFreshRatio = wTotal > 1e-4 ? wFresh / wTotal : 1.0;
// Compute equilibrium target color: mix(canvas, original, eqFreshRatio)
- this.scratchOrig.r = this.originalR;
- this.scratchOrig.g = this.originalG;
- this.scratchOrig.b = this.originalB;
- const eqColor = mixPigmentsWithStrength(
- this.scratchC2,
- this.scratchOrig,
- eqFreshRatio,
- pigmentStrength
+ const eqColor = mixPigmentRgbOut(
+ this.scratchC2.r, this.scratchC2.g, this.scratchC2.b,
+ this.originalR, this.originalG, this.originalB,
+ eqFreshRatio, pigmentStrength, this.scratchEqOut
);
// Pickup responds smoothly on contact; colorStretch governs long ribbon carry
@@ -1720,7 +1943,11 @@ export class SpatialBristleReservoir {
? 1.0 - Math.exp(-(stepDist * Math.max(0.45, wTotal)) / charDist)
: Math.min(0.35, (1.0 - eqFreshRatio) * 0.5 * canvasAlpha);
- const mixed = mixPigmentsWithStrength(this.scratchC1, eqColor, stepRate, pigmentStrength);
+ const mixed = mixPigmentRgbOut(
+ this.scratchC1.r, this.scratchC1.g, this.scratchC1.b,
+ eqColor.r, eqColor.g, eqColor.b,
+ stepRate, pigmentStrength, this.scratchMixOut
+ );
this.r[i] = mixed.r;
this.g[i] = mixed.g;
this.b[i] = mixed.b;
@@ -1746,13 +1973,11 @@ export class SpatialBristleReservoir {
// Smoothly recover toward brush's loaded color as picked-up streaks trail off
const recoverDist = Math.max(24, (0.2 + clampedStretch * 0.8) * (220 / Math.max(0.18, effectiveAmount)));
const recover = 1.0 - Math.exp(-stepDist / recoverDist);
- this.scratchC1.r = this.r[i];
- this.scratchC1.g = this.g[i];
- this.scratchC1.b = this.b[i];
- this.scratchC2.r = this.originalR;
- this.scratchC2.g = this.originalG;
- this.scratchC2.b = this.originalB;
- const recovered = mixPigmentsWithStrength(this.scratchC1, this.scratchC2, recover, pigmentStrength);
+ const recovered = mixPigmentRgbOut(
+ this.r[i], this.g[i], this.b[i],
+ this.originalR, this.originalG, this.originalB,
+ recover, pigmentStrength, this.scratchMixOut
+ );
this.r[i] = recovered.r;
this.g[i] = recovered.g;
this.b[i] = recovered.b;
@@ -1809,12 +2034,30 @@ export interface SpatialTipStampParams {
amountOfPaint: number;
densityOfPaint: number;
colorStretch: number;
+ isPureBlender?: boolean;
mixingMode: NaturalMixingMode;
perceptualMixing: boolean;
pigmentMixingStrength?: number;
+ useBlur?: boolean;
+ blurStrength?: number;
tipImage?: HTMLImageElement;
+ isDualToneTip?: boolean;
+ secondaryColor?: string;
+ freshColor?: RgbColor;
sampler?: LayerPixelSampler;
grainDensity?: number;
+ paperTextureMode?: import('../types/editor').CspPaperTextureMode;
+ paperLumData?: Uint8Array;
+ paperLumWidth?: number;
+ paperLumHeight?: number;
+ paperTextureScale?: number;
+ paperTextureRotate?: number;
+ paperTextureBrightness?: number;
+ paperTextureContrast?: number;
+ paperTextureInverted?: boolean;
+ paperTexturePreserveDensity?: boolean;
+ paperTextureEmphasizeDensity?: boolean;
+ grainPressure?: number;
grainModulate?: (wx: number, wy: number, tipAlpha: number) => number;
}
@@ -1822,6 +2065,11 @@ interface CachedTipMask {
width: number;
height: number;
alpha: Uint8Array;
+ lum: Uint8Array;
+ /** (width+1)*(height+1) 2D summed-area table of alpha for O(1) anti-aliased box-filtered downsampling. */
+ alphaSat: Uint32Array;
+ /** Mean normalized alpha inside the inner 70% of the tip's non-empty bounding box (1.0 = solid, ~0.22 = porous chalk). */
+ coreFill: number;
}
const tipAlphaMaskCache = new WeakMap<HTMLImageElement, CachedTipMask>();
@@ -1833,7 +2081,8 @@ function getCachedTipAlphaMask(img: HTMLImageElement): CachedTipMask | null {
const w = img.naturalWidth || img.width;
const h = img.naturalHeight || img.height;
if (w <= 0 || h <= 0) return null;
- const maxDim = 64;
+ // Preserve full 256x256 procedural tip detail (chipped chalk edges, bristle tufts & mineral micro-pores)
+ const maxDim = 256;
const scale = Math.min(1, maxDim / Math.max(w, h));
const dw = Math.max(4, Math.round(w * scale));
const dh = Math.max(4, Math.round(h * scale));
@@ -1846,16 +2095,71 @@ function getCachedTipAlphaMask(img: HTMLImageElement): CachedTipMask | null {
ctx.drawImage(img, 0, 0, dw, dh);
const raw = ctx.getImageData(0, 0, dw, dh).data;
const alpha = new Uint8Array(dw * dh);
- for (let i = 0; i < alpha.length; i++) {
- alpha[i] = raw[i * 4 + 3];
+ const lum = new Uint8Array(dw * dh);
+ const satW = dw + 1;
+ const alphaSat = new Uint32Array(satW * (dh + 1));
+ let minX = dw;
+ let maxX = -1;
+ let minY = dh;
+ let maxY = -1;
+ for (let y = 0; y < dh; y++) {
+ const row = y * dw;
+ const satRow = (y + 1) * satW;
+ const satPrev = y * satW;
+ let rowSum = 0;
+ for (let x = 0; x < dw; x++) {
+ const i = row + x;
+ const o = i << 2;
+ const a = raw[o + 3];
+ alpha[i] = a;
+ lum[i] = Math.round(0.299 * raw[o] + 0.587 * raw[o + 1] + 0.114 * raw[o + 2]);
+ rowSum += a;
+ alphaSat[satRow + x + 1] = alphaSat[satPrev + x + 1] + rowSum;
+ if (a > 8) {
+ if (x < minX) minX = x;
+ if (x > maxX) maxX = x;
+ if (y < minY) minY = y;
+ if (y > maxY) maxY = y;
+ }
+ }
}
- const mask: CachedTipMask = { width: dw, height: dh, alpha };
+ let coreFill = 1.0;
+ if (maxX >= minX && maxY >= minY) {
+ const bw = maxX - minX + 1;
+ const bh = maxY - minY + 1;
+ const cx0 = minX + Math.floor(bw * 0.15);
+ const cx1 = maxX - Math.floor(bw * 0.15);
+ const cy0 = minY + Math.floor(bh * 0.15);
+ const cy1 = maxY - Math.floor(bh * 0.15);
+ let sumA = 0;
+ let count = 0;
+ for (let y = cy0; y <= cy1; y++) {
+ const row = y * dw;
+ for (let x = cx0; x <= cx1; x++) {
+ sumA += alpha[row + x];
+ count++;
+ }
+ }
+ if (count > 0) {
+ coreFill = sumA / (count * 255);
+ }
+ }
+ const mask: CachedTipMask = { width: dw, height: dh, alpha, lum, alphaSat, coreFill };
tipAlphaMaskCache.set(img, mask);
return mask;
}
-const MAX_SPATIAL_COLOR_DIM = 64;
-const MAX_SPATIAL_OUT_DIM = 256;
+const MAX_SPATIAL_COLOR_DIM = 24;
+const MAX_SPATIAL_BLUR_DIM = 14;
+const MAX_SPATIAL_OUT_DIM = 96;
+const MAX_SPATIAL_SOFT_OUT_DIM = 52;
+const MAX_SPATIAL_SURFACE_POOL = 48;
+
+interface SpatialSurfaceEntry {
+ canvas: HTMLCanvasElement;
+ ctx: CanvasRenderingContext2D;
+ imgData: ImageData;
+}
export class SpatialTipMixer {
public readonly origR: number;
@@ -1865,20 +2169,37 @@ export class SpatialTipMixer {
private gridW: number = 0;
private gridH: number = 0;
private initialized: boolean = false;
+ private latInitialized: boolean = false;
+ private uniR: number;
+ private uniG: number;
+ private uniB: number;
+ private uniCarry: number = 0;
+ private readonly uniLat = new Float32Array(PIGMENT_LATENT_SIZE);
+ private readonly freshLat = new Float32Array(PIGMENT_LATENT_SIZE);
+ private cachedFreshR: number = -9999;
+ private cachedFreshG: number = -9999;
+ private cachedFreshB: number = -9999;
private readonly bufR = new Float32Array(MAX_SPATIAL_COLOR_DIM * MAX_SPATIAL_COLOR_DIM);
private readonly bufG = new Float32Array(MAX_SPATIAL_COLOR_DIM * MAX_SPATIAL_COLOR_DIM);
private readonly bufB = new Float32Array(MAX_SPATIAL_COLOR_DIM * MAX_SPATIAL_COLOR_DIM);
+ private readonly linR = new Float32Array(MAX_SPATIAL_COLOR_DIM * MAX_SPATIAL_COLOR_DIM);
+ private readonly linG = new Float32Array(MAX_SPATIAL_COLOR_DIM * MAX_SPATIAL_COLOR_DIM);
+ private readonly linB = new Float32Array(MAX_SPATIAL_COLOR_DIM * MAX_SPATIAL_COLOR_DIM);
private readonly bufA = new Float32Array(MAX_SPATIAL_COLOR_DIM * MAX_SPATIAL_COLOR_DIM);
private readonly bufCarry = new Float32Array(MAX_SPATIAL_COLOR_DIM * MAX_SPATIAL_COLOR_DIM);
private readonly tmpR = new Float32Array(MAX_SPATIAL_COLOR_DIM * MAX_SPATIAL_COLOR_DIM);
private readonly tmpG = new Float32Array(MAX_SPATIAL_COLOR_DIM * MAX_SPATIAL_COLOR_DIM);
private readonly tmpB = new Float32Array(MAX_SPATIAL_COLOR_DIM * MAX_SPATIAL_COLOR_DIM);
+ private readonly latBuf = new Float32Array(MAX_SPATIAL_COLOR_DIM * MAX_SPATIAL_COLOR_DIM * PIGMENT_LATENT_SIZE);
+ private readonly latTmp = new Float32Array(MAX_SPATIAL_COLOR_DIM * MAX_SPATIAL_COLOR_DIM * PIGMENT_LATENT_SIZE);
+ private readonly canvasLatSum = new Float32Array(PIGMENT_LATENT_SIZE);
+ private readonly latSampleTmp = new Float32Array(PIGMENT_LATENT_SIZE);
+ private readonly latEqTmp = new Float32Array(PIGMENT_LATENT_SIZE);
+ private readonly surfacePool = new Map<number, SpatialSurfaceEntry>();
private scratchCanvas: HTMLCanvasElement | null = null;
private scratchCtx: CanvasRenderingContext2D | null = null;
private scratchImgData: ImageData | null = null;
- private scratchW: number = 0;
- private scratchH: number = 0;
private readonly sampleScratch: RgbaColor = { r: 0, g: 0, b: 0, a: 0 };
private readonly c1Scratch: RgbColor = { r: 0, g: 0, b: 0 };
@@ -1888,38 +2209,44 @@ export class SpatialTipMixer {
this.origR = rgb.r;
this.origG = rgb.g;
this.origB = rgb.b;
+ this.uniR = rgb.r;
+ this.uniG = rgb.g;
+ this.uniB = rgb.b;
}
- private ensureGrid(width: number, height: number): void {
+ private ensureGrid(width: number, height: number, useBlur: boolean): void {
if (this.initialized && this.gridW > 0 && this.gridH > 0) {
return;
}
+ const dimCap = useBlur ? MAX_SPATIAL_BLUR_DIM : MAX_SPATIAL_COLOR_DIM;
const maxDim = Math.max(width, height, 1);
- const scale = Math.min(1, MAX_SPATIAL_COLOR_DIM / maxDim);
- this.gridW = Math.max(8, Math.min(MAX_SPATIAL_COLOR_DIM, Math.ceil(width * scale)));
- this.gridH = Math.max(8, Math.min(MAX_SPATIAL_COLOR_DIM, Math.ceil(height * scale)));
+ const scale = Math.min(1, dimCap / maxDim);
+ this.gridW = Math.max(8, Math.min(dimCap, Math.ceil(width * scale)));
+ this.gridH = Math.max(8, Math.min(dimCap, Math.ceil(height * scale)));
}
private ensureScratchSurface(outW: number, outH: number): boolean {
if (typeof document === 'undefined') return false;
- if (!this.scratchCanvas) {
- this.scratchCanvas = document.createElement('canvas');
- this.scratchCanvas.width = outW;
- this.scratchCanvas.height = outH;
- this.scratchCtx = this.scratchCanvas.getContext('2d');
- this.scratchW = outW;
- this.scratchH = outH;
- } else if (this.scratchW !== outW || this.scratchH !== outH) {
- this.scratchCanvas.width = outW;
- this.scratchCanvas.height = outH;
- this.scratchW = outW;
- this.scratchH = outH;
- this.scratchImgData = null;
- }
- if (!this.scratchCtx || typeof this.scratchCtx.createImageData !== 'function') return false;
- if (!this.scratchImgData) {
- this.scratchImgData = this.scratchCtx.createImageData(outW, outH);
+ const pool = this.surfacePool;
+ const key = (outW << 12) | outH;
+ let entry = pool.get(key);
+ if (!entry) {
+ if (pool.size >= MAX_SPATIAL_SURFACE_POOL) {
+ const oldest = pool.keys().next().value;
+ if (oldest !== undefined) pool.delete(oldest);
+ }
+ const canvas = document.createElement('canvas');
+ canvas.width = outW;
+ canvas.height = outH;
+ const ctx = canvas.getContext('2d');
+ if (!ctx || typeof ctx.createImageData !== 'function') return false;
+ const imgData = ctx.createImageData(outW, outH);
+ entry = { canvas, ctx, imgData };
+ pool.set(key, entry);
}
+ this.scratchCanvas = entry.canvas;
+ this.scratchCtx = entry.ctx;
+ this.scratchImgData = entry.imgData;
return true;
}
@@ -1943,14 +2270,18 @@ export class SpatialTipMixer {
} | null {
if (p.width < 0.25 || p.height < 0.25 || p.flow <= 0.002) return null;
- this.ensureGrid(p.width, p.height);
+ const blurAmt = p.useBlur ? Math.max(0, Math.min(1, p.blurStrength ?? 0.35)) : 0;
+ this.ensureGrid(p.width, p.height, blurAmt > 0.005);
const gw = this.gridW;
const gh = this.gridH;
- // 1:1 output stamp dimensions (capped at 256px) with 1px transparent padding on each edge
+ // 1:1 output stamp dimensions (capped adaptively) with 1px transparent padding on each edge
// so Canvas2D bilinear filtering never blurs or clips sharp rotated chisel corners.
+ // Soft/blurred stamps have no sub-pixel silhouette detail and upscale identically on GPU.
+ const isSoftSmoothStamp = !p.tipImage && (blurAmt > 0.05 || p.hardness < 0.85) && (p.grainDensity ?? 0) <= 0.005;
+ const outDimCap = isSoftSmoothStamp ? MAX_SPATIAL_SOFT_OUT_DIM : MAX_SPATIAL_OUT_DIM;
const maxAxis = Math.max(p.width, p.height);
- const outScale = maxAxis > MAX_SPATIAL_OUT_DIM - 2 ? (MAX_SPATIAL_OUT_DIM - 2) / maxAxis : 1.0;
+ const outScale = maxAxis > outDimCap - 2 ? (outDimCap - 2) / maxAxis : 1.0;
const innerW = Math.max(4, Math.ceil(p.width * outScale));
const innerH = Math.max(4, Math.ceil(p.height * outScale));
const outW = innerW + 2;
@@ -1963,7 +2294,10 @@ export class SpatialTipMixer {
const clampedAmount = Math.max(0, Math.min(1, p.amountOfPaint));
const clampedDensity = Math.max(0, Math.min(1, p.densityOfPaint));
const clampedStretch = Math.max(0, Math.min(1, p.colorStretch));
- const isPureSmudge = clampedAmount <= 0.005 || p.mixingMode === 'smear';
+ const isPureSmudge =
+ p.isPureBlender !== undefined
+ ? p.isPureBlender || p.mixingMode === 'smear'
+ : clampedAmount <= 0.005 || p.mixingMode === 'smear';
const isFullFresh = !isPureSmudge && clampedAmount >= 0.995;
const isRunning = p.mixingMode === 'running_color';
@@ -1990,12 +2324,17 @@ export class SpatialTipMixer {
}
// Fast canvas pickup on contact (~0.25..0.75x tip thickness along stroke);
- // Color Stretch governs long carry persistence (even on small 15-35px brushes!).
+ // For pure blenders (Amount=0), high Color Stretch drags picked-up color far across
+ // contrasting regions and off onto blank canvas (matching CSP Fur Blend / Finger Tip).
const carryScale = Math.max(0.75, brushSpan / 36);
- const pickupLen = Math.max(1.8, diamAlongStroke * (0.26 + 0.44 * clampedStretch));
+ const pickupLen = isPureSmudge
+ ? Math.max(8.0, diamAlongStroke * (0.45 + 2.8 * clampedStretch * clampedStretch))
+ : Math.max(1.8, diamAlongStroke * (0.26 + 0.44 * clampedStretch));
const pickupRate = step > 0 ? 1.0 - Math.exp(-step / pickupLen) : 0.9;
- const stretchDist = Math.max(16.0, (24 + clampedStretch * clampedStretch * 340) * carryScale);
+ const stretchDist = isPureSmudge
+ ? Math.max(40.0, (60 + clampedStretch * clampedStretch * 480) * carryScale)
+ : Math.max(16.0, (24 + clampedStretch * clampedStretch * 340) * carryScale);
const carryDecay = step > 0 ? 1.0 - Math.exp(-step / stretchDist) : 0.0;
const recoverLen = Math.max(
18.0,
@@ -2009,216 +2348,827 @@ export class SpatialTipMixer {
? Math.max(0, Math.min(1, p.pigmentMixingStrength ?? 1.0))
: 0;
- const mixColorInto = (
- r1: number,
- g1: number,
- b1: number,
- r2: number,
- g2: number,
- b2: number,
- w2: number
- ): RgbColor => {
- const w = w2 <= 0 ? 0 : w2 >= 1 ? 1 : w2;
- if (w <= 0.0005) {
- this.c1Scratch.r = r1;
- this.c1Scratch.g = g1;
- this.c1Scratch.b = b1;
- return this.c1Scratch;
- }
- if (w >= 0.9995) {
- this.c1Scratch.r = r2;
- this.c1Scratch.g = g2;
- this.c1Scratch.b = b2;
- return this.c1Scratch;
- }
- if (effPigmentStrength > 0.005) {
- return mixPigmentRgbOut(r1, g1, b1, r2, g2, b2, w, effPigmentStrength, this.c1Scratch);
- }
- this.c1Scratch.r = r1 + (r2 - r1) * w;
- this.c1Scratch.g = g1 + (g2 - g1) * w;
- this.c1Scratch.b = b1 + (b2 - b1) * w;
- return this.c1Scratch;
- };
-
const sampler = p.sampler;
+ const usePigment = effPigmentStrength > 0.005;
+ const partialPigment = usePigment && effPigmentStrength < 0.995;
const firstTouch = !this.initialized;
let pickedUpCanvas = false;
let sumBufR = 0;
let sumBufG = 0;
let sumBufB = 0;
let sumBufA = 0;
+ let canvasSumR = 0;
+ let canvasSumG = 0;
+ let canvasSumB = 0;
+ let canvasAlphaSum = 0;
const totalTexels = gw * gh;
-
- // 1. Sample underlying canvas & update 2D oriented paint buffer
- for (let gy = 0; gy < gh; gy++) {
- const ny = ((gy + 0.5) * invGh - 0.5) * 2.0; // [-1, 1]
- const ly = ny * halfH;
- const rowOff = gy * gw;
- for (let gx = 0; gx < gw; gx++) {
- const nx = ((gx + 0.5) * invGw - 0.5) * 2.0; // [-1, 1]
- const lx = nx * halfW;
- const idx = rowOff + gx;
-
- if (isFullFresh) {
- this.bufR[idx] = this.origR;
- this.bufG[idx] = this.origG;
- this.bufB[idx] = this.origB;
- this.bufA[idx] = 1.0;
- this.bufCarry[idx] = 0.0;
- sumBufR += this.origR;
- sumBufG += this.origG;
- sumBufB += this.origB;
- sumBufA += 1.0;
- continue;
+ if (usePigment) this.canvasLatSum.fill(0);
+
+ // CSP Blend (BrushWaterColor=0) mixes canvas color isotropically across compact/round tips
+ // (like Oil Pastel sticks), while wide flat bristle blades (aspect >= 2.5) and Running Color
+ // preserve spatial per-bristle side-by-side color separation.
+ const tipAspect = brushSpan / Math.max(0.5, thinSpan);
+ const blendUniformity =
+ !isRunning && !isPureSmudge && !isFullFresh
+ ? Math.max(0, Math.min(1, 1.85 - tipAspect))
+ : 0;
+
+ const freshR = p.freshColor ? p.freshColor.r : this.origR;
+ const freshG = p.freshColor ? p.freshColor.g : this.origG;
+ const freshB = p.freshColor ? p.freshColor.b : this.origB;
+
+ const freshLat = this.freshLat;
+ if (usePigment) {
+ if (freshR !== this.cachedFreshR || freshG !== this.cachedFreshG || freshB !== this.cachedFreshB) {
+ srgbToPigmentLatentOut(freshR, freshG, freshB, freshLat, 0);
+ this.cachedFreshR = freshR;
+ this.cachedFreshG = freshG;
+ this.cachedFreshB = freshB;
+ }
+ // If stroke switched into pigment mode after already initializing in linear mode, sync latBuf once
+ if (!firstTouch && !this.latInitialized) {
+ for (let i = 0; i < totalTexels; i++) {
+ srgbToPigmentLatentOut(this.bufR[i], this.bufG[i], this.bufB[i], this.latBuf, i * 7);
+ if (partialPigment) {
+ this.linR[i] = this.bufR[i];
+ this.linG[i] = this.bufG[i];
+ this.linB[i] = this.bufB[i];
+ }
}
+ srgbToPigmentLatentOut(this.uniR, this.uniG, this.uniB, this.uniLat, 0);
+ this.latInitialized = true;
+ }
+ }
- const wx = p.x + lx * cosA - ly * sinA;
- const wy = p.y + lx * sinA + ly * cosA;
- const sampled = sampler
- ? sampler.sampleBilinearFast(wx, wy, this.sampleScratch)
- : ((this.sampleScratch.a = 0), this.sampleScratch);
- const ca = sampled.a;
- if (ca > 0.015) pickedUpCanvas = true;
+ // 1. Sample underlying canvas & update 2D oriented paint buffer
+ // When usePigment is active, ALL mixing & diffusion run directly in 7-channel Kubelka-Munk latent
+ // space (7 linear float ops/texel) with ONE single decode at the end of Step 2 — 15-25x faster!
+ const stretchPickupBoost = 1.0 + clampedStretch * (isRunning ? 1.45 : 1.15);
+ const wFreshBase = clampedAmount * (isRunning ? 0.72 : 0.88);
+ const wFreshFirst = clampedAmount * (isRunning ? 0.75 : 0.9);
+ const latBuf = this.latBuf;
+ const latSamp = this.latSampleTmp;
+ const latEq = this.latEqTmp;
+ const dLxStep = (2.0 * invGw) * halfW;
+ const dWxStep = dLxStep * cosA;
+ const dWyStep = dLxStep * sinA;
+ const lx0Start = (0.5 * invGw - 0.5) * 2.0 * halfW;
- // CSP Blend wet pickup: when crossing existing paint, load canvas pigment strongly into the
- // carried tip buffer (proportional to (1 - amount) boosted by colorStretch) so overlapping
- // colors smear visibly into blank canvas instead of snapping back to pure foreground.
- const stretchPickupBoost = 1.0 + clampedStretch * (isRunning ? 1.45 : 1.15);
+ if (isFullFresh) {
+ for (let i = 0; i < totalTexels; i++) {
+ this.bufR[i] = freshR;
+ this.bufG[i] = freshG;
+ this.bufB[i] = freshB;
+ this.bufA[i] = 1.0;
+ this.bufCarry[i] = 0.0;
+ if (usePigment) {
+ const lo = i * 7;
+ latBuf[lo] = freshLat[0];
+ latBuf[lo + 1] = freshLat[1];
+ latBuf[lo + 2] = freshLat[2];
+ latBuf[lo + 3] = freshLat[3];
+ latBuf[lo + 4] = freshLat[4];
+ latBuf[lo + 5] = freshLat[5];
+ latBuf[lo + 6] = freshLat[6];
+ }
+ }
+ sumBufR = freshR * totalTexels;
+ sumBufG = freshG * totalTexels;
+ sumBufB = freshB * totalTexels;
+ sumBufA = totalTexels;
+ if (usePigment) this.latInitialized = true;
+ } else if (usePigment) {
+ for (let gy = 0; gy < gh; gy++) {
+ const ny = ((gy + 0.5) * invGh - 0.5) * 2.0;
+ const ly = ny * halfH;
+ const rowOff = gy * gw;
+ let wx = p.x + lx0Start * cosA - ly * sinA;
+ let wy = p.y + lx0Start * sinA + ly * cosA;
+ for (let gx = 0; gx < gw; gx++) {
+ const idx = rowOff + gx;
+ const lo = idx * 7;
+ const sampled = sampler
+ ? sampler.sampleBilinearLatentFast(wx, wy, this.sampleScratch, latSamp, 0)
+ : ((this.sampleScratch.a = 0), this.sampleScratch);
+ wx += dWxStep;
+ wy += dWyStep;
+ const ca = sampled.a;
+
+ if (ca > 0.015) {
+ pickedUpCanvas = true;
+ if (blendUniformity > 0.001) {
+ canvasSumR += sampled.r * ca;
+ canvasSumG += sampled.g * ca;
+ canvasSumB += sampled.b * ca;
+ this.canvasLatSum[0] += latSamp[0] * ca;
+ this.canvasLatSum[1] += latSamp[1] * ca;
+ this.canvasLatSum[2] += latSamp[2] * ca;
+ this.canvasLatSum[3] += latSamp[3] * ca;
+ this.canvasLatSum[4] += latSamp[4] * ca;
+ this.canvasLatSum[5] += latSamp[5] * ca;
+ this.canvasLatSum[6] += latSamp[6] * ca;
+ canvasAlphaSum += ca;
+ }
+ }
- if (firstTouch) {
- if (isPureSmudge) {
- this.bufR[idx] = sampled.r;
- this.bufG[idx] = sampled.g;
- this.bufB[idx] = sampled.b;
- this.bufA[idx] = ca;
- this.bufCarry[idx] = ca;
+ if (firstTouch) {
+ if (isPureSmudge) {
+ if (ca > 0.002) {
+ latBuf[lo] = latSamp[0]; latBuf[lo + 1] = latSamp[1]; latBuf[lo + 2] = latSamp[2];
+ latBuf[lo + 3] = latSamp[3]; latBuf[lo + 4] = latSamp[4]; latBuf[lo + 5] = latSamp[5];
+ latBuf[lo + 6] = latSamp[6];
+ if (partialPigment) {
+ this.linR[idx] = sampled.r; this.linG[idx] = sampled.g; this.linB[idx] = sampled.b;
+ }
+ } else {
+ latBuf[lo] = 0; latBuf[lo + 1] = 0; latBuf[lo + 2] = 0; latBuf[lo + 3] = 1;
+ latBuf[lo + 4] = 0; latBuf[lo + 5] = 0; latBuf[lo + 6] = 0;
+ if (partialPigment) {
+ this.linR[idx] = 255; this.linG[idx] = 255; this.linB[idx] = 255;
+ }
+ }
+ this.bufA[idx] = ca;
+ this.bufCarry[idx] = ca;
+ } else if (ca > 0.015) {
+ const wCanvas = (1.0 - clampedAmount) * stretchPickupBoost * ca;
+ const eqFresh = wFreshFirst / Math.max(1e-4, wFreshFirst + wCanvas);
+ const invEq = 1.0 - eqFresh;
+ latBuf[lo] = latSamp[0] * invEq + freshLat[0] * eqFresh;
+ latBuf[lo + 1] = latSamp[1] * invEq + freshLat[1] * eqFresh;
+ latBuf[lo + 2] = latSamp[2] * invEq + freshLat[2] * eqFresh;
+ latBuf[lo + 3] = latSamp[3] * invEq + freshLat[3] * eqFresh;
+ latBuf[lo + 4] = latSamp[4] * invEq + freshLat[4] * eqFresh;
+ latBuf[lo + 5] = latSamp[5] * invEq + freshLat[5] * eqFresh;
+ latBuf[lo + 6] = latSamp[6] * invEq + freshLat[6] * eqFresh;
+ if (partialPigment) {
+ this.linR[idx] = sampled.r * invEq + freshR * eqFresh;
+ this.linG[idx] = sampled.g * invEq + freshG * eqFresh;
+ this.linB[idx] = sampled.b * invEq + freshB * eqFresh;
+ }
+ this.bufA[idx] = 1.0;
+ this.bufCarry[idx] = Math.min(1.0, ca * (1.0 - eqFresh * 0.65));
+ } else {
+ latBuf[lo] = freshLat[0]; latBuf[lo + 1] = freshLat[1]; latBuf[lo + 2] = freshLat[2];
+ latBuf[lo + 3] = freshLat[3]; latBuf[lo + 4] = freshLat[4]; latBuf[lo + 5] = freshLat[5];
+ latBuf[lo + 6] = freshLat[6];
+ if (partialPigment) {
+ this.linR[idx] = freshR; this.linG[idx] = freshG; this.linB[idx] = freshB;
+ }
+ this.bufA[idx] = 1.0;
+ this.bufCarry[idx] = 0.0;
+ }
} else if (ca > 0.015) {
- const wCanvas = (1.0 - clampedAmount) * stretchPickupBoost * ca;
- const wFresh = clampedAmount * (isRunning ? 0.75 : 0.9);
- const eqFresh = wFresh / Math.max(1e-4, wFresh + wCanvas);
- const m = mixColorInto(sampled.r, sampled.g, sampled.b, this.origR, this.origG, this.origB, eqFresh);
- this.bufR[idx] = m.r;
- this.bufG[idx] = m.g;
- this.bufB[idx] = m.b;
- this.bufA[idx] = 1.0;
- this.bufCarry[idx] = Math.min(1.0, ca * (1.0 - eqFresh * 0.65));
- } else {
- this.bufR[idx] = this.origR;
- this.bufG[idx] = this.origG;
- this.bufB[idx] = this.origB;
- this.bufA[idx] = 1.0;
- this.bufCarry[idx] = 0.0;
+ if (isPureSmudge) {
+ const rate = Math.min(1.0, pickupRate * (0.55 + 0.45 * ca));
+ const curA = this.bufA[idx];
+ if (curA <= 0.02) {
+ latBuf[lo] = latSamp[0]; latBuf[lo + 1] = latSamp[1]; latBuf[lo + 2] = latSamp[2];
+ latBuf[lo + 3] = latSamp[3]; latBuf[lo + 4] = latSamp[4]; latBuf[lo + 5] = latSamp[5];
+ latBuf[lo + 6] = latSamp[6];
+ if (partialPigment) {
+ this.linR[idx] = sampled.r; this.linG[idx] = sampled.g; this.linB[idx] = sampled.b;
+ }
+ this.bufA[idx] = ca;
+ this.bufCarry[idx] = ca;
+ } else {
+ latBuf[lo] += (latSamp[0] - latBuf[lo]) * rate;
+ latBuf[lo + 1] += (latSamp[1] - latBuf[lo + 1]) * rate;
+ latBuf[lo + 2] += (latSamp[2] - latBuf[lo + 2]) * rate;
+ latBuf[lo + 3] += (latSamp[3] - latBuf[lo + 3]) * rate;
+ latBuf[lo + 4] += (latSamp[4] - latBuf[lo + 4]) * rate;
+ latBuf[lo + 5] += (latSamp[5] - latBuf[lo + 5]) * rate;
+ latBuf[lo + 6] += (latSamp[6] - latBuf[lo + 6]) * rate;
+ if (partialPigment) {
+ this.linR[idx] += (sampled.r - this.linR[idx]) * rate;
+ this.linG[idx] += (sampled.g - this.linG[idx]) * rate;
+ this.linB[idx] += (sampled.b - this.linB[idx]) * rate;
+ }
+ const aStep = rate > 0.35 ? rate : 0.35;
+ this.bufA[idx] = Math.min(1.0, curA + (ca - curA) * aStep);
+ this.bufCarry[idx] = Math.min(1.0, this.bufCarry[idx] + (ca - this.bufCarry[idx]) * aStep);
+ }
+ } else {
+ const wCanvas = (1.0 - clampedAmount) * stretchPickupBoost * ca;
+ const eqFresh = wFreshBase / Math.max(1e-4, wFreshBase + wCanvas);
+ const invEq = 1.0 - eqFresh;
+ latBuf[lo] += (latSamp[0] * invEq + freshLat[0] * eqFresh - latBuf[lo]) * pickupRate;
+ latBuf[lo + 1] += (latSamp[1] * invEq + freshLat[1] * eqFresh - latBuf[lo + 1]) * pickupRate;
+ latBuf[lo + 2] += (latSamp[2] * invEq + freshLat[2] * eqFresh - latBuf[lo + 2]) * pickupRate;
+ latBuf[lo + 3] += (latSamp[3] * invEq + freshLat[3] * eqFresh - latBuf[lo + 3]) * pickupRate;
+ latBuf[lo + 4] += (latSamp[4] * invEq + freshLat[4] * eqFresh - latBuf[lo + 4]) * pickupRate;
+ latBuf[lo + 5] += (latSamp[5] * invEq + freshLat[5] * eqFresh - latBuf[lo + 5]) * pickupRate;
+ latBuf[lo + 6] += (latSamp[6] * invEq + freshLat[6] * eqFresh - latBuf[lo + 6]) * pickupRate;
+ if (partialPigment) {
+ this.linR[idx] += (sampled.r * invEq + freshR * eqFresh - this.linR[idx]) * pickupRate;
+ this.linG[idx] += (sampled.g * invEq + freshG * eqFresh - this.linG[idx]) * pickupRate;
+ this.linB[idx] += (sampled.b * invEq + freshB * eqFresh - this.linB[idx]) * pickupRate;
+ }
+ this.bufA[idx] = Math.min(1.0, this.bufA[idx] + (1.0 - this.bufA[idx]) * pickupRate);
+ const targetCarry = Math.min(1.0, ca * (1.0 - eqFresh * 0.55));
+ this.bufCarry[idx] += (targetCarry - this.bufCarry[idx]) * pickupRate;
+ }
+ } else if (step > 0) {
+ if (isPureSmudge) {
+ this.bufA[idx] = Math.max(0, this.bufA[idx] * (1.0 - smudgeDecay));
+ this.bufCarry[idx] = Math.max(0, this.bufCarry[idx] * (1.0 - carryDecay));
+ } else {
+ latBuf[lo] += (freshLat[0] - latBuf[lo]) * recoverRate;
+ latBuf[lo + 1] += (freshLat[1] - latBuf[lo + 1]) * recoverRate;
+ latBuf[lo + 2] += (freshLat[2] - latBuf[lo + 2]) * recoverRate;
+ latBuf[lo + 3] += (freshLat[3] - latBuf[lo + 3]) * recoverRate;
+ latBuf[lo + 4] += (freshLat[4] - latBuf[lo + 4]) * recoverRate;
+ latBuf[lo + 5] += (freshLat[5] - latBuf[lo + 5]) * recoverRate;
+ latBuf[lo + 6] += (freshLat[6] - latBuf[lo + 6]) * recoverRate;
+ if (partialPigment) {
+ this.linR[idx] += (freshR - this.linR[idx]) * recoverRate;
+ this.linG[idx] += (freshG - this.linG[idx]) * recoverRate;
+ this.linB[idx] += (freshB - this.linB[idx]) * recoverRate;
+ }
+ this.bufA[idx] = Math.min(1.0, this.bufA[idx] + (1.0 - this.bufA[idx]) * recoverRate);
+ this.bufCarry[idx] = Math.max(0, this.bufCarry[idx] * (1.0 - carryDecay));
+ }
}
- } else if (ca > 0.015) {
- if (isPureSmudge) {
- const rate = Math.min(1.0, pickupRate * (0.45 + 0.55 * ca));
- const curA = this.bufA[idx];
- if (curA <= 0.01) {
+ sumBufA += this.bufA[idx];
+ }
+ }
+ this.latInitialized = true;
+ } else {
+ // Fast pure linear RGB path (Regular / perceptualMixing=false)
+ for (let gy = 0; gy < gh; gy++) {
+ const ny = ((gy + 0.5) * invGh - 0.5) * 2.0;
+ const ly = ny * halfH;
+ const rowOff = gy * gw;
+ let wx = p.x + lx0Start * cosA - ly * sinA;
+ let wy = p.y + lx0Start * sinA + ly * cosA;
+ for (let gx = 0; gx < gw; gx++) {
+ const idx = rowOff + gx;
+ const sampled = sampler
+ ? sampler.sampleBilinearFast(wx, wy, this.sampleScratch, false)
+ : ((this.sampleScratch.a = 0), this.sampleScratch);
+ wx += dWxStep;
+ wy += dWyStep;
+ const ca = sampled.a;
+ if (ca > 0.015) {
+ pickedUpCanvas = true;
+ if (blendUniformity > 0.001) {
+ canvasSumR += sampled.r * ca;
+ canvasSumG += sampled.g * ca;
+ canvasSumB += sampled.b * ca;
+ canvasAlphaSum += ca;
+ }
+ }
+
+ if (firstTouch) {
+ if (isPureSmudge) {
this.bufR[idx] = sampled.r;
this.bufG[idx] = sampled.g;
this.bufB[idx] = sampled.b;
- this.bufA[idx] = ca * rate;
+ this.bufA[idx] = ca;
+ this.bufCarry[idx] = ca;
+ } else if (ca > 0.015) {
+ const wCanvas = (1.0 - clampedAmount) * stretchPickupBoost * ca;
+ const eqFresh = wFreshFirst / Math.max(1e-4, wFreshFirst + wCanvas);
+ const invEq = 1.0 - eqFresh;
+ this.bufR[idx] = sampled.r * invEq + freshR * eqFresh;
+ this.bufG[idx] = sampled.g * invEq + freshG * eqFresh;
+ this.bufB[idx] = sampled.b * invEq + freshB * eqFresh;
+ this.bufA[idx] = 1.0;
+ this.bufCarry[idx] = Math.min(1.0, ca * (1.0 - eqFresh * 0.65));
+ } else {
+ this.bufR[idx] = freshR;
+ this.bufG[idx] = freshG;
+ this.bufB[idx] = freshB;
+ this.bufA[idx] = 1.0;
+ this.bufCarry[idx] = 0.0;
+ }
+ } else if (ca > 0.015) {
+ if (isPureSmudge) {
+ const rate = Math.min(1.0, pickupRate * (0.55 + 0.45 * ca));
+ const curA = this.bufA[idx];
+ if (curA <= 0.02) {
+ this.bufR[idx] = sampled.r;
+ this.bufG[idx] = sampled.g;
+ this.bufB[idx] = sampled.b;
+ this.bufA[idx] = ca;
+ this.bufCarry[idx] = ca;
+ } else {
+ this.bufR[idx] += (sampled.r - this.bufR[idx]) * rate;
+ this.bufG[idx] += (sampled.g - this.bufG[idx]) * rate;
+ this.bufB[idx] += (sampled.b - this.bufB[idx]) * rate;
+ const aStep = rate > 0.35 ? rate : 0.35;
+ this.bufA[idx] = Math.min(1.0, curA + (ca - curA) * aStep);
+ this.bufCarry[idx] = Math.min(1.0, this.bufCarry[idx] + (ca - this.bufCarry[idx]) * aStep);
+ }
} else {
- const m = mixColorInto(this.bufR[idx], this.bufG[idx], this.bufB[idx], sampled.r, sampled.g, sampled.b, rate);
- this.bufR[idx] = m.r;
- this.bufG[idx] = m.g;
- this.bufB[idx] = m.b;
- this.bufA[idx] = curA + (ca - curA) * rate;
+ const wCanvas = (1.0 - clampedAmount) * stretchPickupBoost * ca;
+ const eqFresh = wFreshBase / Math.max(1e-4, wFreshBase + wCanvas);
+ const invEq = 1.0 - eqFresh;
+ const eqR = sampled.r * invEq + freshR * eqFresh;
+ const eqG = sampled.g * invEq + freshG * eqFresh;
+ const eqB = sampled.b * invEq + freshB * eqFresh;
+ this.bufR[idx] += (eqR - this.bufR[idx]) * pickupRate;
+ this.bufG[idx] += (eqG - this.bufG[idx]) * pickupRate;
+ this.bufB[idx] += (eqB - this.bufB[idx]) * pickupRate;
+ this.bufA[idx] = Math.min(1.0, this.bufA[idx] + (1.0 - this.bufA[idx]) * pickupRate);
+ const targetCarry = Math.min(1.0, ca * (1.0 - eqFresh * 0.55));
+ this.bufCarry[idx] += (targetCarry - this.bufCarry[idx]) * pickupRate;
}
- this.bufCarry[idx] = Math.min(1.0, this.bufCarry[idx] + (ca - this.bufCarry[idx]) * rate);
+ } else if (step > 0) {
+ if (isPureSmudge) {
+ this.bufA[idx] = Math.max(0, this.bufA[idx] * (1.0 - smudgeDecay));
+ this.bufCarry[idx] = Math.max(0, this.bufCarry[idx] * (1.0 - carryDecay));
+ } else {
+ this.bufR[idx] += (freshR - this.bufR[idx]) * recoverRate;
+ this.bufG[idx] += (freshG - this.bufG[idx]) * recoverRate;
+ this.bufB[idx] += (freshB - this.bufB[idx]) * recoverRate;
+ this.bufA[idx] = Math.min(1.0, this.bufA[idx] + (1.0 - this.bufA[idx]) * recoverRate);
+ this.bufCarry[idx] = Math.max(0, this.bufCarry[idx] * (1.0 - carryDecay));
+ }
+ }
+ sumBufR += this.bufR[idx];
+ sumBufG += this.bufG[idx];
+ sumBufB += this.bufB[idx];
+ sumBufA += this.bufA[idx];
+ }
+ }
+ this.latInitialized = false;
+ }
+
+ this.initialized = true;
+
+ // Early exit for pure blenders on completely empty canvas (zero visible pixels!)
+ if (isPureSmudge && sumBufA <= 0.002) {
+ return null;
+ }
+
+ // 1b. CSP Blend (BrushWaterColor=0) footprint-averaged isotropic tip mixing for compact/round tips
+ if (blendUniformity > 0.001) {
+ const avgCanvasCa = canvasAlphaSum / Math.max(1, totalTexels);
+ const hasCanvasAvg = avgCanvasCa > 0.015 && canvasAlphaSum > 1e-4;
+ const invCa = hasCanvasAvg ? 1 / canvasAlphaSum : 0;
+ const u = blendUniformity;
+ const invU = 1.0 - u;
+
+ if (usePigment) {
+ const uniLat = this.uniLat;
+ if (hasCanvasAvg) {
+ for (let c = 0; c < 7; c++) latSamp[c] = this.canvasLatSum[c] * invCa;
+ }
+ const avgLinR = hasCanvasAvg ? canvasSumR * invCa : 0;
+ const avgLinG = hasCanvasAvg ? canvasSumG * invCa : 0;
+ const avgLinB = hasCanvasAvg ? canvasSumB * invCa : 0;
+
+ if (firstTouch) {
+ if (hasCanvasAvg) {
+ const wCanvasUni = (1.0 - clampedAmount) * stretchPickupBoost * avgCanvasCa;
+ const uniFresh = wFreshFirst / Math.max(1e-4, wFreshFirst + wCanvasUni);
+ const invUF = 1.0 - uniFresh;
+ for (let c = 0; c < 7; c++) uniLat[c] = latSamp[c] * invUF + freshLat[c] * uniFresh;
+ this.uniR = avgLinR * invUF + freshR * uniFresh;
+ this.uniG = avgLinG * invUF + freshG * uniFresh;
+ this.uniB = avgLinB * invUF + freshB * uniFresh;
+ this.uniCarry = Math.min(1.0, avgCanvasCa * (1.0 - uniFresh * 0.65));
} else {
- const wCanvas = (1.0 - clampedAmount) * stretchPickupBoost * ca;
- const wFresh = clampedAmount * (isRunning ? 0.72 : 0.88);
- const eqFresh = wFresh / Math.max(1e-4, wFresh + wCanvas);
- const eq = mixColorInto(sampled.r, sampled.g, sampled.b, this.origR, this.origG, this.origB, eqFresh);
- const eqR = eq.r;
- const eqG = eq.g;
- const eqB = eq.b;
- const m = mixColorInto(this.bufR[idx], this.bufG[idx], this.bufB[idx], eqR, eqG, eqB, pickupRate);
- this.bufR[idx] = m.r;
- this.bufG[idx] = m.g;
- this.bufB[idx] = m.b;
- this.bufA[idx] = Math.min(1.0, this.bufA[idx] + (1.0 - this.bufA[idx]) * pickupRate);
- const targetCarry = Math.min(1.0, ca * (1.0 - eqFresh * 0.55));
- this.bufCarry[idx] = this.bufCarry[idx] + (targetCarry - this.bufCarry[idx]) * pickupRate;
+ for (let c = 0; c < 7; c++) uniLat[c] = freshLat[c];
+ this.uniR = freshR;
+ this.uniG = freshG;
+ this.uniB = freshB;
+ this.uniCarry = 0.0;
+ }
+ } else if (hasCanvasAvg) {
+ const wCanvasUni = (1.0 - clampedAmount) * stretchPickupBoost * avgCanvasCa;
+ const uniFresh = wFreshBase / Math.max(1e-4, wFreshBase + wCanvasUni);
+ const invUF = 1.0 - uniFresh;
+ for (let c = 0; c < 7; c++) {
+ latEq[c] = latSamp[c] * invUF + freshLat[c] * uniFresh;
+ uniLat[c] += (latEq[c] - uniLat[c]) * pickupRate;
+ }
+ if (partialPigment) {
+ this.uniR += (avgLinR * invUF + freshR * uniFresh - this.uniR) * pickupRate;
+ this.uniG += (avgLinG * invUF + freshG * uniFresh - this.uniG) * pickupRate;
+ this.uniB += (avgLinB * invUF + freshB * uniFresh - this.uniB) * pickupRate;
}
+ const targetCarry = Math.min(1.0, avgCanvasCa * (1.0 - uniFresh * 0.55));
+ this.uniCarry += (targetCarry - this.uniCarry) * pickupRate;
} else if (step > 0) {
- if (isPureSmudge) {
- this.bufA[idx] = Math.max(0, this.bufA[idx] * (1.0 - smudgeDecay));
- this.bufCarry[idx] = Math.max(0, this.bufCarry[idx] * (1.0 - carryDecay));
+ for (let c = 0; c < 7; c++) uniLat[c] += (freshLat[c] - uniLat[c]) * recoverRate;
+ if (partialPigment) {
+ this.uniR += (freshR - this.uniR) * recoverRate;
+ this.uniG += (freshG - this.uniG) * recoverRate;
+ this.uniB += (freshB - this.uniB) * recoverRate;
+ }
+ this.uniCarry = Math.max(0, this.uniCarry * (1.0 - carryDecay));
+ }
+
+ const u0 = uniLat[0], u1 = uniLat[1], u2 = uniLat[2], u3 = uniLat[3], u4 = uniLat[4], u5 = uniLat[5], u6 = uniLat[6];
+ for (let i = 0; i < totalTexels; i++) {
+ const lo = i * 7;
+ latBuf[lo] = latBuf[lo] * invU + u0 * u;
+ latBuf[lo + 1] = latBuf[lo + 1] * invU + u1 * u;
+ latBuf[lo + 2] = latBuf[lo + 2] * invU + u2 * u;
+ latBuf[lo + 3] = latBuf[lo + 3] * invU + u3 * u;
+ latBuf[lo + 4] = latBuf[lo + 4] * invU + u4 * u;
+ latBuf[lo + 5] = latBuf[lo + 5] * invU + u5 * u;
+ latBuf[lo + 6] = latBuf[lo + 6] * invU + u6 * u;
+ if (partialPigment) {
+ this.linR[i] = this.linR[i] * invU + this.uniR * u;
+ this.linG[i] = this.linG[i] * invU + this.uniG * u;
+ this.linB[i] = this.linB[i] * invU + this.uniB * u;
+ }
+ this.bufCarry[i] = this.bufCarry[i] * invU + this.uniCarry * u;
+ }
+ } else {
+ const avgCr = hasCanvasAvg ? canvasSumR * invCa : 0;
+ const avgCg = hasCanvasAvg ? canvasSumG * invCa : 0;
+ const avgCb = hasCanvasAvg ? canvasSumB * invCa : 0;
+ if (firstTouch) {
+ if (hasCanvasAvg) {
+ const wCanvasUni = (1.0 - clampedAmount) * stretchPickupBoost * avgCanvasCa;
+ const uniFresh = wFreshFirst / Math.max(1e-4, wFreshFirst + wCanvasUni);
+ const invUF = 1.0 - uniFresh;
+ this.uniR = avgCr * invUF + freshR * uniFresh;
+ this.uniG = avgCg * invUF + freshG * uniFresh;
+ this.uniB = avgCb * invUF + freshB * uniFresh;
+ this.uniCarry = Math.min(1.0, avgCanvasCa * (1.0 - uniFresh * 0.65));
} else {
- const m = mixColorInto(
- this.bufR[idx],
- this.bufG[idx],
- this.bufB[idx],
- this.origR,
- this.origG,
- this.origB,
- recoverRate
- );
- this.bufR[idx] = m.r;
- this.bufG[idx] = m.g;
- this.bufB[idx] = m.b;
- this.bufA[idx] = Math.min(1.0, this.bufA[idx] + (1.0 - this.bufA[idx]) * recoverRate);
- this.bufCarry[idx] = Math.max(0, this.bufCarry[idx] * (1.0 - carryDecay));
+ this.uniR = freshR;
+ this.uniG = freshG;
+ this.uniB = freshB;
+ this.uniCarry = 0.0;
}
+ } else if (hasCanvasAvg) {
+ const wCanvasUni = (1.0 - clampedAmount) * stretchPickupBoost * avgCanvasCa;
+ const uniFresh = wFreshBase / Math.max(1e-4, wFreshBase + wCanvasUni);
+ const invUF = 1.0 - uniFresh;
+ this.uniR += (avgCr * invUF + freshR * uniFresh - this.uniR) * pickupRate;
+ this.uniG += (avgCg * invUF + freshG * uniFresh - this.uniG) * pickupRate;
+ this.uniB += (avgCb * invUF + freshB * uniFresh - this.uniB) * pickupRate;
+ const targetCarry = Math.min(1.0, avgCanvasCa * (1.0 - uniFresh * 0.55));
+ this.uniCarry += (targetCarry - this.uniCarry) * pickupRate;
+ } else if (step > 0) {
+ this.uniR += (freshR - this.uniR) * recoverRate;
+ this.uniG += (freshG - this.uniG) * recoverRate;
+ this.uniB += (freshB - this.uniB) * recoverRate;
+ this.uniCarry = Math.max(0, this.uniCarry * (1.0 - carryDecay));
+ }
+
+ sumBufR = 0;
+ sumBufG = 0;
+ sumBufB = 0;
+ for (let i = 0; i < totalTexels; i++) {
+ const r = this.bufR[i] * invU + this.uniR * u;
+ const g = this.bufG[i] * invU + this.uniG * u;
+ const b = this.bufB[i] * invU + this.uniB * u;
+ this.bufR[i] = r;
+ this.bufG[i] = g;
+ this.bufB[i] = b;
+ this.bufCarry[i] = this.bufCarry[i] * invU + this.uniCarry * u;
+ sumBufR += r;
+ sumBufG += g;
+ sumBufB += b;
}
- sumBufR += this.bufR[idx];
- sumBufG += this.bufG[idx];
- sumBufB += this.bufB[idx];
- sumBufA += this.bufA[idx];
}
}
- this.initialized = true;
-
- // 2. Gentle lateral diffusion (softens red-to-black cross-brush seam like real oil paint)
- if (!isFullFresh && step > 0 && gw >= 4 && gh >= 4) {
- const diff = (isRunning ? 0.095 : 0.045) * Math.min(1, step / Math.max(1, thinSpan * 0.28));
- if (diff > 0.003) {
- const centerW = 1.0 - 2.0 * diff;
- const wideAlongX = p.width >= p.height;
- if (wideAlongX) {
- for (let gy = 0; gy < gh; gy++) {
- const row = gy * gw;
- this.tmpR[row] = this.bufR[row];
- this.tmpG[row] = this.bufG[row];
- this.tmpB[row] = this.bufB[row];
- this.tmpR[row + gw - 1] = this.bufR[row + gw - 1];
- this.tmpG[row + gw - 1] = this.bufG[row + gw - 1];
- this.tmpB[row + gw - 1] = this.bufB[row + gw - 1];
- for (let gx = 1; gx < gw - 1; gx++) {
- const i = row + gx;
- this.tmpR[i] = this.bufR[i - 1] * diff + this.bufR[i] * centerW + this.bufR[i + 1] * diff;
- this.tmpG[i] = this.bufG[i - 1] * diff + this.bufG[i] * centerW + this.bufG[i + 1] * diff;
- this.tmpB[i] = this.bufB[i - 1] * diff + this.bufB[i] * centerW + this.bufB[i + 1] * diff;
+ // 2. Lateral / isotropic pigment diffusion & CSP useBlur optical smoothing:
+ // - When pigment mode is active, `this.latBuf` is ALREADY in 7-channel Kubelka-Munk latent space
+ // so convolution runs directly with ZERO per-dab re-encoding!
+ if (!isFullFresh && blendUniformity < 0.999 && gw >= 4 && gh >= 4) {
+ if (blurAmt > 0.005) {
+ const passes = blurAmt >= 0.45 ? 2 : 1;
+ const k = Math.min(0.34, 0.08 + blurAmt * 0.30);
+ const cW = 1.0 - 2.0 * k;
+ if (usePigment) {
+ const latTmp = this.latTmp;
+ for (let pass = 0; pass < passes; pass++) {
+ for (let gy = 0; gy < gh; gy++) {
+ const row = gy * gw;
+ for (let gx = 0; gx < gw; gx++) {
+ const i = row + gx;
+ const lo = i * 7;
+ const aC = this.bufA[i];
+ if (aC <= 0.001) {
+ latTmp[lo] = latBuf[lo]; latTmp[lo + 1] = latBuf[lo + 1]; latTmp[lo + 2] = latBuf[lo + 2];
+ latTmp[lo + 3] = latBuf[lo + 3]; latTmp[lo + 4] = latBuf[lo + 4]; latTmp[lo + 5] = latBuf[lo + 5];
+ latTmp[lo + 6] = latBuf[lo + 6];
+ continue;
+ }
+ const iL = row + (gx > 0 ? gx - 1 : 0);
+ const iR = row + (gx < gw - 1 ? gx + 1 : gw - 1);
+ const wL = k * this.bufA[iL];
+ const wC = cW * aC;
+ const wR = k * this.bufA[iR];
+ const wSum = wL + wC + wR;
+ if (wSum > 1e-4) {
+ const invW = 1.0 / wSum;
+ const loL = iL * 7;
+ const loR = iR * 7;
+ latTmp[lo] = (latBuf[loL] * wL + latBuf[lo] * wC + latBuf[loR] * wR) * invW;
+ latTmp[lo + 1] = (latBuf[loL + 1] * wL + latBuf[lo + 1] * wC + latBuf[loR + 1] * wR) * invW;
+ latTmp[lo + 2] = (latBuf[loL + 2] * wL + latBuf[lo + 2] * wC + latBuf[loR + 2] * wR) * invW;
+ latTmp[lo + 3] = (latBuf[loL + 3] * wL + latBuf[lo + 3] * wC + latBuf[loR + 3] * wR) * invW;
+ latTmp[lo + 4] = (latBuf[loL + 4] * wL + latBuf[lo + 4] * wC + latBuf[loR + 4] * wR) * invW;
+ latTmp[lo + 5] = (latBuf[loL + 5] * wL + latBuf[lo + 5] * wC + latBuf[loR + 5] * wR) * invW;
+ latTmp[lo + 6] = (latBuf[loL + 6] * wL + latBuf[lo + 6] * wC + latBuf[loR + 6] * wR) * invW;
+ } else {
+ latTmp[lo] = latBuf[lo]; latTmp[lo + 1] = latBuf[lo + 1]; latTmp[lo + 2] = latBuf[lo + 2];
+ latTmp[lo + 3] = latBuf[lo + 3]; latTmp[lo + 4] = latBuf[lo + 4]; latTmp[lo + 5] = latBuf[lo + 5];
+ latTmp[lo + 6] = latBuf[lo + 6];
+ }
+ }
+ }
+ for (let gy = 0; gy < gh; gy++) {
+ const row = gy * gw;
+ const rowUp = (gy > 0 ? gy - 1 : 0) * gw;
+ const rowDn = (gy < gh - 1 ? gy + 1 : gh - 1) * gw;
+ for (let gx = 0; gx < gw; gx++) {
+ const i = row + gx;
+ const lo = i * 7;
+ const aC = this.bufA[i];
+ if (aC <= 0.001) {
+ latBuf[lo] = latTmp[lo]; latBuf[lo + 1] = latTmp[lo + 1]; latBuf[lo + 2] = latTmp[lo + 2];
+ latBuf[lo + 3] = latTmp[lo + 3]; latBuf[lo + 4] = latTmp[lo + 4]; latBuf[lo + 5] = latTmp[lo + 5];
+ latBuf[lo + 6] = latTmp[lo + 6];
+ continue;
+ }
+ const iU = rowUp + gx;
+ const iD = rowDn + gx;
+ const wU = k * this.bufA[iU];
+ const wC = cW * aC;
+ const wD = k * this.bufA[iD];
+ const wSum = wU + wC + wD;
+ if (wSum > 1e-4) {
+ const invW = 1.0 / wSum;
+ const loU = iU * 7;
+ const loD = iD * 7;
+ latBuf[lo] = (latTmp[loU] * wU + latTmp[lo] * wC + latTmp[loD] * wD) * invW;
+ latBuf[lo + 1] = (latTmp[loU + 1] * wU + latTmp[lo + 1] * wC + latTmp[loD + 1] * wD) * invW;
+ latBuf[lo + 2] = (latTmp[loU + 2] * wU + latTmp[lo + 2] * wC + latTmp[loD + 2] * wD) * invW;
+ latBuf[lo + 3] = (latTmp[loU + 3] * wU + latTmp[lo + 3] * wC + latTmp[loD + 3] * wD) * invW;
+ latBuf[lo + 4] = (latTmp[loU + 4] * wU + latTmp[lo + 4] * wC + latTmp[loD + 4] * wD) * invW;
+ latBuf[lo + 5] = (latTmp[loU + 5] * wU + latTmp[lo + 5] * wC + latTmp[loD + 5] * wD) * invW;
+ latBuf[lo + 6] = (latTmp[loU + 6] * wU + latTmp[lo + 6] * wC + latTmp[loD + 6] * wD) * invW;
+ } else {
+ latBuf[lo] = latTmp[lo]; latBuf[lo + 1] = latTmp[lo + 1]; latBuf[lo + 2] = latTmp[lo + 2];
+ latBuf[lo + 3] = latTmp[lo + 3]; latBuf[lo + 4] = latTmp[lo + 4]; latBuf[lo + 5] = latTmp[lo + 5];
+ latBuf[lo + 6] = latTmp[lo + 6];
+ }
+ }
}
}
} else {
- for (let gx = 0; gx < gw; gx++) {
- this.tmpR[gx] = this.bufR[gx];
- this.tmpG[gx] = this.bufG[gx];
- this.tmpB[gx] = this.bufB[gx];
- const last = (gh - 1) * gw + gx;
- this.tmpR[last] = this.bufR[last];
- this.tmpG[last] = this.bufG[last];
- this.tmpB[last] = this.bufB[last];
+ for (let pass = 0; pass < passes; pass++) {
+ for (let gy = 0; gy < gh; gy++) {
+ const row = gy * gw;
+ for (let gx = 0; gx < gw; gx++) {
+ const i = row + gx;
+ const aC = this.bufA[i];
+ if (aC <= 0.001) {
+ this.tmpR[i] = this.bufR[i];
+ this.tmpG[i] = this.bufG[i];
+ this.tmpB[i] = this.bufB[i];
+ continue;
+ }
+ const iL = row + (gx > 0 ? gx - 1 : 0);
+ const iR = row + (gx < gw - 1 ? gx + 1 : gw - 1);
+ const wL = k * this.bufA[iL];
+ const wC = cW * aC;
+ const wR = k * this.bufA[iR];
+ const wSum = wL + wC + wR;
+ if (wSum > 1e-4) {
+ const invW = 1.0 / wSum;
+ this.tmpR[i] = (this.bufR[iL] * wL + this.bufR[i] * wC + this.bufR[iR] * wR) * invW;
+ this.tmpG[i] = (this.bufG[iL] * wL + this.bufG[i] * wC + this.bufG[iR] * wR) * invW;
+ this.tmpB[i] = (this.bufB[iL] * wL + this.bufB[i] * wC + this.bufB[iR] * wR) * invW;
+ } else {
+ this.tmpR[i] = this.bufR[i];
+ this.tmpG[i] = this.bufG[i];
+ this.tmpB[i] = this.bufB[i];
+ }
+ }
+ }
+ for (let gy = 0; gy < gh; gy++) {
+ const row = gy * gw;
+ const rowUp = (gy > 0 ? gy - 1 : 0) * gw;
+ const rowDn = (gy < gh - 1 ? gy + 1 : gh - 1) * gw;
+ for (let gx = 0; gx < gw; gx++) {
+ const i = row + gx;
+ const aC = this.bufA[i];
+ if (aC <= 0.001) {
+ this.bufR[i] = this.tmpR[i];
+ this.bufG[i] = this.tmpG[i];
+ this.bufB[i] = this.tmpB[i];
+ continue;
+ }
+ const iU = rowUp + gx;
+ const iD = rowDn + gx;
+ const wU = k * this.bufA[iU];
+ const wC = cW * aC;
+ const wD = k * this.bufA[iD];
+ const wSum = wU + wC + wD;
+ if (wSum > 1e-4) {
+ const invW = 1.0 / wSum;
+ this.bufR[i] = (this.tmpR[iU] * wU + this.tmpR[i] * wC + this.tmpR[iD] * wD) * invW;
+ this.bufG[i] = (this.tmpG[iU] * wU + this.tmpG[i] * wC + this.tmpG[iD] * wD) * invW;
+ this.bufB[i] = (this.tmpB[iU] * wU + this.tmpB[i] * wC + this.tmpB[iD] * wD) * invW;
+ } else {
+ this.bufR[i] = this.tmpR[i];
+ this.bufG[i] = this.tmpG[i];
+ this.bufB[i] = this.tmpB[i];
+ }
+ }
+ }
+ }
+ }
+ } else if (step > 0) {
+ if (isPureSmudge) {
+ const diffBase = p.tipImage ? 0.014 : 0.075;
+ const diff2d = diffBase * Math.min(1, step / Math.max(1, thinSpan * 0.25));
+ if (diff2d > 0.003) {
+ const centerW = 1.0 - 4.0 * diff2d;
+ if (usePigment) {
+ const latTmp = this.latTmp;
+ for (let gy = 0; gy < gh; gy++) {
+ const row = gy * gw;
+ const rowUp = (gy > 0 ? gy - 1 : 0) * gw;
+ const rowDn = (gy < gh - 1 ? gy + 1 : gh - 1) * gw;
+ for (let gx = 0; gx < gw; gx++) {
+ const i = row + gx;
+ const lo = i * 7;
+ const loL = (row + (gx > 0 ? gx - 1 : 0)) * 7;
+ const loR = (row + (gx < gw - 1 ? gx + 1 : gw - 1)) * 7;
+ const loU = (rowUp + gx) * 7;
+ const loD = (rowDn + gx) * 7;
+ latTmp[lo] = latBuf[lo] * centerW + (latBuf[loL] + latBuf[loR] + latBuf[loU] + latBuf[loD]) * diff2d;
+ latTmp[lo + 1] = latBuf[lo + 1] * centerW + (latBuf[loL + 1] + latBuf[loR + 1] + latBuf[loU + 1] + latBuf[loD + 1]) * diff2d;
+ latTmp[lo + 2] = latBuf[lo + 2] * centerW + (latBuf[loL + 2] + latBuf[loR + 2] + latBuf[loU + 2] + latBuf[loD + 2]) * diff2d;
+ latTmp[lo + 3] = latBuf[lo + 3] * centerW + (latBuf[loL + 3] + latBuf[loR + 3] + latBuf[loU + 3] + latBuf[loD + 3]) * diff2d;
+ latTmp[lo + 4] = latBuf[lo + 4] * centerW + (latBuf[loL + 4] + latBuf[loR + 4] + latBuf[loU + 4] + latBuf[loD + 4]) * diff2d;
+ latTmp[lo + 5] = latBuf[lo + 5] * centerW + (latBuf[loL + 5] + latBuf[loR + 5] + latBuf[loU + 5] + latBuf[loD + 5]) * diff2d;
+ latTmp[lo + 6] = latBuf[lo + 6] * centerW + (latBuf[loL + 6] + latBuf[loR + 6] + latBuf[loU + 6] + latBuf[loD + 6]) * diff2d;
+ }
+ }
+ latBuf.set(latTmp.subarray(0, totalTexels * 7));
+ } else {
+ for (let gy = 0; gy < gh; gy++) {
+ const row = gy * gw;
+ const rowUp = (gy > 0 ? gy - 1 : 0) * gw;
+ const rowDn = (gy < gh - 1 ? gy + 1 : gh - 1) * gw;
+ for (let gx = 0; gx < gw; gx++) {
+ const i = row + gx;
+ const iL = row + (gx > 0 ? gx - 1 : 0);
+ const iR = row + (gx < gw - 1 ? gx + 1 : gw - 1);
+ const iU = rowUp + gx;
+ const iD = rowDn + gx;
+ this.tmpR[i] = this.bufR[i] * centerW + (this.bufR[iL] + this.bufR[iR] + this.bufR[iU] + this.bufR[iD]) * diff2d;
+ this.tmpG[i] = this.bufG[i] * centerW + (this.bufG[iL] + this.bufG[iR] + this.bufG[iU] + this.bufG[iD]) * diff2d;
+ this.tmpB[i] = this.bufB[i] * centerW + (this.bufB[iL] + this.bufB[iR] + this.bufB[iU] + this.bufB[iD]) * diff2d;
+ }
+ }
+ for (let i = 0; i < totalTexels; i++) {
+ this.bufR[i] = this.tmpR[i];
+ this.bufG[i] = this.tmpG[i];
+ this.bufB[i] = this.tmpB[i];
+ }
+ }
}
- for (let gy = 1; gy < gh - 1; gy++) {
- const row = gy * gw;
- for (let gx = 0; gx < gw; gx++) {
- const i = row + gx;
- this.tmpR[i] = this.bufR[i - gw] * diff + this.bufR[i] * centerW + this.bufR[i + gw] * diff;
- this.tmpG[i] = this.bufG[i - gw] * diff + this.bufG[i] * centerW + this.bufG[i + gw] * diff;
- this.tmpB[i] = this.bufB[i - gw] * diff + this.bufB[i] * centerW + this.bufB[i + gw] * diff;
+ } else {
+ const diff = (isRunning ? 0.095 : 0.045) * Math.min(1, step / Math.max(1, thinSpan * 0.28));
+ if (diff > 0.003) {
+ const centerW = 1.0 - 2.0 * diff;
+ const wideAlongX = p.width >= p.height;
+ if (usePigment) {
+ const latTmp = this.latTmp;
+ if (wideAlongX) {
+ for (let gy = 0; gy < gh; gy++) {
+ const row = gy * gw;
+ const firstOff = row * 7;
+ const lastOff = (row + gw - 1) * 7;
+ for (let c = 0; c < 7; c++) {
+ latTmp[firstOff + c] = latBuf[firstOff + c];
+ latTmp[lastOff + c] = latBuf[lastOff + c];
+ }
+ for (let gx = 1; gx < gw - 1; gx++) {
+ const lo = (row + gx) * 7;
+ latTmp[lo] = latBuf[lo - 7] * diff + latBuf[lo] * centerW + latBuf[lo + 7] * diff;
+ latTmp[lo + 1] = latBuf[lo - 6] * diff + latBuf[lo + 1] * centerW + latBuf[lo + 8] * diff;
+ latTmp[lo + 2] = latBuf[lo - 5] * diff + latBuf[lo + 2] * centerW + latBuf[lo + 9] * diff;
+ latTmp[lo + 3] = latBuf[lo - 4] * diff + latBuf[lo + 3] * centerW + latBuf[lo + 10] * diff;
+ latTmp[lo + 4] = latBuf[lo - 3] * diff + latBuf[lo + 4] * centerW + latBuf[lo + 11] * diff;
+ latTmp[lo + 5] = latBuf[lo - 2] * diff + latBuf[lo + 5] * centerW + latBuf[lo + 12] * diff;
+ latTmp[lo + 6] = latBuf[lo - 1] * diff + latBuf[lo + 6] * centerW + latBuf[lo + 13] * diff;
+ }
+ }
+ } else {
+ const stride = gw * 7;
+ for (let gx = 0; gx < gw; gx++) {
+ const topOff = gx * 7;
+ const botOff = ((gh - 1) * gw + gx) * 7;
+ for (let c = 0; c < 7; c++) {
+ latTmp[topOff + c] = latBuf[topOff + c];
+ latTmp[botOff + c] = latBuf[botOff + c];
+ }
+ }
+ for (let gy = 1; gy < gh - 1; gy++) {
+ const row = gy * gw;
+ for (let gx = 0; gx < gw; gx++) {
+ const lo = (row + gx) * 7;
+ latTmp[lo] = latBuf[lo - stride] * diff + latBuf[lo] * centerW + latBuf[lo + stride] * diff;
+ latTmp[lo + 1] = latBuf[lo - stride + 1] * diff + latBuf[lo + 1] * centerW + latBuf[lo + stride + 1] * diff;
+ latTmp[lo + 2] = latBuf[lo - stride + 2] * diff + latBuf[lo + 2] * centerW + latBuf[lo + stride + 2] * diff;
+ latTmp[lo + 3] = latBuf[lo - stride + 3] * diff + latBuf[lo + 3] * centerW + latBuf[lo + stride + 3] * diff;
+ latTmp[lo + 4] = latBuf[lo - stride + 4] * diff + latBuf[lo + 4] * centerW + latBuf[lo + stride + 4] * diff;
+ latTmp[lo + 5] = latBuf[lo - stride + 5] * diff + latBuf[lo + 5] * centerW + latBuf[lo + stride + 5] * diff;
+ latTmp[lo + 6] = latBuf[lo - stride + 6] * diff + latBuf[lo + 6] * centerW + latBuf[lo + stride + 6] * diff;
+ }
+ }
+ }
+ latBuf.set(latTmp.subarray(0, totalTexels * 7));
+ } else {
+ if (wideAlongX) {
+ for (let gy = 0; gy < gh; gy++) {
+ const row = gy * gw;
+ this.tmpR[row] = this.bufR[row];
+ this.tmpG[row] = this.bufG[row];
+ this.tmpB[row] = this.bufB[row];
+ this.tmpR[row + gw - 1] = this.bufR[row + gw - 1];
+ this.tmpG[row + gw - 1] = this.bufG[row + gw - 1];
+ this.tmpB[row + gw - 1] = this.bufB[row + gw - 1];
+ for (let gx = 1; gx < gw - 1; gx++) {
+ const i = row + gx;
+ this.tmpR[i] = this.bufR[i - 1] * diff + this.bufR[i] * centerW + this.bufR[i + 1] * diff;
+ this.tmpG[i] = this.bufG[i - 1] * diff + this.bufG[i] * centerW + this.bufG[i + 1] * diff;
+ this.tmpB[i] = this.bufB[i - 1] * diff + this.bufB[i] * centerW + this.bufB[i + 1] * diff;
+ }
+ }
+ } else {
+ for (let gx = 0; gx < gw; gx++) {
+ this.tmpR[gx] = this.bufR[gx];
+ this.tmpG[gx] = this.bufG[gx];
+ this.tmpB[gx] = this.bufB[gx];
+ const last = (gh - 1) * gw + gx;
+ this.tmpR[last] = this.bufR[last];
+ this.tmpG[last] = this.bufG[last];
+ this.tmpB[last] = this.bufB[last];
+ }
+ for (let gy = 1; gy < gh - 1; gy++) {
+ const row = gy * gw;
+ for (let gx = 0; gx < gw; gx++) {
+ const i = row + gx;
+ this.tmpR[i] = this.bufR[i - gw] * diff + this.bufR[i] * centerW + this.bufR[i + gw] * diff;
+ this.tmpG[i] = this.bufG[i - gw] * diff + this.bufG[i] * centerW + this.bufG[i + gw] * diff;
+ this.tmpB[i] = this.bufB[i - gw] * diff + this.bufB[i] * centerW + this.bufB[i + gw] * diff;
+ }
+ }
+ }
+ for (let i = 0; i < totalTexels; i++) {
+ this.bufR[i] = this.tmpR[i];
+ this.bufG[i] = this.tmpG[i];
+ this.bufB[i] = this.tmpB[i];
+ }
}
}
}
- const total = gw * gh;
- for (let i = 0; i < total; i++) {
- this.bufR[i] = this.tmpR[i];
- this.bufG[i] = this.tmpG[i];
- this.bufB[i] = this.tmpB[i];
+ }
+ }
+
+ // 2b. Single decode pass from 7-channel Kubelka-Munk latent buffer -> bufR/G/B (ONCE per dab!)
+ if (usePigment && !isFullFresh) {
+ sumBufR = 0;
+ sumBufG = 0;
+ sumBufB = 0;
+ if (partialPigment) {
+ for (let i = 0; i < totalTexels; i++) {
+ if (this.bufA[i] <= 0.002) {
+ this.bufR[i] = this.linR[i];
+ this.bufG[i] = this.linG[i];
+ this.bufB[i] = this.linB[i];
+ continue;
+ }
+ pigmentLatentToSrgbOut(latBuf, i * 7, this.c1Scratch);
+ const r = this.linR[i] + (this.c1Scratch.r - this.linR[i]) * effPigmentStrength;
+ const g = this.linG[i] + (this.c1Scratch.g - this.linG[i]) * effPigmentStrength;
+ const b = this.linB[i] + (this.c1Scratch.b - this.linB[i]) * effPigmentStrength;
+ this.bufR[i] = r;
+ this.bufG[i] = g;
+ this.bufB[i] = b;
+ sumBufR += r;
+ sumBufG += g;
+ sumBufB += b;
+ }
+ } else {
+ for (let i = 0; i < totalTexels; i++) {
+ if (this.bufA[i] <= 0.002) continue;
+ pigmentLatentToSrgbOut(latBuf, i * 7, this.c1Scratch);
+ const r = this.c1Scratch.r;
+ const g = this.c1Scratch.g;
+ const b = this.c1Scratch.b;
+ this.bufR[i] = r;
+ this.bufG[i] = g;
+ this.bufB[i] = b;
+ sumBufR += r;
+ sumBufG += g;
+ sumBufB += b;
}
}
}
@@ -2233,26 +3183,48 @@ export class SpatialTipMixer {
const flowFactor = Math.max(0, Math.min(1.0, p.flow * pressureMod));
const freshDensity = Math.max(0, Math.min(1.0, flowFactor * clampedDensity));
const spacingRatio = Math.max(0.003, Math.min(2.0, p.spacingRatio ?? 0.06));
+ const tipMask = p.tipImage ? getCachedTipAlphaMask(p.tipImage) : null;
+ const effectiveChord = Math.max(1.0, diamAlongStroke * 0.85);
+ const nominalStep =
+ step > 0
+ ? Math.max(0.2, step)
+ : Math.max(0.55, Math.min(effectiveChord, diamAlongStroke * spacingRatio));
+ const overlapHits = Math.max(1.0, effectiveChord / nominalStep);
+ // Physically account for porous sponge/chalk tips (e.g. ~22% core fill): each canvas pixel
+ // is hit only `overlapHits * tipFillFactor` times, whereas solid/soft round tips have coreFill >= 0.85
+ // (tipFillFactor = 1.0, completely unchanged).
+ const tipFillFactor =
+ tipMask && !p.adjustDensityByGap
+ ? Math.max(0.18, Math.min(1.0, tipMask.coreFill / 0.785))
+ : 1.0;
+ const effectiveOverlapHits = Math.max(1.0, overlapHits * tipFillFactor);
+ const invOverlapHits = 1.0 / effectiveOverlapHits;
+ // When CSP BrushAdjustFlowByInterval is OFF, each overlapping stamp deposits freshDensity
+ // without normalizing down by overlap count (use true CSP spacing overlap, not perf-clamped step).
+ const spacingOverlap = 0.85 / Math.max(0.003, spacingRatio);
const gapBoost = !p.adjustDensityByGap
- ? 1.0 + 13.5 * Math.pow(Math.max(0, 1.0 - spacingRatio / 0.15), 2)
+ ? Math.min(14.5, Math.max(1.0, spacingOverlap))
: 1.0;
const baseOpticalDepth =
freshDensity >= 0.995
? 12.0
- : gapBoost * Math.pow(freshDensity, 1.18);
+ : gapBoost * freshDensity;
+ // For pure CSP blenders (Amount=0, Density=0, ColorStretch>0), Color Stretch drives
+ // the visible blend/smear deposition strength directly instead of collapsing to 0.
+ const smudgeBlendStrength = Math.max(clampedDensity, clampedStretch);
+ const smudgeOpticalDepth = isPureSmudge
+ ? (1.6 + smudgeBlendStrength * 4.4) * Math.max(0.08, flowFactor)
+ : 0;
const carriedOpticalScale = flowFactor * clampedStretch * 0.65;
- const effectiveChord = Math.max(1.0, diamAlongStroke * 0.85);
- const nominalStep = step > 0 ? Math.max(0.2, step) : Math.max(0.55, Math.min(1.05, thinSpan * 0.1));
- const overlapHits = Math.max(1.0, effectiveChord / nominalStep);
- const invOverlapHits = 1.0 / overlapHits;
const dabSalt = Math.imul((p.dabSeq ?? 0) + 1, 83492791);
- // 4. Composite crisp 1:1 silhouette SDF + bilinear pigment grid + per-plot paper grain
+ // 4. Composite crisp silhouette SDF/tip + bilinear pigment grid + hoisted per-plot paper grain
const out = this.scratchImgData.data;
- const tipMask = p.tipImage ? getCachedTipAlphaMask(p.tipImage) : null;
const hNorm = Math.max(0.02, Math.min(1.0, p.hardness));
const aaFeatherPx = p.antiAlias === 0 ? 0 : p.antiAlias === 1 ? 0.65 : p.antiAlias === 3 ? 1.65 : 1.0;
- const hasGrain = Boolean(p.grainModulate && (p.grainDensity ?? 0) > 0.005);
+ const grainDensity = p.grainDensity ?? 0;
+ const hasDirectPaper = Boolean(p.paperLumData && p.paperLumWidth && p.paperLumHeight && grainDensity > 0.005);
+ const hasGrain = hasDirectPaper || Boolean(p.grainModulate && grainDensity > 0.005);
const flipX = p.flipX < 0 ? -1 : 1;
const flipY = p.flipY < 0 ? -1 : 1;
const invInnerW = 1 / innerW;
@@ -2260,6 +3232,72 @@ export class SpatialTipMixer {
const gwM1 = gw - 1;
const ghM1 = gh - 1;
+ // Hoist all invariant paper grain math & affine stepping OUTSIDE the inner pixel loop!
+ const paperData = p.paperLumData;
+ const paperW = p.paperLumWidth ?? 0;
+ const paperH = p.paperLumHeight ?? 0;
+ const paperPow2 = (paperW & (paperW - 1)) === 0 && (paperH & (paperH - 1)) === 0;
+ const paperMaskW = paperW - 1;
+ const paperMaskH = paperH - 1;
+ const paperInvScale = 1.0 / Math.max(0.05, p.paperTextureScale ?? 1.0);
+ const paperRotRad = ((p.paperTextureRotate ?? 0) * Math.PI) / 180;
+ const paperHasRot = Math.abs(paperRotRad) > 1e-4;
+ const paperCosR = paperHasRot ? Math.cos(paperRotRad) : 1;
+ const paperSinR = paperHasRot ? Math.sin(paperRotRad) : 0;
+ const paperInv = Boolean(p.paperTextureInverted);
+ const paperEmphasize = Boolean(p.paperTextureEmphasizeDensity);
+ const paperPreserve = Boolean(p.paperTexturePreserveDensity);
+ const paperBright = (p.paperTextureBrightness ?? 0) / 100.0;
+ const paperContrast = p.paperTextureContrast ?? 0;
+ const paperCFactor =
+ paperContrast !== 0 ? Math.pow(Math.max(0.05, (paperContrast + 100.0) / 100.0), 2) : 1.0;
+ const paperMode = p.paperTextureMode ?? 'multiply';
+ const paperModeCode =
+ paperMode === 'multiply' ? 1
+ : paperMode === 'compare' ? 2
+ : paperMode === 'subtract' ? 3
+ : paperMode === 'normal' ? 4
+ : paperMode === 'overlay' ? 5
+ : paperMode === 'color-burn' ? 6
+ : paperMode === 'linear-burn' ? 7
+ : paperMode === 'height' ? 8
+ : paperMode === 'outline' ? 9
+ : 1;
+ const isDryPaperMode = paperModeCode === 2 || paperModeCode === 3;
+ const gP = Math.max(0, Math.min(1, p.grainPressure ?? effPressure));
+ const gHeavy = Math.max(0, (gP - 0.52) / 0.48);
+ const gPen = Math.min(0.92, gP * 0.28 + gHeavy * gHeavy * 0.64);
+ const gEffDensity = paperPreserve ? grainDensity : grainDensity * (1.0 - gPen * 0.85);
+ const gCompareLow = gEffDensity * 0.68 - 0.05;
+ const gCompareInvSpan = 1.0 / 0.21;
+ const gSubScale = paperPreserve ? gEffDensity : gEffDensity * (1.0 - gPen * 0.5);
+ const grainPackFloor = paperPreserve
+ ? 0.0
+ : isDryPaperMode
+ ? Math.min(0.75, 0.06 + Math.max(0, (effPressure - 0.45) * 1.25))
+ : 0.62;
+ const grainPackSpan = 1.0 - grainPackFloor;
+ const dLxDx = 2.0 * invInnerW * halfW;
+ const dWxDx = dLxDx * cosA;
+ const dWyDx = dLxDx * sinA;
+ const lxStart = (0.5 * invInnerW - 0.5) * 2.0 * halfW;
+
+ const tipW = tipMask ? tipMask.width : 0;
+ const tipH = tipMask ? tipMask.height : 0;
+ const tipAlphaBuf = tipMask ? tipMask.alpha : null;
+ const tipAlphaSat = tipMask ? tipMask.alphaSat : null;
+ const tipSatW = tipW + 1;
+ // Use O(1) area-averaged box filtering when downsampling high-frequency tips (e.g. porous chalk/charcoal)
+ // so sub-texel pores never alias into skipped-row longitudinal comb stripes.
+ const useBoxDownsampleTip = Boolean(
+ tipAlphaSat && (tipW > innerW * 1.25 || tipH > innerH * 1.25)
+ );
+ const tipLumBuf = p.isDualToneTip && tipMask ? tipMask.lum : null;
+ const dualSecRgb = tipLumBuf ? parseColorToRgb(p.secondaryColor || '#ffffff') : null;
+ const tipWM1 = tipW - 1;
+ const tipHM1 = tipH - 1;
+ const inv255 = 1 / 255;
+
let hasVisiblePixels = false;
for (let oy = 0; oy < outH; oy++) {
@@ -2273,41 +3311,114 @@ export class SpatialTipMixer {
const vNorm = (oy - 0.5) * invInnerH; // [0, 1] across exact tip height
const ny = (vNorm - 0.5) * 2.0; // [-1, 1]
const ly = ny * halfH;
+ let curWx = p.x + lxStart * cosA - ly * sinA;
+ let curWy = p.y + lxStart * sinA + ly * cosA;
const fy = Math.max(0, Math.min(ghM1, vNorm * gh - 0.5));
- const gy0 = Math.floor(fy);
+ const gy0 = fy | 0;
const gy1 = gy0 < ghM1 ? gy0 + 1 : ghM1;
const ty = fy - gy0;
+ const invTy = 1 - ty;
const gRow0 = gy0 * gw;
const gRow1 = gy1 * gw;
- for (let ox = 0; ox < outW; ox++) {
- const pOff = (rowOff + ox) << 2;
- if (ox === 0 || ox === outW - 1) {
- out[pOff] = 0;
- out[pOff + 1] = 0;
- out[pOff + 2] = 0;
- out[pOff + 3] = 0;
- continue;
+ // Hoist tipMask vertical bilinear rows or SAT box-filter rows per scanline
+ let mRow0 = 0;
+ let mRow1 = 0;
+ let mfy = 0;
+ let invMfy = 1;
+ let satY0Off = 0;
+ let satY1Off = 0;
+ let satBoxH = 1;
+ if (tipAlphaBuf) {
+ const sv = flipY < 0 ? 1.0 - vNorm : vNorm;
+ if (useBoxDownsampleTip) {
+ const vLo = flipY < 0 ? Math.max(0, 1.0 - oy * invInnerH) : Math.max(0, (oy - 1) * invInnerH);
+ const vHi = flipY < 0 ? Math.min(1, 1.0 - (oy - 1) * invInnerH) : Math.min(1, oy * invInnerH);
+ const sy0 = Math.max(0, Math.min(tipHM1, Math.floor(vLo * tipH)));
+ const sy1 = Math.max(sy0 + 1, Math.min(tipH, Math.ceil(vHi * tipH)));
+ satY0Off = sy0 * tipSatW;
+ satY1Off = sy1 * tipSatW;
+ satBoxH = sy1 - sy0;
}
+ const tmy = Math.max(0, Math.min(tipHM1, sv * tipH - 0.5));
+ const my0 = tmy | 0;
+ const my1 = my0 < tipHM1 ? my0 + 1 : tipHM1;
+ mfy = tmy - my0;
+ invMfy = 1 - mfy;
+ mRow0 = my0 * tipW;
+ mRow1 = my1 * tipW;
+ }
+ // Clear left/right 1px transparent border
+ const leftOff = rowOff << 2;
+ out[leftOff] = 0;
+ out[leftOff + 1] = 0;
+ out[leftOff + 2] = 0;
+ out[leftOff + 3] = 0;
+ const rightOff = (rowOff + outW - 1) << 2;
+ out[rightOff] = 0;
+ out[rightOff + 1] = 0;
+ out[rightOff + 2] = 0;
+ out[rightOff + 3] = 0;
+
+ for (let ox = 1; ox < outW - 1; ox++) {
+ const pOff = (rowOff + ox) << 2;
const uNorm = (ox - 0.5) * invInnerW; // [0, 1] across exact tip width
- const nx = (uNorm - 0.5) * 2.0; // [-1, 1]
+ const wx = curWx;
+ const wy = curWy;
+ curWx += dWxDx;
+ curWy += dWyDx;
let tipAlpha = 0;
- if (tipMask) {
+ let tipLum = 0;
+ if (tipAlphaBuf) {
const su = flipX < 0 ? 1.0 - uNorm : uNorm;
- const sv = flipY < 0 ? 1.0 - vNorm : vNorm;
- const tx = Math.max(0, Math.min(tipMask.width - 1, Math.floor(su * tipMask.width)));
- const tyM = Math.max(0, Math.min(tipMask.height - 1, Math.floor(sv * tipMask.height)));
- tipAlpha = tipMask.alpha[tyM * tipMask.width + tx] / 255;
+ if (useBoxDownsampleTip && tipAlphaSat) {
+ const uLo = flipX < 0 ? Math.max(0, 1.0 - ox * invInnerW) : Math.max(0, (ox - 1) * invInnerW);
+ const uHi = flipX < 0 ? Math.min(1, 1.0 - (ox - 1) * invInnerW) : Math.min(1, ox * invInnerW);
+ const sx0 = Math.max(0, Math.min(tipWM1, Math.floor(uLo * tipW)));
+ const sx1 = Math.max(sx0 + 1, Math.min(tipW, Math.ceil(uHi * tipW)));
+ const areaSum =
+ tipAlphaSat[satY1Off + sx1] -
+ tipAlphaSat[satY0Off + sx1] -
+ tipAlphaSat[satY1Off + sx0] +
+ tipAlphaSat[satY0Off + sx0];
+ tipAlpha = (areaSum / ((sx1 - sx0) * satBoxH)) * inv255;
+ if (tipLumBuf) {
+ const tmx = Math.max(0, Math.min(tipWM1, su * tipW - 0.5));
+ const mx0 = tmx | 0;
+ const mx1 = mx0 < tipWM1 ? mx0 + 1 : tipWM1;
+ const mfx = tmx - mx0;
+ const lTop = tipLumBuf[mRow0 + mx0] + (tipLumBuf[mRow0 + mx1] - tipLumBuf[mRow0 + mx0]) * mfx;
+ const lBot = tipLumBuf[mRow1 + mx0] + (tipLumBuf[mRow1 + mx1] - tipLumBuf[mRow1 + mx0]) * mfx;
+ tipLum = (lTop * invMfy + lBot * mfy) * inv255;
+ }
+ } else {
+ const tmx = Math.max(0, Math.min(tipWM1, su * tipW - 0.5));
+ const mx0 = tmx | 0;
+ const mx1 = mx0 < tipWM1 ? mx0 + 1 : tipWM1;
+ const mfx = tmx - mx0;
+ const mTop = tipAlphaBuf[mRow0 + mx0] + (tipAlphaBuf[mRow0 + mx1] - tipAlphaBuf[mRow0 + mx0]) * mfx;
+ const mBot = tipAlphaBuf[mRow1 + mx0] + (tipAlphaBuf[mRow1 + mx1] - tipAlphaBuf[mRow1 + mx0]) * mfx;
+ tipAlpha = (mTop * invMfy + mBot * mfy) * inv255;
+ if (tipLumBuf) {
+ const lTop = tipLumBuf[mRow0 + mx0] + (tipLumBuf[mRow0 + mx1] - tipLumBuf[mRow0 + mx0]) * mfx;
+ const lBot = tipLumBuf[mRow1 + mx0] + (tipLumBuf[mRow1 + mx1] - tipLumBuf[mRow1 + mx0]) * mfx;
+ tipLum = (lTop * invMfy + lBot * mfy) * inv255;
+ }
+ }
} else {
- const dist = Math.hypot(nx, ny);
- if (dist < 1.0) {
+ const nx = (uNorm - 0.5) * 2.0;
+ const distSq = nx * nx + ny * ny;
+ if (distSq < 1.0) {
+ const dist = Math.sqrt(distSq);
if (p.antiAlias === 0) {
tipAlpha = 1.0;
} else if (hNorm >= 0.98) {
- const gradLen = Math.hypot(nx / Math.max(0.5, halfW), ny / Math.max(0.5, halfH));
+ const gxH = nx / Math.max(0.5, halfW);
+ const gyH = ny / Math.max(0.5, halfH);
+ const gradLen = Math.sqrt(gxH * gxH + gyH * gyH);
const edgePx = gradLen > 1e-5 ? (1.0 - dist) / gradLen : halfH;
const u = Math.max(0, Math.min(1, edgePx / Math.max(0.35, aaFeatherPx)));
tipAlpha = u * u * (3.0 - 2.0 * u);
@@ -2321,26 +3432,90 @@ export class SpatialTipMixer {
}
if (tipAlpha <= 0.002) {
- out[pOff] = 0;
- out[pOff + 1] = 0;
- out[pOff + 2] = 0;
out[pOff + 3] = 0;
continue;
}
let grainFactor = 1.0;
- if (hasGrain && p.grainModulate) {
- const lx = nx * halfW;
- const wx = p.x + lx * cosA - ly * sinA;
- const wy = p.y + lx * sinA + ly * cosA;
- const rawGrain = p.grainModulate(wx, wy, 1.0);
- // Wet oil paint fills paper valleys rather than punching static world-locked holes;
- // blend grain depth softly so tooth shows delicately in fades while body stays creamy.
- grainFactor = 0.62 + 0.38 * rawGrain;
+ if (hasGrain) {
+ let rawGrain = 1.0;
+ if (hasDirectPaper && paperData) {
+ let rotX = wx;
+ let rotY = wy;
+ if (paperHasRot) {
+ rotX = wx * paperCosR - wy * paperSinR;
+ rotY = wx * paperSinR + wy * paperCosR;
+ }
+ const psx = rotX * paperInvScale - 0.5;
+ const psy = rotY * paperInvScale - 0.5;
+ const pfx = Math.floor(psx);
+ const pfy = Math.floor(psy);
+ const ptx = psx - pfx;
+ const pty = psy - pfy;
+ let px0: number, py0: number, px1: number, py1: number;
+ if (paperPow2) {
+ px0 = pfx & paperMaskW;
+ py0 = pfy & paperMaskH;
+ px1 = (px0 + 1) & paperMaskW;
+ py1 = (py0 + 1) & paperMaskH;
+ } else {
+ px0 = ((pfx % paperW) + paperW) % paperW;
+ py0 = ((pfy % paperH) + paperH) % paperH;
+ px1 = px0 + 1 < paperW ? px0 + 1 : 0;
+ py1 = py0 + 1 < paperH ? py0 + 1 : 0;
+ }
+ const pr0 = py0 * paperW;
+ const pr1 = py1 * paperW;
+ const pvTop = paperData[pr0 + px0] + (paperData[pr0 + px1] - paperData[pr0 + px0]) * ptx;
+ const pvBot = paperData[pr1 + px0] + (paperData[pr1 + px1] - paperData[pr1 + px0]) * ptx;
+ let g = (pvTop + (pvBot - pvTop) * pty) * inv255;
+ if (paperInv) g = 1.0 - g;
+ if (paperEmphasize) g = Math.max(0, Math.min(1, (g - 0.5) * 2.2 + 0.35));
+ if (paperBright !== 0) g += paperBright;
+ if (paperContrast !== 0) g = (g - 0.5) * paperCFactor + 0.5;
+ g = g <= 0 ? 0 : g >= 1 ? 1 : g;
+
+ // Exact 9-mode CSP TextureCompositeMode math matching applyCspPaperTextureAlpha & WebGL
+ let modTip = tipAlpha;
+ if (paperModeCode === 1) {
+ modTip = Math.max(0, Math.min(1, tipAlpha * (1.0 - gEffDensity * (1.0 - g))));
+ } else if (paperModeCode === 2) {
+ const contactHeight = g * (0.22 + 0.78 * tipAlpha);
+ const ct = (contactHeight - gCompareLow) * gCompareInvSpan;
+ const ctc = ct <= 0 ? 0 : ct >= 1 ? 1 : ct;
+ modTip = Math.max(0, Math.min(1, tipAlpha * ctc * ctc * (3.0 - 2.0 * ctc)));
+ } else if (paperModeCode === 3) {
+ modTip = Math.max(0, Math.min(1, tipAlpha - (1.0 - g) * gSubScale));
+ } else if (paperModeCode === 4) {
+ const sil = tipAlpha * 4.0 >= 1.0 ? 1.0 : tipAlpha * 4.0;
+ modTip = Math.max(0, Math.min(1, tipAlpha * (1.0 - gEffDensity) + g * sil * gEffDensity));
+ } else if (paperModeCode === 5) {
+ const dMod = tipAlpha * (1.0 - gEffDensity * 0.32 * (1.0 - g));
+ const ov = dMod < 0.5 ? 2.0 * dMod * g : 1.0 - 2.0 * (1.0 - dMod) * (1.0 - g);
+ modTip = Math.max(0, Math.min(1, tipAlpha + (ov - tipAlpha) * gEffDensity));
+ } else if (paperModeCode === 6) {
+ const burned = g <= 0.001 ? 0 : Math.max(0, 1.0 - (1.0 - tipAlpha) / g);
+ modTip = Math.max(0, Math.min(1, tipAlpha + (burned - tipAlpha) * gEffDensity));
+ } else if (paperModeCode === 7) {
+ const burned = Math.max(0, tipAlpha + g - 1.0);
+ modTip = Math.max(0, Math.min(1, tipAlpha + (burned - tipAlpha) * gEffDensity));
+ } else if (paperModeCode === 8) {
+ const sil = tipAlpha * 4.0 >= 1.0 ? 1.0 : tipAlpha * 4.0;
+ const relief = Math.max(0, Math.min(1, (tipAlpha + g - 0.5) * 1.6)) * sil;
+ modTip = Math.max(0, Math.min(1, tipAlpha * (1.0 - gEffDensity) + relief * gEffDensity));
+ } else if (paperModeCode === 9) {
+ const edgeFactor = 4.0 * tipAlpha * (1.0 - tipAlpha);
+ modTip = Math.max(
+ 0,
+ Math.min(1, tipAlpha * (1.0 - gEffDensity * (1.0 - g) * (0.35 + 0.65 * edgeFactor)))
+ );
+ }
+ rawGrain = tipAlpha > 0.001 ? Math.max(0, Math.min(1, modTip / tipAlpha)) : 0;
+ } else if (p.grainModulate) {
+ rawGrain = p.grainModulate(wx, wy, 1.0);
+ }
+ grainFactor = grainPackFloor + grainPackSpan * rawGrain;
if (grainFactor <= 0.002) {
- out[pOff] = 0;
- out[pOff + 1] = 0;
- out[pOff + 2] = 0;
out[pOff + 3] = 0;
continue;
}
@@ -2348,58 +3523,73 @@ export class SpatialTipMixer {
// Bilinear sample from color pickup buffer
const fx = Math.max(0, Math.min(gwM1, uNorm * gw - 0.5));
- const gx0 = Math.floor(fx);
+ const gx0 = fx | 0;
const gx1 = gx0 < gwM1 ? gx0 + 1 : gwM1;
const tx = fx - gx0;
+ const invTx = 1 - tx;
const i00 = gRow0 + gx0;
const i10 = gRow0 + gx1;
const i01 = gRow1 + gx0;
const i11 = gRow1 + gx1;
- const w00 = (1 - tx) * (1 - ty);
- const w10 = tx * (1 - ty);
- const w01 = (1 - tx) * ty;
+ const w00 = invTx * invTy;
+ const w10 = tx * invTy;
+ const w01 = invTx * ty;
const w11 = tx * ty;
const bA = this.bufA[i00] * w00 + this.bufA[i10] * w10 + this.bufA[i01] * w01 + this.bufA[i11] * w11;
- const bCarry =
- this.bufCarry[i00] * w00 +
- this.bufCarry[i10] * w10 +
- this.bufCarry[i01] * w01 +
- this.bufCarry[i11] * w11;
- const carriedDensity = bCarry * carriedOpticalScale;
- const carriedTau = carriedDensity > 0.002 ? gapBoost * Math.pow(carriedDensity, 1.18) : 0;
- const localTau = Math.max(baseOpticalDepth, carriedTau) * grainFactor * bA;
- const perStampBody = localTau > 0.0005 ? 1.0 - Math.exp(-localTau * invOverlapHits) : 0;
- const finalAlpha = Math.max(0, Math.min(1, tipAlpha * perStampBody));
+ if (bA <= 0.002) {
+ out[pOff + 3] = 0;
+ continue;
+ }
+ let effBaseTau: number;
+ if (isPureSmudge) {
+ effBaseTau = smudgeOpticalDepth;
+ } else if (carriedOpticalScale > 0.002) {
+ const bCarry =
+ this.bufCarry[i00] * w00 +
+ this.bufCarry[i10] * w10 +
+ this.bufCarry[i01] * w01 +
+ this.bufCarry[i11] * w11;
+ const carriedDensity = bCarry * carriedOpticalScale;
+ effBaseTau =
+ carriedDensity > freshDensity && carriedDensity > 0.002
+ ? Math.max(baseOpticalDepth, gapBoost * carriedDensity)
+ : baseOpticalDepth;
+ } else {
+ effBaseTau = baseOpticalDepth;
+ }
+ const localTau = effBaseTau * grainFactor * bA;
+ const perStampBody = localTau > 0.0005 ? fastOneMinusExpNeg(localTau * invOverlapHits) : 0;
+ const finalAlpha = tipAlpha * perStampBody;
if (finalAlpha <= 0.001) {
- out[pOff] = 0;
- out[pOff + 1] = 0;
- out[pOff + 2] = 0;
out[pOff + 3] = 0;
continue;
}
- const bR = this.bufR[i00] * w00 + this.bufR[i10] * w10 + this.bufR[i01] * w01 + this.bufR[i11] * w11;
- const bG = this.bufG[i00] * w00 + this.bufG[i10] * w10 + this.bufG[i01] * w01 + this.bufG[i11] * w11;
- const bB = this.bufB[i00] * w00 + this.bufB[i10] * w10 + this.bufB[i01] * w01 + this.bufB[i11] * w11;
+ let bR = this.bufR[i00] * w00 + this.bufR[i10] * w10 + this.bufR[i01] * w01 + this.bufR[i11] * w11;
+ let bG = this.bufG[i00] * w00 + this.bufG[i10] * w10 + this.bufG[i01] * w01 + this.bufG[i11] * w11;
+ let bB = this.bufB[i00] * w00 + this.bufB[i10] * w10 + this.bufB[i01] * w01 + this.bufB[i11] * w11;
+
+ if (dualSecRgb) {
+ bR += (dualSecRgb.r - bR) * tipLum;
+ bG += (dualSecRgb.g - bG) * tipLum;
+ bB += (dualSecRgb.b - bB) * tipLum;
+ }
// Deterministic sub-LSB alpha dither prevents 8-bit quantization banding across 15+ low-alpha Fade stamps
let h = (Math.imul(ox, 73856093) ^ Math.imul(oy, 19349663) ^ dabSalt) | 0;
h = Math.imul(h ^ (h >>> 16), 0x85ebca6b);
- const dither = ((h ^ (h >>> 13)) >>> 0) / 4294967296 - 0.5;
- const qAlpha = Math.max(0, Math.min(255, Math.floor(finalAlpha * 255 + 0.5 + dither * 0.95)));
+ const dither = ((h ^ (h >>> 13)) >>> 0) * (1 / 4294967296) - 0.5;
+ const qAlpha = Math.max(0, Math.min(255, (finalAlpha * 255 + 0.5 + dither * 0.95) | 0));
if (qAlpha === 0) {
- out[pOff] = 0;
- out[pOff + 1] = 0;
- out[pOff + 2] = 0;
out[pOff + 3] = 0;
continue;
}
- out[pOff] = Math.max(0, Math.min(255, Math.round(bR)));
- out[pOff + 1] = Math.max(0, Math.min(255, Math.round(bG)));
- out[pOff + 2] = Math.max(0, Math.min(255, Math.round(bB)));
+ out[pOff] = bR <= 0 ? 0 : bR >= 255 ? 255 : (bR + 0.5) | 0;
+ out[pOff + 1] = bG <= 0 ? 0 : bG >= 255 ? 255 : (bG + 0.5) | 0;
+ out[pOff + 2] = bB <= 0 ? 0 : bB >= 255 ? 255 : (bB + 0.5) | 0;
out[pOff + 3] = qAlpha;
hasVisiblePixels = true;
}
@@ -2410,24 +3600,41 @@ export class SpatialTipMixer {
this.scratchCtx.putImageData(this.scratchImgData, 0, 0);
// 5. Trailing self-pickup deposit into LayerPixelSampler strictly behind the trailing edge
- // Dense across the full brush width so continuous back-and-forth scrubbing blends freshly laid strokes cleanly!
- const depositBodyAlpha = baseOpticalDepth > 0.0005 ? 1.0 - Math.exp(-baseOpticalDepth * invOverlapHits) : 0;
- if (sampler && step > 0 && (p.dirX !== 0 || p.dirY !== 0)) {
+ const depositTau = isPureSmudge ? smudgeOpticalDepth : baseOpticalDepth;
+ const depositBodyAlpha = depositTau > 0.0005 ? fastOneMinusExpNeg(depositTau * invOverlapHits) : 0;
+ if (sampler && step > 0 && depositBodyAlpha > 0.005 && (p.dirX !== 0 || p.dirY !== 0)) {
const trailDist = thinSpan * 0.6 + 1.25;
- const targetSamples = Math.max(6, Math.min(gw, 18));
- const sampleStride = Math.max(1, Math.floor(gw / targetSamples));
- const midRow = (gh >> 1) * gw;
- const depRad = Math.max(1, Math.min(6, Math.ceil((brushSpan / targetSamples) * 0.75)));
const depAlphaBoost = Math.min(0.85, Math.max(depositBodyAlpha * 2.1, Math.min(0.45, depositBodyAlpha * 1.4)));
- for (let gx = 0; gx < gw; gx += sampleStride) {
- const idx = midRow + gx;
- const a = this.bufA[idx] * depAlphaBoost;
- if (a <= 0.01) continue;
- const nx = ((gx + 0.5) * invGw - 0.5) * 2.0;
- const lx = nx * halfW;
- const depX = p.x + lx * cosA - p.dirX * trailDist;
- const depY = p.y + lx * sinA - p.dirY * trailDist;
- sampler.depositPointFast(depX, depY, depRad, this.bufR[idx], this.bufG[idx], this.bufB[idx], a);
+ if (p.width >= p.height) {
+ const targetSamples = Math.max(4, Math.min(gw, 7));
+ const sampleStride = Math.max(1, Math.floor(gw / targetSamples));
+ const midRow = (gh >> 1) * gw;
+ const depRad = 1;
+ for (let gx = 0; gx < gw; gx += sampleStride) {
+ const idx = midRow + gx;
+ const a = this.bufA[idx] * depAlphaBoost;
+ if (a <= 0.01) continue;
+ const nx = ((gx + 0.5) * invGw - 0.5) * 2.0;
+ const lx = nx * halfW;
+ const depX = p.x + lx * cosA - p.dirX * trailDist;
+ const depY = p.y + lx * sinA - p.dirY * trailDist;
+ sampler.depositPointFast(depX, depY, depRad, this.bufR[idx], this.bufG[idx], this.bufB[idx], a, effPigmentStrength);
+ }
+ } else {
+ const targetSamples = Math.max(4, Math.min(gh, 7));
+ const sampleStride = Math.max(1, Math.floor(gh / targetSamples));
+ const midCol = gw >> 1;
+ const depRad = 1;
+ for (let gy = 0; gy < gh; gy += sampleStride) {
+ const idx = gy * gw + midCol;
+ const a = this.bufA[idx] * depAlphaBoost;
+ if (a <= 0.01) continue;
+ const ny = ((gy + 0.5) * invGh - 0.5) * 2.0;
+ const ly = ny * halfH;
+ const depX = p.x - ly * sinA - p.dirX * trailDist;
+ const depY = p.y + ly * cosA - p.dirY * trailDist;
+ sampler.depositPointFast(depX, depY, depRad, this.bufR[idx], this.bufG[idx], this.bufB[idx], a, effPigmentStrength);
+ }
}
}
diff --git a/src/utils/compositor.ts b/src/utils/compositor.ts
index 6f7989c..99a5447 100644
--- a/src/utils/compositor.ts
+++ b/src/utils/compositor.ts
@@ -21,6 +21,7 @@ import {
performanceManager,
} from './performanceManager';
import { SparseTileGrid, TILE_SIZE, globalTileGrid } from './tileEngine';
+import { invalidatePigmentLutTexture } from './pigmentEngine';
import { calculateVisibleDocumentBounds } from './compositor/bounds';
import { disposeFboSurface, disposePingPongTarget } from './compositor/fboManager';
import { initGL, resetGLStateOnContextLost } from './compositor/glInit';
@@ -69,6 +70,7 @@ export {
COMPOSITOR_VERTEX_SHADER,
COMPOSITOR_FRAGMENT_SHADER,
VIEWPORT_DRAFT_VERTEX_SHADER,
+ PIGMENT_DRAFT_FRAGMENT_SHADER,
} from './compositor/shaders/coreShaders';
export {
@@ -153,6 +155,30 @@ function createInitialCompositorState(
uViewportDraftTileTexLoc: null,
uViewportDraftIsBgLoc: null,
aViewportDraftQuadPosLoc: -1,
+ pigmentDraftProgram: null,
+ aPigmentDraftQuadPosLoc: -1,
+ uPigmentDraftLayerTexLoc: null,
+ uPigmentDraftDraftTexLoc: null,
+ uPigmentDraftMaskTexLoc: null,
+ uPigmentDraftLutTexLoc: null,
+ uPigmentDraftDocDimensionsLoc: null,
+ uPigmentDraftViewportSizeLoc: null,
+ uPigmentDraftPanLoc: null,
+ uPigmentDraftZoomLoc: null,
+ uPigmentDraftRotationRadLoc: null,
+ uPigmentDraftFlipLoc: null,
+ uPigmentDraftDprLoc: null,
+ uPigmentDraftRectLoc: null,
+ uPigmentDraftSpaceLoc: null,
+ uPigmentDraftOpacityLoc: null,
+ uPigmentDraftStrengthLoc: null,
+ uPigmentDraftWhiteGroundLoc: null,
+ uPigmentDraftCompositeOpLoc: null,
+ uPigmentDraftCombineModeLoc: null,
+ uPigmentDraftMaskEnabledLoc: null,
+ uPigmentDraftLayerColorEnabledLoc: null,
+ uPigmentDraftLayerColorLoc: null,
+ uPigmentDraftLayerSubColorLoc: null,
aQuadPosLoc: -1,
aStylesQuadPosLoc: -1,
aBlitQuadPosLoc: -1,
@@ -167,6 +193,8 @@ function createInitialCompositorState(
draftTexWidth: 0,
draftTexHeight: 0,
draftHasMipmap: false,
+ draftNeedsFullUpload: true,
+ lastDraftLayerId: null,
lastDraftVersion: -1,
currentOptions: null,
currentZoom: 1.0,
@@ -248,6 +276,8 @@ function createInitialCompositorState(
fallbackTileCanvas: null,
fallbackTileImageData: null,
fallbackIsoCanvas: null,
+ fallbackDraftCanvas: null,
+ draftUploadCanvas: null,
lastRenderedGrid: null,
renderBackend,
powerPreference,
@@ -341,6 +371,8 @@ export class ViewportCompositor {
public flushGpuCaches(): void {
invalidateTileTextures(this.state);
invalidateMaskTexture(this.state);
+ this.state.draftNeedsFullUpload = true;
+ this.state.lastDraftVersion = -1;
this.state.stackCache.invalidateAll();
}
@@ -489,6 +521,11 @@ export class ViewportCompositor {
gl.deleteProgram(s.viewportDraftProgram);
s.viewportDraftProgram = null;
}
+ if (s.pigmentDraftProgram) {
+ gl.deleteProgram(s.pigmentDraftProgram);
+ s.pigmentDraftProgram = null;
+ }
+ invalidatePigmentLutTexture(gl, true);
if (s.adjProgram) {
gl.deleteProgram(s.adjProgram);
s.adjProgram = null;
@@ -550,6 +587,16 @@ export class ViewportCompositor {
s.fallbackIsoCanvas.height = 0;
s.fallbackIsoCanvas = null;
}
+ if (s.fallbackDraftCanvas) {
+ s.fallbackDraftCanvas.width = 0;
+ s.fallbackDraftCanvas.height = 0;
+ s.fallbackDraftCanvas = null;
+ }
+ if (s.draftUploadCanvas) {
+ s.draftUploadCanvas.width = 0;
+ s.draftUploadCanvas.height = 0;
+ s.draftUploadCanvas = null;
+ }
s.layerVisScratch.clear();
if (typeof s.canvas.removeEventListener === 'function') {
if (s.onContextLostHandler) {
diff --git a/src/utils/compositor/fallback2d.ts b/src/utils/compositor/fallback2d.ts
index 9497d4f..8fd1546 100644
--- a/src/utils/compositor/fallback2d.ts
+++ b/src/utils/compositor/fallback2d.ts
@@ -1,6 +1,10 @@
import { CanvasDimensions, LayerItem, isFolderLikeLayer, resolveToneDensityType } from '../../types/editor';
import { getCanvasCompositeOperation } from '../canvasUtils';
import { applyMultiFrameClip, renderFrameBorder } from '../frameEngine';
+import {
+ compositePigmentOverPixelInto,
+ isPigmentCompatibleCombineMode,
+} from '../pigmentEngine';
import { applyScreentoneCPU } from '../screentoneEngine';
import { SparseTileGrid, TILE_SIZE, TileBuffer } from '../tileEngine';
import { applyAdjustment } from '../tonalEngine';
@@ -226,6 +230,120 @@ export function render2DSingleLayer(
const draftOp2D = has2DDraft && opts?.activeDraftCanvas
? ((opts.activeDraftCanvas as any).__draftCompositeOp as GlobalCompositeOperation | undefined)
: undefined;
+ const draftPigmentStrength2D = has2DDraft ? (opts?.activeDraftPigmentStrength ?? 0) : 0;
+ const usePigment2DDraft =
+ has2DDraft &&
+ Boolean(opts?.activeDraftCanvas) &&
+ draftOp2D !== 'destination-out' &&
+ draftPigmentStrength2D > 0.005 &&
+ !toneEnabled &&
+ layer.expressionColor !== 'monochrome' &&
+ layer.expressionColor !== 'gray' &&
+ isPigmentCompatibleCombineMode(opts?.activeDraftCombineMode) &&
+ typeof document !== 'undefined' &&
+ Boolean(targetCtx.canvas);
+
+ if (usePigment2DDraft && opts?.activeDraftCanvas && targetCtx.canvas) {
+ if (!state.fallbackIsoCanvas) {
+ state.fallbackIsoCanvas = document.createElement('canvas');
+ }
+ if (!state.fallbackDraftCanvas) {
+ state.fallbackDraftCanvas = document.createElement('canvas');
+ }
+ const iso = state.fallbackIsoCanvas;
+ const dSurf = state.fallbackDraftCanvas;
+ const cw = targetCtx.canvas.width;
+ const ch = targetCtx.canvas.height;
+ if (iso.width !== cw || iso.height !== ch) {
+ iso.width = cw;
+ iso.height = ch;
+ }
+ if (dSurf.width !== cw || dSurf.height !== ch) {
+ dSurf.width = cw;
+ dSurf.height = ch;
+ }
+ const isoCtx = iso.getContext('2d', { willReadFrequently: true });
+ const dSurfCtx = dSurf.getContext('2d', { willReadFrequently: true });
+ if (isoCtx && dSurfCtx && cw > 0 && ch > 0) {
+ if (typeof isoCtx.setTransform === 'function') isoCtx.setTransform(1, 0, 0, 1, 0, 0);
+ if (typeof dSurfCtx.setTransform === 'function') dSurfCtx.setTransform(1, 0, 0, 1, 0, 0);
+ isoCtx.clearRect(0, 0, cw, ch);
+ dSurfCtx.clearRect(0, 0, cw, ch);
+ if (typeof targetCtx.getTransform === 'function') {
+ const xf = targetCtx.getTransform();
+ if (typeof isoCtx.setTransform === 'function') isoCtx.setTransform(xf);
+ if (typeof dSurfCtx.setTransform === 'function') dSurfCtx.setTransform(xf);
+ }
+ drawTiles(isoCtx);
+ dSurfCtx.save();
+ dSurfCtx.globalAlpha = 1.0;
+ if (opts.activeDraftSpace === 'viewport' && typeof dSurfCtx.setTransform === 'function') {
+ dSurfCtx.setTransform(1, 0, 0, 1, 0, 0);
+ dSurfCtx.drawImage(opts.activeDraftCanvas, 0, 0);
+ } else if (opts.activeDraftDirtyRect) {
+ const dr = opts.activeDraftDirtyRect;
+ dSurfCtx.drawImage(opts.activeDraftCanvas, dr.x, dr.y, dr.width, dr.height);
+ } else {
+ dSurfCtx.drawImage(
+ opts.activeDraftCanvas,
+ 0,
+ 0,
+ opts.dimensions?.width ?? opts.activeDraftCanvas.width,
+ opts.dimensions?.height ?? opts.activeDraftCanvas.height
+ );
+ }
+ dSurfCtx.restore();
+
+ const dstImg = isoCtx.getImageData(0, 0, cw, ch);
+ const srcImg = dSurfCtx.getImageData(0, 0, cw, ch);
+ const dd = dstImg.data;
+ const sd = srcImg.data;
+ const draftOpVal = opts.activeDraftOpacity ?? 1.0;
+ const whiteGround = Boolean(opts.activeDraftPigmentWhiteGround);
+ const compOp2D: 'source-over' | 'source-atop' =
+ draftOp2D === 'source-atop' ? 'source-atop' : 'source-over';
+ const combineMode2D =
+ opts.activeDraftCombineMode ??
+ (draftOp2D === 'destination-over' ? 'behind' : 'normal');
+ const pxOut: [number, number, number, number] = [0, 0, 0, 0];
+
+ for (let i = 0; i < dd.length; i += 4) {
+ const sa = sd[i + 3];
+ if (sa === 0) continue;
+ const effA = draftOpVal >= 0.999 ? sa : Math.round(sa * draftOpVal);
+ if (effA <= 0) continue;
+ compositePigmentOverPixelInto(
+ dd[i],
+ dd[i + 1],
+ dd[i + 2],
+ dd[i + 3],
+ sd[i],
+ sd[i + 1],
+ sd[i + 2],
+ effA,
+ draftPigmentStrength2D,
+ whiteGround,
+ compOp2D,
+ combineMode2D,
+ pxOut
+ );
+ dd[i] = pxOut[0];
+ dd[i + 1] = pxOut[1];
+ dd[i + 2] = pxOut[2];
+ dd[i + 3] = pxOut[3];
+ }
+ isoCtx.putImageData(dstImg, 0, 0);
+
+ 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;
+ }
+ }
if (
has2DDraft &&
diff --git a/src/utils/compositor/glInit.ts b/src/utils/compositor/glInit.ts
index c331876..c0fe68a 100644
--- a/src/utils/compositor/glInit.ts
+++ b/src/utils/compositor/glInit.ts
@@ -1,4 +1,5 @@
import { TILE_SIZE } from '../tileEngine';
+import { invalidatePigmentLutTexture } from '../pigmentEngine';
import {
COMPOSITOR_FRAGMENT_SHADER,
COMPOSITOR_VERTEX_SHADER,
@@ -6,6 +7,7 @@ import {
FOLDER_BLIT_VERTEX_SHADER,
FRAME_POLY_FRAGMENT_SHADER,
FRAME_POLY_VERTEX_SHADER,
+ PIGMENT_DRAFT_FRAGMENT_SHADER,
VIEWPORT_DRAFT_VERTEX_SHADER,
} from './shaders/coreShaders';
import {
@@ -209,6 +211,7 @@ export function initTileArrayPool(state: CompositorState, gl: WebGL2RenderingCon
}
export function resetGLStateOnContextLost(state: CompositorState): void {
+ invalidatePigmentLutTexture(state.gl, false);
state.contextLost = true;
state.gl = null;
state.program = null;
@@ -222,6 +225,7 @@ export function resetGLStateOnContextLost(state: CompositorState): void {
state.arrayPoolCapacity = 0;
state.arrayPoolFilterTier = -1;
state.viewportDraftProgram = null;
+ state.pigmentDraftProgram = null;
state.adjProgram = null;
state.stylesProgram = null;
state.blitProgram = null;
@@ -243,6 +247,8 @@ export function resetGLStateOnContextLost(state: CompositorState): void {
state.draftTexWidth = 0;
state.draftTexHeight = 0;
state.draftHasMipmap = false;
+ state.draftNeedsFullUpload = true;
+ state.lastDraftLayerId = null;
state.lastDraftVersion = -1;
state.stackCache.invalidateAll();
}
@@ -414,6 +420,47 @@ export function initGL(state: CompositorState): boolean {
}
}
+ // Compile Live Pigment Draft Compositing Program (reuses FOLDER_BLIT_VERTEX_SHADER)
+ const pigDraftFs = compileShader(gl, gl.FRAGMENT_SHADER, PIGMENT_DRAFT_FRAGMENT_SHADER);
+ if (
+ blitVs &&
+ pigDraftFs &&
+ gl.getShaderParameter(blitVs, gl.COMPILE_STATUS) &&
+ gl.getShaderParameter(pigDraftFs, gl.COMPILE_STATUS)
+ ) {
+ const pdProg = linkProgram(gl, blitVs, pigDraftFs);
+ if (pdProg && gl.getProgramParameter(pdProg, gl.LINK_STATUS)) {
+ state.pigmentDraftProgram = pdProg;
+ state.aPigmentDraftQuadPosLoc = gl.getAttribLocation(pdProg, 'a_quadPos');
+ state.uPigmentDraftLayerTexLoc = gl.getUniformLocation(pdProg, 'u_layerTex');
+ state.uPigmentDraftDraftTexLoc = gl.getUniformLocation(pdProg, 'u_draftTex');
+ state.uPigmentDraftMaskTexLoc = gl.getUniformLocation(pdProg, 'u_maskTex');
+ state.uPigmentDraftLutTexLoc = gl.getUniformLocation(pdProg, 'u_pigmentLut');
+ state.uPigmentDraftDocDimensionsLoc = gl.getUniformLocation(pdProg, 'u_docDimensions');
+ state.uPigmentDraftViewportSizeLoc = gl.getUniformLocation(pdProg, 'u_viewportSize');
+ state.uPigmentDraftPanLoc = gl.getUniformLocation(pdProg, 'u_pan');
+ state.uPigmentDraftZoomLoc = gl.getUniformLocation(pdProg, 'u_zoom');
+ state.uPigmentDraftRotationRadLoc = gl.getUniformLocation(pdProg, 'u_rotationRad');
+ state.uPigmentDraftFlipLoc = gl.getUniformLocation(pdProg, 'u_flip');
+ state.uPigmentDraftDprLoc = gl.getUniformLocation(pdProg, 'u_dpr');
+ state.uPigmentDraftRectLoc = gl.getUniformLocation(pdProg, 'u_draftRect');
+ state.uPigmentDraftSpaceLoc = gl.getUniformLocation(pdProg, 'u_draftSpace');
+ state.uPigmentDraftOpacityLoc = gl.getUniformLocation(pdProg, 'u_draftOpacity');
+ state.uPigmentDraftStrengthLoc = gl.getUniformLocation(pdProg, 'u_pigmentStrength');
+ state.uPigmentDraftWhiteGroundLoc = gl.getUniformLocation(pdProg, 'u_whiteGround');
+ state.uPigmentDraftCompositeOpLoc = gl.getUniformLocation(pdProg, 'u_compositeOp');
+ state.uPigmentDraftCombineModeLoc = gl.getUniformLocation(pdProg, 'u_combineMode');
+ state.uPigmentDraftMaskEnabledLoc = gl.getUniformLocation(pdProg, 'u_maskEnabled');
+ state.uPigmentDraftLayerColorEnabledLoc = gl.getUniformLocation(pdProg, 'u_layerColorEnabled');
+ state.uPigmentDraftLayerColorLoc = gl.getUniformLocation(pdProg, 'u_layerColor');
+ state.uPigmentDraftLayerSubColorLoc = gl.getUniformLocation(pdProg, 'u_layerSubColor');
+ } else if (pdProg) {
+ console.error('Pigment draft link error:', gl.getProgramInfoLog(pdProg));
+ }
+ } else if (pigDraftFs) {
+ console.error('Pigment draft FS error:', gl.getShaderInfoLog(pigDraftFs));
+ }
+
// 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);
diff --git a/src/utils/compositor/layerRenderer.ts b/src/utils/compositor/layerRenderer.ts
index 5dde31f..0922280 100644
--- a/src/utils/compositor/layerRenderer.ts
+++ b/src/utils/compositor/layerRenderer.ts
@@ -1,5 +1,9 @@
import { CanvasDimensions, LayerItem } from '../../types/editor';
import { SparseTileGrid, TILE_SIZE, TileBuffer } from '../tileEngine';
+import {
+ getPigmentLutTexture,
+ isPigmentCompatibleCombineMode,
+} from '../pigmentEngine';
import { parseHexColor } from './bounds';
import { blitFolderTexture } from './effectsPass';
import {
@@ -9,7 +13,11 @@ import {
prepareBackdropFromPingPong,
} from './fboManager';
import { restoreStandardProgram, unbindSceneTextureUnits } from './layerUniforms';
-import { drawVisibleTiles, renderActiveDraftForLayer } from './tileDraw';
+import {
+ drawVisibleTiles,
+ renderActiveDraftForLayer,
+ uploadActiveDraftTexture,
+} from './tileDraw';
import { getMaskTexture } from './tileTexturePool';
import {
BLEND_MODE_MAP,
@@ -87,7 +95,19 @@ export function renderSingleLayer(
const draftOp = hasDraft && draftCanvas
? ((draftCanvas as any).__draftCompositeOp as GlobalCompositeOperation | undefined)
: undefined;
+ const draftPigmentStrength = hasDraft ? (opts?.activeDraftPigmentStrength ?? 0) : 0;
+ const draftCombineMode = opts?.activeDraftCombineMode;
+ const needsPigmentDraftFbo =
+ hasDraft &&
+ draftCanvas !== null &&
+ draftOp !== 'destination-out' &&
+ !layer.toneEnabled &&
+ layer.expressionColor !== 'monochrome' &&
+ layer.expressionColor !== 'gray' &&
+ draftPigmentStrength > 0.005 &&
+ isPigmentCompatibleCombineMode(draftCombineMode);
const needsIsolatedDraftFbo =
+ !needsPigmentDraftFbo &&
hasDraft &&
draftCanvas !== null &&
(draftOp === 'destination-out' || draftOp === 'source-atop');
@@ -101,6 +121,182 @@ export function renderSingleLayer(
const maskTex = hasMask && layer.maskCanvas ? getMaskTexture(state, layer) : null;
const effectiveOpacity = layer.opacity * opacityMultiplier;
+ // Live Physical Pigment Draft Compositing Path (WebGL2 Kubelka-Munk 4-Pigment LUT)
+ // Renders the active layer's existing tiles into state.layerFbo, composites the active draft
+ // in pigment latent space into state.layerStylesOutFbo (matching CPU compositePigmentOverPixelInto 1:1),
+ // and blits the result onto target with the layer's blendMode & opacity — zero pop on pointerUp!
+ if (
+ needsPigmentDraftFbo &&
+ draftCanvas &&
+ target &&
+ fs &&
+ fs.viewportW > 0 &&
+ fs.viewportH > 0 &&
+ state.pigmentDraftProgram &&
+ state.blitProgram &&
+ ensureLayerFbo(state, fs.viewportW, fs.viewportH) &&
+ state.layerFbo &&
+ state.layerTexture
+ ) {
+ if (!state.layerStylesOutFbo) {
+ state.layerStylesOutFbo = createFboSurface(gl, false);
+ }
+ const pigmentLutTex = getPigmentLutTexture(gl);
+ const draftSpace = opts?.activeDraftSpace ?? 'document';
+ const draftUploaded =
+ state.layerStylesOutFbo &&
+ ensureFboSurfaceSize(gl, state.layerStylesOutFbo, fs.viewportW, fs.viewportH) &&
+ pigmentLutTex !== null &&
+ uploadActiveDraftTexture(state, gl, draftCanvas, opts?.activeDraftVersion, draftSpace);
+
+ if (draftUploaded && state.layerStylesOutFbo && state.draftTexture && pigmentLutTex) {
+ const stencilWasEnabled = gl.isEnabled(gl.STENCIL_TEST);
+ if (stencilWasEnabled) gl.disable(gl.STENCIL_TEST);
+
+ // 1. Render existing layer tiles (unmasked, untinted, full opacity) into state.layerFbo
+ 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) {
+ const rawLayerForFbo = layer.layerColorEnabled
+ ? { ...layer, layerColorEnabled: false }
+ : layer;
+ drawVisibleTiles(
+ state,
+ gl,
+ visibleTiles,
+ grid,
+ rawLayerForFbo,
+ dimensions,
+ lodTileDocSize,
+ 1.0,
+ 0,
+ null,
+ null
+ );
+ }
+
+ // 2. Run physical pigment draft compositor into state.layerStylesOutFbo (no feedback loop)
+ unbindSceneTextureUnits(gl);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, state.layerStylesOutFbo.fbo);
+ 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.ZERO);
+
+ gl.useProgram(state.pigmentDraftProgram);
+ gl.bindBuffer(gl.ARRAY_BUFFER, state.stylesQuadBuffer || state.quadBuffer);
+ if (state.aPigmentDraftQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(state.aPigmentDraftQuadPosLoc);
+ gl.vertexAttribPointer(state.aPigmentDraftQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ }
+
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, state.layerTexture);
+ gl.uniform1i(state.uPigmentDraftLayerTexLoc, 0);
+
+ gl.activeTexture(gl.TEXTURE1);
+ gl.bindTexture(gl.TEXTURE_2D, state.draftTexture);
+ gl.uniform1i(state.uPigmentDraftDraftTexLoc, 1);
+
+ gl.activeTexture(gl.TEXTURE2);
+ gl.bindTexture(gl.TEXTURE_2D, maskTex);
+ gl.uniform1i(state.uPigmentDraftMaskTexLoc, 2);
+
+ gl.activeTexture(gl.TEXTURE3);
+ gl.bindTexture(gl.TEXTURE_2D, pigmentLutTex);
+ gl.uniform1i(state.uPigmentDraftLutTexLoc, 3);
+
+ gl.uniform2f(state.uPigmentDraftDocDimensionsLoc, dimensions.width, dimensions.height);
+ gl.uniform2f(state.uPigmentDraftViewportSizeLoc, fs.viewportW, fs.viewportH);
+ gl.uniform2f(state.uPigmentDraftPanLoc, fs.transform.pan.x, fs.transform.pan.y);
+ gl.uniform1f(state.uPigmentDraftZoomLoc, fs.transform.zoom);
+ gl.uniform1f(state.uPigmentDraftRotationRadLoc, fs.rotRad);
+ gl.uniform2f(
+ state.uPigmentDraftFlipLoc,
+ fs.transform.flipX ? -1.0 : 1.0,
+ fs.transform.flipY ? -1.0 : 1.0
+ );
+ gl.uniform1f(state.uPigmentDraftDprLoc, fs.dpr);
+
+ const docRect = opts?.activeDraftDirtyRect;
+ gl.uniform4f(
+ state.uPigmentDraftRectLoc,
+ docRect ? docRect.x : 0,
+ docRect ? docRect.y : 0,
+ docRect ? docRect.width : dimensions.width,
+ docRect ? docRect.height : dimensions.height
+ );
+ gl.uniform1i(state.uPigmentDraftSpaceLoc, draftSpace === 'viewport' ? 1 : 0);
+ gl.uniform1f(state.uPigmentDraftOpacityLoc, opts?.activeDraftOpacity ?? 1.0);
+ gl.uniform1f(state.uPigmentDraftStrengthLoc, draftPigmentStrength);
+ gl.uniform1i(
+ state.uPigmentDraftWhiteGroundLoc,
+ opts?.activeDraftPigmentWhiteGround ? 1 : 0
+ );
+ gl.uniform1i(state.uPigmentDraftCompositeOpLoc, draftOp === 'source-atop' ? 1 : 0);
+ const combineCode =
+ draftCombineMode === 'compare-density'
+ ? 1
+ : draftCombineMode === 'behind' || draftOp === 'destination-over'
+ ? 2
+ : 0;
+ gl.uniform1i(state.uPigmentDraftCombineModeLoc, combineCode);
+ gl.uniform1i(state.uPigmentDraftMaskEnabledLoc, maskTex ? 1 : 0);
+
+ const tintEnabled = Boolean(layer.layerColorEnabled);
+ gl.uniform1i(state.uPigmentDraftLayerColorEnabledLoc, tintEnabled ? 1 : 0);
+ if (tintEnabled) {
+ const prim = parseHexColor(layer.layerColor || '#1c73c2');
+ const sub = parseHexColor(layer.layerSubColor || '#ffffff');
+ gl.uniform3f(state.uPigmentDraftLayerColorLoc, prim[0], prim[1], prim[2]);
+ gl.uniform3f(state.uPigmentDraftLayerSubColorLoc, sub[0], sub[1], sub[2]);
+ }
+
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+
+ // Unbind all texture units before re-binding parent FBO
+ gl.activeTexture(gl.TEXTURE3);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ gl.activeTexture(gl.TEXTURE2);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ gl.activeTexture(gl.TEXTURE1);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+
+ // 3. Blit pigment-composited layer onto parent target with layer blendMode & opacity
+ 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.layerStylesOutFbo.texture,
+ 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;
+ }
+ }
+
// 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 (
diff --git a/src/utils/compositor/renderFrame.ts b/src/utils/compositor/renderFrame.ts
index 3e7aa17..2afc8d3 100644
--- a/src/utils/compositor/renderFrame.ts
+++ b/src/utils/compositor/renderFrame.ts
@@ -45,6 +45,19 @@ export function renderFrame(
state.currentOptions = _options;
state.currentZoom = transform.zoom;
+ const optDraft = _options.activeDraftCanvas;
+ const optDraftLayerId = _options.activeDraftLayerId ?? null;
+ if (
+ !optDraft ||
+ optDraft.width <= 0 ||
+ optDraft.height <= 0 ||
+ (optDraft as any).__draftHasContent === false
+ ) {
+ state.draftNeedsFullUpload = true;
+ } else if (state.lastDraftLayerId !== optDraftLayerId) {
+ state.draftNeedsFullUpload = true;
+ }
+
if (!gl || !state.program || !state.stdLocs) {
render2DFallback(state, layers, transform, dimensions, grid, _options);
return;
diff --git a/src/utils/compositor/shaders/coreShaders.ts b/src/utils/compositor/shaders/coreShaders.ts
index 4d12077..1861bd8 100644
--- a/src/utils/compositor/shaders/coreShaders.ts
+++ b/src/utils/compositor/shaders/coreShaders.ts
@@ -1,5 +1,6 @@
import { buildBlendModeGlsl } from './blendModesGlsl';
import { buildScreentoneGlsl } from './screentoneGlsl';
+import { PIGMENT_GLSL_WEBGL2 } from '../../pigmentEngine';
// Document-Space Solid Polygon Shaders for Frame Border Folder Stencil Clipping & Borders
export const FRAME_POLY_VERTEX_SHADER = `#version 300 es
@@ -330,3 +331,189 @@ void main() {
gl_Position = vec4(clipPos, 0.0, 1.0);
}
`;
+
+// Live Physical Pigment Draft Compositing Fragment Shader (WebGL2)
+// Composites the active layer's existing pixels (u_layerTex) with the active stroke draft (u_draftTex)
+// in 7-channel Kubelka-Munk pigment latent space — matching CPU compositePigmentOverPixelInto 1-to-1
+// for zero-pop live/commit parity.
+export const PIGMENT_DRAFT_FRAGMENT_SHADER = `#version 300 es
+precision highp float;
+
+in vec2 v_uv;
+
+uniform sampler2D u_layerTex;
+uniform sampler2D u_draftTex;
+uniform sampler2D u_maskTex;
+uniform sampler2D u_pigmentLut;
+
+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;
+
+uniform vec4 u_draftRect;
+uniform int u_draftSpace;
+uniform float u_draftOpacity;
+uniform float u_pigmentStrength;
+uniform int u_whiteGround;
+uniform int u_compositeOp; // 0: source-over, 1: source-atop
+uniform int u_combineMode; // 0: normal, 1: compare-density, 2: behind
+uniform int u_maskEnabled;
+uniform int u_layerColorEnabled;
+uniform vec3 u_layerColor;
+uniform vec3 u_layerSubColor;
+
+out vec4 fragColor;
+
+${PIGMENT_GLSL_WEBGL2}
+
+vec4 encodePigmentOverWhiteGpu(vec3 srcRgb, float sA, float strength) {
+ if (sA <= 0.0001) return vec4(0.0);
+ if (sA >= 0.996 || strength <= 0.005) return vec4(srcRgb, sA);
+ vec3 pig = mixPigmentsGpu(vec3(1.0), srcRgb, sA, strength);
+ float minC = min(min(pig.r, pig.g), pig.b);
+ float outA = max(sA, 1.0 - minC);
+ if (outA <= 0.0001) return vec4(0.0);
+ vec3 outRgb = clamp((pig - vec3(1.0 - outA)) / outA, 0.0, 1.0);
+ return vec4(outRgb, outA);
+}
+
+void main() {
+ vec4 dstPremul = texture(u_layerTex, v_uv);
+ float dstA = dstPremul.a;
+ vec3 dstRgb = dstA > 0.001 ? clamp(dstPremul.rgb / dstA, 0.0, 1.0) : vec3(0.0);
+
+ vec2 screenPos = vec2(v_uv.x * u_viewportSize.x, (1.0 - v_uv.y) * u_viewportSize.y);
+ 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
+ );
+ vec2 docCoord = unrotated * u_flip + u_docDimensions * 0.5;
+
+ vec3 outRgb = dstRgb;
+ float outA = dstA;
+
+ vec2 draftUv;
+ bool inDraft = false;
+ if (u_draftSpace == 1) {
+ draftUv = vec2(v_uv.x, 1.0 - v_uv.y);
+ inDraft = true;
+ } else {
+ draftUv = (docCoord - u_draftRect.xy) / max(vec2(1.0), u_draftRect.zw);
+ inDraft =
+ draftUv.x >= 0.0 && draftUv.x <= 1.0 &&
+ draftUv.y >= 0.0 && draftUv.y <= 1.0 &&
+ docCoord.x >= 0.0 && docCoord.x <= u_docDimensions.x &&
+ docCoord.y >= 0.0 && docCoord.y <= u_docDimensions.y;
+ }
+
+ if (inDraft) {
+ vec4 srcPremul = texture(u_draftTex, draftUv);
+ float effA = clamp(srcPremul.a * u_draftOpacity, 0.0, 1.0);
+ if (effA > 0.001) {
+ vec3 srcRgb = srcPremul.a > 0.001 ? clamp(srcPremul.rgb / srcPremul.a, 0.0, 1.0) : vec3(0.0);
+ if (u_compositeOp == 1) {
+ // source-atop (Alpha Lock)
+ if (dstA > 0.001) {
+ if (u_combineMode == 2) {
+ if (dstA < 0.996) {
+ float rem = (1.0 - dstA) * effA;
+ float denom = dstA + rem;
+ if (denom > 0.00001) {
+ outRgb = mixPigmentsGpu(dstRgb, srcRgb, rem / denom, u_pigmentStrength);
+ }
+ }
+ } else if (effA >= 0.996) {
+ outRgb = srcRgb;
+ } else {
+ outRgb = mixPigmentsGpu(dstRgb, srcRgb, effA, u_pigmentStrength);
+ }
+ outA = dstA;
+ }
+ } else if (u_combineMode == 2) {
+ // behind (destination-over)
+ if (dstA < 0.996) {
+ if (dstA <= 0.001) {
+ if (u_whiteGround == 1 && effA < 0.996) {
+ vec4 enc = encodePigmentOverWhiteGpu(srcRgb, effA, u_pigmentStrength);
+ outRgb = enc.rgb;
+ outA = enc.a;
+ } else {
+ outRgb = srcRgb;
+ outA = effA;
+ }
+ } else {
+ float rem = effA * (1.0 - dstA);
+ float compA = dstA + rem;
+ if (compA > 0.00001) {
+ outRgb = mixPigmentsGpu(dstRgb, srcRgb, rem / compA, u_pigmentStrength);
+ outA = compA;
+ }
+ }
+ }
+ } else if (dstA <= 0.001) {
+ if (u_whiteGround == 1 && effA < 0.996) {
+ vec4 enc = encodePigmentOverWhiteGpu(srcRgb, effA, u_pigmentStrength);
+ outRgb = enc.rgb;
+ outA = enc.a;
+ } else {
+ outRgb = srcRgb;
+ outA = effA;
+ }
+ } else if (u_combineMode == 1) {
+ // compare-density
+ float denom = effA + dstA * (1.0 - effA);
+ if (denom > 0.00001) {
+ outRgb = mixPigmentsGpu(dstRgb, srcRgb, effA / denom, u_pigmentStrength);
+ }
+ outA = max(effA, dstA);
+ } else {
+ // standard source-over in Kubelka-Munk pigment space
+ if (effA >= 0.996) {
+ outRgb = srcRgb;
+ outA = 1.0;
+ } else {
+ float compA = effA + dstA * (1.0 - effA);
+ if (compA > 0.00001) {
+ if (u_whiteGround == 1 && dstA < 0.996) {
+ vec3 visDst = dstRgb * dstA + vec3(1.0 - dstA);
+ vec3 pig = mixPigmentsGpu(visDst, srcRgb, effA, u_pigmentStrength);
+ float minC = min(min(pig.r, pig.g), pig.b);
+ outA = max(compA, 1.0 - minC);
+ outRgb = clamp((pig - vec3(1.0 - outA)) / max(0.0001, outA), 0.0, 1.0);
+ } else {
+ outRgb = mixPigmentsGpu(dstRgb, srcRgb, effA / compA, u_pigmentStrength);
+ outA = compA;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if (u_layerColorEnabled == 1 && outA > 0.001) {
+ float lum = dot(outRgb, vec3(0.299, 0.587, 0.114));
+ outRgb = mix(u_layerColor, u_layerSubColor, lum);
+ }
+
+ if (u_maskEnabled == 1 && outA > 0.001) {
+ vec2 maskCoord = clamp(docCoord / max(vec2(1.0), u_docDimensions), 0.0, 1.0);
+ vec4 maskPixel = texture(u_maskTex, maskCoord);
+ float maskLum = dot(maskPixel.rgb, vec3(0.299, 0.587, 0.114)) * maskPixel.a;
+ outA *= maskLum;
+ }
+
+ if (outA < 0.002) {
+ fragColor = vec4(0.0);
+ return;
+ }
+ fragColor = vec4(outRgb * outA, outA);
+}
+`;
diff --git a/src/utils/compositor/tileDraw.ts b/src/utils/compositor/tileDraw.ts
index eded44d..ee55b38 100644
--- a/src/utils/compositor/tileDraw.ts
+++ b/src/utils/compositor/tileDraw.ts
@@ -197,40 +197,43 @@ export function drawVisibleTiles(
}
/**
- * 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.
+ * Uploads or updates `state.draftTexture` from `draftCanvas` if version or dimensions changed.
+ * Returns `true` when `state.draftTexture` is ready to bind.
*/
-export function renderActiveDraftForLayer(
+export function uploadActiveDraftTexture(
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;
+ draftSpace: 'document' | 'viewport' = 'document'
+): boolean {
+ if (draftCanvas.width <= 0 || draftCanvas.height <= 0) return false;
+ if ((draftCanvas as any).__draftHasContent === false) return false;
if (!state.draftTexture) {
state.draftTexture = gl.createTexture();
}
- if (!state.draftTexture) return;
+ if (!state.draftTexture) return false;
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;
+ // Only rebuild full draft mipmap pyramid below 50% zoom where trilinear minification prevents aliasing;
+ // at 50%-100% zoom, hardware GL_LINEAR is sharp and skips a costly 38MB mipmap rebuild every frame!
+ const needsMipmap = hasGenerateMipmap && draftSpace === 'document' && state.currentZoom < 0.5;
const sizeChanged =
state.draftTexWidth !== draftCanvas.width || state.draftTexHeight !== draftCanvas.height;
+ const activeDraftLayerId = state.currentOptions?.activeDraftLayerId ?? null;
+ const forceFullUpload = Boolean(
+ sizeChanged ||
+ state.draftTexWidth === 0 ||
+ state.draftNeedsFullUpload ||
+ (draftCanvas as any).__draftForceFullUpload === true ||
+ state.lastDraftLayerId !== activeDraftLayerId
+ );
- if (ver === -1 || ver !== state.lastDraftVersion || sizeChanged) {
+ if (ver === -1 || ver !== state.lastDraftVersion || forceFullUpload) {
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(
@@ -241,9 +244,50 @@ export function renderActiveDraftForLayer(
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);
+ const frameDirty = (draftCanvas as any).__draftFrameDirtyRect as
+ | { x: number; y: number; width: number; height: number }
+ | null
+ | undefined;
+ if (frameDirty !== undefined) {
+ (draftCanvas as any).__draftFrameDirtyRect = null;
+ }
+ if (!forceFullUpload && !sizeChanged && state.draftTexWidth > 0 && typeof gl.texSubImage2D === 'function') {
+ let uploadedSubRect = false;
+ if (
+ frameDirty &&
+ frameDirty.width > 0 &&
+ frameDirty.height > 0 &&
+ frameDirty.width * frameDirty.height < draftCanvas.width * draftCanvas.height * 0.5 &&
+ typeof document !== 'undefined'
+ ) {
+ const dx = Math.max(0, Math.min(draftCanvas.width - 1, frameDirty.x | 0));
+ const dy = Math.max(0, Math.min(draftCanvas.height - 1, frameDirty.y | 0));
+ const dw = Math.max(1, Math.min(draftCanvas.width - dx, Math.ceil(frameDirty.width)));
+ const dh = Math.max(1, Math.min(draftCanvas.height - dy, Math.ceil(frameDirty.height)));
+ try {
+ if (!state.draftUploadCanvas) {
+ state.draftUploadCanvas = document.createElement('canvas');
+ }
+ if (state.draftUploadCanvas.width !== dw || state.draftUploadCanvas.height !== dh) {
+ state.draftUploadCanvas.width = dw;
+ state.draftUploadCanvas.height = dh;
+ }
+ const subCtx = state.draftUploadCanvas.getContext('2d');
+ if (subCtx && typeof subCtx.drawImage === 'function') {
+ subCtx.clearRect(0, 0, dw, dh);
+ subCtx.drawImage(draftCanvas, dx, dy, dw, dh, 0, 0, dw, dh);
+ gl.texSubImage2D(gl.TEXTURE_2D, 0, dx, dy, gl.RGBA, gl.UNSIGNED_BYTE, state.draftUploadCanvas);
+ uploadedSubRect = true;
+ }
+ } catch {
+ uploadedSubRect = false;
+ }
+ }
+ if (!uploadedSubRect) {
+ gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, draftCanvas);
+ }
} else {
+ // Full texture replacement orphans any stale GPU backing from a prior/undone stroke
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, draftCanvas);
}
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
@@ -255,6 +299,11 @@ export function renderActiveDraftForLayer(
}
state.draftTexWidth = draftCanvas.width;
state.draftTexHeight = draftCanvas.height;
+ state.draftNeedsFullUpload = false;
+ state.lastDraftLayerId = activeDraftLayerId;
+ if ((draftCanvas as any).__draftForceFullUpload) {
+ (draftCanvas as any).__draftForceFullUpload = false;
+ }
state.lastDraftVersion = ver;
} else {
if (needsMipmap && !state.draftHasMipmap) {
@@ -276,6 +325,30 @@ export function renderActiveDraftForLayer(
? gl.NEAREST
: gl.LINEAR;
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, draftMagFilter);
+ return true;
+}
+
+/**
+ * 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 (!uploadActiveDraftTexture(state, gl, draftCanvas, draftVersion, draftSpace)) {
+ return;
+ }
let effectiveDraftLayer: LayerItem =
state.currentOptions?.activeDraftMonochrome && layer.expressionColor !== 'monochrome'
diff --git a/src/utils/compositor/types.ts b/src/utils/compositor/types.ts
index bc908b3..8f018b3 100644
--- a/src/utils/compositor/types.ts
+++ b/src/utils/compositor/types.ts
@@ -3,6 +3,7 @@ import {
CanvasDimensions,
BlendMode,
CanvasColorMode,
+ CspBrushCombineMode,
SoftProofSettings,
} from '../../types/editor';
import type {
@@ -94,6 +95,9 @@ export interface CompositorOptions {
activeDraftSpace?: 'document' | 'viewport';
activeDraftOpacity?: number;
activeDraftMonochrome?: boolean;
+ activeDraftPigmentStrength?: number;
+ activeDraftPigmentWhiteGround?: boolean;
+ activeDraftCombineMode?: CspBrushCombineMode;
}
export interface CompositingUnit {
@@ -283,6 +287,32 @@ export interface CompositorState {
uViewportDraftIsBgLoc: WebGLUniformLocation | null;
aViewportDraftQuadPosLoc: number;
+ // Live physical Kubelka-Munk pigment draft compositing program
+ pigmentDraftProgram: WebGLProgram | null;
+ aPigmentDraftQuadPosLoc: number;
+ uPigmentDraftLayerTexLoc: WebGLUniformLocation | null;
+ uPigmentDraftDraftTexLoc: WebGLUniformLocation | null;
+ uPigmentDraftMaskTexLoc: WebGLUniformLocation | null;
+ uPigmentDraftLutTexLoc: WebGLUniformLocation | null;
+ uPigmentDraftDocDimensionsLoc: WebGLUniformLocation | null;
+ uPigmentDraftViewportSizeLoc: WebGLUniformLocation | null;
+ uPigmentDraftPanLoc: WebGLUniformLocation | null;
+ uPigmentDraftZoomLoc: WebGLUniformLocation | null;
+ uPigmentDraftRotationRadLoc: WebGLUniformLocation | null;
+ uPigmentDraftFlipLoc: WebGLUniformLocation | null;
+ uPigmentDraftDprLoc: WebGLUniformLocation | null;
+ uPigmentDraftRectLoc: WebGLUniformLocation | null;
+ uPigmentDraftSpaceLoc: WebGLUniformLocation | null;
+ uPigmentDraftOpacityLoc: WebGLUniformLocation | null;
+ uPigmentDraftStrengthLoc: WebGLUniformLocation | null;
+ uPigmentDraftWhiteGroundLoc: WebGLUniformLocation | null;
+ uPigmentDraftCompositeOpLoc: WebGLUniformLocation | null;
+ uPigmentDraftCombineModeLoc: WebGLUniformLocation | null;
+ uPigmentDraftMaskEnabledLoc: WebGLUniformLocation | null;
+ uPigmentDraftLayerColorEnabledLoc: WebGLUniformLocation | null;
+ uPigmentDraftLayerColorLoc: WebGLUniformLocation | null;
+ uPigmentDraftLayerSubColorLoc: WebGLUniformLocation | null;
+
// Cached attribute locations
aQuadPosLoc: number;
aStylesQuadPosLoc: number;
@@ -302,6 +332,8 @@ export interface CompositorState {
draftTexWidth: number;
draftTexHeight: number;
draftHasMipmap: boolean;
+ draftNeedsFullUpload: boolean;
+ lastDraftLayerId: string | null;
lastDraftVersion: number;
currentOptions: CompositorOptions | null;
currentZoom: number;
@@ -401,6 +433,8 @@ export interface CompositorState {
fallbackTileCanvas: HTMLCanvasElement | null;
fallbackTileImageData: ImageData | null;
fallbackIsoCanvas: HTMLCanvasElement | null;
+ fallbackDraftCanvas: HTMLCanvasElement | null;
+ draftUploadCanvas: HTMLCanvasElement | null;
lastRenderedGrid: SparseTileGrid | null;
// Performance & Renderer Configuration
diff --git a/src/utils/inkbBrushFormat.ts b/src/utils/inkbBrushFormat.ts
index e57c06b..ec6ba8e 100644
--- a/src/utils/inkbBrushFormat.ts
+++ b/src/utils/inkbBrushFormat.ts
@@ -1,7 +1,6 @@
import { zipSync, unzipSync, strToU8, strFromU8 } from 'fflate';
import {
ALL_BLEND_MODES,
- BlendMode,
BristleProfilePreset,
BristleSettings,
BrushCategory,
@@ -11,10 +10,13 @@ import {
CspAngleDynamicsMode,
CspBlendTipsMode,
CspBrush,
+ CspBrushCombineMode,
+ CspDualBrushConfig,
CspPaperTextureMode,
CspSensorConfig,
CspSpraySettings,
CspSubTip,
+ CspSubTipOrder,
CspTaperSettings,
CspTipFlipMode,
GrainMappingMode,
@@ -32,6 +34,7 @@ import {
saveCustomBrush,
} from './brushStorage';
import { parseSutFile } from './sutParser';
+import { normalizeDualBrushCompositeMode } from '../engine/DualBrushEngine';
import { toolStoreActions } from '../stores';
export const INKB_FORMAT = 'inkb';
@@ -44,9 +47,17 @@ const MAX_SUB_TIPS = 32;
const MAX_CURVE_POINTS = 64;
const SAFE_RASTER_DATA_URL_RE = /^data:image\/(png|jpeg|jpg|webp|gif);base64,[A-Za-z0-9+/=]+$/i;
-const VALID_SUBTIP_ORDERS = new Set(['random', 'sequential', 'direction', 'reverse']);
+const VALID_SUBTIP_ORDERS = new Set<CspSubTipOrder>([
+ 'random',
+ 'random-no-repeat',
+ 'sequential',
+ 'direction',
+ 'reverse',
+ 'once',
+]);
const VALID_ANGLE_DYNAMICS = new Set<CspAngleDynamicsMode>([
'none',
+ 'initial-direction',
'direction',
'tilt',
'twist',
@@ -62,10 +73,14 @@ const VALID_MIXING_MODES = new Set<NaturalMixingMode>([
'impasto_mix',
]);
const VALID_TEXTURE_MODES = new Set<CspPaperTextureMode>([
+ 'normal',
'multiply',
'subtract',
'compare',
'overlay',
+ 'color-burn',
+ 'linear-burn',
+ 'height',
'outline',
]);
const VALID_RENDER_MODES = new Set<BrushRenderMode>(['stamp', 'bristle-ribbon', 'bristle-hybrid']);
@@ -97,10 +112,17 @@ const VALID_CATEGORIES = new Set<BrushCategory | 'custom'>([
'pen',
'sketch',
'brush',
+ 'blend',
'natural-paint',
'custom',
]);
-const VALID_BLEND_MODES = new Set<BlendMode>(ALL_BLEND_MODES);
+const VALID_BRUSH_COMBINE_MODES = new Set<CspBrushCombineMode>([
+ ...ALL_BLEND_MODES,
+ 'add',
+ 'behind',
+ 'clear',
+ 'compare-density',
+]);
interface InkbArchivePayload {
format: typeof INKB_FORMAT;
@@ -158,6 +180,11 @@ function sanitizeSensor(val: unknown): CspSensorConfig | undefined {
if (typeof s.useTilt === 'boolean') out.useTilt = s.useTilt;
const tMin = optNum(s.tiltMin, 0, 1);
if (tMin !== undefined) out.tiltMin = tMin;
+ const tMax = optNum(s.tiltMax, 1, 10);
+ if (tMax !== undefined && tMax > 1) out.tiltMax = tMax;
+ const tCurve = sanitizeCurve(s.tiltCurve);
+ if (tCurve) out.tiltCurve = tCurve;
+ if (typeof s.invertTilt === 'boolean') out.invertTilt = s.invertTilt;
if (typeof s.useTiltAzimuth === 'boolean') out.useTiltAzimuth = s.useTiltAzimuth;
if (typeof s.useBarrelTwist === 'boolean') out.useBarrelTwist = s.useBarrelTwist;
const twMin = optNum(s.twistMin, 0, 1);
@@ -165,6 +192,8 @@ function sanitizeSensor(val: unknown): CspSensorConfig | undefined {
if (typeof s.useVelocity === 'boolean') out.useVelocity = s.useVelocity;
const vMin = optNum(s.velocityMin, 0, 1);
if (vMin !== undefined) out.velocityMin = vMin;
+ const vCurve = sanitizeCurve(s.velocityCurve);
+ if (vCurve) out.velocityCurve = vCurve;
if (typeof s.invertVelocity === 'boolean') out.invertVelocity = s.invertVelocity;
if (typeof s.useDistance === 'boolean') out.useDistance = s.useDistance;
const dMin = optNum(s.distanceMin, 0, 1);
@@ -233,12 +262,33 @@ function sanitizeSpray(val: unknown): CspSpraySettings | undefined {
if (!val || typeof val !== 'object' || Array.isArray(val)) return undefined;
const s = val as Record<string, unknown>;
if (typeof s.enabled !== 'boolean') return undefined;
- return {
+ const out: CspSpraySettings = {
enabled: s.enabled,
size: clampNum(s.size, 0, 1000, 10),
density: clampNum(s.density, 0, 100, 5),
bias: clampNum(s.bias, -100, 100, 0),
};
+ const particleSize = optNum(s.particleSize, 0.5, 2000);
+ if (particleSize !== undefined) out.particleSize = particleSize;
+ const linkSize = optBool(s.linkSize);
+ if (linkSize !== undefined) out.linkSize = linkSize;
+ const sizeSensor = sanitizeSensor(s.sizeSensor);
+ if (sizeSensor) out.sizeSensor = sizeSensor;
+ const densitySensor = sanitizeSensor(s.densitySensor);
+ if (densitySensor) out.densitySensor = densitySensor;
+ const direction = optNum(s.direction, -360, 360);
+ if (direction !== undefined) out.direction = direction;
+ if (
+ typeof s.directionDynamics === 'string' &&
+ VALID_ANGLE_DYNAMICS.has(s.directionDynamics as CspAngleDynamicsMode)
+ ) {
+ out.directionDynamics = s.directionDynamics as CspAngleDynamicsMode;
+ }
+ const directionSensor = sanitizeSensor(s.directionSensor);
+ if (directionSensor) out.directionSensor = directionSensor;
+ const deviation = optNum(s.deviation, -1, 1);
+ if (deviation !== undefined) out.deviation = deviation;
+ return out;
}
function sanitizeTaper(val: unknown): CspTaperSettings | undefined {
@@ -280,11 +330,16 @@ function sanitizeDynamics(val: unknown): BrushDynamics | undefined {
count: Math.round(clampNum(d.count, 1, 10, 1)),
flowJitter: clampNum(d.flowJitter, 0, 1, 0),
colorJitterEnabled: Boolean(d.colorJitterEnabled),
+ colorJitterPerStroke: optBool(d.colorJitterPerStroke),
hueJitter: clampNum(d.hueJitter, 0, 1, 0),
saturationJitter: clampNum(d.saturationJitter, 0, 1, 0),
brightnessJitter: clampNum(d.brightnessJitter, 0, 1, 0),
temperatureJitter: optNum(d.temperatureJitter, 0, 1),
foregroundBackgroundJitter: clampNum(d.foregroundBackgroundJitter, 0, 1, 0),
+ subColorMixSensor: sanitizeSensor(d.subColorMixSensor),
+ hueJitterSensor: sanitizeSensor(d.hueJitterSensor),
+ saturationJitterSensor: sanitizeSensor(d.saturationJitterSensor),
+ luminanceJitterSensor: sanitizeSensor(d.luminanceJitterSensor),
};
}
@@ -301,11 +356,92 @@ function sanitizeSubTips(val: unknown): CspSubTip[] | undefined {
width: Math.round(clampNum(st.width, 1, 4096, 128)),
height: Math.round(clampNum(st.height, 1, 4096, 128)),
isColor: optBool(st.isColor),
+ isDualToneTip: optBool(st.isDualToneTip),
});
}
return out.length > 0 ? out : undefined;
}
+function sanitizeDualBrushConfig(val: unknown): CspDualBrushConfig | undefined {
+ if (!val || typeof val !== 'object' || Array.isArray(val)) return undefined;
+ const d = val as Record<string, unknown>;
+ if (typeof d.enabled !== 'boolean') return undefined;
+ const out: CspDualBrushConfig = {
+ enabled: d.enabled,
+ compositeMode: normalizeDualBrushCompositeMode(
+ typeof d.compositeMode === 'string' ? d.compositeMode : undefined
+ ),
+ };
+ const linkSizeWithMain = optBool(d.linkSizeWithMain);
+ if (linkSizeWithMain !== undefined) out.linkSizeWithMain = linkSizeWithMain;
+ const size = optNum(d.size, 0.5, 2000);
+ if (size !== undefined) out.size = size;
+ const sizeRatio = optNum(d.sizeRatio, 0.01, 20);
+ if (sizeRatio !== undefined) out.sizeRatio = sizeRatio;
+ const spacing = optNum(d.spacing, 0.003, 5);
+ if (spacing !== undefined) out.spacing = spacing;
+ const scatter = optNum(d.scatter, 0, 5);
+ if (scatter !== undefined) out.scatter = scatter;
+ const thickness = optNum(d.thickness, 0.05, 20);
+ if (thickness !== undefined) out.thickness = thickness;
+ const thicknessVertical = optBool(d.thicknessVertical);
+ if (thicknessVertical !== undefined) out.thicknessVertical = thicknessVertical;
+ const hardness = optNum(d.hardness, 0, 1);
+ if (hardness !== undefined) out.hardness = hardness;
+ const density = optNum(d.density, 0, 1);
+ if (density !== undefined) out.density = density;
+ const angle = optNum(d.angle, -360, 360);
+ if (angle !== undefined) out.angle = angle;
+ if (
+ typeof d.angleDynamics === 'string' &&
+ VALID_ANGLE_DYNAMICS.has(d.angleDynamics as CspAngleDynamicsMode)
+ ) {
+ out.angleDynamics = d.angleDynamics as CspAngleDynamicsMode;
+ }
+ const angleSensor = sanitizeSensor(d.angleSensor);
+ if (angleSensor) out.angleSensor = angleSensor;
+ if (typeof d.flipH === 'string' && VALID_FLIP_MODES.has(d.flipH as CspTipFlipMode)) {
+ out.flipH = d.flipH as CspTipFlipMode;
+ }
+ if (typeof d.flipV === 'string' && VALID_FLIP_MODES.has(d.flipV as CspTipFlipMode)) {
+ out.flipV = d.flipV as CspTipFlipMode;
+ }
+ const spray = sanitizeSpray(d.spray);
+ if (spray) out.spray = spray;
+ const tipDataUrl = sanitizeDataUrl(d.tipDataUrl);
+ if (tipDataUrl) out.tipDataUrl = tipDataUrl;
+ const subTips = sanitizeSubTips(d.subTips);
+ if (subTips) out.subTips = subTips;
+ if (
+ typeof d.subTipOrder === 'string' &&
+ VALID_SUBTIP_ORDERS.has(d.subTipOrder as CspSubTipOrder)
+ ) {
+ out.subTipOrder = d.subTipOrder as CspSubTipOrder;
+ }
+ const isRibbon = optBool(d.isRibbon);
+ if (isRibbon !== undefined) out.isRibbon = isRibbon;
+ return out;
+}
+
+function sanitizeImportWarnings(val: unknown): string[] | undefined {
+ if (!Array.isArray(val) || val.length === 0) return undefined;
+ const out: string[] = [];
+ for (const item of val.slice(0, 32)) {
+ if (typeof item !== 'string') continue;
+ const cleaned = item.replace(/[\x00-\x1f\x7f]/g, '').trim().slice(0, 500);
+ if (cleaned) out.push(cleaned);
+ }
+ return out.length > 0 ? out : undefined;
+}
+
+function stripDomImagesFromDualConfig(
+ cfg: CspDualBrushConfig | undefined
+): CspDualBrushConfig | undefined {
+ if (!cfg) return undefined;
+ const { tipImage: _ti, subTipImages: _sti, ...clean } = cfg;
+ return clean;
+}
+
function sanitizeBrushName(raw: unknown, fallbackFileName?: string): string {
const base =
typeof raw === 'string' && raw.trim()
@@ -360,13 +496,16 @@ export function buildExportableBrush(
subTips: merged.subTips ?? existingCustom?.subTips,
subTipOrder: merged.subTipOrder ?? existingCustom?.subTipOrder,
size: clampNum(merged.size, 0.5, 2000, 12),
+ brushSizeUnit: merged.brushSizeUnit,
+ brushSizeSpecifiedByScreen: merged.brushSizeSpecifiedByScreen,
minSizeFactor: clampNum(merged.minSizeFactor, 0, 1, 0.1),
opacity: clampNum(merged.opacity, 0.01, 1, 1),
flow: clampNum(merged.flow, 0.01, 1, 1),
spacing: clampNum(merged.spacing, 0.01, 5, 0.05),
hardness: clampNum(merged.hardness, 0, 1, 0.9),
- thickness: clampNum(merged.thickness, 0.05, 1, 1),
+ thickness: clampNum(merged.thickness, 0.05, 20, 1),
thicknessVertical: merged.thicknessVertical,
+ thicknessSensor: merged.thicknessSensor,
angle: clampNum(merged.customTipAngle ?? existingCustom?.angle, -360, 360, 0),
angleDynamics: merged.customTipAngleDynamics ?? existingCustom?.angleDynamics,
rotationRandomScale: merged.customTipRotationRandomScale ?? existingCustom?.rotationRandomScale,
@@ -390,6 +529,8 @@ export function buildExportableBrush(
sizeSensor: merged.sizeSensor,
opacitySensor: merged.opacitySensor,
densitySensor: merged.densitySensor,
+ intervalSensor: merged.intervalSensor,
+ textureDensitySensor: merged.textureDensitySensor,
bristleSplaySensor: merged.bristleSplaySensor,
paintLoadSensor: merged.paintLoadSensor,
grainPenetrationSensor: merged.grainPenetrationSensor,
@@ -400,6 +541,12 @@ export function buildExportableBrush(
amountOfPaint: merged.amountOfPaint,
densityOfPaint: merged.densityOfPaint,
colorStretch: merged.colorStretch,
+ amountOfPaintSensor: merged.amountOfPaintSensor,
+ densityOfPaintSensor: merged.densityOfPaintSensor,
+ colorStretchSensor: merged.colorStretchSensor,
+ mixGroundColor: merged.mixGroundColor,
+ useBlur: merged.useBlur,
+ blurStrength: merged.blurStrength,
mixingMode: merged.mixingMode,
wetEdge: merged.wetEdge,
wetEdgeRadius: merged.wetEdgeRadius,
@@ -413,15 +560,34 @@ export function buildExportableBrush(
paperTextureBrightness: merged.paperTextureBrightness,
paperTextureContrast: merged.paperTextureContrast,
paperTextureApplyEachPlot: merged.paperTextureApplyEachPlot,
+ paperTextureEmphasizeDensity: merged.paperTextureEmphasizeDensity,
paperTextureInverted: merged.paperTextureInverted,
paperTextureScale: merged.paperTextureScale,
paperTextureRotate: merged.paperTextureRotate,
+ paperTextureOffsetX: merged.paperTextureOffsetX,
+ paperTextureOffsetY: merged.paperTextureOffsetY,
dualBrush: merged.dualBrush,
+ dualBrushConfig: stripDomImagesFromDualConfig(
+ merged.dualBrushConfig ?? existingCustom?.dualBrushConfig
+ ),
dualBrushCompositeMode: merged.dualBrushCompositeMode,
dualSize: merged.dualSize,
+ dualLinkSize: merged.dualLinkSize,
dualSpacing: merged.dualSpacing,
dualScatter: merged.dualScatter,
+ dualThickness: merged.dualThickness,
+ dualThicknessVertical: merged.dualThicknessVertical,
dualAngle: merged.dualAngle,
+ dualAngleDynamics: merged.dualAngleDynamics,
+ dualAngleSensor: merged.dualAngleSensor,
+ dualHardness: merged.dualHardness,
+ dualDensity: merged.dualDensity,
+ dualSubTips: merged.dualSubTips ?? existingCustom?.dualSubTips,
+ dualSubTipOrder: merged.dualSubTipOrder ?? existingCustom?.dualSubTipOrder,
+ dualFlipH: merged.dualFlipH,
+ dualFlipV: merged.dualFlipV,
+ dualSpray: merged.dualSpray,
+ dualIsRibbon: merged.dualIsRibbon,
dualScale: merged.dualScale,
dualSurfaceTextureId: merged.dualSurfaceTextureId,
dualGrainDepth: merged.dualGrainDepth,
@@ -429,6 +595,7 @@ export function buildExportableBrush(
taper: merged.taper,
isRibbon: merged.isRibbon,
isColorTip: merged.isColorTip,
+ isDualToneTip: merged.isDualToneTip,
pressureCurveGamma: merged.pressureCurveGamma,
velocityDynamics: merged.velocityDynamics,
dynamics: merged.dynamics,
@@ -436,6 +603,7 @@ export function buildExportableBrush(
bristle: merged.bristle,
naturalPaint: merged.naturalPaint,
impasto: merged.impasto,
+ importWarnings: merged.importWarnings ?? existingCustom?.importWarnings,
importedAt: Date.now(),
};
}
@@ -450,6 +618,7 @@ export function serializeInkbBrush(brush: CspBrush): Uint8Array {
exportedAt: Date.now(),
brush: {
...brush,
+ dualBrushConfig: stripDomImagesFromDualConfig(brush.dualBrushConfig),
badge: 'INKB',
},
};
@@ -538,17 +707,20 @@ export function parseInkbFile(buffer: ArrayBuffer, fileName: string = 'Brush.ink
secondaryTipHeight: optNum(b.secondaryTipHeight, 1, 4096),
subTips: sanitizeSubTips(b.subTips),
subTipOrder:
- typeof b.subTipOrder === 'string' && VALID_SUBTIP_ORDERS.has(b.subTipOrder)
+ typeof b.subTipOrder === 'string' && VALID_SUBTIP_ORDERS.has(b.subTipOrder as CspSubTipOrder)
? (b.subTipOrder as CspBrush['subTipOrder'])
: undefined,
size: clampNum(b.size, 0.5, 2000, 12),
+ brushSizeUnit: optNum(b.brushSizeUnit, 0, 10),
+ brushSizeSpecifiedByScreen: optBool(b.brushSizeSpecifiedByScreen),
minSizeFactor: clampNum(b.minSizeFactor, 0, 1, 0.1),
opacity: clampNum(b.opacity, 0.01, 1, 1),
flow: clampNum(b.flow, 0.01, 1, 1),
spacing: clampNum(b.spacing, 0.01, 5, 0.05),
hardness: clampNum(b.hardness, 0, 1, 0.9),
- thickness: clampNum(b.thickness, 0.05, 1, 1),
+ thickness: clampNum(b.thickness, 0.05, 20, 1),
thicknessVertical: optBool(b.thicknessVertical),
+ thicknessSensor: sanitizeSensor(b.thicknessSensor),
angle: clampNum(b.angle, -360, 360, 0),
angleDynamics:
typeof b.angleDynamics === 'string' &&
@@ -584,12 +756,14 @@ export function parseInkbFile(buffer: ArrayBuffer, fileName: string = 'Brush.ink
: undefined,
brushCombineMode:
typeof b.brushCombineMode === 'string' &&
- VALID_BLEND_MODES.has(b.brushCombineMode as BlendMode)
- ? (b.brushCombineMode as BlendMode)
+ VALID_BRUSH_COMBINE_MODES.has(b.brushCombineMode as CspBrushCombineMode)
+ ? (b.brushCombineMode as CspBrushCombineMode)
: undefined,
sizeSensor: sanitizeSensor(b.sizeSensor),
opacitySensor: sanitizeSensor(b.opacitySensor),
densitySensor: sanitizeSensor(b.densitySensor),
+ intervalSensor: sanitizeSensor(b.intervalSensor),
+ textureDensitySensor: sanitizeSensor(b.textureDensitySensor),
bristleSplaySensor: sanitizeSensor(b.bristleSplaySensor),
paintLoadSensor: sanitizeSensor(b.paintLoadSensor),
grainPenetrationSensor: sanitizeSensor(b.grainPenetrationSensor),
@@ -600,14 +774,30 @@ export function parseInkbFile(buffer: ArrayBuffer, fileName: string = 'Brush.ink
amountOfPaint: optNum(b.amountOfPaint, 0, 1),
densityOfPaint: optNum(b.densityOfPaint, 0, 1),
colorStretch: optNum(b.colorStretch, 0, 1),
+ amountOfPaintSensor: sanitizeSensor(b.amountOfPaintSensor),
+ densityOfPaintSensor: sanitizeSensor(b.densityOfPaintSensor),
+ colorStretchSensor: sanitizeSensor(b.colorStretchSensor),
+ mixGroundColor: optBool(b.mixGroundColor),
+ useBlur: optBool(b.useBlur),
+ blurStrength: optNum(b.blurStrength, 0, 1),
mixingMode:
typeof b.mixingMode === 'string' && VALID_MIXING_MODES.has(b.mixingMode as NaturalMixingMode)
? (b.mixingMode as CspBrush['mixingMode'])
: undefined,
wetEdge: optNum(b.wetEdge, 0, 1),
wetEdgeRadius: optNum(b.wetEdgeRadius, 0, 100),
- wetEdgeAlphaPower: optNum(b.wetEdgeAlphaPower, 0, 10),
- wetEdgeValuePower: optNum(b.wetEdgeValuePower, 0, 10),
+ wetEdgeAlphaPower:
+ typeof b.wetEdgeAlphaPower === 'number' && Number.isFinite(b.wetEdgeAlphaPower)
+ ? b.wetEdgeAlphaPower > 1
+ ? Math.max(0, Math.min(1, b.wetEdgeAlphaPower / 100))
+ : Math.max(0, Math.min(1, b.wetEdgeAlphaPower))
+ : undefined,
+ wetEdgeValuePower:
+ typeof b.wetEdgeValuePower === 'number' && Number.isFinite(b.wetEdgeValuePower)
+ ? b.wetEdgeValuePower > 1
+ ? Math.max(0, Math.min(1, b.wetEdgeValuePower / 100))
+ : Math.max(0, Math.min(1, b.wetEdgeValuePower))
+ : undefined,
paperTexture: sanitizeDataUrl(b.paperTexture),
surfaceTextureId:
typeof b.surfaceTextureId === 'string' &&
@@ -628,16 +818,47 @@ export function parseInkbFile(buffer: ArrayBuffer, fileName: string = 'Brush.ink
paperTextureBrightness: optNum(b.paperTextureBrightness, -100, 100),
paperTextureContrast: optNum(b.paperTextureContrast, -100, 100),
paperTextureApplyEachPlot: optBool(b.paperTextureApplyEachPlot),
+ paperTextureEmphasizeDensity: optBool(b.paperTextureEmphasizeDensity),
paperTextureScale: optNum(b.paperTextureScale, 0.05, 20),
paperTextureRotate: optNum(b.paperTextureRotate, -360, 360),
+ paperTextureOffsetX: optNum(b.paperTextureOffsetX, -10000, 10000),
+ paperTextureOffsetY: optNum(b.paperTextureOffsetY, -10000, 10000),
paperTextureInverted: optBool(b.paperTextureInverted),
dualBrush: optBool(b.dualBrush),
+ dualBrushConfig: sanitizeDualBrushConfig(b.dualBrushConfig),
dualBrushCompositeMode:
typeof b.dualBrushCompositeMode === 'string' ? b.dualBrushCompositeMode.slice(0, 32) : undefined,
dualSize: optNum(b.dualSize, 0.5, 2000),
- dualSpacing: optNum(b.dualSpacing, 0.01, 5),
+ dualLinkSize: optBool(b.dualLinkSize),
+ dualSpacing: optNum(b.dualSpacing, 0.003, 5),
dualScatter: optNum(b.dualScatter, 0, 5),
+ dualThickness: optNum(b.dualThickness, 0.05, 20),
+ dualThicknessVertical: optBool(b.dualThicknessVertical),
dualAngle: optNum(b.dualAngle, -360, 360),
+ dualAngleDynamics:
+ typeof b.dualAngleDynamics === 'string' &&
+ VALID_ANGLE_DYNAMICS.has(b.dualAngleDynamics as CspAngleDynamicsMode)
+ ? (b.dualAngleDynamics as CspAngleDynamicsMode)
+ : undefined,
+ dualAngleSensor: sanitizeSensor(b.dualAngleSensor),
+ dualHardness: optNum(b.dualHardness, 0, 1),
+ dualDensity: optNum(b.dualDensity, 0, 1),
+ dualSubTips: sanitizeSubTips(b.dualSubTips),
+ dualSubTipOrder:
+ typeof b.dualSubTipOrder === 'string' &&
+ VALID_SUBTIP_ORDERS.has(b.dualSubTipOrder as CspSubTipOrder)
+ ? (b.dualSubTipOrder as CspSubTipOrder)
+ : undefined,
+ dualFlipH:
+ typeof b.dualFlipH === 'string' && VALID_FLIP_MODES.has(b.dualFlipH as CspTipFlipMode)
+ ? (b.dualFlipH as CspTipFlipMode)
+ : undefined,
+ dualFlipV:
+ typeof b.dualFlipV === 'string' && VALID_FLIP_MODES.has(b.dualFlipV as CspTipFlipMode)
+ ? (b.dualFlipV as CspTipFlipMode)
+ : undefined,
+ dualSpray: sanitizeSpray(b.dualSpray),
+ dualIsRibbon: optBool(b.dualIsRibbon),
dualScale: optNum(b.dualScale, 0.05, 10),
dualSurfaceTextureId:
typeof b.dualSurfaceTextureId === 'string' &&
@@ -649,6 +870,7 @@ export function parseInkbFile(buffer: ArrayBuffer, fileName: string = 'Brush.ink
taper: sanitizeTaper(b.taper),
isRibbon: optBool(b.isRibbon),
isColorTip: optBool(b.isColorTip),
+ isDualToneTip: optBool(b.isDualToneTip),
pressureCurveGamma: optNum(b.pressureCurveGamma, 0.1, 5),
velocityDynamics: optBool(b.velocityDynamics),
dynamics: sanitizeDynamics(b.dynamics),
@@ -659,6 +881,7 @@ export function parseInkbFile(buffer: ArrayBuffer, fileName: string = 'Brush.ink
bristle: sanitizeBristle(b.bristle),
naturalPaint: sanitizeNaturalPaint(b.naturalPaint),
impasto: sanitizeImpasto(b.impasto),
+ importWarnings: sanitizeImportWarnings(b.importWarnings),
importedAt: Date.now(),
};
}
diff --git a/src/utils/nativeBackend.ts b/src/utils/nativeBackend.ts
index 4b5bbbf..ceb02c7 100644
--- a/src/utils/nativeBackend.ts
+++ b/src/utils/nativeBackend.ts
@@ -326,16 +326,37 @@ export async function parsePsdNative(
return hydrateParsedDocumentBinary(toUint8Array(raw), fileName, targetGrid);
}
+export type CspExpressionColor = 'color' | 'gray' | 'monochrome';
+
+export interface NativeSutMaterial {
+ pwId: string;
+ originalPath: string;
+ catalogPath: string;
+ fileData: Uint8Array;
+ decodedPng?: Uint8Array;
+ width?: number;
+ height?: number;
+ expressionColor?: CspExpressionColor;
+ isPaperTexture?: boolean;
+ hasSubColor?: boolean;
+ decodedFromLayer?: boolean;
+}
+
export interface NativeSutExtract {
nodeName: string | null;
+ nodeUuid?: string | null;
variantId: number | null;
+ nodeInitVariantId?: number | null;
variantValues: Map<string, unknown>;
- materials: Array<{
- pwId: string;
- originalPath: string;
- catalogPath: string;
- fileData: Uint8Array;
- }>;
+ dualVariantValues?: Map<string, unknown>;
+ materials: NativeSutMaterial[];
+}
+
+function normalizeExpressionColor(val: unknown): CspExpressionColor | undefined {
+ if (val === 'color' || val === 'gray' || val === 'monochrome') {
+ return val;
+ }
+ return undefined;
}
export async function parseSutSqliteNative(bytes: Uint8Array): Promise<NativeSutExtract> {
@@ -353,17 +374,32 @@ export async function parseSutSqliteNative(bytes: Uint8Array): Promise<NativeSut
}
const view = new DataView(wire.buffer, wire.byteOffset, wire.byteLength);
const metaLen = view.getUint32(4, true);
+ if (8 + metaLen > wire.byteLength) {
+ throw new Error('Truncated SUTD metadata header');
+ }
const meta = JSON.parse(utf8Decoder.decode(wire.subarray(8, 8 + metaLen))) as {
nodeName: string | null;
+ nodeUuid?: string | null;
variantId: number | null;
+ nodeInitVariantId?: number | null;
variantScalars: Record<string, unknown>;
variantBlobs: Record<string, { offset: number; len: number }>;
+ dualVariantScalars?: Record<string, unknown>;
+ dualVariantBlobs?: Record<string, { offset: number; len: number }>;
materials: Array<{
pwId: string;
originalPath: string;
catalogPath: string;
fileDataOffset: number;
fileDataLen: number;
+ decodedPngOffset?: number;
+ decodedPngLen?: number;
+ width?: number;
+ height?: number;
+ expressionColor?: string;
+ isPaperTexture?: boolean;
+ hasSubColor?: boolean;
+ decodedFromLayer?: boolean;
}>;
};
const blobs = wire.subarray(8 + metaLen);
@@ -374,16 +410,50 @@ export async function parseSutSqliteNative(bytes: Uint8Array): Promise<NativeSut
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) => ({
+
+ let dualVariantValues: Map<string, unknown> | undefined = undefined;
+ if (meta.dualVariantScalars || meta.dualVariantBlobs) {
+ const dualMap = new Map<string, unknown>();
+ if (meta.dualVariantScalars) {
+ for (const [k, v] of Object.entries(meta.dualVariantScalars)) {
+ dualMap.set(k.toLowerCase(), v);
+ }
+ }
+ if (meta.dualVariantBlobs) {
+ for (const [k, ref] of Object.entries(meta.dualVariantBlobs)) {
+ dualMap.set(k.toLowerCase(), blobs.subarray(ref.offset, ref.offset + ref.len));
+ }
+ }
+ if (dualMap.size > 0) {
+ dualVariantValues = dualMap;
+ }
+ }
+
+ const materials: NativeSutMaterial[] = meta.materials.map((m) => ({
pwId: m.pwId,
originalPath: m.originalPath,
catalogPath: m.catalogPath,
fileData: blobs.subarray(m.fileDataOffset, m.fileDataOffset + m.fileDataLen),
+ decodedPng:
+ typeof m.decodedPngOffset === 'number' &&
+ typeof m.decodedPngLen === 'number' &&
+ m.decodedPngLen > 0
+ ? blobs.subarray(m.decodedPngOffset, m.decodedPngOffset + m.decodedPngLen)
+ : undefined,
+ width: m.width,
+ height: m.height,
+ expressionColor: normalizeExpressionColor(m.expressionColor),
+ isPaperTexture: m.isPaperTexture,
+ hasSubColor: m.hasSubColor,
+ decodedFromLayer: m.decodedFromLayer,
}));
return {
nodeName: meta.nodeName,
+ nodeUuid: meta.nodeUuid ?? null,
variantId: meta.variantId,
+ nodeInitVariantId: meta.nodeInitVariantId ?? null,
variantValues,
+ dualVariantValues,
materials,
};
}
diff --git a/src/utils/nativeTabletInput.ts b/src/utils/nativeTabletInput.ts
index 4f7dc76..a38c37b 100644
--- a/src/utils/nativeTabletInput.ts
+++ b/src/utils/nativeTabletInput.ts
@@ -42,6 +42,10 @@ let activeStatus: NativeTabletStatus = {
maxPressure: 1024,
};
let lastPacketPerfMs = 0;
+let nativePenInProximity = false;
+let nativePenInContact = false;
+let lastNativeClientX = 0;
+let lastNativeClientY = 0;
let startPromise: Promise<NativeTabletStatus> | null = null;
/**
@@ -81,14 +85,103 @@ export function unpackTabletSampleBatch(raw: ArrayBuffer | Uint8Array | number[]
return out;
}
+/**
+ * Updates internal native pen proximity/contact tracking from a received native tablet batch.
+ * Exported for deterministic unit testing of DOM pointer suppression logic.
+ */
+export function recordNativeTabletBatchForSuppression(
+ batch: ReadonlyArray<NativeTabletSample>,
+ nowMs?: number
+): void {
+ if (batch.length === 0) return;
+ lastPacketPerfMs =
+ nowMs !== undefined ? nowMs : typeof performance !== 'undefined' ? performance.now() : Date.now();
+ for (let i = 0; i < batch.length; i++) {
+ const s = batch[i];
+ if (s.phase === 1 || s.phase === 2) {
+ nativePenInProximity = true;
+ nativePenInContact = true;
+ lastNativeClientX = s.clientX;
+ lastNativeClientY = s.clientY;
+ } else if (s.phase === 0 || s.phase === 3) {
+ nativePenInProximity = true;
+ nativePenInContact = false;
+ lastNativeClientX = s.clientX;
+ lastNativeClientY = s.clientY;
+ } else if (s.phase === 4) {
+ const stillDown = (s.buttons & 1) !== 0 || s.pressure > 0.001;
+ if (!stillDown) {
+ nativePenInProximity = false;
+ nativePenInContact = false;
+ }
+ }
+ }
+}
+
+/**
+ * Resets internal native tablet stream state (for unit tests and shutdown).
+ */
+export function resetNativeTabletSuppressionState(activeOverride?: boolean): void {
+ lastPacketPerfMs = 0;
+ nativePenInProximity = false;
+ nativePenInContact = false;
+ lastNativeClientX = 0;
+ lastNativeClientY = 0;
+ if (activeOverride !== undefined) {
+ activeStatus = { ...activeStatus, active: activeOverride };
+ }
+}
+
/**
* 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 {
+export function isNativePenStreamActive(nowMs?: number): boolean {
if (!activeStatus.active) return false;
- const now = typeof performance !== 'undefined' ? performance.now() : Date.now();
- return now - lastPacketPerfMs < 250;
+ const now =
+ nowMs !== undefined ? nowMs : typeof performance !== 'undefined' ? performance.now() : Date.now();
+ return lastPacketPerfMs > 0 && now - lastPacketPerfMs < 1500;
+}
+
+/**
+ * Returns true if a DOM PointerEvent should be suppressed because the native WinTab / Windows Ink
+ * channel already owns this pen interaction.
+ *
+ * Critically suppresses WinTab `CXO_SYSTEM`-synthesized DOM `pointerType === 'mouse'` events
+ * (which carry constant `pressure = 0.5` and would otherwise abort/hijack active native pen strokes!),
+ * while allowing a separate physical mouse to work immediately once the stylus leaves proximity.
+ */
+export function shouldSuppressDomPointerEvent(
+ pointerType: string,
+ clientX: number,
+ clientY: number,
+ nowMs?: number
+): boolean {
+ if (!activeStatus.active || lastPacketPerfMs <= 0) return false;
+ const now =
+ nowMs !== undefined ? nowMs : typeof performance !== 'undefined' ? performance.now() : Date.now();
+ const elapsed = now - lastPacketPerfMs;
+
+ if (pointerType === 'pen') {
+ return elapsed < 1500;
+ }
+
+ if (pointerType === 'mouse') {
+ // Active native pen stroke: NEVER allow a WinTab-synthesized mouse event to abort or duplicate it
+ if (nativePenInContact && elapsed < 1500) {
+ return true;
+ }
+ // Stylus actively hovering/tracking in proximity: WinTab CXO_SYSTEM drives the OS mouse cursor
+ if (nativePenInProximity && elapsed < 400) {
+ return true;
+ }
+ // Brief post-lift/pre-down coincidence window at the exact pen cursor location
+ if (elapsed < 250 && Math.hypot(clientX - lastNativeClientX, clientY - lastNativeClientY) <= 24) {
+ return true;
+ }
+ }
+
+ return false;
}
export function getCachedTabletStatus(): NativeTabletStatus {
@@ -119,7 +212,7 @@ export async function startNativeTablet(mode: TabletInputMode = 'auto'): Promise
channel.onmessage = (payload) => {
const batch = unpackTabletSampleBatch(payload);
if (batch.length === 0) return;
- lastPacketPerfMs = typeof performance !== 'undefined' ? performance.now() : Date.now();
+ recordNativeTabletBatchForSuppression(batch);
for (const fn of listeners) {
fn(batch);
}
@@ -154,6 +247,7 @@ export async function stopNativeTablet(): Promise<void> {
} catch {
// Ignore shutdown errors
}
+ resetNativeTabletSuppressionState(false);
activeStatus = {
...activeStatus,
active: false,
diff --git a/src/utils/presetBrushes.ts b/src/utils/presetBrushes.ts
index 542d891..0951215 100644
--- a/src/utils/presetBrushes.ts
+++ b/src/utils/presetBrushes.ts
@@ -2,27 +2,37 @@ import {
BrushCategory,
BrushPresetId,
BrushSettings,
+ CspSubTip,
DEFAULT_BRUSH_DYNAMICS,
} from '../types/editor';
import { CSP_PRESSURE_CURVE_PRESETS } from '../engine/BrushEngine';
import {
generateRealGPenTip,
- generateTexturedPenTip,
+ generateRoughPenRibbonTip,
generateCalligraphyTip,
generateMechanicalPencilTip,
generateHb2bPencilTip,
generate6b8bPencilTip,
generateCharcoalTip,
generateChalkTip,
- generateOilBristleTip,
- generateThickOilTip,
- generateChalkPaintTip,
- generateNoiseShaderTip,
+ generateOilFlatAllaPrimaTip,
+ generateImpastoFilbertTip,
+ generateDryBristleRakePaintTip,
+ generateConceptMatteChalkTip,
+ generateMineralGrainDualTip,
+ generateSilkyPortraitRoundTip,
+ generateCanvasScumbleSubTip,
+ generateAtmosphericGrainTip,
+ generateDetailFilbertTip,
+ generateBlendOilBristleTip,
+ generateBlendMatteChalkTip,
+ generateBlendRakeHairTip,
+ generateBlendCanvasScumbleTip,
+ generateBlendFingertipTip,
generateFinePaperTexture,
generateSketchPaperTexture,
generateCharcoalPaperTexture,
- generateCanvasWeaveTexture,
- generateNoiseGrainTexture,
+ generatePainterlyChalkGrainTexture,
generateNaturalTipByProfile,
getSurfaceTextureDataUrl,
} from './proceduralBrushTips';
@@ -36,9 +46,12 @@ export interface BuiltinBrushDefinition {
badgeText: string;
badgeBorder: string;
desc: string;
- icon: 'pen' | 'pencil' | 'paintbrush' | 'palette';
+ icon: 'pen' | 'pencil' | 'paintbrush' | 'droplets' | 'palette';
settings: Partial<BrushSettings>;
tipGenerator?: () => string; // Returns Base64 PNG data URL
+ subTipGenerators?: Array<() => string>; // Multi-tip procedural generators (e.g., Rough Pen ribbon, Canvas Scumble)
+ subTipDimensions?: { width: number; height: number }; // Explicit dimensions for subTips metadata (default 256x256)
+ dualTipGenerator?: () => string; // Optional secondary tip generator for built-in Dual Brushes
paperTextureGenerator?: () => string; // Returns seamless Base64 PNG data URL
}
@@ -51,6 +64,7 @@ export const BUILTIN_BRUSH_SECTIONS: BuiltinBrushSection[] = [
{ id: 'pen', label: 'Pen' },
{ id: 'sketch', label: 'Sketch' },
{ id: 'brush', label: 'Brush' },
+ { id: 'blend', label: 'Blend' },
{ id: 'natural-paint', label: 'Natural Paint' },
];
@@ -70,7 +84,7 @@ export function getPreloadedBuiltinTipImage(dataUrl: string): HTMLImageElement |
export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
// =========================================================================
- // PEN SECTION
+ // PEN SECTION (PORTED & ADAPTED FROM OFFICIAL CSP PEN BRUSHES)
// =========================================================================
{
id: 'g-pen',
@@ -80,21 +94,43 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
badgeBg: 'bg-indigo-500/15',
badgeText: 'text-indigo-300',
badgeBorder: 'border-indigo-500/30',
- desc: 'Sharp Pressure Taper & Inking',
+ desc: 'Classic CSP G-Pen — Razor-Sharp Pressure Taper & Pen Tilt Swell',
icon: 'pen',
settings: {
- size: 8,
- minSizeFactor: 0.04,
+ size: 12,
+ minSizeFactor: 0.03,
flow: 1.0,
opacity: 1.0,
hardness: 1.0,
antiAlias: 2,
- spacing: 0.04,
- stabilization: 20,
+ spacing: 0.05,
+ stabilization: 10,
sharpCorners: true,
usePressure: true,
- useTilt: false,
+ useTilt: true,
smoothing: true,
+ pressureCurve: [
+ [0.0, 0.0],
+ [1.0, 1.0],
+ ],
+ sizeSensor: {
+ usePressure: true,
+ pressureMin: 0.0,
+ pressureCurve: [
+ [0.0, 0.0],
+ [1.0, 1.0],
+ ],
+ useTilt: true,
+ tiltMin: 1.0,
+ tiltMax: 1.5,
+ tiltCurve: [
+ [0.0, 1.0],
+ [0.2455, 0.9273],
+ [0.3909, 0.4],
+ [0.6545, 0.0],
+ [1.0, 0.0],
+ ],
+ },
useGpu: true,
},
},
@@ -106,40 +142,59 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
badgeBg: 'bg-indigo-500/15',
badgeText: 'text-indigo-300',
badgeBorder: 'border-indigo-500/30',
- desc: 'Organic Manga Nib with Subtle Ink-on-Paper Edge Texture',
+ desc: 'Authentic CSP Dip-Pen Nib — Jagged Porous Mask, Concave J-Curve & Pressure Nib Spread',
icon: 'pen',
tipGenerator: generateRealGPenTip,
settings: {
- size: 8,
- minSizeFactor: 0.05,
- flow: 0.96,
+ size: 10,
+ minSizeFactor: 0.02,
+ flow: 1.0,
opacity: 1.0,
- hardness: 0.96,
+ hardness: 1.0,
antiAlias: 2,
- spacing: 0.045,
- stabilization: 18,
+ thickness: 0.85,
+ thicknessVertical: false,
+ spacing: 0.07,
+ stabilization: 9,
sharpCorners: true,
usePressure: true,
- useTilt: false,
+ useTilt: true,
smoothing: true,
- pressureCurve: CSP_PRESSURE_CURVE_PRESETS['g-pen'].points,
customTipAngleDynamics: 'random',
- flipH: 'random',
- flipV: 'random',
- grain: 0.24,
- textureDensity: 0.24,
- paperTextureMode: 'outline',
- paperTextureScale: 0.85,
- paperTextureContrast: 25,
- taper: {
- useIn: false,
- inLength: 0,
- inRatio: 0,
- useOut: true,
- outLength: 10,
- outRatio: 0.25,
- endingSharpness: 0.72,
- affectSize: true,
+ customTipRotationRandomScale: 1.0,
+ pressureCurve: [
+ [0.0, 0.0],
+ [0.7455, 0.2545],
+ [1.0, 1.0],
+ ],
+ sizeSensor: {
+ usePressure: true,
+ pressureMin: 0.0,
+ pressureCurve: [
+ [0.0, 0.0],
+ [0.7455, 0.2545],
+ [1.0, 1.0],
+ ],
+ useTilt: true,
+ tiltMin: 1.0,
+ tiltMax: 1.5,
+ tiltCurve: [
+ [0.0, 1.0],
+ [0.2182, 0.9455],
+ [0.4818, 0.2],
+ [0.8, 0.0],
+ [1.0, 0.0],
+ ],
+ },
+ thicknessSensor: {
+ usePressure: true,
+ pressureMin: 0.5,
+ pressureCurve: [
+ [0.0, 0.0],
+ [0.3455, 0.0],
+ [0.6636, 0.9545],
+ [1.0, 1.0],
+ ],
},
useGpu: true,
},
@@ -152,36 +207,115 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
badgeBg: 'bg-indigo-500/15',
badgeText: 'text-indigo-300',
badgeBorder: 'border-indigo-500/30',
- desc: 'Expressive Dry-Edge Inking Pen with Paper Tooth Breakup',
+ desc: 'Authentic CSP Textured Pen — Random-Rotated Elliptical Nib with Compare-Density Edge Tooth',
icon: 'pen',
- tipGenerator: generateTexturedPenTip,
settings: {
- size: 9,
- minSizeFactor: 0.08,
- flow: 0.92,
+ size: 12,
+ minSizeFactor: 0.04,
+ flow: 1.0,
opacity: 1.0,
- hardness: 0.92,
- antiAlias: 2,
- spacing: 0.055,
- stabilization: 15,
+ hardness: 0.6,
+ antiAlias: 1,
+ thickness: 0.6,
+ thicknessVertical: true,
+ spacing: 0.1,
+ stabilization: 8,
sharpCorners: true,
usePressure: true,
useTilt: false,
smoothing: true,
customTipAngleDynamics: 'random',
- flipH: 'random',
- flipV: 'random',
- grain: 0.56,
- textureDensity: 0.56,
- paperTextureMode: 'subtract',
- paperTextureScale: 1.0,
- paperTextureContrast: 38,
- opacitySensor: { usePressure: true, pressureMin: 0.55 },
- dynamics: {
- ...DEFAULT_BRUSH_DYNAMICS,
- sizeJitter: 0.08,
- angleJitter: 1.0,
- flowJitter: 0.12,
+ customTipRotationRandomScale: 1.0,
+ brushCombineMode: 'compare-density',
+ pressureCurve: [
+ [0.0, 0.0],
+ [1.0, 1.0],
+ ],
+ sizeSensor: {
+ usePressure: true,
+ pressureMin: 0.0,
+ pressureCurve: [
+ [0.0, 0.0],
+ [1.0, 1.0],
+ ],
+ },
+ useGpu: true,
+ },
+ },
+ {
+ id: 'rough-pen',
+ category: 'pen',
+ name: 'Rough Pen',
+ badge: 'Pen',
+ badgeBg: 'bg-indigo-500/15',
+ badgeText: 'text-indigo-300',
+ badgeBorder: 'border-indigo-500/30',
+ desc: 'CSP Ribbon Rough Ink Pen — Organic Tiling Ink Strand with Pressure, Tilt & Velocity Dynamics',
+ icon: 'pen',
+ subTipGenerators: [
+ () => generateRoughPenRibbonTip(0),
+ () => generateRoughPenRibbonTip(1),
+ () => generateRoughPenRibbonTip(2),
+ ],
+ subTipDimensions: { width: 64, height: 512 },
+ settings: {
+ size: 11,
+ minSizeFactor: 0.04,
+ flow: 1.0,
+ opacity: 1.0,
+ hardness: 1.0,
+ antiAlias: 1,
+ thickness: 1.5,
+ thicknessVertical: true,
+ spacing: 0.08,
+ stabilization: 8,
+ sharpCorners: false,
+ usePressure: true,
+ useTilt: true,
+ useVelocity: true,
+ smoothing: true,
+ isRibbon: true,
+ subTipOrder: 'random',
+ flipH: 'alternate',
+ flipV: 'alternate',
+ pressureCurve: [
+ [0.0, 0.0],
+ [1.0, 1.0],
+ ],
+ sizeSensor: {
+ usePressure: true,
+ pressureMin: 0.0,
+ pressureCurve: [
+ [0.0, 0.0],
+ [1.0, 1.0],
+ ],
+ useTilt: true,
+ tiltMin: 1.0,
+ tiltMax: 2.0,
+ tiltCurve: [
+ [0.0, 1.0],
+ [0.2182, 0.9455],
+ [0.5545, 0.0],
+ [1.0, 0.0],
+ ],
+ useVelocity: true,
+ velocityMin: 0.5,
+ velocityCurve: [
+ [0.0, 1.0],
+ [1.0, 0.0],
+ ],
+ useRandom: true,
+ randomMin: 0.8,
+ },
+ thicknessSensor: {
+ useVelocity: true,
+ velocityMin: 0.5,
+ velocityCurve: [
+ [0.0, 1.0],
+ [1.0, 0.0],
+ ],
+ useRandom: true,
+ randomMin: 0.85,
},
useGpu: true,
},
@@ -497,251 +631,359 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
},
// =========================================================================
- // BRUSH SECTION (COLORING & PAINTING)
+ // BRUSH SECTION (PRO PAINTERLY ILLUSTRATION & COLORING SUITE)
// =========================================================================
{
- id: 'oil-painting',
+ id: 'oil-flat-alla-prima',
category: 'brush',
- name: 'Oil Painting Brush',
+ name: 'Alla-Prima Oil Flat',
badge: 'Brush',
badgeBg: 'bg-emerald-500/15',
badgeText: 'text-emerald-300',
badgeBorder: 'border-emerald-500/30',
- desc: 'Natural Bristle Oil — Perceptual Pigment Mixing & Smooth Color Stretch',
+ desc: 'Asymmetric Flat Hog-Bristle — Crisp Architectural Edge & Feathered Tail for Lost-and-Found Planes',
icon: 'paintbrush',
- tipGenerator: generateOilBristleTip,
- paperTextureGenerator: generateCanvasWeaveTexture,
+ tipGenerator: generateOilFlatAllaPrimaTip,
+ paperTextureGenerator: () => getSurfaceTextureDataUrl('linen-canvas'),
settings: {
- size: 32,
- minSizeFactor: 0.35,
- flow: 0.88,
+ size: 38,
+ minSizeFactor: 0.34,
+ flow: 0.9,
opacity: 1.0,
- hardness: 0.75,
+ hardness: 0.86,
antiAlias: 2,
- thickness: 0.85,
- spacing: 0.06,
+ thickness: 0.72,
+ customTipAngle: -22,
+ customTipAngleDynamics: 'none',
+ flipH: 'none',
+ flipV: 'none',
+ spacing: 0.05,
+ adjustDensityByGap: false,
stabilization: 8,
sharpCorners: false,
usePressure: true,
useTilt: true,
- tiltScale: 0.9,
+ tiltScale: 1.15,
smoothing: true,
- customTipAngleDynamics: 'direction',
- flipH: 'none',
- flipV: 'alternate',
colorMixing: true,
perceptualMixing: true,
mixingMode: 'blend',
- amountOfPaint: 0.68,
- densityOfPaint: 0.86,
- colorStretch: 0.68,
- grain: 0.22,
- textureDensity: 0.22,
+ amountOfPaint: 0.78,
+ densityOfPaint: 0.92,
+ colorStretch: 0.54,
+ surfaceTextureId: 'linen-canvas',
paperTextureMode: 'multiply',
- paperTextureScale: 1.2,
- opacitySensor: { usePressure: true, pressureMin: 0.35 },
+ grain: 0.2,
+ textureDensity: 0.2,
+ paperTextureScale: 0.9,
+ paperTextureContrast: 10,
+ opacitySensor: { usePressure: true, pressureMin: 0.22 },
useGpu: true,
},
},
{
- id: 'thick-oil-painting',
+ id: 'thick-oil-impasto',
category: 'brush',
- name: 'Thick Oil Painting',
+ name: 'Loaded Impasto Oil',
badge: 'Brush',
badgeBg: 'bg-emerald-500/15',
badgeText: 'text-emerald-300',
badgeBorder: 'border-emerald-500/30',
- desc: 'Heavy Impasto Flat Bristles — Loaded Pigment Ridges & Rich Paint Drag',
+ desc: 'Chiseled Multi-Tuft Hog-Bristle Filbert — Bold Impasto Ridges & Rich Directional Color Drag',
icon: 'paintbrush',
- tipGenerator: generateThickOilTip,
- paperTextureGenerator: generateCanvasWeaveTexture,
+ tipGenerator: generateImpastoFilbertTip,
+ paperTextureGenerator: () => getSurfaceTextureDataUrl('linen-canvas'),
settings: {
- size: 38,
- minSizeFactor: 0.45,
+ size: 42,
+ minSizeFactor: 0.38,
flow: 0.96,
opacity: 1.0,
hardness: 0.9,
antiAlias: 2,
- thickness: 0.62,
- spacing: 0.055,
- stabilization: 10,
+ thickness: 0.66,
+ customTipAngleDynamics: 'direction',
+ flipH: 'none',
+ flipV: 'none',
+ spacing: 0.07,
+ adjustDensityByGap: false,
+ stabilization: 9,
sharpCorners: false,
usePressure: true,
useTilt: true,
- tiltScale: 1.1,
+ tiltScale: 1.15,
smoothing: true,
+ colorMixing: true,
+ perceptualMixing: true,
+ mixingMode: 'running_color',
+ amountOfPaint: 0.84,
+ densityOfPaint: 0.96,
+ colorStretch: 0.76,
+ surfaceTextureId: 'linen-canvas',
+ paperTextureMode: 'compare',
+ grain: 0.28,
+ textureDensity: 0.28,
+ paperTextureScale: 0.95,
+ paperTextureContrast: 20,
+ opacitySensor: { usePressure: true, pressureMin: 0.42 },
+ densityOfPaintSensor: { usePressure: true, pressureMin: 0.55 },
+ useGpu: true,
+ },
+ },
+ {
+ id: 'dry-bristle-rake-paint',
+ category: 'brush',
+ name: 'Dry Bristle Rake',
+ badge: 'Brush',
+ badgeBg: 'bg-emerald-500/15',
+ badgeText: 'text-emerald-300',
+ badgeBorder: 'border-emerald-500/30',
+ desc: 'Separated Organic Bristle Clusters — Expressive Dry Highlights, Cheek Scratches, Hair & Fabric Tooth',
+ icon: 'paintbrush',
+ tipGenerator: generateDryBristleRakePaintTip,
+ paperTextureGenerator: () => getSurfaceTextureDataUrl('linen-canvas'),
+ settings: {
+ size: 40,
+ minSizeFactor: 0.36,
+ flow: 0.92,
+ opacity: 1.0,
+ hardness: 0.92,
+ antiAlias: 2,
+ thickness: 0.86,
customTipAngleDynamics: 'direction',
flipH: 'none',
flipV: 'none',
+ spacing: 0.042,
+ adjustDensityByGap: false,
+ stabilization: 7,
+ sharpCorners: false,
+ usePressure: true,
+ useTilt: true,
+ tiltScale: 1.2,
+ smoothing: true,
colorMixing: true,
perceptualMixing: true,
mixingMode: 'running_color',
amountOfPaint: 0.82,
- densityOfPaint: 0.95,
- colorStretch: 0.78,
- grain: 0.3,
- textureDensity: 0.3,
+ densityOfPaint: 0.94,
+ colorStretch: 0.7,
+ surfaceTextureId: 'linen-canvas',
paperTextureMode: 'multiply',
- paperTextureScale: 1.35,
- opacitySensor: { usePressure: true, pressureMin: 0.55 },
+ grain: 0.24,
+ textureDensity: 0.24,
+ paperTextureScale: 0.88,
+ paperTextureContrast: 10,
+ opacitySensor: { usePressure: true, pressureMin: 0.24 },
useGpu: true,
},
},
{
- id: 'chalk-painting',
+ id: 'concept-matte-chalk',
category: 'brush',
- name: 'Chalk Painting',
+ name: 'Concept Matte Chalk / Gouache',
badge: 'Brush',
badgeBg: 'bg-emerald-500/15',
badgeText: 'text-emerald-300',
badgeBorder: 'border-emerald-500/30',
- desc: 'Painterly Textured Chalk — Blended Pigments with Dry Gritty Tooth',
+ desc: 'Sculptural Chipped Square Chalk + Mineral Dual Brush — Crisp Concept-Art Planes & Velvety Matte Tooth',
icon: 'paintbrush',
- tipGenerator: generateChalkPaintTip,
- paperTextureGenerator: generateCharcoalPaperTexture,
+ tipGenerator: generateConceptMatteChalkTip,
+ dualTipGenerator: generateMineralGrainDualTip,
+ paperTextureGenerator: generatePainterlyChalkGrainTexture,
settings: {
- size: 34,
- minSizeFactor: 0.32,
- flow: 0.85,
+ size: 44,
+ minSizeFactor: 0.26,
+ flow: 0.95,
opacity: 1.0,
- hardness: 0.72,
+ hardness: 0.88,
antiAlias: 2,
- thickness: 0.74,
- spacing: 0.065,
+ thickness: 0.56,
+ customTipAngle: -28,
+ customTipAngleDynamics: 'none',
+ customTipRotationRandomScale: 0,
+ flipH: 'none',
+ flipV: 'none',
+ spacing: 0.08,
+ adjustDensityByGap: false,
stabilization: 6,
- sharpCorners: false,
+ sharpCorners: true,
usePressure: true,
useTilt: true,
- tiltScale: 1.2,
+ tiltScale: 1.3,
smoothing: true,
- customTipAngleDynamics: 'direction-random',
- customTipRotationRandomScale: 0.18,
- flipH: 'random',
- flipV: 'random',
+ pressureCurve: [
+ [0, 0],
+ [0.24, 0.2],
+ [0.6, 0.76],
+ [1, 1],
+ ],
colorMixing: true,
perceptualMixing: true,
mixingMode: 'blend',
- amountOfPaint: 0.72,
- densityOfPaint: 0.86,
- colorStretch: 0.58,
- grain: 0.52,
- textureDensity: 0.52,
- paperTextureMode: 'multiply',
- paperTextureScale: 1.25,
- paperTextureContrast: 32,
- opacitySensor: { usePressure: true, pressureMin: 0.25 },
+ amountOfPaint: 0.86,
+ densityOfPaint: 0.95,
+ colorStretch: 0.38,
+ grain: 0.56,
+ textureDensity: 0.56,
+ paperTextureMode: 'compare',
+ paperTextureScale: 0.9,
+ paperTextureContrast: 24,
+ paperTextureBrightness: -2,
+ opacitySensor: { usePressure: true, pressureMin: 0.16 },
+ dualBrush: true,
+ dualBrushCompositeMode: 'multiply',
+ dualLinkSize: true,
+ dualScale: 1.15,
+ dualSpacing: 0.12,
+ dualDensity: 0.96,
+ dualAngleDynamics: 'random',
+ dualFlipH: 'random',
+ dualFlipV: 'random',
+ dualBrushConfig: {
+ enabled: true,
+ compositeMode: 'multiply',
+ linkSizeWithMain: true,
+ sizeRatio: 1.15,
+ spacing: 0.12,
+ density: 0.96,
+ angleDynamics: 'random',
+ flipH: 'random',
+ flipV: 'random',
+ },
dynamics: {
...DEFAULT_BRUSH_DYNAMICS,
- sizeJitter: 0.06,
- angleJitter: 0.12,
- flowJitter: 0.1,
+ sizeJitter: 0.02,
+ angleJitter: 0.015,
+ flowJitter: 0.05,
},
useGpu: true,
},
},
{
- id: 'blend-brush',
+ id: 'silky-portrait-round',
category: 'brush',
- name: 'Blend Brush',
+ name: 'Silky Portrait Round',
badge: 'Brush',
badgeBg: 'bg-emerald-500/15',
badgeText: 'text-emerald-300',
badgeBorder: 'border-emerald-500/30',
- desc: 'Pure Soft Color Blender — Smooths & Harmonizes Existing Paint',
+ desc: 'Creamy Organic Portrait Round — Luminous Skin Glazing, Rose Petals & Velvety Pigment Blend',
icon: 'paintbrush',
+ tipGenerator: generateSilkyPortraitRoundTip,
settings: {
- size: 36,
- minSizeFactor: 0.45,
- flow: 0.65,
+ size: 32,
+ minSizeFactor: 0.24,
+ flow: 0.82,
opacity: 1.0,
- hardness: 0.25,
+ hardness: 0.72,
antiAlias: 3,
- spacing: 0.06,
- stabilization: 8,
+ thickness: 0.92,
+ customTipAngleDynamics: 'none',
+ flipH: 'none',
+ flipV: 'none',
+ spacing: 0.055,
+ adjustDensityByGap: false,
+ stabilization: 9,
sharpCorners: false,
usePressure: true,
useTilt: false,
smoothing: true,
+ pressureCurve: [
+ [0, 0],
+ [0.28, 0.24],
+ [0.7, 0.76],
+ [1, 1],
+ ],
colorMixing: true,
perceptualMixing: true,
- mixingMode: 'smear',
- amountOfPaint: 0.0,
- densityOfPaint: 0.72,
- colorStretch: 0.74,
+ mixingMode: 'blend',
+ amountOfPaint: 0.62,
+ densityOfPaint: 0.84,
+ colorStretch: 0.62,
grain: 0,
textureDensity: 0,
- opacitySensor: { usePressure: true, pressureMin: 0.2 },
+ opacitySensor: { usePressure: true, pressureMin: 0.14 },
useGpu: true,
},
},
{
- id: 'blend-chalk-brush',
+ id: 'canvas-scumble-oil',
category: 'brush',
- name: 'Blend Chalk Brush',
+ name: 'Canvas Scumble / Old Master',
badge: 'Brush',
badgeBg: 'bg-emerald-500/15',
badgeText: 'text-emerald-300',
badgeBorder: 'border-emerald-500/30',
- desc: 'Textured Chalk Blender — Smudges Pigment While Preserving Gritty Tooth',
+ desc: 'Multi-Tip Dry-Oil Scumble — Broken-Color Tweed, Umber Grounds & Linen Peak Patina',
icon: 'paintbrush',
- tipGenerator: generateChalkPaintTip,
- paperTextureGenerator: generateCharcoalPaperTexture,
+ subTipGenerators: [
+ () => generateCanvasScumbleSubTip(0),
+ () => generateCanvasScumbleSubTip(1),
+ () => generateCanvasScumbleSubTip(2),
+ () => generateCanvasScumbleSubTip(3),
+ ],
+ paperTextureGenerator: () => getSurfaceTextureDataUrl('linen-canvas'),
settings: {
- size: 32,
- minSizeFactor: 0.4,
- flow: 0.72,
+ size: 52,
+ minSizeFactor: 0.34,
+ flow: 0.88,
opacity: 1.0,
- hardness: 0.55,
+ hardness: 0.76,
antiAlias: 2,
- thickness: 0.78,
- spacing: 0.065,
+ thickness: 0.84,
+ subTipOrder: 'random-no-repeat',
+ customTipAngleDynamics: 'random',
+ customTipRotationRandomScale: 0.65,
+ flipH: 'random',
+ flipV: 'random',
+ spacing: 0.11,
+ adjustDensityByGap: false,
stabilization: 6,
sharpCorners: false,
usePressure: true,
useTilt: true,
- tiltScale: 1.0,
+ tiltScale: 1.1,
smoothing: true,
- customTipAngleDynamics: 'random',
- flipH: 'random',
- flipV: 'random',
colorMixing: true,
perceptualMixing: true,
- mixingMode: 'smear',
- amountOfPaint: 0.0,
- densityOfPaint: 0.78,
- colorStretch: 0.68,
- grain: 0.55,
- textureDensity: 0.55,
- paperTextureMode: 'multiply',
- paperTextureScale: 1.25,
+ mixingMode: 'blend',
+ amountOfPaint: 0.76,
+ densityOfPaint: 0.88,
+ colorStretch: 0.46,
+ surfaceTextureId: 'linen-canvas',
+ paperTextureMode: 'compare',
+ grain: 0.66,
+ textureDensity: 0.66,
+ paperTextureScale: 0.92,
paperTextureContrast: 30,
- opacitySensor: { usePressure: true, pressureMin: 0.22 },
+ opacitySensor: { usePressure: true, pressureMin: 0.2 },
dynamics: {
...DEFAULT_BRUSH_DYNAMICS,
- angleJitter: 0.35,
+ sizeJitter: 0.12,
flowJitter: 0.14,
+ colorJitterEnabled: true,
+ temperatureJitter: 0.03,
},
useGpu: true,
},
},
{
- id: 'soft-round',
+ id: 'soft-glaze-airbrush',
category: 'brush',
- name: 'Soft Round',
+ name: 'Soft Glaze Airbrush',
badge: 'Brush',
badgeBg: 'bg-emerald-500/15',
badgeText: 'text-emerald-300',
badgeBorder: 'border-emerald-500/30',
- desc: 'Silky Airbrush Gradient — Cosine Soft Falloff & Pressure Opacity',
+ desc: 'Silky Zero-Banding Airbrush — Atmospheric Halation, Soft Shadow Glazes & Luminous Glow',
icon: 'paintbrush',
settings: {
- size: 48,
+ size: 64,
minSizeFactor: 0.55,
- flow: 0.35,
+ flow: 0.26,
opacity: 1.0,
hardness: 0.0,
antiAlias: 3,
- spacing: 0.06,
+ spacing: 0.055,
stabilization: 8,
sharpCorners: false,
usePressure: true,
@@ -749,30 +991,30 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
smoothing: true,
adjustDensityByGap: true,
pressureCurve: CSP_PRESSURE_CURVE_PRESETS.soft.points,
- opacitySensor: { usePressure: true, pressureMin: 0.08 },
+ opacitySensor: { usePressure: true, pressureMin: 0.06 },
useGpu: true,
},
},
{
- id: 'noise-shader',
+ id: 'atmospheric-grain-shader',
category: 'brush',
- name: 'Textured Grain / Noise Shader',
+ name: 'Atmospheric Grain Shader',
badge: 'Brush',
badgeBg: 'bg-emerald-500/15',
badgeText: 'text-emerald-300',
badgeBorder: 'border-emerald-500/30',
- desc: 'Stippled Film-Grain Atmospheric Shader for Organic Textured Gradients',
+ desc: 'Organic Mineral-Cloud Stipple — Dusty Skies, Painterly Film Grain & Textured Mist',
icon: 'paintbrush',
- tipGenerator: generateNoiseShaderTip,
- paperTextureGenerator: generateNoiseGrainTexture,
+ tipGenerator: generateAtmosphericGrainTip,
+ paperTextureGenerator: () => getSurfaceTextureDataUrl('stipple-grain'),
settings: {
- size: 56,
- minSizeFactor: 0.45,
- flow: 0.48,
+ size: 58,
+ minSizeFactor: 0.44,
+ flow: 0.42,
opacity: 1.0,
- hardness: 0.15,
+ hardness: 0.18,
antiAlias: 2,
- spacing: 0.11,
+ spacing: 0.1,
stabilization: 5,
sharpCorners: false,
usePressure: true,
@@ -783,25 +1025,362 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
customTipAngleDynamics: 'random',
flipH: 'random',
flipV: 'random',
- grain: 0.68,
- textureDensity: 0.68,
+ surfaceTextureId: 'stipple-grain',
+ grain: 0.54,
+ textureDensity: 0.54,
paperTextureMode: 'multiply',
paperTextureScale: 0.85,
- paperTextureContrast: 48,
+ paperTextureContrast: 24,
opacitySensor: { usePressure: true, pressureMin: 0.08 },
- densitySensor: { usePressure: true, pressureMin: 0.15 },
+ densitySensor: { usePressure: true, pressureMin: 0.16 },
dynamics: {
...DEFAULT_BRUSH_DYNAMICS,
- sizeJitter: 0.12,
+ sizeJitter: 0.1,
angleJitter: 1.0,
- flowJitter: 0.25,
- scatter: 0.14,
+ flowJitter: 0.18,
+ scatter: 0.1,
scatterBothAxes: true,
count: 1,
},
useGpu: true,
},
},
+ {
+ id: 'fine-detail-filbert',
+ category: 'brush',
+ name: 'Detail & Specular Liner',
+ badge: 'Brush',
+ badgeBg: 'bg-emerald-500/15',
+ badgeText: 'text-emerald-300',
+ badgeBorder: 'border-emerald-500/30',
+ desc: 'Springy Tapered Sable Detail Filbert — Crisp Gold Filigree, Eyelashes & Glowing Specular Glints',
+ icon: 'paintbrush',
+ tipGenerator: generateDetailFilbertTip,
+ settings: {
+ size: 10,
+ minSizeFactor: 0.1,
+ flow: 0.98,
+ opacity: 1.0,
+ hardness: 0.9,
+ antiAlias: 2,
+ thickness: 0.84,
+ customTipAngleDynamics: 'direction',
+ flipH: 'none',
+ flipV: 'none',
+ spacing: 0.045,
+ adjustDensityByGap: false,
+ stabilization: 11,
+ sharpCorners: true,
+ usePressure: true,
+ useTilt: false,
+ smoothing: true,
+ colorMixing: true,
+ perceptualMixing: true,
+ mixingMode: 'blend',
+ amountOfPaint: 0.94,
+ densityOfPaint: 0.98,
+ colorStretch: 0.2,
+ taper: {
+ useIn: false,
+ inLength: 0,
+ inRatio: 0,
+ useOut: true,
+ outLength: 16,
+ outRatio: 0.22,
+ inOutType: 2,
+ endingSharpness: 0.78,
+ affectSize: true,
+ minSizeRatio: 0.08,
+ },
+ useGpu: true,
+ },
+ },
+
+ // =========================================================================
+ // BLEND SECTION (DEDICATED PURE BLENDERS PAIRED TO EVERY PAINTING STYLE)
+ // =========================================================================
+ {
+ id: 'blend-velvet-soft',
+ category: 'blend',
+ name: 'Velvet Skin Blend',
+ badge: 'Blend',
+ badgeBg: 'bg-sky-500/15',
+ badgeText: 'text-sky-300',
+ badgeBorder: 'border-sky-500/30',
+ desc: 'Silky Optical Skin Blender — Soft CSP Blur Diffusion & Kubelka-Munk Tonal Harmony',
+ icon: 'droplets',
+ settings: {
+ size: 42,
+ minSizeFactor: 0.42,
+ flow: 0.72,
+ opacity: 1.0,
+ hardness: 0.22,
+ antiAlias: 3,
+ spacing: 0.08,
+ stabilization: 8,
+ sharpCorners: false,
+ usePressure: true,
+ useTilt: false,
+ smoothing: true,
+ colorMixing: true,
+ perceptualMixing: true,
+ mixingMode: 'smear',
+ amountOfPaint: 0.0,
+ densityOfPaint: 0.76,
+ colorStretch: 0.78,
+ useBlur: true,
+ blurStrength: 0.38,
+ grain: 0,
+ textureDensity: 0,
+ opacitySensor: { usePressure: true, pressureMin: 0.18 },
+ useGpu: true,
+ },
+ },
+ {
+ id: 'blend-oil-bristle',
+ category: 'blend',
+ name: 'Oil Bristle Smudge',
+ badge: 'Blend',
+ badgeBg: 'bg-sky-500/15',
+ badgeText: 'text-sky-300',
+ badgeBorder: 'border-sky-500/30',
+ desc: 'Directional Flat Bristle Smudger — Pulls & Blends Wet Oil While Keeping Brushwork Alive',
+ icon: 'droplets',
+ tipGenerator: generateBlendOilBristleTip,
+ paperTextureGenerator: () => getSurfaceTextureDataUrl('linen-canvas'),
+ settings: {
+ size: 44,
+ minSizeFactor: 0.36,
+ flow: 0.88,
+ opacity: 1.0,
+ hardness: 0.76,
+ antiAlias: 2,
+ thickness: 0.68,
+ customTipAngleDynamics: 'direction',
+ flipH: 'none',
+ flipV: 'none',
+ spacing: 0.048,
+ adjustDensityByGap: false,
+ stabilization: 8,
+ sharpCorners: false,
+ usePressure: true,
+ useTilt: true,
+ tiltScale: 1.15,
+ smoothing: true,
+ colorMixing: true,
+ perceptualMixing: true,
+ mixingMode: 'smear',
+ amountOfPaint: 0.0,
+ densityOfPaint: 0.9,
+ colorStretch: 0.88,
+ useBlur: false,
+ surfaceTextureId: 'linen-canvas',
+ paperTextureMode: 'multiply',
+ grain: 0.18,
+ textureDensity: 0.18,
+ paperTextureScale: 0.9,
+ paperTextureContrast: 10,
+ opacitySensor: { usePressure: true, pressureMin: 0.22 },
+ useGpu: true,
+ },
+ },
+ {
+ id: 'blend-matte-chalk',
+ category: 'blend',
+ name: 'Matte Chalk Blender',
+ badge: 'Blend',
+ badgeBg: 'bg-sky-500/15',
+ badgeText: 'text-sky-300',
+ badgeBorder: 'border-sky-500/30',
+ desc: 'Velvety Concept-Art Chalk Blender — Melts Hard Planes into Soft Matte Gradients with Tooth Intact',
+ icon: 'droplets',
+ tipGenerator: generateBlendMatteChalkTip,
+ paperTextureGenerator: generatePainterlyChalkGrainTexture,
+ settings: {
+ size: 48,
+ minSizeFactor: 0.36,
+ flow: 0.86,
+ opacity: 1.0,
+ hardness: 0.44,
+ antiAlias: 2,
+ thickness: 0.7,
+ customTipAngle: 0,
+ customTipAngleDynamics: 'direction',
+ customTipRotationRandomScale: 0,
+ flipH: 'none',
+ flipV: 'none',
+ spacing: 0.09,
+ adjustDensityByGap: false,
+ stabilization: 7,
+ sharpCorners: false,
+ usePressure: true,
+ useTilt: true,
+ tiltScale: 1.25,
+ smoothing: true,
+ pressureCurve: [
+ [0, 0],
+ [0.26, 0.24],
+ [0.64, 0.78],
+ [1, 1],
+ ],
+ colorMixing: true,
+ perceptualMixing: true,
+ mixingMode: 'smear',
+ amountOfPaint: 0.0,
+ densityOfPaint: 0.92,
+ colorStretch: 0.82,
+ useBlur: true,
+ blurStrength: 0.14,
+ grain: 0.54,
+ textureDensity: 0.54,
+ paperTextureMode: 'compare',
+ paperTextureScale: 0.94,
+ paperTextureContrast: 24,
+ paperTextureBrightness: -2,
+ opacitySensor: { usePressure: true, pressureMin: 0.16 },
+ dynamics: {
+ ...DEFAULT_BRUSH_DYNAMICS,
+ angleJitter: 0.025,
+ flowJitter: 0.06,
+ },
+ useGpu: true,
+ },
+ },
+ {
+ id: 'blend-rake-hair',
+ category: 'blend',
+ name: 'Rake Hair & Fur Smear',
+ badge: 'Blend',
+ badgeBg: 'bg-sky-500/15',
+ badgeText: 'text-sky-300',
+ badgeBorder: 'border-sky-500/30',
+ desc: 'Fine Multi-Strand Rake Blender — Pulls Wispy Hair, Mane, Fur & Feather Threads Across Edges',
+ icon: 'droplets',
+ tipGenerator: generateBlendRakeHairTip,
+ settings: {
+ size: 36,
+ minSizeFactor: 0.32,
+ flow: 0.92,
+ opacity: 1.0,
+ hardness: 0.82,
+ antiAlias: 2,
+ thickness: 0.82,
+ customTipAngleDynamics: 'direction',
+ flipH: 'none',
+ flipV: 'none',
+ spacing: 0.055,
+ adjustDensityByGap: false,
+ stabilization: 6,
+ sharpCorners: false,
+ usePressure: true,
+ useTilt: true,
+ tiltScale: 1.1,
+ smoothing: true,
+ colorMixing: true,
+ perceptualMixing: true,
+ mixingMode: 'smear',
+ amountOfPaint: 0.0,
+ densityOfPaint: 0.94,
+ colorStretch: 0.92,
+ useBlur: false,
+ grain: 0,
+ textureDensity: 0,
+ opacitySensor: { usePressure: true, pressureMin: 0.24 },
+ useGpu: true,
+ },
+ },
+ {
+ id: 'blend-canvas-scumble',
+ category: 'blend',
+ name: 'Canvas Scumble Melter',
+ badge: 'Blend',
+ badgeBg: 'bg-sky-500/15',
+ badgeText: 'text-sky-300',
+ badgeBorder: 'border-sky-500/30',
+ desc: 'Porous Dry-Bristle Scumble Blender — Dissolves Hard Edges Directly into Authentic Canvas Grain',
+ icon: 'droplets',
+ tipGenerator: generateBlendCanvasScumbleTip,
+ paperTextureGenerator: () => getSurfaceTextureDataUrl('linen-canvas'),
+ settings: {
+ size: 48,
+ minSizeFactor: 0.34,
+ flow: 0.84,
+ opacity: 1.0,
+ hardness: 0.56,
+ antiAlias: 2,
+ thickness: 0.86,
+ customTipAngleDynamics: 'direction-random',
+ customTipRotationRandomScale: 0.45,
+ flipH: 'random',
+ flipV: 'random',
+ spacing: 0.055,
+ adjustDensityByGap: false,
+ stabilization: 7,
+ sharpCorners: false,
+ usePressure: true,
+ useTilt: true,
+ tiltScale: 1.15,
+ smoothing: true,
+ colorMixing: true,
+ perceptualMixing: true,
+ mixingMode: 'smear',
+ amountOfPaint: 0.0,
+ densityOfPaint: 0.86,
+ colorStretch: 0.72,
+ useBlur: true,
+ blurStrength: 0.12,
+ surfaceTextureId: 'linen-canvas',
+ paperTextureMode: 'multiply',
+ grain: 0.42,
+ textureDensity: 0.42,
+ paperTextureScale: 0.9,
+ paperTextureContrast: 16,
+ opacitySensor: { usePressure: true, pressureMin: 0.18 },
+ useGpu: true,
+ },
+ },
+ {
+ id: 'blend-fingertip',
+ category: 'blend',
+ name: 'Wet Finger Tip',
+ badge: 'Blend',
+ badgeBg: 'bg-sky-500/15',
+ badgeText: 'text-sky-300',
+ badgeBorder: 'border-sky-500/30',
+ desc: 'CSP Finger Tip Smudger — Firm Directional Paint Pulling for Flowing Hair, Mist & Long Trails',
+ icon: 'droplets',
+ tipGenerator: generateBlendFingertipTip,
+ settings: {
+ size: 28,
+ minSizeFactor: 0.28,
+ flow: 0.94,
+ opacity: 1.0,
+ hardness: 0.56,
+ antiAlias: 2,
+ thickness: 0.86,
+ customTipAngleDynamics: 'direction',
+ flipH: 'none',
+ flipV: 'none',
+ spacing: 0.045,
+ adjustDensityByGap: false,
+ stabilization: 8,
+ sharpCorners: false,
+ usePressure: true,
+ useTilt: false,
+ smoothing: true,
+ colorMixing: true,
+ perceptualMixing: true,
+ mixingMode: 'smear',
+ amountOfPaint: 0.0,
+ densityOfPaint: 0.96,
+ colorStretch: 0.95,
+ useBlur: false,
+ grain: 0,
+ textureDensity: 0,
+ opacitySensor: { usePressure: true, pressureMin: 0.26 },
+ useGpu: true,
+ },
+ },
// =========================================================================
// NATURAL PAINT SECTION (Realistic Impasto, Bristle Ribbon & Pigment Mixing)
@@ -1491,6 +2070,16 @@ export function prewarmBuiltinBrushAssets(): void {
const url = def.tipGenerator();
if (url) getPreloadedBuiltinTipImage(url);
}
+ if (def.subTipGenerators && def.subTipGenerators.length > 0) {
+ for (let j = 0; j < def.subTipGenerators.length; j++) {
+ const url = def.subTipGenerators[j]();
+ if (url) getPreloadedBuiltinTipImage(url);
+ }
+ }
+ if (def.dualTipGenerator) {
+ const url = def.dualTipGenerator();
+ if (url) getPreloadedBuiltinTipImage(url);
+ }
if (def.paperTextureGenerator) {
const url = def.paperTextureGenerator();
if (url) getPreloadedBuiltinTipImage(url);
@@ -1524,6 +2113,41 @@ export function getBuiltinBrushConfig(presetId: BrushPresetId): Partial<BrushSet
}
}
+ let subTips: CspSubTip[] | undefined = undefined;
+ let subTipImages: HTMLImageElement[] | undefined = undefined;
+ if (def.subTipGenerators && def.subTipGenerators.length > 0) {
+ const stW = def.subTipDimensions?.width ?? 256;
+ const stH = def.subTipDimensions?.height ?? 256;
+ const builtSubTips: CspSubTip[] = [];
+ const builtImages: HTMLImageElement[] = [];
+ for (let i = 0; i < def.subTipGenerators.length; i++) {
+ const url = def.subTipGenerators[i]();
+ if (!url) continue;
+ builtSubTips.push({ dataUrl: url, width: stW, height: stH });
+ const img = getPreloadedBuiltinTipImage(url);
+ if (img) builtImages.push(img);
+ }
+ if (builtSubTips.length > 0) {
+ subTips = builtSubTips;
+ if (builtImages.length > 0) {
+ subTipImages = builtImages;
+ }
+ if (!tipDataUrl) {
+ tipDataUrl = builtSubTips[0].dataUrl;
+ tipImage = builtImages[0];
+ }
+ }
+ }
+
+ let dualTipDataUrl: string | undefined = undefined;
+ let dualTipImage: HTMLImageElement | undefined = undefined;
+ if (def.dualTipGenerator) {
+ dualTipDataUrl = def.dualTipGenerator();
+ if (dualTipDataUrl) {
+ dualTipImage = getPreloadedBuiltinTipImage(dualTipDataUrl);
+ }
+ }
+
let paperTexture: string | undefined = undefined;
let paperTextureImage: HTMLImageElement | undefined = undefined;
if (def.paperTextureGenerator) {
@@ -1533,13 +2157,26 @@ export function getBuiltinBrushConfig(presetId: BrushPresetId): Partial<BrushSet
}
}
+ const resolvedDualBrushConfig = def.settings.dualBrushConfig
+ ? {
+ ...def.settings.dualBrushConfig,
+ tipDataUrl: dualTipDataUrl ?? def.settings.dualBrushConfig.tipDataUrl,
+ tipImage: dualTipImage ?? def.settings.dualBrushConfig.tipImage,
+ }
+ : undefined;
+
return {
preset: def.id,
brushName: def.name,
customTipDataUrl: tipDataUrl,
customTipImage: tipImage,
+ subTips,
+ subTipImages,
+ dualTipDataUrl,
+ dualTipImage,
paperTexture,
paperTextureImage,
...def.settings,
+ ...(resolvedDualBrushConfig ? { dualBrushConfig: resolvedDualBrushConfig } : {}),
};
}
diff --git a/src/utils/proceduralBrushTips.ts b/src/utils/proceduralBrushTips.ts
index 6b65192..88a1c75 100644
--- a/src/utils/proceduralBrushTips.ts
+++ b/src/utils/proceduralBrushTips.ts
@@ -10,6 +10,7 @@
import type { BristleProfilePreset, SurfaceTextureId } from '../types/editor';
const TIP_SIZE = 128;
+const HI_TIP_SIZE = 256;
const PAPER_SIZE = 256;
export const SURFACE_TEXTURE_SIZE = 1024;
/** High-DPI texel density multiplier: 2x oversampled texels per document pixel at scale=1.0 */
@@ -141,25 +142,26 @@ function smoothstep(edge0: number, edge1: number, x: number): number {
}
/**
- * Helper: allocates an offscreen canvas, fills RGBA via callback, and returns a cached PNG data URL.
+ * Helper: allocates an offscreen rectangular canvas, fills RGBA via callback, and returns a cached PNG data URL.
*/
-function buildCachedPng(
+function buildCachedRectPng(
key: string,
- size: number,
- fill: (data: Uint8ClampedArray, size: number) => void
+ width: number,
+ height: number,
+ fill: (data: Uint8ClampedArray, width: number, height: number) => void
): string {
const hit = generatedCache.get(key);
if (hit !== undefined) return hit;
if (typeof document === 'undefined') return '';
const canvas = document.createElement('canvas');
- canvas.width = size;
- canvas.height = size;
+ canvas.width = width;
+ canvas.height = height;
const ctx = canvas.getContext('2d');
if (!ctx || typeof ctx.createImageData !== 'function') return '';
- const imgData = ctx.createImageData(size, size);
- fill(imgData.data, size);
+ const imgData = ctx.createImageData(width, height);
+ fill(imgData.data, width, height);
ctx.putImageData(imgData, 0, 0);
const url = typeof canvas.toDataURL === 'function' ? canvas.toDataURL('image/png') : '';
@@ -169,6 +171,36 @@ function buildCachedPng(
return url;
}
+/**
+ * Helper: allocates an offscreen square canvas, fills RGBA via callback, and returns a cached PNG data URL.
+ */
+function buildCachedPng(
+ key: string,
+ size: number,
+ fill: (data: Uint8ClampedArray, size: number) => void
+): string {
+ return buildCachedRectPng(key, size, size, (data, w) => fill(data, w));
+}
+
+function sampleFieldBilinear(field: Float32Array, fSize: number, u: number, v: number): number {
+ const mask = fSize - 1;
+ const fx = u * fSize;
+ const fy = v * fSize;
+ const x0 = Math.floor(fx);
+ const y0 = Math.floor(fy);
+ const tx = fx - x0;
+ const ty = fy - y0;
+ const ix0 = x0 & mask;
+ const iy0 = y0 & mask;
+ const ix1 = (ix0 + 1) & mask;
+ const iy1 = (iy0 + 1) & mask;
+ const r0 = iy0 * fSize;
+ const r1 = iy1 * fSize;
+ const top = field[r0 + ix0] + (field[r0 + ix1] - field[r0 + ix0]) * tx;
+ const bot = field[r1 + ix0] + (field[r1 + ix1] - field[r1 + ix0]) * tx;
+ return top + (bot - top) * ty;
+}
+
function writeAlphaPixel(data: Uint8ClampedArray, idx: number, alpha: number): void {
const a = Math.round(clamp01(alpha) * 255);
if (a <= 0) return;
@@ -183,43 +215,167 @@ function writeAlphaPixel(data: Uint8ClampedArray, idx: number, alpha: number): v
// -------------------------------------------------------------
/**
- * Real G-Pen: dense manga steel-nib core with subtle organic edge feathering & ink-on-Bristol micro-roughness.
+ * Real G-Pen (256x256, modeled directly on official CSP Real G-Pen.sut 107x133 MaterialFile):
+ * Jagged, porous organic steel-nib ink silhouette with rough ink-bleed perimeter teeth
+ * and 4 authentic internal white paper micro-pinholes (top-center, mid-left, mid-right, lower-center).
*/
export function generateRealGPenTip(): string {
- return buildCachedPng('tip:real-g-pen', TIP_SIZE, (data, size) => {
- const rand = createPrng(0x101a);
+ return buildCachedPng('tip:real-g-pen-csp-v2', HI_TIP_SIZE, (data, size) => {
+ const rand = createPrng(0x101a9);
+ const nCoarse = makePeriodicGrid(16, rand);
const nMed = makePeriodicGrid(32, rand);
const nFine = makePeriodicGrid(64, rand);
const half = size * 0.5;
- const baseR = half - 5;
+ // Matches CSP Real G-Pen's 107x133 (~0.805 aspect) slightly taller organic nib footprint
+ const rx = size * 0.375;
+ const ry = size * 0.455;
+
+ // 4 internal organic white paper micro-pinholes matching Real G-Pen.sut's decoded nib bitmap
+ const pinholes = [
+ { cx: -0.055, cy: -0.34, rx: 0.085, ry: 0.125, rot: -0.36 }, // elongated upper-center pore
+ { cx: -0.145, cy: -0.085, rx: 0.095, ry: 0.085, rot: 0.25 }, // mid-left rounded pore
+ { cx: 0.215, cy: -0.015, rx: 0.105, ry: 0.068, rot: -0.18 }, // mid-right horizontal oval pore
+ { cx: 0.045, cy: 0.195, rx: 0.092, ry: 0.098, rot: 0.48 }, // lower-center jagged pore
+ ];
for (let y = 0; y < size; y++) {
const dy = y - half + 0.5;
+ const ny = dy / ry;
const row = y * size * 4;
for (let x = 0; x < size; x++) {
const dx = x - half + 0.5;
- const dist = Math.hypot(dx, dy);
- const angle = Math.atan2(dy, dx);
+ const nx = dx / rx;
+ const dist = Math.hypot(nx, ny);
+ const angle = Math.atan2(ny, nx);
+
+ // Bold asymmetric jagged lobes + ink-bleed notches along silhouette (like real dip-pen nib on rough paper)
+ const lobes =
+ Math.sin(angle * 3 - 0.6) * 0.085 +
+ Math.cos(angle * 5 + 1.1) * 0.078 +
+ Math.sin(angle * 8 - 0.4) * 0.068 +
+ Math.cos(angle * 13 + 2.3) * 0.048 +
+ Math.sin(angle * 21 - 1.5) * 0.028;
+
+ // Characteristic lower-left and upper-left ink-bite indentations seen in CSP Real G-Pen
+ const biteLowerLeft =
+ Math.exp(-Math.pow((angle - 2.38) * 3.8, 2)) * 0.24 +
+ Math.exp(-Math.pow((angle + 1.85) * 4.5, 2)) * 0.14 +
+ Math.exp(-Math.pow((angle - 0.72) * 4.2, 2)) * 0.12;
+
+ const edgeWarp =
+ (samplePeriodic(nCoarse, 16, x * 0.075, y * 0.075) - 0.5) * 0.26 +
+ (samplePeriodic(nMed, 32, x * 0.17, y * 0.17) - 0.5) * 0.15 +
+ (samplePeriodic(nFine, 64, x * 0.38, y * 0.38) - 0.5) * 0.07;
+
+ const rNorm = dist / Math.max(0.25, 0.96 + lobes - biteLowerLeft + edgeWarp);
+ if (rNorm >= 1.03) continue;
- // Subtle organic nib wobble + Bristol fiber bleed along rim
- const angularWobble =
- Math.sin(angle * 5 + 0.7) * 0.022 +
- Math.cos(angle * 11 - 1.3) * 0.016 +
- Math.sin(angle * 19 + 2.1) * 0.011;
- const edgeNoise =
- (samplePeriodic(nMed, 32, x * 0.25, y * 0.25) - 0.5) * 0.09 +
- (samplePeriodic(nFine, 64, x * 0.5, y * 0.5) - 0.5) * 0.05;
+ // Crisp high-contrast ink edge (authentic dip-pen ink, zero soft airbrush blur)
+ let alpha = 1.0 - smoothstep(0.92, 1.015, rNorm);
+
+ // Carve the 4 jagged organic white paper pinholes inside the nib silhouette
+ for (let p = 0; p < pinholes.length; p++) {
+ const ph = pinholes[p];
+ const pdx = nx - ph.cx;
+ const pdy = ny - ph.cy;
+ const c = Math.cos(ph.rot);
+ const s = Math.sin(ph.rot);
+ const lx = (pdx * c + pdy * s) / ph.rx;
+ const ly = (-pdx * s + pdy * c) / ph.ry;
+ const pWarp =
+ (samplePeriodic(nMed, 32, x * 0.24 + p * 7.1, y * 0.24 + p * 3.7) - 0.5) * 0.34 +
+ (samplePeriodic(nFine, 64, x * 0.55 + p * 5.3, y * 0.55) - 0.5) * 0.14;
+ const pDist = Math.hypot(lx, ly) / Math.max(0.35, 1.0 + pWarp);
+ if (pDist < 1.04) {
+ alpha *= smoothstep(0.84, 1.02, pDist);
+ }
+ }
- const rNorm = dist / (baseR * (1.0 + angularWobble + edgeNoise));
- if (rNorm >= 1.04) continue;
+ if (alpha > 0.005) {
+ writeAlphaPixel(data, row + x * 4, alpha);
+ }
+ }
+ }
+ });
+}
- let alpha = 1.0 - smoothstep(0.84, 1.02, rNorm);
- // Micro-tooth only at the outermost ink rim
- if (rNorm > 0.76) {
- const rimTooth = samplePeriodic(nFine, 64, x * 0.75, y * 0.75);
- alpha *= 0.82 + rimTooth * 0.26;
+/**
+ * Rough Pen Seamless Vertical Ribbon Tip (64x512, modeled on official CSP Rough pen.sut MaterialFile):
+ * Vertical ink strand along Y (which RibbonBrushEngine maps strictly along the stroke path at angle=0°)
+ * with organic swells, pinches, and serrated dry-ink edges.
+ * Top (y=0) and bottom (y=H-1) join at matching centered anchor width for seamless repeat and flipH/flipV alternate tiling.
+ */
+export function generateRoughPenRibbonTip(variant: number = 0): string {
+ const vIdx = Math.max(0, Math.min(3, Math.floor(variant)));
+ return buildCachedRectPng(`tip:rough-pen-ribbon-v${vIdx}`, 64, 512, (data, width, height) => {
+ const rand = createPrng(0x31a07 + vIdx * 0x9e37);
+ const nEdgeL = makePeriodicGrid(64, rand);
+ const nEdgeR = makePeriodicGrid(64, rand);
+ const nMicro = makePeriodicGrid(64, rand);
+ const halfW = width * 0.5;
+ const baseHalfThick = width * 0.31; // Visible ink ~62% of tile width -> exact brush size at thickness=1.5
+
+ // Harmonic phases per variant; use cosine / sin(2*pi*k*v) so endpoints v=0 and v=1 match cleanly
+ const p1 = (vIdx * 1.37) % (Math.PI * 2);
+ const p2 = (vIdx * 2.51 + 0.8) % (Math.PI * 2);
+ const p3 = (vIdx * 3.19 + 1.6) % (Math.PI * 2);
+
+ for (let y = 0; y < height; y++) {
+ const v = y / height; // [0, 1) periodic along stroke length
+ const tau = v * Math.PI * 2;
+ // Smooth window that pins the very ends (v=0, v=1) to symmetric centered width so flipH/flipV alternate tiles join seamlessly
+ const seamEnvelope = Math.sin(v * Math.PI); // 0 at ends, 1 in middle
+ const env = Math.pow(seamEnvelope, 0.32);
+
+ // Organic thick/thin nib-pressure & tooth swells along the vertical strand
+ const swell =
+ (Math.sin(tau * 1 + p1) * 0.14 +
+ Math.sin(tau * 2 + p2) * 0.11 +
+ Math.sin(tau * 3 - p3) * 0.08 +
+ Math.sin(tau * 5 + p1 * 1.7) * 0.055) *
+ env;
+ const centerWander =
+ (Math.sin(tau * 1 + p2) * 0.085 + Math.sin(tau * 2 - p1) * 0.05) * width * env;
+
+ // High-frequency serrated rough-paper ink teeth along left and right edges (periodic in y)
+ const fyCoarse = v * 32;
+ const fyFine = v * 64;
+ const toothL =
+ ((samplePeriodic(nEdgeL, 64, 4.2, fyCoarse) - 0.5) * 0.34 +
+ (samplePeriodic(nEdgeL, 64, 19.7, fyFine) - 0.5) * 0.24 +
+ (samplePeriodic(nMicro, 64, 33.1, fyFine * 2.0) - 0.5) * 0.14) *
+ (0.35 + 0.65 * env);
+ const toothR =
+ ((samplePeriodic(nEdgeR, 64, 11.5, fyCoarse) - 0.5) * 0.34 +
+ (samplePeriodic(nEdgeR, 64, 27.3, fyFine) - 0.5) * 0.24 +
+ (samplePeriodic(nMicro, 64, 48.6, fyFine * 2.0) - 0.5) * 0.14) *
+ (0.35 + 0.65 * env);
+
+ const leftEdge = halfW + centerWander - baseHalfThick * Math.max(0.42, 1.0 + swell + toothL);
+ const rightEdge = halfW + centerWander + baseHalfThick * Math.max(0.42, 1.0 + swell + toothR);
+ const row = y * width * 4;
+
+ for (let x = 0; x < width; x++) {
+ const px = x + 0.5;
+ if (px < leftEdge - 2.0 || px > rightEdge + 2.0) continue;
+
+ const dLeft = px - leftEdge;
+ const dRight = rightEdge - px;
+ const dEdge = Math.min(dLeft, dRight);
+ // Crisp 1.1px rough-ink edge feather (matches CSP Rough pen AntiAlias=1 character)
+ let alpha = smoothstep(-0.55, 0.75, dEdge);
+
+ // Occasional tiny dry-ink notch right along the outer 2px rim
+ if (alpha > 0.01 && dEdge < 2.2) {
+ const rimPore = samplePeriodic(nMicro, 64, x * 0.72, fyFine * 2.0);
+ if (rimPore < 0.24 && dEdge < 1.25) {
+ alpha *= smoothstep(0.08, 0.24, rimPore);
+ }
+ }
+
+ if (alpha > 0.005) {
+ writeAlphaPixel(data, row + x * 4, alpha);
}
- writeAlphaPixel(data, row + x * 4, alpha);
}
}
});
@@ -535,11 +691,836 @@ export function generateChalkTip(): string {
}
// -------------------------------------------------------------
-// BRUSH SECTION TIPS (COLORING & PAINTING)
+// BRUSH & BLEND SECTION TIPS (256x256 HIGH-RES PAINTERLY MEDIA)
// -------------------------------------------------------------
/**
- * Oil Painting Brush: oval natural hog-bristle bundle (~52 soft individual bristles with organic gaps).
+ * Alla-Prima Oil Flat (256x256):
+ * Asymmetric flat/square hog-bristle brush head engineered for effortless lost-and-found edges:
+ * - Leading edge (ny < 0): razor-crisp architectural ferrule plane for eyes, jawlines & folds
+ * - Trailing edge (ny > 0): softly feathered dry-bristle tufts with fine organic bristle teeth
+ */
+export function generateOilFlatAllaPrimaTip(): string {
+ return buildCachedPng('tip:oil-flat-alla-prima-256', HI_TIP_SIZE, (data, size) => {
+ const rand = createPrng(0x81a1f);
+ const nCoarse = makePeriodicGrid(16, rand);
+ const nMed = makePeriodicGrid(32, rand);
+ const nFine = makePeriodicGrid(64, rand);
+ const half = size * 0.5;
+ const rx = size * 0.44;
+ const ry = size * 0.34;
+
+ // 44 organic hog-bristle fibers running along the flat head width for tactile ridges & trailing notches
+ const numFibers = 44;
+ const fiberX = new Float32Array(numFibers);
+ const fiberW = new Float32Array(numFibers);
+ const fiberLen = new Float32Array(numFibers);
+ const fiberAmp = new Float32Array(numFibers);
+ for (let i = 0; i < numFibers; i++) {
+ const u = (i + 0.5) / numFibers;
+ fiberX[i] = half - rx + u * (rx * 2) + (rand() - 0.5) * 3.8;
+ fiberW[i] = 2.4 + rand() * 3.8;
+ // Shorter outer fibers & uneven trailing bristle tips create natural lost edges
+ const edgeU = Math.abs(u * 2 - 1);
+ fiberLen[i] = (0.72 + rand() * 0.38) * (1.0 - edgeU * edgeU * 0.22);
+ fiberAmp[i] = 0.62 + rand() * 0.38;
+ }
+
+ for (let y = 0; y < size; y++) {
+ const dy = y - half + 0.5;
+ const ySigned = dy / ry; // -1 = crisp leading edge, +1 = feathered dry-bristle trailing edge
+ const trail = clamp01((ySigned + 0.05) / 1.05); // 0 on leading half, ramps to 1 on trailing half
+ const row = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ const dx = x - half + 0.5;
+ const warp =
+ (samplePeriodic(nCoarse, 16, x * 0.06, y * 0.06) - 0.5) * (0.045 + trail * 0.14) +
+ (samplePeriodic(nMed, 32, x * 0.18, y * 0.18) - 0.5) * (0.025 + trail * 0.08);
+
+ const nx = Math.abs(dx) / (rx * (1.0 + warp));
+ const ny = Math.abs(dy) / (ry * (1.0 + warp * 0.8));
+ // Architectural flat square bristle head (superellipse p = 4.6)
+ const d = Math.pow(Math.pow(nx, 4.6) + Math.pow(ny, 4.6), 1 / 4.6);
+ if (d >= 1.08) continue;
+
+ // Crisp leading edge (sharp 0.90..1.00), softly feathered trailing edge (0.58..1.04)
+ const edgeStart = 0.91 - trail * 0.33;
+ const edgeEnd = 1.005 + trail * 0.05;
+ const bodyEnv = 1.0 - smoothstep(edgeStart, edgeEnd, d);
+
+ // Evaluate bristle striations & trailing bristle teeth
+ let bristleVal = 0;
+ let maxTailReach = 0.72;
+ for (let f = 0; f < numFibers; f++) {
+ const distX = Math.abs(x - fiberX[f]) / fiberW[f];
+ if (distX < 1.0) {
+ const v = (1.0 - distX * distX) * fiberAmp[f];
+ if (v > bristleVal) {
+ bristleVal = v;
+ maxTailReach = fiberLen[f];
+ }
+ }
+ }
+
+ const fineStreak = samplePeriodic(nFine, 64, x * 0.42, y * 0.14);
+ let alpha: number;
+ if (trail < 0.08) {
+ // Leading architectural plane: crisp opaque edge with subtle oil-bristle tooth
+ const tooth = 0.86 + 0.14 * (bristleVal * 0.65 + fineStreak * 0.35);
+ alpha = bodyEnv * tooth;
+ } else {
+ // Trailing half transitions smoothly into individual separated hog bristles
+ const tailCut = 1.0 - smoothstep(maxTailReach * 0.72, maxTailReach * 1.06, ySigned);
+ const fiberMask = smoothstep(0.10 + trail * 0.28, 0.58 + trail * 0.24, bristleVal * 0.72 + fineStreak * 0.28);
+ const coreBridge = (1.0 - trail) * 0.92;
+ alpha = bodyEnv * Math.max(coreBridge, fiberMask * tailCut * (0.78 + 0.22 * fineStreak));
+ }
+
+ if (alpha > 0.004) {
+ writeAlphaPixel(data, row + x * 4, clamp01(alpha * 1.06));
+ }
+ }
+ }
+ });
+}
+
+/**
+ * Loaded Impasto Oil Filbert (256x256):
+ * Chiseled multi-tuft hog-bristle filbert with ~36 bold clumped bristle ridges aligned along X
+ * (so directional angle dynamics drag lush parallel impasto oil ridges along curves).
+ */
+export function generateImpastoFilbertTip(): string {
+ return buildCachedPng('tip:thick-oil-impasto-256', HI_TIP_SIZE, (data, size) => {
+ const rand = createPrng(0x9093c);
+ const half = size * 0.5;
+ const rx = size * 0.44;
+ const ry = size * 0.35;
+
+ // 10 organic clump attractors + 38 individual hog bristles grouped into bold painterly tufts
+ const numClumps = 10;
+ const clumpY = new Float32Array(numClumps);
+ for (let c = 0; c < numClumps; c++) {
+ clumpY[c] = half - ry * 0.92 + ((c + 0.5) / numClumps) * (ry * 1.84) + (rand() - 0.5) * 6.0;
+ }
+
+ const numRidges = 38;
+ const ridgeCenters = new Float32Array(numRidges);
+ const ridgeWidths = new Float32Array(numRidges);
+ const ridgePower = new Float32Array(numRidges);
+ const ridgeReach = new Float32Array(numRidges);
+ for (let i = 0; i < numRidges; i++) {
+ const u = (i + 0.5) / numRidges;
+ const rawY = half - ry + u * (ry * 2);
+ // Pull slightly toward nearest clump center
+ let bestC = rawY;
+ let bestD = 9999;
+ for (let c = 0; c < numClumps; c++) {
+ const d = Math.abs(rawY - clumpY[c]);
+ if (d < bestD) {
+ bestD = d;
+ bestC = clumpY[c];
+ }
+ }
+ ridgeCenters[i] = rawY + (bestC - rawY) * 0.36 + (rand() - 0.5) * 3.2;
+ ridgeWidths[i] = 3.2 + rand() * 5.2;
+ ridgePower[i] = 0.54 + rand() * 0.46;
+ ridgeReach[i] = 0.80 + rand() * 0.24;
+ }
+
+ const nMed = makePeriodicGrid(32, rand);
+ const nFine = makePeriodicGrid(64, rand);
+ for (let y = 0; y < size; y++) {
+ const dy = y - half + 0.5;
+ const row = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ const dx = x - half + 0.5;
+ const nx = Math.abs(dx) / rx;
+ const ny = Math.abs(dy) / ry;
+ // Rounded filbert profile (superellipse p = 2.8)
+ const d = Math.pow(Math.pow(nx, 2.8) + Math.pow(ny, 2.8), 1 / 2.8);
+ if (d >= 1.07) continue;
+
+ let ridgeVal = 0;
+ let localReach = 0.92;
+ for (let r = 0; r < numRidges; r++) {
+ const distY = Math.abs(y - ridgeCenters[r]) / ridgeWidths[r];
+ if (distY < 1.0) {
+ const v = (1.0 - distY * distY) * ridgePower[r];
+ if (v > ridgeVal) {
+ ridgeVal = v;
+ localReach = ridgeReach[r];
+ }
+ }
+ }
+
+ const tipNoise = samplePeriodic(nMed, 32, x * 0.08, y * 0.28);
+ const fineGrain = samplePeriodic(nFine, 64, x * 0.18, y * 0.55);
+ const edgeMask = 1.0 - smoothstep(localReach * 0.78 - tipNoise * 0.14, localReach * 1.04, d);
+ const body = 0.38 + 0.62 * (ridgeVal * 0.82 + fineGrain * 0.18);
+ const alpha = clamp01(body * edgeMask * 1.16);
+ if (alpha > 0.004) {
+ writeAlphaPixel(data, row + x * 4, alpha);
+ }
+ }
+ }
+ });
+}
+
+/**
+ * Dry Bristle Rake (256x256):
+ * Organic multi-tuft separated bristle rake with irregular varied-width bristle clusters,
+ * delicate stray outer hairs, and genuine airy transparent gaps between tufts (NOT uniform comb teeth).
+ * Oriented along X so `customTipAngleDynamics: 'direction'` pulls expressive dry scratches & highlights.
+ */
+export function generateDryBristleRakePaintTip(): string {
+ return buildCachedPng('tip:dry-bristle-rake-paint-256', HI_TIP_SIZE, (data, size) => {
+ const rand = createPrng(0x9a4e7);
+ const half = size * 0.5;
+ const rx = size * 0.44;
+ const ry = size * 0.43;
+ const nFine = makePeriodicGrid(64, rand);
+
+ // 18 organic varied bristle tufts (mix of chunky 3-hair clumps + fine isolated stray bristles)
+ interface RakeTuft {
+ cy: number;
+ ry: number;
+ rx: number;
+ cx: number;
+ strength: number;
+ }
+ const tufts: RakeTuft[] = [];
+ // Deliberately irregular spacing & grouping across the vertical brush height
+ const anchors = [
+ -0.91, -0.82, -0.69, -0.62, -0.49, -0.37, -0.31, -0.19, -0.08,
+ 0.02, 0.14, 0.21, 0.34, 0.46, 0.54, 0.68, 0.79, 0.90,
+ ];
+ for (let i = 0; i < anchors.length; i++) {
+ const u = anchors[i] + (rand() - 0.5) * 0.035;
+ const absU = Math.abs(u);
+ const isStrayHair = i === 0 || i === 3 || i === 6 || i === 11 || i === 14 || i === 17;
+ const arch = Math.sqrt(Math.max(0.28, 1.0 - absU * absU * 0.52));
+ const tRy = isStrayHair ? 2.2 + rand() * 2.2 : 4.2 + rand() * 5.2;
+ const tRx = rx * (0.62 + rand() * 0.36) * arch;
+ const tCx = half + (rand() - 0.5) * rx * 0.24;
+ const tCy = half + u * ry;
+ tufts.push({
+ cx: tCx,
+ cy: tCy,
+ rx: tRx,
+ ry: tRy,
+ strength: isStrayHair ? 0.65 + rand() * 0.30 : 0.80 + rand() * 0.20,
+ });
+ // Add secondary sub-bristle tucked beside major tufts for authentic clumped hog-hair feel
+ if (!isStrayHair && rand() > 0.35) {
+ tufts.push({
+ cx: tCx + (rand() - 0.5) * 14,
+ cy: tCy + (rand() > 0.5 ? 1 : -1) * (tRy * 0.85 + 1.5),
+ rx: tRx * (0.68 + rand() * 0.24),
+ ry: 1.8 + rand() * 2.2,
+ strength: 0.55 + rand() * 0.35,
+ });
+ }
+ }
+
+ for (let y = 0; y < size; y++) {
+ const row = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ let accum = 0;
+ for (let i = 0; i < tufts.length; i++) {
+ const t = tufts[i];
+ const dy = Math.abs(y - t.cy);
+ if (dy > t.ry * 1.15) continue;
+ const dx = Math.abs(x - t.cx);
+ if (dx > t.rx * 1.1) continue;
+ const nx = dx / t.rx;
+ const ny = dy / t.ry;
+ const d = Math.pow(nx * nx * nx + ny * ny * ny, 1 / 3);
+ if (d < 1.0) {
+ const v = (1.0 - smoothstep(0.45, 1.0, d)) * t.strength;
+ if (v > accum) accum = v;
+ }
+ }
+ if (accum > 0.01) {
+ const dryTooth = 0.78 + 0.22 * samplePeriodic(nFine, 64, x * 0.22, y * 0.65);
+ writeAlphaPixel(data, row + x * 4, clamp01(accum * dryTooth));
+ }
+ }
+ }
+ });
+}
+
+/**
+ * Concept Matte Chalk / Gouache Tip (256x256):
+ * Upgraded high-res hand-chipped flat rectangular chalk/gouache block with a razor-crisp
+ * architectural leading chisel edge, dense creamy matte core, and subtle chipped mineral trailing edge.
+ */
+export function generateConceptMatteChalkTip(): string {
+ return buildCachedPng('tip:concept-matte-chalk-256', HI_TIP_SIZE, (data, size) => {
+ const rand = createPrng(0xa4c89);
+ const nCoarse = makePeriodicGrid(16, rand);
+ const nMed = makePeriodicGrid(32, rand);
+ const nFine = makePeriodicGrid(64, rand);
+ const domes = makeCellularDomeField(128, 44, rand);
+ const half = size * 0.5;
+ const rx = size * 0.45;
+ const ry = size * 0.38;
+
+ const flecks: Array<{ x: number; y: number; r: number; a: number }> = [];
+ for (let i = 0; i < 18; i++) {
+ const fx = half + (rand() * 2 - 1) * rx * 0.92;
+ const fy = half + ry * (0.91 + rand() * 0.14);
+ flecks.push({
+ x: fx,
+ y: fy,
+ r: 1.2 + rand() * 2.0,
+ a: 0.20 + rand() * 0.34,
+ });
+ }
+
+ const invSize = 1 / size;
+ for (let y = 0; y < size; y++) {
+ const dy = y - half + 0.5;
+ const ySigned = dy / ry;
+ const trailFactor = clamp01((ySigned + 0.15) * 0.8);
+ const row = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ const dx = x - half + 0.5;
+ const edgeRough = 0.058 + trailFactor * 0.095;
+ const warp =
+ (samplePeriodic(nCoarse, 16, x * 0.07, y * 0.07) - 0.5) * edgeRough * 1.35 +
+ (samplePeriodic(nMed, 32, x * 0.17, y * 0.17) - 0.5) * edgeRough * 0.75;
+
+ const nx = Math.abs(dx) / (rx * (1.0 + warp));
+ const ny = Math.abs(dy) / (ry * (1.0 + warp * 0.85));
+ const d = Math.pow(Math.pow(nx, 5.0) + Math.pow(ny, 5.0), 1 / 5.0);
+
+ let alpha = 0;
+ if (d < 1.04) {
+ const edgeStart = 0.89 - trailFactor * 0.15;
+ const edgeEnd = 1.01 + trailFactor * 0.025;
+ const env = 1.0 - smoothstep(edgeStart, edgeEnd, d);
+
+ const dome = sampleFieldBilinear(domes, 128, x * invSize, y * invSize);
+ const dragStreak = samplePeriodic(nMed, 32, x * 0.045, y * 0.28);
+ const finePowder = samplePeriodic(nFine, 64, x * 0.38, y * 0.38);
+ const mineral = dome * 0.36 + dragStreak * 0.34 + finePowder * 0.22 + rand() * 0.08;
+
+ const rimDryness = smoothstep(0.58, 1.0, d) * 0.30 + trailFactor * 0.11;
+ const cutLow = 0.05 + rimDryness;
+ const chalkBody = smoothstep(cutLow, cutLow + 0.25, mineral);
+ const coreFloor = (1.0 - smoothstep(0.70, 0.97, d)) * (0.92 - trailFactor * 0.20);
+ alpha = env * Math.max(coreFloor, chalkBody * (0.88 + 0.12 * dragStreak));
+ }
+
+ for (let f = 0; f < flecks.length; f++) {
+ const fl = flecks[f];
+ const fdx = x - fl.x;
+ const fdy = y - fl.y;
+ if (Math.abs(fdx) > 5.0 || Math.abs(fdy) > 5.0) continue;
+ const fd = Math.hypot(fdx, fdy) / fl.r;
+ if (fd < 1.0) {
+ const fa = (1.0 - smoothstep(0.25, 1.0, fd)) * fl.a;
+ if (fa > alpha) alpha = fa;
+ }
+ }
+
+ if (alpha > 0.004) {
+ writeAlphaPixel(data, row + x * 4, alpha);
+ }
+ }
+ }
+ });
+}
+
+/**
+ * Mineral Grain Dual Brush Tip (256x256):
+ * Isotropic porous mineral chalk/gouache modulation mask designed for Dual Brush `multiply`
+ * blending — injects velvety matte non-repeating tooth into sculptural concept-art strokes
+ * without weakening core opacity.
+ */
+export function generateMineralGrainDualTip(): string {
+ return buildCachedPng('tip:mineral-grain-dual-256', HI_TIP_SIZE, (data, size) => {
+ const rand = createPrng(0xcd773);
+ const domes = makeCellularDomeField(128, 38, rand);
+ const nFine = makePeriodicGrid(64, rand);
+ const half = size * 0.5;
+ const rad = size * 0.48;
+ const invSize = 1 / size;
+
+ for (let y = 0; y < size; y++) {
+ const dy = y - half + 0.5;
+ const row = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ const dx = x - half + 0.5;
+ const rNorm = Math.hypot(dx, dy) / rad;
+ if (rNorm >= 1.0) continue;
+
+ const env = 1.0 - smoothstep(0.76, 1.0, rNorm);
+ const dome = sampleFieldBilinear(domes, 128, x * invSize, y * invSize);
+ const fine = samplePeriodic(nFine, 64, x * 0.42, y * 0.42);
+ const mineral = dome * 0.58 + fine * 0.30 + rand() * 0.12;
+ // High baseline density (~0.45..1.0) with crisp micro-pores so multiply stays rich & velvety
+ const tooth = 0.38 + 0.62 * smoothstep(0.18, 0.72, mineral);
+ writeAlphaPixel(data, row + x * 4, env * tooth);
+ }
+ }
+ });
+}
+
+/**
+ * Silky Portrait Round (256x256):
+ * Subtly organic soft-core oval inspired by CSP Dense/Smooth Watercolor and pro portrait rounds:
+ * lush creamy interior with gentle cosine edge (hardness ~0.72) and ultra-delicate rim micro-tooth
+ * so skin, rose petals, and luminous rendering never look sterile or plastic.
+ */
+export function generateSilkyPortraitRoundTip(): string {
+ return buildCachedPng('tip:silky-portrait-round-256', HI_TIP_SIZE, (data, size) => {
+ const rand = createPrng(0x51a72);
+ const nMed = makePeriodicGrid(32, rand);
+ const nFine = makePeriodicGrid(64, rand);
+ const half = size * 0.5;
+ const rx = size * 0.46;
+ const ry = size * 0.43;
+
+ for (let y = 0; y < size; y++) {
+ const dy = y - half + 0.5;
+ const row = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ const dx = x - half + 0.5;
+ const warp = (samplePeriodic(nMed, 32, x * 0.08, y * 0.08) - 0.5) * 0.065;
+ const rNorm = Math.hypot(dx / (rx * (1.0 + warp)), dy / (ry * (1.0 + warp)));
+ if (rNorm >= 1.0) continue;
+
+ // Lush solid core up to 0.56, then silky smooth cosine roll-off to 1.0
+ let alpha = 1.0;
+ if (rNorm > 0.56) {
+ const t = (rNorm - 0.56) / 0.44;
+ alpha = 0.5 * (1.0 + Math.cos(t * Math.PI));
+ }
+ // Ultra-delicate painterly rim micro-tooth ONLY along the outer falloff (core remains silky smooth)
+ if (rNorm > 0.62) {
+ const rimFactor = smoothstep(0.62, 0.96, rNorm);
+ const fine = samplePeriodic(nFine, 64, x * 0.34, y * 0.34);
+ alpha *= 1.0 - rimFactor * 0.16 * (1.0 - fine);
+ }
+ if (alpha > 0.004) {
+ writeAlphaPixel(data, row + x * 4, alpha);
+ }
+ }
+ }
+ });
+}
+
+/**
+ * Canvas Scumble / Old Master Multi-Tip Variants (256x256 x 4):
+ * Irregular fractured dry-oil hog-bristle daubs with broken paint islands & porous pockets
+ * for Sargent/Old Master broken-color tweed, umber grounds, and canvas patina.
+ */
+export function generateCanvasScumbleSubTip(variant: number = 0): string {
+ const vIdx = ((Math.floor(variant) % 4) + 4) % 4;
+ return buildCachedPng(`tip:canvas-scumble-256-v${vIdx}`, HI_TIP_SIZE, (data, size) => {
+ const rand = createPrng(0x6c0b1 + vIdx * 0x4f1bb);
+ const nCoarse = makePeriodicGrid(16, rand);
+ const nMed = makePeriodicGrid(32, rand);
+ const nFine = makePeriodicGrid(64, rand);
+ const domes = makeCellularDomeField(128, 28 + vIdx * 3, rand);
+ const half = size * 0.5;
+ const rx = size * (0.42 + (vIdx % 2) * 0.03);
+ const ry = size * (0.37 + ((vIdx + 1) % 2) * 0.04);
+ const invSize = 1 / size;
+
+ // 4-6 organic dry-bristle sub-blobs per variant to break up circular symmetry completely
+ const blobs: Array<{ x: number; y: number; rx: number; ry: number; rot: number; w: number }> = [];
+ for (let i = 0; i < 6; i++) {
+ const th = (i / 6) * Math.PI * 2 + rand() * 0.9;
+ const dist = (0.12 + rand() * 0.34) * rx;
+ blobs.push({
+ x: half + Math.cos(th) * dist,
+ y: half + Math.sin(th) * dist * 0.85,
+ rx: rx * (0.36 + rand() * 0.32),
+ ry: ry * (0.34 + rand() * 0.30),
+ rot: rand() * Math.PI,
+ w: 0.65 + rand() * 0.35,
+ });
+ }
+
+ for (let y = 0; y < size; y++) {
+ const row = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ let shape = 0;
+ for (let b = 0; b < blobs.length; b++) {
+ const bl = blobs[b];
+ const bdx = x - bl.x;
+ const bdy = y - bl.y;
+ const c = Math.cos(bl.rot);
+ const s = Math.sin(bl.rot);
+ const lx = (bdx * c + bdy * s) / bl.rx;
+ const ly = (-bdx * s + bdy * c) / bl.ry;
+ const d = Math.hypot(lx, ly);
+ if (d < 1.05) {
+ const v = (1.0 - smoothstep(0.42, 1.03, d)) * bl.w;
+ if (v > shape) shape = v;
+ }
+ }
+ if (shape <= 0.01) continue;
+
+ const coarse = samplePeriodic(nCoarse, 16, x * 0.065, y * 0.065);
+ const med = samplePeriodic(nMed, 32, x * 0.16, y * 0.16);
+ const fine = samplePeriodic(nFine, 64, x * 0.36, y * 0.36);
+ const dome = sampleFieldBilinear(domes, 128, x * invSize, y * invSize);
+ const scumbleField = dome * 0.38 + coarse * 0.24 + med * 0.24 + fine * 0.14;
+
+ // Dry broken-oil paint islands: patchy pockets throughout, feathering into open speckles near edge
+ const cutLow = 0.20 + (1.0 - shape) * 0.44;
+ const paintIsland = smoothstep(cutLow, cutLow + 0.26, scumbleField);
+ const alpha = shape * paintIsland;
+ if (alpha > 0.005) {
+ writeAlphaPixel(data, row + x * 4, alpha);
+ }
+ }
+ }
+ });
+}
+
+/**
+ * Atmospheric Grain Shader Tip (256x256):
+ * Silky cosine-feathered mineral-cloud stipple tip (organic cellular micro-clusters + fine film grain,
+ * zero harsh digital white-noise static) for dusty skies, misty backgrounds, and painterly atmosphere.
+ */
+export function generateAtmosphericGrainTip(): string {
+ return buildCachedPng('tip:atmospheric-grain-256', HI_TIP_SIZE, (data, size) => {
+ const rand = createPrng(0xb0b5e);
+ const nMed = makePeriodicGrid(32, rand);
+ const nFine = makePeriodicGrid(64, rand);
+ const domes = makeCellularDomeField(128, 52, rand);
+ const half = size * 0.5;
+ const radius = half - 4;
+ const invSize = 1 / size;
+
+ for (let y = 0; y < size; y++) {
+ const dy = y - half + 0.5;
+ const row = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ const dx = x - half + 0.5;
+ const rNorm = Math.hypot(dx, dy) / radius;
+ if (rNorm >= 1.0) continue;
+
+ const env = Math.pow(0.5 * (1.0 + Math.cos(rNorm * Math.PI)), 1.35);
+ const dome = sampleFieldBilinear(domes, 128, x * invSize, y * invSize);
+ const cloud = samplePeriodic(nMed, 32, x * 0.11, y * 0.11);
+ const fine = samplePeriodic(nFine, 64, x * 0.45, y * 0.45);
+ // Organic mineral mist: blended cellular domes + soft cloud modulation (no raw pixel static!)
+ const organicGrain = dome * 0.48 + fine * 0.34 + cloud * 0.18;
+ const stipple = smoothstep(0.46 - env * 0.34, 0.80 - env * 0.22, organicGrain);
+ const alpha = env * (0.28 + 0.72 * stipple);
+ if (alpha > 0.004) {
+ writeAlphaPixel(data, row + x * 4, alpha);
+ }
+ }
+ }
+ });
+}
+
+/**
+ * Detail & Specular Liner Filbert Tip (256x256):
+ * Compact springy tapered sable detail filbert — crisp opaque core for gold filigree,
+ * eyelashes, tear glints, and luminous water droplets over blended paint.
+ */
+export function generateDetailFilbertTip(): string {
+ return buildCachedPng('tip:fine-detail-filbert-256', HI_TIP_SIZE, (data, size) => {
+ const rand = createPrng(0x7d3a1);
+ const nFine = makePeriodicGrid(64, rand);
+ const half = size * 0.5;
+ const rx = size * 0.45;
+ const ry = size * 0.37;
+
+ for (let y = 0; y < size; y++) {
+ const dy = y - half + 0.5;
+ const row = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ const dx = x - half + 0.5;
+ const nx = dx / rx;
+ // Slight pointed sable-liner taper toward +X tip
+ const taper = 1.0 - Math.max(0, nx) * 0.18;
+ const ny = dy / (ry * Math.max(0.45, taper));
+ const d = Math.hypot(nx, ny);
+ if (d >= 1.02) continue;
+
+ let alpha = 1.0 - smoothstep(0.84, 1.01, d);
+ if (d > 0.78) {
+ const fine = samplePeriodic(nFine, 64, x * 0.32, y * 0.32);
+ alpha *= 0.90 + 0.10 * fine;
+ }
+ if (alpha > 0.004) {
+ writeAlphaPixel(data, row + x * 4, alpha);
+ }
+ }
+ }
+ });
+}
+
+/**
+ * Oil Bristle Smudge Blender Tip (256x256):
+ * Directional flat multi-bristle oil smudger (~34 soft-tipped parallel hog bristles aligned along X)
+ * that blends & pulls wet oil paint while keeping lively brushwork alive.
+ */
+export function generateBlendOilBristleTip(): string {
+ return buildCachedPng('tip:blend-oil-bristle-256', HI_TIP_SIZE, (data, size) => {
+ const rand = createPrng(0xd10b3);
+ const half = size * 0.5;
+ const rx = size * 0.45;
+ const ry = size * 0.36;
+ const nFine = makePeriodicGrid(64, rand);
+
+ const numBristles = 34;
+ const bY = new Float32Array(numBristles);
+ const bW = new Float32Array(numBristles);
+ const bStr = new Float32Array(numBristles);
+ const bLen = new Float32Array(numBristles);
+ for (let i = 0; i < numBristles; i++) {
+ const u = (i + 0.5) / numBristles;
+ const signedU = u * 2 - 1;
+ bY[i] = half + signedU * ry * 0.94 + (rand() - 0.5) * 3.0;
+ bW[i] = 3.2 + rand() * 4.4;
+ bStr[i] = 0.58 + rand() * 0.42;
+ bLen[i] = (0.76 + rand() * 0.24) * Math.sqrt(Math.max(0.35, 1.0 - signedU * signedU * 0.45));
+ }
+
+ for (let y = 0; y < size; y++) {
+ const dy = y - half + 0.5;
+ const row = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ const dx = x - half + 0.5;
+ const nx = Math.abs(dx) / rx;
+ const ny = Math.abs(dy) / ry;
+ const d = Math.pow(Math.pow(nx, 2.4) + Math.pow(ny, 2.4), 1 / 2.4);
+ if (d >= 1.04) continue;
+
+ let bristle = 0;
+ let reach = 0.85;
+ for (let i = 0; i < numBristles; i++) {
+ const distY = Math.abs(y - bY[i]) / bW[i];
+ if (distY < 1.0) {
+ const v = (1.0 - distY * distY) * bStr[i];
+ if (v > bristle) {
+ bristle = v;
+ reach = bLen[i];
+ }
+ }
+ }
+ // Feathered front/back ends so smudge strokes melt smoothly without hard oval stamp rings
+ const envX = 1.0 - smoothstep(reach * 0.34, reach * 1.02, nx);
+ const envY = 1.0 - smoothstep(0.68, 1.02, ny);
+ const streak = 0.80 + 0.20 * samplePeriodic(nFine, 64, x * 0.14, y * 0.52);
+ const alpha = envX * envY * (0.28 + 0.72 * bristle) * streak;
+ if (alpha > 0.004) {
+ writeAlphaPixel(data, row + x * 4, alpha);
+ }
+ }
+ }
+ });
+}
+
+/**
+ * Matte Chalk Blender Tip (256x256):
+ * Upgraded high-res wide feathered matte chalk-pad smudger with fine directional drag filaments
+ * and velvety mineral pores so hard concept-art planes melt cleanly while retaining dry tooth.
+ */
+export function generateBlendMatteChalkTip(): string {
+ return buildCachedPng('tip:blend-matte-chalk-256', HI_TIP_SIZE, (data, size) => {
+ const rand = createPrng(0xb7d98);
+ const nCoarse = makePeriodicGrid(16, rand);
+ const nMed = makePeriodicGrid(32, rand);
+ const nFine = makePeriodicGrid(64, rand);
+ const domes = makeCellularDomeField(128, 44, rand);
+ const half = size * 0.5;
+ const rx = size * 0.46;
+ const ry = size * 0.40;
+ const invSize = 1 / size;
+
+ for (let y = 0; y < size; y++) {
+ const dy = y - half + 0.5;
+ const row = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ const dx = x - half + 0.5;
+ const warp =
+ (samplePeriodic(nCoarse, 16, x * 0.07, y * 0.07) - 0.5) * 0.16 +
+ (samplePeriodic(nMed, 32, x * 0.15, y * 0.15) - 0.5) * 0.07;
+ const nx = Math.abs(dx) / (rx * (1.0 + warp));
+ const ny = Math.abs(dy) / (ry * (1.0 + warp));
+ const d = Math.pow(Math.pow(nx, 2.6) + Math.pow(ny, 2.6), 1 / 2.6);
+ if (d >= 1.04) continue;
+
+ const env = Math.pow(1.0 - smoothstep(0.24, 1.02, d), 1.12);
+ const filaments = samplePeriodic(nMed, 32, x * 0.05, y * 0.34);
+ const dome = sampleFieldBilinear(domes, 128, x * invSize, y * invSize);
+ const fine = samplePeriodic(nFine, 64, x * 0.40, y * 0.40);
+ const powdery = dome * 0.32 + filaments * 0.42 + fine * 0.18 + rand() * 0.08;
+
+ const outerFade = smoothstep(0.38, 1.0, d);
+ const grainMod =
+ 0.74 * (1.0 - outerFade * 0.52) +
+ smoothstep(0.14 + outerFade * 0.20, 0.68 + outerFade * 0.18, powdery) * (0.26 + outerFade * 0.52);
+ const alpha = env * grainMod;
+ if (alpha > 0.004) {
+ writeAlphaPixel(data, row + x * 4, alpha);
+ }
+ }
+ }
+ });
+}
+
+/**
+ * Rake Hair & Fur Smear Blender Tip (256x256):
+ * Fine separated multi-strand rake blender (CSP Fur/Hair Blend equivalent):
+ * ~24 razor-fine organic hair/fur filaments with varied thicknesses and crisp airy gaps
+ * aligned along X for wispy hair, horse mane/tail, feathers, and expressive edge breakup.
+ */
+export function generateBlendRakeHairTip(): string {
+ return buildCachedPng('tip:blend-rake-hair-256', HI_TIP_SIZE, (data, size) => {
+ const rand = createPrng(0xe37c4);
+ const half = size * 0.5;
+ const rx = size * 0.46;
+ const ry = size * 0.44;
+
+ interface Strand {
+ cx: number;
+ cy: number;
+ rx: number;
+ ry: number;
+ strength: number;
+ }
+ const strands: Strand[] = [];
+ const count = 24;
+ for (let i = 0; i < count; i++) {
+ const u = (i / (count - 1)) * 2 - 1;
+ // Organic clumped hair/fur spacing with fine air channels between filaments
+ const jitterU = u + (rand() - 0.5) * 0.055;
+ const arch = Math.sqrt(Math.max(0.24, 1.0 - jitterU * jitterU * 0.62));
+ const isFine = (i % 3) === 0;
+ strands.push({
+ cx: half + (rand() - 0.5) * rx * 0.28,
+ cy: half + jitterU * ry * 0.94,
+ rx: rx * (0.58 + rand() * 0.38) * arch,
+ ry: isFine ? 1.5 + rand() * 1.4 : 2.5 + rand() * 2.4,
+ strength: isFine ? 0.65 + rand() * 0.30 : 0.80 + rand() * 0.20,
+ });
+ }
+
+ for (let y = 0; y < size; y++) {
+ const row = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ let accum = 0;
+ for (let i = 0; i < strands.length; i++) {
+ const st = strands[i];
+ const dy = Math.abs(y - st.cy);
+ if (dy > st.ry * 1.1) continue;
+ const dx = Math.abs(x - st.cx);
+ if (dx > st.rx * 1.05) continue;
+ const nx = dx / st.rx;
+ const ny = dy / st.ry;
+ // Crisp across-strand edge (ny) with soft tapered front/back filament tips (nx)
+ const crossEnv = 1.0 - smoothstep(0.35, 1.0, ny);
+ const alongEnv = 1.0 - smoothstep(0.22, 1.0, nx);
+ const v = crossEnv * alongEnv * st.strength;
+ if (v > accum) accum = v;
+ }
+ if (accum > 0.006) {
+ writeAlphaPixel(data, row + x * 4, accum);
+ }
+ }
+ }
+ });
+}
+
+/**
+ * Canvas Scumble Melter Blender Tip (256x256):
+ * Porous irregular dry-bristle blender with feathered edges and open dry-paint pockets
+ * that dissolves hard edges into authentic Belgian linen canvas grain instead of digital blur.
+ */
+export function generateBlendCanvasScumbleTip(): string {
+ return buildCachedPng('tip:blend-canvas-scumble-256', HI_TIP_SIZE, (data, size) => {
+ const rand = createPrng(0xf2a18);
+ const nCoarse = makePeriodicGrid(16, rand);
+ const nMed = makePeriodicGrid(32, rand);
+ const nFine = makePeriodicGrid(64, rand);
+ const domes = makeCellularDomeField(128, 34, rand);
+ const half = size * 0.5;
+ const rx = size * 0.45;
+ const ry = size * 0.42;
+ const invSize = 1 / size;
+
+ for (let y = 0; y < size; y++) {
+ const dy = y - half + 0.5;
+ const row = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ const dx = x - half + 0.5;
+ const warp =
+ (samplePeriodic(nCoarse, 16, x * 0.06, y * 0.06) - 0.5) * 0.28 +
+ (samplePeriodic(nMed, 32, x * 0.14, y * 0.14) - 0.5) * 0.14;
+ const rNorm = Math.hypot(dx / (rx * (1.0 + warp)), dy / (ry * (1.0 + warp)));
+ if (rNorm >= 1.04) continue;
+
+ const env = Math.pow(1.0 - smoothstep(0.22, 1.02, rNorm), 1.18);
+ const dome = sampleFieldBilinear(domes, 128, x * invSize, y * invSize);
+ const fine = samplePeriodic(nFine, 64, x * 0.36, y * 0.36);
+ const porosity = dome * 0.52 + fine * 0.34 + rand() * 0.14;
+ const pocket = smoothstep(0.16 + rNorm * 0.28, 0.56 + rNorm * 0.24, porosity);
+ const alpha = env * (0.35 * (1.0 - rNorm) + 0.65 * pocket);
+ if (alpha > 0.004) {
+ writeAlphaPixel(data, row + x * 4, alpha);
+ }
+ }
+ }
+ });
+}
+
+/**
+ * Wet Finger Tip Smudger (256x256):
+ * Firm tapered rounded smudge pad with dense central pull and smooth outer rim falloff
+ * for physically dragging wet paint in long expressive trails, smoke, and flowing hair.
+ */
+export function generateBlendFingertipTip(): string {
+ return buildCachedPng('tip:blend-fingertip-256', HI_TIP_SIZE, (data, size) => {
+ const rand = createPrng(0xf91c2);
+ const nFine = makePeriodicGrid(64, rand);
+ const half = size * 0.5;
+ const rx = size * 0.45;
+ const ry = size * 0.40;
+
+ for (let y = 0; y < size; y++) {
+ const dy = y - half + 0.5;
+ const row = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ const dx = x - half + 0.5;
+ const nx = dx / rx;
+ // Subtle directional fingertip pad taper toward leading +X side
+ const padTaper = 1.0 - Math.max(0, nx) * 0.14;
+ const ny = dy / (ry * padTaper);
+ const d = Math.hypot(nx, ny);
+ if (d >= 1.0) continue;
+
+ // Firm core up to 0.54 (matches hardness ~0.56) tapering smoothly to 0 at rim
+ let alpha = 1.0;
+ if (d > 0.54) {
+ const t = (d - 0.54) / 0.46;
+ alpha = 1.0 - (3 * t * t - 2 * t * t * t);
+ }
+ // Subtle organic fingertip drag texture near rim (prevents sterile mechanical circle smear)
+ if (d > 0.48) {
+ const micro = samplePeriodic(nFine, 64, x * 0.16, y * 0.36);
+ alpha *= 0.92 + 0.08 * micro;
+ }
+ if (alpha > 0.004) {
+ writeAlphaPixel(data, row + x * 4, alpha);
+ }
+ }
+ }
+ });
+}
+
+/**
+ * Oil Painting Brush (legacy helper kept for backward compatibility).
*/
export function generateOilBristleTip(): string {
return buildCachedPng('tip:oil-painting', TIP_SIZE, (data, size) => {
@@ -655,35 +1636,137 @@ export function generateThickOilTip(): string {
}
/**
- * Chalk Painting Brush: wide sculpted painterly chalk/oil-pastel head with broken textured streaks.
+ * Painterly Chalk Painting Brush (Concept-Art Square/Chisel Chalk):
+ * Asymmetric hand-chipped flat rectangular chalk block with a crisp architectural leading edge,
+ * creamy dense core, fine mineral tooth along edges, and subtle longitudinal dry-drag striations.
*/
-export function generateChalkPaintTip(): string {
- return buildCachedPng('tip:chalk-painting', TIP_SIZE, (data, size) => {
- const rand = createPrng(0xa0a4);
+export function generatePainterlyChalkTip(): string {
+ return buildCachedPng('tip:painterly-chalk-v2', TIP_SIZE, (data, size) => {
+ const rand = createPrng(0xa4c81);
const nCoarse = makePeriodicGrid(16, rand);
const nMed = makePeriodicGrid(32, rand);
const nFine = makePeriodicGrid(64, rand);
+ const domes = makeCellularDomeField(size, 40, rand);
const half = size * 0.5;
- const rx = half - 8;
+ const rx = half - 5;
const ry = half - 14;
+ // Sparse delicate mineral dust crumbs hugging the trailing chipped rim
+ const flecks: Array<{ x: number; y: number; r: number; a: number }> = [];
+ for (let i = 0; i < 14; i++) {
+ const fx = half + (rand() * 2 - 1) * rx * 0.92;
+ const fy = half + ry * (0.90 + rand() * 0.16);
+ flecks.push({
+ x: fx,
+ y: fy,
+ r: 0.7 + rand() * 1.15,
+ a: 0.20 + rand() * 0.34,
+ });
+ }
+
for (let y = 0; y < size; y++) {
const dy = y - half + 0.5;
+ const ySigned = dy / ry; // -1 = crisp leading chisel edge, +1 = drier trailing chalk face
const row = y * size * 4;
+ const dRow = y * size;
for (let x = 0; x < size; x++) {
const dx = x - half + 0.5;
- // Directional streak noise along X for painterly drag
- const streak = samplePeriodic(nMed, 32, x * 0.14, y * 0.44);
- const warp = (samplePeriodic(nCoarse, 16, x * 0.15, y * 0.15) - 0.5) * 0.22;
+
+ // Subtle organic chipped-chalk edge distortion (crisper leading plane, more expressive trailing edge)
+ const trailFactor = clamp01((ySigned + 0.15) * 0.8);
+ const edgeRough = 0.065 + trailFactor * 0.10;
+ const warp =
+ (samplePeriodic(nCoarse, 16, x * 0.14, y * 0.14) - 0.5) * edgeRough * 1.35 +
+ (samplePeriodic(nMed, 32, x * 0.34, y * 0.34) - 0.5) * edgeRough * 0.75;
+
+ const nx = Math.abs(dx) / (rx * (1.0 + warp));
+ const ny = Math.abs(dy) / (ry * (1.0 + warp * 0.85));
+ // Sculptural flat rectangular concept-art chalk block (superellipse p = 4.8)
+ const d = Math.pow(Math.pow(nx, 4.8) + Math.pow(ny, 4.8), 1 / 4.8);
+
+ let alpha = 0;
+ if (d < 1.04) {
+ // Asymmetric edge sharpness: clean bold architectural leading edge, softer toothy trailing edge
+ const edgeStart = 0.88 - trailFactor * 0.16;
+ const edgeEnd = 1.01 + trailFactor * 0.025;
+ const env = 1.0 - smoothstep(edgeStart, edgeEnd, d);
+
+ // Fine mineral chalk grain + subtle longitudinal dry-drag striations along X
+ const dome = domes[dRow + x];
+ const dragStreak = samplePeriodic(nMed, 32, x * 0.09, y * 0.56);
+ const finePowder = samplePeriodic(nFine, 64, x * 0.78, y * 0.78);
+ const mineral = dome * 0.36 + dragStreak * 0.36 + finePowder * 0.20 + rand() * 0.08;
+
+ // Rich creamy core for solid opaque planes; crisp dry mineral breakup along rim & trailing edge
+ const rimDryness = smoothstep(0.56, 1.0, d) * 0.32 + trailFactor * 0.12;
+ const cutLow = 0.05 + rimDryness;
+ const chalkBody = smoothstep(cutLow, cutLow + 0.26, mineral);
+ const coreFloor = (1.0 - smoothstep(0.68, 0.97, d)) * (0.90 - trailFactor * 0.22);
+ alpha = env * Math.max(coreFloor, chalkBody * (0.88 + 0.12 * dragStreak));
+ }
+
+ for (let f = 0; f < flecks.length; f++) {
+ const fl = flecks[f];
+ const fdx = x - fl.x;
+ const fdy = y - fl.y;
+ if (Math.abs(fdx) > 3.0 || Math.abs(fdy) > 3.0) continue;
+ const fd = Math.hypot(fdx, fdy) / fl.r;
+ if (fd < 1.0) {
+ const fa = (1.0 - smoothstep(0.25, 1.0, fd)) * fl.a;
+ if (fa > alpha) alpha = fa;
+ }
+ }
+
+ writeAlphaPixel(data, row + x * 4, alpha);
+ }
+ }
+ });
+}
+
+/**
+ * Blend Chalk Brush Tip (Painterly Dry-Chalk Smudger):
+ * Wide feathered organic chalk-pad head with fine parallel drag filaments and velvety matte pores
+ * so blended edges melt smoothly while retaining traditional painterly chalk texture.
+ */
+export function generateBlendChalkTip(): string {
+ return buildCachedPng('tip:blend-chalk-v2', TIP_SIZE, (data, size) => {
+ const rand = createPrng(0xb7d92);
+ const nCoarse = makePeriodicGrid(16, rand);
+ const nMed = makePeriodicGrid(32, rand);
+ const nFine = makePeriodicGrid(64, rand);
+ const domes = makeCellularDomeField(size, 44, rand);
+ const half = size * 0.5;
+ const rx = half - 5;
+ const ry = half - 12;
+
+ for (let y = 0; y < size; y++) {
+ const dy = y - half + 0.5;
+ const row = y * size * 4;
+ const dRow = y * size;
+ for (let x = 0; x < size; x++) {
+ const dx = x - half + 0.5;
+ const warp =
+ (samplePeriodic(nCoarse, 16, x * 0.14, y * 0.14) - 0.5) * 0.18 +
+ (samplePeriodic(nMed, 32, x * 0.30, y * 0.30) - 0.5) * 0.08;
const nx = Math.abs(dx) / (rx * (1.0 + warp));
const ny = Math.abs(dy) / (ry * (1.0 + warp));
- const d = Math.pow(Math.pow(nx, 2.4) + Math.pow(ny, 2.4), 1 / 2.4);
- if (d >= 1.06) continue;
+ const d = Math.pow(Math.pow(nx, 2.6) + Math.pow(ny, 2.6), 1 / 2.6);
+ if (d >= 1.04) continue;
+
+ // Smooth velvety feathered radial envelope (melts edges cleanly without hard stamp outlines)
+ const env = Math.pow(1.0 - smoothstep(0.26, 1.02, d), 1.12);
- const env = 1.0 - smoothstep(0.68, 1.05, d);
- const tooth = samplePeriodic(nFine, 64, x * 0.65, y * 0.65);
- const dry = smoothstep(0.16, 0.78, streak * 0.52 + tooth * 0.34 + rand() * 0.14 + (1.0 - d) * 0.35);
- writeAlphaPixel(data, row + x * 4, env * (0.38 + 0.62 * dry));
+ // Directional soft chalk-drag filaments + fine velvety mineral pores
+ const filaments = samplePeriodic(nMed, 32, x * 0.10, y * 0.64);
+ const dome = domes[dRow + x];
+ const fine = samplePeriodic(nFine, 64, x * 0.80, y * 0.80);
+ const powdery = dome * 0.32 + filaments * 0.42 + fine * 0.18 + rand() * 0.08;
+
+ const outerFade = smoothstep(0.40, 1.0, d);
+ const grainMod =
+ 0.72 * (1.0 - outerFade * 0.52) +
+ smoothstep(0.14 + outerFade * 0.20, 0.68 + outerFade * 0.18, powdery) * (0.28 + outerFade * 0.52);
+ writeAlphaPixel(data, row + x * 4, env * grainMod);
}
}
});
@@ -823,6 +1906,41 @@ export function generateCharcoalPaperTexture(): string {
});
}
+/**
+ * Painterly Matte Chalk / Gesso Board Texture (256x256):
+ * Fine isotropic mineral tooth (dual-scale cellular domes + gentle gesso board undulation)
+ * with zero mechanical horizontal stripes — crafted for concept-art chalk painting & blending.
+ */
+export function generatePainterlyChalkGrainTexture(): string {
+ return buildCachedPng('paper:painterly-chalk-gesso', PAPER_SIZE, (data, size) => {
+ const rand = createPrng(0xc8e4);
+ const fineDomes = makeCellularDomeField(size, 92, rand); // ~2.8px velvety matte illustration board tooth
+ const microDomes = makeCellularDomeField(size, 152, rand); // ~1.7px ultra-fine mineral chalk pores
+ const gBoard = makePeriodicGrid(32, rand);
+ const gGrit = makePeriodicGrid(128, rand);
+
+ for (let y = 0; y < size; y++) {
+ const row = y * size * 4;
+ const dRow = y * size;
+ for (let x = 0; x < size; x++) {
+ const d1 = fineDomes[dRow + x];
+ const d2 = microDomes[dRow + x];
+ const board = samplePeriodic(gBoard, 32, x * 0.125, y * 0.125);
+ const grit = samplePeriodic(gGrit, 128, x * 0.5, y * 0.5);
+ const raw = d1 * 0.38 + d2 * 0.26 + grit * 0.18 + board * 0.12 + rand() * 0.06;
+ // Creamy mid-high matte tooth distribution (delicate velvety grain, never chunky polka dots)
+ const crisp = clamp01((raw - 0.10) / 0.78);
+ const v = Math.round((0.18 + 0.82 * Math.pow(crisp, 0.96)) * 255);
+ const idx = row + x * 4;
+ data[idx] = v;
+ data[idx + 1] = v;
+ data[idx + 2] = v;
+ data[idx + 3] = 255;
+ }
+ }
+ });
+}
+
/**
* Primed Linen Oil Canvas Texture:
* Seamless interlocking horizontal/vertical woven canvas threads with subtle organic yarn variation.
diff --git a/src/utils/retouchEngine.ts b/src/utils/retouchEngine.ts
index 80a66d1..e368c1e 100644
--- a/src/utils/retouchEngine.ts
+++ b/src/utils/retouchEngine.ts
@@ -25,15 +25,21 @@ import {
import { parseHexRgb } from './gradientEngine';
import {
RgbColor,
- decodeSpectralKSToSrgb,
- encodeSrgbToSpectralKS,
mixPigmentRgbOut,
} from './colorMixingEngine';
+import {
+ PIGMENT_LATENT_SIZE,
+ detectWhitePaperGround,
+ encodePigmentOverWhiteOut,
+ pigmentLatentToSrgbOut,
+ srgbToPigmentLatentOut,
+} from './pigmentEngine';
const _smudgeMixOut: RgbColor = { r: 0, g: 0, b: 0 };
const _smudgeReloadOut: RgbColor = { r: 0, g: 0, b: 0 };
const _blurDecodeOut: RgbColor = { r: 0, g: 0, b: 0 };
const _blurMixOut: RgbColor = { r: 0, g: 0, b: 0 };
+const _blurWhiteOut: [number, number, number, number] = [0, 0, 0, 0];
export type RetouchMode = 'smudge' | 'blur' | 'dodge' | 'burn' | 'clone-stamp';
export type RetouchTonalRange = 'shadows' | 'midtones' | 'highlights';
@@ -49,7 +55,7 @@ export interface RetouchSettings {
tonalRange: RetouchTonalRange; // Dodge / Burn range
protectTones: boolean; // Dodge / Burn hue preservation
smudgeFingerPainting: boolean; // Load primary color at stroke start
- pigmentBlending: boolean; // Physical 7-band Kubelka-Munk spectral pigment blending for Smudge & Blur
+ pigmentBlending: boolean; // Physical Kubelka-Munk pigment blending for Smudge & Blur
pigmentStrength: number; // 0..100 % Kubelka-Munk pigment blending strength
cloneAligned: boolean; // Keep relative offset across strokes
cloneSampleMode: CloneSampleMode; // Active layer vs all visible composited
@@ -65,7 +71,7 @@ export const DEFAULT_RETOUCH_SETTINGS: RetouchSettings = {
tonalRange: 'midtones',
protectTones: true,
smudgeFingerPainting: false,
- pigmentBlending: false,
+ pigmentBlending: true,
pigmentStrength: 100,
cloneAligned: true,
cloneSampleMode: 'active',
@@ -76,6 +82,7 @@ export interface RetouchStrokeSession {
layerId: string;
targetFormat: TileFormat;
alphaLock: boolean;
+ pigmentWhiteGround: boolean;
dimensions: CanvasDimensions;
selectionMask: Uint8Array | null;
beforeSnapshot: Map<string, TileSnapshotEntry>;
@@ -155,6 +162,7 @@ export function createRetouchStrokeSession(params: {
layerId: string;
targetFormat: TileFormat;
alphaLock: boolean;
+ pigmentWhiteGround?: boolean;
dimensions: CanvasDimensions;
selectionMask: Uint8Array | null;
cloneOffset?: Point2D | null;
@@ -162,11 +170,18 @@ export function createRetouchStrokeSession(params: {
isLayerVisible?: (layer: LayerItem) => boolean;
getEffectiveOpacity?: (layer: LayerItem) => number;
}): RetouchStrokeSession {
+ const pigmentWhiteGround =
+ params.pigmentWhiteGround !== undefined
+ ? params.pigmentWhiteGround
+ : params.visibleLayers
+ ? detectWhitePaperGround(params.visibleLayers, params.layerId)
+ : false;
return {
mode: params.mode,
layerId: params.layerId,
targetFormat: params.targetFormat,
alphaLock: params.alphaLock,
+ pigmentWhiteGround,
dimensions: params.dimensions,
selectionMask: params.selectionMask,
beforeSnapshot: new Map<string, TileSnapshotEntry>(),
@@ -417,6 +432,80 @@ function applySmudgeDab(
const invW = 1 - w;
const outA = alphaLock ? dstA : dstA * invW + srcA * w;
+ const pickupRate = 1 - str * 0.88;
+ const invPickup = 1 - pickupRate;
+
+ // Unified optical white-paper pigment smudge: handles both opaque-to-opaque AND
+ // translucent multi-dab pigment dilution over white ground without collapsing to gray
+ // on subsequent overlapping dabs.
+ if (
+ pigmentBlending &&
+ pigmentStrength > 0.005 &&
+ session.pigmentWhiteGround &&
+ !alphaLock &&
+ (dstA > 0.5 || srcA > 0.5)
+ ) {
+ const srcANorm = srcA / 255;
+ const visDstR = dstPR + 255 * (1 - dstANorm);
+ const visDstG = dstPG + 255 * (1 - dstANorm);
+ const visDstB = dstPB + 255 * (1 - dstANorm);
+ const visSrcR = srcPR + 255 * (1 - srcANorm);
+ const visSrcG = srcPG + 255 * (1 - srcANorm);
+ const visSrcB = srcPB + 255 * (1 - srcANorm);
+
+ mixPigmentRgbOut(
+ visDstR,
+ visDstG,
+ visDstB,
+ visSrcR,
+ visSrcG,
+ visSrcB,
+ w,
+ pigmentStrength,
+ _smudgeMixOut
+ );
+ const baseOutANorm = outA / 255;
+ if (outA <= 0.5) {
+ data[rIdx] = 0;
+ data[rIdx + 1] = 0;
+ data[rIdx + 2] = 0;
+ data[rIdx + 3] = 0;
+ } else {
+ const minC = Math.min(_smudgeMixOut.r, _smudgeMixOut.g, _smudgeMixOut.b);
+ const encA = Math.max(baseOutANorm, 1 - minC / 255);
+ const bg = 255 * (1 - encA);
+ const invEncA = 1 / Math.max(1e-5, encA);
+ data[rIdx] = clamp255(Math.round((_smudgeMixOut.r - bg) * invEncA));
+ data[rIdx + 1] = clamp255(Math.round((_smudgeMixOut.g - bg) * invEncA));
+ data[rIdx + 2] = clamp255(Math.round((_smudgeMixOut.b - bg) * invEncA));
+ data[rIdx + 3] = clamp255(Math.round(encA * 255));
+ }
+
+ // Reload pickup buffer in visible-on-white pigment space so dragging dark pigments
+ // over empty transparent canvas smoothly fades through luminous cerulean/magenta/teal.
+ mixPigmentRgbOut(
+ visSrcR,
+ visSrcG,
+ visSrcB,
+ _smudgeMixOut.r,
+ _smudgeMixOut.g,
+ _smudgeMixOut.b,
+ pickupRate,
+ pigmentStrength,
+ _smudgeReloadOut
+ );
+ const rawNextBufA = srcA * invPickup + outA * pickupRate;
+ const minBufC = Math.min(_smudgeReloadOut.r, _smudgeReloadOut.g, _smudgeReloadOut.b);
+ const nextBufANorm = Math.max(rawNextBufA / 255, 1 - minBufC / 255);
+ const nextBg = 255 * (1 - nextBufANorm);
+ buf[bIdx] = Math.max(0, _smudgeReloadOut.r - nextBg);
+ buf[bIdx + 1] = Math.max(0, _smudgeReloadOut.g - nextBg);
+ buf[bIdx + 2] = Math.max(0, _smudgeReloadOut.b - nextBg);
+ buf[bIdx + 3] = clamp255(nextBufANorm * 255);
+ touched = true;
+ continue;
+ }
+
let outPR: number;
let outPG: number;
let outPB: number;
@@ -474,8 +563,6 @@ function applySmudgeDab(
}
// Reload pickup buffer from blended canvas pixel (prevents rapid fadeout while picking up new pigment)
- const pickupRate = 1 - str * 0.88;
- const invPickup = 1 - pickupRate;
const nextBufA = srcA * invPickup + outA * pickupRate;
if (usePigment && nextBufA > 0.5) {
const invSrcA = 255 / srcA;
@@ -562,20 +649,20 @@ function applyBlurDab(
premul[o + 3] = srcData[o + 3];
}
- // Optional 10-channel premultiplied Kubelka-Munk K/S + residual buffers for true spectral pigment blur
+ // Optional 7-channel premultiplied Kubelka-Munk pigment latent buffers for true physical pigment blur
let specPremul: Float32Array | null = null;
let specHoriz: Float32Array | null = null;
if (usePigment) {
- specPremul = new Float32Array(pw * ph * 10);
- specHoriz = new Float32Array(pw * ph * 10);
- const tmpSpec = new Float32Array(10);
+ specPremul = new Float32Array(pw * ph * PIGMENT_LATENT_SIZE);
+ specHoriz = new Float32Array(pw * ph * PIGMENT_LATENT_SIZE);
+ const tmpSpec = new Float32Array(PIGMENT_LATENT_SIZE);
for (let i = 0; i < pw * ph; i++) {
const o = i * 4;
const a = srcData[o + 3] / 255;
if (a > 0) {
- encodeSrgbToSpectralKS(srcData[o], srcData[o + 1], srcData[o + 2], tmpSpec, 0);
- const so = i * 10;
- for (let c = 0; c < 10; c++) {
+ srgbToPigmentLatentOut(srcData[o], srcData[o + 1], srcData[o + 2], tmpSpec, 0);
+ const so = i * PIGMENT_LATENT_SIZE;
+ for (let c = 0; c < PIGMENT_LATENT_SIZE; c++) {
specPremul[so + c] = tmpSpec[c] * a;
}
}
@@ -583,7 +670,7 @@ function applyBlurDab(
}
// Horizontal pass
- const sRowSum = usePigment ? new Float32Array(10) : null;
+ const sRowSum = usePigment ? new Float32Array(PIGMENT_LATENT_SIZE) : null;
for (let y = 0; y < ph; y++) {
const rowBase = y * pw;
let sr = 0;
@@ -599,8 +686,8 @@ function applyBlurDab(
sb += premul[o + 2];
sa += premul[o + 3];
if (sRowSum && specPremul) {
- const so = (rowBase + sx) * 10;
- for (let c = 0; c < 10; c++) sRowSum[c] += specPremul[so + c];
+ const so = (rowBase + sx) * PIGMENT_LATENT_SIZE;
+ for (let c = 0; c < PIGMENT_LATENT_SIZE; c++) sRowSum[c] += specPremul[so + c];
}
}
for (let x = 0; x < pw; x++) {
@@ -610,8 +697,8 @@ function applyBlurDab(
horiz[o + 2] = sb * invK;
horiz[o + 3] = sa * invK;
if (sRowSum && specHoriz) {
- const so = (rowBase + x) * 10;
- for (let c = 0; c < 10; c++) specHoriz[so + c] = sRowSum[c] * invK;
+ const so = (rowBase + x) * PIGMENT_LATENT_SIZE;
+ for (let c = 0; c < PIGMENT_LATENT_SIZE; c++) specHoriz[so + c] = sRowSum[c] * invK;
}
const remX = x - blurK < 0 ? 0 : x - blurK;
@@ -623,9 +710,11 @@ function applyBlurDab(
sb += premul[ao + 2] - premul[ro + 2];
sa += premul[ao + 3] - premul[ro + 3];
if (sRowSum && specPremul) {
- const rso = (rowBase + remX) * 10;
- const aso = (rowBase + addX) * 10;
- for (let c = 0; c < 10; c++) sRowSum[c] += specPremul[aso + c] - specPremul[rso + c];
+ const rso = (rowBase + remX) * PIGMENT_LATENT_SIZE;
+ const aso = (rowBase + addX) * PIGMENT_LATENT_SIZE;
+ for (let c = 0; c < PIGMENT_LATENT_SIZE; c++) {
+ sRowSum[c] += specPremul[aso + c] - specPremul[rso + c];
+ }
}
}
}
@@ -641,8 +730,8 @@ function applyBlurDab(
snapshotRoiTiles(grid, session.layerId, rx0, ry0, rw, rh, session.beforeSnapshot);
- const sColSum = usePigment ? new Float32Array(10) : null;
- const sColDec = usePigment ? new Float32Array(10) : null;
+ const sColSum = usePigment ? new Float32Array(PIGMENT_LATENT_SIZE) : null;
+ const sColDec = usePigment ? new Float32Array(PIGMENT_LATENT_SIZE) : null;
for (let lx = 0; lx < rw; lx++) {
const sx = rx0 - px0 + lx;
@@ -663,8 +752,8 @@ function applyBlurDab(
sb += horiz[o + 2];
sa += horiz[o + 3];
if (sColSum && specHoriz) {
- const so = (sy * pw + sx) * 10;
- for (let c = 0; c < 10; c++) sColSum[c] += specHoriz[so + c];
+ const so = (sy * pw + sx) * PIGMENT_LATENT_SIZE;
+ for (let c = 0; c < PIGMENT_LATENT_SIZE; c++) sColSum[c] += specHoriz[so + c];
}
}
@@ -682,10 +771,10 @@ function applyBlurDab(
const hasPigBlur = Boolean(sColSum && sColDec && ba > 0.5);
if (hasPigBlur && sColSum && sColDec) {
const invAlphaNorm = 1 / ((ba / 255) * kSize);
- for (let c = 0; c < 10; c++) {
+ for (let c = 0; c < PIGMENT_LATENT_SIZE; c++) {
sColDec[c] = sColSum[c] * invAlphaNorm;
}
- decodeSpectralKSToSrgb(sColDec, 0, _blurDecodeOut);
+ pigmentLatentToSrgbOut(sColDec, 0, _blurDecodeOut);
const invBa = 255 / ba;
const regBlurR = br * invBa;
const regBlurG = bg * invBa;
@@ -704,9 +793,11 @@ function applyBlurDab(
sb += horiz[ao + 2] - horiz[ro + 2];
sa += horiz[ao + 3] - horiz[ro + 3];
if (sColSum && specHoriz) {
- const rso = (remY * pw + sx) * 10;
- const aso = (addY * pw + sx) * 10;
- for (let c = 0; c < 10; c++) sColSum[c] += specHoriz[aso + c] - specHoriz[rso + c];
+ const rso = (remY * pw + sx) * PIGMENT_LATENT_SIZE;
+ const aso = (addY * pw + sx) * PIGMENT_LATENT_SIZE;
+ for (let c = 0; c < PIGMENT_LATENT_SIZE; c++) {
+ sColSum[c] += specHoriz[aso + c] - specHoriz[rso + c];
+ }
}
const distY = gy + 0.5 - cy;
@@ -750,6 +841,19 @@ function applyBlurDab(
outData[oIdx + 1] = clamp255(Math.round(_blurMixOut.g));
outData[oIdx + 2] = clamp255(Math.round(_blurMixOut.b));
outData[oIdx + 3] = clamp255(Math.round(finalA));
+ } else if (hasPigBlur && session.pigmentWhiteGround && finalA < 254.5) {
+ encodePigmentOverWhiteOut(
+ pigBlurR,
+ pigBlurG,
+ pigBlurB,
+ finalA / 255,
+ pigmentStrength,
+ _blurWhiteOut
+ );
+ outData[oIdx] = _blurWhiteOut[0];
+ outData[oIdx + 1] = _blurWhiteOut[1];
+ outData[oIdx + 2] = _blurWhiteOut[2];
+ outData[oIdx + 3] = _blurWhiteOut[3];
} else {
const dstANorm = dstA / 255;
const finalPR = outData[oIdx] * dstANorm * invW + br * w;
diff --git a/src/utils/sutParser.ts b/src/utils/sutParser.ts
index fcebd53..2abbf14 100644
--- a/src/utils/sutParser.ts
+++ b/src/utils/sutParser.ts
@@ -1,17 +1,29 @@
import { unzlibSync, inflateSync } from 'fflate';
import {
+ BrushDynamics,
CspAngleDynamicsMode,
CspBlendTipsMode,
CspBrush,
+ CspBrushCombineMode,
+ CspDualBrushConfig,
CspPaperTextureMode,
CspSensorConfig,
CspSpraySettings,
CspSubTip,
+ CspSubTipOrder,
CspTaperSettings,
CspTipFlipMode,
+ DEFAULT_BRUSH_DYNAMICS,
+ GrainMappingMode,
} from '../types/editor';
import { evaluateFastSpline } from '../engine/BrushEngine';
-import { isNativeRustAvailable, NativeSutExtract, parseSutSqliteNative } from './nativeBackend';
+import { normalizeDualBrushCompositeMode } from '../engine/DualBrushEngine';
+import {
+ CspExpressionColor,
+ isNativeRustAvailable,
+ NativeSutExtract,
+ parseSutSqliteNative,
+} from './nativeBackend';
const MAX_DECOMPRESSED_BLOB_BYTES = 64 * 1024 * 1024;
const MAX_COMPRESSED_BLOB_BYTES = 16 * 1024 * 1024;
@@ -293,22 +305,26 @@ export function bytesToDataUrl(bytes: Uint8Array, mime: string = 'image/png'): s
return `data:${mime};base64,${btoa(parts.join(''))}`;
}
+const CSP_UUID_RE = /[a-f0-9]{10}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{10}/gi;
+const CSP_CATALOG_PATH_RE = /\.:[a-zA-Z0-9_-]+(?::[a-zA-Z0-9_.-]+){2,}/g;
+
function extractCatalogIdsFromBlob(blob: Uint8Array | null | undefined): string[] {
if (!blob || blob.length === 0) return [];
- const results: string[] = [];
+ const catalogPaths: string[] = [];
+ const standaloneUuids: string[] = [];
const addMatches = (text: string) => {
- const re = /\.:\d+:\d+:[a-zA-Z0-9-]+/g;
- let match;
- while ((match = re.exec(text)) !== null) {
- if (!results.includes(match[0])) {
- results.push(match[0]);
+ CSP_CATALOG_PATH_RE.lastIndex = 0;
+ let match: RegExpExecArray | null;
+ while ((match = CSP_CATALOG_PATH_RE.exec(text)) !== null) {
+ if (!catalogPaths.includes(match[0])) {
+ catalogPaths.push(match[0]);
}
}
- const uuidRe = /[a-f0-9]{10}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{10}/gi;
- while ((match = uuidRe.exec(text)) !== null) {
- if (!results.includes(match[0])) {
- results.push(match[0]);
+ CSP_UUID_RE.lastIndex = 0;
+ while ((match = CSP_UUID_RE.exec(text)) !== null) {
+ if (!standaloneUuids.includes(match[0])) {
+ standaloneUuids.push(match[0]);
}
}
};
@@ -329,6 +345,14 @@ function extractCatalogIdsFromBlob(blob: Uint8Array | null | undefined): string[
// Ignore
}
+ const results = [...catalogPaths];
+ for (const uuid of standaloneUuids) {
+ const lowerUuid = uuid.toLowerCase();
+ const alreadyCovered = catalogPaths.some((p) => p.toLowerCase().includes(lowerUuid));
+ if (!alreadyCovered) {
+ results.push(uuid);
+ }
+ }
return results;
}
@@ -339,68 +363,181 @@ export interface DecodedEffector {
useRandom: boolean;
minValue: number;
maxValue: number;
+ pressureMin: number;
+ tiltMin: number;
+ tiltMax: number;
+ velocityMin: number;
+ randomMin: number;
+ invertTilt: boolean;
+ invertVelocity: boolean;
+ sourceFlags: number;
pressureCurve?: [number, number][];
tiltCurve?: [number, number][];
velocityCurve?: [number, number][];
}
+function clamp01(v: number): number {
+ if (!Number.isFinite(v)) return 0;
+ return Math.max(0, Math.min(1, v));
+}
+
export function parseCspEffector(blob: Uint8Array | null | undefined): DecodedEffector | null {
if (!blob || blob.length < 44) return null;
const view = new DataView(blob.buffer, blob.byteOffset, blob.byteLength);
+ const headerLen = view.getUint32(0, false);
const sourceFlags = view.getUint32(8, false);
+ // Real CSP Effector source bitmask (verified across CSP .sut Variant blobs):
+ // 0x10 = Pen Pressure
+ // 0x20 = Tilt
+ // 0x40 = Velocity
+ // 0x80 = Random (legacy synthetic fallback: 0x01)
const usePressure = Boolean(sourceFlags & 0x10);
const useTilt = Boolean(sourceFlags & 0x20);
- const useVelocity = Boolean(sourceFlags & 0x80);
- const useRandom = Boolean(sourceFlags & 0x01);
+ const useVelocity = Boolean(sourceFlags & 0x40);
+ const useRandom = Boolean(sourceFlags & (0x80 | 0x01));
+
+ // CSP's 48-byte big-endian Effector header layout:
+ // [0] headerLen (48 = 0x30)
+ // [4] supportedSourcesMask (0x0f0 or 0x1f0)
+ // [8] sourceFlags (0x10=Pressure, 0x20=Tilt, 0x40=Velocity, 0x80=Random)
+ // [12] pressureMin (0..100)
+ // [16] tiltMin (0..100)
+ // [20] velocityMin (0..100)
+ // [24] randomMin (signed i32: 0..100, or -100 for Hue/Sat/Val color jitter effectors)
+ // [28] reserved / 5th source min (0)
+ // [32] pressureCurveByteLen (0 or 12 + numPts * 16)
+ // [36] tiltCurveByteLen (0 or 12 + numPts * 16)
+ // [40] maxScale / reference range (100, 150, or 500)
+ // [44] velocityCurveByteLen (0 or 12 + numPts * 16)
+ const rawPressureMin = Math.max(0, view.getInt32(12, false));
+ const rawTiltMin = Math.max(0, view.getInt32(16, false));
+ const rawVelocityMin = Math.max(0, view.getInt32(20, false));
+ const rawRandomMin = Math.max(0, view.getInt32(24, false));
+ const pCurveLen = blob.length >= 36 ? view.getUint32(32, false) : 0;
+ const tCurveLen = blob.length >= 40 ? view.getUint32(36, false) : 0;
+ const rawTiltMax = headerLen >= 48 && blob.length >= 44 ? view.getUint32(40, false) : 100;
+ const vCurveLen = blob.length >= 48 ? view.getUint32(44, false) : 0;
+
+ const hasPerSourceNonZero = rawTiltMin > 0 || rawVelocityMin > 0 || rawRandomMin > 0;
+ const pressureMin = clamp01(rawPressureMin / 100.0);
+ let tiltMin = clamp01(rawTiltMin / 100.0);
+ const tiltMax = rawTiltMax > 100 && rawTiltMax <= 1000 ? rawTiltMax / 100.0 : 1.0;
+ let velocityMin = clamp01(rawVelocityMin / 100.0);
+ let randomMin = clamp01(rawRandomMin / 100.0);
+
+ // Backward compatibility with legacy single-min effectors where offset 12 holds the shared min
+ if (!usePressure && !hasPerSourceNonZero && rawPressureMin > 0) {
+ if (useTilt) tiltMin = pressureMin;
+ if (useVelocity) velocityMin = pressureMin;
+ if (useRandom) randomMin = pressureMin;
+ }
- const rawMin = view.getUint32(12, false);
- const rawMax = view.getUint32(16, false);
- const minValue = Math.max(0, Math.min(1.0, rawMin / 100.0));
- const maxValue = rawMax > 0 ? Math.max(0, Math.min(1.0, rawMax / 100.0)) : 1.0;
+ const minValue = usePressure
+ ? pressureMin
+ : useTilt
+ ? tiltMin
+ : useVelocity
+ ? velocityMin
+ : useRandom
+ ? randomMin
+ : pressureMin;
+ const maxValue = 1.0;
+
+ const invertTilt = Boolean(sourceFlags & 0x2000) || Boolean(sourceFlags & 0x0200);
+ const invertVelocity = Boolean(sourceFlags & 0x8000) || Boolean(sourceFlags & 0x0800);
- const curves: [number, number][][] = [];
- const headerLen = view.getUint32(0, false);
let offset = headerLen >= 44 && headerLen <= blob.length ? headerLen : 48;
- if (offset + 12 <= blob.length && view.getUint32(offset, false) !== 12 && blob.length >= 56 && view.getUint32(44, false) === 12) {
+ if (
+ offset + 12 <= blob.length &&
+ view.getUint32(offset, false) !== 12 &&
+ blob.length >= 56 &&
+ view.getUint32(44, false) === 12
+ ) {
offset = 44;
}
- while (offset + 12 <= blob.length) {
- const magic = view.getUint32(offset, false);
- const numPts = view.getUint32(offset + 4, false);
- const ptSize = view.getUint32(offset + 8, false);
-
- if (magic !== 12 || ptSize !== 16 || numPts > 256 || offset + 12 + numPts * 16 > blob.length) {
- break;
+ const readSingleCurve = (
+ start: number,
+ endLimit: number
+ ): { pts: [number, number][]; nextOffset: number } | null => {
+ if (start + 12 > endLimit || start + 12 > blob.length) return null;
+ const magic = view.getUint32(start, false);
+ const numPts = view.getUint32(start + 4, false);
+ const ptSize = view.getUint32(start + 8, false);
+ const byteEnd = start + 12 + numPts * 16;
+ if (magic !== 12 || ptSize !== 16 || numPts > 256 || byteEnd > endLimit || byteEnd > blob.length) {
+ return null;
}
-
- offset += 12;
const pts: [number, number][] = [];
+ let cur = start + 12;
for (let i = 0; i < numPts; i++) {
- const x = view.getFloat64(offset, false);
- const y = view.getFloat64(offset + 8, false);
- pts.push([Math.max(0, Math.min(1.0, x)), Math.max(0, Math.min(1.0, y))]);
- offset += 16;
+ const x = view.getFloat64(cur, false);
+ const y = view.getFloat64(cur + 8, false);
+ pts.push([clamp01(x), clamp01(y)]);
+ cur += 16;
}
- if (pts.length > 0) {
- curves.push(pts);
- }
- }
+ return pts.length > 0 ? { pts, nextOffset: cur } : null;
+ };
- let curveIdx = 0;
let pressureCurve: [number, number][] | undefined = undefined;
let tiltCurve: [number, number][] | undefined = undefined;
let velocityCurve: [number, number][] | undefined = undefined;
- if (usePressure && curveIdx < curves.length) {
- pressureCurve = curves[curveIdx++];
- }
- if (useTilt && curveIdx < curves.length) {
- tiltCurve = curves[curveIdx++];
- }
- if (useVelocity && curveIdx < curves.length) {
- velocityCurve = curves[curveIdx++];
+ const tailBytes = blob.length - offset;
+ const hasExactCurveLengths =
+ headerLen >= 48 &&
+ blob.length >= 48 &&
+ tailBytes > 0 &&
+ (pCurveLen > 0 || tCurveLen > 0 || vCurveLen > 0) &&
+ pCurveLen + tCurveLen + vCurveLen === tailBytes;
+
+ if (hasExactCurveLengths) {
+ // Exact CSP curve slot slicing: CSP often retains saved curves for disabled sources
+ // (e.g., saved pressure curve before an active tilt curve), indexed by header byte lengths.
+ let cursor = offset;
+ if (pCurveLen > 0) {
+ const parsed = readSingleCurve(cursor, cursor + pCurveLen);
+ if (usePressure && parsed) pressureCurve = parsed.pts;
+ cursor += pCurveLen;
+ }
+ if (tCurveLen > 0) {
+ const parsed = readSingleCurve(cursor, cursor + tCurveLen);
+ if (useTilt && parsed) tiltCurve = parsed.pts;
+ cursor += tCurveLen;
+ }
+ if (vCurveLen > 0) {
+ const parsed = readSingleCurve(cursor, cursor + vCurveLen);
+ if (useVelocity && parsed) velocityCurve = parsed.pts;
+ }
+ } else {
+ // Fallback for compact / legacy synthetic effectors without explicit curve byte-length fields
+ const curves: [number, number][][] = [];
+ let cursor = offset;
+ while (cursor + 12 <= blob.length) {
+ const parsed = readSingleCurve(cursor, blob.length);
+ if (!parsed) break;
+ curves.push(parsed.pts);
+ cursor = parsed.nextOffset;
+ }
+
+ const enabledCurveSources = (usePressure ? 1 : 0) + (useTilt ? 1 : 0) + (useVelocity ? 1 : 0);
+ if (curves.length === 3 && enabledCurveSources < 3) {
+ if (usePressure) pressureCurve = curves[0];
+ if (useTilt) tiltCurve = curves[1];
+ if (useVelocity) velocityCurve = curves[2];
+ } else {
+ let curveIdx = 0;
+ if (usePressure && curveIdx < curves.length) {
+ pressureCurve = curves[curveIdx++];
+ }
+ if (useTilt && curveIdx < curves.length) {
+ tiltCurve = curves[curveIdx++];
+ }
+ if (useVelocity && curveIdx < curves.length) {
+ velocityCurve = curves[curveIdx++];
+ }
+ }
}
return {
@@ -410,24 +547,55 @@ export function parseCspEffector(blob: Uint8Array | null | undefined): DecodedEf
useRandom,
minValue,
maxValue,
+ pressureMin,
+ tiltMin,
+ tiltMax,
+ velocityMin,
+ randomMin,
+ invertTilt,
+ invertVelocity,
+ sourceFlags,
pressureCurve,
tiltCurve,
velocityCurve,
};
}
-function effectorToSensorConfig(eff: DecodedEffector): CspSensorConfig {
- return {
+function effectorToSensorConfig(
+ eff: DecodedEffector,
+ allowTiltAboveOne: boolean = false
+): CspSensorConfig {
+ const cfg: CspSensorConfig = {
usePressure: eff.usePressure,
- pressureMin: eff.minValue,
+ pressureMin: eff.pressureMin,
pressureCurve: eff.pressureCurve,
useTilt: eff.useTilt,
- tiltMin: eff.minValue,
+ tiltMin: eff.tiltMin,
+ tiltCurve: eff.tiltCurve,
+ invertTilt: eff.invertTilt,
useVelocity: eff.useVelocity,
- velocityMin: eff.minValue,
+ velocityMin: eff.velocityMin,
+ velocityCurve: eff.velocityCurve,
+ invertVelocity: eff.invertVelocity,
useRandom: eff.useRandom,
- randomMin: eff.minValue,
+ randomMin: eff.randomMin,
};
+ if (allowTiltAboveOne && eff.useTilt && eff.tiltMax > 1.0) {
+ cfg.tiltMax = eff.tiltMax;
+ }
+ return cfg;
+}
+
+function parseEffectorSensor(
+ raw: unknown,
+ allowTiltAboveOne: boolean = false
+): CspSensorConfig | undefined {
+ if (!(raw instanceof Uint8Array)) return undefined;
+ const eff = parseCspEffector(raw);
+ if (eff && (eff.usePressure || eff.useTilt || eff.useVelocity || eff.useRandom)) {
+ return effectorToSensorConfig(eff, allowTiltAboveOne);
+ }
+ return undefined;
}
/**
@@ -438,13 +606,49 @@ export function evaluateCspSpline(x: number, pts?: [number, number][]): number {
return evaluateFastSpline(x, pts);
}
+export interface BrushTipProcessHints {
+ width?: number;
+ height?: number;
+ expressionColor?: CspExpressionColor;
+ hasSubColor?: boolean;
+ fromNativeLayer?: boolean;
+}
+
/**
- * Normalizes brush tip alpha and transparency.
+ * Normalizes brush tip alpha and transparency while preserving full-resolution
+ * Rust-decoded `data/*.layer` 2-channel monochrome/gray and full-color semantics.
*/
export async function processBrushTipImage(
dataUrl: string,
- fallbackProcedural?: { hardness: number; thickness: number; antiAlias: number }
-): Promise<{ dataUrl: string; width: number; height: number; isColor: boolean }> {
+ fallbackProcedural?: { hardness: number; thickness: number; antiAlias: number },
+ hints?: BrushTipProcessHints
+): Promise<{ dataUrl: string; width: number; height: number; isColor: boolean; isDualToneTip: boolean }> {
+ // Fast lossless path: Rust already decoded full-resolution `data/*.layer` RGBA8 with exact
+ // expression color & 2-channel semantics (alpha = opacity, gray = Main/Sub blend).
+ if (hints?.fromNativeLayer && hints.width && hints.height) {
+ const isColor = hints.expressionColor === 'color';
+ const isDualToneTip = !isColor && Boolean(hints.hasSubColor);
+ return {
+ dataUrl,
+ width: hints.width,
+ height: hints.height,
+ isColor,
+ isDualToneTip,
+ };
+ }
+
+ // Headless / Node environment fallback (e.g., vitest without DOM Image loader)
+ if (typeof Image === 'undefined') {
+ const isColor = hints?.expressionColor === 'color';
+ return {
+ dataUrl,
+ width: hints?.width || 64,
+ height: hints?.height || 64,
+ isColor,
+ isDualToneTip: !isColor && Boolean(hints?.hasSubColor),
+ };
+ }
+
return new Promise((resolve) => {
const img = new Image();
img.crossOrigin = 'anonymous';
@@ -459,19 +663,36 @@ export async function processBrushTipImage(
fallbackProcedural.thickness,
fallbackProcedural.antiAlias
);
- resolve({ dataUrl: proc.dataUrl, width: proc.width, height: proc.height, isColor: false });
+ resolve({
+ dataUrl: proc.dataUrl,
+ width: proc.width,
+ height: proc.height,
+ isColor: false,
+ isDualToneTip: false,
+ });
} else {
- resolve({ dataUrl, width: 64, height: 64, isColor: false });
+ resolve({ dataUrl, width: 64, height: 64, isColor: false, isDualToneTip: false });
}
return;
}
+ if (hints?.expressionColor === 'color') {
+ resolve({ dataUrl, width: w, height: h, isColor: true, isDualToneTip: false });
+ return;
+ }
+
const canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext('2d');
if (!ctx) {
- resolve({ dataUrl, width: w, height: h, isColor: false });
+ resolve({
+ dataUrl,
+ width: w,
+ height: h,
+ isColor: false,
+ isDualToneTip: Boolean(hints?.hasSubColor),
+ });
return;
}
@@ -483,6 +704,9 @@ export async function processBrushTipImage(
let hasColor = false;
let maxAlpha = 0;
let nonZeroCount = 0;
+ let opaqueCount = 0;
+ let darkCount = 0;
+ let lightCount = 0;
for (let i = 0; i < data.length; i += 4) {
const a = data[i + 3];
@@ -491,11 +715,15 @@ export async function processBrushTipImage(
if (a < 240) {
hasAlpha = true;
}
- if (a > 20) {
+ if (a >= 16) {
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];
- if (Math.abs(r - g) > 20 || Math.abs(g - b) > 20 || Math.abs(r - b) > 20) {
+ opaqueCount++;
+ const lum = (77 * r + 150 * g + 29 * b) >> 8;
+ if (lum <= 120) darkCount++;
+ if (lum >= 160) lightCount++;
+ if (a > 20 && (Math.abs(r - g) > 20 || Math.abs(g - b) > 20 || Math.abs(r - b) > 20)) {
hasColor = true;
}
}
@@ -507,11 +735,24 @@ export async function processBrushTipImage(
fallbackProcedural?.thickness ?? 1.0,
fallbackProcedural?.antiAlias ?? 2
);
- resolve({ dataUrl: proc.dataUrl, width: proc.width, height: proc.height, isColor: false });
+ resolve({
+ dataUrl: proc.dataUrl,
+ width: proc.width,
+ height: proc.height,
+ isColor: false,
+ isDualToneTip: false,
+ });
return;
}
- if (!hasAlpha) {
+ const minSig = Math.max(1, Math.floor(opaqueCount / 500));
+ const detectedDualTone =
+ Boolean(hints?.hasSubColor) ||
+ (hasAlpha && opaqueCount > 0 && darkCount >= minSig && lightCount >= minSig);
+
+ if (hasColor) {
+ resolve({ dataUrl, width: w, height: h, isColor: true, isDualToneTip: false });
+ } else if (!hasAlpha) {
for (let i = 0; i < data.length; i += 4) {
const lum = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
const alpha = Math.max(0, Math.min(255, Math.round(255 - lum)));
@@ -521,17 +762,30 @@ export async function processBrushTipImage(
data[i + 3] = alpha;
}
ctx.putImageData(imgData, 0, 0);
- resolve({ dataUrl: canvas.toDataURL('image/png'), width: w, height: h, isColor: false });
- } else if (!hasColor) {
+ resolve({
+ dataUrl: canvas.toDataURL('image/png'),
+ width: w,
+ height: h,
+ isColor: false,
+ isDualToneTip: false,
+ });
+ } else if (detectedDualTone) {
+ // Preserve exact 2-channel monochrome/gray semantics (alpha = opacity, gray = Main/Sub blend)
+ resolve({ dataUrl, width: w, height: h, isColor: false, isDualToneTip: true });
+ } else {
for (let i = 0; i < data.length; i += 4) {
data[i] = 255;
data[i + 1] = 255;
data[i + 2] = 255;
}
ctx.putImageData(imgData, 0, 0);
- resolve({ dataUrl: canvas.toDataURL('image/png'), width: w, height: h, isColor: false });
- } else {
- resolve({ dataUrl, width: w, height: h, isColor: true });
+ resolve({
+ dataUrl: canvas.toDataURL('image/png'),
+ width: w,
+ height: h,
+ isColor: false,
+ isDualToneTip: false,
+ });
}
};
@@ -542,9 +796,15 @@ export async function processBrushTipImage(
fallbackProcedural.thickness,
fallbackProcedural.antiAlias
);
- resolve({ dataUrl: proc.dataUrl, width: proc.width, height: proc.height, isColor: false });
+ resolve({
+ dataUrl: proc.dataUrl,
+ width: proc.width,
+ height: proc.height,
+ isColor: false,
+ isDualToneTip: false,
+ });
} else {
- resolve({ dataUrl, width: 64, height: 64, isColor: false });
+ resolve({ dataUrl, width: 64, height: 64, isColor: false, isDualToneTip: false });
}
};
@@ -702,15 +962,597 @@ export function parseCspInOutTarget(blob: Uint8Array | null | undefined): Decode
}
function mapTextureMode(val: unknown): CspPaperTextureMode {
+ if (typeof val === 'string') {
+ const s = val.trim().toLowerCase();
+ if (
+ s === 'normal' ||
+ s === 'multiply' ||
+ s === 'subtract' ||
+ s === 'compare' ||
+ s === 'overlay' ||
+ s === 'color-burn' ||
+ s === 'linear-burn' ||
+ s === 'height' ||
+ s === 'outline'
+ ) {
+ return s;
+ }
+ }
const n = Number(val);
// CSP TextureCompositeMode: 0=Normal, 1=Multiply, 2=Subtract, 3=Compare density,
// 4=Overlay, 5=Color burn, 6=Linear burn, 7=Height, 8=Outline
- if (n === 0 || n === 1 || n === 5 || n === 6) return 'multiply';
- if (n === 2) return 'subtract';
- if (n === 3 || n === 7) return 'compare';
- if (n === 4) return 'overlay';
- if (n === 8) return 'outline';
- return 'multiply';
+ switch (n) {
+ case 0:
+ return 'normal';
+ case 1:
+ return 'multiply';
+ case 2:
+ return 'subtract';
+ case 3:
+ return 'compare';
+ case 4:
+ return 'overlay';
+ case 5:
+ return 'color-burn';
+ case 6:
+ return 'linear-burn';
+ case 7:
+ return 'height';
+ case 8:
+ return 'outline';
+ default:
+ return 'multiply';
+ }
+}
+
+function mapTexturePosition(val: unknown): GrainMappingMode | undefined {
+ if (typeof val === 'string') {
+ const s = val.trim().toLowerCase();
+ if (
+ s === 'canvas-locked' ||
+ s === 'brush-aligned' ||
+ s === 'stroke-flow' ||
+ s === 'random-per-stroke'
+ ) {
+ return s;
+ }
+ }
+ const n = Number(val);
+ if (!Number.isFinite(n)) return undefined;
+ switch (n) {
+ case 0:
+ return 'canvas-locked';
+ case 1:
+ return 'brush-aligned';
+ case 2:
+ return 'stroke-flow';
+ case 3:
+ return 'random-per-stroke';
+ default:
+ return 'canvas-locked';
+ }
+}
+
+/**
+ * Decodes CSP BrushSize accurately using BrushSizeUnit / BrushSizeSpecifiedByScreen
+ * without corrupting large pixel brushes (e.g., 300px airbrush -> 300px, max 2000px).
+ * Legacy tenth-pixel values (> 2000px or explicit tenth-pixel unit) are scaled cleanly.
+ */
+export function decodeCspBrushSize(
+ rawSize: number,
+ rawUnit?: unknown,
+ _rawSpecifiedByScreen?: unknown
+): number {
+ if (!Number.isFinite(rawSize) || rawSize <= 0) return 16;
+
+ // Explicit tenth-pixel unit indicator (if present)
+ if (rawUnit === 'tenth-px' || rawUnit === 10) {
+ return Math.max(0.5, Math.min(2000, rawSize / 10));
+ }
+
+ // Standard CSP BrushSizeUnit (0=px, 1=mm, 2=cm, 3=in, 4=pt, 5=Q) stores BrushSize in pixels (0.5..2000).
+ // Values strictly above CSP's 2000px ceiling originate from legacy tenth-pixel / hundredth-pixel encoders.
+ if (rawSize > 20000) {
+ return Math.max(0.5, Math.min(2000, rawSize / 100));
+ }
+ if (rawSize > 2000) {
+ return Math.max(0.5, Math.min(2000, rawSize / 10));
+ }
+ return Math.max(0.5, Math.min(2000, rawSize));
+}
+
+/**
+ * Decodes CSP BrushCombineMode (brush blending mode against the layer) cleanly,
+ * completely distinct from within-stroke BlendBrushTips.
+ */
+export function mapCspBrushCombineMode(val: unknown): CspBrushCombineMode | undefined {
+ if (val === null || val === undefined) return undefined;
+ if (typeof val === 'string') {
+ const s = val.trim().toLowerCase();
+ const validStrings: CspBrushCombineMode[] = [
+ 'normal',
+ 'darken',
+ 'multiply',
+ 'color-burn',
+ 'linear-burn',
+ 'subtract',
+ 'darker-color',
+ 'lighten',
+ 'screen',
+ 'color-dodge',
+ 'color-dodge-glow',
+ 'add',
+ 'add-glow',
+ 'lighter-color',
+ 'overlay',
+ 'soft-light',
+ 'hard-light',
+ 'vivid-light',
+ 'linear-light',
+ 'pin-light',
+ 'hard-mix',
+ 'difference',
+ 'exclusion',
+ 'hue',
+ 'saturation',
+ 'color',
+ 'luminosity',
+ 'pass-through',
+ 'divide',
+ 'behind',
+ 'clear',
+ 'compare-density',
+ ];
+ if ((validStrings as string[]).includes(s)) {
+ return s as CspBrushCombineMode;
+ }
+ if (s === 'glow-dodge') return 'color-dodge-glow';
+ }
+ const n = Number(val);
+ if (!Number.isFinite(n)) return undefined;
+ switch (n) {
+ case 0:
+ return 'normal';
+ case 1:
+ return 'darken';
+ case 2:
+ return 'multiply';
+ case 3:
+ return 'color-burn';
+ case 4:
+ return 'linear-burn';
+ case 5:
+ return 'subtract';
+ case 6:
+ return 'darker-color';
+ case 7:
+ return 'lighten';
+ case 8:
+ return 'screen';
+ case 9:
+ return 'color-dodge';
+ case 10:
+ return 'color-dodge-glow';
+ case 11:
+ return 'add';
+ case 12:
+ return 'add-glow';
+ case 13:
+ return 'lighter-color';
+ case 14:
+ return 'overlay';
+ case 15:
+ return 'soft-light';
+ case 16:
+ return 'hard-light';
+ case 17:
+ return 'vivid-light';
+ case 18:
+ return 'linear-light';
+ case 19:
+ return 'pin-light';
+ case 20:
+ return '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 27:
+ case 32:
+ return 'behind';
+ case 28:
+ case 33:
+ return 'clear';
+ case 29:
+ case 31:
+ return 'compare-density';
+ case 30:
+ return 'pass-through';
+ case 36:
+ return 'divide';
+ default:
+ return 'normal';
+ }
+}
+
+function mapBlendTipsMode(val: unknown): CspBlendTipsMode {
+ if (typeof val === 'string') {
+ const s = val.trim().toLowerCase();
+ if (s === 'normal' || s === 'darken' || s === 'compare') return s;
+ }
+ if (typeof val === 'boolean') {
+ return val ? 'compare' : 'normal';
+ }
+ const n = Number(val);
+ if (n === 0) return 'normal';
+ if (n === 1) return 'compare';
+ if (n === 2) return 'darken';
+ return 'darken';
+}
+
+function mapPatternOrderType(val: unknown): CspSubTipOrder | undefined {
+ if (val === null || val === undefined) return undefined;
+ if (typeof val === 'string') {
+ const s = val.trim().toLowerCase();
+ if (
+ s === 'sequential' ||
+ s === 'reverse' ||
+ s === 'random' ||
+ s === 'random-no-repeat' ||
+ s === 'once' ||
+ s === 'direction'
+ ) {
+ return s;
+ }
+ }
+ const n = Number(val);
+ if (!Number.isFinite(n)) return undefined;
+ switch (n) {
+ case 0:
+ return 'sequential';
+ case 1:
+ return 'reverse';
+ case 2:
+ return 'once';
+ case 3:
+ return 'random';
+ case 4:
+ return 'random-no-repeat';
+ case 5:
+ return 'direction';
+ default:
+ return 'sequential';
+ }
+}
+
+/**
+ * Decodes CSP BrushHardness, distinguishing discrete 1..5 hardness levels
+ * (1=0.2 .. 5=1.0) from 0..100% continuous values and already-normalized 0..1 values.
+ */
+export function decodeCspHardness(rawHardness: number, rawHardnessMode?: unknown): number {
+ if (!Number.isFinite(rawHardness)) return 1.0;
+ if (rawHardness <= 0) return 0.05;
+ if (rawHardness < 1) {
+ return Math.max(0.05, Math.min(1.0, rawHardness));
+ }
+ const forcePercent = rawHardnessMode === 100 || rawHardnessMode === 'percent';
+ if (!forcePercent && Number.isInteger(rawHardness) && rawHardness >= 1 && rawHardness <= 5) {
+ return Math.max(0.05, Math.min(1.0, rawHardness / 5));
+ }
+ return Math.max(0.05, Math.min(1.0, rawHardness / 100));
+}
+
+/**
+ * Normalizes CSP wet edge alpha/value power from 0..100 (or legacy 0..1) into 0..1.
+ */
+export function normalizeWetEdgePower(val: number): number {
+ if (!Number.isFinite(val) || val <= 0) return 0;
+ if (val > 0 && val < 1) return clamp01(val);
+ return clamp01(val / 100);
+}
+
+function normalizePercent01(raw: unknown): number | undefined {
+ if (typeof raw !== 'number' || !Number.isFinite(raw) || raw < 0) return undefined;
+ if (raw === 0) return 0;
+ if (raw > 0 && raw < 1) return clamp01(raw);
+ return clamp01(raw / 100);
+}
+
+function parseRotationEffector(rawRotEff: unknown): {
+ mode?: CspAngleDynamicsMode;
+ sensor?: CspSensorConfig;
+ usesTilt: boolean;
+} {
+ if (rawRotEff instanceof Uint8Array) {
+ const eff = parseCspEffector(rawRotEff);
+ if (!eff) return { usesTilt: false };
+ const flags = eff.sourceFlags;
+ const sensor =
+ eff.usePressure || eff.useTilt || eff.useVelocity || eff.useRandom || Boolean(flags & 0x02)
+ ? effectorToSensorConfig(eff)
+ : undefined;
+
+ let mode: CspAngleDynamicsMode = 'none';
+ if (eff.useVelocity && eff.useRandom) {
+ mode = 'direction-random';
+ } else if (flags & 0x02) {
+ mode = 'initial-direction';
+ } else if (eff.useTilt) {
+ mode = 'tilt';
+ } else if (eff.useVelocity) {
+ mode = 'direction';
+ } else if (eff.useRandom) {
+ mode = 'random';
+ }
+ return { mode, sensor, usesTilt: mode === 'tilt' || eff.useTilt };
+ }
+
+ if (typeof rawRotEff === 'number' && Number.isFinite(rawRotEff)) {
+ const rotMode = rawRotEff & 0x0f;
+ // Authentic CSP Variant.BrushRotationEffector integer encoding:
+ // Low nibble is 0x03; upper bits select the angle dynamics source:
+ // 3 (0x03) = None (fixed angle)
+ // 19 (0x13) = Direction of pen (Tilt)
+ // 35 (0x23) = Rotation of pen axis (Barrel Twist)
+ // 67 (0x43) = Direction of line
+ // 131 (0x83) = Random
+ // 195 (0xc3) = Direction of line + Random
+ // 259 (0x103) = Initial direction
+ if (rotMode === 3) {
+ if ((rawRotEff & 0x40) && (rawRotEff & 0x80)) {
+ return { mode: 'direction-random', usesTilt: false };
+ }
+ if (rawRotEff & 0x100) {
+ return { mode: 'initial-direction', usesTilt: false };
+ }
+ if (rawRotEff & 0x40) {
+ return { mode: 'direction', usesTilt: false };
+ }
+ if (rawRotEff & 0x80) {
+ return { mode: 'random', usesTilt: false };
+ }
+ if (rawRotEff & 0x20) {
+ return { mode: 'twist', usesTilt: false };
+ }
+ if (rawRotEff & 0x10) {
+ return { mode: 'tilt', usesTilt: true };
+ }
+ return { mode: 'none', usesTilt: false };
+ }
+ if (rotMode === 2) {
+ return { mode: 'tilt', usesTilt: true };
+ }
+ if (rotMode === 4) {
+ return { mode: 'random', usesTilt: false };
+ }
+ if (rotMode === 5) {
+ return { mode: 'twist', usesTilt: false };
+ }
+ if (rotMode === 6) {
+ return { mode: 'initial-direction', usesTilt: false };
+ }
+ if (rotMode === 7) {
+ return { mode: 'direction-random', usesTilt: false };
+ }
+ if (rotMode === 1) {
+ return { mode: 'none', usesTilt: false };
+ }
+ // rotMode === 0: inspect higher flag bits
+ if ((rawRotEff & 0x40) && (rawRotEff & 0x80)) {
+ return { mode: 'direction-random', usesTilt: false };
+ }
+ if (rawRotEff & 0x100) {
+ return { mode: 'initial-direction', usesTilt: false };
+ }
+ if (rawRotEff & 0x40) {
+ return { mode: 'direction', usesTilt: false };
+ }
+ if (rawRotEff & 0x80) {
+ return { mode: 'random', usesTilt: false };
+ }
+ if (rawRotEff & 0x20) {
+ return { mode: 'twist', usesTilt: false };
+ }
+ if (rawRotEff & 0x10) {
+ return { mode: 'tilt', usesTilt: true };
+ }
+ if (rawRotEff & 0x02) {
+ return { mode: 'initial-direction', usesTilt: false };
+ }
+ if (rawRotEff & 0x01) {
+ return { mode: 'random', usesTilt: false };
+ }
+ return { mode: 'none', usesTilt: false };
+ }
+
+ return { usesTilt: false };
+}
+
+function mapDualBrushCompositeMode(val: unknown): string {
+ if (typeof val === 'string' && val.trim().length > 0) {
+ return val.trim().toLowerCase();
+ }
+ const dm = Number(val);
+ if (!Number.isFinite(dm)) return 'multiply';
+ switch (dm) {
+ case 0:
+ return 'multiply';
+ case 1:
+ return 'subtract';
+ case 2:
+ return 'darken';
+ case 3:
+ return 'lighten';
+ case 4:
+ return 'screen';
+ case 5:
+ return 'color-burn';
+ case 6:
+ return 'linear-burn';
+ case 7:
+ return 'color-dodge';
+ case 8:
+ return 'color-dodge-glow';
+ case 9:
+ return 'add';
+ case 10:
+ return 'add-glow';
+ case 11:
+ return 'overlay';
+ case 12:
+ return 'soft-light';
+ case 13:
+ return 'hard-light';
+ case 14:
+ return 'vivid-light';
+ case 15:
+ return 'linear-light';
+ case 16:
+ return 'pin-light';
+ case 17:
+ return 'hard-mix';
+ case 18:
+ return 'difference';
+ case 19:
+ return 'exclusion';
+ case 20:
+ return 'darker-color';
+ case 21:
+ return 'lighter-color';
+ case 22:
+ return 'divide';
+ case 23:
+ return 'hue';
+ case 24:
+ return 'saturation';
+ case 25:
+ return 'color';
+ case 26:
+ return 'luminosity';
+ case 27:
+ return 'normal';
+ case 28:
+ return 'height';
+ case 29:
+ return 'compare-density';
+ default:
+ return 'multiply';
+ }
+}
+
+function decodeAutoOrFixedSpacing(rawAutoInterval: unknown, rawSpacing: unknown): number | undefined {
+ if (typeof rawAutoInterval === 'number' && rawAutoInterval > 0) {
+ if (rawAutoInterval === 1) return 0.04;
+ if (rawAutoInterval === 2) return 0.1;
+ if (rawAutoInterval === 3) return 0.22;
+ }
+ if (typeof rawSpacing === 'number' && rawSpacing > 0) {
+ // In CSP, BrushInterval in Fixed mode is ALWAYS a percentage (0.1%..200% -> 0.001..2.0)
+ return Math.max(0.003, Math.min(2.0, rawSpacing / 100));
+ }
+ return undefined;
+}
+
+function parseSprayConfig(
+ getVal: (aliases: string[]) => any,
+ prefix: '' | 'Dual' = ''
+): CspSpraySettings | undefined {
+ const p = prefix;
+ const rawSpray = getVal(
+ p ? [`${p}BrushUseSpray`, `${p}UseSpray`] : ['BrushUseSpray', 'UseSpray']
+ );
+ if (!Boolean(rawSpray)) return undefined;
+
+ const rawSpraySize = getVal(
+ p ? [`${p}BrushSpraySize`, `${p}SpraySize`] : ['BrushSpraySize', 'SpraySize']
+ );
+ const rawSprayDensity = getVal(
+ p ? [`${p}BrushSprayDensity`, `${p}SprayDensity`] : ['BrushSprayDensity', 'SprayDensity']
+ );
+ const rawSprayBias = getVal(
+ p ? [`${p}BrushSprayBias`, `${p}SprayBias`] : ['BrushSprayBias', 'SprayBias']
+ );
+ const rawDeviation = getVal(
+ p ? [`${p}BrushSprayDeviation`, `${p}SprayDeviation`] : ['BrushSprayDeviation', 'SprayDeviation']
+ );
+ const rawParticleSize = getVal(
+ p
+ ? [`${p}BrushSprayParticleSize`, `${p}SprayParticleSize`]
+ : ['BrushSprayParticleSize', 'SprayParticleSize']
+ );
+ const rawLinkSize = getVal(
+ p ? [`${p}BrushSprayLinkSize`, `${p}SprayLinkSize`] : ['BrushSprayLinkSize', 'SprayLinkSize']
+ );
+ const rawSizeEff = getVal(
+ p
+ ? [`${p}BrushSpraySizeEffector`, `${p}SpraySizeEffector`]
+ : ['BrushSpraySizeEffector', 'SpraySizeEffector']
+ );
+ const rawDensityEff = getVal(
+ p
+ ? [`${p}BrushSprayDensityEffector`, `${p}SprayDensityEffector`]
+ : ['BrushSprayDensityEffector', 'SprayDensityEffector']
+ );
+ const rawDir = getVal(
+ p ? [`${p}BrushSprayDirection`, `${p}SprayDirection`] : ['BrushSprayDirection', 'SprayDirection']
+ );
+ const rawDirEff = getVal(
+ p
+ ? [`${p}BrushSprayDirectionEffector`, `${p}SprayDirectionEffector`]
+ : ['BrushSprayDirectionEffector', 'SprayDirectionEffector']
+ );
+
+ const deviation =
+ typeof rawDeviation === 'number' && Number.isFinite(rawDeviation)
+ ? Math.max(-1, Math.min(1, rawDeviation / 100))
+ : undefined;
+ const bias =
+ typeof rawSprayBias === 'number' && Number.isFinite(rawSprayBias)
+ ? Math.max(-1, Math.min(1, rawSprayBias / 100))
+ : (deviation ?? 0);
+
+ const dirDecoded = parseRotationEffector(rawDirEff);
+
+ const spray: CspSpraySettings = {
+ enabled: true,
+ size: typeof rawSpraySize === 'number' && rawSpraySize > 0 ? Math.max(1, rawSpraySize) : 2.0,
+ density:
+ typeof rawSprayDensity === 'number' && rawSprayDensity > 0
+ ? Math.max(1, Math.min(50, rawSprayDensity))
+ : 5,
+ bias,
+ };
+ if (typeof rawParticleSize === 'number' && rawParticleSize > 0) {
+ spray.particleSize = decodeCspBrushSize(rawParticleSize);
+ }
+ if (rawLinkSize !== null) {
+ spray.linkSize = Boolean(rawLinkSize);
+ }
+ const sizeSensor = parseEffectorSensor(rawSizeEff, true);
+ if (sizeSensor) spray.sizeSensor = sizeSensor;
+ const densitySensor = parseEffectorSensor(rawDensityEff, true);
+ if (densitySensor) spray.densitySensor = densitySensor;
+ if (typeof rawDir === 'number' && Number.isFinite(rawDir)) {
+ spray.direction = ((rawDir % 360) + 360) % 360;
+ }
+ if (dirDecoded.mode && dirDecoded.mode !== 'none') {
+ spray.directionDynamics = dirDecoded.mode;
+ }
+ if (dirDecoded.sensor) {
+ spray.directionSensor = dirDecoded.sensor;
+ }
+ if (deviation !== undefined) {
+ spray.deviation = deviation;
+ }
+ return spray;
}
/**
@@ -740,19 +1582,25 @@ export async function parseSutExtractedData(
let brushName = extracted.nodeName || fileName.replace(/\.sut$/i, '').trim();
let brushSize = 16;
+ let brushSizeUnit: number | undefined = undefined;
+ let brushSizeSpecifiedByScreen: boolean | undefined = undefined;
let minSizeFactor = 0.2;
let opacity = 1.0;
let flow = 0.85;
let adjustDensityByGap = false;
let blendTipsMode: CspBlendTipsMode = 'darken';
+ let brushCombineMode: CspBrushCombineMode | undefined = undefined;
let spacing = 0.08;
let hardness = 1.0;
let thickness = 1.0;
let thicknessVertical = false;
+ let thicknessSensor: CspSensorConfig | undefined = undefined;
+ let subTipOrder: CspSubTipOrder | undefined = undefined;
let flipH: CspTipFlipMode = 'none';
let flipV: CspTipFlipMode = 'none';
let angle = 0;
let angleDynamics: CspAngleDynamicsMode = 'none';
+ let angleSensor: CspSensorConfig | undefined = undefined;
let rotationRandomScale = 0;
let antiAlias = 2;
let stabilization = 0;
@@ -766,620 +1614,1165 @@ export async function parseSutExtractedData(
let sizeSensor: CspSensorConfig | undefined = undefined;
let opacitySensor: CspSensorConfig | undefined = undefined;
let densitySensor: CspSensorConfig | undefined = undefined;
+ let intervalSensor: CspSensorConfig | undefined = undefined;
+ let textureDensitySensor: CspSensorConfig | undefined = undefined;
let colorMixing = false;
let perceptualMixing = false;
let amountOfPaint = 0.7;
let densityOfPaint = 0.8;
let colorStretch = 0.6;
+ let amountOfPaintSensor: CspSensorConfig | undefined = undefined;
+ let densityOfPaintSensor: CspSensorConfig | undefined = undefined;
+ let colorStretchSensor: CspSensorConfig | undefined = undefined;
+ let mixGroundColor: boolean | undefined = undefined;
+ let useBlur: boolean | undefined = undefined;
+ let blurStrength: number | undefined = undefined;
let mixingMode: 'blend' | 'running_color' | 'smear' = 'blend';
let wetEdge = 0;
let wetEdgeRadius = 3.0;
- let wetEdgeAlphaPower = 20;
+ let wetEdgeAlphaPower = 0.2;
let wetEdgeValuePower = 0;
let textureDensity = 0;
+ let grainMappingMode: GrainMappingMode | undefined = undefined;
let paperTextureScale = 1.0;
let paperTextureRotate = 0;
+ let paperTextureOffsetX: number | undefined = undefined;
+ let paperTextureOffsetY: number | undefined = undefined;
let paperTextureMode: CspPaperTextureMode = 'multiply';
let paperTextureBrightness = 0;
let paperTextureContrast = 0;
let paperTextureApplyEachPlot = false;
+ let paperTextureEmphasizeDensity = false;
let paperTextureInverted = false;
let spray: CspSpraySettings | undefined = undefined;
let taper: CspTaperSettings | undefined = undefined;
+ let dynamics: BrushDynamics | undefined = undefined;
let isRibbon = false;
let dualBrush = false;
let dualBrushCompositeMode = 'multiply';
+ let dualSize: number | undefined = undefined;
+ let dualLinkSize: boolean | undefined = undefined;
+ let dualSpacing: number | undefined = undefined;
+ let dualThickness: number | undefined = undefined;
+ let dualThicknessVertical: boolean | undefined = undefined;
+ let dualAngle: number | undefined = undefined;
+ let dualAngleDynamics: CspAngleDynamicsMode | undefined = undefined;
+ let dualAngleSensor: CspSensorConfig | undefined = undefined;
+ let dualHardness: number | undefined = undefined;
+ let dualDensity: number | undefined = undefined;
+ let dualSubTipOrder: CspSubTipOrder | undefined = undefined;
+ let dualFlipH: CspTipFlipMode | undefined = undefined;
+ let dualFlipV: CspTipFlipMode | undefined = undefined;
+ let dualSpray: CspSpraySettings | undefined = undefined;
+ let dualIsRibbon: boolean | undefined = undefined;
let usePatternImage: boolean | null = null;
let rawPatternArrayBlob: Uint8Array | null = null;
let rawTextureImageBlob: Uint8Array | null = null;
let rawDualPatternBlob: Uint8Array | null = null;
+ const importWarnings: string[] = [];
+
+ 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;
+ };
if (extracted.variantValues.size > 0) {
- try {
+ // Detect unsupported non-brush CSP sub-tools (e.g., Liquify, Fill, Gradient, Selection, Ruler, Text)
+ const nonBrushCategories: Array<{ label: string; keys: string[] }> = [
{
- 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;
- };
-
- // Size
- const rawSize = getVal(['BrushSize', 'Size', 'PenSize', 'BrushSizeVal', 'LineWidth']);
- if (typeof rawSize === 'number' && rawSize > 0) {
- if (rawSize > 500) {
- brushSize = Math.max(1, Math.min(500, rawSize / 100));
- } else if (rawSize > 250) {
- brushSize = Math.max(1, Math.min(500, rawSize / 10));
- } else {
- brushSize = Math.max(0.5, Math.min(500, rawSize));
- }
- }
+ label: 'Liquify',
+ keys: ['liquifymode', 'liquifystrength', 'liquifysize', 'liquifyhardness', 'liquifydirection'],
+ },
+ {
+ label: 'Fill',
+ keys: ['fillclosegap', 'fillareascale', 'fillreferlayer', 'filltolerance'],
+ },
+ {
+ label: 'Gradient',
+ keys: ['gradationnode', 'gradationedgeprocess', 'gradationshape'],
+ },
+ {
+ label: 'Selection',
+ keys: ['selectionaddtype', 'selectionareamode'],
+ },
+ {
+ label: 'Text',
+ keys: ['textfontsize', 'textfontname', 'textwritingmode'],
+ },
+ {
+ label: 'Ruler',
+ keys: ['rulertype', 'perspectiverulertype', 'symmetryrulerlines'],
+ },
+ ];
+ const hasCoreBrushParam =
+ extracted.variantValues.has('brushsize') ||
+ extracted.variantValues.has('brushdensity') ||
+ extracted.variantValues.has('brushinterval') ||
+ extracted.variantValues.has('brushhardness');
+
+ for (const cat of nonBrushCategories) {
+ const matched = cat.keys.some((k) => {
+ const v = extracted.variantValues.get(k);
+ return v !== undefined && v !== null;
+ });
+ if (matched && (cat.label === 'Liquify' || !hasCoreBrushParam)) {
+ importWarnings.push(
+ `Unsupported CSP non-brush sub-tool detected (${cat.label}): imported with fallback brush parameters.`
+ );
+ break;
+ }
+ }
- // Size Dynamics Effector
- const sizeEffBlob = getVal(['BrushSizeEffector', 'SizeEffector']);
- if (sizeEffBlob instanceof Uint8Array) {
- const eff = parseCspEffector(sizeEffBlob);
- if (eff) {
- usePressure = eff.usePressure;
- useVelocity = eff.useVelocity;
- useTilt = eff.useTilt;
- minSizeFactor = eff.minValue;
- pressureCurve = eff.pressureCurve;
- velocityCurve = eff.velocityCurve;
- sizeSensor = effectorToSensorConfig(eff);
- }
- }
+ try {
+ // Size (honoring BrushSizeUnit and BrushSizeSpecifiedByScreen)
+ const rawSizeUnit = getVal(['BrushSizeUnit', 'SizeUnit']);
+ if (typeof rawSizeUnit === 'number' && Number.isFinite(rawSizeUnit)) {
+ brushSizeUnit = Math.round(rawSizeUnit);
+ }
+ const rawSizeByScreen = getVal(['BrushSizeSpecifiedByScreen', 'SizeSpecifiedByScreen']);
+ if (rawSizeByScreen !== null) {
+ brushSizeSpecifiedByScreen = Boolean(rawSizeByScreen);
+ }
+ const rawSize = getVal(['BrushSize', 'Size', 'PenSize', 'BrushSizeVal', 'LineWidth']);
+ if (typeof rawSize === 'number' && rawSize > 0) {
+ brushSize = decodeCspBrushSize(rawSize, rawSizeUnit, rawSizeByScreen);
+ }
- // Opacity & Density Effectors
- const opacityEffBlob = getVal(['OpacityEffector', 'BrushOpacityEffector']);
- if (opacityEffBlob instanceof Uint8Array) {
- const eff = parseCspEffector(opacityEffBlob);
- if (eff && (eff.usePressure || eff.useTilt || eff.useVelocity || eff.useRandom)) {
- opacitySensor = effectorToSensorConfig(eff);
- }
- }
+ // Size Dynamics Effector
+ const sizeEffBlob = getVal(['BrushSizeEffector', 'SizeEffector']);
+ if (sizeEffBlob instanceof Uint8Array) {
+ const eff = parseCspEffector(sizeEffBlob);
+ if (eff) {
+ usePressure = eff.usePressure;
+ useVelocity = eff.useVelocity;
+ useTilt = eff.useTilt;
+ minSizeFactor = eff.minValue;
+ pressureCurve = eff.pressureCurve;
+ velocityCurve = eff.velocityCurve;
+ sizeSensor = effectorToSensorConfig(eff, true);
+ }
+ }
- const densityEffBlob = getVal(['BrushDensityEffector', 'BrushFlowEffector', 'DensityEffector']);
- if (densityEffBlob instanceof Uint8Array) {
- const eff = parseCspEffector(densityEffBlob);
- if (eff && (eff.usePressure || eff.useTilt || eff.useVelocity || eff.useRandom)) {
- densitySensor = effectorToSensorConfig(eff);
- }
- }
+ // Opacity, Density, Interval, Texture Density, Thickness Effectors
+ opacitySensor = parseEffectorSensor(getVal(['OpacityEffector', 'BrushOpacityEffector']), true);
+ densitySensor = parseEffectorSensor(
+ getVal(['BrushDensityEffector', 'BrushFlowEffector', 'DensityEffector']),
+ true
+ );
+ intervalSensor = parseEffectorSensor(getVal(['BrushIntervalEffector', 'IntervalEffector']), true);
+ textureDensitySensor = parseEffectorSensor(getVal(['TextureDensityEffector']), true);
+ thicknessSensor = parseEffectorSensor(getVal(['BrushThicknessEffector', 'ThicknessEffector']), true);
+ if (
+ opacitySensor?.useTilt ||
+ densitySensor?.useTilt ||
+ intervalSensor?.useTilt ||
+ textureDensitySensor?.useTilt ||
+ thicknessSensor?.useTilt
+ ) {
+ useTilt = true;
+ }
- // Spacing / Interval (CSP BrushAutoIntervalType: 0=Fixed %, 1=Wide, 2=Normal, 3=Narrow)
- const rawAutoInterval = getVal(['BrushAutoIntervalType']);
- const rawSpacing = getVal(['BrushInterval', 'Interval', 'Spacing', 'BrushSpacing']);
- if (typeof rawAutoInterval === 'number' && rawAutoInterval > 0) {
- if (rawAutoInterval === 1) spacing = 0.25;
- else if (rawAutoInterval === 2) spacing = 0.1;
- else if (rawAutoInterval === 3) spacing = 0.04;
- } else if (typeof rawSpacing === 'number' && rawSpacing > 0) {
- // In CSP, BrushInterval in Fixed mode is ALWAYS a percentage (0.1%..200% -> 0.001..2.0)
- spacing = Math.max(0.003, Math.min(2.0, rawSpacing / 100));
- }
+ // Spacing / Interval (CSP BrushAutoIntervalType: 0=Fixed %, 1=Narrow, 2=Normal, 3=Wide)
+ const decodedSpacing = decodeAutoOrFixedSpacing(
+ getVal(['BrushAutoIntervalType']),
+ getVal(['BrushInterval', 'Interval', 'Spacing', 'BrushSpacing'])
+ );
+ if (decodedSpacing !== undefined) {
+ spacing = decodedSpacing;
+ }
- // Opacity (strictly stroke ceiling opacity, distinct from BrushDensity!)
- const rawOpacity = getVal(['Opacity', 'BrushOpacity']);
- if (typeof rawOpacity === 'number' && rawOpacity > 0) {
- opacity = rawOpacity > 1.0 ? Math.min(1.0, rawOpacity / 100) : rawOpacity;
- }
+ // Opacity (strictly stroke ceiling opacity, distinct from BrushDensity!)
+ const rawOpacity = getVal(['Opacity', 'BrushOpacity']);
+ if (typeof rawOpacity === 'number' && rawOpacity > 0) {
+ opacity = rawOpacity > 1.0 ? Math.min(1.0, rawOpacity / 100) : rawOpacity;
+ }
- // Brush Density / Flow (per-dab alpha)
- const rawFlow = getVal(['BrushDensity', 'Density', 'BrushFlow', 'Flow', 'InkAmount']);
- if (typeof rawFlow === 'number' && rawFlow > 0) {
- flow = rawFlow > 1.0 ? Math.min(1.0, rawFlow / 100) : rawFlow;
- }
+ // Brush Density / Flow (per-dab alpha)
+ const rawFlow = getVal(['BrushDensity', 'Density', 'BrushFlow', 'Flow', 'InkAmount']);
+ if (typeof rawFlow === 'number' && rawFlow > 0) {
+ flow = rawFlow > 1.0 ? Math.min(1.0, rawFlow / 100) : rawFlow;
+ }
- const rawAdjustGap = getVal(['BrushAdjustFlowByInterval', 'BrushAdjustDensityByGap', 'AdjustDensityByGap']);
- if (rawAdjustGap !== null) {
- adjustDensityByGap = Boolean(rawAdjustGap);
- }
+ const rawAdjustGap = getVal([
+ 'BrushAdjustFlowByInterval',
+ 'BrushAdjustDensityByGap',
+ 'AdjustDensityByGap',
+ ]);
+ if (rawAdjustGap !== null) {
+ adjustDensityByGap = Boolean(rawAdjustGap);
+ }
- const rawBlendTips = getVal(['BlendBrushTips', 'BrushCombineMode', 'BrushBlendMode']);
- if (rawBlendTips !== null && Number(rawBlendTips) === 1) {
- blendTipsMode = 'compare';
- }
+ // Strictly separate BrushCombineMode (brush-against-layer blend mode) from BlendBrushTips (within-stroke dab combine)!
+ const rawCombineMode = getVal(['BrushCombineMode', 'BrushBlendMode', 'CompositeMode']);
+ if (rawCombineMode !== null) {
+ brushCombineMode = mapCspBrushCombineMode(rawCombineMode);
+ }
- // Hardness
- const rawHardness = getVal(['BrushHardness', 'Hardness']);
- if (typeof rawHardness === 'number' && rawHardness > 0) {
- hardness =
- rawHardness <= 5
- ? Math.max(0.05, Math.min(1.0, rawHardness / 5))
- : Math.max(0.05, Math.min(1.0, rawHardness / 100));
- }
+ const rawBlendTips = getVal([
+ 'BlendBrushTips',
+ 'BrushMixMode',
+ 'BrushAlphaCombine',
+ 'BrushTipCombineMode',
+ ]);
+ if (rawBlendTips !== null) {
+ blendTipsMode = mapBlendTipsMode(rawBlendTips);
+ }
- // Thickness & Flip
- const rawThickness = getVal(['BrushThickness', 'Thickness']);
- if (typeof rawThickness === 'number' && rawThickness > 0) {
- thickness = Math.max(0.05, Math.min(1.0, rawThickness / 100));
- }
- const rawVertThick = getVal(['BrushVerticalThicknes', 'BrushVerticalThickness', 'VerticalThickness']);
- if (rawVertThick !== null) {
- thicknessVertical = Boolean(rawVertThick);
- }
+ // Hardness (distinguish discrete 1..5 levels vs 0..100%)
+ const rawHardness = getVal(['BrushHardness', 'Hardness']);
+ const rawHardnessMode = getVal(['BrushHardnessUnit', 'BrushHardnessType']);
+ if (typeof rawHardness === 'number' && rawHardness >= 0) {
+ hardness = decodeCspHardness(rawHardness, rawHardnessMode);
+ }
- const rawFlipH = getVal(['BrushPatternReverseHorizontal', 'BrushFlipX', 'FlipHorizontal']);
- if (rawFlipH !== null) flipH = mapFlipMode(rawFlipH);
- const rawFlipV = getVal(['BrushPatternReverseVertical', 'BrushFlipY', 'FlipVertical']);
- if (rawFlipV !== null) flipV = mapFlipMode(rawFlipV);
+ // Sub-tip Order / Repeat
+ const rawPatternOrder = getVal(['BrushPatternOrderType', 'BrushPatternRepeatType']);
+ if (rawPatternOrder !== null) {
+ subTipOrder = mapPatternOrderType(rawPatternOrder);
+ }
- // Rotation & Rotation Dynamics
- // CSP BrushRotationEffector low nibble: 1=None, 2=Pen direction (tilt), 3=Direction of line, 4=Random, 5=Pen rotation (twist)
- const rawAngle = getVal(['BrushRotation', 'Rotation', 'BrushAngle', 'Angle']);
- if (typeof rawAngle === 'number') {
- angle = ((rawAngle % 360) + 360) % 360;
- }
+ // Thickness & Flip
+ // In CSP, BrushThickness spans 1..2000% (e.g. 17%, 51%, 135%).
+ // CSP BrushVerticalThicknes=0 ("Horizontal") scales the tip's local X axis (width),
+ // whereas BrushVerticalThicknes=1 ("Vertical") scales local Y (height).
+ // In BrushEngine, thicknessVertical=true scales X (width) and false scales Y (height).
+ const rawThickness = getVal(['BrushThickness', 'Thickness']);
+ if (typeof rawThickness === 'number' && rawThickness > 0) {
+ thickness = Math.max(0.05, Math.min(20.0, rawThickness / 100));
+ }
+ const rawVertThick = getVal([
+ 'BrushVerticalThicknes',
+ 'BrushVerticalThickness',
+ 'VerticalThickness',
+ ]);
+ if (rawVertThick !== null) {
+ thicknessVertical = !Boolean(rawVertThick);
+ } else {
+ // CSP defaults to Horizontal (BrushVerticalThicknes=0 -> scales X axis)
+ thicknessVertical = true;
+ }
- const rawRotEff = getVal(['BrushRotationEffector', 'RotationEffector', 'AngleDynamics']);
- if (typeof rawRotEff === 'number') {
- const rotMode = rawRotEff & 0x0f;
- if (rotMode === 3) {
- angleDynamics = 'direction';
- } else if (rotMode === 2) {
- angleDynamics = 'tilt';
- useTilt = true;
- } else if (rotMode === 4) {
- angleDynamics = 'random';
- } else if (rotMode === 5) {
- angleDynamics = 'twist';
- } else if (rotMode === 1) {
- angleDynamics = 'none';
- } else if (rawRotEff & 0x80) {
- angleDynamics = 'direction';
- } else if (rawRotEff & 0x20) {
- angleDynamics = 'tilt';
- useTilt = true;
- }
- }
+ const rawFlipH = getVal(['BrushPatternReverseHorizontal', 'BrushFlipX', 'FlipHorizontal']);
+ if (rawFlipH !== null) flipH = mapFlipMode(rawFlipH);
+ const rawFlipV = getVal(['BrushPatternReverseVertical', 'BrushFlipY', 'FlipVertical']);
+ if (rawFlipV !== null) flipV = mapFlipMode(rawFlipV);
- // CSP stores BrushRotationRandomScale=100 by default even when Random rotation is OFF!
- // Only apply random scale when random rotation mode is explicitly enabled.
- if (angleDynamics === 'random') {
- const rawRandRot = getVal(['BrushRotationRandomScale', 'RotationRandomScale']);
- if (typeof rawRandRot === 'number' && rawRandRot > 0) {
- rotationRandomScale = Math.min(1.0, rawRandRot / 100);
- }
- } else {
- rotationRandomScale = 0;
- }
+ // Rotation & Complete Angle Dynamics (integer bitmask OR binary Effector BLOB)
+ const rawAngle = getVal(['BrushRotation', 'Rotation', 'BrushAngle', 'Angle']);
+ if (typeof rawAngle === 'number') {
+ angle = ((rawAngle % 360) + 360) % 360;
+ }
- // CSP "Direction of line" aligns 12 o'clock (-Y) with the stroke tangent,
- // whereas Ink Studio aligns 3 o'clock (+X) with atan2(dy, dx). Offset +90 deg to match CSP exactly.
- if (angleDynamics === 'direction') {
- angle = (angle + 90) % 360;
- }
+ const rawRotEff = getVal(['BrushRotationEffector', 'RotationEffector', 'AngleDynamics']);
+ if (rawRotEff !== null) {
+ const decodedRot = parseRotationEffector(rawRotEff);
+ if (decodedRot.mode !== undefined) {
+ angleDynamics = decodedRot.mode;
+ }
+ if (decodedRot.sensor) {
+ angleSensor = decodedRot.sensor;
+ }
+ if (decodedRot.usesTilt) {
+ useTilt = true;
+ }
+ }
- // Anti-Aliasing
- const rawAA = getVal(['AntiAlias', 'BrushAntiAlias']);
- if (typeof rawAA === 'number') {
- antiAlias = Math.max(0, Math.min(3, Math.round(rawAA)));
- }
+ // CSP stores BrushRotationRandomScale=100 by default even when Random rotation is OFF!
+ // Only apply random scale when random rotation mode is explicitly enabled.
+ if (angleDynamics === 'random' || angleDynamics === 'direction-random') {
+ const rawRandRot = getVal(['BrushRotationRandomScale', 'RotationRandomScale']);
+ if (typeof rawRandRot === 'number' && rawRandRot > 0) {
+ rotationRandomScale = Math.min(1.0, rawRandRot / 100);
+ }
+ } else {
+ rotationRandomScale = 0;
+ }
- // Stabilization & Post-Correction
- const rawRev = getVal(['FlickerReduction', 'BrushStabilization']);
- if (typeof rawRev === 'number' && rawRev >= 0) {
- stabilization = Math.min(50, Math.max(0, Math.round(rawRev)));
- }
- const rawUseRev = getVal(['BrushUseRevision']);
- const rawPostCorr = getVal(['BrushRevision', 'BrushPostCorrection', 'PostCorrection']);
- if (Boolean(rawUseRev) && typeof rawPostCorr === 'number' && rawPostCorr >= 0) {
- postCorrection = Math.min(5, Math.max(0, Math.round(rawPostCorr / 2)));
- }
- const rawSharp = getVal(['BrushSharpenCorner', 'BrushSharpAngles', 'SharpAngles']);
- if (rawSharp !== null) {
- sharpCorners = Boolean(rawSharp);
- }
+ // Anti-Aliasing
+ const rawAA = getVal(['AntiAlias', 'BrushAntiAlias']);
+ if (typeof rawAA === 'number') {
+ antiAlias = Math.max(0, Math.min(3, Math.round(rawAA)));
+ }
- // Ribbon Mode
- const rawRibbon = getVal(['BrushRibbon', 'Ribbon']);
- if (rawRibbon !== null) {
- isRibbon = Boolean(rawRibbon);
- }
+ // Stabilization & Post-Correction
+ const rawRev = getVal(['FlickerReduction', 'BrushStabilization']);
+ if (typeof rawRev === 'number' && rawRev >= 0) {
+ stabilization = Math.min(50, Math.max(0, Math.round(rawRev)));
+ }
+ const rawUseRev = getVal(['BrushUseRevision']);
+ const rawPostCorr = getVal(['BrushRevision', 'BrushPostCorrection', 'PostCorrection']);
+ if (Boolean(rawUseRev) && typeof rawPostCorr === 'number' && rawPostCorr >= 0) {
+ postCorrection = Math.min(5, Math.max(0, Math.round(rawPostCorr / 2)));
+ }
+ const rawSharp = getVal(['BrushSharpenCorner', 'BrushSharpAngles', 'SharpAngles']);
+ if (rawSharp !== null) {
+ sharpCorners = Boolean(rawSharp);
+ }
- // Color Mixing & Smear
- const rawMixing = getVal([
- 'BrushUseWaterColor',
- 'BrushUseWaterColor2',
- 'ColorMixing',
- 'EnableColorMixing',
- ]);
- if (rawMixing !== null) {
- colorMixing = Boolean(rawMixing);
- }
+ // Ribbon Mode
+ const rawRibbon = getVal(['BrushRibbon', 'Ribbon']);
+ if (rawRibbon !== null) {
+ isRibbon = Boolean(rawRibbon);
+ }
- const rawMixColor = getVal([
- 'BrushMixColor',
- 'AmountOfPaint',
- 'PaintAmount',
- 'ColorMixAmount',
- ]);
- if (typeof rawMixColor === 'number' && rawMixColor >= 0) {
- amountOfPaint = rawMixColor > 1.0 ? Math.min(1.0, rawMixColor / 100) : rawMixColor;
- }
+ // Color Jitter
+ const rawColorJitter = getVal(['BrushChangeBrushColor', 'BrushColorJitter']);
+ const rawColorPerStroke = getVal([
+ 'BrushChangeColorPerStroke',
+ 'BrushChangeBrushColorPerStroke',
+ 'ColorJitterPerStroke',
+ ]);
+ const rawSubColorMix = getVal(['BrushSubColorMix', 'BrushMixSubColor', 'SubColorMix']);
+ const subColorMixSensor = parseEffectorSensor(
+ getVal(['BrushSubColorMixEffector', 'SubColorMixEffector'])
+ );
+ const rawRandomHue = getVal(['BrushRandomHue', 'BrushHueJitter', 'RandomHue']);
+ const hueJitterSensor = parseEffectorSensor(
+ getVal(['BrushRandomHueEffector', 'BrushHueEffector', 'RandomHueEffector'])
+ );
+ const rawRandomSat = getVal([
+ 'BrushRandomSaturation',
+ 'BrushSaturationJitter',
+ 'RandomSaturation',
+ ]);
+ const saturationJitterSensor = parseEffectorSensor(
+ getVal([
+ 'BrushRandomSaturationEffector',
+ 'BrushSaturationEffector',
+ 'RandomSaturationEffector',
+ ])
+ );
+ const rawRandomLum = getVal([
+ 'BrushRandomLuminance',
+ 'BrushRandomBrightness',
+ 'BrushLuminanceJitter',
+ 'RandomLuminance',
+ ]);
+ const luminanceJitterSensor = parseEffectorSensor(
+ getVal([
+ 'BrushRandomLuminanceEffector',
+ 'BrushRandomBrightnessEffector',
+ 'BrushLuminanceEffector',
+ 'RandomLuminanceEffector',
+ ])
+ );
+
+ const hasColorJitterFields =
+ rawColorJitter !== null ||
+ rawColorPerStroke !== null ||
+ rawSubColorMix !== null ||
+ rawRandomHue !== null ||
+ rawRandomSat !== null ||
+ rawRandomLum !== null ||
+ Boolean(
+ subColorMixSensor || hueJitterSensor || saturationJitterSensor || luminanceJitterSensor
+ );
- const rawMixAlpha = getVal(['BrushMixAlpha', 'DensityOfPaint', 'PaintDensity']);
- if (typeof rawMixAlpha === 'number' && rawMixAlpha >= 0) {
- densityOfPaint = rawMixAlpha > 1.0 ? Math.min(1.0, rawMixAlpha / 100) : rawMixAlpha;
- }
+ if (hasColorJitterFields) {
+ const subMix = normalizePercent01(rawSubColorMix) ?? 0;
+ const hueJ = normalizePercent01(rawRandomHue) ?? 0;
+ const satJ = normalizePercent01(rawRandomSat) ?? 0;
+ const lumJ = normalizePercent01(rawRandomLum) ?? 0;
+ const enabled =
+ rawColorJitter !== null
+ ? Boolean(rawColorJitter)
+ : subMix > 0 || hueJ > 0 || satJ > 0 || lumJ > 0;
+
+ dynamics = {
+ ...DEFAULT_BRUSH_DYNAMICS,
+ colorJitterEnabled: enabled,
+ colorJitterPerStroke:
+ rawColorPerStroke !== null ? Boolean(rawColorPerStroke) : undefined,
+ foregroundBackgroundJitter: subMix,
+ hueJitter: hueJ,
+ saturationJitter: satJ,
+ brightnessJitter: lumJ,
+ subColorMixSensor,
+ hueJitterSensor,
+ saturationJitterSensor,
+ luminanceJitterSensor,
+ };
+ }
- const rawMixExt = getVal(['BrushMixColorExtension', 'ColorStretch', 'Stretch']);
- if (typeof rawMixExt === 'number' && rawMixExt >= 0) {
- colorStretch = rawMixExt > 1.0 ? Math.min(1.0, rawMixExt / 100) : rawMixExt;
- }
+ // Color Mixing, Effectors, Ground Mixing & Blur
+ const rawMixing = getVal([
+ 'BrushUseWaterColor',
+ 'BrushUseWaterColor2',
+ 'ColorMixing',
+ 'EnableColorMixing',
+ ]);
+ if (rawMixing !== null) {
+ colorMixing = Boolean(rawMixing);
+ }
- // CSP Variant.BrushWaterColor selects Mixing Mode: 0=Blend, 1=Running color, 2=Smear/Blur.
- // CSP Variant.BrushColorMixingMode (CSP 2.0+) selects Color Space: 0=Standard, 1=Perceptual.
- const rawMixMode = getVal(['BrushWaterColor', 'MixingMode']);
- if (rawMixMode !== null) {
- const m = Number(rawMixMode);
- mixingMode = m === 2 ? 'smear' : m === 1 ? 'running_color' : 'blend';
- }
- const rawColorSpaceMode = getVal(['BrushColorMixingMode', 'PerceptualMixing']);
- if (rawColorSpaceMode !== null) {
- perceptualMixing = Number(rawColorSpaceMode) === 1;
- }
+ const rawMixColor = getVal([
+ 'BrushMixColor',
+ 'AmountOfPaint',
+ 'PaintAmount',
+ 'ColorMixAmount',
+ ]);
+ if (typeof rawMixColor === 'number' && rawMixColor >= 0) {
+ amountOfPaint = rawMixColor > 1.0 ? Math.min(1.0, rawMixColor / 100) : rawMixColor;
+ }
- // Wet Edge (strictly gated on BrushUseWaterEdge!)
- const rawWetEdge = getVal(['BrushUseWaterEdge', 'UseWaterEdge']);
- const wetEdgeEnabled = Boolean(rawWetEdge);
- const rawWetRad = getVal(['BrushWaterEdgeRadius', 'WaterEdgeRadius']);
- if (typeof rawWetRad === 'number' && rawWetRad > 0) {
- wetEdgeRadius = rawWetRad;
- }
- const rawWetAlpha = getVal(['BrushWaterEdgeAlphaPower', 'WaterEdgeAlphaPower']);
- if (typeof rawWetAlpha === 'number' && rawWetAlpha > 0) {
- wetEdgeAlphaPower = rawWetAlpha;
- }
- const rawWetVal = getVal(['BrushWaterEdgeValuePower', 'WaterEdgeValuePower']);
- if (typeof rawWetVal === 'number' && rawWetVal > 0) {
- wetEdgeValuePower = rawWetVal;
- }
- wetEdge = wetEdgeEnabled
- ? Math.max(0.15, Math.min(1.0, (wetEdgeAlphaPower || 75) / 100))
- : 0;
-
- // Paper Grain / Texture
- const rawTexDensity = getVal(['TextureDensity', 'Grain', 'BrushTextureDensity']);
- if (typeof rawTexDensity === 'number' && rawTexDensity > 0) {
- textureDensity =
- rawTexDensity > 1.0 ? Math.min(1.0, rawTexDensity / 100) : rawTexDensity;
- }
- const rawTexScale = getVal(['TextureScale2', 'TextureScale']);
- if (typeof rawTexScale === 'number' && rawTexScale > 0) {
- paperTextureScale = rawTexScale / 100;
- }
- const rawTexRotate = getVal(['TextureRotate']);
- if (typeof rawTexRotate === 'number') {
- paperTextureRotate = rawTexRotate;
- }
- const rawTexMode = getVal(['TextureCompositeMode', 'TextureMode', 'BrushTextureMode']);
- if (rawTexMode !== null) {
- paperTextureMode = mapTextureMode(rawTexMode);
- }
- const rawTexInvert = getVal(['TextureReverseDensity', 'TextureInvert', 'BrushTextureInvert']);
- if (rawTexInvert !== null) {
- paperTextureInverted = Boolean(rawTexInvert);
- }
- const rawTexForPlot = getVal(['TextureForPlot']);
- if (rawTexForPlot !== null) {
- paperTextureApplyEachPlot = Boolean(rawTexForPlot);
- }
- const rawTexBright = getVal(['TextureBrightness']);
- if (typeof rawTexBright === 'number') {
- paperTextureBrightness = Math.max(-100, Math.min(100, rawTexBright));
- }
- const rawTexContrast = getVal(['TextureContrast']);
- if (typeof rawTexContrast === 'number') {
- paperTextureContrast = Math.max(-100, Math.min(100, rawTexContrast));
- }
+ const rawMixAlpha = getVal(['BrushMixAlpha', 'DensityOfPaint', 'PaintDensity']);
+ if (typeof rawMixAlpha === 'number' && rawMixAlpha >= 0) {
+ densityOfPaint = rawMixAlpha > 1.0 ? Math.min(1.0, rawMixAlpha / 100) : rawMixAlpha;
+ }
- // Spray / Airbrush
- const rawSpray = getVal(['BrushUseSpray', 'UseSpray']);
- if (Boolean(rawSpray)) {
- const rawSpraySize = getVal(['BrushSpraySize', 'SpraySize']) || 2.0;
- const rawSprayDensity = getVal(['BrushSprayDensity', 'SprayDensity']) || 5;
- const rawSprayBias = getVal(['BrushSprayBias', 'SprayBias']) || 0;
- spray = {
- enabled: true,
- size: typeof rawSpraySize === 'number' ? Math.max(1, rawSpraySize) : 2.0,
- density:
- typeof rawSprayDensity === 'number'
- ? Math.max(1, Math.min(50, rawSprayDensity))
- : 5,
- bias:
- typeof rawSprayBias === 'number'
- ? Math.max(-1, Math.min(1, rawSprayBias / 100))
- : 0,
- };
- }
+ const rawMixExt = getVal(['BrushMixColorExtension', 'ColorStretch', 'Stretch']);
+ if (typeof rawMixExt === 'number' && rawMixExt >= 0) {
+ colorStretch = rawMixExt > 1.0 ? Math.min(1.0, rawMixExt / 100) : rawMixExt;
+ }
- // Taper (Starting and Ending)
- const rawUseIn = getVal(['BrushUseIn']);
- const rawUseOut = getVal(['BrushUseOut']);
- const useIn = rawUseIn !== null ? Boolean(rawUseIn) : false;
- const useOut = rawUseOut !== null ? Boolean(rawUseOut) : false;
- const inLength = Number(getVal(['BrushInLength']) || 0);
- const rawInRatio = Number(getVal(['BrushInRatio']) || 0);
- const inRatio = rawInRatio > 1 ? Math.min(1, rawInRatio / 100) : Math.max(0, rawInRatio);
- const outLength = Number(getVal(['BrushOutLength']) || 0);
- const rawOutRatio = Number(getVal(['BrushOutRatio']) || 0);
- const outRatio = rawOutRatio > 1 ? Math.min(1, rawOutRatio / 100) : Math.max(0, rawOutRatio);
- const inOutType = Number(getVal(['BrushInOutType']) || 0);
- const inOutBySpeed = Boolean(getVal(['BrushInOutBySpeed']));
- const decodedInOut = parseCspInOutTarget(getVal(['BrushInOutTarget']));
-
- if ((useIn || useOut) && inOutType !== 0) {
- taper = {
- useIn,
- inLength,
- inRatio,
- useOut,
- outLength,
- outRatio,
- inOutType,
- inOutBySpeed,
- affectSize: decodedInOut ? decodedInOut.affectSize : true,
- minSizeRatio: decodedInOut ? decodedInOut.minSizeRatio : 0,
- affectDensity: decodedInOut ? decodedInOut.affectDensity : false,
- minDensityRatio: decodedInOut ? decodedInOut.minDensityRatio : 0,
- affectOpacity: decodedInOut ? decodedInOut.affectOpacity : false,
- affectAmountOfPaint: decodedInOut ? decodedInOut.affectAmountOfPaint : false,
- minAmountRatio: decodedInOut ? decodedInOut.minAmountRatio : 0,
- affectDensityOfPaint: decodedInOut ? decodedInOut.affectDensityOfPaint : false,
- minPaintDensityRatio: decodedInOut ? decodedInOut.minPaintDensityRatio : 0,
- };
- }
+ amountOfPaintSensor = parseEffectorSensor(
+ getVal(['BrushMixColorEffector', 'AmountOfPaintEffector'])
+ );
+ densityOfPaintSensor = parseEffectorSensor(
+ getVal(['BrushMixAlphaEffector', 'DensityOfPaintEffector'])
+ );
+ colorStretchSensor = parseEffectorSensor(
+ getVal(['BrushMixColorExtensionEffector', 'ColorStretchEffector'])
+ );
+
+ const rawMixGround = getVal(['BrushMixGroundColor', 'MixGroundColor']);
+ if (rawMixGround !== null) {
+ mixGroundColor = Boolean(rawMixGround);
+ }
- // Dual Brush
- const rawDual = getVal(['UseDualBrush']);
- if (Boolean(rawDual)) {
- dualBrush = true;
- }
- const rawDualMode = getVal(['DualBrushCompositeMode', 'DualBrushMode', 'DualCompositeMode']);
- if (rawDualMode !== null) {
- const dm = Number(rawDualMode);
- if (dm === 1) dualBrushCompositeMode = 'subtract';
- else if (dm === 2) dualBrushCompositeMode = 'darken';
- else if (dm === 3) dualBrushCompositeMode = 'lighten';
- else if (dm === 4) dualBrushCompositeMode = 'screen';
- }
+ const rawUseBlur = getVal(['BrushUseBlur', 'UseBlur']);
+ if (rawUseBlur !== null) {
+ useBlur = Boolean(rawUseBlur);
+ }
+ const rawBlur = getVal(['BrushBlur', 'BlurStrength', 'BrushBlurStrength']);
+ if (typeof rawBlur === 'number' && rawBlur >= 0) {
+ blurStrength = normalizePercent01(rawBlur);
+ }
- const rawUsePattern = getVal(['BrushUsePatternImage']);
- if (rawUsePattern !== null) {
- usePatternImage = Boolean(rawUsePattern);
- }
- rawPatternArrayBlob = getVal(['BrushPatternImageArray']);
- rawTextureImageBlob = getVal(['TextureImage']);
- rawDualPatternBlob = getVal(['DualPatternImageArray']);
+ // CSP Variant.BrushWaterColor selects Mixing Mode: 0=Blend, 1=Running color, 2=Smear, 3=Blur/Finger tip.
+ // CSP Variant.BrushColorMixingMode (CSP 2.0+) selects Color Space: 0=Standard, 1=Perceptual.
+ const rawMixMode = getVal(['BrushWaterColor', 'MixingMode']);
+ if (rawMixMode !== null) {
+ const m = Number(rawMixMode);
+ if (m === 3) {
+ mixingMode = 'smear';
+ if (useBlur === undefined) useBlur = true;
+ } else {
+ mixingMode = m === 2 ? 'smear' : m === 1 ? 'running_color' : 'blend';
}
- } catch {
- // Variant query fallback
- }
- }
-
- // 4. MaterialFile extraction (from native Rust rusqlite rows)
- interface ExtractedMaterial {
- mainPng: Uint8Array;
- catalogPath: string;
- width: number;
- height: number;
- isPaperTexture: boolean;
- }
- const materialMap = new Map<string, ExtractedMaterial>();
- const allMaterialsList: ExtractedMaterial[] = [];
-
- 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 rawColorSpaceMode = getVal(['BrushColorMixingMode', 'PerceptualMixing']);
+ if (rawColorSpaceMode !== null) {
+ perceptualMixing = Number(rawColorSpaceMode) === 1;
+ }
- const entry: ExtractedMaterial = {
- mainPng,
- catalogPath: catPath,
- width,
- height,
- isPaperTexture: isMaterialPaperTexture(fileData),
- };
- 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);
- }
+ // Wet Edge (strictly gated on BrushUseWaterEdge! Alpha/Value power normalized to 0..1)
+ const rawWetEdge = getVal(['BrushUseWaterEdge', 'UseWaterEdge']);
+ const wetEdgeEnabled = Boolean(rawWetEdge);
+ const rawWetRad = getVal(['BrushWaterEdgeRadius', 'WaterEdgeRadius']);
+ if (typeof rawWetRad === 'number' && rawWetRad > 0) {
+ wetEdgeRadius = rawWetRad;
+ }
+ const rawWetAlpha = getVal(['BrushWaterEdgeAlphaPower', 'WaterEdgeAlphaPower']);
+ if (typeof rawWetAlpha === 'number' && rawWetAlpha >= 0) {
+ wetEdgeAlphaPower = normalizeWetEdgePower(rawWetAlpha);
+ }
+ const rawWetVal = getVal(['BrushWaterEdgeValuePower', 'WaterEdgeValuePower']);
+ if (typeof rawWetVal === 'number' && rawWetVal >= 0) {
+ wetEdgeValuePower = normalizeWetEdgePower(rawWetVal);
+ }
+ wetEdge = wetEdgeEnabled
+ ? Math.max(0.15, Math.min(1.0, wetEdgeAlphaPower > 0 ? wetEdgeAlphaPower : 0.75))
+ : 0;
+
+ // Paper Grain / Texture (all 9 TextureCompositeMode values + Position + OffsetX/Y)
+ const rawTexDensity = getVal(['TextureDensity', 'Grain', 'BrushTextureDensity']);
+ if (typeof rawTexDensity === 'number' && rawTexDensity > 0) {
+ textureDensity =
+ rawTexDensity > 1.0 ? Math.min(1.0, rawTexDensity / 100) : rawTexDensity;
+ }
+ const rawTexScale = getVal(['TextureScale2', 'TextureScale']);
+ if (typeof rawTexScale === 'number' && rawTexScale > 0) {
+ paperTextureScale = rawTexScale / 100;
+ }
+ const rawTexRotate = getVal(['TextureRotate']);
+ if (typeof rawTexRotate === 'number') {
+ paperTextureRotate = rawTexRotate;
+ }
+ const rawTexPos = getVal(['TexturePosition', 'TextureMappingMode']);
+ if (rawTexPos !== null) {
+ grainMappingMode = mapTexturePosition(rawTexPos);
+ }
+ const rawTexOffX = getVal(['TextureOffsetX', 'PaperTextureOffsetX']);
+ if (typeof rawTexOffX === 'number' && Number.isFinite(rawTexOffX)) {
+ paperTextureOffsetX = rawTexOffX;
+ }
+ const rawTexOffY = getVal(['TextureOffsetY', 'PaperTextureOffsetY']);
+ if (typeof rawTexOffY === 'number' && Number.isFinite(rawTexOffY)) {
+ paperTextureOffsetY = rawTexOffY;
+ }
+ const rawTexMode = getVal(['TextureCompositeMode', 'TextureMode', 'BrushTextureMode']);
+ if (rawTexMode !== null) {
+ paperTextureMode = mapTextureMode(rawTexMode);
+ }
+ const rawTexInvert = getVal(['TextureReverseDensity', 'TextureInvert', 'BrushTextureInvert']);
+ if (rawTexInvert !== null) {
+ paperTextureInverted = Boolean(rawTexInvert);
+ }
+ const rawTexForPlot = getVal(['TextureForPlot']);
+ if (rawTexForPlot !== null) {
+ paperTextureApplyEachPlot = Boolean(rawTexForPlot);
+ }
+ const rawTexStress = getVal(['TextureStressDensity']);
+ if (rawTexStress !== null) {
+ paperTextureEmphasizeDensity = Boolean(rawTexStress);
+ }
+ const rawTexBright = getVal(['TextureBrightness']);
+ if (typeof rawTexBright === 'number') {
+ paperTextureBrightness = Math.max(-100, Math.min(100, rawTexBright));
+ }
+ const rawTexContrast = getVal(['TextureContrast']);
+ if (typeof rawTexContrast === 'number') {
+ paperTextureContrast = Math.max(-100, Math.min(100, rawTexContrast));
+ }
- allMaterialsList.push(entry);
+ // Extended Spray / Airbrush
+ spray = parseSprayConfig(getVal, '');
+
+ // Taper (Starting and Ending)
+ const rawUseIn = getVal(['BrushUseIn']);
+ const rawUseOut = getVal(['BrushUseOut']);
+ const useIn = rawUseIn !== null ? Boolean(rawUseIn) : false;
+ const useOut = rawUseOut !== null ? Boolean(rawUseOut) : false;
+ const inLength = Number(getVal(['BrushInLength']) || 0);
+ const rawInRatio = Number(getVal(['BrushInRatio']) || 0);
+ const inRatio = rawInRatio > 1 ? Math.min(1, rawInRatio / 100) : Math.max(0, rawInRatio);
+ const outLength = Number(getVal(['BrushOutLength']) || 0);
+ const rawOutRatio = Number(getVal(['BrushOutRatio']) || 0);
+ const outRatio = rawOutRatio > 1 ? Math.min(1, rawOutRatio / 100) : Math.max(0, rawOutRatio);
+ const inOutType = Number(getVal(['BrushInOutType']) || 0);
+ const inOutBySpeed = Boolean(getVal(['BrushInOutBySpeed']));
+ const decodedInOut = parseCspInOutTarget(getVal(['BrushInOutTarget']));
+
+ if ((useIn || useOut) && inOutType !== 0) {
+ taper = {
+ useIn,
+ inLength,
+ inRatio,
+ useOut,
+ outLength,
+ outRatio,
+ inOutType,
+ inOutBySpeed,
+ affectSize: decodedInOut ? decodedInOut.affectSize : true,
+ minSizeRatio: decodedInOut ? decodedInOut.minSizeRatio : 0,
+ affectDensity: decodedInOut ? decodedInOut.affectDensity : false,
+ minDensityRatio: decodedInOut ? decodedInOut.minDensityRatio : 0,
+ affectOpacity: decodedInOut ? decodedInOut.affectOpacity : false,
+ affectAmountOfPaint: decodedInOut ? decodedInOut.affectAmountOfPaint : false,
+ minAmountRatio: decodedInOut ? decodedInOut.minAmountRatio : 0,
+ affectDensityOfPaint: decodedInOut ? decodedInOut.affectDensityOfPaint : false,
+ minPaintDensityRatio: decodedInOut ? decodedInOut.minPaintDensityRatio : 0,
+ };
+ }
+
+ // Dual Brush toggle & composite mode
+ const rawDual = getVal(['UseDualBrush']);
+ if (Boolean(rawDual)) {
+ dualBrush = true;
+ }
+ const rawDualMode = getVal(['DualBrushCompositeMode', 'DualBrushMode', 'DualCompositeMode']);
+ if (rawDualMode !== null) {
+ dualBrushCompositeMode = mapDualBrushCompositeMode(rawDualMode);
+ }
+
+ const rawUsePattern = getVal(['BrushUsePatternImage']);
+ if (rawUsePattern !== null) {
+ usePatternImage = Boolean(rawUsePattern);
+ }
+ rawPatternArrayBlob = getVal(['BrushPatternImageArray']);
+ rawTextureImageBlob = getVal(['TextureImage']);
+ rawDualPatternBlob = getVal(['DualPatternImageArray']);
+ } catch {
+ // Variant query fallback
+ }
+ }
+
+ // 3b. Complete Dual Brush configuration (merges primary Variant DualBrush* columns with extracted.dualVariantValues)
+ if (dualBrush) {
+ const dualMap = extracted.dualVariantValues;
+ const getDualMerged = (dualVariantAliases: string[], primaryDualAliases: string[]): any => {
+ if (dualMap && dualMap.size > 0) {
+ for (const a of dualVariantAliases) {
+ const v = dualMap.get(a.toLowerCase());
+ if (v !== undefined && v !== null) return v;
}
}
+ for (const a of primaryDualAliases) {
+ const v = extracted.variantValues.get(a.toLowerCase());
+ if (v !== undefined && v !== null) return v;
+ }
+ return null;
+ };
+
+ const rawDualSizeUnit = getDualMerged(['BrushSizeUnit', 'SizeUnit'], ['DualBrushSizeUnit']);
+ const rawDualSize = getDualMerged(
+ ['BrushSize', 'Size', 'DualBrushSize'],
+ ['DualBrushSize']
+ );
+ if (typeof rawDualSize === 'number' && rawDualSize > 0) {
+ dualSize = decodeCspBrushSize(rawDualSize, rawDualSizeUnit);
+ }
+
+ const rawDualLinkSize = getDualMerged(
+ ['BrushLinkSize', 'DualBrushLinkSize', 'LinkSize'],
+ ['DualBrushLinkSize']
+ );
+ if (rawDualLinkSize !== null) {
+ dualLinkSize = Boolean(rawDualLinkSize);
+ }
+
+ const decodedDualSpacing = decodeAutoOrFixedSpacing(
+ getDualMerged(['BrushAutoIntervalType', 'DualBrushAutoIntervalType'], ['DualBrushAutoIntervalType']),
+ getDualMerged(
+ ['BrushInterval', 'Interval', 'Spacing', 'DualBrushInterval'],
+ ['DualBrushInterval']
+ )
+ );
+ if (decodedDualSpacing !== undefined) {
+ dualSpacing = decodedDualSpacing;
}
- // 5. Match Paper Texture
- let paperTexture: string | undefined = undefined;
- let paperTextureEntry: ExtractedMaterial | null = null;
+ const rawDualThickness = getDualMerged(
+ ['BrushThickness', 'Thickness', 'DualBrushThickness'],
+ ['DualBrushThickness']
+ );
+ if (typeof rawDualThickness === 'number' && rawDualThickness > 0) {
+ dualThickness = Math.max(0.05, Math.min(20.0, rawDualThickness / 100));
+ }
+
+ const rawDualVertThick = getDualMerged(
+ ['BrushVerticalThicknes', 'BrushVerticalThickness', 'DualBrushVerticalThicknes'],
+ ['DualBrushVerticalThicknes', 'DualBrushVerticalThickness']
+ );
+ if (rawDualVertThick !== null) {
+ dualThicknessVertical = !Boolean(rawDualVertThick);
+ }
- if (rawTextureImageBlob) {
- const texIds = extractCatalogIdsFromBlob(rawTextureImageBlob);
- for (const tid of texIds) {
- if (materialMap.has(tid)) {
- paperTextureEntry = materialMap.get(tid)!;
- paperTexture = bytesToDataUrl(paperTextureEntry.mainPng, 'image/png');
- break;
+ const rawDualAngle = getDualMerged(
+ ['BrushRotation', 'Rotation', 'BrushAngle', 'Angle', 'DualBrushRotation'],
+ ['DualBrushRotation', 'DualBrushAngle']
+ );
+ if (typeof rawDualAngle === 'number') {
+ dualAngle = ((rawDualAngle % 360) + 360) % 360;
+ }
+
+ const rawDualRotEff = getDualMerged(
+ ['BrushRotationEffector', 'RotationEffector', 'DualBrushRotationEffector'],
+ ['DualBrushRotationEffector']
+ );
+ if (rawDualRotEff !== null) {
+ const decodedDualRot = parseRotationEffector(rawDualRotEff);
+ if (decodedDualRot.mode !== undefined) {
+ dualAngleDynamics = decodedDualRot.mode;
+ }
+ if (decodedDualRot.sensor) {
+ dualAngleSensor = decodedDualRot.sensor;
+ }
+ }
+
+ const rawDualHardness = getDualMerged(
+ ['BrushHardness', 'Hardness', 'DualBrushHardness'],
+ ['DualBrushHardness']
+ );
+ if (typeof rawDualHardness === 'number' && rawDualHardness >= 0) {
+ dualHardness = decodeCspHardness(rawDualHardness);
+ }
+
+ const rawDualDensity = getDualMerged(
+ ['BrushDensity', 'BrushFlow', 'Density', 'Flow', 'DualBrushDensity'],
+ ['DualBrushDensity', 'DualBrushFlow']
+ );
+ if (typeof rawDualDensity === 'number' && rawDualDensity >= 0) {
+ dualDensity = rawDualDensity > 1.0 ? Math.min(1.0, rawDualDensity / 100) : rawDualDensity;
+ }
+
+ const rawDualPatternOrder = getDualMerged(
+ ['BrushPatternOrderType', 'BrushPatternRepeatType', 'DualBrushPatternOrderType'],
+ ['DualBrushPatternOrderType', 'DualBrushPatternRepeatType']
+ );
+ if (rawDualPatternOrder !== null) {
+ dualSubTipOrder = mapPatternOrderType(rawDualPatternOrder);
+ }
+
+ const rawDualFlipH = getDualMerged(
+ ['BrushPatternReverseHorizontal', 'BrushFlipX', 'DualBrushFlipH'],
+ ['DualBrushFlipH', 'DualBrushPatternReverseHorizontal', 'DualBrushFlipX']
+ );
+ if (rawDualFlipH !== null) dualFlipH = mapFlipMode(rawDualFlipH);
+
+ const rawDualFlipV = getDualMerged(
+ ['BrushPatternReverseVertical', 'BrushFlipY', 'DualBrushFlipV'],
+ ['DualBrushFlipV', 'DualBrushPatternReverseVertical', 'DualBrushFlipY']
+ );
+ if (rawDualFlipV !== null) dualFlipV = mapFlipMode(rawDualFlipV);
+
+ const rawDualRibbon = getDualMerged(
+ ['BrushRibbon', 'Ribbon', 'DualBrushRibbon'],
+ ['DualBrushRibbon']
+ );
+ if (rawDualRibbon !== null) {
+ dualIsRibbon = Boolean(rawDualRibbon);
+ }
+
+ // Dual spray settings (prefer dualVariantValues if BrushUseSpray is set there, else primary DualBrushUseSpray*)
+ if (dualMap && dualMap.size > 0) {
+ const getDualOnly = (aliases: string[]): any => {
+ for (const a of aliases) {
+ const v = dualMap.get(a.toLowerCase());
+ if (v !== undefined && v !== null) return v;
}
+ return null;
+ };
+ dualSpray = parseSprayConfig(getDualOnly, '');
+ }
+ if (!dualSpray) {
+ dualSpray = parseSprayConfig(getVal, 'Dual');
+ }
+
+ if (!rawDualPatternBlob) {
+ const dualBlob = getDualMerged(
+ ['BrushPatternImageArray', 'DualPatternImageArray'],
+ ['DualPatternImageArray']
+ );
+ if (dualBlob instanceof Uint8Array) {
+ rawDualPatternBlob = dualBlob;
}
}
- if (!paperTexture) {
- // CSP stores TextureDensity=50 even when no texture image is bound; avoid ghost grain.
- textureDensity = 0;
+ }
+
+ // 4. MaterialFile extraction (prefer full-resolution Rust-decoded data/*.layer PNG over thumbnail.png)
+ interface ExtractedMaterial {
+ mainPng: Uint8Array;
+ catalogPath: string;
+ width: number;
+ height: number;
+ isPaperTexture: boolean;
+ expressionColor?: CspExpressionColor;
+ hasSubColor: boolean;
+ fromNativeLayer: boolean;
+ thumbnailScaleComp: number;
+ }
+ const estimatePaperThumbnailScaleFactor = (
+ fileData: Uint8Array,
+ thumbByteLen: number,
+ thumbW: number,
+ thumbH: number
+ ): number => {
+ if (!fileData || fileData.length < 512 || thumbByteLen <= 0 || Math.max(thumbW, thumbH) > 320) {
+ return 1.0;
+ }
+ try {
+ const entries = extractTarEntries(fileData);
+ const layerEntry = entries.find((e) => {
+ const n = e.name.toLowerCase();
+ return n.startsWith('data/') && n.endsWith('.layer') && e.size > 0;
+ });
+ if (!layerEntry || layerEntry.size <= thumbByteLen * 3) {
+ return 1.0;
+ }
+ // Encrypted C2F paper texture fell back to CSP's <=300px thumbnail.png;
+ // byte area scales ~linearly with pixel count, so linear downscale ≈ sqrt(layerBytes / thumbBytes).
+ const ratio = Math.sqrt(layerEntry.size / thumbByteLen);
+ return Math.max(1.0, Math.min(5.0, ratio));
+ } catch {
+ return 1.0;
+ }
+ };
+ const materialMap = new Map<string, ExtractedMaterial>();
+ const allMaterialsList: ExtractedMaterial[] = [];
+
+ const indexMaterialKey = (rawKey: string, entry: ExtractedMaterial) => {
+ const trimmed = rawKey.trim();
+ if (!trimmed) return;
+ materialMap.set(trimmed, entry);
+ // CSP Paint003/Install materials frequently store ".:Paint003:<uuid>:data:material.layer"
+ // in OriginalPath while CatalogPath is empty; also index base/data prefixes and lowercase UUID.
+ const dataIdx = trimmed.indexOf(':data');
+ if (dataIdx > 0) {
+ const basePrefix = trimmed.slice(0, dataIdx);
+ if (basePrefix) materialMap.set(basePrefix, entry);
+ materialMap.set(`${basePrefix}:data`, entry);
+ }
+ const uuidMatch = trimmed.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].toLowerCase(), entry);
}
+ };
- // 6. Match Brush Tip(s) — NEVER hijack a PaperTexture or ignore BrushUsePatternImage=0!
- const tipPngEntries: ExtractedMaterial[] = [];
+ for (const mat of extracted.materials) {
+ const fileData = mat.fileData;
+ const catPath = mat.catalogPath || '';
+ const origPath = mat.originalPath || '';
+ const pwId = mat.pwId;
+
+ const hasNativeDecodedPng = Boolean(
+ mat.decodedPng && mat.decodedPng.length > 0 && isPng(mat.decodedPng)
+ );
+ const mainPng = hasNativeDecodedPng
+ ? mat.decodedPng!
+ : fileData.length > 0
+ ? extractMaterialPng(fileData)
+ : null;
+
+ if (mainPng) {
+ let width = typeof mat.width === 'number' && mat.width > 0 ? mat.width : 64;
+ let height = typeof mat.height === 'number' && mat.height > 0 ? mat.height : 64;
+ if ((!mat.width || !mat.height) && mainPng.length >= 24) {
+ const view = new DataView(mainPng.buffer, mainPng.byteOffset, mainPng.byteLength);
+ width = view.getUint32(16, false);
+ height = view.getUint32(20, false);
+ }
- if (usePatternImage !== false) {
- if (rawPatternArrayBlob) {
- const patternIds = extractCatalogIdsFromBlob(rawPatternArrayBlob);
- for (const pid of patternIds) {
- if (materialMap.has(pid)) {
- const entry = materialMap.get(pid)!;
- if (entry !== paperTextureEntry && !tipPngEntries.includes(entry)) {
- tipPngEntries.push(entry);
- }
- }
+ const fromNativeLayer =
+ typeof mat.decodedFromLayer === 'boolean'
+ ? mat.decodedFromLayer
+ : hasNativeDecodedPng;
+ const isPaperTex =
+ typeof mat.isPaperTexture === 'boolean'
+ ? mat.isPaperTexture
+ : isMaterialPaperTexture(fileData);
+ const entry: ExtractedMaterial = {
+ mainPng,
+ catalogPath: catPath || origPath,
+ width,
+ height,
+ isPaperTexture: isPaperTex,
+ expressionColor: mat.expressionColor,
+ hasSubColor: Boolean(mat.hasSubColor),
+ fromNativeLayer,
+ thumbnailScaleComp:
+ isPaperTex && !fromNativeLayer
+ ? estimatePaperThumbnailScaleFactor(fileData, mainPng.length, width, height)
+ : 1.0,
+ };
+ indexMaterialKey(catPath, entry);
+ indexMaterialKey(origPath, entry);
+ if (pwId) materialMap.set(pwId, entry);
+
+ allMaterialsList.push(entry);
+ }
+ }
+
+ const resolveMaterialRef = (ref: string): ExtractedMaterial | undefined => {
+ const trimmed = ref.trim();
+ if (!trimmed) return undefined;
+ const direct = materialMap.get(trimmed);
+ if (direct) return direct;
+ const dataIdx = trimmed.indexOf(':data');
+ if (dataIdx > 0) {
+ const byBase = materialMap.get(trimmed.slice(0, dataIdx));
+ if (byBase) return byBase;
+ }
+ const uuidMatch = trimmed.match(/[a-f0-9]{10}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{10}/i);
+ if (uuidMatch) {
+ return materialMap.get(uuidMatch[0].toLowerCase());
+ }
+ return undefined;
+ };
+
+ // 5. Match Paper Texture (with missing external material diagnostics)
+ let paperTexture: string | undefined = undefined;
+ let paperTextureEntry: ExtractedMaterial | null = null;
+
+ if (rawTextureImageBlob) {
+ const texIds = extractCatalogIdsFromBlob(rawTextureImageBlob);
+ for (const tid of texIds) {
+ const entry = resolveMaterialRef(tid);
+ if (entry) {
+ paperTextureEntry = entry;
+ paperTexture = bytesToDataUrl(paperTextureEntry.mainPng, 'image/png');
+ if (entry.thumbnailScaleComp > 1.001) {
+ paperTextureScale = Math.min(20.0, paperTextureScale * entry.thumbnailScaleComp);
}
+ break;
}
+ }
+ if (!paperTexture && texIds.length > 0) {
+ importWarnings.push(
+ `Missing external paper texture material (${texIds[0]}): not embedded in MaterialFile; paper grain disabled.`
+ );
+ }
+ }
+ if (!paperTexture) {
+ // CSP stores TextureDensity=50 even when no texture image is bound; avoid ghost grain.
+ textureDensity = 0;
+ }
- if (tipPngEntries.length === 0 && allMaterialsList.length > 0 && usePatternImage === true) {
- for (const m of allMaterialsList) {
- if (
- m !== paperTextureEntry &&
- !m.isPaperTexture &&
- !tipPngEntries.some((e) => e.mainPng === m.mainPng)
- ) {
- tipPngEntries.push(m);
+ // 6. Match Brush Tip(s) — NEVER hijack a PaperTexture or ignore BrushUsePatternImage=0!
+ const tipPngEntries: ExtractedMaterial[] = [];
+
+ if (usePatternImage !== false) {
+ let referencedPatternIds: string[] = [];
+ if (rawPatternArrayBlob) {
+ referencedPatternIds = extractCatalogIdsFromBlob(rawPatternArrayBlob);
+ const missingTipRefs: string[] = [];
+ for (const pid of referencedPatternIds) {
+ const entry = resolveMaterialRef(pid);
+ if (entry) {
+ if (entry !== paperTextureEntry && !entry.isPaperTexture && !tipPngEntries.includes(entry)) {
+ tipPngEntries.push(entry);
}
+ } else {
+ missingTipRefs.push(pid);
}
}
+ if (missingTipRefs.length > 0) {
+ importWarnings.push(
+ `Missing external brush tip material (${missingTipRefs.join(', ')}): not embedded in MaterialFile; using procedural tip fallback.`
+ );
+ }
}
- // 7. Process extracted custom tips; for Circle tips (BrushUsePatternImage=0), leave tipDataUrl undefined
- // so BrushEngine renders its analytical/SDF circular/elliptical tip at native crisp resolution
- // without double-applying thickness!
- let tipDataUrl: string | undefined = undefined;
- let tipWidth: number | undefined = undefined;
- let tipHeight: number | undefined = undefined;
- let isColorTip = false;
- const subTips: CspSubTip[] = [];
- const fallbackProc = { hardness, thickness: 1.0, antiAlias };
+ if (
+ tipPngEntries.length === 0 &&
+ referencedPatternIds.length === 0 &&
+ allMaterialsList.length > 0 &&
+ usePatternImage === true
+ ) {
+ for (const m of allMaterialsList) {
+ if (
+ m !== paperTextureEntry &&
+ !m.isPaperTexture &&
+ !tipPngEntries.some((e) => e.mainPng === m.mainPng)
+ ) {
+ tipPngEntries.push(m);
+ }
+ }
+ }
+ }
- if (tipPngEntries.length > 0) {
- const primaryEntry = tipPngEntries[0];
- const rawUrl = bytesToDataUrl(primaryEntry.mainPng, 'image/png');
- const processed = await processBrushTipImage(rawUrl, fallbackProc);
- tipDataUrl = processed.dataUrl;
- tipWidth = processed.width;
- tipHeight = processed.height;
- isColorTip = processed.isColor;
+ // 7. Process extracted custom tips; for Circle tips (BrushUsePatternImage=0) or missing external tips,
+ // leave tipDataUrl undefined so BrushEngine renders its analytical/SDF circular/elliptical tip cleanly.
+ let tipDataUrl: string | undefined = undefined;
+ let tipWidth: number | undefined = undefined;
+ let tipHeight: number | undefined = undefined;
+ let isColorTip = false;
+ let isDualToneTip = false;
+ const subTips: CspSubTip[] = [];
+ const fallbackProc = { hardness, thickness: 1.0, antiAlias };
+
+ if (tipPngEntries.length > 0) {
+ for (let i = 0; i < tipPngEntries.length; i++) {
+ const entry = tipPngEntries[i];
+ const u = bytesToDataUrl(entry.mainPng, 'image/png');
+ const p = await processBrushTipImage(u, fallbackProc, {
+ width: entry.width,
+ height: entry.height,
+ expressionColor: entry.expressionColor,
+ hasSubColor: entry.hasSubColor,
+ fromNativeLayer: entry.fromNativeLayer,
+ });
+ if (i === 0) {
+ tipDataUrl = p.dataUrl;
+ tipWidth = p.width;
+ tipHeight = p.height;
+ isColorTip = p.isColor;
+ isDualToneTip = p.isDualToneTip;
+ }
+ subTips.push({
+ dataUrl: p.dataUrl,
+ width: p.width,
+ height: p.height,
+ isColor: p.isColor,
+ isDualToneTip: p.isDualToneTip,
+ });
+ }
+ }
- for (const entry of tipPngEntries) {
+ let secondaryTipDataUrl: string | undefined = undefined;
+ let secondaryTipWidth: number | undefined = undefined;
+ let secondaryTipHeight: number | undefined = undefined;
+ const dualSubTips: CspSubTip[] = [];
+
+ if (dualBrush && rawDualPatternBlob) {
+ const dualIds = extractCatalogIdsFromBlob(rawDualPatternBlob);
+ const missingDualRefs: string[] = [];
+ for (const did of dualIds) {
+ const entry = resolveMaterialRef(did);
+ if (entry && entry !== paperTextureEntry && !entry.isPaperTexture) {
const u = bytesToDataUrl(entry.mainPng, 'image/png');
- const p = await processBrushTipImage(u, fallbackProc);
- subTips.push({
+ const p = await processBrushTipImage(u, fallbackProc, {
+ width: entry.width,
+ height: entry.height,
+ expressionColor: entry.expressionColor,
+ hasSubColor: entry.hasSubColor,
+ fromNativeLayer: entry.fromNativeLayer,
+ });
+ if (!secondaryTipDataUrl) {
+ secondaryTipDataUrl = p.dataUrl;
+ secondaryTipWidth = p.width;
+ secondaryTipHeight = p.height;
+ }
+ dualSubTips.push({
dataUrl: p.dataUrl,
width: p.width,
height: p.height,
isColor: p.isColor,
+ isDualToneTip: p.isDualToneTip,
});
+ } else if (!entry) {
+ missingDualRefs.push(did);
}
}
-
- let secondaryTipDataUrl: string | undefined = undefined;
- let secondaryTipWidth: number | undefined = undefined;
- let secondaryTipHeight: number | undefined = undefined;
-
- if (dualBrush && rawDualPatternBlob) {
- const dualIds = extractCatalogIdsFromBlob(rawDualPatternBlob);
- for (const did of dualIds) {
- if (materialMap.has(did)) {
- const entry = materialMap.get(did)!;
- const u = bytesToDataUrl(entry.mainPng, 'image/png');
- const p = await processBrushTipImage(u, fallbackProc);
- secondaryTipDataUrl = p.dataUrl;
- secondaryTipWidth = p.width;
- secondaryTipHeight = p.height;
- break;
- }
- }
+ if (missingDualRefs.length > 0) {
+ importWarnings.push(
+ `Missing external dual brush tip material (${missingDualRefs.join(', ')}): not embedded in MaterialFile; using procedural fallback.`
+ );
}
+ }
- const uniqueId = `csp-${Date.now()}-${Math.random().toString(36).substring(2, 8)}`;
-
- const cspBrush: CspBrush = {
- id: uniqueId,
- name: brushName,
- badge: 'CSP',
- desc: tipPngEntries.length > 0 ? 'Clip Studio Paint Textured Brush' : 'Clip Studio Paint Brush',
- tipDataUrl,
- tipWidth,
- tipHeight,
- isColorTip,
- secondaryTipDataUrl,
- secondaryTipWidth,
- secondaryTipHeight,
- subTips: subTips.length > 1 ? subTips : undefined,
- size: brushSize,
- minSizeFactor,
- opacity,
- flow,
- adjustDensityByGap,
- blendTipsMode,
- spacing,
- hardness,
- thickness,
- thicknessVertical,
- flipH,
- flipV,
- angle,
- angleDynamics,
- rotationRandomScale,
- antiAlias,
- usePressure,
- useVelocity,
- useTilt,
- sizeSensor,
- opacitySensor,
- densitySensor,
- smoothing: true,
- stabilization,
- postCorrection,
- sharpCorners,
- pressureCurve,
- velocityCurve,
- colorMixing,
- perceptualMixing,
- amountOfPaint,
- densityOfPaint,
- colorStretch,
- mixingMode,
- wetEdge,
- wetEdgeRadius,
- wetEdgeAlphaPower,
- wetEdgeValuePower,
- paperTexture,
- textureDensity,
- paperTextureScale,
- paperTextureRotate,
- paperTextureMode,
- paperTextureBrightness,
- paperTextureContrast,
- paperTextureApplyEachPlot,
- paperTextureInverted,
- dualBrush,
- dualBrushCompositeMode,
- spray,
- taper,
- isRibbon,
- pressureCurveGamma: 1.0,
- importedAt: Date.now(),
- };
+ const uniqueId = `csp-${Date.now()}-${Math.random().toString(36).substring(2, 8)}`;
+
+ const dualBrushConfig: CspDualBrushConfig | undefined = dualBrush
+ ? {
+ enabled: true,
+ compositeMode: normalizeDualBrushCompositeMode(dualBrushCompositeMode),
+ linkSizeWithMain: dualLinkSize,
+ size: dualSize,
+ sizeRatio:
+ dualSize !== undefined && brushSize > 0 ? dualSize / brushSize : undefined,
+ spacing: dualSpacing,
+ thickness: dualThickness,
+ thicknessVertical: dualThicknessVertical,
+ hardness: dualHardness,
+ density: dualDensity,
+ angle: dualAngle,
+ angleDynamics: dualAngleDynamics,
+ angleSensor: dualAngleSensor,
+ flipH: dualFlipH,
+ flipV: dualFlipV,
+ spray: dualSpray,
+ tipDataUrl: secondaryTipDataUrl,
+ subTips: dualSubTips.length > 1 ? dualSubTips : undefined,
+ subTipOrder: dualSubTipOrder,
+ isRibbon: dualIsRibbon,
+ }
+ : undefined;
+
+ const cspBrush: CspBrush = {
+ id: uniqueId,
+ name: brushName,
+ badge: 'CSP',
+ desc: tipPngEntries.length > 0 ? 'Clip Studio Paint Textured Brush' : 'Clip Studio Paint Brush',
+ tipDataUrl,
+ tipWidth,
+ tipHeight,
+ isColorTip,
+ isDualToneTip,
+ secondaryTipDataUrl,
+ secondaryTipWidth,
+ secondaryTipHeight,
+ subTips: subTips.length > 1 ? subTips : undefined,
+ subTipOrder,
+ size: brushSize,
+ brushSizeUnit,
+ brushSizeSpecifiedByScreen,
+ minSizeFactor,
+ opacity,
+ flow,
+ adjustDensityByGap,
+ blendTipsMode,
+ brushCombineMode,
+ spacing,
+ hardness,
+ thickness,
+ thicknessVertical,
+ thicknessSensor,
+ flipH,
+ flipV,
+ angle,
+ angleDynamics,
+ angleSensor,
+ rotationRandomScale,
+ antiAlias,
+ usePressure,
+ useVelocity,
+ useTilt,
+ sizeSensor,
+ opacitySensor,
+ densitySensor,
+ intervalSensor,
+ textureDensitySensor,
+ smoothing: true,
+ stabilization,
+ postCorrection,
+ sharpCorners,
+ pressureCurve,
+ velocityCurve,
+ colorMixing,
+ perceptualMixing,
+ amountOfPaint,
+ densityOfPaint,
+ colorStretch,
+ amountOfPaintSensor,
+ densityOfPaintSensor,
+ colorStretchSensor,
+ mixGroundColor,
+ useBlur,
+ blurStrength,
+ mixingMode,
+ wetEdge,
+ wetEdgeRadius,
+ wetEdgeAlphaPower,
+ wetEdgeValuePower,
+ paperTexture,
+ grainMappingMode,
+ textureDensity,
+ paperTextureScale,
+ paperTextureRotate,
+ paperTextureOffsetX,
+ paperTextureOffsetY,
+ paperTextureMode,
+ paperTextureBrightness,
+ paperTextureContrast,
+ paperTextureApplyEachPlot,
+ paperTextureEmphasizeDensity,
+ paperTextureInverted,
+ dualBrush,
+ dualBrushConfig,
+ dualBrushCompositeMode,
+ dualSize,
+ dualLinkSize,
+ dualSpacing,
+ dualThickness,
+ dualThicknessVertical,
+ dualAngle,
+ dualAngleDynamics,
+ dualAngleSensor,
+ dualHardness,
+ dualDensity,
+ dualSubTips: dualSubTips.length > 1 ? dualSubTips : undefined,
+ dualSubTipOrder,
+ dualFlipH,
+ dualFlipV,
+ dualSpray,
+ dualIsRibbon,
+ spray,
+ taper,
+ dynamics,
+ isRibbon,
+ pressureCurveGamma: 1.0,
+ importWarnings: importWarnings.length > 0 ? importWarnings : undefined,
+ importedAt: Date.now(),
+ };
- return cspBrush;
+ return cspBrush;
}
diff --git a/src/utils/tileEngine/mipmap.ts b/src/utils/tileEngine/mipmap.ts
index aae632f..052672f 100644
--- a/src/utils/tileEngine/mipmap.ts
+++ b/src/utils/tileEngine/mipmap.ts
@@ -183,7 +183,7 @@ export function downsample2x2ToParentTile(
dst[outIdx + 3] = 255;
} else {
const halfA = sumA >> 1;
- dst[outIdx + 3] = sumA >> 2;
+ dst[outIdx + 3] = (sumA + 2) >> 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;
diff --git a/src/utils/tileEngine/strokeComposite.ts b/src/utils/tileEngine/strokeComposite.ts
index 44e76b8..880319c 100644
--- a/src/utils/tileEngine/strokeComposite.ts
+++ b/src/utils/tileEngine/strokeComposite.ts
@@ -1,7 +1,14 @@
/**
* In-place brush stroke compositing directly onto LOD 0 sparse tiles.
+ * Supports all 28+ CSP/Photoshop BrushCombineMode blend modes, behind (destination-over),
+ * clear (destination-out), compare-density, alpha-lock (source-atop), and selection masks.
*/
+import type { CspBrushCombineMode } from '../../types/editor';
+import {
+ compositePigmentOverPixelInto,
+ isPigmentCompatibleCombineMode,
+} from '../pigmentEngine';
import { packRGBATo1Bit, packRGBATo8Bit, unpack8BitToRGBA } from './pixelCodec';
import {
ISparseTileGridHost,
@@ -20,7 +27,12 @@ export interface CompositeStrokeOptions {
destY: number;
format: TileFormat;
compositeOp: 'source-over' | 'destination-out' | 'source-atop';
+ brushCombineMode?: CspBrushCombineMode;
opacity: number;
+ /** Physical Kubelka-Munk pigment compositing strength [0..1]. 0 = standard RGB compositing. */
+ pigmentStrength?: number;
+ /** True when painting on a layer over a visible white/light paper ground (enables optical pigment dilution on transparent pixels). */
+ pigmentWhiteGround?: boolean;
monochrome?: {
threshold: number;
expressBlack: boolean;
@@ -34,6 +46,448 @@ export interface CompositeStrokeOptions {
suppressNotify?: boolean;
}
+// ============================================================================
+// Exact CPU implementation of all CSP / Photoshop / W3C Blend Modes
+// Matches `src/utils/compositor/shaders/blendModesGlsl.ts` 1-to-1.
+// ============================================================================
+
+function clamp01(v: number): number {
+ return v <= 0 ? 0 : v >= 1 ? 1 : v;
+}
+
+function blendLum(r: number, g: number, b: number): number {
+ return 0.3 * r + 0.59 * g + 0.11 * b;
+}
+
+function blendSat(r: number, g: number, b: number): number {
+ const mx = r > g ? (r > b ? r : b) : g > b ? g : b;
+ const mn = r < g ? (r < b ? r : b) : g < b ? g : b;
+ return mx - mn;
+}
+
+function clipColorInto(r: number, g: number, b: number, out: [number, number, number]): void {
+ const l = clamp01(blendLum(r, g, b));
+ const n = r < g ? (r < b ? r : b) : g < b ? g : b;
+ const x = r > g ? (r > b ? r : b) : g > b ? g : b;
+ let cr = r;
+ let cg = g;
+ let cb = b;
+ if (n < 0) {
+ const denom = Math.max(0.0001, l - n);
+ cr = l + ((cr - l) * l) / denom;
+ cg = l + ((cg - l) * l) / denom;
+ cb = l + ((cb - l) * l) / denom;
+ }
+ if (x > 1) {
+ const denom = Math.max(0.0001, x - l);
+ cr = l + ((cr - l) * (1 - l)) / denom;
+ cg = l + ((cg - l) * (1 - l)) / denom;
+ cb = l + ((cb - l) * (1 - l)) / denom;
+ }
+ out[0] = clamp01(cr);
+ out[1] = clamp01(cg);
+ out[2] = clamp01(cb);
+}
+
+function setLumInto(
+ r: number,
+ g: number,
+ b: number,
+ l: number,
+ out: [number, number, number]
+): void {
+ const d = l - blendLum(r, g, b);
+ clipColorInto(r + d, g + d, b + d, out);
+}
+
+function setSatInto(
+ r: number,
+ g: number,
+ b: number,
+ s: number,
+ out: [number, number, number]
+): void {
+ const cMin = r < g ? (r < b ? r : b) : g < b ? g : b;
+ const cMax = r > g ? (r > b ? r : b) : g > b ? g : b;
+ const delta = cMax - cMin;
+ if (delta <= 0.0001) {
+ out[0] = 0;
+ out[1] = 0;
+ out[2] = 0;
+ return;
+ }
+ const scale = s / delta;
+ out[0] = (r - cMin) * scale;
+ out[1] = (g - cMin) * scale;
+ out[2] = (b - cMin) * scale;
+}
+
+function blendChannel(b: number, s: number, mode: CspBrushCombineMode): number {
+ switch (mode) {
+ case 'multiply':
+ return b * s;
+ case 'screen':
+ return b + s - b * s;
+ case 'overlay':
+ return b < 0.5 ? 2.0 * b * s : 1.0 - 2.0 * (1.0 - b) * (1.0 - s);
+ case 'darken':
+ return b < s ? b : s;
+ case 'lighten':
+ return b > s ? b : s;
+ case 'color-dodge':
+ return b <= 0 ? 0 : s >= 1 ? 1 : Math.min(1.0, b / Math.max(0.0001, 1.0 - s));
+ case 'color-burn':
+ return b >= 1 ? 1 : s <= 0 ? 0 : 1.0 - Math.min(1.0, (1.0 - b) / Math.max(0.0001, s));
+ case 'hard-light':
+ return s < 0.5 ? 2.0 * b * s : 1.0 - 2.0 * (1.0 - b) * (1.0 - s);
+ case 'soft-light': {
+ const d = b <= 0.25 ? ((16.0 * b - 12.0) * b + 4.0) * b : Math.sqrt(Math.max(0, b));
+ return s <= 0.5 ? b - (1.0 - 2.0 * s) * b * (1.0 - b) : b + (2.0 * s - 1.0) * (d - b);
+ }
+ case 'difference':
+ return Math.abs(b - s);
+ case 'exclusion':
+ return b + s - 2.0 * b * s;
+ case 'linear-burn':
+ return Math.max(0, b + s - 1.0);
+ case 'add':
+ case 'add-glow':
+ return Math.min(1.0, b + s);
+ case 'color-dodge-glow':
+ return s >= 1 ? 1 : Math.min(1.0, b / Math.max(0.0001, 1.0 - s));
+ case 'divide':
+ return s <= 0.0001 ? 1.0 : clamp01(b / s);
+ case 'vivid-light':
+ if (s <= 0.5) {
+ const s2 = 2.0 * s;
+ return s2 <= 0 ? 0 : b >= 1 ? 1 : 1.0 - Math.min(1.0, (1.0 - b) / Math.max(0.0001, s2));
+ } else {
+ const s2 = 2.0 * (s - 0.5);
+ return s2 >= 1 ? 1 : b <= 0 ? 0 : Math.min(1.0, b / Math.max(0.0001, 1.0 - s2));
+ }
+ case 'linear-light':
+ return clamp01(b + 2.0 * s - 1.0);
+ case 'pin-light':
+ return s <= 0.5 ? Math.min(b, 2.0 * s) : Math.max(b, 2.0 * (s - 0.5));
+ case 'hard-mix':
+ return b + s >= 1.0 ? 1.0 : 0.0;
+ case 'subtract':
+ return Math.max(0, b - s);
+ default:
+ return s;
+ }
+}
+
+const _blendScratchSat: [number, number, number] = [0, 0, 0];
+
+/**
+ * Evaluates any CSP/Photoshop color blend mode in normalized [0..1] RGB space.
+ */
+export function evaluateCpuBlendModeInto(
+ br: number,
+ bg: number,
+ bb: number,
+ sr: number,
+ sg: number,
+ sb: number,
+ mode: CspBrushCombineMode,
+ out: [number, number, number]
+): void {
+ switch (mode) {
+ case 'darker-color':
+ if (blendLum(sr, sg, sb) < blendLum(br, bg, bb)) {
+ out[0] = sr;
+ out[1] = sg;
+ out[2] = sb;
+ } else {
+ out[0] = br;
+ out[1] = bg;
+ out[2] = bb;
+ }
+ return;
+ case 'lighter-color':
+ if (blendLum(sr, sg, sb) > blendLum(br, bg, bb)) {
+ out[0] = sr;
+ out[1] = sg;
+ out[2] = sb;
+ } else {
+ out[0] = br;
+ out[1] = bg;
+ out[2] = bb;
+ }
+ return;
+ case 'hue':
+ setSatInto(sr, sg, sb, blendSat(br, bg, bb), _blendScratchSat);
+ setLumInto(_blendScratchSat[0], _blendScratchSat[1], _blendScratchSat[2], blendLum(br, bg, bb), out);
+ return;
+ case 'saturation':
+ setSatInto(br, bg, bb, blendSat(sr, sg, sb), _blendScratchSat);
+ setLumInto(_blendScratchSat[0], _blendScratchSat[1], _blendScratchSat[2], blendLum(br, bg, bb), out);
+ return;
+ case 'color':
+ setLumInto(sr, sg, sb, blendLum(br, bg, bb), out);
+ return;
+ case 'luminosity':
+ setLumInto(br, bg, bb, blendLum(sr, sg, sb), out);
+ return;
+ default:
+ out[0] = blendChannel(br, sr, mode);
+ out[1] = blendChannel(bg, sg, mode);
+ out[2] = blendChannel(bb, sb, mode);
+ }
+}
+
+export function isCustomBrushCombineMode(mode?: CspBrushCombineMode): boolean {
+ return Boolean(mode && mode !== 'normal' && mode !== 'pass-through');
+}
+
+const _blendRgbOut: [number, number, number] = [0, 0, 0];
+
+/**
+ * Composites a single RGBA pixel with full CSP `BrushCombineMode` + Porter-Duff semantics.
+ * Writes [outR, outG, outB, outA] (0..255) into `out`.
+ */
+export function compositeBrushPixelInto(
+ dr: number,
+ dg: number,
+ db: number,
+ da: number,
+ sr: number,
+ sg: number,
+ sb: number,
+ effA: number,
+ compositeOp: 'source-over' | 'destination-out' | 'source-atop',
+ combineMode: CspBrushCombineMode | undefined,
+ out: [number, number, number, number]
+): void {
+ const mode: CspBrushCombineMode = combineMode ?? 'normal';
+
+ if (compositeOp === 'destination-out' || mode === 'clear') {
+ if (da === 0) {
+ out[0] = dr;
+ out[1] = dg;
+ out[2] = db;
+ out[3] = 0;
+ return;
+ }
+ if (effA >= 255) {
+ out[0] = 0;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 0;
+ } else {
+ const outA = Math.round(da * (1 - effA / 255));
+ if (outA <= 0) {
+ out[0] = 0;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 0;
+ } else {
+ out[0] = dr;
+ out[1] = dg;
+ out[2] = db;
+ out[3] = outA;
+ }
+ }
+ return;
+ }
+
+ if (mode === 'behind') {
+ // CSP Behind = Porter-Duff destination-over
+ if (compositeOp === 'source-atop') {
+ // Alpha-locked behind cannot paint onto transparent pixels and cannot change opaque front pixels
+ if (da === 0 || da >= 255) {
+ out[0] = dr;
+ out[1] = dg;
+ out[2] = db;
+ out[3] = da;
+ return;
+ }
+ const dA = da / 255;
+ const sA = effA / 255;
+ const rem = (1 - dA) * sA;
+ const denom = dA + rem;
+ if (denom > 0) {
+ const inv = 1 / denom;
+ out[0] = Math.round((dr * dA + sr * rem) * inv);
+ out[1] = Math.round((dg * dA + sg * rem) * inv);
+ out[2] = Math.round((db * dA + sb * rem) * inv);
+ } else {
+ out[0] = dr;
+ out[1] = dg;
+ out[2] = db;
+ }
+ out[3] = da;
+ return;
+ }
+ if (da >= 255) {
+ out[0] = dr;
+ out[1] = dg;
+ out[2] = db;
+ out[3] = da;
+ return;
+ }
+ if (da === 0) {
+ out[0] = sr;
+ out[1] = sg;
+ out[2] = sb;
+ out[3] = effA;
+ return;
+ }
+ const dA = da / 255;
+ const sA = effA / 255;
+ const invDA = 1 - dA;
+ const compA = dA + sA * invDA;
+ const invOut = 1 / compA;
+ out[0] = Math.round((dr * dA + sr * sA * invDA) * invOut);
+ out[1] = Math.round((dg * dA + sg * sA * invDA) * invOut);
+ out[2] = Math.round((db * dA + sb * sA * invDA) * invOut);
+ out[3] = Math.round(compA * 255);
+ return;
+ }
+
+ if (mode === 'compare-density') {
+ if (compositeOp === 'source-atop' && da === 0) {
+ out[0] = 0;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 0;
+ return;
+ }
+ if (da === 0) {
+ out[0] = sr;
+ out[1] = sg;
+ out[2] = sb;
+ out[3] = effA;
+ return;
+ }
+ const sA = effA / 255;
+ const dA = da / 255;
+ const dstWeight = dA * (1 - sA);
+ const denom = sA + dstWeight;
+ if (denom <= 1e-6) {
+ out[0] = dr;
+ out[1] = dg;
+ out[2] = db;
+ out[3] = da;
+ return;
+ }
+ const invDenom = 1 / denom;
+ out[0] = Math.round((sr * sA + dr * dstWeight) * invDenom);
+ out[1] = Math.round((sg * sA + dg * dstWeight) * invDenom);
+ out[2] = Math.round((sb * sA + db * dstWeight) * invDenom);
+ out[3] = compositeOp === 'source-atop' ? da : Math.max(effA, da);
+ return;
+ }
+
+ const isStandardNormal = mode === 'normal' || mode === 'pass-through';
+
+ if (compositeOp === 'source-atop') {
+ if (da === 0) {
+ out[0] = dr;
+ out[1] = dg;
+ out[2] = db;
+ out[3] = 0;
+ return;
+ }
+ const sA = effA / 255;
+ if (isStandardNormal) {
+ if (effA >= 255) {
+ out[0] = sr;
+ out[1] = sg;
+ out[2] = sb;
+ out[3] = da;
+ } else {
+ const inv = 1 - sA;
+ out[0] = Math.round(sr * sA + dr * inv);
+ out[1] = Math.round(sg * sA + dg * inv);
+ out[2] = Math.round(sb * sA + db * inv);
+ out[3] = da;
+ }
+ return;
+ }
+ evaluateCpuBlendModeInto(dr / 255, dg / 255, db / 255, sr / 255, sg / 255, sb / 255, mode, _blendRgbOut);
+ const inv = 1 - sA;
+ out[0] = Math.round(_blendRgbOut[0] * 255 * sA + dr * inv);
+ out[1] = Math.round(_blendRgbOut[1] * 255 * sA + dg * inv);
+ out[2] = Math.round(_blendRgbOut[2] * 255 * sA + db * inv);
+ out[3] = da;
+ return;
+ }
+
+ // Standard source-over with optional CSP color blend mode
+ if (da === 0) {
+ out[0] = sr;
+ out[1] = sg;
+ out[2] = sb;
+ out[3] = effA;
+ return;
+ }
+
+ if (isStandardNormal) {
+ if (effA >= 255) {
+ out[0] = sr;
+ out[1] = sg;
+ out[2] = sb;
+ out[3] = 255;
+ return;
+ }
+ const sA = effA / 255;
+ const dA = da / 255;
+ const invSA = 1 - sA;
+ const compA = sA + dA * invSA;
+ if (compA > 0) {
+ const invOut = 1 / compA;
+ out[0] = Math.round((sr * sA + dr * dA * invSA) * invOut);
+ out[1] = Math.round((sg * sA + dg * dA * invSA) * invOut);
+ out[2] = Math.round((sb * sA + db * dA * invSA) * invOut);
+ out[3] = Math.round(compA * 255);
+ } else {
+ out[0] = dr;
+ out[1] = dg;
+ out[2] = db;
+ out[3] = da;
+ }
+ return;
+ }
+
+ // W3C Compositing & Blending Level 1 formula for non-normal blend modes:
+ // Cr = (1 - dA) * Cs + dA * B(Cb, Cs)
+ // Co * Ao = sA * Cr + (1 - sA) * dA * Cb
+ // Ao = sA + dA * (1 - sA)
+ const sA = effA / 255;
+ const dA = da / 255;
+ const invSA = 1 - sA;
+ const invDA = 1 - dA;
+ const compA = sA + dA * invSA;
+ const inv255 = 1 / 255;
+ const srN = sr * inv255;
+ const sgN = sg * inv255;
+ const sbN = sb * inv255;
+ const drN = dr * inv255;
+ const dgN = dg * inv255;
+ const dbN = db * inv255;
+
+ evaluateCpuBlendModeInto(drN, dgN, dbN, srN, sgN, sbN, mode, _blendRgbOut);
+
+ const crR = invDA * srN + dA * _blendRgbOut[0];
+ const crG = invDA * sgN + dA * _blendRgbOut[1];
+ const crB = invDA * sbN + dA * _blendRgbOut[2];
+
+ if (compA > 0) {
+ const invOut = 255 / compA;
+ out[0] = Math.max(0, Math.min(255, Math.round((sA * crR + invSA * dA * drN) * invOut)));
+ out[1] = Math.max(0, Math.min(255, Math.round((sA * crG + invSA * dA * dgN) * invOut)));
+ out[2] = Math.max(0, Math.min(255, Math.round((sA * crB + invSA * dA * dbN) * invOut)));
+ out[3] = Math.max(0, Math.min(255, Math.round(compA * 255)));
+ } else {
+ out[0] = dr;
+ out[1] = dg;
+ out[2] = db;
+ out[3] = da;
+ }
+}
+
/**
* Composites an isolated stroke RGBA buffer directly onto LOD 0 tiles in-place,
* avoiding full-region canvas allocation, existing-tile unpacking, and separate
@@ -51,6 +505,7 @@ export function compositeStrokeToTiles(
destY,
format: targetFormat,
compositeOp,
+ brushCombineMode,
monochrome,
selectionMask,
snapshotOut,
@@ -61,6 +516,15 @@ export function compositeStrokeToTiles(
const h = strokeData.height;
if (w <= 0 || h <= 0 || opacity <= 0.001) return false;
+ const effectiveCombineMode: CspBrushCombineMode =
+ compositeOp === 'destination-out' ? 'clear' : brushCombineMode ?? 'normal';
+ const useCustomBlend = isCustomBrushCombineMode(effectiveCombineMode);
+ const isEraseOp = compositeOp === 'destination-out' || effectiveCombineMode === 'clear';
+ const pigmentStrength = Math.max(0, Math.min(1, options.pigmentStrength ?? 0));
+ const pigmentWhiteGround = Boolean(options.pigmentWhiteGround);
+ const usePigmentComposite =
+ pigmentStrength > 0.005 && !isEraseOp && isPigmentCompatibleCombineMode(effectiveCombineMode);
+
host.ingestedLayers.add(layerId);
host.setLayerFormat(layerId, targetFormat);
@@ -85,6 +549,7 @@ export function compositeStrokeToTiles(
const selBh = selectionMask ? Math.ceil(selectionMask.bounds.height) : 0;
const fullOpacity = opacity >= 0.999;
const memoryManager = host.getMemoryManager();
+ const pxOut: [number, number, number, number] = [0, 0, 0, 0];
let anyModified = false;
@@ -102,7 +567,7 @@ export function compositeStrokeToTiles(
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 ((isEraseOp || compositeOp === 'source-atop') && (!existingTile || !existingTile.data)) {
if (existingTile && existingTile.data === null && existingTile.isPagedToDisk && memoryManager) {
void memoryManager.requestTileData(existingTile);
}
@@ -201,10 +666,21 @@ export function compositeStrokeToTiles(
const byteIdx = rowByteBase + (lx >> 3);
const mask = 1 << (7 - (lx & 7));
- if (compositeOp === 'destination-out') {
+ if (isEraseOp) {
if (effA >= 128) {
dst[byteIdx] &= ~mask;
}
+ } else if (effectiveCombineMode === 'behind') {
+ const hadInk = (dst[byteIdx] & mask) !== 0;
+ if (!hadInk && compositeOp !== 'source-atop') {
+ 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 (effA >= 128 && lum < monoThresh && monoExpressBlack) {
+ dst[byteIdx] |= mask;
+ }
+ }
} else if (compositeOp === 'source-atop') {
if ((dst[byteIdx] & mask) === 0) continue;
const r = srcData[srcOff];
@@ -272,7 +748,45 @@ export function compositeStrokeToTiles(
let outB = dst[dstOff + 2];
let outA = da;
- if (compositeOp === 'destination-out') {
+ if (usePigmentComposite) {
+ compositePigmentOverPixelInto(
+ outR,
+ outG,
+ outB,
+ da,
+ sr,
+ sg,
+ sb,
+ effA,
+ pigmentStrength,
+ pigmentWhiteGround,
+ compositeOp,
+ effectiveCombineMode,
+ pxOut
+ );
+ outR = pxOut[0];
+ outG = pxOut[1];
+ outB = pxOut[2];
+ outA = pxOut[3];
+ } else if (useCustomBlend) {
+ compositeBrushPixelInto(
+ outR,
+ outG,
+ outB,
+ da,
+ sr,
+ sg,
+ sb,
+ effA,
+ compositeOp,
+ effectiveCombineMode,
+ pxOut
+ );
+ outR = pxOut[0];
+ outG = pxOut[1];
+ outB = pxOut[2];
+ outA = pxOut[3];
+ } else if (compositeOp === 'destination-out') {
if (da === 0) continue;
if (effA === 255) {
outR = 0;
@@ -358,16 +872,24 @@ export function compositeStrokeToTiles(
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));
- }
+ if (effA <= 0) continue;
+ compositeBrushPixelInto(
+ tileScratch[dstOff],
+ tileScratch[dstOff + 1],
+ tileScratch[dstOff + 2],
+ tileScratch[dstOff + 3],
+ srcData[srcOff],
+ srcData[srcOff + 1],
+ srcData[srcOff + 2],
+ effA,
+ compositeOp,
+ effectiveCombineMode,
+ pxOut
+ );
+ tileScratch[dstOff] = pxOut[0];
+ tileScratch[dstOff + 1] = pxOut[1];
+ tileScratch[dstOff + 2] = pxOut[2];
+ tileScratch[dstOff + 3] = pxOut[3];
}
}
packRGBATo8Bit(tileScratch, tile.data);
diff --git a/src/utils/undoCache.ts b/src/utils/undoCache.ts
index e15daa0..48fde04 100644
--- a/src/utils/undoCache.ts
+++ b/src/utils/undoCache.ts
@@ -248,6 +248,35 @@ export class UndoCacheManager {
return job;
}
+ /**
+ * Returns true if tile deltas for this history item can be resolved synchronously
+ * without awaiting compressed RAM decompression, disk IPC, or an in-flight offload.
+ */
+ public canResolveDeltasSync(item: HistoryItem): boolean {
+ if (item.tileDeltas && item.tileDeltas.length > 0) {
+ return true;
+ }
+ return (
+ !this.inFlightOffloads.has(item.id) &&
+ !this.compressedRamCache.has(item.id) &&
+ !this.diskCachedIds.has(item.id)
+ );
+ }
+
+ /**
+ * Synchronously returns in-RAM tile deltas for a history item (pinning it against
+ * any in-flight offload). Only call when `canResolveDeltasSync(item)` is true.
+ */
+ public resolveDeltasSync(item: HistoryItem): TileDelta[] | null {
+ if (item.tileDeltas && item.tileDeltas.length > 0) {
+ if (this.inFlightOffloads.has(item.id)) {
+ this.keepInRamIds.add(item.id);
+ }
+ return item.tileDeltas;
+ }
+ return null;
+ }
+
/**
* Retrieve tile deltas for a history item, restoring from compressed RAM or disk if necessary.
*/