Skip to content

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

improvedd all app and design

sorae83d4d9adc75
diff --git a/package.json b/package.json
index 667ce79..7685f74 100644
--- a/package.json
+++ b/package.json
@@ -7,6 +7,7 @@
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
+ "test": "vitest run",
"tauri": "tauri"
},
"dependencies": {
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index c4ef812..8f2b236 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -2146,6 +2146,15 @@ version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
+[[package]]
+name = "lz4_flex"
+version = "0.11.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "373f5eceeeab7925e0c1098212f2fbc4d416adec9d35051a6ab251e824c1854a"
+dependencies = [
+ "twox-hash",
+]
+
[[package]]
name = "markup5ever"
version = "0.38.0"
@@ -3714,6 +3723,7 @@ version = "0.1.0"
dependencies = [
"axum",
"futures-util",
+ "lz4_flex",
"mime_guess",
"rust-embed",
"serde",
@@ -4355,6 +4365,12 @@ dependencies = [
"utf-8",
]
+[[package]]
+name = "twox-hash"
+version = "2.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2"
+
[[package]]
name = "typeid"
version = "1.0.3"
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 7125807..92f1416 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -28,6 +28,7 @@ tower-http = { version = "0.5", features = ["fs", "cors"] }
futures-util = "0.3"
rust-embed = "8.12.0"
mime_guess = "2.0.5"
+lz4_flex = "0.11"
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 9a3cd2d..b96e946 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -1,4 +1,6 @@
mod server;
+mod recovery;
+mod scratch_disk;
use server::{start_embedded_server, stop_embedded_server, get_server_status, get_local_ip, ServerInfo};
@@ -29,17 +31,50 @@ fn get_local_lan_ip() -> String {
get_local_ip()
}
+fn sanitize_id(raw: &str) -> String {
+ let s: String = raw
+ .chars()
+ .map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' })
+ .collect();
+ if s.is_empty() {
+ "default".to_string()
+ } else {
+ s
+ }
+}
+
+const ALLOWED_DOCUMENT_EXTS: &[&str] = &[
+ "sora", "ink", "psd", "psb", "clip", "csp", "sut", "png", "jpg", "jpeg", "webp", "bmp", "gif",
+ "svg", "glb", "gltf", "obj",
+];
+
+const MAX_READ_FILE_BYTES: u64 = 512 * 1024 * 1024; // 512 MB ceiling
+const MAX_UNDO_CACHE_BYTES: usize = 128 * 1024 * 1024; // 128 MB ceiling
+
+fn has_allowed_extension(p: &std::path::Path, allowed: &[&str]) -> bool {
+ p.extension()
+ .and_then(|e| e.to_str())
+ .map(|e| e.to_ascii_lowercase())
+ .map(|ext| allowed.contains(&ext.as_str()))
+ .unwrap_or(false)
+}
+
#[tauri::command]
async fn save_undo_tile_cache(
session_id: String,
state_id: String,
data: Vec<u8>,
) -> Result<(), String> {
- let temp_dir = std::env::temp_dir().join("inkstudio_undo").join(&session_id);
+ if data.len() > MAX_UNDO_CACHE_BYTES {
+ return Err("Undo tile payload exceeds maximum allowed size".to_string());
+ }
+ let safe_session = sanitize_id(&session_id);
+ let safe_state = sanitize_id(&state_id);
+ let temp_dir = std::env::temp_dir().join("inkstudio_undo").join(&safe_session);
tokio::fs::create_dir_all(&temp_dir)
.await
.map_err(|e| e.to_string())?;
- let file_path = temp_dir.join(format!("{}.bin", state_id));
+ let file_path = temp_dir.join(format!("{}.bin", safe_state));
tokio::fs::write(&file_path, data)
.await
.map_err(|e| e.to_string())?;
@@ -51,10 +86,12 @@ async fn load_undo_tile_cache(
session_id: String,
state_id: String,
) -> Result<Vec<u8>, String> {
+ let safe_session = sanitize_id(&session_id);
+ let safe_state = sanitize_id(&state_id);
let file_path = std::env::temp_dir()
.join("inkstudio_undo")
- .join(&session_id)
- .join(format!("{}.bin", state_id));
+ .join(&safe_session)
+ .join(format!("{}.bin", safe_state));
let data = tokio::fs::read(&file_path)
.await
.map_err(|e| e.to_string())?;
@@ -63,7 +100,8 @@ async fn load_undo_tile_cache(
#[tauri::command]
async fn clear_undo_tile_cache(session_id: String) -> Result<(), String> {
- let temp_dir = std::env::temp_dir().join("inkstudio_undo").join(&session_id);
+ let safe_session = sanitize_id(&session_id);
+ let temp_dir = std::env::temp_dir().join("inkstudio_undo").join(&safe_session);
if temp_dir.exists() {
let _ = tokio::fs::remove_dir_all(&temp_dir).await;
}
@@ -73,21 +111,123 @@ async fn clear_undo_tile_cache(session_id: String) -> Result<(), String> {
#[tauri::command]
async fn delete_file_from_disk(path: String) -> Result<bool, String> {
let p = std::path::Path::new(&path);
- if p.exists() {
- if p.is_file() {
- tokio::fs::remove_file(p).await.map_err(|e| e.to_string())?;
- return Ok(true);
- } else if p.is_dir() {
- tokio::fs::remove_dir_all(p).await.map_err(|e| e.to_string())?;
- return Ok(true);
- }
+ let meta = match tokio::fs::symlink_metadata(p).await {
+ Ok(m) => m,
+ Err(_) => return Ok(false),
+ };
+ if meta.file_type().is_symlink() {
+ return Err("Refusing to delete symbolic link".to_string());
}
- Ok(false)
+ if !meta.is_file() {
+ return Ok(false);
+ }
+ const DELETE_ALLOWED_EXTS: &[&str] = &[
+ "sora", "ink", "psd", "psb", "clip", "csp", "png", "jpg", "jpeg", "webp", "bmp", "gif", "svg",
+ ];
+ if !has_allowed_extension(p, DELETE_ALLOWED_EXTS) {
+ return Err("Refusing to delete file with unsupported extension".to_string());
+ }
+ tokio::fs::remove_file(p).await.map_err(|e| e.to_string())?;
+ Ok(true)
}
#[tauri::command]
async fn read_file_from_disk(path: String) -> Result<Vec<u8>, String> {
- tokio::fs::read(&path).await.map_err(|e| e.to_string())
+ let p = std::path::Path::new(&path);
+ if !has_allowed_extension(p, ALLOWED_DOCUMENT_EXTS) {
+ return Err("Refusing to read file with unsupported extension".to_string());
+ }
+ let meta = tokio::fs::metadata(p)
+ .await
+ .map_err(|_| "File does not exist or is inaccessible".to_string())?;
+ if !meta.is_file() {
+ return Err("Path is not a regular file".to_string());
+ }
+ if meta.len() > MAX_READ_FILE_BYTES {
+ return Err("File exceeds 512 MB safety limit".to_string());
+ }
+ tokio::fs::read(p).await.map_err(|e| e.to_string())
+}
+
+#[tauri::command]
+async fn recovery_init_session(
+ app: tauri::AppHandle,
+ session_id: String,
+ manifest_json: String,
+) -> Result<(), String> {
+ recovery::init_session(&app, &session_id, &manifest_json).await
+}
+
+#[tauri::command]
+async fn recovery_append_wal_entry(
+ app: tauri::AppHandle,
+ session_id: String,
+ entry_type: u8,
+ payload: Vec<u8>,
+) -> Result<(), String> {
+ recovery::append_wal_entry(&app, &session_id, entry_type, &payload).await
+}
+
+#[tauri::command]
+async fn recovery_checkpoint(
+ app: tauri::AppHandle,
+ session_id: String,
+ base_snapshot: Vec<u8>,
+ manifest_json: String,
+ thumbnail_png: Vec<u8>,
+) -> Result<(), String> {
+ recovery::checkpoint(&app, &session_id, &base_snapshot, &manifest_json, &thumbnail_png).await
+}
+
+#[tauri::command]
+async fn recovery_close_session(
+ app: tauri::AppHandle,
+ session_id: String,
+) -> Result<(), String> {
+ recovery::close_session(&app, &session_id).await
+}
+
+#[tauri::command]
+async fn recovery_check_crashed_sessions(
+ app: tauri::AppHandle,
+) -> Result<Vec<recovery::CrashedSessionInfo>, String> {
+ recovery::check_crashed_sessions(&app).await
+}
+
+#[tauri::command]
+async fn recovery_load_session_data(
+ app: tauri::AppHandle,
+ session_id: String,
+) -> Result<recovery::RecoveryReplayData, String> {
+ recovery::load_session_data(&app, &session_id).await
+}
+
+#[tauri::command]
+async fn scratch_disk_init(session_id: String) -> Result<(), String> {
+ scratch_disk::init_scratch_disk(&session_id).await.map(|_| ())
+}
+
+#[tauri::command]
+async fn scratch_disk_write_tiles(
+ session_id: String,
+ tiles: Vec<scratch_disk::TileWritePayload>,
+) -> Result<usize, String> {
+ scratch_disk::write_tiles(&session_id, tiles).await
+}
+
+#[tauri::command]
+async fn scratch_disk_read_tile(
+ session_id: String,
+ layer_id: String,
+ tile_x: i32,
+ tile_y: i32,
+) -> Result<Vec<u8>, String> {
+ scratch_disk::read_tile(&session_id, &layer_id, tile_x, tile_y).await
+}
+
+#[tauri::command]
+async fn scratch_disk_clear(session_id: String) -> Result<(), String> {
+ scratch_disk::clear_scratch_disk(&session_id).await
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
@@ -103,7 +243,17 @@ pub fn run() {
load_undo_tile_cache,
clear_undo_tile_cache,
delete_file_from_disk,
- read_file_from_disk
+ read_file_from_disk,
+ recovery_init_session,
+ recovery_append_wal_entry,
+ recovery_checkpoint,
+ recovery_close_session,
+ recovery_check_crashed_sessions,
+ recovery_load_session_data,
+ scratch_disk_init,
+ scratch_disk_write_tiles,
+ scratch_disk_read_tile,
+ scratch_disk_clear
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
diff --git a/src-tauri/src/recovery.rs b/src-tauri/src/recovery.rs
new file mode 100644
index 0000000..7e79be8
--- /dev/null
+++ b/src-tauri/src/recovery.rs
@@ -0,0 +1,535 @@
+use serde::{Deserialize, Serialize};
+use std::path::PathBuf;
+use tauri::Manager;
+use tokio::io::AsyncWriteExt;
+
+pub const WAL_MAGIC: &[u8; 4] = b"INKW";
+#[allow(dead_code)]
+pub const WAL_ENTRY_STROKE_TILE_DELTA: u8 = 1;
+#[allow(dead_code)]
+pub const WAL_ENTRY_VECTOR_STROKE: u8 = 2;
+#[allow(dead_code)]
+pub const WAL_ENTRY_LAYER_MUTATION: u8 = 3;
+
+const MAX_WAL_FRAME_PAYLOAD_BYTES: usize = 64 * 1024 * 1024; // 64 MB per WAL frame ceiling
+
+static WAL_IO_LOCK: std::sync::LazyLock<tokio::sync::Mutex<()>> =
+ std::sync::LazyLock::new(|| tokio::sync::Mutex::new(()));
+
+static WAL_TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
+
+// IEEE 802.3 standard CRC-32 table
+const CRC32_TABLE: [u32; 256] = {
+ let mut table = [0u32; 256];
+ let mut i = 0;
+ while i < 256 {
+ let mut c = i as u32;
+ let mut k = 0;
+ while k < 8 {
+ if c & 1 != 0 {
+ c = 0xEDB88320 ^ (c >> 1);
+ } else {
+ c >>= 1;
+ }
+ k += 1;
+ }
+ table[i] = c;
+ i += 1;
+ }
+ table
+};
+
+pub fn compute_crc32(data: &[u8]) -> u32 {
+ let mut crc = 0xFFFFFFFFu32;
+ for &byte in data {
+ let index = ((crc ^ (byte as u32)) & 0xFF) as usize;
+ crc = CRC32_TABLE[index] ^ (crc >> 8);
+ }
+ crc ^ 0xFFFFFFFFu32
+}
+
+pub fn to_base64(data: &[u8]) -> String {
+ const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ let mut result = String::with_capacity((data.len() + 2) / 3 * 4);
+ for chunk in data.chunks(3) {
+ let b0 = chunk[0];
+ let b1 = if chunk.len() > 1 { chunk[1] } else { 0 };
+ let b2 = if chunk.len() > 2 { chunk[2] } else { 0 };
+ result.push(CHARS[(b0 >> 2) as usize] as char);
+ result.push(CHARS[(((b0 & 0x03) << 4) | (b1 >> 4)) as usize] as char);
+ if chunk.len() > 1 {
+ result.push(CHARS[(((b1 & 0x0f) << 2) | (b2 >> 6)) as usize] as char);
+ } else {
+ result.push('=');
+ }
+ if chunk.len() > 2 {
+ result.push(CHARS[(b2 & 0x3f) as usize] as char);
+ } else {
+ result.push('=');
+ }
+ }
+ result
+}
+
+#[cfg(target_os = "windows")]
+pub fn is_process_running(pid: u32) -> bool {
+ if pid == 0 {
+ return false;
+ }
+ if pid == std::process::id() {
+ return true;
+ }
+ extern "system" {
+ fn OpenProcess(dwDesiredAccess: u32, bInheritHandle: i32, dwProcessId: u32) -> *mut std::ffi::c_void;
+ fn GetExitCodeProcess(hProcess: *mut std::ffi::c_void, lpExitCode: *mut u32) -> i32;
+ fn CloseHandle(hObject: *mut std::ffi::c_void) -> i32;
+ }
+
+ const PROCESS_QUERY_LIMITED_INFORMATION: u32 = 0x1000;
+ const STILL_ACTIVE: u32 = 259;
+
+ unsafe {
+ let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
+ if handle.is_null() {
+ return false;
+ }
+ let mut exit_code: u32 = 0;
+ let success = GetExitCodeProcess(handle, &mut exit_code);
+ CloseHandle(handle);
+ success != 0 && exit_code == STILL_ACTIVE
+ }
+}
+
+#[cfg(not(target_os = "windows"))]
+pub fn is_process_running(pid: u32) -> bool {
+ if pid == 0 {
+ return false;
+ }
+ if pid == std::process::id() {
+ return true;
+ }
+ extern "C" {
+ fn kill(pid: i32, sig: i32) -> i32;
+ }
+ unsafe {
+ kill(pid as i32, 0) == 0
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SessionLock {
+ pub pid: u32,
+ pub timestamp: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CrashedSessionInfo {
+ pub session_id: String,
+ pub timestamp: u64,
+ pub pid: u32,
+ pub manifest_json: Option<String>,
+ pub has_thumbnail: bool,
+ pub thumbnail_data_url: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct WalEntryData {
+ pub entry_type: u8,
+ pub payload: Vec<u8>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct RecoveryReplayData {
+ pub session_id: String,
+ pub manifest_json: String,
+ pub base_snapshot: Option<Vec<u8>>,
+ pub wal_entries: Vec<WalEntryData>,
+}
+
+pub fn get_recovery_root(app: &tauri::AppHandle) -> PathBuf {
+ #[cfg(target_os = "windows")]
+ {
+ if let Ok(local_app_data) = std::env::var("LOCALAPPDATA") {
+ return PathBuf::from(local_app_data).join("inkstudio_recovery");
+ }
+ }
+ if let Ok(dir) = app.path().app_local_data_dir() {
+ dir.join("inkstudio_recovery")
+ } else {
+ std::env::temp_dir().join("inkstudio_recovery")
+ }
+}
+
+fn sanitize_session_id(session_id: &str) -> String {
+ let s: String = session_id
+ .chars()
+ .map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' })
+ .collect();
+ if s.is_empty() {
+ "default_session".to_string()
+ } else {
+ s
+ }
+}
+
+pub async fn init_session(
+ app: &tauri::AppHandle,
+ session_id: &str,
+ manifest_json: &str,
+) -> Result<(), String> {
+ let _wal_guard = WAL_IO_LOCK.lock().await;
+ let safe_id = sanitize_session_id(session_id);
+ let session_dir = get_recovery_root(app).join(&safe_id);
+ tokio::fs::create_dir_all(&session_dir)
+ .await
+ .map_err(|e| format!("Failed to create recovery dir: {}", e))?;
+
+ let lock = SessionLock {
+ pid: std::process::id(),
+ timestamp: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_millis() as u64)
+ .unwrap_or(0),
+ };
+
+ let lock_json = serde_json::to_string_pretty(&lock).map_err(|e| e.to_string())?;
+ tokio::fs::write(session_dir.join("session.lock"), lock_json.as_bytes())
+ .await
+ .map_err(|e| format!("Failed to write session.lock: {}", e))?;
+
+ tokio::fs::write(session_dir.join("manifest.json"), manifest_json.as_bytes())
+ .await
+ .map_err(|e| format!("Failed to write manifest.json: {}", e))?;
+
+ let wal_path = session_dir.join("journal.wal");
+ if !tokio::fs::try_exists(&wal_path).await.unwrap_or(false) {
+ let _ = tokio::fs::write(&wal_path, &[]).await;
+ }
+
+ Ok(())
+}
+
+pub async fn append_wal_entry(
+ app: &tauri::AppHandle,
+ session_id: &str,
+ entry_type: u8,
+ payload: &[u8],
+) -> Result<(), String> {
+ if payload.len() > MAX_WAL_FRAME_PAYLOAD_BYTES {
+ return Err("WAL payload exceeds 64 MB safety ceiling".to_string());
+ }
+ let _wal_guard = WAL_IO_LOCK.lock().await;
+ let safe_id = sanitize_session_id(session_id);
+ let session_dir = get_recovery_root(app).join(&safe_id);
+ let wal_path = session_dir.join("journal.wal");
+
+ let mut frame = Vec::with_capacity(13 + payload.len());
+ frame.extend_from_slice(WAL_MAGIC);
+ frame.push(entry_type);
+ frame.extend_from_slice(&(payload.len() as u32).to_le_bytes());
+ let crc = compute_crc32(payload);
+ frame.extend_from_slice(&crc.to_le_bytes());
+ frame.extend_from_slice(payload);
+
+ let mut file = tokio::fs::OpenOptions::new()
+ .create(true)
+ .append(true)
+ .open(&wal_path)
+ .await
+ .map_err(|e| format!("Failed to open journal.wal for appending: {}", e))?;
+
+ file.write_all(&frame)
+ .await
+ .map_err(|e| format!("Failed to write WAL frame: {}", e))?;
+ file.flush()
+ .await
+ .map_err(|e| format!("Failed to flush WAL frame: {}", e))?;
+
+ Ok(())
+}
+
+pub async fn checkpoint(
+ app: &tauri::AppHandle,
+ session_id: &str,
+ base_snapshot: &[u8],
+ manifest_json: &str,
+ thumbnail_png: &[u8],
+) -> Result<(), String> {
+ let _wal_guard = WAL_IO_LOCK.lock().await;
+ let safe_id = sanitize_session_id(session_id);
+ let session_dir = get_recovery_root(app).join(&safe_id);
+ tokio::fs::create_dir_all(&session_dir)
+ .await
+ .map_err(|e| format!("Failed to create recovery dir: {}", e))?;
+
+ let seq = WAL_TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+
+ // 1. Atomically overwrite base_snapshot.bin (write to temp file, then rename)
+ let snapshot_path = session_dir.join("base_snapshot.bin");
+ let temp_snapshot_path = session_dir.join(format!("base_snapshot.bin.{}.{}.tmp", std::process::id(), seq));
+ tokio::fs::write(&temp_snapshot_path, base_snapshot)
+ .await
+ .map_err(|e| format!("Failed to write temp snapshot: {}", e))?;
+
+ if tokio::fs::rename(&temp_snapshot_path, &snapshot_path).await.is_err() {
+ let _ = tokio::fs::remove_file(&snapshot_path).await;
+ tokio::fs::rename(&temp_snapshot_path, &snapshot_path)
+ .await
+ .map_err(|e| format!("Failed to atomically rename snapshot: {}", e))?;
+ }
+
+ // 2. Truncate journal.wal to zero bytes while holding WAL_IO_LOCK
+ let wal_path = session_dir.join("journal.wal");
+ tokio::fs::write(&wal_path, &[])
+ .await
+ .map_err(|e| format!("Failed to truncate journal.wal: {}", e))?;
+
+ // 3. Updates manifest.json and thumbnail.png
+ let manifest_path = session_dir.join("manifest.json");
+ let temp_manifest_path = session_dir.join(format!("manifest.json.{}.{}.tmp", std::process::id(), seq));
+ tokio::fs::write(&temp_manifest_path, manifest_json.as_bytes())
+ .await
+ .map_err(|e| format!("Failed to write temp manifest.json: {}", e))?;
+ if tokio::fs::rename(&temp_manifest_path, &manifest_path).await.is_err() {
+ let _ = tokio::fs::remove_file(&manifest_path).await;
+ tokio::fs::rename(&temp_manifest_path, &manifest_path)
+ .await
+ .map_err(|e| format!("Failed to rename manifest.json: {}", e))?;
+ }
+
+ if !thumbnail_png.is_empty() {
+ let thumb_path = session_dir.join("thumbnail.png");
+ let _ = tokio::fs::write(&thumb_path, thumbnail_png).await;
+ }
+
+ Ok(())
+}
+
+pub async fn close_session(app: &tauri::AppHandle, session_id: &str) -> Result<(), String> {
+ let _wal_guard = WAL_IO_LOCK.lock().await;
+ let safe_id = sanitize_session_id(session_id);
+ let session_dir = get_recovery_root(app).join(&safe_id);
+ if tokio::fs::try_exists(&session_dir).await.unwrap_or(false) {
+ tokio::fs::remove_dir_all(&session_dir)
+ .await
+ .map_err(|e| format!("Failed to remove recovery session directory: {}", e))?;
+ }
+ Ok(())
+}
+
+pub async fn check_crashed_sessions(app: &tauri::AppHandle) -> Result<Vec<CrashedSessionInfo>, String> {
+ let root = get_recovery_root(app);
+ if !tokio::fs::try_exists(&root).await.unwrap_or(false) {
+ return Ok(Vec::new());
+ }
+
+ let mut read_dir = tokio::fs::read_dir(&root)
+ .await
+ .map_err(|e| format!("Failed to read recovery directory: {}", e))?;
+
+ let mut crashed_list = Vec::new();
+
+ while let Ok(Some(entry)) = read_dir.next_entry().await {
+ let path = entry.path();
+ if !path.is_dir() {
+ continue;
+ }
+
+ let lock_path = path.join("session.lock");
+ if !tokio::fs::try_exists(&lock_path).await.unwrap_or(false) {
+ continue;
+ }
+
+ let lock_data = match tokio::fs::read_to_string(&lock_path).await {
+ Ok(s) => s,
+ Err(_) => continue,
+ };
+
+ let lock: SessionLock = match serde_json::from_str(&lock_data) {
+ Ok(l) => l,
+ Err(_) => continue,
+ };
+
+ // If the process with that PID is dead/stale, it crashed!
+ if !is_process_running(lock.pid) {
+ let session_id = entry.file_name().to_string_lossy().to_string();
+
+ let manifest_path = path.join("manifest.json");
+ let manifest_json = tokio::fs::read_to_string(&manifest_path).await.ok();
+
+ let thumb_path = path.join("thumbnail.png");
+ let mut has_thumbnail = false;
+ let mut thumbnail_data_url = None;
+
+ if let Ok(thumb_bytes) = tokio::fs::read(&thumb_path).await {
+ if !thumb_bytes.is_empty() {
+ has_thumbnail = true;
+ thumbnail_data_url = Some(format!("data:image/png;base64,{}", to_base64(&thumb_bytes)));
+ }
+ }
+
+ crashed_list.push(CrashedSessionInfo {
+ session_id,
+ timestamp: lock.timestamp,
+ pid: lock.pid,
+ manifest_json,
+ has_thumbnail,
+ thumbnail_data_url,
+ });
+ }
+ }
+
+ // Sort newest crash first
+ crashed_list.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));
+ Ok(crashed_list)
+}
+
+pub async fn load_session_data(
+ app: &tauri::AppHandle,
+ session_id: &str,
+) -> Result<RecoveryReplayData, String> {
+ let safe_id = sanitize_session_id(session_id);
+ let session_dir = get_recovery_root(app).join(&safe_id);
+ if !tokio::fs::try_exists(&session_dir).await.unwrap_or(false) {
+ return Err(format!("Session {} does not exist", session_id));
+ }
+
+ let manifest_path = session_dir.join("manifest.json");
+ let manifest_json = tokio::fs::read_to_string(&manifest_path)
+ .await
+ .map_err(|e| format!("Failed to read manifest.json: {}", e))?;
+
+ let snapshot_path = session_dir.join("base_snapshot.bin");
+ let base_snapshot = tokio::fs::read(&snapshot_path).await.ok();
+
+ let wal_path = session_dir.join("journal.wal");
+ let mut wal_entries = Vec::new();
+
+ if let Ok(wal_bytes) = tokio::fs::read(&wal_path).await {
+ let mut offset = 0;
+ let total_len = wal_bytes.len();
+
+ while offset + 13 <= total_len {
+ if &wal_bytes[offset..offset + 4] != WAL_MAGIC {
+ // Bad magic header; discard remainder safely
+ break;
+ }
+
+ let entry_type = wal_bytes[offset + 4];
+ let payload_len = u32::from_le_bytes(
+ wal_bytes[offset + 5..offset + 9]
+ .try_into()
+ .unwrap(),
+ ) as usize;
+ let expected_crc = u32::from_le_bytes(
+ wal_bytes[offset + 9..offset + 13]
+ .try_into()
+ .unwrap(),
+ );
+
+ // Incomplete or oversized frame tail (process killed mid-write or corrupt length)
+ if payload_len > MAX_WAL_FRAME_PAYLOAD_BYTES || offset + 13 + payload_len > total_len {
+ break;
+ }
+
+ let payload = &wal_bytes[offset + 13..offset + 13 + payload_len];
+ let actual_crc = compute_crc32(payload);
+
+ // CRC32 mismatch (corrupted chunk)
+ if actual_crc != expected_crc {
+ break;
+ }
+
+ wal_entries.push(WalEntryData {
+ entry_type,
+ payload: payload.to_vec(),
+ });
+
+ offset += 13 + payload_len;
+ }
+ }
+
+ Ok(RecoveryReplayData {
+ session_id: session_id.to_string(),
+ manifest_json,
+ base_snapshot,
+ wal_entries,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_crc32_standard_vector() {
+ assert_eq!(compute_crc32(b"123456789"), 0xCBF43926);
+ }
+
+ #[test]
+ fn test_wal_frame_creation_and_parse() {
+ let payload = b"stroke-delta-test-data";
+ let mut frame = Vec::new();
+ frame.extend_from_slice(WAL_MAGIC);
+ frame.push(WAL_ENTRY_STROKE_TILE_DELTA);
+ frame.extend_from_slice(&(payload.len() as u32).to_le_bytes());
+ let crc = compute_crc32(payload);
+ frame.extend_from_slice(&crc.to_le_bytes());
+ frame.extend_from_slice(payload);
+
+ assert_eq!(&frame[0..4], b"INKW");
+ assert_eq!(frame[4], WAL_ENTRY_STROKE_TILE_DELTA);
+ let len = u32::from_le_bytes(frame[5..9].try_into().unwrap());
+ assert_eq!(len as usize, payload.len());
+ let read_crc = u32::from_le_bytes(frame[9..13].try_into().unwrap());
+ assert_eq!(read_crc, crc);
+ }
+
+ #[test]
+ fn test_incomplete_tail_discarded() {
+ let payload1 = b"first_stroke";
+ let payload2 = b"second_stroke";
+
+ let mut wal_bytes = Vec::new();
+
+ // Frame 1: valid
+ wal_bytes.extend_from_slice(WAL_MAGIC);
+ wal_bytes.push(1);
+ wal_bytes.extend_from_slice(&(payload1.len() as u32).to_le_bytes());
+ wal_bytes.extend_from_slice(&compute_crc32(payload1).to_le_bytes());
+ wal_bytes.extend_from_slice(payload1);
+
+ // Frame 2: partially written (only header + 3 bytes of payload)
+ wal_bytes.extend_from_slice(WAL_MAGIC);
+ wal_bytes.push(1);
+ wal_bytes.extend_from_slice(&(payload2.len() as u32).to_le_bytes());
+ wal_bytes.extend_from_slice(&compute_crc32(payload2).to_le_bytes());
+ wal_bytes.extend_from_slice(&payload2[..3]); // Truncated mid-write
+
+ // Parse logic simulation
+ let mut offset = 0;
+ let mut valid_entries = Vec::new();
+ while offset + 13 <= wal_bytes.len() {
+ if &wal_bytes[offset..offset + 4] != WAL_MAGIC {
+ break;
+ }
+ let entry_type = wal_bytes[offset + 4];
+ let payload_len = u32::from_le_bytes(wal_bytes[offset + 5..offset + 9].try_into().unwrap()) as usize;
+ let expected_crc = u32::from_le_bytes(wal_bytes[offset + 9..offset + 13].try_into().unwrap());
+
+ if offset + 13 + payload_len > wal_bytes.len() {
+ break; // Discard partial tail
+ }
+ let p = &wal_bytes[offset + 13..offset + 13 + payload_len];
+ if compute_crc32(p) != expected_crc {
+ break; // Discard corrupted tail
+ }
+ valid_entries.push((entry_type, p.to_vec()));
+ offset += 13 + payload_len;
+ }
+
+ assert_eq!(valid_entries.len(), 1);
+ assert_eq!(valid_entries[0].1, payload1);
+ }
+}
+
diff --git a/src-tauri/src/scratch_disk.rs b/src-tauri/src/scratch_disk.rs
new file mode 100644
index 0000000..95d0fe4
--- /dev/null
+++ b/src-tauri/src/scratch_disk.rs
@@ -0,0 +1,435 @@
+use serde::{Deserialize, Serialize};
+use std::collections::HashMap;
+use std::path::PathBuf;
+use std::sync::Mutex;
+use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt, SeekFrom};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TileWritePayload {
+ #[serde(alias = "layer_id", alias = "layerId")]
+ pub layer_id: String,
+ #[serde(alias = "tile_x", alias = "tileX")]
+ pub tile_x: i32,
+ #[serde(alias = "tile_y", alias = "tileY")]
+ pub tile_y: i32,
+ pub data: Vec<u8>,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
+pub struct TileIndexEntry {
+ pub tile_x: i32,
+ pub tile_y: i32,
+ pub offset: u64,
+ pub compressed_len: u32,
+ pub uncompressed_len: u32,
+}
+
+// Global in-memory index table: session_id -> layer_id -> (tile_x, tile_y) -> TileIndexEntry
+type ScratchRegistry = Mutex<HashMap<String, HashMap<String, HashMap<(i32, i32), TileIndexEntry>>>>;
+
+static SCRATCH_REGISTRY: std::sync::LazyLock<ScratchRegistry> =
+ std::sync::LazyLock::new(|| Mutex::new(HashMap::new()));
+
+static SCRATCH_IO_LOCK: std::sync::LazyLock<tokio::sync::Mutex<()>> =
+ std::sync::LazyLock::new(|| tokio::sync::Mutex::new(()));
+
+static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
+
+const MAX_UNCOMPRESSED_TILE_BYTES: usize = 4 * 1024 * 1024; // 4 MB max per 256x256 tile
+const MAX_COMPRESSED_TILE_BYTES: u32 = 8 * 1024 * 1024; // 8 MB max compressed payload
+
+pub fn get_scratch_root(session_id: &str) -> PathBuf {
+ let safe_session = sanitize_layer_id(session_id);
+ std::env::temp_dir()
+ .join("inkstudio_scratch")
+ .join(safe_session)
+}
+
+fn sanitize_layer_id(layer_id: &str) -> String {
+ let s: String = layer_id
+ .chars()
+ .map(|c| if c.is_alphanumeric() || c == '-' || c == '_' { c } else { '_' })
+ .collect();
+ if s.is_empty() {
+ "default_layer".to_string()
+ } else {
+ s
+ }
+}
+
+pub async fn init_scratch_disk(session_id: &str) -> Result<PathBuf, String> {
+ let dir = get_scratch_root(session_id);
+ tokio::fs::create_dir_all(&dir)
+ .await
+ .map_err(|e| format!("Failed to create scratch directory: {}", e))?;
+
+ {
+ let mut reg = SCRATCH_REGISTRY
+ .lock()
+ .map_err(|_| "Failed to acquire scratch registry lock".to_string())?;
+ reg.entry(session_id.to_string()).or_default();
+ }
+
+ Ok(dir)
+}
+
+pub async fn write_tiles(
+ session_id: &str,
+ tiles: Vec<TileWritePayload>,
+) -> Result<usize, String> {
+ if tiles.is_empty() {
+ return Ok(0);
+ }
+
+ let _io_guard = SCRATCH_IO_LOCK.lock().await;
+
+ let scratch_dir = get_scratch_root(session_id);
+ if !scratch_dir.exists() {
+ tokio::fs::create_dir_all(&scratch_dir)
+ .await
+ .map_err(|e| format!("Failed to create scratch dir: {}", e))?;
+ }
+
+ // Group tiles by layer
+ let mut tiles_by_layer: HashMap<String, Vec<TileWritePayload>> = HashMap::new();
+ for tile in tiles {
+ tiles_by_layer
+ .entry(tile.layer_id.clone())
+ .or_default()
+ .push(tile);
+ }
+
+ let count_written = tiles_by_layer.values().map(|v| v.len()).sum();
+
+ for (layer_id, layer_tiles) in tiles_by_layer {
+ let safe_name = sanitize_layer_id(&layer_id);
+ let bucket_path = scratch_dir.join(format!("bucket_{}.bin", safe_name));
+ let index_path = scratch_dir.join(format!("index_{}.bin", safe_name));
+ let seq = TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ let index_tmp_path = scratch_dir.join(format!("index_{}_{}.tmp", safe_name, seq));
+
+ // Snapshot existing entries for this layer so we can reuse in-place slots when compressed data fits
+ let existing_layer_entries = {
+ let reg = SCRATCH_REGISTRY
+ .lock()
+ .map_err(|_| "Failed to lock scratch registry".to_string())?;
+ reg.get(session_id)
+ .and_then(|sm| sm.get(&layer_id))
+ .cloned()
+ .unwrap_or_default()
+ };
+
+ // Open bucket file in read+write mode
+ let mut bucket_file = tokio::fs::OpenOptions::new()
+ .create(true)
+ .read(true)
+ .write(true)
+ .open(&bucket_path)
+ .await
+ .map_err(|e| format!("Failed to open bucket file {}: {}", bucket_path.display(), e))?;
+
+ let mut end_offset = bucket_file
+ .seek(SeekFrom::End(0))
+ .await
+ .map_err(|e| format!("Failed to seek bucket file: {}", e))?;
+
+ let mut new_entries: Vec<TileIndexEntry> = Vec::with_capacity(layer_tiles.len());
+
+ for tile in layer_tiles {
+ if tile.data.len() > MAX_UNCOMPRESSED_TILE_BYTES {
+ return Err("Tile uncompressed payload exceeds 4 MB safety ceiling".to_string());
+ }
+ let uncompressed_len = tile.data.len() as u32;
+ let compressed = lz4_flex::compress_prepend_size(&tile.data);
+ let compressed_len = compressed.len() as u32;
+
+ let write_offset = if let Some(prev) = existing_layer_entries.get(&(tile.tile_x, tile.tile_y)) {
+ if compressed_len <= prev.compressed_len {
+ bucket_file
+ .seek(SeekFrom::Start(prev.offset))
+ .await
+ .map_err(|e| format!("Failed to seek bucket file: {}", e))?;
+ prev.offset
+ } else {
+ bucket_file
+ .seek(SeekFrom::Start(end_offset))
+ .await
+ .map_err(|e| format!("Failed to seek bucket file: {}", e))?;
+ let off = end_offset;
+ end_offset += compressed_len as u64;
+ off
+ }
+ } else {
+ bucket_file
+ .seek(SeekFrom::Start(end_offset))
+ .await
+ .map_err(|e| format!("Failed to seek bucket file: {}", e))?;
+ let off = end_offset;
+ end_offset += compressed_len as u64;
+ off
+ };
+
+ bucket_file
+ .write_all(&compressed)
+ .await
+ .map_err(|e| format!("Failed to write to bucket file: {}", e))?;
+
+ new_entries.push(TileIndexEntry {
+ tile_x: tile.tile_x,
+ tile_y: tile.tile_y,
+ offset: write_offset,
+ compressed_len,
+ uncompressed_len,
+ });
+ }
+
+ bucket_file
+ .flush()
+ .await
+ .map_err(|e| format!("Failed to flush bucket file: {}", e))?;
+
+ // Update in-memory registry and prepare binary index bytes without holding lock across await
+ let index_bytes = {
+ let mut reg = SCRATCH_REGISTRY
+ .lock()
+ .map_err(|_| "Failed to lock scratch registry".to_string())?;
+
+ let session_map = reg.entry(session_id.to_string()).or_default();
+ let layer_map = session_map.entry(layer_id.clone()).or_default();
+
+ for entry in &new_entries {
+ layer_map.insert((entry.tile_x, entry.tile_y), *entry);
+ }
+
+ let total_entries = layer_map.len();
+ let mut bytes = Vec::with_capacity(4 + total_entries * 24);
+ bytes.extend_from_slice(&(total_entries as u32).to_le_bytes());
+
+ for entry in layer_map.values() {
+ bytes.extend_from_slice(&entry.tile_x.to_le_bytes());
+ bytes.extend_from_slice(&entry.tile_y.to_le_bytes());
+ bytes.extend_from_slice(&entry.offset.to_le_bytes());
+ bytes.extend_from_slice(&entry.compressed_len.to_le_bytes());
+ bytes.extend_from_slice(&entry.uncompressed_len.to_le_bytes());
+ }
+
+ bytes
+ };
+
+ // Atomically write index table to .tmp then rename (with fallback remove on Windows)
+ tokio::fs::write(&index_tmp_path, &index_bytes)
+ .await
+ .map_err(|e| format!("Failed to write index temp file: {}", e))?;
+
+ if tokio::fs::rename(&index_tmp_path, &index_path).await.is_err() {
+ let _ = tokio::fs::remove_file(&index_path).await;
+ tokio::fs::rename(&index_tmp_path, &index_path)
+ .await
+ .map_err(|e| format!("Failed to atomically update index file: {}", e))?;
+ }
+ }
+
+ Ok(count_written)
+}
+
+pub async fn read_tile(
+ session_id: &str,
+ layer_id: &str,
+ tile_x: i32,
+ tile_y: i32,
+) -> Result<Vec<u8>, String> {
+ let _io_guard = SCRATCH_IO_LOCK.lock().await;
+
+ // 1. Look up in in-memory registry first
+ let entry = {
+ let reg = SCRATCH_REGISTRY
+ .lock()
+ .map_err(|_| "Failed to lock scratch registry".to_string())?;
+
+ reg.get(session_id)
+ .and_then(|sm| sm.get(layer_id))
+ .and_then(|lm| lm.get(&(tile_x, tile_y)).copied())
+ };
+
+ let entry = match entry {
+ Some(e) => e,
+ None => {
+ // Not in memory; attempt to load index table from disk
+ let safe_name = sanitize_layer_id(layer_id);
+ let index_path = get_scratch_root(session_id).join(format!("index_{}.bin", safe_name));
+ if !index_path.exists() {
+ return Err(format!(
+ "Tile index not found for layer {} (tile=[{}, {}])",
+ layer_id, tile_x, tile_y
+ ));
+ }
+
+ let data = tokio::fs::read(&index_path)
+ .await
+ .map_err(|e| format!("Failed to read index file: {}", e))?;
+
+ if data.len() < 4 {
+ return Err("Corrupt index table: header too short".to_string());
+ }
+
+ let count = u32::from_le_bytes(data[0..4].try_into().unwrap()) as usize;
+ let mut offset = 4;
+ let mut found_entry: Option<TileIndexEntry> = None;
+
+ {
+ let mut reg = SCRATCH_REGISTRY
+ .lock()
+ .map_err(|_| "Failed to lock scratch registry".to_string())?;
+
+ let session_map = reg.entry(session_id.to_string()).or_default();
+ let layer_map = session_map.entry(layer_id.to_string()).or_default();
+
+ for _ in 0..count {
+ if offset + 24 <= data.len() {
+ let tx = i32::from_le_bytes(data[offset..offset + 4].try_into().unwrap());
+ let ty = i32::from_le_bytes(data[offset + 4..offset + 8].try_into().unwrap());
+ let off = u64::from_le_bytes(data[offset + 8..offset + 16].try_into().unwrap());
+ let clen = u32::from_le_bytes(data[offset + 16..offset + 20].try_into().unwrap());
+ let ulen = u32::from_le_bytes(data[offset + 20..offset + 24].try_into().unwrap());
+ offset += 24;
+
+ let ent = TileIndexEntry {
+ tile_x: tx,
+ tile_y: ty,
+ offset: off,
+ compressed_len: clen,
+ uncompressed_len: ulen,
+ };
+
+ if tx == tile_x && ty == tile_y {
+ found_entry = Some(ent);
+ }
+
+ layer_map.insert((tx, ty), ent);
+ }
+ }
+ }
+
+ found_entry.ok_or_else(|| {
+ format!(
+ "Tile not found in index (session={}, layer={}, tile=[{}, {}])",
+ session_id, layer_id, tile_x, tile_y
+ )
+ })?
+ }
+ };
+
+ if entry.compressed_len == 0
+ || entry.compressed_len > MAX_COMPRESSED_TILE_BYTES
+ || (entry.uncompressed_len as usize) > MAX_UNCOMPRESSED_TILE_BYTES
+ {
+ return Err("Corrupt or oversized tile index entry".to_string());
+ }
+
+ // 2. Read compressed payload from bucket file
+ let safe_name = sanitize_layer_id(layer_id);
+ let bucket_path = get_scratch_root(session_id).join(format!("bucket_{}.bin", safe_name));
+
+ let mut bucket_file = tokio::fs::File::open(&bucket_path)
+ .await
+ .map_err(|e| format!("Failed to open bucket file {}: {}", bucket_path.display(), e))?;
+
+ bucket_file
+ .seek(SeekFrom::Start(entry.offset))
+ .await
+ .map_err(|e| format!("Failed to seek to tile offset {}: {}", entry.offset, e))?;
+
+ let mut compressed_buf = vec![0u8; entry.compressed_len as usize];
+ bucket_file
+ .read_exact(&mut compressed_buf)
+ .await
+ .map_err(|e| format!("Failed to read compressed tile bytes: {}", e))?;
+
+ if compressed_buf.len() < 4 {
+ return Err("Corrupt LZ4 tile header".to_string());
+ }
+ let declared_uncompressed = u32::from_le_bytes(compressed_buf[0..4].try_into().unwrap()) as usize;
+ if declared_uncompressed > MAX_UNCOMPRESSED_TILE_BYTES {
+ return Err("LZ4 declared uncompressed size exceeds 4 MB safety ceiling".to_string());
+ }
+
+ // 3. Decompress using LZ4
+ let decompressed = lz4_flex::decompress_size_prepended(&compressed_buf)
+ .map_err(|e| format!("LZ4 decompression failed: {}", e))?;
+
+ Ok(decompressed)
+}
+
+pub async fn clear_scratch_disk(session_id: &str) -> Result<(), String> {
+ let _io_guard = SCRATCH_IO_LOCK.lock().await;
+
+ // 1. Remove from in-memory registry
+ if let Ok(mut reg) = SCRATCH_REGISTRY.lock() {
+ reg.remove(session_id);
+ }
+
+ // 2. Recursively delete disk files
+ let dir = get_scratch_root(session_id);
+ if dir.exists() {
+ tokio::fs::remove_dir_all(&dir)
+ .await
+ .map_err(|e| format!("Failed to remove scratch directory {}: {}", dir.display(), e))?;
+ }
+
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[tokio::test]
+ async fn test_scratch_disk_roundtrip() {
+ let session_id = format!("test_session_{}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos());
+
+ let _ = init_scratch_disk(&session_id).await.expect("init failed");
+
+ let test_data_1 = vec![42u8; 8192]; // 1-bit tile 8KB
+ let test_data_2 = vec![127u8; 65536]; // 8-bit tile 64KB
+ let test_data_3 = vec![255u8; 262144]; // 32-bit tile 256KB
+
+ let tiles = vec![
+ TileWritePayload {
+ layer_id: "layer_mono".to_string(),
+ tile_x: 0,
+ tile_y: 0,
+ data: test_data_1.clone(),
+ },
+ TileWritePayload {
+ layer_id: "layer_gray".to_string(),
+ tile_x: 1,
+ tile_y: 0,
+ data: test_data_2.clone(),
+ },
+ TileWritePayload {
+ layer_id: "layer_color".to_string(),
+ tile_x: 0,
+ tile_y: 1,
+ data: test_data_3.clone(),
+ },
+ ];
+
+ let count = write_tiles(&session_id, tiles).await.expect("write failed");
+ assert_eq!(count, 3);
+
+ // Read each back
+ let read_1 = read_tile(&session_id, "layer_mono", 0, 0).await.expect("read 1 failed");
+ assert_eq!(read_1, test_data_1);
+
+ let read_2 = read_tile(&session_id, "layer_gray", 1, 0).await.expect("read 2 failed");
+ assert_eq!(read_2, test_data_2);
+
+ let read_3 = read_tile(&session_id, "layer_color", 0, 1).await.expect("read 3 failed");
+ assert_eq!(read_3, test_data_3);
+
+ // Clear scratch disk
+ clear_scratch_disk(&session_id).await.expect("clear failed");
+ assert!(!get_scratch_root(&session_id).exists());
+ }
+}
diff --git a/src-tauri/src/server.rs b/src-tauri/src/server.rs
index dc74cba..c24a82f 100644
--- a/src-tauri/src/server.rs
+++ b/src-tauri/src/server.rs
@@ -170,29 +170,32 @@ async fn locate_or_download_cloudflared() -> Result<PathBuf, String> {
}
}
- // 5. Automatic background download from official Cloudflare releases
+ // 5. Automatic background download from official Cloudflare releases (no shell interpolation)
if let Some(parent) = target_path.parent() {
let _ = tokio::fs::create_dir_all(parent).await;
}
- let download_cmd = format!(
- "curl.exe -L \"https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-windows-amd64.exe\" -o \"{}\"",
- target_path.display()
- );
-
- let mut download_proc = tokio::process::Command::new("powershell");
- download_proc.args(&["-NoProfile", "-Command", &download_cmd]);
+ let mut download_proc = tokio::process::Command::new("curl.exe");
+ download_proc.args([
+ "-f",
+ "-L",
+ "-s",
+ "https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-windows-amd64.exe",
+ "-o",
+ ]);
+ download_proc.arg(&target_path);
#[cfg(windows)]
download_proc.creation_flags(CREATE_NO_WINDOW);
let status = download_proc
.status()
.await
- .map_err(|e| format!("Failed to run download process: {}", e))?;
+ .map_err(|e| format!("Failed to run curl.exe download process: {}", e))?;
if status.success() && target_path.exists() {
Ok(target_path)
} else {
+ let _ = tokio::fs::remove_file(&target_path).await;
Err("Failed to download cloudflared tunnel client".to_string())
}
}
@@ -214,13 +217,13 @@ fn extract_trycloudflare_url(line: &str) -> Option<String> {
async fn start_cloudflare_tunnel(port: u16) -> Result<(tokio::process::Child, String), String> {
let exe_path = locate_or_download_cloudflared().await?;
let mut cmd = tokio::process::Command::new(exe_path);
- cmd.args(&[
+ cmd.args([
"tunnel",
"--url",
&format!("http://127.0.0.1:{}", port),
"--no-autoupdate",
])
- .stdout(Stdio::piped())
+ .stdout(Stdio::null())
.stderr(Stdio::piped());
#[cfg(windows)]
@@ -237,22 +240,26 @@ async fn start_cloudflare_tunnel(port: u16) -> Result<(tokio::process::Child, St
let mut reader = BufReader::new(stderr).lines();
- let find_url = async {
- while let Ok(Some(line)) = reader.next_line().await {
- if let Some(url) = extract_trycloudflare_url(&line) {
- return Some(url);
- }
- }
- None
- };
-
let tunnel_url = tokio::select! {
- url = find_url => url,
+ url = async {
+ while let Ok(Some(line)) = reader.next_line().await {
+ if let Some(url) = extract_trycloudflare_url(&line) {
+ return Some(url);
+ }
+ }
+ None
+ } => url,
_ = tokio::time::sleep(tokio::time::Duration::from_secs(18)) => None,
};
match tunnel_url {
- Some(url) => Ok((child, url)),
+ Some(url) => {
+ // Keep draining stderr in the background so cloudflared never receives EPIPE
+ tokio::spawn(async move {
+ while let Ok(Some(_)) = reader.next_line().await {}
+ });
+ Ok((child, url))
+ }
None => {
let _ = child.kill().await;
Err("Timed out waiting for Cloudflare tunnel URL".to_string())
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index 403269a..f03a443 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -22,7 +22,7 @@
}
],
"security": {
- "csp": null
+ "csp": "default-src 'self' ipc: http://ipc.localhost; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' asset: http://asset.localhost blob: data:; font-src 'self' data:; media-src 'self' blob: data:; worker-src 'self' blob:; connect-src 'self' ipc: http://ipc.localhost asset: http://asset.localhost ws: wss: http://127.0.0.1:* http://localhost:*; object-src 'none'; base-uri 'self'"
}
},
"bundle": {
diff --git a/src/App.tsx b/src/App.tsx
index 929d063..91216c4 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -34,7 +34,7 @@ import {
import { applyLiquifyStep, createLiquifySelectionMask, DirtyRect } from './utils/liquifyEngine';
import { PerspectiveRuler, ConstraintAxis } from './types/perspective';
import { createDefaultPerspectiveRuler, applyWormsEyePreset } from './utils/perspectiveMath';
-import { executeFloodFill, compositeVisibleLayers, executeLassoFill } from './utils/floodFill';
+import { executeFloodFill, compositeVisibleLayers, compositeReferenceLayers, executeLassoFill } from './utils/floodFill';
import {
isPointInSelection,
liftSelectionToFloating,
@@ -67,15 +67,14 @@ import {
promptSaveAs,
saveToExistingHandle,
promptExportPngImage,
+ compositeCanvas,
SaveDocumentData,
SavedFileInfo,
} from './utils/saveManager';
import { Header } from './components/Header';
-import { DocumentTabBar } from './components/DocumentTabBar';
import { LeftPanel } from './components/LeftPanel';
import { CanvasArea } from './components/CanvasArea';
import { RightSidebar } from './components/RightSidebar';
-import { StatusBar } from './components/StatusBar';
import { NewCanvasModal } from './components/NewCanvasModal';
import { ResizeCanvasModal } from './components/ResizeCanvasModal';
import { SettingsModal } from './components/SettingsModal';
@@ -85,10 +84,10 @@ import { HostModal } from './components/HostModal';
import { ClipboardInviteToast } from './components/ClipboardInviteToast';
import { WebLandingModal } from './components/WebLandingModal';
import { WelcomeScreen } from './components/WelcomeScreen';
-import { ModernPropertyBar } from './components/ModernPropertyBar';
-import { FirstTimeNameModal } from './components/FirstTimeNameModal';
import { AdjustmentModal } from './components/AdjustmentModal';
import { LayerStylesModal } from './components/LayerStylesModal';
+import { recoveryService, CrashedSessionInfo } from './services/recoveryService';
+import { CrashRecoveryModal } from './components/CrashRecoveryModal';
import { applyFilter } from './utils/filterEngine';
import { saveRecentDocument, RecentDocument } from './utils/recentDocumentsManager';
import {
@@ -101,7 +100,7 @@ import {
screenToCanvas,
sampleCompositedColor,
} from './utils/canvasUtils';
-import { globalTileGrid } from './utils/tileEngine';
+import { globalTileGrid, globalTileMemoryManager } from './utils/tileEngine';
import { getNextCollabLayerName } from './hooks/useLayerManager';
import { drawPencilDot, drawPencilBezierSegment, PencilGrade } from './utils/pencilEngine';
import { Point } from './types/editor';
@@ -135,6 +134,7 @@ import {
saveAppSettings,
ResizeCanvasOptions,
resolveModernAccentColor,
+ getAccentContrastColor,
hexToRgb,
} from './types/settings';
import {
@@ -179,7 +179,6 @@ import {
Sparkles,
MessageSquare,
Spline,
- Check,
} from 'lucide-react';
import { parseSutFile } from './utils/sutParser';
import {
@@ -189,7 +188,9 @@ import {
loadCustomBrushes,
} from './utils/brushStorage';
import {
- saveBrushSettingsImmediately,
+ saveBrushSettingsDebounced,
+ flushPendingBrushSettingsSave,
+ stepBrushSizePreset,
getEffectiveBrushSettings,
getActivePresetId,
saveActivePresetId,
@@ -393,25 +394,26 @@ export function App() {
const hasOpenDocument = Boolean(activeDocumentId && documents.some((d) => d.id === activeDocumentId));
const [appView, setAppView] = useState<'home' | 'workspace'>('workspace');
- // Panels width & visibility (global resizability)
+ // Panels width & visibility (compact defaults dedicating >80% viewport to canvas)
const [leftPanelWidth, setLeftPanelWidth] = useState<number>(() => {
- const s = localStorage.getItem('sora_paint_left_panel_width');
- return s ? Number(s) : 260;
+ const s = localStorage.getItem('ink_left_panel_width_v3');
+ return s ? Number(s) : 118;
});
const [isLeftPanelHidden, setIsLeftPanelHidden] = useState<boolean>(false);
+ const [isRightSidebarHidden, setIsRightSidebarHidden] = useState<boolean>(false);
const [rightSidebarWidth, setRightSidebarWidth] = useState<number>(() => {
- const s = localStorage.getItem('sora_paint_right_sidebar_width');
- return s ? Number(s) : 320;
+ const s = localStorage.getItem('ink_right_sidebar_width_v3');
+ return s ? Number(s) : 162;
});
const handleLeftPanelWidthChange = useCallback((w: number) => {
setLeftPanelWidth(w);
- localStorage.setItem('sora_paint_left_panel_width', String(w));
+ localStorage.setItem('ink_left_panel_width_v3', String(w));
}, []);
const handleRightSidebarWidthChange = useCallback((w: number) => {
setRightSidebarWidth(w);
- localStorage.setItem('sora_paint_right_sidebar_width', String(w));
+ localStorage.setItem('ink_right_sidebar_width_v3', String(w));
}, []);
const draftCanvasRef = useRef<HTMLCanvasElement | null>(null);
@@ -424,32 +426,25 @@ export function App() {
const [appSettings, setAppSettings] = useState<AppSettings>(loadAppSettings);
useEffect(() => {
- const theme = appSettings.themePreset || 'vintage-manga';
- document.documentElement.setAttribute('data-theme', theme);
-
- if (theme === 'modern') {
- const accent = appSettings.modernAccent || 'blue';
- const hex = resolveModernAccentColor(accent, appSettings.modernCustomColor);
- const rgb = hexToRgb(hex) || { r: 59, g: 130, b: 246 };
- document.documentElement.setAttribute('data-accent', accent);
- document.documentElement.setAttribute('data-tone', appSettings.uiTone || 'slate');
- document.documentElement.style.setProperty('--modern-accent', hex);
- document.documentElement.style.setProperty('--modern-accent-rgb', `${rgb.r}, ${rgb.g}, ${rgb.b}`);
- document.documentElement.style.setProperty('--modern-accent-glow', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.3)`);
- document.documentElement.style.setProperty('--modern-accent-subtle', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.12)`);
- document.documentElement.style.setProperty('--modern-accent-border', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.4)`);
- document.documentElement.style.setProperty('--modern-accent-hover', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.2)`);
- } else {
- document.documentElement.removeAttribute('data-accent');
- document.documentElement.removeAttribute('data-tone');
- document.documentElement.style.removeProperty('--modern-accent');
- document.documentElement.style.removeProperty('--modern-accent-rgb');
- document.documentElement.style.removeProperty('--modern-accent-glow');
- document.documentElement.style.removeProperty('--modern-accent-subtle');
- document.documentElement.style.removeProperty('--modern-accent-border');
- document.documentElement.style.removeProperty('--modern-accent-hover');
- }
- }, [appSettings.themePreset, appSettings.modernAccent, appSettings.modernCustomColor, appSettings.uiTone]);
+ const accent = appSettings.modernAccent || 'neutral';
+ const hex = resolveModernAccentColor(accent, appSettings.modernCustomColor);
+ const rgb = hexToRgb(hex) || { r: 229, g: 229, b: 229 };
+ const contrast = getAccentContrastColor(hex);
+
+ const root = document.documentElement;
+ root.setAttribute('data-theme', 'modern');
+ root.setAttribute('data-accent', accent);
+ root.style.setProperty('--accent', hex);
+ root.style.setProperty('--accent-rgb', `${rgb.r}, ${rgb.g}, ${rgb.b}`);
+ root.style.setProperty('--accent-contrast', contrast);
+ root.style.setProperty('--accent-subtle', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.14)`);
+ root.style.setProperty('--accent-border', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.32)`);
+ root.style.setProperty('--modern-accent', hex);
+ root.style.setProperty('--modern-accent-rgb', `${rgb.r}, ${rgb.g}, ${rgb.b}`);
+ root.style.setProperty('--modern-accent-subtle', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.14)`);
+ root.style.setProperty('--modern-accent-border', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.32)`);
+ root.style.setProperty('--modern-accent-hover', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.2)`);
+ }, [appSettings.modernAccent, appSettings.modernCustomColor]);
const [isNewCanvasModalOpen, setIsNewCanvasModalOpen] = useState<boolean>(false);
const [isResizeCanvasModalOpen, setIsResizeCanvasModalOpen] = useState<boolean>(false);
@@ -477,6 +472,26 @@ export function App() {
const [isLoadingFile, setIsLoadingFile] = useState<boolean>(false);
const [loadingStatus, setLoadingStatus] = useState<string>('');
+ // Fault-Tolerant Crash Recovery (WAL Architecture) State
+ const [crashedSessions, setCrashedSessions] = useState<CrashedSessionInfo[]>([]);
+ const [isRecoveryModalOpen, setIsRecoveryModalOpen] = useState<boolean>(false);
+
+ // Crash Recovery: detect unfinalized crashed sessions on startup
+ useEffect(() => {
+ recoveryService
+ .checkForCrashedSessions()
+ .then((sessions) => {
+ if (sessions && sessions.length > 0) {
+ setCrashedSessions(sessions);
+ setIsRecoveryModalOpen(true);
+ }
+ })
+ .catch((err) => {
+ console.warn('[Recovery] Error scanning for crashed sessions:', err);
+ });
+ }, []);
+
+
const fileInputRef = useRef<HTMLInputElement>(null);
const pasteFileInputRef = useRef<HTMLInputElement>(null);
const import3DFileInputRef = useRef<HTMLInputElement>(null);
@@ -629,7 +644,68 @@ export function App() {
addAdjustmentLayer,
updateAdjustmentData,
updateLayerStyles,
- } = useLayerManager({ dimensions });
+ } = useLayerManager({ dimensions, activeSessionId: activeDocumentId });
+
+ // Synchronize active document recovery session and WAL periodic checkpointing
+ const recoveryStateRef = useRef({
+ documents,
+ documentName,
+ dimensions,
+ colorMode,
+ layers,
+ activeLayerId,
+ });
+ recoveryStateRef.current = {
+ documents,
+ documentName,
+ dimensions,
+ colorMode,
+ layers,
+ activeLayerId,
+ };
+
+ useEffect(() => {
+ if (!activeDocumentId) return;
+ const st = recoveryStateRef.current;
+ const initDoc = st.documents.find((d) => d.id === activeDocumentId);
+ if (!initDoc) return;
+
+ recoveryService.initSession(
+ activeDocumentId,
+ () => {
+ const cur = recoveryStateRef.current;
+ const doc = cur.documents.find((d) => d.id === activeDocumentId);
+ return {
+ sessionId: activeDocumentId,
+ documentName: doc?.name || cur.documentName || 'Untitled Document',
+ width: doc?.dimensions.width || cur.dimensions.width,
+ height: doc?.dimensions.height || cur.dimensions.height,
+ dpi: doc?.dimensions.dpi || cur.dimensions.dpi || 600,
+ colorMode: doc?.colorMode || cur.colorMode || 'color',
+ layers: doc?.layers || cur.layers,
+ activeLayerId: doc?.activeLayerId || cur.activeLayerId,
+ timestamp: Date.now(),
+ };
+ },
+ async () => {
+ const cur = recoveryStateRef.current;
+ const doc = cur.documents.find((d) => d.id === activeDocumentId);
+ const firstCanvas =
+ layerCanvasesRef.current.get(doc?.activeLayerId || cur.activeLayerId) ||
+ layerCanvasesRef.current.values().next().value;
+ if (!firstCanvas) return null;
+ return new Promise((resolve) => {
+ firstCanvas.toBlob((blob: Blob | null) => {
+ if (!blob) return resolve(null);
+ blob
+ .arrayBuffer()
+ .then((buf: ArrayBuffer) => resolve(new Uint8Array(buf)))
+ .catch(() => resolve(null));
+ }, 'image/png');
+ });
+ }
+ );
+ }, [activeDocumentId, layerCanvasesRef]);
// Active edit target for painting/erasing ('layer' content vs 'mask')
const [activeEditTarget, setActiveEditTarget] = useState<'layer' | 'mask'>('layer');
@@ -759,29 +835,84 @@ export function App() {
[layerStylesModalState.layerId, updateLayerStyles, showToast]
);
+ const pushHistoryStepRef = useRef<any>(null);
+
const handleApplyFilter = useCallback(
(type: FilterType, params?: any) => {
if (!hasOpenDocument || !activeLayer || activeLayer.type !== 'raster' || activeLayer.locked) {
showToast('Select an unlocked raster layer to apply filter');
return;
}
- const canvas = layerCanvasesRef.current.get(activeLayerId);
- if (!canvas) return;
- const ctx = get2DContext(canvas);
+ const isTone = Boolean(activeLayer.toneEnabled && layerSourceCanvasesRef.current?.get(activeLayerId));
+ const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
+ const displayCanvas = layerCanvasesRef.current.get(activeLayerId);
+ const targetCanvas = isTone && sourceCanvas ? sourceCanvas : displayCanvas;
+ if (!targetCanvas || !displayCanvas) return;
+ const ctx = get2DContext(targetCanvas);
if (!ctx) return;
- const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- const filtered = applyFilter(imgData, type, params);
- ctx.putImageData(filtered, 0, 0);
+ const beforeImageData = ctx.getImageData(0, 0, targetCanvas.width, targetCanvas.height);
+ const rawFiltered = applyFilter(
+ new ImageData(new Uint8ClampedArray(beforeImageData.data), beforeImageData.width, beforeImageData.height),
+ type,
+ params
+ );
+
+ let finalImageData = rawFiltered;
+ if (selection) {
+ const selMask = createSelectionMask(selection, targetCanvas.width, targetCanvas.height);
+ if (selMask) {
+ finalImageData = new ImageData(new Uint8ClampedArray(beforeImageData.data), targetCanvas.width, targetCanvas.height);
+ const src = beforeImageData.data;
+ const flt = rawFiltered.data;
+ const dst = finalImageData.data;
+ for (let i = 0; i < selMask.length; i++) {
+ const m = selMask[i];
+ if (m === 0) continue;
+ const p = i * 4;
+ if (m === 255) {
+ dst[p] = flt[p];
+ dst[p + 1] = flt[p + 1];
+ dst[p + 2] = flt[p + 2];
+ dst[p + 3] = flt[p + 3];
+ } else {
+ const a = m / 255;
+ const inv = 1 - a;
+ dst[p] = Math.round(src[p] * inv + flt[p] * a);
+ dst[p + 1] = Math.round(src[p + 1] * inv + flt[p + 1] * a);
+ dst[p + 2] = Math.round(src[p + 2] * inv + flt[p + 2] * a);
+ dst[p + 3] = Math.round(src[p + 3] * inv + flt[p + 3] * a);
+ }
+ }
+ }
+ }
- const isMono = colorMode === 'monochrome' || activeLayer.expressionColor === 'monochrome';
- const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
- globalTileGrid.writeImageData(activeLayerId, filtered, 0, 0, targetFormat);
+ ctx.putImageData(finalImageData, 0, 0);
+
+ if (!isTone && sourceCanvas) {
+ get2DContext(sourceCanvas)?.putImageData(finalImageData, 0, 0);
+ }
+
+ if (isTone && sourceCanvas) {
+ applyLayerEffects(sourceCanvas, displayCanvas, activeLayer, dimensions.dpi ?? 600);
+ } else {
+ const isMono = colorMode === 'monochrome' || activeLayer.expressionColor === 'monochrome';
+ const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
+ globalTileGrid.writeImageData(activeLayerId, finalImageData, 0, 0, targetFormat);
+ }
+
+ pushHistoryStepRef.current?.(
+ 'filter',
+ `Filter: ${type.replace('-', ' ')}`,
+ beforeImageData,
+ finalImageData,
+ activeLayerId
+ );
globalTileGrid.notifyChange(true);
updateLayerThumbnail(activeLayerId, true);
showToast(`Filter applied: ${type.replace('-', ' ')}`);
},
- [hasOpenDocument, activeLayer, activeLayerId, layerCanvasesRef, colorMode, updateLayerThumbnail, showToast]
+ [hasOpenDocument, activeLayer, activeLayerId, selection, dimensions.dpi, layerCanvasesRef, layerSourceCanvasesRef, colorMode, updateLayerThumbnail, showToast]
);
const {
@@ -838,7 +969,7 @@ export function App() {
ctx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
const bs = msg.brushSettings;
const isEraser = msg.tool === 'eraser';
- const isBgEraser = isEraser && msg.layerId === 'layer-bg';
+ const isBgEraser = isEraser && (msg.layerId === 'layer-bg' || msg.layerId.startsWith('layer-bg'));
const isPencil = !isEraser && (bs.preset?.startsWith('pencil') ?? false);
const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, colorMode);
@@ -875,7 +1006,7 @@ export function App() {
const bs = strokeState.brushSettings;
const isEraser = strokeState.tool === 'eraser';
- const isBgEraser = isEraser && strokeState.layerId === 'layer-bg';
+ const isBgEraser = isEraser && (strokeState.layerId === 'layer-bg' || strokeState.layerId.startsWith('layer-bg'));
const isPencil = !isEraser && (bs.preset?.startsWith('pencil') ?? false);
const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, colorMode);
const pts = strokeState.points;
@@ -1046,12 +1177,12 @@ export function App() {
renderCompleteStroke(
bCtx,
strokeState.points,
- bs,
+ { ...bs, opacity: 1.0, isTransparentInk: false },
strokeState.tool,
colorMode,
isBgEraser,
targetCanvas,
- isAlphaLocked
+ false
);
ctx.save();
ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
@@ -1156,12 +1287,14 @@ export function App() {
}, [setActiveLayerId]);
const handleRemoteJoinRequest = useCallback((peer: import('./types/multiplayer').CollabPeer) => {
- // Automatically allocate a dedicated layer for the joining peer: "[Name] 1", "[Name] 2", etc.
+ // Automatically allocate a dedicated layer for the joining peer without hijacking host's active layer
const layerName = getNextCollabLayerName(peer.name, layersRef.current);
const layerId = `layer-${peer.id}-1`;
- const newLayer = addLayer('raster', null, layerName, layerId);
+ const newLayer = addLayer('raster', null, layerName, layerId, false);
multiplayerService.sendLayerAdd(newLayer);
- const updated = [newLayer, ...layersRef.current.filter((l) => l.id !== newLayer.id)];
+ const updated = layersRef.current.some((l) => l.id === newLayer.id)
+ ? layersRef.current
+ : [newLayer, ...layersRef.current];
return {
assignedLayerId: layerId,
updatedLayers: updated,
@@ -1186,12 +1319,16 @@ export function App() {
if (targetCanvas) {
const ctx = get2DContext(targetCanvas);
if (ctx) {
- if (layerId === 'layer-bg' || layerId.startsWith('layer-bg')) {
+ const isBg = layerId === 'layer-bg' || layerId.startsWith('layer-bg');
+ if (isBg) {
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, targetCanvas.width, targetCanvas.height);
+ globalTileGrid.ingestCanvas(layerId, targetCanvas, 'color-32bit');
} else {
ctx.clearRect(0, 0, targetCanvas.width, targetCanvas.height);
+ globalTileGrid.clearLayer(layerId);
}
+ globalTileGrid.notifyChange(true);
updateLayerThumbnail(layerId, true);
}
}
@@ -1260,7 +1397,7 @@ export function App() {
// When hosting starts, ensure host's primary drawing layer has the host's nickname
const handleStartHosting = useCallback(
- async (roomName: string, port: number, hostNickname?: string) => {
+ async (roomName: string, port: number, hostNickname?: string, isGlobal?: boolean) => {
if (!hasOpenDocument) {
showToast('Please create or open a canvas before hosting a session.');
return false;
@@ -1268,7 +1405,7 @@ export function App() {
const finalHostName = (hostNickname || collabMyPeer.name || 'Sora').trim();
const defaultLayer =
layersRef.current.find((l) => l.id === activeLayerId) ||
- layersRef.current.find((l) => l.type === 'raster' && l.id !== 'layer-bg');
+ layersRef.current.find((l) => l.type === 'raster' && l.id !== 'layer-bg' && !l.id.startsWith('layer-bg'));
if (
defaultLayer &&
(defaultLayer.name === 'Layer 1' ||
@@ -1280,9 +1417,9 @@ export function App() {
);
renameLayer(defaultLayer.id, hostLayerName);
}
- return await startHosting(roomName, port, finalHostName);
+ return await startHosting(roomName, port, finalHostName, isGlobal);
},
- [collabMyPeer.name, activeLayerId, renameLayer, startHosting]
+ [hasOpenDocument, showToast, collabMyPeer.name, activeLayerId, renameLayer, startHosting]
);
// Collaborative-aware Layer Operations
@@ -1365,6 +1502,7 @@ export function App() {
const {
interactionRef,
+ isDrawingRef,
getActiveCanvas,
pushHistoryStep,
handlePointerDown: handleCanvasDrawingPointerDown,
@@ -1383,7 +1521,6 @@ export function App() {
resetHistory,
selectiveUndo,
cursorPos,
- currentPressure,
isHovering,
} = useCanvasDrawing({
tool,
@@ -1396,6 +1533,7 @@ export function App() {
zoom,
rotation,
activeLayerId,
+ activeSessionId: activeDocumentId,
activeLayerLocked: activeLayer?.locked ?? false,
activeLayerVisible: activeLayer ? isLayerEffectivelyVisible(activeLayer) : true,
layerCanvasesRef,
@@ -1428,9 +1566,11 @@ export function App() {
},
perspectiveRuler: hasOpenDocument ? perspectiveRuler : null,
onActiveConstraintAxisChange: handleActiveConstraintAxisChange,
+ selection: hasOpenDocument ? selection : null,
});
selectiveUndoRef.current = selectiveUndo;
+ pushHistoryStepRef.current = pushHistoryStep;
const handleUndo = useCallback(() => {
if (isCollabConnected && collabMyPeer.id) {
@@ -1473,7 +1613,7 @@ export function App() {
? ERASER_PRESET_ID
: (next.preset || prev.preset || DEFAULT_BRUSH_PRESET_ID);
- saveBrushSettingsImmediately(targetPresetId, next);
+ saveBrushSettingsDebounced(targetPresetId, next);
if (next.preset && toolRef.current === 'brush') {
saveActivePresetId(next.preset);
}
@@ -1481,12 +1621,14 @@ export function App() {
});
}, []);
- const handleBrushSizeChange = useCallback(
- (size: number) => {
- updateBrushSettings({ size });
- },
- [updateBrushSettings]
- );
+ useEffect(() => {
+ const handleBeforeUnload = () => flushPendingBrushSettingsSave();
+ window.addEventListener('beforeunload', handleBeforeUnload);
+ return () => {
+ flushPendingBrushSettingsSave();
+ window.removeEventListener('beforeunload', handleBeforeUnload);
+ };
+ }, []);
const addRecentColor = useCallback((color: string) => {
@@ -1597,20 +1739,27 @@ export function App() {
commitFloatingSelection(canvas, selection.floating, sourceCanvas);
const ctx = get2DContext(canvas);
- if (ctx && selection.floating.beforeImageData) {
+ if (ctx) {
const afterData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- pushHistoryStep(
- 'selection-move',
- 'Move Selection',
- selection.floating.beforeImageData,
- afterData,
- targetLayerId
- );
+ if (selection.floating.beforeImageData) {
+ pushHistoryStep(
+ 'selection-move',
+ 'Move Selection',
+ selection.floating.beforeImageData,
+ afterData,
+ targetLayerId
+ );
+ } else {
+ const lyr = layers.find((l) => l.id === targetLayerId);
+ const isMono = colorMode === 'monochrome' || lyr?.expressionColor === 'monochrome';
+ globalTileGrid.writeImageData(targetLayerId, afterData, 0, 0, isMono ? 'monochrome-1bit' : 'color-32bit');
+ }
+ globalTileGrid.notifyChange(true);
}
updateLayerThumbnail(targetLayerId, true);
setSelection((prev) => (prev ? { ...prev, floating: null } : null));
- }, [selection, activeLayerId, layerCanvasesRef, getActiveCanvas, layerSourceCanvasesRef, pushHistoryStep, updateLayerThumbnail]);
+ }, [selection, activeLayerId, layers, colorMode, layerCanvasesRef, getActiveCanvas, layerSourceCanvasesRef, pushHistoryStep, updateLayerThumbnail]);
const handleDeselect = useCallback(() => {
if (selection?.floating) {
@@ -1622,6 +1771,22 @@ export function App() {
const handleClearSelection = useCallback(() => {
if (!selection) return;
if (selection.floating) {
+ const targetLayerId = selection.floating.layerId || activeLayerId;
+ const canvas = layerCanvasesRef.current.get(targetLayerId) || getActiveCanvas();
+ if (canvas && selection.floating.beforeImageData) {
+ const ctx = get2DContext(canvas);
+ if (ctx) {
+ const afterData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ pushHistoryStep(
+ 'clear',
+ 'Clear Selection',
+ selection.floating.beforeImageData,
+ afterData,
+ targetLayerId
+ );
+ globalTileGrid.notifyChange(true);
+ }
+ }
setSelection(null);
return;
}
@@ -1633,6 +1798,7 @@ export function App() {
const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
+ const isBg = activeLayerId === 'layer-bg' || activeLayerId.startsWith('layer-bg');
const clearOn = (target: HTMLCanvasElement) => {
const c = get2DContext(target);
@@ -1646,19 +1812,19 @@ export function App() {
if (mCtx) {
const mImg = mCtx.createImageData(target.width, target.height);
for (let i = 0; i < selection.mask.length; i++) {
+ if (isBg) {
+ mImg.data[i * 4] = 255;
+ mImg.data[i * 4 + 1] = 255;
+ mImg.data[i * 4 + 2] = 255;
+ }
mImg.data[i * 4 + 3] = selection.mask[i];
}
mCtx.putImageData(mImg, 0, 0);
- if (activeLayerId === 'layer-bg') {
- c.fillStyle = '#ffffff';
- c.fillRect(selection.bounds.x, selection.bounds.y, selection.bounds.width, selection.bounds.height);
- } else {
- c.globalCompositeOperation = 'destination-out';
- c.drawImage(maskCanvas, 0, 0);
- }
+ c.globalCompositeOperation = isBg ? 'source-over' : 'destination-out';
+ c.drawImage(maskCanvas, 0, 0);
}
} else if (selection.type === 'rect') {
- if (activeLayerId === 'layer-bg') {
+ if (isBg) {
c.fillStyle = '#ffffff';
c.fillRect(selection.bounds.x, selection.bounds.y, selection.bounds.width, selection.bounds.height);
} else {
@@ -1671,7 +1837,7 @@ export function App() {
c.lineTo(selection.polygon[i].x, selection.polygon[i].y);
}
c.closePath();
- if (activeLayerId === 'layer-bg') {
+ if (isBg) {
c.fillStyle = '#ffffff';
c.fill();
} else {
@@ -1695,7 +1861,8 @@ export function App() {
afterImageData,
activeLayerId
);
- }, [selection, getActiveCanvas, activeLayerId, layerSourceCanvasesRef, updateLayerThumbnail, pushHistoryStep]);
+ globalTileGrid.notifyChange(true);
+ }, [selection, getActiveCanvas, activeLayerId, layerCanvasesRef, layerSourceCanvasesRef, updateLayerThumbnail, pushHistoryStep]);
const handleFillSelectionColor = useCallback(() => {
if (!selection) return;
@@ -2036,8 +2203,14 @@ export function App() {
dpi: dimensions.dpi ?? 600,
});
}
+
+ if (displayCanvas) {
+ const isMono = colorMode === 'monochrome' || targetLayer?.expressionColor === 'monochrome';
+ globalTileGrid.ingestCanvas(targetLayerId, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ globalTileGrid.notifyChange(true);
+ }
},
- [layers, layerCanvasesRef, layerSourceCanvasesRef, dimensions.dpi]
+ [layers, colorMode, layerCanvasesRef, layerSourceCanvasesRef, dimensions.dpi]
);
const handleTonalApply = useCallback(
@@ -2083,6 +2256,7 @@ export function App() {
finalData,
targetLayerId
);
+ globalTileGrid.notifyChange(true);
const resetState = {
isOpen: false,
@@ -2130,6 +2304,11 @@ export function App() {
dpi: dimensions.dpi ?? 600,
});
}
+ if (displayCanvas) {
+ const isMono = colorMode === 'monochrome' || targetLayer?.expressionColor === 'monochrome';
+ globalTileGrid.ingestCanvas(targetLayerId, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ globalTileGrid.notifyChange(true);
+ }
}
}
}
@@ -2144,7 +2323,7 @@ export function App() {
};
tonalModalStateRef.current = resetState;
setTonalModalState(resetState);
- }, [layers, layerCanvasesRef, layerSourceCanvasesRef, dimensions.dpi]);
+ }, [layers, colorMode, layerCanvasesRef, layerSourceCanvasesRef, dimensions.dpi]);
const handleApplyReverseGradient = useCallback(() => {
if (!hasOpenDocument || !activeLayer || activeLayer.locked || activeLayer.type !== 'raster') return;
@@ -2269,6 +2448,9 @@ export function App() {
if (!lifted) return;
floatCanvas = lifted.floatingCanvas;
beforeData = lifted.beforeImageData;
+ const isMono = colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
+ globalTileGrid.ingestCanvas(activeLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ globalTileGrid.notifyChange(true);
updateLayerThumbnail(activeLayerId, true);
}
@@ -2387,8 +2569,11 @@ export function App() {
}
}
}
+ const isMono = colorMode === 'monochrome' || lyr.expressionColor === 'monochrome';
+ globalTileGrid.ingestCanvas(lyr.id, c, isMono ? 'monochrome-1bit' : 'color-32bit');
updateLayerThumbnail(lyr.id, true);
}
+ globalTileGrid.notifyChange(true);
const quad = createDefaultPerspectiveQuad(b.x, b.y, b.width, b.height, 0);
setTransformSession({
@@ -2459,6 +2644,9 @@ export function App() {
}
}
+ const isMono = colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
+ globalTileGrid.ingestCanvas(activeLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ globalTileGrid.notifyChange(true);
updateLayerThumbnail(activeLayerId, true);
const quad = createDefaultPerspectiveQuad(b.x, b.y, b.width, b.height, 0);
@@ -2538,26 +2726,23 @@ export function App() {
});
}
- updateLayerThumbnail(lId, true);
- }
-
- if (transformSession.beforeImageData) {
- const primaryCanvas = layerCanvasesRef.current.get(transformSession.layerId);
- if (primaryCanvas) {
- const primaryCtx = get2DContext(primaryCanvas);
- if (primaryCtx) {
- const afterImageData = primaryCtx.getImageData(0, 0, primaryCanvas.width, primaryCanvas.height);
- pushHistoryStep(
- 'transform',
- 'Batch Free Transform',
- transformSession.beforeImageData,
- afterImageData,
- transformSession.layerId
- );
- }
+ const beforeDataForLayer = transformSession.layerBeforeImages?.get(lId);
+ const afterDataForLayer = cCtx.getImageData(0, 0, c.width, c.height);
+ const isMono = colorMode === 'monochrome' || lyr?.expressionColor === 'monochrome';
+ globalTileGrid.ingestCanvas(lId, c, isMono ? 'monochrome-1bit' : 'color-32bit');
+ if (beforeDataForLayer) {
+ pushHistoryStep(
+ 'transform',
+ 'Batch Free Transform',
+ beforeDataForLayer,
+ afterDataForLayer,
+ lId
+ );
}
+ updateLayerThumbnail(lId, true);
}
+ globalTileGrid.notifyChange(true);
setTransformSession(null);
setTool('brush');
return;
@@ -2621,12 +2806,14 @@ export function App() {
afterImageData,
transformSession.layerId
);
+ globalTileGrid.notifyChange(true);
updateLayerThumbnail(transformSession.layerId, true);
setTransformSession(null);
setTool('brush');
}, [
transformSession,
+ colorMode,
layerCanvasesRef,
getActiveCanvas,
layers,
@@ -2646,12 +2833,12 @@ export function App() {
const ctx = get2DContext(c);
ctx?.putImageData(beforeData, 0, 0);
+ const lyr = layers.find((l) => l.id === lId);
const sourceCanvas = layerSourceCanvasesRef.current?.get(lId);
if (sourceCanvas) {
const sCtx = get2DContext(sourceCanvas);
sCtx?.putImageData(beforeData, 0, 0);
- const lyr = layers.find((l) => l.id === lId);
if (lyr?.toneEnabled) {
applyScreentone(sourceCanvas, c, {
frequency: lyr.toneFrequency ?? 60,
@@ -2661,9 +2848,12 @@ export function App() {
});
}
}
+ const isMono = colorMode === 'monochrome' || lyr?.expressionColor === 'monochrome';
+ globalTileGrid.ingestCanvas(lId, c, isMono ? 'monochrome-1bit' : 'color-32bit');
updateLayerThumbnail(lId, true);
}
}
+ globalTileGrid.notifyChange(true);
setTransformSession(null);
setTool('brush');
return;
@@ -2674,12 +2864,12 @@ export function App() {
const ctx = get2DContext(canvas);
ctx?.putImageData(transformSession.beforeImageData, 0, 0);
+ const layer = layers.find((l) => l.id === transformSession.layerId);
const sourceCanvas = layerSourceCanvasesRef.current?.get(transformSession.layerId);
if (sourceCanvas) {
const sCtx = get2DContext(sourceCanvas);
sCtx?.putImageData(transformSession.beforeImageData, 0, 0);
- const layer = layers.find((l) => l.id === transformSession.layerId);
if (layer?.toneEnabled) {
applyScreentone(
sourceCanvas,
@@ -2693,12 +2883,16 @@ export function App() {
);
}
}
+ const isMono = colorMode === 'monochrome' || layer?.expressionColor === 'monochrome';
+ globalTileGrid.ingestCanvas(transformSession.layerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ globalTileGrid.notifyChange(true);
updateLayerThumbnail(transformSession.layerId, true);
}
setTransformSession(null);
setTool('brush');
}, [
transformSession,
+ colorMode,
layerCanvasesRef,
getActiveCanvas,
layers,
@@ -2735,6 +2929,7 @@ export function App() {
outline: s.outline,
outlineColor: s.outlineColor,
outlineWidth: s.outlineWidth,
+ anchorTopLeft: true,
});
};
@@ -2750,6 +2945,7 @@ export function App() {
afterImageData,
activeLayerId
);
+ globalTileGrid.notifyChange(true);
setTextSession(null);
}, [textSession, getActiveCanvas, activeLayerId, layerSourceCanvasesRef, updateLayerThumbnail, pushHistoryStep]);
@@ -2786,6 +2982,7 @@ export function App() {
afterImageData,
activeLayerId
);
+ globalTileGrid.notifyChange(true);
setActiveBalloon(null);
}, [activeBalloon, getActiveCanvas, activeLayerId, layerSourceCanvasesRef, updateLayerThumbnail, pushHistoryStep]);
@@ -2820,6 +3017,7 @@ export function App() {
const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
updateLayerThumbnail(activeLayerId, true);
pushHistoryStep('brush', `Manga Effect (${type})`, beforeImageData, afterImageData, activeLayerId);
+ globalTileGrid.notifyChange(true);
showToast(`Applied manga ${type} lines`);
},
[getActiveCanvas, activeLayerId, layerSourceCanvasesRef, updateLayerThumbnail, pushHistoryStep, showToast]
@@ -2955,7 +3153,15 @@ export function App() {
if (displayCanvas) {
applyLayerEffects(sourceCanvas, displayCanvas, activeLayer, dimensions.dpi ?? 600, dirty);
}
+ } else {
+ const dCtx = get2DContext(canvas);
+ if (dCtx && dirty.width > 0 && dirty.height > 0) {
+ const subData = dCtx.getImageData(dirty.x, dirty.y, dirty.width, dirty.height);
+ const isMono = colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
+ globalTileGrid.writeImageData(activeLayerId, subData, dirty.x, dirty.y, isMono ? 'monochrome-1bit' : 'color-32bit');
+ }
}
+ globalTileGrid.notifyChange(true);
}
liquifyRafIdRef.current = requestAnimationFrame(tick);
@@ -2963,11 +3169,11 @@ export function App() {
liquifyRafIdRef.current = requestAnimationFrame(tick);
},
- [activeLayer, activeLayerId, dimensions.dpi, layerCanvasesRef]
+ [activeLayer, activeLayerId, colorMode, dimensions.dpi, layerCanvasesRef]
);
const handlePointerDown = useCallback(
- (e: React.PointerEvent<HTMLElement>) => {
+ (e: React.PointerEvent<HTMLElement>, coalescedEvents?: PointerEvent[]) => {
if (!hasOpenDocument || e.button !== 0) return;
const pt = getCanvasCoords(e);
@@ -2998,9 +3204,7 @@ export function App() {
isLiquifyingRef.current = true;
prevLiquifyPointRef.current = pt;
liquifyBeforeImageDataRef.current = ctx.getImageData(0, 0, canvas.width, canvas.height);
- if (!liquifyInitialImageDataRef.current) {
- liquifyInitialImageDataRef.current = liquifyBeforeImageDataRef.current;
- }
+ liquifyInitialImageDataRef.current = liquifyBeforeImageDataRef.current;
liquifySelectionMaskRef.current = createLiquifySelectionMask(selection, canvas.width, canvas.height);
liquifyDirtyRectRef.current = null;
liquifyLastPointerPosRef.current = { pt, pressure: e.pressure || 1.0 };
@@ -3027,7 +3231,12 @@ export function App() {
liquifyDirtyRectRef.current = dirty;
if (activeLayer?.toneEnabled && sourceCanvas && displayCanvas) {
applyLayerEffects(sourceCanvas, displayCanvas, activeLayer, dimensions.dpi ?? 600, dirty);
+ } else if (dirty.width > 0 && dirty.height > 0) {
+ const subData = ctx.getImageData(dirty.x, dirty.y, dirty.width, dirty.height);
+ const isMono = colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
+ globalTileGrid.writeImageData(targetLayerId, subData, dirty.x, dirty.y, isMono ? 'monochrome-1bit' : 'color-32bit');
}
+ globalTileGrid.notifyChange(true);
}
startLiquifyLoop(canvas, sourceCanvas, isTone);
}
@@ -3038,7 +3247,7 @@ export function App() {
if (selection?.floating) {
handleCommitFloatingSelection();
}
- handleCanvasDrawingPointerDown(e);
+ handleCanvasDrawingPointerDown(e, coalescedEvents);
return;
}
@@ -3193,6 +3402,9 @@ export function App() {
const isBg = activeLayerId === 'layer-bg' || activeLayerId.startsWith('layer-bg');
const lifted = liftSelectionToFloating(canvas, selection, sourceCanvas, isBg);
if (lifted) {
+ const isMono = colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
+ globalTileGrid.ingestCanvas(activeLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ globalTileGrid.notifyChange(true);
updateLayerThumbnail(activeLayerId, true);
const floatingObj = {
canvas: lifted.floatingCanvas,
@@ -3274,11 +3486,28 @@ export function App() {
let refCanvas: HTMLCanvasElement;
if (fillSettings.method === 'refer-all') {
refCanvas = compositeVisibleLayers(layers, layerCanvasesRef.current, dimensions);
+ } else if (fillSettings.method === 'refer-reference') {
+ refCanvas = compositeReferenceLayers(layers, layerCanvasesRef.current, dimensions);
} else {
refCanvas = canvas;
}
- const fillRes = executeFloodFill(canvas, refCanvas, px, py, primaryColor, fillSettings.tolerance, sourceCanvas);
+ const selMask = selection ? createSelectionMask(selection, canvas.width, canvas.height) : null;
+ const fillRes = executeFloodFill(
+ canvas,
+ refCanvas,
+ px,
+ py,
+ primaryColor,
+ fillSettings.tolerance,
+ sourceCanvas,
+ {
+ closeGap: fillSettings.closeGap ?? 0,
+ areaScale: fillSettings.areaScale ?? 0,
+ antiAlias: fillSettings.antiAlias ?? true,
+ selectionMask: selMask,
+ }
+ );
if (activeLayer?.toneEnabled && sourceCanvas) {
applyLayerEffects(sourceCanvas, canvas, activeLayer, dimensions.dpi ?? 600, fillRes.dirtyRect ?? undefined);
}
@@ -3292,6 +3521,7 @@ export function App() {
afterImageData,
activeLayerId
);
+ globalTileGrid.notifyChange(true);
return;
}
@@ -3369,7 +3599,7 @@ export function App() {
);
const handlePointerMove = useCallback(
- (e: React.PointerEvent<HTMLElement>) => {
+ (e: React.PointerEvent<HTMLElement>, coalescedEvents?: PointerEvent[], predictedEvents?: PointerEvent[]) => {
if (tool === 'pipette') {
if (isPipetteSamplingRef.current) {
const pt = getCanvasCoords(e);
@@ -3379,7 +3609,7 @@ export function App() {
}
if (tool === 'brush' || tool === 'eraser') {
- handleCanvasDrawingPointerMove(e);
+ handleCanvasDrawingPointerMove(e, coalescedEvents, predictedEvents);
return;
}
@@ -3427,6 +3657,9 @@ export function App() {
if (ctx) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
renderVectorLayer(ctx, newStrokes);
+ const isMono = colorMode === 'monochrome' || activeLayer.expressionColor === 'monochrome';
+ globalTileGrid.ingestCanvas(activeLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ globalTileGrid.notifyChange(true);
updateLayerThumbnail(activeLayerId, true);
}
}
@@ -3491,7 +3724,15 @@ export function App() {
if (overallDirty) {
if (activeLayer?.toneEnabled && sourceCanvas && displayCanvas) {
applyLayerEffects(sourceCanvas, displayCanvas, activeLayer, dimensions.dpi ?? 600, overallDirty);
+ } else if (overallDirty.width > 0 && overallDirty.height > 0) {
+ const cCtx = get2DContext(canvas);
+ if (cCtx) {
+ const subData = cCtx.getImageData(overallDirty.x, overallDirty.y, overallDirty.width, overallDirty.height);
+ const isMono = colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
+ globalTileGrid.writeImageData(targetLayerId, subData, overallDirty.x, overallDirty.y, isMono ? 'monochrome-1bit' : 'color-32bit');
+ }
}
+ globalTileGrid.notifyChange(true);
if (!liquifyDirtyRectRef.current) {
liquifyDirtyRectRef.current = overallDirty;
} else {
@@ -3530,28 +3771,6 @@ export function App() {
mCtx.restore();
selectionPenDrawingRef.current.lastPt = pt;
-
- const w = dimensions.width;
- const h = dimensions.height;
- const mImgData = mCtx.getImageData(0, 0, w, h);
- const newMask = new Uint8Array(w * h);
- for (let i = 0; i < newMask.length; i++) {
- newMask[i] = mImgData.data[i * 4 + 3] > 0 ? 255 : 0;
- }
- const b = maskToBounds(newMask, w, h);
- if (b) {
- const svg = maskToSvgPath(newMask, w, h);
- setSelection({
- type: 'mask',
- bounds: b,
- mask: newMask,
- maskWidth: w,
- maskHeight: h,
- svgPath: svg,
- });
- } else {
- setSelection(null);
- }
return;
}
@@ -3617,7 +3836,23 @@ export function App() {
return;
}
},
- [tool, handleCanvasDrawingPointerMove, getCanvasCoords, fillSettings.method, handleSampleColor, brushSettings.size, dimensions]
+ [
+ tool,
+ activeLayer,
+ activeLayerId,
+ colorMode,
+ vectorEditSettings,
+ getActiveCanvas,
+ updateLayerThumbnail,
+ layerSourceCanvasesRef,
+ layerCanvasesRef,
+ handleCanvasDrawingPointerMove,
+ getCanvasCoords,
+ fillSettings.method,
+ handleSampleColor,
+ brushSettings.size,
+ dimensions,
+ ]
);
const handlePointerUp = useCallback(
@@ -3669,11 +3904,13 @@ export function App() {
afterImageData,
targetLayerId
);
+ globalTileGrid.notifyChange(true);
updateLayerThumbnail(targetLayerId, true);
}
}
liquifyBeforeImageDataRef.current = null;
+ liquifyInitialImageDataRef.current = null;
liquifySelectionMaskRef.current = null;
liquifyDirtyRectRef.current = null;
prevLiquifyPointRef.current = null;
@@ -3773,6 +4010,7 @@ export function App() {
afterImageData,
activeLayerId
);
+ globalTileGrid.notifyChange(true);
return;
}
@@ -3819,6 +4057,7 @@ export function App() {
afterImageData,
activeLayerId
);
+ globalTileGrid.notifyChange(true);
}
return;
}
@@ -3836,19 +4075,23 @@ export function App() {
undefined,
{ before: vectorEditBeforeStrokesRef.current, after: [...activeLayer.vectorStrokes] }
);
+ globalTileGrid.notifyChange(true);
}
return;
}
},
[
tool,
+ activeLayer,
+ activeLayerId,
+ vectorEditSettings,
+ layerCanvasesRef,
handleCanvasDrawingPointerUp,
getCanvasCoords,
selection,
fillSettings.method,
getActiveCanvas,
layerSourceCanvasesRef,
- activeLayerId,
primaryColor,
updateLayerThumbnail,
pushHistoryStep,
@@ -3939,6 +4182,59 @@ export function App() {
[primaryColor, resetHistory, resetToNewCanvas, resetZoomAndCenter, showToast, updateBrushSettings]
);
+ // Initialize a default white canvas on launch so >80% of the viewport is immediately dedicated to drawing
+ const hasAutoCreatedInitialDocRef = useRef(false);
+ useEffect(() => {
+ if (hasAutoCreatedInitialDocRef.current || documents.length > 0) return;
+ hasAutoCreatedInitialDocRef.current = true;
+ const initDims: CanvasDimensions = {
+ width: appSettings.defaultWidth || 1920,
+ height: appSettings.defaultHeight || 1080,
+ dpi: appSettings.defaultDpi || 300,
+ };
+ const initColorMode = appSettings.defaultColorMode || 'color';
+ const initBg = appSettings.defaultBgColor || '#ffffff';
+ const initName = 'Untitled*';
+ setDimensions(initDims);
+ setColorMode(initColorMode);
+ setDocumentName(initName);
+ const { layers: initialLayers, activeLayerId: topId } = resetToNewCanvas(
+ initDims,
+ initBg,
+ initColorMode,
+ 60
+ );
+ needsAdaptiveFitRef.current = true;
+ pendingFitDimsRef.current = initDims;
+ resetZoomAndCenter(initDims);
+ resetHistory();
+ const newDocId = `doc-${Date.now()}`;
+ setDocuments([
+ {
+ id: newDocId,
+ name: initName,
+ dimensions: initDims,
+ colorMode: initColorMode,
+ layers: initialLayers,
+ activeLayerId: topId,
+ perspectiveRuler: null,
+ defaultFrequency: 60,
+ },
+ ]);
+ setActiveDocumentId(newDocId);
+ setAppView('workspace');
+ }, [
+ appSettings.defaultBgColor,
+ appSettings.defaultColorMode,
+ appSettings.defaultDpi,
+ appSettings.defaultHeight,
+ appSettings.defaultWidth,
+ documents.length,
+ resetHistory,
+ resetToNewCanvas,
+ resetZoomAndCenter,
+ ]);
+
// Copy selected layer
const handleCopySelectedLayer = useCallback(() => {
if (!activeLayer) return;
@@ -4040,6 +4336,7 @@ export function App() {
const handleUpdateSettings = useCallback((newSettings: AppSettings) => {
setAppSettings(newSettings);
saveAppSettings(newSettings);
+ globalTileMemoryManager.setBudgetMb(newSettings.tileMemoryBudgetMb || 1024);
setBrushSettings((prev) => ({
...prev,
stabilization: newSettings.defaultStabilization,
@@ -4048,6 +4345,11 @@ export function App() {
}));
}, []);
+ // Synchronize initial tile memory budget
+ useEffect(() => {
+ globalTileMemoryManager.setBudgetMb(appSettings.tileMemoryBudgetMb || 1024);
+ }, [appSettings.tileMemoryBudgetMb]);
+
// File loading handler
const handleProcessFile = useCallback(
async (file: File) => {
@@ -4146,7 +4448,12 @@ export function App() {
setDocuments((prev) => {
const curr = prev.find((d) => d.id === activeDocumentId);
if (!curr) return prev;
- if (curr.layers === layers && curr.activeLayerId === activeLayerId) {
+ if (
+ curr.layers === layers &&
+ curr.activeLayerId === activeLayerId &&
+ curr.layerCanvasesMap &&
+ curr.layerCanvasesMap.size === layerCanvasesRef.current.size
+ ) {
return prev;
}
return prev.map((d) =>
@@ -4248,10 +4555,122 @@ export function App() {
}
return next;
});
+ if (id) {
+ recoveryService.closeSession(id).catch(console.warn);
+ }
},
[activeDocumentId, clearDocument, loadDocument, resetHistory]
);
+ // Fault-Tolerant Crash Recovery Restore Handler
+ const handleRestoreCrashedSession = useCallback(
+ async (session: CrashedSessionInfo) => {
+ try {
+ const replayData = await recoveryService.loadSessionData(session.session_id);
+ const { manifest, replayedStrokesCount, replayedMutationsCount } =
+ recoveryService.replaySessionData(replayData, globalTileGrid);
+
+ const restoredDims: CanvasDimensions = {
+ width: manifest.width,
+ height: manifest.height,
+ dpi: manifest.dpi,
+ };
+
+ // Reconstruct layer canvases backing buffers
+ const restoredLayerCanvases = new Map<string, HTMLCanvasElement>();
+ for (const layer of manifest.layers) {
+ if (layer.type === 'raster' || layer.type === 'vector' || layer.type === 'frame') {
+ const canvas = document.createElement('canvas');
+ canvas.width = restoredDims.width;
+ canvas.height = restoredDims.height;
+ globalTileGrid.renderLayerToCanvas(layer.id, canvas);
+ restoredLayerCanvases.set(layer.id, canvas);
+ }
+ }
+
+ // Load document into useLayerManager
+ loadDocument({
+ name: manifest.documentName,
+ dimensions: restoredDims,
+ colorMode: manifest.colorMode,
+ layers: manifest.layers,
+ layerCanvases: restoredLayerCanvases,
+ });
+ if (manifest.activeLayerId) {
+ setActiveLayerId(manifest.activeLayerId);
+ }
+
+ // Set dimensions & color mode
+ setDimensions(restoredDims);
+ setColorMode(manifest.colorMode);
+ setDocumentName(manifest.documentName);
+
+ const restoredDoc: DocumentTab = {
+ id: session.session_id,
+ name: manifest.documentName,
+ dimensions: restoredDims,
+ colorMode: manifest.colorMode,
+ layers: manifest.layers,
+ activeLayerId: manifest.activeLayerId || manifest.layers[0]?.id || '',
+ layerCanvasesMap: restoredLayerCanvases,
+ };
+
+ setDocuments((prev) => {
+ const filtered = prev.filter((d) => d.id !== session.session_id);
+ return [restoredDoc, ...filtered];
+ });
+ setActiveDocumentId(session.session_id);
+ setAppView('workspace');
+
+ needsAdaptiveFitRef.current = true;
+ pendingFitDimsRef.current = restoredDims;
+ resetZoomAndCenter(restoredDims);
+ resetHistory();
+
+ // Push undo history entry
+ pushHistoryStep(
+ 'initial',
+ 'Session restored from crash',
+ null,
+ null,
+ manifest.activeLayerId || manifest.layers[0]?.id || ''
+ );
+
+ // Invalidate GPU textures & trigger compositor
+ globalTileGrid.notifyChange(true);
+
+ setIsRecoveryModalOpen(false);
+ setCrashedSessions((prev) => prev.filter((s) => s.session_id !== session.session_id));
+ showToast(
+ `Restored "${manifest.documentName}" (${replayedStrokesCount} strokes, ${replayedMutationsCount} mutations recovered)`
+ );
+ } catch (err: any) {
+ console.error('[Recovery] Restore error:', err);
+ alert('Failed to restore crashed session: ' + err.message);
+ }
+ },
+ [loadDocument, resetHistory, resetZoomAndCenter, showToast, pushHistoryStep, setActiveLayerId]
+ );
+
+ const handleDiscardCrashedSession = useCallback(
+ async (session: CrashedSessionInfo) => {
+ try {
+ await recoveryService.discardCrashedSession(session.session_id);
+ setCrashedSessions((prev) => {
+ const next = prev.filter((s) => s.session_id !== session.session_id);
+ if (next.length === 0) {
+ setIsRecoveryModalOpen(false);
+ }
+ return next;
+ });
+ showToast('Crashed session discarded');
+ } catch (err: any) {
+ console.warn('[Recovery] Discard error:', err);
+ }
+ },
+ [showToast]
+ );
+
const handleRenameDocument = useCallback(
(id: string, newName: string) => {
setDocuments((prev) =>
@@ -4289,6 +4708,7 @@ export function App() {
layerCanvasesMap: layerCanvasesRef.current,
getEffectiveOpacity,
isLayerEffectivelyVisible,
+ tabId: activeDocumentId || undefined,
};
// If haven't saved the file yet, prompt to select a path and file extension
@@ -4387,6 +4807,7 @@ export function App() {
layerCanvasesMap: layerCanvasesRef.current,
getEffectiveOpacity,
isLayerEffectivelyVisible,
+ tabId: activeDocumentId || undefined,
};
try {
@@ -4458,140 +4879,234 @@ export function App() {
showToast,
]);
- // Global Keyboard Shortcuts (Ctrl+N, Ctrl+O, Ctrl+S, Ctrl+Shift+S, B, E, X)
+ const isAnyModalOpen =
+ isRecoveryModalOpen ||
+ isNewCanvasModalOpen ||
+ isResizeCanvasModalOpen ||
+ isSettingsModalOpen ||
+ tonalModalState.isOpen ||
+ adjustmentModalState.isOpen ||
+ layerStylesModalState.isOpen ||
+ isToneModalOpen ||
+ isHostModalOpen ||
+ isMangaEffectsModalOpen ||
+ isWebtoonExportModalOpen ||
+ isLoadingFile;
+
+ const isAnyModalOpenRef = useRef<boolean>(isAnyModalOpen);
+ isAnyModalOpenRef.current = isAnyModalOpen;
+
+ const tempToolHoldRef = useRef<{
+ code: string;
+ prevTool: ToolType;
+ targetTool: ToolType;
+ downAt: number;
+ usedWhileHeld: boolean;
+ } | null>(null);
+
+ const handleResetDefaultColors = useCallback(() => {
+ setIsTransparentColor(false);
+ const prim = enforceColorMode('#000000', colorMode);
+ const sec = enforceColorMode('#ffffff', colorMode);
+ setPrimaryColor(prim);
+ setSecondaryColor(sec);
+ updateBrushSettings({ color: prim, secondaryColor: sec, isTransparentInk: false });
+ }, [colorMode, updateBrushSettings]);
+
+ // Global Keyboard Shortcuts (Layout-Independent e.code + CSP Hold-and-Release Temporary Tools)
useEffect(() => {
+ const isEditableTarget = (target: EventTarget | null): boolean => {
+ if (!(target instanceof HTMLElement)) return false;
+ const tag = target.tagName;
+ return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || target.isContentEditable;
+ };
+
+ const CODE_TO_TOOL: Record<string, ToolType> = {
+ KeyB: 'brush',
+ KeyE: 'eraser',
+ KeyI: 'pipette',
+ KeyJ: 'liquify',
+ KeyM: 'select-rect',
+ KeyL: 'select-lasso',
+ KeyW: 'select-wand',
+ KeyG: 'fill',
+ KeyT: 'text',
+ KeyF: 'frame',
+ KeyO: 'balloon',
+ KeyY: 'vector-edit',
+ };
+
const handleKeyDown = (e: KeyboardEvent) => {
- if (['INPUT', 'TEXTAREA'].includes((e.target as HTMLElement).tagName)) {
+ if (isAnyModalOpenRef.current || isEditableTarget(e.target)) {
return;
}
const key = e.key.toLowerCase();
+ const code = e.code;
// Ctrl / Cmd shortcuts
if (e.ctrlKey || e.metaKey) {
+ // Toggle Animation Timeline: Ctrl+Alt+A
+ if (e.altKey && !e.shiftKey && (code === 'KeyA' || key === 'a')) {
+ if (!hasOpenDocument) return;
+ e.preventDefault();
+ if (activeAnimationTimeline) {
+ handleUpdateAnimationTimeline(null);
+ } else {
+ handleUpdateAnimationTimeline(createDefaultAnimationTimeline(layers));
+ }
+ return;
+ }
+
+ // Soft Proof Colors: Ctrl+Alt+Y
+ if (e.altKey && !e.shiftKey && (code === 'KeyY' || key === 'y')) {
+ if (!hasOpenDocument) return;
+ e.preventDefault();
+ toggleSoftProof();
+ return;
+ }
+
+ // Ignore other Ctrl+Alt combinations (reserved for Ctrl+Alt+Drag resize & Ctrl+Alt+0 reset rotation)
+ if (e.altKey) return;
+
// Undo: Ctrl+Z (Cmd+Z)
- if (!e.shiftKey && (key === 'z' || e.code === 'KeyZ')) {
+ if (!e.shiftKey && (code === 'KeyZ' || key === 'z')) {
if (!hasOpenDocument) return;
e.preventDefault();
handleUndo();
return;
}
- // Redo: Ctrl+Shift+Z
- if (e.shiftKey && (key === 'z' || e.code === 'KeyZ')) {
+ // Redo: Ctrl+Shift+Z or Ctrl+Y
+ if (
+ (e.shiftKey && (code === 'KeyZ' || key === 'z')) ||
+ (!e.shiftKey && (code === 'KeyY' || key === 'y'))
+ ) {
if (!hasOpenDocument) return;
e.preventDefault();
redo();
return;
}
- // Proof Colors (Ctrl+Y) & Gamut Warning (Ctrl+Shift+Y)
- if (key === 'y' || e.code === 'KeyY') {
+ // Gamut Warning: Ctrl+Shift+Y
+ if (e.shiftKey && (code === 'KeyY' || key === 'y')) {
if (!hasOpenDocument) return;
e.preventDefault();
- if (e.shiftKey) {
- toggleGamutWarning();
- } else {
- toggleSoftProof();
- }
+ toggleGamutWarning();
+ return;
+ }
+ // New Raster Layer: Ctrl+Shift+N
+ if (e.shiftKey && (code === 'KeyN' || key === 'n')) {
+ if (!hasOpenDocument) return;
+ e.preventDefault();
+ handleAddLayer('raster');
return;
}
- if (!e.shiftKey && key === 'n') {
+ // New Canvas: Ctrl+N
+ if (!e.shiftKey && (code === 'KeyN' || key === 'n')) {
e.preventDefault();
setIsNewCanvasModalOpen(true);
return;
}
- if (!e.shiftKey && key === 'o') {
+ // Open File: Ctrl+O
+ if (!e.shiftKey && (code === 'KeyO' || key === 'o')) {
e.preventDefault();
handleTriggerOpenFile();
return;
}
// Save As: Ctrl+Shift+S
- if (e.shiftKey && key === 's') {
+ if (e.shiftKey && (code === 'KeyS' || key === 's')) {
if (!hasOpenDocument) return;
e.preventDefault();
handleSaveAs();
return;
}
// Save: Ctrl+S
- if (!e.shiftKey && key === 's') {
+ if (!e.shiftKey && (code === 'KeyS' || key === 's')) {
if (!hasOpenDocument) return;
e.preventDefault();
handleSave();
return;
}
+ // Duplicate Layer: Ctrl+J
+ if (!e.shiftKey && (code === 'KeyJ' || key === 'j')) {
+ if (!hasOpenDocument || !activeLayer) return;
+ e.preventDefault();
+ duplicateLayer(activeLayerId);
+ return;
+ }
// Copy Layer: Ctrl+C (only when no text is selected)
- if (!e.shiftKey && key === 'c') {
+ if (!e.shiftKey && (code === 'KeyC' || key === 'c')) {
if (!hasOpenDocument) return;
- const selection = window.getSelection()?.toString();
- if (!selection || selection.length === 0) {
+ const textSel = window.getSelection()?.toString();
+ if (!textSel || textSel.length === 0) {
e.preventDefault();
handleCopySelectedLayer();
return;
}
}
// Paste Layer: Ctrl+V
- if (!e.shiftKey && key === 'v') {
+ if (!e.shiftKey && (code === 'KeyV' || key === 'v')) {
if (!hasOpenDocument) return;
e.preventDefault();
handlePasteSelectedLayer();
return;
}
// Group Layers: Ctrl+G
- if (!e.shiftKey && (key === 'g' || e.code === 'KeyG')) {
+ if (!e.shiftKey && (code === 'KeyG' || key === 'g')) {
if (!hasOpenDocument) return;
e.preventDefault();
handleGroupSelectedLayers();
return;
}
// Transform: Ctrl+T
- if (!e.shiftKey && (key === 't' || e.code === 'KeyT')) {
+ if (!e.shiftKey && (code === 'KeyT' || key === 't')) {
if (!hasOpenDocument) return;
e.preventDefault();
handleStartTransform();
return;
}
// Select All: Ctrl+A
- if (!e.shiftKey && (key === 'a' || e.code === 'KeyA')) {
+ if (!e.shiftKey && (code === 'KeyA' || key === 'a')) {
if (!hasOpenDocument) return;
e.preventDefault();
handleSelectAll();
return;
}
// Deselect: Ctrl+D
- if (!e.shiftKey && (key === 'd' || e.code === 'KeyD')) {
+ if (!e.shiftKey && (code === 'KeyD' || key === 'd')) {
if (!hasOpenDocument) return;
e.preventDefault();
handleDeselect();
return;
}
// Invert Selection: Ctrl+Shift+I
- if (e.shiftKey && (key === 'i' || e.code === 'KeyI')) {
+ if (e.shiftKey && (code === 'KeyI' || key === 'i')) {
if (!hasOpenDocument) return;
e.preventDefault();
handleInvertSelection();
return;
}
// Reverse Gradient (Invert Colors): Ctrl+I
- if (!e.shiftKey && (key === 'i' || e.code === 'KeyI')) {
+ if (!e.shiftKey && (code === 'KeyI' || key === 'i')) {
if (!hasOpenDocument || !activeLayer || activeLayer.locked || activeLayer.type !== 'raster') return;
e.preventDefault();
handleApplyReverseGradient();
return;
}
// Hue / Saturation / Luminosity: Ctrl+U
- if (!e.shiftKey && (key === 'u' || e.code === 'KeyU')) {
+ if (!e.shiftKey && (code === 'KeyU' || key === 'u')) {
if (!hasOpenDocument || !activeLayer || activeLayer.locked || activeLayer.type !== 'raster') return;
e.preventDefault();
handleOpenTonalModal('hue-saturation');
return;
}
// Settings: Ctrl+,
- if (!e.shiftKey && (key === ',' || key === '<')) {
+ if (!e.shiftKey && (code === 'Comma' || key === ',' || key === '<')) {
e.preventDefault();
setIsSettingsModalOpen(true);
return;
}
// Toggle Perspective Ruler: Ctrl+Shift+R
- if (e.shiftKey && (key === 'r' || e.code === 'KeyR')) {
+ if (e.shiftKey && (code === 'KeyR' || key === 'r')) {
e.preventDefault();
updatePerspectiveRuler((prev) => {
if (!prev) {
@@ -4606,7 +5121,7 @@ export function App() {
return;
}
// Toggle Perspective Snapping: Ctrl+Shift+P
- if (e.shiftKey && (key === 'p' || e.code === 'KeyP')) {
+ if (e.shiftKey && (code === 'KeyP' || key === 'p')) {
e.preventDefault();
updatePerspectiveRuler((prev) => {
if (!prev) return null;
@@ -4616,108 +5131,210 @@ export function App() {
});
return;
}
+ return;
}
- // Tool shortcuts (without modifier keys)
- if (!e.ctrlKey && !e.metaKey && !e.altKey) {
- if (key === 'b') {
- handleSelectTool('brush');
- } else if (key === 'e') {
- handleSelectTool('eraser');
- } else if (key === 'w') {
- handleSelectTool('select-wand');
- } else if (key === 'm') {
- handleSelectTool('select-rect');
- } else if (key === 'l') {
- handleSelectTool('select-lasso');
- } else if (key === 'g') {
- handleSelectTool('fill');
- } else if (key === 't') {
- handleSelectTool('text');
- } else if (key === 'f') {
- handleSelectTool('frame');
- } else if (key === 'i') {
- handleSelectTool('pipette');
- } else if (key === 'j') {
- handleSelectTool('liquify');
- } else if (key === 'x') {
- handleSwapColors();
- } else if (key === 'c') {
- toggleTransparentColor();
- } else if (key === '[') {
- setIsLeftPanelHidden((prev) => !prev);
- } else if (key === 'delete' || key === 'backspace') {
- if (!hasOpenDocument) return;
+ // Alt-only shortcuts: Alt+C -> Add Animation Cel
+ if (e.altKey && !e.ctrlKey && !e.metaKey) {
+ if (!e.shiftKey && (code === 'KeyC' || key === 'c')) {
+ if (!hasOpenDocument || !activeAnimationTimeline) return;
e.preventDefault();
- if (selection) {
- handleClearSelection();
- } else {
- handleDeleteSelectedLayer();
- }
- } else if (key === 'escape') {
- if (transformSession?.active) {
- e.preventDefault();
- handleCancelTransform();
- } else if (textSession) {
- e.preventDefault();
- handleCancelText();
- } else if (selection) {
- e.preventDefault();
- handleDeselect();
+ // Revert temporary Alt pipette if it activated on Alt down
+ if (isAltActiveRef.current && previousToolBeforeAltRef.current !== null) {
+ setTool(previousToolBeforeAltRef.current);
+ previousToolBeforeAltRef.current = null;
+ isAltActiveRef.current = false;
}
- } else if (key === 'enter') {
- if (transformSession?.active) {
- e.preventDefault();
- handleApplyTransform();
+ handleAddAnimationCel(activeAnimationTimeline.currentFrame);
+ }
+ return;
+ }
+
+ // Tab / Shift+Tab: Toggle UI Panels (CSP workspace hide)
+ if (code === 'Tab' && !textSession) {
+ e.preventDefault();
+ if (e.shiftKey) {
+ setIsLeftPanelHidden((prev) => !prev);
+ } else {
+ const hideBoth = !(isLeftPanelHidden && isRightSidebarHidden);
+ setIsLeftPanelHidden(hideBoth);
+ setIsRightSidebarHidden(hideBoth);
+ }
+ return;
+ }
+
+ // Brush Size Stepper: [ and ] (BracketLeft / BracketRight, supports key-repeat)
+ if (!e.shiftKey && (code === 'BracketLeft' || code === 'BracketRight')) {
+ e.preventDefault();
+ const dir: -1 | 1 = code === 'BracketLeft' ? -1 : 1;
+ if (toolRef.current === 'liquify') {
+ const nextSize = Math.max(4, Math.min(500, Math.round(stepBrushSizePreset(liquifySettings.size, dir))));
+ handleUpdateLiquifySettings({ size: nextSize });
+ } else {
+ const nextSize = stepBrushSizePreset(brushSettings.size, dir);
+ updateBrushSettings({ size: nextSize });
+ }
+ return;
+ }
+
+ // Single-key tool & color shortcuts (no modifiers)
+ if (!e.shiftKey) {
+ const mappedTool = CODE_TO_TOOL[code];
+ if (mappedTool) {
+ if (e.repeat) return;
+ const prev = toolRef.current;
+ if (prev !== mappedTool) {
+ tempToolHoldRef.current = {
+ code,
+ prevTool: prev,
+ targetTool: mappedTool,
+ downAt: performance.now(),
+ usedWhileHeld: false,
+ };
+ handleSelectTool(mappedTool);
}
+ return;
+ }
+
+ if (code === 'KeyX' || key === 'x') {
+ if (!e.repeat) handleSwapColors();
+ return;
+ }
+ if (code === 'KeyD' || key === 'd') {
+ if (!e.repeat) handleResetDefaultColors();
+ return;
+ }
+ if (code === 'KeyC' || key === 'c') {
+ if (!e.repeat) toggleTransparentColor();
+ return;
+ }
+ }
+
+ if (key === 'delete' || key === 'backspace') {
+ if (!hasOpenDocument) return;
+ e.preventDefault();
+ if (selection) {
+ handleClearSelection();
+ } else {
+ handleDeleteSelectedLayer();
+ }
+ } else if (key === 'escape') {
+ if (transformSession?.active) {
+ e.preventDefault();
+ handleCancelTransform();
+ } else if (textSession) {
+ e.preventDefault();
+ handleCancelText();
+ } else if (selection) {
+ e.preventDefault();
+ handleDeselect();
+ }
+ } else if (key === 'enter') {
+ if (transformSession?.active) {
+ e.preventDefault();
+ handleApplyTransform();
}
}
};
+ const handleKeyUp = (e: KeyboardEvent) => {
+ const hold = tempToolHoldRef.current;
+ if (hold && e.code === hold.code) {
+ const heldMs = performance.now() - hold.downAt;
+ tempToolHoldRef.current = null;
+ if ((heldMs >= 220 || hold.usedWhileHeld) && toolRef.current === hold.targetTool) {
+ handleSelectTool(hold.prevTool);
+ }
+ }
+ };
+
+ const handlePointerDownMarkUsed = () => {
+ if (tempToolHoldRef.current) {
+ tempToolHoldRef.current.usedWhileHeld = true;
+ }
+ };
+
+ const handleWindowBlur = () => {
+ tempToolHoldRef.current = null;
+ };
+
window.addEventListener('keydown', handleKeyDown);
- return () => window.removeEventListener('keydown', handleKeyDown);
+ window.addEventListener('keyup', handleKeyUp);
+ window.addEventListener('pointerdown', handlePointerDownMarkUsed, true);
+ window.addEventListener('blur', handleWindowBlur);
+ return () => {
+ window.removeEventListener('keydown', handleKeyDown);
+ window.removeEventListener('keyup', handleKeyUp);
+ window.removeEventListener('pointerdown', handlePointerDownMarkUsed, true);
+ window.removeEventListener('blur', handleWindowBlur);
+ };
}, [
+ activeAnimationTimeline,
+ activeLayer,
+ activeLayerId,
+ brushSettings.size,
+ dimensions,
+ duplicateLayer,
+ handleAddAnimationCel,
+ handleAddLayer,
+ handleApplyReverseGradient,
+ handleApplyTransform,
+ handleCancelText,
+ handleCancelTransform,
+ handleClearSelection,
handleCopySelectedLayer,
handleDeleteSelectedLayer,
+ handleDeselect,
handleGroupSelectedLayers,
- handleExportImage,
+ handleInvertSelection,
+ handleOpenTonalModal,
handlePasteSelectedLayer,
+ handleResetDefaultColors,
handleSave,
handleSaveAs,
+ handleSelectAll,
+ handleSelectTool,
+ handleStartTransform,
handleSwapColors,
- toggleTransparentColor,
handleTriggerOpenFile,
+ handleUndo,
+ handleUpdateAnimationTimeline,
+ handleUpdateLiquifySettings,
hasOpenDocument,
- activeLayer,
+ isLeftPanelHidden,
+ isRightSidebarHidden,
+ layers,
+ liquifySettings.size,
redo,
- handleUndo,
- handleStartTransform,
- handleDeselect,
- handleSelectAll,
- handleInvertSelection,
- handleClearSelection,
- handleCancelTransform,
- handleApplyTransform,
- handleCancelText,
- handleApplyReverseGradient,
- handleOpenTonalModal,
selection,
- transformSession,
+ showToast,
textSession,
- handleSelectTool,
- toggleSoftProof,
toggleGamutWarning,
+ toggleSoftProof,
+ toggleTransparentColor,
+ transformSession,
+ updateBrushSettings,
+ updatePerspectiveRuler,
]);
// Pipette tool: hold Alt to activate, release Alt to switch back to previous tool
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
- if (['INPUT', 'TEXTAREA'].includes((e.target as HTMLElement).tagName)) {
+ const target = e.target as HTMLElement | null;
+ if (
+ isAnyModalOpenRef.current ||
+ (target && (['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName) || target.isContentEditable))
+ ) {
return;
}
if (e.key === 'Alt') {
- if (!e.ctrlKey && !e.metaKey) {
+ if (
+ !e.ctrlKey &&
+ !e.metaKey &&
+ !isDrawingRef.current &&
+ !selectionPenDrawingRef.current?.isDrawing
+ ) {
e.preventDefault();
if (!isAltActiveRef.current && !e.repeat) {
isAltActiveRef.current = true;
@@ -4730,8 +5347,8 @@ export function App() {
return;
}
- // If user holds Ctrl while Alt is active (e.g. initiating Ctrl+Alt brush resize), revert pipette
- if ((e.ctrlKey || e.metaKey) && isAltActiveRef.current) {
+ // If user presses Ctrl or Space while Alt is active (Ctrl+Alt resize or Alt+Space play), revert pipette
+ if (((e.ctrlKey || e.metaKey) || e.code === 'Space') && isAltActiveRef.current) {
if (previousToolBeforeAltRef.current !== null) {
setTool(previousToolBeforeAltRef.current);
previousToolBeforeAltRef.current = null;
@@ -4772,7 +5389,7 @@ export function App() {
window.removeEventListener('keyup', handleKeyUp);
window.removeEventListener('blur', handleBlur);
};
- }, []);
+ }, [isDrawingRef]);
// Drag and drop onto application window
useEffect(() => {
@@ -4821,8 +5438,8 @@ export function App() {
};
}, [handleProcessFile, showToast, updateBrushSettings]);
- // Application Menu Bar Sections
- const menuSections: MenuSection[] = [
+ // Application Menu Bar Sections (Memoized to prevent 240Hz navigation re-allocations)
+ const menuSections: MenuSection[] = useMemo(() => [
{
id: 'file',
label: 'File',
@@ -5539,7 +6156,8 @@ export function App() {
disabled: !hasOpenDocument,
submenu: [2, 4, 6, 8, 12, 16].map((count) => ({
id: `ruler-rays-${count}`,
- label: `${count} Rays per VP${(perspectiveRuler.guideRayCount || 6) === count ? ' ✓' : ''}`,
+ label: `${count} Rays per VP`,
+ checked: (perspectiveRuler.guideRayCount || 6) === count,
onClick: () =>
updatePerspectiveRuler((prev) =>
prev ? { ...prev, guideRayCount: count } : null
@@ -5703,21 +6321,18 @@ export function App() {
id: 'proof-setup-us-web',
label: 'Working CMYK - U.S. Web Coated (SWOP) v2',
checked: softProofSettings.standard === 'us-web-coated-swop',
- icon: softProofSettings.standard === 'us-web-coated-swop' ? <Check className="w-3.5 h-3.5 text-cyan-400" /> : undefined,
onClick: () => setProofStandard('us-web-coated-swop'),
},
{
id: 'proof-setup-japan',
label: 'Japan Color 2001 Coated',
checked: softProofSettings.standard === 'japan-color-2001',
- icon: softProofSettings.standard === 'japan-color-2001' ? <Check className="w-3.5 h-3.5 text-cyan-400" /> : undefined,
onClick: () => setProofStandard('japan-color-2001'),
},
{
id: 'proof-setup-iso',
label: 'ISO Coated v2 (ECI)',
checked: softProofSettings.standard === 'iso-coated-v2',
- icon: softProofSettings.standard === 'iso-coated-v2' ? <Check className="w-3.5 h-3.5 text-cyan-400" /> : undefined,
onClick: () => setProofStandard('iso-coated-v2'),
},
],
@@ -5725,9 +6340,8 @@ export function App() {
{
id: 'view-proof-colors',
label: 'Proof Colors',
- shortcut: 'Ctrl+Y',
+ shortcut: 'Ctrl+Alt+Y',
checked: softProofSettings.enabled,
- icon: softProofSettings.enabled ? <Check className="w-3.5 h-3.5 text-cyan-400" /> : undefined,
disabled: !hasOpenDocument,
onClick: toggleSoftProof,
},
@@ -5736,7 +6350,6 @@ export function App() {
label: 'Gamut Warning',
shortcut: 'Ctrl+Shift+Y',
checked: softProofSettings.gamutWarning,
- icon: softProofSettings.gamutWarning ? <Check className="w-3.5 h-3.5 text-cyan-400" /> : undefined,
disabled: !hasOpenDocument,
onClick: toggleGamutWarning,
},
@@ -5850,39 +6463,83 @@ export function App() {
icon: <InfoIcon className="w-3.5 h-3.5 text-[#93c5fd]" />,
onClick: () => {
alert(
- 'Ink Studio — Professional Digital Painting & Manga Studio\n\n' +
- '• Full Layer Management with 12 Blend Modes\n' +
- '• Supports Opening PSD (Photoshop) & CSP (Clip Studio Paint) with layers\n' +
- '• Supports Common Images: PNG, JPG, WEBP, GIF, BMP, SVG\n' +
- '• Save & Save As: PSD (layered), Ink Studio Project (.sora / .ink), PNG, JPG, WebP\n' +
- '• Export Image: High-resolution PNG\n' +
- '• Color Modes: Full Color (RGB), Grayscale, and 1-bit Manga Monochrome\n' +
- '• Tablet Pressure & Inking Stabilization'
+ 'Ink Studio - Professional Digital Painting & Manga Studio\n\n' +
+ '- Full Layer Management with 17 Blend Modes\n' +
+ '- Supports Opening PSD (Photoshop) & CSP (Clip Studio Paint) with layers\n' +
+ '- Supports Common Images: PNG, JPG, WEBP, GIF, BMP, SVG\n' +
+ '- Save & Save As: PSD (layered), Ink Studio Project (.sora / .ink), PNG, JPG, WebP\n' +
+ '- Export Image: High-resolution PNG\n' +
+ '- Color Modes: Full Color (RGB), Grayscale, and 1-bit Manga Monochrome\n' +
+ '- CSP Sub-Tool Engine, Tablet Pressure, Tilt & Inking Stabilization'
);
},
},
],
},
- ];
-
- const handleSaveFirstTimeName = useCallback(
- (name: string) => {
- const updated: AppSettings = {
- ...appSettings,
- userName: name,
- hasPromptedName: true,
- };
- setAppSettings(updated);
- saveAppSettings(updated);
- try {
- localStorage.setItem('sora_paint_nickname', name);
- } catch {
- // ignore
- }
- showToast(`Welcome, ${name}!`);
- },
- [appSettings, showToast]
- );
+ ], [
+ activeAnimationTimeline,
+ activeLayer,
+ activeLayerId,
+ addLayerMask,
+ canRedo,
+ canUndo,
+ clearCanvas,
+ deleteLayer,
+ dimensions,
+ duplicateLayer,
+ handleAddAnimationCel,
+ handleAddLayer,
+ handleApplyFilter,
+ handleApplyReverseGradient,
+ handleClearActiveLayer,
+ handleContractSelection,
+ handleConvertLayer,
+ handleCopySelectedLayer,
+ handleDeleteSelectedLayer,
+ handleDeselect,
+ handleExpandSelection,
+ handleExportImage,
+ handleFeatherSelection,
+ handleFillSelectionColor,
+ handleInvertSelection,
+ handleOpenAdjustmentModal,
+ handleOpenLayerStylesModal,
+ handleOpenTonalModal,
+ handlePasteSelectedLayer,
+ handleSave,
+ handleSaveAs,
+ handleSelectAll,
+ handleSelectTool,
+ handleStartTransform,
+ handleTriggerImport3DFile,
+ handleTriggerOpenFile,
+ handleTriggerPasteFromFile,
+ handleUndo,
+ handleUpdateAnimationTimeline,
+ hasOpenDocument,
+ isWebtoonMode,
+ layers,
+ perspectiveRuler,
+ redo,
+ removeLayerMask,
+ resetRotation,
+ resetZoomAndCenter,
+ selection,
+ setProofStandard,
+ showToast,
+ softProofSettings.enabled,
+ softProofSettings.gamutWarning,
+ softProofSettings.standard,
+ toggleGamutWarning,
+ toggleLayerColor,
+ toggleLayerMask,
+ toggleMaskLinked,
+ toggleSoftProof,
+ updateBrushSettings,
+ updatePerspectiveRuler,
+ zoomIn,
+ zoomOut,
+ ]);
const handleSelectWelcomeDocument = useCallback(
async (doc: RecentDocument) => {
@@ -5921,29 +6578,33 @@ export function App() {
[handleCreateNewCanvas, handleProcessFile, showToast]
);
- const isModernTheme = appSettings.themePreset === 'modern';
- const modernAccent = appSettings.modernAccent || 'blue';
+ const modernAccent = appSettings.modernAccent || 'neutral';
const modernAccentHex = resolveModernAccentColor(modernAccent, appSettings.modernCustomColor);
- const modernAccentRgb = hexToRgb(modernAccentHex) || { r: 59, g: 130, b: 246 };
-
- const modernStyleVars = useMemo(() => {
- if (!isModernTheme) return undefined;
- return {
- '--modern-accent': modernAccentHex,
- '--modern-accent-rgb': `${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}`,
- '--modern-accent-glow': `rgba(${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}, 0.28)`,
- '--modern-accent-subtle': `rgba(${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}, 0.12)`,
- '--modern-accent-border': `rgba(${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}, 0.42)`,
- '--modern-accent-hover': `rgba(${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}, 0.2)`,
- } as React.CSSProperties;
- }, [isModernTheme, modernAccentHex, modernAccentRgb.r, modernAccentRgb.g, modernAccentRgb.b]);
+ const modernAccentRgb = hexToRgb(modernAccentHex) || { r: 229, g: 229, b: 229 };
+ const modernAccentContrast = getAccentContrastColor(modernAccentHex);
+
+ const modernStyleVars = useMemo(
+ () =>
+ ({
+ '--accent': modernAccentHex,
+ '--accent-rgb': `${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}`,
+ '--accent-contrast': modernAccentContrast,
+ '--accent-subtle': `rgba(${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}, 0.14)`,
+ '--accent-border': `rgba(${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}, 0.32)`,
+ '--modern-accent': modernAccentHex,
+ '--modern-accent-rgb': `${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}`,
+ '--modern-accent-subtle': `rgba(${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}, 0.14)`,
+ '--modern-accent-border': `rgba(${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}, 0.32)`,
+ '--modern-accent-hover': `rgba(${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}, 0.2)`,
+ }) as React.CSSProperties,
+ [modernAccentHex, modernAccentRgb.r, modernAccentRgb.g, modernAccentRgb.b, modernAccentContrast]
+ );
return (
<div
- className="flex flex-col w-screen h-screen overflow-hidden bg-[#1e1e1e] text-[#cccccc] font-sans app-root-container"
- data-theme={appSettings.themePreset || 'vintage-manga'}
- data-accent={isModernTheme ? modernAccent : undefined}
- data-tone={isModernTheme ? (appSettings.uiTone || 'slate') : undefined}
+ className="flex flex-col w-screen h-screen overflow-hidden bg-[#161616] text-[#e5e5e5] font-sans gap-px app-root-container"
+ data-theme="modern"
+ data-accent={modernAccent}
style={modernStyleVars}
>
{/* Hidden File Input for Native File Picker */}
@@ -5973,13 +6634,8 @@ export function App() {
className="hidden"
/>
- {/* Top Application Bar */}
+ {/* Consolidated Single Slim 36px Header Bar */}
<Header
- tool={tool}
- preset={brushSettings.preset}
- brushName={brushSettings.brushName}
- brushSize={brushSettings.size}
- onBrushSizeChange={handleBrushSizeChange}
canUndo={hasOpenDocument && canUndo}
canRedo={hasOpenDocument && canRedo}
onUndo={handleUndo}
@@ -5994,11 +6650,17 @@ export function App() {
colorMode={colorMode}
menuSections={menuSections}
hasOpenDocument={hasOpenDocument}
+ documents={documents}
+ activeDocumentId={activeDocumentId}
+ onSelectDocument={handleSelectDocument}
+ onCloseDocument={handleCloseDocument}
+ onNewDocument={() => setIsNewCanvasModalOpen(true)}
+ onRenameDocument={handleRenameDocument}
isCollabConnected={isCollabConnected}
collabPeerCount={collabPeers.length + 1}
onOpenCollabModal={() => setIsHostModalOpen(true)}
+ onOpenSettings={() => setIsSettingsModalOpen(true)}
themePreset={appSettings.themePreset}
- activeDocumentTitle={documents.find((d) => d.id === activeDocumentId)?.name}
softProofSettings={softProofSettings}
appView={appView}
onSelectAppView={(view) => {
@@ -6010,19 +6672,8 @@ export function App() {
}}
/>
- {/* Modern Horizontal Property Bar below Header in Workspace matching Reference 3 */}
- {isModernTheme && hasOpenDocument && appView === 'workspace' && (
- <ModernPropertyBar
- tool={tool}
- brushSettings={brushSettings}
- onUpdateBrushSettings={updateBrushSettings}
- onToggleBrushEditor={() => setIsLeftPanelHidden((prev) => !prev)}
- isBrushEditorOpen={!isLeftPanelHidden}
- />
- )}
-
{/* Main Workspace */}
- <div className="flex flex-1 overflow-hidden relative">
+ <div className="flex flex-1 overflow-hidden relative gap-px bg-[#161616]">
{!hasOpenDocument || appView === 'home' ? (
<WelcomeScreen
userName={appSettings.userName}
@@ -6035,237 +6686,226 @@ export function App() {
) : (
<>
<LeftPanel
- currentTool={tool}
- onSelectTool={handleSelectTool}
- brushSettings={brushSettings}
- onUpdateBrushSettings={updateBrushSettings}
- primaryColor={primaryColor}
- secondaryColor={secondaryColor}
- isTransparentColor={isTransparentColor}
- onToggleTransparentColor={toggleTransparentColor}
- onPrimaryColorChange={handlePrimaryColorChange}
- onSecondaryColorChange={handleSecondaryColorChange}
- onSwapColors={handleSwapColors}
- recentColors={recentColors}
- width={leftPanelWidth}
- onWidthChange={handleLeftPanelWidthChange}
- isHidden={isLeftPanelHidden}
- onToggleHidden={() => setIsLeftPanelHidden((prev) => !prev)}
- fillSettings={fillSettings}
- onUpdateFillSettings={(newSettings) => setFillSettings((prev) => ({ ...prev, ...newSettings }))}
- textSettings={textSettings}
- onUpdateTextSettings={(newSettings) => setTextSettings((prev) => ({ ...prev, ...newSettings }))}
- frameSettings={frameSettings}
- onUpdateFrameSettings={(newSettings) => setFrameSettings((prev) => ({ ...prev, ...newSettings }))}
- hasSelection={Boolean(selection)}
- onDeselect={handleDeselect}
- onTransformSelection={handleStartTransform}
- onFillScreentone={handleFillScreentone}
- liquifySettings={liquifySettings}
- onUpdateLiquifySettings={handleUpdateLiquifySettings}
- balloonSettings={balloonSettings}
- onUpdateBalloonSettings={(newSettings) => setBalloonSettings((prev) => ({ ...prev, ...newSettings }))}
- vectorEditSettings={vectorEditSettings}
- onUpdateVectorEditSettings={(newSettings) => setVectorEditSettings((prev) => ({ ...prev, ...newSettings }))}
- onOpenMangaEffects={() => setIsMangaEffectsModalOpen(true)}
- wandSettings={wandSettings}
- onUpdateWandSettings={(newSettings) => setWandSettings((prev) => ({ ...prev, ...newSettings }))}
- onExpandSelection={handleExpandSelection}
- onContractSelection={handleContractSelection}
- onFeatherSelection={handleFeatherSelection}
- onInvertSelection={handleInvertSelection}
- />
-
- {/* Center Workspace: Document Tab Bar (Projects) + Canvas Area */}
- <div className="flex flex-col flex-1 min-w-0 overflow-hidden relative">
- <DocumentTabBar
- documents={documents}
- activeDocumentId={activeDocumentId}
- onSelectDocument={handleSelectDocument}
- onCloseDocument={handleCloseDocument}
- onNewDocument={() => setIsNewCanvasModalOpen(true)}
- onRenameDocument={handleRenameDocument}
- themePreset={appSettings.themePreset}
- />
-
- <CanvasArea
- viewportRef={viewportRef}
- onViewportReady={handleViewportReady}
- dimensions={dimensions}
- brushSettings={brushSettings}
- onUpdateBrushSettings={updateBrushSettings}
- zoom={zoom}
- pan={pan}
- rotation={rotation}
- isSpaceDown={isSpaceDown}
- isShiftDown={isShiftDown}
- isRotateModifier={isRotateModifier}
- isPanning={isPanning}
- isRotating={isRotating}
- onStartPan={startPan}
- onStartRotate={startRotate}
- isHovering={isHovering}
- cursorPos={cursorPos}
- onPointerDown={handlePointerDown}
- onPointerMove={handlePointerMove}
- onPointerUp={handlePointerUp}
- onPointerEnter={handlePointerEnter}
- onPointerLeave={handlePointerLeave}
- layers={layers}
- activeLayerId={activeLayerId}
- colorMode={colorMode}
- layerCanvasesRef={layerCanvasesRef}
- registerLayerCanvas={registerLayerCanvas}
- getEffectiveOpacity={getEffectiveOpacity}
- isLayerEffectivelyVisible={isLayerEffectivelyVisible}
- interactionRef={interactionRef}
- showCheckerboard={appSettings.showCheckerboard}
- hasOpenDocument={hasOpenDocument}
- draftCanvasRef={draftCanvasRef}
- strokeCanvasRef={strokeCanvasRef}
- peers={collabPeers}
- activePings={collabActivePings}
- remoteDraftCanvasesRef={remoteDraftCanvasesRef}
- tool={tool}
- liquifySettings={liquifySettings}
- selection={selection}
- onDeselect={handleDeselect}
- onTransformSelection={handleStartTransform}
- onFillScreentone={handleFillScreentone}
- onFillColor={handleFillSelectionColor}
- onClearSelection={handleClearSelection}
- onInvertSelection={handleInvertSelection}
- onExpandSelection={handleExpandSelection}
- onContractSelection={handleContractSelection}
- onFeatherSelection={handleFeatherSelection}
- transformSession={transformSession}
- onUpdateTransformSession={(updater) =>
- setTransformSession((prev) => (prev ? updater(prev) : null))
- }
- onApplyTransform={handleApplyTransform}
- onCancelTransform={handleCancelTransform}
- textSession={textSession}
- onUpdateTextSettings={(updater) =>
- setTextSession((prev) => (prev ? { ...prev, settings: updater(prev.settings) } : null))
- }
- onMoveTextSession={(newX, newY) =>
- setTextSession((prev) => (prev ? { ...prev, x: newX, y: newY } : null))
- }
- onConfirmText={handleConfirmText}
- onCancelText={handleCancelText}
- perspectiveRuler={hasOpenDocument ? perspectiveRuler : null}
- onUpdatePerspectiveRuler={setPerspectiveRuler}
- activeLockedAxis={activeLockedAxis}
- is3DLayerOpen={is3DLayerOpen}
- initial3DFile={initial3DFile}
- onClose3DLayer={() => {
- setIs3DLayerOpen(false);
- setInitial3DFile(null);
- }}
- onInsertRasterLayer={handleInsert3DRasterLayer}
- isWebtoonMode={isWebtoonMode}
- onToggleWebtoonMode={() => setIsWebtoonMode((prev) => !prev)}
- onOpenWebtoonExport={() => setIsWebtoonExportModalOpen(true)}
- activeBalloon={activeBalloon}
- onUpdateBalloon={(updater) => setActiveBalloon((prev) => (prev ? updater(prev) : null))}
- onConfirmBalloon={handleConfirmBalloon}
- onDeleteBalloon={handleDeleteBalloon}
- animationTimeline={activeAnimationTimeline}
- onUpdateAnimationTimeline={handleUpdateAnimationTimeline}
- onAddAnimationCel={handleAddAnimationCel}
- onDeleteAnimationCel={handleDeleteAnimationCel}
- onSelectCelLayer={setActiveLayerId}
- softProofSettings={softProofSettings}
- />
- </div>
+ currentTool={tool}
+ onSelectTool={handleSelectTool}
+ brushSettings={brushSettings}
+ onUpdateBrushSettings={updateBrushSettings}
+ primaryColor={primaryColor}
+ secondaryColor={secondaryColor}
+ isTransparentColor={isTransparentColor}
+ onToggleTransparentColor={toggleTransparentColor}
+ onPrimaryColorChange={handlePrimaryColorChange}
+ onSecondaryColorChange={handleSecondaryColorChange}
+ onSwapColors={handleSwapColors}
+ recentColors={recentColors}
+ width={leftPanelWidth}
+ onWidthChange={handleLeftPanelWidthChange}
+ isHidden={isLeftPanelHidden}
+ onToggleHidden={() => setIsLeftPanelHidden((prev) => !prev)}
+ fillSettings={fillSettings}
+ onUpdateFillSettings={(newSettings) => setFillSettings((prev) => ({ ...prev, ...newSettings }))}
+ textSettings={textSettings}
+ onUpdateTextSettings={(newSettings) => setTextSettings((prev) => ({ ...prev, ...newSettings }))}
+ frameSettings={frameSettings}
+ onUpdateFrameSettings={(newSettings) => setFrameSettings((prev) => ({ ...prev, ...newSettings }))}
+ hasSelection={Boolean(selection)}
+ onDeselect={handleDeselect}
+ onTransformSelection={handleStartTransform}
+ onFillScreentone={handleFillScreentone}
+ liquifySettings={liquifySettings}
+ onUpdateLiquifySettings={handleUpdateLiquifySettings}
+ balloonSettings={balloonSettings}
+ onUpdateBalloonSettings={(newSettings) => setBalloonSettings((prev) => ({ ...prev, ...newSettings }))}
+ vectorEditSettings={vectorEditSettings}
+ onUpdateVectorEditSettings={(newSettings) => setVectorEditSettings((prev) => ({ ...prev, ...newSettings }))}
+ onOpenMangaEffects={() => setIsMangaEffectsModalOpen(true)}
+ wandSettings={wandSettings}
+ onUpdateWandSettings={(newSettings) => setWandSettings((prev) => ({ ...prev, ...newSettings }))}
+ onExpandSelection={handleExpandSelection}
+ onContractSelection={handleContractSelection}
+ onFeatherSelection={handleFeatherSelection}
+ onInvertSelection={handleInvertSelection}
+ />
+
+ {/* Center Workspace: >80% Viewport Dedicated to Drawing Canvas */}
+ <div className="flex flex-col flex-1 min-w-0 overflow-hidden relative">
+ <CanvasArea
+ viewportRef={viewportRef}
+ onViewportReady={handleViewportReady}
+ dimensions={dimensions}
+ brushSettings={brushSettings}
+ onUpdateBrushSettings={updateBrushSettings}
+ zoom={zoom}
+ pan={pan}
+ rotation={rotation}
+ isSpaceDown={isSpaceDown}
+ isShiftDown={isShiftDown}
+ isRotateModifier={isRotateModifier}
+ isPanning={isPanning}
+ isRotating={isRotating}
+ onStartPan={startPan}
+ onStartRotate={startRotate}
+ isHovering={isHovering}
+ cursorPos={cursorPos}
+ onPointerDown={handlePointerDown}
+ onPointerMove={handlePointerMove}
+ onPointerUp={handlePointerUp}
+ onPointerEnter={handlePointerEnter}
+ onPointerLeave={handlePointerLeave}
+ layers={layers}
+ activeLayerId={activeLayerId}
+ colorMode={colorMode}
+ layerCanvasesRef={layerCanvasesRef}
+ registerLayerCanvas={registerLayerCanvas}
+ getEffectiveOpacity={getEffectiveOpacity}
+ isLayerEffectivelyVisible={isLayerEffectivelyVisible}
+ interactionRef={interactionRef}
+ showCheckerboard={appSettings.showCheckerboard}
+ showCursorCoordinates={appSettings.showCursorCoordinates}
+ showPressureInStatusBar={appSettings.showPressureInStatusBar}
+ hasOpenDocument={hasOpenDocument}
+ draftCanvasRef={draftCanvasRef}
+ strokeCanvasRef={strokeCanvasRef}
+ peers={collabPeers}
+ activePings={collabActivePings}
+ remoteDraftCanvasesRef={remoteDraftCanvasesRef}
+ tool={tool}
+ liquifySettings={liquifySettings}
+ onUpdateLiquifySettings={handleUpdateLiquifySettings}
+ primaryColor={primaryColor}
+ onSwapColors={handleSwapColors}
+ selection={selection}
+ onDeselect={handleDeselect}
+ onTransformSelection={handleStartTransform}
+ onFillScreentone={handleFillScreentone}
+ onFillColor={handleFillSelectionColor}
+ onClearSelection={handleClearSelection}
+ onInvertSelection={handleInvertSelection}
+ onExpandSelection={handleExpandSelection}
+ onContractSelection={handleContractSelection}
+ onFeatherSelection={handleFeatherSelection}
+ transformSession={transformSession}
+ onUpdateTransformSession={(updater) =>
+ setTransformSession((prev) => (prev ? updater(prev) : null))
+ }
+ onApplyTransform={handleApplyTransform}
+ onCancelTransform={handleCancelTransform}
+ textSession={textSession}
+ onUpdateTextSettings={(updater) =>
+ setTextSession((prev) => (prev ? { ...prev, settings: updater(prev.settings) } : null))
+ }
+ onMoveTextSession={(newX, newY) =>
+ setTextSession((prev) => (prev ? { ...prev, x: newX, y: newY } : null))
+ }
+ onConfirmText={handleConfirmText}
+ onCancelText={handleCancelText}
+ perspectiveRuler={hasOpenDocument ? perspectiveRuler : null}
+ onUpdatePerspectiveRuler={updatePerspectiveRuler}
+ activeLockedAxis={activeLockedAxis}
+ is3DLayerOpen={is3DLayerOpen}
+ initial3DFile={initial3DFile}
+ onClose3DLayer={() => {
+ setIs3DLayerOpen(false);
+ setInitial3DFile(null);
+ }}
+ onInsertRasterLayer={handleInsert3DRasterLayer}
+ isWebtoonMode={isWebtoonMode}
+ onToggleWebtoonMode={() => setIsWebtoonMode((prev) => !prev)}
+ onOpenWebtoonExport={() => setIsWebtoonExportModalOpen(true)}
+ activeBalloon={activeBalloon}
+ onUpdateBalloon={(updater) => setActiveBalloon((prev) => (prev ? updater(prev) : null))}
+ onConfirmBalloon={handleConfirmBalloon}
+ onDeleteBalloon={handleDeleteBalloon}
+ animationTimeline={activeAnimationTimeline}
+ onUpdateAnimationTimeline={handleUpdateAnimationTimeline}
+ onAddAnimationCel={handleAddAnimationCel}
+ onDeleteAnimationCel={handleDeleteAnimationCel}
+ onSelectCelLayer={setActiveLayerId}
+ softProofSettings={softProofSettings}
+ />
+ </div>
- <RightSidebar
- hasOpenDocument={hasOpenDocument}
- onNewCanvas={() => setIsNewCanvasModalOpen(true)}
- onOpenFile={handleTriggerOpenFile}
- primaryColor={primaryColor}
- secondaryColor={secondaryColor}
- onPrimaryColorChange={handlePrimaryColorChange}
- onSecondaryColorChange={handleSecondaryColorChange}
- onSwapColors={handleSwapColors}
- recentColors={recentColors}
- currentTool={tool}
- onSelectTool={setTool}
- colorMode={colorMode}
- historyList={hasOpenDocument ? historyList : []}
- historyIndex={hasOpenDocument ? historyIndex : -1}
- onJumpToHistory={jumpToHistoryIndex}
- canUndo={hasOpenDocument && canUndo}
- canRedo={hasOpenDocument && canRedo}
- onUndo={handleUndo}
- onRedo={redo}
- layers={hasOpenDocument ? layers : []}
- activeLayerId={hasOpenDocument ? activeLayerId : ''}
- selectedLayerIds={hasOpenDocument ? selectedLayerIds : []}
- onSelectLayer={setActiveLayerId}
- onToggleLayerSelection={toggleLayerSelection}
- onGroupSelectedLayers={handleGroupSelectedLayers}
- onDeleteSelectedLayers={handleDeleteSelectedLayers}
- onAddLayer={handleAddLayer}
- onOpen3DLayer={hasOpenDocument ? () => setIs3DLayerOpen(true) : undefined}
- onDuplicateLayer={duplicateLayer}
- onDeleteLayer={handleDeleteLayer}
- onToggleVisibility={handleToggleVisibility}
- onSetOpacity={handleSetOpacity}
- onSetBlendMode={setBlendMode}
- onToggleLock={toggleLock}
- onToggleAlphaLock={toggleAlphaLock}
- onToggleClipping={toggleClipping}
- onToggleCollapse={toggleCollapse}
- onRenameLayer={handleRenameLayer}
- onMoveLayer={moveLayer}
- onMoveLayerToFolder={moveLayerToFolder}
- onReorderLayers={reorderLayers}
- onToggleReferenceLayer={handleToggleReferenceLayer}
- onToggleTone={toggleTone}
- onSetToneFrequency={setToneFrequency}
- onSetToneAngle={setToneAngle}
- onSetToneDotShape={setToneDotShape}
- onSetToneDensity={setToneDensity}
- onSetToneDensityType={setToneDensityType}
- onToggleLayerColor={toggleLayerColor}
- onSetLayerColor={setLayerColor}
- onSetLayerSubColor={setLayerSubColor}
- onSetLayerExpressionColor={setLayerExpressionColor}
- onSetLayerMonoThreshold={setLayerMonoThreshold}
- onSetLayerMonoExpressMode={setLayerMonoExpressMode}
- onApplyExpressionColor={handleApplyExpressionColor}
- onApplyLayerColor={handleApplyLayerColor}
- activeEditTarget={activeEditTarget}
- onSelectEditTarget={setActiveEditTarget}
- onAddLayerMask={addLayerMask}
- onRemoveLayerMask={removeLayerMask}
- onToggleLayerMask={toggleLayerMask}
- onToggleMaskLinked={toggleMaskLinked}
- onOpenAdjustmentModal={handleOpenAdjustmentModal}
- onOpenLayerStylesModal={handleOpenLayerStylesModal}
- width={rightSidebarWidth}
- onWidthChange={handleRightSidebarWidthChange}
- />
- </>
+ {!isRightSidebarHidden && (
+ <RightSidebar
+ hasOpenDocument={hasOpenDocument}
+ onNewCanvas={() => setIsNewCanvasModalOpen(true)}
+ onOpenFile={handleTriggerOpenFile}
+ primaryColor={primaryColor}
+ secondaryColor={secondaryColor}
+ onPrimaryColorChange={handlePrimaryColorChange}
+ onSecondaryColorChange={handleSecondaryColorChange}
+ onSwapColors={handleSwapColors}
+ recentColors={recentColors}
+ currentTool={tool}
+ onSelectTool={handleSelectTool}
+ colorMode={colorMode}
+ historyList={hasOpenDocument ? historyList : []}
+ historyIndex={hasOpenDocument ? historyIndex : -1}
+ onJumpToHistory={jumpToHistoryIndex}
+ canUndo={hasOpenDocument && canUndo}
+ canRedo={hasOpenDocument && canRedo}
+ onUndo={handleUndo}
+ onRedo={redo}
+ layers={hasOpenDocument ? layers : []}
+ activeLayerId={hasOpenDocument ? activeLayerId : ''}
+ selectedLayerIds={hasOpenDocument ? selectedLayerIds : []}
+ onSelectLayer={setActiveLayerId}
+ onToggleLayerSelection={toggleLayerSelection}
+ onGroupSelectedLayers={handleGroupSelectedLayers}
+ onDeleteSelectedLayers={handleDeleteSelectedLayers}
+ onAddLayer={handleAddLayer}
+ onOpen3DLayer={hasOpenDocument ? () => setIs3DLayerOpen(true) : undefined}
+ onDuplicateLayer={duplicateLayer}
+ onDeleteLayer={handleDeleteLayer}
+ onToggleVisibility={handleToggleVisibility}
+ onSetOpacity={handleSetOpacity}
+ onSetBlendMode={setBlendMode}
+ onToggleLock={toggleLock}
+ onToggleAlphaLock={toggleAlphaLock}
+ onToggleClipping={toggleClipping}
+ onToggleCollapse={toggleCollapse}
+ onRenameLayer={handleRenameLayer}
+ onMoveLayer={moveLayer}
+ onMoveLayerToFolder={moveLayerToFolder}
+ onReorderLayers={reorderLayers}
+ onToggleReferenceLayer={handleToggleReferenceLayer}
+ onToggleTone={toggleTone}
+ onSetToneFrequency={setToneFrequency}
+ onSetToneAngle={setToneAngle}
+ onSetToneDotShape={setToneDotShape}
+ onSetToneDensity={setToneDensity}
+ onSetToneDensityType={setToneDensityType}
+ onToggleLayerColor={toggleLayerColor}
+ onSetLayerColor={setLayerColor}
+ onSetLayerSubColor={setLayerSubColor}
+ onSetLayerExpressionColor={setLayerExpressionColor}
+ onSetLayerMonoThreshold={setLayerMonoThreshold}
+ onSetLayerMonoExpressMode={setLayerMonoExpressMode}
+ onApplyExpressionColor={handleApplyExpressionColor}
+ onApplyLayerColor={handleApplyLayerColor}
+ activeEditTarget={activeEditTarget}
+ onSelectEditTarget={setActiveEditTarget}
+ onAddLayerMask={addLayerMask}
+ onRemoveLayerMask={removeLayerMask}
+ onToggleLayerMask={toggleLayerMask}
+ onToggleMaskLinked={toggleMaskLinked}
+ onOpenAdjustmentModal={handleOpenAdjustmentModal}
+ onOpenLayerStylesModal={handleOpenLayerStylesModal}
+ width={rightSidebarWidth}
+ onWidthChange={handleRightSidebarWidthChange}
+ />
+ )}
+ </>
)}
</div>
- {/* Bottom Status Bar */}
- <StatusBar
- cursorPos={cursorPos}
- currentPressure={currentPressure}
- tool={tool}
- brushSettings={brushSettings}
- zoom={zoom}
- rotation={rotation}
- onResetRotation={resetRotation}
- colorMode={colorMode}
- showCursorCoordinates={appSettings.showCursorCoordinates}
- showPressureInStatusBar={appSettings.showPressureInStatusBar}
- hasOpenDocument={hasOpenDocument}
- themePreset={appSettings.themePreset}
- softProofSettings={softProofSettings}
+ {/* Fault-Tolerant Crash Recovery Modal */}
+ <CrashRecoveryModal
+ isOpen={isRecoveryModalOpen}
+ sessions={crashedSessions}
+ onRestore={handleRestoreCrashedSession}
+ onDiscard={handleDiscardCrashedSession}
+ onClose={() => setIsRecoveryModalOpen(false)}
/>
{/* New Canvas Modal Dialog */}
@@ -6377,12 +7017,12 @@ export function App() {
{/* Loading Modal when parsing large PSD or CSP files */}
{isLoadingFile && (
- <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-xs select-none animate-in fade-in duration-100">
- <div className="bg-[#252528] border border-[#3e3e42] rounded-lg shadow-2xl px-6 py-4 flex items-center space-x-3 text-xs text-white">
- <Loader2 className="w-5 h-5 text-[#38bdf8] animate-spin" />
+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 select-none">
+ <div className="bg-[#202020] rounded-md shadow-[0_16px_48px_rgba(0,0,0,0.75)] px-5 py-3.5 flex items-center gap-3 text-xs text-[#e5e5e5]">
+ <Loader2 className="w-4 h-4 text-[var(--accent)] animate-spin" />
<div className="flex flex-col">
- <span className="font-semibold text-sm">{loadingStatus || 'Opening Document...'}</span>
- <span className="text-[#888888] text-[11px]">Extracting layers, blend modes, and pixel data</span>
+ <span className="font-medium text-xs">{loadingStatus || 'Opening Document...'}</span>
+ <span className="text-[#8a8a8a] text-[10px]">Extracting layers and pixel data</span>
</div>
</div>
</div>
@@ -6390,18 +7030,12 @@ export function App() {
{/* Toast Notification */}
{toastMessage && (
- <div className="fixed bottom-12 right-6 z-50 bg-[#252528] border border-[#007acc] text-white px-4 py-2.5 rounded-md shadow-2xl flex items-center space-x-2.5 text-xs animate-in slide-in-from-bottom-2 fade-in duration-150">
- <CheckCircle2 className="w-4 h-4 text-[#38bdf8]" />
+ <div className="fixed bottom-5 right-5 z-50 bg-[#202020] text-[#e5e5e5] px-3.5 py-2 rounded-md shadow-[0_12px_32px_rgba(0,0,0,0.65)] flex items-center gap-2 text-xs">
+ <CheckCircle2 className="w-3.5 h-3.5 text-[var(--accent)]" />
<span className="font-medium">{toastMessage}</span>
</div>
)}
- {/* First Time Setup Name Modal */}
- <FirstTimeNameModal
- isOpen={!appSettings.hasPromptedName && !appSettings.userName}
- onSaveName={handleSaveFirstTimeName}
- />
-
{/* Manga Effect Lines Generator Modal */}
<MangaEffectsModal
isOpen={isMangaEffectsModalOpen}
@@ -6415,7 +7049,16 @@ export function App() {
<WebtoonExportModal
isOpen={isWebtoonExportModalOpen}
onClose={() => setIsWebtoonExportModalOpen(false)}
- getActiveCanvas={getActiveCanvas}
+ getActiveCanvas={() =>
+ compositeCanvas(
+ dimensions,
+ layers,
+ layerCanvasesRef.current,
+ getEffectiveOpacity,
+ isLayerEffectivelyVisible,
+ false
+ )
+ }
canvasWidth={dimensions.width}
canvasHeight={dimensions.height}
documentTitle={documents.find((d) => d.id === activeDocumentId)?.name || 'webtoon_chapter'}
diff --git a/src/components/AnimationTimeline.tsx b/src/components/AnimationTimeline.tsx
index 71b39a6..ab25901 100644
--- a/src/components/AnimationTimeline.tsx
+++ b/src/components/AnimationTimeline.tsx
@@ -53,8 +53,13 @@ export const AnimationTimeline: React.FC<AnimationTimelineProps> = ({
const [isExporting, setIsExporting] = useState<boolean>(false);
const [exportProgress, setExportProgress] = useState<string>('');
+ const timelineRootRef = useRef<HTMLDivElement | null>(null);
const scrubberRef = useRef<HTMLDivElement | null>(null);
const playTimerRef = useRef<number | null>(null);
+ const timelineRef = useRef<TimelineData>(timeline);
+ timelineRef.current = timeline;
+ const onChangeTimelineRef = useRef(onChangeTimeline);
+ onChangeTimelineRef.current = onChangeTimeline;
// Playback timer loop
useEffect(() => {
@@ -66,19 +71,22 @@ export const AnimationTimeline: React.FC<AnimationTimelineProps> = ({
return;
}
- const intervalMs = Math.max(10, Math.round(1000 / timeline.fps));
+ const intervalMs = Math.max(10, Math.round(1000 / Math.max(1, timeline.fps)));
playTimerRef.current = window.setInterval(() => {
- onChangeTimeline({
- ...timeline,
- currentFrame:
- timeline.currentFrame + 1 >= timeline.totalFrames
- ? timeline.loop
- ? 0
- : timeline.totalFrames - 1
- : timeline.currentFrame + 1,
+ const curr = timelineRef.current;
+ const nextFrame =
+ curr.currentFrame + 1 >= curr.totalFrames
+ ? curr.loop
+ ? 0
+ : curr.totalFrames - 1
+ : curr.currentFrame + 1;
+
+ onChangeTimelineRef.current({
+ ...curr,
+ currentFrame: nextFrame,
});
- if (!timeline.loop && timeline.currentFrame + 1 >= timeline.totalFrames) {
+ if (!curr.loop && curr.currentFrame + 1 >= curr.totalFrames) {
setIsPlaying(false);
}
}, intervalMs);
@@ -89,7 +97,7 @@ export const AnimationTimeline: React.FC<AnimationTimelineProps> = ({
playTimerRef.current = null;
}
};
- }, [isPlaying, timeline, onChangeTimeline]);
+ }, [isPlaying, timeline.fps]);
// Synchronize active cel layer when frame changes
useEffect(() => {
@@ -130,15 +138,35 @@ export const AnimationTimeline: React.FC<AnimationTimelineProps> = ({
window.addEventListener('pointerup', onPointerUp);
};
- // Keyboard navigation shortcuts
+ // Keyboard navigation shortcuts (Alt+Space anywhere, or Space when timeline has focus, avoiding canvas Space-pan collision)
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
- if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) return;
+ const target = e.target as HTMLElement | null;
+ if (
+ target instanceof HTMLInputElement ||
+ target instanceof HTMLTextAreaElement ||
+ target instanceof HTMLSelectElement ||
+ target?.isContentEditable ||
+ document.querySelector('[role="dialog"]')
+ ) {
+ return;
+ }
if (e.code === 'Space') {
- e.preventDefault();
- setIsPlaying((p) => !p);
- } else if (e.code === 'ArrowLeft') {
+ if (e.repeat || e.ctrlKey || e.metaKey) return;
+ const isTimelineFocused = Boolean(
+ timelineRootRef.current && document.activeElement && timelineRootRef.current.contains(document.activeElement)
+ );
+ if (e.altKey || isTimelineFocused) {
+ e.preventDefault();
+ setIsPlaying((p) => !p);
+ }
+ return;
+ }
+
+ if (e.ctrlKey || e.metaKey || e.altKey || e.shiftKey) return;
+
+ if (e.code === 'ArrowLeft') {
e.preventDefault();
onChangeTimeline({
...timeline,
@@ -198,7 +226,11 @@ export const AnimationTimeline: React.FC<AnimationTimelineProps> = ({
const currentCelLayer = currentCelId ? layers.find((l) => l.id === currentCelId) : null;
return (
- <div className="absolute inset-x-0 bottom-0 z-40 bg-[#17191e]/95 backdrop-blur-md border-t border-[#2e323b] shadow-2xl flex flex-col select-none text-xs text-gray-300">
+ <div
+ ref={timelineRootRef}
+ tabIndex={-1}
+ className="absolute inset-x-0 bottom-0 z-40 bg-[#17191e]/95 backdrop-blur-md border-t border-[#2e323b] shadow-2xl flex flex-col select-none text-xs text-gray-300 outline-none"
+ >
{/* 1. Header & Transport Controls Dock */}
<div className="flex items-center justify-between px-3 py-1.5 border-b border-[#242730] bg-[#1a1d24]">
{/* Playback Transport */}
@@ -232,7 +264,7 @@ export const AnimationTimeline: React.FC<AnimationTimelineProps> = ({
? 'bg-amber-600 hover:bg-amber-500 text-white'
: 'bg-emerald-600 hover:bg-emerald-500 text-white'
}`}
- title="Play / Pause (Space)"
+ title="Play / Pause (Alt+Space)"
>
{isPlaying ? <Pause className="w-3.5 h-3.5" /> : <Play className="w-3.5 h-3.5" />}
<span className="text-[11px] font-semibold">{isPlaying ? 'Pause' : 'Play'}</span>
diff --git a/src/components/CanvasArea.tsx b/src/components/CanvasArea.tsx
index 4b1e08f..75a1655 100644
--- a/src/components/CanvasArea.tsx
+++ b/src/components/CanvasArea.tsx
@@ -29,6 +29,7 @@ import { Smartphone, Archive } from 'lucide-react';
import { AnimationTimeline } from './AnimationTimeline';
import { AnimationTimeline as AnimationTimelineType } from '../types/editor';
import { getOnionSkinFrames } from '../utils/animationEngine';
+import { FloatingBrushPill } from './FloatingBrushPill';
const PIPETTE_CURSOR_CSS = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cg stroke='%23000000' stroke-width='3.5' stroke-linecap='round' stroke-linejoin='round' fill='none'%3E%3Cpath d='m14 7 3 3'/%3E%3Cpath d='M16.6 5.6a2.12 2.12 0 0 1 3 3L7 20.6 2 22l1.4-5L16.6 5.6z'/%3E%3C/g%3E%3Cg stroke='%23ffffff' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round' fill='none'%3E%3Cpath d='m14 7 3 3'/%3E%3Cpath d='M16.6 5.6a2.12 2.12 0 0 1 3 3L7 20.6 2 22l1.4-5L16.6 5.6z'/%3E%3C/g%3E%3C/svg%3E") 2 22, crosshair`;
@@ -98,6 +99,11 @@ interface CanvasAreaProps {
onInsertRasterLayer?: (layer: LayerItem, canvas: HTMLCanvasElement) => void;
onBake3DSuccess?: (layer: LayerItem) => void;
liquifySettings?: LiquifySettings;
+ onUpdateLiquifySettings?: (newSettings: Partial<LiquifySettings>) => void;
+ primaryColor?: string;
+ onSwapColors?: () => void;
+ showCursorCoordinates?: boolean;
+ showPressureInStatusBar?: boolean;
isWebtoonMode?: boolean;
onToggleWebtoonMode?: () => void;
onOpenWebtoonExport?: () => void;
@@ -215,6 +221,11 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
onInsertRasterLayer,
onBake3DSuccess,
liquifySettings,
+ onUpdateLiquifySettings,
+ primaryColor = '#000000',
+ onSwapColors,
+ showCursorCoordinates = false,
+ showPressureInStatusBar = false,
animationTimeline = null,
onUpdateAnimationTimeline,
onAddAnimationCel,
@@ -310,6 +321,33 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
// Zero-latency direct DOM cursor preview element
const cursorRingRef = useRef<HTMLDivElement | null>(null);
+ const pointerStatRef = useRef<HTMLDivElement | null>(null);
+
+ useEffect(() => {
+ if (!showCursorCoordinates && !showPressureInStatusBar) return;
+ let rafId = 0;
+ const handlePointerStat = (e: Event) => {
+ const detail = (e as CustomEvent).detail;
+ cancelAnimationFrame(rafId);
+ rafId = requestAnimationFrame(() => {
+ const el = pointerStatRef.current;
+ if (!el || !detail) return;
+ const parts: string[] = [];
+ if (showCursorCoordinates && detail.x !== null && detail.x !== undefined) {
+ parts.push(`${detail.x}, ${detail.y}`);
+ }
+ if (showPressureInStatusBar && detail.pressure > 0) {
+ parts.push(`${Math.round(detail.pressure * 100)}%`);
+ }
+ el.textContent = parts.join(' · ');
+ });
+ };
+ window.addEventListener('canvas-pointer-stat', handlePointerStat);
+ return () => {
+ window.removeEventListener('canvas-pointer-stat', handlePointerStat);
+ cancelAnimationFrame(rafId);
+ };
+ }, [showCursorCoordinates, showPressureInStatusBar]);
// Update cursor rotation in-place when viewport rotates or brush tip angle changes while hovering
useEffect(() => {
@@ -330,6 +368,8 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
};
window.addEventListener('resize', updateRect);
+ const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(updateRect) : null;
+ ro?.observe(viewport);
const handleWindowPointerMove = (e: PointerEvent) => {
const ring = cursorRingRef.current;
@@ -378,6 +418,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
return () => {
window.removeEventListener('resize', updateRect);
+ ro?.disconnect();
viewport.removeEventListener('pointermove', handleWindowPointerMove);
viewport.removeEventListener('pointerleave', handlePointerLeave);
};
@@ -407,6 +448,26 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
// Unified GPU Viewport Compositor
const viewportCanvasRef = useRef<HTMLCanvasElement | null>(null);
const compositorRef = useRef<ViewportCompositor | null>(null);
+ const renderParamsRef = useRef({
+ effectiveLayers,
+ pan,
+ zoom,
+ rotation,
+ dimensions,
+ showCheckerboard,
+ onionSkinFrames,
+ softProofSettings,
+ });
+ renderParamsRef.current = {
+ effectiveLayers,
+ pan,
+ zoom,
+ rotation,
+ dimensions,
+ showCheckerboard,
+ onionSkinFrames,
+ softProofSettings,
+ };
// Synchronize viewport and draft overlay canvas resolution with the screen viewport
useEffect(() => {
@@ -426,12 +487,19 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
compositorRef.current = new ViewportCompositor(vCanvas);
}
compositorRef.current.resize(w, h);
+ const rp = renderParamsRef.current;
compositorRef.current.render(
- effectiveLayers,
- { pan, zoom, rotation },
- dimensions,
+ rp.effectiveLayers,
+ { pan: rp.pan, zoom: rp.zoom, rotation: rp.rotation },
+ rp.dimensions,
globalTileGrid,
- { dimensions, showCheckerboard, devicePixelRatio: dpr, onionSkinFrames, softProof: softProofSettings }
+ {
+ dimensions: rp.dimensions,
+ showCheckerboard: rp.showCheckerboard,
+ devicePixelRatio: dpr,
+ onionSkinFrames: rp.onionSkinFrames,
+ softProof: rp.softProofSettings,
+ }
);
}
@@ -450,8 +518,17 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
updateCanvasSizes();
window.addEventListener('resize', updateCanvasSizes);
- return () => window.removeEventListener('resize', updateCanvasSizes);
- }, [viewportRef, effectiveDraftCanvasRef, effectivePredictedCanvasRef, effectiveLayers, pan, zoom, rotation, dimensions, showCheckerboard, onionSkinFrames, softProofSettings]);
+ const ro = typeof ResizeObserver !== 'undefined' && viewportRef.current
+ ? new ResizeObserver(updateCanvasSizes)
+ : null;
+ if (ro && viewportRef.current) {
+ ro.observe(viewportRef.current);
+ }
+ return () => {
+ window.removeEventListener('resize', updateCanvasSizes);
+ ro?.disconnect();
+ };
+ }, [viewportRef, effectiveDraftCanvasRef, effectivePredictedCanvasRef]);
useEffect(() => {
if (viewportRef.current) {
@@ -483,8 +560,9 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
c.height = dimensions.height;
registerLayerCanvas(layer.id, c);
}
- if (c && !globalTileGrid.hasTile(layer.id, 0, 0) && globalTileGrid.getLayerTiles(layer.id).length === 0) {
- const isMono = layer.expressionColor === 'monochrome';
+ if (c && !globalTileGrid.isLayerIngested(layer.id)) {
+ const isBg = layer.id === 'layer-bg' || layer.id.startsWith('layer-bg');
+ const isMono = !isBg && (layer.expressionColor === 'monochrome' || colorMode === 'monochrome');
globalTileGrid.ingestCanvas(layer.id, c, isMono ? 'monochrome-1bit' : 'color-32bit');
}
}
@@ -507,12 +585,19 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
const renderCompositor = () => {
if (compositorRef.current) {
const dpr = window.devicePixelRatio || 1;
+ const rp = renderParamsRef.current;
compositorRef.current.render(
- effectiveLayers,
- { pan, zoom, rotation },
- dimensions,
+ rp.effectiveLayers,
+ { pan: rp.pan, zoom: rp.zoom, rotation: rp.rotation },
+ rp.dimensions,
globalTileGrid,
- { dimensions, showCheckerboard, devicePixelRatio: dpr, onionSkinFrames, softProof: softProofSettings }
+ {
+ dimensions: rp.dimensions,
+ showCheckerboard: rp.showCheckerboard,
+ devicePixelRatio: dpr,
+ onionSkinFrames: rp.onionSkinFrames,
+ softProof: rp.softProofSettings,
+ }
);
}
};
@@ -538,7 +623,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
unsubscribe();
if (rafId !== null) cancelAnimationFrame(rafId);
};
- }, [effectiveLayers, layers, pan, zoom, rotation, dimensions, showCheckerboard, onionSkinFrames, softProofSettings]);
+ }, []);
useEffect(() => {
return () => {
@@ -582,18 +667,30 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
useEffect(() => {
if (!isResizingBrush) return;
+ let rafId: number | null = null;
+ let pendingSize = resizeStartSettingsRef.current.size;
+ let pendingHardness = resizeStartSettingsRef.current.hardness;
+
+ const commitResize = () => {
+ rafId = null;
+ if (tool === 'liquify' && onUpdateLiquifySettings) {
+ onUpdateLiquifySettings({ size: Math.round(pendingSize) });
+ } else {
+ onUpdateBrushSettings({ size: pendingSize, hardness: pendingHardness });
+ }
+ };
+
const handleWindowPointerMove = (e: PointerEvent) => {
const dx = e.clientX - resizeOriginRef.current.clientX;
const dy = resizeOriginRef.current.clientY - e.clientY;
- // Horizontal drag: adjusts size (1 to 250px)
- const newSize = Math.max(
- 1,
- Math.min(250, Math.round(resizeStartSettingsRef.current.size + dx * 0.75))
- );
+ // Exponential + linear hybrid sensitivity for 0.5px..1000px precision (CSP-style)
+ const baseSize = Math.max(0.5, resizeStartSettingsRef.current.size);
+ const rawSize = baseSize * Math.exp(dx * 0.006) + dx * 0.15;
+ const clampedSize = Math.max(0.5, Math.min(1000, rawSize));
+ pendingSize = clampedSize < 10 ? Math.round(clampedSize * 10) / 10 : Math.round(clampedSize);
- // Vertical drag: adjusts hardness (0.0 to 1.0)
- const newHardness = Math.max(
+ pendingHardness = Math.max(
0.05,
Math.min(
1.0,
@@ -601,10 +698,16 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
)
);
- onUpdateBrushSettings({ size: newSize, hardness: newHardness });
+ if (rafId === null) {
+ rafId = requestAnimationFrame(commitResize);
+ }
};
const handleWindowPointerUp = () => {
+ if (rafId !== null) {
+ cancelAnimationFrame(rafId);
+ commitResize();
+ }
setIsResizingBrush(false);
};
@@ -618,16 +721,28 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
document.body.style.userSelect = 'none';
return () => {
+ if (rafId !== null) cancelAnimationFrame(rafId);
window.removeEventListener('pointermove', handleWindowPointerMove);
window.removeEventListener('pointerup', handleWindowPointerUp);
window.removeEventListener('pointercancel', handleWindowPointerUp);
document.body.style.cursor = prevCursor;
document.body.style.userSelect = prevUserSelect;
};
- }, [isResizingBrush, onUpdateBrushSettings]);
+ }, [isResizingBrush, onUpdateBrushSettings, onUpdateLiquifySettings, tool]);
+
+ const releaseExternalFocus = () => {
+ const active = document.activeElement as HTMLElement | null;
+ if (!active || active === document.body) return;
+ if (viewportRef.current?.contains(active)) return;
+ const tag = active.tagName;
+ if (tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA' || tag === 'BUTTON') {
+ active.blur();
+ }
+ };
// Viewport background pointer down (clicking gray area to pan or rotate)
const handleViewportPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
+ releaseExternalFocus();
if (e.button === 1) {
onStartPan(e);
return;
@@ -652,13 +767,14 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
setIsResizingBrush(true);
resizeOriginRef.current = { clientX: e.clientX, clientY: e.clientY };
resizeStartSettingsRef.current = {
- size: brushSettings.size,
+ size: tool === 'liquify' && liquifySettings ? liquifySettings.size : brushSettings.size,
hardness: brushSettings.hardness ?? 1.0,
};
};
// Canvas pointer down: check for resize, rotate, pan, or normal draw
const handleCanvasPointerDown = (e: React.PointerEvent<HTMLElement>) => {
+ releaseExternalFocus();
if (e.button === 1) {
onStartPan(e);
return;
@@ -736,7 +852,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
};
// Viewport bounds for positioning floating preview
- const viewportRect = viewportRef.current?.getBoundingClientRect();
+ const viewportRect = isResizingBrush ? viewportRef.current?.getBoundingClientRect() : null;
const resizePreviewX = viewportRect
? resizeOriginRef.current.clientX - viewportRect.left
: pan.x;
@@ -749,21 +865,41 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
return (
<main
ref={viewportRef}
- className="flex-1 bg-[#1e1e1e] overflow-hidden relative select-none"
+ className="flex-1 bg-[#161616] overflow-hidden relative select-none"
/>
);
}
+ const showFloatingPill =
+ tool === 'brush' ||
+ tool === 'eraser' ||
+ tool === 'liquify' ||
+ tool === 'select-pen' ||
+ tool === 'select-eraser';
+
return (
<main
ref={viewportRef}
onPointerDown={handleViewportPointerDown}
- className="flex-1 bg-[#282828] overflow-hidden relative select-none"
+ className="flex-1 bg-[#161616] overflow-hidden relative select-none canvas-viewport"
style={{
touchAction: 'none',
...getCursorStyle(false),
}}
>
+ {/* Sleek Floating Pill Slider near Canvas Edge for Brush Size & Opacity */}
+ {showFloatingPill && (
+ <FloatingBrushPill
+ tool={tool}
+ brushSettings={brushSettings}
+ onUpdateBrushSettings={onUpdateBrushSettings}
+ liquifySettings={liquifySettings}
+ onUpdateLiquifySettings={onUpdateLiquifySettings}
+ primaryColor={primaryColor}
+ onSwapColors={onSwapColors}
+ zoom={zoom}
+ />
+ )}
{/* Unified GPU Viewport Canvas (WebGL2 with Frustum Culling & Shaders) */}
<canvas
ref={viewportCanvasRef}
@@ -830,7 +966,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
style={{ backgroundColor: peer.color }}
>
<span>{peer.name}</span>
- {peer.isDrawing && <span className="text-[9px]">✏️</span>}
+ {peer.isDrawing && <span className="w-1.5 h-1.5 rounded-full bg-white animate-pulse" />}
</div>
</div>
);
@@ -855,7 +991,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
className="absolute top-5 left-1/2 -translate-x-1/2 px-1.5 py-0.5 rounded text-[10px] font-bold text-white whitespace-nowrap shadow-md"
style={{ backgroundColor: ping.color }}
>
- {ping.name} 📍
+ {ping.name}
</div>
</div>
))}
@@ -1154,50 +1290,50 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
{/* Floating HUD Tooltip Card */}
<div
- className="absolute top-full mt-3 bg-[#1e1e1e]/95 backdrop-blur border border-[#444444] text-[#cccccc] px-3.5 py-1.5 rounded-[3px] shadow-2xl flex flex-col items-center pointer-events-none whitespace-nowrap min-w-36"
+ className="absolute top-full mt-3 bg-[#202020] text-[#e5e5e5] px-3 py-1.5 rounded-md shadow-[0_8px_24px_rgba(0,0,0,0.65)] flex flex-col items-center pointer-events-none whitespace-nowrap min-w-36"
style={{ zIndex: 60 }}
>
- <div className="flex items-center space-x-2.5 text-xs font-mono font-semibold text-white">
- <span className="text-emerald-400">Size: {brushSettings.size}px</span>
- <span className="text-[#555555]">|</span>
- <span className="text-amber-300">
- Hardness: {Math.round((brushSettings.hardness ?? 1.0) * 100)}%
- </span>
- </div>
- <div className="text-[10px] text-[#888888] mt-0.5 font-sans">
- ↔ Drag horizontal: Size • ↕ Vertical: Hardness
+ <div className="flex items-center gap-2 text-[11px] font-mono font-medium text-[#e5e5e5]">
+ <span>Size {brushSettings.size}px</span>
+ <span className="text-[#8a8a8a]">·</span>
+ <span>Hard {Math.round((brushSettings.hardness ?? 1.0) * 100)}%</span>
</div>
</div>
</div>
)}
- {/* Floating Webtoon Mode Quick-Access Bar */}
- <div className="absolute top-3 right-4 z-40 flex items-center space-x-2 select-none">
- <button
- onClick={onToggleWebtoonMode}
- className={`px-3 py-1.5 rounded-full text-xs font-medium flex items-center space-x-1.5 shadow-lg border transition-colors cursor-pointer ${
- isWebtoonMode
- ? 'bg-[#1e382d] text-[#55eaab] border-[#2a7a5c]'
- : 'bg-[#222326]/90 text-[#aaaaaa] hover:text-white border-[#3b3d45]'
- }`}
- title="Toggle Webtoon Studio Mode (Smartphone Simulator & Vertical Scrolling)"
- >
- <Smartphone className="w-3.5 h-3.5" />
- <span>Webtoon Mode</span>
- {isWebtoonMode && <span className="w-1.5 h-1.5 rounded-full bg-[#55eaab] animate-pulse" />}
- </button>
-
- {isWebtoonMode && onOpenWebtoonExport && (
+ {/* Floating Webtoon Mode Controls (only shown when Webtoon Mode is active) */}
+ {isWebtoonMode && (
+ <div className="absolute top-3 right-3 z-40 flex items-center gap-1.5 select-none">
<button
- onClick={onOpenWebtoonExport}
- className="px-3 py-1.5 rounded-full text-xs font-medium bg-[#1a2d3e] hover:bg-[#234059] text-cyan-300 border border-[#2d5573] flex items-center space-x-1.5 shadow-lg transition-colors cursor-pointer"
- title="Export Chapter Slices (.zip)"
+ onClick={onToggleWebtoonMode}
+ className="px-2.5 py-1 rounded-full text-[11px] font-medium flex items-center gap-1.5 bg-[#202020] hover:bg-[#2c2c2c] text-[#e5e5e5] shadow-lg transition-colors cursor-pointer"
+ title="Exit Webtoon Studio Mode"
>
- <Archive className="w-3.5 h-3.5" />
- <span>Export Slices</span>
+ <Smartphone className="w-3.5 h-3.5 text-[var(--accent)]" />
+ <span>Exit Webtoon</span>
</button>
- )}
- </div>
+
+ {onOpenWebtoonExport && (
+ <button
+ onClick={onOpenWebtoonExport}
+ className="px-2.5 py-1 rounded-full text-[11px] font-medium bg-[#202020] hover:bg-[#2c2c2c] text-[#e5e5e5] flex items-center gap-1.5 shadow-lg transition-colors cursor-pointer"
+ title="Export Chapter Slices (.zip)"
+ >
+ <Archive className="w-3.5 h-3.5 text-[#8a8a8a]" />
+ <span>Export Slices</span>
+ </button>
+ )}
+ </div>
+ )}
+
+ {/* Subtle Zero-Height Canvas Coordinate / Pressure Readout */}
+ {(showCursorCoordinates || showPressureInStatusBar) && (
+ <div
+ ref={pointerStatRef}
+ className="pointer-events-none absolute bottom-2 right-3 z-30 text-[10px] font-mono text-[#8a8a8a]/70 select-none"
+ />
+ )}
{/* Smartphone Viewport Simulator in Webtoon Mode */}
{isWebtoonMode && (
diff --git a/src/components/ColorPanel.tsx b/src/components/ColorPanel.tsx
index 5a142fc..9ecd218 100644
--- a/src/components/ColorPanel.tsx
+++ b/src/components/ColorPanel.tsx
@@ -1,13 +1,9 @@
-import React, { useState, useEffect, useRef } from 'react';
-import {
- Menu,
- Disc,
- ArrowLeftRight,
- Columns,
-} from 'lucide-react';
+import React, { useState } from 'react';
+import { Disc, SlidersHorizontal, ArrowLeftRight } from 'lucide-react';
import { ColorWheel } from './ColorWheel';
import { ColorSlider } from './ColorSlider';
import { ToolType, CanvasColorMode } from '../types/editor';
+import { isValidHex, enforceColorMode } from '../utils/colorUtils';
export interface ColorPanelProps {
primaryColor: string;
@@ -23,18 +19,6 @@ export interface ColorPanelProps {
containerHeight?: number;
}
-// Clip Studio Paint style 3-slider horizontal icon
-export const ColorSliderIcon: React.FC<{ className?: string }> = ({ className = 'w-3.5 h-3.5' }) => (
- <svg className={className} viewBox="0 0 16 16" fill="currentColor">
- {/* 3 slider tracks */}
- <path d="M1 3.5h14v1H1zM1 7.5h14v1H1zM1 11.5h14v1H1z" fill="currentColor" opacity="0.5" />
- {/* 3 slider knobs matching CSP reference */}
- <rect x="2.5" y="2" width="3.5" height="4" rx="0.5" fill="currentColor" />
- <rect x="2.5" y="6" width="3.5" height="4" rx="0.5" fill="currentColor" />
- <rect x="2.5" y="10" width="3.5" height="4" rx="0.5" fill="currentColor" />
- </svg>
-);
-
export const ColorPanel: React.FC<ColorPanelProps> = ({
primaryColor,
secondaryColor,
@@ -45,291 +29,169 @@ export const ColorPanel: React.FC<ColorPanelProps> = ({
currentTool = 'brush',
onSelectTool,
recentColors = [],
- containerWidth = 320,
+ containerWidth = 180,
containerHeight,
}) => {
- // Active palette tab: 'wheel' | 'slider'
const [activeTab, setActiveTab] = useState<'wheel' | 'slider'>(() => {
try {
- const saved = localStorage.getItem('forsora_color_tab');
+ const saved = localStorage.getItem('ink_color_tab');
if (saved === 'wheel' || saved === 'slider') return saved;
} catch {
// ignore
}
- // Default to 'slider' so the newly requested Color Slider is immediately front and center!
- return 'slider';
+ return 'wheel';
});
- // Display mode: 'tabbed' (default matching Photo 2) or 'split' (shows both stacked)
- const [viewMode, setViewMode] = useState<'tabbed' | 'split'>('tabbed');
-
- // Shared activeTarget ('primary' | 'secondary') so switching tabs preserves target
const [activeTarget, setActiveTarget] = useState<'primary' | 'secondary'>('primary');
+ const activeColor = activeTarget === 'primary' ? primaryColor : secondaryColor;
- // Hamburger popup menu state
- const [menuOpen, setMenuOpen] = useState(false);
- const menuRef = useRef<HTMLDivElement | null>(null);
-
- // Close menu on click outside
- useEffect(() => {
- if (!menuOpen) return;
- const handleClickOutside = (e: MouseEvent) => {
- if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
- setMenuOpen(false);
- }
- };
- window.addEventListener('mousedown', handleClickOutside);
- return () => window.removeEventListener('mousedown', handleClickOutside);
- }, [menuOpen]);
-
- const selectTab = (tab: 'wheel' | 'slider') => {
- setActiveTab(tab);
+ const toggleTab = () => {
+ const next = activeTab === 'wheel' ? 'slider' : 'wheel';
+ setActiveTab(next);
try {
- localStorage.setItem('forsora_color_tab', tab);
+ localStorage.setItem('ink_color_tab', next);
} catch {
// ignore
}
};
- // Determine if tab labels should be compact icon-only when narrow
- const isNarrow = containerWidth < 275;
- const contentHeight = containerHeight ? Math.max(80, containerHeight - 30) : undefined;
+ const handleHexChange = (raw: string) => {
+ const clean = raw.trim();
+ if (!isValidHex(clean)) return;
+ let hex = clean.startsWith('#') ? clean : `#${clean}`;
+ if (colorMode && colorMode !== 'color') {
+ hex = enforceColorMode(hex, colorMode);
+ }
+ if (activeTarget === 'primary') {
+ onPrimaryColorChange(hex, true);
+ } else {
+ onSecondaryColorChange(hex, true);
+ }
+ };
return (
- <div className="flex flex-col select-none text-[#cccccc] text-xs h-full">
- {/* Clip Studio Paint Palette Tab Header Bar */}
- <div className="bg-[#242426] px-2 py-0 border-b border-[#333333] flex items-center justify-between h-[30px] shrink-0 relative">
- {/* Left: Menu & Palette Tabs */}
- <div className="flex items-center space-x-1.5 h-full">
- {/* Hamburger Menu Button */}
- <div className="relative" ref={menuRef}>
- <button
- onClick={() => setMenuOpen((o) => !o)}
- title="Color Palette Options"
- className="p-1 text-[#888888] hover:text-white rounded-[2px] transition-colors cursor-pointer"
- >
- <Menu className="w-3.5 h-3.5" />
- </button>
-
- {/* Popup Context Menu */}
- {menuOpen && (
- <div className="absolute left-0 top-7 z-50 w-48 bg-[#202022] border border-[#3e3e42] rounded-[3px] shadow-2xl py-1 text-xs text-[#cccccc]">
- <button
- onClick={() => {
- setViewMode('tabbed');
- selectTab('wheel');
- setMenuOpen(false);
- }}
- className="w-full text-left px-3 py-1.5 hover:bg-[#333338] flex items-center space-x-2 cursor-pointer"
- >
- <Disc className="w-3.5 h-3.5 text-[#5ce1e6]" />
- <span>Color Wheel</span>
- {viewMode === 'tabbed' && activeTab === 'wheel' && (
- <span className="ml-auto text-[#5ce1e6] text-[10px]">✓</span>
- )}
- </button>
- <button
- onClick={() => {
- setViewMode('tabbed');
- selectTab('slider');
- setMenuOpen(false);
- }}
- className="w-full text-left px-3 py-1.5 hover:bg-[#333338] flex items-center space-x-2 cursor-pointer"
- >
- <ColorSliderIcon className="w-3.5 h-3.5 text-[#5ce1e6]" />
- <span>Color Slider</span>
- {viewMode === 'tabbed' && activeTab === 'slider' && (
- <span className="ml-auto text-[#5ce1e6] text-[10px]">✓</span>
- )}
- </button>
-
- <div className="border-t border-[#343438] my-1" />
-
- <button
- onClick={() => {
- setViewMode((v) => (v === 'split' ? 'tabbed' : 'split'));
- setMenuOpen(false);
- }}
- className="w-full text-left px-3 py-1.5 hover:bg-[#333338] flex items-center space-x-2 cursor-pointer"
- >
- <Columns className="w-3.5 h-3.5 text-[#888888]" />
- <span>
- {viewMode === 'split' ? 'Switch to Tabbed View' : 'Show Both (Split View)'}
- </span>
- </button>
-
- <div className="border-t border-[#343438] my-1" />
-
- <button
- onClick={() => {
- onSwapColors();
- setMenuOpen(false);
- }}
- className="w-full text-left px-3 py-1.5 hover:bg-[#333338] flex items-center justify-between cursor-pointer"
- >
- <span>Swap Colors</span>
- <span className="font-mono text-[10px] text-[#777777]">X</span>
- </button>
- </div>
- )}
- </div>
-
- {/* Palette Tabs: Tab 1 (Color Wheel) & Tab 2 (Color Slider) */}
- <div className="flex items-center h-full space-x-0.5">
- {/* Tab 1: Color Wheel */}
+ <div className="flex flex-col h-full w-full select-none bg-[#202020] text-[#e5e5e5] overflow-hidden">
+ {/* Compact Header Strip: Swatches + Hex + Recent Dots + Mode Toggle */}
+ <div className="h-6 px-2 pt-1 flex items-center justify-between gap-1 shrink-0">
+ <div className="flex items-center gap-1.5 min-w-0">
+ {/* Primary / Secondary Swatch Pair */}
+ <div className="flex items-center gap-1 shrink-0">
<button
- onClick={() => {
- if (viewMode === 'split') setViewMode('tabbed');
- selectTab('wheel');
- }}
- title="Color Wheel"
- className={`h-full px-2 flex items-center space-x-1.5 border-t-2 transition-all cursor-pointer rounded-t-[2px] ${
- viewMode === 'tabbed' && activeTab === 'wheel'
- ? 'bg-[#252526] border-t-[#5ce1e6] border-x border-[#333333] text-white font-medium shadow-sm -mb-[1px] z-10'
- : 'bg-transparent border-t-transparent text-[#888888] hover:text-[#cccccc] hover:bg-[#2b2b2e]'
+ type="button"
+ onClick={() => setActiveTarget('primary')}
+ title={`Primary: ${primaryColor}`}
+ className={`w-3.5 h-3.5 rounded-xs cursor-pointer transition-transform ${
+ activeTarget === 'primary'
+ ? 'scale-110 shadow-[0_0_0_1.5px_var(--accent)]'
+ : 'opacity-70 hover:opacity-100 shadow-[0_0_0_1px_rgba(255,255,255,0.2)]'
}`}
- >
- <Disc
- className={`w-3.5 h-3.5 ${
- viewMode === 'tabbed' && activeTab === 'wheel'
- ? 'text-[#5ce1e6]'
- : 'text-[#888888]'
- }`}
- />
- {/* Show text if not narrow or if this is the active tab */}
- {(!isNarrow || (viewMode === 'tabbed' && activeTab === 'wheel')) && (
- <span className="tracking-wide">Color Wheel</span>
- )}
- </button>
-
- {/* Tab 2: Color Slider (Matching Reference Photo 2) */}
+ style={{ backgroundColor: primaryColor }}
+ />
<button
- onClick={() => {
- if (viewMode === 'split') setViewMode('tabbed');
- selectTab('slider');
- }}
- title="Color Slider"
- className={`h-full px-2 flex items-center space-x-1.5 border-t-2 transition-all cursor-pointer rounded-t-[2px] ${
- viewMode === 'tabbed' && activeTab === 'slider'
- ? 'bg-[#252526] border-t-[#5ce1e6] border-x border-[#333333] text-white font-medium shadow-sm -mb-[1px] z-10'
- : 'bg-transparent border-t-transparent text-[#888888] hover:text-[#cccccc] hover:bg-[#2b2b2e]'
+ type="button"
+ onClick={() => setActiveTarget('secondary')}
+ title={`Secondary: ${secondaryColor}`}
+ className={`w-3.5 h-3.5 rounded-xs cursor-pointer transition-transform ${
+ activeTarget === 'secondary'
+ ? 'scale-110 shadow-[0_0_0_1.5px_var(--accent)]'
+ : 'opacity-70 hover:opacity-100 shadow-[0_0_0_1px_rgba(255,255,255,0.2)]'
}`}
- >
- <ColorSliderIcon
- className={`w-3.5 h-3.5 ${
- viewMode === 'tabbed' && activeTab === 'slider'
- ? 'text-[#5ce1e6]'
- : 'text-[#888888]'
- }`}
- />
- {/* Show text if not narrow or if this is the active tab */}
- {(!isNarrow || (viewMode === 'tabbed' && activeTab === 'slider')) && (
- <span className="tracking-wide">Color Slider</span>
- )}
- </button>
+ style={{ backgroundColor: secondaryColor }}
+ />
</div>
+
+ {/* Compact Hex Readout / Input */}
+ <input
+ type="text"
+ value={activeColor.toUpperCase()}
+ onChange={(e) => handleHexChange(e.target.value)}
+ maxLength={7}
+ className="w-[58px] bg-[#161616] text-[#e5e5e5] font-mono text-[10px] px-1.5 py-0.5 rounded"
+ title="Hex Color"
+ />
</div>
- {/* Right: Swap Colors Shortcut Button (X) */}
- <div className="flex items-center space-x-1">
+ {/* Recent Micro Swatches (when wide) + Swap + Wheel/Slider Toggle */}
+ <div className="flex items-center gap-0.5 shrink-0">
+ {containerWidth >= 220 && (
+ <div className="flex items-center gap-0.5 mr-0.5">
+ {recentColors.slice(0, 3).map((c, idx) => (
+ <button
+ key={`${c}-${idx}`}
+ type="button"
+ onClick={() =>
+ activeTarget === 'primary'
+ ? onPrimaryColorChange(c, false)
+ : onSecondaryColorChange(c, false)
+ }
+ title={c}
+ className="w-2.5 h-2.5 rounded-full cursor-pointer hover:scale-120 transition-transform"
+ style={{ backgroundColor: c }}
+ />
+ ))}
+ </div>
+ )}
+
<button
+ type="button"
onClick={onSwapColors}
- title="Swap Primary & Secondary Colors (X)"
- className="flex items-center space-x-1 px-1.5 py-0.5 bg-[#1e1e1e] hover:bg-[#333333] text-[#888888] hover:text-[#cccccc] rounded-[2px] border border-[#3a3a3a] transition-colors cursor-pointer"
+ title="Swap Colors (X)"
+ className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer"
>
- <ArrowLeftRight className="w-3 h-3" />
- <span className="text-[10px] font-mono">X</span>
+ <ArrowLeftRight className="w-2.5 h-2.5" />
+ </button>
+
+ <button
+ type="button"
+ onClick={toggleTab}
+ title={activeTab === 'wheel' ? 'Switch to Sliders' : 'Switch to Color Wheel'}
+ className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ {activeTab === 'wheel' ? (
+ <SlidersHorizontal className="w-3 h-3" />
+ ) : (
+ <Disc className="w-3 h-3" />
+ )}
</button>
</div>
</div>
- {/* Palette Content Area */}
- <div className="flex-1 min-h-0 overflow-y-auto">
- {viewMode === 'tabbed' ? (
- activeTab === 'wheel' ? (
- <ColorWheel
- primaryColor={primaryColor}
- secondaryColor={secondaryColor}
- onPrimaryColorChange={onPrimaryColorChange}
- onSecondaryColorChange={onSecondaryColorChange}
- onSwapColors={onSwapColors}
- colorMode={colorMode}
- currentTool={currentTool}
- onSelectTool={onSelectTool}
- recentColors={recentColors}
- containerWidth={containerWidth}
- containerHeight={contentHeight}
- activeTarget={activeTarget}
- onActiveTargetChange={setActiveTarget}
- hideHeader={true}
- />
- ) : (
- <ColorSlider
- primaryColor={primaryColor}
- secondaryColor={secondaryColor}
- onPrimaryColorChange={onPrimaryColorChange}
- onSecondaryColorChange={onSecondaryColorChange}
- onSwapColors={onSwapColors}
- colorMode={colorMode}
- currentTool={currentTool}
- onSelectTool={onSelectTool}
- recentColors={recentColors}
- containerWidth={containerWidth}
- containerHeight={contentHeight}
- activeTarget={activeTarget}
- onActiveTargetChange={setActiveTarget}
- hideHeader={true}
- />
- )
+ {/* Wheel or Compact Sliders */}
+ <div className="flex-1 min-h-0 overflow-y-auto flex flex-col">
+ {activeTab === 'wheel' ? (
+ <ColorWheel
+ primaryColor={primaryColor}
+ secondaryColor={secondaryColor}
+ onPrimaryColorChange={onPrimaryColorChange}
+ onSecondaryColorChange={onSecondaryColorChange}
+ onSwapColors={onSwapColors}
+ colorMode={colorMode}
+ currentTool={currentTool}
+ onSelectTool={onSelectTool}
+ recentColors={recentColors}
+ containerWidth={containerWidth}
+ containerHeight={containerHeight ? Math.max(72, containerHeight - 24) : undefined}
+ activeTarget={activeTarget}
+ onActiveTargetChange={setActiveTarget}
+ hideHeader={true}
+ />
) : (
- /* Split View Mode: Both Color Wheel & Color Slider Stacked */
- <div className="divide-y divide-[#333333]">
- <div className="pb-1">
- <div className="px-3 py-1 bg-[#1e1e20] text-[10px] font-semibold text-[#888888] uppercase tracking-wider flex items-center space-x-1">
- <Disc className="w-3 h-3 text-[#5ce1e6]" />
- <span>Color Wheel</span>
- </div>
- <ColorWheel
- primaryColor={primaryColor}
- secondaryColor={secondaryColor}
- onPrimaryColorChange={onPrimaryColorChange}
- onSecondaryColorChange={onSecondaryColorChange}
- onSwapColors={onSwapColors}
- colorMode={colorMode}
- currentTool={currentTool}
- onSelectTool={onSelectTool}
- recentColors={[]}
- containerWidth={containerWidth}
- containerHeight={contentHeight ? Math.max(80, Math.floor(contentHeight / 2) - 20) : undefined}
- activeTarget={activeTarget}
- onActiveTargetChange={setActiveTarget}
- hideHeader={true}
- />
- </div>
-
- <div className="pt-1">
- <div className="px-3 py-1 bg-[#1e1e20] text-[10px] font-semibold text-[#888888] uppercase tracking-wider flex items-center space-x-1">
- <ColorSliderIcon className="w-3 h-3 text-[#5ce1e6]" />
- <span>Color Slider</span>
- </div>
- <ColorSlider
- primaryColor={primaryColor}
- secondaryColor={secondaryColor}
- onPrimaryColorChange={onPrimaryColorChange}
- onSecondaryColorChange={onSecondaryColorChange}
- onSwapColors={onSwapColors}
- colorMode={colorMode}
- currentTool={currentTool}
- onSelectTool={onSelectTool}
- recentColors={recentColors}
- containerWidth={containerWidth}
- containerHeight={contentHeight ? Math.max(80, Math.floor(contentHeight / 2) - 20) : undefined}
- activeTarget={activeTarget}
- onActiveTargetChange={setActiveTarget}
- hideHeader={true}
- />
- </div>
- </div>
+ <ColorSlider
+ primaryColor={primaryColor}
+ secondaryColor={secondaryColor}
+ onPrimaryColorChange={onPrimaryColorChange}
+ onSecondaryColorChange={onSecondaryColorChange}
+ onSwapColors={onSwapColors}
+ colorMode={colorMode}
+ currentTool={currentTool}
+ onSelectTool={onSelectTool}
+ recentColors={[]}
+ containerWidth={containerWidth}
+ containerHeight={containerHeight ? Math.max(72, containerHeight - 24) : undefined}
+ activeTarget={activeTarget}
+ onActiveTargetChange={setActiveTarget}
+ hideHeader={true}
+ />
)}
</div>
</div>
diff --git a/src/components/ColorWheel.tsx b/src/components/ColorWheel.tsx
index ed30bbf..f334d52 100644
--- a/src/components/ColorWheel.tsx
+++ b/src/components/ColorWheel.tsx
@@ -1,22 +1,10 @@
import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react';
-import {
- ArrowLeftRight,
- Disc,
- Menu,
- Square,
- Play,
- Copy,
- Check,
- ChevronDown,
- ChevronRight,
-} from 'lucide-react';
+import { Play, Square } from 'lucide-react';
import { ToolType, CanvasColorMode } from '../types/editor';
import {
hsvToRgb,
- rgbToHsv,
hexToHsv,
hsvToHex,
- isValidHex,
enforceColorMode,
HSV,
} from '../utils/colorUtils';
@@ -38,7 +26,6 @@ export interface ColorWheelProps {
hideHeader?: boolean;
}
-// In Clip Studio Paint, Red (H=0) is positioned at 10:30 o'clock (-135 degrees)
const HUE_OFFSET = -135;
export const ColorWheel: React.FC<ColorWheelProps> = ({
@@ -46,72 +33,39 @@ export const ColorWheel: React.FC<ColorWheelProps> = ({
secondaryColor,
onPrimaryColorChange,
onSecondaryColorChange,
- onSwapColors,
colorMode = 'color',
- currentTool = 'brush',
- onSelectTool,
- recentColors = [],
- containerWidth = 320,
+ containerWidth = 180,
containerHeight,
activeTarget: controlledActiveTarget,
- onActiveTargetChange,
- hideHeader = false,
}) => {
- // Target swatch being edited: 'primary' or 'secondary'
- const [internalActiveTarget, setInternalActiveTarget] = useState<'primary' | 'secondary'>('primary');
- const activeTarget = controlledActiveTarget ?? internalActiveTarget;
-
- const setActiveTarget = (target: 'primary' | 'secondary') => {
- if (onActiveTargetChange) {
- onActiveTargetChange(target);
- } else {
- setInternalActiveTarget(target);
- }
- };
-
- // Wheel inner display mode: 'square' or 'triangle'
+ const activeTarget = controlledActiveTarget ?? 'primary';
const [wheelMode, setWheelMode] = useState<'square' | 'triangle'>('square');
-
- // Toggle for expanded RGB / Hex controls
- const [showAdvanced, setShowAdvanced] = useState(false);
- const [copiedHex, setCopiedHex] = useState(false);
-
- // Active color string
const activeColor = activeTarget === 'primary' ? primaryColor : secondaryColor;
- // Internal HSV representation to preserve Hue when Saturation or Value is 0
- const [hsv, setHsv] = useState<HSV>(() => {
- const initial = hexToHsv(activeColor);
- return initial;
- });
-
- // Track dragging state: 'hue' | 'sv' | null
+ const [hsv, setHsv] = useState<HSV>(() => hexToHsv(activeColor));
const [isDragging, setIsDragging] = useState<'hue' | 'sv' | null>(null);
const isDraggingRef = useRef<'hue' | 'sv' | null>(null);
isDraggingRef.current = isDragging;
- // Canvas refs
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const containerRef = useRef<HTMLDivElement | null>(null);
- // Synchronize internal HSV when external activeColor changes (e.g. eye-dropper, palette swap)
useEffect(() => {
- if (isDraggingRef.current) return; // Don't overwrite while user is actively dragging
+ if (isDraggingRef.current) return;
const currentHex = hsvToHex(hsv.h, hsv.s, hsv.v);
if (currentHex.toLowerCase() !== activeColor.toLowerCase()) {
const parsed = hexToHsv(activeColor);
- // Preserve hue if activeColor has 0 saturation or 0 value (pure white, black, gray)
if (parsed.s > 0.02 && parsed.v > 0.02) {
setHsv(parsed);
} else {
setHsv((prev) => ({ h: prev.h, s: parsed.s, v: parsed.v }));
}
}
- }, [activeColor]);
+ }, [activeColor, hsv.h, hsv.s, hsv.v]);
const [measuredSize, setMeasuredSize] = useState<{ width: number; height: number }>({
width: containerWidth,
- height: containerHeight || 0,
+ height: containerHeight || 150,
});
useEffect(() => {
@@ -120,43 +74,30 @@ export const ColorWheel: React.FC<ColorWheelProps> = ({
const ro = new ResizeObserver((entries) => {
for (const entry of entries) {
const { width: w, height: h } = entry.contentRect;
- setMeasuredSize({
- width: w > 0 ? Math.round(w) : containerWidth,
- height: h > 0 ? Math.round(h) : (containerHeight || 0),
- });
+ if (w > 0 && h > 0) {
+ setMeasuredSize({ width: Math.round(w), height: Math.round(h) });
+ }
}
});
ro.observe(el);
return () => ro.disconnect();
- }, [containerWidth, containerHeight]);
-
- // Dynamically compute canvas diameter to fit sidebar neatly and adapt to size
- const effectiveWidth = measuredSize.width || containerWidth || 280;
- const effectiveHeight = containerHeight || measuredSize.height || 0;
+ }, []);
const wheelSize = useMemo(() => {
- const pad = 24;
- const availableWidth = Math.max(90, effectiveWidth - pad);
- if (effectiveHeight > 0) {
- const headerSpace = hideHeader ? 0 : 32;
- const bottomControlsSpace = 80 + (recentColors.length > 0 ? 32 : 0) + (showAdvanced ? 82 : 0);
- const availableHeight = Math.max(90, effectiveHeight - headerSpace - bottomControlsSpace - 14);
- return Math.round(Math.min(availableWidth, availableHeight));
- }
- return Math.round(availableWidth);
- }, [effectiveWidth, effectiveHeight, hideHeader, recentColors.length, showAdvanced]);
+ const availW = Math.max(72, measuredSize.width - 12);
+ const availH = Math.max(72, measuredSize.height - 8);
+ return Math.min(200, Math.round(Math.min(availW, availH)));
+ }, [measuredSize.width, measuredSize.height]);
- // Dimensions & radiuses
const cx = wheelSize / 2;
const cy = wheelSize / 2;
- const outerRadius = Math.max(20, wheelSize / 2 - 8);
- const ringThickness = Math.max(14, Math.round(wheelSize * 0.088));
+ const outerRadius = Math.max(20, wheelSize / 2 - 4);
+ const ringThickness = Math.max(11, Math.round(wheelSize * 0.1));
const innerRadius = outerRadius - ringThickness;
- const squareSize = Math.max(10, Math.floor((innerRadius - 8) * Math.SQRT2));
+ const squareSize = Math.max(10, Math.floor((innerRadius - 5) * Math.SQRT2));
const sqX = cx - squareSize / 2;
const sqY = cy - squareSize / 2;
- // Emit color updates to parent
const handleColorChange = useCallback(
(newHsv: HSV, commitToRecent = false) => {
setHsv(newHsv);
@@ -173,7 +114,6 @@ export const ColorWheel: React.FC<ColorWheelProps> = ({
[activeTarget, colorMode, onPrimaryColorChange, onSecondaryColorChange]
);
- // Draw the entire color wheel (Outer Hue Ring + Inner SV Box)
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
@@ -187,7 +127,7 @@ export const ColorWheel: React.FC<ColorWheelProps> = ({
ctx.scale(dpr, dpr);
ctx.clearRect(0, 0, wheelSize, wheelSize);
- // 1. Draw Outer Hue Ring using Conic Gradient
+ // 1. Hue Ring
ctx.save();
const angleRad = (HUE_OFFSET * Math.PI) / 180;
const conic = ctx.createConicGradient(angleRad, cx, cy);
@@ -205,106 +145,61 @@ export const ColorWheel: React.FC<ColorWheelProps> = ({
ctx.closePath();
ctx.fillStyle = conic;
ctx.fill();
-
- // Ring borders
- ctx.strokeStyle = '#1b1b1b';
- ctx.lineWidth = 1;
- ctx.stroke();
-
- ctx.beginPath();
- ctx.arc(cx, cy, outerRadius, 0, Math.PI * 2);
- ctx.strokeStyle = '#38383a';
- ctx.lineWidth = 0.75;
- ctx.stroke();
-
- ctx.beginPath();
- ctx.arc(cx, cy, innerRadius, 0, Math.PI * 2);
- ctx.strokeStyle = '#38383a';
- ctx.lineWidth = 0.75;
- ctx.stroke();
ctx.restore();
- // 2. Draw Outer Hue Ring Indicator Handle (Clip Studio Paint style rectangular frame)
+ // 2. Hue Indicator
ctx.save();
const hueAngle = ((hsv.h + HUE_OFFSET) * Math.PI) / 180;
ctx.translate(cx, cy);
ctx.rotate(hueAngle);
-
const midRadius = (outerRadius + innerRadius) / 2;
- const indicatorSpan = ringThickness + 6;
- const indicatorWidth = Math.max(6, Math.min(14, Math.round(wheelSize * 0.045)));
- const indX = midRadius - indicatorSpan / 2;
- const indY = -indicatorWidth / 2;
-
- // Outer white border
+ const handleRadius = ringThickness / 2 + 1;
ctx.beginPath();
- ctx.rect(indX, indY, indicatorSpan, indicatorWidth);
- ctx.strokeStyle = '#ffffff';
- ctx.lineWidth = 2;
+ ctx.arc(midRadius, 0, handleRadius, 0, Math.PI * 2);
+ ctx.strokeStyle = 'rgba(0, 0, 0, 0.7)';
+ ctx.lineWidth = 2.5;
ctx.stroke();
-
- // Inner dark contrast border
- ctx.beginPath();
- ctx.rect(indX + 1, indY + 1, indicatorSpan - 2, indicatorWidth - 2);
- ctx.strokeStyle = '#000000';
- ctx.lineWidth = 1;
+ ctx.strokeStyle = '#ffffff';
+ ctx.lineWidth = 1.5;
ctx.stroke();
-
ctx.restore();
- // 3. Draw Inner Area: Square or Triangle
+ // 3. Inner SV Area
if (wheelMode === 'square') {
- // 3A: SV Square Mode
ctx.save();
- // Base pure hue background
const pureRgb = hsvToRgb(hsv.h, 1, 1);
ctx.fillStyle = `rgb(${pureRgb.r}, ${pureRgb.g}, ${pureRgb.b})`;
ctx.fillRect(sqX, sqY, squareSize, squareSize);
- // Horizontal gradient: Pure White on left -> Transparent on right
const gradWhite = ctx.createLinearGradient(sqX, sqY, sqX + squareSize, sqY);
gradWhite.addColorStop(0, 'rgba(255, 255, 255, 1)');
gradWhite.addColorStop(1, 'rgba(255, 255, 255, 0)');
ctx.fillStyle = gradWhite;
ctx.fillRect(sqX, sqY, squareSize, squareSize);
- // Vertical gradient: Transparent on top -> Pure Black on bottom
const gradBlack = ctx.createLinearGradient(sqX, sqY, sqX, sqY + squareSize);
gradBlack.addColorStop(0, 'rgba(0, 0, 0, 0)');
gradBlack.addColorStop(1, 'rgba(0, 0, 0, 1)');
ctx.fillStyle = gradBlack;
ctx.fillRect(sqX, sqY, squareSize, squareSize);
- // Square dark border
- ctx.strokeStyle = '#1a1a1a';
- ctx.lineWidth = 1;
- ctx.strokeRect(sqX, sqY, squareSize, squareSize);
-
- // 4A: SV Square Cursor
const curX = sqX + hsv.s * squareSize;
const curY = sqY + (1 - hsv.v) * squareSize;
+ const cursorRadius = 4;
- const cursorRadius = Math.max(3.5, Math.min(6, wheelSize * 0.025));
- // Double ring for 100% visibility over any color
ctx.beginPath();
ctx.arc(curX, curY, cursorRadius, 0, Math.PI * 2);
- ctx.strokeStyle = '#000000';
+ ctx.strokeStyle = 'rgba(0, 0, 0, 0.75)';
ctx.lineWidth = 2.5;
ctx.stroke();
-
- ctx.beginPath();
- ctx.arc(curX, curY, cursorRadius, 0, Math.PI * 2);
ctx.strokeStyle = '#ffffff';
ctx.lineWidth = 1.5;
ctx.stroke();
-
ctx.restore();
} else {
- // 3B: SV Triangle Mode (Tip pointing towards current Hue angle)
ctx.save();
const tipAngle = ((hsv.h + HUE_OFFSET) * Math.PI) / 180;
- const rTri = innerRadius - 8;
-
+ const rTri = innerRadius - 5;
const pTip = { x: cx + rTri * Math.cos(tipAngle), y: cy + rTri * Math.sin(tipAngle) };
const pWhite = {
x: cx + rTri * Math.cos(tipAngle + (2 * Math.PI) / 3),
@@ -315,7 +210,6 @@ export const ColorWheel: React.FC<ColorWheelProps> = ({
y: cy + rTri * Math.sin(tipAngle - (2 * Math.PI) / 3),
};
- // Clip inside triangle
ctx.beginPath();
ctx.moveTo(pTip.x, pTip.y);
ctx.lineTo(pWhite.x, pWhite.y);
@@ -324,12 +218,10 @@ export const ColorWheel: React.FC<ColorWheelProps> = ({
ctx.save();
ctx.clip();
- // Pure hue fill
const pureRgb = hsvToRgb(hsv.h, 1, 1);
ctx.fillStyle = `rgb(${pureRgb.r}, ${pureRgb.g}, ${pureRgb.b})`;
ctx.fill();
- // Gradient from White vertex to opposite edge
const gradWhite = ctx.createLinearGradient(
pWhite.x,
pWhite.y,
@@ -341,7 +233,6 @@ export const ColorWheel: React.FC<ColorWheelProps> = ({
ctx.fillStyle = gradWhite;
ctx.fill();
- // Gradient from Black vertex to opposite edge
const gradBlack = ctx.createLinearGradient(
pBlack.x,
pBlack.y,
@@ -352,44 +243,61 @@ export const ColorWheel: React.FC<ColorWheelProps> = ({
gradBlack.addColorStop(1, 'rgba(0, 0, 0, 0)');
ctx.fillStyle = gradBlack;
ctx.fill();
+ ctx.restore();
- ctx.restore(); // unclip
-
- // Triangle border
- ctx.beginPath();
- ctx.moveTo(pTip.x, pTip.y);
- ctx.lineTo(pWhite.x, pWhite.y);
- ctx.lineTo(pBlack.x, pBlack.y);
- ctx.closePath();
- ctx.strokeStyle = '#222222';
- ctx.lineWidth = 1;
- ctx.stroke();
-
- // 4B: Triangle Cursor using Barycentric coordinates
- const wA = hsv.s * hsv.v; // Pure Hue weight
- const wB = (1 - hsv.s) * hsv.v; // White weight
- const wC = 1 - hsv.v; // Black weight
+ const wA = hsv.s * hsv.v;
+ const wB = (1 - hsv.s) * hsv.v;
+ const wC = 1 - hsv.v;
const curX = wA * pTip.x + wB * pWhite.x + wC * pBlack.x;
const curY = wA * pTip.y + wB * pWhite.y + wC * pBlack.y;
- const cursorRadius = Math.max(3.5, Math.min(6, wheelSize * 0.025));
ctx.beginPath();
- ctx.arc(curX, curY, cursorRadius, 0, Math.PI * 2);
- ctx.strokeStyle = '#000000';
+ ctx.arc(curX, curY, 4, 0, Math.PI * 2);
+ ctx.strokeStyle = 'rgba(0, 0, 0, 0.75)';
ctx.lineWidth = 2.5;
ctx.stroke();
-
- ctx.beginPath();
- ctx.arc(curX, curY, cursorRadius, 0, Math.PI * 2);
ctx.strokeStyle = '#ffffff';
ctx.lineWidth = 1.5;
ctx.stroke();
-
ctx.restore();
}
}, [cx, cy, outerRadius, innerRadius, ringThickness, sqX, sqY, squareSize, wheelSize, hsv, wheelMode]);
- // Pointer Interaction Handlers
+ const sampleTriangleSV = (px: number, py: number) => {
+ const rTri = innerRadius - 5;
+ const tipAngle = ((hsv.h + HUE_OFFSET) * Math.PI) / 180;
+ const pTip = { x: cx + rTri * Math.cos(tipAngle), y: cy + rTri * Math.sin(tipAngle) };
+ const pWhite = {
+ x: cx + rTri * Math.cos(tipAngle + (2 * Math.PI) / 3),
+ y: cy + rTri * Math.sin(tipAngle + (2 * Math.PI) / 3),
+ };
+ const pBlack = {
+ x: cx + rTri * Math.cos(tipAngle - (2 * Math.PI) / 3),
+ y: cy + rTri * Math.sin(tipAngle - (2 * Math.PI) / 3),
+ };
+
+ const det =
+ (pWhite.y - pBlack.y) * (pTip.x - pBlack.x) +
+ (pBlack.x - pWhite.x) * (pTip.y - pBlack.y);
+ let wA = ((pWhite.y - pBlack.y) * (px - pBlack.x) + (pBlack.x - pWhite.x) * (py - pBlack.y)) / det;
+ let wB = ((pBlack.y - pTip.y) * (px - pBlack.x) + (pTip.x - pBlack.x) * (py - pBlack.y)) / det;
+ let wC = 1 - wA - wB;
+
+ wA = Math.max(0, Math.min(1, wA));
+ wB = Math.max(0, Math.min(1, wB));
+ wC = Math.max(0, Math.min(1, wC));
+ const sum = wA + wB + wC;
+ if (sum > 0) {
+ wA /= sum;
+ wB /= sum;
+ wC /= sum;
+ }
+
+ const v = Math.max(0, Math.min(1, 1 - wC));
+ const s = v > 0.001 ? Math.max(0, Math.min(1, wA / v)) : 0;
+ return { s, v };
+ };
+
const handlePointerDown = (e: React.PointerEvent<HTMLCanvasElement>) => {
const canvas = canvasRef.current;
if (!canvas) return;
@@ -399,65 +307,26 @@ export const ColorWheel: React.FC<ColorWheelProps> = ({
const rect = canvas.getBoundingClientRect();
const px = e.clientX - rect.left;
const py = e.clientY - rect.top;
-
const dx = px - cx;
const dy = py - cy;
const dist = Math.hypot(dx, dy);
- // Click on Outer Hue Ring
- if (dist >= innerRadius - 5 && dist <= outerRadius + 8) {
+ if (dist >= innerRadius - 4 && dist <= outerRadius + 6) {
setIsDragging('hue');
- const angle = Math.atan2(dy, dx);
- const deg = (angle * 180) / Math.PI;
- let newHue = Math.round((deg - HUE_OFFSET + 360) % 360);
+ const deg = (Math.atan2(dy, dx) * 180) / Math.PI;
+ const newHue = Math.round((deg - HUE_OFFSET + 360) % 360);
handleColorChange({ ...hsv, h: newHue }, false);
return;
}
- // Click in Inner Area (zero dead zone)
- if (dist < innerRadius - 5) {
+ if (dist < innerRadius - 4) {
setIsDragging('sv');
if (wheelMode === 'square') {
const s = Math.max(0, Math.min(1, (px - sqX) / squareSize));
const v = Math.max(0, Math.min(1, 1 - (py - sqY) / squareSize));
handleColorChange({ ...hsv, s, v }, false);
} else {
- // Triangle Mode
- const rTri = innerRadius - 8;
- const tipAngle = ((hsv.h + HUE_OFFSET) * Math.PI) / 180;
- const pTip = { x: cx + rTri * Math.cos(tipAngle), y: cy + rTri * Math.sin(tipAngle) };
- const pWhite = {
- x: cx + rTri * Math.cos(tipAngle + (2 * Math.PI) / 3),
- y: cy + rTri * Math.sin(tipAngle + (2 * Math.PI) / 3),
- };
- const pBlack = {
- x: cx + rTri * Math.cos(tipAngle - (2 * Math.PI) / 3),
- y: cy + rTri * Math.sin(tipAngle - (2 * Math.PI) / 3),
- };
-
- // Barycentric coordinate calculation for point P
- const det =
- (pWhite.y - pBlack.y) * (pTip.x - pBlack.x) +
- (pBlack.x - pWhite.x) * (pTip.y - pBlack.y);
- let wA =
- ((pWhite.y - pBlack.y) * (px - pBlack.x) + (pBlack.x - pWhite.x) * (py - pBlack.y)) / det;
- let wB =
- ((pBlack.y - pTip.y) * (px - pBlack.x) + (pTip.x - pBlack.x) * (py - pBlack.y)) / det;
- let wC = 1 - wA - wB;
-
- // Clamp inside triangle
- wA = Math.max(0, Math.min(1, wA));
- wB = Math.max(0, Math.min(1, wB));
- wC = Math.max(0, Math.min(1, wC));
- const sum = wA + wB + wC;
- if (sum > 0) {
- wA /= sum;
- wB /= sum;
- wC /= sum;
- }
-
- const v = Math.max(0, Math.min(1, 1 - wC));
- const s = v > 0.001 ? Math.max(0, Math.min(1, wA / v)) : 0;
+ const { s, v } = sampleTriangleSV(px, py);
handleColorChange({ ...hsv, s, v }, false);
}
}
@@ -473,11 +342,8 @@ export const ColorWheel: React.FC<ColorWheelProps> = ({
const py = e.clientY - rect.top;
if (isDragging === 'hue') {
- const dx = px - cx;
- const dy = py - cy;
- const angle = Math.atan2(dy, dx);
- const deg = (angle * 180) / Math.PI;
- let newHue = Math.round((deg - HUE_OFFSET + 360) % 360);
+ const deg = (Math.atan2(py - cy, px - cx) * 180) / Math.PI;
+ const newHue = Math.round((deg - HUE_OFFSET + 360) % 360);
handleColorChange({ ...hsv, h: newHue }, false);
} else if (isDragging === 'sv') {
if (wheelMode === 'square') {
@@ -485,40 +351,8 @@ export const ColorWheel: React.FC<ColorWheelProps> = ({
const v = Math.max(0, Math.min(1, 1 - (py - sqY) / squareSize));
handleColorChange({ ...hsv, s, v }, false);
} else {
- const rTri = innerRadius - 8;
- const tipAngle = ((hsv.h + HUE_OFFSET) * Math.PI) / 180;
- const pTip = { x: cx + rTri * Math.cos(tipAngle), y: cy + rTri * Math.sin(tipAngle) };
- const pWhite = {
- x: cx + rTri * Math.cos(tipAngle + (2 * Math.PI) / 3),
- y: cy + rTri * Math.sin(tipAngle + (2 * Math.PI) / 3),
- };
- const pBlack = {
- x: cx + rTri * Math.cos(tipAngle - (2 * Math.PI) / 3),
- y: cy + rTri * Math.sin(tipAngle - (2 * Math.PI) / 3),
- };
-
- const det =
- (pWhite.y - pBlack.y) * (pTip.x - pBlack.x) +
- (pBlack.x - pWhite.x) * (pTip.y - pBlack.y);
- let wA =
- ((pWhite.y - pBlack.y) * (px - pBlack.x) + (pBlack.x - pWhite.x) * (py - pBlack.y)) / det;
- let wB =
- ((pBlack.y - pTip.y) * (px - pBlack.x) + (pTip.x - pBlack.x) * (py - pBlack.y)) / det;
- let wC = 1 - wA - wB;
-
- wA = Math.max(0, Math.min(1, wA));
- wB = Math.max(0, Math.min(1, wB));
- wC = Math.max(0, Math.min(1, wC));
- const sum = wA + wB + wC;
- if (sum > 0) {
- wA /= sum;
- wB /= sum;
- wC /= sum;
- }
-
- const v = Math.max(0, Math.min(1, 1 - wC));
- const s = v > 0.001 ? Math.max(0, Math.min(1, wA / v)) : 0;
- handleColorChange({ ...hsv, s, v });
+ const { s, v } = sampleTriangleSV(px, py);
+ handleColorChange({ ...hsv, s, v }, false);
}
}
};
@@ -530,396 +364,36 @@ export const ColorWheel: React.FC<ColorWheelProps> = ({
canvas.releasePointerCapture(e.pointerId);
}
setIsDragging(null);
- // Commit final color
handleColorChange(hsv, true);
};
- // Direct HSV Numeric Inputs Handlers
- const handleHueInput = (valStr: string) => {
- const val = parseInt(valStr, 10);
- if (!isNaN(val)) {
- const clamped = Math.max(0, Math.min(359, val));
- handleColorChange({ ...hsv, h: clamped }, true);
- }
- };
-
- const handleSatInput = (valStr: string) => {
- const val = parseInt(valStr, 10);
- if (!isNaN(val)) {
- const clamped = Math.max(0, Math.min(100, val)) / 100;
- handleColorChange({ ...hsv, s: clamped }, true);
- }
- };
-
- const handleValInput = (valStr: string) => {
- const val = parseInt(valStr, 10);
- if (!isNaN(val)) {
- const clamped = Math.max(0, Math.min(100, val)) / 100;
- handleColorChange({ ...hsv, v: clamped }, true);
- }
- };
-
- // Direct Hex Input Handler
- const handleHexInput = (valStr: string) => {
- const trimmed = valStr.trim();
- if (isValidHex(trimmed)) {
- const formatted = trimmed.startsWith('#') ? trimmed : `#${trimmed}`;
- const newHsv = hexToHsv(formatted);
- handleColorChange(newHsv, true);
- }
- };
-
- // Direct RGB Input Handlers
- const currentRgb = useMemo(() => hsvToRgb(hsv.h, hsv.s, hsv.v), [hsv]);
-
- const handleRgbInput = (channel: 'r' | 'g' | 'b', valStr: string) => {
- const val = parseInt(valStr, 10);
- if (!isNaN(val)) {
- const clamped = Math.max(0, Math.min(255, val));
- const nextRgb = { ...currentRgb, [channel]: clamped };
- const nextHsv = rgbToHsv(nextRgb.r, nextRgb.g, nextRgb.b);
- handleColorChange(nextHsv, true);
- }
- };
-
- const copyHexToClipboard = () => {
- navigator.clipboard.writeText(activeColor.toUpperCase());
- setCopiedHex(true);
- setTimeout(() => setCopiedHex(false), 1500);
- };
-
- // Transparent Color Toggle (CSP checkered button)
- const isTransparentActive = currentTool === 'eraser';
- const handleToggleTransparent = () => {
- if (onSelectTool) {
- if (isTransparentActive) {
- onSelectTool('brush');
- } else {
- onSelectTool('eraser');
- }
- }
- };
-
return (
- <div ref={containerRef} className="flex flex-col select-none text-[#cccccc] text-xs h-full">
- {/* Header Bar matching Clip Studio Paint Color Wheel */}
- {!hideHeader && (
- <div className="bg-[#2a2a2a] px-3 py-1.5 border-b border-[#333333] flex items-center justify-between">
- <div className="flex items-center space-x-2 text-xs font-medium text-[#cccccc]">
- <Menu className="w-3.5 h-3.5 text-[#888888] cursor-pointer hover:text-white transition-colors" />
- <div className="flex items-center space-x-1.5">
- <Disc className="w-3.5 h-3.5 text-[#5ce1e6]" />
- <span className="font-semibold tracking-wide">Color Wheel</span>
- </div>
- </div>
-
- <div className="flex items-center space-x-1">
- {/* Swap Colors Shortcut Button */}
- <button
- onClick={onSwapColors}
- title="Swap Primary & Secondary Colors (X)"
- className="flex items-center space-x-1 px-1.5 py-0.5 bg-[#1e1e1e] hover:bg-[#333333] text-[#888888] hover:text-[#cccccc] rounded-[2px] border border-[#3a3a3a] transition-colors cursor-pointer"
- >
- <ArrowLeftRight className="w-3 h-3" />
- <span className="text-[10px] font-mono">X</span>
- </button>
- </div>
- </div>
- )}
-
- {/* Main Wheel Canvas Section */}
- <div className="flex flex-col items-center justify-center pt-2.5 pb-1 px-3">
- <div
- style={{ width: wheelSize, height: wheelSize }}
- className="relative flex items-center justify-center cursor-crosshair touch-none"
- >
- <canvas
- ref={canvasRef}
- style={{ width: wheelSize, height: wheelSize }}
- onPointerDown={handlePointerDown}
- onPointerMove={handlePointerMove}
- onPointerUp={handlePointerUp}
- onPointerCancel={handlePointerUp}
- className="block"
- />
- </div>
-
- {/* Clip Studio Paint Bottom Controls: Dual Swatches + Transparent Swatch + H S V Readout + Mode Toggle */}
- <div
- style={{ width: '100%', maxWidth: Math.max(wheelSize, 280) }}
- className="flex items-center justify-between mt-1 px-1 pt-1 pb-1"
- >
- {/* Left: Dual Primary/Secondary Swatches & Transparent Checker Button */}
- <div className="flex items-center space-x-2">
- {/* Overlapping Primary / Secondary Swatches */}
- <div className="relative w-8 h-8 shrink-0">
- {/* Secondary Color Swatch (bottom-right) */}
- <div
- onClick={() => {
- setActiveTarget('secondary');
- if (currentTool === 'eraser' && onSelectTool) onSelectTool('brush');
- }}
- title={`Secondary Color: ${secondaryColor} (Click to select & edit)`}
- className={`absolute bottom-0 right-0 w-5 h-5 rounded-[2px] cursor-pointer transition-all ${
- activeTarget === 'secondary' && !isTransparentActive
- ? 'border-2 border-[#5ce1e6] ring-2 ring-[#5ce1e6]/40 shadow-sm z-10 scale-105'
- : 'border border-[#555555] hover:border-white z-0'
- }`}
- style={{ backgroundColor: secondaryColor }}
- />
-
- {/* Primary Color Swatch (top-left) */}
- <div
- onClick={() => {
- setActiveTarget('primary');
- if (currentTool === 'eraser' && onSelectTool) onSelectTool('brush');
- }}
- title={`Primary Color: ${primaryColor} (Click to select & edit)`}
- className={`absolute top-0 left-0 w-5 h-5 rounded-[2px] cursor-pointer transition-all ${
- activeTarget === 'primary' && !isTransparentActive
- ? 'border-2 border-[#5ce1e6] ring-2 ring-[#5ce1e6]/40 shadow-md z-10 scale-105'
- : 'border border-white/80 hover:border-white z-0'
- }`}
- style={{ backgroundColor: primaryColor }}
- />
- </div>
-
- {/* Transparent Color Button (CSP checkered swatch) */}
- <button
- onClick={handleToggleTransparent}
- title="Transparent Color / Eraser Mode (C)"
- className={`w-6 h-5 rounded-[2px] overflow-hidden border cursor-pointer transition-all relative ${
- isTransparentActive
- ? 'border-[#5ce1e6] ring-2 ring-[#5ce1e6]/40 scale-105'
- : 'border-[#444444] hover:border-[#888888]'
- }`}
- style={{
- backgroundImage:
- 'repeating-conic-gradient(#555555 0% 25%, #333333 0% 50%)',
- backgroundSize: '8px 8px',
- }}
- />
- </div>
-
- {/* Center: Numeric H, S, V Readout / Inputs (matching screenshot `H 0 S 1 V 0`) */}
- <div className="flex items-center space-x-1.5 text-[11px] font-mono text-[#aaaaaa]">
- {/* Hue */}
- <div className="flex items-center space-x-0.5">
- <span className="text-[#888888] font-sans text-[10px] font-semibold">H</span>
- <input
- type="number"
- min={0}
- max={359}
- value={Math.round(hsv.h)}
- onChange={(e) => handleHueInput(e.target.value)}
- className="w-8 bg-[#1e1e1e] border border-[#333333] hover:border-[#555555] focus:border-[#5ce1e6] rounded-[2px] px-0.5 py-0.5 text-center text-[#dddddd] text-[10px] outline-none [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- />
- </div>
-
- {/* Saturation */}
- <div className="flex items-center space-x-0.5">
- <span className="text-[#888888] font-sans text-[10px] font-semibold">S</span>
- <input
- type="number"
- min={0}
- max={100}
- value={Math.round(hsv.s * 100)}
- onChange={(e) => handleSatInput(e.target.value)}
- className="w-8 bg-[#1e1e1e] border border-[#333333] hover:border-[#555555] focus:border-[#5ce1e6] rounded-[2px] px-0.5 py-0.5 text-center text-[#dddddd] text-[10px] outline-none [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- />
- </div>
-
- {/* Value */}
- <div className="flex items-center space-x-0.5">
- <span className="text-[#888888] font-sans text-[10px] font-semibold">V</span>
- <input
- type="number"
- min={0}
- max={100}
- value={Math.round(hsv.v * 100)}
- onChange={(e) => handleValInput(e.target.value)}
- className="w-8 bg-[#1e1e1e] border border-[#333333] hover:border-[#555555] focus:border-[#5ce1e6] rounded-[2px] px-0.5 py-0.5 text-center text-[#dddddd] text-[10px] outline-none [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- />
- </div>
- </div>
-
- {/* Right: Wheel Mode Toggle (Square vs Triangle, matching bottom-right circular button in screenshot) */}
- <button
- onClick={() => setWheelMode((m) => (m === 'square' ? 'triangle' : 'square'))}
- title={`Switch to ${wheelMode === 'square' ? 'Triangle' : 'Square'} Color Wheel`}
- className="w-6 h-6 rounded-full bg-[#1e1e1e] border border-[#3a3a3a] hover:border-[#666666] flex items-center justify-center text-[#888888] hover:text-[#5ce1e6] transition-colors cursor-pointer"
- >
- {wheelMode === 'square' ? (
- <Play className="w-3 h-3 rotate-90 fill-current" />
- ) : (
- <Square className="w-2.5 h-2.5" />
- )}
- </button>
- </div>
- </div>
-
- {/* Hex Code & Quick Toggle Strip */}
- <div className="px-3 pb-2 pt-0.5 space-y-2">
- <div className="flex items-center space-x-2">
- {/* Active Hex Input */}
- <div className="relative flex-1 flex items-center">
- <span className="absolute left-2 text-[#777777] font-mono text-[11px]">#</span>
- <input
- type="text"
- value={activeColor.replace('#', '').toUpperCase()}
- onChange={(e) => handleHexInput(e.target.value)}
- className="w-full bg-[#1e1e1e] border border-[#333333] focus:border-[#5ce1e6] rounded-[2px] pl-5 pr-7 py-1 text-[#dddddd] font-mono text-xs outline-none"
- maxLength={6}
- placeholder="000000"
- />
- <button
- onClick={copyHexToClipboard}
- title="Copy Hex Code"
- className="absolute right-1.5 p-1 text-[#777777] hover:text-white rounded transition-colors"
- >
- {copiedHex ? (
- <Check className="w-3 h-3 text-emerald-400" />
- ) : (
- <Copy className="w-3 h-3" />
- )}
- </button>
- </div>
-
- {/* Harmony Button matching Reference 2 */}
- <button
- onClick={() => {
- const compHue = (hsv.h + 180) % 360;
- const compHex = hsvToHex(compHue, hsv.s, hsv.v);
- if (activeTarget === 'primary') {
- onSecondaryColorChange(compHex);
- } else {
- onPrimaryColorChange(compHex);
- }
- }}
- title="Set complementary harmony color to secondary swatch"
- className="px-2 py-1 rounded-md bg-white/[0.05] hover:bg-white/[0.09] border border-white/[0.08] text-white/80 hover:text-white text-[11px] font-medium transition-colors cursor-pointer"
- >
- Harmony
- </button>
-
- {/* Toggle RGB Sliders */}
- <button
- onClick={() => setShowAdvanced((v) => !v)}
- title="Toggle RGB / Advanced Inputs"
- className={`px-2 py-1 rounded-[2px] border text-[10px] font-medium transition-colors flex items-center space-x-1 cursor-pointer ${
- showAdvanced
- ? 'bg-[#2b353a] text-[#5ce1e6] border-[#3e535e]'
- : 'bg-[#1e1e1e] text-[#888888] hover:text-[#cccccc] border-[#333333]'
- }`}
- >
- <span>RGB</span>
- {showAdvanced ? (
- <ChevronDown className="w-3 h-3" />
- ) : (
- <ChevronRight className="w-3 h-3" />
- )}
- </button>
- </div>
-
- {/* Collapsible RGB Channels */}
- {showAdvanced && (
- <div className="bg-[#1a1a1c] p-2 rounded-[2px] border border-[#2d2d30] space-y-1.5 animate-in fade-in duration-150">
- {/* R */}
- <div className="flex items-center space-x-2">
- <span className="w-3 text-[10px] font-bold text-rose-400">R</span>
- <input
- type="range"
- min={0}
- max={255}
- value={currentRgb.r}
- onChange={(e) => handleRgbInput('r', e.target.value)}
- className="flex-1 h-1 bg-[#333333] rounded appearance-none cursor-pointer accent-rose-500"
- />
- <input
- type="number"
- min={0}
- max={255}
- value={currentRgb.r}
- onChange={(e) => handleRgbInput('r', e.target.value)}
- className="w-10 bg-[#222224] border border-[#333333] rounded px-1 py-0.5 text-center font-mono text-[10px] text-[#cccccc] outline-none"
- />
- </div>
-
- {/* G */}
- <div className="flex items-center space-x-2">
- <span className="w-3 text-[10px] font-bold text-emerald-400">G</span>
- <input
- type="range"
- min={0}
- max={255}
- value={currentRgb.g}
- onChange={(e) => handleRgbInput('g', e.target.value)}
- className="flex-1 h-1 bg-[#333333] rounded appearance-none cursor-pointer accent-emerald-500"
- />
- <input
- type="number"
- min={0}
- max={255}
- value={currentRgb.g}
- onChange={(e) => handleRgbInput('g', e.target.value)}
- className="w-10 bg-[#222224] border border-[#333333] rounded px-1 py-0.5 text-center font-mono text-[10px] text-[#cccccc] outline-none"
- />
- </div>
-
- {/* B */}
- <div className="flex items-center space-x-2">
- <span className="w-3 text-[10px] font-bold text-blue-400">B</span>
- <input
- type="range"
- min={0}
- max={255}
- value={currentRgb.b}
- onChange={(e) => handleRgbInput('b', e.target.value)}
- className="flex-1 h-1 bg-[#333333] rounded appearance-none cursor-pointer accent-blue-500"
- />
- <input
- type="number"
- min={0}
- max={255}
- value={currentRgb.b}
- onChange={(e) => handleRgbInput('b', e.target.value)}
- className="w-10 bg-[#222224] border border-[#333333] rounded px-1 py-0.5 text-center font-mono text-[10px] text-[#cccccc] outline-none"
- />
- </div>
- </div>
- )}
-
- {/* Recent Color History Swatches */}
- {recentColors && recentColors.length > 0 && (
- <div className="pt-1.5 border-t border-[#2e2e30]">
- <div className="flex items-center justify-between text-[10px] text-[#777777] mb-1 font-medium">
- <span>Recent Colors</span>
- <span className="text-[9px] text-[#555555]">{recentColors.length} items</span>
- </div>
- <div className="flex items-center space-x-1 overflow-x-auto py-0.5 scrollbar-thin">
- {recentColors.map((color, idx) => (
- <button
- key={`${color}-${idx}`}
- onClick={() => {
- if (activeTarget === 'primary') {
- onPrimaryColorChange(color);
- } else {
- onSecondaryColorChange(color);
- }
- }}
- title={`Recent: ${color}`}
- className={`w-5 h-5 rounded-[2px] border shrink-0 cursor-pointer transition-transform hover:scale-110 ${
- activeColor.toLowerCase() === color.toLowerCase()
- ? 'border-white ring-1 ring-[#5ce1e6]'
- : 'border-[#383838] hover:border-[#777777]'
- }`}
- style={{ backgroundColor: color }}
- />
- ))}
- </div>
- </div>
+ <div
+ ref={containerRef}
+ className="relative flex-1 min-h-0 w-full h-full flex items-center justify-center select-none"
+ >
+ <canvas
+ ref={canvasRef}
+ style={{ width: wheelSize, height: wheelSize }}
+ onPointerDown={handlePointerDown}
+ onPointerMove={handlePointerMove}
+ onPointerUp={handlePointerUp}
+ onPointerCancel={handlePointerUp}
+ className="block cursor-crosshair touch-none"
+ />
+
+ <button
+ type="button"
+ onClick={() => setWheelMode((m) => (m === 'square' ? 'triangle' : 'square'))}
+ title={`Switch to ${wheelMode === 'square' ? 'Triangle' : 'Square'} Mode`}
+ className="absolute bottom-1 right-1.5 w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"
+ >
+ {wheelMode === 'square' ? (
+ <Play className="w-2.5 h-2.5 rotate-90 fill-current" />
+ ) : (
+ <Square className="w-2.5 h-2.5" />
)}
- </div>
+ </button>
</div>
);
};
diff --git a/src/components/CrashRecoveryModal.tsx b/src/components/CrashRecoveryModal.tsx
new file mode 100644
index 0000000..edc86cb
--- /dev/null
+++ b/src/components/CrashRecoveryModal.tsx
@@ -0,0 +1,251 @@
+import React, { useState } from 'react';
+import {
+ RotateCcw,
+ Trash2,
+ AlertTriangle,
+ Layers,
+ Calendar,
+ Maximize2,
+ Cpu,
+ FileText,
+ Clock,
+ Sparkles,
+ ShieldCheck,
+} from 'lucide-react';
+import { CrashedSessionInfo } from '../services/recoveryService';
+
+interface CrashRecoveryModalProps {
+ isOpen: boolean;
+ sessions: CrashedSessionInfo[];
+ onRestore: (session: CrashedSessionInfo) => Promise<void>;
+ onDiscard: (session: CrashedSessionInfo) => Promise<void>;
+ onClose?: () => void;
+}
+
+export const CrashRecoveryModal: React.FC<CrashRecoveryModalProps> = ({
+ isOpen,
+ sessions,
+ onRestore,
+ onDiscard,
+}) => {
+ const [selectedIndex, setSelectedIndex] = useState<number>(0);
+ const [isRestoring, setIsRestoring] = useState<boolean>(false);
+ const [isDiscarding, setIsDiscarding] = useState<boolean>(false);
+
+ if (!isOpen || sessions.length === 0) return null;
+
+ const currentSession = sessions[selectedIndex] || sessions[0];
+
+ let manifestData: any = null;
+ if (currentSession.manifest_json) {
+ try {
+ manifestData = JSON.parse(currentSession.manifest_json);
+ } catch {
+ manifestData = null;
+ }
+ }
+
+ const documentName = manifestData?.documentName || 'Untitled Document';
+ const width = manifestData?.width || 3000;
+ const height = manifestData?.height || 3000;
+ const dpi = manifestData?.dpi || 600;
+ const colorMode = manifestData?.colorMode || 'color';
+ const layerCount = manifestData?.layers?.length || 1;
+
+ const crashDate = currentSession.timestamp
+ ? new Date(currentSession.timestamp).toLocaleString(undefined, {
+ dateStyle: 'medium',
+ timeStyle: 'medium',
+ })
+ : 'Unknown';
+
+ const handleRestoreClick = async () => {
+ setIsRestoring(true);
+ try {
+ await onRestore(currentSession);
+ } finally {
+ setIsRestoring(false);
+ }
+ };
+
+ const handleDiscardClick = async () => {
+ setIsDiscarding(true);
+ try {
+ await onDiscard(currentSession);
+ } finally {
+ setIsDiscarding(false);
+ }
+ };
+
+ return (
+ <div
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="crash-recovery-title"
+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-xs p-4 select-none animate-in fade-in duration-150"
+ >
+ <div className="bg-[#242426] border border-[#3c3c40] rounded-xl shadow-2xl w-full max-w-2xl flex flex-col overflow-hidden text-xs text-[#d0d0d0]">
+ {/* Header Bar */}
+ <div className="flex items-center justify-between px-6 py-4 bg-[#2a2a2d] border-b border-[#38383a]">
+ <div className="flex items-center space-x-3">
+ <div className="w-8 h-8 rounded-lg bg-amber-500/15 border border-amber-500/30 flex items-center justify-center text-amber-400">
+ <AlertTriangle className="w-4 h-4" />
+ </div>
+ <div>
+ <h2 id="crash-recovery-title" className="text-sm font-semibold text-white tracking-wide flex items-center gap-2">
+ Restore Unsaved Session?
+ <span className="px-2 py-0.5 rounded-full text-[10px] font-medium bg-emerald-500/15 text-emerald-400 border border-emerald-500/30 flex items-center gap-1">
+ <ShieldCheck className="w-3 h-3" />
+ WAL Protected
+ </span>
+ </h2>
+ <p className="text-[11px] text-[#999999] mt-0.5">
+ Ink Studio detected an unexpected application shutdown. Your progress can be restored with zero data loss.
+ </p>
+ </div>
+ </div>
+ </div>
+
+ {/* Multiple Sessions Selector (if > 1 session detected) */}
+ {sessions.length > 1 && (
+ <div className="px-6 py-2 bg-[#1e1e20] border-b border-[#323235] flex items-center gap-2 overflow-x-auto">
+ <span className="text-[10px] text-[#888888] font-semibold uppercase tracking-wider shrink-0">
+ Sessions:
+ </span>
+ {sessions.map((s, idx) => (
+ <button
+ key={s.session_id}
+ onClick={() => setSelectedIndex(idx)}
+ className={`px-3 py-1 rounded text-xs transition-colors border ${
+ idx === selectedIndex
+ ? 'bg-[#007acc] border-[#007acc] text-white font-medium'
+ : 'bg-[#29292c] border-[#38383c] text-[#a0a0a0] hover:text-white'
+ }`}
+ >
+ Session {idx + 1}
+ </button>
+ ))}
+ </div>
+ )}
+
+ {/* Modal Main Content */}
+ <div className="p-6 space-y-5">
+ {/* Document Preview & Metadata Card */}
+ <div className="bg-[#1b1b1d] border border-[#323235] rounded-lg p-4 grid grid-cols-1 md:grid-cols-12 gap-5">
+ {/* Visual Thumbnail Preview (5 cols) */}
+ <div className="md:col-span-5 flex flex-col items-center justify-center">
+ <div className="w-full aspect-square max-w-[210px] bg-[#141416] border border-[#38383c] rounded-md overflow-hidden relative flex items-center justify-center shadow-inner group">
+ {currentSession.thumbnail_data_url ? (
+ <img
+ src={currentSession.thumbnail_data_url}
+ alt="Document preview"
+ className="w-full h-full object-contain p-1"
+ />
+ ) : (
+ <div className="flex flex-col items-center justify-center text-[#666666] p-4 text-center">
+ <Layers className="w-10 h-10 mb-2 opacity-50 text-[#888888]" />
+ <span className="text-[11px] font-medium text-[#888888]">No Snapshot Preview</span>
+ <span className="text-[10px] text-[#555555]">WAL journal entries intact</span>
+ </div>
+ )}
+ <div className="absolute bottom-2 left-2 bg-black/75 px-1.5 py-0.5 rounded text-[10px] font-mono text-[#aaaaaa] border border-white/10">
+ {width} × {height}
+ </div>
+ </div>
+ </div>
+
+ {/* Metadata Fields (7 cols) */}
+ <div className="md:col-span-7 flex flex-col justify-between space-y-3">
+ <div>
+ <div className="flex items-center gap-2">
+ <FileText className="w-4 h-4 text-sky-400 shrink-0" />
+ <h3 className="text-sm font-semibold text-white truncate" title={documentName}>
+ {documentName}
+ </h3>
+ </div>
+ <p className="text-[11px] text-[#777777] font-mono mt-0.5 truncate">
+ ID: {currentSession.session_id}
+ </p>
+ </div>
+
+ <div className="grid grid-cols-2 gap-2 text-xs">
+ <div className="bg-[#242427] border border-[#323236] rounded p-2 flex items-center gap-2">
+ <Maximize2 className="w-3.5 h-3.5 text-sky-400 shrink-0" />
+ <div>
+ <span className="text-[10px] text-[#888888] block">Canvas Size</span>
+ <span className="font-semibold text-white">{width} × {height}</span>
+ </div>
+ </div>
+
+ <div className="bg-[#242427] border border-[#323236] rounded p-2 flex items-center gap-2">
+ <Sparkles className="w-3.5 h-3.5 text-amber-400 shrink-0" />
+ <div>
+ <span className="text-[10px] text-[#888888] block">Resolution</span>
+ <span className="font-semibold text-white">{dpi} DPI</span>
+ </div>
+ </div>
+
+ <div className="bg-[#242427] border border-[#323236] rounded p-2 flex items-center gap-2">
+ <Layers className="w-3.5 h-3.5 text-purple-400 shrink-0" />
+ <div>
+ <span className="text-[10px] text-[#888888] block">Layer Tree</span>
+ <span className="font-semibold text-white">{layerCount} {layerCount === 1 ? 'Layer' : 'Layers'}</span>
+ </div>
+ </div>
+
+ <div className="bg-[#242427] border border-[#323236] rounded p-2 flex items-center gap-2">
+ <Cpu className="w-3.5 h-3.5 text-emerald-400 shrink-0" />
+ <div>
+ <span className="text-[10px] text-[#888888] block">Color Expression</span>
+ <span className="font-semibold text-white capitalize">{colorMode}</span>
+ </div>
+ </div>
+ </div>
+
+ {/* Timestamp & Process Info */}
+ <div className="bg-[#202022] border border-[#2d2d30] rounded p-2 text-[11px] space-y-1">
+ <div className="flex items-center justify-between text-[#888888]">
+ <span className="flex items-center gap-1.5">
+ <Clock className="w-3 h-3 text-[#999999]" />
+ Terminated At:
+ </span>
+ <span className="text-white font-mono">{crashDate}</span>
+ </div>
+ <div className="flex items-center justify-between text-[#888888]">
+ <span className="flex items-center gap-1.5">
+ <Calendar className="w-3 h-3 text-[#999999]" />
+ Previous PID:
+ </span>
+ <span className="text-[#aaaaaa] font-mono">{currentSession.pid}</span>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* Modal Action Footer */}
+ <div className="flex items-center justify-between px-6 py-4 bg-[#202022] border-t border-[#343438]">
+ <button
+ type="button"
+ disabled={isRestoring || isDiscarding}
+ onClick={handleDiscardClick}
+ className="flex items-center gap-2 px-4 py-2 rounded-md text-xs font-medium bg-red-500/10 hover:bg-red-500/20 text-red-400 border border-red-500/30 transition-colors disabled:opacity-50 cursor-pointer"
+ >
+ <Trash2 className="w-3.5 h-3.5" />
+ <span>{isDiscarding ? 'Discarding...' : 'Discard & Start Fresh'}</span>
+ </button>
+
+ <button
+ type="button"
+ disabled={isRestoring || isDiscarding}
+ onClick={handleRestoreClick}
+ className="flex items-center gap-2 px-5 py-2 rounded-md text-xs font-semibold bg-[#007acc] hover:bg-[#008ae6] text-white shadow-md shadow-sky-950/40 border border-[#0090f0]/30 transition-all disabled:opacity-50 cursor-pointer active:scale-98"
+ >
+ <RotateCcw className={`w-3.5 h-3.5 ${isRestoring ? 'animate-spin' : ''}`} />
+ <span>{isRestoring ? 'Restoring Canvas...' : 'Restore Session'}</span>
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/src/components/FloatingBrushPill.tsx b/src/components/FloatingBrushPill.tsx
new file mode 100644
index 0000000..1a7881f
--- /dev/null
+++ b/src/components/FloatingBrushPill.tsx
@@ -0,0 +1,236 @@
+import React, { useState, useRef, useCallback } from 'react';
+import { ToolType, BrushSettings, LiquifySettings } from '../types/editor';
+
+interface FloatingBrushPillProps {
+ tool: ToolType;
+ brushSettings: BrushSettings;
+ onUpdateBrushSettings: (patch: Partial<BrushSettings>) => void;
+ liquifySettings?: LiquifySettings;
+ onUpdateLiquifySettings?: (patch: Partial<LiquifySettings>) => void;
+ primaryColor?: string;
+ onSwapColors?: () => void;
+ zoom?: number;
+}
+
+const MIN_BRUSH_SIZE = 0.5;
+const MAX_BRUSH_SIZE = 250;
+
+function sizeToRatio(size: number, min: number, max: number): number {
+ const clamped = Math.max(min, Math.min(max, size));
+ return Math.sqrt((clamped - min) / (max - min));
+}
+
+function ratioToSize(ratio: number, min: number, max: number): number {
+ const r = Math.max(0, Math.min(1, ratio));
+ const raw = min + r * r * (max - min);
+ if (raw < 10) return Math.round(raw * 2) / 2;
+ return Math.round(raw);
+}
+
+export const FloatingBrushPill: React.FC<FloatingBrushPillProps> = React.memo(({
+ tool,
+ brushSettings,
+ onUpdateBrushSettings,
+ liquifySettings,
+ onUpdateLiquifySettings,
+ primaryColor = '#000000',
+ onSwapColors,
+ zoom = 1,
+}) => {
+ const [activeDrag, setActiveDrag] = useState<'size' | 'opacity' | null>(null);
+ const [hoveredTrack, setHoveredTrack] = useState<'size' | 'opacity' | null>(null);
+ const sizeTrackRef = useRef<HTMLDivElement>(null);
+ const opacityTrackRef = useRef<HTMLDivElement>(null);
+
+ const isLiquify = tool === 'liquify';
+ const minSize = isLiquify ? 5 : MIN_BRUSH_SIZE;
+ const maxSize = isLiquify ? 500 : MAX_BRUSH_SIZE;
+
+ const currentSize = isLiquify ? (liquifySettings?.size ?? 80) : brushSettings.size;
+ const currentOpacity = isLiquify
+ ? (liquifySettings?.strength ?? 50) / 100
+ : (brushSettings.opacity ?? 1);
+
+ const sizeRatio = sizeToRatio(currentSize, minSize, maxSize);
+ const opacityRatio = Math.max(0.01, Math.min(1, currentOpacity));
+
+ const updateSizeFromPointer = useCallback(
+ (clientY: number) => {
+ const el = sizeTrackRef.current;
+ if (!el) return;
+ const rect = el.getBoundingClientRect();
+ const ratio = 1 - (clientY - rect.top) / rect.height;
+ const nextSize = ratioToSize(ratio, minSize, maxSize);
+ if (isLiquify) {
+ onUpdateLiquifySettings?.({ size: nextSize });
+ } else {
+ onUpdateBrushSettings({ size: nextSize });
+ }
+ },
+ [isLiquify, maxSize, minSize, onUpdateBrushSettings, onUpdateLiquifySettings]
+ );
+
+ const updateOpacityFromPointer = useCallback(
+ (clientY: number) => {
+ const el = opacityTrackRef.current;
+ if (!el) return;
+ const rect = el.getBoundingClientRect();
+ const ratio = Math.max(0.01, Math.min(1, 1 - (clientY - rect.top) / rect.height));
+ if (isLiquify) {
+ onUpdateLiquifySettings?.({ strength: Math.round(ratio * 100) });
+ } else {
+ onUpdateBrushSettings({ opacity: Math.round(ratio * 100) / 100 });
+ }
+ },
+ [isLiquify, onUpdateBrushSettings, onUpdateLiquifySettings]
+ );
+
+ const showSizeHud = activeDrag === 'size' || hoveredTrack === 'size';
+ const showOpacityHud = activeDrag === 'opacity' || hoveredTrack === 'opacity';
+ const previewDiameter = Math.max(4, Math.min(220, currentSize * zoom));
+
+ return (
+ <div
+ onPointerDown={(e) => e.stopPropagation()}
+ onWheel={(e) => e.stopPropagation()}
+ className="absolute left-3 top-1/2 -translate-y-1/2 z-35 flex flex-col items-center py-3 px-1.5 w-7 rounded-full bg-[#202020]/95 backdrop-blur-sm shadow-[0_8px_28px_rgba(0,0,0,0.55)] select-none"
+ >
+ {/* Top Vertical Slider: Brush Size */}
+ <div
+ ref={sizeTrackRef}
+ onPointerEnter={() => setHoveredTrack('size')}
+ onPointerLeave={() => setHoveredTrack((prev) => (prev === 'size' ? null : prev))}
+ onPointerDown={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ e.currentTarget.setPointerCapture(e.pointerId);
+ setActiveDrag('size');
+ updateSizeFromPointer(e.clientY);
+ }}
+ onPointerMove={(e) => {
+ if (activeDrag === 'size') {
+ updateSizeFromPointer(e.clientY);
+ }
+ }}
+ onPointerUp={(e) => {
+ if (activeDrag === 'size') {
+ if (e.currentTarget.hasPointerCapture(e.pointerId)) {
+ e.currentTarget.releasePointerCapture(e.pointerId);
+ }
+ setActiveDrag(null);
+ }
+ }}
+ onPointerCancel={() => setActiveDrag(null)}
+ title={`Brush Size: ${currentSize}px`}
+ className="relative w-4 h-28 flex items-center justify-center cursor-ns-resize touch-none group"
+ >
+ <div className="w-1.5 h-full rounded-full bg-[#161616] group-hover:bg-[#2c2c2c] relative overflow-hidden transition-colors">
+ <div
+ className="absolute bottom-0 left-0 right-0 rounded-full transition-[height] duration-75"
+ style={{
+ height: `${sizeRatio * 100}%`,
+ backgroundColor: 'var(--accent)',
+ }}
+ />
+ </div>
+ <div
+ className="absolute left-1/2 -translate-x-1/2 w-3 h-3 rounded-full shadow-sm pointer-events-none transition-transform group-hover:scale-110"
+ style={{
+ bottom: `calc(${sizeRatio * 100}% - 6px)`,
+ backgroundColor: 'var(--accent)',
+ }}
+ />
+
+ {showSizeHud && (
+ <div className="pointer-events-none absolute left-8 top-1/2 -translate-y-1/2 flex items-center gap-2.5">
+ <div className="px-2 py-1 rounded bg-[#202020] shadow-[0_4px_16px_rgba(0,0,0,0.6)] whitespace-nowrap flex items-center gap-1.5">
+ <span className="text-[10px] text-[#8a8a8a]">Size</span>
+ <span className="text-[11px] font-mono text-[#e5e5e5] font-medium">
+ {currentSize}px
+ </span>
+ </div>
+ {activeDrag === 'size' && (
+ <div
+ className="rounded-full border border-[#e5e5e5]/80 bg-[#e5e5e5]/10 shrink-0 shadow-[0_0_0_1px_rgba(0,0,0,0.6)]"
+ style={{
+ width: `${previewDiameter}px`,
+ height: `${previewDiameter}px`,
+ }}
+ />
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* Center Active Color Dot / Quick Swap */}
+ <button
+ type="button"
+ onClick={onSwapColors}
+ title="Active Color (Click to swap Primary/Secondary)"
+ className="my-2 w-3.5 h-3.5 rounded-full shrink-0 cursor-pointer transition-transform hover:scale-115 shadow-[0_0_0_1px_rgba(255,255,255,0.22)]"
+ style={{ backgroundColor: primaryColor }}
+ />
+
+ {/* Bottom Vertical Slider: Brush Opacity */}
+ <div
+ ref={opacityTrackRef}
+ onPointerEnter={() => setHoveredTrack('opacity')}
+ onPointerLeave={() => setHoveredTrack((prev) => (prev === 'opacity' ? null : prev))}
+ onPointerDown={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ e.currentTarget.setPointerCapture(e.pointerId);
+ setActiveDrag('opacity');
+ updateOpacityFromPointer(e.clientY);
+ }}
+ onPointerMove={(e) => {
+ if (activeDrag === 'opacity') {
+ updateOpacityFromPointer(e.clientY);
+ }
+ }}
+ onPointerUp={(e) => {
+ if (activeDrag === 'opacity') {
+ if (e.currentTarget.hasPointerCapture(e.pointerId)) {
+ e.currentTarget.releasePointerCapture(e.pointerId);
+ }
+ setActiveDrag(null);
+ }
+ }}
+ onPointerCancel={() => setActiveDrag(null)}
+ title={`${isLiquify ? 'Strength' : 'Opacity'}: ${Math.round(opacityRatio * 100)}%`}
+ className="relative w-4 h-28 flex items-center justify-center cursor-ns-resize touch-none group"
+ >
+ <div className="w-1.5 h-full rounded-full bg-[#161616] group-hover:bg-[#2c2c2c] relative overflow-hidden transition-colors">
+ <div
+ className="absolute bottom-0 left-0 right-0 rounded-full transition-[height] duration-75"
+ style={{
+ height: `${opacityRatio * 100}%`,
+ backgroundColor: 'var(--accent)',
+ opacity: 0.75,
+ }}
+ />
+ </div>
+ <div
+ className="absolute left-1/2 -translate-x-1/2 w-3 h-3 rounded-full shadow-sm pointer-events-none transition-transform group-hover:scale-110"
+ style={{
+ bottom: `calc(${opacityRatio * 100}% - 6px)`,
+ backgroundColor: 'var(--accent)',
+ }}
+ />
+
+ {showOpacityHud && (
+ <div className="pointer-events-none absolute left-8 top-1/2 -translate-y-1/2 px-2 py-1 rounded bg-[#202020] shadow-[0_4px_16px_rgba(0,0,0,0.6)] whitespace-nowrap flex items-center gap-1.5">
+ <span className="text-[10px] text-[#8a8a8a]">
+ {isLiquify ? 'Strength' : 'Opacity'}
+ </span>
+ <span className="text-[11px] font-mono text-[#e5e5e5] font-medium">
+ {Math.round(opacityRatio * 100)}%
+ </span>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+});
+
+FloatingBrushPill.displayName = 'FloatingBrushPill';
diff --git a/src/components/Header.tsx b/src/components/Header.tsx
index 48148b4..2800965 100644
--- a/src/components/Header.tsx
+++ b/src/components/Header.tsx
@@ -1,14 +1,21 @@
-import React from 'react';
+import React, { useState } from 'react';
import {
Undo2,
Redo2,
- ZoomIn,
- ZoomOut,
- RotateCcw,
- RotateCw,
+ Minus,
+ Plus,
+ X,
Users,
+ Settings,
+ RotateCcw,
} from 'lucide-react';
-import { ToolType, CanvasDimensions, MenuSection, CanvasColorMode, BrushPresetId, SoftProofSettings } from '../types/editor';
+import {
+ CanvasDimensions,
+ MenuSection,
+ CanvasColorMode,
+ SoftProofSettings,
+ DocumentTab,
+} from '../types/editor';
import { ThemePreset } from '../types/settings';
import { formatZoomPercent } from '../hooks/useCanvasNavigation';
import { formatRotationDegrees } from '../utils/canvasUtils';
@@ -16,17 +23,10 @@ import { MenuBar } from './MenuBar';
import { WindowControls } from './WindowControls';
interface HeaderProps {
- tool?: ToolType;
- preset?: BrushPresetId;
- brushName?: string;
- brushSize?: number;
- onBrushSizeChange?: (size: number) => void;
canUndo: boolean;
canRedo: boolean;
onUndo: () => void;
onRedo: () => void;
- onClear?: () => void;
- onExport?: () => void;
zoom: number;
onZoomIn: () => void;
onZoomOut: () => void;
@@ -37,22 +37,23 @@ interface HeaderProps {
colorMode?: CanvasColorMode;
menuSections?: MenuSection[];
hasOpenDocument?: boolean;
+ documents?: DocumentTab[];
+ activeDocumentId?: string | null;
+ onSelectDocument?: (id: string) => void;
+ onCloseDocument?: (id: string) => void;
+ onNewDocument?: () => void;
+ onRenameDocument?: (id: string, newName: string) => void;
isCollabConnected?: boolean;
collabPeerCount?: number;
onOpenCollabModal?: () => void;
+ onOpenSettings?: () => void;
themePreset?: ThemePreset;
- activeDocumentTitle?: string;
softProofSettings?: SoftProofSettings;
appView?: 'home' | 'workspace';
onSelectAppView?: (view: 'home' | 'workspace') => void;
}
export const Header: React.FC<HeaderProps> = React.memo(({
- tool: _tool,
- preset: _preset,
- brushName: _brushName,
- brushSize: _brushSize,
- onBrushSizeChange: _onBrushSizeChange,
canUndo,
canRedo,
onUndo,
@@ -63,427 +64,273 @@ export const Header: React.FC<HeaderProps> = React.memo(({
onResetZoom,
rotation,
onResetRotation,
- dimensions = { width: 1440, height: 900 },
colorMode = 'color',
menuSections,
hasOpenDocument = true,
+ documents = [],
+ activeDocumentId = null,
+ onSelectDocument,
+ onCloseDocument,
+ onNewDocument,
+ onRenameDocument,
isCollabConnected = false,
collabPeerCount = 1,
onOpenCollabModal,
- themePreset = 'vintage-manga',
- activeDocumentTitle,
+ onOpenSettings,
+ themePreset,
softProofSettings,
appView = 'workspace',
onSelectAppView,
}) => {
- if (themePreset === 'modern') {
- return (
- <header
- data-tauri-drag-region
- className="h-10 px-3 flex items-center justify-between text-xs select-none z-30 shrink-0 cursor-default bg-[#18191d] border-b border-white/[0.08] text-white/90"
- >
- {/* Brand, Menus, Home/Workspace Pills & Document Info */}
- <div className="flex items-center space-x-3 min-w-0">
- <div className="flex items-center space-x-2" title="Ink Studio">
- <div className="w-5 h-5 flex items-center justify-center">
- <img
- src="/app-icon.png"
- alt="Studio Logo"
- className="w-4 h-4 object-contain select-none pointer-events-none drop-shadow-xs"
- />
- </div>
- <span className="font-semibold text-xs text-white tracking-tight hidden sm:inline">Ink Studio</span>
- </div>
-
- <span className="text-white/15">|</span>
-
- {/* Menu Bar Sections: File, Edit, Layer, View, Help */}
- <MenuBar sections={menuSections} />
-
- {/* Home / Workspace Navigation Pills matching Reference 1 & 3 */}
- <div className="flex items-center space-x-0.5 bg-white/[0.04] p-0.5 rounded-lg border border-white/[0.08]">
- <button
- onClick={() => onSelectAppView?.('home')}
- className={`px-3 py-1 rounded-md text-xs transition-colors cursor-pointer ${
- appView === 'home'
- ? 'bg-white/[0.14] text-white font-medium border border-white/10 shadow-xs'
- : 'text-white/60 hover:text-white hover:bg-white/[0.06] border border-transparent'
- }`}
- >
- Home
- </button>
- <button
- onClick={() => onSelectAppView?.('workspace')}
- className={`px-3 py-1 rounded-md text-xs transition-colors cursor-pointer ${
- appView === 'workspace'
- ? 'bg-white/[0.14] text-white font-medium border border-white/10 shadow-xs'
- : 'text-white/60 hover:text-white hover:bg-white/[0.06] border border-transparent'
- }`}
- >
- Workspace
- </button>
- </div>
-
- {hasOpenDocument && (
- <>
- <span className="text-white/15">|</span>
-
- <div className="flex items-center space-x-2 truncate">
- <span
- className="text-white/90 font-medium text-xs truncate max-w-[280px]"
- title={`${activeDocumentTitle || 'New canvas*'} (${dimensions.width}×${dimensions.height}px ${dimensions.dpi ? `${dimensions.dpi}dpi ` : ''}${formatZoomPercent(zoom)})`}
- >
- {activeDocumentTitle || 'New canvas*'}
- </span>
- <span className="text-[10px] text-white/40 font-mono hidden md:inline">
- {dimensions.width}×{dimensions.height}px
- </span>
-
- <span
- className={`text-[9px] px-1.5 py-0.5 rounded-full font-mono uppercase tracking-wider ${
- colorMode === 'monochrome'
- ? 'bg-amber-500/15 text-amber-300 border border-amber-500/30'
- : colorMode === 'grayscale'
- ? 'bg-slate-500/15 text-slate-300 border border-slate-500/30'
- : 'bg-[var(--modern-accent-subtle)] text-[var(--modern-accent)] border border-[var(--modern-accent-border)]'
- }`}
- title={`Active Canvas Color Mode: ${colorMode}`}
- >
- {colorMode === 'monochrome' ? 'Manga' : colorMode}
- </span>
-
- {softProofSettings?.enabled && (
- <span
- className="text-[9px] px-1.5 py-0.5 rounded-full font-mono uppercase tracking-wider bg-cyan-500/15 text-cyan-300 border border-cyan-500/30"
- title={`CMYK Soft Proofing Active (${softProofSettings.standard})`}
- >
- CMYK Proof
- </span>
- )}
-
- {softProofSettings?.gamutWarning && (
- <span
- className="text-[9px] px-1.5 py-0.5 rounded-full font-mono uppercase tracking-wider bg-amber-500/15 text-amber-300 border border-amber-500/30"
- title="Gamut Warning Overlay Active"
- >
- Gamut Warning
- </span>
- )}
- </div>
- </>
- )}
- </div>
-
- {/* Action Tools & Zoom */}
- <div className="flex items-center space-x-2">
- {/* Undo / Redo */}
- <div className="flex items-center rounded-lg p-0.5 space-x-0.5 bg-white/[0.04] border border-white/[0.08]">
- <button
- onClick={onUndo}
- disabled={!canUndo}
- title="Undo (Ctrl+Z)"
- className={`p-1 rounded-md transition-colors ${
- canUndo
- ? 'text-white/80 hover:text-white hover:bg-white/10 cursor-pointer'
- : 'text-white/20 cursor-not-allowed'
- }`}
- >
- <Undo2 className="w-3.5 h-3.5" />
- </button>
- <button
- onClick={onRedo}
- disabled={!canRedo}
- title="Redo (Ctrl+Y)"
- className={`p-1 rounded-md transition-colors ${
- canRedo
- ? 'text-white/80 hover:text-white hover:bg-white/10 cursor-pointer'
- : 'text-white/20 cursor-not-allowed'
- }`}
- >
- <Redo2 className="w-3.5 h-3.5" />
- </button>
- </div>
-
- {/* Zoom Controls */}
- <div
- className={`flex items-center space-x-0.5 rounded-lg px-1 py-0.5 bg-white/[0.04] border border-white/[0.08] ${
- !hasOpenDocument ? 'opacity-40 pointer-events-none' : ''
- }`}
- >
- <button
- onClick={onZoomOut}
- title="Zoom Out (Ctrl + Minus)"
- className="p-1 hover:text-white hover:bg-white/10 rounded-md text-white/60 transition-colors cursor-pointer"
- >
- <ZoomOut className="w-3.5 h-3.5" />
- </button>
- <button
- onClick={onResetZoom}
- title="Reset Zoom & Center (Ctrl + 0)"
- className="font-mono text-xs px-1.5 text-white/90 hover:text-white hover:bg-white/10 rounded-md transition-colors cursor-pointer"
- >
- {formatZoomPercent(zoom)}
- </button>
- <button
- onClick={onZoomIn}
- title="Zoom In (Ctrl + Plus)"
- className="p-1 hover:text-white hover:bg-white/10 rounded-md text-white/60 transition-colors cursor-pointer"
- >
- <ZoomIn className="w-3.5 h-3.5" />
- </button>
- <button
- onClick={onResetZoom}
- title="Reset to 100% & Center (Ctrl + 0)"
- className="p-1 hover:text-white hover:bg-white/10 rounded-md text-white/60 transition-colors cursor-pointer"
- >
- <RotateCcw className="w-3 h-3" />
- </button>
- </div>
-
- {/* Rotation Controls */}
- <div
- className={`flex items-center space-x-0.5 rounded-lg px-1 py-0.5 bg-white/[0.04] border border-white/[0.08] ${
- !hasOpenDocument ? 'opacity-40 pointer-events-none' : ''
- }`}
- >
- <RotateCw className="w-3.5 h-3.5 text-white/40 ml-0.5" />
- <button
- onClick={onResetRotation}
- onDoubleClick={onResetRotation}
- title="Canvas Rotation (Double-click or Ctrl+Alt+0 to Reset 0°)"
- className="font-mono text-xs px-1.5 text-white/90 hover:text-white hover:bg-white/10 rounded-md transition-colors cursor-pointer"
- >
- {formatRotationDegrees(rotation)}
- </button>
- {Math.abs(rotation % 360) > 0.05 && (
- <button
- onClick={onResetRotation}
- title="Reset Rotation to 0° (Ctrl+Alt+0)"
- className="p-1 hover:text-white hover:bg-white/10 rounded-md text-white/60 transition-colors cursor-pointer"
- >
- <RotateCcw className="w-3 h-3" />
- </button>
- )}
- </div>
+ const [editingId, setEditingId] = useState<string | null>(null);
+ const [editingName, setEditingName] = useState<string>('');
- <span className="text-white/15">|</span>
+ const handleStartRename = (e: React.MouseEvent, doc: DocumentTab) => {
+ e.stopPropagation();
+ setEditingId(doc.id);
+ setEditingName(doc.name);
+ };
- {/* Multiplayer Host / Connection Indicator */}
- <button
- onClick={onOpenCollabModal}
- className={`flex items-center space-x-1.5 px-2.5 py-1 rounded-lg text-xs font-medium transition-all cursor-pointer ${
- isCollabConnected
- ? 'bg-emerald-500/20 border border-emerald-500/40 text-emerald-300 hover:bg-emerald-500/30 shadow-xs'
- : 'bg-white/[0.04] hover:bg-white/[0.08] border border-white/[0.08] text-white/80 hover:text-white'
- }`}
- title={isCollabConnected ? `Collaborative Room (${collabPeerCount} online)` : 'Start Collaborative Session (Host)'}
- >
- {isCollabConnected ? (
- <>
- <span className="w-2 h-2 rounded-full bg-emerald-400 animate-pulse" />
- <span>{collabPeerCount} online</span>
- </>
- ) : (
- <>
- <Users className="w-3.5 h-3.5 text-white/60" />
- <span>Collab</span>
- </>
- )}
- </button>
+ const handleFinishRename = (id: string) => {
+ if (editingName.trim() && onRenameDocument) {
+ onRenameDocument(id, editingName.trim());
+ }
+ setEditingId(null);
+ };
- {/* Desktop Native Window Controls (Minimize, Maximize, Close) */}
- <WindowControls themePreset={themePreset} />
- </div>
- </header>
- );
- }
+ const isRotated = Math.abs(rotation % 360) > 0.05;
return (
<header
data-tauri-drag-region
- className="h-10 px-3 flex items-center justify-between text-xs select-none z-30 shrink-0 cursor-default transition-colors bg-gradient-to-b from-[#505053] to-[#3e3e40] border-b border-[#242426] text-[#e0e0e3] shadow-[inset_0_1px_0_rgba(255,255,255,0.18)]"
+ className="h-[36px] px-2 flex items-center justify-between gap-2 bg-[#202020] text-[#e5e5e5] select-none z-40 shrink-0"
>
- {/* Brand, Menus & Document Info */}
- <div className="flex items-center space-x-2.5 min-w-0">
- <div className="flex items-center" title="Old Studio">
- <div className="w-5 h-5 flex items-center justify-center">
- <img
- src="/app-icon.png"
- alt="Studio Logo"
- className="w-5 h-5 object-contain select-none pointer-events-none drop-shadow-xs"
- />
- </div>
- </div>
-
- <span className="text-[#3a3a3a]">|</span>
+ {/* Left: App Icon (Home Toggle) + Menu Bar */}
+ <div
+ className="flex items-center gap-1 shrink-0"
+ style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
+ >
+ <button
+ type="button"
+ onClick={() => onSelectAppView?.(appView === 'home' ? 'workspace' : 'home')}
+ title={appView === 'home' ? 'Return to Workspace' : 'Home & Recent Documents'}
+ className={`w-6 h-6 rounded flex items-center justify-center transition-colors cursor-pointer ${
+ appView === 'home'
+ ? 'bg-[#2c2c2c] text-[var(--accent)]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'
+ }`}
+ >
+ <img
+ src="/app-icon.png"
+ alt="Ink Studio"
+ className="w-3.5 h-3.5 object-contain pointer-events-none opacity-90"
+ />
+ </button>
- {/* Menu Bar Sections: File, Edit, Layer, View, Help */}
<MenuBar sections={menuSections} />
+ </div>
- {hasOpenDocument && (
- <>
- <span className="text-[#3a3a3a]">|</span>
-
- <div className="flex items-center space-x-2 truncate">
- <span className="text-[#f0f0f4] font-medium text-xs truncate max-w-[280px]" title={`${activeDocumentTitle || 'New canvas*'} (${dimensions.width}×${dimensions.height}px ${dimensions.dpi ? `${dimensions.dpi}dpi ` : ''}${formatZoomPercent(zoom)})`}>
- {activeDocumentTitle || 'New canvas*'} ({dimensions.width}×${dimensions.height}px {dimensions.dpi ? `${dimensions.dpi}dpi ` : ''}{formatZoomPercent(zoom)})
- </span>
-
- <span
- className={`text-[9px] px-1.5 py-0.5 rounded font-mono uppercase tracking-wider ${
- colorMode === 'monochrome'
- ? 'bg-amber-500/15 text-amber-300 border border-amber-500/30'
- : colorMode === 'grayscale'
- ? 'bg-slate-500/15 text-slate-300 border border-slate-500/30'
- : 'bg-emerald-500/15 text-emerald-300 border border-emerald-500/30'
- }`}
- title={`Active Canvas Color Mode: ${colorMode}`}
- >
- {colorMode === 'monochrome' ? 'Manga B&W' : colorMode}
- </span>
-
- {softProofSettings?.enabled && (
+ {/* Center: Consolidated Compact Document Tabs */}
+ <div
+ className="flex-1 min-w-0 flex items-center gap-1 overflow-x-auto no-scrollbar px-1"
+ style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
+ >
+ {documents.map((doc) => {
+ const isActive = doc.id === activeDocumentId && appView === 'workspace';
+ return (
+ <div
+ key={doc.id}
+ onClick={() => onSelectDocument?.(doc.id)}
+ onDoubleClick={(e) => handleStartRename(e, doc)}
+ title={`${doc.name} (${doc.dimensions.width}×${doc.dimensions.height}px)`}
+ className={`group relative h-6 flex items-center gap-1.5 pl-2.5 pr-1.5 rounded text-[11px] cursor-pointer shrink-0 transition-colors ${
+ isActive
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
+ >
+ {isActive && (
<span
- className="text-[9px] px-1.5 py-0.5 rounded font-mono uppercase tracking-wider bg-cyan-500/20 text-cyan-300 border border-cyan-500/30"
- title={`CMYK Soft Proofing Active (${softProofSettings.standard})`}
- >
- CMYK Proof
- </span>
+ className="w-1.5 h-1.5 rounded-full shrink-0"
+ style={{ backgroundColor: 'var(--accent)' }}
+ />
)}
- {softProofSettings?.gamutWarning && (
- <span
- className="text-[9px] px-1.5 py-0.5 rounded font-mono uppercase tracking-wider bg-amber-500/20 text-amber-300 border border-amber-500/30"
- title="Gamut Warning Overlay Active"
+ {editingId === doc.id ? (
+ <input
+ type="text"
+ value={editingName}
+ onChange={(e) => setEditingName(e.target.value)}
+ onBlur={() => handleFinishRename(doc.id)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') handleFinishRename(doc.id);
+ if (e.key === 'Escape') setEditingId(null);
+ }}
+ autoFocus
+ onClick={(e) => e.stopPropagation()}
+ className="bg-[#161616] text-[#e5e5e5] text-[11px] px-1 py-0.5 rounded w-24"
+ />
+ ) : (
+ <span className="truncate max-w-[130px]">{doc.name}</span>
+ )}
+
+ {onCloseDocument && (
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ onCloseDocument(doc.id);
+ }}
+ title="Close tab"
+ className={`w-4 h-4 rounded flex items-center justify-center transition-colors cursor-pointer ${
+ isActive
+ ? 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#161616]/50'
+ : 'opacity-0 group-hover:opacity-100 text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
>
- Gamut Warning
- </span>
+ <X className="w-2.5 h-2.5" />
+ </button>
)}
</div>
- </>
+ );
+ })}
+
+ {onNewDocument && (
+ <button
+ type="button"
+ onClick={onNewDocument}
+ title="New Canvas (Ctrl+N)"
+ className="w-6 h-6 rounded flex items-center justify-center shrink-0 text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"
+ >
+ <Plus className="w-3.5 h-3.5" />
+ </button>
)}
</div>
- {/* Action Tools & Zoom */}
- <div className="flex items-center space-x-2">
+ {/* Right: Mode Badges, Undo/Redo, Zoom Level, Settings & Window Controls */}
+ <div
+ className="flex items-center gap-1.5 shrink-0"
+ style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
+ >
+ {hasOpenDocument && colorMode !== 'color' && (
+ <span className="text-[10px] font-mono uppercase px-1.5 py-0.5 rounded bg-[#161616] text-[#8a8a8a]">
+ {colorMode === 'monochrome' ? '1-bit' : 'Gray'}
+ </span>
+ )}
+
+ {hasOpenDocument && softProofSettings?.enabled && (
+ <span className="text-[10px] font-mono uppercase px-1.5 py-0.5 rounded bg-[#161616] text-[var(--accent)]">
+ CMYK
+ </span>
+ )}
+
+ {hasOpenDocument && isRotated && (
+ <button
+ type="button"
+ onClick={onResetRotation}
+ title="Reset Canvas Rotation (Ctrl+Alt+0)"
+ className="h-6 px-1.5 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[11px] font-mono text-[#8a8a8a] hover:text-[#e5e5e5] flex items-center gap-1 transition-colors cursor-pointer"
+ >
+ <RotateCcw className="w-3 h-3" />
+ <span>{formatRotationDegrees(rotation)}</span>
+ </button>
+ )}
+
{/* Undo / Redo */}
- <div className="flex items-center rounded-[2px] p-0.5 space-x-1 bg-[#2c2c2f] border border-[#202022] shadow-[inset_0_1px_2px_rgba(0,0,0,0.5),0_1px_0_rgba(255,255,255,0.08)]">
+ <div className="flex items-center gap-0.5">
<button
+ type="button"
onClick={onUndo}
disabled={!canUndo}
title="Undo (Ctrl+Z)"
- className={`p-1 rounded-[2px] transition-colors ${
+ className={`w-6 h-6 rounded flex items-center justify-center transition-colors ${
canUndo
- ? 'text-[#d8d8dc] hover:text-white bg-gradient-to-b from-[#56565a] to-[#404043] hover:from-[#626266] hover:to-[#4a4a4d] border border-[#262628] shadow-[inset_0_1px_0_rgba(255,255,255,0.22),0_1px_1px_rgba(0,0,0,0.3)] active:brightness-90 cursor-pointer'
- : 'text-[#444444] cursor-not-allowed opacity-50'
+ ? 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer'
+ : 'text-[#8a8a8a]/25 cursor-not-allowed'
}`}
>
<Undo2 className="w-3.5 h-3.5" />
</button>
<button
+ type="button"
onClick={onRedo}
disabled={!canRedo}
title="Redo (Ctrl+Y)"
- className={`p-1 rounded-[2px] transition-colors ${
+ className={`w-6 h-6 rounded flex items-center justify-center transition-colors ${
canRedo
- ? 'text-[#d8d8dc] hover:text-white bg-gradient-to-b from-[#56565a] to-[#404043] hover:from-[#626266] hover:to-[#4a4a4d] border border-[#262628] shadow-[inset_0_1px_0_rgba(255,255,255,0.22),0_1px_1px_rgba(0,0,0,0.3)] active:brightness-90 cursor-pointer'
- : 'text-[#444444] cursor-not-allowed opacity-50'
+ ? 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer'
+ : 'text-[#8a8a8a]/25 cursor-not-allowed'
}`}
>
<Redo2 className="w-3.5 h-3.5" />
</button>
</div>
- {/* Zoom Controls */}
- <div className={`flex items-center space-x-1 rounded-[2px] px-1.5 py-0.5 bg-[#2c2c2f] border border-[#202022] shadow-[inset_0_1px_2px_rgba(0,0,0,0.5),0_1px_0_rgba(255,255,255,0.08)] ${
- !hasOpenDocument ? 'opacity-40 pointer-events-none' : ''
- }`}>
+ {/* Compact Zoom Control */}
+ <div
+ className={`h-6 flex items-center bg-[#161616] rounded px-0.5 ${
+ !hasOpenDocument ? 'opacity-40 pointer-events-none' : ''
+ }`}
+ >
<button
+ type="button"
onClick={onZoomOut}
- title="Zoom Out (Ctrl + Minus)"
- className="p-1 hover:text-white hover:bg-[#404044] rounded-[2px] text-[#888888] transition-colors cursor-pointer"
+ title="Zoom Out (Ctrl+-)"
+ className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"
>
- <ZoomOut className="w-3.5 h-3.5" />
+ <Minus className="w-3 h-3" />
</button>
<button
- onClick={onResetZoom}
- title="Reset Zoom & Center (Ctrl + 0)"
- className="font-mono text-xs px-1.5 text-[#cccccc] hover:text-white hover:bg-[#404044] rounded-[2px] transition-colors cursor-pointer"
+ type="button"
+ onClick={() => onResetZoom()}
+ title="Reset Zoom & Center (Ctrl+0)"
+ className="h-5 px-1.5 rounded font-mono text-[11px] text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer min-w-[42px] text-center"
>
{formatZoomPercent(zoom)}
</button>
<button
+ type="button"
onClick={onZoomIn}
- title="Zoom In (Ctrl + Plus)"
- className="p-1 hover:text-white hover:bg-[#404044] rounded-[2px] text-[#888888] transition-colors cursor-pointer"
+ title="Zoom In (Ctrl++)"
+ className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"
>
- <ZoomIn className="w-3.5 h-3.5" />
+ <Plus className="w-3 h-3" />
</button>
+ </div>
+
+ {/* Collab Session Button */}
+ {onOpenCollabModal && (
<button
- onClick={onResetZoom}
- title="Reset to 100% & Center (Ctrl + 0)"
- className="p-1 hover:text-white hover:bg-[#404044] rounded-[2px] text-[#888888] transition-colors ml-0.5 cursor-pointer"
+ type="button"
+ onClick={onOpenCollabModal}
+ title={isCollabConnected ? `Collab (${collabPeerCount} online)` : 'Collaborative Session'}
+ className={`h-6 px-1.5 rounded flex items-center gap-1 text-[11px] transition-colors cursor-pointer ${
+ isCollabConnected
+ ? 'bg-[#2c2c2c] text-[var(--accent)]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'
+ }`}
>
- <RotateCcw className="w-3 h-3" />
+ <Users className="w-3.5 h-3.5" />
+ {isCollabConnected && <span className="font-mono text-[10px]">{collabPeerCount}</span>}
</button>
- </div>
+ )}
- {/* Rotation Controls */}
- <div className={`flex items-center space-x-1 rounded-[2px] px-1.5 py-0.5 bg-[#2c2c2f] border border-[#202022] shadow-[inset_0_1px_2px_rgba(0,0,0,0.5),0_1px_0_rgba(255,255,255,0.08)] ${
- !hasOpenDocument ? 'opacity-40 pointer-events-none' : ''
- }`}>
- <RotateCw className="w-3.5 h-3.5 text-[#888888] ml-0.5" />
+ {/* Settings Button */}
+ {onOpenSettings && (
<button
- onClick={onResetRotation}
- onDoubleClick={onResetRotation}
- title="Canvas Rotation (Double-click or Ctrl+Alt+0 to Reset 0°)"
- className="font-mono text-xs px-1.5 text-[#cccccc] hover:text-white hover:bg-[#404044] rounded-[2px] transition-colors cursor-pointer"
+ type="button"
+ onClick={onOpenSettings}
+ title="Preferences (Ctrl+,)"
+ className="w-6 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"
>
- {formatRotationDegrees(rotation)}
+ <Settings className="w-3.5 h-3.5" />
</button>
- {Math.abs(rotation % 360) > 0.05 && (
- <button
- onClick={onResetRotation}
- title="Reset Rotation to 0° (Ctrl+Alt+0)"
- className="p-1 hover:text-white hover:bg-[#404044] rounded-[2px] text-[#888888] transition-colors ml-0.5 cursor-pointer"
- >
- <RotateCcw className="w-3 h-3" />
- </button>
- )}
- </div>
-
- <span className="text-[#3a3a3a]">|</span>
-
- {/* Multiplayer Host / Connection Indicator */}
- <button
- onClick={onOpenCollabModal}
- className={`flex items-center space-x-1.5 px-2.5 py-1 rounded-[3px] text-xs font-medium transition-colors cursor-pointer ${
- isCollabConnected
- ? 'bg-emerald-500/20 border border-emerald-500/40 text-emerald-300 hover:bg-emerald-500/30 shadow-xs'
- : 'bg-gradient-to-b from-[#525255] to-[#404043] border border-[#28282a] text-[#cccccc] hover:text-white shadow-[inset_0_1px_0_rgba(255,255,255,0.18)]'
- }`}
- title={isCollabConnected ? `Collaborative Room (${collabPeerCount} online)` : 'Start Collaborative Session (Host)'}
- >
- {isCollabConnected ? (
- <>
- <span className="w-2 h-2 rounded-full bg-emerald-400 animate-pulse" />
- <span>{collabPeerCount} online</span>
- </>
- ) : (
- <>
- <Users className="w-3.5 h-3.5 text-[#888888]" />
- <span>Collab</span>
- </>
- )}
- </button>
+ )}
- {/* Desktop Native Window Controls (Minimize, Maximize, Close) */}
<WindowControls themePreset={themePreset} />
</div>
</header>
-
);
});
Header.displayName = 'Header';
-
diff --git a/src/components/LeftPanel.tsx b/src/components/LeftPanel.tsx
index e4d8b7a..2a78928 100644
--- a/src/components/LeftPanel.tsx
+++ b/src/components/LeftPanel.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useRef, useEffect } from 'react';
+import React, { useState, useRef, useEffect, useCallback } from 'react';
import {
Paintbrush,
Pencil,
@@ -8,16 +8,10 @@ import {
ArrowLeftRight,
ChevronDown,
ChevronRight,
- Activity,
- Sparkles,
- X,
- LayoutList,
Plus,
Trash2,
Loader2,
FolderDown,
- Zap,
- Droplets,
Palette,
Square,
BoxSelect,
@@ -27,20 +21,15 @@ import {
Frame,
Scaling,
Pipette,
- Move,
Maximize2,
Minimize2,
- RotateCw,
RotateCcw,
- Undo2,
- CornerUpLeft,
- CornerUpRight,
Wand2,
PenTool,
Feather,
MessageSquare,
Spline,
- Shuffle,
+ Sparkles,
} from 'lucide-react';
import {
ToolType,
@@ -57,25 +46,27 @@ import {
WandSettings,
BalloonSettings,
VectorEditSettings,
+ CspAngleDynamicsMode,
+ CspBlendTipsMode,
+ CspPaperTextureMode,
+ CspTipFlipMode,
+ CspTaperSettings,
+ CspSpraySettings,
} from '../types/editor';
import { LiquifyIcon } from './LiquifyIcon';
-import { PENCIL_CONFIGS, PencilGrade } from '../utils/pencilEngine';
-import { BrushPreview } from './BrushPreview';
import { parseSutFile } from '../utils/sutParser';
-import { WebGlBrushEngine } from '../utils/webglBrushEngine';
import {
loadCustomBrushes,
+ getCachedCustomBrushes,
saveCustomBrush,
+ saveCustomBrushDebounced,
deleteCustomBrush,
- getPreloadedTipImage,
preloadTipImage,
prepareBrushSettingsForCsp,
+ CUSTOM_BRUSHES_CHANGED_EVENT,
} from '../utils/brushStorage';
-import {
- BUILTIN_BRUSHES,
- BrushCategory,
-} from '../utils/presetBrushes';
-import { BrushSizePalette } from './BrushSizePalette';
+import { resolveBrushTipImage } from '../utils/brushOutline';
+import { BUILTIN_BRUSHES, BrushCategory } from '../utils/presetBrushes';
import {
getEffectiveBrushSettings,
getSavedBrushSettings,
@@ -83,6 +74,8 @@ import {
saveActivePresetId,
ERASER_PRESET_ID,
} from '../utils/brushPresetManager';
+import { renderBrushStrokePreview } from '../utils/brushPreview';
+import { CSP_PRESSURE_CURVE_PRESETS } from '../engine/CspBrushEngine';
interface LeftPanelProps {
currentTool: ToolType;
@@ -126,6 +119,74 @@ interface LeftPanelProps {
onInvertSelection?: () => void;
}
+interface CompactSliderProps {
+ label: string;
+ valueLabel: string;
+ min: number;
+ max: number;
+ step?: number;
+ value: number;
+ onChange: (val: number) => void;
+}
+
+const CompactSlider: React.FC<CompactSliderProps> = ({
+ label,
+ valueLabel,
+ min,
+ max,
+ step = 1,
+ value,
+ onChange,
+}) => (
+ <div className="space-y-1">
+ <div className="flex items-center justify-between text-[11px]">
+ <span className="text-[#8a8a8a] truncate">{label}</span>
+ <span className="font-mono text-[10px] text-[#e5e5e5] ml-1 shrink-0">{valueLabel}</span>
+ </div>
+ <input
+ type="range"
+ min={min}
+ max={max}
+ step={step}
+ value={value}
+ onChange={(e) => onChange(Number(e.target.value))}
+ className="w-full"
+ />
+ </div>
+);
+
+const LIQUIFY_MODES: Array<{ id: LiquifyMode; label: string }> = [
+ { id: 'push', label: 'Push' },
+ { id: 'expand', label: 'Expand' },
+ { id: 'pinch', label: 'Pinch' },
+ { id: 'push-left', label: 'Push Left' },
+ { id: 'push-right', label: 'Push Right' },
+ { id: 'twirl-cw', label: 'Twirl CW' },
+ { id: 'twirl-ccw', label: 'Twirl CCW' },
+ { id: 'reconstruct', label: 'Reconstruct' },
+];
+
+type InspectorAccordionId = 'ink' | 'tip' | 'stroke' | 'mixing' | 'texture' | 'dynamics';
+
+const DEFAULT_TAPER: CspTaperSettings = {
+ useIn: false,
+ inLength: 24,
+ inRatio: 0.9,
+ useOut: false,
+ outLength: 32,
+ outRatio: 0.9,
+ startingSharpness: 0.85,
+ endingSharpness: 0.85,
+ affectSize: true,
+};
+
+const DEFAULT_SPRAY: CspSpraySettings = {
+ enabled: false,
+ size: 4,
+ density: 12,
+ bias: 0.5,
+};
+
export const LeftPanel: React.FC<LeftPanelProps> = React.memo(({
currentTool,
onSelectTool,
@@ -146,10 +207,8 @@ export const LeftPanel: React.FC<LeftPanelProps> = React.memo(({
onUpdateTextSettings,
frameSettings,
onUpdateFrameSettings,
- hasSelection: _hasSelection,
onDeselect,
onTransformSelection,
- onFillScreentone: _onFillScreentone,
liquifySettings,
onUpdateLiquifySettings,
balloonSettings,
@@ -164,38 +223,24 @@ export const LeftPanel: React.FC<LeftPanelProps> = React.memo(({
onFeatherSelection,
onInvertSelection,
}) => {
- const [showAdvanced, setShowAdvanced] = useState(false);
- const [showDynamics, setShowDynamics] = useState(false);
-
- const [customBrushes, setCustomBrushes] = useState<CspBrush[]>([]);
+ const [openAccordion, setOpenAccordion] = useState<InspectorAccordionId | null>(null);
+ const [customBrushes, setCustomBrushes] = useState<CspBrush[]>(() => getCachedCustomBrushes());
const [isImportingSut, setIsImportingSut] = useState(false);
- const [importStatus, setImportStatus] = useState<string | null>(null);
const [isDraggingFileOver, setIsDraggingFileOver] = useState(false);
- const sutInputRef = useRef<HTMLInputElement>(null);
- const gpuInfo = useRef(WebGlBrushEngine.getInstance().getGpuInfo()).current;
-
const [selectedCategory, setSelectedCategory] = useState<'all' | BrushCategory | 'csp'>('all');
- const [bottomTab, setBottomTab] = useState<'settings' | 'size'>(() => {
- try {
- const saved = localStorage.getItem('sora_paint_left_bottom_tab');
- return saved === 'size' ? 'size' : 'settings';
- } catch {
- return 'settings';
- }
- });
+ const sutInputRef = useRef<HTMLInputElement>(null);
+ const previewCanvasRef = useRef<HTMLCanvasElement>(null);
- const handleSelectBottomTab = (tab: 'settings' | 'size') => {
- setBottomTab(tab);
- try {
- localStorage.setItem('sora_paint_left_bottom_tab', tab);
- } catch {}
- };
+ const [isDraggingWidth, setIsDraggingWidth] = useState(false);
+ const dragStartXRef = useRef(0);
+ const dragStartWidthRef = useRef(width);
- useEffect(() => {
+ const syncCustomBrushes = useCallback(() => {
loadCustomBrushes().then((brushes) => {
setCustomBrushes(brushes);
for (const b of brushes) {
if (b.tipDataUrl) preloadTipImage(b.tipDataUrl).catch(() => {});
+ if (b.secondaryTipDataUrl) preloadTipImage(b.secondaryTipDataUrl).catch(() => {});
if (b.subTips) {
for (const st of b.subTips) {
if (st.dataUrl) preloadTipImage(st.dataUrl).catch(() => {});
@@ -206,11 +251,84 @@ export const LeftPanel: React.FC<LeftPanelProps> = React.memo(({
});
}, []);
+ useEffect(() => {
+ syncCustomBrushes();
+ const handleChanged = () => {
+ setCustomBrushes([...getCachedCustomBrushes()]);
+ };
+ window.addEventListener(CUSTOM_BRUSHES_CHANGED_EVENT, handleChanged);
+ return () => window.removeEventListener(CUSTOM_BRUSHES_CHANGED_EVENT, handleChanged);
+ }, [syncCustomBrushes]);
+
+ useEffect(() => {
+ if (!isDraggingWidth) return;
+ const handlePointerMove = (e: PointerEvent) => {
+ const delta = e.clientX - dragStartXRef.current;
+ const newWidth = Math.max(128, Math.min(300, Math.round(dragStartWidthRef.current + delta)));
+ onWidthChange(newWidth);
+ };
+ const handlePointerUp = () => setIsDraggingWidth(false);
+ window.addEventListener('pointermove', handlePointerMove);
+ window.addEventListener('pointerup', handlePointerUp);
+ return () => {
+ window.removeEventListener('pointermove', handlePointerMove);
+ window.removeEventListener('pointerup', handlePointerUp);
+ };
+ }, [isDraggingWidth, onWidthChange]);
+
+ const isBrushOrEraser = currentTool === 'brush' || currentTool === 'eraser';
+
+ // Coalesce live S-curve stroke preview redraws to a single animation frame
+ useEffect(() => {
+ if (isHidden || !isBrushOrEraser) return;
+ const canvas = previewCanvasRef.current;
+ if (!canvas) return;
+ const cssWidth = Math.max(96, width - 16);
+ const cssHeight = 32;
+ const rafId = requestAnimationFrame(() => {
+ const resolvedTip = resolveBrushTipImage(brushSettings);
+ renderBrushStrokePreview(
+ canvas,
+ cssWidth,
+ cssHeight,
+ {
+ preset: brushSettings.preset,
+ size: brushSettings.size,
+ flow: brushSettings.flow,
+ opacity: brushSettings.opacity,
+ grain: brushSettings.grain,
+ hardness: brushSettings.hardness,
+ spacing: brushSettings.spacing,
+ minSizeFactor: brushSettings.minSizeFactor,
+ usePressure: brushSettings.usePressure,
+ color: currentTool === 'eraser' ? '#e5e5e5' : '#ececec',
+ backgroundColor: '#161616',
+ tool: currentTool === 'eraser' ? 'eraser' : 'brush',
+ customTipImage: resolvedTip,
+ customTipAngle: brushSettings.customTipAngle,
+ thickness: brushSettings.thickness,
+ thicknessVertical: brushSettings.thicknessVertical,
+ flipH: brushSettings.flipH,
+ flipV: brushSettings.flipV,
+ blendTipsMode: brushSettings.blendTipsMode,
+ adjustDensityByGap: brushSettings.adjustDensityByGap,
+ antiAlias: brushSettings.antiAlias,
+ pressureCurve: brushSettings.pressureCurve,
+ spray: brushSettings.spray,
+ colorMixing: brushSettings.colorMixing,
+ amountOfPaint: brushSettings.amountOfPaint,
+ densityOfPaint: brushSettings.densityOfPaint,
+ colorStretch: brushSettings.colorStretch,
+ wetEdge: brushSettings.wetEdge,
+ },
+ true
+ );
+ });
+ return () => cancelAnimationFrame(rafId);
+ }, [isHidden, isBrushOrEraser, width, currentTool, brushSettings]);
+
const activePreset: BrushPresetId = brushSettings.preset || 'pencil-2b';
- const isPencilActive = currentTool === 'brush' && activePreset.startsWith('pencil');
- const activePencilConfig = isPencilActive ? PENCIL_CONFIGS[activePreset as PencilGrade] : null;
const activeBuiltinBrush = BUILTIN_BRUSHES.find((b) => b.id === activePreset);
-
const isCustomBrushActive =
currentTool === 'brush' &&
(activePreset.startsWith('csp-') || (Boolean(brushSettings.customTipDataUrl) && !activeBuiltinBrush));
@@ -218,60 +336,68 @@ export const LeftPanel: React.FC<LeftPanelProps> = React.memo(({
? customBrushes.find((b) => b.id === activePreset)
: null;
- const activeToolLabel = (() => {
- if (currentTool === 'eraser') return 'Eraser';
- if (currentTool === 'pipette') return 'Eyedropper';
- if (currentTool === 'select-rect') return 'Marquee';
- if (currentTool === 'select-lasso') return 'Lasso';
- if (currentTool === 'select-wand') return 'Magic Wand';
- if (currentTool === 'select-pen') return 'Selection Pen';
- if (currentTool === 'select-eraser') return 'Selection Eraser';
- if (currentTool === 'fill') return 'Fill';
- if (currentTool === 'text') return 'Text';
- if (currentTool === 'frame') return 'Frame Border';
- if (currentTool === 'transform') return 'Transform';
- if (currentTool === 'liquify') return 'Liquify';
- return isPencilActive ? 'Pencil' : brushSettings.brushName || activeCustomBrush?.name || activeBuiltinBrush?.name || 'Drawing';
- })();
-
const handleUpdateBrushSettings = (newSettings: Partial<BrushSettings>) => {
onUpdateBrushSettings(newSettings);
if (isCustomBrushActive && activeCustomBrush) {
const updatedBrush: CspBrush = {
...activeCustomBrush,
- size: newSettings.size !== undefined ? newSettings.size : activeCustomBrush.size,
- opacity: newSettings.opacity !== undefined ? newSettings.opacity : activeCustomBrush.opacity,
- flow: newSettings.flow !== undefined ? newSettings.flow : activeCustomBrush.flow,
- spacing: newSettings.spacing !== undefined ? newSettings.spacing : activeCustomBrush.spacing,
- hardness: newSettings.hardness !== undefined ? newSettings.hardness : activeCustomBrush.hardness,
- stabilization: newSettings.stabilization !== undefined ? newSettings.stabilization : activeCustomBrush.stabilization,
- dynamics: newSettings.dynamics !== undefined ? newSettings.dynamics : activeCustomBrush.dynamics,
+ size: newSettings.size ?? activeCustomBrush.size,
+ opacity: newSettings.opacity ?? activeCustomBrush.opacity,
+ flow: newSettings.flow ?? activeCustomBrush.flow,
+ brushDensity: newSettings.brushDensity ?? newSettings.flow ?? activeCustomBrush.brushDensity,
+ adjustDensityByGap: newSettings.adjustDensityByGap ?? activeCustomBrush.adjustDensityByGap,
+ blendTipsMode: newSettings.blendTipsMode ?? activeCustomBrush.blendTipsMode,
+ spacing: newSettings.spacing ?? activeCustomBrush.spacing,
+ hardness: newSettings.hardness ?? activeCustomBrush.hardness,
+ thickness: newSettings.thickness ?? activeCustomBrush.thickness,
+ thicknessVertical: newSettings.thicknessVertical ?? activeCustomBrush.thicknessVertical,
+ antiAlias: newSettings.antiAlias ?? activeCustomBrush.antiAlias,
+ stabilization: newSettings.stabilization ?? activeCustomBrush.stabilization,
+ postCorrection: newSettings.postCorrection ?? activeCustomBrush.postCorrection,
+ sharpCorners: newSettings.sharpCorners ?? activeCustomBrush.sharpCorners,
+ angle: newSettings.customTipAngle ?? activeCustomBrush.angle,
+ angleDynamics: newSettings.customTipAngleDynamics ?? activeCustomBrush.angleDynamics,
+ flipH: newSettings.flipH ?? activeCustomBrush.flipH,
+ flipV: newSettings.flipV ?? activeCustomBrush.flipV,
+ isRibbon: newSettings.isRibbon ?? activeCustomBrush.isRibbon,
+ usePressure: newSettings.usePressure ?? activeCustomBrush.usePressure,
+ useTilt: newSettings.useTilt ?? activeCustomBrush.useTilt,
+ useVelocity: newSettings.useVelocity ?? activeCustomBrush.useVelocity,
+ pressureCurve: newSettings.pressureCurve ?? activeCustomBrush.pressureCurve,
+ taper: newSettings.taper ?? activeCustomBrush.taper,
+ spray: newSettings.spray ?? activeCustomBrush.spray,
+ colorMixing: newSettings.colorMixing ?? activeCustomBrush.colorMixing,
+ mixingMode: newSettings.mixingMode ?? activeCustomBrush.mixingMode,
+ amountOfPaint: newSettings.amountOfPaint ?? activeCustomBrush.amountOfPaint,
+ densityOfPaint: newSettings.densityOfPaint ?? activeCustomBrush.densityOfPaint,
+ colorStretch: newSettings.colorStretch ?? activeCustomBrush.colorStretch,
+ wetEdge: newSettings.wetEdge ?? activeCustomBrush.wetEdge,
+ wetEdgeRadius: newSettings.wetEdgeRadius ?? activeCustomBrush.wetEdgeRadius,
+ textureDensity: newSettings.grain ?? activeCustomBrush.textureDensity,
+ paperTextureMode: newSettings.paperTextureMode ?? activeCustomBrush.paperTextureMode,
+ paperTextureScale: newSettings.paperTextureScale ?? activeCustomBrush.paperTextureScale,
+ paperTextureInverted: newSettings.paperTextureInverted ?? activeCustomBrush.paperTextureInverted,
+ dynamics: newSettings.dynamics ?? activeCustomBrush.dynamics,
};
setCustomBrushes((prev) => prev.map((b) => (b.id === updatedBrush.id ? updatedBrush : b)));
- saveCustomBrush(updatedBrush).catch(() => {});
+ saveCustomBrushDebounced(updatedBrush);
}
};
const handleUpdateDynamics = (patch: Partial<BrushDynamics>) => {
const cur = brushSettings.dynamics || DEFAULT_BRUSH_DYNAMICS;
- handleUpdateBrushSettings({
- dynamics: {
- ...cur,
- ...patch,
- },
- });
+ handleUpdateBrushSettings({ dynamics: { ...cur, ...patch } });
};
- const isDynamicsActive = Boolean(
- brushSettings.dynamics &&
- (brushSettings.dynamics.sizeJitter > 0 ||
- brushSettings.dynamics.angleJitter > 0 ||
- brushSettings.dynamics.roundnessJitter > 0 ||
- brushSettings.dynamics.scatter > 0 ||
- (brushSettings.dynamics.count ?? 1) > 1 ||
- brushSettings.dynamics.flowJitter > 0 ||
- brushSettings.dynamics.colorJitterEnabled)
- );
+ const handleUpdateTaper = (patch: Partial<CspTaperSettings>) => {
+ const cur = brushSettings.taper || DEFAULT_TAPER;
+ handleUpdateBrushSettings({ taper: { ...cur, ...patch } });
+ };
+
+ const handleUpdateSpray = (patch: Partial<CspSpraySettings>) => {
+ const cur = brushSettings.spray || DEFAULT_SPRAY;
+ handleUpdateBrushSettings({ spray: { ...cur, ...patch } });
+ };
const handleSelectBrushPreset = (presetId: BrushPresetId) => {
onSelectTool('brush');
@@ -282,9 +408,14 @@ export const LeftPanel: React.FC<LeftPanelProps> = React.memo(({
customTipImage: undefined,
customTipAngle: 0,
customTipAngleDynamics: 'none',
+ flipH: 'none',
+ flipV: 'none',
+ isRibbon: false,
colorMixing: false,
wetEdge: 0,
grain: 0,
+ spray: undefined,
+ taper: undefined,
...effective,
preset: presetId,
});
@@ -304,32 +435,25 @@ export const LeftPanel: React.FC<LeftPanelProps> = React.memo(({
const handleImportSut = async (file: File) => {
setIsImportingSut(true);
- setImportStatus(`Importing ${file.name}...`);
try {
const buffer = await file.arrayBuffer();
const parsedBrush = await parseSutFile(buffer, file.name);
-
- // Clean out any previously imported brush with matching name or ID to avoid stale cache
const existing = customBrushes.filter(
(b) => b.name.toLowerCase() === parsedBrush.name.toLowerCase() || b.id === parsedBrush.id
);
for (const old of existing) {
await deleteCustomBrush(old.id).catch(() => {});
}
-
await saveCustomBrush(parsedBrush);
- setCustomBrushes((prev) => {
- const filtered = prev.filter(
+ setCustomBrushes((prev) => [
+ parsedBrush,
+ ...prev.filter(
(b) => b.name.toLowerCase() !== parsedBrush.name.toLowerCase() && b.id !== parsedBrush.id
- );
- return [parsedBrush, ...filtered];
- });
+ ),
+ ]);
await handleSelectCustomBrush(parsedBrush);
- setImportStatus(null);
} catch (err: any) {
- console.error('CSP brush import error:', err);
alert(err.message || 'Failed to import Clip Studio Paint brush file.');
- setImportStatus(null);
} finally {
setIsImportingSut(false);
}
@@ -346,2713 +470,1593 @@ export const LeftPanel: React.FC<LeftPanelProps> = React.memo(({
}
};
- // View mode for brushes list: 'preview' (shows authentic CSP S-curve stroke) or 'compact'
- const [brushViewMode, setBrushViewMode] = useState<'preview' | 'compact'>(() => {
- return (localStorage.getItem('sora_paint_brush_view_mode') as 'preview' | 'compact') || 'preview';
- });
-
- const toggleBrushViewMode = () => {
- setBrushViewMode((prev) => {
- const next = prev === 'preview' ? 'compact' : 'preview';
- localStorage.setItem('sora_paint_brush_view_mode', next);
- return next;
- });
- };
-
- // Live preview stroke color in Tool Settings: false = neutral white (CSP standard), true = primary color
- const [usePrimaryColorPreview, setUsePrimaryColorPreview] = useState(false);
-
- // Vertical split between Top (Brushes) and Bottom (Tool Settings)
- const [topHeight, setTopHeight] = useState<number>(() => {
- const saved = localStorage.getItem('sora_paint_left_top_height');
- return saved ? Number(saved) : 255;
- });
-
- // Dragging states for resizers
- const [isDraggingWidth, setIsDraggingWidth] = useState(false);
- const [isDraggingHeight, setIsDraggingHeight] = useState(false);
- const dragStartXRef = useRef(0);
- const dragStartWidthRef = useRef(width);
- const dragStartYRef = useRef(0);
- const dragStartHeightRef = useRef(topHeight);
-
- // Resize Width Handler (Right edge of LeftPanel)
- const handleWidthResizeMouseDown = (e: React.MouseEvent) => {
- e.preventDefault();
- setIsDraggingWidth(true);
- dragStartXRef.current = e.clientX;
- dragStartWidthRef.current = width;
- };
-
- useEffect(() => {
- if (!isDraggingWidth) return;
-
- const handlePointerMove = (e: PointerEvent) => {
- const delta = e.clientX - dragStartXRef.current;
- const newWidth = Math.max(180, Math.min(500, Math.round(dragStartWidthRef.current + delta)));
- onWidthChange(newWidth);
- };
-
- const handlePointerUp = () => {
- setIsDraggingWidth(false);
- };
-
- window.addEventListener('pointermove', handlePointerMove);
- window.addEventListener('pointerup', handlePointerUp);
- return () => {
- window.removeEventListener('pointermove', handlePointerMove);
- window.removeEventListener('pointerup', handlePointerUp);
- };
- }, [isDraggingWidth, onWidthChange]);
-
- // Resize Height Handler (Divider between Top Brushes and Bottom Tool Settings)
- const handleHeightResizeMouseDown = (e: React.MouseEvent) => {
- e.preventDefault();
- setIsDraggingHeight(true);
- dragStartYRef.current = e.clientY;
- dragStartHeightRef.current = topHeight;
+ const toggleAccordion = (id: InspectorAccordionId) => {
+ setOpenAccordion((prev) => (prev === id ? null : id));
};
- useEffect(() => {
- if (!isDraggingHeight) return;
-
- const handlePointerMove = (e: PointerEvent) => {
- const delta = e.clientY - dragStartYRef.current;
- const newHeight = Math.max(80, Math.min(450, Math.round(dragStartHeightRef.current + delta)));
- setTopHeight(newHeight);
- localStorage.setItem('sora_paint_left_top_height', String(newHeight));
- };
-
- const handlePointerUp = () => {
- setIsDraggingHeight(false);
- };
-
- window.addEventListener('pointermove', handlePointerMove);
- window.addEventListener('pointerup', handlePointerUp);
- return () => {
- window.removeEventListener('pointermove', handlePointerMove);
- window.removeEventListener('pointerup', handlePointerUp);
- };
- }, [isDraggingHeight]);
-
- const isBrushOrEraser = currentTool === 'brush' || currentTool === 'eraser';
-
- const renderToolSettings = () => {
+ const toolItems: Array<{
+ id: ToolType;
+ label: string;
+ icon: React.ReactNode;
+ dividerAfter?: boolean;
+ onClick?: () => void;
+ }> = [
+ {
+ id: 'brush',
+ label: 'Brush (B)',
+ icon: <Paintbrush className="w-3.5 h-3.5" />,
+ onClick: () => {
+ onSelectTool('brush');
+ if (isHidden) onToggleHidden();
+ },
+ },
+ { id: 'eraser', label: 'Eraser (E)', icon: <Eraser className="w-3.5 h-3.5" /> },
+ { id: 'pipette', label: 'Eyedropper (I)', icon: <Pipette className="w-3.5 h-3.5" /> },
+ {
+ id: 'liquify',
+ label: 'Liquify (J)',
+ icon: <LiquifyIcon className="w-3.5 h-3.5" />,
+ dividerAfter: true,
+ },
+ {
+ id: 'transform',
+ label: 'Transform (Ctrl+T)',
+ icon: <Scaling className="w-3.5 h-3.5" />,
+ onClick: () => {
+ onSelectTool('transform');
+ onTransformSelection?.();
+ },
+ },
+ { id: 'select-rect', label: 'Marquee (M)', icon: <BoxSelect className="w-3.5 h-3.5" /> },
+ { id: 'select-lasso', label: 'Lasso (L)', icon: <Lasso className="w-3.5 h-3.5" /> },
+ { id: 'select-wand', label: 'Magic Wand (W)', icon: <Wand2 className="w-3.5 h-3.5" /> },
+ {
+ id: 'select-pen',
+ label: 'Selection Pen',
+ icon: <PenTool className="w-3.5 h-3.5" />,
+ dividerAfter: true,
+ },
+ { id: 'fill', label: 'Fill (G)', icon: <PaintBucket className="w-3.5 h-3.5" /> },
+ { id: 'text', label: 'Text (T)', icon: <Type className="w-3.5 h-3.5" /> },
+ { id: 'frame', label: 'Frame Border (F)', icon: <Frame className="w-3.5 h-3.5" /> },
+ { id: 'balloon', label: 'Speech Balloon', icon: <MessageSquare className="w-3.5 h-3.5" /> },
+ { id: 'vector-edit', label: 'Correct Line', icon: <Spline className="w-3.5 h-3.5" /> },
+ ];
+
+ const renderContextualToolPanel = () => {
if (currentTool === 'fill') {
+ const method = fillSettings?.method ?? 'refer-all';
return (
- <div className="flex-1 flex flex-col overflow-y-auto">
- <div className="h-9 px-3 flex items-center justify-between border-b border-[#2b2d31] bg-[#1a1b1e] shrink-0">
- <div className="flex items-center space-x-2">
- <PaintBucket className="w-4 h-4 text-amber-400" />
- <span className="text-xs font-semibold text-white">Fill Tool (G)</span>
- </div>
- <button onClick={onToggleHidden} className="p-1 text-[#828690] hover:text-rose-400 rounded cursor-pointer">
- <X className="w-3.5 h-3.5" />
- </button>
+ <div className="p-2.5 space-y-3 overflow-y-auto flex-1">
+ <div className="text-[11px] font-medium text-[#e5e5e5]">Fill</div>
+ <div className="space-y-1">
+ {(
+ [
+ { id: 'refer-all', label: 'All Visible' },
+ { id: 'refer-active', label: 'Active Layer' },
+ { id: 'refer-reference', label: 'Reference Layer' },
+ { id: 'lasso', label: 'Lasso Fill' },
+ ] as const
+ ).map((m) => (
+ <button
+ key={m.id}
+ type="button"
+ onClick={() => onUpdateFillSettings?.({ method: m.id })}
+ className={`w-full px-2 py-1 rounded text-left text-[11px] transition-colors cursor-pointer ${
+ method === m.id
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
+ >
+ {m.label}
+ </button>
+ ))}
</div>
-
- <div className="p-3 space-y-4">
- <div>
- <label className="text-[11px] font-medium text-[#aaaaaa] block mb-1.5">Fill Method:</label>
- <div className="space-y-1">
- <button
- onClick={() => onUpdateFillSettings?.({ method: 'refer-all' })}
- className={`w-full px-2.5 py-1.5 rounded text-left text-xs transition-colors cursor-pointer flex items-center justify-between ${
- fillSettings?.method === 'refer-all'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] font-medium'
- : 'bg-[#202226] text-[#aaaaaa] hover:bg-[#282a2e] hover:text-white border border-transparent'
- }`}
- >
- <span>Refer to Other Layers</span>
- <span className="text-[10px] text-[#777777]">All Visible</span>
- </button>
-
- <button
- onClick={() => onUpdateFillSettings?.({ method: 'refer-active' })}
- className={`w-full px-2.5 py-1.5 rounded text-left text-xs transition-colors cursor-pointer flex items-center justify-between ${
- fillSettings?.method === 'refer-active'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] font-medium'
- : 'bg-[#202226] text-[#aaaaaa] hover:bg-[#282a2e] hover:text-white border border-transparent'
- }`}
- >
- <span>Refer Only to Editing Layer</span>
- <span className="text-[10px] text-[#777777]">Editing Layer</span>
- </button>
-
- <button
- onClick={() => onUpdateFillSettings?.({ method: 'lasso' })}
- className={`w-full px-2.5 py-1.5 rounded text-left text-xs transition-colors cursor-pointer flex items-center justify-between ${
- fillSettings?.method === 'lasso'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] font-medium'
- : 'bg-[#202226] text-[#aaaaaa] hover:bg-[#282a2e] hover:text-white border border-transparent'
- }`}
- >
- <span>Lasso Fill</span>
- <span className="text-[10px] text-[#777777]">Enclose & Fill</span>
- </button>
- </div>
- </div>
-
- {fillSettings?.method !== 'lasso' && (
- <div className="space-y-1.5">
- <div className="flex items-center justify-between">
- <label className="text-[11px] font-medium text-[#aaaaaa]">Color Tolerance:</label>
- <span className="text-xs font-mono text-cyan-400">{fillSettings?.tolerance ?? 32}</span>
- </div>
+ {method !== 'lasso' && (
+ <>
+ <CompactSlider
+ label="Tolerance"
+ valueLabel={`${fillSettings?.tolerance ?? 32}`}
+ min={0}
+ max={100}
+ value={fillSettings?.tolerance ?? 32}
+ onChange={(v) => onUpdateFillSettings?.({ tolerance: v })}
+ />
+ <CompactSlider
+ label="Close Gap"
+ valueLabel={`${fillSettings?.closeGap ?? 0}px`}
+ min={0}
+ max={20}
+ value={fillSettings?.closeGap ?? 0}
+ onChange={(v) => onUpdateFillSettings?.({ closeGap: v })}
+ />
+ <CompactSlider
+ label="Area Scaling"
+ valueLabel={`${(fillSettings?.areaScale ?? 0) > 0 ? '+' : ''}${fillSettings?.areaScale ?? 0}px`}
+ min={-20}
+ max={20}
+ value={fillSettings?.areaScale ?? 0}
+ onChange={(v) => onUpdateFillSettings?.({ areaScale: v })}
+ />
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Anti-Alias</span>
<input
- type="range"
- min={0}
- max={100}
- value={fillSettings?.tolerance ?? 32}
- onChange={(e) => onUpdateFillSettings?.({ tolerance: Number(e.target.value) })}
- className="w-full accent-cyan-400"
+ type="checkbox"
+ checked={fillSettings?.antiAlias ?? true}
+ onChange={(e) => onUpdateFillSettings?.({ antiAlias: e.target.checked })}
/>
- </div>
- )}
-
- <div className="pt-2 border-t border-[#26282c] flex items-center space-x-2">
- <div className="w-5 h-5 rounded border border-[#44464c]" style={{ backgroundColor: primaryColor }} />
- <span className="text-[11px] text-[#aaaaaa]">Fill Color: {primaryColor}</span>
- </div>
- </div>
+ </label>
+ </>
+ )}
</div>
);
}
- if (currentTool === 'frame') {
+ if (currentTool === 'liquify') {
+ const activeMode = liquifySettings?.mode ?? 'push';
return (
- <div className="flex-1 flex flex-col overflow-y-auto">
- <div className="h-9 px-3 flex items-center justify-between border-b border-[#2b2d31] bg-[#1a1b1e] shrink-0">
- <div className="flex items-center space-x-2">
- <Frame className="w-4 h-4 text-cyan-400" />
- <span className="text-xs font-semibold text-white">Frame Border Tool (F)</span>
- </div>
- <button onClick={onToggleHidden} className="p-1 text-[#828690] hover:text-rose-400 rounded cursor-pointer">
- <X className="w-3.5 h-3.5" />
- </button>
- </div>
-
- <div className="p-3 space-y-4">
- <div className="space-y-1.5">
- <div className="flex items-center justify-between">
- <label className="text-[11px] font-medium text-[#aaaaaa]">Frame Thickness (1 - 100):</label>
- <input
- type="number"
- min={1}
- max={100}
- value={frameSettings?.thickness ?? 4}
- onChange={(e) =>
- onUpdateFrameSettings?.({
- thickness: Math.max(1, Math.min(100, Number(e.target.value) || 1)),
- })
- }
- className="w-14 bg-[#141517] text-white text-right px-1.5 py-0.5 rounded border border-[#383a40] text-xs font-mono"
- />
- </div>
- <input
- type="range"
- min={1}
- max={100}
- value={frameSettings?.thickness ?? 4}
- onChange={(e) => onUpdateFrameSettings?.({ thickness: Number(e.target.value) })}
- className="w-full accent-cyan-400"
- />
- </div>
-
- <div className="space-y-1.5">
- <label className="text-[11px] font-medium text-[#aaaaaa] block mb-1">Frame Interior:</label>
- <div className="grid grid-cols-2 gap-1.5">
- <button
- onClick={() => onUpdateFrameSettings?.({ fillBackground: true })}
- className={`py-1.5 px-2 rounded text-xs text-center transition-colors cursor-pointer ${
- frameSettings?.fillBackground
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] font-medium'
- : 'bg-[#202226] text-[#aaaaaa] hover:bg-[#282a2e] hover:text-white border border-transparent'
- }`}
- >
- White Fill
- </button>
- <button
- onClick={() => onUpdateFrameSettings?.({ fillBackground: false })}
- className={`py-1.5 px-2 rounded text-xs text-center transition-colors cursor-pointer ${
- !frameSettings?.fillBackground
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] font-medium'
- : 'bg-[#202226] text-[#aaaaaa] hover:bg-[#282a2e] hover:text-white border border-transparent'
- }`}
- >
- Transparent
- </button>
- </div>
- </div>
-
-
- <div className="pt-2 border-t border-[#26282c] flex items-center space-x-2">
- <div className="w-5 h-5 rounded border border-[#44464c]" style={{ backgroundColor: primaryColor }} />
- <span className="text-[11px] text-[#aaaaaa]">Border Color: {primaryColor}</span>
- </div>
+ <div className="p-2 space-y-3 overflow-y-auto flex-1">
+ <div className="px-0.5 text-[11px] font-medium text-[#e5e5e5]">Liquify</div>
+ <div className="space-y-0.5">
+ {LIQUIFY_MODES.map((sub) => (
+ <button
+ key={sub.id}
+ type="button"
+ onClick={() => onUpdateLiquifySettings?.({ mode: sub.id })}
+ className={`w-full px-2 py-1 rounded text-left text-[11px] transition-colors cursor-pointer ${
+ activeMode === sub.id
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
+ >
+ {sub.label}
+ </button>
+ ))}
</div>
+ <CompactSlider
+ label="Size"
+ valueLabel={`${liquifySettings?.size ?? 80}px`}
+ min={4}
+ max={500}
+ value={liquifySettings?.size ?? 80}
+ onChange={(v) => onUpdateLiquifySettings?.({ size: v })}
+ />
+ <CompactSlider
+ label="Strength"
+ valueLabel={`${liquifySettings?.strength ?? 50}%`}
+ min={1}
+ max={100}
+ value={liquifySettings?.strength ?? 50}
+ onChange={(v) => onUpdateLiquifySettings?.({ strength: v })}
+ />
+ <CompactSlider
+ label="Hardness"
+ valueLabel={`${liquifySettings?.hardness ?? 50}%`}
+ min={0}
+ max={100}
+ value={liquifySettings?.hardness ?? 50}
+ onChange={(v) => onUpdateLiquifySettings?.({ hardness: v })}
+ />
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Pressure</span>
+ <input
+ type="checkbox"
+ checked={liquifySettings?.usePressure ?? true}
+ onChange={(e) => onUpdateLiquifySettings?.({ usePressure: e.target.checked })}
+ />
+ </label>
</div>
);
}
- if (currentTool === 'balloon') {
+ if (
+ currentTool === 'select-rect' ||
+ currentTool === 'select-lasso' ||
+ currentTool === 'select-wand' ||
+ currentTool === 'select-pen' ||
+ currentTool === 'select-eraser'
+ ) {
+ const activeWand = wandSettings || {
+ tolerance: 32,
+ contiguous: true,
+ antiAlias: true,
+ referMode: 'active' as const,
+ };
return (
- <div className="flex-1 flex flex-col overflow-y-auto">
- <div className="h-9 px-3 flex items-center justify-between border-b border-[#2b2d31] bg-[#1a1b1e] shrink-0">
- <div className="flex items-center space-x-2">
- <MessageSquare className="w-4 h-4 text-cyan-400" />
- <span className="text-xs font-semibold text-white">Speech Balloon Tool</span>
- </div>
- <button onClick={onToggleHidden} className="p-1 text-[#828690] hover:text-rose-400 rounded cursor-pointer">
- <X className="w-3.5 h-3.5" />
- </button>
+ <div className="p-2.5 space-y-3 overflow-y-auto flex-1">
+ <div className="text-[11px] font-medium text-[#e5e5e5]">Selection</div>
+ <div className="grid grid-cols-2 gap-1">
+ {(
+ [
+ { id: 'select-rect', label: 'Rect' },
+ { id: 'select-lasso', label: 'Lasso' },
+ { id: 'select-wand', label: 'Wand' },
+ { id: 'select-pen', label: 'Pen' },
+ { id: 'select-eraser', label: 'Erase' },
+ ] as const
+ ).map((s) => (
+ <button
+ key={s.id}
+ type="button"
+ onClick={() => onSelectTool(s.id)}
+ className={`py-1 px-1.5 rounded text-[11px] transition-colors cursor-pointer ${
+ currentTool === s.id
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
+ >
+ {s.label}
+ </button>
+ ))}
</div>
- <div className="p-3 space-y-4">
- <div className="space-y-1.5">
- <label className="text-[11px] font-medium text-[#aaaaaa] block mb-1">Balloon Shape:</label>
- <div className="grid grid-cols-2 gap-1.5">
- {(['ellipse', 'rounded-rect', 'jagged-flash', 'thought'] as const).map((shape) => (
+ {(currentTool === 'select-pen' || currentTool === 'select-eraser') && (
+ <CompactSlider
+ label="Brush Size"
+ valueLabel={`${brushSettings.size}px`}
+ min={1}
+ max={250}
+ value={Math.round(brushSettings.size)}
+ onChange={(v) => onUpdateBrushSettings({ size: v })}
+ />
+ )}
+
+ {currentTool === 'select-wand' && (
+ <div className="space-y-2.5 pt-1">
+ <CompactSlider
+ label="Tolerance"
+ valueLabel={`${activeWand.tolerance}`}
+ min={0}
+ max={255}
+ value={activeWand.tolerance}
+ onChange={(v) => onUpdateWandSettings?.({ tolerance: v })}
+ />
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Contiguous</span>
+ <input
+ type="checkbox"
+ checked={activeWand.contiguous}
+ onChange={(e) => onUpdateWandSettings?.({ contiguous: e.target.checked })}
+ />
+ </label>
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Anti-Alias</span>
+ <input
+ type="checkbox"
+ checked={activeWand.antiAlias}
+ onChange={(e) => onUpdateWandSettings?.({ antiAlias: e.target.checked })}
+ />
+ </label>
+ <div className="grid grid-cols-3 gap-0.5 bg-[#161616] p-0.5 rounded">
+ {(['active', 'all', 'reference'] as const).map((mode) => (
<button
- key={shape}
+ key={mode}
type="button"
- onClick={() => onUpdateBalloonSettings?.({ shape })}
- className={`py-1.5 px-2 rounded text-xs text-center transition-colors cursor-pointer capitalize font-medium ${
- balloonSettings?.shape === shape
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b]'
- : 'bg-[#202226] text-[#aaaaaa] hover:bg-[#282a2e] hover:text-white border border-transparent'
+ onClick={() => onUpdateWandSettings?.({ referMode: mode })}
+ className={`py-0.5 rounded text-[10px] capitalize cursor-pointer ${
+ activeWand.referMode === mode
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
}`}
>
- {shape.replace('-', ' ')}
+ {mode === 'reference' ? 'Ref' : mode}
</button>
))}
</div>
</div>
+ )}
- <div className="space-y-1.5">
- <label className="text-[11px] font-medium text-[#aaaaaa] block">Writing Direction:</label>
- <div className="grid grid-cols-2 gap-1.5">
- <button
- type="button"
- onClick={() => onUpdateBalloonSettings?.({ vertical: false })}
- className={`py-1 px-2 rounded text-xs text-center transition-colors cursor-pointer font-medium ${
- !balloonSettings?.vertical
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b]'
- : 'bg-[#202226] text-[#aaaaaa] hover:text-white border border-transparent'
- }`}
- >
- Horizontal (横)
- </button>
- <button
- type="button"
- onClick={() => onUpdateBalloonSettings?.({ vertical: true })}
- className={`py-1 px-2 rounded text-xs text-center transition-colors cursor-pointer font-medium ${
- balloonSettings?.vertical
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b]'
- : 'bg-[#202226] text-[#aaaaaa] hover:text-white border border-transparent'
- }`}
- >
- Vertical (縦書き)
- </button>
- </div>
- </div>
-
- <div className="space-y-1.5">
- <div className="flex items-center justify-between">
- <label className="text-[11px] font-medium text-[#aaaaaa]">Border Width:</label>
- <span className="text-xs font-mono text-cyan-400">{balloonSettings?.strokeWidth ?? 3}px</span>
- </div>
- <input
- type="range"
- min={1}
- max={15}
- value={balloonSettings?.strokeWidth ?? 3}
- onChange={(e) => onUpdateBalloonSettings?.({ strokeWidth: Number(e.target.value) })}
- className="w-full accent-cyan-400"
- />
- </div>
-
- <div className="pt-2 border-t border-[#26282c] space-y-1 text-[11px] text-[#888888]">
- <p>• Click on canvas to place parametric speech balloon.</p>
- <p>• Drag handles to resize body or re-orient bezier tail.</p>
+ <div className="space-y-1 pt-1">
+ <div className="grid grid-cols-3 gap-1">
+ <button
+ type="button"
+ onClick={() => onExpandSelection?.(5)}
+ title="Expand 5px"
+ className="py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[#8a8a8a] hover:text-[#e5e5e5] flex items-center justify-center cursor-pointer"
+ >
+ <Maximize2 className="w-3 h-3" />
+ </button>
+ <button
+ type="button"
+ onClick={() => onContractSelection?.(5)}
+ title="Contract 5px"
+ className="py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[#8a8a8a] hover:text-[#e5e5e5] flex items-center justify-center cursor-pointer"
+ >
+ <Minimize2 className="w-3 h-3" />
+ </button>
+ <button
+ type="button"
+ onClick={() => onFeatherSelection?.(5)}
+ title="Feather 5px"
+ className="py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[#8a8a8a] hover:text-[#e5e5e5] flex items-center justify-center cursor-pointer"
+ >
+ <Feather className="w-3 h-3" />
+ </button>
</div>
+ <button
+ type="button"
+ onClick={onInvertSelection}
+ className="w-full py-1 px-2 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] flex items-center gap-1.5 cursor-pointer"
+ >
+ <RotateCcw className="w-3 h-3" />
+ <span>Invert</span>
+ </button>
+ <button
+ type="button"
+ onClick={onTransformSelection}
+ className="w-full py-1 px-2 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] flex items-center gap-1.5 cursor-pointer"
+ >
+ <Scaling className="w-3 h-3" />
+ <span>Transform</span>
+ </button>
+ <button
+ type="button"
+ onClick={onDeselect}
+ className="w-full py-1 px-2 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer text-left"
+ >
+ Deselect
+ </button>
</div>
</div>
);
}
- if (currentTool === 'vector-edit') {
- const activeMode = vectorEditSettings?.mode || 'pinch';
-
+ if (currentTool === 'text') {
return (
- <div className="flex-1 flex flex-col overflow-y-auto">
- <div className="h-9 px-3 flex items-center justify-between border-b border-[#2b2d31] bg-[#1a1b1e] shrink-0">
- <div className="flex items-center space-x-2">
- <Spline className="w-4 h-4 text-cyan-400" />
- <span className="text-xs font-semibold text-white">Correct Line (Vector)</span>
- </div>
- <button onClick={onToggleHidden} className="p-1 text-[#828690] hover:text-rose-400 rounded cursor-pointer">
- <X className="w-3.5 h-3.5" />
+ <div className="p-2.5 space-y-3 overflow-y-auto flex-1">
+ <div className="text-[11px] font-medium text-[#e5e5e5]">Text</div>
+ <select
+ value={textSettings?.fontFamily}
+ onChange={(e) => onUpdateTextSettings?.({ fontFamily: e.target.value })}
+ className="w-full px-2 py-1 text-[11px]"
+ >
+ <option value="'Neucha', 'Anime Ace', 'Comic Sans MS', sans-serif">Manga / Anime</option>
+ <option value="'Anime Ace', 'Comic Sans MS', sans-serif">Anime Ace</option>
+ <option value="Arial, sans-serif">Arial</option>
+ <option value="Impact, sans-serif">Impact</option>
+ <option value="Georgia, serif">Georgia</option>
+ </select>
+ <div className="grid grid-cols-2 gap-1 bg-[#161616] p-0.5 rounded">
+ <button
+ type="button"
+ onClick={() => onUpdateTextSettings?.({ writingMode: 'horizontal-tb' })}
+ className={`py-1 rounded text-[10px] cursor-pointer ${
+ textSettings?.writingMode !== 'vertical-rl'
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ Horiz
</button>
- </div>
-
- <div className="p-3 space-y-4">
- <div className="space-y-1.5">
- <label className="text-[11px] font-medium text-[#aaaaaa] block mb-1">Operation Mode:</label>
- <div className="space-y-1">
- <button
- type="button"
- onClick={() => onUpdateVectorEditSettings?.({ mode: 'pinch' })}
- className={`w-full px-2.5 py-1.5 rounded text-left text-xs transition-colors cursor-pointer flex items-center justify-between ${
- activeMode === 'pinch'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] font-medium'
- : 'bg-[#202226] text-[#aaaaaa] hover:bg-[#282a2e] hover:text-white border border-transparent'
- }`}
- >
- <span>Pinch / Reshape Line</span>
- <span className="text-[10px] text-[#777777]">Bell-curve</span>
- </button>
-
- <button
- type="button"
- onClick={() => onUpdateVectorEditSettings?.({ mode: 'width' })}
- className={`w-full px-2.5 py-1.5 rounded text-left text-xs transition-colors cursor-pointer flex items-center justify-between ${
- activeMode === 'width'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] font-medium'
- : 'bg-[#202226] text-[#aaaaaa] hover:bg-[#282a2e] hover:text-white border border-transparent'
- }`}
- >
- <span>Modify Line Width</span>
- <span className="text-[10px] text-[#777777]">Local scale</span>
- </button>
-
- <button
- type="button"
- onClick={() => onUpdateVectorEditSettings?.({ mode: 'simplify' })}
- className={`w-full px-2.5 py-1.5 rounded text-left text-xs transition-colors cursor-pointer flex items-center justify-between ${
- activeMode === 'simplify'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] font-medium'
- : 'bg-[#202226] text-[#aaaaaa] hover:bg-[#282a2e] hover:text-white border border-transparent'
- }`}
- >
- <span>Simplify Vector Line</span>
- <span className="text-[10px] text-[#777777]">Ramer-Douglas</span>
- </button>
- </div>
- </div>
-
- <div className="space-y-1.5">
- <div className="flex items-center justify-between">
- <label className="text-[11px] font-medium text-[#aaaaaa]">Influence Radius:</label>
- <span className="text-xs font-mono text-cyan-400">{vectorEditSettings?.radius ?? 30}px</span>
- </div>
- <input
- type="range"
- min={5}
- max={150}
- value={vectorEditSettings?.radius ?? 30}
- onChange={(e) => onUpdateVectorEditSettings?.({ radius: Number(e.target.value) })}
- className="w-full accent-cyan-400"
- />
- </div>
-
- {activeMode === 'width' && (
- <div className="space-y-1.5">
- <div className="flex items-center justify-between">
- <label className="text-[11px] font-medium text-[#aaaaaa]">Width Factor:</label>
- <span className="text-xs font-mono text-cyan-400">
- {(vectorEditSettings?.widthFactor ?? 1.5).toFixed(1)}x
- </span>
- </div>
- <input
- type="range"
- min={2}
- max={30}
- value={Math.round((vectorEditSettings?.widthFactor ?? 1.5) * 10)}
- onChange={(e) =>
- onUpdateVectorEditSettings?.({ widthFactor: Number(e.target.value) / 10 })
- }
- className="w-full accent-cyan-400"
- />
- </div>
- )}
-
- {activeMode === 'simplify' && (
- <div className="space-y-1.5">
- <div className="flex items-center justify-between">
- <label className="text-[11px] font-medium text-[#aaaaaa]">Reduction Tolerance:</label>
- <span className="text-xs font-mono text-cyan-400">
- {(vectorEditSettings?.simplifyTolerance ?? 2.0).toFixed(1)}px
- </span>
- </div>
- <input
- type="range"
- min={5}
- max={80}
- value={Math.round((vectorEditSettings?.simplifyTolerance ?? 2.0) * 10)}
- onChange={(e) =>
- onUpdateVectorEditSettings?.({ simplifyTolerance: Number(e.target.value) / 10 })
- }
- className="w-full accent-cyan-400"
- />
- </div>
- )}
-
- {onOpenMangaEffects && (
- <div className="pt-2 border-t border-[#26282c]">
- <button
- type="button"
- onClick={onOpenMangaEffects}
- className="w-full py-2 px-3 rounded bg-[#18191c] hover:bg-[#25272b] border border-[#383a40] text-cyan-300 text-xs font-medium flex items-center justify-center space-x-2 transition-colors cursor-pointer"
- >
- <Sparkles className="w-3.5 h-3.5 text-amber-400" />
- <span>Manga Effect Lines...</span>
- </button>
- </div>
- )}
- </div>
- </div>
- );
- }
-
- if (currentTool === 'text') {
- return (
- <div className="flex-1 flex flex-col overflow-y-auto">
- <div className="h-9 px-3 flex items-center justify-between border-b border-[#2b2d31] bg-[#1a1b1e] shrink-0">
- <div className="flex items-center space-x-2">
- <Type className="w-4 h-4 text-cyan-400" />
- <span className="text-xs font-semibold text-white">Text Creation Tool (T)</span>
- </div>
- <button onClick={onToggleHidden} className="p-1 text-[#828690] hover:text-rose-400 rounded cursor-pointer">
- <X className="w-3.5 h-3.5" />
- </button>
- </div>
-
- <div className="p-3 space-y-4">
- <div className="space-y-1.5">
- <label className="text-[11px] font-medium text-[#aaaaaa]">Manga Font Family:</label>
- <select
- value={textSettings?.fontFamily}
- onChange={(e) => onUpdateTextSettings?.({ fontFamily: e.target.value })}
- className="w-full bg-[#141517] text-white text-xs border border-[#383a40] rounded px-2 py-1.5 focus:border-cyan-500 focus:outline-none"
- >
- <option value="'Neucha', 'Anime Ace', 'Comic Sans MS', sans-serif">Manga / Anime (RU/EN)</option>
- <option value="'Anime Ace', 'Comic Sans MS', sans-serif">Anime Ace (Comic)</option>
- <option value="'Comic Sans MS', cursive, sans-serif">Comic Sans MS</option>
- <option value="Arial, sans-serif">Arial</option>
- <option value="Impact, sans-serif">Impact</option>
- <option value="'Times New Roman', serif">Times New Roman</option>
- <option value="Georgia, serif">Georgia</option>
- </select>
- </div>
-
- <div className="space-y-1.5">
- <label className="text-[11px] font-medium text-[#aaaaaa]">Writing Direction:</label>
- <div className="grid grid-cols-2 gap-1.5">
- <button
- type="button"
- onClick={() => onUpdateTextSettings?.({ writingMode: 'horizontal-tb' })}
- className={`px-2 py-1 rounded text-xs transition-colors cursor-pointer text-center font-medium ${
- textSettings?.writingMode !== 'vertical-rl'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b]'
- : 'bg-[#202226] text-[#888888] hover:text-white border border-transparent'
- }`}
- >
- Horizontal (横)
- </button>
- <button
- type="button"
- onClick={() => onUpdateTextSettings?.({ writingMode: 'vertical-rl' })}
- className={`px-2 py-1 rounded text-xs transition-colors cursor-pointer text-center font-medium ${
- textSettings?.writingMode === 'vertical-rl'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b]'
- : 'bg-[#202226] text-[#888888] hover:text-white border border-transparent'
- }`}
- >
- Vertical (縦書き)
- </button>
- </div>
- </div>
-
- <div className="space-y-1.5">
- <div className="flex items-center justify-between">
- <label className="text-[11px] font-medium text-[#aaaaaa]">Default Font Size:</label>
- <span className="text-xs font-mono text-cyan-400">{textSettings?.fontSize ?? 28}px</span>
- </div>
- <input
- type="range"
- min={12}
- max={160}
- value={textSettings?.fontSize ?? 28}
- onChange={(e) => onUpdateTextSettings?.({ fontSize: Number(e.target.value) })}
- className="w-full accent-cyan-400"
- />
- </div>
-
- <div className="pt-2 border-t border-[#26282c] flex items-center space-x-2">
- <div className="w-5 h-5 rounded border border-[#44464c]" style={{ backgroundColor: primaryColor }} />
- <span className="text-[11px] text-[#aaaaaa]">Text Color: {primaryColor}</span>
- </div>
- </div>
- </div>
- );
- }
-
- const isSelectionTool =
- currentTool === 'select-rect' ||
- currentTool === 'select-lasso' ||
- currentTool === 'select-wand' ||
- currentTool === 'select-pen' ||
- currentTool === 'select-eraser';
-
- if (isSelectionTool) {
- const activeWand = wandSettings || {
- tolerance: 32,
- contiguous: true,
- antiAlias: true,
- referMode: 'active' as const,
- };
-
- const selectionTitle =
- currentTool === 'select-rect'
- ? 'Rectangular Marquee (M)'
- : currentTool === 'select-lasso'
- ? 'Lasso Selection (L)'
- : currentTool === 'select-wand'
- ? 'Magic Wand (W)'
- : currentTool === 'select-pen'
- ? 'Selection Pen'
- : 'Selection Eraser';
-
- return (
- <div className="flex-1 flex flex-col overflow-y-auto">
- <div className="h-9 px-3 flex items-center justify-between border-b border-[#2b2d31] bg-[#1a1b1e] shrink-0">
- <div className="flex items-center space-x-2">
- {currentTool === 'select-rect' && <BoxSelect className="w-4 h-4 text-cyan-400" />}
- {currentTool === 'select-lasso' && <Lasso className="w-4 h-4 text-cyan-400" />}
- {currentTool === 'select-wand' && <Wand2 className="w-4 h-4 text-cyan-400" />}
- {currentTool === 'select-pen' && <PenTool className="w-4 h-4 text-cyan-400" />}
- {currentTool === 'select-eraser' && <Eraser className="w-4 h-4 text-cyan-400" />}
- <span className="text-xs font-semibold text-white">{selectionTitle}</span>
- </div>
- <button onClick={onToggleHidden} className="p-1 text-[#828690] hover:text-rose-400 rounded cursor-pointer">
- <X className="w-3.5 h-3.5" />
+ <button
+ type="button"
+ onClick={() => onUpdateTextSettings?.({ writingMode: 'vertical-rl' })}
+ className={`py-1 rounded text-[10px] cursor-pointer ${
+ textSettings?.writingMode === 'vertical-rl'
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ Vert
</button>
</div>
-
- <div className="p-3 space-y-4">
- <div className="space-y-1.5">
- <label className="text-[11px] font-medium text-[#aaaaaa] block mb-1">Selection Tool:</label>
- <div className="grid grid-cols-2 gap-1.5">
- <button
- onClick={() => onSelectTool('select-rect')}
- className={`py-1.5 px-2 rounded text-xs text-center transition-colors cursor-pointer flex items-center justify-center space-x-1 ${
- currentTool === 'select-rect'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] font-medium'
- : 'bg-[#202226] text-[#aaaaaa] hover:bg-[#282a2e] hover:text-white border border-transparent'
- }`}
- >
- <BoxSelect className="w-3.5 h-3.5" />
- <span>Marquee</span>
- </button>
-
- <button
- onClick={() => onSelectTool('select-lasso')}
- className={`py-1.5 px-2 rounded text-xs text-center transition-colors cursor-pointer flex items-center justify-center space-x-1 ${
- currentTool === 'select-lasso'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] font-medium'
- : 'bg-[#202226] text-[#aaaaaa] hover:bg-[#282a2e] hover:text-white border border-transparent'
- }`}
- >
- <Lasso className="w-3.5 h-3.5" />
- <span>Lasso</span>
- </button>
-
- <button
- onClick={() => onSelectTool('select-wand')}
- className={`py-1.5 px-2 rounded text-xs text-center transition-colors cursor-pointer flex items-center justify-center space-x-1 ${
- currentTool === 'select-wand'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] font-medium'
- : 'bg-[#202226] text-[#aaaaaa] hover:bg-[#282a2e] hover:text-white border border-transparent'
- }`}
- >
- <Wand2 className="w-3.5 h-3.5" />
- <span>Wand</span>
- </button>
-
- <button
- onClick={() => onSelectTool('select-pen')}
- className={`py-1.5 px-2 rounded text-xs text-center transition-colors cursor-pointer flex items-center justify-center space-x-1 ${
- currentTool === 'select-pen'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] font-medium'
- : 'bg-[#202226] text-[#aaaaaa] hover:bg-[#282a2e] hover:text-white border border-transparent'
- }`}
- >
- <PenTool className="w-3.5 h-3.5" />
- <span>Sel Pen</span>
- </button>
-
- <button
- onClick={() => onSelectTool('select-eraser')}
- className={`col-span-2 py-1.5 px-2 rounded text-xs text-center transition-colors cursor-pointer flex items-center justify-center space-x-1 ${
- currentTool === 'select-eraser'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] font-medium'
- : 'bg-[#202226] text-[#aaaaaa] hover:bg-[#282a2e] hover:text-white border border-transparent'
- }`}
- >
- <Eraser className="w-3.5 h-3.5" />
- <span>Selection Eraser</span>
- </button>
- </div>
- </div>
-
- {/* Magic Wand Specific Settings */}
- {currentTool === 'select-wand' && (
- <div className="space-y-3 pt-2 border-t border-[#26282c]">
- <div>
- <div className="flex items-center justify-between text-xs mb-1">
- <span className="text-[#aaaaaa]">Tolerance:</span>
- <span className="text-white font-mono">{activeWand.tolerance}</span>
- </div>
- <input
- type="range"
- min="0"
- max="255"
- value={activeWand.tolerance}
- onChange={(e) => onUpdateWandSettings?.({ tolerance: Number(e.target.value) })}
- className="w-full accent-cyan-400"
- />
- </div>
-
- <div className="flex items-center justify-between text-xs py-1">
- <span className="text-[#cccccc]">Contiguous</span>
- <input
- type="checkbox"
- checked={activeWand.contiguous}
- onChange={(e) => onUpdateWandSettings?.({ contiguous: e.target.checked })}
- className="accent-cyan-400 rounded cursor-pointer"
- />
- </div>
-
- <div className="flex items-center justify-between text-xs py-1">
- <span className="text-[#cccccc]">Anti-Aliasing</span>
- <input
- type="checkbox"
- checked={activeWand.antiAlias}
- onChange={(e) => onUpdateWandSettings?.({ antiAlias: e.target.checked })}
- className="accent-cyan-400 rounded cursor-pointer"
- />
- </div>
-
- <div className="space-y-1">
- <span className="text-[11px] text-[#aaaaaa] block">Reference Source:</span>
- <div className="grid grid-cols-3 gap-1">
- {(['active', 'all', 'reference'] as const).map((mode) => (
- <button
- key={mode}
- onClick={() => onUpdateWandSettings?.({ referMode: mode })}
- className={`py-1 px-1.5 rounded text-[11px] text-center capitalize cursor-pointer transition-colors ${
- activeWand.referMode === mode
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] font-medium'
- : 'bg-[#202226] text-[#aaaaaa] hover:bg-[#282a2e] hover:text-white'
- }`}
- >
- {mode === 'active' ? 'Active' : mode === 'all' ? 'All' : 'Ref Layer'}
- </button>
- ))}
- </div>
- </div>
- </div>
- )}
-
- {/* Selection Pen / Eraser Size */}
- {(currentTool === 'select-pen' || currentTool === 'select-eraser') && (
- <div className="space-y-3 pt-2 border-t border-[#26282c]">
- <div>
- <div className="flex items-center justify-between text-xs mb-1">
- <span className="text-[#aaaaaa]">Pen Size:</span>
- <span className="text-white font-mono">{Math.round(brushSettings.size)} px</span>
- </div>
- <input
- type="range"
- min="1"
- max="300"
- value={brushSettings.size}
- onChange={(e) => onUpdateBrushSettings({ size: Number(e.target.value) })}
- className="w-full accent-cyan-400"
- />
- </div>
-
- <div>
- <div className="flex items-center justify-between text-xs mb-1">
- <span className="text-[#aaaaaa]">Stabilization:</span>
- <span className="text-white font-mono">{brushSettings.stabilization ?? 10}</span>
- </div>
- <input
- type="range"
- min="0"
- max="50"
- value={brushSettings.stabilization ?? 10}
- onChange={(e) => onUpdateBrushSettings({ stabilization: Number(e.target.value) })}
- className="w-full accent-cyan-400"
- />
- </div>
- </div>
- )}
-
- {/* Selection Boundary Modifiers & Actions */}
- <div className="space-y-1.5 pt-2 border-t border-[#26282c]">
- <label className="text-[11px] font-medium text-[#aaaaaa] block mb-1">Boundary Modifiers:</label>
- <div className="grid grid-cols-3 gap-1">
- <button
- onClick={() => onExpandSelection?.(5)}
- title="Expand Selection by 5px"
- className="py-1.5 px-1 bg-[#202226] hover:bg-[#282a2e] text-[#cccccc] hover:text-white rounded text-[11px] transition-colors flex items-center justify-center space-x-1 cursor-pointer border border-[#2f323a]"
- >
- <Maximize2 className="w-3 h-3 text-cyan-400" />
- <span>Expand</span>
- </button>
-
- <button
- onClick={() => onContractSelection?.(5)}
- title="Contract Selection by 5px"
- className="py-1.5 px-1 bg-[#202226] hover:bg-[#282a2e] text-[#cccccc] hover:text-white rounded text-[11px] transition-colors flex items-center justify-center space-x-1 cursor-pointer border border-[#2f323a]"
- >
- <Minimize2 className="w-3 h-3 text-cyan-400" />
- <span>Contract</span>
- </button>
-
- <button
- onClick={() => onFeatherSelection?.(5)}
- title="Feather Selection (5px)"
- className="py-1.5 px-1 bg-[#202226] hover:bg-[#282a2e] text-[#cccccc] hover:text-white rounded text-[11px] transition-colors flex items-center justify-center space-x-1 cursor-pointer border border-[#2f323a]"
- >
- <Feather className="w-3 h-3 text-cyan-400" />
- <span>Feather</span>
- </button>
- </div>
-
- <button
- onClick={onInvertSelection}
- className="w-full py-1.5 px-2 bg-[#202226] hover:bg-[#282a2e] text-[#cccccc] hover:text-white rounded text-xs transition-colors flex items-center justify-center space-x-1.5 cursor-pointer border border-[#2f323a]"
- >
- <RotateCcw className="w-3.5 h-3.5 text-amber-400" />
- <span>Invert Selection (Ctrl+Shift+I)</span>
- </button>
-
- <button
- onClick={onTransformSelection}
- className="w-full py-1.5 px-2 bg-[#202226] hover:bg-[#282a2e] text-[#cccccc] hover:text-white rounded text-xs transition-colors flex items-center justify-center space-x-1.5 cursor-pointer border border-[#2f323a]"
- >
- <Scaling className="w-3.5 h-3.5 text-emerald-400" />
- <span>Transform Selection (Ctrl+T)</span>
- </button>
-
- <button
- onClick={onDeselect}
- className="w-full py-1.5 px-2 bg-[#202226] hover:bg-[#282a2e] text-[#cccccc] hover:text-white rounded text-xs transition-colors flex items-center justify-center space-x-1.5 cursor-pointer border border-[#2f323a]"
- >
- <X className="w-3.5 h-3.5 text-red-400" />
- <span>Deselect (Ctrl+D)</span>
- </button>
- </div>
- </div>
+ <CompactSlider
+ label="Font Size"
+ valueLabel={`${textSettings?.fontSize ?? 28}px`}
+ min={12}
+ max={160}
+ value={textSettings?.fontSize ?? 28}
+ onChange={(v) => onUpdateTextSettings?.({ fontSize: v })}
+ />
</div>
);
}
- if (currentTool === 'transform') {
+ if (currentTool === 'frame') {
return (
- <div className="flex-1 flex flex-col overflow-y-auto">
- <div className="h-9 px-3 flex items-center justify-between border-b border-[#2b2d31] bg-[#1a1b1e] shrink-0">
- <div className="flex items-center space-x-2">
- <Scaling className="w-4 h-4 text-cyan-400" />
- <span className="text-xs font-semibold text-white">Free Transform (Ctrl+T)</span>
- </div>
- <button onClick={onToggleHidden} className="p-1 text-[#828690] hover:text-rose-400 rounded cursor-pointer">
- <X className="w-3.5 h-3.5" />
+ <div className="p-2.5 space-y-3 overflow-y-auto flex-1">
+ <div className="text-[11px] font-medium text-[#e5e5e5]">Frame Border</div>
+ <CompactSlider
+ label="Thickness"
+ valueLabel={`${frameSettings?.thickness ?? 4}px`}
+ min={1}
+ max={100}
+ value={frameSettings?.thickness ?? 4}
+ onChange={(v) => onUpdateFrameSettings?.({ thickness: v })}
+ />
+ <div className="grid grid-cols-2 gap-1 bg-[#161616] p-0.5 rounded">
+ <button
+ type="button"
+ onClick={() => onUpdateFrameSettings?.({ fillBackground: true })}
+ className={`py-1 rounded text-[10px] cursor-pointer ${
+ frameSettings?.fillBackground
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ White
</button>
- </div>
-
- <div className="p-3 space-y-4">
- <div className="space-y-1.5">
- <span className="text-[11px] text-[#777777] block">Keyboard Shortcuts:</span>
- <div className="text-[11px] text-[#aaaaaa] space-y-0.5 font-mono">
- <div>• Enter: Apply transform</div>
- <div>• Esc: Cancel transform</div>
- <div>• Shift + Drag: Lock aspect ratio</div>
- </div>
- </div>
- </div>
- </div>
- );
- }
-
- if (currentTool === 'liquify') {
- const activeMode = liquifySettings?.mode ?? 'push';
- const size = liquifySettings?.size ?? 80;
- const strength = liquifySettings?.strength ?? 50;
- const hardness = liquifySettings?.hardness ?? 50;
- const usePressure = liquifySettings?.usePressure ?? true;
-
- const LIQUIFY_SUB_TOOLS: Array<{
- id: LiquifyMode;
- name: string;
- desc: string;
- badge: string;
- icon: React.ReactNode;
- }> = [
- { id: 'push', name: 'Push', desc: 'Distort along stroke direction', badge: 'Move', icon: <Move className="w-3.5 h-3.5" /> },
- { id: 'expand', name: 'Expand', desc: 'Inflate outwards radially', badge: 'Bloat', icon: <Maximize2 className="w-3.5 h-3.5" /> },
- { id: 'pinch', name: 'Pinch', desc: 'Deflate inwards radially', badge: 'Shrink', icon: <Minimize2 className="w-3.5 h-3.5" /> },
- { id: 'push-left', name: 'Push Left', desc: 'Displace left of stroke', badge: 'Left', icon: <CornerUpLeft className="w-3.5 h-3.5" /> },
- { id: 'push-right', name: 'Push Right', desc: 'Displace right of stroke', badge: 'Right', icon: <CornerUpRight className="w-3.5 h-3.5" /> },
- { id: 'twirl-cw', name: 'Twirl Clockwise', desc: 'Rotate pixels clockwise', badge: 'CW', icon: <RotateCw className="w-3.5 h-3.5" /> },
- { id: 'twirl-ccw', name: 'Twirl Counterclockwise', desc: 'Rotate pixels counter-clockwise', badge: 'CCW', icon: <RotateCcw className="w-3.5 h-3.5" /> },
- { id: 'reconstruct', name: 'Reconstruct', desc: 'Restore towards original image', badge: 'Restore', icon: <Undo2 className="w-3.5 h-3.5" /> },
- ];
-
- return (
- <div className="flex-1 flex flex-col overflow-y-auto">
- {/* Header */}
- <div className="h-8 px-2.5 flex items-center justify-between border-b border-[#2b2d31] bg-[#1a1b1e] shrink-0">
- <div className="flex items-center space-x-1.5">
- <LiquifyIcon className="w-4 h-4 text-cyan-400" />
- <span className="text-xs font-semibold tracking-tight text-white">Sub Tool [Liquify]</span>
- </div>
<button
- onClick={onToggleHidden}
- title="Hide Panel ( [ )"
- className="p-1 text-[#828690] hover:text-rose-400 hover:bg-[#282a2e] rounded transition-colors cursor-pointer"
+ type="button"
+ onClick={() => onUpdateFrameSettings?.({ fillBackground: false })}
+ className={`py-1 rounded text-[10px] cursor-pointer ${
+ !frameSettings?.fillBackground
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
>
- <X className="w-3.5 h-3.5" />
+ Empty
</button>
</div>
-
- {/* Sub Tools List (Authentic CSP Style matching screenshot) */}
- <div className="p-2 space-y-1 border-b border-[#2b2d31]">
- <div className="text-[10px] uppercase font-semibold tracking-wider text-[#777777] px-1 mb-1">
- Liquify Sub Tools
- </div>
- {LIQUIFY_SUB_TOOLS.map((sub) => {
- const isSelected = activeMode === sub.id;
- return (
- <button
- key={sub.id}
- onClick={() => onUpdateLiquifySettings?.({ mode: sub.id })}
- title={sub.desc}
- className={`w-full px-2 py-1.5 rounded flex items-center justify-between transition-colors cursor-pointer ${
- isSelected
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] font-medium shadow-xs'
- : 'bg-[#202226] text-[#aaaaaa] hover:bg-[#282a2e] hover:text-white border border-transparent'
- }`}
- >
- <div className="flex items-center space-x-2 truncate">
- <LiquifyIcon className={`w-3.5 h-3.5 shrink-0 ${isSelected ? 'text-[#5ce1e6]' : 'text-[#888888]'}`} />
- <span className="text-xs truncate">{sub.name}</span>
- </div>
- <div className="flex items-center space-x-1.5 shrink-0">
- <span className="text-[9px] uppercase px-1 py-0.5 rounded bg-[#161719] text-[#777777] border border-[#2b2d31]">
- {sub.badge}
- </span>
- <span className={isSelected ? 'text-[#5ce1e6]' : 'text-[#666666]'}>
- {sub.icon}
- </span>
- </div>
- </button>
- );
- })}
- </div>
-
- {/* Tool Property Section */}
- <div className="p-3 space-y-4">
- <div className="text-[10px] uppercase font-semibold tracking-wider text-[#777777]">
- Tool Property [Liquify]
- </div>
-
- {/* Size Slider */}
- <div className="space-y-1.5">
- <div className="flex items-center justify-between">
- <label className="text-[11px] font-medium text-[#aaaaaa]">Brush Size:</label>
- <div className="flex items-center space-x-1">
- <input
- type="number"
- min={5}
- max={500}
- value={size}
- onChange={(e) =>
- onUpdateLiquifySettings?.({
- size: Math.max(5, Math.min(500, Number(e.target.value) || 5)),
- })
- }
- className="w-14 bg-[#141517] text-white text-right px-1.5 py-0.5 rounded border border-[#383a40] text-xs font-mono"
- />
- <span className="text-[10px] text-[#777777]">px</span>
- </div>
- </div>
- <input
- type="range"
- min={5}
- max={500}
- value={size}
- onChange={(e) => onUpdateLiquifySettings?.({ size: Number(e.target.value) })}
- className="w-full accent-cyan-400"
- />
- {/* Quick size chips */}
- <div className="flex items-center gap-1 pt-0.5 overflow-x-auto no-scrollbar">
- {[20, 50, 80, 120, 200, 350].map((sz) => (
- <button
- key={sz}
- onClick={() => onUpdateLiquifySettings?.({ size: sz })}
- className={`px-1.5 py-0.5 text-[10px] rounded font-mono transition-colors cursor-pointer ${
- size === sz
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b]'
- : 'bg-[#202226] text-[#888888] hover:text-white border border-[#2e3036]'
- }`}
- >
- {sz}
- </button>
- ))}
- </div>
- </div>
-
- {/* Strength Slider */}
- <div className="space-y-1.5">
- <div className="flex items-center justify-between">
- <label className="text-[11px] font-medium text-[#aaaaaa]">Strength (Intensity):</label>
- <div className="flex items-center space-x-1">
- <input
- type="number"
- min={1}
- max={100}
- value={strength}
- onChange={(e) =>
- onUpdateLiquifySettings?.({
- strength: Math.max(1, Math.min(100, Number(e.target.value) || 1)),
- })
- }
- className="w-14 bg-[#141517] text-white text-right px-1.5 py-0.5 rounded border border-[#383a40] text-xs font-mono"
- />
- <span className="text-[10px] text-[#777777]">%</span>
- </div>
- </div>
- <input
- type="range"
- min={1}
- max={100}
- value={strength}
- onChange={(e) => onUpdateLiquifySettings?.({ strength: Number(e.target.value) })}
- className="w-full accent-cyan-400"
- />
- </div>
-
- {/* Hardness Slider */}
- <div className="space-y-1.5">
- <div className="flex items-center justify-between">
- <label className="text-[11px] font-medium text-[#aaaaaa]">Hardness:</label>
- <div className="flex items-center space-x-1">
- <input
- type="number"
- min={0}
- max={100}
- value={hardness}
- onChange={(e) =>
- onUpdateLiquifySettings?.({
- hardness: Math.max(0, Math.min(100, Number(e.target.value) || 0)),
- })
- }
- className="w-14 bg-[#141517] text-white text-right px-1.5 py-0.5 rounded border border-[#383a40] text-xs font-mono"
- />
- <span className="text-[10px] text-[#777777]">%</span>
- </div>
- </div>
- <input
- type="range"
- min={0}
- max={100}
- value={hardness}
- onChange={(e) => onUpdateLiquifySettings?.({ hardness: Number(e.target.value) })}
- className="w-full accent-cyan-400"
- />
- </div>
-
- {/* Pen Pressure sensitivity */}
- <div className="pt-2 border-t border-[#26282c]">
- <label className="flex items-center space-x-2 text-xs text-[#cccccc] cursor-pointer">
- <input
- type="checkbox"
- checked={usePressure}
- onChange={(e) => onUpdateLiquifySettings?.({ usePressure: e.target.checked })}
- className="rounded border-[#383a40] bg-[#141517] text-cyan-500 focus:ring-0"
- />
- <span>Pen Pressure Sensitivity</span>
- </label>
- </div>
-
- {/* Reset to Defaults */}
- <div className="pt-2">
- <button
- onClick={() =>
- onUpdateLiquifySettings?.({
- mode: 'push',
- size: 80,
- strength: 50,
- hardness: 50,
- usePressure: true,
- })
- }
- className="w-full py-1.5 px-2 bg-[#202226] hover:bg-[#282a2e] text-[#888888] hover:text-white rounded text-xs transition-colors flex items-center justify-center space-x-1.5 cursor-pointer border border-[#2f323a]"
- >
- <span>Reset to Defaults</span>
- </button>
- </div>
- </div>
</div>
);
- }
-
- return null;
- };
-
- return (
- <div className="flex h-full select-none z-10 shrink-0">
- {/* 1. Far Left Tool Strip */}
- <aside className="w-12 bg-[#1b1c1e] border-r border-[#2b2d31] flex flex-col items-center py-2 z-20 shrink-0">
- <div className="flex flex-col items-center space-y-1 w-full px-1">
- {/* Brush (B) */}
- <button
- onClick={() => {
- onSelectTool('brush');
- if (isHidden) onToggleHidden();
- }}
- title="Brush Tool (B)"
- className={`w-9 h-9 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${
- currentTool === 'brush'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] shadow-xs'
- : 'text-[#8c9099] hover:text-[#d0d3d9] hover:bg-[#25272a]'
- }`}
- >
- <Paintbrush className="w-4 h-4" />
- <div className="absolute left-11 bg-[#18191b] text-[#cccccc] text-xs px-2 py-1 rounded border border-[#33353b] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 shadow-md">
- Brush (B)
- </div>
- </button>
-
- {/* Eraser (E) */}
- <button
- onClick={() => onSelectTool('eraser')}
- title="Eraser Tool (E)"
- className={`w-9 h-9 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${
- currentTool === 'eraser'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] shadow-xs'
- : 'text-[#8c9099] hover:text-[#d0d3d9] hover:bg-[#25272a]'
- }`}
- >
- <Eraser className="w-4 h-4" />
- <div className="absolute left-11 bg-[#18191b] text-[#cccccc] text-xs px-2 py-1 rounded border border-[#33353b] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 shadow-md">
- Eraser (E)
- </div>
- </button>
-
- {/* Pipette / Eyedropper (I / Hold Alt) */}
- <button
- onClick={() => onSelectTool('pipette')}
- title="Pipette / Eyedropper (I / Hold Alt)"
- className={`w-9 h-9 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${
- currentTool === 'pipette'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] shadow-xs'
- : 'text-[#8c9099] hover:text-[#d0d3d9] hover:bg-[#25272a]'
- }`}
- >
- <Pipette className="w-4 h-4" />
- <div className="absolute left-11 bg-[#18191b] text-[#cccccc] text-xs px-2 py-1 rounded border border-[#33353b] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 shadow-md">
- Pipette (I / Hold Alt)
- </div>
- </button>
-
- {/* Liquify Tool (J) */}
- <button
- onClick={() => {
- onSelectTool('liquify');
- if (isHidden) onToggleHidden();
- }}
- title="Liquify Tool (J)"
- className={`w-9 h-9 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${
- currentTool === 'liquify'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] shadow-xs'
- : 'text-[#8c9099] hover:text-[#d0d3d9] hover:bg-[#25272a]'
- }`}
- >
- <LiquifyIcon className="w-4 h-4" />
- <div className="absolute left-11 bg-[#18191b] text-[#cccccc] text-xs px-2 py-1 rounded border border-[#33353b] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 shadow-md">
- Liquify (J)
- </div>
- </button>
-
- <div className="w-5 h-px bg-[#2b2d31] my-0.5" />
-
- {/* Transform (Ctrl+T) */}
- <button
- onClick={() => {
- onSelectTool('transform');
- onTransformSelection?.();
- }}
- title="Free Transform (Ctrl+T)"
- className={`w-9 h-9 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${
- currentTool === 'transform'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] shadow-xs'
- : 'text-[#8c9099] hover:text-[#d0d3d9] hover:bg-[#25272a]'
- }`}
- >
- <Scaling className="w-4 h-4" />
- <div className="absolute left-11 bg-[#18191b] text-[#cccccc] text-xs px-2 py-1 rounded border border-[#33353b] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 shadow-md">
- Transform (Ctrl+T)
- </div>
- </button>
-
- {/* Rectangular Marquee (M) */}
- <button
- onClick={() => onSelectTool('select-rect')}
- title="Rectangular Marquee (M)"
- className={`w-9 h-9 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${
- currentTool === 'select-rect'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] shadow-xs'
- : 'text-[#8c9099] hover:text-[#d0d3d9] hover:bg-[#25272a]'
- }`}
- >
- <BoxSelect className="w-4 h-4" />
- <div className="absolute left-11 bg-[#18191b] text-[#cccccc] text-xs px-2 py-1 rounded border border-[#33353b] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 shadow-md">
- Rect Marquee (M)
- </div>
- </button>
-
- {/* Lasso Selection (L) */}
- <button
- onClick={() => onSelectTool('select-lasso')}
- title="Lasso Selection (L)"
- className={`w-9 h-9 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${
- currentTool === 'select-lasso'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] shadow-xs'
- : 'text-[#8c9099] hover:text-[#d0d3d9] hover:bg-[#25272a]'
- }`}
- >
- <Lasso className="w-4 h-4" />
- <div className="absolute left-11 bg-[#18191b] text-[#cccccc] text-xs px-2 py-1 rounded border border-[#33353b] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 shadow-md">
- Lasso Tool (L)
- </div>
- </button>
-
- {/* Magic Wand (W) */}
- <button
- onClick={() => onSelectTool('select-wand')}
- title="Magic Wand (W)"
- className={`w-9 h-9 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${
- currentTool === 'select-wand'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] shadow-xs'
- : 'text-[#8c9099] hover:text-[#d0d3d9] hover:bg-[#25272a]'
- }`}
- >
- <Wand2 className="w-4 h-4" />
- <div className="absolute left-11 bg-[#18191b] text-[#cccccc] text-xs px-2 py-1 rounded border border-[#33353b] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 shadow-md">
- Magic Wand (W)
- </div>
- </button>
-
- {/* Selection Pen */}
- <button
- onClick={() => onSelectTool('select-pen')}
- title="Selection Pen"
- className={`w-9 h-9 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${
- currentTool === 'select-pen'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] shadow-xs'
- : 'text-[#8c9099] hover:text-[#d0d3d9] hover:bg-[#25272a]'
- }`}
- >
- <PenTool className="w-4 h-4" />
- <div className="absolute left-11 bg-[#18191b] text-[#cccccc] text-xs px-2 py-1 rounded border border-[#33353b] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 shadow-md">
- Selection Pen
- </div>
- </button>
-
- {/* Selection Eraser */}
- <button
- onClick={() => onSelectTool('select-eraser')}
- title="Selection Eraser"
- className={`w-9 h-9 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${
- currentTool === 'select-eraser'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] shadow-xs'
- : 'text-[#8c9099] hover:text-[#d0d3d9] hover:bg-[#25272a]'
- }`}
- >
- <Eraser className="w-4 h-4" />
- <div className="absolute left-11 bg-[#18191b] text-[#cccccc] text-xs px-2 py-1 rounded border border-[#33353b] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 shadow-md">
- Selection Eraser
- </div>
- </button>
+ }
- <div className="w-5 h-px bg-[#2b2d31] my-0.5" />
+ if (currentTool === 'balloon') {
+ return (
+ <div className="p-2.5 space-y-3 overflow-y-auto flex-1">
+ <div className="text-[11px] font-medium text-[#e5e5e5]">Balloon</div>
+ <div className="space-y-0.5">
+ {(['ellipse', 'rounded-rect', 'jagged-flash', 'thought'] as const).map((shape) => (
+ <button
+ key={shape}
+ type="button"
+ onClick={() => onUpdateBalloonSettings?.({ shape })}
+ className={`w-full px-2 py-1 rounded text-left text-[11px] capitalize cursor-pointer ${
+ balloonSettings?.shape === shape
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
+ >
+ {shape.replace('-', ' ')}
+ </button>
+ ))}
+ </div>
+ <CompactSlider
+ label="Border"
+ valueLabel={`${balloonSettings?.strokeWidth ?? 3}px`}
+ min={1}
+ max={15}
+ value={balloonSettings?.strokeWidth ?? 3}
+ onChange={(v) => onUpdateBalloonSettings?.({ strokeWidth: v })}
+ />
+ </div>
+ );
+ }
- {/* Fill Tool (G) */}
- <button
- onClick={() => onSelectTool('fill')}
- title="Fill Tool (G)"
- className={`w-9 h-9 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${
- currentTool === 'fill'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] shadow-xs'
- : 'text-[#8c9099] hover:text-[#d0d3d9] hover:bg-[#25272a]'
- }`}
- >
- <PaintBucket className="w-4 h-4" />
- <div className="absolute left-11 bg-[#18191b] text-[#cccccc] text-xs px-2 py-1 rounded border border-[#33353b] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 shadow-md">
- Fill Tool (G)
- </div>
- </button>
+ if (currentTool === 'vector-edit') {
+ const activeMode = vectorEditSettings?.mode || 'pinch';
+ return (
+ <div className="p-2.5 space-y-3 overflow-y-auto flex-1">
+ <div className="text-[11px] font-medium text-[#e5e5e5]">Correct Line</div>
+ <div className="space-y-0.5">
+ {(['pinch', 'width', 'simplify'] as const).map((m) => (
+ <button
+ key={m}
+ type="button"
+ onClick={() => onUpdateVectorEditSettings?.({ mode: m })}
+ className={`w-full px-2 py-1 rounded text-left text-[11px] capitalize cursor-pointer ${
+ activeMode === m
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
+ >
+ {m}
+ </button>
+ ))}
+ </div>
+ <CompactSlider
+ label="Radius"
+ valueLabel={`${vectorEditSettings?.radius ?? 30}px`}
+ min={5}
+ max={150}
+ value={vectorEditSettings?.radius ?? 30}
+ onChange={(v) => onUpdateVectorEditSettings?.({ radius: v })}
+ />
+ {activeMode === 'pinch' && (
+ <CompactSlider
+ label="Pinch Level"
+ valueLabel={`${Math.round((vectorEditSettings?.pinchStrength ?? 0.65) * 100)}%`}
+ min={10}
+ max={100}
+ value={Math.round((vectorEditSettings?.pinchStrength ?? 0.65) * 100)}
+ onChange={(v) => onUpdateVectorEditSettings?.({ pinchStrength: v / 100 })}
+ />
+ )}
+ {activeMode === 'width' && (
+ <CompactSlider
+ label="Adjust Width"
+ valueLabel={`${(vectorEditSettings?.widthFactor ?? 1.2) >= 1 ? '+' : ''}${Math.round(((vectorEditSettings?.widthFactor ?? 1.2) - 1) * 100)}%`}
+ min={50}
+ max={200}
+ value={Math.round((vectorEditSettings?.widthFactor ?? 1.2) * 100)}
+ onChange={(v) => onUpdateVectorEditSettings?.({ widthFactor: v / 100 })}
+ />
+ )}
+ {activeMode === 'simplify' && (
+ <CompactSlider
+ label="Simplify"
+ valueLabel={`${(vectorEditSettings?.simplifyTolerance ?? 2.0).toFixed(1)}px`}
+ min={0.5}
+ max={12}
+ step={0.5}
+ value={vectorEditSettings?.simplifyTolerance ?? 2.0}
+ onChange={(v) => onUpdateVectorEditSettings?.({ simplifyTolerance: v })}
+ />
+ )}
+ {onOpenMangaEffects && (
+ <button
+ type="button"
+ onClick={onOpenMangaEffects}
+ className="w-full py-1.5 px-2 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[11px] text-[#e5e5e5] cursor-pointer"
+ >
+ Effect Lines...
+ </button>
+ )}
+ </div>
+ );
+ }
- {/* Text Tool (T) */}
- <button
- onClick={() => onSelectTool('text')}
- title="Text Tool (T)"
- className={`w-9 h-9 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${
- currentTool === 'text'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] shadow-xs'
- : 'text-[#8c9099] hover:text-[#d0d3d9] hover:bg-[#25272a]'
- }`}
- >
- <Type className="w-4 h-4" />
- <div className="absolute left-11 bg-[#18191b] text-[#cccccc] text-xs px-2 py-1 rounded border border-[#33353b] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 shadow-md">
- Text Tool (T)
- </div>
- </button>
+ return (
+ <div className="p-2.5 text-[11px] text-[#8a8a8a]">
+ <div className="text-[#e5e5e5] font-medium capitalize mb-1">{currentTool}</div>
+ <p className="leading-relaxed">Click or drag directly on the canvas.</p>
+ </div>
+ );
+ };
- {/* Frame Border Tool (F) */}
- <button
- onClick={() => onSelectTool('frame')}
- title="Frame Border Tool (F)"
- className={`w-9 h-9 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${
- currentTool === 'frame'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] shadow-xs'
- : 'text-[#8c9099] hover:text-[#d0d3d9] hover:bg-[#25272a]'
- }`}
- >
- <Frame className="w-4 h-4" />
- <div className="absolute left-11 bg-[#18191b] text-[#cccccc] text-xs px-2 py-1 rounded border border-[#33353b] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 shadow-md">
- Frame Border (F)
- </div>
- </button>
+ const visibleBuiltinBrushes = BUILTIN_BRUSHES.filter((b) => {
+ if (selectedCategory === 'all') return true;
+ if (selectedCategory === 'csp') return false;
+ return b.category === selectedCategory;
+ });
- {/* Speech Balloon Tool (B) */}
- <button
- onClick={() => onSelectTool('balloon')}
- title="Speech Balloon Tool"
- className={`w-9 h-9 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${
- currentTool === 'balloon'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] shadow-xs'
- : 'text-[#8c9099] hover:text-[#d0d3d9] hover:bg-[#25272a]'
- }`}
- >
- <MessageSquare className="w-4 h-4" />
- <div className="absolute left-11 bg-[#18191b] text-[#cccccc] text-xs px-2 py-1 rounded border border-[#33353b] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 shadow-md">
- Speech Balloon
- </div>
- </button>
+ const showCspBrushes = selectedCategory === 'all' || selectedCategory === 'csp';
+ const currentAntiAlias = brushSettings.antiAlias ?? 2;
- {/* Correct Line (Vector Edit) Tool (Y) */}
- <button
- onClick={() => onSelectTool('vector-edit')}
- title="Correct Line (Vector Pinch/Width/Simplify)"
- className={`w-9 h-9 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${
- currentTool === 'vector-edit'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] shadow-xs'
- : 'text-[#8c9099] hover:text-[#d0d3d9] hover:bg-[#25272a]'
- }`}
- >
- <Spline className="w-4 h-4" />
- <div className="absolute left-11 bg-[#18191b] text-[#cccccc] text-xs px-2 py-1 rounded border border-[#33353b] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 shadow-md">
- Correct Line (Vector)
- </div>
- </button>
+ return (
+ <div className="flex h-full select-none z-10 shrink-0 gap-px bg-[#161616]">
+ {/* 1. Narrow 44px Tool Strip */}
+ <aside className="w-[44px] bg-[#202020] flex flex-col items-center py-1.5 z-20 shrink-0">
+ <div className="flex flex-col items-center gap-0.5 w-full px-1">
+ {toolItems.map((item) => {
+ const isActive = currentTool === item.id;
+ return (
+ <React.Fragment key={item.id}>
+ <button
+ type="button"
+ onClick={() => (item.onClick ? item.onClick() : onSelectTool(item.id))}
+ title={item.label}
+ className={`relative w-8 h-7 rounded flex items-center justify-center transition-colors cursor-pointer ${
+ isActive
+ ? 'bg-[#2c2c2c] text-[var(--accent)]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'
+ }`}
+ >
+ {isActive && (
+ <span
+ className="absolute left-0 top-1.5 bottom-1.5 w-[2px] rounded-full"
+ style={{ backgroundColor: 'var(--accent)' }}
+ />
+ )}
+ {item.icon}
+ </button>
+ {item.dividerAfter && <div className="w-4 h-px bg-[#2c2c2c] my-1" />}
+ </React.Fragment>
+ );
+ })}
</div>
- {/* Bottom Swatches, Swap Button, and Hide/Show Button */}
- <div className="mt-auto flex flex-col items-center space-y-1.5 pb-2 w-full pt-2 border-t border-[#26282c]">
- {/* Overlapping Primary / Secondary Color Swatches */}
- <div className="relative w-8 h-8">
- {/* Secondary Color Swatch (bottom-right) */}
+ {/* Bottom Color Swatches & Collapse Toggle */}
+ <div className="mt-auto flex flex-col items-center gap-1.5 pt-2 pb-1 w-full">
+ <div className="relative w-6 h-6">
<div
onClick={onSwapColors}
- title={`Secondary Color: ${secondaryColor} (Click or press X to swap)`}
- className="absolute bottom-0 right-0 w-5 h-5 rounded-[1px] border border-[#44464c] cursor-pointer hover:border-white shadow-xs z-0"
+ title={`Secondary: ${secondaryColor} (X to swap, D to reset)`}
+ className="absolute bottom-0 right-0 w-4 h-4 rounded-sm cursor-pointer shadow-[0_0_0_1px_rgba(255,255,255,0.18)]"
style={{ backgroundColor: secondaryColor }}
/>
-
- {/* Primary Color Swatch (top-left) */}
<div
onClick={() => {
- if (isTransparentColor) {
- onToggleTransparentColor?.();
- } else {
- onSwapColors();
- }
+ if (isTransparentColor) onToggleTransparentColor?.();
+ else onSwapColors();
}}
- title={`Primary Active Color: ${primaryColor} (Click to select/swap)`}
- className={`absolute top-0 left-0 w-5 h-5 rounded-[1px] cursor-pointer shadow-md z-10 transition-all ${
+ title={`Primary: ${primaryColor}`}
+ className={`absolute top-0 left-0 w-4 h-4 rounded-sm cursor-pointer z-10 ${
!isTransparentColor
- ? 'border border-white ring-1 ring-white/40'
- : 'border border-[#44464c] hover:border-white opacity-80'
+ ? 'shadow-[0_0_0_1.5px_var(--accent)]'
+ : 'opacity-70 shadow-[0_0_0_1px_rgba(255,255,255,0.2)]'
}`}
style={{ backgroundColor: primaryColor }}
/>
</div>
- {/* Transparent Color Swatch (Clip Studio Paint style 'C' key toggle) */}
<div
onClick={onToggleTransparentColor}
- title="Transparent Ink / Color (C) - Brush as textured eraser"
- className={`w-7 h-3 rounded-[1px] border cursor-pointer relative overflow-hidden transition-all ${
- isTransparentColor
- ? 'border-[#38bdf8] ring-1 ring-[#38bdf8] shadow-xs scale-105'
- : 'border-[#44464c] hover:border-white opacity-80 hover:opacity-100'
+ title="Transparent Ink (C)"
+ className={`w-6 h-2.5 rounded-xs cursor-pointer transition-all ${
+ isTransparentColor ? 'shadow-[0_0_0_1.5px_var(--accent)]' : 'opacity-65 hover:opacity-100'
}`}
style={{
- backgroundImage:
- 'linear-gradient(45deg, #777 25%, transparent 25%), linear-gradient(-45deg, #777 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #777 75%), linear-gradient(-45deg, transparent 75%, #777 75%)',
+ backgroundImage: 'repeating-conic-gradient(#777 0% 25%, #ccc 0% 50%)',
backgroundSize: '4px 4px',
- backgroundPosition: '0 0, 0 2px, 2px -2px, -2px 0px',
- backgroundColor: '#bbb',
}}
/>
- {/* Swap Shortcut Button (X) */}
<button
+ type="button"
onClick={onSwapColors}
title="Swap Colors (X)"
- className="p-1 text-[#8c9099] hover:text-[#e0e0e0] hover:bg-[#282a2d] rounded transition-colors cursor-pointer"
+ className="w-7 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"
>
<ArrowLeftRight className="w-3 h-3" />
</button>
- {/* Panel Visibility Toggle Button */}
<button
+ type="button"
onClick={onToggleHidden}
- title={isHidden ? 'Show Brush Settings ( [ )' : 'Hide Brush Settings ( [ )'}
- className="p-1.5 text-[#8c9099] hover:text-[#5ce1e6] hover:bg-[#282a2d] rounded transition-colors cursor-pointer"
+ title={isHidden ? 'Show Panel (Shift+Tab)' : 'Hide Panel (Shift+Tab)'}
+ className="w-7 h-7 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"
>
- {isHidden ? <PanelLeftOpen className="w-4 h-4" /> : <PanelLeftClose className="w-4 h-4" />}
+ {isHidden ? <PanelLeftOpen className="w-3.5 h-3.5" /> : <PanelLeftClose className="w-3.5 h-3.5" />}
</button>
</div>
</aside>
- {/* 2. Tool Settings & Brushes Panel (Collapsible & Resizable) */}
+ {/* 2. CSP Sub-Tool List + Sub-Tool Detail Inspector */}
{!isHidden && (
<aside
style={{ width }}
- className="relative bg-[#1e2023] border-r border-[#2b2d31] flex flex-col text-[#cccccc] text-xs shrink-0 overflow-hidden"
+ className="relative bg-[#202020] flex flex-col text-[#e5e5e5] text-xs shrink-0 overflow-hidden"
>
{isBrushOrEraser ? (
<>
- {/* TOP SECTION: Brushes List */}
- <div
- style={{ height: topHeight }}
- className="flex flex-col shrink-0 overflow-hidden border-b border-[#2b2d31]"
- >
- {/* Top Section Header: Sub Tool [Tool] with view toggle & hide button */}
- <div className="h-8 px-2.5 flex items-center justify-between border-b border-[#2b2d31] bg-[#1a1b1e] shrink-0">
- <span className="text-xs font-semibold tracking-tight text-white truncate max-w-[150px]" title={`Sub Tool [${activeToolLabel}]`}>
- Sub Tool [{activeToolLabel}]
- </span>
-
- <div className="flex items-center space-x-1">
- {/* Import CSP Brush Button */}
- <button
- onClick={() => sutInputRef.current?.click()}
- title="Import Clip Studio Paint Brush (.sut)"
- className="flex items-center space-x-1 px-1.5 py-0.5 rounded bg-[#202226] hover:bg-[#2a2e36] text-[#9fa3ad] hover:text-[#5ce1e6] border border-[#2f323a] text-[10px] font-medium transition-colors cursor-pointer"
- >
- <Plus className="w-3 h-3 text-[#5ce1e6]" />
- <span>Import .sut</span>
- </button>
-
- {/* View Mode Toggle (Preview vs Compact) */}
- <button
- onClick={toggleBrushViewMode}
- title={brushViewMode === 'preview' ? 'Switch to Compact List View' : 'Switch to Stroke Preview View (CSP Style)'}
- className={`p-1 rounded transition-colors cursor-pointer ${
- brushViewMode === 'preview'
- ? 'text-[#5ce1e6] bg-[#293d45]/40 hover:bg-[#293d45]/70'
- : 'text-[#828690] hover:text-[#cccccc] hover:bg-[#282a2e]'
- }`}
+ {/* Category Filter Strip + Import .sut */}
+ <div className="px-1.5 py-1.5 flex items-center gap-1 shrink-0">
+ <select
+ value={selectedCategory}
+ onChange={(e) => setSelectedCategory(e.target.value as 'all' | BrushCategory | 'csp')}
+ aria-label="Brush Category"
+ className="flex-1 min-w-0 h-5 bg-[#161616] text-[#e5e5e5] text-[11px] px-1.5 rounded cursor-pointer"
>
- <LayoutList className="w-3.5 h-3.5" />
- </button>
+ <option value="all" className="bg-[#202020]">All Brushes</option>
+ <option value="pencil-line" className="bg-[#202020]">Pencil &amp; Ink</option>
+ <option value="color-paint" className="bg-[#202020]">Color &amp; Paint</option>
+ <option value="csp" className="bg-[#202020]">CSP Imported</option>
+ </select>
<button
- onClick={onToggleHidden}
- title="Hide Panel ( [ )"
- className="p-1 text-[#828690] hover:text-rose-400 hover:bg-[#282a2e] rounded transition-colors cursor-pointer"
+ type="button"
+ onClick={() => sutInputRef.current?.click()}
+ title="Import CSP Brush (.sut)"
+ className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] shrink-0 cursor-pointer"
>
- <X className="w-3.5 h-3.5" />
+ <Plus className="w-3 h-3" />
</button>
</div>
- </div>
-
- <input
- type="file"
- ref={sutInputRef}
- accept=".sut"
- className="hidden"
- onChange={(e) => {
- const file = e.target.files?.[0];
- if (file) {
- handleImportSut(file);
- }
- e.target.value = '';
- }}
- />
- {/* Category Filter Tabs */}
- <div className="px-2 pt-1 pb-1 flex items-center space-x-1 border-b border-[#25272c] overflow-x-auto no-scrollbar shrink-0 bg-[#161719]">
- {[
- { id: 'all', label: 'All' },
- { id: 'pencil-line', label: 'Pencil & Line' },
- { id: 'color-paint', label: 'Color & Paint' },
- { id: 'csp', label: `CSP${customBrushes.length > 0 ? ` (${customBrushes.length})` : ''}` },
- ].map((tab) => {
- const isActive = selectedCategory === tab.id;
- return (
- <button
- key={tab.id}
- onClick={() => setSelectedCategory(tab.id as any)}
- className={`px-2 py-0.5 rounded text-[10px] font-medium transition-all whitespace-nowrap cursor-pointer ${
- isActive
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] shadow-xs'
- : 'text-[#828690] hover:text-[#d0d3d9] hover:bg-[#202226] border border-transparent'
- }`}
- >
- {tab.label}
- </button>
- );
- })}
- </div>
+ <input
+ type="file"
+ ref={sutInputRef}
+ accept=".sut"
+ className="hidden"
+ onChange={(e) => {
+ const file = e.target.files?.[0];
+ if (file) handleImportSut(file);
+ e.target.value = '';
+ }}
+ />
- {/* Brushes List: Built-in Categories (Pencil & Line, Color & Paint) + Imported CSP Brushes */}
- <div
- onDragOver={(e) => {
- if (e.dataTransfer.types.includes('Files')) {
- e.preventDefault();
- setIsDraggingFileOver(true);
- }
- }}
- onDragLeave={() => setIsDraggingFileOver(false)}
- onDrop={(e) => {
- e.preventDefault();
- setIsDraggingFileOver(false);
- const files = Array.from(e.dataTransfer.files).filter((f) =>
- f.name.toLowerCase().endsWith('.sut')
- );
- if (files.length > 0) {
- for (const f of files) {
- handleImportSut(f);
+ {/* Compact High-Density Sub-Tool List */}
+ <div
+ onDragOver={(e) => {
+ if (e.dataTransfer.types.includes('Files')) {
+ e.preventDefault();
+ setIsDraggingFileOver(true);
}
- }
- }}
- className={`flex-1 overflow-y-auto p-2 space-y-1.5 relative ${
- isDraggingFileOver ? 'ring-2 ring-inset ring-[#5ce1e6] bg-[#5ce1e6]/5' : ''
- }`}
- >
- {/* Drag overlay indicator */}
- {isDraggingFileOver && (
- <div className="absolute inset-0 bg-[#161d22]/95 border-2 border-dashed border-[#5ce1e6] rounded z-30 flex flex-col items-center justify-center p-3 text-center pointer-events-none">
- <FolderDown className="w-6 h-6 text-[#5ce1e6] mb-1 animate-bounce" />
- <span className="text-xs font-semibold text-white">Drop .sut brush file</span>
- <span className="text-[10px] text-[#5ce1e6]">Import to Ink Studio</span>
- </div>
- )}
+ }}
+ onDragLeave={() => setIsDraggingFileOver(false)}
+ onDrop={(e) => {
+ e.preventDefault();
+ setIsDraggingFileOver(false);
+ const files = Array.from(e.dataTransfer.files).filter((f) =>
+ f.name.toLowerCase().endsWith('.sut')
+ );
+ for (const f of files) handleImportSut(f);
+ }}
+ className="flex-1 overflow-y-auto px-1.5 py-0.5 space-y-0.5 relative min-h-[84px]"
+ >
+ {isDraggingFileOver && (
+ <div className="absolute inset-1 bg-[#161616]/95 rounded flex flex-col items-center justify-center p-2 text-center z-30 pointer-events-none">
+ <FolderDown className="w-4 h-4 text-[var(--accent)] mb-1" />
+ <span className="text-[10px] text-[#e5e5e5]">Drop .sut</span>
+ </div>
+ )}
- {/* Importing progress notice */}
- {isImportingSut && (
- <div className="p-2 rounded bg-[#1e2329] border border-[#37444d] text-center text-xs text-[#5ce1e6] flex items-center justify-center space-x-1.5 animate-pulse">
- <Loader2 className="w-3.5 h-3.5 animate-spin" />
- <span>{importStatus || 'Importing Clip Studio Paint Brush...'}</span>
- </div>
- )}
-
- {/* Category: Pencil & Line */}
- {(selectedCategory === 'all' || selectedCategory === 'pencil-line') && (
- <div className="space-y-1.5">
- {selectedCategory === 'all' && (
- <div className="pt-0.5 pb-0.5 px-1 flex items-center justify-between">
- <span className="text-[10px] font-semibold uppercase tracking-wider text-[#757a87]">
- Pencil & Line
- </span>
- </div>
- )}
- {BUILTIN_BRUSHES.filter((b) => b.category === 'pencil-line').map((item) => {
- const isSelected =
- currentTool === 'brush' &&
- (brushSettings.preset === item.id || (!brushSettings.preset && item.id === 'pencil-2b'));
+ {isImportingSut && (
+ <div className="px-2 py-1 rounded bg-[#2c2c2c] text-[10px] text-[#e5e5e5] flex items-center gap-1.5">
+ <Loader2 className="w-3 h-3 animate-spin" />
+ <span className="truncate">Importing...</span>
+ </div>
+ )}
+
+ {visibleBuiltinBrushes.map((item) => {
+ const isSelected =
+ currentTool === 'brush' &&
+ (brushSettings.preset === item.id || (!brushSettings.preset && item.id === 'pencil-2b'));
+
+ return (
+ <button
+ key={item.id}
+ type="button"
+ onClick={() => handleSelectBrushPreset(item.id)}
+ title={`${item.name} - ${item.desc}`}
+ className={`w-full flex items-center gap-1.5 px-2 py-1 rounded text-left transition-colors cursor-pointer ${
+ isSelected
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
+ >
+ {item.icon === 'pencil' ? (
+ <Pencil className="w-3 h-3 shrink-0 opacity-80" />
+ ) : item.icon === 'palette' ? (
+ <Palette className="w-3 h-3 shrink-0 opacity-80" />
+ ) : item.icon === 'square' ? (
+ <Square className="w-3 h-3 shrink-0 opacity-80" />
+ ) : (
+ <Paintbrush className="w-3 h-3 shrink-0 opacity-80" />
+ )}
+ <span className="text-[11px] truncate leading-tight flex-1">{item.name}</span>
+ </button>
+ );
+ })}
+ {showCspBrushes &&
+ customBrushes.map((brush) => {
+ const isSelected = currentTool === 'brush' && brushSettings.preset === brush.id;
return (
<div
- key={item.id}
- onClick={() => handleSelectBrushPreset(item.id)}
- title={`${item.name} - ${item.desc}`}
- className={`rounded cursor-pointer transition-colors border ${
+ key={brush.id}
+ onClick={() => handleSelectCustomBrush(brush)}
+ title={brush.name}
+ className={`group flex items-center justify-between gap-1 px-2 py-1 rounded cursor-pointer transition-colors ${
isSelected
- ? 'bg-[#293d45] text-white border-[#3e5e6b] shadow-xs'
- : 'bg-[#1b1c1f]/60 hover:bg-[#232529] text-[#9fa3ad] hover:text-white border-[#27292e]/60 hover:border-[#34373e]'
- } ${brushViewMode === 'preview' ? 'p-1.5' : 'px-2 py-1.5'}`}
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
>
- <div className="flex items-center space-x-1.5 min-w-0">
- {item.icon === 'pencil' ? (
- <Pencil
- className={`w-3.5 h-3.5 shrink-0 ${
- isSelected ? 'text-amber-400' : 'text-[#8c9099]'
- }`}
+ <div className="flex items-center gap-1.5 min-w-0">
+ {brush.tipDataUrl ? (
+ <img
+ src={brush.tipDataUrl}
+ alt=""
+ className="w-3 h-3 object-contain shrink-0 brightness-125"
/>
) : (
- <Paintbrush
- className={`w-3.5 h-3.5 shrink-0 ${
- isSelected ? 'text-[#5ce1e6]' : 'text-[#8c9099]'
- }`}
- />
+ <Sparkles className="w-3 h-3 shrink-0 opacity-80" />
)}
- <div className="min-w-0">
- <span className="font-medium text-xs block truncate leading-tight">
- {item.name}
- </span>
- {brushViewMode === 'compact' && (
- <span className="text-[10px] text-[#717682] block truncate leading-tight">
- {item.desc}
- </span>
- )}
- </div>
- </div>
-
- {brushViewMode === 'preview' && (
- <div
- className={`mt-1.5 w-full h-7 rounded-[3px] overflow-hidden flex items-center justify-center transition-colors ${
- isSelected
- ? 'bg-[#18262b] border border-[#3e5e6b]/40'
- : 'bg-[#141517] border border-[#24262b]'
- }`}
- title={`${item.name} stroke preview`}
- >
- <BrushPreview
- preset={item.id}
- strokeColor="#ffffff"
- height={28}
- />
- </div>
- )}
- </div>
- );
- })}
- </div>
- )}
-
- {/* Category: Color & Paint (Soft Airbrush, Square Color Brush) */}
- {(selectedCategory === 'all' || selectedCategory === 'color-paint') && (
- <div className={`space-y-1.5 ${selectedCategory === 'all' ? 'pt-2' : ''}`}>
- {selectedCategory === 'all' && (
- <div className="pt-1 pb-0.5 px-1 flex items-center justify-between border-t border-[#26282c]">
- <span className="text-[10px] font-semibold uppercase tracking-wider text-[#757a87]">
- Color & Paint
- </span>
- </div>
- )}
- {BUILTIN_BRUSHES.filter((b) => b.category === 'color-paint').map((item) => {
- const isSelected =
- currentTool === 'brush' && brushSettings.preset === item.id;
-
- return (
- <div
- key={item.id}
- onClick={() => handleSelectBrushPreset(item.id)}
- className={`rounded cursor-pointer transition-colors border ${
- isSelected
- ? 'bg-[#293d45] text-white border-[#3e5e6b] shadow-xs'
- : 'bg-[#1b1c1f]/60 hover:bg-[#232529] text-[#9fa3ad] hover:text-white border-[#27292e]/60 hover:border-[#34373e]'
- } ${brushViewMode === 'preview' ? 'p-1.5' : 'px-2.5 py-1.5'}`}
- >
- <div className="flex items-center justify-between min-w-0">
- <div className="flex items-center space-x-1.5 min-w-0">
- {item.icon === 'palette' ? (
- <Palette
- className={`w-3.5 h-3.5 shrink-0 ${
- isSelected ? 'text-emerald-400' : 'text-[#8c9099]'
- }`}
- />
- ) : item.icon === 'square' ? (
- <Square
- className={`w-3.5 h-3.5 shrink-0 ${
- isSelected ? 'text-teal-400' : 'text-[#8c9099]'
- }`}
- />
- ) : (
- <Paintbrush
- className={`w-3.5 h-3.5 shrink-0 ${
- isSelected ? 'text-[#5ce1e6]' : 'text-[#8c9099]'
- }`}
- />
- )}
- <div className="min-w-0">
- <span className="font-medium text-xs block truncate leading-tight">
- {item.name}
- </span>
- {brushViewMode === 'compact' && (
- <span className="text-[10px] text-[#717682] block truncate leading-tight">
- {item.desc}
- </span>
- )}
- </div>
- </div>
+ <span className="text-[11px] truncate leading-tight">{brush.name}</span>
</div>
-
- {brushViewMode === 'preview' && (
- <div
- className={`mt-1.5 w-full h-7 rounded-[3px] overflow-hidden flex items-center justify-center transition-colors ${
- isSelected
- ? 'bg-[#18262b] border border-[#3e5e6b]/40'
- : 'bg-[#141517] border border-[#24262b]'
- }`}
- title={`${item.name} stroke preview`}
- >
- <BrushPreview
- preset={item.id}
- strokeColor="#ffffff"
- height={28}
- />
- </div>
- )}
+ <button
+ type="button"
+ onClick={(e) => handleDeleteCustomBrush(e, brush.id)}
+ title="Delete brush"
+ className="opacity-0 group-hover:opacity-100 text-[#8a8a8a] hover:text-red-400 shrink-0 cursor-pointer"
+ >
+ <Trash2 className="w-2.5 h-2.5" />
+ </button>
</div>
);
})}
- </div>
- )}
-
- {/* Category: Clip Studio Paint Imported Brushes */}
- {(selectedCategory === 'all' || selectedCategory === 'csp') && (
- <>
- {customBrushes.length > 0 ? (
- <div className={`space-y-1.5 ${selectedCategory === 'all' ? 'pt-2' : ''}`}>
- {selectedCategory === 'all' && (
- <div className="pt-1 pb-0.5 px-1 flex items-center justify-between border-t border-[#26282c]">
- <span className="text-[10px] font-semibold uppercase tracking-wider text-[#757a87]">
- Clip Studio Paint ({customBrushes.length})
- </span>
- <span className="text-[9px] px-1.5 py-0.2 rounded bg-[#5ce1e6]/10 text-[#5ce1e6] font-mono">
- SUT
- </span>
- </div>
- )}
-
- {customBrushes.map((brush) => {
- const isSelected = currentTool === 'brush' && brushSettings.preset === brush.id;
- const tipImg = brush.tipDataUrl
- ? getPreloadedTipImage(brush.tipDataUrl) || undefined
- : undefined;
-
- return (
- <div
- key={brush.id}
- onClick={() => handleSelectCustomBrush(brush)}
- className={`rounded cursor-pointer transition-colors border group relative ${
- isSelected
- ? 'bg-[#293d45] text-white border-[#3e5e6b] shadow-xs'
- : 'bg-[#1b1c1f]/60 hover:bg-[#232529] text-[#9fa3ad] hover:text-white border-[#27292e]/60 hover:border-[#34373e]'
- } ${brushViewMode === 'preview' ? 'p-1.5' : 'px-2.5 py-1.5'}`}
- >
- <div className="flex items-center justify-between min-w-0">
- <div className="flex items-center space-x-1.5 min-w-0">
- {brush.tipDataUrl ? (
- <div className="w-4 h-4 rounded-[2px] bg-[#121315] border border-[#2b2d31] flex items-center justify-center overflow-hidden shrink-0">
- <img
- src={brush.tipDataUrl}
- alt=""
- className="w-full h-full object-contain brightness-125"
- />
- </div>
- ) : (
- <Sparkles
- className={`w-3.5 h-3.5 shrink-0 ${
- isSelected ? 'text-[#5ce1e6]' : 'text-[#8c9099]'
- }`}
- />
- )}
- <div className="min-w-0">
- <span className="font-medium text-xs block truncate leading-tight">
- {brush.name}
- </span>
- {brushViewMode === 'compact' && (
- <span className="text-[10px] text-[#717682] block truncate leading-tight">
- {brush.desc || 'Clip Studio Paint Brush'}
- </span>
- )}
- </div>
- </div>
-
- <div className="flex items-center space-x-1 shrink-0 ml-1.5">
- <button
- onClick={(e) => handleDeleteCustomBrush(e, brush.id)}
- title="Delete brush"
- className="opacity-0 group-hover:opacity-100 p-0.5 hover:text-rose-400 rounded transition-opacity"
- >
- <Trash2 className="w-3 h-3" />
- </button>
- </div>
- </div>
-
- {/* Authentic CSP S-Curve Stroke Preview */}
- {brushViewMode === 'preview' && (
- <div
- className={`mt-1.5 w-full h-7 rounded-[3px] overflow-hidden flex items-center justify-center transition-colors ${
- isSelected
- ? 'bg-[#18262b] border border-[#3e5e6b]/40'
- : 'bg-[#141517] border border-[#24262b]'
- }`}
- title={`${brush.name} stroke preview`}
- >
- <BrushPreview
- preset={brush.id}
- settings={brush}
- customTipImage={tipImg}
- customTipAngle={brush.angle}
- strokeColor="#ffffff"
- height={28}
- />
- </div>
- )}
- </div>
- );
- })}
- </div>
- ) : selectedCategory === 'csp' ? (
- <div className="text-center py-6 px-3 border border-dashed border-[#2d3036] rounded-lg my-2">
- <FolderDown className="w-6 h-6 text-[#5ce1e6]/60 mx-auto mb-1.5" />
- <p className="text-xs font-medium text-[#cccccc]">No imported CSP brushes</p>
- <p className="text-[10px] text-[#717682] mt-0.5 mb-2.5">
- Drag & drop any Clip Studio Paint .sut file here
- </p>
- <button
- onClick={() => sutInputRef.current?.click()}
- className="inline-flex items-center space-x-1 px-2.5 py-1 rounded bg-[#202226] hover:bg-[#293d45] text-[#5ce1e6] border border-[#33363e] text-xs font-medium transition-colors cursor-pointer"
- >
- <Plus className="w-3.5 h-3.5" />
- <span>Select .sut File</span>
- </button>
- </div>
- ) : null}
- </>
- )}
- </div>
- </div>
-
- {/* RESIZABLE HORIZONTAL DIVIDER between Brushes and Tool Settings */}
- <div
- onMouseDown={handleHeightResizeMouseDown}
- title="Drag to resize height"
- className="group relative h-1.5 w-full cursor-row-resize flex items-center justify-center shrink-0 hover:bg-[#5ce1e6]/40 transition-colors z-20"
- >
- <div className="w-8 h-0.5 bg-[#3a3d44] group-hover:bg-[#5ce1e6] rounded-full transition-colors" />
- </div>
-
- {/* BOTTOM SECTION: Tool Property & Brush Size Presets */}
- <div className="flex-1 flex flex-col overflow-hidden">
- {/* Sub-Palette Tabs: Tool Property vs Brush Size */}
- <div className="h-9 px-2 flex items-center justify-between border-b border-[#2b2d31] bg-[#1a1b1e] shrink-0">
- <div className="flex items-center space-x-1">
- <button
- type="button"
- onClick={() => handleSelectBottomTab('settings')}
- className={`px-2 py-0.5 rounded text-xs font-medium transition-colors cursor-pointer truncate max-w-[140px] ${
- bottomTab === 'settings'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] shadow-xs'
- : 'text-[#828690] hover:text-[#cccccc] hover:bg-[#202226] border border-transparent'
- }`}
- title={`Tool property [${activeToolLabel}]`}
- >
- Tool property [{activeToolLabel}]
- </button>
- <button
- type="button"
- onClick={() => handleSelectBottomTab('size')}
- className={`px-2.5 py-1 rounded text-xs font-medium transition-colors flex items-center space-x-1 cursor-pointer ${
- bottomTab === 'size'
- ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] shadow-xs'
- : 'text-[#828690] hover:text-[#cccccc] hover:bg-[#202226] border border-transparent'
- }`}
- >
- <span>Brush Size</span>
- <span className="text-[10px] font-mono text-[#5ce1e6] bg-[#141517] px-1 rounded border border-[#2b2d31]">
- {brushSettings.size}
- </span>
- </button>
- </div>
- </div>
-
- {bottomTab === 'size' ? (
- <BrushSizePalette
- currentSize={brushSettings.size}
- onSelectSize={(newSize) => handleUpdateBrushSettings({ size: newSize })}
- activeBrushName={
- currentTool === 'eraser'
- ? 'Eraser'
- : brushSettings.brushName || activeCustomBrush?.name || activeBuiltinBrush?.name || activePencilConfig?.name || 'Brush'
- }
- tool={currentTool}
- presetId={currentTool === 'eraser' ? ERASER_PRESET_ID : brushSettings.preset}
- onResetSizeToDefault={() => {
- const def = resetBrushSettingsToDefault(currentTool === 'eraser' ? ERASER_PRESET_ID : (brushSettings.preset || 'pencil-2b'), customBrushes);
- if (def.size !== undefined) {
- handleUpdateBrushSettings({ size: def.size });
- }
- }}
- onResetAllSettings={() => {
- const def = resetBrushSettingsToDefault(currentTool === 'eraser' ? ERASER_PRESET_ID : (brushSettings.preset || 'pencil-2b'), customBrushes);
- handleUpdateBrushSettings(def);
- }}
- className="flex-1 overflow-y-auto"
- />
- ) : (
- <div className="flex-1 overflow-y-auto p-3.5 space-y-4">
- {/* Active Tool Name Indicator */}
- <div className="flex items-center justify-between pb-1 text-white font-medium text-xs border-b border-[#26282c]">
- <div className="flex items-center space-x-2 min-w-0">
- {currentTool === 'brush' ? (
- isPencilActive ? (
- <>
- <Pencil className="w-4 h-4 text-amber-400 shrink-0" />
- <span className="truncate">{activePencilConfig?.name || 'Pencil'}</span>
- </>
- ) : isCustomBrushActive ? (
- <>
- <Sparkles className="w-4 h-4 text-[#5ce1e6] shrink-0" />
- <span className="truncate">
- {brushSettings.brushName || activeCustomBrush?.name || 'CSP Brush'}
- </span>
- </>
- ) : activeBuiltinBrush ? (
- <>
- {activeBuiltinBrush.icon === 'palette' ? (
- <Palette className="w-4 h-4 text-emerald-400 shrink-0" />
- ) : activeBuiltinBrush.icon === 'square' ? (
- <Square className="w-4 h-4 text-teal-400 shrink-0" />
- ) : (
- <Paintbrush className="w-4 h-4 text-[#5ce1e6] shrink-0" />
- )}
- <span className="truncate">{activeBuiltinBrush.name}</span>
- </>
- ) : (
- <>
- <Paintbrush className="w-4 h-4 text-[#5ce1e6] shrink-0" />
- <span className="truncate">Round Brush</span>
- </>
- )
- ) : (
- <>
- <Eraser className="w-4 h-4 text-rose-400 shrink-0" />
- <span>Eraser</span>
- </>
- )}
- </div>
-
- {currentTool === 'brush' && isPencilActive && activePencilConfig && (
- <span className="text-[10px] px-1.5 py-0.5 rounded font-mono bg-amber-500/15 text-amber-300 border border-amber-500/30 uppercase shrink-0">
- Grade {activePencilConfig.gradeLabel}
- </span>
- )}
- {currentTool === 'brush' && activeBuiltinBrush && !isPencilActive && (
- <span className={`text-[10px] px-1.5 py-0.5 rounded font-mono border uppercase shrink-0 ${activeBuiltinBrush.badgeBg} ${activeBuiltinBrush.badgeText} ${activeBuiltinBrush.badgeBorder}`}>
- {activeBuiltinBrush.badge}
- </span>
- )}
- {currentTool === 'brush' && isCustomBrushActive && (
- <span className="text-[10px] px-1.5 py-0.5 rounded font-mono bg-cyan-500/15 text-cyan-300 border border-cyan-500/30 uppercase shrink-0">
- CSP
- </span>
- )}
- </div>
-
- {/* Brush Tip Shape Card (Custom CSP or Procedural Tip) */}
- {brushSettings.customTipDataUrl && (
- <div className="bg-[#141517] border border-[#292b30] rounded p-2 flex items-center space-x-2.5">
- <div className="w-9 h-9 rounded bg-[#0d0e10] border border-[#2b2d31] flex items-center justify-center overflow-hidden shrink-0">
- <img
- src={brushSettings.customTipDataUrl}
- alt="Tip Shape"
- className="w-full h-full object-contain filter invert contrast-200"
- />
- </div>
- <div className="min-w-0 flex-1">
- <span className="text-[11px] font-medium text-[#cccccc] block truncate">
- {activeBuiltinBrush ? 'Procedural Tip Shape' : 'Extracted Tip Mask'}
- </span>
- <span className="text-[10px] text-[#717682] block truncate">
- {activeBuiltinBrush
- ? `${activeBuiltinBrush.name} Mask`
- : activeCustomBrush?.tipWidth && activeCustomBrush?.tipHeight
- ? `${activeCustomBrush.tipWidth} × ${activeCustomBrush.tipHeight} px`
- : 'SUT Tip Bitmap'}
- </span>
- </div>
- </div>
- )}
-
- {/* Dynamic Live Brush Dynamics Preview Card */}
- <div className="bg-[#141517] border border-[#292b30] rounded p-2.5 space-y-1.5 shadow-sm">
- <div className="flex items-center justify-between text-xs text-[#8c9099]">
- <span className="font-medium text-[#cccccc] flex items-center space-x-1.5 text-[11px]">
- <Sparkles className="w-3.5 h-3.5 text-[#5ce1e6]" />
- <span>Live Stroke Preview</span>
- </span>
-
- <button
- onClick={() => setUsePrimaryColorPreview(!usePrimaryColorPreview)}
- title={usePrimaryColorPreview ? 'Switch to Neutral White Preview' : 'Switch to Active Color Preview'}
- className="flex items-center space-x-1 px-1.5 py-0.5 rounded bg-[#1f2125] hover:bg-[#282b30] border border-[#33363d] text-[10px] text-[#a0a4ae] hover:text-white transition-colors cursor-pointer"
- >
- <span
- className="w-2 h-2 rounded-full inline-block border border-white/40"
- style={{ backgroundColor: usePrimaryColorPreview ? primaryColor : '#ffffff' }}
- />
- <span>{usePrimaryColorPreview ? 'Color' : 'White'}</span>
- </button>
- </div>
-
- {/* S-curve stroke preview canvas */}
- <div className="w-full h-11 rounded bg-[#0d0e10] border border-[#212327] overflow-hidden flex items-center justify-center">
- <BrushPreview
- preset={brushSettings.preset}
- settings={brushSettings}
- customTipImage={brushSettings.customTipImage}
- customTipAngle={brushSettings.customTipAngle}
- tool={currentTool}
- strokeColor={usePrimaryColorPreview ? primaryColor : '#ffffff'}
- height={44}
- isLiveCard={true}
- />
- </div>
-
- {/* Live parameters summary */}
- <div className="flex items-center justify-between text-[10px] text-[#6e727d] font-mono px-0.5 pt-0.5">
- <span>{brushSettings.size}px</span>
- <span>{Math.round((brushSettings.flow ?? 0.85) * 100)}% flow</span>
- {isPencilActive ? (
- <span>{Math.round((brushSettings.grain ?? 0.95) * 100)}% tooth</span>
- ) : (
- <span>{Math.round((brushSettings.hardness ?? 1.0) * 100)}% hard</span>
- )}
- <span>{Math.round((brushSettings.opacity ?? 1.0) * 100)}% op</span>
- </div>
- </div>
-
- {/* 1. Size Slider */}
- <div className="space-y-1.5">
- <div className="flex justify-between items-center text-xs">
- <span className="text-[#a0a4ae] font-medium">Size</span>
- <div className="bg-[#151618] border border-[#2e3035] rounded px-2 py-0.5 text-right font-mono text-[#dcdfe6] text-xs min-w-16">
- {brushSettings.size} px
- </div>
- </div>
- <input
- type="range"
- min="0.5"
- max={isPencilActive ? 80 : 250}
- step={isPencilActive ? 0.5 : 1}
- value={brushSettings.size}
- onChange={(e) => handleUpdateBrushSettings({ size: Number(e.target.value) })}
- className="w-full h-1 bg-[#282a2e] rounded appearance-none cursor-pointer accent-[#5ce1e6]"
- />
- {/* Quick Presets Row under Size Slider */}
- <div className="pt-1">
- <div className="flex items-center justify-between mb-1">
- <span className="text-[10px] text-[#717682] uppercase tracking-wider font-semibold">Presets</span>
+ {selectedCategory === 'csp' && customBrushes.length === 0 && (
+ <div className="py-4 px-2 text-center space-y-2">
+ <p className="text-[10px] text-[#8a8a8a]">Drop .sut brush file</p>
<button
type="button"
- onClick={() => handleSelectBottomTab('size')}
- className="text-[10px] text-[#5ce1e6] hover:underline cursor-pointer flex items-center space-x-0.5"
+ onClick={() => sutInputRef.current?.click()}
+ className="px-2 py-1 rounded bg-[#2c2c2c] text-[10px] text-[#e5e5e5] cursor-pointer"
>
- <span>All 40 Presets</span>
- <ChevronRight className="w-3 h-3" />
+ Import .sut
</button>
</div>
- <div className="grid grid-cols-8 gap-1">
- {[1, 2, 4, 8, 12, 20, 30, 60].map((sz) => (
- <button
- key={sz}
- type="button"
- onClick={() => handleUpdateBrushSettings({ size: sz })}
- className={`py-0.5 rounded text-[10px] font-mono text-center transition-colors cursor-pointer border ${
- Math.abs(brushSettings.size - sz) < 0.05
- ? 'bg-[#37485e] border-[#4e6a88] text-white font-bold'
- : 'bg-[#151618] border-[#292b30] text-[#999fae] hover:text-white hover:bg-[#25282f]'
- }`}
- >
- {sz}
- </button>
- ))}
- </div>
- </div>
+ )}
</div>
- {/* 2. Opacity Slider */}
- <div className="space-y-1.5">
- <div className="flex justify-between items-center text-xs">
- <span className="text-[#a0a4ae] font-medium">Opacity</span>
- <div className="bg-[#151618] border border-[#2e3035] rounded px-2 py-0.5 text-right font-mono text-[#dcdfe6] text-xs min-w-16">
- {Math.round((brushSettings.opacity ?? 1.0) * 100)}%
- </div>
- </div>
- <input
- type="range"
- min="1"
- max="100"
- value={Math.round((brushSettings.opacity ?? 1.0) * 100)}
- onChange={(e) => handleUpdateBrushSettings({ opacity: Number(e.target.value) / 100 })}
- className="w-full h-1 bg-[#282a2e] rounded appearance-none cursor-pointer accent-[#5ce1e6]"
+ {/* Live S-Curve Stroke Preview + Quick Size/Opacity Bar */}
+ <div className="shrink-0 bg-[#1b1b1b] border-t border-[#2a2a2a] px-2 py-1.5 space-y-1.5">
+ <canvas
+ ref={previewCanvasRef}
+ className="w-full h-8 rounded bg-[#161616] block"
/>
- </div>
-
- {/* 3. Flow Slider (Graphite Flow Rate) */}
- <div className="space-y-1.5">
- <div className="flex justify-between items-center text-xs">
- <span className="text-[#a0a4ae] font-medium">
- {isPencilActive ? 'Graphite Flow' : 'Flow'}
- </span>
- <div className="bg-[#151618] border border-[#2e3035] rounded px-2 py-0.5 text-right font-mono text-[#dcdfe6] text-xs min-w-16">
- {Math.round((brushSettings.flow ?? 0.85) * 100)}%
- </div>
- </div>
- <input
- type="range"
- min="1"
- max="100"
- value={Math.round((brushSettings.flow ?? 0.85) * 100)}
- onChange={(e) => handleUpdateBrushSettings({ flow: Number(e.target.value) / 100 })}
- className="w-full h-1 bg-[#282a2e] rounded appearance-none cursor-pointer accent-[#5ce1e6]"
+ <CompactSlider
+ label="Brush Size ([ / ])"
+ valueLabel={`${brushSettings.size < 10 ? brushSettings.size.toFixed(1) : Math.round(brushSettings.size)}px`}
+ min={0.5}
+ max={500}
+ step={0.5}
+ value={brushSettings.size}
+ onChange={(v) => handleUpdateBrushSettings({ size: v })}
/>
- </div>
-
- {/* 3b. Real Paper Grain Tooth Slider (for pencils) */}
- {isPencilActive && (
- <div className="space-y-1.5">
- <div className="flex justify-between items-center text-xs">
- <div className="flex items-center space-x-1.5">
- <Sparkles className="w-3.5 h-3.5 text-amber-400" />
- <span className="text-[#a0a4ae] font-medium">Paper Tooth (Grain)</span>
- </div>
- <div className="bg-[#151618] border border-[#2e3035] rounded px-2 py-0.5 text-right font-mono text-[#dcdfe6] text-xs min-w-16">
- {Math.round((brushSettings.grain ?? 0.95) * 100)}%
- </div>
- </div>
- <input
- type="range"
- min="0"
- max="100"
- value={Math.round((brushSettings.grain ?? 0.95) * 100)}
- onChange={(e) => handleUpdateBrushSettings({ grain: Number(e.target.value) / 100 })}
- className="w-full h-1 bg-[#282a2e] rounded appearance-none cursor-pointer accent-amber-400"
- title="Real Cold-Press Paper Grain: higher values produce richer organic sketchbook tooth"
- />
- </div>
- )}
-
- {/* 4. Spacing Slider */}
- <div className="space-y-1.5">
- <div className="flex justify-between items-center text-xs">
- <span className="text-[#a0a4ae] font-medium">Spacing</span>
- <div className="bg-[#151618] border border-[#2e3035] rounded px-2 py-0.5 text-right font-mono text-[#dcdfe6] text-xs min-w-16">
- {Math.round((brushSettings.spacing ?? 0.1) * 100)}%
- </div>
- </div>
- <input
- type="range"
- min="1"
- max="100"
- value={Math.round((brushSettings.spacing ?? 0.1) * 100)}
- onChange={(e) => handleUpdateBrushSettings({ spacing: Number(e.target.value) / 100 })}
- className="w-full h-1 bg-[#282a2e] rounded appearance-none cursor-pointer accent-[#5ce1e6]"
+ <CompactSlider
+ label="Opacity"
+ valueLabel={`${Math.round((brushSettings.opacity ?? 1.0) * 100)}%`}
+ min={1}
+ max={100}
+ value={Math.round((brushSettings.opacity ?? 1.0) * 100)}
+ onChange={(v) => handleUpdateBrushSettings({ opacity: v / 100 })}
/>
</div>
- {/* 5. Stabilization Slider */}
- <div className="space-y-1.5">
- <div className="flex justify-between items-center text-xs">
- <span className="text-[#a0a4ae] font-medium">Stabilization</span>
- <div className="bg-[#151618] border border-[#2e3035] rounded px-2 py-0.5 text-right font-mono text-[#dcdfe6] text-xs min-w-16">
- {brushSettings.stabilization ?? 15}
- </div>
- </div>
- <input
- type="range"
- min="0"
- max="50"
- value={brushSettings.stabilization ?? 15}
- onChange={(e) => handleUpdateBrushSettings({ stabilization: Number(e.target.value) })}
- className="w-full h-1 bg-[#282a2e] rounded appearance-none cursor-pointer accent-[#5ce1e6]"
- />
- </div>
+ {/* CSP Sub-Tool Detail Accordions */}
+ <div className="shrink-0 bg-[#161616] pt-px space-y-px max-h-[50%] overflow-y-auto">
+ {/* 1. Ink (Brush Density, Gap Compensation, Blend Tips, 4-stage Anti-Alias) */}
+ <div className="bg-[#202020]">
+ <button
+ type="button"
+ onClick={() => toggleAccordion('ink')}
+ className="w-full px-2 py-1.5 flex items-center justify-between text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 transition-colors cursor-pointer"
+ >
+ <span>Ink</span>
+ <div className="flex items-center gap-1">
+ <span className="font-mono text-[10px] text-[#e5e5e5]">
+ {Math.round((brushSettings.flow ?? 0.85) * 100)}%
+ </span>
+ {openAccordion === 'ink' ? (
+ <ChevronDown className="w-3 h-3" />
+ ) : (
+ <ChevronRight className="w-3 h-3" />
+ )}
+ </div>
+ </button>
- {/* 5b. Tip Angle Slider (for CSP / Custom Brushes) */}
- {isCustomBrushActive && brushSettings.customTipDataUrl && (
- <div className="space-y-1.5">
- <div className="flex justify-between items-center text-xs">
- <span className="text-[#a0a4ae] font-medium">Tip Angle</span>
- <div className="flex items-center space-x-1">
- <button
- onClick={() => handleUpdateBrushSettings({ customTipAngle: 0 })}
- className="text-[10px] text-[#717682] hover:text-[#5ce1e6] px-1.5 py-0.5 rounded bg-[#151618] border border-[#2e3035] transition-colors cursor-pointer"
- title="Reset Angle to 0°"
- >
- 0°
- </button>
- <div className="bg-[#151618] border border-[#2e3035] rounded px-2 py-0.5 text-right font-mono text-[#dcdfe6] text-xs min-w-14">
- {Math.round(brushSettings.customTipAngle ?? 0)}°
+ {openAccordion === 'ink' && (
+ <div className="px-2.5 pb-2.5 pt-1 space-y-2.5">
+ <CompactSlider
+ label="Brush Density"
+ valueLabel={`${Math.round((brushSettings.flow ?? 0.85) * 100)}%`}
+ min={1}
+ max={100}
+ value={Math.round((brushSettings.flow ?? 0.85) * 100)}
+ onChange={(v) =>
+ handleUpdateBrushSettings({ flow: v / 100, brushDensity: v / 100 })
+ }
+ />
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Adjust by Gap</span>
+ <input
+ type="checkbox"
+ checked={Boolean(brushSettings.adjustDensityByGap)}
+ onChange={(e) =>
+ handleUpdateBrushSettings({ adjustDensityByGap: e.target.checked })
+ }
+ />
+ </label>
+ <div className="space-y-1">
+ <span className="text-[11px] text-[#8a8a8a]">Blend Tips</span>
+ <div className="grid grid-cols-3 gap-0.5 bg-[#161616] p-0.5 rounded">
+ {(
+ [
+ { id: 'normal', label: 'Normal' },
+ { id: 'darken', label: 'Darken' },
+ { id: 'compare', label: 'Compare' },
+ ] as Array<{ id: CspBlendTipsMode; label: string }>
+ ).map((mode) => (
+ <button
+ key={mode.id}
+ type="button"
+ onClick={() => handleUpdateBrushSettings({ blendTipsMode: mode.id })}
+ className={`py-0.5 rounded text-[10px] cursor-pointer ${
+ (brushSettings.blendTipsMode ?? 'normal') === mode.id
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ {mode.label}
+ </button>
+ ))}
+ </div>
+ </div>
+ <div className="space-y-1">
+ <span className="text-[11px] text-[#8a8a8a]">Anti-Aliasing</span>
+ <div className="grid grid-cols-4 gap-0.5 bg-[#161616] p-0.5 rounded">
+ {(
+ [
+ { val: 0, label: 'None' },
+ { val: 1, label: 'Weak' },
+ { val: 2, label: 'Med' },
+ { val: 3, label: 'Strong' },
+ ] as const
+ ).map((aa) => (
+ <button
+ key={aa.val}
+ type="button"
+ onClick={() => handleUpdateBrushSettings({ antiAlias: aa.val })}
+ className={`py-0.5 rounded text-[10px] cursor-pointer ${
+ currentAntiAlias === aa.val
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ {aa.label}
+ </button>
+ ))}
+ </div>
</div>
</div>
- </div>
- <input
- type="range"
- min="0"
- max="360"
- value={Math.round(brushSettings.customTipAngle ?? 0)}
- onChange={(e) => handleUpdateBrushSettings({ customTipAngle: Number(e.target.value) })}
- className="w-full h-1 bg-[#282a2e] rounded appearance-none cursor-pointer accent-[#5ce1e6]"
- />
+ )}
</div>
- )}
- {/* Advanced Dynamics Accordion */}
- <div className="pt-2 border-t border-[#2b2d31]">
- <button
- onClick={() => setShowAdvanced(!showAdvanced)}
- className="w-full flex items-center justify-between text-xs text-[#8c9099] hover:text-white py-1 transition-colors cursor-pointer"
- >
- <span>Advanced Dynamics</span>
- {showAdvanced ? <ChevronDown className="w-3.5 h-3.5" /> : <ChevronRight className="w-3.5 h-3.5" />}
- </button>
+ {/* 2. Brush Tip (Hardness, Spacing, Thickness H/V, Angle + Dynamics, Flip H/V, Ribbon) */}
+ <div className="bg-[#202020]">
+ <button
+ type="button"
+ onClick={() => toggleAccordion('tip')}
+ className="w-full px-2 py-1.5 flex items-center justify-between text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 transition-colors cursor-pointer"
+ >
+ <span>Brush Tip</span>
+ {openAccordion === 'tip' ? (
+ <ChevronDown className="w-3 h-3" />
+ ) : (
+ <ChevronRight className="w-3 h-3" />
+ )}
+ </button>
- {showAdvanced && (
- <div className="pt-2 space-y-3">
- {/* Hardness */}
- <div className="space-y-1">
- <div className="flex justify-between text-xs">
- <span className="text-[#8c9099]">Hardness</span>
- <span className="font-mono text-white">
- {Math.round((brushSettings.hardness ?? 1.0) * 100)}%
- </span>
- </div>
- <input
- type="range"
- min="0.05"
- max="1.0"
- step="0.05"
- value={brushSettings.hardness ?? 1.0}
- onChange={(e) => handleUpdateBrushSettings({ hardness: Number(e.target.value) })}
- className="w-full h-1 bg-[#282a2e] rounded appearance-none cursor-pointer accent-[#5ce1e6]"
+ {openAccordion === 'tip' && (
+ <div className="px-2.5 pb-2.5 pt-1 space-y-2.5">
+ <CompactSlider
+ label="Hardness"
+ valueLabel={`${Math.round((brushSettings.hardness ?? 1.0) * 100)}%`}
+ min={5}
+ max={100}
+ value={Math.round((brushSettings.hardness ?? 1.0) * 100)}
+ onChange={(v) => handleUpdateBrushSettings({ hardness: v / 100 })}
/>
- </div>
-
- {/* Stylus Pressure Sensitivity */}
- <div className="flex items-center justify-between py-1">
- <div className="flex items-center space-x-1.5">
- <Activity className="w-3.5 h-3.5 text-[#8c9099]" />
- <span className="text-xs text-[#cccccc]">Stylus Pressure</span>
+ <CompactSlider
+ label="Gap (Spacing)"
+ valueLabel={`${Math.round((brushSettings.spacing ?? 0.1) * 100)}%`}
+ min={1}
+ max={100}
+ value={Math.round((brushSettings.spacing ?? 0.1) * 100)}
+ onChange={(v) => handleUpdateBrushSettings({ spacing: v / 100 })}
+ />
+ <CompactSlider
+ label="Thickness"
+ valueLabel={`${Math.round((brushSettings.thickness ?? 1.0) * 100)}%`}
+ min={5}
+ max={100}
+ value={Math.round((brushSettings.thickness ?? 1.0) * 100)}
+ onChange={(v) => handleUpdateBrushSettings({ thickness: v / 100 })}
+ />
+ <div className="grid grid-cols-2 gap-0.5 bg-[#161616] p-0.5 rounded">
+ <button
+ type="button"
+ onClick={() => handleUpdateBrushSettings({ thicknessVertical: false })}
+ className={`py-0.5 rounded text-[10px] cursor-pointer ${
+ !brushSettings.thicknessVertical
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'text-[#8a8a8a]'
+ }`}
+ >
+ Horizontal
+ </button>
+ <button
+ type="button"
+ onClick={() => handleUpdateBrushSettings({ thicknessVertical: true })}
+ className={`py-0.5 rounded text-[10px] cursor-pointer ${
+ brushSettings.thicknessVertical
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'text-[#8a8a8a]'
+ }`}
+ >
+ Vertical
+ </button>
</div>
- <input
- type="checkbox"
- checked={brushSettings.usePressure}
- onChange={(e) => handleUpdateBrushSettings({ usePressure: e.target.checked })}
- className="rounded bg-[#1a1b1e] border-[#383a40] text-[#5ce1e6] focus:ring-0 cursor-pointer"
+ <CompactSlider
+ label="Angle"
+ valueLabel={`${Math.round(brushSettings.customTipAngle ?? 0)}deg`}
+ min={0}
+ max={360}
+ value={Math.round(brushSettings.customTipAngle ?? 0)}
+ onChange={(v) => handleUpdateBrushSettings({ customTipAngle: v })}
/>
- </div>
-
- {/* Min Pressure Taper */}
- {brushSettings.usePressure && (
<div className="space-y-1">
- <div className="flex justify-between text-xs">
- <span className="text-[#8c9099]">Min Pressure Width</span>
- <span className="font-mono text-white">
- {Math.round(brushSettings.minSizeFactor * 100)}%
- </span>
+ <span className="text-[11px] text-[#8a8a8a]">Angle Dynamics</span>
+ <select
+ value={brushSettings.customTipAngleDynamics ?? 'none'}
+ onChange={(e) =>
+ handleUpdateBrushSettings({
+ customTipAngleDynamics: e.target.value as CspAngleDynamicsMode,
+ })
+ }
+ className="w-full h-6 bg-[#161616] text-[#e5e5e5] text-[10px] px-1.5 rounded cursor-pointer"
+ >
+ <option value="none">None</option>
+ <option value="direction">Direction of Line</option>
+ <option value="tilt">Pen Tilt</option>
+ <option value="twist">Barrel Twist</option>
+ <option value="random">Random</option>
+ <option value="direction-random">Direction + Random</option>
+ </select>
+ </div>
+ <div className="grid grid-cols-2 gap-1.5">
+ <div className="space-y-0.5">
+ <span className="text-[10px] text-[#8a8a8a]">Flip H</span>
+ <select
+ value={brushSettings.flipH ?? 'none'}
+ onChange={(e) =>
+ handleUpdateBrushSettings({ flipH: e.target.value as CspTipFlipMode })
+ }
+ className="w-full h-5 bg-[#161616] text-[#e5e5e5] text-[10px] px-1 rounded cursor-pointer"
+ >
+ <option value="none">None</option>
+ <option value="random">Random</option>
+ <option value="alternate">Alternate</option>
+ </select>
+ </div>
+ <div className="space-y-0.5">
+ <span className="text-[10px] text-[#8a8a8a]">Flip V</span>
+ <select
+ value={brushSettings.flipV ?? 'none'}
+ onChange={(e) =>
+ handleUpdateBrushSettings({ flipV: e.target.value as CspTipFlipMode })
+ }
+ className="w-full h-5 bg-[#161616] text-[#e5e5e5] text-[10px] px-1 rounded cursor-pointer"
+ >
+ <option value="none">None</option>
+ <option value="random">Random</option>
+ <option value="alternate">Alternate</option>
+ </select>
</div>
+ </div>
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Ribbon</span>
<input
- type="range"
- min="0.05"
- max="0.8"
- step="0.05"
- value={brushSettings.minSizeFactor}
- onChange={(e) => handleUpdateBrushSettings({ minSizeFactor: Number(e.target.value) })}
- className="w-full h-1 bg-[#282a2e] rounded appearance-none cursor-pointer accent-[#5ce1e6]"
+ type="checkbox"
+ checked={Boolean(brushSettings.isRibbon)}
+ onChange={(e) => handleUpdateBrushSettings({ isRibbon: e.target.checked })}
/>
- </div>
- )}
+ </label>
+ </div>
+ )}
+ </div>
- {/* Bézier Smoothing */}
- <div className="flex items-center justify-between py-1">
- <div className="flex items-center space-x-1.5">
- <Sparkles className="w-3.5 h-3.5 text-[#8c9099]" />
- <span className="text-xs text-[#cccccc]">Bézier Smoothing</span>
- </div>
- <input
- type="checkbox"
- checked={brushSettings.smoothing}
- onChange={(e) => handleUpdateBrushSettings({ smoothing: e.target.checked })}
- className="rounded bg-[#1a1b1e] border-[#383a40] text-[#5ce1e6] focus:ring-0 cursor-pointer"
- />
+ {/* 3. Stroke & Stabilization */}
+ <div className="bg-[#202020]">
+ <button
+ type="button"
+ onClick={() => toggleAccordion('stroke')}
+ className="w-full px-2 py-1.5 flex items-center justify-between text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 transition-colors cursor-pointer"
+ >
+ <span>Stabilization &amp; Stroke</span>
+ <div className="flex items-center gap-1">
+ <span className="font-mono text-[10px] text-[#e5e5e5]">
+ {brushSettings.stabilization ?? 15}
+ </span>
+ {openAccordion === 'stroke' ? (
+ <ChevronDown className="w-3 h-3" />
+ ) : (
+ <ChevronRight className="w-3 h-3" />
+ )}
</div>
+ </button>
- {/* GPU Video Card Hardware Acceleration */}
- <div className="pt-2 border-t border-[#26282c] space-y-2">
- <div className="flex items-center justify-between">
- <div className="flex items-center space-x-1.5">
- <Zap className="w-3.5 h-3.5 text-[#5ce1e6]" />
- <span className="text-xs text-[#cccccc] font-medium">Video Card (GPU)</span>
- </div>
+ {openAccordion === 'stroke' && (
+ <div className="px-2.5 pb-2.5 pt-1 space-y-2.5">
+ <CompactSlider
+ label="Stabilization"
+ valueLabel={`${brushSettings.stabilization ?? 15}`}
+ min={0}
+ max={50}
+ value={brushSettings.stabilization ?? 15}
+ onChange={(v) => handleUpdateBrushSettings({ stabilization: v })}
+ />
+ <CompactSlider
+ label="Post-Correction"
+ valueLabel={`${brushSettings.postCorrection ?? 0}`}
+ min={0}
+ max={5}
+ value={brushSettings.postCorrection ?? 0}
+ onChange={(v) => handleUpdateBrushSettings({ postCorrection: v })}
+ />
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Sharp Angles</span>
<input
type="checkbox"
- checked={brushSettings.useGpu !== false}
- onChange={(e) => handleUpdateBrushSettings({ useGpu: e.target.checked })}
- className="rounded bg-[#1a1b1e] border-[#383a40] text-[#5ce1e6] focus:ring-0 cursor-pointer"
+ checked={brushSettings.sharpCorners ?? true}
+ onChange={(e) =>
+ handleUpdateBrushSettings({ sharpCorners: e.target.checked })
+ }
/>
+ </label>
+
+ <div className="grid grid-cols-2 gap-1.5">
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Taper In</span>
+ <input
+ type="checkbox"
+ checked={Boolean(brushSettings.taper?.useIn)}
+ onChange={(e) => handleUpdateTaper({ useIn: e.target.checked })}
+ />
+ </label>
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Taper Out</span>
+ <input
+ type="checkbox"
+ checked={Boolean(brushSettings.taper?.useOut)}
+ onChange={(e) => handleUpdateTaper({ useOut: e.target.checked })}
+ />
+ </label>
</div>
- <div className="bg-[#121315] border border-[#27292e] rounded p-2 text-[10px] space-y-0.5">
- <div className="flex items-center justify-between text-[#5ce1e6]">
- <span className="font-semibold">GPU Shader Core</span>
- <span className="px-1 py-0.2 rounded bg-[#5ce1e6]/10 text-[9px] font-mono">ACTIVE</span>
- </div>
- <div className="text-[#8c9099] truncate font-mono text-[9px]" title={gpuInfo.renderer}>
- {gpuInfo.renderer || 'Hardware Accelerated Video Card'}
- </div>
- </div>
+ {(brushSettings.taper?.useIn || brushSettings.taper?.useOut) && (
+ <CompactSlider
+ label="Taper Length"
+ valueLabel={`${Math.round(brushSettings.taper?.outLength ?? 32)}px`}
+ min={4}
+ max={200}
+ value={Math.round(brushSettings.taper?.outLength ?? 32)}
+ onChange={(v) =>
+ handleUpdateTaper({ inLength: v, outLength: v })
+ }
+ />
+ )}
+
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Pen Pressure</span>
+ <input
+ type="checkbox"
+ checked={brushSettings.usePressure}
+ onChange={(e) =>
+ handleUpdateBrushSettings({ usePressure: e.target.checked })
+ }
+ />
+ </label>
+ {brushSettings.usePressure && (
+ <>
+ <CompactSlider
+ label="Min Width"
+ valueLabel={`${Math.round(brushSettings.minSizeFactor * 100)}%`}
+ min={0}
+ max={95}
+ value={Math.round(brushSettings.minSizeFactor * 100)}
+ onChange={(v) => handleUpdateBrushSettings({ minSizeFactor: v / 100 })}
+ />
+ <div className="space-y-1">
+ <span className="text-[10px] text-[#8a8a8a]">Pressure Curve</span>
+ <div className="grid grid-cols-5 gap-0.5 bg-[#161616] p-0.5 rounded">
+ {(
+ [
+ { id: 'linear', short: 'Lin' },
+ { id: 'g-pen', short: 'G' },
+ { id: 'soft', short: 'Soft' },
+ { id: 'firm', short: 'Firm' },
+ { id: 'chisel', short: 'Hard' },
+ ] as const
+ ).map((p) => (
+ <button
+ key={p.id}
+ type="button"
+ title={CSP_PRESSURE_CURVE_PRESETS[p.id]?.label}
+ onClick={() =>
+ handleUpdateBrushSettings({
+ pressureCurve: CSP_PRESSURE_CURVE_PRESETS[p.id]?.points,
+ })
+ }
+ className="py-0.5 rounded text-[9px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ {p.short}
+ </button>
+ ))}
+ </div>
+ </div>
+ </>
+ )}
+
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Stylus Tilt</span>
+ <input
+ type="checkbox"
+ checked={Boolean(brushSettings.useTilt)}
+ onChange={(e) => handleUpdateBrushSettings({ useTilt: e.target.checked })}
+ />
+ </label>
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Velocity Dynamics</span>
+ <input
+ type="checkbox"
+ checked={Boolean(brushSettings.useVelocity)}
+ onChange={(e) =>
+ handleUpdateBrushSettings({ useVelocity: e.target.checked })
+ }
+ />
+ </label>
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Bezier Smoothing</span>
+ <input
+ type="checkbox"
+ checked={brushSettings.smoothing}
+ onChange={(e) =>
+ handleUpdateBrushSettings({ smoothing: e.target.checked })
+ }
+ />
+ </label>
+ <button
+ type="button"
+ onClick={() => {
+ const def = resetBrushSettingsToDefault(
+ currentTool === 'eraser'
+ ? ERASER_PRESET_ID
+ : brushSettings.preset || 'pencil-2b',
+ customBrushes
+ );
+ handleUpdateBrushSettings(def);
+ }}
+ className="w-full py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer"
+ >
+ Reset Brush to Default
+ </button>
</div>
+ )}
+ </div>
- {/* CSP Color Mixing */}
- <div className="pt-2 border-t border-[#26282c] space-y-2">
- <div className="flex items-center justify-between">
- <div className="flex items-center space-x-1.5">
- <Droplets className="w-3.5 h-3.5 text-cyan-400" />
- <span className="text-xs text-[#cccccc] font-medium">Color Mixing</span>
- <span className="text-[9px] px-1 py-0.2 rounded bg-cyan-500/15 text-cyan-300 font-mono font-medium">SUBTRACTIVE</span>
- </div>
+ {/* 4. Color Mixing & Watercolor Edge */}
+ <div className="bg-[#202020]">
+ <button
+ type="button"
+ onClick={() => toggleAccordion('mixing')}
+ className="w-full px-2 py-1.5 flex items-center justify-between text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 transition-colors cursor-pointer"
+ >
+ <span>Color Mixing &amp; Edge</span>
+ {openAccordion === 'mixing' ? (
+ <ChevronDown className="w-3 h-3" />
+ ) : (
+ <ChevronRight className="w-3 h-3" />
+ )}
+ </button>
+
+ {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">
+ <span>Color Mixing</span>
<input
type="checkbox"
checked={Boolean(brushSettings.colorMixing)}
- onChange={(e) => handleUpdateBrushSettings({ colorMixing: e.target.checked })}
- className="rounded bg-[#1a1b1e] border-[#383a40] text-[#5ce1e6] focus:ring-0 cursor-pointer"
+ onChange={(e) =>
+ handleUpdateBrushSettings({ colorMixing: e.target.checked })
+ }
/>
- </div>
-
+ </label>
{brushSettings.colorMixing && (
- <div className="space-y-2.5 pt-1 pl-1 border-l border-[#2e3138]">
- {/* Mixing Mode: Blend vs Running Color */}
- <div className="flex rounded bg-[#151618] p-0.5 border border-[#2b2d32]">
- <button
- onClick={() => handleUpdateBrushSettings({ mixingMode: 'blend' })}
- className={`flex-1 py-0.5 text-[10px] rounded transition-colors ${
- (brushSettings.mixingMode || 'blend') === 'blend'
- ? 'bg-[#293d45] text-[#5ce1e6] font-medium shadow-xs'
- : 'text-[#828690] hover:text-[#cccccc]'
- }`}
- >
- Blend
- </button>
- <button
- onClick={() => handleUpdateBrushSettings({ mixingMode: 'running_color' })}
- className={`flex-1 py-0.5 text-[10px] rounded transition-colors ${
- brushSettings.mixingMode === 'running_color'
- ? 'bg-[#293d45] text-[#5ce1e6] font-medium shadow-xs'
- : 'text-[#828690] hover:text-[#cccccc]'
- }`}
- >
- Running Color
- </button>
+ <>
+ <div className="grid grid-cols-3 gap-0.5 bg-[#161616] p-0.5 rounded">
+ {(
+ [
+ { id: 'blend', label: 'Blend' },
+ { id: 'running_color', label: 'Running' },
+ { id: 'smear', label: 'Smear' },
+ ] as const
+ ).map((m) => (
+ <button
+ key={m.id}
+ type="button"
+ onClick={() => handleUpdateBrushSettings({ mixingMode: m.id })}
+ className={`py-0.5 rounded text-[10px] cursor-pointer ${
+ (brushSettings.mixingMode || 'blend') === m.id
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'text-[#8a8a8a]'
+ }`}
+ >
+ {m.label}
+ </button>
+ ))}
</div>
-
- {/* Amount of Paint */}
- <div className="space-y-1">
- <div className="flex justify-between text-xs">
- <span className="text-[#8c9099]">Amount of Paint</span>
- <span className="font-mono text-white">
- {Math.round((brushSettings.amountOfPaint ?? 0.7) * 100) === 0
- ? '0% (Pure Smudge)'
- : `${Math.round((brushSettings.amountOfPaint ?? 0.7) * 100)}%`}
- </span>
- </div>
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Perceptual (OKLab)</span>
<input
- type="range"
- min="0"
- max="100"
- value={Math.round((brushSettings.amountOfPaint ?? 0.7) * 100)}
- onChange={(e) => handleUpdateBrushSettings({ amountOfPaint: Number(e.target.value) / 100 })}
- className="w-full h-1 bg-[#282a2e] rounded appearance-none cursor-pointer accent-[#5ce1e6]"
+ type="checkbox"
+ checked={brushSettings.perceptualMixing ?? true}
+ onChange={(e) =>
+ handleUpdateBrushSettings({ perceptualMixing: e.target.checked })
+ }
/>
- </div>
+ </label>
+ <CompactSlider
+ label="Amount of Paint"
+ valueLabel={`${Math.round((brushSettings.amountOfPaint ?? 0.7) * 100)}%`}
+ min={0}
+ max={100}
+ value={Math.round((brushSettings.amountOfPaint ?? 0.7) * 100)}
+ onChange={(v) => handleUpdateBrushSettings({ amountOfPaint: v / 100 })}
+ />
+ <CompactSlider
+ label="Density of Paint"
+ valueLabel={`${Math.round((brushSettings.densityOfPaint ?? 0.8) * 100)}%`}
+ min={1}
+ max={100}
+ value={Math.round((brushSettings.densityOfPaint ?? 0.8) * 100)}
+ onChange={(v) => handleUpdateBrushSettings({ densityOfPaint: v / 100 })}
+ />
+ <CompactSlider
+ label="Color Stretch"
+ valueLabel={`${Math.round((brushSettings.colorStretch ?? 0.6) * 100)}%`}
+ min={0}
+ max={100}
+ value={Math.round((brushSettings.colorStretch ?? 0.6) * 100)}
+ onChange={(v) => handleUpdateBrushSettings({ colorStretch: v / 100 })}
+ />
+ </>
+ )}
+ <CompactSlider
+ label="Watercolor Edge"
+ valueLabel={`${Math.round((brushSettings.wetEdge ?? 0) * 100)}%`}
+ min={0}
+ max={100}
+ value={Math.round((brushSettings.wetEdge ?? 0) * 100)}
+ onChange={(v) => handleUpdateBrushSettings({ wetEdge: v / 100 })}
+ />
+ {(brushSettings.wetEdge ?? 0) > 0.01 && (
+ <CompactSlider
+ label="Edge Width"
+ valueLabel={`${brushSettings.wetEdgeRadius ?? 4}px`}
+ min={1}
+ max={20}
+ value={Math.round(brushSettings.wetEdgeRadius ?? 4)}
+ onChange={(v) => handleUpdateBrushSettings({ wetEdgeRadius: v })}
+ />
+ )}
+ </div>
+ )}
+ </div>
- {/* Density of Paint */}
- <div className="space-y-1">
- <div className="flex justify-between text-xs">
- <span className="text-[#8c9099]">Density of Paint</span>
- <span className="font-mono text-white">
- {Math.round((brushSettings.densityOfPaint ?? 0.8) * 100)}%
- </span>
- </div>
- <input
- type="range"
- min="1"
- max="100"
- value={Math.round((brushSettings.densityOfPaint ?? 0.8) * 100)}
- onChange={(e) => handleUpdateBrushSettings({ densityOfPaint: Number(e.target.value) / 100 })}
- className="w-full h-1 bg-[#282a2e] rounded appearance-none cursor-pointer accent-[#5ce1e6]"
- />
- </div>
+ {/* 5. Texture & Spraying Effect */}
+ <div className="bg-[#202020]">
+ <button
+ type="button"
+ onClick={() => toggleAccordion('texture')}
+ className="w-full px-2 py-1.5 flex items-center justify-between text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 transition-colors cursor-pointer"
+ >
+ <span>Texture &amp; Spray</span>
+ {openAccordion === 'texture' ? (
+ <ChevronDown className="w-3 h-3" />
+ ) : (
+ <ChevronRight className="w-3 h-3" />
+ )}
+ </button>
- {/* Color Stretch */}
+ {openAccordion === 'texture' && (
+ <div className="px-2.5 pb-2.5 pt-1 space-y-2.5">
+ <CompactSlider
+ label="Texture Density"
+ valueLabel={`${Math.round((brushSettings.grain ?? 0) * 100)}%`}
+ min={0}
+ max={100}
+ value={Math.round((brushSettings.grain ?? 0) * 100)}
+ onChange={(v) =>
+ handleUpdateBrushSettings({ grain: v / 100, textureDensity: v / 100 })
+ }
+ />
+ {(brushSettings.grain ?? 0) > 0.005 && (
+ <>
<div className="space-y-1">
- <div className="flex justify-between text-xs">
- <span className="text-[#8c9099]">Color Stretch</span>
- <span className="font-mono text-white">
- {Math.round((brushSettings.colorStretch ?? 0.6) * 100)}%
- </span>
- </div>
+ <span className="text-[11px] text-[#8a8a8a]">Texture Mode</span>
+ <select
+ value={brushSettings.paperTextureMode ?? 'subtract'}
+ onChange={(e) =>
+ handleUpdateBrushSettings({
+ paperTextureMode: e.target.value as CspPaperTextureMode,
+ })
+ }
+ 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="multiply">Multiply</option>
+ <option value="compare">Compare Density</option>
+ <option value="overlay">Overlay</option>
+ <option value="outline">Outline</option>
+ </select>
+ </div>
+ <CompactSlider
+ label="Texture Scale"
+ valueLabel={`${Math.round((brushSettings.paperTextureScale ?? 1.0) * 100)}%`}
+ min={10}
+ max={400}
+ step={5}
+ value={Math.round((brushSettings.paperTextureScale ?? 1.0) * 100)}
+ onChange={(v) =>
+ handleUpdateBrushSettings({ paperTextureScale: v / 100 })
+ }
+ />
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Invert Texture</span>
<input
- type="range"
- min="1"
- max="100"
- value={Math.round((brushSettings.colorStretch ?? 0.6) * 100)}
- onChange={(e) => handleUpdateBrushSettings({ colorStretch: Number(e.target.value) / 100 })}
- className="w-full h-1 bg-[#282a2e] rounded appearance-none cursor-pointer accent-[#5ce1e6]"
+ type="checkbox"
+ checked={Boolean(brushSettings.paperTextureInverted)}
+ onChange={(e) =>
+ handleUpdateBrushSettings({
+ paperTextureInverted: e.target.checked,
+ })
+ }
/>
- </div>
- </div>
+ </label>
+ </>
)}
- </div>
-
- {/* Wet Edge (Watercolor) */}
- <div className="space-y-1 pt-2 border-t border-[#26282c]">
- <div className="flex justify-between text-xs">
- <span className="text-[#8c9099]">Wet Edge (Watercolor)</span>
- <span className="font-mono text-white">
- {Math.round((brushSettings.wetEdge ?? 0) * 100)}%
- </span>
- </div>
- <input
- type="range"
- min="0"
- max="100"
- value={Math.round((brushSettings.wetEdge ?? 0) * 100)}
- onChange={(e) => handleUpdateBrushSettings({ wetEdge: Number(e.target.value) / 100 })}
- className="w-full h-1 bg-[#282a2e] rounded appearance-none cursor-pointer accent-cyan-400"
- />
- </div>
- {/* Paper Tooth Grain (for non-pencil brushes as well) */}
- {!isPencilActive && (
- <div className="space-y-1 pt-1">
- <div className="flex justify-between text-xs">
- <span className="text-[#8c9099]">Paper Tooth (Grain)</span>
- <span className="font-mono text-white">
- {Math.round((brushSettings.grain ?? 0) * 100)}%
- </span>
- </div>
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer pt-1">
+ <span>Spraying Effect</span>
<input
- type="range"
- min="0"
- max="100"
- value={Math.round((brushSettings.grain ?? 0) * 100)}
- onChange={(e) => handleUpdateBrushSettings({ grain: Number(e.target.value) / 100 })}
- className="w-full h-1 bg-[#282a2e] rounded appearance-none cursor-pointer accent-amber-400"
+ type="checkbox"
+ checked={Boolean(brushSettings.spray?.enabled)}
+ onChange={(e) => handleUpdateSpray({ enabled: e.target.checked })}
/>
- </div>
- )}
- </div>
- )}
- </div>
+ </label>
+ {brushSettings.spray?.enabled && (
+ <>
+ <CompactSlider
+ label="Particle Size"
+ valueLabel={`${brushSettings.spray.size ?? 4}px`}
+ min={1}
+ max={80}
+ value={Math.round(brushSettings.spray.size ?? 4)}
+ onChange={(v) => handleUpdateSpray({ size: v })}
+ />
+ <CompactSlider
+ label="Spray Density"
+ valueLabel={`${brushSettings.spray.density ?? 12}`}
+ min={1}
+ max={64}
+ value={Math.round(brushSettings.spray.density ?? 12)}
+ onChange={(v) => handleUpdateSpray({ density: v })}
+ />
+ </>
+ )}
+ </div>
+ )}
+ </div>
- {/* Brush Dynamics (Multi-Axis Jitter Matrix) Accordion */}
- <div className="pt-2 border-t border-[#2b2d31]">
- <button
- type="button"
- onClick={() => setShowDynamics(!showDynamics)}
- className="w-full flex items-center justify-between text-xs text-[#8c9099] hover:text-white py-1 transition-colors cursor-pointer"
- >
- <div className="flex items-center space-x-1.5">
- <Shuffle className="w-3.5 h-3.5 text-[#5ce1e6]" />
- <span className="font-medium">Brush Dynamics & Jitter</span>
- {isDynamicsActive && (
- <span className="px-1 py-0.2 rounded bg-[#5ce1e6]/15 text-[#5ce1e6] text-[9px] font-mono font-medium">
- ACTIVE
- </span>
+ {/* 6. Dynamics & Jitter */}
+ <div className="bg-[#202020]">
+ <button
+ type="button"
+ onClick={() => toggleAccordion('dynamics')}
+ className="w-full px-2 py-1.5 flex items-center justify-between text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 transition-colors cursor-pointer"
+ >
+ <span>Dynamics &amp; Jitter</span>
+ {openAccordion === 'dynamics' ? (
+ <ChevronDown className="w-3 h-3" />
+ ) : (
+ <ChevronRight className="w-3 h-3" />
)}
- </div>
- {showDynamics ? <ChevronDown className="w-3.5 h-3.5" /> : <ChevronRight className="w-3.5 h-3.5" />}
- </button>
-
- {showDynamics && (
- <div className="pt-2 space-y-3">
- {/* Header with Reset Button */}
- <div className="flex items-center justify-between pb-1 border-b border-[#26282c]">
- <span className="text-[10px] text-[#717682] uppercase tracking-wider font-semibold">Jitter Matrix</span>
- <button
- type="button"
- onClick={() => handleUpdateDynamics(DEFAULT_BRUSH_DYNAMICS)}
- className="text-[10px] text-[#717682] hover:text-[#5ce1e6] px-1.5 py-0.5 rounded bg-[#151618] border border-[#2e3035] transition-colors cursor-pointer"
- title="Reset all dynamics jitter to zero"
- >
- Reset Dynamics
- </button>
- </div>
+ </button>
- {/* 1. Size Jitter */}
- <div className="space-y-1">
- <div className="flex justify-between text-xs">
- <span className="text-[#8c9099]">Size Jitter</span>
- <span className="font-mono text-white">
- {Math.round((brushSettings.dynamics?.sizeJitter ?? 0) * 100)}%
- </span>
- </div>
- <input
- type="range"
- min="0"
- max="100"
+ {openAccordion === 'dynamics' && (
+ <div className="px-2.5 pb-2.5 pt-1 space-y-2.5">
+ <CompactSlider
+ label="Size Jitter"
+ valueLabel={`${Math.round((brushSettings.dynamics?.sizeJitter ?? 0) * 100)}%`}
+ min={0}
+ max={100}
value={Math.round((brushSettings.dynamics?.sizeJitter ?? 0) * 100)}
- onChange={(e) => handleUpdateDynamics({ sizeJitter: Number(e.target.value) / 100 })}
- className="w-full h-1 bg-[#282a2e] rounded appearance-none cursor-pointer accent-[#5ce1e6]"
+ onChange={(v) => handleUpdateDynamics({ sizeJitter: v / 100 })}
/>
- </div>
-
- {/* 2. Angle Jitter */}
- <div className="space-y-1">
- <div className="flex justify-between text-xs">
- <span className="text-[#8c9099]">Angle Jitter</span>
- <span className="font-mono text-white">
- {Math.round((brushSettings.dynamics?.angleJitter ?? 0) * 100)}%
- </span>
- </div>
- <input
- type="range"
- min="0"
- max="100"
+ <CompactSlider
+ label="Angle Jitter"
+ valueLabel={`${Math.round((brushSettings.dynamics?.angleJitter ?? 0) * 100)}%`}
+ min={0}
+ max={100}
value={Math.round((brushSettings.dynamics?.angleJitter ?? 0) * 100)}
- onChange={(e) => handleUpdateDynamics({ angleJitter: Number(e.target.value) / 100 })}
- className="w-full h-1 bg-[#282a2e] rounded appearance-none cursor-pointer accent-[#5ce1e6]"
+ onChange={(v) => handleUpdateDynamics({ angleJitter: v / 100 })}
/>
- </div>
-
- {/* 3. Roundness / Thickness Jitter */}
- <div className="space-y-1">
- <div className="flex justify-between text-xs">
- <span className="text-[#8c9099]">Roundness Jitter</span>
- <span className="font-mono text-white">
- {Math.round((brushSettings.dynamics?.roundnessJitter ?? 0) * 100)}%
- </span>
- </div>
- <input
- type="range"
- min="0"
- max="100"
+ <CompactSlider
+ label="Roundness Jitter"
+ valueLabel={`${Math.round((brushSettings.dynamics?.roundnessJitter ?? 0) * 100)}%`}
+ min={0}
+ max={95}
value={Math.round((brushSettings.dynamics?.roundnessJitter ?? 0) * 100)}
- onChange={(e) => handleUpdateDynamics({ roundnessJitter: Number(e.target.value) / 100 })}
- className="w-full h-1 bg-[#282a2e] rounded appearance-none cursor-pointer accent-[#5ce1e6]"
+ onChange={(v) => handleUpdateDynamics({ roundnessJitter: v / 100 })}
/>
- </div>
-
- {/* 4. Scatter Jitter */}
- <div className="space-y-1">
- <div className="flex justify-between text-xs">
- <span className="text-[#8c9099]">Scatter</span>
- <span className="font-mono text-white">
- {(brushSettings.dynamics?.scatter ?? 0).toFixed(1)}x
- </span>
- </div>
- <input
- type="range"
- min="0"
- max="5"
- step="0.1"
+ <CompactSlider
+ label="Scatter"
+ valueLabel={`${(brushSettings.dynamics?.scatter ?? 0).toFixed(1)}x`}
+ min={0}
+ max={5}
+ step={0.1}
value={brushSettings.dynamics?.scatter ?? 0}
- onChange={(e) => handleUpdateDynamics({ scatter: Number(e.target.value) })}
- className="w-full h-1 bg-[#282a2e] rounded appearance-none cursor-pointer accent-[#5ce1e6]"
- />
- </div>
-
- {/* Scatter Both Axes Toggle */}
- <div className="flex items-center justify-between py-1">
- <span className="text-xs text-[#cccccc]">Scatter Both Axes</span>
- <input
- type="checkbox"
- checked={Boolean(brushSettings.dynamics?.scatterBothAxes)}
- onChange={(e) => handleUpdateDynamics({ scatterBothAxes: e.target.checked })}
- className="rounded bg-[#1a1b1e] border-[#383a40] text-[#5ce1e6] focus:ring-0 cursor-pointer"
+ onChange={(v) => handleUpdateDynamics({ scatter: v })}
/>
- </div>
-
- {/* 5. Count Slider */}
- <div className="space-y-1">
- <div className="flex justify-between text-xs">
- <span className="text-[#8c9099]">Count (Dabs per Step)</span>
- <span className="font-mono text-white">
- {brushSettings.dynamics?.count ?? 1}
- </span>
- </div>
- <input
- type="range"
- min="1"
- max="10"
- step="1"
+ {(brushSettings.dynamics?.scatter ?? 0) > 0 && (
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Scatter Both Axes</span>
+ <input
+ type="checkbox"
+ checked={Boolean(brushSettings.dynamics?.scatterBothAxes)}
+ onChange={(e) =>
+ handleUpdateDynamics({ scatterBothAxes: e.target.checked })
+ }
+ />
+ </label>
+ )}
+ <CompactSlider
+ label="Count"
+ valueLabel={`${brushSettings.dynamics?.count ?? 1}`}
+ min={1}
+ max={10}
value={brushSettings.dynamics?.count ?? 1}
- onChange={(e) => handleUpdateDynamics({ count: Number(e.target.value) })}
- className="w-full h-1 bg-[#282a2e] rounded appearance-none cursor-pointer accent-[#5ce1e6]"
+ onChange={(v) => handleUpdateDynamics({ count: v })}
/>
- </div>
-
- {/* 6. Flow / Opacity Jitter */}
- <div className="space-y-1">
- <div className="flex justify-between text-xs">
- <span className="text-[#8c9099]">Flow / Opacity Jitter</span>
- <span className="font-mono text-white">
- {Math.round((brushSettings.dynamics?.flowJitter ?? 0) * 100)}%
- </span>
- </div>
- <input
- type="range"
- min="0"
- max="100"
+ <CompactSlider
+ label="Flow Jitter"
+ valueLabel={`${Math.round((brushSettings.dynamics?.flowJitter ?? 0) * 100)}%`}
+ min={0}
+ max={100}
value={Math.round((brushSettings.dynamics?.flowJitter ?? 0) * 100)}
- onChange={(e) => handleUpdateDynamics({ flowJitter: Number(e.target.value) / 100 })}
- className="w-full h-1 bg-[#282a2e] rounded appearance-none cursor-pointer accent-[#5ce1e6]"
+ onChange={(v) => handleUpdateDynamics({ flowJitter: v / 100 })}
/>
- </div>
-
- {/* 7. Color Dynamics Section */}
- <div className="pt-2 border-t border-[#26282c] space-y-2">
- <div className="flex items-center justify-between">
- <div className="flex items-center space-x-1.5">
- <Palette className="w-3.5 h-3.5 text-cyan-400" />
- <span className="text-xs text-[#cccccc] font-medium">Color Dynamics</span>
- </div>
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Color Jitter</span>
<input
type="checkbox"
checked={Boolean(brushSettings.dynamics?.colorJitterEnabled)}
- onChange={(e) => handleUpdateDynamics({ colorJitterEnabled: e.target.checked })}
- className="rounded bg-[#1a1b1e] border-[#383a40] text-[#5ce1e6] focus:ring-0 cursor-pointer"
+ onChange={(e) =>
+ handleUpdateDynamics({ colorJitterEnabled: e.target.checked })
+ }
/>
- </div>
-
+ </label>
{brushSettings.dynamics?.colorJitterEnabled && (
- <div className="space-y-2.5 pt-1 pl-1 border-l border-[#2e3138]">
- {/* Color preview swatch showing foreground & secondary color */}
- <div className="flex items-center justify-between text-[11px] text-[#8c9099] bg-[#151618] p-1.5 rounded border border-[#2b2d32]">
- <span>Mix FG & BG</span>
- <div className="flex items-center space-x-1.5">
- <span
- className="w-3.5 h-3.5 rounded-full border border-white/20"
- style={{ backgroundColor: brushSettings.color }}
- title={`Primary (FG): ${brushSettings.color}`}
- />
- <span className="text-[10px]">⇄</span>
- <span
- className="w-3.5 h-3.5 rounded-full border border-white/20"
- style={{ backgroundColor: secondaryColor }}
- title={`Secondary (BG): ${secondaryColor}`}
- />
- </div>
- </div>
-
- {/* Foreground / Background Jitter */}
- <div className="space-y-1">
- <div className="flex justify-between text-xs">
- <span className="text-[#8c9099]">FG/BG Jitter</span>
- <span className="font-mono text-white">
- {Math.round((brushSettings.dynamics?.foregroundBackgroundJitter ?? 0) * 100)}%
- </span>
- </div>
- <input
- type="range"
- min="0"
- max="100"
- value={Math.round((brushSettings.dynamics?.foregroundBackgroundJitter ?? 0) * 100)}
- onChange={(e) => handleUpdateDynamics({ foregroundBackgroundJitter: Number(e.target.value) / 100 })}
- className="w-full h-1 bg-[#282a2e] rounded appearance-none cursor-pointer accent-[#5ce1e6]"
- />
- </div>
-
- {/* Hue Jitter */}
- <div className="space-y-1">
- <div className="flex justify-between text-xs">
- <span className="text-[#8c9099]">Hue Jitter</span>
- <span className="font-mono text-white">
- {Math.round((brushSettings.dynamics?.hueJitter ?? 0) * 100)}%
- </span>
- </div>
- <input
- type="range"
- min="0"
- max="100"
- value={Math.round((brushSettings.dynamics?.hueJitter ?? 0) * 100)}
- onChange={(e) => handleUpdateDynamics({ hueJitter: Number(e.target.value) / 100 })}
- className="w-full h-1 bg-[#282a2e] rounded appearance-none cursor-pointer accent-[#5ce1e6]"
- />
- </div>
-
- {/* Saturation Jitter */}
- <div className="space-y-1">
- <div className="flex justify-between text-xs">
- <span className="text-[#8c9099]">Saturation Jitter</span>
- <span className="font-mono text-white">
- {Math.round((brushSettings.dynamics?.saturationJitter ?? 0) * 100)}%
- </span>
- </div>
- <input
- type="range"
- min="0"
- max="100"
- value={Math.round((brushSettings.dynamics?.saturationJitter ?? 0) * 100)}
- onChange={(e) => handleUpdateDynamics({ saturationJitter: Number(e.target.value) / 100 })}
- className="w-full h-1 bg-[#282a2e] rounded appearance-none cursor-pointer accent-[#5ce1e6]"
- />
- </div>
-
- {/* Brightness Jitter */}
- <div className="space-y-1">
- <div className="flex justify-between text-xs">
- <span className="text-[#8c9099]">Brightness Jitter</span>
- <span className="font-mono text-white">
- {Math.round((brushSettings.dynamics?.brightnessJitter ?? 0) * 100)}%
- </span>
- </div>
- <input
- type="range"
- min="0"
- max="100"
- value={Math.round((brushSettings.dynamics?.brightnessJitter ?? 0) * 100)}
- onChange={(e) => handleUpdateDynamics({ brightnessJitter: Number(e.target.value) / 100 })}
- className="w-full h-1 bg-[#282a2e] rounded appearance-none cursor-pointer accent-[#5ce1e6]"
- />
- </div>
- </div>
+ <>
+ <CompactSlider
+ label="Hue"
+ valueLabel={`${Math.round((brushSettings.dynamics?.hueJitter ?? 0) * 100)}%`}
+ min={0}
+ max={100}
+ value={Math.round((brushSettings.dynamics?.hueJitter ?? 0) * 100)}
+ onChange={(v) => handleUpdateDynamics({ hueJitter: v / 100 })}
+ />
+ <CompactSlider
+ label="Saturation"
+ valueLabel={`${Math.round((brushSettings.dynamics?.saturationJitter ?? 0) * 100)}%`}
+ min={0}
+ max={100}
+ value={Math.round((brushSettings.dynamics?.saturationJitter ?? 0) * 100)}
+ onChange={(v) => handleUpdateDynamics({ saturationJitter: v / 100 })}
+ />
+ <CompactSlider
+ label="Brightness"
+ valueLabel={`${Math.round((brushSettings.dynamics?.brightnessJitter ?? 0) * 100)}%`}
+ min={0}
+ max={100}
+ value={Math.round((brushSettings.dynamics?.brightnessJitter ?? 0) * 100)}
+ onChange={(v) => handleUpdateDynamics({ brightnessJitter: v / 100 })}
+ />
+ <CompactSlider
+ label="FG / BG Mix"
+ valueLabel={`${Math.round((brushSettings.dynamics?.foregroundBackgroundJitter ?? 0) * 100)}%`}
+ min={0}
+ max={100}
+ value={Math.round((brushSettings.dynamics?.foregroundBackgroundJitter ?? 0) * 100)}
+ onChange={(v) => handleUpdateDynamics({ foregroundBackgroundJitter: v / 100 })}
+ />
+ </>
)}
</div>
- </div>
- )}
+ )}
+ </div>
</div>
- </div>
+ </>
+ ) : (
+ renderContextualToolPanel()
)}
- </div>
- </>
- ) : (
- renderToolSettings()
- )}
- {/* RESIZABLE RIGHT EDGE (Hover gives col-resize; dragging adjusts panel width) */}
+ {/* Subtle Drag Handle on Right Edge */}
<div
- onMouseDown={handleWidthResizeMouseDown}
- title="Drag to resize brush settings panel width"
- className="group absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize hover:bg-[#5ce1e6]/60 active:bg-[#5ce1e6] transition-colors z-30"
- >
- <div className="w-full h-full opacity-0 group-hover:opacity-100 bg-[#5ce1e6]/60 transition-opacity" />
- </div>
+ onMouseDown={(e) => {
+ e.preventDefault();
+ setIsDraggingWidth(true);
+ dragStartXRef.current = e.clientX;
+ dragStartWidthRef.current = width;
+ }}
+ title="Resize brush panel"
+ className="absolute right-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-[var(--accent)]/40 transition-colors z-30"
+ />
</aside>
)}
</div>
diff --git a/src/components/Local3DContainer.tsx b/src/components/Local3DContainer.tsx
index c38a302..fa3d890 100644
--- a/src/components/Local3DContainer.tsx
+++ b/src/components/Local3DContainer.tsx
@@ -101,6 +101,12 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({
const [showPoseDrawer, setShowPoseDrawer] = useState<boolean>(false);
const [showLTModal, setShowLTModal] = useState<boolean>(false);
const [syncCameraPerspective, setSyncCameraPerspective] = useState<boolean>(true);
+ const syncCameraPerspectiveRef = useRef<boolean>(syncCameraPerspective);
+ syncCameraPerspectiveRef.current = syncCameraPerspective;
+ const onUpdatePerspectiveRulerRef = useRef(onUpdatePerspectiveRuler);
+ onUpdatePerspectiveRulerRef.current = onUpdatePerspectiveRuler;
+ const perspectiveRulerRef = useRef(perspectiveRuler);
+ perspectiveRulerRef.current = perspectiveRuler;
const [activeIKHandle, setActiveIKHandle] = useState<string | null>(null);
const [ltLineThreshold, setLtLineThreshold] = useState<number>(0.28);
const [ltToneBands, setLtToneBands] = useState<2 | 3>(2);
@@ -335,14 +341,14 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({
controls.dampingFactor = 0.08;
controls.target.set(0, 0.3, 0);
controls.addEventListener('change', () => {
- if (onUpdatePerspectiveRuler && cameraRef.current) {
+ if (syncCameraPerspectiveRef.current && onUpdatePerspectiveRulerRef.current && cameraRef.current) {
const ruler = calculatePerspectiveFromCamera(
cameraRef.current,
dimensions.width,
dimensions.height,
- perspectiveRuler
+ perspectiveRulerRef.current
);
- onUpdatePerspectiveRuler(ruler);
+ onUpdatePerspectiveRulerRef.current(ruler);
}
});
controlsRef.current = controls;
@@ -807,6 +813,12 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({
updateGizmoTarget();
// Detect humanoid skinned mesh hierarchy
+ if (ikHandlesContainerRef.current && sceneRef.current) {
+ disposeThreeResources(ikHandlesContainerRef.current, null);
+ sceneRef.current.remove(ikHandlesContainerRef.current);
+ ikHandlesContainerRef.current = null;
+ ikHandlesRef.current = null;
+ }
const detectedBones = findHumanoidBones(model);
if (detectedBones.hips || detectedBones.leftHand || detectedBones.rightHand || detectedBones.head) {
mannequinBonesRef.current = detectedBones;
@@ -905,8 +917,10 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({
modelRootRef.current = null;
}
if (ikHandlesContainerRef.current) {
+ disposeThreeResources(ikHandlesContainerRef.current, null);
sceneRef.current.remove(ikHandlesContainerRef.current);
ikHandlesContainerRef.current = null;
+ ikHandlesRef.current = null;
}
const { group, bones } = createProceduralMannequin();
@@ -1024,9 +1038,10 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({
setIsBaking(true);
try {
- // Temporarily hide helper gizmo and ground grid
+ // Temporarily hide helper gizmo, ground grid, and IK handles
if (transformHelperRef.current) transformHelperRef.current.visible = false;
if (gridHelperRef.current) gridHelperRef.current.visible = false;
+ if (ikHandlesContainerRef.current) ikHandlesContainerRef.current.visible = false;
const result = await bake3DToRasterLayer({
scene: sceneRef.current,
@@ -1048,6 +1063,7 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({
setIsBaking(false);
if (gridHelperRef.current) gridHelperRef.current.visible = showGrid;
if (transformHelperRef.current && gizmoMode !== 'none') transformHelperRef.current.visible = true;
+ if (ikHandlesContainerRef.current) ikHandlesContainerRef.current.visible = true;
}
};
diff --git a/src/components/MenuBar.tsx b/src/components/MenuBar.tsx
index 0cb4d8d..9465517 100644
--- a/src/components/MenuBar.tsx
+++ b/src/components/MenuBar.tsx
@@ -1,15 +1,17 @@
-import React, { useState, useRef, useEffect } from 'react';
+import React, { useState, useRef, useEffect, useCallback } from 'react';
+import { createPortal } from 'react-dom';
import { ChevronRight, Check } from 'lucide-react';
import { MenuSection, MenuItem } from '../types/editor';
export const DEFAULT_MENU_SECTIONS: MenuSection[] = [
{ id: 'file', label: 'File', items: [] },
{ id: 'edit', label: 'Edit', items: [] },
- { id: 'select', label: 'Select', items: [] },
+ { id: 'animation', label: 'Animation', items: [] },
{ id: 'layer', label: 'Layer', items: [] },
- { id: 'ruler', label: 'Ruler', items: [] },
+ { id: 'select', label: 'Select', items: [] },
+ { id: 'filter', label: 'Filter', items: [] },
{ id: 'view', label: 'View', items: [] },
- { id: 'manga', label: 'Manga', items: [] },
+ { id: 'window', label: 'Window', items: [] },
{ id: 'help', label: 'Help', items: [] },
];
@@ -17,219 +19,476 @@ interface MenuBarProps {
sections?: MenuSection[];
}
-export const MenuBar: React.FC<MenuBarProps> = ({ sections = DEFAULT_MENU_SECTIONS }) => {
+interface FloatingPosition {
+ top: number;
+ left: number;
+}
+
+export const MenuBar: React.FC<MenuBarProps> = React.memo(({ sections = DEFAULT_MENU_SECTIONS }) => {
const [activeMenuId, setActiveMenuId] = useState<string | null>(null);
const [activeSubmenuId, setActiveSubmenuId] = useState<string | null>(null);
+ const [focusedIndex, setFocusedIndex] = useState<number>(-1);
+ const [focusedSubIndex, setFocusedSubIndex] = useState<number>(-1);
+ const [menuPos, setMenuPos] = useState<FloatingPosition>({ top: 36, left: 8 });
+ const [submenuPos, setSubmenuPos] = useState<FloatingPosition>({ top: 36, left: 210 });
+
const containerRef = useRef<HTMLDivElement>(null);
+ const buttonRefs = useRef<Map<string, HTMLButtonElement>>(new Map());
+ const itemRefs = useRef<Map<string, HTMLButtonElement>>(new Map());
+ const menuPortalRef = useRef<HTMLDivElement>(null);
+ const submenuPortalRef = useRef<HTMLDivElement>(null);
+ const submenuTimerRef = useRef<number | null>(null);
+
+ const clearSubmenuTimer = useCallback(() => {
+ if (submenuTimerRef.current !== null) {
+ window.clearTimeout(submenuTimerRef.current);
+ submenuTimerRef.current = null;
+ }
+ }, []);
+
+ const closeAllMenus = useCallback(() => {
+ clearSubmenuTimer();
+ setActiveMenuId(null);
+ setActiveSubmenuId(null);
+ setFocusedIndex(-1);
+ setFocusedSubIndex(-1);
+ }, [clearSubmenuTimer]);
+
+ const computeMenuPosition = useCallback((menuId: string) => {
+ const btn = buttonRefs.current.get(menuId);
+ if (!btn) return;
+ const rect = btn.getBoundingClientRect();
+ const menuWidth = 220;
+ const clampedLeft = Math.max(4, Math.min(rect.left, window.innerWidth - menuWidth - 8));
+ setMenuPos({
+ top: Math.round(rect.bottom + 4),
+ left: Math.round(clampedLeft),
+ });
+ }, []);
+
+ const computeSubmenuPosition = useCallback((itemId: string, submenuCount: number) => {
+ const btn = itemRefs.current.get(itemId);
+ if (!btn) return;
+ const rect = btn.getBoundingClientRect();
+ const estWidth = 224;
+ const estHeight = Math.min(window.innerHeight - 16, submenuCount * 28 + 12);
+ const fitsRight = rect.right + 4 + estWidth <= window.innerWidth - 4;
+ const left = fitsRight ? rect.right + 2 : Math.max(4, rect.left - estWidth - 2);
+ const top = Math.max(8, Math.min(rect.top - 4, window.innerHeight - estHeight - 8));
+ setSubmenuPos({
+ top: Math.round(top),
+ left: Math.round(left),
+ });
+ }, []);
+
+ const openMenu = useCallback(
+ (menuId: string, autoFocusFirst = false) => {
+ clearSubmenuTimer();
+ computeMenuPosition(menuId);
+ setActiveMenuId(menuId);
+ setActiveSubmenuId(null);
+ setFocusedSubIndex(-1);
+ if (autoFocusFirst) {
+ const sec = sections.find((s) => s.id === menuId);
+ const firstIdx = sec?.items.findIndex((it) => !it.divider && !it.disabled) ?? -1;
+ setFocusedIndex(firstIdx);
+ } else {
+ setFocusedIndex(-1);
+ }
+ },
+ [clearSubmenuTimer, computeMenuPosition, sections]
+ );
+
+ const activeSection = activeMenuId ? sections.find((s) => s.id === activeMenuId) ?? null : null;
+ const activeSubmenuParent =
+ activeSection && activeSubmenuId
+ ? activeSection.items.find((it) => it.id === activeSubmenuId && !it.disabled && it.submenu?.length) ?? null
+ : null;
+
+ useEffect(() => {
+ return () => clearSubmenuTimer();
+ }, [clearSubmenuTimer]);
- // Close active dropdown on pointerdown outside or on Escape
useEffect(() => {
if (!activeMenuId) return;
- const handlePointerDown = (e: PointerEvent) => {
- if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
- setActiveMenuId(null);
- setActiveSubmenuId(null);
+ const handlePointerDownCapture = (e: PointerEvent) => {
+ const target = e.target as Node | null;
+ if (!target) return;
+ if (containerRef.current?.contains(target)) return;
+ if (menuPortalRef.current?.contains(target)) return;
+ if (submenuPortalRef.current?.contains(target)) return;
+ closeAllMenus();
+ };
+
+ const handleWindowDismiss = () => {
+ closeAllMenus();
+ };
+
+ const findNextEnabledIndex = (items: MenuItem[], current: number, delta: 1 | -1): number => {
+ if (items.length === 0) return -1;
+ let idx = current;
+ for (let step = 0; step < items.length; step++) {
+ idx = (idx + delta + items.length) % items.length;
+ const candidate = items[idx];
+ if (candidate && !candidate.divider && !candidate.disabled) {
+ return idx;
+ }
}
+ return -1;
};
const handleKeyDown = (e: KeyboardEvent) => {
+ if (!activeSection) return;
+
if (e.key === 'Escape') {
- setActiveMenuId(null);
- setActiveSubmenuId(null);
+ e.preventDefault();
+ e.stopPropagation();
+ if (activeSubmenuId) {
+ setActiveSubmenuId(null);
+ setFocusedSubIndex(-1);
+ } else {
+ closeAllMenus();
+ }
+ return;
+ }
+
+ if (e.key === 'ArrowDown') {
+ e.preventDefault();
+ e.stopPropagation();
+ if (activeSubmenuParent?.submenu) {
+ setFocusedSubIndex((prev) => findNextEnabledIndex(activeSubmenuParent.submenu!, prev, 1));
+ } else {
+ setFocusedIndex((prev) => findNextEnabledIndex(activeSection.items, prev, 1));
+ }
+ return;
+ }
+
+ if (e.key === 'ArrowUp') {
+ e.preventDefault();
+ e.stopPropagation();
+ if (activeSubmenuParent?.submenu) {
+ setFocusedSubIndex((prev) =>
+ findNextEnabledIndex(
+ activeSubmenuParent.submenu!,
+ prev < 0 ? 0 : prev,
+ -1
+ )
+ );
+ } else {
+ setFocusedIndex((prev) =>
+ findNextEnabledIndex(activeSection.items, prev < 0 ? 0 : prev, -1)
+ );
+ }
+ return;
+ }
+
+ if (e.key === 'ArrowRight') {
+ e.preventDefault();
+ e.stopPropagation();
+ const focusedItem = focusedIndex >= 0 ? activeSection.items[focusedIndex] : undefined;
+ if (!activeSubmenuId && focusedItem && !focusedItem.disabled && focusedItem.submenu?.length) {
+ computeSubmenuPosition(focusedItem.id, focusedItem.submenu.length);
+ setActiveSubmenuId(focusedItem.id);
+ setFocusedSubIndex(findNextEnabledIndex(focusedItem.submenu, -1, 1));
+ return;
+ }
+ const secIdx = sections.findIndex((s) => s.id === activeMenuId);
+ if (secIdx >= 0 && sections.length > 1) {
+ const nextSec = sections[(secIdx + 1) % sections.length];
+ openMenu(nextSec.id, true);
+ }
+ return;
+ }
+
+ if (e.key === 'ArrowLeft') {
+ e.preventDefault();
+ e.stopPropagation();
+ if (activeSubmenuId) {
+ setActiveSubmenuId(null);
+ setFocusedSubIndex(-1);
+ return;
+ }
+ const secIdx = sections.findIndex((s) => s.id === activeMenuId);
+ if (secIdx >= 0 && sections.length > 1) {
+ const prevSec = sections[(secIdx - 1 + sections.length) % sections.length];
+ openMenu(prevSec.id, true);
+ }
+ return;
+ }
+
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ e.stopPropagation();
+ if (activeSubmenuParent?.submenu && focusedSubIndex >= 0) {
+ const subItem = activeSubmenuParent.submenu[focusedSubIndex];
+ if (subItem && !subItem.disabled && !subItem.divider) {
+ closeAllMenus();
+ subItem.onClick?.();
+ }
+ return;
+ }
+ if (focusedIndex >= 0) {
+ const item = activeSection.items[focusedIndex];
+ if (!item || item.disabled || item.divider) return;
+ if (item.submenu?.length) {
+ computeSubmenuPosition(item.id, item.submenu.length);
+ setActiveSubmenuId(item.id);
+ setFocusedSubIndex(findNextEnabledIndex(item.submenu, -1, 1));
+ } else {
+ closeAllMenus();
+ item.onClick?.();
+ }
+ }
}
};
- window.addEventListener('pointerdown', handlePointerDown);
- window.addEventListener('keydown', handleKeyDown);
+ window.addEventListener('pointerdown', handlePointerDownCapture, true);
+ window.addEventListener('keydown', handleKeyDown, true);
+ window.addEventListener('blur', handleWindowDismiss);
+ window.addEventListener('resize', handleWindowDismiss);
return () => {
- window.removeEventListener('pointerdown', handlePointerDown);
- window.removeEventListener('keydown', handleKeyDown);
+ window.removeEventListener('pointerdown', handlePointerDownCapture, true);
+ window.removeEventListener('keydown', handleKeyDown, true);
+ window.removeEventListener('blur', handleWindowDismiss);
+ window.removeEventListener('resize', handleWindowDismiss);
};
- }, [activeMenuId]);
+ }, [
+ activeMenuId,
+ activeSection,
+ activeSubmenuId,
+ activeSubmenuParent,
+ closeAllMenus,
+ computeSubmenuPosition,
+ focusedIndex,
+ focusedSubIndex,
+ openMenu,
+ sections,
+ ]);
const handleHeaderClick = (menuId: string) => {
- setActiveMenuId((prev) => (prev === menuId ? null : menuId));
- setActiveSubmenuId(null);
+ if (activeMenuId === menuId) {
+ closeAllMenus();
+ } else {
+ openMenu(menuId, false);
+ }
};
const handleHeaderMouseEnter = (menuId: string) => {
- // If any menu is currently open, hovering over another top-level section switches to it
if (activeMenuId !== null && activeMenuId !== menuId) {
- setActiveMenuId(menuId);
- setActiveSubmenuId(null);
+ openMenu(menuId, false);
+ }
+ };
+
+ const handleItemMouseEnter = (item: MenuItem, idx: number) => {
+ clearSubmenuTimer();
+ if (!item.disabled) {
+ setFocusedIndex(idx);
+ }
+ const hasSub = Boolean(!item.disabled && item.submenu && item.submenu.length > 0);
+ if (hasSub) {
+ computeSubmenuPosition(item.id, item.submenu!.length);
+ setActiveSubmenuId(item.id);
+ setFocusedSubIndex(-1);
+ } else if (activeSubmenuId !== null) {
+ submenuTimerRef.current = window.setTimeout(() => {
+ setActiveSubmenuId(null);
+ setFocusedSubIndex(-1);
+ submenuTimerRef.current = null;
+ }, 160);
}
};
const handleItemClick = (item: MenuItem) => {
if (item.disabled) return;
if (item.submenu && item.submenu.length > 0) {
+ clearSubmenuTimer();
+ computeSubmenuPosition(item.id, item.submenu.length);
setActiveSubmenuId((prev) => (prev === item.id ? null : item.id));
return;
}
- setActiveMenuId(null);
- setActiveSubmenuId(null);
- if (item.onClick) {
- item.onClick();
- }
+ closeAllMenus();
+ item.onClick?.();
};
return (
- <nav
- ref={containerRef}
- className="flex items-center space-x-0.5 relative z-50"
- role="menubar"
- aria-label="Application Menu"
- >
- {sections.map((section) => {
- const isOpen = activeMenuId === section.id;
-
- return (
- <div key={section.id} className="relative">
- <button
- type="button"
- role="menuitem"
- aria-haspopup="true"
- aria-expanded={isOpen}
- onClick={() => handleHeaderClick(section.id)}
- onMouseEnter={() => handleHeaderMouseEnter(section.id)}
- className={`px-2.5 py-1 rounded-[2px] text-xs font-normal transition-colors select-none ${
- isOpen
- ? 'bg-[#37373d] text-white shadow-sm'
- : 'text-[#cccccc] hover:text-white hover:bg-[#333333]'
- }`}
+ <>
+ <nav
+ ref={containerRef}
+ className="flex items-center gap-0.5 relative z-50 shrink-0"
+ role="menubar"
+ aria-label="Application Menu"
+ >
+ {sections.map((section) => {
+ const isOpen = activeMenuId === section.id;
+
+ return (
+ <div key={section.id} className="relative">
+ <button
+ ref={(el) => {
+ if (el) buttonRefs.current.set(section.id, el);
+ else buttonRefs.current.delete(section.id);
+ }}
+ type="button"
+ role="menuitem"
+ aria-haspopup="true"
+ aria-expanded={isOpen}
+ onClick={() => handleHeaderClick(section.id)}
+ onMouseEnter={() => handleHeaderMouseEnter(section.id)}
+ className={`h-6 px-2 rounded text-[11px] transition-colors cursor-pointer ${
+ isOpen
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'
+ }`}
+ >
+ {section.label}
+ </button>
+ </div>
+ );
+ })}
+ </nav>
+
+ {activeSection &&
+ typeof document !== 'undefined' &&
+ createPortal(
+ <>
+ <div
+ ref={menuPortalRef}
+ role="menu"
+ style={{ top: menuPos.top, left: menuPos.left }}
+ onMouseEnter={clearSubmenuTimer}
+ className="fixed min-w-[216px] max-h-[calc(100vh-44px)] overflow-y-auto bg-[#202020] border border-[#2f2f2f] rounded-md p-1 z-[9998] text-[11px] text-[#e5e5e5] shadow-[0_14px_36px_rgba(0,0,0,0.72)] select-none"
>
- {section.label}
- </button>
+ {activeSection.items.length === 0 ? (
+ <div className="px-2.5 py-1.5 text-[#8a8a8a]">Empty</div>
+ ) : (
+ activeSection.items.map((item, idx) => {
+ if (item.divider) {
+ return <div key={`div-${idx}`} className="my-1 h-px bg-[#2c2c2c]" />;
+ }
- {/* Dropdown Menu */}
- {isOpen && (
+ const hasSubmenu = Boolean(item.submenu && item.submenu.length > 0);
+ const isSubmenuOpen = activeSubmenuId === item.id && !item.disabled;
+ const isFocused = focusedIndex === idx && !item.disabled;
+ const itemKey = item.id || `item-${idx}`;
+
+ return (
+ <button
+ key={itemKey}
+ ref={(el) => {
+ if (el && item.id) itemRefs.current.set(item.id, el);
+ else if (item.id) itemRefs.current.delete(item.id);
+ }}
+ type="button"
+ role="menuitem"
+ aria-haspopup={hasSubmenu ? 'true' : undefined}
+ aria-expanded={hasSubmenu ? isSubmenuOpen : undefined}
+ disabled={item.disabled}
+ onMouseEnter={() => handleItemMouseEnter(item, idx)}
+ onClick={() => handleItemClick(item)}
+ className={`w-full flex items-center justify-between px-2 py-1.5 rounded text-left transition-colors ${
+ item.disabled
+ ? 'text-[#8a8a8a]/40 cursor-not-allowed'
+ : isSubmenuOpen || isFocused
+ ? item.danger
+ ? 'bg-red-500/15 text-red-300 cursor-pointer'
+ : 'bg-[#2c2c2c] text-[#e5e5e5] cursor-pointer'
+ : item.danger
+ ? 'text-red-400 hover:bg-red-500/15 hover:text-red-300 cursor-pointer'
+ : 'text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer'
+ }`}
+ >
+ <span className="flex items-center gap-2 min-w-0">
+ <span className="w-3.5 h-3.5 flex items-center justify-center shrink-0">
+ {item.checked ? (
+ <Check className="w-3 h-3 text-[var(--accent)]" />
+ ) : item.icon ? (
+ <span className="w-3.5 h-3.5 flex items-center justify-center opacity-75">
+ {item.icon}
+ </span>
+ ) : null}
+ </span>
+ <span className="truncate">{item.label}</span>
+ </span>
+ {hasSubmenu ? (
+ <ChevronRight className="w-3 h-3 text-[#8a8a8a] ml-3 shrink-0" />
+ ) : (
+ item.shortcut && (
+ <span className="ml-4 font-mono text-[10px] text-[#8a8a8a] shrink-0">
+ {item.shortcut}
+ </span>
+ )
+ )}
+ </button>
+ );
+ })
+ )}
+ </div>
+
+ {activeSubmenuParent && activeSubmenuParent.submenu && (
<div
+ ref={submenuPortalRef}
role="menu"
- className="absolute top-full left-0 mt-1 min-w-[170px] bg-[#252526] border border-[#3e3e3e] rounded-[3px] shadow-2xl py-1 z-50 text-xs text-[#cccccc]"
- style={{
- boxShadow: '0 8px 24px rgba(0, 0, 0, 0.5), 0 2px 6px rgba(0, 0, 0, 0.4)',
- }}
+ style={{ top: submenuPos.top, left: submenuPos.left }}
+ onMouseEnter={clearSubmenuTimer}
+ className="fixed min-w-[220px] max-h-[calc(100vh-16px)] overflow-y-auto bg-[#202020] border border-[#2f2f2f] rounded-md p-1 z-[9999] text-[11px] text-[#e5e5e5] shadow-[0_14px_36px_rgba(0,0,0,0.75)] select-none"
>
- {section.items.length === 0 ? (
- <div className="px-3.5 py-2 text-xs text-[#777777] italic select-none">
- (Empty)
- </div>
- ) : (
- section.items.map((item, idx) => {
- if (item.divider) {
- return <div key={idx} className="my-1 border-t border-[#333333]" />;
- }
-
- const hasSubmenu = Boolean(item.submenu && item.submenu.length > 0);
- const isSubmenuOpen = activeSubmenuId === item.id;
-
- return (
- <div
- key={item.id || idx}
- className="relative"
- onMouseEnter={() => {
- if (hasSubmenu) {
- setActiveSubmenuId(item.id);
- } else {
- setActiveSubmenuId(null);
- }
- }}
- >
- <button
- type="button"
- role="menuitem"
- aria-haspopup={hasSubmenu ? 'true' : undefined}
- aria-expanded={hasSubmenu ? isSubmenuOpen : undefined}
- disabled={item.disabled}
- onClick={() => handleItemClick(item)}
- className={`w-full flex items-center justify-between px-3 py-1.5 text-left transition-colors ${
- item.disabled
- ? 'text-[#555555] cursor-not-allowed'
- : isSubmenuOpen
- ? 'bg-[#04395e] text-white'
- : item.danger
- ? 'hover:bg-red-600/20 hover:text-red-300 text-red-400'
- : 'hover:bg-[#04395e] hover:text-white text-[#cccccc]'
- }`}
- >
- <span className="flex items-center space-x-2">
- {item.icon ? (
- <span className="w-3.5 h-3.5 flex items-center justify-center">{item.icon}</span>
- ) : item.checked ? (
- <span className="w-3.5 h-3.5 flex items-center justify-center"><Check className="w-3.5 h-3.5 text-cyan-400" /></span>
- ) : null}
- <span>{item.label}</span>
- </span>
- {hasSubmenu ? (
- <ChevronRight className="w-3.5 h-3.5 text-[#888888] ml-3" />
- ) : (
- item.shortcut && (
- <span className="ml-4 font-mono text-[11px] text-[#777777]">
- {item.shortcut}
- </span>
- )
- )}
- </button>
-
- {/* Nested Submenu */}
- {hasSubmenu && isSubmenuOpen && !item.disabled && (
- <div
- role="menu"
- className="absolute top-0 left-full -ml-1 min-w-[210px] bg-[#252526] border border-[#3e3e3e] rounded-[3px] shadow-2xl py-1 z-50 text-xs text-[#cccccc]"
- style={{
- boxShadow: '0 8px 24px rgba(0, 0, 0, 0.5), 0 2px 6px rgba(0, 0, 0, 0.4)',
- }}
- >
- {item.submenu!.map((subItem, sIdx) => {
- if (subItem.divider) {
- return (
- <div key={sIdx} className="my-1 border-t border-[#333333]" />
- );
- }
-
- return (
- <button
- key={subItem.id || sIdx}
- type="button"
- role="menuitem"
- disabled={subItem.disabled}
- onClick={() => handleItemClick(subItem)}
- className={`w-full flex items-center justify-between px-3 py-1.5 text-left transition-colors ${
- subItem.disabled
- ? 'text-[#555555] cursor-not-allowed'
- : 'hover:bg-[#04395e] hover:text-white text-[#cccccc]'
- }`}
- >
- <span className="flex items-center space-x-2">
- {subItem.icon ? (
- <span className="w-3.5 h-3.5 flex items-center justify-center">{subItem.icon}</span>
- ) : subItem.checked ? (
- <span className="w-3.5 h-3.5 flex items-center justify-center"><Check className="w-3.5 h-3.5 text-cyan-400" /></span>
- ) : null}
- <span>{subItem.label}</span>
- </span>
- {subItem.shortcut && (
- <span className="ml-4 font-mono text-[11px] text-[#777777]">
- {subItem.shortcut}
- </span>
- )}
- </button>
- );
- })}
- </div>
- )}
- </div>
- );
- })
- )}
+ {activeSubmenuParent.submenu.map((subItem, sIdx) => {
+ if (subItem.divider) {
+ return <div key={`subdiv-${sIdx}`} className="my-1 h-px bg-[#2c2c2c]" />;
+ }
+ const isSubFocused = focusedSubIndex === sIdx && !subItem.disabled;
+ return (
+ <button
+ key={subItem.id || `sub-${sIdx}`}
+ type="button"
+ role="menuitem"
+ disabled={subItem.disabled}
+ onMouseEnter={() => {
+ clearSubmenuTimer();
+ if (!subItem.disabled) setFocusedSubIndex(sIdx);
+ }}
+ onClick={() => handleItemClick(subItem)}
+ className={`w-full flex items-center justify-between px-2 py-1.5 rounded text-left transition-colors ${
+ subItem.disabled
+ ? 'text-[#8a8a8a]/40 cursor-not-allowed'
+ : isSubFocused
+ ? subItem.danger
+ ? 'bg-red-500/15 text-red-300 cursor-pointer'
+ : 'bg-[#2c2c2c] text-[#e5e5e5] cursor-pointer'
+ : subItem.danger
+ ? 'text-red-400 hover:bg-red-500/15 hover:text-red-300 cursor-pointer'
+ : 'text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer'
+ }`}
+ >
+ <span className="flex items-center gap-2 min-w-0">
+ <span className="w-3.5 h-3.5 flex items-center justify-center shrink-0">
+ {subItem.checked ? (
+ <Check className="w-3 h-3 text-[var(--accent)]" />
+ ) : subItem.icon ? (
+ <span className="w-3.5 h-3.5 flex items-center justify-center opacity-75">
+ {subItem.icon}
+ </span>
+ ) : null}
+ </span>
+ <span className="truncate">{subItem.label}</span>
+ </span>
+ {subItem.shortcut && (
+ <span className="ml-4 font-mono text-[10px] text-[#8a8a8a] shrink-0">
+ {subItem.shortcut}
+ </span>
+ )}
+ </button>
+ );
+ })}
</div>
)}
- </div>
- );
- })}
- </nav>
+ </>,
+ document.body
+ )}
+ </>
);
-};
+});
+MenuBar.displayName = 'MenuBar';
diff --git a/src/components/RightSidebar.tsx b/src/components/RightSidebar.tsx
index adae5fc..cfe6cce 100644
--- a/src/components/RightSidebar.tsx
+++ b/src/components/RightSidebar.tsx
@@ -1,8 +1,5 @@
import React, { useState, useRef, useEffect } from 'react';
import {
- Palette,
- Layers,
- History,
Eye,
EyeOff,
Lock,
@@ -11,26 +8,26 @@ import {
Trash2,
Undo2,
Redo2,
- Paintbrush,
- Eraser,
Folder,
FolderOpen,
FolderPlus,
ChevronRight,
ChevronDown,
- ChevronUp,
Copy,
- FolderInput,
- FolderOutput,
Box,
- GripVertical,
Compass,
- SquareDot,
Link2,
SlidersHorizontal,
Sparkles,
} from 'lucide-react';
-import { HistoryItemMeta, LayerItem, BlendMode, ToolType, CanvasColorMode, ExpressionColor } from '../types/editor';
+import {
+ HistoryItemMeta,
+ LayerItem,
+ BlendMode,
+ ToolType,
+ CanvasColorMode,
+ ExpressionColor,
+} from '../types/editor';
import { BLEND_MODES } from '../utils/canvasUtils';
import { ColorPanel } from './ColorPanel';
@@ -48,7 +45,6 @@ interface RightSidebarProps {
canRedo: boolean;
onUndo: () => void;
onRedo: () => void;
- // Multi-layer management props
layers: LayerItem[];
activeLayerId: string;
selectedLayerIds?: string[];
@@ -70,25 +66,25 @@ interface RightSidebarProps {
onRenameLayer: (id: string, name: string) => void;
onMoveLayer?: (id: string, direction: 'up' | 'down') => void;
onMoveLayerToFolder: (id: string, targetFolderId: string | null) => void;
- // Non-destructive Layer Mask & Adjustment Props
activeEditTarget?: 'layer' | 'mask';
onSelectEditTarget?: (target: 'layer' | 'mask') => void;
onAddLayerMask?: (layerId: string) => void;
onRemoveLayerMask?: (layerId: string, apply?: boolean) => void;
onToggleLayerMask?: (layerId: string) => void;
onToggleMaskLinked?: (layerId: string) => void;
- onOpenAdjustmentModal?: (layerId?: string, initialType?: 'curves' | 'gradient-map' | 'levels' | 'color-balance') => void;
+ onOpenAdjustmentModal?: (
+ layerId?: string,
+ initialType?: 'curves' | 'gradient-map' | 'levels' | 'color-balance'
+ ) => void;
onOpenLayerStylesModal?: (layerId: string) => void;
onReorderLayers?: (draggedId: string, targetId: string, position: 'above' | 'below' | 'inside') => void;
onToggleReferenceLayer?: (id: string) => void;
- // Tone (Screentone) Effect Props
onToggleTone?: (id: string) => void;
onSetToneFrequency?: (id: string, frequency: number) => void;
onSetToneAngle?: (id: string, angle: number) => void;
onSetToneDotShape?: (id: string, dotShape: 'circle' | 'euclidean') => void;
onSetToneDensity?: (id: string, density: number) => void;
onSetToneDensityType?: (id: string, densityType: 'specified' | 'image') => void;
- // Clip Studio Paint Layer Color (Tint) & Expression Color Props
onToggleLayerColor?: (id: string) => void;
onSetLayerColor?: (id: string, color: string) => void;
onSetLayerSubColor?: (id: string, color: string) => void;
@@ -107,76 +103,19 @@ interface RightSidebarProps {
onOpenFile?: () => void;
}
-// Clip Studio Paint style Screentone / Halftone icon
-const ScreentoneIcon: React.FC<{ className?: string }> = ({ className = 'w-3.5 h-3.5' }) => (
- <svg viewBox="0 0 16 16" fill="currentColor" className={className}>
- <circle cx="3.5" cy="3.5" r="1.5" />
- <circle cx="12.5" cy="3.5" r="1.5" />
- <circle cx="8" cy="8" r="2.2" />
- <circle cx="3.5" cy="12.5" r="1.5" />
- <circle cx="12.5" cy="12.5" r="1.5" />
- </svg>
-);
-
-// Clip Studio Paint style Expression Color icons matching the screenshot
-export const CspColorIcon: React.FC<{ className?: string }> = ({ className = 'w-3.5 h-3.5' }) => (
- <svg viewBox="0 0 16 16" className={className} fill="none">
- <circle cx="8" cy="5.2" r="3.2" fill="#ef4444" />
- <circle cx="5.2" cy="10.8" r="3.2" fill="#22c55e" />
- <circle cx="10.8" cy="10.8" r="3.2" fill="#3b82f6" />
- <circle cx="8" cy="8.6" r="1.5" fill="#f59e0b" opacity="0.85" />
- </svg>
-);
-
-export const CspGrayIcon: React.FC<{ className?: string }> = ({ className = 'w-3.5 h-3.5' }) => (
- <svg viewBox="0 0 16 16" className={className}>
- <circle cx="8" cy="8" r="6" fill="#888888" stroke="#333333" strokeWidth="0.8" />
- <path d="M 8 2 A 6 6 0 0 0 3.76 12.24 L 12.24 3.76 A 6 6 0 0 0 8 2 Z" fill="#444444" />
- <line x1="3.76" y1="12.24" x2="12.24" y2="3.76" stroke="#222222" strokeWidth="0.8" />
- </svg>
-);
-
-export const CspMonoIcon: React.FC<{ className?: string }> = ({ className = 'w-3.5 h-3.5' }) => (
- <svg viewBox="0 0 16 16" className={className}>
- <rect x="2.5" y="2.5" width="11" height="11" rx="1" fill="#1e1e1e" stroke="#555555" strokeWidth="0.8" />
- <polygon points="2.5,13.5 13.5,13.5 2.5,2.5" fill="#d4d4d4" />
- <line x1="2.5" y1="2.5" x2="13.5" y2="13.5" stroke="#444444" strokeWidth="0.8" />
- </svg>
-);
-
-export const CspLayerColorIcon: React.FC<{ className?: string; color?: string }> = ({
- className = 'w-3.5 h-3.5',
- color = '#1c73c2',
-}) => (
- <svg viewBox="0 0 16 16" className={className}>
- <rect x="2" y="3.5" width="8" height="8" rx="1" fill={color} stroke="#333333" strokeWidth="0.8" />
- <rect x="6" y="6.5" width="8" height="6.5" rx="1" fill="#ffffff" stroke="#333333" strokeWidth="0.8" />
- </svg>
-);
-
-// Clip Studio Paint / Photoshop style "Clip to Layer Below" Indent Arrow icon
-export const ClipToLayerIcon: React.FC<{ className?: string }> = ({ className = 'w-3.5 h-3.5' }) => (
+const ClipToLayerIcon: React.FC<{ className?: string }> = ({ className = 'w-3 h-3' }) => (
<svg viewBox="0 0 16 16" fill="currentColor" className={className}>
- <path
- d="M3 2v6a2 2 0 0 0 2 2h4.5v2.5L14 9l-4.5-3.5V8H5V2H3z"
- stroke="currentColor"
- strokeWidth="0.5"
- />
+ <path d="M3 2v6a2 2 0 0 0 2 2h4.5v2.5L14 9l-4.5-3.5V8H5V2H3z" />
</svg>
);
-// Clip Studio Paint / Photoshop style "Lock Transparent Pixels" (Alpha Lock) icon
-export const AlphaLockIcon: React.FC<{ className?: string }> = ({ className = 'w-3.5 h-3.5' }) => (
+const AlphaLockIcon: React.FC<{ className?: string }> = ({ className = 'w-3 h-3' }) => (
<svg viewBox="0 0 16 16" className={className} fill="none">
- {/* Checkered pattern background */}
- <rect x="1.5" y="1.5" width="13" height="13" rx="1.5" stroke="currentColor" strokeWidth="1" />
- <rect x="2.5" y="2.5" width="5.5" height="5.5" fill="#888" opacity="0.6" />
- <rect x="8" y="8" width="5.5" height="5.5" fill="#888" opacity="0.6" />
- <rect x="8" y="2.5" width="5.5" height="5.5" fill="#ddd" opacity="0.4" />
- <rect x="2.5" y="8" width="5.5" height="5.5" fill="#ddd" opacity="0.4" />
- {/* Centered lock badge */}
+ <rect x="1.5" y="1.5" width="13" height="13" rx="1.5" stroke="currentColor" strokeWidth="1.2" />
+ <rect x="2.5" y="2.5" width="5.5" height="5.5" fill="currentColor" opacity="0.35" />
+ <rect x="8" y="8" width="5.5" height="5.5" fill="currentColor" opacity="0.35" />
<rect x="5.5" y="7.5" width="5" height="4.5" rx="1" fill="currentColor" />
- <path d="M6.5 7.5V6a1.5 1.5 0 0 1 3 0v1.5" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" />
+ <path d="M6.5 7.5V6a1.5 1.5 0 0 1 3 0v1.5" stroke="currentColor" strokeWidth="1.2" />
</svg>
);
@@ -216,7 +155,6 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
onToggleClipping,
onToggleCollapse,
onRenameLayer,
- onMoveLayerToFolder,
onReorderLayers,
activeEditTarget = 'layer',
onSelectEditTarget,
@@ -241,7 +179,7 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
onSetLayerMonoExpressMode,
onApplyExpressionColor,
onApplyLayerColor,
- width = 320,
+ width = 176,
onWidthChange,
hasOpenDocument = true,
onNewCanvas,
@@ -251,25 +189,15 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
const [editingLayerId, setEditingLayerId] = useState<string | null>(null);
const [editingName, setEditingName] = useState<string>('');
const [draggedLayerId, setDraggedLayerId] = useState<string | null>(null);
- const [dropIndicator, setDropIndicator] = useState<{ id: string; position: 'above' | 'below' | 'inside' } | null>(null);
- const [openFolderMenuLayerId, setOpenFolderMenuLayerId] = useState<string | null>(null);
- const [isToneSettingsOpen, setIsToneSettingsOpen] = useState(false);
- const [isLayerColorSettingsOpen, setIsLayerColorSettingsOpen] = useState(false);
- const [isExpressionMenuOpen, setIsExpressionMenuOpen] = useState(false);
- const expressionMenuRef = useRef<HTMLDivElement>(null);
+ const [dropIndicator, setDropIndicator] = useState<{
+ id: string;
+ position: 'above' | 'below' | 'inside';
+ } | null>(null);
- useEffect(() => {
- if (!isExpressionMenuOpen) return;
- const handlePointerDown = (e: MouseEvent) => {
- if (expressionMenuRef.current && !expressionMenuRef.current.contains(e.target as Node)) {
- setIsExpressionMenuOpen(false);
- }
- };
- window.addEventListener('mousedown', handlePointerDown);
- return () => window.removeEventListener('mousedown', handlePointerDown);
- }, [isExpressionMenuOpen]);
+ // Tucked collapsible accordions for advanced layer settings
+ const [isExpressionAccordionOpen, setIsExpressionAccordionOpen] = useState(false);
+ const [isEffectsAccordionOpen, setIsEffectsAccordionOpen] = useState(false);
- // Right-click layer context menu state
const [contextMenu, setContextMenu] = useState<{ layerId: string; x: number; y: number } | null>(null);
const contextMenuRef = useRef<HTMLDivElement>(null);
@@ -281,9 +209,7 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
}
};
const handleKeyDown = (e: KeyboardEvent) => {
- if (e.key === 'Escape') {
- setContextMenu(null);
- }
+ if (e.key === 'Escape') setContextMenu(null);
};
window.addEventListener('pointerdown', handleOutsideClick);
window.addEventListener('keydown', handleKeyDown);
@@ -293,71 +219,18 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
};
}, [contextMenu]);
- // Top Section (Color Panel) Height & Resizer
- const [topHeight, setTopHeight] = useState<number>(() => {
- const saved = localStorage.getItem('sora_paint_right_color_height');
- return saved ? Math.max(160, Math.min(500, parseInt(saved, 10))) : 280;
- });
- const [isDraggingHeight, setIsDraggingHeight] = useState(false);
- const dragStartYRef = useRef(0);
- const dragStartHeightRef = useRef(0);
-
- const handleHeightResizeMouseDown = (e: React.MouseEvent) => {
- e.preventDefault();
- setIsDraggingHeight(true);
- dragStartYRef.current = e.clientY;
- dragStartHeightRef.current = topHeight;
- };
-
- useEffect(() => {
- if (!isDraggingHeight) return;
-
- const handlePointerMove = (e: PointerEvent) => {
- const delta = e.clientY - dragStartYRef.current;
- const newHeight = Math.max(160, Math.min(600, Math.round(dragStartHeightRef.current + delta)));
- setTopHeight(newHeight);
- localStorage.setItem('sora_paint_right_color_height', String(newHeight));
- };
-
- const handlePointerUp = () => {
- setIsDraggingHeight(false);
- };
-
- window.addEventListener('pointermove', handlePointerMove);
- window.addEventListener('pointerup', handlePointerUp);
- return () => {
- window.removeEventListener('pointermove', handlePointerMove);
- window.removeEventListener('pointerup', handlePointerUp);
- };
- }, [isDraggingHeight]);
-
const [isResizing, setIsResizing] = useState(false);
const startXRef = useRef(0);
const startWidthRef = useRef(width);
- const handleResizeMouseDown = (e: React.MouseEvent) => {
- e.preventDefault();
- setIsResizing(true);
- startXRef.current = e.clientX;
- startWidthRef.current = width;
- };
-
useEffect(() => {
if (!isResizing) return;
-
const handlePointerMove = (e: PointerEvent) => {
- // Dragging left increases width, dragging right decreases width
const delta = startXRef.current - e.clientX;
- const newWidth = Math.max(220, Math.min(550, Math.round(startWidthRef.current + delta)));
- if (onWidthChange) {
- onWidthChange(newWidth);
- }
- };
-
- const handlePointerUp = () => {
- setIsResizing(false);
+ const newWidth = Math.max(164, Math.min(360, Math.round(startWidthRef.current + delta)));
+ onWidthChange?.(newWidth);
};
-
+ const handlePointerUp = () => setIsResizing(false);
window.addEventListener('pointermove', handlePointerMove);
window.addEventListener('pointerup', handlePointerUp);
return () => {
@@ -366,8 +239,7 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
};
}, [isResizing, onWidthChange]);
- const activeLayer = hasOpenDocument ? (layers.find((l) => l.id === activeLayerId) || layers[0]) : undefined;
- const folders = layers.filter((l) => l.type === 'folder');
+ const activeLayer = hasOpenDocument ? layers.find((l) => l.id === activeLayerId) || layers[0] : undefined;
const startRename = (layer: LayerItem) => {
setEditingLayerId(layer.id);
@@ -382,12 +254,7 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
};
const layerListContainerRef = useRef<HTMLDivElement>(null);
- const dragRef = useRef<{
- active: boolean;
- layerId: string | null;
- startX: number;
- startY: number;
- }>({
+ const dragRef = useRef<{ active: boolean; layerId: string | null; startX: number; startY: number }>({
active: false,
layerId: null,
startX: 0,
@@ -404,21 +271,11 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
}, []);
const handleLayerPointerDown = (e: React.PointerEvent<HTMLDivElement>, layerId: string) => {
- if (e.button !== 0) return;
- if (editingLayerId !== null) return;
+ if (e.button !== 0 || editingLayerId !== null) return;
const target = e.target as HTMLElement | null;
- if (target?.closest('button, input, select, textarea, [data-no-drag]')) {
- return;
- }
+ if (target?.closest('button, input, select, textarea, [data-no-drag]')) return;
- const startX = e.clientX;
- const startY = e.clientY;
- dragRef.current = {
- active: false,
- layerId,
- startX,
- startY,
- };
+ dragRef.current = { active: false, layerId, startX: e.clientX, startY: e.clientY };
dropIndicatorRef.current = null;
let autoScrollTimer: number | null = null;
@@ -444,19 +301,21 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
}
}
- // Autoscroll container when dragging near top or bottom edges
const container = layerListContainerRef.current;
if (container) {
const cRect = container.getBoundingClientRect();
const topDist = moveEvt.clientY - cRect.top;
const bottomDist = cRect.bottom - moveEvt.clientY;
-
stopAutoScroll();
if (topDist < 32 && topDist > -30 && container.scrollTop > 0) {
autoScrollTimer = window.setInterval(() => {
container.scrollTop -= 7;
}, 16);
- } else if (bottomDist < 32 && bottomDist > -30 && container.scrollTop + container.clientHeight < container.scrollHeight) {
+ } else if (
+ bottomDist < 32 &&
+ bottomDist > -30 &&
+ container.scrollTop + container.clientHeight < container.scrollHeight
+ ) {
autoScrollTimer = window.setInterval(() => {
container.scrollTop += 7;
}, 16);
@@ -465,7 +324,6 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
const hovered = document.elementFromPoint(moveEvt.clientX, moveEvt.clientY) as HTMLElement | null;
const row = hovered?.closest('[data-layer-id]') as HTMLElement | null;
-
if (!row) {
if (dropIndicatorRef.current) {
dropIndicatorRef.current = null;
@@ -474,10 +332,8 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
return;
}
- const draggedIds = selectedLayerIds && selectedLayerIds.includes(layerId)
- ? selectedLayerIds
- : [layerId];
-
+ const draggedIds =
+ selectedLayerIds && selectedLayerIds.includes(layerId) ? selectedLayerIds : [layerId];
const targetId = row.dataset.layerId;
if (!targetId || draggedIds.includes(targetId)) {
if (dropIndicatorRef.current) {
@@ -488,15 +344,8 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
}
const targetLayer = layers.find((l) => l.id === targetId);
- if (!targetLayer) {
- if (dropIndicatorRef.current) {
- dropIndicatorRef.current = null;
- setDropIndicator(null);
- }
- return;
- }
+ if (!targetLayer) return;
- // Prevent dragging a folder into its own subtree
let isDescendant = false;
for (const dId of draggedIds) {
const draggedItem = layers.find((l) => l.id === dId);
@@ -512,32 +361,15 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
}
if (isDescendant) break;
}
- if (isDescendant) {
- if (dropIndicatorRef.current) {
- dropIndicatorRef.current = null;
- setDropIndicator(null);
- }
- return;
- }
+ if (isDescendant) return;
const rect = row.getBoundingClientRect();
const yRatio = (moveEvt.clientY - rect.top) / rect.height;
-
let position: 'above' | 'below' | 'inside';
if (targetLayer.type === 'folder') {
- if (yRatio > 0.25 && yRatio < 0.75) {
- position = 'inside';
- } else if (yRatio <= 0.25) {
- position = 'above';
- } else {
- position = 'below';
- }
+ position = yRatio > 0.25 && yRatio < 0.75 ? 'inside' : yRatio <= 0.25 ? 'above' : 'below';
} else {
- if (yRatio <= 0.5) {
- position = 'above';
- } else {
- position = 'below';
- }
+ position = yRatio <= 0.5 ? 'above' : 'below';
}
const nextIndicator = { id: targetId, position };
@@ -550,7 +382,6 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
window.removeEventListener('pointerup', handlePointerUp);
window.removeEventListener('pointercancel', handlePointerUp);
stopAutoScroll();
-
document.body.style.userSelect = '';
document.body.style.cursor = '';
@@ -561,9 +392,8 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
}, 100);
const currentIndicator = dropIndicatorRef.current;
- const draggedIds = selectedLayerIds && selectedLayerIds.includes(layerId)
- ? selectedLayerIds
- : [layerId];
+ const draggedIds =
+ selectedLayerIds && selectedLayerIds.includes(layerId) ? selectedLayerIds : [layerId];
if (currentIndicator && !draggedIds.includes(currentIndicator.id) && onReorderLayers) {
onReorderLayers(layerId, currentIndicator.id, currentIndicator.position);
}
@@ -583,170 +413,185 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
return (
<aside
style={{ width }}
- className="relative bg-[#252526] border-l border-[#333333] flex flex-col text-[#cccccc] text-xs select-none z-10 shrink-0 overflow-hidden"
+ className="relative bg-[#161616] flex flex-col gap-px text-[#e5e5e5] text-xs select-none z-10 shrink-0 overflow-hidden"
>
- {/* Resizable Left Edge (Hover gives col-resize; dragging adjusts panel width) */}
+ {/* Left Resize Seam */}
<div
- onMouseDown={handleResizeMouseDown}
- title="Drag to resize panel width"
- className="group absolute left-0 top-0 bottom-0 w-1.5 cursor-col-resize hover:bg-[#5ce1e6]/60 active:bg-[#5ce1e6] transition-colors z-30"
- >
- <div className="w-full h-full opacity-0 group-hover:opacity-100 bg-[#5ce1e6]/60 transition-opacity" />
- </div>
- {/* Scrollable Upper Section: Color & Brush Properties */}
- <div style={{ height: topHeight }} className="overflow-y-auto shrink-0 border-b border-[#333333]">
- {/* 1. Full-Featured Color Palette Panel: Color Wheel & Color Slider (Clip Studio Paint style) */}
- <section className="bg-[#252526] h-full">
- <ColorPanel
- primaryColor={primaryColor}
- secondaryColor={secondaryColor}
- onPrimaryColorChange={onPrimaryColorChange}
- onSecondaryColorChange={onSecondaryColorChange}
- onSwapColors={onSwapColors}
- colorMode={colorMode}
- currentTool={currentTool}
- onSelectTool={onSelectTool}
- recentColors={recentColors}
- containerWidth={width}
- containerHeight={topHeight}
- />
- </section>
- </div>
-
- {/* Resizable Horizontal Divider between Color and Layers */}
- <div
- onMouseDown={handleHeightResizeMouseDown}
- title="Drag to resize height"
- className="group relative h-1.5 w-full cursor-row-resize flex items-center justify-center shrink-0 hover:bg-[#5ce1e6]/40 transition-colors z-20 bg-[#1e1e1e]"
- >
- <div className="w-8 h-0.5 bg-[#3a3d44] group-hover:bg-[#5ce1e6] rounded-full transition-colors" />
- </div>
-
- {/* 3. Bottom Multi-Panel: Full Layer Management & History Stack */}
- <section className="flex-1 min-h-[160px] border-t border-[#333333] flex flex-col bg-[#222223] overflow-hidden">
- {/* Tab Headers */}
- <div className="bg-[#2a2a2a] px-2 py-1.5 border-b border-[#333333] flex items-center justify-between shrink-0">
- <div className="flex items-center space-x-1">
+ onMouseDown={(e) => {
+ e.preventDefault();
+ setIsResizing(true);
+ startXRef.current = e.clientX;
+ startWidthRef.current = width;
+ }}
+ title="Resize sidebar"
+ className="absolute left-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-[var(--accent)]/40 transition-colors z-30"
+ />
+
+ {/* 1. Compact Color Wheel (<= 30% of sidebar height) */}
+ <section className="h-[28%] max-h-[30%] shrink-0 overflow-hidden bg-[#202020]">
+ <ColorPanel
+ primaryColor={primaryColor}
+ secondaryColor={secondaryColor}
+ onPrimaryColorChange={onPrimaryColorChange}
+ onSecondaryColorChange={onSecondaryColorChange}
+ onSwapColors={onSwapColors}
+ colorMode={colorMode}
+ currentTool={currentTool}
+ onSelectTool={onSelectTool}
+ recentColors={recentColors}
+ containerWidth={width}
+ />
+ </section>
+
+ {/* 2. Spacious Layers Panel (>= 70% of sidebar height) */}
+ <section className="flex-1 min-h-[70%] flex flex-col bg-[#202020] overflow-hidden">
+ {/* Header Bar: Layers / History Switch + Quick Layer Actions */}
+ <div className="h-7 px-1.5 flex items-center justify-between shrink-0">
+ <div className="flex items-center gap-0.5">
<button
+ type="button"
onClick={() => setBottomTab('layers')}
- className={`flex items-center space-x-1.5 px-2.5 py-1 rounded-[2px] font-medium transition-colors ${
+ className={`px-1.5 py-0.5 rounded text-[11px] transition-colors cursor-pointer ${
bottomTab === 'layers'
- ? 'bg-[#383838] text-white border border-[#4a4a4a]'
- : 'text-[#888888] hover:text-[#cccccc]'
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
}`}
>
- <Layers className="w-3.5 h-3.5" />
- <span>Layers</span>
- <span className="text-[10px] font-mono px-1 rounded bg-[#1e1e1e] text-[#aaaaaa]">
- {hasOpenDocument ? layers.length : 0}
- </span>
+ Layers
</button>
-
<button
+ type="button"
onClick={() => setBottomTab('history')}
- className={`flex items-center space-x-1.5 px-2.5 py-1 rounded-[2px] font-medium transition-colors ${
+ className={`px-1.5 py-0.5 rounded text-[11px] transition-colors cursor-pointer ${
bottomTab === 'history'
- ? 'bg-[#383838] text-white border border-[#4a4a4a]'
- : 'text-[#888888] hover:text-[#cccccc]'
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
}`}
>
- <History className="w-3.5 h-3.5" />
- <span>History</span>
- <span className="text-[10px] font-mono px-1 rounded bg-[#1e1e1e] text-[#aaaaaa]">
- {hasOpenDocument && historyList.length > 0 ? `${historyIndex + 1}/${historyList.length}` : '0/0'}
- </span>
+ History
</button>
</div>
- {/* Quick Undo / Redo in tab header if history active */}
+ {bottomTab === 'layers' && hasOpenDocument && (
+ <div className="flex items-center gap-0.5">
+ <button
+ type="button"
+ onClick={() => onAddLayer('raster')}
+ title="New Layer (Ctrl+Shift+N)"
+ className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ <Plus className="w-3.5 h-3.5" />
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ if (onGroupSelectedLayers && selectedLayerIds && selectedLayerIds.length > 1) {
+ onGroupSelectedLayers();
+ } else {
+ onAddLayer('folder');
+ }
+ }}
+ title="New Folder / Group (Ctrl+G)"
+ className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ <FolderPlus className="w-3 h-3" />
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ if (onDeleteSelectedLayers && selectedLayerIds && selectedLayerIds.length > 1) {
+ onDeleteSelectedLayers();
+ } else {
+ onDeleteLayer(activeLayerId);
+ }
+ }}
+ title="Delete Layer"
+ className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-red-400 hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ <Trash2 className="w-3 h-3" />
+ </button>
+ </div>
+ )}
+
{bottomTab === 'history' && (
- <div className="flex items-center space-x-1">
+ <div className="flex items-center gap-0.5">
<button
+ type="button"
onClick={onUndo}
disabled={!hasOpenDocument || !canUndo}
- title="Undo (Ctrl+Z)"
- className={`p-1 rounded-[2px] transition-colors ${
+ title="Undo"
+ className={`w-5 h-5 rounded flex items-center justify-center ${
hasOpenDocument && canUndo
- ? 'text-[#aaaaaa] hover:text-white hover:bg-[#383838]'
- : 'text-[#444444] cursor-not-allowed'
+ ? 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer'
+ : 'text-[#8a8a8a]/25 cursor-not-allowed'
}`}
>
- <Undo2 className="w-3.5 h-3.5" />
+ <Undo2 className="w-3 h-3" />
</button>
<button
+ type="button"
onClick={onRedo}
disabled={!hasOpenDocument || !canRedo}
- title="Redo (Ctrl+Y)"
- className={`p-1 rounded-[2px] transition-colors ${
+ title="Redo"
+ className={`w-5 h-5 rounded flex items-center justify-center ${
hasOpenDocument && canRedo
- ? 'text-[#aaaaaa] hover:text-white hover:bg-[#383838]'
- : 'text-[#444444] cursor-not-allowed'
+ ? 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer'
+ : 'text-[#8a8a8a]/25 cursor-not-allowed'
}`}
>
- <Redo2 className="w-3.5 h-3.5" />
+ <Redo2 className="w-3 h-3" />
</button>
</div>
)}
</div>
- {/* Tab Content 1: Comprehensive Layer Management Panel */}
- {bottomTab === 'layers' && (
+ {/* Layers Content */}
+ {bottomTab === 'layers' ? (
<div className="flex-1 flex flex-col overflow-hidden min-h-0">
{!hasOpenDocument ? (
- <div className="flex-1 flex flex-col items-center justify-center p-4 text-center select-none text-[#777777]">
- <Layers className="w-8 h-8 mb-2 opacity-30 text-[#aaaaaa]" />
- <p className="text-xs text-[#aaaaaa] font-medium">No Project Open</p>
- <p className="text-[11px] text-[#666666] mt-1 max-w-[200px]">
- Create a new canvas or open a file to manage layers.
- </p>
- {(onNewCanvas || onOpenFile) && (
- <div className="flex items-center space-x-2 mt-3.5">
- {onNewCanvas && (
- <button
- onClick={onNewCanvas}
- className="px-2.5 py-1 text-[11px] bg-[#2d2d30] hover:bg-[#38383c] hover:text-white text-[#cccccc] border border-[#3e3e42] rounded-[3px] transition-colors cursor-pointer"
- >
- New Canvas
- </button>
- )}
- {onOpenFile && (
- <button
- onClick={onOpenFile}
- className="px-2.5 py-1 text-[11px] bg-[#2d2d30] hover:bg-[#38383c] hover:text-white text-[#cccccc] border border-[#3e3e42] rounded-[3px] transition-colors cursor-pointer"
- >
- Open File
- </button>
- )}
- </div>
- )}
+ <div className="flex-1 flex flex-col items-center justify-center p-4 text-center text-[#8a8a8a]">
+ <p className="text-[11px] mb-2">No canvas open</p>
+ <div className="flex items-center gap-1.5">
+ {onNewCanvas && (
+ <button
+ type="button"
+ onClick={onNewCanvas}
+ className="px-2.5 py-1 rounded bg-[#2c2c2c] text-[11px] text-[#e5e5e5] cursor-pointer"
+ >
+ New
+ </button>
+ )}
+ {onOpenFile && (
+ <button
+ type="button"
+ onClick={onOpenFile}
+ className="px-2.5 py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer"
+ >
+ Open
+ </button>
+ )}
+ </div>
</div>
) : (
<>
- {/* Active Layer Blend Mode & Opacity Controls */}
- {/* Active Layer Blend Mode, Opacity & Tone Property Controls */}
{activeLayer && (
- <div className="px-2.5 py-1.5 bg-[#252526] border-b border-[#333333] flex flex-col space-y-1.5 shrink-0 max-h-[48%] overflow-y-auto">
- {/* Blend Mode & Opacity */}
- <div className="flex items-center space-x-2">
- {/* Blend Mode Dropdown */}
- <div className="w-1/2">
- <select
- value={activeLayer.blendMode}
- onChange={(e) => onSetBlendMode(activeLayer.id, e.target.value as BlendMode)}
- className="w-full bg-[#1e1e1e] border border-[#3a3a3a] text-[#cccccc] text-[11px] rounded-[2px] px-1.5 py-0.5 outline-none cursor-pointer hover:border-[#555555]"
- title="Active Layer Blending Mode"
- >
- {BLEND_MODES.map((mode) => (
- <option key={mode.value} value={mode.value}>
- {mode.label}
- </option>
- ))}
- </select>
- </div>
-
- {/* Opacity Slider */}
- <div className="w-1/2 flex items-center space-x-1.5">
- <span className="text-[10px] text-[#777777]">Op:</span>
+ <div className="px-2 pb-1.5 space-y-1.5 shrink-0">
+ {/* Quick Access: Blend Mode & Layer Opacity */}
+ <div className="flex items-center gap-1.5">
+ <select
+ value={activeLayer.blendMode}
+ onChange={(e) => onSetBlendMode(activeLayer.id, e.target.value as BlendMode)}
+ className="w-[46%] min-w-0 h-6 bg-[#161616] text-[#e5e5e5] text-[11px] px-1.5 rounded cursor-pointer truncate"
+ title="Blend Mode"
+ >
+ {BLEND_MODES.map((mode) => (
+ <option key={mode.value} value={mode.value} className="bg-[#202020] text-[#e5e5e5]">
+ {mode.label}
+ </option>
+ ))}
+ </select>
+
+ <div className="flex-1 min-w-0 flex items-center gap-1 bg-[#161616] rounded px-1.5 h-6">
<input
type="range"
min="0"
@@ -754,1515 +599,890 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
step="0.01"
value={activeLayer.opacity}
onChange={(e) => onSetOpacity(activeLayer.id, parseFloat(e.target.value))}
- className="flex-1 cursor-pointer h-3"
+ className="flex-1 min-w-0"
title={`Layer Opacity: ${Math.round(activeLayer.opacity * 100)}%`}
/>
- <span className="text-[10px] font-mono text-[#aaaaaa] w-7 text-right">
+ <span className="text-[10px] font-mono text-[#8a8a8a] w-7 text-right shrink-0">
{Math.round(activeLayer.opacity * 100)}%
</span>
</div>
</div>
- {/* Clip Studio Paint Style Effect Toggle & Controls (Tone & Layer Color) */}
- {activeLayer.type !== 'folder' && (
- <div className="pt-1 border-t border-[#333333]/70 flex flex-col space-y-1">
- <div className="flex items-center justify-between">
- <div className="flex items-center space-x-1.5 flex-wrap gap-y-1">
- <span className="text-[10px] uppercase font-semibold tracking-wider text-[#888888]">Effect:</span>
+ {/* Quick Layer Property Flags */}
+ <div className="flex items-center justify-between gap-0.5">
+ <div className="flex items-center gap-0.5">
+ {activeLayer.type !== 'folder' && (
+ <button
+ type="button"
+ onClick={() => onToggleAlphaLock?.(activeLayer.id)}
+ title="Lock Transparent Pixels (Alpha Lock)"
+ className={`w-5 h-5 rounded flex items-center justify-center transition-colors cursor-pointer ${
+ activeLayer.alphaLocked
+ ? 'bg-[#2c2c2c] text-[var(--accent)]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'
+ }`}
+ >
+ <AlphaLockIcon />
+ </button>
+ )}
+ {activeLayer.id !== 'layer-bg' && (
+ <button
+ type="button"
+ onClick={() => onToggleClipping?.(activeLayer.id)}
+ title="Clip to Layer Below"
+ className={`w-5 h-5 rounded flex items-center justify-center transition-colors cursor-pointer ${
+ activeLayer.clipped
+ ? 'bg-[#2c2c2c] text-[var(--accent)]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'
+ }`}
+ >
+ <ClipToLayerIcon />
+ </button>
+ )}
+ <button
+ type="button"
+ onClick={() => onToggleReferenceLayer?.(activeLayer.id)}
+ title="Reference Layer"
+ className={`w-5 h-5 rounded flex items-center justify-center transition-colors cursor-pointer ${
+ activeLayer.isReference
+ ? 'bg-[#2c2c2c] text-[var(--accent)]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'
+ }`}
+ >
+ <Compass className="w-3 h-3" />
+ </button>
+ <button
+ type="button"
+ onClick={() => onToggleLock(activeLayer.id)}
+ title={activeLayer.locked ? 'Unlock Layer' : 'Lock Layer'}
+ className={`w-5 h-5 rounded flex items-center justify-center transition-colors cursor-pointer ${
+ activeLayer.locked
+ ? 'bg-[#2c2c2c] text-[var(--accent)]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'
+ }`}
+ >
+ {activeLayer.locked ? (
+ <Lock className="w-3 h-3" />
+ ) : (
+ <Unlock className="w-3 h-3" />
+ )}
+ </button>
+ </div>
- {/* Tone (Screentone) Effect Toggle */}
+ <div className="flex items-center gap-0.5">
+ <button
+ type="button"
+ onClick={() => onDuplicateLayer(activeLayer.id)}
+ title="Duplicate Layer (Ctrl+J)"
+ className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ <Copy className="w-3 h-3" />
+ </button>
+ {onOpen3DLayer && (
+ <button
+ type="button"
+ onClick={onOpen3DLayer}
+ title="3D Reference Layer"
+ className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ <Box className="w-3 h-3" />
+ </button>
+ )}
+ {onOpenLayerStylesModal &&
+ activeLayer.type !== 'folder' &&
+ activeLayer.type !== 'adjustment' && (
<button
type="button"
- onClick={() => {
- const willEnable = !activeLayer.toneEnabled;
- onToggleTone?.(activeLayer.id);
- if (willEnable) {
- setIsToneSettingsOpen(true);
- }
- }}
- title={
- activeLayer.toneEnabled
- ? 'Tone is active (Click to disable and restore smooth drawing)'
- : 'Convert Layer to Screentone (Clip Studio Paint style halftone effect)'
- }
- className={`flex items-center space-x-1.5 px-2 py-0.5 rounded text-[11px] font-medium transition-all cursor-pointer ${
- activeLayer.toneEnabled
- ? 'bg-amber-500/25 text-amber-300 border border-amber-500/50 shadow-sm'
- : 'bg-[#1e1e1e] text-[#888888] hover:text-[#cccccc] hover:bg-[#2a2a2a] border border-[#3a3a3a]'
- }`}
+ onClick={() => onOpenLayerStylesModal(activeLayer.id)}
+ title="Layer Styles (fx)"
+ className="h-5 px-1 rounded text-[10px] font-mono text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer"
>
- <ScreentoneIcon className={`w-3 h-3 ${activeLayer.toneEnabled ? 'text-amber-400' : 'text-[#888888]'}`} />
- <span>Tone</span>
+ fx
</button>
+ )}
+ </div>
+ </div>
+ </div>
+ )}
- {/* Layer Color (Tint) Effect Toggle */}
- <button
- type="button"
- onClick={() => {
- const willEnable = !activeLayer.layerColorEnabled;
- onToggleLayerColor?.(activeLayer.id);
- if (willEnable) {
- setIsLayerColorSettingsOpen(true);
- }
- }}
- title={
- activeLayer.layerColorEnabled
- ? 'Layer color tint is active (Click to disable)'
- : 'Apply tint to layer (Clip Studio Paint style Layer Color effect)'
- }
- className={`flex items-center space-x-1.5 px-2 py-0.5 rounded text-[11px] font-medium transition-all cursor-pointer ${
- activeLayer.layerColorEnabled
- ? 'bg-blue-500/25 text-blue-300 border border-blue-500/50 shadow-sm'
- : 'bg-[#1e1e1e] text-[#888888] hover:text-[#cccccc] hover:bg-[#2a2a2a] border border-[#3a3a3a]'
- }`}
- >
- <CspLayerColorIcon className="w-3 h-3" color={activeLayer.layerColor || '#1c73c2'} />
- <span>Layer color</span>
- </button>
- </div>
+ {/* Spacious Scrollable Layer Stack */}
+ <div
+ ref={layerListContainerRef}
+ className="flex-1 overflow-y-auto px-1.5 py-0.5 space-y-0.5 min-h-0"
+ >
+ {layers.map((layer) => {
+ if (layer.parentId) {
+ const parentFolder = layers.find((l) => l.id === layer.parentId);
+ if (parentFolder?.collapsed) return null;
+ }
- {/* Quick Settings Expand/Collapse Icons */}
- <div className="flex items-center space-x-1">
- {activeLayer.toneEnabled && (
- <button
- type="button"
- onClick={() => setIsToneSettingsOpen((prev) => !prev)}
- title={isToneSettingsOpen ? 'Hide tone settings' : 'Show tone settings'}
- className="flex items-center space-x-1 px-1.5 py-0.5 rounded bg-[#1e1e1e] hover:bg-[#2a2a2a] border border-[#3a3a3a] text-amber-400/90 font-mono text-[10px] transition-colors cursor-pointer"
+ const isActive = layer.id === activeLayerId;
+ const isSelected = selectedLayerIds ? selectedLayerIds.includes(layer.id) : isActive;
+ const isFolder = layer.type === 'folder';
+ const isInsideFolder = Boolean(layer.parentId);
+ const isTarget = dropIndicator?.id === layer.id;
+ const isDropInside = isTarget && dropIndicator.position === 'inside';
+ const isDropAbove = isTarget && dropIndicator.position === 'above';
+ const isDropBelow = isTarget && dropIndicator.position === 'below';
+ const isBeingDragged =
+ draggedLayerId === layer.id ||
+ (draggedLayerId !== null &&
+ Boolean(selectedLayerIds?.includes(draggedLayerId)) &&
+ Boolean(selectedLayerIds?.includes(layer.id)));
+
+ const hasStyles = Boolean(
+ (layer.styles?.stroke?.enabled && layer.styles.stroke.size > 0) ||
+ (layer.styles?.dropShadow?.enabled && layer.styles.dropShadow.opacity > 0) ||
+ (layer.styles?.outerGlow?.enabled && layer.styles.outerGlow.opacity > 0)
+ );
+
+ return (
+ <div
+ key={layer.id}
+ data-layer-id={layer.id}
+ onPointerDown={(e) => handleLayerPointerDown(e, layer.id)}
+ onClick={(e) => {
+ if (justDraggedRef.current) return;
+ if (onToggleLayerSelection) {
+ onToggleLayerSelection(layer.id, e.shiftKey, e.ctrlKey || e.metaKey);
+ } else {
+ onSelectLayer(layer.id);
+ }
+ if (activeEditTarget === 'mask' && !layer.maskCanvas && layer.maskEnabled === undefined) {
+ onSelectEditTarget?.('layer');
+ }
+ }}
+ onDoubleClick={() => {
+ if (layer.type === 'adjustment') {
+ onOpenAdjustmentModal?.(layer.id, layer.adjustmentData?.type);
+ } else {
+ startRename(layer);
+ }
+ }}
+ onContextMenu={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ if (selectedLayerIds && !selectedLayerIds.includes(layer.id)) {
+ onToggleLayerSelection
+ ? onToggleLayerSelection(layer.id, false, false)
+ : onSelectLayer(layer.id);
+ }
+ setContextMenu({ layerId: layer.id, x: e.clientX, y: e.clientY });
+ }}
+ className={`group relative flex items-center gap-1.5 px-1.5 py-1 rounded transition-colors select-none ${
+ isInsideFolder ? 'ml-3' : ''
+ } ${layer.clipped ? 'ml-2.5' : ''} ${
+ isDropInside
+ ? 'bg-[#2c2c2c] ring-1 ring-[var(--accent)]'
+ : isSelected
+ ? isActive
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'bg-[#2c2c2c]/65 text-[#e5e5e5]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/45'
+ } ${isBeingDragged ? 'opacity-40 cursor-grabbing' : 'cursor-grab'}`}
+ >
+ {isActive && (
+ <span
+ className="absolute left-0 top-1 bottom-1 w-[2px] rounded-full"
+ style={{ backgroundColor: 'var(--accent)' }}
+ />
+ )}
+
+ {isDropAbove && (
+ <div
+ className="absolute -top-0.5 left-0 right-0 h-[2px] rounded-full z-30 pointer-events-none"
+ style={{ backgroundColor: 'var(--accent)' }}
+ />
+ )}
+ {isDropBelow && (
+ <div
+ className="absolute -bottom-0.5 left-0 right-0 h-[2px] rounded-full z-30 pointer-events-none"
+ style={{ backgroundColor: 'var(--accent)' }}
+ />
+ )}
+
+ {/* Visibility Toggle */}
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ onToggleVisibility(layer.id);
+ }}
+ title={layer.visible ? 'Hide Layer' : 'Show Layer'}
+ className={`p-0.5 rounded transition-colors shrink-0 cursor-pointer ${
+ layer.visible
+ ? 'text-[#8a8a8a] hover:text-[#e5e5e5]'
+ : 'text-[#8a8a8a]/30 hover:text-[#8a8a8a]'
+ }`}
+ >
+ {layer.visible ? <Eye className="w-3 h-3" /> : <EyeOff className="w-3 h-3" />}
+ </button>
+
+ {/* Folder Controls or Thumbnail */}
+ {isFolder ? (
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ onToggleCollapse(layer.id);
+ }}
+ className="flex items-center gap-0.5 text-[#8a8a8a] hover:text-[#e5e5e5] shrink-0 cursor-pointer"
+ >
+ {layer.collapsed ? (
+ <ChevronRight className="w-3 h-3" />
+ ) : (
+ <ChevronDown className="w-3 h-3" />
+ )}
+ {layer.collapsed ? (
+ <Folder className="w-3.5 h-3.5" />
+ ) : (
+ <FolderOpen className="w-3.5 h-3.5" />
+ )}
+ </button>
+ ) : (
+ <div className="flex items-center gap-1 shrink-0">
+ {layer.type === 'adjustment' ? (
+ <div
+ onClick={(e) => {
+ e.stopPropagation();
+ onSelectLayer(layer.id);
+ onSelectEditTarget?.('layer');
+ }}
+ className="w-6 h-5 rounded-xs bg-[#161616] flex items-center justify-center shrink-0"
+ >
+ <SlidersHorizontal className="w-3 h-3 text-[var(--accent)]" />
+ </div>
+ ) : (
+ <div
+ onClick={(e) => {
+ e.stopPropagation();
+ onSelectLayer(layer.id);
+ onSelectEditTarget?.('layer');
+ }}
+ className={`w-6 h-5 rounded-xs overflow-hidden shrink-0 relative ${
+ isActive && activeEditTarget !== 'mask'
+ ? 'shadow-[0_0_0_1px_var(--accent)]'
+ : ''
+ }`}
+ style={{
+ backgroundColor: '#161616',
+ backgroundImage:
+ layer.id === 'layer-bg'
+ ? 'none'
+ : 'conic-gradient(#262626 90deg, #1a1a1a 90deg 180deg, #262626 180deg 270deg, #1a1a1a 270deg)',
+ backgroundSize: '6px 6px',
+ }}
>
- <span>
- {activeLayer.toneFrequency ?? 60}L
- {(activeLayer.toneDensityType ?? 'specified') === 'specified'
- ? ` • ${activeLayer.toneDensity ?? 40}%`
- : ''}
- </span>
- {isToneSettingsOpen ? (
- <ChevronUp className="w-3 h-3 text-[#aaaaaa]" />
+ {layer.thumbnailUrl ? (
+ <img
+ src={layer.thumbnailUrl}
+ alt=""
+ className="w-full h-full object-cover"
+ />
) : (
- <ChevronDown className="w-3 h-3 text-[#aaaaaa]" />
+ <div
+ className="w-full h-full"
+ style={{
+ backgroundColor: layer.id === 'layer-bg' ? '#ffffff' : 'transparent',
+ }}
+ />
)}
- </button>
+ </div>
)}
- {activeLayer.layerColorEnabled && (
- <button
- type="button"
- onClick={() => setIsLayerColorSettingsOpen((prev) => !prev)}
- title={isLayerColorSettingsOpen ? 'Hide tint settings' : 'Show tint settings'}
- className="flex items-center space-x-1 px-1.5 py-0.5 rounded bg-[#1e1e1e] hover:bg-[#2a2a2a] border border-[#3a3a3a] text-blue-400/90 font-mono text-[10px] transition-colors cursor-pointer"
+ {(layer.maskCanvas ||
+ layer.maskEnabled !== undefined ||
+ layer.maskThumbnailUrl) && (
+ <div
+ onClick={(e) => {
+ e.stopPropagation();
+ onSelectLayer(layer.id);
+ onSelectEditTarget?.('mask');
+ }}
+ className={`w-5 h-5 rounded-xs overflow-hidden shrink-0 relative bg-black ${
+ isActive && activeEditTarget === 'mask'
+ ? 'shadow-[0_0_0_1.5px_var(--accent)]'
+ : ''
+ }`}
+ title="Layer Mask"
>
- <span className="w-2 h-2 rounded-full inline-block" style={{ backgroundColor: activeLayer.layerColor || '#1c73c2' }} />
- {isLayerColorSettingsOpen ? (
- <ChevronUp className="w-3 h-3 text-[#aaaaaa]" />
+ {layer.maskThumbnailUrl ? (
+ <img
+ src={layer.maskThumbnailUrl}
+ alt=""
+ className="w-full h-full object-cover"
+ />
) : (
- <ChevronDown className="w-3 h-3 text-[#aaaaaa]" />
+ <div className="w-full h-full bg-white" />
)}
- </button>
+ {layer.maskEnabled === false && (
+ <div className="absolute inset-0 flex items-center justify-center">
+ <div className="w-[140%] h-[1.5px] bg-red-500 rotate-45" />
+ </div>
+ )}
+ </div>
)}
</div>
+ )}
+
+ {/* Layer Name */}
+ <div className="flex-1 min-w-0 flex items-center gap-1">
+ {editingLayerId === layer.id ? (
+ <input
+ type="text"
+ value={editingName}
+ autoFocus
+ onChange={(e) => setEditingName(e.target.value)}
+ onBlur={finishRename}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') finishRename();
+ if (e.key === 'Escape') setEditingLayerId(null);
+ }}
+ onClick={(e) => e.stopPropagation()}
+ className="bg-[#161616] rounded px-1 py-0.5 text-[11px] text-[#e5e5e5] w-full"
+ />
+ ) : (
+ <span
+ onDoubleClick={(e) => {
+ e.stopPropagation();
+ startRename(layer);
+ }}
+ title={layer.name}
+ className={`text-[11px] truncate ${
+ isActive ? 'text-[#e5e5e5] font-medium' : ''
+ }`}
+ >
+ {layer.name}
+ </span>
+ )}
+ </div>
+
+ {/* Compact Metadata Badges */}
+ <div className="flex items-center gap-1 shrink-0 text-[9px] font-mono text-[#8a8a8a]">
+ {layer.clipped && <ClipToLayerIcon className="w-2.5 h-2.5 text-[var(--accent)]" />}
+ {layer.expressionColor && layer.expressionColor !== 'color' && (
+ <span>{layer.expressionColor === 'monochrome' ? '1b' : 'Gr'}</span>
+ )}
+ {layer.toneEnabled && <span>{layer.toneFrequency ?? 60}L</span>}
+ {hasStyles && <span>fx</span>}
+ {layer.opacity < 0.99 && <span>{Math.round(layer.opacity * 100)}%</span>}
+ {layer.locked && <Lock className="w-2.5 h-2.5" />}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+
+ {/* Tucked Collapsible Accordions for Advanced Layer Settings */}
+ {activeLayer && activeLayer.type !== 'folder' && (
+ <div className="shrink-0 bg-[#161616] pt-px space-y-px max-h-[45%] overflow-y-auto">
+ {/* Accordion 1: Monochrome Expression Color & Color Threshold */}
+ <div className="bg-[#202020]">
+ <button
+ type="button"
+ onClick={() => setIsExpressionAccordionOpen((p) => !p)}
+ className="w-full px-2.5 py-1.5 flex items-center justify-between text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 transition-colors cursor-pointer"
+ >
+ <span>Expression Color</span>
+ <div className="flex items-center gap-1">
+ <span className="text-[10px] font-mono capitalize text-[#e5e5e5]">
+ {activeLayer.expressionColor === 'monochrome'
+ ? 'Mono'
+ : activeLayer.expressionColor || 'Color'}
+ </span>
+ {isExpressionAccordionOpen ? (
+ <ChevronDown className="w-3 h-3" />
+ ) : (
+ <ChevronRight className="w-3 h-3" />
+ )}
</div>
+ </button>
+
+ {isExpressionAccordionOpen && (
+ <div className="px-2.5 pb-2.5 pt-1 space-y-2">
+ <div className="grid grid-cols-3 gap-0.5 bg-[#161616] p-0.5 rounded">
+ {(
+ [
+ { id: 'color', label: 'Color' },
+ { id: 'gray', label: 'Gray' },
+ { id: 'monochrome', label: 'Mono' },
+ ] as const
+ ).map((m) => {
+ const selected = (activeLayer.expressionColor || 'color') === m.id;
+ return (
+ <button
+ key={m.id}
+ type="button"
+ onClick={() => onSetLayerExpressionColor?.(activeLayer.id, m.id)}
+ className={`py-0.5 rounded text-[10px] cursor-pointer transition-colors ${
+ selected
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ {m.label}
+ </button>
+ );
+ })}
+ </div>
- {/* Tone Settings Controls */}
- {activeLayer.toneEnabled && isToneSettingsOpen && (
- <div className="p-1.5 bg-[#1b1b1b] rounded border border-[#333333] flex flex-col space-y-1.5 mt-0.5">
- {/* Density Selector & Slider (Clip Studio Paint style) */}
- <div>
- <div className="flex items-center justify-between text-[10px] mb-1">
- <span className="text-[#999999] font-medium">Density:</span>
- <select
- value={activeLayer.toneDensityType ?? 'specified'}
+ {(activeLayer.expressionColor || 'color') === 'monochrome' && (
+ <div className="space-y-2">
+ <div className="space-y-1">
+ <div className="flex items-center justify-between text-[11px]">
+ <span className="text-[#8a8a8a]">Color Threshold</span>
+ <span className="font-mono text-[10px] text-[#e5e5e5]">
+ {activeLayer.monoThreshold ?? 128}
+ </span>
+ </div>
+ <input
+ type="range"
+ min="1"
+ max="255"
+ value={activeLayer.monoThreshold ?? 128}
onChange={(e) =>
- onSetToneDensityType?.(activeLayer.id, e.target.value as 'specified' | 'image')
+ onSetLayerMonoThreshold?.(activeLayer.id, parseInt(e.target.value, 10))
}
- className="bg-[#252526] border border-[#3a3a3a] text-[#cccccc] text-[10px] rounded px-1.5 py-0.5 outline-none cursor-pointer hover:border-[#555555]"
- >
- <option value="specified">Use specified density</option>
- <option value="image">Use image brightness</option>
- </select>
+ className="w-full"
+ />
</div>
- {(activeLayer.toneDensityType ?? 'specified') === 'specified' && (
- <div className="space-y-1">
- <div className="flex items-center space-x-2">
- <input
- type="range"
- min="1"
- max="100"
- step="1"
- value={activeLayer.toneDensity ?? 40}
- onChange={(e) =>
- onSetToneDensity?.(activeLayer.id, parseInt(e.target.value, 10))
- }
- className="flex-1 cursor-pointer h-1.5 accent-amber-400"
- />
- <div className="flex items-center">
- <input
- type="number"
- min="1"
- max="100"
- value={activeLayer.toneDensity ?? 40}
- onChange={(e) => {
- const val = parseInt(e.target.value, 10);
- if (!isNaN(val)) {
- onSetToneDensity?.(activeLayer.id, Math.max(1, Math.min(100, val)));
- }
- }}
- className="w-10 bg-[#252526] border border-[#3a3a3a] text-amber-300 font-mono text-[10px] rounded px-1 py-0.5 text-right outline-none hover:border-[#555555] focus:border-amber-400"
- />
- <span className="text-[10px] text-[#888888] ml-0.5 font-mono">%</span>
- </div>
- </div>
- <div className="flex items-center justify-between text-[8px] text-[#666666] font-mono">
- {[5, 10, 20, 30, 40, 50, 60, 70, 80].map((preset) => (
- <button
- key={preset}
- type="button"
- onClick={() => onSetToneDensity?.(activeLayer.id, preset)}
- className={`hover:text-amber-300 transition-colors ${
- (activeLayer.toneDensity ?? 40) === preset
- ? 'text-amber-400 font-bold'
- : ''
- }`}
- >
- {preset}
- </button>
- ))}
- </div>
- </div>
- )}
- </div>
-
- {/* Frequency (Lines / LPI) */}
- <div>
- <div className="flex items-center justify-between text-[10px] mb-0.5">
- <span className="text-[#999999] font-medium">Frequency (LPI):</span>
- <span className="font-mono text-amber-300 font-bold">{activeLayer.toneFrequency ?? 60}</span>
- </div>
- <input
- type="range"
- min="20"
- max="85"
- step="1"
- value={activeLayer.toneFrequency ?? 60}
- onChange={(e) => onSetToneFrequency?.(activeLayer.id, parseInt(e.target.value, 10))}
- className="w-full cursor-pointer h-1.5 accent-amber-400"
- />
- <div className="flex items-center justify-between text-[8px] text-[#666666] mt-0.5 font-mono">
- {[28, 42.5, 50, 60, 70, 85].map((preset) => (
+ <div className="flex items-center justify-between text-[10px]">
+ <span className="text-[#8a8a8a]">Express</span>
+ <div className="flex items-center gap-1">
<button
- key={preset}
type="button"
- onClick={() => onSetToneFrequency?.(activeLayer.id, preset)}
- className={`hover:text-amber-300 transition-colors ${
- (activeLayer.toneFrequency ?? 60) === preset ? 'text-amber-400 font-bold' : ''
+ onClick={() =>
+ onSetLayerMonoExpressMode?.(
+ activeLayer.id,
+ !(activeLayer.monoExpressBlack ?? true),
+ activeLayer.monoExpressWhite ?? true
+ )
+ }
+ className={`px-1.5 py-0.5 rounded cursor-pointer ${
+ (activeLayer.monoExpressBlack ?? true)
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'bg-[#161616] text-[#8a8a8a]'
}`}
>
- {preset}
+ Black
</button>
- ))}
- </div>
- </div>
-
- {/* Angle Slider 0° to 90° */}
- <div>
- <div className="flex items-center justify-between text-[10px] mb-0.5">
- <span className="text-[#999999] font-medium">Angle:</span>
- <span className="font-mono text-amber-300 font-bold">{activeLayer.toneAngle ?? 45}°</span>
- </div>
- <input
- type="range"
- min="0"
- max="90"
- step="1"
- value={activeLayer.toneAngle ?? 45}
- onChange={(e) => onSetToneAngle?.(activeLayer.id, parseInt(e.target.value, 10))}
- className="w-full cursor-pointer h-1.5 accent-amber-400"
- />
- <div className="flex items-center justify-between text-[8px] text-[#666666] mt-0.5 font-mono">
- {[0, 30, 45, 60, 90].map((preset) => (
<button
- key={preset}
type="button"
- onClick={() => onSetToneAngle?.(activeLayer.id, preset)}
- className={`hover:text-amber-300 transition-colors ${
- (activeLayer.toneAngle ?? 45) === preset ? 'text-amber-400 font-bold' : ''
+ onClick={() =>
+ onSetLayerMonoExpressMode?.(
+ activeLayer.id,
+ activeLayer.monoExpressBlack ?? true,
+ !(activeLayer.monoExpressWhite ?? true)
+ )
+ }
+ className={`px-1.5 py-0.5 rounded cursor-pointer ${
+ (activeLayer.monoExpressWhite ?? true)
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'bg-[#161616] text-[#8a8a8a]'
}`}
>
- {preset}°
- </button>
- ))}
- </div>
- </div>
-
- {/* Dot Shape */}
- <div className="flex items-center justify-between text-[10px]">
- <span className="text-[#999999] font-medium">Dot Shape:</span>
- <select
- value={activeLayer.toneDotShape ?? 'circle'}
- onChange={(e) => onSetToneDotShape?.(activeLayer.id, e.target.value as 'circle' | 'euclidean')}
- className="bg-[#252526] border border-[#3a3a3a] text-[#cccccc] text-[10px] rounded px-1.5 py-0.5 outline-none cursor-pointer hover:border-[#555555]"
- >
- <option value="circle">Circle (Standard CSP)</option>
- <option value="euclidean">Euclidean (Classic Halftone)</option>
- </select>
- </div>
- </div>
- )}
-
- {/* Layer Color (Tint) Settings Controls */}
- {activeLayer.layerColorEnabled && isLayerColorSettingsOpen && (
- <div className="p-1.5 bg-[#1b1b1b] rounded border border-[#333333] flex flex-col space-y-1.5 mt-0.5">
- {/* Layer Color (Primary Tint) */}
- <div className="flex items-center justify-between text-[10px]">
- <span className="text-[#999999]">Layer color:</span>
- <div className="flex items-center space-x-1.5">
- <input
- type="color"
- value={activeLayer.layerColor || '#1c73c2'}
- onChange={(e) => onSetLayerColor?.(activeLayer.id, e.target.value)}
- className="w-5 h-4 cursor-pointer bg-transparent border-none p-0 rounded"
- title="Pick Layer Color"
- />
- <input
- type="text"
- value={activeLayer.layerColor || '#1c73c2'}
- onChange={(e) => onSetLayerColor?.(activeLayer.id, e.target.value)}
- className="w-16 bg-[#252526] border border-[#3a3a3a] text-[#cccccc] text-[9px] font-mono px-1 py-0.5 rounded outline-none"
- />
- </div>
- </div>
-
- {/* Sub Color (Secondary Tint) */}
- <div className="flex items-center justify-between text-[10px]">
- <span className="text-[#999999]">Sub color:</span>
- <div className="flex items-center space-x-1.5">
- <input
- type="color"
- value={activeLayer.layerSubColor || '#ffffff'}
- onChange={(e) => onSetLayerSubColor?.(activeLayer.id, e.target.value)}
- className="w-5 h-4 cursor-pointer bg-transparent border-none p-0 rounded"
- title="Pick Sub Color"
- />
- <input
- type="text"
- value={activeLayer.layerSubColor || '#ffffff'}
- onChange={(e) => onSetLayerSubColor?.(activeLayer.id, e.target.value)}
- className="w-16 bg-[#252526] border border-[#3a3a3a] text-[#cccccc] text-[9px] font-mono px-1 py-0.5 rounded outline-none"
- />
- </div>
- </div>
-
- {/* CSP Classic Presets */}
- <div className="flex items-center justify-between text-[8px] pt-0.5">
- <span className="text-[#777777]">Presets:</span>
- <div className="flex items-center space-x-1 font-mono">
- {[
- { label: 'Cyan', color: '#1c73c2' },
- { label: 'Red', color: '#e04b4b' },
- { label: 'Sepia', color: '#8a5a36' },
- { label: 'Purple', color: '#6355a4' },
- ].map((preset) => (
- <button
- key={preset.label}
- type="button"
- onClick={() => onSetLayerColor?.(activeLayer.id, preset.color)}
- className="px-1 py-0.2 rounded bg-[#252526] hover:bg-[#333333] border border-[#444444] text-[8px] text-[#cccccc] cursor-pointer"
- >
- {preset.label}
+ White
</button>
- ))}
+ </div>
</div>
</div>
+ )}
+ {(activeLayer.expressionColor || 'color') !== 'color' && (
<button
type="button"
- onClick={() => onApplyLayerColor?.(activeLayer.id)}
- className="w-full text-center py-1 px-2 rounded bg-[#252526] hover:bg-[#333333] border border-[#444444] text-blue-300 hover:text-blue-200 text-[10px] font-medium transition-colors cursor-pointer mt-0.5"
- title="Permanently bake layer color tint into pixels"
+ onClick={() => onApplyExpressionColor?.(activeLayer.id)}
+ className="w-full py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer"
>
- Apply tint to layer permanently
+ Apply Expression Color
</button>
- </div>
- )}
+ )}
+ </div>
+ )}
+ </div>
- {/* Clip Studio Paint Style ―Expression color― Section */}
- <div className="pt-1.5 border-t border-[#333333]/70 flex flex-col space-y-1">
- <div className="text-[10px] text-[#888888] font-medium tracking-wide">
- ―Expression color―
- </div>
+ {/* Accordion 2: Screentone & Layer Tint */}
+ <div className="bg-[#202020]">
+ <button
+ type="button"
+ onClick={() => setIsEffectsAccordionOpen((p) => !p)}
+ className="w-full px-2.5 py-1.5 flex items-center justify-between text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 transition-colors cursor-pointer"
+ >
+ <span>Tone & Tint</span>
+ {isEffectsAccordionOpen ? (
+ <ChevronDown className="w-3 h-3" />
+ ) : (
+ <ChevronRight className="w-3 h-3" />
+ )}
+ </button>
- {/* Custom Dropdown matching CSP screenshot */}
- <div className="relative" ref={expressionMenuRef}>
- <button
- type="button"
- onClick={() => setIsExpressionMenuOpen((prev) => !prev)}
- className="w-full bg-[#2a2a2a] hover:bg-[#323232] border border-[#444444] rounded px-2 py-1 flex items-center justify-between text-xs text-[#cccccc] cursor-pointer transition-colors shadow-xs"
- title="Expression color: Color, Gray, or Monochrome"
- >
- <div className="flex items-center space-x-2">
- {(activeLayer.expressionColor || 'color') === 'monochrome' ? (
- <CspMonoIcon className="w-3.5 h-3.5" />
- ) : (activeLayer.expressionColor || 'color') === 'gray' ? (
- <CspGrayIcon className="w-3.5 h-3.5" />
- ) : (
- <CspColorIcon className="w-3.5 h-3.5" />
- )}
- <span className="capitalize font-medium">
- {(activeLayer.expressionColor || 'color') === 'monochrome'
- ? 'Monochrome'
- : (activeLayer.expressionColor || 'color') === 'gray'
- ? 'Gray'
- : 'Color'}
- </span>
- </div>
- <ChevronDown className="w-3.5 h-3.5 text-[#888888]" />
- </button>
+ {isEffectsAccordionOpen && (
+ <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">
+ <span>Screentone</span>
+ <input
+ type="checkbox"
+ checked={Boolean(activeLayer.toneEnabled)}
+ onChange={() => onToggleTone?.(activeLayer.id)}
+ />
+ </label>
+
+ {activeLayer.toneEnabled && (
+ <div className="space-y-2">
+ <select
+ value={activeLayer.toneDensityType ?? 'specified'}
+ onChange={(e) =>
+ onSetToneDensityType?.(
+ activeLayer.id,
+ e.target.value as 'specified' | 'image'
+ )
+ }
+ className="w-full h-6 px-1.5 text-[10px]"
+ >
+ <option value="specified">Specified Density</option>
+ <option value="image">Image Brightness</option>
+ </select>
- {/* Dropdown popup with selection background matching CSP screenshot */}
- {isExpressionMenuOpen && (
- <div className="absolute top-full left-0 right-0 mt-1 bg-[#252526] border border-[#444444] rounded shadow-2xl z-50 overflow-hidden text-xs py-0.5">
- {[
- { mode: 'color' as ExpressionColor, label: 'Color', icon: <CspColorIcon className="w-3.5 h-3.5" /> },
- { mode: 'gray' as ExpressionColor, label: 'Gray', icon: <CspGrayIcon className="w-3.5 h-3.5" /> },
- { mode: 'monochrome' as ExpressionColor, label: 'Monochrome', icon: <CspMonoIcon className="w-3.5 h-3.5" /> },
- ].map((item) => {
- const isSelected = (activeLayer.expressionColor || 'color') === item.mode;
- return (
- <button
- key={item.mode}
- type="button"
- onClick={() => {
- onSetLayerExpressionColor?.(activeLayer.id, item.mode);
- setIsExpressionMenuOpen(false);
- }}
- className={`w-full flex items-center space-x-2 px-2.5 py-1.5 cursor-pointer text-left transition-colors ${
- isSelected
- ? 'bg-[#3b4b61] text-white font-medium'
- : 'text-[#cccccc] hover:bg-[#2f3542] hover:text-white'
- }`}
- >
- {item.icon}
- <span>{item.label}</span>
- </button>
- );
- })}
- </div>
- )}
- </div>
+ {(activeLayer.toneDensityType ?? 'specified') === 'specified' && (
+ <div className="space-y-1">
+ <div className="flex justify-between text-[10px]">
+ <span className="text-[#8a8a8a]">Density</span>
+ <span className="font-mono text-[#e5e5e5]">
+ {activeLayer.toneDensity ?? 40}%
+ </span>
+ </div>
+ <input
+ type="range"
+ min="1"
+ max="100"
+ value={activeLayer.toneDensity ?? 40}
+ onChange={(e) =>
+ onSetToneDensity?.(activeLayer.id, parseInt(e.target.value, 10))
+ }
+ className="w-full"
+ />
+ </div>
+ )}
- {/* Monochrome Controls when activeLayer.expressionColor === 'monochrome' */}
- {(activeLayer.expressionColor || 'color') === 'monochrome' && (
- <div className="p-1.5 bg-[#1b1b1b] rounded border border-[#333333] flex flex-col space-y-1.5 mt-0.5">
- <div>
- <div className="flex items-center justify-between text-[10px] mb-0.5">
- <span className="text-[#999999]">Color threshold:</span>
- <span className="font-mono text-cyan-300 font-bold">{activeLayer.monoThreshold ?? 128}</span>
+ <div className="space-y-1">
+ <div className="flex justify-between text-[10px]">
+ <span className="text-[#8a8a8a]">Frequency</span>
+ <span className="font-mono text-[#e5e5e5]">
+ {activeLayer.toneFrequency ?? 60} LPI
+ </span>
</div>
<input
type="range"
- min="1"
- max="255"
- step="1"
- value={activeLayer.monoThreshold ?? 128}
- onChange={(e) => onSetLayerMonoThreshold?.(activeLayer.id, parseInt(e.target.value, 10))}
- className="w-full cursor-pointer h-1.5 accent-cyan-400"
+ min="20"
+ max="85"
+ value={activeLayer.toneFrequency ?? 60}
+ onChange={(e) =>
+ onSetToneFrequency?.(activeLayer.id, parseInt(e.target.value, 10))
+ }
+ className="w-full"
/>
</div>
- {/* Color to express: Black and White toggles */}
- <div className="flex items-center justify-between text-[10px]">
- <span className="text-[#999999]">Color to express:</span>
- <div className="flex items-center space-x-1.5">
- <button
- type="button"
- onClick={() => {
- const nextBlack = !(activeLayer.monoExpressBlack ?? true);
- onSetLayerMonoExpressMode?.(activeLayer.id, nextBlack, activeLayer.monoExpressWhite ?? true);
- }}
- title="Express Black pixels (lines/dark tones)"
- className={`flex items-center space-x-1 px-1.5 py-0.5 rounded border text-[10px] cursor-pointer transition-colors ${
- (activeLayer.monoExpressBlack ?? true)
- ? 'bg-[#111111] text-white border-cyan-500/60 font-bold shadow-xs'
- : 'bg-[#222222] text-[#666666] border-[#3a3a3a]'
- }`}
- >
- <span className="w-2 h-2 rounded-xs bg-black border border-[#555555] inline-block" />
- <span>Black</span>
- </button>
- <button
- type="button"
- onClick={() => {
- const nextWhite = !(activeLayer.monoExpressWhite ?? true);
- onSetLayerMonoExpressMode?.(activeLayer.id, activeLayer.monoExpressBlack ?? true, nextWhite);
- }}
- title="Express White pixels (if disabled, light pixels become transparent paper!)"
- className={`flex items-center space-x-1 px-1.5 py-0.5 rounded border text-[10px] cursor-pointer transition-colors ${
- (activeLayer.monoExpressWhite ?? true)
- ? 'bg-[#333333] text-white border-cyan-500/60 font-bold shadow-xs'
- : 'bg-[#222222] text-[#666666] border-[#3a3a3a]'
- }`}
- >
- <span className="w-2 h-2 rounded-xs bg-white border border-[#777777] inline-block" />
- <span>White</span>
- </button>
+ <div className="space-y-1">
+ <div className="flex justify-between text-[10px]">
+ <span className="text-[#8a8a8a]">Angle</span>
+ <span className="font-mono text-[#e5e5e5]">
+ {activeLayer.toneAngle ?? 45}°
+ </span>
</div>
+ <input
+ type="range"
+ min="0"
+ max="90"
+ value={activeLayer.toneAngle ?? 45}
+ onChange={(e) =>
+ onSetToneAngle?.(activeLayer.id, parseInt(e.target.value, 10))
+ }
+ className="w-full"
+ />
</div>
- <button
- type="button"
- onClick={() => onApplyExpressionColor?.(activeLayer.id)}
- className="w-full text-center py-1 px-2 rounded bg-[#252526] hover:bg-[#333333] border border-[#444444] text-cyan-300 hover:text-cyan-200 text-[10px] font-medium transition-colors cursor-pointer mt-1"
- title="Permanently bake monochrome threshold into this layer"
+ <select
+ value={activeLayer.toneDotShape ?? 'circle'}
+ onChange={(e) =>
+ onSetToneDotShape?.(
+ activeLayer.id,
+ e.target.value as 'circle' | 'euclidean'
+ )
+ }
+ className="w-full h-6 px-1.5 text-[10px]"
>
- Apply expression color of preview
- </button>
+ <option value="circle">Circle Dot</option>
+ <option value="euclidean">Euclidean Dot</option>
+ </select>
</div>
)}
- {/* Grayscale Controls when activeLayer.expressionColor === 'gray' */}
- {(activeLayer.expressionColor || 'color') === 'gray' && (
- <div className="p-1.5 bg-[#1b1b1b] rounded border border-[#333333] flex flex-col space-y-1 mt-0.5">
- <div className="text-[10px] text-[#888888]">
- Converted to 8-bit grayscale (256 shades).
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Layer Tint</span>
+ <input
+ type="checkbox"
+ checked={Boolean(activeLayer.layerColorEnabled)}
+ onChange={() => onToggleLayerColor?.(activeLayer.id)}
+ />
+ </label>
+
+ {activeLayer.layerColorEnabled && (
+ <div className="space-y-1.5">
+ <div className="flex items-center justify-between text-[10px]">
+ <span className="text-[#8a8a8a]">Main</span>
+ <input
+ type="color"
+ value={activeLayer.layerColor || '#1c73c2'}
+ onChange={(e) => onSetLayerColor?.(activeLayer.id, e.target.value)}
+ className="w-5 h-4 bg-transparent cursor-pointer"
+ />
+ </div>
+ <div className="flex items-center justify-between text-[10px]">
+ <span className="text-[#8a8a8a]">Sub</span>
+ <input
+ type="color"
+ value={activeLayer.layerSubColor || '#ffffff'}
+ onChange={(e) => onSetLayerSubColor?.(activeLayer.id, e.target.value)}
+ className="w-5 h-4 bg-transparent cursor-pointer"
+ />
</div>
<button
type="button"
- onClick={() => onApplyExpressionColor?.(activeLayer.id)}
- className="w-full text-center py-1 px-2 rounded bg-[#252526] hover:bg-[#333333] border border-[#444444] text-cyan-300 hover:text-cyan-200 text-[10px] font-medium transition-colors cursor-pointer"
- title="Permanently bake grayscale into this layer"
+ onClick={() => onApplyLayerColor?.(activeLayer.id)}
+ className="w-full py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer"
>
- Apply expression color of preview
+ Apply Tint
</button>
</div>
)}
</div>
- </div>
- )}
+ )}
+ </div>
</div>
)}
+ </>
+ )}
+ </div>
+ ) : (
+ /* History Tab */
+ <div className="flex-1 overflow-y-auto px-1.5 py-1 space-y-0.5 min-h-0">
+ {!hasOpenDocument || historyList.length === 0 ? (
+ <div className="p-4 text-center text-[11px] text-[#8a8a8a]">No history</div>
+ ) : (
+ historyList.map((item, idx) => {
+ const isActive = idx === historyIndex;
+ const isFuture = idx > historyIndex;
+ return (
+ <button
+ key={item.id}
+ type="button"
+ onClick={() => onJumpToHistory(idx)}
+ className={`w-full flex items-center justify-between gap-2 px-2 py-1 rounded text-left text-[11px] transition-colors cursor-pointer ${
+ isActive
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : isFuture
+ ? 'opacity-40 hover:opacity-80 text-[#8a8a8a]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/50'
+ }`}
+ >
+ <span className="truncate">{item.label}</span>
+ <span className="text-[9px] font-mono text-[#8a8a8a] shrink-0">
+ {item.timeFormatted}
+ </span>
+ </button>
+ );
+ })
+ )}
+ </div>
+ )}
+ </section>
- {/* Layer Action Bar: Add Layer, Add Folder, Duplicate, Delete, Move Up/Down, Lock */}
- <div className="px-2.5 py-1 bg-[#1e1e1e] border-b border-[#2d2d2d] flex items-center justify-between text-[#888888] shrink-0">
- <div className="flex items-center space-x-1">
- {/* Add Raster Layer */}
- <button
- onClick={() => onAddLayer('raster')}
- title="New Layer"
- className="flex items-center space-x-1 px-1.5 py-0.5 hover:text-white hover:bg-[#333333] rounded-[2px] transition-colors"
- >
- <Plus className="w-3.5 h-3.5 text-blue-400" />
- <span className="text-[10px]">Layer</span>
- </button>
+ {/* Right-Click Context Menu */}
+ {contextMenu &&
+ (() => {
+ const targetLayer = layers.find((l) => l.id === contextMenu.layerId);
+ if (!targetLayer) return null;
+ const hasMask = Boolean(
+ targetLayer.maskCanvas ||
+ targetLayer.maskEnabled !== undefined ||
+ targetLayer.maskThumbnailUrl
+ );
+ const isAdj = targetLayer.type === 'adjustment';
+
+ return (
+ <div
+ ref={contextMenuRef}
+ className="fixed z-50 min-w-44 bg-[#202020] rounded-md shadow-[0_12px_32px_rgba(0,0,0,0.7)] p-1 text-[11px] text-[#e5e5e5] select-none"
+ style={{
+ left: Math.max(10, Math.min(contextMenu.x, window.innerWidth - 190)),
+ top: Math.max(10, Math.min(contextMenu.y, window.innerHeight - 320)),
+ }}
+ onClick={(e) => e.stopPropagation()}
+ onContextMenu={(e) => e.preventDefault()}
+ >
+ <div className="px-2.5 py-1 text-[10px] text-[#8a8a8a] truncate">
+ {targetLayer.name}
+ </div>
+ <div className="my-0.5 h-px bg-[#2c2c2c]" />
+
+ {targetLayer.type !== 'folder' && (
+ <>
+ {!hasMask ? (
+ <button
+ type="button"
+ onClick={() => {
+ onAddLayerMask?.(targetLayer.id);
+ setContextMenu(null);
+ }}
+ className="w-full text-left px-2.5 py-1 rounded hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ Add Layer Mask
+ </button>
+ ) : (
+ <>
+ <button
+ type="button"
+ onClick={() => {
+ onToggleLayerMask?.(targetLayer.id);
+ setContextMenu(null);
+ }}
+ className="w-full text-left px-2.5 py-1 rounded hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ {targetLayer.maskEnabled === false ? 'Enable Mask' : 'Disable Mask'}
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ onToggleMaskLinked?.(targetLayer.id);
+ setContextMenu(null);
+ }}
+ className="w-full text-left px-2.5 py-1 rounded hover:bg-[#2c2c2c] flex items-center justify-between cursor-pointer"
+ >
+ <span>{targetLayer.maskLinked === false ? 'Link Mask' : 'Unlink Mask'}</span>
+ <Link2 className="w-3 h-3 text-[#8a8a8a]" />
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ onRemoveLayerMask?.(targetLayer.id);
+ setContextMenu(null);
+ }}
+ className="w-full text-left px-2.5 py-1 rounded hover:bg-[#2c2c2c] text-red-400 cursor-pointer"
+ >
+ Delete Mask
+ </button>
+ </>
+ )}
+ <div className="my-0.5 h-px bg-[#2c2c2c]" />
+ </>
+ )}
- {/* Add Folder / Group Selected Layers */}
+ {isAdj && (
<button
+ type="button"
onClick={() => {
- if (onGroupSelectedLayers && selectedLayerIds && selectedLayerIds.length > 1) {
- onGroupSelectedLayers();
- } else {
- onAddLayer('folder');
- }
+ onOpenAdjustmentModal?.(targetLayer.id, targetLayer.adjustmentData?.type);
+ setContextMenu(null);
}}
- title={selectedLayerIds && selectedLayerIds.length > 1 ? `Group ${selectedLayerIds.length} Selected Layers (Ctrl+G)` : 'New Folder'}
- className="flex items-center space-x-1 px-1.5 py-0.5 hover:text-white hover:bg-[#333333] rounded-[2px] transition-colors"
+ className="w-full text-left px-2.5 py-1 rounded hover:bg-[#2c2c2c] cursor-pointer"
>
- <FolderPlus className="w-3.5 h-3.5 text-amber-400" />
- <span className="text-[10px]">{selectedLayerIds && selectedLayerIds.length > 1 ? 'Group' : 'Folder'}</span>
+ Edit Adjustment...
</button>
+ )}
- {/* Local-Only 3D Viewport Ghost Layer */}
- {onOpen3DLayer && (
- <button
- onClick={onOpen3DLayer}
- title="New 3D Reference Layer (Local Ghost Layer)"
- className="flex items-center space-x-1 px-1.5 py-0.5 hover:text-white hover:bg-[#333333] rounded-[2px] transition-colors text-purple-400"
- >
- <Box className="w-3.5 h-3.5" />
- <span className="text-[10px]">3D</span>
- </button>
- )}
-
- {/* Layer Styles (Blending Options) Button */}
- {onOpenLayerStylesModal && (
+ {onOpenAdjustmentModal && (
+ <>
+ {(['curves', 'levels', 'gradient-map', 'color-balance'] as const).map((adjType) => (
+ <button
+ key={adjType}
+ type="button"
+ onClick={() => {
+ onOpenAdjustmentModal(undefined, adjType);
+ setContextMenu(null);
+ }}
+ className="w-full text-left px-2.5 py-1 rounded hover:bg-[#2c2c2c] capitalize cursor-pointer"
+ >
+ New {adjType.replace('-', ' ')}...
+ </button>
+ ))}
+ <div className="my-0.5 h-px bg-[#2c2c2c]" />
+ </>
+ )}
+
+ {targetLayer.type !== 'folder' &&
+ targetLayer.type !== 'adjustment' &&
+ onOpenLayerStylesModal && (
<button
- onClick={() => activeLayerId && onOpenLayerStylesModal(activeLayerId)}
- title="Layer Styles (Stroke, Drop Shadow, Outer Glow)"
- disabled={!activeLayerId || activeLayer?.type === 'folder' || activeLayer?.type === 'adjustment'}
- className="flex items-center space-x-1 px-1.5 py-0.5 hover:text-white hover:bg-[#333333] disabled:opacity-40 rounded-[2px] transition-colors text-amber-400"
+ type="button"
+ onClick={() => {
+ onOpenLayerStylesModal(targetLayer.id);
+ setContextMenu(null);
+ }}
+ className="w-full text-left px-2.5 py-1 rounded hover:bg-[#2c2c2c] flex items-center gap-1.5 cursor-pointer"
>
- <Sparkles className="w-3.5 h-3.5" />
- <span className="text-[10px] font-bold">fx</span>
+ <Sparkles className="w-3 h-3 text-[#8a8a8a]" />
+ <span>Layer Styles...</span>
</button>
)}
- </div>
- <div className="flex items-center space-x-0.5">
- {/* Single-Click Duplicate Active Layer */}
+ {onGroupSelectedLayers && (
<button
- onClick={() => onDuplicateLayer(activeLayerId)}
- title="Duplicate Layer (Single Click)"
- className="p-1 text-[#888888] hover:text-white hover:bg-[#333333] rounded-[2px] transition-colors"
+ type="button"
+ onClick={() => {
+ onGroupSelectedLayers();
+ setContextMenu(null);
+ }}
+ className="w-full text-left px-2.5 py-1 rounded hover:bg-[#2c2c2c] cursor-pointer"
>
- <Copy className="w-3.5 h-3.5 text-emerald-400" />
+ Group (Ctrl+G)
</button>
+ )}
- {/* Toggle Alpha Lock (Lock Transparent Pixels) */}
- {activeLayer && activeLayer.type !== 'folder' && (
- <button
- onClick={() => onToggleAlphaLock?.(activeLayer.id)}
- title={
- activeLayer.alphaLocked
- ? 'Unlock Transparent Pixels (Alpha Lock ON)'
- : 'Lock Transparent Pixels (Alpha Lock OFF)'
- }
- className={`p-1 rounded-[2px] transition-colors ${
- activeLayer.alphaLocked
- ? 'text-amber-400 bg-amber-950/50 ring-1 ring-amber-500/60 shadow-xs'
- : 'text-[#888888] hover:text-white hover:bg-[#333333]'
- }`}
- >
- <AlphaLockIcon className="w-3.5 h-3.5" />
- </button>
- )}
-
- {/* Toggle Clip to Layer Below (Clipping Mask) */}
- {activeLayer && activeLayer.id !== 'layer-bg' && (
- <button
- onClick={() => onToggleClipping?.(activeLayer.id)}
- title={
- activeLayer.clipped
- ? 'Release Clipping Mask (Clip to Layer Below)'
- : 'Clip to Layer Below (Clipping Mask)'
- }
- className={`p-1 rounded-[2px] transition-colors ${
- activeLayer.clipped
- ? 'text-blue-400 bg-blue-950/50 ring-1 ring-blue-500/60 shadow-xs'
- : 'text-[#888888] hover:text-white hover:bg-[#333333]'
- }`}
- >
- <ClipToLayerIcon className="w-3.5 h-3.5" />
- </button>
- )}
-
- {/* Toggle Reference Layer */}
- {activeLayer && (
- <button
- onClick={() => onToggleReferenceLayer?.(activeLayer.id)}
- title={
- activeLayer.isReference
- ? 'Unset as Reference Layer'
- : 'Set as Reference Layer (Sampled by Magic Wand / Fill)'
- }
- className={`p-1 rounded-[2px] transition-colors ${
- activeLayer.isReference
- ? 'text-cyan-400 bg-cyan-950/50 ring-1 ring-cyan-500/60 shadow-xs'
- : 'text-[#888888] hover:text-white hover:bg-[#333333]'
- }`}
- >
- <Compass className="w-3.5 h-3.5" />
- </button>
- )}
+ <button
+ type="button"
+ onClick={() => {
+ onDuplicateLayer(targetLayer.id);
+ setContextMenu(null);
+ }}
+ className="w-full text-left px-2.5 py-1 rounded hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ Duplicate
+ </button>
- {/* Toggle Lock */}
- {activeLayer && (
- <button
- onClick={() => onToggleLock(activeLayer.id)}
- title={activeLayer.locked ? 'Unlock Layer' : 'Lock Layer'}
- className={`p-1 rounded-[2px] transition-colors ${
- activeLayer.locked ? 'text-amber-400' : 'text-[#888888] hover:text-white'
- }`}
- >
- {activeLayer.locked ? (
- <Lock className="w-3.5 h-3.5" />
- ) : (
- <Unlock className="w-3.5 h-3.5" />
- )}
- </button>
- )}
+ <button
+ type="button"
+ onClick={() => {
+ startRename(targetLayer);
+ setContextMenu(null);
+ }}
+ className="w-full text-left px-2.5 py-1 rounded hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ Rename
+ </button>
- {/* Delete Active or Selected Layer(s) */}
+ {targetLayer.id !== 'layer-bg' && (
<button
+ type="button"
onClick={() => {
if (onDeleteSelectedLayers && selectedLayerIds && selectedLayerIds.length > 1) {
onDeleteSelectedLayers();
} else {
- onDeleteLayer(activeLayerId);
+ onDeleteLayer(targetLayer.id);
}
+ setContextMenu(null);
}}
- title={selectedLayerIds && selectedLayerIds.length > 1 ? `Delete ${selectedLayerIds.length} Selected Layers` : 'Delete Layer'}
- className="p-1 text-[#888888] hover:text-rose-400 hover:bg-[#333333] rounded-[2px] transition-colors"
+ className="w-full text-left px-2.5 py-1 rounded hover:bg-[#2c2c2c] text-red-400 cursor-pointer"
>
- <Trash2 className="w-3.5 h-3.5" />
+ Delete
</button>
- </div>
+ )}
</div>
-
- {/* Scrollable Layer Stack List */}
- <div ref={layerListContainerRef} className="flex-1 overflow-y-auto p-1.5 space-y-1 min-h-0">
- {layers.map((layer) => {
- // If parent folder is collapsed, hide child layers
- if (layer.parentId) {
- const parentFolder = layers.find((l) => l.id === layer.parentId);
- if (parentFolder && parentFolder.collapsed) {
- return null;
- }
- }
-
- const isActive = layer.id === activeLayerId;
- const isSelected = selectedLayerIds ? selectedLayerIds.includes(layer.id) : isActive;
- const isFolder = layer.type === 'folder';
- const isInsideFolder = !!layer.parentId;
- const isTarget = dropIndicator?.id === layer.id;
- const isDropInside = isTarget && dropIndicator.position === 'inside';
- const isDropAbove = isTarget && dropIndicator.position === 'above';
- const isDropBelow = isTarget && dropIndicator.position === 'below';
- const isBeingDragged = draggedLayerId === layer.id || (draggedLayerId !== null && !!selectedLayerIds?.includes(draggedLayerId) && !!selectedLayerIds?.includes(layer.id));
-
- return (
- <div
- key={layer.id}
- data-layer-id={layer.id}
- onPointerDown={(e) => handleLayerPointerDown(e, layer.id)}
- onClick={(e) => {
- if (justDraggedRef.current) return;
- if (onToggleLayerSelection) {
- onToggleLayerSelection(layer.id, e.shiftKey, e.ctrlKey || e.metaKey);
- } else {
- onSelectLayer(layer.id);
- }
- if (activeEditTarget === 'mask' && !layer.maskCanvas && layer.maskEnabled === undefined) {
- onSelectEditTarget?.('layer');
- }
- }}
- onDoubleClick={() => {
- if (layer.type === 'adjustment') {
- onOpenAdjustmentModal?.(layer.id, layer.adjustmentData?.type);
- } else if (layer.type !== 'folder') {
- onOpenLayerStylesModal?.(layer.id);
- }
- }}
- onContextMenu={(e) => {
- e.preventDefault();
- e.stopPropagation();
- if (selectedLayerIds && !selectedLayerIds.includes(layer.id)) {
- if (onToggleLayerSelection) {
- onToggleLayerSelection(layer.id, false, false);
- } else {
- onSelectLayer(layer.id);
- }
- }
- setContextMenu({
- layerId: layer.id,
- x: e.clientX,
- y: e.clientY,
- });
- }}
- className={`group relative flex items-center space-x-1.5 px-2 py-1.5 rounded-[2px] transition-colors border select-none ${
- isInsideFolder ? 'ml-4 border-l-2 border-l-[#444444]' : ''
- } ${
- layer.clipped ? 'ml-3 pl-2 border-l-2 border-l-blue-500 bg-blue-950/20 shadow-xs' : ''
- } ${
- isDropInside
- ? 'border-2 border-amber-400 bg-amber-950/40 shadow-md'
- : isSelected
- ? (isActive ? 'bg-[#383838] border-blue-500 text-white shadow-sm ring-1 ring-blue-500/50' : 'bg-[#2b2b2e] border-blue-500/60 text-white shadow-sm')
- : 'bg-[#242425] hover:bg-[#2b2b2c] border-transparent text-[#cccccc]'
- } ${
- isBeingDragged ? 'opacity-40 cursor-grabbing' : 'cursor-grab'
- }`}
- >
- {/* Visual Drop Insertion Line (Above / Below) */}
- {isDropAbove && (
- <div className="absolute -top-1 left-0 right-0 h-[2.5px] bg-blue-500 rounded-full z-30 pointer-events-none shadow-[0_0_8px_rgba(59,130,246,1)]" />
- )}
- {isDropBelow && (
- <div className="absolute -bottom-1 left-0 right-0 h-[2.5px] bg-blue-500 rounded-full z-30 pointer-events-none shadow-[0_0_8px_rgba(59,130,246,1)]" />
- )}
-
- {/* Drag Grip Handle */}
- <div
- className="w-3 h-3.5 flex items-center justify-center shrink-0 text-[#555555] group-hover:text-[#aaaaaa] transition-colors"
- title="Drag to reorder"
- >
- <GripVertical className="w-3 h-3" />
- </div>
- {/* Visibility Eye Toggle */}
- <button
- onClick={(e) => {
- e.stopPropagation();
- onToggleVisibility(layer.id);
- }}
- title={layer.visible ? 'Hide Layer' : 'Show Layer'}
- className={`p-0.5 rounded-[2px] transition-colors ${
- layer.visible
- ? 'text-[#aaaaaa] hover:text-white'
- : 'text-[#555555] hover:text-[#888888]'
- }`}
- >
- {layer.visible ? (
- <Eye className="w-3.5 h-3.5" />
- ) : (
- <EyeOff className="w-3.5 h-3.5" />
- )}
- </button>
-
- {/* Clip to Layer Below Toggle Button (with standard indent arrow icon) */}
- {layer.id !== 'layer-bg' && (
- <button
- onClick={(e) => {
- e.stopPropagation();
- onToggleClipping?.(layer.id);
- }}
- title={layer.clipped ? 'Release Clipping Mask' : 'Clip to Layer Below (Clipping Mask)'}
- className={`p-0.5 rounded-[2px] transition-colors shrink-0 ${
- layer.clipped
- ? 'text-blue-400 bg-blue-950/60 ring-1 ring-blue-500/50 shadow-xs'
- : 'text-[#555555] hover:text-white hover:bg-[#333333]'
- }`}
- >
- <ClipToLayerIcon className="w-3.5 h-3.5" />
- </button>
- )}
-
- {/* Folder Collapse / Expand Chevron */}
- {isFolder && (
- <button
- onClick={(e) => {
- e.stopPropagation();
- onToggleCollapse(layer.id);
- }}
- title={layer.collapsed ? 'Expand Folder' : 'Collapse Folder'}
- className="p-0.5 text-[#888888] hover:text-white"
- >
- {layer.collapsed ? (
- <ChevronRight className="w-3.5 h-3.5" />
- ) : (
- <ChevronDown className="w-3.5 h-3.5" />
- )}
- </button>
- )}
-
- {/* Layer Icon: Folder icon for folders, Sliders for adjustment, Layers for raster */}
- {isFolder ? (
- <div className="w-4 h-4 flex items-center justify-center shrink-0 text-amber-400">
- {layer.collapsed ? (
- <Folder className="w-4 h-4" />
- ) : (
- <FolderOpen className="w-4 h-4" />
- )}
- </div>
- ) : layer.type === 'adjustment' ? (
- <div className="w-4 h-4 flex items-center justify-center shrink-0 text-cyan-400">
- <SlidersHorizontal className="w-3.5 h-3.5" />
- </div>
- ) : (
- <div className="w-4 h-4 flex items-center justify-center shrink-0 text-[#888888] group-hover:text-blue-400 transition-colors">
- <Layers className={`w-3.5 h-3.5 ${isActive ? 'text-blue-400' : ''}`} />
- </div>
- )}
-
- {/* Live Layer Thumbnail & Secondary Mask Thumbnail Preview */}
- {!isFolder && (
- <div className="flex items-center space-x-1 shrink-0">
- {/* Primary Layer Thumbnail */}
- {layer.type === 'adjustment' ? (
- <div
- onClick={(e) => {
- e.stopPropagation();
- onSelectLayer(layer.id);
- onSelectEditTarget?.('layer');
- }}
- onDoubleClick={(e) => {
- e.stopPropagation();
- onOpenAdjustmentModal?.(layer.id, layer.adjustmentData?.type);
- }}
- className={`w-10 h-7 rounded-[2px] border border-[#484848] overflow-hidden shrink-0 relative flex items-center justify-center shadow-inner cursor-pointer bg-linear-to-br from-[#1a2332] to-[#0e1726] ${
- isActive && activeEditTarget !== 'mask' ? 'ring-2 ring-blue-500 border-blue-400' : ''
- }`}
- title="Adjustment Layer (Double-click to edit parameters)"
- >
- <SlidersHorizontal className="w-3.5 h-3.5 text-cyan-400" />
- </div>
- ) : (
- <div
- onClick={(e) => {
- e.stopPropagation();
- onSelectLayer(layer.id);
- onSelectEditTarget?.('layer');
- }}
- className={`w-10 h-7 rounded-[2px] border border-[#484848] overflow-hidden shrink-0 relative flex items-center justify-center shadow-inner cursor-pointer ${
- isActive && activeEditTarget !== 'mask' ? 'ring-2 ring-blue-500 border-blue-400' : ''
- }`}
- style={{
- backgroundColor: '#1e1e1e',
- backgroundImage:
- layer.id === 'layer-bg'
- ? 'none'
- : 'conic-gradient(#2d2d2d 90deg, #1f1f1f 90deg 180deg, #2d2d2d 180deg 270deg, #1f1f1f 270deg)',
- backgroundSize: '6px 6px',
- }}
- title={`Layer content preview for ${layer.name}`}
- >
- {layer.thumbnailUrl ? (
- <img
- src={layer.thumbnailUrl}
- alt={layer.name}
- className="w-full h-full object-cover"
- />
- ) : (
- <div
- className="w-full h-full"
- style={{
- backgroundColor: layer.id === 'layer-bg' ? '#ffffff' : 'transparent',
- }}
- />
- )}
-
- {/* Clipping Mask Left Indicator Stripe (CSP style) */}
- {layer.clipped && (
- <div
- className="absolute left-0 top-0 bottom-0 w-1 bg-blue-500 rounded-l-[1px] z-10 shadow-xs"
- title="Clipped to layer below"
- />
- )}
- </div>
- )}
-
- {/* Secondary Mask Thumbnail (if layer has mask) */}
- {(layer.maskCanvas || layer.maskEnabled !== undefined || layer.maskThumbnailUrl) && (
- <>
- {/* Link Toggle Icon */}
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- onToggleMaskLinked?.(layer.id);
- }}
- title={layer.maskLinked !== false ? 'Mask Linked to Layer (Click to Unlink)' : 'Mask Unlinked (Click to Link)'}
- className={`p-0.5 transition-colors ${
- layer.maskLinked !== false ? 'text-zinc-400 hover:text-white' : 'text-zinc-600 hover:text-zinc-400'
- }`}
- >
- <Link2 className={`w-2.5 h-2.5 ${layer.maskLinked === false ? 'opacity-30' : ''}`} />
- </button>
-
- {/* Mask Thumbnail */}
- <div
- onClick={(e) => {
- e.stopPropagation();
- onSelectLayer(layer.id);
- onSelectEditTarget?.('mask');
- }}
- onContextMenu={(e) => {
- e.preventDefault();
- e.stopPropagation();
- onSelectLayer(layer.id);
- onSelectEditTarget?.('mask');
- setContextMenu({
- layerId: layer.id,
- x: e.clientX,
- y: e.clientY,
- });
- }}
- className={`w-10 h-7 rounded-[2px] border border-[#484848] overflow-hidden shrink-0 relative flex items-center justify-center shadow-inner cursor-pointer bg-black ${
- isActive && activeEditTarget === 'mask' ? 'ring-2 ring-blue-500 border-blue-400' : ''
- }`}
- title={`Layer Mask for ${layer.name} (Click to paint on mask, Right-click to toggle enabled)`}
- >
- {layer.maskThumbnailUrl ? (
- <img
- src={layer.maskThumbnailUrl}
- alt={`${layer.name} Mask`}
- className="w-full h-full object-cover"
- />
- ) : (
- <div className="w-full h-full bg-white" />
- )}
-
- {/* Red slash when mask is disabled */}
- {layer.maskEnabled === false && (
- <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
- <div className="w-[140%] h-[1.5px] bg-red-500 rotate-45 transform shadow-xs" />
- </div>
- )}
- </div>
- </>
- )}
- </div>
- )}
-
- {/* Layer Name / Inline Renaming */}
- <div className="flex-1 min-w-0 flex items-center space-x-1.5">
- {editingLayerId === layer.id ? (
- <input
- type="text"
- value={editingName}
- autoFocus
- onChange={(e) => setEditingName(e.target.value)}
- onBlur={finishRename}
- onKeyDown={(e) => {
- if (e.key === 'Enter') finishRename();
- if (e.key === 'Escape') setEditingLayerId(null);
- }}
- onClick={(e) => e.stopPropagation()}
- className="bg-[#1e1e1e] border border-blue-500 rounded px-1 py-0.5 text-xs text-white w-full outline-none"
- />
- ) : (
- <span
- onDoubleClick={() => startRename(layer)}
- title={`${layer.name} (Double-click to rename)`}
- className="text-xs font-medium truncate select-none"
- >
- {layer.name}
- </span>
- )}
-
- {/* Blend Mode Tag if not normal */}
- {layer.blendMode !== 'normal' && (
- <span className="text-[9px] px-1 py-0.2 rounded bg-[#1e1e1e] border border-[#3e3e3e] text-indigo-300 font-mono capitalize shrink-0">
- {layer.blendMode.replace('-', ' ')}
- </span>
- )}
-
- {/* Opacity Tag if < 100% */}
- {layer.opacity < 0.99 && (
- <span className="text-[9px] px-1 py-0.2 rounded bg-[#1e1e1e] text-[#888888] font-mono shrink-0">
- {Math.round(layer.opacity * 100)}%
- </span>
- )}
-
- {/* Screentone Indicator Tag */}
- {layer.toneEnabled && (
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- onToggleTone?.(layer.id);
- }}
- className="text-[9px] px-1.5 py-0.5 rounded bg-amber-950/60 border border-amber-600/50 text-amber-300 font-mono flex items-center gap-1 shrink-0 hover:border-amber-400 hover:text-amber-200 transition-colors"
- title={`Tone: ${layer.toneFrequency ?? 60} LPI, ${layer.toneAngle ?? 45}°, ${(layer.toneDensityType ?? 'specified') === 'specified' ? `${layer.toneDensity ?? 40}%` : 'Image'} (Click to toggle)`}
- >
- <ScreentoneIcon className="w-2.5 h-2.5 text-amber-400" />
- <span>
- {layer.toneFrequency ?? 60}L
- {(layer.toneDensityType ?? 'specified') === 'specified'
- ? ` • ${layer.toneDensity ?? 40}%`
- : ''}
- </span>
- </button>
- )}
-
- {/* Layer Color Tint Indicator Tag */}
- {layer.layerColorEnabled && (
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- onToggleLayerColor?.(layer.id);
- }}
- className="text-[9px] px-1.5 py-0.5 rounded bg-blue-950/60 border border-blue-600/50 text-blue-300 font-mono flex items-center gap-1 shrink-0 hover:border-blue-400 hover:text-blue-200 transition-colors cursor-pointer"
- title={`Tint: ${layer.layerColor || '#1c73c2'} (Click to toggle)`}
- >
- <span
- className="w-2 h-2 rounded-full inline-block shrink-0"
- style={{ backgroundColor: layer.layerColor || '#1c73c2' }}
- />
- <span>Tint</span>
- </button>
- )}
-
- {/* Expression Color Tag if Gray or Monochrome */}
- {layer.expressionColor && layer.expressionColor !== 'color' && (
- <span className="text-[9px] px-1 py-0.2 rounded bg-[#1e1e1e] border border-[#444444] text-cyan-300 font-mono shrink-0">
- {layer.expressionColor === 'monochrome' ? '1-bit' : 'Gray'}
- </span>
- )}
-
- {/* Adjustment Layer Tag */}
- {layer.type === 'adjustment' && (
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- onOpenAdjustmentModal?.(layer.id, layer.adjustmentData?.type);
- }}
- className="text-[9px] px-1.5 py-0.5 rounded bg-cyan-950/60 border border-cyan-600/50 text-cyan-300 font-mono flex items-center gap-1 shrink-0 hover:border-cyan-400 hover:text-cyan-200 transition-colors cursor-pointer"
- title="Click to edit adjustment parameters"
- >
- <SlidersHorizontal className="w-2.5 h-2.5" />
- <span className="capitalize">{layer.adjustmentData?.type?.replace('-', ' ') || 'Adjustment'}</span>
- </button>
- )}
-
- {/* Non-Destructive Layer Styles fx Indicator Tag */}
- {Boolean(
- (layer.styles?.stroke?.enabled && layer.styles.stroke.size > 0 && layer.styles.stroke.opacity > 0) ||
- (layer.styles?.dropShadow?.enabled && layer.styles.dropShadow.opacity > 0) ||
- (layer.styles?.outerGlow?.enabled && layer.styles.outerGlow.opacity > 0)
- ) && (
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- onOpenLayerStylesModal?.(layer.id);
- }}
- className="text-[9px] px-1 py-0.5 rounded bg-amber-500/20 border border-amber-500/40 text-amber-300 font-mono font-bold flex items-center gap-0.5 shrink-0 hover:border-amber-400 hover:text-amber-200 hover:bg-amber-500/30 transition-colors cursor-pointer"
- title="Layer Styles (Stroke, Drop Shadow, Outer Glow) active. Click to edit."
- >
- <Sparkles className="w-2.5 h-2.5 text-amber-400" />
- <span>fx</span>
- </button>
- )}
- </div>
-
- {/* Alpha Lock Indicator Tag */}
- {layer.alphaLocked && (
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- onToggleAlphaLock?.(layer.id);
- }}
- className="p-0.5 text-amber-400 hover:text-amber-300 shrink-0"
- title="Transparent Pixels Locked (Alpha Lock: ON - click to toggle)"
- >
- <AlphaLockIcon className="w-3.5 h-3.5" />
- </button>
- )}
-
- {/* Reference Layer Indicator */}
- {layer.isReference && (
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- onToggleReferenceLayer?.(layer.id);
- }}
- className="p-0.5 text-cyan-400 hover:text-cyan-300 shrink-0"
- title="Reference Layer (Click to toggle)"
- >
- <Compass className="w-3.5 h-3.5" />
- </button>
- )}
-
- {/* Lock Indicator */}
- {layer.locked && (
- <Lock className="w-3 h-3 text-[#777777] shrink-0" />
- )}
-
- {/* Hover Quick Actions: Single-Click Duplicate, Move to/from folder, Delete */}
- <div className="flex items-center space-x-0.5 opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
- {/* Delete Layer Mask Quick Action */}
- {(layer.maskCanvas || layer.maskEnabled !== undefined) && onRemoveLayerMask && (
- <button
- onClick={(e) => {
- e.stopPropagation();
- onRemoveLayerMask(layer.id);
- }}
- title="Delete Layer Mask"
- className="p-1 hover:text-rose-400 hover:bg-[#333333] rounded-[2px] text-zinc-400"
- >
- <SquareDot className="w-3 h-3 text-rose-400/80" />
- </button>
- )}
-
- {/* Single-Click Duplicate Button */}
- <button
- onClick={(e) => {
- e.stopPropagation();
- onDuplicateLayer(layer.id);
- }}
- title="Duplicate (Single Click)"
- className="p-1 hover:text-emerald-400 hover:bg-[#333333] rounded-[2px]"
- >
- <Copy className="w-3 h-3" />
- </button>
-
- {/* Move to folder or move out of folder button */}
- {isInsideFolder ? (
- <button
- onClick={(e) => {
- e.stopPropagation();
- onMoveLayerToFolder(layer.id, null);
- }}
- title="Move out of Folder"
- className="p-1 hover:text-amber-400 hover:bg-[#333333] rounded-[2px]"
- >
- <FolderOutput className="w-3 h-3" />
- </button>
- ) : (
- folders.length > 0 &&
- !isFolder && (
- <div className="relative">
- <button
- onClick={(e) => {
- e.stopPropagation();
- if (folders.length === 1) {
- onMoveLayerToFolder(layer.id, folders[0].id);
- } else {
- setOpenFolderMenuLayerId(
- openFolderMenuLayerId === layer.id ? null : layer.id
- );
- }
- }}
- title={
- folders.length === 1
- ? `Move into "${folders[0].name}"`
- : 'Move into Folder...'
- }
- className="p-1 hover:text-amber-400 hover:bg-[#333333] rounded-[2px]"
- >
- <FolderInput className="w-3 h-3" />
- </button>
-
- {/* Dropdown Menu when multiple folders exist */}
- {openFolderMenuLayerId === layer.id && (
- <div
- onClick={(e) => e.stopPropagation()}
- className="absolute right-0 top-full mt-1 w-40 bg-[#1e1e1e] border border-[#444444] rounded shadow-xl z-50 p-1 text-[11px] space-y-0.5"
- >
- <div className="px-2 py-0.5 text-[10px] text-[#888888] font-semibold border-b border-[#2d2d2d]">
- Move into:
- </div>
- {folders.map((f) => (
- <button
- key={f.id}
- onClick={() => {
- onMoveLayerToFolder(layer.id, f.id);
- setOpenFolderMenuLayerId(null);
- }}
- className="w-full text-left flex items-center space-x-1.5 px-2 py-1 rounded hover:bg-[#333333] text-[#cccccc] hover:text-white"
- >
- <Folder className="w-3 h-3 text-amber-400 shrink-0" />
- <span className="truncate">{f.name}</span>
- </button>
- ))}
- </div>
- )}
- </div>
- )
- )}
-
- {/* Delete Layer button */}
- <button
- onClick={(e) => {
- e.stopPropagation();
- onDeleteLayer(layer.id);
- }}
- title="Delete Layer"
- className="p-1 hover:text-rose-400 hover:bg-[#333333] rounded-[2px]"
- >
- <Trash2 className="w-3 h-3" />
- </button>
- </div>
- </div>
- );
- })}
- </div>
- </>
- )}
- </div>
- )}
-
- {/* Tab Content 2: History Stack List */}
- {bottomTab === 'history' && (
- <div className="flex-1 flex flex-col overflow-hidden min-h-0">
- {!hasOpenDocument || historyList.length === 0 ? (
- <div className="flex-1 flex flex-col items-center justify-center p-4 text-center select-none text-[#777777]">
- <History className="w-8 h-8 mb-2 opacity-30 text-[#aaaaaa]" />
- <p className="text-xs text-[#aaaaaa] font-medium">No History</p>
- <p className="text-[11px] text-[#666666] mt-1">
- {!hasOpenDocument ? 'No project is open.' : 'History will appear as you paint.'}
- </p>
- </div>
- ) : (
- <div className="flex-1 overflow-y-auto p-2 space-y-1 min-h-0">
- {historyList.map((item, idx) => {
- const isActive = idx === historyIndex;
- const isPast = idx < historyIndex;
- const isFuture = idx > historyIndex;
-
- return (
- <div
- key={item.id}
- onClick={() => onJumpToHistory(idx)}
- title={`Jump to step ${idx + 1}: ${item.label} (${item.timeFormatted})`}
- className={`flex items-center space-x-2.5 px-2 py-1.5 rounded-[2px] cursor-pointer transition-colors ${
- isActive
- ? 'bg-[#353535] border border-[#555555] text-white shadow-sm'
- : isFuture
- ? 'opacity-35 hover:opacity-75 hover:bg-[#2a2a2a] text-[#777777]'
- : 'text-[#cccccc] hover:bg-[#2a2a2a]'
- }`}
- >
- {/* Step Thumbnail */}
- <div className="w-9 h-6 rounded-[2px] bg-[#1a1a1a] border border-[#3a3a3a] overflow-hidden shrink-0 flex items-center justify-center">
- {item.thumbnailUrl ? (
- <img
- src={item.thumbnailUrl}
- alt={item.label}
- className="w-full h-full object-cover"
- />
- ) : (
- <div className="w-full h-full bg-white" />
- )}
- </div>
-
- {/* Step Action Name & Timestamp */}
- <div className="flex-1 min-w-0">
- <div className="flex items-center space-x-1.5">
- {item.type === 'eraser' ? (
- <Eraser className="w-3.5 h-3.5 text-amber-400 shrink-0" />
- ) : item.type === 'clear' ? (
- <Trash2 className="w-3.5 h-3.5 text-rose-400 shrink-0" />
- ) : item.type === 'initial' ? (
- <Palette className="w-3.5 h-3.5 text-violet-400 shrink-0" />
- ) : (
- <Paintbrush className="w-3.5 h-3.5 text-blue-400 shrink-0" />
- )}
- <span className="text-xs font-medium truncate">{item.label}</span>
- </div>
- <span className="text-[10px] text-[#666666] font-mono block">
- {item.timeFormatted}
- </span>
- </div>
-
- {/* Active Indicator Pin */}
- {isActive && (
- <div
- title="Current active state"
- className="w-2 h-2 rounded-full bg-emerald-400 shrink-0 shadow-[0_0_6px_rgba(52,211,153,0.9)]"
- />
- )}
- {isPast && (
- <div className="text-[10px] text-[#555555] font-mono shrink-0">
- #{idx + 1}
- </div>
- )}
- </div>
- );
- })}
- </div>
- )}
- </div>
- )}
- </section>
-
- {/* Right-Click Layer Context Menu */}
- {contextMenu && (() => {
- const targetLayer = layers.find((l) => l.id === contextMenu.layerId);
- if (!targetLayer) return null;
- const hasMask = Boolean(targetLayer.maskCanvas || targetLayer.maskEnabled !== undefined || targetLayer.maskThumbnailUrl);
- const isAdj = targetLayer.type === 'adjustment';
-
- return (
- <div
- ref={contextMenuRef}
- className="fixed z-50 min-w-52 bg-[#222225] border border-[#3e3e42] rounded-md shadow-2xl py-1 text-xs text-[#cccccc] select-none animate-in fade-in duration-75"
- style={{
- left: Math.max(10, Math.min(contextMenu.x, window.innerWidth - 220)),
- top: Math.max(10, Math.min(contextMenu.y, window.innerHeight - 360)),
- }}
- onClick={(e) => e.stopPropagation()}
- onContextMenu={(e) => e.preventDefault()}
- >
- {/* Header / Layer info */}
- <div className="px-3 py-1 text-[10px] text-[#777777] font-semibold uppercase tracking-wider border-b border-[#2d2d30] mb-0.5 truncate flex items-center justify-between">
- <span className="truncate">{targetLayer.name}</span>
- {isAdj && <span className="text-cyan-400 font-mono text-[9px] lowercase">adjustment</span>}
- </div>
-
- {/* --- MASK OPTIONS --- */}
- {targetLayer.type !== 'folder' && (
- <>
- <div className="px-3 py-1 text-[10px] text-[#888888] font-semibold tracking-wide flex items-center space-x-1">
- <SquareDot className="w-3 h-3 text-emerald-400" />
- <span>Layer Mask</span>
- </div>
- {!hasMask ? (
- <button
- onClick={() => {
- onAddLayerMask?.(targetLayer.id);
- setContextMenu(null);
- }}
- className="w-full text-left px-3 py-1.5 pl-6 flex items-center space-x-2 hover:bg-[#333333] hover:text-white transition-colors"
- >
- <span>Add Layer Mask</span>
- </button>
- ) : (
- <>
- <button
- onClick={() => {
- onToggleLayerMask?.(targetLayer.id);
- setContextMenu(null);
- }}
- className="w-full text-left px-3 py-1.5 pl-6 flex items-center justify-between hover:bg-[#333333] hover:text-white transition-colors"
- >
- <span>{targetLayer.maskEnabled === false ? 'Enable Mask' : 'Disable Mask'}</span>
- <span className="text-[10px] font-mono text-zinc-400">
- {targetLayer.maskEnabled === false ? 'OFF' : 'ON'}
- </span>
- </button>
- <button
- onClick={() => {
- onToggleMaskLinked?.(targetLayer.id);
- setContextMenu(null);
- }}
- className="w-full text-left px-3 py-1.5 pl-6 flex items-center justify-between hover:bg-[#333333] hover:text-white transition-colors"
- >
- <span>{targetLayer.maskLinked === false ? 'Link Mask' : 'Unlink Mask'}</span>
- <Link2 className={`w-3 h-3 ${targetLayer.maskLinked === false ? 'text-zinc-600' : 'text-zinc-400'}`} />
- </button>
- <button
- onClick={() => {
- onRemoveLayerMask?.(targetLayer.id);
- setContextMenu(null);
- }}
- className="w-full text-left px-3 py-1.5 pl-6 flex items-center space-x-2 hover:bg-rose-950/40 text-rose-400 hover:text-rose-300 transition-colors"
- >
- <span>Delete Mask</span>
- </button>
- </>
- )}
- <div className="my-1 border-t border-[#2d2d30]" />
- </>
- )}
-
- {/* --- ADJUSTMENT OPTIONS --- */}
- {isAdj && (
- <>
- <button
- onClick={() => {
- onOpenAdjustmentModal?.(targetLayer.id, targetLayer.adjustmentData?.type);
- setContextMenu(null);
- }}
- className="w-full text-left px-3 py-1.5 flex items-center space-x-2 hover:bg-[#333333] text-cyan-400 hover:text-cyan-300 transition-colors"
- >
- <SlidersHorizontal className="w-3.5 h-3.5" />
- <span className="font-medium">Edit Adjustment Parameters...</span>
- </button>
- <div className="my-1 border-t border-[#2d2d30]" />
- </>
- )}
-
- {onOpenAdjustmentModal && (
- <>
- <div className="px-3 py-1 text-[10px] text-[#888888] font-semibold tracking-wide flex items-center space-x-1">
- <SlidersHorizontal className="w-3 h-3 text-cyan-400" />
- <span>New Adjustment Layer</span>
- </div>
- <button
- onClick={() => {
- onOpenAdjustmentModal(undefined, 'curves');
- setContextMenu(null);
- }}
- className="w-full text-left px-3 py-1.5 pl-6 flex items-center space-x-2 hover:bg-[#333333] hover:text-white transition-colors"
- >
- <span>Tone Curves...</span>
- </button>
- <button
- onClick={() => {
- onOpenAdjustmentModal(undefined, 'gradient-map');
- setContextMenu(null);
- }}
- className="w-full text-left px-3 py-1.5 pl-6 flex items-center space-x-2 hover:bg-[#333333] hover:text-white transition-colors"
- >
- <span>Gradient Map...</span>
- </button>
- <button
- onClick={() => {
- onOpenAdjustmentModal(undefined, 'levels');
- setContextMenu(null);
- }}
- className="w-full text-left px-3 py-1.5 pl-6 flex items-center space-x-2 hover:bg-[#333333] hover:text-white transition-colors"
- >
- <span>Levels...</span>
- </button>
- <button
- onClick={() => {
- onOpenAdjustmentModal(undefined, 'color-balance');
- setContextMenu(null);
- }}
- className="w-full text-left px-3 py-1.5 pl-6 flex items-center space-x-2 hover:bg-[#333333] hover:text-white transition-colors"
- >
- <span>Color Balance...</span>
- </button>
- <div className="my-1 border-t border-[#2d2d30]" />
- </>
- )}
-
- {/* --- LAYER STYLES / BLENDING OPTIONS --- */}
- {targetLayer.type !== 'folder' && targetLayer.type !== 'adjustment' && onOpenLayerStylesModal && (
- <>
- <button
- onClick={() => {
- onOpenLayerStylesModal(targetLayer.id);
- setContextMenu(null);
- }}
- className="w-full text-left px-3 py-1.5 flex items-center space-x-2 hover:bg-[#333333] text-amber-400 hover:text-amber-300 transition-colors"
- >
- <Sparkles className="w-3.5 h-3.5" />
- <span className="font-medium">Blending Options / Layer Styles...</span>
- </button>
- <div className="my-1 border-t border-[#2d2d30]" />
- </>
- )}
-
- {/* --- GENERAL ACTIONS --- */}
- {onGroupSelectedLayers && (
- <button
- onClick={() => {
- onGroupSelectedLayers();
- setContextMenu(null);
- }}
- className="w-full text-left px-3 py-1.5 flex items-center space-x-2 hover:bg-[#333333] hover:text-white transition-colors text-amber-300"
- >
- <FolderPlus className="w-3.5 h-3.5 text-amber-400" />
- <span>Group into Folder (Ctrl+G)</span>
- </button>
- )}
- <button
- onClick={() => {
- onDuplicateLayer(targetLayer.id);
- setContextMenu(null);
- }}
- className="w-full text-left px-3 py-1.5 flex items-center space-x-2 hover:bg-[#333333] hover:text-white transition-colors"
- >
- <Copy className="w-3.5 h-3.5 text-zinc-400" />
- <span>Duplicate</span>
- </button>
- <button
- onClick={() => {
- startRename(targetLayer);
- setContextMenu(null);
- }}
- className="w-full text-left px-3 py-1.5 flex items-center space-x-2 hover:bg-[#333333] hover:text-white transition-colors"
- >
- <span>Rename</span>
- </button>
- {targetLayer.id !== 'layer-bg' && (
- <button
- onClick={() => {
- if (onDeleteSelectedLayers && selectedLayerIds && selectedLayerIds.length > 1) {
- onDeleteSelectedLayers();
- } else {
- onDeleteLayer(targetLayer.id);
- }
- setContextMenu(null);
- }}
- className="w-full text-left px-3 py-1.5 flex items-center space-x-2 hover:bg-rose-950/40 text-rose-400 hover:text-rose-300 transition-colors"
- >
- <Trash2 className="w-3.5 h-3.5 text-rose-400" />
- <span>{selectedLayerIds && selectedLayerIds.length > 1 ? `Delete Selected Layers (${selectedLayerIds.length})` : 'Delete'}</span>
- </button>
- )}
- </div>
- );
- })()}
- </aside>
- );
-});
+ );
+ })()}
+ </aside>
+ );
+});
RightSidebar.displayName = 'RightSidebar';
-
-
diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsx
index 366ab1d..624f44d 100644
--- a/src/components/SettingsModal.tsx
+++ b/src/components/SettingsModal.tsx
@@ -9,9 +9,6 @@ import {
RotateCcw,
Check,
Search,
- User,
- Settings as SettingsIcon,
- Sparkles,
} from 'lucide-react';
import {
AppSettings,
@@ -41,33 +38,27 @@ interface ShortcutRow {
}
const SHORTCUTS_DATA: ShortcutRow[] = [
- // File
- { category: 'File', action: 'New Canvas', shortcut: 'Ctrl + N', desc: 'Create a new canvas with custom dimensions' },
+ { category: 'File', action: 'New Canvas', shortcut: 'Ctrl + N', desc: 'Create a new canvas' },
{ category: 'File', action: 'Open File', shortcut: 'Ctrl + O', desc: 'Open images, PSD, or CSP files' },
- { category: 'File', action: 'Save', shortcut: 'Ctrl + S', desc: 'Save current document or export changes' },
- { category: 'File', action: 'Save As', shortcut: 'Ctrl + Shift + S', desc: 'Save as a new layered file or image format' },
- // Edit
- { category: 'Edit', action: 'Undo', shortcut: 'Ctrl + Z', desc: 'Undo last drawing or layer action' },
- { category: 'Edit', action: 'Redo', shortcut: 'Ctrl + Y', desc: 'Redo previously undone action' },
- { category: 'Edit', action: 'Copy Layer', shortcut: 'Ctrl + C', desc: 'Copy selected layer to clipboard' },
- { category: 'Edit', action: 'Paste Layer', shortcut: 'Ctrl + V', desc: 'Paste copied layer or clipboard image' },
- { category: 'Edit', action: 'Delete Layer', shortcut: 'Del', desc: 'Delete currently selected layer' },
- { category: 'Edit', action: 'Settings', shortcut: 'Ctrl + ,', desc: 'Open application preferences' },
- // Tools
- { category: 'Tools', action: 'Brush Tool', shortcut: 'B', desc: 'Switch to drawing brush' },
- { category: 'Tools', action: 'Eraser Tool', shortcut: 'E', desc: 'Switch to transparent eraser' },
+ { category: 'File', action: 'Save', shortcut: 'Ctrl + S', desc: 'Save current document' },
+ { category: 'File', action: 'Save As', shortcut: 'Ctrl + Shift + S', desc: 'Save as a new file' },
+ { category: 'Edit', action: 'Undo', shortcut: 'Ctrl + Z', desc: 'Undo last action' },
+ { category: 'Edit', action: 'Redo', shortcut: 'Ctrl + Y', desc: 'Redo undone action' },
+ { category: 'Edit', action: 'Copy Layer', shortcut: 'Ctrl + C', desc: 'Copy selected layer' },
+ { category: 'Edit', action: 'Paste Layer', shortcut: 'Ctrl + V', desc: 'Paste copied layer' },
+ { category: 'Edit', action: 'Delete Layer', shortcut: 'Del', desc: 'Delete selected layer' },
+ { category: 'Edit', action: 'Preferences', shortcut: 'Ctrl + ,', desc: 'Open preferences' },
+ { category: 'Tools', action: 'Brush Tool', shortcut: 'B', desc: 'Switch to brush' },
+ { category: 'Tools', action: 'Eraser Tool', shortcut: 'E', desc: 'Switch to eraser' },
{ category: 'Tools', action: 'Swap Colors', shortcut: 'X', desc: 'Swap primary and secondary colors' },
- { category: 'Tools', action: 'Adjust Brush Size & Hardness', shortcut: 'Ctrl + Alt + Drag', desc: 'Horizontal: size, Vertical: hardness' },
- // Navigation
- { category: 'Navigation', action: 'Pan Canvas', shortcut: 'Space + Drag', desc: 'Move viewport across canvas' },
- { category: 'Navigation', action: 'Rotate Canvas', shortcut: 'Shift + Space + Drag', desc: 'Freely rotate canvas at any angle' },
- { category: 'Navigation', action: 'Zoom In', shortcut: 'Ctrl + +', desc: 'Increase canvas magnification' },
- { category: 'Navigation', action: 'Zoom Out', shortcut: 'Ctrl + -', desc: 'Decrease canvas magnification' },
- { category: 'Navigation', action: 'Reset Zoom & Center', shortcut: 'Ctrl + 0', desc: 'Fit canvas into viewport center' },
- { category: 'Navigation', action: 'Reset Rotation', shortcut: 'Ctrl + Alt + 0', desc: 'Snap canvas back to 0° upright' },
- // Layers
- { category: 'Layers', action: 'New Raster Layer', shortcut: 'Ctrl + Shift + N', desc: 'Add a new blank transparent layer' },
- { category: 'Layers', action: 'Duplicate Layer', shortcut: 'Ctrl + J', desc: 'Clone current layer with all pixel contents' },
+ { category: 'Tools', action: 'Brush Size & Hardness', shortcut: 'Ctrl + Alt + Drag', desc: 'Horizontal: size, Vertical: hardness' },
+ { category: 'Navigation', action: 'Pan Canvas', shortcut: 'Space + Drag', desc: 'Pan viewport' },
+ { category: 'Navigation', action: 'Rotate Canvas', shortcut: 'Shift + Space + Drag', desc: 'Rotate viewport' },
+ { category: 'Navigation', action: 'Zoom In / Out', shortcut: 'Ctrl + +/-', desc: 'Adjust magnification' },
+ { category: 'Navigation', action: 'Reset Zoom', shortcut: 'Ctrl + 0', desc: 'Fit & center canvas' },
+ { category: 'Navigation', action: 'Reset Rotation', shortcut: 'Ctrl + Alt + 0', desc: 'Reset angle to 0°' },
+ { category: 'Layers', action: 'New Raster Layer', shortcut: 'Ctrl + Shift + N', desc: 'Add transparent layer' },
+ { category: 'Layers', action: 'Duplicate Layer', shortcut: 'Ctrl + J', desc: 'Clone current layer' },
];
export const SettingsModal: React.FC<SettingsModalProps> = ({
@@ -96,7 +87,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
const handleResetDefaults = () => {
setLocalSettings(DEFAULT_APP_SETTINGS);
onUpdateSettings(DEFAULT_APP_SETTINGS);
- onShowToast('Settings reset to default values');
+ onShowToast('Preferences reset to defaults');
};
const filteredShortcuts = SHORTCUTS_DATA.filter(
@@ -107,224 +98,101 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
s.category.toLowerCase().includes(searchQuery.toLowerCase())
);
+ const resolvedAccent = resolveModernAccentColor(
+ localSettings.modernAccent,
+ localSettings.modernCustomColor
+ );
+
+ const tabs: Array<{ id: SettingsTab; label: string; icon: React.ReactNode }> = [
+ { id: 'appearance', label: 'Appearance', icon: <Palette className="w-3.5 h-3.5" /> },
+ { 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: 'shortcuts', label: 'Shortcuts', icon: <Keyboard className="w-3.5 h-3.5" /> },
+ { id: 'about', label: 'About', icon: <Info className="w-3.5 h-3.5" /> },
+ ];
+
return (
<div
- className="fixed inset-0 z-50 flex items-center justify-center bg-black/75 backdrop-blur-xs p-4 select-none animate-in fade-in duration-150"
+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/75 p-4 select-none"
+ onClick={onClose}
onKeyDown={(e) => {
if (e.key === 'Escape') onClose();
}}
>
- <div className="bg-[#444447] border border-[#242426] rounded-[2px] shadow-[0_8px_24px_rgba(0,0,0,0.7)] w-full max-w-3xl flex flex-col overflow-hidden text-xs text-[#d6d6da] h-[580px]">
+ <div
+ onClick={(e) => e.stopPropagation()}
+ className="bg-[#202020] rounded-lg shadow-[0_24px_64px_rgba(0,0,0,0.8)] w-full max-w-2xl flex flex-col overflow-hidden text-xs text-[#e5e5e5] h-[520px]"
+ >
{/* Header */}
- <div className="flex items-center justify-between px-4 py-2.5 bg-gradient-to-b from-[#525255] to-[#3e3e40] border-b border-[#242426] shrink-0">
- <div className="flex items-center space-x-2">
- <SettingsIcon className="w-4 h-4 text-[#93c5fd]" />
- <h2 className="text-xs font-semibold text-[#f0f0f4] tracking-wide">Application Preferences</h2>
- </div>
+ <div className="h-10 px-4 flex items-center justify-between bg-[#161616] shrink-0">
+ <span className="text-xs font-medium text-[#e5e5e5]">Preferences</span>
<button
+ type="button"
onClick={onClose}
- className="p-1 rounded-[2px] hover:bg-[#525255] text-[#a0a0a5] hover:text-white transition-colors"
+ className="w-6 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"
title="Close (Esc)"
>
- <X className="w-4 h-4" />
+ <X className="w-3.5 h-3.5" />
</button>
</div>
- {/* Body: Left Tabs + Right Content */}
- <div className="flex flex-1 overflow-hidden">
- {/* Left Tabs Bar */}
- <div className="w-44 bg-[#37373a] border-r border-[#242426] p-2 space-y-1 shrink-0 flex flex-col justify-between">
- <div className="space-y-1">
- <button
- type="button"
- onClick={() => setActiveTab('appearance')}
- className={`w-full flex items-center space-x-2 px-2.5 py-1.5 rounded-[2px] text-left transition-colors border ${
- activeTab === 'appearance'
- ? 'bg-gradient-to-b from-[#376590] to-[#204264] border-[#4a8fc7] text-white font-medium shadow-[inset_0_1px_2px_rgba(0,0,0,0.5)]'
- : 'border-transparent text-[#b0b0b5] hover:bg-[#424245] hover:text-white'
- }`}
- >
- <Palette className="w-3.5 h-3.5 shrink-0" />
- <span>Appearance</span>
- </button>
-
- <button
- type="button"
- onClick={() => setActiveTab('canvas')}
- className={`w-full flex items-center space-x-2 px-2.5 py-1.5 rounded-[2px] text-left transition-colors border ${
- activeTab === 'canvas'
- ? 'bg-gradient-to-b from-[#376590] to-[#204264] border-[#4a8fc7] text-white font-medium shadow-[inset_0_1px_2px_rgba(0,0,0,0.5)]'
- : 'border-transparent text-[#b0b0b5] hover:bg-[#424245] hover:text-white'
- }`}
- >
- <Layers className="w-3.5 h-3.5 shrink-0" />
- <span>Canvas Defaults</span>
- </button>
-
- <button
- type="button"
- onClick={() => setActiveTab('brush')}
- className={`w-full flex items-center space-x-2 px-2.5 py-1.5 rounded-[2px] text-left transition-colors border ${
- activeTab === 'brush'
- ? 'bg-gradient-to-b from-[#376590] to-[#204264] border-[#4a8fc7] text-white font-medium shadow-[inset_0_1px_2px_rgba(0,0,0,0.5)]'
- : 'border-transparent text-[#b0b0b5] hover:bg-[#424245] hover:text-white'
- }`}
- >
- <Paintbrush className="w-3.5 h-3.5 shrink-0" />
- <span>Brush & Stylus</span>
- </button>
-
- <button
- type="button"
- onClick={() => setActiveTab('shortcuts')}
- className={`w-full flex items-center space-x-2 px-2.5 py-1.5 rounded-[2px] text-left transition-colors border ${
- activeTab === 'shortcuts'
- ? 'bg-gradient-to-b from-[#376590] to-[#204264] border-[#4a8fc7] text-white font-medium shadow-[inset_0_1px_2px_rgba(0,0,0,0.5)]'
- : 'border-transparent text-[#b0b0b5] hover:bg-[#424245] hover:text-white'
- }`}
- >
- <Keyboard className="w-3.5 h-3.5 shrink-0" />
- <span>Shortcuts</span>
- </button>
-
- <button
- type="button"
- onClick={() => setActiveTab('about')}
- className={`w-full flex items-center space-x-2 px-2.5 py-1.5 rounded-[2px] text-left transition-colors border ${
- activeTab === 'about'
- ? 'bg-gradient-to-b from-[#376590] to-[#204264] border-[#4a8fc7] text-white font-medium shadow-[inset_0_1px_2px_rgba(0,0,0,0.5)]'
- : 'border-transparent text-[#b0b0b5] hover:bg-[#424245] hover:text-white'
- }`}
- >
- <Info className="w-3.5 h-3.5 shrink-0" />
- <span>About</span>
- </button>
+ {/* Body */}
+ <div className="flex flex-1 overflow-hidden gap-px bg-[#161616]">
+ {/* Left Navigation */}
+ <div className="w-40 bg-[#202020] p-2 flex flex-col justify-between shrink-0">
+ <div className="space-y-0.5">
+ {tabs.map((t) => {
+ const active = activeTab === t.id;
+ return (
+ <button
+ key={t.id}
+ type="button"
+ onClick={() => setActiveTab(t.id)}
+ className={`w-full flex items-center gap-2 px-2.5 py-1.5 rounded text-left transition-colors cursor-pointer ${
+ active
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/50'
+ }`}
+ >
+ <span className={active ? 'text-[var(--accent)]' : ''}>{t.icon}</span>
+ <span>{t.label}</span>
+ </button>
+ );
+ })}
</div>
- <div className="pt-2 border-t border-[#2a2a2d]">
- <button
- type="button"
- onClick={handleResetDefaults}
- className="w-full flex items-center justify-center space-x-1.5 px-2 py-1.5 rounded text-[11px] text-[#888888] hover:text-rose-300 hover:bg-rose-500/10 border border-transparent hover:border-rose-500/20 transition-colors"
- title="Reset all settings to default"
- >
- <RotateCcw className="w-3.5 h-3.5" />
- <span>Reset Defaults</span>
- </button>
- </div>
+ <button
+ type="button"
+ onClick={handleResetDefaults}
+ className="w-full flex items-center justify-center gap-1.5 px-2 py-1.5 rounded text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"
+ >
+ <RotateCcw className="w-3 h-3" />
+ <span>Reset Defaults</span>
+ </button>
</div>
- {/* Right Content Area */}
- <div className="flex-1 p-5 overflow-y-auto bg-[#222224]">
- {/* 1. Appearance */}
+ {/* Content */}
+ <div className="flex-1 p-5 overflow-y-auto bg-[#202020] space-y-5">
{activeTab === 'appearance' && (
- <div className="space-y-5">
- <div>
- <h3 className="text-sm font-semibold text-white">Appearance & Profile</h3>
- <p className="text-[11px] text-[#888888]">Personalize your workspace, profile, and theme settings</p>
- </div>
-
- {/* User Profile */}
- <div className="bg-[#1a1a1c] border border-[#333336] rounded-md p-3.5 space-y-2.5">
- <div className="flex items-center space-x-2">
- <User className="w-3.5 h-3.5 text-[#38bdf8]" />
- <span className="text-[11px] font-semibold text-[#aaaaaa] uppercase tracking-wider block">
- User Profile
- </span>
- </div>
- <p className="text-[11px] text-[#888888]">
- Displayed on the Welcome Screen and in collaboration sessions
- </p>
- <div>
- <label className="text-[11px] text-[#cccccc] block mb-1">Display Name</label>
- <input
- type="text"
- value={localSettings.userName || ''}
- onChange={(e) => {
- const val = e.target.value;
- handleChange('userName', val);
- try {
- localStorage.setItem('sora_paint_nickname', val);
- } catch {
- // ignore
- }
- }}
- placeholder="Enter your name"
- className="w-full bg-[#141416] border border-[#3a3a3d] focus:border-[#007acc] rounded px-3 py-1.5 text-xs text-white placeholder-[#555555] outline-hidden transition-colors"
- />
- </div>
- </div>
-
- {/* Interface Theme Switcher */}
- <div className="bg-[#1a1a1c] border border-[#333336] rounded-md p-3.5 space-y-3">
+ <>
+ {/* Accent Color Customization */}
+ <section className="space-y-2.5">
<div className="flex items-center justify-between">
- <span className="text-[11px] font-semibold text-[#aaaaaa] uppercase tracking-wider block">
- Theme Preset
- </span>
- <span className="text-[10px] text-[#777777] font-mono">
- {localSettings.themePreset === 'modern' ? 'Minimalist Sleek' : 'Vintage DCC'}
- </span>
- </div>
- <div className="grid grid-cols-2 gap-2.5">
- <button
- type="button"
- onClick={() => handleChange('themePreset', 'vintage-manga')}
- className={`flex items-center justify-between py-2.5 px-3 rounded text-xs font-medium border transition-all cursor-pointer ${
- localSettings.themePreset === 'vintage-manga'
- ? 'bg-[#293d45] border-[#5ce1e6] text-[#5ce1e6] shadow-xs'
- : 'bg-[#222225] border-[#38383c] text-[#bbbbbb] hover:bg-[#28282c] hover:text-white'
- }`}
- >
- <div className="flex items-center space-x-2">
- <span className="font-semibold text-xs">Old Studio</span>
- </div>
- {localSettings.themePreset === 'vintage-manga' && <Check className="w-3.5 h-3.5 shrink-0" />}
- </button>
-
- <button
- type="button"
- onClick={() => handleChange('themePreset', 'modern')}
- className={`flex items-center justify-between py-2.5 px-3 rounded text-xs font-medium border transition-all cursor-pointer ${
- localSettings.themePreset === 'modern'
- ? 'bg-[var(--modern-accent-subtle,#1e293b)] border-[var(--modern-accent,#3b82f6)] text-[var(--modern-accent,#3b82f6)] shadow-xs'
- : 'bg-[#222225] border-[#38383c] text-[#bbbbbb] hover:bg-[#28282c] hover:text-white'
- }`}
- >
- <div className="flex items-center space-x-2">
- <Sparkles className="w-3.5 h-3.5 shrink-0 text-[var(--modern-accent,#3b82f6)]" />
- <span className="font-semibold text-xs">Modern</span>
- </div>
- {localSettings.themePreset === 'modern' && <Check className="w-3.5 h-3.5 shrink-0" />}
- </button>
- </div>
- </div>
-
- {/* Modern Accent Colors (When Modern design is selected) */}
- {localSettings.themePreset === 'modern' && (
- <div className="bg-[#1a1a1c] border border-[#333336] rounded-md p-3.5 space-y-3">
- <div className="flex items-center justify-between">
- <div>
- <span className="text-[11px] font-semibold text-[#aaaaaa] uppercase tracking-wider block">
- Accent Color
- </span>
- <span className="text-[10px] text-[#888888]">
- Select accent color for active tools, highlights, buttons, and sliders
- </span>
- </div>
- <div
- className="w-4 h-4 rounded-full border border-white/20 shadow-xs shrink-0"
- style={{
- backgroundColor: resolveModernAccentColor(
- localSettings.modernAccent,
- localSettings.modernCustomColor
- ),
- }}
- title={`Current Accent: ${localSettings.modernAccent}`}
- />
+ <div>
+ <h3 className="text-xs font-medium text-[#e5e5e5]">Accent Color</h3>
+ <p className="text-[11px] text-[#8a8a8a]">
+ Updates the <code className="font-mono text-[#e5e5e5]">--accent</code> CSS variable across controls and sliders
+ </p>
</div>
+ <span
+ className="w-4 h-4 rounded-full shrink-0 shadow-[0_0_0_1px_rgba(255,255,255,0.2)]"
+ style={{ backgroundColor: resolvedAccent }}
+ />
+ </div>
- <div className="grid grid-cols-3 gap-2">
- {(Object.keys(MODERN_ACCENTS) as Array<Exclude<ModernAccentColor, 'custom'>>).map((accKey) => {
+ <div className="grid grid-cols-3 gap-1.5">
+ {(Object.keys(MODERN_ACCENTS) as Array<Exclude<ModernAccentColor, 'custom'>>).map(
+ (accKey) => {
const acc = MODERN_ACCENTS[accKey];
const isSelected = localSettings.modernAccent === accKey;
return (
@@ -332,313 +200,247 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
key={accKey}
type="button"
onClick={() => handleChange('modernAccent', accKey)}
- className={`flex items-center space-x-2 px-2.5 py-2 rounded border text-xs transition-all cursor-pointer ${
+ className={`flex items-center gap-2 px-2.5 py-2 rounded text-xs transition-colors cursor-pointer ${
isSelected
- ? 'bg-[#26272c] border-white/30 text-white font-medium ring-1 ring-white/20'
- : 'bg-[#202125] border-[#35363b] text-[#aaaaaa] hover:bg-[#28292f] hover:text-white'
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'bg-[#161616] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
}`}
>
<span
- className="w-3.5 h-3.5 rounded-full shrink-0 shadow-xs border border-black/20"
+ className="w-3 h-3 rounded-full shrink-0"
style={{ backgroundColor: acc.hex }}
/>
<span className="truncate">{acc.label}</span>
- {isSelected && <Check className="w-3 h-3 ml-auto text-white shrink-0" />}
+ {isSelected && <Check className="w-3 h-3 ml-auto text-[var(--accent)]" />}
</button>
);
- })}
-
- {/* Custom color option */}
- <button
- type="button"
- onClick={() => handleChange('modernAccent', 'custom')}
- className={`flex items-center space-x-2 px-2.5 py-2 rounded border text-xs transition-all cursor-pointer ${
- localSettings.modernAccent === 'custom'
- ? 'bg-[#26272c] border-white/30 text-white font-medium ring-1 ring-white/20'
- : 'bg-[#202125] border-[#35363b] text-[#aaaaaa] hover:bg-[#28292f] hover:text-white'
- }`}
- >
- <span
- className="w-3.5 h-3.5 rounded-full shrink-0 shadow-xs border border-black/20"
- style={{
- backgroundColor: localSettings.modernCustomColor || '#3b82f6',
- }}
- />
- <span className="truncate">Custom</span>
- {localSettings.modernAccent === 'custom' && (
- <Check className="w-3 h-3 ml-auto text-white shrink-0" />
- )}
- </button>
- </div>
-
- {/* Custom Color Picker Input */}
- {localSettings.modernAccent === 'custom' && (
- <div className="p-2.5 rounded bg-[#141416] border border-[#303136] flex items-center space-x-3">
- <div className="relative w-8 h-8 rounded-full overflow-hidden border border-white/20 shadow-xs shrink-0 cursor-pointer">
- <input
- type="color"
- value={localSettings.modernCustomColor || '#3b82f6'}
- onChange={(e) => {
- const hex = e.target.value;
- const updated = {
- ...localSettings,
- modernAccent: 'custom' as ModernAccentColor,
- modernCustomColor: hex,
- };
- setLocalSettings(updated);
- onUpdateSettings(updated);
- }}
- className="absolute -inset-2 w-12 h-12 cursor-pointer opacity-0"
- title="Pick custom accent color"
- />
- <div
- className="w-full h-full"
- style={{ backgroundColor: localSettings.modernCustomColor || '#3b82f6' }}
- />
- </div>
-
- <div className="flex-1 space-y-1">
- <label className="text-[10px] text-[#888888] block">Custom Hex Value</label>
- <input
- type="text"
- value={localSettings.modernCustomColor || '#3b82f6'}
- onChange={(e) => {
- const val = e.target.value;
- const updated = {
- ...localSettings,
- modernAccent: 'custom' as ModernAccentColor,
- modernCustomColor: val,
- };
- setLocalSettings(updated);
- if (/^#[0-9a-fA-F]{6}$/i.test(val)) {
- onUpdateSettings(updated);
- }
- }}
- placeholder="#3b82f6"
- maxLength={7}
- className="w-full bg-[#1e1f23] border border-[#3a3b40] focus:border-[#3b82f6] rounded px-2.5 py-1 font-mono text-xs text-white outline-hidden"
- />
- </div>
- </div>
+ }
)}
- {/* Dark Tone Selector */}
- <div className="pt-2 border-t border-[#2d2e33]">
- <div className="flex items-center justify-between mb-2">
- <span className="text-[11px] font-semibold text-[#aaaaaa] uppercase tracking-wider block">
- Surface Tone
- </span>
- <span className="text-[10px] text-[#777777] font-mono capitalize">
- {localSettings.uiTone || 'slate'}
- </span>
- </div>
- <div className="grid grid-cols-3 gap-2">
- {([
- { id: 'slate', label: 'Slate', desc: 'Cold tech' },
- { id: 'charcoal', label: 'Charcoal', desc: 'Neutral grey' },
- { id: 'oled', label: 'OLED Black', desc: 'Pure ink black' },
- ] as const).map((tone) => {
- const isSelected = (localSettings.uiTone || 'slate') === tone.id;
- return (
- <button
- key={tone.id}
- type="button"
- onClick={() => handleChange('uiTone', tone.id)}
- className={`px-2.5 py-1.5 rounded border text-left text-xs transition-all cursor-pointer ${
- isSelected
- ? 'bg-[#26272c] border-white/30 text-white font-medium ring-1 ring-white/20'
- : 'bg-[#202125] border-[#35363b] text-[#aaaaaa] hover:bg-[#28292f] hover:text-white'
- }`}
- >
- <div className="flex items-center justify-between">
- <span className="font-medium text-xs text-white">{tone.label}</span>
- {isSelected && <Check className="w-3 h-3 text-white shrink-0" />}
- </div>
- <span className="text-[10px] text-[#777777] block mt-0.5">{tone.desc}</span>
- </button>
- );
- })}
- </div>
- </div>
+ <button
+ type="button"
+ onClick={() => handleChange('modernAccent', 'custom')}
+ className={`flex items-center gap-2 px-2.5 py-2 rounded text-xs transition-colors cursor-pointer ${
+ localSettings.modernAccent === 'custom'
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'bg-[#161616] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
+ >
+ <span
+ className="w-3 h-3 rounded-full shrink-0"
+ style={{ backgroundColor: localSettings.modernCustomColor || '#e5e5e5' }}
+ />
+ <span className="truncate">Custom</span>
+ {localSettings.modernAccent === 'custom' && (
+ <Check className="w-3 h-3 ml-auto text-[var(--accent)]" />
+ )}
+ </button>
</div>
- )}
- {/* Toggles */}
- <div className="bg-[#1a1a1c] border border-[#333336] rounded-md p-3.5 space-y-3">
- <span className="text-[11px] font-semibold text-[#aaaaaa] uppercase tracking-wider block">
- Workspace Overlays
- </span>
-
- <label className="flex items-center justify-between cursor-pointer py-1">
- <div>
- <span className="text-xs text-white block">Canvas Transparency Checkerboard</span>
- <span className="text-[10px] text-[#888888]">Display pattern behind transparent layers</span>
- </div>
+ {/* Custom Hex & Native Picker */}
+ <div className="flex items-center gap-2.5 p-2.5 rounded bg-[#161616]">
<input
- type="checkbox"
- checked={localSettings.showCheckerboard}
- onChange={(e) => handleChange('showCheckerboard', e.target.checked)}
- className="w-4 h-4 accent-[#007acc] cursor-pointer"
+ type="color"
+ value={resolvedAccent}
+ onChange={(e) => {
+ const hex = e.target.value;
+ const updated: AppSettings = {
+ ...localSettings,
+ themePreset: 'modern',
+ modernAccent: 'custom',
+ modernCustomColor: hex,
+ };
+ setLocalSettings(updated);
+ onUpdateSettings(updated);
+ }}
+ className="w-7 h-7 rounded cursor-pointer bg-transparent border-0 p-0 shrink-0"
+ title="Pick Custom Accent Color"
/>
- </label>
-
- <label className="flex items-center justify-between cursor-pointer py-1 border-t border-[#2e2e32]">
- <div>
- <span className="text-xs text-white block">Status Bar Cursor Coordinates (X, Y)</span>
- <span className="text-[10px] text-[#888888]">Live cursor pixel position in bottom bar</span>
+ <div className="flex-1">
+ <span className="text-[10px] text-[#8a8a8a] block mb-0.5">Custom Hex</span>
+ <input
+ type="text"
+ value={
+ localSettings.modernAccent === 'custom'
+ ? localSettings.modernCustomColor
+ : resolvedAccent
+ }
+ onChange={(e) => {
+ const val = e.target.value;
+ const updated: AppSettings = {
+ ...localSettings,
+ themePreset: 'modern',
+ modernAccent: 'custom',
+ modernCustomColor: val,
+ };
+ setLocalSettings(updated);
+ if (/^#[0-9a-fA-F]{6}$/i.test(val)) {
+ onUpdateSettings(updated);
+ }
+ }}
+ placeholder="#e5e5e5"
+ maxLength={7}
+ className="w-full bg-[#202020] px-2 py-1 rounded font-mono text-xs text-[#e5e5e5]"
+ />
</div>
- <input
- type="checkbox"
- checked={localSettings.showCursorCoordinates}
- onChange={(e) => handleChange('showCursorCoordinates', e.target.checked)}
- className="w-4 h-4 accent-[#007acc] cursor-pointer"
- />
- </label>
+ </div>
+ </section>
- <label className="flex items-center justify-between cursor-pointer py-1 border-t border-[#2e2e32]">
- <div>
- <span className="text-xs text-white block">Status Bar Stylus Pressure Gauge</span>
- <span className="text-[10px] text-[#888888]">Display real-time stylus pressure %</span>
- </div>
- <input
- type="checkbox"
- checked={localSettings.showPressureInStatusBar}
- onChange={(e) => handleChange('showPressureInStatusBar', e.target.checked)}
- className="w-4 h-4 accent-[#007acc] cursor-pointer"
- />
- </label>
- </div>
- </div>
+ {/* User Profile */}
+ <section className="space-y-2">
+ <h3 className="text-xs font-medium text-[#e5e5e5]">Artist Name</h3>
+ <input
+ type="text"
+ value={localSettings.userName || ''}
+ onChange={(e) => {
+ const val = e.target.value;
+ handleChange('userName', val);
+ try {
+ localStorage.setItem('sora_paint_nickname', val);
+ } catch {
+ // ignore
+ }
+ }}
+ placeholder="Artist"
+ className="w-full bg-[#161616] px-3 py-1.5 rounded text-xs text-[#e5e5e5] placeholder-[#8a8a8a]/50"
+ />
+ </section>
+
+ {/* Overlays */}
+ <section className="space-y-2">
+ <h3 className="text-xs font-medium text-[#e5e5e5]">Viewport Overlays</h3>
+ <div className="space-y-1 bg-[#161616] rounded p-2.5">
+ <label className="flex items-center justify-between py-1 cursor-pointer">
+ <span className="text-xs text-[#e5e5e5]">Transparency Checkerboard</span>
+ <input
+ type="checkbox"
+ checked={localSettings.showCheckerboard}
+ onChange={(e) => handleChange('showCheckerboard', e.target.checked)}
+ />
+ </label>
+ <label className="flex items-center justify-between py-1 cursor-pointer">
+ <span className="text-xs text-[#e5e5e5]">Cursor Coordinates</span>
+ <input
+ type="checkbox"
+ checked={localSettings.showCursorCoordinates}
+ onChange={(e) => handleChange('showCursorCoordinates', e.target.checked)}
+ />
+ </label>
+ <label className="flex items-center justify-between py-1 cursor-pointer">
+ <span className="text-xs text-[#e5e5e5]">Stylus Pressure Readout</span>
+ <input
+ type="checkbox"
+ checked={localSettings.showPressureInStatusBar}
+ onChange={(e) => handleChange('showPressureInStatusBar', e.target.checked)}
+ />
+ </label>
+ </div>
+ </section>
+ </>
)}
- {/* 2. Canvas Defaults */}
{activeTab === 'canvas' && (
- <div className="space-y-5">
- <div>
- <h3 className="text-sm font-semibold text-white">Default Canvas Settings</h3>
- <p className="text-[11px] text-[#888888]">Default dimensions, resolution, and color mode for new files</p>
- </div>
-
- {/* Default Dimensions */}
- <div className="bg-[#1a1a1c] border border-[#333336] rounded-md p-3.5 space-y-3">
- <span className="text-[11px] font-semibold text-[#aaaaaa] uppercase tracking-wider block">
- Default Dimensions
- </span>
- <div className="grid grid-cols-2 gap-3">
+ <>
+ <section className="space-y-2">
+ <h3 className="text-xs font-medium text-[#e5e5e5]">Default Dimensions</h3>
+ <div className="grid grid-cols-2 gap-2.5">
<div className="space-y-1">
- <label className="text-[11px] text-[#888888]">Default Width (px)</label>
+ <label className="text-[11px] text-[#8a8a8a]">Width (px)</label>
<input
type="number"
min="64"
max="16384"
value={localSettings.defaultWidth}
onChange={(e) => handleChange('defaultWidth', Number(e.target.value))}
- className="w-full bg-[#222225] border border-[#3e3e42] rounded px-3 py-1.5 font-mono text-sm text-white focus:outline-hidden focus:border-[#007acc]"
+ className="w-full bg-[#161616] px-2.5 py-1.5 rounded font-mono text-xs text-[#e5e5e5]"
/>
</div>
<div className="space-y-1">
- <label className="text-[11px] text-[#888888]">Default Height (px)</label>
+ <label className="text-[11px] text-[#8a8a8a]">Height (px)</label>
<input
type="number"
min="64"
max="16384"
value={localSettings.defaultHeight}
onChange={(e) => handleChange('defaultHeight', Number(e.target.value))}
- className="w-full bg-[#222225] border border-[#3e3e42] rounded px-3 py-1.5 font-mono text-sm text-white focus:outline-hidden focus:border-[#007acc]"
+ className="w-full bg-[#161616] px-2.5 py-1.5 rounded font-mono text-xs text-[#e5e5e5]"
/>
</div>
</div>
+ </section>
- <label className="flex items-center space-x-2 pt-1 cursor-pointer">
- <input
- type="checkbox"
- checked={localSettings.defaultLockRatio}
- onChange={(e) => handleChange('defaultLockRatio', e.target.checked)}
- className="w-4 h-4 accent-[#007acc] cursor-pointer"
- />
- <span className="text-xs text-[#cccccc]">Keep aspect ratio locked by default</span>
- </label>
- </div>
-
- {/* Default DPI */}
- <div className="bg-[#1a1a1c] border border-[#333336] rounded-md p-3.5 space-y-2.5">
- <span className="text-[11px] font-semibold text-[#aaaaaa] uppercase tracking-wider block">
- Default Resolution (DPI)
- </span>
- <div className="grid grid-cols-3 sm:grid-cols-6 gap-1.5">
+ <section className="space-y-2">
+ <h3 className="text-xs font-medium text-[#e5e5e5]">Resolution (DPI)</h3>
+ <div className="grid grid-cols-6 gap-1.5">
{DPI_PRESETS.map((p) => {
- const isSelected = localSettings.defaultDpi === p.dpi;
+ const selected = localSettings.defaultDpi === p.dpi;
return (
<button
key={p.dpi}
type="button"
onClick={() => handleChange('defaultDpi', p.dpi)}
- className={`flex flex-col items-center justify-center py-1 px-1 rounded border transition-colors ${
- isSelected
- ? 'bg-[#007acc] border-[#007acc] text-white font-medium'
- : 'bg-[#252528] border-[#38383c] text-[#bbbbbb] hover:bg-[#303034] hover:text-white'
+ className={`py-1.5 rounded font-mono text-xs cursor-pointer transition-colors ${
+ selected
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'bg-[#161616] text-[#8a8a8a] hover:text-[#e5e5e5]'
}`}
>
- <span className="font-mono text-xs font-semibold">{p.dpi}</span>
- <span className="text-[9px] opacity-75">{p.desc}</span>
+ {p.dpi}
</button>
);
})}
</div>
- </div>
+ </section>
- {/* Default Color Mode */}
- <div className="bg-[#1a1a1c] border border-[#333336] rounded-md p-3.5 space-y-2.5">
- <span className="text-[11px] font-semibold text-[#aaaaaa] uppercase tracking-wider block">
- Default Color Mode
- </span>
- <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
+ <section className="space-y-2">
+ <h3 className="text-xs font-medium text-[#e5e5e5]">Color Mode</h3>
+ <div className="grid grid-cols-3 gap-1.5">
{(['color', 'grayscale', 'monochrome'] as CanvasColorMode[]).map((mode) => {
- const isSelected = localSettings.defaultColorMode === mode;
+ const selected = localSettings.defaultColorMode === mode;
return (
<button
key={mode}
type="button"
onClick={() => handleChange('defaultColorMode', mode)}
- className={`p-2.5 rounded border text-left transition-all ${
- isSelected
- ? 'border-[#007acc] bg-[#007acc]/15 text-white ring-1 ring-[#007acc]'
- : 'border-[#38383c] bg-[#222225] text-[#aaaaaa] hover:border-[#4a4a4e]'
+ className={`p-2 rounded text-left capitalize cursor-pointer transition-colors ${
+ selected
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'bg-[#161616] text-[#8a8a8a] hover:text-[#e5e5e5]'
}`}
>
- <div className="font-semibold text-xs text-white capitalize mb-0.5">
- {mode === 'monochrome' ? 'Monochrome (Manga)' : mode}
- </div>
- <div className="text-[10px] text-[#888888]">
- {mode === 'color'
- ? 'Full RGB palette'
- : mode === 'grayscale'
- ? '256 gray shades'
- : '1-bit black & white'}
- </div>
+ {mode}
</button>
);
})}
</div>
- </div>
- </div>
+ </section>
+
+ <section className="space-y-2">
+ <div className="flex items-center justify-between">
+ <h3 className="text-xs font-medium text-[#e5e5e5]">Tile RAM Budget</h3>
+ <span className="font-mono text-xs text-[#e5e5e5]">
+ {localSettings.tileMemoryBudgetMb || 1024} MB
+ </span>
+ </div>
+ <input
+ type="range"
+ min="512"
+ max="4096"
+ step="128"
+ value={localSettings.tileMemoryBudgetMb || 1024}
+ onChange={(e) => handleChange('tileMemoryBudgetMb', Number(e.target.value))}
+ className="w-full"
+ />
+ </section>
+ </>
)}
- {/* 3. Brush & Stylus */}
{activeTab === 'brush' && (
- <div className="space-y-5">
- <div>
- <h3 className="text-sm font-semibold text-white">Brush & Stylus Inking</h3>
- <p className="text-[11px] text-[#888888]">Configure stroke stabilization, pressure response, and history buffer</p>
- </div>
-
- {/* Stabilization Slider */}
- <div className="bg-[#1a1a1c] border border-[#333336] rounded-md p-3.5 space-y-2.5">
+ <>
+ <section className="space-y-2">
<div className="flex items-center justify-between">
- <span className="text-[11px] font-semibold text-[#aaaaaa] uppercase tracking-wider">
- Stroke Stabilization Level (Clip Studio Style)
- </span>
- <span className="font-mono text-xs text-[#38bdf8] font-semibold">
+ <h3 className="text-xs font-medium text-[#e5e5e5]">Default Stabilization</h3>
+ <span className="font-mono text-xs text-[#e5e5e5]">
{localSettings.defaultStabilization}
</span>
</div>
@@ -648,176 +450,105 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
max="50"
value={localSettings.defaultStabilization}
onChange={(e) => handleChange('defaultStabilization', Number(e.target.value))}
- className="w-full accent-[#007acc] cursor-pointer"
+ className="w-full"
/>
- <div className="flex justify-between text-[10px] text-[#666666]">
- <span>0 (Raw / No Smoothing)</span>
- <span>15 (Standard Inking)</span>
- <span>50 (Maximum Glide)</span>
- </div>
- </div>
+ </section>
- {/* Toggles */}
- <div className="bg-[#1a1a1c] border border-[#333336] rounded-md p-3.5 space-y-3">
- <label className="flex items-center justify-between cursor-pointer py-1">
- <div>
- <span className="text-xs text-white block">Stylus Pressure Sensitivity</span>
- <span className="text-[10px] text-[#888888]">Taper stroke width by tablet stylus pressure</span>
- </div>
+ <section className="space-y-1 bg-[#161616] rounded p-2.5">
+ <label className="flex items-center justify-between py-1 cursor-pointer">
+ <span className="text-xs text-[#e5e5e5]">Stylus Pressure Sensitivity</span>
<input
type="checkbox"
checked={localSettings.usePressureByDefault}
onChange={(e) => handleChange('usePressureByDefault', e.target.checked)}
- className="w-4 h-4 accent-[#007acc] cursor-pointer"
/>
</label>
-
- <label className="flex items-center justify-between cursor-pointer py-1 border-t border-[#2e2e32]">
- <div>
- <span className="text-xs text-white block">Bézier Quadratic Curve Smoothing</span>
- <span className="text-[10px] text-[#888888]">Render smooth interpolated inking curves</span>
- </div>
+ <label className="flex items-center justify-between py-1 cursor-pointer">
+ <span className="text-xs text-[#e5e5e5]">Bezier Curve Smoothing</span>
<input
type="checkbox"
checked={localSettings.smoothingEnabled}
onChange={(e) => handleChange('smoothingEnabled', e.target.checked)}
- className="w-4 h-4 accent-[#007acc] cursor-pointer"
/>
</label>
- </div>
+ </section>
- {/* Max History Steps */}
- <div className="bg-[#1a1a1c] border border-[#333336] rounded-md p-3.5 space-y-2.5">
- <span className="text-[11px] font-semibold text-[#aaaaaa] uppercase tracking-wider block">
- Max Undo History States
- </span>
- <div className="grid grid-cols-4 gap-2">
+ <section className="space-y-2">
+ <h3 className="text-xs font-medium text-[#e5e5e5]">Undo History Limit</h3>
+ <div className="grid grid-cols-4 gap-1.5">
{[25, 50, 75, 100].map((steps) => {
- const isSelected = localSettings.maxHistorySteps === steps;
+ const selected = localSettings.maxHistorySteps === steps;
return (
<button
key={steps}
type="button"
onClick={() => handleChange('maxHistorySteps', steps)}
- className={`py-1.5 px-3 rounded border text-center font-mono text-xs transition-colors ${
- isSelected
- ? 'bg-[#007acc] border-[#007acc] text-white font-medium shadow-xs'
- : 'bg-[#252528] border-[#38383c] text-[#bbbbbb] hover:bg-[#303034] hover:text-white'
+ className={`py-1.5 rounded font-mono text-xs cursor-pointer transition-colors ${
+ selected
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'bg-[#161616] text-[#8a8a8a] hover:text-[#e5e5e5]'
}`}
>
- {steps} steps
+ {steps}
</button>
);
})}
</div>
- </div>
- </div>
+ </section>
+ </>
)}
- {/* 4. Shortcuts */}
{activeTab === 'shortcuts' && (
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <div>
- <h3 className="text-sm font-semibold text-white">Keyboard Shortcuts</h3>
- <p className="text-[11px] text-[#888888]">Quick reference for all application hotkeys</p>
- </div>
-
- {/* Search */}
- <div className="relative w-48">
- <Search className="w-3.5 h-3.5 text-[#666666] absolute left-2.5 top-1/2 -translate-y-1/2" />
- <input
- type="text"
- placeholder="Search..."
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- className="w-full bg-[#18181a] border border-[#3c3c40] rounded pl-8 pr-2.5 py-1 text-xs text-white focus:outline-hidden focus:border-[#007acc]"
- />
- </div>
+ <div className="space-y-3">
+ <div className="relative">
+ <Search className="w-3.5 h-3.5 text-[#8a8a8a] absolute left-2.5 top-1/2 -translate-y-1/2" />
+ <input
+ type="text"
+ placeholder="Filter shortcuts..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ className="w-full bg-[#161616] rounded pl-8 pr-3 py-1.5 text-xs text-[#e5e5e5] placeholder-[#8a8a8a]"
+ />
</div>
-
- <div className="bg-[#1a1a1c] border border-[#333336] rounded-md overflow-hidden">
- <div className="max-h-[360px] overflow-y-auto divide-y divide-[#2a2a2e]">
- {filteredShortcuts.map((row, idx) => (
- <div
- key={idx}
- className="flex items-center justify-between px-3.5 py-2 hover:bg-[#222225] transition-colors"
- >
- <div className="flex flex-col pr-3">
- <span className="text-xs text-white font-medium">{row.action}</span>
- <span className="text-[10px] text-[#888888]">{row.desc}</span>
- </div>
- <kbd className="px-2 py-0.5 rounded bg-[#252528] border border-[#3e3e42] font-mono text-[11px] text-[#38bdf8] whitespace-nowrap shadow-xs">
- {row.shortcut}
- </kbd>
- </div>
- ))}
- {filteredShortcuts.length === 0 && (
- <div className="p-6 text-center text-[#777777] italic text-xs">
- No shortcuts matching "{searchQuery}"
+ <div className="space-y-0.5">
+ {filteredShortcuts.map((row, idx) => (
+ <div
+ key={idx}
+ className="flex items-center justify-between px-2.5 py-1.5 rounded hover:bg-[#2c2c2c]/50"
+ >
+ <div>
+ <div className="text-xs text-[#e5e5e5]">{row.action}</div>
+ <div className="text-[10px] text-[#8a8a8a]">{row.desc}</div>
</div>
- )}
- </div>
+ <kbd className="px-2 py-0.5 rounded bg-[#161616] font-mono text-[10px] text-[#e5e5e5]">
+ {row.shortcut}
+ </kbd>
+ </div>
+ ))}
</div>
</div>
)}
- {/* 5. About */}
{activeTab === 'about' && (
<div className="space-y-4">
- <div className="bg-[#1a1a1c] border border-[#333336] rounded-md p-5 flex flex-col items-center text-center space-y-3">
- <div className="w-16 h-16 flex items-center justify-center">
- <img
- src="/app-icon.png"
- alt="Ink Studio"
- className="w-16 h-16 object-contain drop-shadow-md select-none"
- />
- </div>
+ <div className="p-4 rounded bg-[#161616] flex items-center gap-3.5">
+ <img
+ src="/app-icon.png"
+ alt="Ink Studio"
+ className="w-10 h-10 object-contain shrink-0"
+ />
<div>
- <h2 className="text-lg font-bold text-white tracking-wide">Ink Studio</h2>
- <span className="text-[11px] font-mono text-[#38bdf8]">Version 0.1.0 • Built with Tauri & React</span>
- </div>
- <p className="text-xs text-[#aaaaaa] max-w-md leading-relaxed">
- A professional-grade desktop graphics editor & manga inking studio featuring a full layered workflow,
- Photoshop PSD & Clip Studio Paint CSP compatibility, smooth tablet stylus pressure, and infinite zoom/rotation.
- </p>
- </div>
-
- <div className="grid grid-cols-2 gap-3 text-xs">
- <div className="bg-[#1a1a1c] border border-[#333336] rounded p-3 space-y-1">
- <span className="text-[11px] font-semibold text-[#888888] uppercase tracking-wider block">
- Supported Import Formats
- </span>
- <p className="text-[#cccccc] font-mono text-[11px]">
- .psd, .psb, .clip, .csp, .sora, .ink, .png, .jpg, .jpeg, .webp, .bmp, .gif, .svg
- </p>
- </div>
- <div className="bg-[#1a1a1c] border border-[#333336] rounded p-3 space-y-1">
- <span className="text-[11px] font-semibold text-[#888888] uppercase tracking-wider block">
- Supported Export Formats
- </span>
- <p className="text-[#cccccc] font-mono text-[11px]">
- PSD (Layered), Ink Studio Project (.sora / .ink), PNG, JPG, WebP
- </p>
+ <h2 className="text-sm font-semibold text-[#e5e5e5]">Ink Studio</h2>
+ <p className="text-[11px] font-mono text-[#8a8a8a]">v0.1.0</p>
</div>
</div>
+ <p className="text-xs text-[#8a8a8a] leading-relaxed">
+ Digital drawing and manga studio supporting layered PSD/CSP workflows, GPU tile compositing, stylus pressure dynamics, and 1-bit monochrome inking.
+ </p>
</div>
)}
</div>
</div>
-
- {/* Footer */}
- <div className="flex items-center justify-between px-4 py-2.5 bg-[#3a3a3d] border-t border-[#242426] shrink-0">
- <span className="text-[11px] text-[#8c8c92]">Preferences save automatically</span>
- <button
- type="button"
- onClick={onClose}
- className="flex items-center space-x-1.5 px-4 py-1.5 rounded-[2px] bg-gradient-to-b from-[#56565a] to-[#424245] hover:from-[#626266] hover:to-[#4b4b4e] border border-[#242426] text-xs font-medium text-[#f0f0f4] shadow-[inset_0_1px_0_rgba(255,255,255,0.18),0_1px_1px_rgba(0,0,0,0.3)] cursor-pointer ml-auto"
- >
- <Check className="w-3.5 h-3.5 text-emerald-400" />
- <span>Close</span>
- </button>
- </div>
</div>
</div>
);
diff --git a/src/components/WelcomeScreen.tsx b/src/components/WelcomeScreen.tsx
index cf323cc..71be334 100644
--- a/src/components/WelcomeScreen.tsx
+++ b/src/components/WelcomeScreen.tsx
@@ -5,7 +5,6 @@ import {
Search,
X,
Star,
- Trash2,
FileText,
} from 'lucide-react';
import {
@@ -34,9 +33,7 @@ export const WelcomeScreen: React.FC<WelcomeScreenProps> = ({
onOpenFile,
onSelectRecentDocument,
showToast,
- themePreset = 'vintage-manga',
}) => {
- const displayName = userName?.trim() || 'Artist';
const [documents, setDocuments] = useState<RecentDocument[]>([]);
const [searchQuery, setSearchQuery] = useState<string>('');
const [deleteTargetDoc, setDeleteTargetDoc] = useState<RecentDocument | null>(null);
@@ -58,7 +55,7 @@ export const WelcomeScreen: React.FC<WelcomeScreenProps> = ({
setDocuments((prev) =>
prev.map((d) => (d.id === doc.id ? { ...d, isStarred: newStarred } : d))
);
- showToast(newStarred ? `Starred: ${doc.title}` : `Unstarred: ${doc.title}`);
+ showToast(newStarred ? `Starred ${doc.title}` : `Unstarred ${doc.title}`);
};
const handleOpenDelete = (doc: RecentDocument, e: React.MouseEvent) => {
@@ -80,11 +77,7 @@ export const WelcomeScreen: React.FC<WelcomeScreenProps> = ({
const result = await permanentlyDeleteDocument(doc);
setDocuments((prev) => prev.filter((d) => d.id !== doc.id));
setDeleteTargetDoc(null);
- showToast(
- result.success
- ? `Deleted "${doc.title}"`
- : `Removed from list (file not found on disk)`
- );
+ showToast(result.success ? `Deleted "${doc.title}"` : `Removed from list`);
};
const cleanQuery = searchQuery.trim().toLowerCase();
@@ -97,234 +90,72 @@ export const WelcomeScreen: React.FC<WelcomeScreenProps> = ({
});
const starredDocs = filtered.filter((d) => d.isStarred);
- const regularDocs = filtered;
-
- if (themePreset === 'modern') {
- return (
- <div className="flex-1 flex flex-col h-full bg-[#18191d] text-white/90 overflow-y-auto select-none font-sans">
- {/* Main Content Container matching Reference 1 */}
- <div className="max-w-4xl w-full mx-auto px-6 py-12 flex-1 flex flex-col">
- {/* Header Row: Greeting & Action Buttons */}
- <div className="flex items-start justify-between gap-6 mb-8">
- <div>
- <h1 className="text-3xl font-light tracking-tight text-white/95">
- Welcome back{userName?.trim() ? `, ${userName.trim()}` : ', my Lord'}.
- </h1>
- <p className="text-xs text-white/40 mt-1 font-mono tracking-wide">
- bdt.greeting
- </p>
- </div>
-
- <div className="flex items-center gap-2.5 shrink-0 pt-1">
- <button
- type="button"
- onClick={onNewDocument}
- className="flex items-center gap-1.5 px-4 py-2 rounded-lg bg-white/[0.08] hover:bg-white/[0.14] active:scale-[0.98] border border-white/10 text-xs font-medium text-white shadow-xs transition-all cursor-pointer"
- >
- <FilePlus className="w-3.5 h-3.5 text-white/90" />
- <span>+ New document</span>
- </button>
-
- <button
- type="button"
- onClick={onOpenFile}
- className="flex items-center gap-1.5 px-4 py-2 rounded-lg bg-white/[0.04] hover:bg-white/[0.08] active:scale-[0.98] border border-white/10 text-xs font-medium text-white/80 hover:text-white transition-all cursor-pointer"
- >
- <FolderOpen className="w-3.5 h-3.5 text-white/70" />
- <span>Open file...</span>
- </button>
- </div>
- </div>
-
- {/* Wide Search Bar */}
- <div className="mb-2">
- <div className="relative w-full">
- <input
- type="text"
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- placeholder="Search your documents"
- className="w-full pl-4 pr-10 py-2.5 text-xs bg-[#222328] border border-white/[0.06] rounded-xl text-white placeholder-white/35 outline-none focus:border-white/20 focus:ring-1 focus:ring-white/20 transition-all shadow-inner"
- />
- {searchQuery ? (
- <button
- type="button"
- onClick={() => setSearchQuery('')}
- className="absolute right-3 top-2.5 text-white/40 hover:text-white cursor-pointer"
- >
- <X className="w-3.5 h-3.5" />
- </button>
- ) : (
- <Search className="w-3.5 h-3.5 text-white/30 absolute right-3.5 top-3 pointer-events-none" />
- )}
- </div>
- </div>
-
- <p className="text-[11px] text-white/35 mb-8">
- Removed from Home. Saved files are kept.
- </p>
-
- {/* Starred Section */}
- <div className="mb-8">
- <div className="flex items-center gap-2 mb-3">
- <span className="text-xs font-medium text-white/80">Starred</span>
- <span className="text-[10px] px-2 py-0.5 rounded-full bg-white/[0.06] text-white/50 font-mono">
- {starredDocs.length}
- </span>
- </div>
-
- {starredDocs.length === 0 ? (
- <p className="text-xs text-white/35">
- Star a document below to keep it close.
- </p>
- ) : (
- <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
- {starredDocs.map((doc) => (
- <ModernDocCard
- key={`starred-${doc.id}`}
- doc={doc}
- onSelect={() =>
- onSelectRecentDocument ? onSelectRecentDocument(doc) : onOpenFile()
- }
- onToggleStar={(e) => handleToggleStar(doc, e)}
- onDelete={(e) => handleOpenDelete(doc, e)}
- />
- ))}
- </div>
- )}
- </div>
-
- {/* Recent Documents Section */}
- <div>
- <div className="flex items-center gap-2 mb-3">
- <span className="text-xs font-medium text-white/80">Recent documents</span>
- <span className="text-[10px] px-2 py-0.5 rounded-full bg-white/[0.06] text-white/50 font-mono">
- {regularDocs.length}
- </span>
- </div>
-
- {regularDocs.length === 0 ? (
- <div className="border border-dashed border-white/10 bg-white/[0.02] p-8 text-center rounded-xl">
- <p className="text-xs text-white/40">
- {cleanQuery
- ? 'No documents matched the filter.'
- : 'No recent documents found.'}
- </p>
- </div>
- ) : (
- <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
- {regularDocs.map((doc) => (
- <ModernDocCard
- key={`recent-${doc.id}`}
- doc={doc}
- onSelect={() =>
- onSelectRecentDocument ? onSelectRecentDocument(doc) : onOpenFile()
- }
- onToggleStar={(e) => handleToggleStar(doc, e)}
- onDelete={(e) => handleOpenDelete(doc, e)}
- />
- ))}
- </div>
- )}
- </div>
- </div>
-
- {/* Delete Confirmation Modal */}
- <DeleteDocumentModal
- isOpen={isDeleteModalOpen}
- document={deleteTargetDoc}
- onClose={() => {
- setIsDeleteModalOpen(false);
- setDeleteTargetDoc(null);
- }}
- onHideFromApp={handleHideFromApp}
- onPermanentlyDelete={handlePermanentDelete}
- />
- </div>
- );
- }
return (
- <div className="flex-1 flex flex-col h-full bg-[#3c3c3f] text-[#d6d6da] overflow-y-auto select-none font-sans">
- {/* Top Utility Header */}
- <div className="border-b border-[#242426] bg-[#444447] px-6 py-3 shrink-0 shadow-[inset_0_1px_0_rgba(255,255,255,0.12)]">
- <div className="max-w-6xl mx-auto flex items-center justify-between gap-4">
- <div className="flex items-center space-x-3">
- <span className="text-sm font-semibold text-[#f0f0f4] tracking-wide">
- Ink Studio
- </span>
- <span className="text-[#68686d]">|</span>
- <span className="text-xs text-[#a0a0a5]">Recent Work</span>
+ <div className="flex-1 flex flex-col h-full bg-[#161616] text-[#e5e5e5] overflow-y-auto select-none">
+ <div className="max-w-4xl w-full mx-auto px-6 py-10 flex-1 flex flex-col space-y-8">
+ <div className="flex items-center justify-between gap-4">
+ <div>
+ <h1 className="text-lg font-medium text-[#e5e5e5]">
+ {userName?.trim() ? `Welcome, ${userName.trim()}` : 'Ink Studio'}
+ </h1>
+ <p className="text-xs text-[#8a8a8a] mt-0.5">Recent projects and canvases</p>
</div>
- <div className="flex items-center space-x-2">
+ <div className="flex items-center gap-2 shrink-0">
<button
type="button"
onClick={onNewDocument}
- className="flex items-center space-x-1.5 px-3 py-1.5 rounded-[2px] bg-gradient-to-b from-[#58585c] to-[#424245] hover:from-[#626266] hover:to-[#4b4b4e] active:from-[#3a3a3d] active:to-[#2e2e30] border border-[#242426] text-xs font-medium text-[#f0f0f4] shadow-[inset_0_1px_0_rgba(255,255,255,0.18),0_1px_1px_rgba(0,0,0,0.3)] cursor-pointer"
+ className="flex items-center gap-1.5 px-3.5 py-1.5 rounded text-xs font-medium transition-opacity hover:opacity-90 cursor-pointer"
+ style={{
+ backgroundColor: 'var(--accent)',
+ color: 'var(--accent-contrast)',
+ }}
>
- <FilePlus className="w-3.5 h-3.5 text-[#93c5fd]" />
+ <FilePlus className="w-3.5 h-3.5" />
<span>New Canvas</span>
</button>
<button
type="button"
onClick={onOpenFile}
- className="flex items-center space-x-1.5 px-3 py-1.5 rounded-[2px] bg-gradient-to-b from-[#58585c] to-[#424245] hover:from-[#626266] hover:to-[#4b4b4e] active:from-[#3a3a3d] active:to-[#2e2e30] border border-[#242426] text-xs font-medium text-[#f0f0f4] shadow-[inset_0_1px_0_rgba(255,255,255,0.18),0_1px_1px_rgba(0,0,0,0.3)] cursor-pointer"
+ className="flex items-center gap-1.5 px-3.5 py-1.5 rounded bg-[#202020] hover:bg-[#2c2c2c] text-xs font-medium text-[#e5e5e5] transition-colors cursor-pointer"
>
- <FolderOpen className="w-3.5 h-3.5 text-[#facc15]" />
- <span>Open File...</span>
+ <FolderOpen className="w-3.5 h-3.5 text-[#8a8a8a]" />
+ <span>Open...</span>
</button>
</div>
</div>
- </div>
- {/* Main Container */}
- <div className="max-w-6xl w-full mx-auto p-6 space-y-6 flex-1">
- <div>
- <h1 className="text-base font-semibold text-[#f0f0f4] tracking-wide">
- Welcome back, {displayName}
- </h1>
- </div>
-
- {/* Search Bar */}
- <div className="flex items-center justify-between gap-4 pb-2 border-b border-[#2d2d30]">
- <div className="relative w-72">
- <Search className="w-3.5 h-3.5 text-[#737378] absolute left-2.5 top-2 pointer-events-none" />
- <input
- type="text"
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- placeholder="Filter files..."
- className="w-full pl-8 pr-7 py-1 text-xs bg-[#2b2b2e] border border-[#1e1e20] rounded-[2px] text-[#f0f0f4] placeholder-[#707075] outline-none focus:border-[#4a8fc7] shadow-[inset_1px_1px_2px_rgba(0,0,0,0.5)]"
- />
- {searchQuery && (
- <button
- type="button"
- onClick={() => setSearchQuery('')}
- className="absolute right-2 top-2 text-[#88888d] hover:text-white"
- >
- <X className="w-3 h-3" />
- </button>
- )}
- </div>
-
- <div className="text-[11px] font-mono text-[#8c8c92]">
- {filtered.length} {filtered.length === 1 ? 'file' : 'files'}
- </div>
+ {/* Search */}
+ <div className="relative w-full">
+ <Search className="w-3.5 h-3.5 text-[#8a8a8a] absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none" />
+ <input
+ type="text"
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ placeholder="Search documents..."
+ className="w-full pl-9 pr-8 py-2 text-xs bg-[#202020] rounded-md text-[#e5e5e5] placeholder-[#8a8a8a]"
+ />
+ {searchQuery && (
+ <button
+ type="button"
+ onClick={() => setSearchQuery('')}
+ className="absolute right-2.5 top-1/2 -translate-y-1/2 text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer"
+ >
+ <X className="w-3.5 h-3.5" />
+ </button>
+ )}
</div>
- {/* Starred Section */}
{starredDocs.length > 0 && (
<section className="space-y-3">
- <div className="flex items-center space-x-1.5 text-xs font-semibold text-[#c8c8cc] uppercase tracking-wider">
- <Star className="w-3.5 h-3.5 text-amber-400 fill-amber-400" />
- <span>Favorites ({starredDocs.length})</span>
+ <div className="text-[11px] font-medium text-[#8a8a8a] uppercase tracking-wider">
+ Starred ({starredDocs.length})
</div>
-
- <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
+ <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
{starredDocs.map((doc) => (
- <VintageDocCard
+ <DocCard
key={`starred-${doc.id}`}
doc={doc}
onSelect={() =>
@@ -338,24 +169,21 @@ export const WelcomeScreen: React.FC<WelcomeScreenProps> = ({
</section>
)}
- {/* Recent Section */}
<section className="space-y-3">
- <div className="text-xs font-semibold text-[#c8c8cc] uppercase tracking-wider">
- All Documents ({regularDocs.length})
+ <div className="text-[11px] font-medium text-[#8a8a8a] uppercase tracking-wider">
+ Recent ({filtered.length})
</div>
- {regularDocs.length === 0 ? (
- <div className="border border-dashed border-[#333336] bg-[#323235] p-8 text-center rounded-[2px]">
- <p className="text-xs text-[#8c8c92]">
- {cleanQuery
- ? 'No documents matched the filter.'
- : 'No recent documents found.'}
+ {filtered.length === 0 ? (
+ <div className="bg-[#202020] p-8 text-center rounded-md">
+ <p className="text-xs text-[#8a8a8a]">
+ {cleanQuery ? 'No matching documents.' : 'No recent documents yet.'}
</p>
</div>
) : (
- <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
- {regularDocs.map((doc) => (
- <VintageDocCard
+ <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
+ {filtered.map((doc) => (
+ <DocCard
key={`recent-${doc.id}`}
doc={doc}
onSelect={() =>
@@ -370,7 +198,6 @@ export const WelcomeScreen: React.FC<WelcomeScreenProps> = ({
</section>
</div>
- {/* Delete Confirmation Modal */}
<DeleteDocumentModal
isOpen={isDeleteModalOpen}
document={deleteTargetDoc}
@@ -385,155 +212,55 @@ export const WelcomeScreen: React.FC<WelcomeScreenProps> = ({
);
};
-interface VintageDocCardProps {
+interface DocCardProps {
doc: RecentDocument;
onSelect: () => void;
onToggleStar: (e: React.MouseEvent) => void;
onDelete: (e: React.MouseEvent) => void;
}
-const VintageDocCard: React.FC<VintageDocCardProps> = ({
- doc,
- onSelect,
- onToggleStar,
- onDelete,
-}) => {
- return (
- <div
- onClick={onSelect}
- className="group relative flex flex-col bg-[#444447] border border-[#242426] hover:border-[#5a5a60] rounded-[2px] p-2 cursor-pointer shadow-[0_1px_2px_rgba(0,0,0,0.3)] transition-colors"
- title={`${doc.title}\n${doc.path}`}
- >
- {/* Thumbnail Area */}
- <div className="relative aspect-[4/3] bg-[#222224] border border-[#1a1a1c] overflow-hidden flex items-center justify-center rounded-[1px] mb-2 shadow-[inset_0_1px_2px_rgba(0,0,0,0.6)]">
- {doc.coverUrl ? (
- <img
- src={doc.coverUrl}
- alt={doc.title}
- className="w-full h-full object-cover select-none pointer-events-none"
- />
- ) : (
- <div className="flex flex-col items-center justify-center text-[#58585d] space-y-1">
- <FileText className="w-6 h-6" />
- <span className="text-[9px] font-mono uppercase">{doc.fileType || 'CANVAS'}</span>
- </div>
- )}
-
- {/* Quick Actions (top corners) */}
- <div className="absolute top-1 left-1 flex items-center space-x-1">
- <button
- type="button"
- onClick={onToggleStar}
- title={doc.isStarred ? 'Remove favorite' : 'Add favorite'}
- className={`w-5 h-5 rounded-[2px] border flex items-center justify-center transition-colors cursor-pointer ${
- doc.isStarred
- ? 'bg-[#252528] border-[#38383c] text-amber-400'
- : 'bg-[#252528]/80 border-[#38383c] text-[#77777c] opacity-0 group-hover:opacity-100 hover:text-amber-400 hover:border-[#555]'
- }`}
- >
- <Star
- className={`w-3 h-3 ${doc.isStarred ? 'fill-amber-400' : ''}`}
- />
- </button>
- </div>
-
- <div className="absolute top-1 right-1">
- <button
- type="button"
- onClick={onDelete}
- title="Delete file options"
- className="w-5 h-5 rounded-[2px] bg-[#252528]/80 border border-[#38383c] text-[#88888d] hover:text-rose-400 hover:border-rose-900 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer"
- >
- <Trash2 className="w-3 h-3" />
- </button>
- </div>
- </div>
-
- {/* Meta */}
- <div className="min-w-0 space-y-0.5">
- <div className="text-xs font-medium text-[#f0f0f4] truncate group-hover:text-[#93c5fd]">
- {doc.title}
- </div>
- <div className="flex items-center justify-between text-[10px] text-[#8a8a90] font-mono">
- <span>{formatFileSize(doc.size)}</span>
- <span className="uppercase text-[9px] px-1 py-0.2 bg-[#2d2d30] border border-[#222224] rounded-[1px] text-[#aaa]">
- {doc.fileType || 'CANVAS'}
- </span>
+const DocCard: React.FC<DocCardProps> = ({ doc, onSelect, onToggleStar, onDelete }) => (
+ <div
+ onClick={onSelect}
+ className="group relative flex flex-col bg-[#202020] hover:bg-[#2c2c2c] rounded-md p-2.5 cursor-pointer transition-colors"
+ title={doc.title}
+ >
+ <div className="relative aspect-[4/3] bg-[#161616] overflow-hidden flex items-center justify-center rounded mb-2">
+ {doc.coverUrl ? (
+ <img
+ src={doc.coverUrl}
+ alt={doc.title}
+ className="w-full h-full object-cover select-none pointer-events-none"
+ />
+ ) : (
+ <div className="w-3/4 h-3/4 bg-white rounded-xs flex items-center justify-center text-[#8a8a8a]">
+ <FileText className="w-5 h-5" />
</div>
+ )}
+
+ <div className="absolute top-1.5 right-1.5 flex items-center gap-1">
+ <button
+ type="button"
+ onClick={onToggleStar}
+ className={`w-5 h-5 rounded bg-[#161616]/80 flex items-center justify-center cursor-pointer ${
+ doc.isStarred
+ ? 'text-[var(--accent)]'
+ : 'text-[#8a8a8a] opacity-0 group-hover:opacity-100 hover:text-[#e5e5e5]'
+ }`}
+ >
+ <Star className={`w-3 h-3 ${doc.isStarred ? 'fill-current' : ''}`} />
+ </button>
+ <button
+ type="button"
+ onClick={onDelete}
+ className="w-5 h-5 rounded bg-[#161616]/80 text-[#8a8a8a] hover:text-red-400 flex items-center justify-center opacity-0 group-hover:opacity-100 cursor-pointer"
+ >
+ <X className="w-3 h-3" />
+ </button>
</div>
</div>
- );
-};
-
-const ModernDocCard: React.FC<VintageDocCardProps> = ({
- doc,
- onSelect,
- onToggleStar,
- onDelete,
-}) => {
- return (
- <div
- onClick={onSelect}
- className="group relative flex flex-col bg-[#222328] hover:bg-[#282930] border border-white/[0.07] hover:border-white/20 rounded-xl p-3 cursor-pointer transition-all duration-150 shadow-md hover:shadow-xl"
- title={`${doc.title}\n${doc.path}`}
- >
- {/* Thumbnail Area - Aspect Square with Checkerboard Canvas Preview */}
- <div
- className="relative aspect-square border border-white/[0.05] overflow-hidden flex items-center justify-center rounded-lg mb-2.5"
- style={{
- background:
- 'repeating-conic-gradient(#202126 0% 25%, #17181c 0% 50%) 50% / 12px 12px',
- }}
- >
- {doc.coverUrl ? (
- <img
- src={doc.coverUrl}
- alt={doc.title}
- className="w-full h-full object-cover select-none pointer-events-none group-hover:scale-102 transition-transform duration-200"
- />
- ) : (
- <div className="w-3/4 h-3/4 bg-white/90 rounded-sm shadow-md flex flex-col items-center justify-center text-zinc-400">
- <FileText className="w-6 h-6 stroke-[1.5]" />
- </div>
- )}
-
- {/* Top Right Quick Actions: Close (X) and Star */}
- <div className="absolute top-1.5 right-1.5 flex items-center space-x-1">
- <button
- type="button"
- onClick={onDelete}
- title="Remove from recents"
- className="w-5 h-5 rounded-md bg-black/60 hover:bg-black/90 text-white/50 hover:text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all backdrop-blur-xs cursor-pointer"
- >
- <X className="w-3 h-3" />
- </button>
- <button
- type="button"
- onClick={onToggleStar}
- title={doc.isStarred ? 'Remove favorite' : 'Add favorite'}
- className={`w-5 h-5 rounded-md flex items-center justify-center transition-all cursor-pointer ${
- doc.isStarred
- ? 'bg-black/70 text-amber-400 backdrop-blur-xs'
- : 'bg-black/60 text-white/50 opacity-0 group-hover:opacity-100 hover:text-amber-400 backdrop-blur-xs'
- }`}
- >
- <Star className={`w-3 h-3 ${doc.isStarred ? 'fill-amber-400' : ''}`} />
- </button>
- </div>
- </div>
- {/* Meta matching Reference 1 */}
- <div className="min-w-0 space-y-0.5">
- <div className="text-xs font-semibold text-white/95 truncate">
- {doc.title}
- </div>
- <div className="text-[10px] text-white/45 truncate">
- Previous session · Last worked on {formatFileSize(doc.size)}
- </div>
- <div className="text-[9px] text-white/30 font-mono truncate">
- {doc.path}
- </div>
- </div>
- </div>
- );
-};
+ <div className="text-xs font-medium text-[#e5e5e5] truncate">{doc.title}</div>
+ <div className="text-[10px] font-mono text-[#8a8a8a] mt-0.5">{formatFileSize(doc.size)}</div>
+ </div>
+);
diff --git a/src/components/WindowControls.tsx b/src/components/WindowControls.tsx
index 4c45d02..20eef52 100644
--- a/src/components/WindowControls.tsx
+++ b/src/components/WindowControls.tsx
@@ -6,7 +6,7 @@ interface WindowControlsProps {
themePreset?: ThemePreset;
}
-export const WindowControls: React.FC<WindowControlsProps> = ({ themePreset: _themePreset = 'vintage-manga' }) => {
+export const WindowControls: React.FC<WindowControlsProps> = () => {
const [isTauri, setIsTauri] = useState(false);
const [isMaximized, setIsMaximized] = useState(false);
@@ -38,155 +38,104 @@ export const WindowControls: React.FC<WindowControlsProps> = ({ themePreset: _th
};
setupWindow();
-
return () => {
if (unlistenResize) unlistenResize();
};
}, []);
- const handleMinimize = useCallback(async (e: React.MouseEvent) => {
- e.stopPropagation();
- try {
- if (isTauri) {
- const { getCurrentWindow } = await import('@tauri-apps/api/window');
- await getCurrentWindow().minimize();
+ const handleMinimize = useCallback(
+ async (e: React.MouseEvent) => {
+ e.stopPropagation();
+ try {
+ if (isTauri) {
+ const { getCurrentWindow } = await import('@tauri-apps/api/window');
+ await getCurrentWindow().minimize();
+ }
+ } catch (err) {
+ console.error('Failed to minimize window:', err);
}
- } catch (err) {
- console.error('Failed to minimize window:', err);
- }
- }, [isTauri]);
+ },
+ [isTauri]
+ );
- const handleToggleMaximize = useCallback(async (e: React.MouseEvent) => {
- e.stopPropagation();
- try {
- if (isTauri) {
- const { getCurrentWindow } = await import('@tauri-apps/api/window');
- const appWindow = getCurrentWindow();
- await appWindow.toggleMaximize();
- const max = await appWindow.isMaximized();
- setIsMaximized(max);
- } else {
- if (!document.fullscreenElement) {
+ const handleToggleMaximize = useCallback(
+ async (e: React.MouseEvent) => {
+ e.stopPropagation();
+ try {
+ if (isTauri) {
+ const { getCurrentWindow } = await import('@tauri-apps/api/window');
+ const appWindow = getCurrentWindow();
+ await appWindow.toggleMaximize();
+ const max = await appWindow.isMaximized();
+ setIsMaximized(max);
+ } else if (!document.fullscreenElement) {
await document.documentElement.requestFullscreen().catch(() => {});
setIsMaximized(true);
} else {
await document.exitFullscreen().catch(() => {});
setIsMaximized(false);
}
+ } catch (err) {
+ console.error('Failed to toggle maximize:', err);
}
- } catch (err) {
- console.error('Failed to toggle maximize:', err);
- }
- }, [isTauri]);
+ },
+ [isTauri]
+ );
- const handleClose = useCallback(async (e: React.MouseEvent) => {
- e.stopPropagation();
- try {
- if (isTauri) {
- const { getCurrentWindow } = await import('@tauri-apps/api/window');
- await getCurrentWindow().close();
- } else {
- window.close();
+ const handleClose = useCallback(
+ async (e: React.MouseEvent) => {
+ e.stopPropagation();
+ try {
+ if (isTauri) {
+ const { getCurrentWindow } = await import('@tauri-apps/api/window');
+ await getCurrentWindow().close();
+ } else {
+ window.close();
+ }
+ } catch (err) {
+ console.error('Failed to close window:', err);
}
- } catch (err) {
- console.error('Failed to close window:', err);
- }
- }, [isTauri]);
-
- if (_themePreset === 'modern') {
- return (
- <div
- className="flex items-center ml-2 shrink-0 select-none"
- data-tauri-drag-region="false"
- style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
- >
- <div className="flex items-center space-x-1.5 px-2 py-1 rounded-full bg-white/[0.04] border border-white/[0.08]">
- {/* Minimize button */}
- <button
- type="button"
- onClick={handleMinimize}
- tabIndex={-1}
- title="Minimize"
- className="w-3 h-3 rounded-full bg-white/20 hover:bg-amber-400 hover:text-black flex items-center justify-center text-white/50 transition-all cursor-pointer"
- >
- <span className="w-1.5 h-[1px] bg-currentColor rounded-full" />
- </button>
-
- {/* Maximize button */}
- <button
- type="button"
- onClick={handleToggleMaximize}
- tabIndex={-1}
- title={isMaximized ? 'Restore' : 'Maximize'}
- className="w-3 h-3 rounded-full bg-white/20 hover:bg-emerald-400 hover:text-black flex items-center justify-center text-white/50 transition-all cursor-pointer"
- >
- <span className="w-1.5 h-1.5 border border-currentColor rounded-[0.5px]" />
- </button>
-
- {/* Close button */}
- <button
- type="button"
- onClick={handleClose}
- tabIndex={-1}
- title="Close"
- className="w-3 h-3 rounded-full bg-white/20 hover:bg-rose-500 hover:text-white flex items-center justify-center text-white/50 transition-all cursor-pointer"
- >
- <svg width="6" height="6" viewBox="0 0 8 8" fill="none" stroke="currentColor" strokeWidth="1.2">
- <path d="M1 1L7 7M7 1L1 7" strokeLinecap="round" />
- </svg>
- </button>
- </div>
- </div>
- );
- }
+ },
+ [isTauri]
+ );
- // Japanese Manga Studio / ComicStudio rounded capsule control pod (Old Studio)
return (
<div
- className="flex items-center ml-2 shrink-0 select-none"
+ className="flex items-center gap-0.5 ml-1 shrink-0 select-none"
data-tauri-drag-region="false"
style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
>
- <div className="bg-[#242426] border border-[#161618] rounded-full px-1.5 py-0.5 shadow-[inset_0_1px_3px_rgba(0,0,0,0.7),0_1px_0_rgba(255,255,255,0.12)] flex items-center space-x-1.5">
- {/* Minimize button */}
- <button
- type="button"
- onClick={handleMinimize}
- tabIndex={-1}
- title="Minimize"
- className="w-4 h-4 rounded-full bg-gradient-to-b from-[#646468] via-[#4a4a4d] to-[#363638] border border-[#202022] shadow-[inset_0_1px_0_rgba(255,255,255,0.35),0_1px_2px_rgba(0,0,0,0.5)] flex items-center justify-center text-[#d0d0d5] hover:text-white hover:brightness-110 active:brightness-90 transition-all cursor-pointer"
- >
- <span className="w-2 h-[1.5px] bg-currentColor rounded-full" />
- </button>
-
- {/* Maximize button */}
- <button
- type="button"
- onClick={handleToggleMaximize}
- tabIndex={-1}
- title={isMaximized ? 'Restore' : 'Maximize'}
- className="w-4 h-4 rounded-full bg-gradient-to-b from-[#646468] via-[#4a4a4d] to-[#363638] border border-[#202022] shadow-[inset_0_1px_0_rgba(255,255,255,0.35),0_1px_2px_rgba(0,0,0,0.5)] flex items-center justify-center text-[#d0d0d5] hover:text-white hover:brightness-110 active:brightness-90 transition-all cursor-pointer"
- >
- {isMaximized ? (
- <span className="w-2 h-2 border border-currentColor rounded-[0.5px]" />
- ) : (
- <span className="w-2 h-2 border border-currentColor rounded-[0.5px]" />
- )}
- </button>
-
- {/* Close button */}
- <button
- type="button"
- onClick={handleClose}
- tabIndex={-1}
- title="Close"
- className="w-4 h-4 rounded-full bg-gradient-to-b from-[#646468] via-[#4a4a4d] to-[#363638] hover:from-rose-600 hover:via-rose-700 hover:to-rose-900 border border-[#202022] shadow-[inset_0_1px_0_rgba(255,255,255,0.35),0_1px_2px_rgba(0,0,0,0.5)] flex items-center justify-center text-[#d0d0d5] hover:text-white transition-all cursor-pointer"
- >
- <svg width="7" height="7" viewBox="0 0 8 8" fill="none" stroke="currentColor" strokeWidth="1.2">
- <path d="M1 1L7 7M7 1L1 7" strokeLinecap="round" />
- </svg>
- </button>
- </div>
+ <button
+ type="button"
+ onClick={handleMinimize}
+ tabIndex={-1}
+ title="Minimize"
+ className="w-6 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"
+ >
+ <span className="w-2.5 h-[1.5px] bg-current rounded-full" />
+ </button>
+
+ <button
+ type="button"
+ onClick={handleToggleMaximize}
+ tabIndex={-1}
+ title={isMaximized ? 'Restore' : 'Maximize'}
+ className="w-6 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"
+ >
+ <span className="w-2.5 h-2.5 border-[1.25px] border-current rounded-[1px]" />
+ </button>
+
+ <button
+ type="button"
+ onClick={handleClose}
+ tabIndex={-1}
+ title="Close"
+ className="w-6 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:text-white hover:bg-red-500/80 transition-colors cursor-pointer"
+ >
+ <svg width="9" height="9" viewBox="0 0 9 9" fill="none" stroke="currentColor" strokeWidth="1.3">
+ <path d="M1.5 1.5L7.5 7.5M7.5 1.5L1.5 7.5" strokeLinecap="round" />
+ </svg>
+ </button>
</div>
);
};
diff --git a/src/engine/CspBrushEngine.ts b/src/engine/CspBrushEngine.ts
new file mode 100644
index 0000000..f740383
--- /dev/null
+++ b/src/engine/CspBrushEngine.ts
@@ -0,0 +1,601 @@
+/**
+ * CspBrushEngine.ts
+ * Authentic Clip Studio Paint (CSP) Brush Mathematics & Zero-Allocation Dynamics Engine.
+ *
+ * Implements:
+ * 1. O(1) Precompiled Monotone Cubic Hermite (PCHIP) Spline Curve LUTs (256-entry Float32Array, zero GC).
+ * 2. Zero-Closure Deterministic Hash PRNG for live/bake-identical scatter, jitter, and multi-tip selection.
+ * 3. Multi-Sensor CSP Effector Matrix (Pressure x Tilt x Velocity x Random with independent min-floors & curves).
+ * 4. Ellipse-Aware Directional Spacing (eliminates Venetian-blind gaps on flat/calligraphic nibs).
+ * 5. CSP "Adjust Brush Density by Gap" (gap-invariant Beer-Lambert optical transmittance).
+ * 6. 4-Stage CSP Anti-Aliasing (None/Binary, Weak, Medium, Strong) + 2D Sub-Pixel Hairline Coverage.
+ * 7. 5-Mode CSP Paper Texture Physics (Multiply, Subtract/Valley-Fill, Compare, Overlay, Outline).
+ * 8. Corner-Preserving CSP Post-Correction (Levels 1-5) & Stroke-Silhouette Watercolor Edge Filter.
+ */
+
+import {
+ Point,
+ CspSensorConfig,
+ CspPaperTextureMode,
+ CspTipFlipMode,
+} from '../types/editor';
+
+const LUT_SIZE = 256;
+const LUT_MAX_IDX = LUT_SIZE - 1;
+const curveWeakCache = new WeakMap<readonly [number, number][], Float32Array>();
+const curveStringCache = new Map<string, Float32Array>();
+const MAX_STRING_CURVE_CACHE = 128;
+
+/**
+ * Compiles a CSP control-point array [[x0,y0], [x1,y1], ...] into a 256-sample Float32Array LUT
+ * using Fritsch-Carlson Monotone Piecewise Cubic Hermite Interpolation (PCHIP).
+ */
+export function getCompiledCurveLut(curve?: readonly [number, number][]): Float32Array | null {
+ if (!curve || curve.length === 0) return null;
+
+ const weakHit = curveWeakCache.get(curve);
+ if (weakHit) return weakHit;
+
+ let key = '';
+ for (let i = 0; i < curve.length; i++) {
+ key += `${curve[i][0].toFixed(4)},${curve[i][1].toFixed(4)};`;
+ }
+ const strHit = curveStringCache.get(key);
+ if (strHit) {
+ curveWeakCache.set(curve, strHit);
+ return strHit;
+ }
+
+ const lut = new Float32Array(LUT_SIZE);
+ const pts = curve.slice().sort((a, b) => a[0] - b[0]);
+ const dedup: [number, number][] = [pts[0]];
+ for (let i = 1; i < pts.length; i++) {
+ if (pts[i][0] - dedup[dedup.length - 1][0] > 1e-5) {
+ dedup.push(pts[i]);
+ }
+ }
+
+ const n = dedup.length;
+ if (n === 1) {
+ const val = Math.max(0, Math.min(1, dedup[0][1]));
+ lut.fill(val);
+ } else if (n === 2) {
+ const [x0, y0] = dedup[0];
+ const [x1, y1] = dedup[1];
+ const span = Math.max(1e-5, x1 - x0);
+ for (let s = 0; s < LUT_SIZE; s++) {
+ const x = s / LUT_MAX_IDX;
+ if (x <= x0) lut[s] = Math.max(0, Math.min(1, y0));
+ else if (x >= x1) lut[s] = Math.max(0, Math.min(1, y1));
+ else {
+ const t = (x - x0) / span;
+ lut[s] = Math.max(0, Math.min(1, y0 + t * (y1 - y0)));
+ }
+ }
+ } else {
+ const deltas = new Float64Array(n - 1);
+ const m = new Float64Array(n);
+ for (let k = 0; k < n - 1; k++) {
+ deltas[k] = (dedup[k + 1][1] - dedup[k][1]) / Math.max(1e-5, dedup[k + 1][0] - dedup[k][0]);
+ }
+ m[0] = deltas[0];
+ for (let k = 1; k < n - 1; k++) {
+ if (deltas[k - 1] * deltas[k] <= 0) {
+ m[k] = 0;
+ } else {
+ m[k] = (deltas[k - 1] + deltas[k]) * 0.5;
+ }
+ }
+ m[n - 1] = deltas[n - 2];
+
+ for (let k = 0; k < n - 1; k++) {
+ const dk = deltas[k];
+ if (Math.abs(dk) < 1e-6) {
+ m[k] = 0;
+ m[k + 1] = 0;
+ } else {
+ const alpha = m[k] / dk;
+ const beta = m[k + 1] / dk;
+ const sumSq = alpha * alpha + beta * beta;
+ if (sumSq > 9) {
+ const tau = 3 / Math.sqrt(sumSq);
+ m[k] = tau * alpha * dk;
+ m[k + 1] = tau * beta * dk;
+ }
+ }
+ }
+
+ let segIdx = 0;
+ for (let s = 0; s < LUT_SIZE; s++) {
+ const x = s / LUT_MAX_IDX;
+ if (x <= dedup[0][0]) {
+ lut[s] = Math.max(0, Math.min(1, dedup[0][1]));
+ continue;
+ }
+ if (x >= dedup[n - 1][0]) {
+ lut[s] = Math.max(0, Math.min(1, dedup[n - 1][1]));
+ continue;
+ }
+ while (segIdx < n - 2 && x > dedup[segIdx + 1][0]) {
+ segIdx++;
+ }
+ const x0 = dedup[segIdx][0];
+ const y0 = dedup[segIdx][1];
+ const x1 = dedup[segIdx + 1][0];
+ const y1 = dedup[segIdx + 1][1];
+ const h = Math.max(1e-5, x1 - x0);
+ const t = (x - x0) / h;
+ const t2 = t * t;
+ const t3 = t2 * t;
+ const h00 = 2 * t3 - 3 * t2 + 1;
+ const h10 = t3 - 2 * t2 + t;
+ const h01 = -2 * t3 + 3 * t2;
+ const h11 = t3 - t2;
+ const y = h00 * y0 + h10 * h * m[segIdx] + h01 * y1 + h11 * h * m[segIdx + 1];
+ lut[s] = Math.max(0, Math.min(1, y));
+ }
+ }
+
+ if (curveStringCache.size >= MAX_STRING_CURVE_CACHE) {
+ const oldest = curveStringCache.keys().next().value;
+ if (oldest !== undefined) curveStringCache.delete(oldest);
+ }
+ curveStringCache.set(key, lut);
+ curveWeakCache.set(curve, lut);
+ return lut;
+}
+
+/**
+ * Evaluates a CSP spline curve in O(1) time with zero allocations.
+ */
+export function evaluateFastSpline(x: number, curve?: readonly [number, number][]): number {
+ const clamped = x <= 0 ? 0 : x >= 1 ? 1 : x;
+ if (!curve || curve.length === 0) return clamped;
+ const lut = getCompiledCurveLut(curve);
+ if (!lut) return clamped;
+
+ const pos = clamped * LUT_MAX_IDX;
+ const idx = pos | 0;
+ if (idx >= LUT_MAX_IDX) return lut[LUT_MAX_IDX];
+ const frac = pos - idx;
+ return lut[idx] + (lut[idx + 1] - lut[idx]) * frac;
+}
+
+/**
+ * Zero-closure deterministic 32-bit integer hash returning [0, 1).
+ * Guarantees identical dab scatter/jitter/sub-tip order between live preview and stroke commit.
+ */
+export function dabHashFloat(x: number, y: number, dabIndex: number, salt: number): number {
+ const ix = (x * 100) | 0;
+ const iy = (y * 100) | 0;
+ let h = (Math.imul(ix, 73856093) ^ Math.imul(iy, 19349663) ^ Math.imul(dabIndex + 1, 83492791) ^ Math.imul(salt + 1, 0x9e3779b9)) | 0;
+ h = Math.imul(h ^ (h >>> 16), 0x85ebca6b);
+ h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35);
+ return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
+}
+
+/**
+ * Evaluates a CSP multi-sensor dynamic multiplier in [0, 1].
+ * Follows Clip Studio Paint's exact multiplicative sensor law:
+ * factor = pFactor * tFactor * vFactor * rFactor
+ */
+export function evaluateCspSensor(
+ sensor: CspSensorConfig | undefined,
+ pressure: number,
+ tiltMagnitude: number, // [0, 1] where 0 = upright, 1 = flat horizontal
+ speedPxPerMs: number, // stylus speed in px/ms
+ randomVal: number // deterministic [0, 1)
+): number {
+ if (!sensor) return 1.0;
+
+ let factor = 1.0;
+
+ if (sensor.usePressure) {
+ const pMin = Math.max(0, Math.min(1, sensor.pressureMin ?? 0));
+ const curvedP = sensor.pressureCurve
+ ? evaluateFastSpline(pressure, sensor.pressureCurve)
+ : Math.max(0, Math.min(1, pressure));
+ factor *= pMin + (1.0 - pMin) * curvedP;
+ }
+
+ if (sensor.useTilt) {
+ const tMin = Math.max(0, Math.min(1, sensor.tiltMin ?? 0));
+ const clampedTilt = Math.max(0, Math.min(1, tiltMagnitude));
+ factor *= tMin + (1.0 - tMin) * clampedTilt;
+ }
+
+ if (sensor.useVelocity) {
+ const vMin = Math.max(0, Math.min(1, sensor.velocityMin ?? 0));
+ // Normalize speed: 3.5 px/ms (~3500 px/s) maps to full velocity 1.0
+ const vNorm = Math.max(0, Math.min(1, speedPxPerMs / 3.5));
+ const vVal = sensor.invertVelocity !== false ? 1.0 - vNorm : vNorm;
+ factor *= vMin + (1.0 - vMin) * vVal;
+ }
+
+ if (sensor.useRandom) {
+ const rMin = Math.max(0, Math.min(1, sensor.randomMin ?? 0));
+ factor *= rMin + (1.0 - rMin) * Math.max(0, Math.min(1, randomVal));
+ }
+
+ return Math.max(0, Math.min(1, factor));
+}
+
+/**
+ * Computes ellipse-aware step distance along the local stroke tangent.
+ * Prevents discrete "Venetian blind" stamp gaps when drawing perpendicular to a flat/calligraphic brush's thin axis.
+ */
+export function computeEllipticalStepDistance(
+ width: number,
+ height: number,
+ dabAngleRad: number,
+ tangentDx: number,
+ tangentDy: number,
+ spacingRatio: number,
+ minStepPx: number = 0.12
+): number {
+ const ratio = Math.max(0.01, Math.min(2.0, spacingRatio));
+ const w = Math.max(0.1, width);
+ const h = Math.max(0.1, height);
+
+ // Fast isotropic path for round tips
+ if (Math.abs(w - h) < 1e-2) {
+ return Math.max(minStepPx, w * ratio);
+ }
+
+ const tLen = Math.hypot(tangentDx, tangentDy);
+ if (tLen < 1e-4) {
+ return Math.max(minStepPx, Math.min(w, h) * ratio);
+ }
+
+ // Project tangent unit vector into the rotated ellipse's local frame
+ const ux = tangentDx / tLen;
+ const uy = tangentDy / tLen;
+ const cosA = Math.cos(dabAngleRad);
+ const sinA = Math.sin(dabAngleRad);
+ const localX = ux * cosA + uy * sinA;
+ const localY = -ux * sinA + uy * cosA;
+
+ // Support diameter of ellipse (w, h) along direction (localX, localY)
+ const denom = Math.hypot(localX / w, localY / h);
+ const effectiveDiameter = denom > 1e-5 ? 1.0 / denom : Math.min(w, h);
+ return Math.max(minStepPx, effectiveDiameter * ratio);
+}
+
+/**
+ * CSP "Adjust brush density by gap":
+ * Compensates dab alpha using Beer-Lambert transmittance law so changing spacing
+ * preserves perceived stroke optical density and prevents 8-bit Mach-band rings.
+ */
+export function computeGapAdjustedAlpha(
+ baseAlpha: number,
+ spacingRatio: number,
+ adjustByGap: boolean = false,
+ referenceSpacing: number = 0.08
+): number {
+ const a = Math.max(0, Math.min(1, baseAlpha));
+ if (!adjustByGap || a >= 0.998 || a <= 0.001) return a;
+ const ratio = Math.max(0.12, Math.min(4.0, spacingRatio / Math.max(0.01, referenceSpacing)));
+ return Math.max(0.002, Math.min(1.0, 1.0 - Math.pow(1.0 - a, ratio)));
+}
+
+/**
+ * Computes exact 2D sub-pixel area conservation for ultra-fine manga hairlines (< 1.0px).
+ * Prevents sub-pixel widths/heights from bloating to 1.25px or flickering.
+ */
+export function computeSubpixelDabDimensions(
+ width: number,
+ height: number,
+ alpha: number,
+ minRenderDim: number = 0.75
+): { renderW: number; renderH: number; effAlpha: number } {
+ const renderW = Math.max(minRenderDim, width);
+ const renderH = Math.max(minRenderDim, height);
+ if (width >= minRenderDim && height >= minRenderDim) {
+ return { renderW, renderH, effAlpha: alpha };
+ }
+ const scaleW = width < minRenderDim ? Math.max(0.04, width / renderW) : 1.0;
+ const scaleH = height < minRenderDim ? Math.max(0.04, height / renderH) : 1.0;
+ return {
+ renderW,
+ renderH,
+ effAlpha: Math.max(0.003, Math.min(1.0, alpha * scaleW * scaleH)),
+ };
+}
+
+/**
+ * Maps CSP 4-level Anti-Aliasing setting (0: None, 1: Weak, 2: Medium, 3: Strong)
+ * into feather width in pixels.
+ */
+export function getCspAntiAliasFeather(antiAlias: number = 2): number {
+ switch (antiAlias) {
+ case 0:
+ return 0.0; // Binary 1-bit crisp threshold
+ case 1:
+ return 0.65; // Weak (sharp manga pen)
+ case 3:
+ return 1.95; // Strong (silky illustration pen)
+ case 2:
+ default:
+ return 1.15; // Medium (standard CSP G-Pen)
+ }
+}
+
+/**
+ * Resolves horizontal/vertical flip signs (+1 or -1) for a dab according to CSP Tip Flip mode.
+ */
+export function resolveTipFlipSigns(
+ flipH: CspTipFlipMode | undefined,
+ flipV: CspTipFlipMode | undefined,
+ dabSeq: number,
+ x: number,
+ y: number
+): { signX: number; signY: number } {
+ let signX = 1;
+ let signY = 1;
+ if (flipH === 'alternate') {
+ signX = (dabSeq & 1) === 0 ? 1 : -1;
+ } else if (flipH === 'random') {
+ signX = dabHashFloat(x, y, dabSeq, 71) < 0.5 ? 1 : -1;
+ }
+ if (flipV === 'alternate') {
+ signY = (dabSeq & 1) === 0 ? 1 : -1;
+ } else if (flipV === 'random') {
+ signY = dabHashFloat(x, y, dabSeq, 73) < 0.5 ? 1 : -1;
+ }
+ return { signX, signY };
+}
+
+/**
+ * Evaluates CSP 5-mode Paper Texture modulation on dab alpha:
+ * - multiply: tipAlpha * grain
+ * - subtract: max(0, tipAlpha - (1 - grain) * density) [CSP classic valley-fill with pressure!]
+ * - compare: tipAlpha >= (1 - grain) ? tipAlpha : 0
+ * - overlay: contrast-preserving texture tooth
+ * - outline: accentuates texture contours along dab edges
+ */
+export function applyCspPaperTextureAlpha(
+ tipAlpha: number,
+ grainNorm: number, // [0, 1] raw paper height
+ textureDensity: number, // [0, 1]
+ pressure: number, // [0, 1]
+ mode: CspPaperTextureMode = 'subtract',
+ brightness: number = 0, // [-100, 100]
+ contrast: number = 0, // [-100, 100]
+ inverted: boolean = false
+): number {
+ if (textureDensity <= 0.001 || tipAlpha <= 0.001) return tipAlpha;
+
+ let g = inverted ? 1.0 - grainNorm : grainNorm;
+ if (brightness !== 0) {
+ g += brightness / 100.0;
+ }
+ if (contrast !== 0) {
+ const cFactor = Math.pow((contrast + 100.0) / 100.0, 2);
+ g = (g - 0.5) * cFactor + 0.5;
+ }
+ g = Math.max(0, Math.min(1, g));
+
+ //Stylus pressure pushes pigment deeper into paper valleys
+ const penetration = Math.max(0, Math.min(0.85, pressure * 0.65));
+ const effDensity = textureDensity * (1.0 - penetration * 0.6);
+
+ switch (mode) {
+ case 'multiply': {
+ const m = 1.0 - effDensity * (1.0 - g);
+ return Math.max(0, Math.min(1, tipAlpha * m));
+ }
+ case 'subtract': {
+ const sub = (1.0 - g) * effDensity;
+ return Math.max(0, Math.min(1, tipAlpha - sub * (1.0 - penetration * 0.5)));
+ }
+ case 'compare': {
+ const thresh = (1.0 - g) * effDensity;
+ return tipAlpha > thresh ? Math.min(1, (tipAlpha - thresh) / Math.max(0.08, 1.0 - thresh)) : 0;
+ }
+ case 'overlay': {
+ const ov = tipAlpha < 0.5
+ ? 2.0 * tipAlpha * g
+ : 1.0 - 2.0 * (1.0 - tipAlpha) * (1.0 - g);
+ return Math.max(0, Math.min(1, tipAlpha + (ov - tipAlpha) * effDensity));
+ }
+ case 'outline': {
+ const edgeFactor = 4.0 * tipAlpha * (1.0 - tipAlpha);
+ return Math.max(0, Math.min(1, tipAlpha * (1.0 - effDensity * (1.0 - g) * (0.35 + 0.65 * edgeFactor))));
+ }
+ default:
+ return tipAlpha;
+ }
+}
+
+/**
+ * Applies Clip Studio Paint Post-Correction (levels 1..5) to a finished stroke's knot array,
+ * smoothing micro-wobble while strictly preserving endpoints and sharp corner vertices (isCorner).
+ */
+export function applyCspPostCorrection(
+ points: Point[],
+ level: number = 0,
+ preserveSharpCorners: boolean = true
+): Point[] {
+ const passes = Math.max(0, Math.min(5, Math.round(level)));
+ if (passes <= 0 || points.length < 4) return points;
+
+ let current = points.map((p) => ({ ...p }));
+ const next = points.map((p) => ({ ...p }));
+
+ for (let pass = 0; pass < passes; pass++) {
+ const n = current.length;
+ next[0] = { ...current[0] };
+ next[n - 1] = { ...current[n - 1] };
+
+ for (let i = 1; i < n - 1; i++) {
+ const cur = current[i];
+ if (preserveSharpCorners && cur.isCorner) {
+ next[i] = { ...cur };
+ continue;
+ }
+ const prev = current[i - 1];
+ const nxt = current[i + 1];
+
+ // Check local angle so deliberate acute corners (< 115 deg) aren't rounded off
+ if (preserveSharpCorners) {
+ const ax = cur.x - prev.x;
+ const ay = cur.y - prev.y;
+ const bx = nxt.x - cur.x;
+ const by = nxt.y - cur.y;
+ const la = Math.hypot(ax, ay);
+ const lb = Math.hypot(bx, by);
+ if (la > 1.5 && lb > 1.5) {
+ const cos = (ax * bx + ay * by) / (la * lb);
+ if (cos < 0.35) {
+ next[i] = { ...cur };
+ continue;
+ }
+ }
+ }
+
+ // [0.25, 0.50, 0.25] zero-phase Gaussian smoothing kernel
+ next[i] = {
+ ...cur,
+ x: prev.x * 0.25 + cur.x * 0.5 + nxt.x * 0.25,
+ y: prev.y * 0.25 + cur.y * 0.5 + nxt.y * 0.25,
+ width: prev.width * 0.2 + cur.width * 0.6 + nxt.width * 0.2,
+ pressure: prev.pressure * 0.2 + cur.pressure * 0.6 + nxt.pressure * 0.2,
+ };
+ }
+
+ for (let i = 0; i < n; i++) {
+ current[i] = next[i];
+ }
+ }
+
+ return current;
+}
+
+/**
+ * Applies authentic Clip Studio Paint Stroke-Perimeter Watercolor Edge ("Water Edge")
+ * onto an isolated stroke ImageData buffer before compositing onto the canvas layer.
+ * Produces capillary pigment accumulation & darkening ONLY at the outer silhouette of the entire stroke
+ * (eliminating internal fish-scale dab rings!).
+ */
+export function applyCspWatercolorEdge(
+ strokeImageData: { data: Uint8ClampedArray; width: number; height: number },
+ wetEdge: number,
+ radiusPx: number = 2.5,
+ alphaPower: number = 0.65,
+ valuePower: number = 0.55
+): void {
+ if (wetEdge <= 0.01) return;
+ const { data, width, height } = strokeImageData;
+ if (width < 3 || height < 3) return;
+
+ const strength = Math.max(0, Math.min(1, wetEdge));
+ const r = Math.max(1, Math.min(8, Math.round(radiusPx)));
+ const totalPixels = width * height;
+
+ // Separable box-blur of stroke alpha channel to detect silhouette boundary gradient
+ const alphaOrig = new Float32Array(totalPixels);
+ const alphaTemp = new Float32Array(totalPixels);
+ for (let i = 0; i < totalPixels; i++) {
+ alphaOrig[i] = data[i * 4 + 3] / 255.0;
+ }
+
+ // Horizontal pass
+ const invKernel = 1.0 / (2 * r + 1);
+ for (let y = 0; y < height; y++) {
+ const row = y * width;
+ let sum = alphaOrig[row] * (r + 1);
+ for (let k = 1; k <= r; k++) {
+ sum += alphaOrig[row + Math.min(width - 1, k)];
+ }
+ for (let x = 0; x < width; x++) {
+ alphaTemp[row + x] = sum * invKernel;
+ const leftIdx = Math.max(0, x - r);
+ const rightIdx = Math.min(width - 1, x + r + 1);
+ sum += alphaOrig[row + rightIdx] - alphaOrig[row + leftIdx];
+ }
+ }
+
+ // Vertical pass + capillary rim modulation
+ const aBoost = strength * (0.45 + alphaPower * 1.15);
+ const vDarken = strength * (0.25 + valuePower * 0.55);
+
+ for (let x = 0; x < width; x++) {
+ let sum = alphaTemp[x] * (r + 1);
+ for (let k = 1; k <= r; k++) {
+ sum += alphaTemp[Math.min(height - 1, k) * width + x];
+ }
+ for (let y = 0; y < height; y++) {
+ const idx = y * width + x;
+ const blurredA = sum * invKernel;
+ const origA = alphaOrig[idx];
+
+ if (origA > 0.015) {
+ // Rim is high where pixel is inside the stroke (origA > 0) but near transparent exterior (origA > blurredA)
+ const rim = Math.max(0, origA - blurredA) * 2.4;
+ if (rim > 0.01) {
+ const p = idx * 4;
+ const darkScale = Math.max(0.18, 1.0 - rim * vDarken);
+ data[p] = Math.round(data[p] * darkScale);
+ data[p + 1] = Math.round(data[p + 1] * darkScale);
+ data[p + 2] = Math.round(data[p + 2] * darkScale);
+ const nextA = Math.min(1.0, origA * (1.0 + rim * aBoost));
+ data[p + 3] = Math.round(nextA * 255);
+ }
+ }
+
+ const topIdx = Math.max(0, y - r);
+ const botIdx = Math.min(height - 1, y + r + 1);
+ sum += alphaTemp[botIdx * width + x] - alphaTemp[topIdx * width + x];
+ }
+ }
+}
+
+/**
+ * Built-in CSP Pressure Curve Presets for quick 1-click studio switching.
+ */
+export const CSP_PRESSURE_CURVE_PRESETS: Record<string, { label: string; points: [number, number][] }> = {
+ linear: {
+ label: 'Linear',
+ points: [
+ [0, 0],
+ [1, 1],
+ ],
+ },
+ 'g-pen': {
+ label: 'G-Pen S-Curve',
+ points: [
+ [0, 0],
+ [0.2, 0.08],
+ [0.55, 0.52],
+ [0.82, 0.88],
+ [1, 1],
+ ],
+ },
+ soft: {
+ label: 'Soft Touch',
+ points: [
+ [0, 0],
+ [0.25, 0.48],
+ [0.65, 0.84],
+ [1, 1],
+ ],
+ },
+ firm: {
+ label: 'Firm Nib',
+ points: [
+ [0, 0],
+ [0.35, 0.12],
+ [0.7, 0.48],
+ [1, 1],
+ ],
+ },
+ chisel: {
+ label: 'Steep Threshold',
+ points: [
+ [0, 0],
+ [0.15, 0.03],
+ [0.45, 0.72],
+ [1, 1],
+ ],
+ },
+};
diff --git a/src/engine/InputStabilizer.ts b/src/engine/InputStabilizer.ts
index d20db61..ff851ee 100644
--- a/src/engine/InputStabilizer.ts
+++ b/src/engine/InputStabilizer.ts
@@ -69,8 +69,11 @@ export class OneEuroAxis {
return x;
}
- const dt = Math.max(1e-4, (timestampMs - this.tPrev) * 0.001); // dt in seconds
- this.tPrev = timestampMs;
+ 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;
+ const dt = Math.max(0.002, effectiveMs * 0.001);
+ this.tPrev = rawElapsedMs <= 0.5 ? this.tPrev + 4.0 : Math.max(this.tPrev, timestampMs);
const rate = 1.0 / dt;
// Filter derivative
@@ -128,6 +131,8 @@ export class InputStabilizer {
private hasPrevDir: boolean = false;
private rawPrevX: number = 0;
private rawPrevY: number = 0;
+ private lastRawSampleX: number = 0;
+ private lastRawSampleY: number = 0;
// Single pre-allocated sample object for output to eliminate GC allocation
private outputSample: StabilizedSample = {
@@ -142,12 +147,24 @@ export class InputStabilizer {
};
private isStarted: boolean = false;
+ private zoomScale: number = 1.0;
+ private sharpCornersEnabled: boolean = true;
private config: StabilizerConfig = { ...DEFAULT_STABILIZER_CONFIG };
public configure(config: Partial<StabilizerConfig>): void {
Object.assign(this.config, config);
}
+ public setZoomScale(zoom: number): void {
+ if (Number.isFinite(zoom) && zoom > 0) {
+ this.zoomScale = zoom;
+ }
+ }
+
+ public setSharpCorners(enabled: boolean): void {
+ this.sharpCornersEnabled = enabled;
+ }
+
public setStabilizerLevel(level: number): void {
// level: 0 to 50 (CSP slider equivalent)
if (level <= 0) {
@@ -157,8 +174,8 @@ export class InputStabilizer {
} 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.6, 5.0 - t * 4.4); // 5.0 -> 0.6 Hz
- this.config.beta = Math.max(0.008, 0.06 - t * 0.05); // 0.06 -> 0.01
+ 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
}
}
@@ -183,9 +200,15 @@ export class InputStabilizer {
this.hasPrevDir = false;
this.rawPrevX = 0;
this.rawPrevY = 0;
+ this.lastRawSampleX = 0;
+ this.lastRawSampleY = 0;
this.isStarted = false;
}
+ public getLastSample(): Readonly<StabilizedSample> {
+ return this.outputSample;
+ }
+
public process(
rawX: number,
rawY: number,
@@ -199,6 +222,8 @@ export class InputStabilizer {
this.lastTime = timestampMs;
this.rawPrevX = rawX;
this.rawPrevY = rawY;
+ this.lastRawSampleX = rawX;
+ this.lastRawSampleY = rawY;
this.smX = rawX;
this.smY = rawY;
this.smVx = 0;
@@ -224,17 +249,25 @@ export class InputStabilizer {
const dtMs = Math.max(1, timestampMs - this.lastTime);
const dtSec = dtMs * 0.001;
- // 1. Critical Angle Detection (Corner Snapping)
+ const stepRawDx = rawX - this.lastRawSampleX;
+ const stepRawDy = rawY - this.lastRawSampleY;
+ const stepRawDist = Math.hypot(stepRawDx, stepRawDy);
+ 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
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));
let isCorner = false;
- if (rawDist >= 6.0) {
+ if (rawDist >= minCornerChord) {
const curDirX = rawDx / rawDist;
const curDirY = rawDy / rawDist;
- if (this.hasPrevDir) {
+ if (this.hasPrevDir && this.sharpCornersEnabled) {
// Dot product between consecutive motion vectors
const dot = Math.max(-1.0, Math.min(1.0, this.prevDirX * curDirX + this.prevDirY * curDirY));
const angle = Math.acos(dot);
@@ -259,16 +292,25 @@ export class InputStabilizer {
this.rawPrevY = rawY;
}
- // 2. Velocity-Adaptive Damping Scaling
- // On high-speed ballistic flicks, scale cutoff up and latency toward zero
- const estimatedSpeed = rawDist / dtMs; // px / ms
- const speedBoost = Math.min(15.0, estimatedSpeed * 4.0);
+ // 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.8);
-
- // 3. Coordinate Filtering
- let fX = isCorner ? rawX : this.filterX.filter(rawX, timestampMs, dynamicMinCutoff, dynamicBeta, this.config.dCutoff);
- let fY = isCorner ? rawY : this.filterY.filter(rawY, timestampMs, dynamicMinCutoff, dynamicBeta, this.config.dCutoff);
+ const dynamicBeta = this.config.beta * (1.0 + speedBoost * 0.35);
+
+ // 3. Coordinate Filtering with sub-pixel deadzone suppression
+ let fX: number;
+ let fY: number;
+ if (isCorner) {
+ fX = rawX;
+ fY = rawY;
+ } else if (stepRawDist < this.config.deadzone && this.config.minCutoff < 50.0) {
+ fX = this.lastX;
+ fY = this.lastY;
+ } else {
+ fX = this.filterX.filter(rawX, timestampMs, dynamicMinCutoff, dynamicBeta, this.config.dCutoff);
+ fY = this.filterY.filter(rawY, timestampMs, dynamicMinCutoff, dynamicBeta, this.config.dCutoff);
+ }
// 4. Asymmetric Pressure Filtering (Fast Attack, Critically Damped Decay)
const pressureDelta = rawPressure - this.lastRawPressure;
@@ -284,7 +326,7 @@ export class InputStabilizer {
const m = this.config.springMass;
// Dynamic damping reduction on fast flicks
- const effectiveDamping = Math.max(c * 0.35, c / (1.0 + estimatedSpeed * 0.5));
+ const effectiveDamping = Math.max(c * 0.35, c / (1.0 + screenSpeed * 0.5));
const disX = fX - this.smX;
const disY = fY - this.smY;
diff --git a/src/engine/SplineGenerator.ts b/src/engine/SplineGenerator.ts
index 5fc5b10..495915c 100644
--- a/src/engine/SplineGenerator.ts
+++ b/src/engine/SplineGenerator.ts
@@ -216,13 +216,13 @@ export class SplineGenerator {
this.segment.c1.x = p1.x + dx1;
this.segment.c1.y = p1.y + dy1;
- this.segment.c1.pressure = p1.pressure + (p2.pressure - p0.pressure) / 6.0;
- this.segment.c1.width = p1.width + (p2.width - p0.width) / 6.0;
+ this.segment.c1.pressure = Math.max(0, Math.min(1, p1.pressure + (p2.pressure - p0.pressure) / 6.0));
+ this.segment.c1.width = Math.max(0.1, p1.width + (p2.width - p0.width) / 6.0);
this.segment.c2.x = p2.x - dx2;
this.segment.c2.y = p2.y - dy2;
- this.segment.c2.pressure = p2.pressure - (p3.pressure - p1.pressure) / 6.0;
- this.segment.c2.width = p2.width - (p3.width - p1.width) / 6.0;
+ this.segment.c2.pressure = Math.max(0, Math.min(1, p2.pressure - (p3.pressure - p1.pressure) / 6.0));
+ this.segment.c2.width = Math.max(0.1, p2.width - (p3.width - p1.width) / 6.0);
this.segment.p3.x = p2.x;
this.segment.p3.y = p2.y;
@@ -230,9 +230,13 @@ export class SplineGenerator {
this.segment.p3.width = p2.width;
// Cache tangent at P2 for subsequent Hermite provisional segment stitching
- this.lastTangentX = dx2 * 3.0;
- this.lastTangentY = dy2 * 3.0;
- this.hasLastTangent = true;
+ if (Math.hypot(dx2, dy2) > 1e-4) {
+ this.lastTangentX = dx2 * 3.0;
+ this.lastTangentY = dy2 * 3.0;
+ this.hasLastTangent = true;
+ } else {
+ this.hasLastTangent = false;
+ }
return this.segment;
}
diff --git a/src/engine/StrokePipeline.ts b/src/engine/StrokePipeline.ts
index e005838..14617b7 100644
--- a/src/engine/StrokePipeline.ts
+++ b/src/engine/StrokePipeline.ts
@@ -177,9 +177,9 @@ export class StrokePipeline {
this.ingestPointerEvent(e, view);
this.flush();
- // Evaluate exit flick taper
+ // Evaluate exit flick taper using cached velocity from last processed sample (do not re-process knotP2)
if (this.knotCount >= 2 && this.scratchCtx) {
- const exitSample = this.stabilizer.process(this.knotP2.x, this.knotP2.y, this.knotP2.pressure, e.timeStamp);
+ const exitSample = this.stabilizer.getLastSample();
const flick = this.taperEngine.computeFlickTaper(
this.knotP2.x,
this.knotP2.y,
@@ -195,6 +195,15 @@ export class StrokePipeline {
const pt = flick.points[i];
this.processStabilizedPoint(pt.x, pt.y, pt.pressure, pt.width, exitSample.vx, exitSample.vy, false);
}
+ } else {
+ // Seal the final segment knotP1 -> knotP2 onto scratchCtx
+ const finalSeg = this.splineGen.generateCatmullRomSegment(
+ this.knotP0,
+ this.knotP1,
+ this.knotP2,
+ this.knotP2
+ );
+ this.renderSegment(this.scratchCtx, finalSeg, false);
}
}
@@ -317,7 +326,8 @@ export class StrokePipeline {
if (isCorner && this.knotCount >= 1) {
const cornerPt: SplinePoint = { x, y, pressure, width };
- const cornerSeg = this.splineGen.generateCornerSegment(this.knotP1, cornerPt);
+ const prevKnot = this.knotCount >= 2 ? this.knotP2 : this.knotP1;
+ const cornerSeg = this.splineGen.generateCornerSegment(prevKnot, cornerPt);
this.renderSegment(this.scratchCtx, cornerSeg, false);
this.splineGen.commitCornerKnot(cornerPt);
@@ -359,7 +369,8 @@ export class StrokePipeline {
this.knotP2.width = width;
const seg = this.splineGen.generateProvisionalSegment(this.knotP1, this.knotP2, vx, vy);
- this.renderSegment(this.scratchCtx, seg, true);
+ const provTarget = this.predictedCtx || this.scratchCtx;
+ this.renderSegment(provTarget, seg, true);
this.knotCount = 2;
return;
}
@@ -378,8 +389,10 @@ export class StrokePipeline {
);
this.renderSegment(this.scratchCtx, sealedSeg, false);
- const nextProvSeg = this.splineGen.generateProvisionalSegment(this.knotP2, this.knotP3, vx, vy);
- this.renderSegment(this.scratchCtx, nextProvSeg, true);
+ if (this.predictedCtx) {
+ const nextProvSeg = this.splineGen.generateProvisionalSegment(this.knotP2, this.knotP3, vx, vy);
+ this.renderSegment(this.predictedCtx, nextProvSeg, true);
+ }
// Shift window
this.knotP0.x = this.knotP1.x;
@@ -431,8 +444,8 @@ export class StrokePipeline {
prevPt = curPt;
}
} else {
- // Hermite extrapolation forward along velocity vector
- const sample = this.stabilizer.process(this.knotP2.x, this.knotP2.y, this.knotP2.pressure, e.timeStamp);
+ // Hermite extrapolation forward along velocity vector without mutating stabilizer filter state
+ const sample = this.stabilizer.getLastSample();
if (sample.speed > 0.05) {
const dt = 12.0; // ms forward
const predPt: SplinePoint = {
@@ -469,9 +482,11 @@ export class StrokePipeline {
ctx.stroke();
}
- this.expandDirtyRect(seg.p0.x, seg.p0.y, seg.p0.width);
- this.expandDirtyRect(seg.c1.x, seg.c1.y, seg.c1.width);
- this.expandDirtyRect(seg.c2.x, seg.c2.y, seg.c2.width);
- this.expandDirtyRect(seg.p3.x, seg.p3.y, seg.p3.width);
+ if (ctx === this.scratchCtx) {
+ this.expandDirtyRect(seg.p0.x, seg.p0.y, seg.p0.width);
+ this.expandDirtyRect(seg.c1.x, seg.c1.y, seg.c1.width);
+ this.expandDirtyRect(seg.c2.x, seg.c2.y, seg.c2.width);
+ this.expandDirtyRect(seg.p3.x, seg.p3.y, seg.p3.width);
+ }
}
}
diff --git a/src/engine/TaperEngine.ts b/src/engine/TaperEngine.ts
index e1f37b3..8e93ded 100644
--- a/src/engine/TaperEngine.ts
+++ b/src/engine/TaperEngine.ts
@@ -86,24 +86,33 @@ export class TaperEngine {
const u = Math.max(0, Math.min(1, pNorm));
const pMin = this.pConfig.minPressure;
- // Piecewise cubic Hermite transfer curve with matched slopes
+ // C1-continuous piecewise cubic Hermite transfer curve with matched derivatives at knots
+ const evalHermite = (t: number, h: number, y0: number, y1: number, m0: number, m1: number): number => {
+ const t2 = t * t;
+ const t3 = t2 * t;
+ const h00 = 2.0 * t3 - 3.0 * t2 + 1.0;
+ const h10 = t3 - 2.0 * t2 + t;
+ const h01 = -2.0 * t3 + 3.0 * t2;
+ const h11 = t3 - t2;
+ return h00 * y0 + h10 * (h * m0) + h01 * y1 + h11 * (h * m1);
+ };
+
+ const y1 = 0.145;
+ const y2 = 0.685;
+ const m0 = 0.15;
+ const m1 = 0.98;
+ const m2 = 1.05;
+ const m3 = 0.55;
+
if (u <= 0.15) {
- // Zone 1: Hairline zone [0.0, 0.15] -> [pMin, 0.18]
- // Quadratic-cubic ease-in
- const t = u / 0.15;
- const curve = t * t * (1.5 - 0.5 * t);
- return pMin + (0.18 - pMin) * curve;
+ // Zone 1: Hairline zone [0.0, 0.15] -> [pMin, 0.145]
+ return evalHermite(u / 0.15, 0.15, pMin, y1, m0, m1);
} else if (u <= 0.70) {
- // Zone 2: Stable controllable body [0.15, 0.70] -> [0.18, 0.72]
- const t = (u - 0.15) / 0.55;
- // Gentle linear-smooth slope
- return 0.18 + (0.72 - 0.18) * t;
+ // Zone 2: Stable controllable body [0.15, 0.70] -> [0.145, 0.685]
+ return evalHermite((u - 0.15) / 0.55, 0.55, y1, y2, m1, m2);
} else {
- // Zone 3: Saturated expansion [0.70, 1.00] -> [0.72, 1.00]
- const t = Math.max(0, Math.min(1.0, (u - 0.70) / 0.30));
- // Cubic ease-out acceleration to maximum saturated weight
- const easeOut = 1.0 - Math.pow(Math.max(0, 1.0 - t), 2.5);
- return 0.72 + (1.00 - 0.72) * easeOut;
+ // Zone 3: Saturated expansion [0.70, 1.00] -> [0.685, 1.00]
+ return evalHermite(Math.min(1.0, (u - 0.70) / 0.30), 0.30, y2, 1.0, m2, m3);
}
}
@@ -112,17 +121,20 @@ export class TaperEngine {
* to eliminate bumpy / sausage-like stroke artifacts.
*/
public smoothPressure(currentMappedPressure: number): number {
- const idx = this.pressureHistoryCount % this.pressureHistory.length;
+ const len = this.pressureHistory.length;
+ const idx = this.pressureHistoryCount % len;
this.pressureHistory[idx] = currentMappedPressure;
this.pressureHistoryCount++;
- const sampleCount = Math.min(this.pressureHistoryCount, this.pressureHistory.length);
+ const sampleCount = Math.min(this.pressureHistoryCount, len);
+ const startIdx = this.pressureHistoryCount - sampleCount;
let sum = 0;
let weightSum = 0;
for (let i = 0; i < sampleCount; i++) {
+ const ringIdx = (startIdx + i) % len;
const w = 1.0 + i * 0.4;
- sum += this.pressureHistory[i] * w;
+ sum += this.pressureHistory[ringIdx] * w;
weightSum += w;
}
@@ -142,7 +154,8 @@ export class TaperEngine {
lastPressure: number,
exitVx: number, // px / ms
exitVy: number, // px / ms
- lastTimestampMs: number
+ lastTimestampMs: number,
+ angularVelRadPerMs: number = 0
): { points: ExtrapolatedPoint[]; count: number } {
const exitSpeed = Math.hypot(exitVx, exitVy); // px / ms
@@ -150,8 +163,8 @@ export class TaperEngine {
return { points: this.flickPointPool, count: 0 };
}
- const dirX = exitVx / exitSpeed;
- const dirY = exitVy / exitSpeed;
+ let curAngle = Math.atan2(exitVy, exitVx);
+ const clampedOmega = Math.max(-0.012, Math.min(0.012, angularVelRadPerMs));
const count = Math.min(this.fConfig.flickPoints, this.flickPointPool.length);
let curX = lastX;
@@ -163,13 +176,14 @@ export class TaperEngine {
const lambda = this.fConfig.decayRate;
for (let i = 0; i < count; i++) {
- // Inertial damping on velocity: v(t) = v0 * exp(-drag * t)
+ // Inertial damping on velocity & gentle curvature continuation (prevents linear kinks on curved flicks)
const dragFactor = Math.exp(-this.fConfig.dragCoefficient * (dt * 0.05));
curSpeed *= dragFactor;
+ curAngle += clampedOmega * dt * Math.exp(-0.22 * i);
const stepDist = curSpeed * dt;
- curX += dirX * stepDist;
- curY += dirY * stepDist;
+ curX += Math.cos(curAngle) * stepDist;
+ curY += Math.sin(curAngle) * stepDist;
curTime += dt;
// Exponential attenuation of radius: w(k) = w0 * exp(-lambda * (k + 1))
diff --git a/src/hooks/useCanvasDrawing.ts b/src/hooks/useCanvasDrawing.ts
index 727cf61..3ddf564 100644
--- a/src/hooks/useCanvasDrawing.ts
+++ b/src/hooks/useCanvasDrawing.ts
@@ -4,6 +4,7 @@ import {
BrushSettings,
Point,
CanvasDimensions,
+ CanvasSelection,
HistoryActionType,
HistoryItem,
HistoryItemMeta,
@@ -14,8 +15,9 @@ import {
VectorStroke,
VectorKnot,
} from '../types/editor';
-import { globalTileGrid } from '../utils/tileEngine';
+import { globalTileGrid, TILE_SIZE, TileFormat } from '../utils/tileEngine';
import { globalUndoCache } from '../utils/undoCache';
+import { recoveryService } from '../services/recoveryService';
import {
applyVectorEraser,
renderVectorLayer,
@@ -39,7 +41,8 @@ import {
} from '../utils/canvasUtils';
import { InputStabilizer } from '../engine/InputStabilizer';
import { TaperEngine } from '../engine/TaperEngine';
-import { enforceColorMode, binarizeCanvasRect, binarizeImageDataBuffer } from '../utils/colorUtils';
+import { applyCspWatercolorEdge } from '../engine/CspBrushEngine';
+import { enforceColorMode, binarizeImageDataBuffer } from '../utils/colorUtils';
import { drawPencilCubicBezierSegment, drawPencilDot, PencilGrade } from '../utils/pencilEngine';
import {
drawTexturedCubicBezierSegment,
@@ -52,10 +55,97 @@ import { applyLayerEffects } from '../utils/layerEffectsEngine';
import { PerspectiveRuler, ConstraintAxis } from '../types/perspective';
import { PerspectiveSnapSession } from '../utils/perspectiveSnapping';
+function isBackgroundLayerId(id: string): boolean {
+ return id === 'layer-bg' || id.startsWith('layer-bg');
+}
+
+function applySelectionCanvasClip(
+ ctx: CanvasRenderingContext2D,
+ sel: CanvasSelection | null | undefined
+): void {
+ if (!sel) return;
+ if (sel.type === 'rect') {
+ ctx.beginPath();
+ ctx.rect(sel.bounds.x, sel.bounds.y, sel.bounds.width, sel.bounds.height);
+ ctx.clip();
+ } else if (sel.type === 'lasso' && sel.polygon && sel.polygon.length >= 3) {
+ ctx.beginPath();
+ ctx.moveTo(sel.polygon[0].x, sel.polygon[0].y);
+ for (let i = 1; i < sel.polygon.length; i++) {
+ ctx.lineTo(sel.polygon[i].x, sel.polygon[i].y);
+ }
+ ctx.closePath();
+ ctx.clip();
+ } else if (sel.svgPath && typeof Path2D !== 'undefined') {
+ try {
+ ctx.clip(new Path2D(sel.svgPath), 'evenodd');
+ } catch {
+ // Fallback to bounds clip if svgPath fails
+ ctx.beginPath();
+ ctx.rect(sel.bounds.x, sel.bounds.y, sel.bounds.width, sel.bounds.height);
+ ctx.clip();
+ }
+ }
+}
+
+function applySelectionMaskToImageData(
+ beforeData: ImageData,
+ afterData: ImageData,
+ rx: number,
+ ry: number,
+ sel: CanvasSelection | null | undefined
+): void {
+ if (!sel || !sel.mask || !sel.maskWidth || !sel.maskHeight) return;
+ const mask = sel.mask;
+ const mw = sel.maskWidth;
+ const mh = sel.maskHeight;
+ const w = afterData.width;
+ const h = afterData.height;
+ const src = beforeData.data;
+ const dst = afterData.data;
+
+ for (let ly = 0; ly < h; ly++) {
+ const docY = ry + ly;
+ const inY = docY >= 0 && docY < mh;
+ const maskRow = docY * mw;
+ const imgRow = ly * w;
+ for (let lx = 0; lx < w; lx++) {
+ const docX = rx + lx;
+ const mAlpha = inY && docX >= 0 && docX < mw ? mask[maskRow + docX] : 0;
+ if (mAlpha === 255) continue;
+ const idx = (imgRow + lx) * 4;
+ if (mAlpha === 0) {
+ dst[idx] = src[idx];
+ dst[idx + 1] = src[idx + 1];
+ dst[idx + 2] = src[idx + 2];
+ dst[idx + 3] = src[idx + 3];
+ } else {
+ const wAfter = mAlpha / 255;
+ const wBefore = 1 - wAfter;
+ const aB = (src[idx + 3] / 255) * wBefore;
+ const aA = (dst[idx + 3] / 255) * wAfter;
+ const outA = aB + aA;
+ if (outA <= 0.0001) {
+ dst[idx] = 0;
+ dst[idx + 1] = 0;
+ dst[idx + 2] = 0;
+ dst[idx + 3] = 0;
+ } else {
+ dst[idx] = Math.round((src[idx] * aB + dst[idx] * aA) / outA);
+ dst[idx + 1] = Math.round((src[idx + 1] * aB + dst[idx + 1] * aA) / outA);
+ dst[idx + 2] = Math.round((src[idx + 2] * aB + dst[idx + 2] * aA) / outA);
+ dst[idx + 3] = Math.round(outA * 255);
+ }
+ }
+ }
+ }
+}
+
interface UseCanvasDrawingProps {
tool: ToolType;
brushSettings: BrushSettings;
dimensions: CanvasDimensions;
+ selection?: CanvasSelection | null;
colorMode?: CanvasColorMode;
disabled?: boolean;
viewportRef: React.RefObject<HTMLDivElement | null>;
@@ -80,12 +170,14 @@ interface UseCanvasDrawingProps {
onCollabCursorMove?: (x: number, y: number, isDrawing: boolean, tool: ToolType) => void;
perspectiveRuler?: PerspectiveRuler | null;
onActiveConstraintAxisChange?: (axis: ConstraintAxis | null) => void;
+ activeSessionId?: string | null;
}
export function useCanvasDrawing({
tool,
brushSettings,
dimensions,
+ selection = null,
colorMode = 'color',
disabled = false,
viewportRef,
@@ -93,6 +185,7 @@ export function useCanvasDrawing({
zoom,
rotation,
activeLayerId,
+ activeSessionId,
activeLayerLocked = false,
activeLayerVisible = true,
layerCanvasesRef,
@@ -164,6 +257,7 @@ export function useCanvasDrawing({
const activeLayerLockedRef = useRef(activeLayerLocked);
const activeLayerVisibleRef = useRef(activeLayerVisible);
const dimensionsRef = useRef(dimensions);
+ const selectionRef = useRef(selection);
const isMaskModeRef = useRef(isMaskMode);
const onUpdateMaskThumbnailRef = useRef(onUpdateMaskThumbnail);
@@ -178,6 +272,7 @@ export function useCanvasDrawing({
activeLayerLockedRef.current = activeLayerLocked;
activeLayerVisibleRef.current = activeLayerVisible;
dimensionsRef.current = dimensions;
+ selectionRef.current = selection;
layersRef.current = layers;
isMaskModeRef.current = isMaskMode;
onUpdateMaskThumbnailRef.current = onUpdateMaskThumbnail;
@@ -256,43 +351,44 @@ export function useCanvasDrawing({
const activeReservoirRef = useRef<PaintReservoir | null>(null);
const layerPixelSamplerRef = useRef<LayerPixelSampler | null>(null);
const strokeBackupCanvasRef = useRef<HTMLCanvasElement | null>(null);
- const dedicatedBackupCanvasRef = useRef<HTMLCanvasElement | null>(null);
- const docDraftCanvasRef = useRef<HTMLCanvasElement | null>(null);
-
- const getDedicatedBackupCanvas = useCallback((width: number, height: number): HTMLCanvasElement => {
- if (!dedicatedBackupCanvasRef.current) {
- dedicatedBackupCanvasRef.current = document.createElement('canvas');
- }
- const c = dedicatedBackupCanvasRef.current;
- if (c.width !== width || c.height !== height) {
- c.width = width;
- c.height = height;
- }
- return c;
- }, []);
-
- const getDocDraftCanvas = useCallback((width: number, height: number): HTMLCanvasElement => {
- if (!docDraftCanvasRef.current) {
- docDraftCanvasRef.current = document.createElement('canvas');
- }
- const c = docDraftCanvasRef.current;
- if (c.width !== width || c.height !== height) {
- c.width = width;
- c.height = height;
- }
- return c;
- }, []);
const isWetColorStrokeRef = useRef<boolean>(false);
const drewDirectlyOnLayerCanvasRef = useRef<boolean>(false);
+ const liveStrokeIsolationRef = useRef<boolean>(false);
+ const liveAccumCanvasRef = useRef<HTMLCanvasElement | null>(null);
+ const liveOrigCanvasTilesRef = useRef<Map<number, ImageData>>(new Map());
+ const liveBeforeTileSnapshotRef = useRef<Map<string, { format: TileFormat; data: Uint8Array | null }>>(new Map());
+ const liveNeedsNotifyRef = useRef<boolean>(false);
+ const lastStrokeEndRef = useRef<{ x: number; y: number; pressure: number; width: number; layerId: string } | null>(null);
+ const isShiftLineStrokeRef = useRef<boolean>(false);
+ const historyQueueRef = useRef<Promise<void>>(Promise.resolve());
const lastPointTimeRef = useRef<number>(0);
const recentPointsTrailRef = useRef<{ x: number; y: number; t: number; pressure: number; width: number }[]>([]);
const strokeTotalDistanceRef = useRef<number>(0);
// Dirty bounding box for the active stroke
const dirtyRectRef = useRef<{ minX: number; minY: number; maxX: number; maxY: number } | null>(null);
+ const touchedTilesRef = useRef<Set<number>>(new Set());
const lastProcessedPointRef = useRef<{ x: number; y: number } | null>(null);
+ const markTouchedTiles = useCallback((minX: number, minY: number, maxX: number, maxY: number) => {
+ const dims = dimensionsRef.current;
+ const clampedMinX = Math.max(0, Math.floor(minX));
+ const clampedMinY = Math.max(0, Math.floor(minY));
+ const clampedMaxX = Math.min(dims.width, Math.ceil(maxX));
+ const clampedMaxY = Math.min(dims.height, Math.ceil(maxY));
+ if (clampedMaxX <= clampedMinX || clampedMaxY <= clampedMinY) return;
+ const minTx = clampedMinX >> 8;
+ const minTy = clampedMinY >> 8;
+ const maxTx = (clampedMaxX - 1) >> 8;
+ const maxTy = (clampedMaxY - 1) >> 8;
+ for (let ty = minTy; ty <= maxTy; ty++) {
+ for (let tx = minTx; tx <= maxTx; tx++) {
+ touchedTilesRef.current.add(ty * 65536 + tx);
+ }
+ }
+ }, []);
+
// Queue of incoming pointer coordinates to be batched and processed via requestAnimationFrame (rAF)
const pendingPointsQueueRef = useRef<{ x: number; y: number; pressure: number; pointerType: string; tiltX?: number; tiltY?: number; twist?: number; timestamp?: number }[]>([]);
const drawRafIdRef = useRef<number | null>(null);
@@ -326,8 +422,14 @@ export function useCanvasDrawing({
cachedViewportRectRef.current = null;
};
window.addEventListener('resize', handleResize);
+ let ro: ResizeObserver | null = null;
+ if (typeof ResizeObserver !== 'undefined' && viewportRef.current) {
+ ro = new ResizeObserver(handleResize);
+ ro.observe(viewportRef.current);
+ }
return () => {
window.removeEventListener('resize', handleResize);
+ ro?.disconnect();
if (clearDraftRafRef.current !== null) {
cancelAnimationFrame(clearDraftRafRef.current);
}
@@ -335,7 +437,7 @@ export function useCanvasDrawing({
cancelAnimationFrame(drawRafIdRef.current);
}
};
- }, []);
+ }, [viewportRef]);
const dispatchPointerStat = useCallback((x: number | null, y: number | null, pressure: number) => {
pendingStatRef.current = {
@@ -395,11 +497,16 @@ export function useCanvasDrawing({
const ensureInitialHistory = useCallback(
(canvas: HTMLCanvasElement, _ctx: CanvasRenderingContext2D) => {
if (historyRef.current.length === 0) {
- const initialThumb = createCanvasThumbnail(canvas, activeLayerIdRef.current !== 'layer-bg');
const now = Date.now();
-
- const isMono = colorModeRef.current === 'monochrome';
- globalTileGrid.ingestCanvas(activeLayerIdRef.current, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ const isMono = !isBackgroundLayerId(activeLayerIdRef.current) && colorModeRef.current === 'monochrome';
+ if (!globalTileGrid.isLayerIngested(activeLayerIdRef.current)) {
+ globalTileGrid.ingestCanvas(activeLayerIdRef.current, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ }
+ const isLarge = canvas.width * canvas.height > 1024 * 1024;
+ const targetH = Math.max(38, Math.round((canvas.height / Math.max(1, canvas.width)) * 60));
+ const initialThumb = isLarge
+ ? globalTileGrid.generateThumbnail(activeLayerIdRef.current, 60, targetH, { width: canvas.width, height: canvas.height })
+ : createCanvasThumbnail(canvas, !isBackgroundLayerId(activeLayerIdRef.current));
const initialItem: HistoryItem = {
id: `hist-init-${now}`,
@@ -433,7 +540,8 @@ export function useCanvasDrawing({
explicitTileDeltas?: TileDelta[],
vectorDelta?: { before: VectorStroke[]; after: VectorStroke[] },
peerId?: string | number,
- strokeId?: string
+ strokeId?: string,
+ isMaskEdit?: boolean
) => {
const now = Date.now();
const canvas = layerCanvasesRef.current.get(targetLayerId) || getActiveCanvas();
@@ -442,16 +550,24 @@ export function useCanvasDrawing({
const effectiveDirtyRect = dirtyRect || (canvas ? { x: 0, y: 0, width: canvas.width, height: canvas.height } : undefined);
- // Automatically convert ImageData change into minimal SparseTileGrid TileDeltas
- if (!tileDeltas && effectiveDirtyRect && (beforeData || afterData)) {
+ // Automatically convert ImageData change into minimal SparseTileGrid TileDeltas (skip for mask edits)
+ if (!isMaskEdit && !tileDeltas && effectiveDirtyRect && (beforeData || afterData)) {
const activeLayer = layersRef.current?.find((l) => l.id === targetLayerId);
- const isMono = colorModeRef.current === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
+ const isMono = !isBackgroundLayerId(targetLayerId) && (colorModeRef.current === 'monochrome' || activeLayer?.expressionColor === 'monochrome');
const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
+ if (beforeData) {
+ const bx = beforeData.width === effectiveDirtyRect.width && beforeData.height === effectiveDirtyRect.height ? effectiveDirtyRect.x : 0;
+ const by = beforeData.width === effectiveDirtyRect.width && beforeData.height === effectiveDirtyRect.height ? effectiveDirtyRect.y : 0;
+ globalTileGrid.writeImageData(targetLayerId, beforeData, bx, by, targetFormat);
+ }
+
const beforeSnapshot = globalTileGrid.snapshotTilesInRect(targetLayerId, effectiveDirtyRect);
if (afterData) {
- globalTileGrid.writeImageData(targetLayerId, afterData, effectiveDirtyRect.x, effectiveDirtyRect.y, targetFormat);
+ const ax = afterData.width === effectiveDirtyRect.width && afterData.height === effectiveDirtyRect.height ? effectiveDirtyRect.x : 0;
+ const ay = afterData.width === effectiveDirtyRect.width && afterData.height === effectiveDirtyRect.height ? effectiveDirtyRect.y : 0;
+ globalTileGrid.writeImageData(targetLayerId, afterData, ax, ay, targetFormat);
} else if (actionType === 'clear') {
globalTileGrid.clearLayer(targetLayerId);
}
@@ -459,6 +575,8 @@ export function useCanvasDrawing({
tileDeltas = globalTileGrid.computeDeltasFromSnapshot(beforeSnapshot, targetLayerId, effectiveDirtyRect);
}
+ const hasDeltas = Boolean(tileDeltas && tileDeltas.length > 0);
+
const item: HistoryItem = {
id: `hist-${now}-${Math.random().toString(36).substring(2, 7)}`,
type: actionType,
@@ -468,14 +586,15 @@ export function useCanvasDrawing({
thumbnailUrl: '',
layerId: targetLayerId,
// Memory optimization for 600 DPI manga: eliminate large 35MP ImageData arrays in RAM when tile deltas exist
- beforeImageData: tileDeltas ? null : beforeData,
- afterImageData: tileDeltas ? null : afterData,
- imageData: tileDeltas ? undefined : (afterData || undefined),
+ beforeImageData: hasDeltas ? null : beforeData,
+ afterImageData: hasDeltas ? null : afterData,
+ imageData: hasDeltas ? undefined : (afterData || undefined),
dirtyRect: effectiveDirtyRect,
- tileDeltas,
+ tileDeltas: hasDeltas ? tileDeltas : undefined,
vectorStrokesDelta: vectorDelta,
peerId,
strokeId,
+ isMaskEdit,
};
// Branching: truncate any future redo steps
@@ -489,6 +608,14 @@ export function useCanvasDrawing({
historyRef.current = newHistory;
historyIndexRef.current = newHistory.length - 1;
+
+ if (canvas) {
+ const isLarge = canvas.width * canvas.height > 1024 * 1024 && globalTileGrid.isLayerIngested(targetLayerId);
+ const targetH = Math.max(38, Math.round((canvas.height / Math.max(1, canvas.width)) * 60));
+ item.thumbnailUrl = isLarge
+ ? globalTileGrid.generateThumbnail(targetLayerId, 60, targetH, { width: canvas.width, height: canvas.height })
+ : createCanvasThumbnail(canvas, !isBackgroundLayerId(targetLayerId));
+ }
syncHistoryState();
// Seamless LRU disk cache offloading via Tauri v2 Rust IPC
@@ -498,13 +625,11 @@ export function useCanvasDrawing({
});
}
- // Defer thumbnail generation so stroke release is 100% instant
- requestAnimationFrame(() => {
- if (canvas) {
- item.thumbnailUrl = createCanvasThumbnail(canvas, targetLayerId !== 'layer-bg');
- syncHistoryState();
- }
- });
+ // Non-blocking WAL journaling for crash recovery
+ if ((tileDeltas && tileDeltas.length > 0) || vectorDelta) {
+ const sessionKey = activeSessionId || recoveryService.getCurrentSessionId() || 'default-session';
+ recoveryService.logStrokeDelta(sessionKey, tileDeltas, vectorDelta, targetLayerId);
+ }
},
[getActiveCanvas, layerCanvasesRef, syncHistoryState]
);
@@ -535,8 +660,19 @@ export function useCanvasDrawing({
const enqueueHistoryTask = useCallback((task: () => void) => {
pendingHistoryTasksRef.current.push(task);
if (idleCallbackIdRef.current === null) {
+ const scheduleRun = () => {
+ if (typeof window !== 'undefined' && 'requestIdleCallback' in window) {
+ idleCallbackIdRef.current = (window as any).requestIdleCallback(runTasks, { timeout: 250 });
+ } else {
+ idleCallbackIdRef.current = setTimeout(runTasks, 32);
+ }
+ };
const runTasks = () => {
idleCallbackIdRef.current = null;
+ if (isDrawingRef.current) {
+ scheduleRun();
+ return;
+ }
const tasks = pendingHistoryTasksRef.current.splice(0);
for (const t of tasks) {
try {
@@ -546,14 +682,182 @@ export function useCanvasDrawing({
}
}
};
- if (typeof window !== 'undefined' && 'requestIdleCallback' in window) {
- idleCallbackIdRef.current = (window as any).requestIdleCallback(runTasks, { timeout: 120 });
- } else {
- idleCallbackIdRef.current = setTimeout(runTasks, 0);
- }
+ scheduleRun();
+ }
+ }, []);
+
+ // Helper to restore all live-backed-up tiles back onto a layer canvas
+ const restoreLiveOrigTilesToCanvas = useCallback((canvas: HTMLCanvasElement) => {
+ if (liveOrigCanvasTilesRef.current.size === 0) return;
+ const cCtx = get2DContext(canvas);
+ if (!cCtx) return;
+ for (const [numKey, tileImg] of liveOrigCanvasTilesRef.current) {
+ const ty = Math.floor(numKey / 65536);
+ const tx = numKey % 65536;
+ cCtx.putImageData(tileImg, tx * TILE_SIZE, ty * TILE_SIZE);
}
}, []);
+ // Helper to restore a specific sub-rectangle on `canvasCtx` from `liveOrigCanvasTilesRef`
+ const restoreLiveRectFromOrigTiles = useCallback(
+ (canvasCtx: CanvasRenderingContext2D, rx: number, ry: number, rw: number, rh: number) => {
+ if (rw <= 0 || rh <= 0 || liveOrigCanvasTilesRef.current.size === 0) return;
+ const minTx = rx >> 8;
+ const minTy = ry >> 8;
+ const maxTx = (rx + rw - 1) >> 8;
+ const maxTy = (ry + rh - 1) >> 8;
+ for (let ty = minTy; ty <= maxTy; ty++) {
+ for (let tx = minTx; tx <= maxTx; tx++) {
+ const tileImg = liveOrigCanvasTilesRef.current.get(ty * 65536 + tx);
+ if (!tileImg) continue;
+ const tileOriginX = tx * TILE_SIZE;
+ const tileOriginY = ty * TILE_SIZE;
+ const ix0 = Math.max(rx, tileOriginX);
+ const iy0 = Math.max(ry, tileOriginY);
+ const ix1 = Math.min(rx + rw, tileOriginX + tileImg.width);
+ const iy1 = Math.min(ry + rh, tileOriginY + tileImg.height);
+ if (ix1 > ix0 && iy1 > iy0) {
+ canvasCtx.putImageData(
+ tileImg,
+ tileOriginX,
+ tileOriginY,
+ ix0 - tileOriginX,
+ iy0 - tileOriginY,
+ ix1 - ix0,
+ iy1 - iy0
+ );
+ }
+ }
+ }
+ },
+ []
+ );
+
+ // Lazily snapshot pre-stroke tiles in both SparseTileGrid and canvas ImageData before live mutation
+ const ensureLiveTileSnapshots = useCallback(
+ (
+ canvas: HTMLCanvasElement,
+ canvasCtx: CanvasRenderingContext2D,
+ layerId: string,
+ minX: number,
+ minY: number,
+ maxX: number,
+ maxY: number
+ ) => {
+ const cMinX = Math.max(0, Math.floor(minX));
+ const cMinY = Math.max(0, Math.floor(minY));
+ const cMaxX = Math.min(canvas.width, Math.ceil(maxX));
+ const cMaxY = Math.min(canvas.height, Math.ceil(maxY));
+ if (cMaxX <= cMinX || cMaxY <= cMinY) return;
+
+ const minTx = cMinX >> 8;
+ const minTy = cMinY >> 8;
+ const maxTx = (cMaxX - 1) >> 8;
+ const maxTy = (cMaxY - 1) >> 8;
+
+ for (let ty = minTy; ty <= maxTy; ty++) {
+ for (let tx = minTx; tx <= maxTx; tx++) {
+ const numKey = ty * 65536 + tx;
+ if (!liveOrigCanvasTilesRef.current.has(numKey)) {
+ const ox = tx * TILE_SIZE;
+ const oy = ty * TILE_SIZE;
+ const tw = Math.min(TILE_SIZE, canvas.width - ox);
+ const th = Math.min(TILE_SIZE, canvas.height - oy);
+ if (tw <= 0 || th <= 0) continue;
+ const subSnap = globalTileGrid.snapshotTilesInRect(layerId, {
+ x: ox,
+ y: oy,
+ width: tw,
+ height: th,
+ });
+ for (const [k, v] of subSnap) {
+ if (!liveBeforeTileSnapshotRef.current.has(k)) {
+ liveBeforeTileSnapshotRef.current.set(k, v);
+ }
+ }
+ liveOrigCanvasTilesRef.current.set(numKey, canvasCtx.getImageData(ox, oy, tw, th));
+ }
+ }
+ }
+ },
+ []
+ );
+
+ // Sync a small mutated region of `canvas` into `globalTileGrid` during Live WYSIWYG preview
+ const syncLiveRegionToTiles = useCallback(
+ (
+ canvas: HTMLCanvasElement,
+ canvasCtx: CanvasRenderingContext2D,
+ layerId: string,
+ minX: number,
+ minY: number,
+ maxX: number,
+ maxY: number,
+ isMonochrome: boolean,
+ activeLayer: LayerItem | undefined,
+ bs: BrushSettings,
+ isEraser: boolean,
+ isBgEraser: boolean
+ ) => {
+ const rx = Math.max(0, Math.floor(minX));
+ const ry = Math.max(0, Math.floor(minY));
+ const rw = Math.min(canvas.width, Math.ceil(maxX)) - rx;
+ const rh = Math.min(canvas.height, Math.ceil(maxY)) - ry;
+ if (rw <= 0 || rh <= 0) return;
+
+ ensureLiveTileSnapshots(canvas, canvasCtx, layerId, rx, ry, rx + rw, ry + rh);
+
+ if (liveStrokeIsolationRef.current && liveAccumCanvasRef.current) {
+ restoreLiveRectFromOrigTiles(canvasCtx, rx, ry, rw, rh);
+ canvasCtx.save();
+ canvasCtx.beginPath();
+ canvasCtx.rect(rx, ry, rw, rh);
+ canvasCtx.clip();
+ applySelectionCanvasClip(canvasCtx, selectionRef.current);
+ canvasCtx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
+ if ((isEraser && !isBgEraser) || bs.isTransparentInk) {
+ canvasCtx.globalCompositeOperation = 'destination-out';
+ } else if (activeLayer?.alphaLocked) {
+ canvasCtx.globalCompositeOperation = 'source-atop';
+ } else {
+ canvasCtx.globalCompositeOperation = 'source-over';
+ }
+ canvasCtx.drawImage(liveAccumCanvasRef.current, rx, ry, rw, rh, rx, ry, rw, rh);
+ canvasCtx.restore();
+ }
+
+ const segData = canvasCtx.getImageData(rx, ry, rw, rh);
+ if (selectionRef.current?.mask) {
+ // Reconstruct before pixels for exact 8-bit selection mask blending
+ restoreLiveRectFromOrigTiles(canvasCtx, rx, ry, rw, rh);
+ const beforeSub = canvasCtx.getImageData(rx, ry, rw, rh);
+ applySelectionMaskToImageData(beforeSub, segData, rx, ry, selectionRef.current);
+ canvasCtx.putImageData(segData, rx, ry);
+ }
+
+ if (isMonochrome) {
+ binarizeImageDataBuffer(
+ segData,
+ activeLayer?.monoThreshold ?? 128,
+ activeLayer?.monoExpressBlack ?? true,
+ activeLayer?.monoExpressWhite ?? true
+ );
+ canvasCtx.putImageData(segData, rx, ry);
+ }
+
+ globalTileGrid.writeImageData(
+ layerId,
+ segData,
+ rx,
+ ry,
+ isMonochrome ? 'monochrome-1bit' : 'color-32bit',
+ true
+ );
+ liveNeedsNotifyRef.current = true;
+ },
+ [ensureLiveTileSnapshots, restoreLiveRectFromOrigTiles]
+ );
+
// Abort any in-progress stroke session immediately
const abortActiveStroke = useCallback(() => {
if (!isDrawingRef.current) return;
@@ -572,19 +876,31 @@ export function useCanvasDrawing({
dCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
}
}
- if (docDraftCanvasRef.current) {
- const docCtx = get2DContext(docDraftCanvasRef.current);
- docCtx?.clearRect(0, 0, docDraftCanvasRef.current.width, docDraftCanvasRef.current.height);
- }
clearPredictedCanvas();
- if (drewDirectlyOnLayerCanvasRef.current && strokeBackupCanvasRef.current) {
+ if (drewDirectlyOnLayerCanvasRef.current) {
const currentLayerId = activeLayerIdRef.current;
const canvas = layerCanvasesRef.current.get(currentLayerId) || getActiveCanvas();
- if (canvas && strokeBackupCanvasRef.current) {
+ if (canvas) {
+ restoreLiveOrigTilesToCanvas(canvas);
const cCtx = get2DContext(canvas);
if (cCtx) {
- cCtx.clearRect(0, 0, canvas.width, canvas.height);
- cCtx.drawImage(strokeBackupCanvasRef.current, 0, 0);
+ const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);
+ const isMono =
+ !isBackgroundLayerId(currentLayerId) &&
+ (colorModeRef.current === 'monochrome' || activeLayer?.expressionColor === 'monochrome');
+ for (const [numKey, tileImg] of liveOrigCanvasTilesRef.current) {
+ const ty = Math.floor(numKey / 65536);
+ const tx = numKey % 65536;
+ globalTileGrid.writeImageData(
+ currentLayerId,
+ tileImg,
+ tx * TILE_SIZE,
+ ty * TILE_SIZE,
+ isMono ? 'monochrome-1bit' : 'color-32bit',
+ true
+ );
+ }
+ globalTileGrid.notifyChange(true);
}
}
}
@@ -595,41 +911,57 @@ export function useCanvasDrawing({
stabilizedPointRef.current = null;
lastProcessedPointRef.current = null;
dirtyRectRef.current = null;
+ touchedTilesRef.current.clear();
pendingPointsQueueRef.current = [];
drewDirectlyOnLayerCanvasRef.current = false;
+ liveStrokeIsolationRef.current = false;
+ liveOrigCanvasTilesRef.current.clear();
+ liveBeforeTileSnapshotRef.current.clear();
+ liveNeedsNotifyRef.current = false;
+ isShiftLineStrokeRef.current = false;
isToneStrokeRef.current = false;
strokeBackupCanvasRef.current = null;
layerPixelSamplerRef.current = null;
activeReservoirRef.current = null;
snapSessionRef.current.endStroke();
emitConstraintAxisChange(null);
- }, [clearPredictedCanvas, effectiveDraftCanvasRef, emitConstraintAxisChange, getActiveCanvas, layerCanvasesRef]);
+ }, [clearPredictedCanvas, effectiveDraftCanvasRef, emitConstraintAxisChange, getActiveCanvas, layerCanvasesRef, restoreLiveOrigTilesToCanvas]);
- // Jump directly to any past or future history step
+ // Jump directly to any past or future history step (serialized via historyQueueRef to prevent async race on rapid Ctrl+Z)
const jumpToHistoryIndex = useCallback(
- async (targetIndex: number) => {
+ (targetIndex: number): Promise<void> => {
flushPendingHistoryTasks();
if (isDrawingRef.current) {
abortActiveStroke();
}
- if (targetIndex < 0 || targetIndex >= historyRef.current.length) return;
- const currentIndex = historyIndexRef.current;
- if (targetIndex === currentIndex) return;
-
- if (targetIndex < currentIndex) {
- // Rolling back (undoing) in reverse chronological order
- for (let i = currentIndex; i > targetIndex; i--) {
- const item = historyRef.current[i];
- if (item) {
- const targetLayerId = item.layerId || activeLayerId;
- const canvas = layerCanvasesRef.current.get(targetLayerId) || getActiveCanvas();
- const sourceCanvas = layerSourceCanvasesRef?.current?.get(targetLayerId);
- const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);
- const isToneStep = Boolean(targetLayer?.toneEnabled && sourceCanvas);
- const deltas = await globalUndoCache.resolveDeltas(item);
-
- // Restore vector strokes if vector delta exists
- if (item.vectorStrokesDelta && targetLayer && canvas) {
+ const nextOp = historyQueueRef.current.then(async () => {
+ if (targetIndex < 0 || targetIndex >= historyRef.current.length) return;
+ const currentIndex = historyIndexRef.current;
+ if (targetIndex === currentIndex) return;
+
+ if (targetIndex < currentIndex) {
+ // Rolling back (undoing) in reverse chronological order
+ for (let i = currentIndex; i > targetIndex; i--) {
+ const item = historyRef.current[i];
+ if (item) {
+ const targetLayerId = item.layerId || activeLayerId;
+ const canvas = layerCanvasesRef.current.get(targetLayerId) || null;
+ const sourceCanvas = layerSourceCanvasesRef?.current?.get(targetLayerId);
+ const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);
+ const isToneStep = Boolean(targetLayer?.toneEnabled && sourceCanvas);
+ const deltas = await globalUndoCache.resolveDeltas(item);
+
+ // Restore mask canvas if mask edit
+ 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);
+ }
+ } else if (item.vectorStrokesDelta && targetLayer && canvas) {
targetLayer.vectorStrokes = item.vectorStrokesDelta.before;
const cCtx = get2DContext(canvas);
if (cCtx) {
@@ -667,7 +999,7 @@ export function useCanvasDrawing({
} else if (item.beforeImageData) {
sCtx.putImageData(item.beforeImageData, 0, 0);
} else if (item.type === 'initial') {
- if (targetLayerId === 'layer-bg') {
+ if (isBackgroundLayerId(targetLayerId)) {
sCtx.fillStyle = '#ffffff';
sCtx.fillRect(0, 0, sourceCanvas.width, sourceCanvas.height);
} else {
@@ -690,18 +1022,20 @@ export function useCanvasDrawing({
if (canvas) {
const cCtx = get2DContext(canvas);
if (cCtx) {
- if (item.dirtyRect && item.beforeImageData) {
+ if (item.dirtyRect && item.beforeImageData && item.beforeImageData.width === item.dirtyRect.width && item.beforeImageData.height === item.dirtyRect.height) {
cCtx.putImageData(item.beforeImageData, item.dirtyRect.x, item.dirtyRect.y);
} else if (item.beforeImageData) {
cCtx.putImageData(item.beforeImageData, 0, 0);
} else if (item.type === 'initial') {
- if (targetLayerId === 'layer-bg') {
+ if (isBackgroundLayerId(targetLayerId)) {
cCtx.fillStyle = '#ffffff';
cCtx.fillRect(0, 0, canvas.width, canvas.height);
} else {
cCtx.clearRect(0, 0, canvas.width, canvas.height);
}
}
+ const isMono = !isBackgroundLayerId(targetLayerId) && (targetLayer?.expressionColor === 'monochrome' || colorModeRef.current === 'monochrome');
+ globalTileGrid.ingestCanvas(targetLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
}
}
@@ -709,12 +1043,12 @@ export function useCanvasDrawing({
if (sourceCanvas) {
const sCtx = get2DContext(sourceCanvas);
if (sCtx) {
- if (item.dirtyRect && item.beforeImageData) {
+ if (item.dirtyRect && item.beforeImageData && item.beforeImageData.width === item.dirtyRect.width && item.beforeImageData.height === item.dirtyRect.height) {
sCtx.putImageData(item.beforeImageData, item.dirtyRect.x, item.dirtyRect.y);
} else if (item.beforeImageData) {
sCtx.putImageData(item.beforeImageData, 0, 0);
} else if (item.type === 'initial') {
- if (targetLayerId === 'layer-bg') {
+ if (isBackgroundLayerId(targetLayerId)) {
sCtx.fillStyle = '#ffffff';
sCtx.fillRect(0, 0, sourceCanvas.width, sourceCanvas.height);
} else {
@@ -737,14 +1071,23 @@ export function useCanvasDrawing({
const dataToApply = item?.afterImageData || item?.imageData;
if (item) {
const targetLayerId = item.layerId || activeLayerId;
- const canvas = layerCanvasesRef.current.get(targetLayerId) || getActiveCanvas();
+ const canvas = layerCanvasesRef.current.get(targetLayerId) || null;
const sourceCanvas = layerSourceCanvasesRef?.current?.get(targetLayerId);
const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);
const isToneStep = Boolean(targetLayer?.toneEnabled && sourceCanvas);
const deltas = await globalUndoCache.resolveDeltas(item);
- // Restore vector strokes if vector delta exists
- if (item.vectorStrokesDelta && targetLayer && canvas) {
+ // Restore mask canvas if mask edit
+ 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);
+ }
+ } else if (item.vectorStrokesDelta && targetLayer && canvas) {
targetLayer.vectorStrokes = item.vectorStrokesDelta.after;
const cCtx = get2DContext(canvas);
if (cCtx) {
@@ -782,7 +1125,7 @@ export function useCanvasDrawing({
} else if (dataToApply) {
sCtx.putImageData(dataToApply, 0, 0);
} else if (item.type === 'initial') {
- if (targetLayerId === 'layer-bg') {
+ if (isBackgroundLayerId(targetLayerId)) {
sCtx.fillStyle = '#ffffff';
sCtx.fillRect(0, 0, sourceCanvas.width, sourceCanvas.height);
} else {
@@ -805,18 +1148,20 @@ export function useCanvasDrawing({
if (canvas) {
const cCtx = get2DContext(canvas);
if (cCtx) {
- if (item.dirtyRect && dataToApply) {
+ if (item.dirtyRect && dataToApply && dataToApply.width === item.dirtyRect.width && dataToApply.height === item.dirtyRect.height) {
cCtx.putImageData(dataToApply, item.dirtyRect.x, item.dirtyRect.y);
} else if (dataToApply) {
cCtx.putImageData(dataToApply, 0, 0);
} else if (item.type === 'initial') {
- if (targetLayerId === 'layer-bg') {
+ if (isBackgroundLayerId(targetLayerId)) {
cCtx.fillStyle = '#ffffff';
cCtx.fillRect(0, 0, canvas.width, canvas.height);
} else {
cCtx.clearRect(0, 0, canvas.width, canvas.height);
}
}
+ const isMono = !isBackgroundLayerId(targetLayerId) && (targetLayer?.expressionColor === 'monochrome' || colorModeRef.current === 'monochrome');
+ globalTileGrid.ingestCanvas(targetLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
}
}
@@ -824,12 +1169,12 @@ export function useCanvasDrawing({
if (sourceCanvas) {
const sCtx = get2DContext(sourceCanvas);
if (sCtx) {
- if (item.dirtyRect && dataToApply) {
+ if (item.dirtyRect && dataToApply && dataToApply.width === item.dirtyRect.width && dataToApply.height === item.dirtyRect.height) {
sCtx.putImageData(dataToApply, item.dirtyRect.x, item.dirtyRect.y);
} else if (dataToApply) {
sCtx.putImageData(dataToApply, 0, 0);
} else if (item.type === 'initial') {
- if (targetLayerId === 'layer-bg') {
+ if (isBackgroundLayerId(targetLayerId)) {
sCtx.fillStyle = '#ffffff';
sCtx.fillRect(0, 0, sourceCanvas.width, sourceCanvas.height);
} else {
@@ -847,11 +1192,16 @@ export function useCanvasDrawing({
}
}
- historyIndexRef.current = targetIndex;
- syncHistoryState();
- globalTileGrid.notifyChange(true);
+ historyIndexRef.current = targetIndex;
+ syncHistoryState();
+ globalTileGrid.notifyChange(true);
+ });
+ historyQueueRef.current = nextOp.catch((err) => {
+ console.warn('[History] Error during jumpToHistoryIndex:', err);
+ });
+ return historyQueueRef.current;
},
- [abortActiveStroke, activeLayerId, flushPendingHistoryTasks, getActiveCanvas, layerCanvasesRef, layerSourceCanvasesRef, onUpdateLayerThumbnail, syncHistoryState]
+ [abortActiveStroke, activeLayerId, flushPendingHistoryTasks, layerCanvasesRef, layerSourceCanvasesRef, onUpdateLayerThumbnail, syncHistoryState]
);
// Undo action
@@ -964,7 +1314,8 @@ export function useCanvasDrawing({
vectorDelta = { before: beforeStrokes, after: [] };
}
- if (activeLayerId === 'layer-bg') {
+ const isBg = isBackgroundLayerId(activeLayerId);
+ if (isBg) {
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, canvas.width, canvas.height);
} else {
@@ -975,7 +1326,7 @@ export function useCanvasDrawing({
if (sourceCanvas) {
const sCtx = get2DContext(sourceCanvas);
if (sCtx) {
- if (activeLayerId === 'layer-bg') {
+ if (isBg) {
sCtx.fillStyle = '#ffffff';
sCtx.fillRect(0, 0, sourceCanvas.width, sourceCanvas.height);
} else {
@@ -1063,23 +1414,146 @@ export function useCanvasDrawing({
[getViewportRect]
);
- // Render a single smooth segment onto the draft overlay context using Catmull-Rom cubic splines
+ const buildLiveTexturedOptions = useCallback(
+ (
+ bs: BrushSettings,
+ strokeFlow: number,
+ strokeSpacing: number,
+ strokeHardness: number,
+ isMonochrome: boolean,
+ canvas: HTMLCanvasElement | null,
+ activeLayer: LayerItem | undefined,
+ isEraser: boolean,
+ isBgEraser: boolean,
+ isolatedPass: boolean = false
+ ): TexturedBrushOptions => ({
+ size: bs.size,
+ minSizeFactor: bs.minSizeFactor,
+ opacity: isolatedPass ? 1.0 : bs.opacity,
+ flow: strokeFlow,
+ adjustDensityByGap: bs.adjustDensityByGap,
+ blendTipsMode: bs.blendTipsMode,
+ spacing: strokeSpacing,
+ thickness: bs.thickness,
+ thicknessVertical: bs.thicknessVertical,
+ flipH: bs.flipH,
+ flipV: bs.flipV,
+ isColorTip: bs.isColorTip,
+ angle: bs.customTipAngle,
+ angleDynamics: bs.customTipAngleDynamics,
+ rotationRandomScale: bs.customTipRotationRandomScale,
+ hardness: strokeHardness,
+ antiAlias: isMonochrome ? 0 : bs.antiAlias,
+ pressureCurve: bs.pressureCurve,
+ velocityCurve: bs.velocityCurve,
+ usePressure: bs.usePressure,
+ useVelocity: bs.useVelocity,
+ useTilt: Boolean(bs.useTilt),
+ sizeSensor: bs.sizeSensor,
+ opacitySensor: bs.opacitySensor,
+ densitySensor: bs.densitySensor,
+ subTips: bs.subTips,
+ subTipOrder: bs.subTipOrder,
+ subTipImages: bs.subTipImages,
+ spray: bs.spray,
+ taper: bs.taper,
+ colorMixing: bs.colorMixing,
+ perceptualMixing: bs.perceptualMixing,
+ amountOfPaint: bs.amountOfPaint,
+ densityOfPaint: bs.densityOfPaint,
+ colorStretch: bs.colorStretch,
+ mixingMode: bs.mixingMode,
+ wetEdge: 0,
+ grain: bs.grain ?? bs.textureDensity,
+ paperTextureMode: bs.paperTextureMode,
+ paperTextureBrightness: bs.paperTextureBrightness,
+ paperTextureContrast: bs.paperTextureContrast,
+ paperTextureInverted: bs.paperTextureInverted,
+ paperTextureImage: bs.paperTextureImage,
+ paperTextureScale: bs.paperTextureScale,
+ paperTextureRotate: bs.paperTextureRotate,
+ dualBrush: bs.dualBrush,
+ dualTipImage: bs.dualTipImage,
+ dualBrushCompositeMode: bs.dualBrushCompositeMode,
+ useGpu: bs.useGpu,
+ underlyingCanvas: canvas || undefined,
+ sampler: layerPixelSamplerRef.current || undefined,
+ reservoir: activeReservoirRef.current || undefined,
+ isEraser: isolatedPass ? false : isEraser && !isBgEraser,
+ isBgEraser: isolatedPass ? false : isBgEraser,
+ alphaLocked: isolatedPass ? false : Boolean(activeLayer?.alphaLocked),
+ isTransparentInk: isolatedPass ? false : Boolean(bs.isTransparentInk),
+ currentStrokeDist: strokeTotalDistanceRef.current,
+ dynamics: bs.dynamics,
+ secondaryColor: bs.secondaryColor,
+ }),
+ []
+ );
+
+ const buildLiveRadialOptions = useCallback(
+ (
+ bs: BrushSettings,
+ isMonochrome: boolean,
+ canvas: HTMLCanvasElement | null,
+ activeLayer: LayerItem | undefined,
+ isolatedPass: boolean = false
+ ): RadialMixingOptions => ({
+ colorMixing: bs.colorMixing,
+ perceptualMixing: bs.perceptualMixing,
+ amountOfPaint: bs.amountOfPaint,
+ densityOfPaint: bs.densityOfPaint,
+ colorStretch: bs.colorStretch,
+ mixingMode: bs.mixingMode,
+ underlyingCanvas: canvas || undefined,
+ sampler: layerPixelSamplerRef.current || undefined,
+ reservoir: activeReservoirRef.current || undefined,
+ alphaLocked: isolatedPass ? false : Boolean(activeLayer?.alphaLocked),
+ isTransparentInk: isolatedPass ? false : Boolean(bs.isTransparentInk),
+ dynamics: bs.dynamics,
+ secondaryColor: bs.secondaryColor,
+ useGpu: bs.useGpu,
+ dualBrush: bs.dualBrush,
+ dualTipImage: bs.dualTipImage,
+ dualBrushCompositeMode: bs.dualBrushCompositeMode,
+ useTilt: Boolean(bs.useTilt),
+ thicknessVertical: bs.thicknessVertical,
+ flipH: bs.flipH,
+ flipV: bs.flipV,
+ antiAlias: isMonochrome ? 0 : bs.antiAlias,
+ angleDynamics: bs.customTipAngleDynamics,
+ rotationRandomScale: bs.customTipRotationRandomScale,
+ adjustDensityByGap: bs.adjustDensityByGap,
+ blendTipsMode: bs.blendTipsMode,
+ grain: bs.grain ?? bs.textureDensity,
+ paperTextureMode: bs.paperTextureMode,
+ paperTextureBrightness: bs.paperTextureBrightness,
+ paperTextureContrast: bs.paperTextureContrast,
+ paperTextureInverted: bs.paperTextureInverted,
+ paperTextureImage: bs.paperTextureImage,
+ paperTextureScale: bs.paperTextureScale,
+ paperTextureRotate: bs.paperTextureRotate,
+ sizeSensor: bs.sizeSensor,
+ opacitySensor: bs.opacitySensor,
+ densitySensor: bs.densitySensor,
+ taper: bs.taper,
+ }),
+ []
+ );
+
+ // Render a single smooth segment onto either Live Direct Layer/Tile preview or the viewport draft overlay
const renderDraftSegment = useCallback((draftCtx: CanvasRenderingContext2D, point: Point) => {
const pts = strokePointsRef.current;
const isEraser = toolRef.current === 'eraser';
- const isBgEraser = isEraser && activeLayerIdRef.current === 'layer-bg';
+ const isBgEraser = isEraser && isBackgroundLayerId(activeLayerIdRef.current);
const bs = brushSettingsRef.current;
const mode = colorModeRef.current;
- const isPencil = !isEraser && (bs.preset?.startsWith('pencil') ?? false);
+ const isPencil = !isEraser && !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
const canvas = getActiveCanvas();
const currentLayerId = activeLayerIdRef.current;
const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);
- const isToneLayer = Boolean(activeLayer?.toneEnabled);
const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
const isMonochrome = mode === 'monochrome' || isMonoLayer;
- const isTone = isToneStrokeRef.current;
- const sourceCanvas = isTone ? layerSourceCanvasesRef?.current?.get(currentLayerId) : null;
let strokeColor: string;
if (isMaskModeRef.current) {
@@ -1099,70 +1573,45 @@ export function useCanvasDrawing({
strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, isMonochrome ? 'monochrome' : mode);
}
const strokeHardness = isMonochrome ? 1.0 : (bs.hardness ?? 1.0);
- const strokeFlow = bs.flow ?? 1.0;
- const strokeSpacing = bs.spacing ?? 0.08;
-
- const renderSegmentToContext = (ctx: CanvasRenderingContext2D, sStart: Point, c1Pt: Point, c2Pt: Point, sEnd: Point): number => {
+ const baseFlow = isMonochrome ? 1.0 : (bs.flow ?? 1.0);
+ const baseSpacing = bs.spacing ?? 0.08;
+ const curZoom = Math.max(0.05, zoomRef.current || 1.0);
+ const avgW = Math.max(1, ((pts[pts.length - 1]?.width || bs.size || 10) + (point.width || bs.size || 10)) * 0.5);
+ const strokeSpacing = curZoom < 0.75
+ ? Math.max(baseSpacing, Math.min(0.14, (0.45 / curZoom) / avgW))
+ : baseSpacing;
+ const strokeFlow = strokeSpacing > baseSpacing && baseFlow < 0.995
+ ? 1.0 - Math.pow(1.0 - baseFlow, strokeSpacing / Math.max(0.01, baseSpacing))
+ : baseFlow;
+
+ const renderSegmentToContext = (
+ ctx: CanvasRenderingContext2D,
+ sStart: Point,
+ c1Pt: Point,
+ c2Pt: Point,
+ sEnd: Point,
+ isolatedPass: boolean = false
+ ): number => {
if (bs.customTipImage) {
- const tipOptions: TexturedBrushOptions = {
- size: bs.size,
- minSizeFactor: bs.minSizeFactor,
- opacity: bs.opacity,
- flow: strokeFlow,
- spacing: strokeSpacing,
- thickness: bs.thickness,
- thicknessVertical: bs.thicknessVertical,
- angle: bs.customTipAngle,
- angleDynamics: bs.customTipAngleDynamics,
- rotationRandomScale: bs.customTipRotationRandomScale,
- hardness: strokeHardness,
- antiAlias: isMonochrome ? 0 : bs.antiAlias,
- pressureCurve: bs.pressureCurve,
- velocityCurve: bs.velocityCurve,
- usePressure: bs.usePressure,
- useVelocity: bs.useVelocity,
- subTips: bs.subTips,
- subTipOrder: bs.subTipOrder,
- subTipImages: bs.subTipImages,
- spray: bs.spray,
- taper: bs.taper,
- colorMixing: bs.colorMixing,
- perceptualMixing: bs.perceptualMixing,
- amountOfPaint: bs.amountOfPaint,
- densityOfPaint: bs.densityOfPaint,
- colorStretch: bs.colorStretch,
- mixingMode: bs.mixingMode,
- wetEdge: bs.wetEdge,
- wetEdgeRadius: bs.wetEdgeRadius,
- wetEdgeAlphaPower: bs.wetEdgeAlphaPower,
- wetEdgeValuePower: bs.wetEdgeValuePower,
- grain: bs.grain ?? bs.textureDensity,
- paperTextureImage: bs.paperTextureImage,
- paperTextureScale: bs.paperTextureScale,
- paperTextureRotate: bs.paperTextureRotate,
- dualBrush: bs.dualBrush,
- dualTipImage: bs.dualTipImage,
- dualBrushCompositeMode: bs.dualBrushCompositeMode,
- useGpu: bs.useGpu,
- underlyingCanvas: canvas || undefined,
- sampler: layerPixelSamplerRef.current || undefined,
- reservoir: activeReservoirRef.current || undefined,
- isEraser: isEraser && !isBgEraser,
+ const tipOptions = buildLiveTexturedOptions(
+ bs,
+ strokeFlow,
+ strokeSpacing,
+ strokeHardness,
+ isMonochrome,
+ canvas,
+ activeLayer,
+ isEraser,
isBgEraser,
- alphaLocked: Boolean(activeLayer?.alphaLocked),
- isTransparentInk: Boolean(bs.isTransparentInk),
- currentStrokeDist: strokeTotalDistanceRef.current,
- dynamics: bs.dynamics,
- secondaryColor: bs.secondaryColor,
- };
-
+ isolatedPass
+ );
return drawTexturedCubicBezierSegment(
ctx,
sStart,
c1Pt,
c2Pt,
sEnd,
- strokeColor,
+ isolatedPass && isEraser && !isBgEraser ? '#000000' : strokeColor,
bs.customTipImage,
tipOptions,
stampRemainderDistRef.current
@@ -1177,41 +1626,30 @@ export function useCanvasDrawing({
sEnd,
strokeColor,
grade,
- bs.flow ?? 0.74,
+ isMonochrome ? 1.0 : (bs.flow ?? 0.74),
bs.grain ?? 1.0,
- bs.hardness,
+ strokeHardness,
stampRemainderDistRef.current,
- Boolean(activeLayer?.alphaLocked),
- Boolean(bs.isTransparentInk)
+ isolatedPass ? false : Boolean(activeLayer?.alphaLocked),
+ isolatedPass ? false : Boolean(bs.isTransparentInk),
+ bs.useTilt ?? true
);
} else {
- const radialMixingOptions: RadialMixingOptions = {
- colorMixing: bs.colorMixing,
- perceptualMixing: bs.perceptualMixing,
- amountOfPaint: bs.amountOfPaint,
- densityOfPaint: bs.densityOfPaint,
- colorStretch: bs.colorStretch,
- mixingMode: bs.mixingMode,
- underlyingCanvas: canvas || undefined,
- sampler: layerPixelSamplerRef.current || undefined,
- reservoir: activeReservoirRef.current || undefined,
- alphaLocked: Boolean(activeLayer?.alphaLocked),
- isTransparentInk: Boolean(bs.isTransparentInk),
- dynamics: bs.dynamics,
- secondaryColor: bs.secondaryColor,
- useGpu: bs.useGpu,
- dualBrush: bs.dualBrush,
- dualTipImage: bs.dualTipImage,
- dualBrushCompositeMode: bs.dualBrushCompositeMode,
- };
+ const radialMixingOptions = buildLiveRadialOptions(
+ bs,
+ isMonochrome,
+ canvas,
+ activeLayer,
+ isolatedPass
+ );
return drawSmoothCubicBezierSegment(
ctx,
sStart,
c1Pt,
c2Pt,
sEnd,
- strokeColor,
- isEraser && !isBgEraser,
+ isolatedPass && isEraser && !isBgEraser ? '#000000' : strokeColor,
+ isolatedPass ? false : isEraser && !isBgEraser,
strokeHardness,
strokeFlow,
strokeSpacing,
@@ -1251,44 +1689,53 @@ export function useCanvasDrawing({
const segStart = k1;
const segEnd = k2;
- if (isEraser) {
- drewDirectlyOnLayerCanvasRef.current = true;
- if (canvas) {
- const cCtx = get2DContext(canvas);
- if (cCtx) {
- drawSmoothCubicBezierSegment(
- cCtx,
- segStart,
- c1,
- c2,
- segEnd,
- strokeColor,
- !isBgEraser,
- strokeHardness,
- strokeFlow,
- strokeSpacing
- );
- }
- }
- if (isToneLayer && sourceCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- if (sCtx) {
- drawSmoothCubicBezierSegment(
- sCtx,
- segStart,
- c1,
- c2,
- segEnd,
- strokeColor,
- !isBgEraser,
- strokeHardness,
- strokeFlow,
- strokeSpacing
- );
+ const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
+ const segPad = Math.ceil(Math.max(segStart.width, segEnd.width, bs.size || 10) * (1.5 + scatterFactor * 2) + 32);
+ const segMinX = Math.min(segStart.x, c1.x, c2.x, segEnd.x) - segPad;
+ const segMinY = Math.min(segStart.y, c1.y, c2.y, segEnd.y) - segPad;
+ const segMaxX = Math.max(segStart.x, c1.x, c2.x, segEnd.x) + segPad;
+ const segMaxY = Math.max(segStart.y, c1.y, c2.y, segEnd.y) + segPad;
+ markTouchedTiles(segMinX, segMinY, segMaxX, segMaxY);
+
+ // Live WYSIWYG Direct Layer/Tile Preview (Eraser, Transparent Ink, Alpha Lock, Color Mixing, Translucent, Clipped, Blend, Under-Layer)
+ if (drewDirectlyOnLayerCanvasRef.current && canvas) {
+ const canvasCtx = get2DContext(canvas);
+ if (canvasCtx) {
+ ensureLiveTileSnapshots(canvas, canvasCtx, currentLayerId, segMinX, segMinY, segMaxX, segMaxY);
+ if (liveStrokeIsolationRef.current && liveAccumCanvasRef.current) {
+ const accumCtx = get2DContext(liveAccumCanvasRef.current);
+ if (accumCtx) {
+ accumCtx.save();
+ applySelectionCanvasClip(accumCtx, selectionRef.current);
+ stampRemainderDistRef.current = renderSegmentToContext(accumCtx, segStart, c1, c2, segEnd, true);
+ accumCtx.restore();
+ }
+ } else {
+ canvasCtx.save();
+ applySelectionCanvasClip(canvasCtx, selectionRef.current);
+ stampRemainderDistRef.current = renderSegmentToContext(canvasCtx, segStart, c1, c2, segEnd, false);
+ canvasCtx.restore();
}
+ syncLiveRegionToTiles(
+ canvas,
+ canvasCtx,
+ currentLayerId,
+ segMinX,
+ segMinY,
+ segMaxX,
+ segMaxY,
+ isMonochrome,
+ activeLayer,
+ bs,
+ isEraser,
+ isBgEraser
+ );
+ return;
}
+ }
- // Eraser path preview on draft overlay
+ // Fallback wireframe only for Vector / Screentone / Mask Eraser when direct preview is disabled
+ if (isEraser && !isBgEraser) {
draftCtx.save();
draftCtx.lineCap = 'round';
draftCtx.lineJoin = 'round';
@@ -1303,28 +1750,9 @@ export function useCanvasDrawing({
return;
}
- // Single-pass document draft rendering + dirty-ROI blit to draft overlay (50% less CPU/GPU work & 100% identical scatter/reservoir state)
- drewDirectlyOnLayerCanvasRef.current = false;
- const docDraftCanvas = docDraftCanvasRef.current;
- const docCtx = docDraftCanvas ? get2DContext(docDraftCanvas) : null;
- if (docCtx && docDraftCanvas) {
- stampRemainderDistRef.current = renderSegmentToContext(docCtx, segStart, c1, c2, segEnd);
- const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
- const maxW = Math.max(segStart.width, segEnd.width, bs.size || 10) * (1.5 + scatterFactor * 2) + 24;
- const sx = Math.max(0, Math.floor(Math.min(segStart.x, c1.x, c2.x, segEnd.x) - maxW));
- const sy = Math.max(0, Math.floor(Math.min(segStart.y, c1.y, c2.y, segEnd.y) - maxW));
- const ex = Math.min(docDraftCanvas.width, Math.ceil(Math.max(segStart.x, c1.x, c2.x, segEnd.x) + maxW));
- const ey = Math.min(docDraftCanvas.height, Math.ceil(Math.max(segStart.y, c1.y, c2.y, segEnd.y) + maxW));
- const sw = ex - sx;
- const sh = ey - sy;
- if (sw > 0 && sh > 0) {
- draftCtx.clearRect(sx, sy, sw, sh);
- draftCtx.drawImage(docDraftCanvas, sx, sy, sw, sh, sx, sy, sw, sh);
- }
- } else {
- stampRemainderDistRef.current = renderSegmentToContext(draftCtx, segStart, c1, c2, segEnd);
- }
- }, [getActiveCanvas]);
+ // Ultra-fast viewport draft overlay for top-layer opaque strokes
+ stampRemainderDistRef.current = renderSegmentToContext(draftCtx, segStart, c1, c2, segEnd, false);
+ }, [buildLiveRadialOptions, buildLiveTexturedOptions, ensureLiveTileSnapshots, getActiveCanvas, markTouchedTiles, syncLiveRegionToTiles]);
// Stabilize and render point onto draft canvas
const applyStabilizedPointAndRender = useCallback(
@@ -1354,9 +1782,13 @@ export function useCanvasDrawing({
velocityScale = Math.max(0.65, Math.min(1.0, 1.0 - Math.max(0, speed - 0.5) * 0.12));
}
+ const hasCustomCurve = Boolean(bs.pressureCurve && bs.pressureCurve.length > 0);
let pt: Point;
if (stab <= 0) {
- const mappedP = bs.usePressure ? taperEngineRef.current.mapPressure(rawPressure) : (rawPressure > 0 ? 1.0 : 0);
+ const baseP = bs.usePressure
+ ? (hasCustomCurve ? rawPressure : taperEngineRef.current.mapPressure(rawPressure))
+ : (rawPressure > 0 ? 1.0 : 0);
+ const mappedP = bs.usePressure ? taperEngineRef.current.smoothPressure(baseP) : baseP;
const width = calculateStrokeWidth(
bs.size,
mappedP,
@@ -1371,7 +1803,10 @@ export function useCanvasDrawing({
stabilizedPointRef.current = pt;
} else {
const sample = inputStabilizerRef.current.process(rawX, rawY, rawPressure, now);
- const mappedP = bs.usePressure ? taperEngineRef.current.mapPressure(sample.pressure) : (rawPressure > 0 ? 1.0 : 0);
+ const baseP = bs.usePressure
+ ? (hasCustomCurve ? sample.pressure : taperEngineRef.current.mapPressure(sample.pressure))
+ : (rawPressure > 0 ? 1.0 : 0);
+ const mappedP = bs.usePressure ? taperEngineRef.current.smoothPressure(baseP) : baseP;
const smoothWidth = calculateStrokeWidth(
bs.size,
mappedP,
@@ -1422,49 +1857,194 @@ export function useCanvasDrawing({
[renderDraftSegment]
);
- // Low-latency speculative predicted tip overlay with tangent/distance guard to prevent stray streaks
+ // Zero-gap provisional + predicted tip overlay matching exact brush geometry
const renderPredictedStroke = useCallback(
(predEvents: PointerEvent[], vRect: DOMRect) => {
clearPredictedCanvas();
- if (!predEvents || predEvents.length === 0 || toolRef.current === 'eraser') return;
+ if (toolRef.current === 'eraser' || drewDirectlyOnLayerCanvasRef.current) return;
+ const pts = strokePointsRef.current;
+ if (pts.length < 2) return;
const pCanvas = getPredictedCanvas();
- const lastPt = stabilizedPointRef.current;
- if (!pCanvas || !lastPt) return;
+ if (!pCanvas) return;
const pCtx = get2DContext(pCanvas);
if (!pCtx) return;
const bs = brushSettingsRef.current;
const dims = dimensionsRef.current;
- const maxPredDist = Math.min(20, Math.max(4, (bs.size || 10) * 1.15));
+ const mode = colorModeRef.current;
+ const currentLayerId = activeLayerIdRef.current;
+ const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);
+ const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
+ const isMonochrome = mode === 'monochrome' || isMonoLayer;
+ const isPencil = bs.preset?.startsWith('pencil') ?? false;
- const ev = predEvents[0];
- const rawPred = screenToCanvas(
- ev.clientX,
- ev.clientY,
- vRect,
+ let strokeColor: string;
+ if (isMaskModeRef.current) {
+ let clean = bs.color.replace('#', '');
+ if (clean.length === 3) clean = clean.split('').map((c) => c + c).join('');
+ const r = parseInt(clean.slice(0, 2), 16) || 0;
+ const g = parseInt(clean.slice(2, 4), 16) || 0;
+ const b = parseInt(clean.slice(4, 6), 16) || 0;
+ const gray = Math.round(0.299 * r + 0.587 * g + 0.114 * b);
+ const hexVal = gray.toString(16).padStart(2, '0');
+ strokeColor = `#${hexVal}${hexVal}${hexVal}`;
+ } else {
+ strokeColor = enforceColorMode(bs.color, isMonochrome ? 'monochrome' : mode);
+ }
+
+ const strokeHardness = isMonochrome ? 1.0 : (bs.hardness ?? 1.0);
+ const strokeFlow = isMonochrome ? 1.0 : (bs.flow ?? 1.0);
+ const strokeSpacing = bs.spacing ?? 0.08;
+
+ const pLast = pts[pts.length - 1];
+ const pPrev = pts[pts.length - 2];
+ const pPrev2 = pts.length >= 3 ? pts[pts.length - 3] : pPrev;
+
+ let predPt: Point | null = null;
+ if (predEvents && predEvents.length > 0) {
+ const maxPredDist = Math.min(20, Math.max(4, (bs.size || 10) * 1.15));
+ const ev = predEvents[0];
+ const rawPred = screenToCanvas(
+ ev.clientX,
+ ev.clientY,
+ vRect,
+ panRef.current,
+ zoomRef.current,
+ rotationRef.current,
+ dims
+ );
+ const dx = rawPred.x - pLast.x;
+ const dy = rawPred.y - pLast.y;
+ const dist = Math.hypot(dx, dy);
+ if (dist >= 0.5 && dist <= maxPredDist * 2.5) {
+ const clampedScale = dist > maxPredDist ? maxPredDist / dist : 1.0;
+ predPt = {
+ x: pLast.x + dx * clampedScale,
+ y: pLast.y + dy * clampedScale,
+ pressure: pLast.pressure * 0.9,
+ width: Math.max(0.5, pLast.width * 0.9),
+ tiltX: pLast.tiltX,
+ tiltY: pLast.tiltY,
+ twist: pLast.twist,
+ };
+ }
+ }
+
+ const scaleX = pCanvas.width / Math.max(1, vRect.width);
+ const scaleY = pCanvas.height / Math.max(1, vRect.height);
+ const matrix = getCanvasToViewportMatrix(
panRef.current,
zoomRef.current,
rotationRef.current,
- dims
+ dims,
+ scaleX,
+ scaleY
);
- const dx = rawPred.x - lastPt.x;
- const dy = rawPred.y - lastPt.y;
- const dist = Math.hypot(dx, dy);
- if (dist < 0.5 || dist > maxPredDist * 2.5) return;
-
- const clampedScale = dist > maxPredDist ? maxPredDist / dist : 1.0;
- const targetX = lastPt.x + dx * clampedScale;
- const targetY = lastPt.y + dy * clampedScale;
pCtx.save();
- pCtx.globalAlpha = Math.min(0.65, (bs.opacity ?? 1.0) * 0.65);
- pCtx.strokeStyle = bs.color || '#000000';
- pCtx.lineCap = 'round';
- pCtx.lineWidth = Math.max(0.5, lastPt.width * 0.85);
+ pCtx.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.e, matrix.f);
pCtx.beginPath();
- pCtx.moveTo(lastPt.x, lastPt.y);
- pCtx.lineTo(targetX, targetY);
- pCtx.stroke();
+ pCtx.rect(0, 0, dims.width, dims.height);
+ pCtx.clip();
+ applySelectionCanvasClip(pCtx, selectionRef.current);
+
+ const drawProvisionalSeg = (s0: Point, c1Pt: Point, c2Pt: Point, s3: Point, rem: number): number => {
+ if (bs.customTipImage) {
+ return drawTexturedCubicBezierSegment(
+ pCtx,
+ s0,
+ c1Pt,
+ c2Pt,
+ s3,
+ strokeColor,
+ bs.customTipImage,
+ {
+ size: bs.size,
+ minSizeFactor: bs.minSizeFactor,
+ opacity: bs.opacity,
+ flow: strokeFlow,
+ spacing: strokeSpacing,
+ thickness: bs.thickness,
+ thicknessVertical: bs.thicknessVertical,
+ angle: bs.customTipAngle,
+ angleDynamics: bs.customTipAngleDynamics,
+ rotationRandomScale: bs.customTipRotationRandomScale,
+ hardness: strokeHardness,
+ antiAlias: isMonochrome ? 0 : bs.antiAlias,
+ pressureCurve: bs.pressureCurve,
+ usePressure: bs.usePressure,
+ subTips: bs.subTips,
+ subTipOrder: bs.subTipOrder,
+ subTipImages: bs.subTipImages,
+ spray: bs.spray,
+ wetEdge: bs.wetEdge,
+ grain: bs.grain ?? bs.textureDensity,
+ dualBrush: bs.dualBrush,
+ dualTipImage: bs.dualTipImage,
+ dualBrushCompositeMode: bs.dualBrushCompositeMode,
+ alphaLocked: Boolean(activeLayer?.alphaLocked),
+ isTransparentInk: Boolean(bs.isTransparentInk),
+ dynamics: bs.dynamics,
+ secondaryColor: bs.secondaryColor,
+ },
+ rem
+ );
+ } else if (isPencil) {
+ const grade = (bs.preset as PencilGrade) || 'pencil-2b';
+ return drawPencilCubicBezierSegment(
+ pCtx,
+ s0,
+ c1Pt,
+ c2Pt,
+ s3,
+ strokeColor,
+ grade,
+ isMonochrome ? 1.0 : (bs.flow ?? 0.74),
+ bs.grain ?? 1.0,
+ strokeHardness,
+ rem,
+ Boolean(activeLayer?.alphaLocked),
+ Boolean(bs.isTransparentInk)
+ );
+ } else {
+ return drawSmoothCubicBezierSegment(
+ pCtx,
+ s0,
+ c1Pt,
+ c2Pt,
+ s3,
+ strokeColor,
+ false,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
+ rem,
+ bs.thickness ?? 1.0,
+ ((bs.customTipAngle ?? 0) * Math.PI) / 180,
+ {
+ alphaLocked: Boolean(activeLayer?.alphaLocked),
+ isTransparentInk: Boolean(bs.isTransparentInk),
+ dynamics: bs.dynamics,
+ secondaryColor: bs.secondaryColor,
+ dualBrush: bs.dualBrush,
+ dualTipImage: bs.dualTipImage,
+ dualBrushCompositeMode: bs.dualBrushCompositeMode,
+ }
+ );
+ }
+ };
+
+ // 1. Provisional unsealed segment (pPrev -> pLast) bridging draftCanvas to current stylus head
+ const provNextKnot = predPt || pLast;
+ const provCtrl = catmullRomToBezier(pPrev2, pPrev, pLast, provNextKnot);
+ const remAfterProv = drawProvisionalSeg(pPrev, provCtrl.c1, provCtrl.c2, pLast, stampRemainderDistRef.current);
+
+ // 2. Speculative lookahead segment (pLast -> predPt) if predicted events exist
+ if (predPt) {
+ const predCtrl = catmullRomToBezier(pPrev, pLast, predPt, predPt);
+ drawProvisionalSeg(pLast, predCtrl.c1, predCtrl.c2, predPt, remAfterProv);
+ }
+
pCtx.restore();
},
[clearPredictedCanvas, getPredictedCanvas]
@@ -1549,6 +2129,11 @@ export function useCanvasDrawing({
onCollabStrokeChunkRef.current?.(currentStrokeIdRef.current, chunkPts);
}
+ if (liveNeedsNotifyRef.current) {
+ liveNeedsNotifyRef.current = false;
+ globalTileGrid.notifyChange();
+ }
+
// Update predicted stroke overlay throttled to rAF
const predData = latestPredictedRef.current;
latestPredictedRef.current = null;
@@ -1620,26 +2205,26 @@ export function useCanvasDrawing({
draftCtx.beginPath();
draftCtx.rect(0, 0, dimensionsRef.current.width, dimensionsRef.current.height);
draftCtx.clip();
+ applySelectionCanvasClip(draftCtx, selectionRef.current);
clearPredictedCanvas();
const isEraser = toolRef.current === 'eraser';
- const isBgEraser = isEraser && activeLayerIdRef.current === 'layer-bg';
+ const isBgEraser = isEraser && isBackgroundLayerId(activeLayerIdRef.current);
const currentLayerId = activeLayerIdRef.current;
- const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);
+ const allLayers = layersRef.current || [];
+ const activeIdx = allLayers.findIndex((l) => l.id === currentLayerId);
+ const activeLayer = activeIdx >= 0 ? allLayers[activeIdx] : undefined;
+ const hasVisibleLayersAbove =
+ activeIdx > 0 && allLayers.slice(0, activeIdx).some((l) => l.visible && l.opacity > 0.001);
const bs = brushSettingsRef.current;
const mode = colorModeRef.current;
- const isPencil = !isEraser && (bs.preset?.startsWith('pencil') ?? false);
+ const isPencil = !isEraser && !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
- const isToneLayer = Boolean(activeLayer?.toneEnabled);
const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
const isMonochrome = mode === 'monochrome' || isMonoLayer;
- const isTone = Boolean(
- activeLayer?.toneEnabled ||
- activeLayer?.layerColorEnabled ||
- (activeLayer?.expressionColor && activeLayer.expressionColor !== 'color')
- );
+ const isTone = Boolean(activeLayer?.toneEnabled);
isToneStrokeRef.current = isTone;
let sourceCanvas: HTMLCanvasElement | null = null;
@@ -1671,11 +2256,71 @@ export function useCanvasDrawing({
const startPoint = snapSessionRef.current.snapPoint(rawStartPoint, rulerRef.current, isAltOverride);
emitConstraintAxisChange(snapSessionRef.current.getActiveAxis());
- allStrokePointsRef.current = [startPoint];
- strokePointsRef.current = [startPoint];
inputStabilizerRef.current.reset();
inputStabilizerRef.current.setStabilizerLevel(bs.stabilization ?? 0);
+ inputStabilizerRef.current.setZoomScale(zoomRef.current || 1.0);
+ inputStabilizerRef.current.setSharpCorners(bs.sharpCorners !== false);
taperEngineRef.current.reset();
+
+ const startNow = startPoint.timestamp ?? performance.now();
+ lastPointTimeRef.current = startNow;
+ if ((bs.stabilization ?? 0) > 0) {
+ inputStabilizerRef.current.process(startPoint.x, startPoint.y, startPoint.pressure, startNow);
+ }
+ const hasCustomCurve = Boolean(bs.pressureCurve && bs.pressureCurve.length > 0);
+ if (bs.usePressure) {
+ const baseStartP = hasCustomCurve ? startPoint.pressure : taperEngineRef.current.mapPressure(startPoint.pressure);
+ const smoothStartP = taperEngineRef.current.smoothPressure(baseStartP);
+ startPoint.pressure = smoothStartP;
+ startPoint.width = calculateStrokeWidth(
+ bs.size,
+ smoothStartP,
+ bs.minSizeFactor,
+ bs.usePressure,
+ firstEvent.pointerType,
+ bs.pressureCurveGamma ?? 1.0,
+ 1.0,
+ bs.pressureCurve
+ );
+ }
+
+ // CSP Shift + Click Straight Line from previous stroke end on the same layer
+ const prevStrokeEnd = lastStrokeEndRef.current;
+ const isShiftLine =
+ Boolean(e.shiftKey) &&
+ !isMaskModeRef.current &&
+ prevStrokeEnd !== null &&
+ prevStrokeEnd.layerId === currentLayerId;
+ isShiftLineStrokeRef.current = isShiftLine;
+
+ if (isShiftLine && prevStrokeEnd) {
+ const pLineStart: Point = {
+ x: prevStrokeEnd.x,
+ y: prevStrokeEnd.y,
+ pressure: startPoint.pressure,
+ width: startPoint.width,
+ tiltX: startPoint.tiltX,
+ tiltY: startPoint.tiltY,
+ twist: startPoint.twist,
+ timestamp: startNow - 16,
+ };
+ const pLineMid: Point = {
+ x: (pLineStart.x + startPoint.x) * 0.5,
+ y: (pLineStart.y + startPoint.y) * 0.5,
+ pressure: startPoint.pressure,
+ width: startPoint.width,
+ tiltX: startPoint.tiltX,
+ tiltY: startPoint.tiltY,
+ twist: startPoint.twist,
+ timestamp: startNow - 8,
+ };
+ allStrokePointsRef.current = [pLineStart, pLineMid, startPoint];
+ strokePointsRef.current = [pLineStart, pLineMid];
+ } else {
+ allStrokePointsRef.current = [startPoint];
+ strokePointsRef.current = [startPoint];
+ }
+
rawPointsBufferRef.current = [{
x: startPoint.x,
y: startPoint.y,
@@ -1696,9 +2341,11 @@ export function useCanvasDrawing({
pressure: startPoint.pressure,
width: startPoint.width,
}];
- strokeTotalDistanceRef.current = 0;
+ strokeTotalDistanceRef.current = isShiftLine && prevStrokeEnd
+ ? Math.hypot(startPoint.x - prevStrokeEnd.x, startPoint.y - prevStrokeEnd.y)
+ : 0;
- if (events.length > 1) {
+ if (!isShiftLine && events.length > 1) {
for (let i = 1; i < events.length; i++) {
const cEv = events[i];
const rawPt = getCanvasPoint(cEv);
@@ -1726,12 +2373,23 @@ export function useCanvasDrawing({
const blurMargin = (1 - (bs.hardness ?? 1.0)) * (startPoint.width * 1.5);
const r = Math.max(32, Math.ceil(startPoint.width + blurMargin + 32));
+ const minInitX = isShiftLine && prevStrokeEnd ? Math.min(startPoint.x, prevStrokeEnd.x) : startPoint.x;
+ const minInitY = isShiftLine && prevStrokeEnd ? Math.min(startPoint.y, prevStrokeEnd.y) : startPoint.y;
+ const maxInitX = isShiftLine && prevStrokeEnd ? Math.max(startPoint.x, prevStrokeEnd.x) : startPoint.x;
+ const maxInitY = isShiftLine && prevStrokeEnd ? Math.max(startPoint.y, prevStrokeEnd.y) : startPoint.y;
dirtyRectRef.current = {
- minX: Math.max(0, Math.floor(startPoint.x - r)),
- minY: Math.max(0, Math.floor(startPoint.y - r)),
- maxX: Math.min(dims.width, Math.ceil(startPoint.x + r)),
- maxY: Math.min(dims.height, Math.ceil(startPoint.y + r)),
+ minX: Math.max(0, Math.floor(minInitX - r)),
+ minY: Math.max(0, Math.floor(minInitY - r)),
+ maxX: Math.min(dims.width, Math.ceil(maxInitX + r)),
+ maxY: Math.min(dims.height, Math.ceil(maxInitY + r)),
};
+ touchedTilesRef.current.clear();
+ markTouchedTiles(
+ dirtyRectRef.current.minX,
+ dirtyRectRef.current.minY,
+ dirtyRectRef.current.maxX,
+ dirtyRectRef.current.maxY
+ );
let strokeColor: string;
if (isMaskModeRef.current) {
@@ -1740,10 +2398,10 @@ export function useCanvasDrawing({
} else {
let clean = bs.color.replace('#', '');
if (clean.length === 3) clean = clean.split('').map((c) => c + c).join('');
- const r = parseInt(clean.slice(0, 2), 16) || 0;
- const g = parseInt(clean.slice(2, 4), 16) || 0;
- const b = parseInt(clean.slice(4, 6), 16) || 0;
- const gray = Math.round(0.299 * r + 0.587 * g + 0.114 * b);
+ const cr = parseInt(clean.slice(0, 2), 16) || 0;
+ const cg = parseInt(clean.slice(2, 4), 16) || 0;
+ const cb = parseInt(clean.slice(4, 6), 16) || 0;
+ const gray = Math.round(0.299 * cr + 0.587 * cg + 0.114 * cb);
const hexVal = gray.toString(16).padStart(2, '0');
strokeColor = `#${hexVal}${hexVal}${hexVal}`;
}
@@ -1755,222 +2413,182 @@ export function useCanvasDrawing({
const isWetColor = !isEraser && Boolean(bs.colorMixing);
isWetColorStrokeRef.current = isWetColor;
- drewDirectlyOnLayerCanvasRef.current = false;
+ liveOrigCanvasTilesRef.current.clear();
+ liveBeforeTileSnapshotRef.current.clear();
+ liveNeedsNotifyRef.current = false;
+ strokeBackupCanvasRef.current = null;
- if (isToneLayer && sourceCanvas) {
- const backupCanvas = getDedicatedBackupCanvas(sourceCanvas.width, sourceCanvas.height);
- const backupCtx = get2DContext(backupCanvas);
- if (backupCtx) {
- backupCtx.clearRect(0, 0, sourceCanvas.width, sourceCanvas.height);
- backupCtx.drawImage(sourceCanvas, 0, 0);
- strokeBackupCanvasRef.current = backupCanvas;
- }
- layerPixelSamplerRef.current = null;
- activeReservoirRef.current = null;
- } else if (isEraser && canvas) {
- const backupCanvas = getDedicatedBackupCanvas(canvas.width, canvas.height);
- const backupCtx = get2DContext(backupCanvas);
- if (backupCtx) {
- backupCtx.clearRect(0, 0, canvas.width, canvas.height);
- backupCtx.drawImage(canvas, 0, 0);
- strokeBackupCanvasRef.current = backupCanvas;
+ const useDirectLayerPreview =
+ !isTone &&
+ activeLayer?.type !== 'vector' &&
+ !isMaskModeRef.current &&
+ (isEraser ||
+ Boolean(bs.isTransparentInk) ||
+ Boolean(activeLayer?.alphaLocked) ||
+ isWetColor ||
+ Boolean(activeLayer?.clipped) ||
+ Boolean(activeLayer?.maskEnabled) ||
+ Boolean(selectionRef.current?.mask) ||
+ (activeLayer?.blendMode !== undefined &&
+ activeLayer.blendMode !== 'normal' &&
+ activeLayer.blendMode !== 'pass-through') ||
+ hasVisibleLayersAbove ||
+ (bs.opacity ?? 1.0) < 0.999 ||
+ bs.blendTipsMode === 'compare');
+
+ drewDirectlyOnLayerCanvasRef.current = useDirectLayerPreview;
+ const needsIsolation = useDirectLayerPreview && (bs.opacity ?? 1.0) < 0.999 && !isWetColor;
+ liveStrokeIsolationRef.current = needsIsolation;
+ if (needsIsolation) {
+ if (
+ !liveAccumCanvasRef.current ||
+ liveAccumCanvasRef.current.width !== canvas.width ||
+ liveAccumCanvasRef.current.height !== canvas.height
+ ) {
+ liveAccumCanvasRef.current = document.createElement('canvas');
+ liveAccumCanvasRef.current.width = canvas.width;
+ liveAccumCanvasRef.current.height = canvas.height;
+ } else {
+ const accCtx = get2DContext(liveAccumCanvasRef.current);
+ accCtx?.clearRect(0, 0, canvas.width, canvas.height);
}
+ }
+
+ if (isWetColor && canvas) {
+ layerPixelSamplerRef.current = new LayerPixelSampler(canvas, activeLayerIdRef.current);
+ activeReservoirRef.current = new PaintReservoir(strokeColor);
+ } else {
layerPixelSamplerRef.current = null;
activeReservoirRef.current = null;
- } else {
- strokeBackupCanvasRef.current = null;
- if (isWetColor && canvas) {
- layerPixelSamplerRef.current = new LayerPixelSampler(canvas, activeLayerIdRef.current);
- activeReservoirRef.current = new PaintReservoir(strokeColor);
- } else {
- layerPixelSamplerRef.current = null;
- activeReservoirRef.current = null;
- }
}
const strokeId = `stroke-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`;
currentStrokeIdRef.current = strokeId;
onCollabStrokeStartRef.current?.(strokeId, activeLayerIdRef.current, bs, toolRef.current, startPoint);
- stampRemainderDistRef.current = Math.max(0.2, startPoint.width * (bs.spacing ?? 0.08));
+ stampRemainderDistRef.current = Math.max(0.12, startPoint.width * (bs.spacing ?? 0.08));
- if (isEraser) {
- drewDirectlyOnLayerCanvasRef.current = true;
- if (canvas) {
- const cCtx = get2DContext(canvas);
- if (cCtx) {
- drawDot(cCtx, startPoint, strokeColor, !isBgEraser, strokeHardness, strokeFlow);
- }
- }
- if (isToneLayer && sourceCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- if (sCtx) {
- drawDot(sCtx, startPoint, strokeColor, !isBgEraser, strokeHardness, strokeFlow);
- }
- }
- draftCtx.save();
- draftCtx.strokeStyle = 'rgba(255, 80, 80, 0.75)';
- draftCtx.setLineDash([3, 3]);
- draftCtx.lineWidth = 1.5;
- draftCtx.beginPath();
- draftCtx.arc(startPoint.x, startPoint.y, Math.max(1, startPoint.width / 2), 0, Math.PI * 2);
- draftCtx.stroke();
- draftCtx.restore();
- } else {
- drewDirectlyOnLayerCanvasRef.current = false;
- const docDraft = canvas ? getDocDraftCanvas(canvas.width, canvas.height) : null;
- const docCtx = docDraft ? get2DContext(docDraft) : null;
- if (docCtx && canvas) {
- docCtx.clearRect(0, 0, canvas.width, canvas.height);
- }
+ const firstDotPoint = allStrokePointsRef.current[0];
- const primaryTargetCtx = docCtx || draftCtx;
+ const drawInitialDotToCtx = (targetCtx: CanvasRenderingContext2D, isolatedPass: boolean) => {
if (bs.customTipImage) {
- const tipOptions: TexturedBrushOptions = {
- size: bs.size,
- minSizeFactor: bs.minSizeFactor,
- opacity: bs.opacity,
- flow: bs.flow ?? 0.85,
- spacing: bs.spacing ?? 0.08,
- thickness: bs.thickness,
- thicknessVertical: bs.thicknessVertical,
- angle: bs.customTipAngle,
- angleDynamics: bs.customTipAngleDynamics,
- rotationRandomScale: bs.customTipRotationRandomScale,
- hardness: strokeHardness,
- antiAlias: isMonochrome ? 0 : bs.antiAlias,
- pressureCurve: bs.pressureCurve,
- velocityCurve: bs.velocityCurve,
- useVelocity: bs.useVelocity,
- subTips: bs.subTips,
- subTipOrder: bs.subTipOrder,
- subTipImages: bs.subTipImages,
- spray: bs.spray,
- taper: bs.taper,
- colorMixing: bs.colorMixing,
- perceptualMixing: bs.perceptualMixing,
- amountOfPaint: bs.amountOfPaint,
- densityOfPaint: bs.densityOfPaint,
- colorStretch: bs.colorStretch,
- mixingMode: bs.mixingMode,
- wetEdge: bs.wetEdge,
- wetEdgeRadius: bs.wetEdgeRadius,
- wetEdgeAlphaPower: bs.wetEdgeAlphaPower,
- wetEdgeValuePower: bs.wetEdgeValuePower,
- grain: bs.grain ?? bs.textureDensity,
- paperTextureImage: bs.paperTextureImage,
- paperTextureScale: bs.paperTextureScale,
- paperTextureRotate: bs.paperTextureRotate,
- dualBrush: bs.dualBrush,
- dualTipImage: bs.dualTipImage,
- dualBrushCompositeMode: bs.dualBrushCompositeMode,
- useGpu: bs.useGpu,
- underlyingCanvas: canvas || undefined,
- sampler: layerPixelSamplerRef.current || undefined,
- reservoir: activeReservoirRef.current || undefined,
- isEraser: false,
- isBgEraser: false,
- alphaLocked: Boolean(activeLayer?.alphaLocked),
- isTransparentInk: Boolean(bs.isTransparentInk),
- dynamics: bs.dynamics,
- secondaryColor: bs.secondaryColor,
- };
- drawTexturedDot(primaryTargetCtx, startPoint, strokeColor, bs.customTipImage, tipOptions);
+ const tipOptions = buildLiveTexturedOptions(
+ bs,
+ bs.flow ?? 0.85,
+ bs.spacing ?? 0.08,
+ strokeHardness,
+ isMonochrome,
+ canvas,
+ activeLayer,
+ isEraser,
+ isBgEraser,
+ isolatedPass
+ );
+ drawTexturedDot(
+ targetCtx,
+ firstDotPoint,
+ isolatedPass && isEraser && !isBgEraser ? '#000000' : strokeColor,
+ bs.customTipImage,
+ tipOptions
+ );
} else if (isPencil) {
const grade = (bs.preset as PencilGrade) || 'pencil-2b';
drawPencilDot(
- primaryTargetCtx,
- startPoint,
+ targetCtx,
+ firstDotPoint,
strokeColor,
grade,
- bs.flow ?? 0.74,
+ isMonochrome ? 1.0 : (bs.flow ?? 0.74),
bs.grain ?? 1.0,
- bs.hardness,
- Boolean(activeLayer?.alphaLocked),
- Boolean(bs.isTransparentInk)
+ strokeHardness,
+ isolatedPass ? false : Boolean(activeLayer?.alphaLocked),
+ isolatedPass ? false : Boolean(bs.isTransparentInk)
);
} else {
- const radialMixingOptions: RadialMixingOptions = {
- colorMixing: bs.colorMixing,
- perceptualMixing: bs.perceptualMixing,
- amountOfPaint: bs.amountOfPaint,
- densityOfPaint: bs.densityOfPaint,
- colorStretch: bs.colorStretch,
- mixingMode: bs.mixingMode,
- underlyingCanvas: canvas || undefined,
- sampler: layerPixelSamplerRef.current || undefined,
- reservoir: activeReservoirRef.current || undefined,
- alphaLocked: Boolean(activeLayer?.alphaLocked),
- isTransparentInk: Boolean(bs.isTransparentInk),
- dynamics: bs.dynamics,
- secondaryColor: bs.secondaryColor,
- useGpu: bs.useGpu,
- dualBrush: bs.dualBrush,
- dualTipImage: bs.dualTipImage,
- dualBrushCompositeMode: bs.dualBrushCompositeMode,
- };
+ const radialMixingOptions = buildLiveRadialOptions(
+ bs,
+ isMonochrome,
+ canvas,
+ activeLayer,
+ isolatedPass
+ );
drawDot(
- primaryTargetCtx,
- startPoint,
- strokeColor,
- false,
+ targetCtx,
+ firstDotPoint,
+ isolatedPass && isEraser && !isBgEraser ? '#000000' : strokeColor,
+ isolatedPass ? false : isEraser && !isBgEraser,
strokeHardness,
- bs.flow ?? 1.0,
- radialMixingOptions
+ isMonochrome ? 1.0 : strokeFlow,
+ radialMixingOptions,
+ bs.thickness ?? 1.0,
+ ((bs.customTipAngle ?? 0) * Math.PI) / 180
);
}
+ };
- if (docCtx && docDraft) {
- const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
- const pad = Math.max(startPoint.width, bs.size || 10) * (1.5 + scatterFactor * 2) + 24;
- const sx = Math.max(0, Math.floor(startPoint.x - pad));
- const sy = Math.max(0, Math.floor(startPoint.y - pad));
- const ex = Math.min(docDraft.width, Math.ceil(startPoint.x + pad));
- const ey = Math.min(docDraft.height, Math.ceil(startPoint.y + pad));
- const sw = ex - sx;
- const sh = ey - sy;
- if (sw > 0 && sh > 0) {
- draftCtx.drawImage(docDraft, sx, sy, sw, sh, sx, sy, sw, sh);
+ if (useDirectLayerPreview) {
+ const cCtx = get2DContext(canvas);
+ if (cCtx) {
+ const d = dirtyRectRef.current;
+ ensureLiveTileSnapshots(canvas, cCtx, currentLayerId, d.minX, d.minY, d.maxX, d.maxY);
+ if (needsIsolation && liveAccumCanvasRef.current) {
+ const accCtx = get2DContext(liveAccumCanvasRef.current);
+ if (accCtx) {
+ accCtx.save();
+ applySelectionCanvasClip(accCtx, selectionRef.current);
+ drawInitialDotToCtx(accCtx, true);
+ accCtx.restore();
+ }
+ } else {
+ cCtx.save();
+ applySelectionCanvasClip(cCtx, selectionRef.current);
+ drawInitialDotToCtx(cCtx, false);
+ cCtx.restore();
}
- }
- }
-
- if (isEraser && isMonochrome && canvas && dirtyRectRef.current) {
- const dotDirty = dirtyRectRef.current;
- const dw = dotDirty.maxX - dotDirty.minX;
- const dh = dotDirty.maxY - dotDirty.minY;
- if (dw > 0 && dh > 0) {
- binarizeCanvasRect(
- get2DContext(canvas)!,
- { x: dotDirty.minX, y: dotDirty.minY, width: dw, height: dh },
- activeLayer?.monoThreshold ?? 128,
- activeLayer?.monoExpressBlack ?? true,
- activeLayer?.monoExpressWhite ?? true
+ syncLiveRegionToTiles(
+ canvas,
+ cCtx,
+ currentLayerId,
+ firstDotPoint.x - r,
+ firstDotPoint.y - r,
+ firstDotPoint.x + r,
+ firstDotPoint.y + r,
+ isMonochrome,
+ activeLayer,
+ bs,
+ isEraser,
+ isBgEraser
);
- if (sourceCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- sCtx?.drawImage(canvas, dotDirty.minX, dotDirty.minY, dw, dh, dotDirty.minX, dotDirty.minY, dw, dh);
+ if (isShiftLine) {
+ renderDraftSegment(draftCtx, startPoint);
}
+ globalTileGrid.notifyChange();
+ liveNeedsNotifyRef.current = false;
+ }
+ } else if (isEraser && !isBgEraser) {
+ draftCtx.save();
+ draftCtx.strokeStyle = 'rgba(255, 80, 80, 0.75)';
+ draftCtx.setLineDash([3, 3]);
+ draftCtx.lineWidth = Math.max(1, 1.5 / Math.max(0.05, zoomRef.current));
+ draftCtx.beginPath();
+ draftCtx.arc(firstDotPoint.x, firstDotPoint.y, Math.max(1, firstDotPoint.width / 2), 0, Math.PI * 2);
+ draftCtx.stroke();
+ draftCtx.restore();
+ if (isShiftLine) {
+ renderDraftSegment(draftCtx, startPoint);
+ }
+ } else {
+ drawInitialDotToCtx(draftCtx, false);
+ if (isShiftLine) {
+ renderDraftSegment(draftCtx, startPoint);
}
- } else if (isEraser && isToneLayer && sourceCanvas && canvas && activeLayer) {
- applyLayerEffects(
- sourceCanvas,
- canvas,
- activeLayer,
- dims.dpi ?? 600,
- {
- x: dirtyRectRef.current.minX,
- y: dirtyRectRef.current.minY,
- width: dirtyRectRef.current.maxX - dirtyRectRef.current.minX,
- height: dirtyRectRef.current.maxY - dirtyRectRef.current.minY,
- }
- );
}
+
if (pendingPointsQueueRef.current.length > 0 && drawRafIdRef.current === null) {
drawRafIdRef.current = requestAnimationFrame(flushPendingPoints);
}
},
- [clearPredictedCanvas, disabled, dispatchPointerStat, effectiveDraftCanvasRef, emitConstraintAxisChange, flushPendingHistoryTasks, flushPendingPoints, getActiveCanvas, getCanvasPoint, getDocDraftCanvas, getPredictedCanvas, getViewportRect, viewportRef]
+ [buildLiveRadialOptions, buildLiveTexturedOptions, clearPredictedCanvas, disabled, dispatchPointerStat, effectiveDraftCanvasRef, emitConstraintAxisChange, ensureLiveTileSnapshots, flushPendingHistoryTasks, flushPendingPoints, getActiveCanvas, getCanvasPoint, getViewportRect, markTouchedTiles, renderDraftSegment, syncLiveRegionToTiles, viewportRef]
);
// Pointer Move handler: throttled & batched coordinate ingestion via rAF with coalesced and predicted events
@@ -1980,11 +2598,10 @@ export function useCanvasDrawing({
coalescedEvents?: PointerEvent[],
_predictedEvents?: PointerEvent[]
) => {
- const point = getCanvasPoint(e);
- dispatchPointerStat(point.x, point.y, point.pressure);
- onCollabCursorMoveRef.current?.(point.x, point.y, isDrawingRef.current, toolRef.current);
-
if (!isDrawingRef.current || e.pointerId !== activePointerIdRef.current) {
+ const point = getCanvasPoint(e);
+ dispatchPointerStat(point.x, point.y, point.pressure);
+ onCollabCursorMoveRef.current?.(point.x, point.y, false, toolRef.current);
return;
}
@@ -2001,8 +2618,11 @@ export function useCanvasDrawing({
const events: PointerEvent[] =
rawCoalesced && rawCoalesced.length > 0 ? Array.from(rawCoalesced) : [e.nativeEvent];
- const draftCanvas = effectiveDraftCanvasRef?.current;
- const draftCtx = draftCanvas ? get2DContext(draftCanvas) : null;
+ const minStepDoc = Math.min(0.25, 0.25 / Math.max(0.05, zoomRef.current));
+ let lastQueuedX = 0;
+ let lastQueuedY = 0;
+ let lastQueuedPressure = 0.5;
+ let hasQueued = false;
for (let i = 0; i < events.length; i++) {
const cEvent = events[i];
@@ -2018,18 +2638,27 @@ export function useCanvasDrawing({
const isAltOverride = e.altKey;
const snapRes = snapSessionRef.current.processPoint(rawCoords, rulerRef.current, isAltOverride);
- const cx = snapRes.x;
- const cy = snapRes.y;
+ let cx = snapRes.x;
+ let cy = snapRes.y;
if (snapRes.axis) {
emitConstraintAxisChange(snapRes.axis);
+ } else if (
+ !isShiftLineStrokeRef.current &&
+ e.shiftKey &&
+ !rulerRef.current?.enabled &&
+ allStrokePointsRef.current.length > 0
+ ) {
+ const originPt = allStrokePointsRef.current[0];
+ const dx = cx - originPt.x;
+ const dy = cy - originPt.y;
+ const dist = Math.hypot(dx, dy);
+ if (dist > 0.5) {
+ const snapAngle = Math.round(Math.atan2(dy, dx) / (Math.PI / 4)) * (Math.PI / 4);
+ cx = originPt.x + Math.cos(snapAngle) * dist;
+ cy = originPt.y + Math.sin(snapAngle) * dist;
+ }
}
- const last = lastProcessedPointRef.current;
- if (last && Math.hypot(cx - last.x, cy - last.y) < 0.25) {
- continue;
- }
-
- lastProcessedPointRef.current = { x: cx, y: cy };
let cPressure = 0;
if (cEvent.pointerType === 'mouse') {
cPressure = (cEvent.buttons & 1) ? 0.5 : 0;
@@ -2037,23 +2666,49 @@ export function useCanvasDrawing({
cPressure = cEvent.pressure !== undefined ? Math.max(0, Math.min(1.0, cEvent.pressure)) : 0;
}
- // Render segment immediately on draft canvas for zero-latency stylus tracking (CSP style)
- if (draftCtx) {
- applyStabilizedPointAndRender(
- draftCtx,
- cx,
- cy,
- cPressure,
- cEvent.pointerType,
- cEvent.tiltX ?? 0,
- cEvent.tiltY ?? 0,
- cEvent.twist ?? 0,
- cEvent.timeStamp
- );
+ const last = lastProcessedPointRef.current;
+ if (
+ last &&
+ Math.hypot(cx - last.x, cy - last.y) < minStepDoc &&
+ Math.abs(cPressure - lastQueuedPressure) <= 0.04
+ ) {
+ continue;
}
+
+ lastProcessedPointRef.current = { x: cx, y: cy };
+
+ pendingPointsQueueRef.current.push({
+ x: cx,
+ y: cy,
+ pressure: cPressure,
+ pointerType: cEvent.pointerType,
+ tiltX: cEvent.tiltX ?? 0,
+ tiltY: cEvent.tiltY ?? 0,
+ twist: cEvent.twist ?? 0,
+ timestamp: cEvent.timeStamp,
+ });
+ lastQueuedX = cx;
+ lastQueuedY = cy;
+ lastQueuedPressure = cPressure;
+ hasQueued = true;
+ }
+
+ if (_predictedEvents && _predictedEvents.length > 0) {
+ latestPredictedRef.current = { predEvents: _predictedEvents, vRect };
+ } else {
+ latestPredictedRef.current = null;
+ }
+
+ if (hasQueued) {
+ dispatchPointerStat(lastQueuedX, lastQueuedY, lastQueuedPressure);
+ onCollabCursorMoveRef.current?.(lastQueuedX, lastQueuedY, true, toolRef.current);
+ }
+
+ if (pendingPointsQueueRef.current.length > 0 && drawRafIdRef.current === null) {
+ drawRafIdRef.current = requestAnimationFrame(flushPendingPoints);
}
},
- [applyStabilizedPointAndRender, dispatchPointerStat, effectiveDraftCanvasRef, emitConstraintAxisChange, getCanvasPoint, getViewportRect]
+ [dispatchPointerStat, emitConstraintAxisChange, flushPendingPoints, getCanvasPoint, getViewportRect]
);
// Pointer Up / Cancel handler: composite and bake stroke into high-res canvas at dirty rect
@@ -2084,15 +2739,19 @@ export function useCanvasDrawing({
const draftCanvas = effectiveDraftCanvasRef?.current;
const draftCtx = draftCanvas ? get2DContext(draftCanvas) : null;
const canvas = getActiveCanvas();
+ if (canvas) {
+ (canvas as any).__isBlank = false;
+ (canvas as any).__isSolidWhite = false;
+ }
// Finalize tail segment on draft canvas using Catmull-Rom cubic Bézier
const pts = strokePointsRef.current;
const currentTool = toolRef.current;
const currentLayerId = activeLayerIdRef.current;
const isEraser = currentTool === 'eraser';
- const isBgEraser = isEraser && currentLayerId === 'layer-bg';
+ const isBgEraser = isEraser && isBackgroundLayerId(currentLayerId);
const mode = colorModeRef.current;
- const isPencil = !isEraser && (bs.preset?.startsWith('pencil') ?? false);
+ const isPencil = !isEraser && !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
const isTone = isToneStrokeRef.current;
const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);
@@ -2100,9 +2759,7 @@ export function useCanvasDrawing({
const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
const isMonochrome = mode === 'monochrome' || isMonoLayer;
const sourceCanvas = isTone ? layerSourceCanvasesRef?.current?.get(currentLayerId) : null;
- const targetTailCtx = isToneLayer && sourceCanvas
- ? get2DContext(sourceCanvas)
- : (drewDirectlyOnLayerCanvasRef.current && canvas ? get2DContext(canvas) : draftCtx);
+ const targetTailCtx = draftCtx;
let strokeColor: string;
if (isMaskModeRef.current) {
@@ -2123,68 +2780,43 @@ export function useCanvasDrawing({
}
const strokeHardness = isMonochrome ? 1.0 : (bs.hardness ?? 1.0);
- if (targetTailCtx && pts.length >= 2) {
+ if (pts.length >= 2 && bs.usePressure && e.pointerType === 'pen') {
+ const pLast = pts[pts.length - 1];
+ pLast.pressure = 0;
+ pLast.width = Math.max(0.1, bs.size * (bs.minSizeFactor ?? 0));
+ }
+
+ if (targetTailCtx && !drewDirectlyOnLayerCanvasRef.current && pts.length >= 2) {
const pLast = pts[pts.length - 1];
const pPrev = pts[pts.length - 2];
const pPrev2 = pts.length >= 3 ? pts[pts.length - 3] : pPrev;
-
- // If stylus pen is lifted, naturally taper pressure to 0 at release point
- if (bs.usePressure && e.pointerType === 'pen') {
- pLast.pressure = 0;
- pLast.width = Math.max(0.1, bs.size * (bs.minSizeFactor ?? 0));
- }
-
const { c1, c2 } = catmullRomToBezier(pPrev2, pPrev, pLast, pLast);
- const docCtx = (!isEraser && docDraftCanvasRef.current) ? get2DContext(docDraftCanvasRef.current) : null;
- if (bs.customTipImage) {
- const tipOptions: TexturedBrushOptions = {
- size: bs.size,
- minSizeFactor: bs.minSizeFactor,
- opacity: bs.opacity,
- flow: bs.flow ?? 0.85,
- spacing: bs.spacing ?? 0.08,
- thickness: bs.thickness,
- thicknessVertical: bs.thicknessVertical,
- angle: bs.customTipAngle,
- angleDynamics: bs.customTipAngleDynamics,
- rotationRandomScale: bs.customTipRotationRandomScale,
- hardness: strokeHardness,
- antiAlias: isMonochrome ? 0 : bs.antiAlias,
- pressureCurve: bs.pressureCurve,
- velocityCurve: bs.velocityCurve,
- usePressure: bs.usePressure,
- useVelocity: bs.useVelocity,
- subTips: bs.subTips,
- subTipOrder: bs.subTipOrder,
- subTipImages: bs.subTipImages,
- spray: bs.spray,
- taper: bs.taper,
- colorMixing: bs.colorMixing,
- amountOfPaint: bs.amountOfPaint,
- densityOfPaint: bs.densityOfPaint,
- colorStretch: bs.colorStretch,
- mixingMode: bs.mixingMode,
- wetEdge: bs.wetEdge,
- wetEdgeRadius: bs.wetEdgeRadius,
- wetEdgeAlphaPower: bs.wetEdgeAlphaPower,
- wetEdgeValuePower: bs.wetEdgeValuePower,
- grain: bs.grain ?? bs.textureDensity,
- paperTextureImage: bs.paperTextureImage,
- paperTextureScale: bs.paperTextureScale,
- paperTextureRotate: bs.paperTextureRotate,
- useGpu: bs.useGpu,
- underlyingCanvas: canvas || undefined,
- sampler: layerPixelSamplerRef.current || undefined,
- reservoir: activeReservoirRef.current || undefined,
- isEraser: isEraser && !isBgEraser,
+ if (isEraser && !isBgEraser) {
+ targetTailCtx.save();
+ targetTailCtx.lineCap = 'round';
+ targetTailCtx.lineJoin = 'round';
+ targetTailCtx.setLineDash([4, 4]);
+ targetTailCtx.strokeStyle = 'rgba(255, 80, 80, 0.75)';
+ targetTailCtx.lineWidth = Math.max(1, (pPrev.width + pLast.width) / 2);
+ targetTailCtx.beginPath();
+ targetTailCtx.moveTo(pPrev.x, pPrev.y);
+ targetTailCtx.bezierCurveTo(c1.x, c1.y, c2.x, c2.y, pLast.x, pLast.y);
+ targetTailCtx.stroke();
+ targetTailCtx.restore();
+ } else if (bs.customTipImage) {
+ const tipOptions = buildLiveTexturedOptions(
+ bs,
+ bs.flow ?? 0.85,
+ bs.spacing ?? 0.08,
+ strokeHardness,
+ isMonochrome,
+ canvas,
+ activeLayer,
+ isEraser,
isBgEraser,
- alphaLocked: Boolean(activeLayer?.alphaLocked),
- isTransparentInk: Boolean(bs.isTransparentInk),
- currentStrokeDist: strokeTotalDistanceRef.current,
- dynamics: bs.dynamics,
- secondaryColor: bs.secondaryColor,
- };
+ false
+ );
drawTexturedCubicBezierSegment(
targetTailCtx,
pPrev,
@@ -2196,19 +2828,6 @@ export function useCanvasDrawing({
tipOptions,
stampRemainderDistRef.current
);
- if (docCtx) {
- drawTexturedCubicBezierSegment(
- docCtx,
- pPrev,
- c1,
- c2,
- pLast,
- strokeColor,
- bs.customTipImage,
- tipOptions,
- stampRemainderDistRef.current
- );
- }
} else if (isPencil) {
const grade = (bs.preset as PencilGrade) || 'pencil-2b';
drawPencilCubicBezierSegment(
@@ -2219,45 +2838,22 @@ export function useCanvasDrawing({
pLast,
strokeColor,
grade,
- bs.flow ?? 0.74,
+ isMonochrome ? 1.0 : (bs.flow ?? 0.74),
bs.grain ?? 1.0,
- bs.hardness,
+ strokeHardness,
stampRemainderDistRef.current,
Boolean(activeLayer?.alphaLocked),
- Boolean(bs.isTransparentInk)
+ Boolean(bs.isTransparentInk),
+ bs.useTilt ?? true
);
- if (docCtx) {
- drawPencilCubicBezierSegment(
- docCtx,
- pPrev,
- c1,
- c2,
- pLast,
- strokeColor,
- grade,
- bs.flow ?? 0.74,
- bs.grain ?? 1.0,
- bs.hardness,
- stampRemainderDistRef.current,
- Boolean(activeLayer?.alphaLocked),
- Boolean(bs.isTransparentInk)
- );
- }
} else {
- const radialMixingOptions: RadialMixingOptions = {
- colorMixing: bs.colorMixing,
- amountOfPaint: bs.amountOfPaint,
- densityOfPaint: bs.densityOfPaint,
- colorStretch: bs.colorStretch,
- mixingMode: bs.mixingMode,
- underlyingCanvas: canvas || undefined,
- sampler: layerPixelSamplerRef.current || undefined,
- reservoir: activeReservoirRef.current || undefined,
- alphaLocked: Boolean(activeLayer?.alphaLocked),
- isTransparentInk: Boolean(bs.isTransparentInk),
- dynamics: bs.dynamics,
- secondaryColor: bs.secondaryColor,
- };
+ const radialMixingOptions = buildLiveRadialOptions(
+ bs,
+ isMonochrome,
+ canvas,
+ activeLayer,
+ false
+ );
drawSmoothCubicBezierSegment(
targetTailCtx,
pPrev,
@@ -2267,45 +2863,13 @@ export function useCanvasDrawing({
strokeColor,
isEraser && !isBgEraser,
strokeHardness,
- bs.flow ?? 1.0,
+ isMonochrome ? 1.0 : (bs.flow ?? 1.0),
bs.spacing ?? 0.06,
stampRemainderDistRef.current,
bs.thickness ?? 1.0,
((bs.customTipAngle ?? 0) * Math.PI) / 180,
radialMixingOptions
);
- if (docCtx) {
- drawSmoothCubicBezierSegment(
- docCtx,
- pPrev,
- c1,
- c2,
- pLast,
- strokeColor,
- false,
- strokeHardness,
- bs.flow ?? 1.0,
- bs.spacing ?? 0.06,
- stampRemainderDistRef.current,
- bs.thickness ?? 1.0,
- ((bs.customTipAngle ?? 0) * Math.PI) / 180,
- radialMixingOptions
- );
- }
- }
-
- if (isEraser && draftCtx) {
- draftCtx.save();
- draftCtx.lineCap = 'round';
- draftCtx.lineJoin = 'round';
- draftCtx.setLineDash([4, 4]);
- draftCtx.strokeStyle = 'rgba(255, 80, 80, 0.75)';
- draftCtx.lineWidth = Math.max(1, (pPrev.width + pLast.width) / 2);
- draftCtx.beginPath();
- draftCtx.moveTo(pPrev.x, pPrev.y);
- draftCtx.bezierCurveTo(c1.x, c1.y, c2.x, c2.y, pLast.x, pLast.y);
- draftCtx.stroke();
- draftCtx.restore();
}
}
@@ -2324,65 +2888,75 @@ export function useCanvasDrawing({
dirtyRectRef.current.maxX = Math.max(dirtyRectRef.current.maxX, tMaxX);
dirtyRectRef.current.maxY = Math.max(dirtyRectRef.current.maxY, tMaxY);
}
-
- if (isEraser && isMonochrome && canvas && dirtyRectRef.current) {
- const eDirty = dirtyRectRef.current;
- const eMinX = Math.max(0, Math.floor(eDirty.minX));
- const eMinY = Math.max(0, Math.floor(eDirty.minY));
- const eMaxX = Math.min(canvas.width, Math.ceil(eDirty.maxX));
- const eMaxY = Math.min(canvas.height, Math.ceil(eDirty.maxY));
- const eW = eMaxX - eMinX;
- const eH = eMaxY - eMinY;
- if (eW > 0 && eH > 0) {
- const cCtx = get2DContext(canvas);
- if (cCtx) {
- binarizeCanvasRect(
- cCtx,
- { x: eMinX, y: eMinY, width: eW, height: eH },
- activeLayer?.monoThreshold ?? 128,
- activeLayer?.monoExpressBlack ?? true,
- activeLayer?.monoExpressWhite ?? true
- );
- }
- if (sourceCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- sCtx?.drawImage(canvas, eMinX, eMinY, eW, eH, eMinX, eMinY, eW, eH);
- }
- }
- }
+ markTouchedTiles(tMinX, tMinY, tMaxX, tMaxY);
}
// BAKE STROKE INTO HIGH-RESOLUTION BASE CANVAS (Dirty Rect only)
const dirty = dirtyRectRef.current;
-
- if (isEraser && isToneLayer && sourceCanvas && canvas) {
- if (activeLayer) {
- const freq = activeLayer?.toneFrequency ?? 60;
- const cellSize = Math.max(3.5, (dimensionsRef.current.dpi ?? 600) / freq);
- const cellMargin = Math.ceil(cellSize * 2 + 32);
- applyLayerEffects(
- sourceCanvas,
- canvas,
- activeLayer,
- dimensionsRef.current.dpi ?? 600,
- dirty ? {
- x: Math.max(0, Math.floor(dirty.minX - cellMargin)),
- y: Math.max(0, Math.floor(dirty.minY - cellMargin)),
- width: Math.min(canvas.width, Math.ceil(dirty.maxX + cellMargin)) - Math.max(0, Math.floor(dirty.minX - cellMargin)),
- height: Math.min(canvas.height, Math.ceil(dirty.maxY + cellMargin)) - Math.max(0, Math.floor(dirty.minY - cellMargin)),
- } : undefined
- );
- }
- }
let exitSpeed = 0;
+ let exitVx = 0;
+ let exitVy = 0;
if (recentPointsTrailRef.current.length >= 2) {
const trail = recentPointsTrailRef.current;
const sampleIdx = Math.max(0, trail.length - 4);
const pA = trail[sampleIdx];
const pB = trail[trail.length - 1];
- const dt = Math.max(1, pB.t - pA.t);
- const dist = Math.hypot(pB.x - pA.x, pB.y - pA.y);
+ const dwellMs = Math.max(0, performance.now() - pB.t);
+ const dt = Math.max(1, (pB.t - pA.t) + dwellMs);
+ const dx = pB.x - pA.x;
+ const dy = pB.y - pA.y;
+ const dist = Math.hypot(dx, dy);
exitSpeed = dist / dt;
+ exitVx = dx / dt;
+ exitVy = dy / dt;
+ }
+
+ // Synthesize ballistic flick tail (Iri-Nuki) when lifting stylus at high velocity
+ if (!isEraser && exitSpeed >= 0.7 && allStrokePointsRef.current.length >= 3) {
+ const lastKnot = allStrokePointsRef.current[allStrokePointsRef.current.length - 1];
+ const prevKnot = allStrokePointsRef.current[allStrokePointsRef.current.length - 2];
+ const refWidth = Math.max(lastKnot.width, prevKnot.width);
+ const refPressure = Math.max(lastKnot.pressure, prevKnot.pressure);
+ const flick = taperEngineRef.current.computeFlickTaper(
+ lastKnot.x,
+ lastKnot.y,
+ refWidth,
+ refPressure,
+ exitVx,
+ exitVy,
+ performance.now()
+ );
+ if (flick.count > 0) {
+ const docW = canvas ? canvas.width : dimensionsRef.current.width;
+ const docH = canvas ? canvas.height : dimensionsRef.current.height;
+ for (let i = 0; i < flick.count; i++) {
+ const fp = flick.points[i];
+ const fx = Math.max(0, Math.min(docW, fp.x));
+ const fy = Math.max(0, Math.min(docH, fp.y));
+ allStrokePointsRef.current.push({
+ x: fx,
+ y: fy,
+ pressure: fp.pressure,
+ width: fp.width,
+ tiltX: lastKnot.tiltX,
+ tiltY: lastKnot.tiltY,
+ twist: lastKnot.twist,
+ timestamp: fp.timestamp,
+ });
+ const fMargin = Math.ceil(fp.width * 1.5 + 24);
+ const fMinX = Math.max(0, Math.floor(fx - fMargin));
+ const fMinY = Math.max(0, Math.floor(fy - fMargin));
+ const fMaxX = Math.min(docW, Math.ceil(fx + fMargin));
+ const fMaxY = Math.min(docH, Math.ceil(fy + fMargin));
+ if (dirty) {
+ dirty.minX = Math.min(dirty.minX, fMinX);
+ dirty.minY = Math.min(dirty.minY, fMinY);
+ dirty.maxX = Math.max(dirty.maxX, fMaxX);
+ dirty.maxY = Math.max(dirty.maxY, fMaxY);
+ }
+ markTouchedTiles(fMinX, fMinY, fMaxX, fMaxY);
+ }
+ }
}
const shouldTaperOut = (bs.usePressure && e.pointerType === 'pen') || exitSpeed > 0.5 || Boolean(bs.taper?.useOut) || Boolean(bs.velocityDynamics);
@@ -2398,6 +2972,18 @@ export function useCanvasDrawing({
const allPoints = allStrokePointsRef.current;
let createdVectorStroke: VectorStroke | undefined;
+ // Track final stroke point for Shift + Click straight line continuation
+ if (allPoints.length > 0 && !isMaskModeRef.current) {
+ const finalPt = allPoints[allPoints.length - 1];
+ lastStrokeEndRef.current = {
+ x: finalPt.x,
+ y: finalPt.y,
+ pressure: finalPt.pressure,
+ width: finalPt.width,
+ layerId: currentLayerId,
+ };
+ }
+
if (activeLayer?.type === 'vector' && canvas && allPoints.length > 0) {
const knots: VectorKnot[] = allPoints.map((pt, idx) => ({
x: pt.x,
@@ -2515,7 +3101,8 @@ export function useCanvasDrawing({
);
}
} else if (canvas && dirty && allPoints.length > 0) {
- const pad = Math.ceil(Math.max(32, (bs.size || 10) * 1.5));
+ const wetMargin = (bs.wetEdge ?? 0) > 0.01 ? Math.ceil((bs.wetEdgeRadius ?? 3.0) * 2 + 8) : 0;
+ const pad = Math.ceil(Math.max(32, (bs.size || 10) * 1.5)) + wetMargin;
const sx = Math.max(0, Math.floor(dirty.minX - pad));
const sy = Math.max(0, Math.floor(dirty.minY - pad));
const maxX = Math.min(canvas.width, Math.ceil(dirty.maxX + pad));
@@ -2524,6 +3111,11 @@ export function useCanvasDrawing({
const dh = maxY - sy;
if (dw > 0 && dh > 0) {
+ // If Live Direct Layer Preview mutated `canvas`, restore pre-stroke pixels first so final bake is 100% clean
+ if (drewDirectlyOnLayerCanvasRef.current) {
+ restoreLiveOrigTilesToCanvas(canvas);
+ }
+
const ctx = get2DContext(canvas);
if (ctx) {
let label = 'Brush Stroke';
@@ -2545,60 +3137,108 @@ export function useCanvasDrawing({
label = isMonochrome ? 'Monochrome Pen' : 'Round Brush';
}
- const docDraft = docDraftCanvasRef.current;
const dirtyRect = { x: sx, y: sy, width: dw, height: dh };
const toolForHistory = currentTool === 'eraser' ? 'eraser' : (isPencil ? 'pencil' : 'brush');
+ const targetFormat = isMonochrome ? 'monochrome-1bit' : 'color-32bit';
+ const effectiveMode: CanvasColorMode = isMonochrome ? 'monochrome' : mode;
+ const activeSelection = selectionRef.current;
+
+ if (isMaskModeRef.current) {
+ const beforeMaskData = ctx.getImageData(sx, sy, dw, dh);
+ const maskBs: BrushSettings = {
+ ...bs,
+ color: strokeColor,
+ isTransparentInk: false,
+ colorMixing: false,
+ };
+ const maskTool: ToolType = isEraser ? 'brush' : currentTool;
- if (isEraser && strokeBackupCanvasRef.current) {
- // Synchronize dirty bounding box to sourceCanvas so tone can be toggled without losing edits
- if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {
- const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);
- if (existingSource) {
- const sCtx = get2DContext(existingSource);
- if (sCtx) {
- sCtx.clearRect(sx, sy, dw, dh);
- sCtx.drawImage(canvas, sx, sy, dw, dh, sx, sy, dw, dh);
- }
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(sx, sy, dw, dh);
+ ctx.clip();
+ applySelectionCanvasClip(ctx, activeSelection);
+
+ if ((bs.opacity ?? 1.0) >= 0.999) {
+ renderCompleteStroke(ctx, allPoints, maskBs, maskTool, 'grayscale', false, canvas, false);
+ } else {
+ ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
+ ctx.globalCompositeOperation = 'source-over';
+ const bakeCanvas = getReusableBakeCanvas(dw, dh);
+ const bCtx = bakeCanvas.getContext('2d', { alpha: true });
+ if (bCtx) {
+ bCtx.clearRect(0, 0, dw, dh);
+ bCtx.save();
+ bCtx.translate(-sx, -sy);
+ renderCompleteStroke(bCtx, allPoints, { ...maskBs, opacity: 1.0 }, maskTool, 'grayscale', false, canvas, false);
+ bCtx.restore();
+ ctx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
}
}
+ ctx.restore();
- // Synchronously snapshot and write committed tiles to globalTileGrid
- const targetFormat = isMonochrome ? 'monochrome-1bit' : 'color-32bit';
- const beforeSnapshot = globalTileGrid.snapshotTilesInRect(currentLayerId, dirtyRect);
- const afterData = ctx.getImageData(sx, sy, dw, dh);
- globalTileGrid.writeImageData(currentLayerId, afterData, sx, sy, targetFormat);
-
- // Offload history step and tile delta generation to background task
+ const afterMaskData = ctx.getImageData(sx, sy, dw, dh);
+ if (activeSelection?.mask) {
+ applySelectionMaskToImageData(beforeMaskData, afterMaskData, sx, sy, activeSelection);
+ ctx.putImageData(afterMaskData, sx, sy);
+ }
+ if (activeLayer) {
+ activeLayer.maskVersion = (activeLayer.maskVersion || 0) + 1;
+ }
enqueueHistoryTask(() => {
- const tileDeltas = globalTileGrid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId, dirtyRect);
- pushHistoryStep('eraser', label, null, null, currentLayerId, dirtyRect, tileDeltas);
+ pushHistoryStep(
+ toolForHistory,
+ 'Layer Mask Stroke',
+ beforeMaskData,
+ afterMaskData,
+ currentLayerId,
+ dirtyRect,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ true
+ );
});
} else if (isToneLayer && sourceCanvas) {
const sCtx = get2DContext(sourceCanvas);
+ const beforeSelectionData =
+ activeSelection?.mask && sCtx ? sCtx.getImageData(sx, sy, dw, dh) : null;
if (sCtx) {
sCtx.save();
sCtx.beginPath();
sCtx.rect(sx, sy, dw, dh);
sCtx.clip();
- sCtx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
- if (bs.isTransparentInk) {
- sCtx.globalCompositeOperation = 'destination-out';
- } else if (activeLayer?.alphaLocked) {
- sCtx.globalCompositeOperation = 'source-atop';
- } else {
- sCtx.globalCompositeOperation = 'source-over';
- }
+ applySelectionCanvasClip(sCtx, activeSelection);
- if (docDraft) {
- sCtx.drawImage(docDraft, sx, sy, dw, dh, sx, sy, dw, dh);
+ const needsIsolatedBake = (bs.opacity ?? 1.0) < 0.999;
+ if (!needsIsolatedBake) {
+ renderCompleteStroke(sCtx, allPoints, bs, currentTool, effectiveMode, isBgEraser, sourceCanvas, Boolean(activeLayer?.alphaLocked));
} else {
+ sCtx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
+ if ((isEraser && !isBgEraser) || bs.isTransparentInk) {
+ sCtx.globalCompositeOperation = 'destination-out';
+ } else if (activeLayer?.alphaLocked) {
+ sCtx.globalCompositeOperation = 'source-atop';
+ } else {
+ sCtx.globalCompositeOperation = 'source-over';
+ }
const bakeCanvas = getReusableBakeCanvas(dw, dh);
const bCtxBake = bakeCanvas.getContext('2d', { alpha: true });
if (bCtxBake) {
- bCtxBake.clearRect(0, 0, bakeCanvas.width, bakeCanvas.height);
+ bCtxBake.clearRect(0, 0, dw, dh);
bCtxBake.save();
bCtxBake.translate(-sx, -sy);
- renderCompleteStroke(bCtxBake, allPoints, bs, currentTool, mode, isBgEraser, sourceCanvas, Boolean(activeLayer?.alphaLocked));
+ renderCompleteStroke(
+ bCtxBake,
+ allPoints,
+ { ...bs, opacity: 1.0, isTransparentInk: false, color: isEraser && !isBgEraser ? '#000000' : bs.color },
+ isEraser && !isBgEraser ? 'brush' : currentTool,
+ effectiveMode,
+ isBgEraser,
+ sourceCanvas,
+ false
+ );
bCtxBake.restore();
sCtx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
}
@@ -2606,127 +3246,253 @@ export function useCanvasDrawing({
sCtx.restore();
}
+ const beforeSnapshot = globalTileGrid.snapshotTilesInRect(currentLayerId, dirtyRect);
+ const afterData = sCtx ? sCtx.getImageData(sx, sy, dw, dh) : null;
+ if (afterData && beforeSelectionData && activeSelection?.mask && sCtx) {
+ applySelectionMaskToImageData(beforeSelectionData, afterData, sx, sy, activeSelection);
+ sCtx.putImageData(afterData, sx, sy);
+ }
+
if (activeLayer) {
+ const freq = activeLayer?.toneFrequency ?? 60;
+ const cellSize = Math.max(3.5, (dimensionsRef.current.dpi ?? 600) / freq);
+ const cellMargin = isEraser ? Math.ceil(cellSize * 2 + 32) : 0;
+ const fxX = Math.max(0, sx - cellMargin);
+ const fxY = Math.max(0, sy - cellMargin);
+ const fxW = Math.min(canvas.width, sx + dw + cellMargin) - fxX;
+ const fxH = Math.min(canvas.height, sy + dh + cellMargin) - fxY;
applyLayerEffects(
sourceCanvas,
canvas,
activeLayer,
dimensionsRef.current.dpi ?? 600,
- { x: sx, y: sy, width: dw, height: dh }
+ { x: fxX, y: fxY, width: fxW, height: fxH }
);
}
- if (docDraft) {
- const dCtx = get2DContext(docDraft);
- dCtx?.clearRect(sx, sy, dw, dh);
- }
-
- // Synchronously snapshot and write committed tiles to globalTileGrid
- const targetFormat = isMonochrome ? 'monochrome-1bit' : 'color-32bit';
- const beforeSnapshot = globalTileGrid.snapshotTilesInRect(currentLayerId, dirtyRect);
- const afterData = sCtx ? sCtx.getImageData(sx, sy, dw, dh) : null;
if (afterData) {
globalTileGrid.writeImageData(currentLayerId, afterData, sx, sy, targetFormat);
}
+ const tileDeltas = globalTileGrid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId, dirtyRect);
enqueueHistoryTask(() => {
- const tileDeltas = globalTileGrid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId, dirtyRect);
pushHistoryStep(toolForHistory, label, null, null, currentLayerId, dirtyRect, tileDeltas);
});
} else {
- // Direct zero-stall GPU blit from docDraft to layer canvas (<0.2 ms)
+ const beforeSelectionData =
+ activeSelection?.mask ? ctx.getImageData(sx, sy, dw, dh) : null;
+
ctx.save();
ctx.beginPath();
ctx.rect(sx, sy, dw, dh);
ctx.clip();
+ applySelectionCanvasClip(ctx, activeSelection);
- ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
- if (bs.isTransparentInk) {
- ctx.globalCompositeOperation = 'destination-out';
- } else if (activeLayer?.alphaLocked) {
- ctx.globalCompositeOperation = 'source-atop';
- } else {
- ctx.globalCompositeOperation = 'source-over';
- }
+ const hasWetEdge =
+ !isMonochrome &&
+ !isEraser &&
+ !bs.isTransparentInk &&
+ (bs.wetEdge ?? 0) > 0.01;
+ const needsIsolatedBake = (bs.opacity ?? 1.0) < 0.999 || hasWetEdge;
- if (docDraft) {
- ctx.drawImage(docDraft, sx, sy, dw, dh, sx, sy, dw, dh);
+ if (!needsIsolatedBake) {
+ renderCompleteStroke(ctx, allPoints, bs, currentTool, effectiveMode, isBgEraser, canvas, Boolean(activeLayer?.alphaLocked));
} else {
+ ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
+ if ((isEraser && !isBgEraser) || bs.isTransparentInk) {
+ ctx.globalCompositeOperation = 'destination-out';
+ } else if (activeLayer?.alphaLocked) {
+ ctx.globalCompositeOperation = 'source-atop';
+ } else {
+ ctx.globalCompositeOperation = 'source-over';
+ }
const bakeCanvas = getReusableBakeCanvas(dw, dh);
- const bCtx = bakeCanvas.getContext('2d', { alpha: true });
+ const bCtx = bakeCanvas.getContext('2d', { alpha: true, willReadFrequently: hasWetEdge });
if (bCtx) {
- bCtx.clearRect(0, 0, bakeCanvas.width, bakeCanvas.height);
+ bCtx.clearRect(0, 0, dw, dh);
bCtx.save();
bCtx.translate(-sx, -sy);
- renderCompleteStroke(bCtx, allPoints, bs, currentTool, mode, isBgEraser, canvas, Boolean(activeLayer?.alphaLocked));
+ renderCompleteStroke(
+ bCtx,
+ allPoints,
+ {
+ ...bs,
+ opacity: 1.0,
+ isTransparentInk: false,
+ wetEdge: 0,
+ color: isEraser && !isBgEraser ? '#000000' : bs.color,
+ },
+ isEraser && !isBgEraser ? 'brush' : currentTool,
+ effectiveMode,
+ isBgEraser,
+ canvas,
+ false
+ );
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);
+ }
+
ctx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
}
}
ctx.restore();
- // Single-pass snapshot: read pixel buffer once, binarize in-place if monochrome, then write
- const targetFormat = isMonochrome ? 'monochrome-1bit' : 'color-32bit';
- const beforeSnapshot = globalTileGrid.snapshotTilesInRect(currentLayerId, dirtyRect);
- const afterData = ctx.getImageData(sx, sy, dw, dh);
- if (isMonochrome) {
- binarizeImageDataBuffer(
- afterData,
- activeLayer?.monoThreshold ?? 128,
- activeLayer?.monoExpressBlack ?? true,
- activeLayer?.monoExpressWhite ?? true
- );
- ctx.putImageData(afterData, sx, sy);
+ if (beforeSelectionData && activeSelection?.mask) {
+ const fullAfter = ctx.getImageData(sx, sy, dw, dh);
+ applySelectionMaskToImageData(beforeSelectionData, fullAfter, sx, sy, activeSelection);
+ ctx.putImageData(fullAfter, sx, sy);
}
- if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {
- const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);
- if (existingSource) {
- const sCtx = get2DContext(existingSource);
- if (sCtx) {
- sCtx.clearRect(sx, sy, dw, dh);
- sCtx.drawImage(canvas, sx, sy, dw, dh, sx, sy, dw, dh);
+ const useSparseTileSpans = dw * dh > 512 * 512 && touchedTilesRef.current.size > 0;
+ if (useSparseTileSpans) {
+ const rows = new Map<number, number[]>();
+ for (const key of touchedTilesRef.current) {
+ const ty = Math.floor(key / 65536);
+ const tx = key % 65536;
+ let list = rows.get(ty);
+ if (!list) {
+ list = [];
+ rows.set(ty, list);
}
+ list.push(tx);
}
- }
- if (docDraft) {
- const dCtx = get2DContext(docDraft);
- dCtx?.clearRect(sx, sy, dw, dh);
- }
+ const spans: Array<{ x: number; y: number; width: number; height: number }> = [];
+ for (const [ty, txList] of rows) {
+ txList.sort((a, b) => a - b);
+ let spanStart = txList[0];
+ let spanEnd = txList[0];
+ for (let i = 1; i < txList.length; i++) {
+ if (txList[i] <= spanEnd + 1) {
+ spanEnd = txList[i];
+ } else {
+ const rx = Math.max(0, spanStart * TILE_SIZE);
+ const ry = Math.max(0, ty * TILE_SIZE);
+ const rw = Math.min(canvas.width, (spanEnd + 1) * TILE_SIZE) - rx;
+ const rh = Math.min(canvas.height, (ty + 1) * TILE_SIZE) - ry;
+ if (rw > 0 && rh > 0) spans.push({ x: rx, y: ry, width: rw, height: rh });
+ spanStart = txList[i];
+ spanEnd = txList[i];
+ }
+ }
+ const rx = Math.max(0, spanStart * TILE_SIZE);
+ const ry = Math.max(0, ty * TILE_SIZE);
+ const rw = Math.min(canvas.width, (spanEnd + 1) * TILE_SIZE) - rx;
+ const rh = Math.min(canvas.height, (ty + 1) * TILE_SIZE) - ry;
+ if (rw > 0 && rh > 0) spans.push({ x: rx, y: ry, width: rw, height: rh });
+ }
- globalTileGrid.writeImageData(currentLayerId, afterData, sx, sy, targetFormat);
+ const beforeSnapshot = new Map<string, { format: TileFormat; data: Uint8Array | null }>(
+ liveBeforeTileSnapshotRef.current
+ );
+ for (let i = 0; i < spans.length; i++) {
+ const sp = spans[i];
+ const subSnap = globalTileGrid.snapshotTilesInRect(currentLayerId, sp);
+ for (const [k, v] of subSnap) {
+ if (!beforeSnapshot.has(k)) beforeSnapshot.set(k, v);
+ }
+ const spanData = ctx.getImageData(sp.x, sp.y, sp.width, sp.height);
+ if (isMonochrome) {
+ binarizeImageDataBuffer(
+ spanData,
+ activeLayer?.monoThreshold ?? 128,
+ activeLayer?.monoExpressBlack ?? true,
+ activeLayer?.monoExpressWhite ?? true
+ );
+ ctx.putImageData(spanData, sp.x, sp.y);
+ }
+ globalTileGrid.writeImageData(currentLayerId, spanData, sp.x, sp.y, targetFormat, true);
+ }
- enqueueHistoryTask(() => {
+ if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {
+ const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);
+ if (existingSource) {
+ const sCtx = get2DContext(existingSource);
+ if (sCtx) {
+ for (let i = 0; i < spans.length; i++) {
+ const sp = spans[i];
+ sCtx.clearRect(sp.x, sp.y, sp.width, sp.height);
+ sCtx.drawImage(canvas, sp.x, sp.y, sp.width, sp.height, sp.x, sp.y, sp.width, sp.height);
+ }
+ }
+ }
+ }
+
+ const tileDeltas = globalTileGrid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId);
+ enqueueHistoryTask(() => {
+ pushHistoryStep(toolForHistory, label, null, null, currentLayerId, dirtyRect, tileDeltas);
+ });
+ } else {
+ const beforeSnapshot = new Map<string, { format: TileFormat; data: Uint8Array | null }>(
+ liveBeforeTileSnapshotRef.current
+ );
+ const subSnap = globalTileGrid.snapshotTilesInRect(currentLayerId, dirtyRect);
+ for (const [k, v] of subSnap) {
+ if (!beforeSnapshot.has(k)) beforeSnapshot.set(k, v);
+ }
+
+ const afterData = ctx.getImageData(sx, sy, dw, dh);
+ if (isMonochrome) {
+ binarizeImageDataBuffer(
+ afterData,
+ activeLayer?.monoThreshold ?? 128,
+ activeLayer?.monoExpressBlack ?? true,
+ activeLayer?.monoExpressWhite ?? true
+ );
+ ctx.putImageData(afterData, sx, sy);
+ }
+
+ if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {
+ const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);
+ if (existingSource) {
+ const sCtx = get2DContext(existingSource);
+ if (sCtx) {
+ sCtx.clearRect(sx, sy, dw, dh);
+ sCtx.drawImage(canvas, sx, sy, dw, dh, sx, sy, dw, dh);
+ }
+ }
+ }
+
+ globalTileGrid.writeImageData(currentLayerId, afterData, sx, sy, targetFormat);
const tileDeltas = globalTileGrid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId, dirtyRect);
- pushHistoryStep(toolForHistory, label, null, null, currentLayerId, dirtyRect, tileDeltas);
- });
+
+ enqueueHistoryTask(() => {
+ pushHistoryStep(toolForHistory, label, null, null, currentLayerId, dirtyRect, tileDeltas);
+ });
+ }
}
}
}
}
- // Synchronously notify tile grid compositor
+ // Synchronously notify tile grid compositor AND synchronously clear draft overlay in the same frame (zero double-alpha flash!)
globalTileGrid.notifyChange(true);
- // Atomic Zero-Flicker handoff: wait 1 frame for WebGL compositor to present its swap chain, then clear draft overlay
if (clearDraftRafRef.current !== null) {
cancelAnimationFrame(clearDraftRafRef.current);
- }
- clearDraftRafRef.current = requestAnimationFrame(() => {
clearDraftRafRef.current = null;
- if (draftCanvas) {
- const dCtx = get2DContext(draftCanvas);
- if (dCtx) {
- try {
- dCtx.restore(); // Restore artboard clip
- } catch (_) {}
- dCtx.resetTransform();
- dCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
- }
+ }
+ if (draftCanvas) {
+ const dCtx = get2DContext(draftCanvas);
+ if (dCtx) {
+ try {
+ dCtx.restore();
+ } catch (_) {}
+ dCtx.resetTransform();
+ dCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
}
- });
+ }
clearPredictedCanvas();
if (currentStrokeIdRef.current) {
@@ -2752,8 +3518,14 @@ export function useCanvasDrawing({
stabilizedPointRef.current = null;
lastProcessedPointRef.current = null;
dirtyRectRef.current = null;
+ touchedTilesRef.current.clear();
pendingPointsQueueRef.current = [];
drewDirectlyOnLayerCanvasRef.current = false;
+ liveStrokeIsolationRef.current = false;
+ liveOrigCanvasTilesRef.current.clear();
+ liveBeforeTileSnapshotRef.current.clear();
+ liveNeedsNotifyRef.current = false;
+ isShiftLineStrokeRef.current = false;
isToneStrokeRef.current = false;
strokeBackupCanvasRef.current = null;
layerPixelSamplerRef.current = null;
@@ -2771,7 +3543,8 @@ export function useCanvasDrawing({
}
},
[
- applyStabilizedPointAndRender,
+ buildLiveRadialOptions,
+ buildLiveTexturedOptions,
clearPredictedCanvas,
effectiveDraftCanvasRef,
emitConstraintAxisChange,
@@ -2779,13 +3552,14 @@ export function useCanvasDrawing({
flushPendingPoints,
getActiveCanvas,
getCanvasPoint,
+ layerSourceCanvasesRef,
+ markTouchedTiles,
onUpdateLayerThumbnail,
pushHistoryStep,
- renderDraftSegment,
+ restoreLiveOrigTilesToCanvas,
]
);
-
const handlePointerEnter = useCallback(() => {
if (viewportRef.current) {
cachedViewportRectRef.current = viewportRef.current.getBoundingClientRect();
@@ -2799,46 +3573,22 @@ export function useCanvasDrawing({
}
}, [dispatchPointerStat]);
- // Keyboard shortcut listener (Ctrl+Z for undo, Ctrl+Y / Ctrl+Shift+Z for redo)
- useEffect(() => {
- const handleKeyDown = (e: KeyboardEvent) => {
- // Ignore if typing in text inputs or textareas
- if (['INPUT', 'TEXTAREA'].includes((e.target as HTMLElement).tagName)) {
- return;
- }
-
- const key = e.key.toLowerCase();
- const isZ = key === 'z' || e.code === 'KeyZ';
-
- if ((e.ctrlKey || e.metaKey) && isZ) {
- e.preventDefault();
- e.stopPropagation();
- if (e.shiftKey) {
- redo();
- } else {
- undo();
- }
- }
- };
-
- window.addEventListener('keydown', handleKeyDown, true);
- return () => window.removeEventListener('keydown', handleKeyDown, true);
- }, [undo, redo]);
-
const resetHistory = useCallback(() => {
historyRef.current = [];
historyIndexRef.current = -1;
+ lastStrokeEndRef.current = null;
setHistoryList([]);
setHistoryIndex(-1);
setCanUndo(false);
setCanRedo(false);
+ globalUndoCache.clearCache().catch(() => {});
// Re-seed initial history state after DOM canvas updates without heavy getImageData readback
setTimeout(() => {
const canvas = layerCanvasesRef.current.get(activeLayerId) || layerCanvasesRef.current.values().next().value;
if (!canvas) return;
- const thumbnail = createCanvasThumbnail(canvas, activeLayerId !== 'layer-bg');
+ const thumbnail = createCanvasThumbnail(canvas, !isBackgroundLayerId(activeLayerId));
const now = Date.now();
const initialItem: HistoryItem = {
@@ -2862,6 +3612,7 @@ export function useCanvasDrawing({
return {
interactionRef,
+ isDrawingRef,
getActiveCanvas,
pushHistoryStep,
handlePointerDown,
diff --git a/src/hooks/useCanvasNavigation.ts b/src/hooks/useCanvasNavigation.ts
index cff6568..5ebb897 100644
--- a/src/hooks/useCanvasNavigation.ts
+++ b/src/hooks/useCanvasNavigation.ts
@@ -1,45 +1,44 @@
import { useState, useRef, useEffect, useCallback } from 'react';
import { CanvasDimensions } from '../types/editor';
-export const MIN_ZOOM = 0.01; // 1% (supports large manga/print canvas vertical adaptation)
+export const MIN_ZOOM = 0.01; // 1%
export const MAX_ZOOM = 32.0; // 3200%
-// Discrete zoom steps used in professional software (Photoshop / Clip Studio Paint)
export const ZOOM_PRESETS = [
- 0.01, // 1%
- 0.02, // 2%
- 0.03, // 3%
- 0.05, // 5%
- 0.0625, // 6.25%
- 0.0833, // 8.33%
- 0.1, // 10%
- 0.125, // 12.5%
- 0.1667, // 16.7%
- 0.25, // 25%
- 0.3333, // 33.3%
- 0.5, // 50%
- 0.6667, // 66.7%
- 0.75, // 75%
- 1.0, // 100%
- 1.25, // 125%
- 1.5, // 150%
- 2.0, // 200%
- 3.0, // 300%
- 4.0, // 400%
- 6.0, // 600%
- 8.0, // 800%
- 12.0, // 1200%
- 16.0, // 1600%
- 24.0, // 2400%
- 32.0, // 3200%
+ 0.01,
+ 0.02,
+ 0.03,
+ 0.05,
+ 0.0625,
+ 0.0833,
+ 0.1,
+ 0.125,
+ 0.1667,
+ 0.25,
+ 0.3333,
+ 0.5,
+ 0.6667,
+ 0.75,
+ 1.0,
+ 1.25,
+ 1.5,
+ 2.0,
+ 3.0,
+ 4.0,
+ 6.0,
+ 8.0,
+ 12.0,
+ 16.0,
+ 24.0,
+ 32.0,
];
-// Dual-tone circular rotation arrows SVG cursor (Clip Studio Paint style)
export const ROTATE_CURSOR_SVG = `data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32" fill="none"><path d="M16 5 A11 11 0 0 1 27 16 A11 11 0 0 1 24.5 22.5" stroke="%23ffffff" stroke-width="3.5" stroke-linecap="round"/><path d="M16 5 A11 11 0 0 1 27 16 A11 11 0 0 1 24.5 22.5" stroke="%231a1a1a" stroke-width="2" stroke-linecap="round"/><polygon points="25.5,18 28.5,24 22,24" fill="%231a1a1a" stroke="%23ffffff" stroke-width="1.5"/><path d="M16 27 A11 11 0 0 1 5 16 A11 11 0 0 1 7.5 9.5" stroke="%23ffffff" stroke-width="3.5" stroke-linecap="round"/><path d="M16 27 A11 11 0 0 1 5 16 A11 11 0 0 1 7.5 9.5" stroke="%231a1a1a" stroke-width="2" stroke-linecap="round"/><polygon points="6.5,14 3.5,8 10,8" fill="%231a1a1a" stroke="%23ffffff" stroke-width="1.5"/><circle cx="16" cy="16" r="2" fill="%231a1a1a" stroke="%23ffffff" stroke-width="1.5"/></svg>`;
export const ROTATE_CURSOR_CSS = `url('${ROTATE_CURSOR_SVG}') 16 16, crosshair`;
export function formatZoomPercent(zoom: number): string {
- const percent = zoom * 100;
+ const safeZoom = Number.isFinite(zoom) ? zoom : 1.0;
+ const percent = safeZoom * 100;
if (percent >= 100) {
return `${Math.round(percent)}%`;
}
@@ -47,26 +46,30 @@ export function formatZoomPercent(zoom: number): string {
return `${rounded % 1 === 0 ? rounded.toFixed(0) : rounded.toFixed(1)}%`;
}
-export const VIEWPORT_FIT_PADDING = 48; // 24px margin on each side for clean artboard visibility
+export const VIEWPORT_FIT_PADDING = 48;
/**
* Calculates adaptive zoom based on layer/canvas dimensions and viewport size.
- * 100% (1.0) is the default zoom level when canvas fits.
- * If canvas exceeds viewport (e.g. manga canvas), adapts vertically to fit cleanly.
- * 100% is the default zoom level rather than the maximum zoom level (MAX_ZOOM = 32.0).
*/
export function calculateAdaptiveZoom(
dimensions: CanvasDimensions | undefined,
viewport: HTMLDivElement | null
): number {
- if (!dimensions || dimensions.height <= 0 || dimensions.width <= 0) {
+ if (
+ !dimensions ||
+ typeof dimensions.width !== 'number' ||
+ typeof dimensions.height !== 'number' ||
+ !Number.isFinite(dimensions.width) ||
+ !Number.isFinite(dimensions.height) ||
+ dimensions.height <= 0 ||
+ dimensions.width <= 0
+ ) {
return 1.0;
}
let vw = viewport?.clientWidth ?? 0;
let vh = viewport?.clientHeight ?? 0;
- // Fallback to window dimensions if viewport is not yet attached to DOM or measured
if (vw <= 0 || vh <= 0) {
if (typeof window !== 'undefined') {
vw = Math.max(300, window.innerWidth - 300);
@@ -101,19 +104,21 @@ export function useCanvasNavigation({
const viewportRef = useRef<HTMLDivElement | null>(null);
const [zoom, setZoomState] = useState<number>(1.0);
- // Pan represents the canvas center in viewport coordinates
const [pan, setPanState] = useState<{ x: number; y: number }>({ x: 0, y: 0 });
const [rotation, setRotationState] = useState<number>(0.0);
const dimensionsRef = useRef<CanvasDimensions | undefined>(dimensions);
dimensionsRef.current = dimensions;
+ const isWebtoonModeRef = useRef<boolean>(isWebtoonMode);
+ isWebtoonModeRef.current = isWebtoonMode;
+
const [isSpaceDown, setIsSpaceDown] = useState<boolean>(false);
const [isShiftDown, setIsShiftDown] = useState<boolean>(false);
const [isPanning, setIsPanning] = useState<boolean>(false);
const [isRotating, setIsRotating] = useState<boolean>(false);
- // Synchronous refs to prevent stale closure drift during high-frequency pointer movement
+ // Synchronous refs for sub-frame precision
const zoomRef = useRef<number>(1.0);
const panRef = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
const rotationRef = useRef<number>(0.0);
@@ -123,6 +128,27 @@ export function useCanvasNavigation({
const isPanningRef = useRef<boolean>(false);
const isRotatingRef = useRef<boolean>(false);
+ // Coalesce high-frequency (240Hz) wheel/pan/rotate updates into 1 React render per animation frame
+ const navCommitRafRef = useRef<number | null>(null);
+ const scheduleNavStateCommit = useCallback(() => {
+ if (navCommitRafRef.current !== null) return;
+ navCommitRafRef.current = requestAnimationFrame(() => {
+ navCommitRafRef.current = null;
+ setZoomState(zoomRef.current);
+ setPanState({ x: panRef.current.x, y: panRef.current.y });
+ setRotationState(rotationRef.current);
+ });
+ }, []);
+
+ useEffect(() => {
+ return () => {
+ if (navCommitRafRef.current !== null) {
+ cancelAnimationFrame(navCommitRafRef.current);
+ navCommitRafRef.current = null;
+ }
+ };
+ }, []);
+
const panStartRef = useRef<{ clientX: number; clientY: number; panX: number; panY: number }>({
clientX: 0,
clientY: 0,
@@ -151,7 +177,8 @@ export function useCanvasNavigation({
const setZoom = useCallback((newZoomOrFn: number | ((prev: number) => number)) => {
setZoomState((prev) => {
const next = typeof newZoomOrFn === 'function' ? newZoomOrFn(prev) : newZoomOrFn;
- const clamped = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, next));
+ const safe = Number.isFinite(next) ? next : 1.0;
+ const clamped = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, safe));
zoomRef.current = clamped;
return clamped;
});
@@ -176,13 +203,11 @@ export function useCanvasNavigation({
});
}, []);
- // Center canvas in viewport given target zoom
const centerCanvas = useCallback((targetZoom: number = zoomRef.current) => {
const viewport = viewportRef.current;
let vw = viewport?.clientWidth ?? 0;
let vh = viewport?.clientHeight ?? 0;
- // Fallback to window bounds if viewport not yet mounted
if (vw <= 0 || vh <= 0) {
if (typeof window !== 'undefined') {
vw = Math.max(300, window.innerWidth - 300);
@@ -197,18 +222,27 @@ export function useCanvasNavigation({
y: Math.round(vh / 2),
};
- const clampedZoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, targetZoom));
+ const safeZoom = Number.isFinite(targetZoom) ? targetZoom : 1.0;
+ const clampedZoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, safeZoom));
panRef.current = newCenter;
setPanState(newCenter);
zoomRef.current = clampedZoom;
setZoomState(clampedZoom);
}, []);
- // Reset zoom based on layer/canvas dimensions (adapts vertically for oversized formats like manga,
- // defaults to 100% when fitting, centered, rotation to 0°)
+ /**
+ * Reset zoom based on layer/canvas dimensions.
+ * Validates customDims so passing a React MouseEvent directly from onClick never produces NaN.
+ */
const resetZoomAndCenter = useCallback(
(customDims?: CanvasDimensions) => {
- const activeDims = customDims || dimensionsRef.current;
+ const isValidCustom =
+ customDims &&
+ typeof (customDims as CanvasDimensions).width === 'number' &&
+ typeof (customDims as CanvasDimensions).height === 'number' &&
+ Number.isFinite((customDims as CanvasDimensions).width) &&
+ Number.isFinite((customDims as CanvasDimensions).height);
+ const activeDims = isValidCustom ? customDims : dimensionsRef.current;
const targetZoom = calculateAdaptiveZoom(activeDims, viewportRef.current);
rotationRef.current = 0.0;
setRotationState(0.0);
@@ -218,7 +252,6 @@ export function useCanvasNavigation({
[centerCanvas]
);
- // Reset only rotation to 0° around the viewport center (Ctrl + Alt + 0)
const resetRotation = useCallback(() => {
const viewport = viewportRef.current;
if (!viewport) {
@@ -235,7 +268,6 @@ export function useCanvasNavigation({
const currentRotation = rotationRef.current;
if (Math.abs(currentRotation) < 0.0001) return;
- // Rotate the canvas center back by -currentRotation around viewport center
const dRad = (-currentRotation * Math.PI) / 180;
const rx = panRef.current.x - vc.x;
const ry = panRef.current.y - vc.y;
@@ -248,36 +280,30 @@ export function useCanvasNavigation({
setPanState({ x: newPanX, y: newPanY });
}, []);
- // Zoom centered on the viewport center (for shortcuts Ctrl + Plus / Ctrl + Minus and toolbar buttons)
- const zoomToViewportCenter = useCallback(
- (targetZoom: number) => {
- const viewport = viewportRef.current;
- if (!viewport) return;
+ const zoomToViewportCenter = useCallback((targetZoom: number) => {
+ const viewport = viewportRef.current;
+ if (!viewport) return;
- const currentZoom = zoomRef.current;
- const clampedZoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, targetZoom));
- if (Math.abs(clampedZoom - currentZoom) < 0.0001) return;
+ const currentZoom = zoomRef.current;
+ const clampedZoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, targetZoom));
+ if (Math.abs(clampedZoom - currentZoom) < 0.0001) return;
- const vw = viewport.clientWidth;
- const vh = viewport.clientHeight;
- const centerX = vw / 2;
- const centerY = vh / 2;
+ const vw = viewport.clientWidth;
+ const vh = viewport.clientHeight;
+ const centerX = vw / 2;
+ const centerY = vh / 2;
- // Adjust pan offset relative to viewport center
- const ratio = clampedZoom / currentZoom;
- const newPanX = centerX - (centerX - panRef.current.x) * ratio;
- const newPanY = centerY - (centerY - panRef.current.y) * ratio;
+ const ratio = clampedZoom / currentZoom;
+ const newPanX = centerX - (centerX - panRef.current.x) * ratio;
+ const newPanY = centerY - (centerY - panRef.current.y) * ratio;
- zoomRef.current = clampedZoom;
- panRef.current = { x: newPanX, y: newPanY };
+ zoomRef.current = clampedZoom;
+ panRef.current = { x: newPanX, y: newPanY };
- setZoomState(clampedZoom);
- setPanState({ x: newPanX, y: newPanY });
- },
- []
- );
+ setZoomState(clampedZoom);
+ setPanState({ x: newPanX, y: newPanY });
+ }, []);
- // Incremental Zoom In to the next standard preset
const zoomIn = useCallback(() => {
const current = zoomRef.current;
let target = ZOOM_PRESETS.find((p) => p > current * 1.01);
@@ -285,7 +311,6 @@ export function useCanvasNavigation({
zoomToViewportCenter(target);
}, [zoomToViewportCenter]);
- // Incremental Zoom Out to the previous standard preset
const zoomOut = useCallback(() => {
const current = zoomRef.current;
let target: number | undefined;
@@ -299,7 +324,6 @@ export function useCanvasNavigation({
zoomToViewportCenter(target);
}, [zoomToViewportCenter]);
- // Start panning drag from a pointer event
const startPan = useCallback((e: React.PointerEvent | PointerEvent) => {
e.preventDefault();
isPanningRef.current = true;
@@ -313,7 +337,6 @@ export function useCanvasNavigation({
};
}, []);
- // Start rotation drag from a pointer event
const startRotate = useCallback((e: React.PointerEvent | PointerEvent) => {
e.preventDefault();
const viewport = viewportRef.current;
@@ -327,7 +350,6 @@ export function useCanvasNavigation({
const px = e.clientX - rect.left;
const py = e.clientY - rect.top;
-
const initialAngle = Math.atan2(py - vc.y, px - vc.x) * (180 / Math.PI);
rotateStartRef.current = {
@@ -343,12 +365,10 @@ export function useCanvasNavigation({
setIsRotating(true);
}, []);
- // Reset centering flag when active document changes
useEffect(() => {
hasInitializedCenterRef.current = false;
}, [activeDocumentId]);
- // Center on mount, document change, and handle window / viewport resize gracefully
useEffect(() => {
const viewport = viewportRef.current;
if (!viewport) return;
@@ -372,7 +392,6 @@ export function useCanvasNavigation({
centerCanvas(initialZoom);
hasInitializedCenterRef.current = true;
} else {
- // Adjust canvas center by half the size difference to keep canvas centered
const dx = (width - prevWidth) / 2;
const dy = (height - prevHeight) / 2;
if (dx !== 0 || dy !== 0) {
@@ -389,7 +408,7 @@ export function useCanvasNavigation({
return () => ro.disconnect();
}, [centerCanvas, setPan, activeDocumentId]);
- // Mouse wheel zoom centered on cursor position (accounts for rotation angle)
+ // Mouse wheel zoom centered on cursor position (coalesced to 1 React render per rAF)
useEffect(() => {
const viewport = viewportRef.current;
if (!viewport) return;
@@ -403,20 +422,17 @@ export function useCanvasNavigation({
let delta = e.deltaY;
if (e.deltaMode === 1) {
- delta *= 28; // Lines to pixels
+ delta *= 28;
} else if (e.deltaMode === 2) {
- delta *= 500; // Pages to pixels
+ delta *= 500;
}
- // In Webtoon mode, standard wheel scrolls canvas vertically
- if (isWebtoonMode && !e.ctrlKey && !e.metaKey) {
- const nextPanY = panRef.current.y - delta;
- panRef.current = { x: panRef.current.x, y: nextPanY };
- setPanState({ x: panRef.current.x, y: nextPanY });
+ if (isWebtoonModeRef.current && !e.ctrlKey && !e.metaKey) {
+ panRef.current = { x: panRef.current.x, y: panRef.current.y - delta };
+ scheduleNavStateCommit();
return;
}
- // Smooth exponential zoom factor
const zoomFactor = Math.exp(-delta * 0.0018);
const currentZoom = zoomRef.current;
const nextZoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, currentZoom * zoomFactor));
@@ -428,9 +444,7 @@ export function useCanvasNavigation({
zoomRef.current = nextZoom;
panRef.current = { x: nextPanX, y: nextPanY };
-
- setZoomState(nextZoom);
- setPanState({ x: nextPanX, y: nextPanY });
+ scheduleNavStateCommit();
}
};
@@ -438,17 +452,22 @@ export function useCanvasNavigation({
return () => {
viewport.removeEventListener('wheel', handleWheel);
};
- }, []);
+ }, [activeDocumentId, scheduleNavStateCommit]);
// Global Keyboard Shortcuts (Space, Shift, Ctrl+0, Ctrl+Alt+0, Ctrl++, Ctrl+-)
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
- // Ignore keyboard shortcuts if user is typing in a text field
- if (['INPUT', 'TEXTAREA'].includes((e.target as HTMLElement).tagName)) {
+ const targetEl = e.target as HTMLElement | null;
+ if (
+ targetEl &&
+ (['INPUT', 'TEXTAREA', 'SELECT'].includes(targetEl.tagName) || targetEl.isContentEditable)
+ ) {
+ return;
+ }
+ if (document.querySelector('[role="dialog"]')) {
return;
}
- // Shift key detection
if (e.key === 'Shift') {
if (!isShiftDownRef.current) {
isShiftDownRef.current = true;
@@ -456,8 +475,8 @@ export function useCanvasNavigation({
}
}
- // Space key for Pan Hand Tool or Rotate with Shift+Space
- if (e.code === 'Space' || e.key === ' ') {
+ // Space key for Pan Hand Tool or Rotate with Shift+Space (skip Alt+Space so Animation playback can use it)
+ if ((e.code === 'Space' || e.key === ' ') && !e.altKey && !e.ctrlKey && !e.metaKey) {
e.preventDefault();
if (!isSpaceDownRef.current) {
isSpaceDownRef.current = true;
@@ -466,41 +485,26 @@ export function useCanvasNavigation({
return;
}
- // Ctrl / Cmd shortcuts
if (e.ctrlKey || e.metaKey) {
- // Ctrl + Alt + 0: Reset rotation only to 0°
- if (e.altKey && (e.key === '0' || e.code === 'Digit0' || e.code === 'Numpad0')) {
+ if (e.altKey && (e.code === 'Digit0' || e.code === 'Numpad0' || e.key === '0')) {
e.preventDefault();
resetRotation();
return;
}
- // Ctrl + 0: Reset zoom to 100%, rotation to 0°, and re-center
- if (!e.altKey && (e.key === '0' || e.code === 'Digit0' || e.code === 'Numpad0')) {
+ if (!e.altKey && (e.code === 'Digit0' || e.code === 'Numpad0' || e.key === '0')) {
e.preventDefault();
resetZoomAndCenter();
return;
}
- // Ctrl + Plus / Ctrl + = : Incremental zoom in
- if (
- e.key === '+' ||
- e.key === '=' ||
- e.code === 'Equal' ||
- e.code === 'NumpadAdd'
- ) {
+ if (e.code === 'Equal' || e.code === 'NumpadAdd' || e.key === '+' || e.key === '=') {
e.preventDefault();
zoomIn();
return;
}
- // Ctrl + Minus / Ctrl + _ : Incremental zoom out
- if (
- e.key === '-' ||
- e.key === '_' ||
- e.code === 'Minus' ||
- e.code === 'NumpadSubtract'
- ) {
+ if (e.code === 'Minus' || e.code === 'NumpadSubtract' || e.key === '-' || e.key === '_') {
e.preventDefault();
zoomOut();
return;
@@ -541,7 +545,7 @@ export function useCanvasNavigation({
};
}, [resetRotation, resetZoomAndCenter, zoomIn, zoomOut]);
- // Window pointermove and pointerup listeners while panning is active
+ // Panning pointermove coalesced to rAF
useEffect(() => {
if (!isPanning) return;
@@ -550,18 +554,17 @@ export function useCanvasNavigation({
const dx = e.clientX - panStartRef.current.clientX;
const dy = e.clientY - panStartRef.current.clientY;
- const newPan = {
- x: isWebtoonMode ? panStartRef.current.panX : panStartRef.current.panX + dx,
+ panRef.current = {
+ x: isWebtoonModeRef.current ? panStartRef.current.panX : panStartRef.current.panX + dx,
y: panStartRef.current.panY + dy,
};
-
- panRef.current = newPan;
- setPanState(newPan);
+ scheduleNavStateCommit();
};
const handleWindowPointerUp = () => {
isPanningRef.current = false;
setIsPanning(false);
+ setPanState({ x: panRef.current.x, y: panRef.current.y });
};
window.addEventListener('pointermove', handleWindowPointerMove, { passive: true });
@@ -580,21 +583,25 @@ export function useCanvasNavigation({
document.body.style.cursor = prevCursor;
document.body.style.userSelect = prevUserSelect;
};
- }, [isPanning]);
+ }, [isPanning, scheduleNavStateCommit]);
- // Window pointermove and pointerup listeners while rotating is active
+ // Rotating pointermove coalesced to rAF
useEffect(() => {
if (!isRotating) return;
+ let cachedRect: DOMRect | null = viewportRef.current
+ ? viewportRef.current.getBoundingClientRect()
+ : null;
+
const handleWindowPointerMove = (e: PointerEvent) => {
if (!isRotatingRef.current) return;
const viewport = viewportRef.current;
if (!viewport) return;
- const rect = viewport.getBoundingClientRect();
+ if (!cachedRect) cachedRect = viewport.getBoundingClientRect();
const vc = rotateStartRef.current.center;
- const px = e.clientX - rect.left;
- const py = e.clientY - rect.top;
+ const px = e.clientX - cachedRect.left;
+ const py = e.clientY - cachedRect.top;
const curAngle = Math.atan2(py - vc.y, px - vc.x) * (180 / Math.PI);
let diff = curAngle - rotateStartRef.current.lastPointerAngle;
@@ -607,11 +614,9 @@ export function useCanvasNavigation({
let newRotation =
rotateStartRef.current.startCanvasRotation + rotateStartRef.current.totalAngleDelta;
- // Snapping to 15-degree increments when Alt or Ctrl is held:
if (e.altKey || e.ctrlKey) {
newRotation = Math.round(newRotation / 15) * 15;
} else {
- // Magnetic snap near cardinal angles (0°, 90°, 180°, -90°, etc.) within ±2.5°
const nearestCardinal = Math.round(newRotation / 90) * 90;
if (Math.abs(newRotation - nearestCardinal) <= 2.5) {
newRotation = nearestCardinal;
@@ -619,22 +624,22 @@ export function useCanvasNavigation({
}
rotationRef.current = newRotation;
- setRotationState(newRotation);
- // Rotate canvas center around the viewport center so the focal point stays in place
const dRad = ((newRotation - rotateStartRef.current.startCanvasRotation) * Math.PI) / 180;
const rx = rotateStartRef.current.startPan.x - vc.x;
const ry = rotateStartRef.current.startPan.y - vc.y;
- const newPanX = vc.x + rx * Math.cos(dRad) - ry * Math.sin(dRad);
- const newPanY = vc.y + rx * Math.sin(dRad) + ry * Math.cos(dRad);
-
- panRef.current = { x: newPanX, y: newPanY };
- setPanState({ x: newPanX, y: newPanY });
+ panRef.current = {
+ x: vc.x + rx * Math.cos(dRad) - ry * Math.sin(dRad),
+ y: vc.y + rx * Math.sin(dRad) + ry * Math.cos(dRad),
+ };
+ scheduleNavStateCommit();
};
const handleWindowPointerUp = () => {
isRotatingRef.current = false;
setIsRotating(false);
+ setRotationState(rotationRef.current);
+ setPanState({ x: panRef.current.x, y: panRef.current.y });
};
window.addEventListener('pointermove', handleWindowPointerMove, { passive: true });
@@ -653,9 +658,8 @@ export function useCanvasNavigation({
document.body.style.cursor = prevCursor;
document.body.style.userSelect = prevUserSelect;
};
- }, [isRotating]);
+ }, [isRotating, scheduleNavStateCommit]);
- // Prevent browser auto-scroll on middle click
useEffect(() => {
const handleAuxClick = (e: MouseEvent) => {
if (e.button === 1) {
diff --git a/src/hooks/useLayerManager.ts b/src/hooks/useLayerManager.ts
index d5af405..14a70b3 100644
--- a/src/hooks/useLayerManager.ts
+++ b/src/hooks/useLayerManager.ts
@@ -5,9 +5,15 @@ import { createCanvasThumbnail, get2DContext } from '../utils/canvasUtils';
import { applyLayerEffects, applyExpressionColorToImageData } from '../utils/layerEffectsEngine';
import { HalftoneDotShape } from '../utils/screentoneEngine';
import { globalTileGrid } from '../utils/tileEngine';
+import { recoveryService } from '../services/recoveryService';
interface UseLayerManagerProps {
dimensions: CanvasDimensions;
+ activeSessionId?: string | null;
+}
+
+export function isBackgroundLayerId(id: string): boolean {
+ return id === 'layer-bg' || id.startsWith('layer-bg');
}
// Helper to generate the next collaborative layer name (e.g. "Sora 1", "Sora 2", "Alex 1")
@@ -337,7 +343,7 @@ export function computeBatchLock(
return layers.map((l) => (selectedSet.has(l.id) ? { ...l, locked: newLocked } : l));
}
-export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProps) {
+export function useLayerManager({ dimensions: _dimensions, activeSessionId }: UseLayerManagerProps) {
// Store canvas DOM elements for each raster layer by layer ID
const layerCanvasesRef = useRef<Map<string, HTMLCanvasElement>>(new Map());
@@ -365,6 +371,19 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
const layersRef = useRef(layers);
layersRef.current = layers;
+ // Track layer mutations and log to recovery service WAL
+ const isInitialLayerMount = useRef(true);
+ useEffect(() => {
+ if (isInitialLayerMount.current) {
+ isInitialLayerMount.current = false;
+ return;
+ }
+ const sId = activeSessionId || recoveryService.getCurrentSessionId();
+ if (sId && layers.length > 0) {
+ recoveryService.logLayerMutation(sId, 'update', layers, activeLayerId);
+ }
+ }, [layers, activeSessionId, activeLayerId]);
+
const setSelectedLayerIds = useCallback((ids: string[] | ((prev: string[]) => string[])) => {
setSelectedLayerIdsState((prev) => {
const next = typeof ids === 'function' ? ids(prev) : ids;
@@ -434,23 +453,35 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
if (initialData !== 'transparent') {
ctx.fillStyle = initialData;
ctx.fillRect(0, 0, canvas.width, canvas.height);
+ if (initialData.toLowerCase() === '#ffffff' || initialData.toLowerCase() === '#fff' || initialData.toLowerCase() === 'white') {
+ (canvas as any).__isSolidWhite = true;
+ }
+ } else {
+ (canvas as any).__isBlank = true;
}
} else {
ctx.drawImage(initialData, 0, 0);
}
}
pendingInitialDataRef.current.delete(id);
- } else if (id === 'layer-bg' || id.startsWith('layer-bg')) {
+ } else if (isBackgroundLayerId(id)) {
// If it's the background layer and uninitialized, fill with solid white
const ctx = get2DContext(canvas);
if (ctx) {
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, canvas.width, canvas.height);
+ (canvas as any).__isSolidWhite = true;
+ }
+ } else if (!sourceId) {
+ if (globalTileGrid.isLayerIngested(id)) {
+ globalTileGrid.renderLayerToCanvas(id, canvas);
+ } else {
+ (canvas as any).__isBlank = true;
}
}
- // Ingest into globalTileGrid if unindexed
- if (!globalTileGrid.hasTile(id, 0, 0) && globalTileGrid.getLayerTiles(id).length === 0) {
+ // Ingest into globalTileGrid if unindexed or if freshly copied/initialized
+ if (!globalTileGrid.isLayerIngested(id) || sourceId || initialData) {
const layer = layersRef.current.find((l) => l.id === id);
const isMono = layer?.expressionColor === 'monochrome';
globalTileGrid.ingestCanvas(id, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
@@ -460,7 +491,11 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
requestAnimationFrame(() => {
const c = layerCanvasesRef.current.get(id);
if (c) {
- const thumb = createCanvasThumbnail(c, id !== 'layer-bg');
+ const targetW = 60;
+ const targetH = Math.max(38, Math.round((c.height / Math.max(1, c.width)) * targetW));
+ const thumb = (c.width * c.height > 1024 * 1024 && globalTileGrid.isLayerIngested(id))
+ ? globalTileGrid.generateThumbnail(id, targetW, targetH, { width: c.width, height: c.height })
+ : createCanvasThumbnail(c, !isBackgroundLayerId(id));
setLayers((prev) =>
prev.map((l) => (l.id === id && !l.thumbnailUrl ? { ...l, thumbnailUrl: thumb } : l))
);
@@ -483,7 +518,7 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
}
});
- // When a layer is removed, delete its canvas from layerCanvasesRef.current
+ // When a layer is removed, delete its canvas from layerCanvasesRef.current and clean up tile grid
const currentLayerIds = new Set(layers.map((l) => l.id));
for (const id of Array.from(layerCanvasesRef.current.keys())) {
if (!currentLayerIds.has(id)) {
@@ -499,12 +534,21 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
const updateLayerThumbnail = useCallback((id: string, immediate: boolean = false) => {
const run = () => {
const canvas = layerCanvasesRef.current.get(id);
- if (!canvas) return;
+ const dims = canvas ? { width: canvas.width, height: canvas.height } : _dimensions;
+ const targetW = 60;
+ const targetH = Math.max(38, Math.round((dims.height / Math.max(1, dims.width)) * targetW));
+ const isLarge = dims.width * dims.height > 1024 * 1024;
+ const thumb = (isLarge && globalTileGrid.isLayerIngested(id))
+ ? globalTileGrid.generateThumbnail(id, targetW, targetH, dims)
+ : (canvas ? createCanvasThumbnail(canvas, !isBackgroundLayerId(id)) : globalTileGrid.generateThumbnail(id, targetW, targetH, dims));
- const thumb = createCanvasThumbnail(canvas, id !== 'layer-bg');
- setLayers((prev) =>
- prev.map((l) => (l.id === id ? { ...l, thumbnailUrl: thumb } : l))
- );
+ if (!thumb) return;
+
+ setLayers((prev) => {
+ const existingLayer = prev.find((l) => l.id === id);
+ if (!existingLayer || existingLayer.thumbnailUrl === thumb) return prev;
+ return prev.map((l) => (l.id === id ? { ...l, thumbnailUrl: thumb } : l));
+ });
};
const existing = thumbDebounceTimersRef.current.get(id);
@@ -517,10 +561,10 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
const timer = setTimeout(() => {
thumbDebounceTimersRef.current.delete(id);
run();
- }, 150);
+ }, 350);
thumbDebounceTimersRef.current.set(id, timer);
}
- }, []);
+ }, [_dimensions]);
// Add a new raster layer, folder, or adjustment layer
const addLayer = useCallback(
@@ -528,74 +572,93 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
type: 'raster' | 'folder' | 'vector' | 'frame' | 'adjustment' = 'raster',
explicitParentId?: string | null,
customName?: string,
- customId?: string
+ customId?: string,
+ selectNewLayer: boolean = true
): LayerItem => {
- let createdLayer: LayerItem | null = null;
const id = customId || `${type}-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
+ const currentLayers = layersRef.current;
+ const currentActiveIdx = currentLayers.findIndex((l) => l.id === activeLayerIdRef.current);
+ const currentActiveLayer = currentLayers[currentActiveIdx];
+
+ let initialParentId: string | null = null;
+ if (explicitParentId !== undefined) {
+ initialParentId = explicitParentId;
+ } else if (currentActiveLayer) {
+ initialParentId = currentActiveLayer.type === 'folder' ? currentActiveLayer.id : currentActiveLayer.parentId;
+ }
+
+ const resolveLayerName = (list: LayerItem[]) => {
+ if (customName) return customName;
+ let count = 1;
+ const prefix =
+ type === 'folder' ? 'Folder ' :
+ type === 'vector' ? 'Vector ' :
+ type === 'frame' ? 'Frame ' :
+ type === 'adjustment' ? 'Adjustment ' : 'Layer ';
+ list.forEach((l) => {
+ if (l.type === type && l.name.startsWith(prefix)) {
+ const num = parseInt(l.name.replace(prefix, ''), 10);
+ if (!isNaN(num) && num >= count) {
+ count = num + 1;
+ }
+ }
+ });
+ return `${prefix}${count}`;
+ };
+
+ const createdLayer: LayerItem = {
+ id,
+ name: resolveLayerName(currentLayers),
+ type,
+ visible: true,
+ opacity: 1,
+ blendMode: type === 'folder' ? 'pass-through' : 'normal',
+ locked: false,
+ collapsed: false,
+ parentId: initialParentId,
+ thumbnailUrl: '',
+ expressionColor:
+ currentActiveLayer?.expressionColor === 'monochrome'
+ ? 'monochrome'
+ : currentActiveLayer?.expressionColor === 'gray'
+ ? 'gray'
+ : 'color',
+ monoThreshold: currentActiveLayer?.monoThreshold ?? 128,
+ monoExpressBlack: currentActiveLayer?.monoExpressBlack ?? true,
+ monoExpressWhite: currentActiveLayer?.monoExpressWhite ?? true,
+ };
setLayers((prev) => {
- // Find active layer to determine placement
- const activeIdx = prev.findIndex((l) => l.id === activeLayerId);
+ if (prev.some((l) => l.id === id)) return prev;
+ const activeIdx = prev.findIndex((l) => l.id === activeLayerIdRef.current);
const activeLayer = prev[activeIdx];
let parentId: string | null = null;
if (explicitParentId !== undefined) {
parentId = explicitParentId;
} else if (activeLayer) {
- if (activeLayer.type === 'folder') {
- parentId = activeLayer.id;
- } else {
- parentId = activeLayer.parentId;
- }
- }
-
- let name = customName;
- if (!name) {
- let count = 1;
- const prefix =
- type === 'folder' ? 'Folder ' :
- type === 'vector' ? 'Vector ' :
- type === 'frame' ? 'Frame ' :
- type === 'adjustment' ? 'Adjustment ' : 'Layer ';
- prev.forEach((l) => {
- if (l.type === type && l.name.startsWith(prefix)) {
- const num = parseInt(l.name.replace(prefix, ''), 10);
- if (!isNaN(num) && num >= count) {
- count = num + 1;
- }
- }
- });
- name = `${prefix}${count}`;
+ parentId = activeLayer.type === 'folder' ? activeLayer.id : activeLayer.parentId;
}
const newLayer: LayerItem = {
- id,
- name,
- type,
- visible: true,
- opacity: 1,
- blendMode: type === 'folder' ? 'pass-through' : 'normal',
- locked: false,
- collapsed: false,
+ ...createdLayer,
+ name: resolveLayerName(prev),
parentId,
- thumbnailUrl: '',
- expressionColor: activeLayer?.expressionColor === 'monochrome' ? 'monochrome' : activeLayer?.expressionColor === 'gray' ? 'gray' : 'color',
- monoThreshold: activeLayer?.monoThreshold ?? 128,
- monoExpressBlack: activeLayer?.monoExpressBlack ?? true,
- monoExpressWhite: activeLayer?.monoExpressWhite ?? true,
};
- createdLayer = newLayer;
const insertIndex = activeIdx >= 0 ? activeIdx : 0;
const nextLayers = [...prev];
nextLayers.splice(insertIndex, 0, newLayer);
+ layersRef.current = nextLayers;
return nextLayers;
});
- setActiveLayerId(id);
- return createdLayer!;
+ if (selectNewLayer) {
+ setActiveLayerId(id);
+ }
+ return createdLayer;
},
- [activeLayerId]
+ [setActiveLayerId]
);
// Add a layer that originated from a remote peer
@@ -610,6 +673,9 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
if (ctx) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
+ const isMono = layerItem.expressionColor === 'monochrome';
+ globalTileGrid.ingestCanvas(layerItem.id, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ globalTileGrid.notifyChange(true);
updateLayerThumbnail(layerItem.id, true);
}
} else {
@@ -622,7 +688,7 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
setLayers((prev) => {
if (prev.some((l) => l.id === layerItem.id)) return prev;
const next = [...prev];
- const bgIdx = next.findIndex((l) => l.id === 'layer-bg' || l.id.startsWith('layer-bg'));
+ const bgIdx = next.findIndex((l) => isBackgroundLayerId(l.id));
if (bgIdx >= 0) {
next.splice(bgIdx, 0, layerItem);
} else {
@@ -638,6 +704,8 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
const deleteRemoteLayer = useCallback((layerId: string) => {
setLayers((prev) => prev.filter((l) => l.id !== layerId));
layerCanvasesRef.current.delete(layerId);
+ layerSourceCanvasesRef.current.delete(layerId);
+ globalTileGrid.clearLayer(layerId);
}, []);
// Sync entire document state from remote host
@@ -652,7 +720,7 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
if (assignedLayerId) {
setActiveLayerId(assignedLayerId);
} else {
- const topRaster = syncedLayers.find((l) => l.type === 'raster' && l.id !== 'layer-bg' && !l.id.startsWith('layer-bg'));
+ const topRaster = syncedLayers.find((l) => l.type === 'raster' && !isBackgroundLayerId(l.id));
if (topRaster) {
setActiveLayerId(topRaster.id);
}
@@ -670,6 +738,9 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
if (ctx) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
+ const isMono = layer.expressionColor === 'monochrome';
+ globalTileGrid.ingestCanvas(layer.id, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ globalTileGrid.notifyChange(true);
updateLayerThumbnail(layer.id, true);
}
} else {
@@ -684,30 +755,29 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
}
});
},
- [updateLayerThumbnail]
+ [setActiveLayerId, updateLayerThumbnail]
);
- // Duplicate an existing layer with a single click
+ // Duplicate an existing layer or folder hierarchy with a single click
const duplicateLayer = useCallback((id: string) => {
setLayers((prev) => {
const sourceIdx = prev.findIndex((l) => l.id === id);
if (sourceIdx < 0) return prev;
- const source = prev[sourceIdx];
- const newId = `${source.type}-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
-
- if (source.type === 'raster') {
- // Record pending copy so when canvas mounts it copies pixel data
- pendingCanvasCopiesRef.current.set(newId, source.id);
-
- // Also duplicate offscreen source canvas if it exists
- const srcSource = layerSourceCanvasesRef.current.get(source.id);
- if (srcSource) {
- const newSource = document.createElement('canvas');
- newSource.width = srcSource.width;
- newSource.height = srcSource.height;
- get2DContext(newSource)?.drawImage(srcSource, 0, 0);
- layerSourceCanvasesRef.current.set(newId, newSource);
+ const cloneSingleLayer = (source: LayerItem, newParentId: string | null, nameSuffix: string = ' Copy'): LayerItem => {
+ const newId = `${source.type}-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
+
+ if (source.type === 'raster' || source.type === 'vector' || source.type === 'frame') {
+ pendingCanvasCopiesRef.current.set(newId, source.id);
+
+ const srcSource = layerSourceCanvasesRef.current.get(source.id);
+ if (srcSource) {
+ const newSource = document.createElement('canvas');
+ newSource.width = srcSource.width;
+ newSource.height = srcSource.height;
+ get2DContext(newSource)?.drawImage(srcSource, 0, 0);
+ layerSourceCanvasesRef.current.set(newId, newSource);
+ }
}
let newMaskCanvas: HTMLCanvasElement | undefined;
@@ -721,85 +791,77 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
newMaskThumb = source.maskThumbnailUrl;
}
- const newLayer: LayerItem = {
+ return {
...source,
id: newId,
- name: `${source.name} Copy`,
+ name: `${source.name}${nameSuffix}`,
+ parentId: newParentId,
thumbnailUrl: source.thumbnailUrl,
maskCanvas: newMaskCanvas,
maskThumbnailUrl: newMaskThumb,
+ maskVersion: source.maskCanvas ? 1 : undefined,
+ vectorStrokes: source.vectorStrokes ? JSON.parse(JSON.stringify(source.vectorStrokes)) : undefined,
+ comicFrames: source.comicFrames ? JSON.parse(JSON.stringify(source.comicFrames)) : undefined,
+ balloons: source.balloons ? JSON.parse(JSON.stringify(source.balloons)) : undefined,
adjustmentData: source.adjustmentData ? JSON.parse(JSON.stringify(source.adjustmentData)) : undefined,
+ styles: source.styles ? JSON.parse(JSON.stringify(source.styles)) : undefined,
};
+ };
+ const source = prev[sourceIdx];
+ if (source.type !== 'folder') {
+ const newLayer = cloneSingleLayer(source, source.parentId, ' Copy');
const nextLayers = [...prev];
nextLayers.splice(sourceIdx, 0, newLayer);
- setActiveLayerId(newId);
+ setActiveLayerId(newLayer.id);
return nextLayers;
- } else {
- // Duplicate folder and all child layers inside
- const folderCopyId = newId;
- const newFolder: LayerItem = {
- ...source,
- id: folderCopyId,
- name: `${source.name} Copy`,
- };
+ }
- // Find all child layers inside this folder
- const childLayers = prev.filter((l) => l.parentId === source.id);
- const childCopies: LayerItem[] = childLayers.map((child) => {
- const childCopyId = `raster-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
- pendingCanvasCopiesRef.current.set(childCopyId, child.id);
- return {
- ...child,
- id: childCopyId,
- name: `${child.name} Copy`,
- parentId: folderCopyId,
- };
- });
+ // Recursively duplicate folder and all nested descendants in stack order
+ const clonedItems: LayerItem[] = [];
+ const cloneFolderSubtree = (folder: LayerItem, targetParentId: string | null, isRootFolder: boolean) => {
+ const folderCopy = cloneSingleLayer(folder, targetParentId, isRootFolder ? ' Copy' : '');
+ clonedItems.push(folderCopy);
+ const directChildren = prev.filter((l) => l.parentId === folder.id);
+ for (const child of directChildren) {
+ if (child.type === 'folder') {
+ cloneFolderSubtree(child, folderCopy.id, false);
+ } else {
+ clonedItems.push(cloneSingleLayer(child, folderCopy.id, ' Copy'));
+ }
+ }
+ };
- const nextLayers = [...prev];
- nextLayers.splice(sourceIdx, 0, newFolder, ...childCopies);
- setActiveLayerId(folderCopyId);
- return nextLayers;
+ cloneFolderSubtree(source, source.parentId, true);
+ const nextLayers = [...prev];
+ nextLayers.splice(sourceIdx, 0, ...clonedItems);
+ if (clonedItems[0]) {
+ setActiveLayerId(clonedItems[0].id);
}
+ return nextLayers;
});
- }, []);
+ }, [setActiveLayerId]);
- // Delete a layer or folder
+ // Delete a layer or folder (including nested folder hierarchies)
const deleteLayer = useCallback((id: string) => {
setLayers((prev) => {
- // Don't delete if it's the only raster layer
- const rasterCount = prev.filter((l) => l.type === 'raster').length;
- const target = prev.find((l) => l.id === id);
- if (!target) return prev;
-
- if (target.type === 'raster' && rasterCount <= 1) {
- return prev;
- }
+ const res = computeBatchDeleteLayers(prev, [id], activeLayerIdRef.current);
+ if (res.deletedIds.length === 0) return prev;
- // If deleting folder, also delete all child layers
- let nextLayers: LayerItem[];
- if (target.type === 'folder') {
- nextLayers = prev.filter((l) => l.id !== id && l.parentId !== id);
- } else {
- nextLayers = prev.filter((l) => l.id !== id);
+ for (const delId of res.deletedIds) {
+ layerCanvasesRef.current.delete(delId);
+ layerSourceCanvasesRef.current.delete(delId);
+ globalTileGrid.clearLayer(delId);
}
- // If deleted active layer, choose next available layer
- if (activeLayerId === id || (target.type === 'folder' && prev.find((l) => l.id === activeLayerId)?.parentId === id)) {
- const nextActive = nextLayers.find((l) => l.type === 'raster') || nextLayers[0];
- if (nextActive) {
- setActiveLayerId(nextActive.id);
- }
+ if (res.deletedIds.includes(activeLayerIdRef.current)) {
+ setActiveLayerId(res.nextActiveId);
} else {
- setSelectedLayerIds((prevSelected) => prevSelected.filter((sid) => sid !== id));
+ setSelectedLayerIds((prevSelected) => prevSelected.filter((sid) => !res.deletedIds.includes(sid)));
}
-
- layerCanvasesRef.current.delete(id);
- layerSourceCanvasesRef.current.delete(id);
- return nextLayers;
+ return res.nextLayers;
});
- }, [activeLayerId, setActiveLayerId, setSelectedLayerIds]);
+ }, [setActiveLayerId, setSelectedLayerIds]);
// Delete all selected layers or folders
const deleteSelectedLayers = useCallback(() => {
@@ -865,7 +927,7 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
const toggleClipping = useCallback((id: string) => {
setLayers((prev) => {
const idx = prev.findIndex((l) => l.id === id);
- if (idx === -1 || idx === prev.length - 1 || id === 'layer-bg') {
+ if (idx === -1 || idx === prev.length - 1 || isBackgroundLayerId(id)) {
return prev;
}
return prev.map((l) => (l.id === id ? { ...l, clipped: !l.clipped } : l));
@@ -901,6 +963,7 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
maskEnabled: true,
maskLinked: true,
maskThumbnailUrl: thumb,
+ maskVersion: 1,
};
})
);
@@ -931,6 +994,26 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
d[i + 3] = Math.round(d[i + 3] * maskLum);
}
ctx.putImageData(imgData, 0, 0);
+
+ const sCanvas = layerSourceCanvasesRef.current.get(layerId);
+ if (sCanvas) {
+ const sCtx = get2DContext(sCanvas);
+ if (sCtx) {
+ const sData = sCtx.getImageData(0, 0, sCanvas.width, sCanvas.height);
+ const sd = sData.data;
+ for (let i = 0; i < sd.length; i += 4) {
+ if (sd[i + 3] === 0) continue;
+ const maskLum =
+ ((0.299 * maskData[i] + 0.587 * maskData[i + 1] + 0.114 * maskData[i + 2]) / 255) *
+ (maskData[i + 3] / 255);
+ sd[i + 3] = Math.round(sd[i + 3] * maskLum);
+ }
+ sCtx.putImageData(sData, 0, 0);
+ }
+ }
+
+ const isMono = l.expressionColor === 'monochrome';
+ globalTileGrid.ingestCanvas(layerId, c, isMono ? 'monochrome-1bit' : 'color-32bit');
updateLayerThumbnail(layerId, true);
}
}
@@ -942,6 +1025,7 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
maskEnabled: undefined,
maskLinked: undefined,
maskThumbnailUrl: undefined,
+ maskVersion: undefined,
};
})
);
@@ -972,8 +1056,13 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
if (!target?.maskCanvas) return;
const thumb = createCanvasThumbnail(target.maskCanvas, false);
setLayers((prev) =>
- prev.map((l) => (l.id === layerId ? { ...l, maskThumbnailUrl: thumb } : l))
+ prev.map((l) =>
+ l.id === layerId
+ ? { ...l, maskThumbnailUrl: thumb, maskVersion: (l.maskVersion || 0) + 1 }
+ : l
+ )
);
+ globalTileGrid.notifyChange(true);
};
if (immediate) {
@@ -1457,6 +1546,9 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
sCtx.clearRect(0, 0, sourceCanvas.width, sourceCanvas.height);
sCtx.drawImage(displayCanvas, 0, 0);
+ const isMono = target.expressionColor === 'monochrome';
+ globalTileGrid.ingestCanvas(id, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ globalTileGrid.notifyChange(true);
updateLayerThumbnail(id, true);
return { beforeImageData, afterImageData };
@@ -1493,6 +1585,9 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
prev.map((l) => (l.id === id ? { ...l, layerColorEnabled: false } : l))
);
+ const isMono = target.expressionColor === 'monochrome';
+ globalTileGrid.ingestCanvas(id, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ globalTileGrid.notifyChange(true);
updateLayerThumbnail(id, true);
return { beforeImageData, afterImageData };
@@ -1544,6 +1639,9 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
const afterImageData = dCtx.getImageData(0, 0, displayCanvas.width, displayCanvas.height);
+ const isMono = targetMode === 'monochrome';
+ globalTileGrid.ingestCanvas(id, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ globalTileGrid.notifyChange(true);
setLayers((prev) => prev.map((l) => (l.id === id ? updatedLayer : l)));
updateLayerThumbnail(id, true);
@@ -1678,18 +1776,21 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
const ctx = get2DContext(canvas);
if (!ctx) return;
- if (activeLayerId === 'layer-bg') {
+ const isBg = isBackgroundLayerId(activeLayerId);
+ if (isBg) {
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, canvas.width, canvas.height);
+ (canvas as any).__isSolidWhite = true;
} else {
ctx.clearRect(0, 0, canvas.width, canvas.height);
+ (canvas as any).__isBlank = true;
}
const sCanvas = layerSourceCanvasesRef.current.get(activeLayerId);
if (sCanvas) {
const sCtx = get2DContext(sCanvas);
if (sCtx) {
- if (activeLayerId === 'layer-bg') {
+ if (isBg) {
sCtx.fillStyle = '#ffffff';
sCtx.fillRect(0, 0, sCanvas.width, sCanvas.height);
} else {
@@ -1698,6 +1799,12 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
}
}
+ if (isBg) {
+ globalTileGrid.ingestCanvas(activeLayerId, canvas, 'color-32bit');
+ } else {
+ globalTileGrid.clearLayer(activeLayerId);
+ }
+ globalTileGrid.notifyChange(true);
updateLayerThumbnail(activeLayerId);
}, [activeLayerId, updateLayerThumbnail]);
@@ -1705,6 +1812,12 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
const resetToNewCanvas = useCallback(
(_dims: CanvasDimensions, backgroundColor: string = '#ffffff', _mode: CanvasColorMode = 'color', defaultToneFrequency: number = 60) => {
defaultToneFrequencyRef.current = Math.max(20, Math.min(85, Math.round(defaultToneFrequency || 60)));
+ for (const oldId of Array.from(layerCanvasesRef.current.keys())) {
+ globalTileGrid.clearLayer(oldId);
+ }
+ for (const l of layersRef.current) {
+ globalTileGrid.clearLayer(l.id);
+ }
pendingCanvasCopiesRef.current.clear();
pendingInitialDataRef.current.clear();
layerCanvasesRef.current.clear();
@@ -1751,21 +1864,34 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
setActiveLayerId(topId);
return { layers: initialLayers, activeLayerId: topId };
},
- []
+ [setActiveLayerId]
);
// Clear all layers and canvas references when no document is active
const clearDocument = useCallback(() => {
+ for (const oldId of Array.from(layerCanvasesRef.current.keys())) {
+ globalTileGrid.clearLayer(oldId);
+ }
+ for (const l of layersRef.current) {
+ globalTileGrid.clearLayer(l.id);
+ }
pendingCanvasCopiesRef.current.clear();
pendingInitialDataRef.current.clear();
layerCanvasesRef.current.clear();
layerSourceCanvasesRef.current.clear();
setLayers([]);
setActiveLayerId('');
- }, []);
+ globalTileGrid.notifyChange(true);
+ }, [setActiveLayerId]);
// Load an entire document (from PSD, CSP, or Image)
const loadDocument = useCallback((doc: LoadedDocument) => {
+ for (const oldId of Array.from(layerCanvasesRef.current.keys())) {
+ globalTileGrid.clearLayer(oldId);
+ }
+ for (const l of layersRef.current) {
+ globalTileGrid.clearLayer(l.id);
+ }
pendingCanvasCopiesRef.current.clear();
pendingInitialDataRef.current.clear();
layerCanvasesRef.current.clear();
@@ -1773,8 +1899,11 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
if (doc.layerCanvases) {
doc.layerCanvases.forEach((c, id) => {
+ layerCanvasesRef.current.set(id, c);
pendingInitialDataRef.current.set(id, c);
const layerMeta = doc.layers.find((l) => l.id === id);
+ const isMono = layerMeta?.expressionColor === 'monochrome';
+ globalTileGrid.ingestCanvas(id, c, isMono ? 'monochrome-1bit' : 'color-32bit');
if (
layerMeta &&
(layerMeta.toneEnabled ||
@@ -1793,7 +1922,8 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
setLayers(doc.layers);
const topRaster = doc.layers.find((l) => l.type === 'raster');
setActiveLayerId(topRaster ? topRaster.id : doc.layers[0]?.id || '');
- }, []);
+ globalTileGrid.notifyChange(true);
+ }, [setActiveLayerId]);
// Internal Layer Clipboard
const layerClipboardRef = useRef<{
@@ -1885,7 +2015,23 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
sCtx.fillStyle = `rgb(${grayVal},${grayVal},${grayVal})`;
if (selection) {
- if (selection.type === 'rect') {
+ if (selection.mask) {
+ const imgData = sCtx.createImageData(targetW, targetH);
+ const d = imgData.data;
+ const m = selection.mask;
+ const len = Math.min(m.length, targetW * targetH);
+ for (let i = 0; i < len; i++) {
+ const a = m[i];
+ if (a > 0) {
+ const p = i * 4;
+ d[p] = grayVal;
+ d[p + 1] = grayVal;
+ d[p + 2] = grayVal;
+ d[p + 3] = a;
+ }
+ }
+ sCtx.putImageData(imgData, 0, 0);
+ } else if (selection.type === 'rect') {
sCtx.fillRect(
selection.bounds.x,
selection.bounds.y,
@@ -1932,6 +2078,7 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
toneDensityType: densityType,
};
+ globalTileGrid.ingestCanvas(newId, sourceCanvas, 'color-32bit');
applyLayerEffects(sourceCanvas, displayCanvas, newLayer, _dimensions.dpi ?? 600, selection ? selection.bounds : undefined);
const thumb = createCanvasThumbnail(displayCanvas, true);
@@ -2221,8 +2368,33 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
}
});
- // Re-apply screentone and layer effects for layers that have them enabled
+ // Re-apply screentone and layer effects for layers that have them enabled, and resize mask canvases
+ const updatedMasks = new Map<string, { maskCanvas: HTMLCanvasElement; maskThumb: string }>();
layers.forEach((l) => {
+ if (l.maskCanvas) {
+ const tempMask = document.createElement('canvas');
+ tempMask.width = l.maskCanvas.width;
+ tempMask.height = l.maskCanvas.height;
+ get2DContext(tempMask)?.drawImage(l.maskCanvas, 0, 0);
+
+ l.maskCanvas.width = newW;
+ l.maskCanvas.height = newH;
+ const mCtx = get2DContext(l.maskCanvas);
+ if (mCtx) {
+ mCtx.fillStyle = '#ffffff';
+ mCtx.fillRect(0, 0, newW, newH);
+ if (scaleContent) {
+ mCtx.drawImage(tempMask, 0, 0, tempMask.width, tempMask.height, 0, 0, newW, newH);
+ } else {
+ mCtx.drawImage(tempMask, offsetX, offsetY);
+ }
+ }
+ updatedMasks.set(l.id, {
+ maskCanvas: l.maskCanvas,
+ maskThumb: createCanvasThumbnail(l.maskCanvas, false),
+ });
+ }
+
if (l.toneEnabled || l.layerColorEnabled || (l.expressionColor && l.expressionColor !== 'color')) {
const sCanvas = layerSourceCanvasesRef.current.get(l.id);
const dCanvas = layerCanvasesRef.current.get(l.id);
@@ -2234,10 +2406,31 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
}
});
+ // Re-ingest all resized canvases into globalTileGrid
+ layerCanvasesRef.current.forEach((canvas, layerId) => {
+ const l = layers.find((item) => item.id === layerId);
+ const isMono = l?.expressionColor === 'monochrome';
+ globalTileGrid.clearLayer(layerId);
+ globalTileGrid.ingestCanvas(layerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ });
+ globalTileGrid.notifyChange(true);
+
setLayers((prev) =>
prev.map((l) => {
const newThumb = updatedThumbnails.get(l.id);
- return newThumb ? { ...l, thumbnailUrl: newThumb } : l;
+ const maskInfo = updatedMasks.get(l.id);
+ if (!newThumb && !maskInfo) return l;
+ return {
+ ...l,
+ ...(newThumb ? { thumbnailUrl: newThumb } : {}),
+ ...(maskInfo
+ ? {
+ maskCanvas: maskInfo.maskCanvas,
+ maskThumbnailUrl: maskInfo.maskThumb,
+ maskVersion: (l.maskVersion || 0) + 1,
+ }
+ : {}),
+ };
})
);
},
diff --git a/src/hooks/useMultiplayer.ts b/src/hooks/useMultiplayer.ts
index 83feed9..99270e0 100644
--- a/src/hooks/useMultiplayer.ts
+++ b/src/hooks/useMultiplayer.ts
@@ -147,8 +147,8 @@ export function useMultiplayer({
}
case 'JOIN_REQUEST': {
- // A guest wants to join
- if (msg.peer) {
+ // Only the host processes join requests; other guests will receive PEER_JOINED
+ if (msg.peer && isHostRef.current) {
const guestPeer = msg.peer;
setPeers((prev) => {
@@ -158,59 +158,56 @@ export function useMultiplayer({
return next;
});
- showToastRef.current(`🎨 ${guestPeer.name} joined the canvas`);
+ showToastRef.current(`${guestPeer.name} joined the canvas`);
- // If we are host, set up a dedicated layer for the guest and reply with accept + current doc
- if (isHostRef.current) {
- let assignedLayerId: string | undefined;
- let effectiveLayers = layersRef.current;
+ let assignedLayerId: string | undefined;
+ let effectiveLayers = layersRef.current;
- // Delegate layer creation to the host application
- if (onRemoteJoinRequestRef.current) {
- const res = onRemoteJoinRequestRef.current(guestPeer);
- if (res) {
- assignedLayerId = res.assignedLayerId;
- effectiveLayers = res.updatedLayers;
- }
+ // Delegate layer creation to the host application
+ if (onRemoteJoinRequestRef.current) {
+ const res = onRemoteJoinRequestRef.current(guestPeer);
+ if (res) {
+ assignedLayerId = res.assignedLayerId;
+ effectiveLayers = res.updatedLayers;
}
+ }
- // Send JOIN_ACCEPTED to the joining guest
- const joinAcceptedMsg: JoinAcceptedMessage = {
- type: 'JOIN_ACCEPTED',
- targetPeerId: guestPeer.id,
- roomName: hostInfoRef.current?.roomName || 'Studio',
- peers: [...peersRef.current.filter((p) => p.id !== guestPeer.id), myPeerRef.current],
- hostId: myPeerRef.current.id,
- docDimensions: dimensionsRef.current,
- colorMode: colorModeRef.current,
- assignedLayerId,
- };
- multiplayerService.sendMessage(joinAcceptedMsg);
-
- // Send document synchronization
- multiplayerService.sendMessage({
- type: 'DOC_SYNC_RESPONSE',
- targetPeerId: guestPeer.id,
- dimensions: dimensionsRef.current,
- colorMode: colorModeRef.current,
- layers: effectiveLayers,
- layerDataUrls: {},
- });
-
- // Progressive Tile Streaming: stream active layer tiles progressively from sparse tile grid
- for (const layer of effectiveLayers) {
- const tiles = globalTileGrid.getLayerTiles(layer.id);
- for (const tile of tiles) {
- multiplayerService.sendTileDelta(layer.id, tile);
- }
- }
+ // Send JOIN_ACCEPTED to the joining guest
+ const joinAcceptedMsg: JoinAcceptedMessage = {
+ type: 'JOIN_ACCEPTED',
+ targetPeerId: guestPeer.id,
+ roomName: hostInfoRef.current?.roomName || 'Studio',
+ peers: [...peersRef.current.filter((p) => p.id !== guestPeer.id), myPeerRef.current],
+ hostId: myPeerRef.current.id,
+ docDimensions: dimensionsRef.current,
+ colorMode: colorModeRef.current,
+ assignedLayerId,
+ };
+ multiplayerService.sendMessage(joinAcceptedMsg);
+
+ // Send document synchronization
+ multiplayerService.sendMessage({
+ type: 'DOC_SYNC_RESPONSE',
+ targetPeerId: guestPeer.id,
+ dimensions: dimensionsRef.current,
+ colorMode: colorModeRef.current,
+ layers: effectiveLayers,
+ layerDataUrls: {},
+ });
- // Broadcast PEER_JOINED to other already connected peers
- multiplayerService.sendMessage({
- type: 'PEER_JOINED',
- peer: guestPeer,
- });
+ // Progressive Tile Streaming: stream active layer tiles progressively from sparse tile grid
+ for (const layer of effectiveLayers) {
+ const tiles = globalTileGrid.getLayerTiles(layer.id);
+ for (const tile of tiles) {
+ multiplayerService.sendTileDelta(layer.id, tile);
+ }
}
+
+ // Broadcast PEER_JOINED to other already connected peers
+ multiplayerService.sendMessage({
+ type: 'PEER_JOINED',
+ peer: guestPeer,
+ });
}
break;
}
@@ -374,6 +371,9 @@ export function useMultiplayer({
version: tMsg.version,
data: tMsg.data,
dirty: true,
+ isPagedToDisk: false,
+ lastAccessTimestamp: typeof performance !== 'undefined' ? performance.now() : Date.now(),
+ lod: 0,
};
globalTileGrid.setTile(tMsg.layerId, tMsg.tileX, tMsg.tileY, tile);
const canvas = layerCanvasesRef.current.get(tMsg.layerId);
@@ -385,6 +385,7 @@ export function useMultiplayer({
height: TILE_SIZE,
});
}
+ globalTileGrid.notifyChange(true);
break;
}
diff --git a/src/index.css b/src/index.css
index c71ae30..403efb3 100644
--- a/src/index.css
+++ b/src/index.css
@@ -1,5 +1,32 @@
@import "tailwindcss";
+:root {
+ --bg-canvas: #161616;
+ --bg-panel: #202020;
+ --bg-hover: #2c2c2c;
+ --text-primary: #e5e5e5;
+ --text-muted: #8a8a8a;
+
+ --accent: #e5e5e5;
+ --accent-rgb: 229, 229, 229;
+ --accent-contrast: #161616;
+ --accent-subtle: rgba(229, 229, 229, 0.14);
+ --accent-border: rgba(229, 229, 229, 0.32);
+
+ /* Aliases for secondary modals */
+ --modern-accent: var(--accent);
+ --modern-accent-rgb: var(--accent-rgb);
+ --modern-accent-subtle: var(--accent-subtle);
+ --modern-accent-border: var(--accent-border);
+ --modern-accent-hover: rgba(229, 229, 229, 0.2);
+ --modern-accent-glow: transparent;
+ --modern-bg-base: #161616;
+ --modern-bg-surface: #202020;
+ --modern-bg-elevated: #2c2c2c;
+ --modern-bg-input: #161616;
+ --modern-border: transparent;
+}
+
@layer base {
* {
box-sizing: border-box;
@@ -7,16 +34,29 @@
-webkit-user-select: none;
}
- html, body, #root {
+ html {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
overflow: hidden;
- background-color: #1e1e1e;
- color: #cccccc;
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
- font-size: 13px;
+ font-size: 16px;
+ }
+
+ body,
+ #root {
+ margin: 0;
+ padding: 0;
+ width: 100%;
+ height: 100%;
+ overflow: hidden;
+ background-color: var(--bg-canvas);
+ color: var(--text-primary);
+ font-family: Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
+ font-size: 12px;
+ line-height: 1.35;
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
touch-action: none;
-webkit-touch-callout: none;
}
@@ -27,32 +67,42 @@
}
}
-/* Utilitarian desktop scrollbars */
+.no-scrollbar {
+ scrollbar-width: none;
+ -ms-overflow-style: none;
+}
+
+.no-scrollbar::-webkit-scrollbar {
+ display: none;
+}
+
+/* Minimalist scrollbars */
::-webkit-scrollbar {
- width: 6px;
- height: 6px;
+ width: 4px;
+ height: 4px;
}
::-webkit-scrollbar-track {
- background: #1e1e1e;
+ background: transparent;
}
::-webkit-scrollbar-thumb {
- background: #333333;
- border-radius: 2px;
+ background: #2c2c2c;
+ border-radius: 9999px;
}
::-webkit-scrollbar-thumb:hover {
- background: #444444;
+ background: #3d3d3d;
}
-/* Tactile desktop range sliders (scaled for comfortable stylus interaction) */
+/* Minimalist range sliders */
input[type="range"] {
-webkit-appearance: none;
appearance: none;
background: transparent;
cursor: pointer;
- height: 22px;
+ height: 16px;
+ accent-color: var(--accent);
}
input[type="range"]:focus {
@@ -60,713 +110,67 @@ input[type="range"]:focus {
}
input[type="range"]::-webkit-slider-runnable-track {
- height: 6px;
- background: #2a2a2a;
- border: 1px solid #383838;
- border-radius: 2px;
+ height: 3px;
+ background: #2c2c2c;
+ border: none;
+ border-radius: 9999px;
}
input[type="range"]::-moz-range-track {
- height: 6px;
- background: #2a2a2a;
- border: 1px solid #383838;
- border-radius: 2px;
+ height: 3px;
+ background: #2c2c2c;
+ border: none;
+ border-radius: 9999px;
}
input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
- width: 14px;
- height: 20px;
- background: #555555;
- border: 1px solid #707070;
- border-radius: 2px;
- margin-top: -7px;
+ width: 10px;
+ height: 10px;
+ background: var(--accent);
+ border: none;
+ border-radius: 9999px;
+ margin-top: -3.5px;
+ transition: transform 0.1s ease;
}
input[type="range"]:hover::-webkit-slider-thumb {
- background: #666666;
- border-color: #888888;
-}
-
-input[type="range"]:active::-webkit-slider-thumb {
- background: #808080;
- border-color: #aaaaaa;
+ transform: scale(1.18);
}
input[type="range"]::-moz-range-thumb {
- width: 14px;
- height: 20px;
- background: #555555;
- border: 1px solid #707070;
- border-radius: 2px;
-}
-
-input[type="range"]:hover::-moz-range-thumb {
- background: #666666;
- border-color: #888888;
-}
-
-input[type="range"]:active::-moz-range-thumb {
- background: #808080;
- border-color: #aaaaaa;
-}
-
-/* ==========================================================================
- VINTAGE MANGA STUDIO (COMIC STUDIO / CSP VINTAGE) DESIGN SYSTEM
- Japanese desktop DCC styling: neutral industrial grey, tactile beveled relief,
- sunken grooves, steel-blue highlights, and utilitarian compact controls.
- ========================================================================== */
-
-[data-theme="vintage-manga"] {
- --theme-bg-workbench: #48484b;
- --theme-bg-panel: #4a4a4d;
- --theme-bg-panel-dark: #3e3e41;
- --theme-bg-header: linear-gradient(180deg, #525255 0%, #3e3e40 100%);
- --theme-bg-button: linear-gradient(180deg, #56565a 0%, #424245 100%);
- --theme-bg-button-hover: linear-gradient(180deg, #626266 0%, #4b4b4e 100%);
- --theme-bg-active: linear-gradient(180deg, #376590 0%, #204264 100%);
- --theme-border-active: #4a8fc7;
- --theme-border-dark: #242426;
- --theme-border-highlight: rgba(255, 255, 255, 0.18);
- --theme-bg-sunken: #2b2b2e;
-}
-
-[data-theme="vintage-manga"] body,
-[data-theme="vintage-manga"] #root,
-[data-theme="vintage-manga"] .app-root-container {
- background-color: #48484b !important;
- color: #d6d6da !important;
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Meiryo", "MS UI Gothic", "Hiragino Kaku Gothic ProN", Arial, sans-serif !important;
-}
-
-/* Vintage panel & sidebar surfaces */
-[data-theme="vintage-manga"] .bg-\[\#1e1e1e\],
-[data-theme="vintage-manga"] .bg-\[\#1e2023\],
-[data-theme="vintage-manga"] .bg-\[\#252526\],
-[data-theme="vintage-manga"] .bg-\[\#222223\],
-[data-theme="vintage-manga"] .bg-\[\#222224\],
-[data-theme="vintage-manga"] .bg-\[\#222225\],
-[data-theme="vintage-manga"] .bg-\[\#252528\] {
- background-color: #48484b !important;
-}
-
-[data-theme="vintage-manga"] .bg-\[\#1b1c1e\],
-[data-theme="vintage-manga"] .bg-\[\#1a1b1e\],
-[data-theme="vintage-manga"] .bg-\[\#161719\],
-[data-theme="vintage-manga"] .bg-\[\#141517\],
-[data-theme="vintage-manga"] .bg-\[\#141518\],
-[data-theme="vintage-manga"] .bg-\[\#18191b\],
-[data-theme="vintage-manga"] .bg-\[\#1c1d1f\],
-[data-theme="vintage-manga"] .bg-\[\#242426\],
-[data-theme="vintage-manga"] .bg-\[\#2a2a2a\],
-[data-theme="vintage-manga"] .bg-\[\#2a2a2d\],
-[data-theme="vintage-manga"] .bg-\[\#202226\] {
- background-color: #3e3e41 !important;
-}
-
-/* Vintage borders */
-[data-theme="vintage-manga"] .border-\[\#333333\],
-[data-theme="vintage-manga"] .border-\[\#2b2d31\],
-[data-theme="vintage-manga"] .border-\[\#25272c\],
-[data-theme="vintage-manga"] .border-\[\#26282c\],
-[data-theme="vintage-manga"] .border-\[\#3e3e42\],
-[data-theme="vintage-manga"] .border-\[\#282a2e\],
-[data-theme="vintage-manga"] .border-\[\#333336\],
-[data-theme="vintage-manga"] .border-\[\#38383a\],
-[data-theme="vintage-manga"] .border-\[\#3a3a3a\] {
- border-color: #242426 !important;
-}
-
-/* Vintage tactile buttons in toolbars & panels */
-[data-theme="vintage-manga"] button[class*="rounded"]:not([class*="rounded-full"]):not([class*="accent"]):not([class*="bg-transparent"]) {
- background-image: linear-gradient(180deg, #56565a 0%, #424245 100%);
- border: 1px solid #242426;
- box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.18), 0 1px 1px rgba(0, 0, 0, 0.3);
- color: #cccccc;
-}
-
-[data-theme="vintage-manga"] button[class*="rounded"]:not([class*="rounded-full"]):not([class*="accent"]):not([class*="bg-transparent"]):hover {
- background-image: linear-gradient(180deg, #626266 0%, #4b4b4e 100%);
- color: #ffffff;
-}
-
-/* Signature Manga Studio steel-blue active state */
-[data-theme="vintage-manga"] button[class*="bg-\[\#293d45\]"],
-[data-theme="vintage-manga"] button[class*="bg-\[\#383838\]"],
-[data-theme="vintage-manga"] button[class*="bg-\[\#37485e\]"],
-[data-theme="vintage-manga"] button[class*="bg-\[\#007acc\]"],
-[data-theme="vintage-manga"] div[class*="bg-\[\#007acc\]"],
-[data-theme="vintage-manga"] div[class*="bg-\[\#293d45\]"],
-[data-theme="vintage-manga"] .active-item {
- background-image: linear-gradient(180deg, #376590 0%, #204264 100%) !important;
- background-color: #204264 !important;
- border-color: #4a8fc7 !important;
- box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.65), 0 0 4px rgba(74, 143, 199, 0.4) !important;
- color: #ffffff !important;
-}
-
-/* Vintage sunken inputs, select boxes & textareas */
-[data-theme="vintage-manga"] input[type="text"],
-[data-theme="vintage-manga"] input[type="number"],
-[data-theme="vintage-manga"] select,
-[data-theme="vintage-manga"] textarea {
- background-color: #2b2b2e !important;
- border: 1px solid #1c1c1e !important;
- box-shadow: inset 1px 1px 2px rgba(0, 0, 0, 0.6), inset -1px -1px 0 rgba(255, 255, 255, 0.06) !important;
- color: #f0f0f4 !important;
- border-radius: 1px !important;
-}
-
-[data-theme="vintage-manga"] input[type="text"]:focus,
-[data-theme="vintage-manga"] input[type="number"]:focus,
-[data-theme="vintage-manga"] select:focus {
- border-color: #3888cc !important;
- outline: none !important;
-}
-
-/* Vintage tactile range sliders */
-[data-theme="vintage-manga"] input[type="range"]::-webkit-slider-runnable-track {
- height: 5px;
- background: #1c1c1e;
- border: 1px solid #141416;
- box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.8), 0 1px 0 rgba(255, 255, 255, 0.12);
- border-radius: 1px;
-}
-
-[data-theme="vintage-manga"] input[type="range"]::-moz-range-track {
- height: 5px;
- background: #1c1c1e;
- border: 1px solid #141416;
- box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.8), 0 1px 0 rgba(255, 255, 255, 0.12);
- border-radius: 1px;
-}
-
-[data-theme="vintage-manga"] input[type="range"]::-webkit-slider-thumb {
- width: 10px;
- height: 16px;
- background: linear-gradient(180deg, #78787e 0%, #4e4e52 100%);
- border: 1px solid #222224;
- box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.35), 0 1px 2px rgba(0, 0, 0, 0.5);
- border-radius: 1px;
- margin-top: -6px;
-}
-
-[data-theme="vintage-manga"] input[type="range"]:hover::-webkit-slider-thumb {
- background: linear-gradient(180deg, #88888e 0%, #5a5a5e 100%);
- border-color: #303034;
-}
-
-[data-theme="vintage-manga"] input[type="range"]::-moz-range-thumb {
width: 10px;
- height: 16px;
- background: linear-gradient(180deg, #78787e 0%, #4e4e52 100%);
- border: 1px solid #222224;
- box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.35), 0 1px 2px rgba(0, 0, 0, 0.5);
- border-radius: 1px;
-}
-
-/* Vintage scrollbars */
-[data-theme="vintage-manga"] ::-webkit-scrollbar {
- width: 7px;
- height: 7px;
-}
-
-[data-theme="vintage-manga"] ::-webkit-scrollbar-track {
- background: #343437;
-}
-
-[data-theme="vintage-manga"] ::-webkit-scrollbar-thumb {
- background: linear-gradient(180deg, #58585c 0%, #444447 100%);
- border: 1px solid #242426;
- border-radius: 1px;
-}
-
-[data-theme="vintage-manga"] ::-webkit-scrollbar-thumb:hover {
- background: linear-gradient(180deg, #646469 0%, #4e4e52 100%);
-}
-
-/* Canvas viewport paper drop shadow in vintage mode */
-[data-theme="vintage-manga"] canvas.canvas-paper {
- box-shadow: 0 4px 20px rgba(0, 0, 0, 0.65), 0 0 0 1px rgba(0, 0, 0, 0.45);
-}
-
-[data-theme="vintage-manga"] .canvas-viewport,
-[data-theme="vintage-manga"] main[class*="bg-\[\#282828\]"] {
- background-color: #48484b !important;
-}
-
-/* Vintage Manga Studio popup menus and dropdowns */
-[data-theme="vintage-manga"] div[role="menu"] {
- background-color: #3e3e41 !important;
- border-color: #242426 !important;
- box-shadow: 0 8px 24px rgba(0, 0, 0, 0.65), inset 0 1px 0 rgba(255, 255, 255, 0.15) !important;
-}
-
-[data-theme="vintage-manga"] div[role="menu"] button[role="menuitem"]:hover:not([disabled]) {
- background-image: linear-gradient(180deg, #376590 0%, #204264 100%) !important;
- color: #ffffff !important;
-}
-
-/* Vintage Manga Studio modal dialogs */
-[data-theme="vintage-manga"] div[class*="shadow-2xl"][class*="border"] {
- border-color: #242426 !important;
- box-shadow: 0 12px 36px rgba(0, 0, 0, 0.8), 0 0 0 1px #1e1e20 !important;
-}
-
-/* Neutralize AI-styled rounded pill corners and glassmorphism in vintage theme */
-[data-theme="vintage-manga"] div[class*="rounded-xl"],
-[data-theme="vintage-manga"] div[class*="rounded-2xl"],
-[data-theme="vintage-manga"] div[class*="rounded-lg"] {
- border-radius: 2px !important;
-}
-
-[data-theme="vintage-manga"] .backdrop-blur-xs,
-[data-theme="vintage-manga"] .backdrop-blur-sm,
-[data-theme="vintage-manga"] .backdrop-blur-md {
- backdrop-filter: none !important;
- -webkit-backdrop-filter: none !important;
-}
-
-/* ==========================================================================
- MODERN DESIGN SYSTEM
- Contemporary, minimalist, sleek workstation with dynamic accent colors and tone support.
- ========================================================================== */
-
-:root {
- --modern-accent: #3b82f6;
- --modern-accent-rgb: 59, 130, 246;
- --modern-accent-glow: rgba(59, 130, 246, 0.28);
- --modern-accent-subtle: rgba(59, 130, 246, 0.12);
- --modern-accent-hover: rgba(59, 130, 246, 0.2);
- --modern-accent-border: rgba(59, 130, 246, 0.42);
-
- /* Modern Theme Tone - Neutral Charcoal / Graphite Palette */
- --modern-bg-base: #18191d;
- --modern-bg-surface: #1e1f24;
- --modern-bg-elevated: #25262c;
- --modern-bg-input: #151619;
- --modern-border: rgba(255, 255, 255, 0.08);
- --modern-border-subtle: rgba(255, 255, 255, 0.04);
-}
-
-[data-theme="modern"] {
- /* Surface tokens (accent variables cascade dynamically from :root or inline element styles) */
- --modern-bg-base: #18191d;
- --modern-bg-surface: #1e1f24;
- --modern-bg-elevated: #25262c;
- --modern-bg-input: #151619;
- --modern-border: rgba(255, 255, 255, 0.08);
- --modern-border-subtle: rgba(255, 255, 255, 0.04);
-}
-
-[data-tone="oled"],
-[data-theme="modern"][data-tone="oled"] {
- --modern-bg-base: #000000;
- --modern-bg-surface: #070709;
- --modern-bg-elevated: #0f0f13;
- --modern-bg-input: #050507;
- --modern-border: rgba(255, 255, 255, 0.1);
- --modern-border-subtle: rgba(255, 255, 255, 0.05);
-}
-
-[data-tone="charcoal"],
-[data-theme="modern"][data-tone="charcoal"] {
- --modern-bg-base: #18191d;
- --modern-bg-surface: #1f2025;
- --modern-bg-elevated: #26272e;
- --modern-bg-input: #15161a;
- --modern-border: rgba(255, 255, 255, 0.08);
- --modern-border-subtle: rgba(255, 255, 255, 0.04);
-}
-
-[data-accent="blue"],
-[data-theme="modern"][data-accent="blue"] {
- --modern-accent: #3b82f6;
- --modern-accent-rgb: 59, 130, 246;
- --modern-accent-glow: rgba(59, 130, 246, 0.28);
- --modern-accent-subtle: rgba(59, 130, 246, 0.12);
- --modern-accent-hover: rgba(59, 130, 246, 0.2);
- --modern-accent-border: rgba(59, 130, 246, 0.42);
-}
-
-[data-accent="burgundy"],
-[data-theme="modern"][data-accent="burgundy"] {
- --modern-accent: #be123c;
- --modern-accent-rgb: 190, 18, 60;
- --modern-accent-glow: rgba(190, 18, 60, 0.28);
- --modern-accent-subtle: rgba(190, 18, 60, 0.12);
- --modern-accent-hover: rgba(190, 18, 60, 0.2);
- --modern-accent-border: rgba(190, 18, 60, 0.42);
-}
-
-[data-accent="green"],
-[data-theme="modern"][data-accent="green"] {
- --modern-accent: #10b981;
- --modern-accent-rgb: 16, 185, 129;
- --modern-accent-glow: rgba(16, 185, 129, 0.28);
- --modern-accent-subtle: rgba(16, 185, 129, 0.12);
- --modern-accent-hover: rgba(16, 185, 129, 0.2);
- --modern-accent-border: rgba(16, 185, 129, 0.42);
-}
-
-[data-accent="purple"],
-[data-theme="modern"][data-accent="purple"] {
- --modern-accent: #8b5cf6;
- --modern-accent-rgb: 139, 92, 246;
- --modern-accent-glow: rgba(139, 92, 246, 0.28);
- --modern-accent-subtle: rgba(139, 92, 246, 0.12);
- --modern-accent-hover: rgba(139, 92, 246, 0.2);
- --modern-accent-border: rgba(139, 92, 246, 0.42);
-}
-
-[data-accent="orange"],
-[data-theme="modern"][data-accent="orange"] {
- --modern-accent: #f97316;
- --modern-accent-rgb: 249, 115, 22;
- --modern-accent-glow: rgba(249, 115, 22, 0.28);
- --modern-accent-subtle: rgba(249, 115, 22, 0.12);
- --modern-accent-hover: rgba(249, 115, 22, 0.2);
- --modern-accent-border: rgba(249, 115, 22, 0.42);
-}
-
-/* Strip all legacy gradients and inset bevel shadows in modern mode */
-[data-theme="modern"] [class*="bg-gradient-to-b"],
-[data-theme="modern"] button[class*="from-"],
-[data-theme="modern"] header,
-[data-theme="modern"] footer {
- background-image: none !important;
-}
-
-[data-theme="modern"] [class*="shadow-[inset"],
-[data-theme="modern"] [class*="shadow-inner"] {
- box-shadow: none !important;
-}
-
-/* Base surface & typography for modern theme */
-[data-theme="modern"] body,
-[data-theme="modern"] #root,
-[data-theme="modern"] .app-root-container {
- background-color: var(--modern-bg-base) !important;
- color: #e5e7eb !important;
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Inter", "Helvetica Neue", Arial, sans-serif !important;
-}
-
-/* Primary dark panels, sidebars, and containers */
-[data-theme="modern"] .bg-\[\#1e1e1e\],
-[data-theme="modern"] .bg-\[\#1e2023\],
-[data-theme="modern"] .bg-\[\#252526\],
-[data-theme="modern"] .bg-\[\#222223\],
-[data-theme="modern"] .bg-\[\#222224\],
-[data-theme="modern"] .bg-\[\#222225\],
-[data-theme="modern"] .bg-\[\#252528\],
-[data-theme="modern"] .bg-\[\#3c3c3f\],
-[data-theme="modern"] .bg-\[\#444447\] {
- background-color: var(--modern-bg-surface) !important;
-}
-
-/* Elevated sub-surfaces and cards */
-[data-theme="modern"] .bg-\[\#1b1c1e\],
-[data-theme="modern"] .bg-\[\#1a1b1e\],
-[data-theme="modern"] .bg-\[\#161719\],
-[data-theme="modern"] .bg-\[\#141517\],
-[data-theme="modern"] .bg-\[\#141518\],
-[data-theme="modern"] .bg-\[\#18191b\],
-[data-theme="modern"] .bg-\[\#1c1d1f\],
-[data-theme="modern"] .bg-\[\#242426\],
-[data-theme="modern"] .bg-\[\#2a2a2a\],
-[data-theme="modern"] .bg-\[\#2a2a2d\],
-[data-theme="modern"] .bg-\[\#202226\],
-[data-theme="modern"] .bg-\[\#2c2c2f\],
-[data-theme="modern"] .bg-\[\#28282a\],
-[data-theme="modern"] .bg-\[\#2b2b2e\],
-[data-theme="modern"] .bg-\[\#333336\],
-[data-theme="modern"] .bg-\[\#37373a\],
-[data-theme="modern"] .bg-\[\#3a3a3d\],
-[data-theme="modern"] .bg-\[\#404043\],
-[data-theme="modern"] .bg-\[\#424245\],
-[data-theme="modern"] .bg-\[\#464649\],
-[data-theme="modern"] .bg-\[\#4a4a4d\],
-[data-theme="modern"] .bg-\[\#505053\],
-[data-theme="modern"] .bg-\[\#525255\],
-[data-theme="modern"] .bg-\[\#56565a\],
-[data-theme="modern"] .bg-\[\#58585c\] {
- background-color: var(--modern-bg-elevated) !important;
-}
-
-/* Hairline modern borders */
-[data-theme="modern"] [class*="border-\[\#"]:not([class*="bg-[#293d45]"]):not([class*="bg-[#383838]"]):not([class*="bg-[#37485e]"]):not([class*="bg-[#353535]"]):not([class*="bg-[#007acc]"]):not([class*="from-[#376590]"]):not([class*="border-[#5ce1e6]"]):not([class*="border-[#007acc]"]):not([class*="border-[#38bdf8]"]):not([class*="border-t-[#5ce1e6]"]):not([data-layer-id]) {
- border-color: var(--modern-border) !important;
-}
-
-/* Modern Header */
-[data-theme="modern"] header {
- background-color: var(--modern-bg-surface) !important;
- border-bottom: 1px solid var(--modern-border) !important;
- box-shadow: none !important;
-}
-
-/* Modern Document Tab Bar */
-[data-theme="modern"] div[class*="DocumentTabBar"],
-[data-theme="modern"] div[class*="no-scrollbar"][class*="h-8"] {
- background-color: var(--modern-bg-base) !important;
- border-bottom: 1px solid var(--modern-border) !important;
-}
-
-/* Sleek minimalist rounded buttons */
-[data-theme="modern"] button[class*="rounded"]:not([class*="rounded-full"]):not([class*="color-swatch"]) {
- border-radius: 6px !important;
- transition: all 0.15s cubic-bezier(0.16, 1, 0.3, 1) !important;
- box-shadow: none !important;
-}
-
-[data-theme="modern"] [class*="rounded-\[2px\]"],
-[data-theme="modern"] [class*="rounded-\[3px\]"],
-[data-theme="modern"] [class*="rounded-\[1px\]"],
-[data-theme="modern"] [class*="rounded-xs"],
-[data-theme="modern"] [class*="rounded-sm"] {
- border-radius: 6px !important;
-}
-
-[data-theme="modern"] button[class*="rounded-full"] {
- border-radius: 9999px !important;
-}
-
-/* Active buttons, tools, layers & selection cards themed with dynamic accent */
-[data-theme="modern"] button[class*="bg-\[\#293d45\]"],
-[data-theme="modern"] button[class*="bg-\[\#383838\]"],
-[data-theme="modern"] button[class*="bg-\[\#37485e\]"],
-[data-theme="modern"] button[class*="bg-\[\#007acc\]"],
-[data-theme="modern"] button[class*="bg-\[\#353535\]"],
-[data-theme="modern"] button[class*="from-\[\#376590\]"],
-[data-theme="modern"] div[class*="bg-\[\#007acc\]"],
-[data-theme="modern"] div[class*="bg-\[\#293d45\]"],
-[data-theme="modern"] div[class*="bg-\[\#37485e\]"],
-[data-theme="modern"] div[class*="bg-\[\#383838\]"],
-[data-theme="modern"] div[data-layer-id][class*="bg-\[\#383838\]"],
-[data-theme="modern"] div[class*="bg-\[\#353535\]"],
-[data-theme="modern"] [class*="from-\[\#376590\]"],
-[data-theme="modern"] .active-item {
- background-image: none !important;
- background-color: var(--modern-accent-subtle) !important;
- border-color: var(--modern-accent-border) !important;
- color: var(--modern-accent) !important;
- box-shadow: 0 0 10px var(--modern-accent-glow) !important;
-}
-
-[data-theme="modern"] button[class*="bg-\[\#293d45\]"] svg,
-[data-theme="modern"] button[class*="bg-\[\#007acc\]"] svg,
-[data-theme="modern"] button[class*="bg-\[\#383838\]"] svg,
-[data-theme="modern"] button[class*="from-\[\#376590\]"] svg {
- color: var(--modern-accent) !important;
- stroke: var(--modern-accent) !important;
-}
-
-/* Text, tab and border accent overrides */
-[data-theme="modern"] .text-\[\#5ce1e6\],
-[data-theme="modern"] .text-\[\#007acc\],
-[data-theme="modern"] .text-\[\#38bdf8\],
-[data-theme="modern"] [class*="text-[#5ce1e6]"],
-[data-theme="modern"] [class*="text-[#007acc]"],
-[data-theme="modern"] [class*="text-[#38bdf8]"] {
- color: var(--modern-accent) !important;
-}
-
-[data-theme="modern"] .border-\[\#5ce1e6\],
-[data-theme="modern"] .border-\[\#007acc\],
-[data-theme="modern"] .border-\[\#38bdf8\],
-[data-theme="modern"] [class*="border-[#5ce1e6]"],
-[data-theme="modern"] [class*="border-[#007acc]"],
-[data-theme="modern"] [class*="border-[#38bdf8]"] {
- border-color: var(--modern-accent-border) !important;
-}
-
-[data-theme="modern"] .border-t-\[\#5ce1e6\],
-[data-theme="modern"] [class*="border-t-[#5ce1e6]"] {
- border-top-color: var(--modern-accent) !important;
-}
-
-[data-theme="modern"] [class*="ring-[#5ce1e6]"],
-[data-theme="modern"] [class*="ring-[#007acc]"],
-[data-theme="modern"] [class*="ring-[#38bdf8]"] {
- --tw-ring-color: var(--modern-accent) !important;
- box-shadow: 0 0 0 1px var(--modern-accent) !important;
-}
-
-[data-theme="modern"] input[type="checkbox"],
-[data-theme="modern"] input[type="range"] {
- accent-color: var(--modern-accent) !important;
-}
-
-/* Modern inputs, number boxes & textareas */
-[data-theme="modern"] input[type="text"],
-[data-theme="modern"] input[type="number"],
-[data-theme="modern"] select,
-[data-theme="modern"] textarea {
- background-color: var(--modern-bg-input) !important;
- border: 1px solid var(--modern-border) !important;
- box-shadow: none !important;
- color: #f3f4f6 !important;
- border-radius: 6px !important;
- transition: border-color 0.15s ease, box-shadow 0.15s ease !important;
-}
-
-[data-theme="modern"] input[type="text"]:focus,
-[data-theme="modern"] input[type="number"]:focus,
-[data-theme="modern"] select:focus,
-[data-theme="modern"] textarea:focus {
- border-color: var(--modern-accent) !important;
- box-shadow: 0 0 0 2px var(--modern-accent-subtle) !important;
- outline: none !important;
-}
-
-/* Modern smooth pill range sliders */
-[data-theme="modern"] input[type="range"] {
- height: 18px;
-}
-
-[data-theme="modern"] input[type="range"]::-webkit-slider-runnable-track {
- height: 3px;
- background: rgba(255, 255, 255, 0.14);
+ height: 10px;
+ background: var(--accent);
border: none;
border-radius: 9999px;
- box-shadow: none;
-}
-
-[data-theme="modern"] input[type="range"]::-moz-range-track {
- height: 3px;
- background: rgba(255, 255, 255, 0.14);
- border: none;
- border-radius: 9999px;
- box-shadow: none;
-}
-
-[data-theme="modern"] input[type="range"]::-webkit-slider-thumb {
- width: 12px;
- height: 12px;
- background: var(--modern-accent);
- border: 2px solid #ffffff;
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
- border-radius: 9999px;
- margin-top: -4.5px;
- transition: transform 0.12s ease, box-shadow 0.12s ease;
-}
-
-[data-theme="modern"] input[type="range"]:hover::-webkit-slider-thumb {
- transform: scale(1.2);
- box-shadow: 0 0 8px var(--modern-accent-glow);
-}
-
-[data-theme="modern"] input[type="range"]:active::-webkit-slider-thumb {
- transform: scale(1.05);
-}
-
-[data-theme="modern"] input[type="range"]::-moz-range-thumb {
- width: 12px;
- height: 12px;
- background: var(--modern-accent);
- border: 2px solid #ffffff;
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
- border-radius: 9999px;
- transition: transform 0.12s ease, box-shadow 0.12s ease;
+ transition: transform 0.1s ease;
}
-[data-theme="modern"] input[type="range"]:hover::-moz-range-thumb {
- transform: scale(1.2);
- box-shadow: 0 0 8px var(--modern-accent-glow);
-}
-
-/* Modern minimalist scrollbars */
-[data-theme="modern"] ::-webkit-scrollbar {
- width: 4px;
- height: 4px;
+input[type="range"]:hover::-moz-range-thumb {
+ transform: scale(1.18);
}
-[data-theme="modern"] ::-webkit-scrollbar-track {
- background: transparent;
+input[type="checkbox"] {
+ accent-color: var(--accent);
}
-[data-theme="modern"] ::-webkit-scrollbar-thumb {
- background: rgba(255, 255, 255, 0.14);
- border-radius: 9999px;
+/* Minimalist inputs & selects */
+input[type="text"],
+input[type="number"],
+select,
+textarea {
+ background-color: #161616;
+ color: #e5e5e5;
border: none;
+ border-radius: 4px;
+ outline: none;
}
-[data-theme="modern"] ::-webkit-scrollbar-thumb:hover {
- background: rgba(255, 255, 255, 0.28);
-}
-
-/* Modern Status Bar */
-[data-theme="modern"] footer,
-[data-theme="modern"] footer[class*="StatusBar"] {
- background-color: var(--modern-bg-base) !important;
- border-top: 1px solid var(--modern-border) !important;
- box-shadow: none !important;
-}
-
-[data-theme="modern"] footer div[class*="bg-gradient-to-r from-emerald-500 to-cyan-400"] {
- background-image: none !important;
- background-color: var(--modern-accent) !important;
-}
-
-/* Modern canvas viewport & paper elevation */
-[data-theme="modern"] canvas.canvas-paper {
- box-shadow: 0 20px 50px -10px rgba(0, 0, 0, 0.8), 0 0 0 1px rgba(255, 255, 255, 0.06);
-}
-
-[data-theme="modern"] .canvas-viewport,
-[data-theme="modern"] main[class*="bg-\[\#282828\]"] {
- background-color: var(--modern-bg-base) !important;
-}
-
-/* Modern popup menus and dropdowns */
-[data-theme="modern"] div[role="menu"] {
- background-color: var(--modern-bg-elevated) !important;
- border: 1px solid var(--modern-border) !important;
- border-radius: 8px !important;
- box-shadow: 0 14px 40px rgba(0, 0, 0, 0.75) !important;
- padding: 4px !important;
-}
-
-[data-theme="modern"] div[role="menu"] button[role="menuitem"] {
- border-radius: 4px !important;
- padding: 5px 8px !important;
-}
-
-[data-theme="modern"] div[role="menu"] button[role="menuitem"]:hover:not([disabled]),
-[data-theme="modern"] div[role="menu"] button[class*="bg-\[\#04395e\]"] {
- background-color: var(--modern-accent-subtle) !important;
- color: var(--modern-accent) !important;
-}
-
-/* Modern modal dialogs */
-[data-theme="modern"] div[class*="shadow-2xl"][class*="border"],
-[data-theme="modern"] div[class*="shadow-[0_8px_24px"] {
- background-color: var(--modern-bg-surface) !important;
- border: 1px solid var(--modern-border) !important;
- border-radius: 14px !important;
- box-shadow: 0 24px 64px -12px rgba(0, 0, 0, 0.9) !important;
- overflow: hidden;
-}
-
-[data-theme="modern"] div[class*="rounded-xl"] {
- border-radius: 12px !important;
-}
-
-[data-theme="modern"] div[class*="rounded-2xl"] {
- border-radius: 16px !important;
-}
-
-[data-theme="modern"] div[class*="rounded-lg"] {
- border-radius: 10px !important;
-}
-
-[data-theme="modern"] .backdrop-blur-xs,
-[data-theme="modern"] .backdrop-blur-sm,
-[data-theme="modern"] .backdrop-blur-md {
- backdrop-filter: blur(12px) !important;
- -webkit-backdrop-filter: blur(12px) !important;
+input[type="text"]:focus,
+input[type="number"]:focus,
+select:focus,
+textarea:focus {
+ box-shadow: 0 0 0 1px var(--accent-border);
}
-
-
-
diff --git a/src/services/bake3DService.ts b/src/services/bake3DService.ts
index 1a6280b..45ad429 100644
--- a/src/services/bake3DService.ts
+++ b/src/services/bake3DService.ts
@@ -60,13 +60,21 @@ export function disposeThreeResources(
}
const line = obj as THREE.Line;
- if (line.isLine && line.geometry) {
- line.geometry.dispose();
+ if (line.isLine) {
+ if (line.geometry) line.geometry.dispose();
+ if (line.material) {
+ if (Array.isArray(line.material)) line.material.forEach((m) => disposeMaterialTextures(m));
+ else disposeMaterialTextures(line.material);
+ }
}
const points = obj as THREE.Points;
- if (points.isPoints && points.geometry) {
- points.geometry.dispose();
+ if (points.isPoints) {
+ if (points.geometry) points.geometry.dispose();
+ if (points.material) {
+ if (Array.isArray(points.material)) points.material.forEach((m) => disposeMaterialTextures(m));
+ else disposeMaterialTextures(points.material);
+ }
}
});
@@ -76,6 +84,11 @@ export function disposeThreeResources(
}
if (renderer) {
+ try {
+ if (typeof renderer.forceContextLoss === 'function') {
+ renderer.forceContextLoss();
+ }
+ } catch {}
renderer.dispose();
}
@@ -669,7 +682,7 @@ export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<Bak
const pIdx = i * 4;
const alpha = diffData[pIdx + 3];
// Skip background pixels and lineart contours
- if (alpha === 0 || (lineData32[i] & 0xff000000) !== 0) continue;
+ if (alpha === 0 || (lineData32[i] & SOLID_BLACK_U32) !== 0) continue;
const r = diffData[pIdx];
const g = diffData[pIdx + 1];
@@ -753,6 +766,7 @@ export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<Bak
};
// 8. Immediate Cleanup of Offscreen WebGL Resources
+ normalMat.dispose();
quadGeo.dispose();
sobelMaterial.dispose();
displayMaterial.dispose();
@@ -770,6 +784,11 @@ export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<Bak
disposeThreeResources(null, activeRenderer);
}
} else {
+ try {
+ if (typeof offscreenRenderer.forceContextLoss === 'function') {
+ offscreenRenderer.forceContextLoss();
+ }
+ } catch {}
offscreenRenderer.dispose();
}
@@ -794,11 +813,11 @@ export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<Bak
if (onBroadcastLayer) {
onBroadcastLayer(folderLayer, '');
onBroadcastLayer(lineLayer, lineDataUrl);
- toneLayers.forEach((l, i) => onBroadcastLayer(l, toneCanvases[i].toDataURL('image/png')));
+ toneLayersStackOrder.forEach((l, i) => onBroadcastLayer(l, toneCanvasesStackOrder[i].toDataURL('image/png')));
} else if (multiplayerService.isConnected()) {
multiplayerService.sendLayerAdd(folderLayer);
multiplayerService.sendLayerAdd(lineLayer, lineDataUrl);
- toneLayers.forEach((l, i) => multiplayerService.sendLayerAdd(l, toneCanvases[i].toDataURL('image/png')));
+ toneLayersStackOrder.forEach((l, i) => multiplayerService.sendLayerAdd(l, toneCanvasesStackOrder[i].toDataURL('image/png')));
}
return {
diff --git a/src/services/multiplayerService.ts b/src/services/multiplayerService.ts
index 4cb6316..e1894f0 100644
--- a/src/services/multiplayerService.ts
+++ b/src/services/multiplayerService.ts
@@ -26,6 +26,53 @@ export const CODE_TILE_DELTA = 0x04;
export const CODE_CURSOR_MOVE = 0x05;
export const CODE_SELECTIVE_UNDO = 0x06;
+const MAX_BINARY_PACKET_BYTES = 16 * 1024 * 1024;
+const MAX_JSON_MESSAGE_CHARS = 8 * 1024 * 1024;
+const MAX_STROKE_CHUNK_POINTS = 4096;
+
+function sanitizeRemoteBrushSettings(raw: unknown): BrushSettings | null {
+ if (!raw || typeof raw !== 'object') return null;
+ const bs = raw as BrushSettings;
+ const size = Number.isFinite(bs.size) ? Math.max(0.5, Math.min(2000, bs.size)) : 8;
+ const opacity = Number.isFinite(bs.opacity) ? Math.max(0, Math.min(1, bs.opacity)) : 1;
+ const flow = Number.isFinite(bs.flow) ? Math.max(0.01, Math.min(1, bs.flow)) : 1;
+ const spacing = Number.isFinite(bs.spacing) ? Math.max(0.01, Math.min(2, bs.spacing)) : 0.1;
+ const dynamics = bs.dynamics
+ ? {
+ ...bs.dynamics,
+ count: Number.isFinite(bs.dynamics.count)
+ ? Math.max(1, Math.min(16, Math.round(bs.dynamics.count)))
+ : 1,
+ }
+ : undefined;
+ const spray = bs.spray
+ ? {
+ ...bs.spray,
+ density: Number.isFinite(bs.spray.density)
+ ? Math.max(1, Math.min(64, Math.round(bs.spray.density)))
+ : 12,
+ size: Number.isFinite(bs.spray.size)
+ ? Math.max(1, Math.min(200, bs.spray.size))
+ : 3,
+ }
+ : undefined;
+ return {
+ ...bs,
+ size,
+ opacity,
+ flow,
+ spacing,
+ dynamics,
+ spray,
+ };
+}
+
+function isValidRemotePoint(pt: unknown): pt is Point {
+ if (!pt || typeof pt !== 'object') return false;
+ const p = pt as Point;
+ return Number.isFinite(p.x) && Number.isFinite(p.y);
+}
+
class MultiplayerService {
private ws: WebSocket | null = null;
private messageHandlers: Set<MessageHandler> = new Set();
@@ -89,9 +136,12 @@ class MultiplayerService {
if (parsed) {
this.notifyHandlers(parsed);
}
- } else {
- const data: MultiplayerMessage = JSON.parse(event.data);
- this.notifyHandlers(data);
+ } else if (typeof event.data === 'string') {
+ if (event.data.length > MAX_JSON_MESSAGE_CHARS) return;
+ const data = JSON.parse(event.data) as MultiplayerMessage;
+ if (data && typeof data === 'object' && typeof data.type === 'string') {
+ this.notifyHandlers(data);
+ }
}
} catch (err) {
console.error('[Multiplayer] Failed to parse message:', err, event.data);
@@ -168,7 +218,7 @@ class MultiplayerService {
// --- Binary Packet Encoding & Decoding ---
private decodeBinaryPacket(buf: ArrayBuffer): MultiplayerMessage | null {
- if (buf.byteLength < 11) return null;
+ if (buf.byteLength < 11 || buf.byteLength > MAX_BINARY_PACKET_BYTES) return null;
const view = new DataView(buf);
// Verify magic
@@ -181,43 +231,78 @@ class MultiplayerService {
this.updateLamport(lamport);
const payloadLen = view.getUint32(7, true);
+ if (payloadLen > MAX_BINARY_PACKET_BYTES || 11 + payloadLen > buf.byteLength) return null;
const payloadBytes = new Uint8Array(buf, 11, payloadLen);
const decoder = new TextDecoder();
+ const TOOL_TYPES_LIST: ToolType[] = [
+ 'brush',
+ 'eraser',
+ 'pipette',
+ 'transform',
+ 'select-rect',
+ 'select-lasso',
+ 'select-wand',
+ 'select-pen',
+ 'select-eraser',
+ 'fill',
+ 'text',
+ 'frame',
+ 'balloon',
+ 'vector-edit',
+ 'liquify',
+ ];
+
switch (code) {
case CODE_STROKE_START: {
const jsonStr = decoder.decode(payloadBytes);
const data = JSON.parse(jsonStr);
+ const safeSettings = sanitizeRemoteBrushSettings(data?.brushSettings);
+ if (!safeSettings || !isValidRemotePoint(data?.startPoint)) return null;
return {
type: 'STROKE_START',
- strokeId: data.strokeId,
+ strokeId: String(data.strokeId || ''),
peerId: data.peerId,
- peerName: data.peerName,
- peerColor: data.peerColor,
- layerId: data.layerId,
- brushSettings: data.brushSettings,
- tool: data.tool,
- startPoint: data.startPoint,
+ peerName: String(data.peerName || 'Peer').slice(0, 64),
+ peerColor: String(data.peerColor || '#38bdf8').slice(0, 32),
+ layerId: String(data.layerId || ''),
+ brushSettings: safeSettings,
+ tool: TOOL_TYPES_LIST.includes(data.tool) ? data.tool : 'brush',
+ startPoint: {
+ ...data.startPoint,
+ pressure: Number.isFinite(data.startPoint.pressure)
+ ? Math.max(0, Math.min(1, data.startPoint.pressure))
+ : 0.5,
+ width: Number.isFinite(data.startPoint.width)
+ ? Math.max(0.1, Math.min(2000, data.startPoint.width))
+ : safeSettings.size,
+ },
} as StrokeStartMessage;
}
case CODE_STROKE_CHUNK: {
// Format: [strokeIdLen: uint16, strokeIdStr, peerIdLen: uint16, peerIdStr, pointCount: uint16, points...]
let offset = 0;
+ if (payloadBytes.byteLength < 6) return null;
const pView = new DataView(payloadBytes.buffer, payloadBytes.byteOffset, payloadBytes.byteLength);
const sIdLen = pView.getUint16(offset, true);
offset += 2;
+ if (sIdLen > 256 || offset + sIdLen + 4 > payloadBytes.byteLength) return null;
const strokeId = decoder.decode(payloadBytes.subarray(offset, offset + sIdLen));
offset += sIdLen;
const pIdLen = pView.getUint16(offset, true);
offset += 2;
+ if (pIdLen > 256 || offset + pIdLen + 2 > payloadBytes.byteLength) return null;
const peerId = decoder.decode(payloadBytes.subarray(offset, offset + pIdLen));
offset += pIdLen;
const pointCount = pView.getUint16(offset, true);
offset += 2;
+ if (pointCount > MAX_STROKE_CHUNK_POINTS || offset + pointCount * 16 > payloadBytes.byteLength) {
+ return null;
+ }
const points: Point[] = [];
for (let i = 0; i < pointCount; i++) {
@@ -226,9 +311,17 @@ class MultiplayerService {
const pressure = pView.getFloat32(offset + 8, true);
const width = pView.getFloat32(offset + 12, true);
offset += 16;
- points.push({ x, y, pressure, width });
+ if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
+ points.push({
+ x,
+ y,
+ pressure: Number.isFinite(pressure) ? Math.max(0, Math.min(1, pressure)) : 0.5,
+ width: Number.isFinite(width) ? Math.max(0.1, Math.min(2000, width)) : 1,
+ });
}
+ if (points.length === 0) return null;
+
return {
type: 'STROKE_CHUNK',
strokeId,
@@ -247,15 +340,18 @@ class MultiplayerService {
layerId: data.layerId,
endPoint: data.endPoint,
dirtyRect: data.dirtyRect,
+ vectorStroke: data.vectorStroke,
} as StrokeFinishMessage;
}
case CODE_TILE_DELTA: {
// Format: [layerIdLen: uint16, layerIdStr, serializedTileBuffer...]
let offset = 0;
+ if (payloadBytes.byteLength < 2) return null;
const pView = new DataView(payloadBytes.buffer, payloadBytes.byteOffset, payloadBytes.byteLength);
const layerIdLen = pView.getUint16(offset, true);
offset += 2;
+ if (offset + layerIdLen > payloadBytes.byteLength) return null;
const layerId = decoder.decode(payloadBytes.subarray(offset, offset + layerIdLen));
offset += layerIdLen;
@@ -274,18 +370,21 @@ class MultiplayerService {
}
case CODE_CURSOR_MOVE: {
+ if (payloadBytes.byteLength < 12) return null;
const pView = new DataView(payloadBytes.buffer, payloadBytes.byteOffset, payloadBytes.byteLength);
let offset = 0;
const pIdLen = pView.getUint16(offset, true);
offset += 2;
+ if (offset + pIdLen + 10 > payloadBytes.byteLength) return null;
const peerId = decoder.decode(payloadBytes.subarray(offset, offset + pIdLen));
offset += pIdLen;
const x = pView.getFloat32(offset, true);
const y = pView.getFloat32(offset + 4, true);
+ if (!Number.isFinite(x) || !Number.isFinite(y)) return null;
const isDrawing = pView.getUint8(offset + 8) === 1;
const toolCode = pView.getUint8(offset + 9);
- const tool: ToolType = toolCode === 1 ? 'eraser' : 'brush';
+ const tool: ToolType = TOOL_TYPES_LIST[toolCode] || 'brush';
return {
type: 'CURSOR_MOVE',
@@ -352,6 +451,14 @@ class MultiplayerService {
public sendStrokeChunk(strokeId: string, points: Point[]) {
if (!this.isConnected() || !this.currentPeer || points.length === 0) return;
+ const MAX_POINTS_PER_PACKET = 4096;
+ if (points.length > MAX_POINTS_PER_PACKET) {
+ for (let start = 0; start < points.length; start += MAX_POINTS_PER_PACKET) {
+ this.sendStrokeChunk(strokeId, points.slice(start, start + MAX_POINTS_PER_PACKET));
+ }
+ return;
+ }
+
const encoder = new TextEncoder();
const strokeIdBytes = encoder.encode(strokeId);
const peerIdBytes = encoder.encode(String(this.currentPeer.id));
@@ -522,10 +629,28 @@ class MultiplayerService {
packet.set(peerIdBytes, offset);
offset += peerIdBytes.length;
+ const TOOL_TYPES_LIST: ToolType[] = [
+ 'brush',
+ 'eraser',
+ 'pipette',
+ 'transform',
+ 'select-rect',
+ 'select-lasso',
+ 'select-wand',
+ 'select-pen',
+ 'select-eraser',
+ 'fill',
+ 'text',
+ 'frame',
+ 'balloon',
+ 'vector-edit',
+ 'liquify',
+ ];
+ const toolIdx = Math.max(0, TOOL_TYPES_LIST.indexOf(this.pendingCursor.tool));
view.setFloat32(offset, this.pendingCursor.x, true);
view.setFloat32(offset + 4, this.pendingCursor.y, true);
view.setUint8(offset + 8, this.pendingCursor.isDrawing ? 1 : 0);
- view.setUint8(offset + 9, this.pendingCursor.tool === 'eraser' ? 1 : 0);
+ view.setUint8(offset + 9, toolIdx);
this.sendBinary(packet);
this.pendingCursor = null;
diff --git a/src/services/recoveryService.ts b/src/services/recoveryService.ts
new file mode 100644
index 0000000..a31d5e6
--- /dev/null
+++ b/src/services/recoveryService.ts
@@ -0,0 +1,620 @@
+/**
+ * Production-Grade Fault-Tolerant Crash Recovery & Auto-Save System (WAL Architecture)
+ *
+ * Implements Write-Ahead Logging (WAL) with zero latency impact on stylus inking (120-240 Hz).
+ * Provides atomic checkpoints, binary framing headers, CRC32 checksums, and rapid crash recovery.
+ */
+
+import { deflateSync, inflateSync } from 'fflate';
+import {
+ TileDelta,
+ VectorStroke,
+ LayerItem,
+ CanvasColorMode,
+} from '../types/editor';
+import {
+ globalTileGrid,
+ SparseTileGrid,
+ serializeTileDeltas,
+ deserializeTileDeltas,
+ serializeSparseTileGrid,
+ deserializeSparseTileGrid,
+} from '../utils/tileEngine';
+
+export const WAL_MAGIC_BYTES = new Uint8Array([0x49, 0x4e, 0x4b, 0x57]); // 'INKW'
+export const WAL_ENTRY_STROKE_TILE_DELTA = 1;
+export const WAL_ENTRY_VECTOR_STROKE = 2;
+export const WAL_ENTRY_LAYER_MUTATION = 3;
+
+export const CHECKPOINT_STROKE_THRESHOLD = 25; // Trigger checkpoint after 25-30 completed strokes
+export const CHECKPOINT_IDLE_TIMEOUT_MS = 30000; // Trigger checkpoint after 30 seconds of idle
+
+// IEEE 802.3 standard CRC-32 lookup table
+const CRC32_TABLE = new Uint32Array(256);
+for (let i = 0; i < 256; i++) {
+ let c = i;
+ for (let k = 0; k < 8; k++) {
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ }
+ CRC32_TABLE[i] = c >>> 0;
+}
+
+/**
+ * Computes standard IEEE 802.3 CRC32 checksum for arbitrary byte arrays.
+ */
+export function computeCrc32(data: Uint8Array): number {
+ let crc = 0xffffffff;
+ for (let i = 0; i < data.length; i++) {
+ crc = CRC32_TABLE[(crc ^ data[i]) & 0xff] ^ (crc >>> 8);
+ }
+ return (crc ^ 0xffffffff) >>> 0;
+}
+
+export interface WalFrame {
+ entryType: number;
+ payload: Uint8Array;
+}
+
+/**
+ * Packs a WAL entry into atomic framing header:
+ * [Magic: 4 bytes (0x494E4B57 "INKW")][EntryType: 1 byte][PayloadLength: 4 bytes (u32 LE)][CRC32: 4 bytes][Payload]
+ */
+export function formatWalFrame(entryType: number, payload: Uint8Array): Uint8Array {
+ const frame = new Uint8Array(13 + payload.length);
+ const view = new DataView(frame.buffer, frame.byteOffset, frame.byteLength);
+
+ frame[0] = 0x49; // 'I'
+ frame[1] = 0x4e; // 'N'
+ frame[2] = 0x4b; // 'K'
+ frame[3] = 0x57; // 'W'
+
+ frame[4] = entryType;
+ view.setUint32(5, payload.length, true);
+
+ const crc = computeCrc32(payload);
+ view.setUint32(9, crc, true);
+
+ frame.set(payload, 13);
+ return frame;
+}
+
+/**
+ * Parses all valid binary chunks from a WAL stream, safely discarding incomplete or corrupted trailing bytes.
+ */
+export function parseWalFrames(buffer: Uint8Array): {
+ validFrames: WalFrame[];
+ corruptedTail: boolean;
+} {
+ const validFrames: WalFrame[] = [];
+ let offset = 0;
+ const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
+
+ while (offset + 13 <= buffer.length) {
+ if (
+ buffer[offset] !== 0x49 ||
+ buffer[offset + 1] !== 0x4e ||
+ buffer[offset + 2] !== 0x4b ||
+ buffer[offset + 3] !== 0x57
+ ) {
+ return { validFrames, corruptedTail: true };
+ }
+
+ const entryType = buffer[offset + 4];
+ const payloadLen = view.getUint32(offset + 5, true);
+ const expectedCrc = view.getUint32(offset + 9, true);
+
+ if (offset + 13 + payloadLen > buffer.length) {
+ // Incomplete trailing chunk from sudden crash mid-write
+ return { validFrames, corruptedTail: true };
+ }
+
+ const payload = buffer.subarray(offset + 13, offset + 13 + payloadLen);
+ const actualCrc = computeCrc32(payload);
+ if (actualCrc !== expectedCrc) {
+ // CRC32 mismatch from corrupted tail
+ return { validFrames, corruptedTail: true };
+ }
+
+ validFrames.push({ entryType, payload: new Uint8Array(payload) });
+ offset += 13 + payloadLen;
+ }
+
+ const hasRemainingBytes = offset < buffer.length;
+ return { validFrames, corruptedTail: hasRemainingBytes };
+}
+
+export interface DocumentManifest {
+ sessionId: string;
+ documentName: string;
+ width: number;
+ height: number;
+ dpi: number;
+ colorMode: CanvasColorMode;
+ layers: LayerItem[];
+ activeLayerId: string;
+ timestamp: number;
+}
+
+export interface CrashedSessionInfo {
+ session_id: string;
+ timestamp: number;
+ pid: number;
+ manifest_json?: string | null;
+ has_thumbnail: boolean;
+ thumbnail_data_url?: string | null;
+}
+
+export interface WalEntryData {
+ entry_type: number;
+ payload: number[] | Uint8Array;
+}
+
+export interface RecoveryReplayData {
+ session_id: string;
+ manifest_json: string;
+ base_snapshot?: number[] | Uint8Array | null;
+ wal_entries: WalEntryData[];
+}
+
+export function isTauriEnvironment(): boolean {
+ if (typeof window === 'undefined') return false;
+ return Boolean(
+ (window as any).__TAURI_INTERNALS__ ||
+ (window as any).__TAURI__ ||
+ (window as any).isTauri
+ );
+}
+
+class RecoveryService {
+ private currentSessionId: string | null = null;
+ private strokesSinceCheckpoint: number = 0;
+ private idleCheckpointTimer: any = null;
+ private layerMutationDebounceTimer: ReturnType<typeof setTimeout> | null = null;
+ private isCheckpointing: boolean = false;
+
+ private stripLayerTransientFields(layers?: LayerItem[]): LayerItem[] {
+ if (!layers) return [];
+ return layers.map(({ maskCanvas: _mc, maskThumbnailUrl: _mt, ...rest }) => ({
+ ...rest,
+ thumbnailUrl: '',
+ }));
+ }
+
+ private manifestProvider: (() => DocumentManifest | null) | null = null;
+ private thumbnailProvider: (() => Promise<Uint8Array | null>) | null = null;
+
+ public getCurrentSessionId(): string | null {
+ return this.currentSessionId;
+ }
+
+ /**
+ * Initializes or binds an active recovery session for a document tab.
+ */
+ public async initSession(
+ sessionId: string,
+ manifestProvider: () => DocumentManifest | null,
+ thumbnailProvider?: () => Promise<Uint8Array | null>
+ ): Promise<void> {
+ const isSameSession = this.currentSessionId === sessionId;
+ this.currentSessionId = sessionId;
+ this.manifestProvider = manifestProvider;
+ if (thumbnailProvider) {
+ this.thumbnailProvider = thumbnailProvider;
+ }
+
+ if (isSameSession) {
+ return;
+ }
+
+ this.strokesSinceCheckpoint = 0;
+
+ if (this.idleCheckpointTimer) {
+ clearTimeout(this.idleCheckpointTimer);
+ this.idleCheckpointTimer = null;
+ }
+
+ if (!isTauriEnvironment()) return;
+
+ try {
+ const rawManifest = manifestProvider();
+ const safeManifest = rawManifest
+ ? {
+ ...rawManifest,
+ layers: this.stripLayerTransientFields(rawManifest.layers),
+ }
+ : {};
+ const manifestJson = JSON.stringify(safeManifest);
+ const { invoke } = await import('@tauri-apps/api/core');
+ await invoke('recovery_init_session', {
+ sessionId,
+ manifestJson,
+ });
+ } catch (err) {
+ console.warn('[RecoveryService] Failed to init session in Rust backend:', err);
+ }
+ }
+
+ /**
+ * Asynchronously appends a completed stroke's tile deltas or vector deltas to journal.wal without blocking UI.
+ */
+ public logStrokeDelta(
+ sessionId: string,
+ tileDeltas?: TileDelta[],
+ vectorDelta?: { before: VectorStroke[]; after: VectorStroke[] },
+ layerId?: string
+ ): void {
+ const activeId = sessionId || this.currentSessionId;
+ if (!activeId) return;
+
+ // 1. Dispatch tile deltas
+ if (tileDeltas && tileDeltas.length > 0) {
+ try {
+ const serialized = serializeTileDeltas(tileDeltas);
+ const compressed = deflateSync(serialized, { level: 1 }); // Ultra-fast compression (<0.3ms)
+
+ if (isTauriEnvironment()) {
+ import('@tauri-apps/api/core').then(({ invoke }) => {
+ void invoke('recovery_append_wal_entry', {
+ sessionId: activeId,
+ entryType: WAL_ENTRY_STROKE_TILE_DELTA,
+ payload: compressed,
+ }).catch((err) => {
+ console.warn('[RecoveryService] Non-blocking WAL tile append error:', err);
+ });
+ });
+ }
+ } catch (err) {
+ console.warn('[RecoveryService] Error serializing stroke tile delta:', err);
+ }
+ }
+
+ // 2. Dispatch vector stroke deltas
+ if (vectorDelta && vectorDelta.after && vectorDelta.after.length > 0) {
+ try {
+ const payloadData = {
+ layerId,
+ strokes: vectorDelta.after,
+ };
+ const jsonBytes = new TextEncoder().encode(JSON.stringify(payloadData));
+ const compressed = deflateSync(jsonBytes, { level: 1 });
+
+ if (isTauriEnvironment()) {
+ import('@tauri-apps/api/core').then(({ invoke }) => {
+ void invoke('recovery_append_wal_entry', {
+ sessionId: activeId,
+ entryType: WAL_ENTRY_VECTOR_STROKE,
+ payload: compressed,
+ }).catch((err) => {
+ console.warn('[RecoveryService] Non-blocking WAL vector append error:', err);
+ });
+ });
+ }
+ } catch (err) {
+ console.warn('[RecoveryService] Error serializing vector stroke delta:', err);
+ }
+ }
+
+ // Increment checkpoint stroke counter
+ this.strokesSinceCheckpoint++;
+
+ // Check Checkpoint Policy: 25-30 completed strokes
+ if (this.strokesSinceCheckpoint >= CHECKPOINT_STROKE_THRESHOLD) {
+ void this.triggerCheckpoint(activeId);
+ } else {
+ // Schedule 30-second idle timer
+ this.resetIdleCheckpointTimer(activeId);
+ }
+ }
+
+ /**
+ * Logs layer structure changes (add, delete, reorder, visibility, opacity, blendMode).
+ */
+ public logLayerMutation(
+ sessionId: string,
+ mutationType: string,
+ layers: LayerItem[],
+ activeLayerId?: string
+ ): void {
+ const activeId = sessionId || this.currentSessionId;
+ if (!activeId) return;
+
+ const flushMutation = () => {
+ try {
+ const payloadData = {
+ mutationType,
+ layers: this.stripLayerTransientFields(layers),
+ activeLayerId,
+ timestamp: Date.now(),
+ };
+ const jsonBytes = new TextEncoder().encode(JSON.stringify(payloadData));
+ const compressed = deflateSync(jsonBytes, { level: 1 });
+
+ if (isTauriEnvironment()) {
+ import('@tauri-apps/api/core').then(({ invoke }) => {
+ void invoke('recovery_append_wal_entry', {
+ sessionId: activeId,
+ entryType: WAL_ENTRY_LAYER_MUTATION,
+ payload: compressed,
+ }).catch((err) => {
+ console.warn('[RecoveryService] Non-blocking WAL layer mutation append error:', err);
+ });
+ });
+ }
+ } catch (err) {
+ console.warn('[RecoveryService] Error logging layer mutation:', err);
+ }
+ };
+
+ const isContinuous =
+ mutationType === 'opacity' ||
+ mutationType === 'set-opacity' ||
+ mutationType === 'tone' ||
+ mutationType === 'layer-color';
+
+ if (isContinuous) {
+ if (this.layerMutationDebounceTimer) {
+ clearTimeout(this.layerMutationDebounceTimer);
+ }
+ this.layerMutationDebounceTimer = setTimeout(() => {
+ this.layerMutationDebounceTimer = null;
+ flushMutation();
+ }, 250);
+ } else {
+ if (this.layerMutationDebounceTimer) {
+ clearTimeout(this.layerMutationDebounceTimer);
+ this.layerMutationDebounceTimer = null;
+ }
+ flushMutation();
+ }
+
+ this.resetIdleCheckpointTimer(activeId);
+ }
+
+ private resetIdleCheckpointTimer(sessionId: string): void {
+ if (this.idleCheckpointTimer) {
+ clearTimeout(this.idleCheckpointTimer);
+ }
+ this.idleCheckpointTimer = setTimeout(() => {
+ this.idleCheckpointTimer = null;
+ void this.triggerCheckpoint(sessionId);
+ }, CHECKPOINT_IDLE_TIMEOUT_MS);
+ }
+
+ /**
+ * Executes a full background checkpoint:
+ * 1. Compresses full active SparseTileGrid into baseline snapshot.
+ * 2. Atomically overwrites base_snapshot.bin.
+ * 3. Truncates journal.wal to zero bytes.
+ * 4. Updates manifest.json & thumbnail.png.
+ */
+ public async triggerCheckpoint(sessionId: string): Promise<void> {
+ if (this.isCheckpointing) return;
+ const activeId = sessionId || this.currentSessionId;
+ if (!activeId) return;
+
+ this.isCheckpointing = true;
+ if (this.idleCheckpointTimer) {
+ clearTimeout(this.idleCheckpointTimer);
+ this.idleCheckpointTimer = null;
+ }
+
+ try {
+ // 1. Snapshot SparseTileGrid
+ const rawSnapshot = serializeSparseTileGrid(globalTileGrid);
+ const compressedSnapshot = deflateSync(rawSnapshot, { level: 4 });
+
+ // 2. Manifest JSON (strip DOM canvas elements before serializing)
+ const rawManifest = this.manifestProvider?.() || null;
+ const safeManifest = rawManifest
+ ? {
+ ...rawManifest,
+ layers: this.stripLayerTransientFields(rawManifest.layers),
+ }
+ : {};
+ const manifestJson = JSON.stringify(safeManifest);
+
+ // 3. Thumbnail PNG
+ let thumbnailPng: Uint8Array = new Uint8Array(0);
+ if (this.thumbnailProvider) {
+ try {
+ const t = await this.thumbnailProvider();
+ if (t && t.length > 0) thumbnailPng = new Uint8Array(t);
+ } catch (_) {}
+ }
+
+ if (isTauriEnvironment()) {
+ const { invoke } = await import('@tauri-apps/api/core');
+ await invoke('recovery_checkpoint', {
+ sessionId: activeId,
+ baseSnapshot: compressedSnapshot,
+ manifestJson,
+ thumbnailPng,
+ });
+ }
+
+ this.strokesSinceCheckpoint = 0;
+ } catch (err) {
+ console.warn('[RecoveryService] Checkpoint failed:', err);
+ } finally {
+ this.isCheckpointing = false;
+ }
+ }
+
+ /**
+ * Called upon clean document save (Ctrl+S / Save As) to remove recovery session lock and folder.
+ */
+ public async markCleanSaved(sessionId: string): Promise<void> {
+ const activeId = sessionId || this.currentSessionId;
+ if (!activeId) return;
+
+ if (this.idleCheckpointTimer) {
+ clearTimeout(this.idleCheckpointTimer);
+ this.idleCheckpointTimer = null;
+ }
+ this.strokesSinceCheckpoint = 0;
+
+ if (isTauriEnvironment()) {
+ try {
+ const { invoke } = await import('@tauri-apps/api/core');
+ await invoke('recovery_close_session', { sessionId: activeId });
+ } catch (err) {
+ console.warn('[RecoveryService] Failed to clean up saved recovery session:', err);
+ }
+ }
+ }
+
+ /**
+ * Called upon intentional tab closure.
+ */
+ public async closeSession(sessionId: string): Promise<void> {
+ await this.markCleanSaved(sessionId);
+ if (this.currentSessionId === sessionId) {
+ this.currentSessionId = null;
+ }
+ }
+
+ /**
+ * Scans for any crashed sessions with dead/stale PIDs.
+ */
+ public async checkForCrashedSessions(): Promise<CrashedSessionInfo[]> {
+ if (!isTauriEnvironment()) return [];
+ try {
+ const { invoke } = await import('@tauri-apps/api/core');
+ const sessions = await invoke<CrashedSessionInfo[]>('recovery_check_crashed_sessions');
+ return sessions || [];
+ } catch (err) {
+ console.warn('[RecoveryService] Error checking crashed sessions:', err);
+ return [];
+ }
+ }
+
+ /**
+ * Discards an unrecovered crashed session directory.
+ */
+ public async discardCrashedSession(sessionId: string): Promise<void> {
+ if (!isTauriEnvironment()) return;
+ try {
+ const { invoke } = await import('@tauri-apps/api/core');
+ await invoke('recovery_close_session', { sessionId });
+ } catch (err) {
+ console.warn('[RecoveryService] Failed to discard crashed session:', err);
+ }
+ }
+
+ /**
+ * Loads raw snapshot and parsed WAL entries for replaying a crashed session.
+ */
+ public async loadSessionData(sessionId: string): Promise<RecoveryReplayData> {
+ if (!isTauriEnvironment()) {
+ throw new Error('Recovery requires Tauri environment');
+ }
+ const { invoke } = await import('@tauri-apps/api/core');
+ return await invoke<RecoveryReplayData>('recovery_load_session_data', { sessionId });
+ }
+
+ /**
+ * Replays a crashed session and reconstructs state into target tile grid.
+ */
+ public replaySessionData(
+ replayData: RecoveryReplayData,
+ targetGrid: SparseTileGrid = globalTileGrid
+ ): {
+ manifest: DocumentManifest;
+ replayedStrokesCount: number;
+ replayedMutationsCount: number;
+ } {
+ targetGrid.clearAll();
+
+ const manifest: DocumentManifest = JSON.parse(replayData.manifest_json);
+
+ // 1. Replay baseline snapshot if present
+ if (replayData.base_snapshot) {
+ const rawPayload =
+ replayData.base_snapshot instanceof Uint8Array
+ ? replayData.base_snapshot
+ : new Uint8Array(replayData.base_snapshot);
+
+ if (rawPayload.length > 0) {
+ let decompressed: Uint8Array;
+ // Check if deflate compressed (not raw 'INKG')
+ if (
+ rawPayload[0] === 0x49 &&
+ rawPayload[1] === 0x4e &&
+ rawPayload[2] === 0x4b &&
+ rawPayload[3] === 0x47
+ ) {
+ decompressed = rawPayload;
+ } else {
+ decompressed = inflateSync(rawPayload);
+ }
+ deserializeSparseTileGrid(targetGrid, decompressed);
+ }
+ }
+
+ let replayedStrokesCount = 0;
+ let replayedMutationsCount = 0;
+
+ // 2. Replay all WAL entries in exact sequential append order
+ for (const entry of replayData.wal_entries) {
+ const payloadBytes =
+ entry.payload instanceof Uint8Array
+ ? entry.payload
+ : new Uint8Array(entry.payload);
+
+ if (entry.entry_type === WAL_ENTRY_STROKE_TILE_DELTA) {
+ try {
+ const decompressed = inflateSync(payloadBytes);
+ const deltas = deserializeTileDeltas(decompressed);
+ targetGrid.applyTileDeltas(deltas, 'redo');
+ replayedStrokesCount++;
+ } catch (err) {
+ console.warn('[RecoveryService] Failed to replay stroke delta entry:', err);
+ }
+ } else if (entry.entry_type === WAL_ENTRY_VECTOR_STROKE) {
+ try {
+ const jsonStr = new TextDecoder().decode(inflateSync(payloadBytes));
+ const parsed = JSON.parse(jsonStr);
+ if (parsed.layerId && parsed.strokes) {
+ const targetLayer = manifest.layers.find((l) => l.id === parsed.layerId);
+ if (targetLayer) {
+ targetLayer.vectorStrokes = parsed.strokes;
+ }
+ }
+ replayedStrokesCount++;
+ } catch (err) {
+ console.warn('[RecoveryService] Failed to replay vector stroke entry:', err);
+ }
+ } else if (entry.entry_type === WAL_ENTRY_LAYER_MUTATION) {
+ try {
+ const jsonStr = new TextDecoder().decode(inflateSync(payloadBytes));
+ const parsed = JSON.parse(jsonStr);
+ if (parsed.layers) {
+ const existingVectors = new Map<string, VectorStroke[]>();
+ for (const l of manifest.layers) {
+ if (l.vectorStrokes && l.vectorStrokes.length > 0) {
+ existingVectors.set(l.id, l.vectorStrokes);
+ }
+ }
+ manifest.layers = parsed.layers.map((l: LayerItem) => {
+ if ((!l.vectorStrokes || l.vectorStrokes.length === 0) && existingVectors.has(l.id)) {
+ return { ...l, vectorStrokes: existingVectors.get(l.id) };
+ }
+ return l;
+ });
+ }
+ if (parsed.activeLayerId) {
+ manifest.activeLayerId = parsed.activeLayerId;
+ }
+ replayedMutationsCount++;
+ } catch (err) {
+ console.warn('[RecoveryService] Failed to replay layer mutation entry:', err);
+ }
+ }
+ }
+
+ targetGrid.notifyChange(true);
+ return { manifest, replayedStrokesCount, replayedMutationsCount };
+ }
+}
+
+export const recoveryService = new RecoveryService();
diff --git a/src/types/editor.ts b/src/types/editor.ts
index dfcf4cc..a766b22 100644
--- a/src/types/editor.ts
+++ b/src/types/editor.ts
@@ -70,6 +70,45 @@ export interface CspTaperSettings {
outRatio: number;
inOutType?: number;
inOutBySpeed?: boolean;
+ startingSharpness?: number; // 0.0 to 1.0 (CSP Starting sharpness)
+ endingSharpness?: number; // 0.0 to 1.0 (CSP Ending sharpness)
+ affectSize?: boolean; // Taper modulates brush size (default true)
+ affectDensity?: boolean; // Taper modulates brush density
+ affectOpacity?: boolean; // Taper modulates dab opacity
+}
+
+export type CspAntiAliasLevel = 0 | 1 | 2 | 3; // 0: None (Binary), 1: Weak, 2: Medium, 3: Strong
+
+export type CspPaperTextureMode =
+ | 'multiply'
+ | 'subtract'
+ | 'compare'
+ | 'overlay'
+ | 'outline';
+
+export type CspBlendTipsMode = 'normal' | 'darken' | 'compare';
+
+export type CspTipFlipMode = 'none' | 'random' | 'alternate';
+
+export type CspAngleDynamicsMode =
+ | 'none'
+ | 'direction'
+ | 'tilt'
+ | 'twist'
+ | 'random'
+ | 'direction-random';
+
+export interface CspSensorConfig {
+ usePressure?: boolean;
+ pressureMin?: number; // 0.0 to 1.0
+ pressureCurve?: [number, number][];
+ useTilt?: boolean;
+ tiltMin?: number; // 0.0 to 1.0
+ useVelocity?: boolean;
+ velocityMin?: number; // 0.0 to 1.0
+ invertVelocity?: boolean;
+ useRandom?: boolean;
+ randomMin?: number; // 0.0 to 1.0
}
export interface BrushDynamics {
@@ -125,36 +164,57 @@ export interface CspBrush {
thickness: number; // 0.05 to 1.0 (elliptical aspect ratio)
thicknessVertical?: boolean;
angle: number;
- angleDynamics?: 'none' | 'direction' | 'random';
+ angleDynamics?: CspAngleDynamicsMode;
rotationRandomScale?: number; // 0.0 to 1.0
+ flipH?: CspTipFlipMode;
+ flipV?: CspTipFlipMode;
antiAlias?: number; // 0: none/binary, 1: low, 2: mid, 3: high
usePressure: boolean;
+ useTilt?: boolean;
+ tiltScale?: number;
useVelocity?: boolean;
smoothing: boolean;
stabilization: number;
+ postCorrection?: number; // 0 to 5 (CSP Post-correction)
+ sharpCorners?: boolean; // CSP Sharp angles
pressureCurve?: [number, number][]; // Exact CSP cubic spline control points
velocityCurve?: [number, number][];
+ // CSP Ink & Density Controls
+ 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;
+ sizeSensor?: CspSensorConfig;
+ opacitySensor?: CspSensorConfig;
+ densitySensor?: CspSensorConfig;
// Advanced CSP Mathematics Parameters
colorMixing?: boolean; // Enable CSP pigment mixing
perceptualMixing?: boolean; // OKLab / Kubelka-Munk perceptual pigment mixing (default true)
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)
- mixingMode?: 'blend' | 'running_color'; // CSP Mixing mode
+ mixingMode?: 'blend' | 'running_color' | 'smear'; // CSP Mixing mode
wetEdge?: number; // 0.0 to 1.0 (CSP: Watercolor Wet / Water Edge)
wetEdgeRadius?: number;
wetEdgeAlphaPower?: number;
wetEdgeValuePower?: number;
paperTexture?: string; // Paper grain texture data URL
textureDensity?: number; // 0.0 to 1.0 (CSP: Texture / Paper Grain intensity)
+ paperTextureMode?: CspPaperTextureMode;
+ paperTextureBrightness?: number; // -100 to 100
+ paperTextureContrast?: number; // -100 to 100
+ paperTextureApplyEachPlot?: boolean;
paperTextureScale?: number;
paperTextureRotate?: number;
paperTextureInverted?: boolean;
dualBrush?: boolean; // CSP Dual Brush compositing
dualBrushCompositeMode?: string;
+ dualSize?: number;
+ dualSpacing?: number;
spray?: CspSpraySettings;
taper?: CspTaperSettings;
isRibbon?: boolean;
+ isColorTip?: boolean;
pressureCurveGamma?: number; // CSP Pressure response curve gamma
velocityDynamics?: boolean; // Velocity-based taper
dynamics?: BrushDynamics; // Multi-axis jitter matrix
@@ -167,24 +227,39 @@ export interface BrushSettings {
color: string;
secondaryColor?: string; // Secondary / background color for color dynamics
opacity: number; // Brush opacity (0.0 to 1.0)
- flow: number; // Ink flow rate (0.0 to 1.0)
+ flow: number; // Ink flow rate / CSP Brush Density (0.0 to 1.0)
+ 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;
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)
+ tiltScale?: number; // 0.0 to 2.0 tilt spread multiplier
useVelocity?: boolean;
smoothing: boolean;
stabilization: number; // Stroke stabilization slider (0 to 50)
+ 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)
thicknessVertical?: boolean;
+ flipH?: CspTipFlipMode;
+ flipV?: CspTipFlipMode;
antiAlias?: number; // 0: none, 1: low, 2: mid, 3: high
preset?: BrushPresetId; // Currently active brush preset
grain?: number; // Paper grain tooth intensity (0.0 to 1.0)
+ // CSP Per-Property Dynamic Sensors
+ sizeSensor?: CspSensorConfig;
+ opacitySensor?: CspSensorConfig;
+ densitySensor?: CspSensorConfig;
// Custom / CSP brush tip properties
customTipDataUrl?: string;
customTipImage?: HTMLImageElement;
customTipAngle?: number;
- customTipAngleDynamics?: 'none' | 'direction' | 'random';
+ customTipAngleDynamics?: CspAngleDynamicsMode;
customTipRotationRandomScale?: number;
+ isColorTip?: boolean;
brushName?: string; // Custom display name
subTips?: CspSubTip[];
subTipOrder?: 'random' | 'sequential' | 'direction' | 'reverse';
@@ -200,7 +275,7 @@ 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)
- mixingMode?: 'blend' | 'running_color'; // 'blend' or 'running_color'
+ mixingMode?: 'blend' | 'running_color' | 'smear'; // 'blend', 'running_color', or 'smear'
wetEdge?: number; // 0.0 to 1.0 (CSP Water Edge rim density)
wetEdgeRadius?: number;
wetEdgeAlphaPower?: number;
@@ -208,10 +283,17 @@ export interface BrushSettings {
paperTexture?: string; // Optional paper texture data URL
paperTextureImage?: HTMLImageElement; // Preloaded paper grain image
textureDensity?: number; // 0.0 to 1.0 (paper grain tooth)
+ paperTextureMode?: CspPaperTextureMode;
+ paperTextureBrightness?: number;
+ paperTextureContrast?: number;
+ paperTextureApplyEachPlot?: boolean;
+ paperTextureInverted?: boolean;
paperTextureScale?: number;
paperTextureRotate?: number;
dualBrush?: boolean;
dualBrushCompositeMode?: 'multiply' | 'subtract' | 'darken' | 'overlay' | 'screen' | string;
+ dualSize?: number;
+ dualSpacing?: number;
dualTipDataUrl?: string;
dualTipImage?: HTMLImageElement;
pressureCurveGamma?: number; // 0.4 (soft) to 2.5 (hard) response curve
@@ -278,7 +360,8 @@ export type HistoryActionType =
| 'layer-color'
| 'expression-color'
| 'layer-convert'
- | 'liquify';
+ | 'liquify'
+ | 'filter';
export type LiquifyMode =
| 'push'
@@ -523,6 +606,7 @@ export interface HistoryItem extends HistoryItemMeta {
};
peerId?: string | number;
strokeId?: string;
+ isMaskEdit?: boolean;
}
export type ExpressionColor = 'color' | 'gray' | 'monochrome';
diff --git a/src/types/settings.ts b/src/types/settings.ts
index 1562191..b87a48e 100644
--- a/src/types/settings.ts
+++ b/src/types/settings.ts
@@ -22,27 +22,30 @@ export interface ResizeCanvasOptions {
export type ThemePreset = 'vintage-manga' | 'modern';
-export type ModernAccentColor = 'blue' | 'burgundy' | 'green' | 'purple' | 'orange' | 'custom';
+export type ModernAccentColor = 'neutral' | 'blue' | 'burgundy' | 'green' | 'purple' | 'orange' | 'custom';
export interface ModernAccentConfig {
- id: ModernAccentColor;
+ id: Exclude<ModernAccentColor, 'custom'>;
label: string;
hex: string;
}
+export const DEFAULT_ACCENT_HEX = '#e5e5e5';
+
export const MODERN_ACCENTS: Record<Exclude<ModernAccentColor, 'custom'>, ModernAccentConfig> = {
+ neutral: { id: 'neutral', label: 'Neutral', hex: '#e5e5e5' },
blue: { id: 'blue', label: 'Blue', hex: '#3b82f6' },
- burgundy: { id: 'burgundy', label: 'Burgundy', hex: '#be123c' },
green: { id: 'green', label: 'Green', hex: '#10b981' },
- purple: { id: 'purple', label: 'Purple', hex: '#8b5cf6' },
orange: { id: 'orange', label: 'Orange', hex: '#f97316' },
+ purple: { id: 'purple', label: 'Purple', hex: '#8b5cf6' },
+ burgundy: { id: 'burgundy', label: 'Burgundy', hex: '#be123c' },
};
export function resolveModernAccentColor(accent: ModernAccentColor, customColor?: string): string {
if (accent === 'custom') {
- return customColor && /^#[0-9a-fA-F]{6}$/i.test(customColor) ? customColor : '#3b82f6';
+ return customColor && /^#[0-9a-fA-F]{6}$/i.test(customColor) ? customColor : DEFAULT_ACCENT_HEX;
}
- return MODERN_ACCENTS[accent]?.hex || '#3b82f6';
+ return MODERN_ACCENTS[accent]?.hex || DEFAULT_ACCENT_HEX;
}
export function hexToRgb(hex: string): { r: number; g: number; b: number } | null {
@@ -62,6 +65,13 @@ export function hexToRgb(hex: string): { r: number; g: number; b: number } | nul
return null;
}
+export function getAccentContrastColor(hex: string): string {
+ const rgb = hexToRgb(hex);
+ if (!rgb) return '#161616';
+ const luminance = (0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b) / 255;
+ return luminance > 0.55 ? '#161616' : '#e5e5e5';
+}
+
export interface AppSettings {
// User Profile
userName: string;
@@ -90,15 +100,18 @@ export interface AppSettings {
usePressureByDefault: boolean;
smoothingEnabled: boolean;
maxHistorySteps: number;
+
+ // Performance & Scratch Disk
+ tileMemoryBudgetMb: number;
}
export const DEFAULT_APP_SETTINGS: AppSettings = {
userName: '',
- hasPromptedName: false,
- themePreset: 'vintage-manga',
- modernAccent: 'blue',
- modernCustomColor: '#3b82f6',
- uiTone: 'slate',
+ hasPromptedName: true,
+ themePreset: 'modern',
+ modernAccent: 'neutral',
+ modernCustomColor: DEFAULT_ACCENT_HEX,
+ uiTone: 'charcoal',
showCheckerboard: true,
showCursorCoordinates: true,
showPressureInStatusBar: true,
@@ -115,9 +128,11 @@ export const DEFAULT_APP_SETTINGS: AppSettings = {
usePressureByDefault: true,
smoothingEnabled: true,
maxHistorySteps: 50,
+
+ tileMemoryBudgetMb: 1024,
};
-const SETTINGS_KEY = 'sora_paint_app_settings';
+const SETTINGS_KEY = 'ink_studio_app_settings';
export function loadAppSettings(): AppSettings {
try {
@@ -125,25 +140,39 @@ export function loadAppSettings(): AppSettings {
const legacyName = localStorage.getItem('sora_paint_nickname') || '';
if (raw) {
const parsed = JSON.parse(raw);
- const validTheme: ThemePreset = parsed.themePreset === 'modern' ? 'modern' : 'vintage-manga';
- const validAccent: ModernAccentColor = ['blue', 'burgundy', 'green', 'purple', 'orange', 'custom'].includes(parsed.modernAccent)
+ const validTheme: ThemePreset = parsed.themePreset === 'vintage-manga' ? 'vintage-manga' : 'modern';
+ const validAccent: ModernAccentColor = [
+ 'neutral',
+ 'blue',
+ 'burgundy',
+ 'green',
+ 'purple',
+ 'orange',
+ 'custom',
+ ].includes(parsed.modernAccent)
? parsed.modernAccent
- : 'blue';
- const validCustomColor: string = typeof parsed.modernCustomColor === 'string' && /^#[0-9a-fA-F]{6}$/i.test(parsed.modernCustomColor)
- ? parsed.modernCustomColor
- : '#3b82f6';
+ : 'neutral';
+ const validCustomColor: string =
+ typeof parsed.modernCustomColor === 'string' && /^#[0-9a-fA-F]{6}$/i.test(parsed.modernCustomColor)
+ ? parsed.modernCustomColor
+ : DEFAULT_ACCENT_HEX;
const validTone: 'slate' | 'oled' | 'charcoal' = ['slate', 'oled', 'charcoal'].includes(parsed.uiTone)
? parsed.uiTone
- : 'slate';
+ : 'charcoal';
+ const validBudget: number =
+ typeof parsed.tileMemoryBudgetMb === 'number' && parsed.tileMemoryBudgetMb >= 256 && parsed.tileMemoryBudgetMb <= 8192
+ ? parsed.tileMemoryBudgetMb
+ : 1024;
return {
...DEFAULT_APP_SETTINGS,
...parsed,
userName: parsed.userName !== undefined ? parsed.userName : legacyName,
- hasPromptedName: parsed.hasPromptedName !== undefined ? parsed.hasPromptedName : Boolean(legacyName),
+ hasPromptedName: parsed.hasPromptedName !== undefined ? parsed.hasPromptedName : true,
themePreset: validTheme,
modernAccent: validAccent,
modernCustomColor: validCustomColor,
uiTone: validTone,
+ tileMemoryBudgetMb: validBudget,
};
} else if (legacyName) {
return {
diff --git a/src/utils/__tests__/brushEngine.test.ts b/src/utils/__tests__/brushEngine.test.ts
index c7d2564..b447e10 100644
--- a/src/utils/__tests__/brushEngine.test.ts
+++ b/src/utils/__tests__/brushEngine.test.ts
@@ -702,4 +702,83 @@ describe('Brush & Spline Engine (CSP / Photoshop Architectural Parity)', () => {
expect(fastTaperedCount).toBeGreaterThan(slowTaperedCount);
});
});
+
+ describe('8. Multi-Resolution Mipmap Masters, Corner Knots & Deterministic Bake Parity', () => {
+ it('selects optimal resolution buckets in getRadialDabMaster when targetSize is provided', () => {
+ const mSmall = getRadialDabMaster(1.0, '#000000', false, 4);
+ const mMed = getRadialDabMaster(1.0, '#000000', false, 16);
+ const mLarge = getRadialDabMaster(1.0, '#000000', false, 48);
+ const mHuge = getRadialDabMaster(1.0, '#000000', false, 100);
+
+ expect(mSmall.width).toBe(24);
+ expect(mMed.width).toBe(48);
+ expect(mLarge.width).toBe(64);
+ expect(mHuge.width).toBe(128);
+ });
+
+ it('breaks tangent influence across sharp corners when isCorner is set on knots', () => {
+ const p0: Point = { x: 0, y: 50, pressure: 0.5, width: 10 };
+ const p1: Point = { x: 50, y: 0, pressure: 0.5, width: 10, isCorner: true };
+ const p2: Point = { x: 100, y: 0, pressure: 0.5, width: 10 };
+ const p3: Point = { x: 150, y: 0, pressure: 0.5, width: 10 };
+
+ const { c1, c2 } = centripetalCatmullRomToBezier(p0, p1, p2, p3);
+ // Since p1.isCorner is true, c1 should lie strictly on the horizontal chord y = 0 without pulling toward p0 (y = 50)
+ expect(c1.y).toBeCloseTo(0, 4);
+ expect(c2.y).toBeCloseTo(0, 4);
+ });
+
+ it('produces identical scattered/jittered dab coordinates across repeated renderCompleteStroke calls', () => {
+ const c1 = createMockCanvas(200, 200);
+ const c2 = createMockCanvas(200, 200);
+ const ctx1 = c1.getContext('2d') as unknown as CanvasRenderingContext2D;
+ const ctx2 = c2.getContext('2d') as unknown as CanvasRenderingContext2D;
+
+ const pts: Point[] = [
+ { x: 20, y: 40, pressure: 0.6, width: 12 },
+ { x: 60, y: 50, pressure: 0.8, width: 14 },
+ { x: 110, y: 45, pressure: 0.7, width: 13 },
+ ];
+
+ const settings: BrushSettings = {
+ size: 14,
+ minSizeFactor: 0.2,
+ opacity: 1.0,
+ color: '#2255aa',
+ secondaryColor: '#ffaa00',
+ flow: 0.9,
+ spacing: 0.1,
+ smoothing: true,
+ stabilization: 10,
+ hardness: 0.9,
+ usePressure: true,
+ dynamics: {
+ sizeJitter: 0.5,
+ angleJitter: 0.4,
+ roundnessJitter: 0.3,
+ scatter: 1.2,
+ scatterBothAxes: true,
+ count: 2,
+ flowJitter: 0.3,
+ colorJitterEnabled: true,
+ hueJitter: 0.2,
+ saturationJitter: 0.2,
+ brightnessJitter: 0.2,
+ foregroundBackgroundJitter: 0.3,
+ },
+ };
+
+ renderCompleteStroke(ctx1, pts, settings, 'brush', 'color', false);
+ renderCompleteStroke(ctx2, pts, settings, 'brush', 'color', false);
+
+ expect(c1.drawnDabs.length).toBeGreaterThan(10);
+ expect(c1.drawnDabs.length).toBe(c2.drawnDabs.length);
+ for (let i = 0; i < c1.drawnDabs.length; i++) {
+ expect(c1.drawnDabs[i].x).toBeCloseTo(c2.drawnDabs[i].x, 5);
+ expect(c1.drawnDabs[i].y).toBeCloseTo(c2.drawnDabs[i].y, 5);
+ expect(c1.drawnDabs[i].width).toBeCloseTo(c2.drawnDabs[i].width, 5);
+ expect(c1.drawnDabs[i].alpha).toBeCloseTo(c2.drawnDabs[i].alpha, 5);
+ }
+ });
+ });
});
diff --git a/src/utils/__tests__/cspBrushEngineV2.test.ts b/src/utils/__tests__/cspBrushEngineV2.test.ts
new file mode 100644
index 0000000..8ef6048
--- /dev/null
+++ b/src/utils/__tests__/cspBrushEngineV2.test.ts
@@ -0,0 +1,172 @@
+import { describe, it, expect } from 'vitest';
+import {
+ getCompiledCurveLut,
+ evaluateFastSpline,
+ dabHashFloat,
+ evaluateCspSensor,
+ computeEllipticalStepDistance,
+ computeGapAdjustedAlpha,
+ computeSubpixelDabDimensions,
+ getCspAntiAliasFeather,
+ resolveTipFlipSigns,
+ applyCspPaperTextureAlpha,
+ applyCspPostCorrection,
+ applyCspWatercolorEdge,
+ CSP_PRESSURE_CURVE_PRESETS,
+} from '../../engine/CspBrushEngine';
+import { stepBrushSizePreset } from '../brushPresetManager';
+import { BUILTIN_BRUSHES } from '../presetBrushes';
+import { Point } from '../../types/editor';
+
+describe('CSP Brush Engine V2 - Mathematics, Sensors & Post-Processing', () => {
+ it('compiles PCHIP LUTs with strict monotonicity and caches identical curves', () => {
+ const curve = CSP_PRESSURE_CURVE_PRESETS['g-pen'].points;
+ const lut1 = getCompiledCurveLut(curve);
+ const lut2 = getCompiledCurveLut(curve);
+ expect(lut1).not.toBeNull();
+ expect(lut1).toBe(lut2);
+ expect(lut1!.length).toBe(256);
+
+ let prev = -1;
+ for (let i = 0; i <= 100; i++) {
+ const y = evaluateFastSpline(i / 100, curve);
+ expect(y).toBeGreaterThanOrEqual(prev - 1e-6);
+ expect(y).toBeGreaterThanOrEqual(0);
+ expect(y).toBeLessThanOrEqual(1);
+ prev = y;
+ }
+ expect(evaluateFastSpline(0, curve)).toBeCloseTo(0, 4);
+ expect(evaluateFastSpline(1, curve)).toBeCloseTo(1, 4);
+ });
+
+ it('produces deterministic dab hashes across repeated calls', () => {
+ const h1 = dabHashFloat(128.45, 256.9, 17, 3);
+ const h2 = dabHashFloat(128.45, 256.9, 17, 3);
+ const hDiff = dabHashFloat(128.45, 256.9, 18, 3);
+ expect(h1).toBe(h2);
+ expect(h1).toBeGreaterThanOrEqual(0);
+ expect(h1).toBeLessThan(1);
+ expect(h1).not.toBe(hDiff);
+ });
+
+ it('evaluates multiplicative CSP multi-sensor dynamics (Pressure x Tilt x Velocity x Random)', () => {
+ const val = evaluateCspSensor(
+ {
+ usePressure: true,
+ pressureMin: 0.2,
+ useTilt: true,
+ tiltMin: 0.5,
+ useVelocity: true,
+ velocityMin: 0.4,
+ invertVelocity: true,
+ useRandom: true,
+ randomMin: 0.5,
+ },
+ 0.5, // pFactor = 0.2 + 0.8 * 0.5 = 0.6
+ 0.5, // tFactor = 0.5 + 0.5 * 0.5 = 0.75
+ 1.75, // vNorm = 0.5 -> inverted 0.5 -> vFactor = 0.4 + 0.6 * 0.5 = 0.7
+ 0.5 // rFactor = 0.5 + 0.5 * 0.5 = 0.75
+ );
+ expect(val).toBeCloseTo(0.6 * 0.75 * 0.7 * 0.75, 5);
+ });
+
+ it('computes directional elliptical step distance to prevent calligraphic gaps', () => {
+ // 40px wide, 4px tall flat nib at 0 rad
+ const alongWide = computeEllipticalStepDistance(40, 4, 0, 1, 0, 0.1);
+ const alongThin = computeEllipticalStepDistance(40, 4, 0, 0, 1, 0.1);
+ expect(alongWide).toBeCloseTo(4.0, 3);
+ expect(alongThin).toBeCloseTo(0.4, 3);
+ expect(alongThin).toBeLessThan(alongWide * 0.2);
+ });
+
+ it('compensates dab density by gap using Beer-Lambert transmittance', () => {
+ const tightAlpha = computeGapAdjustedAlpha(0.3, 0.08, true, 0.08);
+ const wideAlpha = computeGapAdjustedAlpha(0.3, 0.24, true, 0.08);
+ expect(tightAlpha).toBeCloseTo(0.3, 4);
+ // 3x wider gap should yield 1 - (1 - 0.3)^3 = 0.657
+ expect(wideAlpha).toBeCloseTo(1 - Math.pow(0.7, 3), 3);
+ expect(wideAlpha).toBeGreaterThan(tightAlpha);
+ });
+
+ it('conserves 2D sub-pixel hairline coverage and maps 4-stage CSP anti-aliasing', () => {
+ const sub = computeSubpixelDabDimensions(0.375, 0.375, 0.8, 0.75);
+ expect(sub.renderW).toBe(0.75);
+ expect(sub.renderH).toBe(0.75);
+ // 0.5 * 0.5 = 0.25 area ratio -> 0.8 * 0.25 = 0.2
+ expect(sub.effAlpha).toBeCloseTo(0.2, 4);
+
+ expect(getCspAntiAliasFeather(0)).toBe(0);
+ expect(getCspAntiAliasFeather(1)).toBeLessThan(getCspAntiAliasFeather(2));
+ expect(getCspAntiAliasFeather(2)).toBeLessThan(getCspAntiAliasFeather(3));
+ });
+
+ it('supports tip flip modes and all 5 CSP paper texture physics modes', () => {
+ const alt0 = resolveTipFlipSigns('alternate', 'none', 0, 10, 10);
+ const alt1 = resolveTipFlipSigns('alternate', 'none', 1, 10, 10);
+ expect(alt0.signX).toBe(1);
+ expect(alt1.signX).toBe(-1);
+
+ const modes = ['multiply', 'subtract', 'compare', 'overlay', 'outline'] as const;
+ for (const mode of modes) {
+ const a = applyCspPaperTextureAlpha(0.7, 0.35, 0.8, 0.4, mode, 0, 10, false);
+ expect(a).toBeGreaterThanOrEqual(0);
+ expect(a).toBeLessThanOrEqual(1);
+ }
+
+ // Subtract valley-fill: higher stylus pressure penetrates deeper -> higher alpha
+ const lightTouch = applyCspPaperTextureAlpha(0.6, 0.3, 0.85, 0.1, 'subtract');
+ const heavyTouch = applyCspPaperTextureAlpha(0.6, 0.3, 0.85, 0.95, 'subtract');
+ expect(heavyTouch).toBeGreaterThan(lightTouch);
+ });
+
+ it('applies post-correction smoothing while preserving sharp corners and endpoints', () => {
+ const pts: Point[] = [
+ { x: 0, y: 0, pressure: 0.5, width: 4 },
+ { x: 10, y: 2, pressure: 0.5, width: 4 },
+ { x: 20, y: -2, pressure: 0.5, width: 4 },
+ { x: 30, y: 0, pressure: 0.5, width: 4, isCorner: true },
+ { x: 30, y: 30, pressure: 0.5, width: 4 },
+ ];
+ const smoothed = applyCspPostCorrection(pts, 4, true);
+ expect(smoothed[0].x).toBe(0);
+ expect(smoothed[0].y).toBe(0);
+ expect(smoothed[3].x).toBe(30);
+ expect(smoothed[3].y).toBe(0);
+ expect(smoothed[4].x).toBe(30);
+ expect(smoothed[4].y).toBe(30);
+ // Jittered interior point y=2 should be damped toward 0
+ expect(Math.abs(smoothed[1].y)).toBeLessThan(2);
+ });
+
+ it('applies stroke-silhouette watercolor edge darkening at outer rim without fish-scale interior artifacts', () => {
+ const w = 24;
+ const h = 24;
+ const data = new Uint8ClampedArray(w * h * 4);
+ for (let y = 4; y < 20; y++) {
+ for (let x = 4; x < 20; x++) {
+ const p = (y * w + x) * 4;
+ data[p] = 200;
+ data[p + 1] = 150;
+ data[p + 2] = 100;
+ data[p + 3] = 180;
+ }
+ }
+ applyCspWatercolorEdge({ data, width: w, height: h }, 0.9, 2, 0.7, 0.6);
+
+ const centerIdx = (12 * w + 12) * 4;
+ const rimIdx = (4 * w + 12) * 4;
+ // Deep center remains untouched while outer rim darkens and concentrates alpha
+ expect(data[centerIdx]).toBe(200);
+ expect(data[centerIdx + 3]).toBe(180);
+ expect(data[rimIdx]).toBeLessThan(200);
+ expect(data[rimIdx + 3]).toBeGreaterThan(180);
+ });
+
+ it('steps brush size presets cleanly and includes all 18 studio presets', () => {
+ expect(stepBrushSizePreset(10, 1)).toBe(12);
+ expect(stepBrushSizePreset(10, -1)).toBe(8);
+ expect(stepBrushSizePreset(0.5, -1)).toBe(0.5);
+ expect(stepBrushSizePreset(2000, 1)).toBe(2000);
+ expect(BUILTIN_BRUSHES.length).toBeGreaterThanOrEqual(18);
+ });
+});
diff --git a/src/utils/__tests__/cspEngineRefactor.test.ts b/src/utils/__tests__/cspEngineRefactor.test.ts
index 8205078..c46964c 100644
--- a/src/utils/__tests__/cspEngineRefactor.test.ts
+++ b/src/utils/__tests__/cspEngineRefactor.test.ts
@@ -87,6 +87,21 @@ describe('Clip Studio Paint Drawing Engine Refactor Tests', () => {
// Decay should be smooth and damped (not jumping immediately to 0.1)
expect(decaySample.pressure).toBeGreaterThan(0.2);
});
+
+ it('remains stable when coalesced events share identical timestamps', () => {
+ const stab = new InputStabilizer();
+ stab.setStabilizerLevel(20);
+
+ stab.process(0, 0, 0.5, 100);
+ const s1X = stab.process(4, 0, 0.5, 116).x;
+ // Coalesced event with identical timestamp (116ms)
+ const s2X = stab.process(8, 0, 0.5, 116).x;
+
+ expect(Number.isFinite(s2X)).toBe(true);
+ expect(s2X).toBeGreaterThan(s1X);
+ // Should still be smoothed rather than snapping raw due to derivative explosion
+ expect(s2X).toBeLessThan(8);
+ });
});
describe('Phase 4: Japanese Inking Dynamics (TaperEngine)', () => {
diff --git a/src/utils/__tests__/recovery.test.ts b/src/utils/__tests__/recovery.test.ts
new file mode 100644
index 0000000..a0f78f2
--- /dev/null
+++ b/src/utils/__tests__/recovery.test.ts
@@ -0,0 +1,421 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import {
+ computeCrc32,
+ formatWalFrame,
+ parseWalFrames,
+ WAL_ENTRY_STROKE_TILE_DELTA,
+ WAL_ENTRY_VECTOR_STROKE,
+ WAL_ENTRY_LAYER_MUTATION,
+ recoveryService,
+ RecoveryReplayData,
+} from '../../services/recoveryService';
+import {
+ SparseTileGrid,
+ serializeTileDeltas,
+ serializeSparseTileGrid,
+ deserializeSparseTileGrid,
+} from '../tileEngine';
+import { TileDelta } from '../../types/editor';
+import { deflateSync } from 'fflate';
+
+describe('Crash Recovery & WAL Architecture Engine', () => {
+ describe('CRC32 & Binary Framing Headers', () => {
+ it('computes standard IEEE 802.3 CRC32 checksums accurately', () => {
+ const testVec = new TextEncoder().encode('123456789');
+ const crc = computeCrc32(testVec);
+ expect(crc).toBe(0xcbf43926);
+
+ const emptyVec = new Uint8Array(0);
+ expect(computeCrc32(emptyVec)).toBe(0x00000000);
+
+ const simple = new Uint8Array([1, 2, 3, 4]);
+ expect(computeCrc32(simple)).toBeGreaterThan(0);
+ });
+
+ it('serializes WAL frames with atomic 13-byte headers', () => {
+ const payload = new Uint8Array([10, 20, 30, 40, 50]);
+ const frame = formatWalFrame(WAL_ENTRY_STROKE_TILE_DELTA, payload);
+
+ // Total length: 13 header + 5 payload = 18 bytes
+ expect(frame.length).toBe(18);
+
+ // Magic header 'INKW'
+ expect(frame[0]).toBe(0x49); // 'I'
+ expect(frame[1]).toBe(0x4e); // 'N'
+ expect(frame[2]).toBe(0x4b); // 'K'
+ expect(frame[3]).toBe(0x57); // 'W'
+
+ // Entry type
+ expect(frame[4]).toBe(WAL_ENTRY_STROKE_TILE_DELTA);
+
+ const view = new DataView(frame.buffer, frame.byteOffset, frame.byteLength);
+ // Payload length
+ expect(view.getUint32(5, true)).toBe(5);
+
+ // CRC32
+ const expectedCrc = computeCrc32(payload);
+ expect(view.getUint32(9, true)).toBe(expectedCrc);
+
+ // Payload content
+ expect(Array.from(frame.subarray(13))).toEqual([10, 20, 30, 40, 50]);
+ });
+
+ it('deserializes multiple contiguous valid WAL frames', () => {
+ const p1 = new Uint8Array([1, 2, 3]);
+ const p2 = new Uint8Array([4, 5, 6, 7]);
+ const p3 = new Uint8Array([8, 9]);
+
+ const f1 = formatWalFrame(WAL_ENTRY_STROKE_TILE_DELTA, p1);
+ const f2 = formatWalFrame(WAL_ENTRY_VECTOR_STROKE, p2);
+ const f3 = formatWalFrame(WAL_ENTRY_LAYER_MUTATION, p3);
+
+ const combined = new Uint8Array(f1.length + f2.length + f3.length);
+ combined.set(f1, 0);
+ combined.set(f2, f1.length);
+ combined.set(f3, f1.length + f2.length);
+
+ const { validFrames, corruptedTail } = parseWalFrames(combined);
+
+ expect(corruptedTail).toBe(false);
+ expect(validFrames.length).toBe(3);
+
+ expect(validFrames[0].entryType).toBe(WAL_ENTRY_STROKE_TILE_DELTA);
+ expect(Array.from(validFrames[0].payload)).toEqual([1, 2, 3]);
+
+ expect(validFrames[1].entryType).toBe(WAL_ENTRY_VECTOR_STROKE);
+ expect(Array.from(validFrames[1].payload)).toEqual([4, 5, 6, 7]);
+
+ expect(validFrames[2].entryType).toBe(WAL_ENTRY_LAYER_MUTATION);
+ expect(Array.from(validFrames[2].payload)).toEqual([8, 9]);
+ });
+
+ it('safely discards incomplete tail chunks caused by crash mid-write', () => {
+ const p1 = new Uint8Array([10, 20, 30]);
+ const f1 = formatWalFrame(WAL_ENTRY_STROKE_TILE_DELTA, p1);
+
+ const p2 = new Uint8Array([40, 50, 60, 70, 80]);
+ const f2 = formatWalFrame(WAL_ENTRY_VECTOR_STROKE, p2);
+
+ // Truncate f2 mid-write: include only 13 header bytes + 2 payload bytes (missing 3 bytes)
+ const truncatedF2 = f2.subarray(0, 15);
+
+ const combined = new Uint8Array(f1.length + truncatedF2.length);
+ combined.set(f1, 0);
+ combined.set(truncatedF2, f1.length);
+
+ const { validFrames, corruptedTail } = parseWalFrames(combined);
+
+ // Only the first complete frame is returned; truncated tail is safely discarded
+ expect(validFrames.length).toBe(1);
+ expect(validFrames[0].entryType).toBe(WAL_ENTRY_STROKE_TILE_DELTA);
+ expect(Array.from(validFrames[0].payload)).toEqual([10, 20, 30]);
+ expect(corruptedTail).toBe(true);
+ });
+
+ it('safely detects and discards corrupted tail chunk with CRC32 mismatch', () => {
+ const p1 = new Uint8Array([100, 101, 102]);
+ const f1 = formatWalFrame(WAL_ENTRY_STROKE_TILE_DELTA, p1);
+
+ const p2 = new Uint8Array([200, 201, 202, 203]);
+ const f2 = formatWalFrame(WAL_ENTRY_STROKE_TILE_DELTA, p2);
+
+ // Corrupt a byte in f2's payload without updating CRC
+ f2[14] = 99; // corrupt payload byte
+
+ const combined = new Uint8Array(f1.length + f2.length);
+ combined.set(f1, 0);
+ combined.set(f2, f1.length);
+
+ const { validFrames, corruptedTail } = parseWalFrames(combined);
+
+ expect(validFrames.length).toBe(1);
+ expect(validFrames[0].entryType).toBe(WAL_ENTRY_STROKE_TILE_DELTA);
+ expect(Array.from(validFrames[0].payload)).toEqual([100, 101, 102]);
+ expect(corruptedTail).toBe(true);
+ });
+ });
+
+ describe('Replay Ordering Logic on Sparse Tile Grids', () => {
+ let grid: SparseTileGrid;
+
+ beforeEach(() => {
+ grid = new SparseTileGrid();
+ });
+
+ it('serializes and deserializes baseline snapshots accurately', () => {
+ const img1 = new Uint8ClampedArray(256 * 256 * 4);
+ img1[0] = 255; // Red pixel at (0, 0)
+ img1[3] = 255;
+ grid.writeImageData('layer-1', { data: img1, width: 256, height: 256 }, 0, 0, 'color-32bit');
+
+ const img2 = new Uint8ClampedArray(256 * 256 * 4);
+ img2[1] = 255; // Green pixel at (256, 256)
+ img2[3] = 255;
+ grid.writeImageData('layer-2', { data: img2, width: 256, height: 256 }, 256, 256, 'color-32bit');
+
+ const snapshotBytes = serializeSparseTileGrid(grid);
+ expect(snapshotBytes.length).toBeGreaterThan(0);
+
+ const newGrid = new SparseTileGrid();
+ deserializeSparseTileGrid(newGrid, snapshotBytes);
+
+ expect(newGrid.hasTile('layer-1', 0, 0)).toBe(true);
+ expect(newGrid.hasTile('layer-2', 1, 1)).toBe(true);
+ expect(newGrid.hasTile('layer-1', 1, 1)).toBe(false);
+
+ const tile1 = newGrid.getTile('layer-1', 0, 0);
+ expect(tile1?.data![0]).toBe(255);
+ expect(tile1?.data![3]).toBe(255);
+
+ const tile2 = newGrid.getTile('layer-2', 1, 1);
+ expect(tile2?.data![1]).toBe(255);
+ expect(tile2?.data![3]).toBe(255);
+ });
+
+ it('replays baseline snapshot followed by sequential WAL stroke deltas in exact order', () => {
+ // Step 1: Base state at tile (0, 0)
+ const baseData = new Uint8ClampedArray(256 * 256 * 4);
+ baseData[0] = 50;
+ baseData[3] = 255;
+ grid.writeImageData('layer-art', { data: baseData, width: 256, height: 256 }, 0, 0, 'color-32bit');
+
+ const baseSnapshot = serializeSparseTileGrid(grid);
+
+ // Step 2: Stroke 1 modifies pixel 0 to 120
+ const stroke1After = new Uint8Array(256 * 256 * 4);
+ stroke1After[0] = 120;
+ stroke1After[3] = 255;
+ const stroke1Delta: TileDelta = {
+ key: 'layer-art:0:0',
+ format: 'color-32bit',
+ beforeData: new Uint8Array(baseData),
+ afterData: stroke1After,
+ };
+
+ // Step 3: Stroke 2 modifies pixel 0 to 240 and pixel 1 to 180
+ const stroke2After = new Uint8Array(256 * 256 * 4);
+ stroke2After[0] = 240;
+ stroke2After[1] = 180;
+ stroke2After[3] = 255;
+ const stroke2Delta: TileDelta = {
+ key: 'layer-art:0:0',
+ format: 'color-32bit',
+ beforeData: stroke1After,
+ afterData: stroke2After,
+ };
+
+ // Package deltas with deflate
+ const walPayload1 = deflateSync(serializeTileDeltas([stroke1Delta]));
+ const walPayload2 = deflateSync(serializeTileDeltas([stroke2Delta]));
+
+ const replayData: RecoveryReplayData = {
+ session_id: 'test-session-123',
+ manifest_json: JSON.stringify({
+ sessionId: 'test-session-123',
+ documentName: 'Manga Page 1',
+ width: 3000,
+ height: 3000,
+ dpi: 600,
+ colorMode: 'color',
+ layers: [{ id: 'layer-art', name: 'Lineart', type: 'raster', visible: true, opacity: 1, blendMode: 'normal', locked: false, parentId: null }],
+ activeLayerId: 'layer-art',
+ timestamp: Date.now(),
+ }),
+ base_snapshot: baseSnapshot,
+ wal_entries: [
+ { entry_type: WAL_ENTRY_STROKE_TILE_DELTA, payload: walPayload1 },
+ { entry_type: WAL_ENTRY_STROKE_TILE_DELTA, payload: walPayload2 },
+ ],
+ };
+
+ // Target empty grid to simulate fresh launch after crash
+ const targetGrid = new SparseTileGrid();
+ const result = recoveryService.replaySessionData(replayData, targetGrid);
+
+ expect(result.replayedStrokesCount).toBe(2);
+ expect(result.manifest.documentName).toBe('Manga Page 1');
+ expect(result.manifest.width).toBe(3000);
+
+ // Verify final tile state reflects sequential stroke application (Stroke 2 was applied after Stroke 1)
+ const tile = targetGrid.getTile('layer-art', 0, 0);
+ expect(tile).not.toBeNull();
+ expect(tile?.data![0]).toBe(240);
+ expect(tile?.data![1]).toBe(180);
+ expect(tile?.data![3]).toBe(255);
+ });
+
+ it('correctly handles layer mutations and vector strokes during WAL replay', () => {
+ const manifest = {
+ sessionId: 'test-session-vec',
+ documentName: 'Vector Manga',
+ width: 2000,
+ height: 2000,
+ dpi: 300,
+ colorMode: 'color' as const,
+ layers: [
+ { id: 'layer-vec', name: 'Vector 1', type: 'vector' as const, visible: true, opacity: 1, blendMode: 'normal' as const, locked: false, parentId: null, vectorStrokes: [] },
+ ],
+ activeLayerId: 'layer-vec',
+ timestamp: Date.now(),
+ };
+
+ // 1. Vector stroke entry
+ const vecStroke = {
+ id: 'stroke-1',
+ layerId: 'layer-vec',
+ tool: 'brush',
+ knots: [{ x: 10, y: 10, pressure: 0.5, width: 5, timestamp: 100 }],
+ color: '#000000',
+ baseWidth: 5,
+ opacity: 1,
+ bounds: { minX: 10, minY: 10, maxX: 10, maxY: 10 },
+ };
+ const vecPayload = deflateSync(new TextEncoder().encode(JSON.stringify({ layerId: 'layer-vec', strokes: [vecStroke] })));
+
+ // 2. Layer mutation entry (added a new background layer)
+ const mutationPayload = deflateSync(new TextEncoder().encode(JSON.stringify({
+ mutationType: 'add-layer',
+ layers: [
+ { id: 'layer-bg', name: 'Background', type: 'raster', visible: true, opacity: 1, blendMode: 'normal', locked: false, parentId: null },
+ manifest.layers[0],
+ ],
+ activeLayerId: 'layer-bg',
+ })));
+
+ const replayData: RecoveryReplayData = {
+ session_id: 'test-session-vec',
+ manifest_json: JSON.stringify(manifest),
+ base_snapshot: null,
+ wal_entries: [
+ { entry_type: WAL_ENTRY_VECTOR_STROKE, payload: vecPayload },
+ { entry_type: WAL_ENTRY_LAYER_MUTATION, payload: mutationPayload },
+ ],
+ };
+
+ const targetGrid = new SparseTileGrid();
+ const result = recoveryService.replaySessionData(replayData, targetGrid);
+
+ expect(result.replayedStrokesCount).toBe(1);
+ expect(result.replayedMutationsCount).toBe(1);
+ expect(result.manifest.layers.length).toBe(2);
+ expect(result.manifest.layers[0].id).toBe('layer-bg');
+
+ const vecLayer = result.manifest.layers.find((l) => l.id === 'layer-vec');
+ expect(vecLayer?.vectorStrokes?.length).toBe(1);
+ expect(vecLayer?.vectorStrokes?.[0].id).toBe('stroke-1');
+ });
+
+ it('simulates hard kill crash after 15 strokes on 3000x3000 canvas with 3 layers and partial tail discard', () => {
+ // 1. Initial 3000x3000 canvas with 3 layers
+ const originalGrid = new SparseTileGrid();
+ const layers = [
+ { id: 'layer-bg', name: 'Paper', type: 'raster' as const, visible: true, opacity: 1, blendMode: 'normal' as const, locked: false, parentId: null },
+ { id: 'layer-sketch', name: 'Rough Sketch', type: 'raster' as const, visible: true, opacity: 0.6, blendMode: 'normal' as const, locked: false, parentId: null },
+ { id: 'layer-ink', name: 'Line Ink', type: 'raster' as const, visible: true, opacity: 1, blendMode: 'normal' as const, locked: false, parentId: null },
+ ];
+
+ // Fill background layer with white
+ const bgData = new Uint8ClampedArray(256 * 256 * 4);
+ bgData.fill(255);
+ originalGrid.writeImageData('layer-bg', { data: bgData, width: 256, height: 256 }, 0, 0, 'color-32bit');
+
+ // 2. Draw 10 strokes on 'layer-sketch'
+ for (let i = 0; i < 10; i++) {
+ const strokeData = new Uint8ClampedArray(256 * 256 * 4);
+ strokeData[i * 4] = (i + 1) * 20; // Distinct pixel values
+ strokeData[i * 4 + 3] = 255;
+ originalGrid.writeImageData('layer-sketch', { data: strokeData, width: 256, height: 256 }, 0, 0, 'color-32bit');
+ }
+
+ // 3. Trigger periodic checkpoint after stroke 10
+ const baselineSnapshot = serializeSparseTileGrid(originalGrid);
+
+ // 4. Draw strokes 11 to 15 on 'layer-ink' (these generate WAL delta entries)
+ const walFrames: Uint8Array[] = [];
+ const deltaBuffers: TileDelta[][] = [];
+
+ for (let i = 10; i < 15; i++) {
+ const beforeTile = originalGrid.getTile('layer-ink', 0, 0);
+ const beforeData = beforeTile && beforeTile.data ? new Uint8Array(beforeTile.data) : new Uint8Array(256 * 256 * 4);
+
+ const afterData = new Uint8Array(beforeData);
+ afterData[(i - 10) * 16] = 255; // Stroke mark
+ afterData[(i - 10) * 16 + 1] = (i + 1) * 15;
+ afterData[(i - 10) * 16 + 3] = 255;
+
+ originalGrid.writeImageData('layer-ink', { data: new Uint8ClampedArray(afterData), width: 256, height: 256 }, 0, 0, 'color-32bit');
+
+ const delta: TileDelta = {
+ key: 'layer-ink:0:0',
+ format: 'color-32bit',
+ beforeData,
+ afterData,
+ };
+ deltaBuffers.push([delta]);
+
+ const compressed = deflateSync(serializeTileDeltas([delta]));
+ const frame = formatWalFrame(WAL_ENTRY_STROKE_TILE_DELTA, compressed);
+ walFrames.push(frame);
+ }
+
+ // 5. Simulate sudden force kill mid-write on stroke 16 (incomplete WAL frame tail)
+ const corruptedPartialFrame = new Uint8Array([0x49, 0x4e, 0x4b, 0x57, 0x01, 0x20, 0x00, 0x00, 0x00, 0x12, 0x34]); // Incomplete 11 bytes
+
+ // Assemble binary journal.wal
+ const totalWalLen = walFrames.reduce((acc, f) => acc + f.length, 0) + corruptedPartialFrame.length;
+ const journalWal = new Uint8Array(totalWalLen);
+ let offset = 0;
+ for (const f of walFrames) {
+ journalWal.set(f, offset);
+ offset += f.length;
+ }
+ journalWal.set(corruptedPartialFrame, offset);
+
+ // 6. Next launch: Parse journal.wal
+ const { validFrames, corruptedTail } = parseWalFrames(journalWal);
+ expect(corruptedTail).toBe(true);
+ expect(validFrames.length).toBe(5); // Strokes 11-15 recovered; stroke 16 safely discarded
+
+ // 7. Replay session data
+ const replayData: RecoveryReplayData = {
+ session_id: 'crash-hard-kill-session',
+ manifest_json: JSON.stringify({
+ sessionId: 'crash-hard-kill-session',
+ documentName: 'Acceptance Manga',
+ width: 3000,
+ height: 3000,
+ dpi: 600,
+ colorMode: 'color',
+ layers,
+ activeLayerId: 'layer-ink',
+ timestamp: Date.now(),
+ }),
+ base_snapshot: baselineSnapshot,
+ wal_entries: validFrames.map((f) => ({ entry_type: f.entryType, payload: f.payload })),
+ };
+
+ const restoredGrid = new SparseTileGrid();
+ const replayResult = recoveryService.replaySessionData(replayData, restoredGrid);
+
+ expect(replayResult.replayedStrokesCount).toBe(5);
+ expect(replayResult.manifest.documentName).toBe('Acceptance Manga');
+ expect(replayResult.manifest.width).toBe(3000);
+ expect(replayResult.manifest.height).toBe(3000);
+ expect(replayResult.manifest.dpi).toBe(600);
+ expect(replayResult.manifest.layers.length).toBe(3);
+
+ // Verify pixel-for-pixel accuracy on restoredGrid against originalGrid
+ const restoredBg = restoredGrid.getTile('layer-bg', 0, 0);
+ const originalBg = originalGrid.getTile('layer-bg', 0, 0);
+ expect(restoredBg?.data).toEqual(originalBg?.data);
+
+ const restoredSketch = restoredGrid.getTile('layer-sketch', 0, 0);
+ const originalSketch = originalGrid.getTile('layer-sketch', 0, 0);
+ expect(restoredSketch?.data).toEqual(originalSketch?.data);
+
+ const restoredInk = restoredGrid.getTile('layer-ink', 0, 0);
+ const originalInk = originalGrid.getTile('layer-ink', 0, 0);
+ expect(restoredInk?.data).toEqual(originalInk?.data);
+ });
+ });
+});
diff --git a/src/utils/__tests__/scratchDisk.test.ts b/src/utils/__tests__/scratchDisk.test.ts
new file mode 100644
index 0000000..f5b085c
--- /dev/null
+++ b/src/utils/__tests__/scratchDisk.test.ts
@@ -0,0 +1,460 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import {
+ SparseTileGrid,
+ TileMemoryManager,
+ TILE_SIZE,
+ BYTES_1BIT,
+ BYTES_8BIT,
+ BYTES_32BIT,
+ setPixel1Bit,
+ getPixel1Bit,
+ InMemoryScratchDiskDriver,
+} from '../tileEngine';
+
+describe('Production-Grade Virtual Memory & SSD Scratch Disk Engine', () => {
+ let grid: SparseTileGrid;
+ let driver: InMemoryScratchDiskDriver;
+ let memoryManager: TileMemoryManager;
+
+ beforeEach(() => {
+ grid = new SparseTileGrid();
+ driver = new InMemoryScratchDiskDriver();
+ memoryManager = new TileMemoryManager(grid, {
+ budgetMb: 1, // 1 MB budget = 4 color tiles (262,144 bytes each)
+ driver,
+ sessionId: 'test-scratch-session',
+ });
+ grid.setMemoryManager(memoryManager);
+ });
+
+ // ==========================================================================
+ // Pillar 1: LRU Eviction Ordering & RAM Budget Threshold Enforcement
+ // ==========================================================================
+ describe('Pillar 1: LRU Eviction Ordering and RAM Budget Threshold Enforcement', () => {
+ it('strictly caps active RAM consumption below the configured budget', async () => {
+ // 1 MB budget = 1,048,576 bytes = 4 color-32bit tiles (256 KB each)
+ expect(memoryManager.getBudgetBytes()).toBe(1024 * 1024);
+
+ // Allocate 6 color tiles (1.5 MB total, exceeding 1 MB budget)
+ for (let i = 0; i < 6; i++) {
+ const tile = grid.getOrCreateTile('layer-1', i, 0, 'color-32bit');
+ tile.data!.fill(i + 1);
+ tile.dirty = false;
+ }
+
+ await memoryManager.checkBudgetAndEvict();
+
+ // Active RAM must be within budget (<= 90% target threshold = 943,718 bytes, or <= 1 MB)
+ expect(memoryManager.getActiveMemoryBytes()).toBeLessThanOrEqual(memoryManager.getBudgetBytes());
+
+ const stats = grid.getMemoryStats();
+ expect(stats.activeBytes).toBeLessThanOrEqual(memoryManager.getBudgetBytes());
+ expect(stats.pagedTileCount).toBeGreaterThan(0);
+ expect(stats.activeTileCount).toBeLessThan(6);
+ });
+
+ it('prioritizes evicting hidden layers before visible layers', async () => {
+ // Layer 1: Visible (active layer)
+ // Layer 2: Hidden
+ const visibility = new Map<string, boolean>([
+ ['layer-visible', true],
+ ['layer-hidden', false],
+ ]);
+
+ memoryManager.updateViewport(
+ { minX: 0, minY: 0, maxX: 512, maxY: 512 },
+ 'layer-visible',
+ visibility
+ );
+
+ // Allocate 2 tiles on visible layer
+ const vis1 = grid.getOrCreateTile('layer-visible', 0, 0, 'color-32bit');
+ vis1.data!.fill(10);
+ vis1.dirty = false;
+
+ const vis2 = grid.getOrCreateTile('layer-visible', 1, 0, 'color-32bit');
+ vis2.data!.fill(20);
+ vis2.dirty = false;
+
+ // Allocate 3 tiles on hidden layer (pushes active RAM over 1MB budget)
+ const hid1 = grid.getOrCreateTile('layer-hidden', 0, 0, 'color-32bit');
+ hid1.data!.fill(100);
+ hid1.dirty = false;
+
+ const hid2 = grid.getOrCreateTile('layer-hidden', 1, 0, 'color-32bit');
+ hid2.data!.fill(101);
+ hid2.dirty = false;
+
+ const hid3 = grid.getOrCreateTile('layer-hidden', 2, 0, 'color-32bit');
+ hid3.data!.fill(102);
+ hid3.dirty = false;
+
+ await memoryManager.checkBudgetAndEvict();
+
+ // Hidden layer tiles should be evicted first!
+ expect(hid1.data).toBeNull();
+ expect(hid1.isPagedToDisk).toBe(true);
+
+ // Visible active tiles should still be active in memory
+ expect(vis1.data).not.toBeNull();
+ expect(vis2.data).not.toBeNull();
+ });
+
+ it('prioritizes evicting tiles farthest outside the viewport frustum', async () => {
+ // Frustum covers document [0..512, 0..512] -> tiles (0,0) to (1,1)
+ memoryManager.updateViewport(
+ { minX: 0, minY: 0, maxX: 512, maxY: 512 },
+ 'layer-art',
+ new Map([['layer-art', true]])
+ );
+
+ // In-frustum tile (0, 0)
+ const inFrustum = grid.getOrCreateTile('layer-art', 0, 0, 'color-32bit');
+ inFrustum.data!.fill(1);
+ inFrustum.dirty = false;
+
+ // Near outside frustum (3, 0)
+ const nearOutside = grid.getOrCreateTile('layer-art', 3, 0, 'color-32bit');
+ nearOutside.data!.fill(2);
+ nearOutside.dirty = false;
+
+ // Far outside frustum (20, 20)
+ const farOutside = grid.getOrCreateTile('layer-art', 20, 20, 'color-32bit');
+ farOutside.data!.fill(3);
+ farOutside.dirty = false;
+
+ // Far outside frustum (30, 30)
+ const farthestOutside = grid.getOrCreateTile('layer-art', 30, 30, 'color-32bit');
+ farthestOutside.data!.fill(4);
+ farthestOutside.dirty = false;
+
+ // Another in-frustum tile
+ const inFrustum2 = grid.getOrCreateTile('layer-art', 1, 1, 'color-32bit');
+ inFrustum2.data!.fill(5);
+ inFrustum2.dirty = false;
+
+ await memoryManager.checkBudgetAndEvict();
+
+ // The farthest outside tile (30, 30) must be evicted first
+ expect(farthestOutside.data).toBeNull();
+ expect(farthestOutside.isPagedToDisk).toBe(true);
+
+ // In-frustum tiles are protected
+ expect(inFrustum.data).not.toBeNull();
+ expect(inFrustum2.data).not.toBeNull();
+ });
+ });
+
+ // ==========================================================================
+ // Pillar 2: Lossless Round-Trip Byte Integrity
+ // ==========================================================================
+ describe('Pillar 2: Lossless Round-Trip Byte Integrity Across Formats', () => {
+ it('losslessly round-trips 1-bit monochrome tiles (8 KB)', async () => {
+ const tile = grid.getOrCreateTile('layer-mono', 5, 5, 'monochrome-1bit');
+ expect(tile.data!.byteLength).toBe(BYTES_1BIT);
+
+ // Draw custom binary ink pattern with isolated pixels and bit runs
+ setPixel1Bit(tile.data!, 0, 0, true);
+ setPixel1Bit(tile.data!, 7, 0, true);
+ setPixel1Bit(tile.data!, 128, 64, true);
+ setPixel1Bit(tile.data!, 255, 255, true);
+
+ // Save a copy of the original raw bytes
+ const originalBytes = new Uint8Array(tile.data!);
+
+ // Evict to scratch disk
+ await memoryManager.evictTiles([tile]);
+ expect(tile.data).toBeNull();
+ expect(tile.isPagedToDisk).toBe(true);
+
+ // Transparent Page-In
+ const pagedIn = await memoryManager.requestTileData(tile);
+ expect(pagedIn.byteLength).toBe(BYTES_1BIT);
+ expect(tile.data).not.toBeNull();
+
+ // Bit-for-bit, byte-for-byte lossless verification
+ expect(Array.from(tile.data!)).toEqual(Array.from(originalBytes));
+ expect(getPixel1Bit(tile.data!, 0, 0)).toBe(1);
+ expect(getPixel1Bit(tile.data!, 7, 0)).toBe(1);
+ expect(getPixel1Bit(tile.data!, 128, 64)).toBe(1);
+ expect(getPixel1Bit(tile.data!, 255, 255)).toBe(1);
+ expect(getPixel1Bit(tile.data!, 1, 0)).toBe(0);
+ });
+
+ it('losslessly round-trips 8-bit grayscale tiles (64 KB)', async () => {
+ const tile = grid.getOrCreateTile('layer-gray', 2, 2, 'grayscale-8bit');
+ expect(tile.data!.byteLength).toBe(BYTES_8BIT);
+
+ // Fill with tonal gradient pattern
+ for (let i = 0; i < BYTES_8BIT; i++) {
+ tile.data![i] = i % 256;
+ }
+ const originalBytes = new Uint8Array(tile.data!);
+
+ // Evict to scratch disk
+ await memoryManager.evictTiles([tile]);
+ expect(tile.data).toBeNull();
+ expect(tile.isPagedToDisk).toBe(true);
+
+ // Transparent Page-In
+ await memoryManager.requestTileData(tile);
+ expect(tile.data).not.toBeNull();
+ expect(Array.from(tile.data!)).toEqual(Array.from(originalBytes));
+ });
+
+ it('losslessly round-trips 32-bit color tiles (256 KB)', async () => {
+ const tile = grid.getOrCreateTile('layer-color', 1, 1, 'color-32bit');
+ expect(tile.data!.byteLength).toBe(BYTES_32BIT);
+
+ // Fill with RGBA test values
+ for (let i = 0; i < BYTES_32BIT; i += 4) {
+ tile.data![i] = (i * 3) & 0xff; // R
+ tile.data![i + 1] = (i * 7) & 0xff; // G
+ tile.data![i + 2] = (i * 11) & 0xff; // B
+ tile.data![i + 3] = 255; // A
+ }
+ const originalBytes = new Uint8Array(tile.data!);
+
+ // Evict to scratch disk
+ await memoryManager.evictTiles([tile]);
+ expect(tile.data).toBeNull();
+ expect(tile.isPagedToDisk).toBe(true);
+
+ // Transparent Page-In
+ await memoryManager.requestTileData(tile);
+ expect(tile.data).not.toBeNull();
+ expect(Array.from(tile.data!)).toEqual(Array.from(originalBytes));
+ });
+ });
+
+ // ==========================================================================
+ // Pillar 3: On-Demand Mipmap Tile Pyramid (LOD 0 to LOD 3)
+ // ==========================================================================
+ describe('Pillar 3: Multi-Resolution Mipmap Tile Pyramid Generation', () => {
+ it('correctly downsamples 2x2 LOD 0 tiles into a single 256x256 LOD 1 tile', () => {
+ // Setup 4 quadrants at LOD 0
+ // (0, 0): Solid Red
+ const c00 = grid.getOrCreateTile('layer-mipmap', 0, 0, 'color-32bit', 0);
+ for (let i = 0; i < BYTES_32BIT; i += 4) {
+ c00.data![i] = 255; // R
+ c00.data![i + 1] = 0;
+ c00.data![i + 2] = 0;
+ c00.data![i + 3] = 255;
+ }
+
+ // (1, 0): Solid Green
+ const c10 = grid.getOrCreateTile('layer-mipmap', 1, 0, 'color-32bit', 0);
+ for (let i = 0; i < BYTES_32BIT; i += 4) {
+ c10.data![i] = 0;
+ c10.data![i + 1] = 255; // G
+ c10.data![i + 2] = 0;
+ c10.data![i + 3] = 255;
+ }
+
+ // (0, 1): Solid Blue
+ const c01 = grid.getOrCreateTile('layer-mipmap', 0, 1, 'color-32bit', 0);
+ for (let i = 0; i < BYTES_32BIT; i += 4) {
+ c01.data![i] = 0;
+ c01.data![i + 1] = 0;
+ c01.data![i + 2] = 255; // B
+ c01.data![i + 3] = 255;
+ }
+
+ // (1, 1): Solid Yellow
+ const c11 = grid.getOrCreateTile('layer-mipmap', 1, 1, 'color-32bit', 0);
+ for (let i = 0; i < BYTES_32BIT; i += 4) {
+ c11.data![i] = 255; // R
+ c11.data![i + 1] = 255; // G
+ c11.data![i + 2] = 0;
+ c11.data![i + 3] = 255;
+ }
+
+ // Generate LOD 1 tile (0, 0)
+ const lod1 = grid.generateLodTile('layer-mipmap', 0, 0, 1);
+ expect(lod1).not.toBeNull();
+ expect(lod1!.lod).toBe(1);
+ expect(lod1!.data!.byteLength).toBe(BYTES_32BIT);
+
+ // Verify Quadrant 0 (top-left, x: 0..127, y: 0..127): should be Red (255, 0, 0, 255)
+ const pTL = (10 * TILE_SIZE + 10) * 4;
+ expect(lod1!.data![pTL]).toBe(255);
+ expect(lod1!.data![pTL + 1]).toBe(0);
+ expect(lod1!.data![pTL + 2]).toBe(0);
+ expect(lod1!.data![pTL + 3]).toBe(255);
+
+ // Verify Quadrant 1 (top-right, x: 128..255, y: 0..127): should be Green (0, 255, 0, 255)
+ const pTR = (10 * TILE_SIZE + 140) * 4;
+ expect(lod1!.data![pTR]).toBe(0);
+ expect(lod1!.data![pTR + 1]).toBe(255);
+ expect(lod1!.data![pTR + 2]).toBe(0);
+ expect(lod1!.data![pTR + 3]).toBe(255);
+
+ // Verify Quadrant 2 (bottom-left, x: 0..127, y: 128..255): should be Blue (0, 0, 255, 255)
+ const pBL = (140 * TILE_SIZE + 10) * 4;
+ expect(lod1!.data![pBL]).toBe(0);
+ expect(lod1!.data![pBL + 1]).toBe(0);
+ expect(lod1!.data![pBL + 2]).toBe(255);
+ expect(lod1!.data![pBL + 3]).toBe(255);
+
+ // Verify Quadrant 3 (bottom-right, x: 128..255, y: 128..255): should be Yellow (255, 255, 0, 255)
+ const pBR = (140 * TILE_SIZE + 140) * 4;
+ expect(lod1!.data![pBR]).toBe(255);
+ expect(lod1!.data![pBR + 1]).toBe(255);
+ expect(lod1!.data![pBR + 2]).toBe(0);
+ expect(lod1!.data![pBR + 3]).toBe(255);
+ });
+
+ it('recursively generates LOD 2 (1/4 scale) and LOD 3 (1/8 scale) tiles', () => {
+ // Paint at LOD 0
+ const tile = grid.getOrCreateTile('layer-pyr', 0, 0, 'color-32bit', 0);
+ tile.data!.fill(200);
+
+ // Generate LOD 2
+ const lod2 = grid.generateLodTile('layer-pyr', 0, 0, 2);
+ expect(lod2).not.toBeNull();
+ expect(lod2!.lod).toBe(2);
+
+ // Generate LOD 3
+ const lod3 = grid.generateLodTile('layer-pyr', 0, 0, 3);
+ expect(lod3).not.toBeNull();
+ expect(lod3!.lod).toBe(3);
+ });
+
+ it('marks higher LOD tiles as dirty when drawing modifies LOD 0', () => {
+ const tile = grid.getOrCreateTile('layer-paint', 4, 6, 'color-32bit', 0);
+ tile.data!.fill(50);
+ grid.markLodAncestorsDirty('layer-paint', 4, 6);
+
+ // LOD 1 (2, 3), LOD 2 (1, 1), LOD 3 (0, 0)
+ expect(grid.hasTile('layer-paint', 2, 3, 1)).toBe(false);
+
+ // Flush dirty mipmaps
+ grid.flushMipmaps('layer-paint');
+
+ expect(grid.hasTile('layer-paint', 2, 3, 1)).toBe(true);
+ expect(grid.hasTile('layer-paint', 1, 1, 2)).toBe(true);
+ expect(grid.hasTile('layer-paint', 0, 0, 3)).toBe(true);
+ });
+ });
+
+ // ==========================================================================
+ // Pillar 4: Simulated Manga B4 600 DPI (7016 x 9921 px, 20 Layers)
+ // ==========================================================================
+ describe('Pillar 4: Simulated Manga B4 600 DPI Canvas with 20 Layers', () => {
+ it('maintains active RAM strictly within configured budget across 20 layers without crash', async () => {
+ const B4_WIDTH = 7016;
+ const B4_HEIGHT = 9921;
+ const LAYER_COUNT = 20;
+
+ // 7016 x 9921 px canvas = 28 x 39 tiles = 1,092 tiles per layer
+ const tilesAcross = Math.ceil(B4_WIDTH / TILE_SIZE);
+ const tilesDown = Math.ceil(B4_HEIGHT / TILE_SIZE);
+ expect(tilesAcross).toBe(28);
+ expect(tilesDown).toBe(39);
+
+ // Configure a strict 16 MB RAM budget
+ // 16 MB = 64 color tiles (256 KB each) or 256 gray tiles (64 KB each)
+ memoryManager.setBudgetMb(16);
+ expect(memoryManager.getBudgetBytes()).toBe(16 * 1024 * 1024);
+
+ // Viewport is centered on page center [3000..4000, 4000..5000]
+ memoryManager.updateViewport(
+ { minX: 3000, minY: 4000, maxX: 4000, maxY: 5000 },
+ 'layer-active',
+ new Map()
+ );
+
+ // Simulate drawing on 20 layers across diverse regions of the 70 MP page
+ let totalTilesCreated = 0;
+ for (let l = 0; l < LAYER_COUNT; l++) {
+ const layerId = `layer-${l}`;
+ // Create 10 tiles per layer in various quadrants (200 tiles total)
+ for (let t = 0; t < 10; t++) {
+ const tx = (t * 2) % tilesAcross;
+ const ty = (l * 2 + t) % tilesDown;
+
+ const tile = grid.getOrCreateTile(layerId, tx, ty, 'color-32bit', 0);
+ tile.data!.fill((l * 10 + t) & 0xff);
+ tile.dirty = false;
+ totalTilesCreated++;
+ }
+ }
+
+ expect(totalTilesCreated).toBe(200);
+
+ // Run budget enforcement eviction pass
+ await memoryManager.checkBudgetAndEvict();
+
+ const stats = grid.getMemoryStats();
+
+ // Peak active RAM must remain strictly <= 16 MB budget!
+ expect(stats.activeBytes).toBeLessThanOrEqual(memoryManager.getBudgetBytes());
+
+ // Excess tiles must have been transparently offloaded to scratch disk
+ expect(stats.pagedTileCount).toBeGreaterThan(0);
+ expect(stats.pagedBytes).toBeGreaterThan(0);
+
+ // Transparent Page-In test: pick an evicted tile and request it back
+ const allTiles = grid.getAllTiles().filter((t) => t.lod === 0);
+ const pagedTile = allTiles.find((t) => t.data === null && t.isPagedToDisk);
+ expect(pagedTile).toBeDefined();
+
+ if (pagedTile) {
+ const recoveredData = await memoryManager.requestTileData(pagedTile);
+ expect(recoveredData).not.toBeNull();
+ expect(recoveredData.byteLength).toBe(BYTES_32BIT);
+ expect(pagedTile.data).not.toBeNull();
+ }
+ });
+
+ it('compositor correctly calculates intersecting tile ranges and selects optimal LOD for zoom scale', () => {
+ // Verify LOD math:
+ // zoom <= 12.5% -> LOD 3 (2048x2048 doc area)
+ // zoom <= 25% -> LOD 2 (1024x1024 doc area)
+ // zoom <= 50% -> LOD 1 (512x512 doc area)
+ // zoom > 50% -> LOD 0 (256x256 doc area)
+
+ const frustum = { minX: 1000, minY: 2000, maxX: 3000, maxY: 4000 };
+
+ // Zoom 10% -> LOD 3
+ const zoom10 = 0.10;
+ const lod10 = zoom10 <= 0.125 ? 3 : zoom10 <= 0.25 ? 2 : zoom10 <= 0.5 ? 1 : 0;
+ expect(lod10).toBe(3);
+ const lodDocSize3 = TILE_SIZE << 3; // 2048
+ const startX3 = Math.floor(frustum.minX / lodDocSize3);
+ const endX3 = Math.floor(frustum.maxX / lodDocSize3);
+ expect(startX3).toBe(0);
+ expect(endX3).toBe(1);
+
+ // Zoom 20% -> LOD 2
+ const zoom20 = 0.20;
+ const lod20 = zoom20 <= 0.125 ? 3 : zoom20 <= 0.25 ? 2 : zoom20 <= 0.5 ? 1 : 0;
+ expect(lod20).toBe(2);
+ const lodDocSize2 = TILE_SIZE << 2; // 1024
+ const startX2 = Math.floor(frustum.minX / lodDocSize2);
+ const endX2 = Math.floor(frustum.maxX / lodDocSize2);
+ expect(startX2).toBe(0);
+ expect(endX2).toBe(2);
+
+ // Zoom 40% -> LOD 1
+ const zoom40 = 0.40;
+ const lod40 = zoom40 <= 0.125 ? 3 : zoom40 <= 0.25 ? 2 : zoom40 <= 0.5 ? 1 : 0;
+ expect(lod40).toBe(1);
+ const lodDocSize1 = TILE_SIZE << 1; // 512
+ const startX1 = Math.floor(frustum.minX / lodDocSize1);
+ const endX1 = Math.floor(frustum.maxX / lodDocSize1);
+ expect(startX1).toBe(1);
+ expect(endX1).toBe(5);
+
+ // Zoom 100% -> LOD 0
+ const zoom100 = 1.0;
+ const lod0 = zoom100 <= 0.125 ? 3 : zoom100 <= 0.25 ? 2 : zoom100 <= 0.5 ? 1 : 0;
+ expect(lod0).toBe(0);
+ const lodDocSize0 = TILE_SIZE << 0; // 256
+ const startX0 = Math.floor(frustum.minX / lodDocSize0);
+ const endX0 = Math.floor(frustum.maxX / lodDocSize0);
+ expect(startX0).toBe(3);
+ expect(endX0).toBe(11);
+ });
+ });
+});
diff --git a/src/utils/__tests__/settings.test.ts b/src/utils/__tests__/settings.test.ts
index 49c0ea7..314f2a0 100644
--- a/src/utils/__tests__/settings.test.ts
+++ b/src/utils/__tests__/settings.test.ts
@@ -1,9 +1,11 @@
import { describe, it, expect, beforeEach } from 'vitest';
import {
DEFAULT_APP_SETTINGS,
+ DEFAULT_ACCENT_HEX,
loadAppSettings,
saveAppSettings,
resolveModernAccentColor,
+ getAccentContrastColor,
hexToRgb,
MODERN_ACCENTS,
} from '../../types/settings';
@@ -25,11 +27,12 @@ describe('settings theme & accent system', () => {
};
});
- it('loads default settings when storage is empty', () => {
+ it('loads minimalist default settings with neutral #e5e5e5 accent when storage is empty', () => {
const settings = loadAppSettings();
- expect(settings.themePreset).toBe('vintage-manga');
- expect(settings.modernAccent).toBe('blue');
- expect(settings.modernCustomColor).toBe('#3b82f6');
+ expect(settings.themePreset).toBe('modern');
+ expect(settings.modernAccent).toBe('neutral');
+ expect(settings.modernCustomColor).toBe('#e5e5e5');
+ expect(resolveModernAccentColor(settings.modernAccent)).toBe(DEFAULT_ACCENT_HEX);
});
it('correctly loads and persists modern theme with presets', () => {
@@ -45,6 +48,7 @@ describe('settings theme & accent system', () => {
});
it('correctly resolves preset accent hex codes', () => {
+ expect(resolveModernAccentColor('neutral')).toBe(MODERN_ACCENTS.neutral.hex);
expect(resolveModernAccentColor('blue')).toBe(MODERN_ACCENTS.blue.hex);
expect(resolveModernAccentColor('burgundy')).toBe(MODERN_ACCENTS.burgundy.hex);
expect(resolveModernAccentColor('green')).toBe(MODERN_ACCENTS.green.hex);
@@ -52,12 +56,18 @@ describe('settings theme & accent system', () => {
expect(resolveModernAccentColor('orange')).toBe(MODERN_ACCENTS.orange.hex);
});
- it('handles custom accent color with validation fallback', () => {
+ it('handles custom accent color with validation fallback to #e5e5e5', () => {
expect(resolveModernAccentColor('custom', '#123456')).toBe('#123456');
- expect(resolveModernAccentColor('custom', 'invalid-hex')).toBe('#3b82f6');
+ expect(resolveModernAccentColor('custom', 'invalid-hex')).toBe('#e5e5e5');
+ });
+
+ it('computes high-contrast foreground text color for light and dark accents', () => {
+ expect(getAccentContrastColor('#e5e5e5')).toBe('#161616');
+ expect(getAccentContrastColor('#3b82f6')).toBe('#e5e5e5');
});
it('converts hex strings to valid RGB objects', () => {
+ expect(hexToRgb('#e5e5e5')).toEqual({ r: 229, g: 229, b: 229 });
expect(hexToRgb('#3b82f6')).toEqual({ r: 59, g: 130, b: 246 });
expect(hexToRgb('#fff')).toEqual({ r: 255, g: 255, b: 255 });
expect(hexToRgb('invalid')).toBeNull();
@@ -74,6 +84,6 @@ describe('settings theme & accent system', () => {
...DEFAULT_APP_SETTINGS,
uiTone: 'invalid-tone' as any,
});
- expect(loadAppSettings().uiTone).toBe('slate');
+ expect(loadAppSettings().uiTone).toBe('charcoal');
});
});
diff --git a/src/utils/__tests__/strokeHandshake.test.ts b/src/utils/__tests__/strokeHandshake.test.ts
index bf50f18..be815ae 100644
--- a/src/utils/__tests__/strokeHandshake.test.ts
+++ b/src/utils/__tests__/strokeHandshake.test.ts
@@ -142,4 +142,53 @@ describe('Zero-Flicker Stroke Handshake & WYSIWYG Monochrome Pipeline', () => {
// Final point should taper close to minimum
expect(flick.points[flick.count - 1].width).toBeLessThan(5);
});
+
+ it('preserves monochrome-1bit strokes across LOD 1, 2, and 3 mipmaps on large manga canvases', () => {
+ const layerId = 'layer-mono-manga';
+ const blankCanvas = {
+ width: 7016,
+ height: 9921,
+ __isBlank: true,
+ } as unknown as HTMLCanvasElement;
+
+ // 1. Ingest blank large monochrome canvas (simulating new B4 600 DPI manga document)
+ grid.ingestCanvas(layerId, blankCanvas, 'monochrome-1bit');
+ expect(grid.getLayerFormat(layerId)).toBe('monochrome-1bit');
+
+ // 2. Commit first black ink stroke at (300, 300) via writeImageData
+ const stroke1 = new Uint8ClampedArray(20 * 20 * 4);
+ for (let i = 0; i < 20 * 20; i++) {
+ stroke1[i * 4 + 3] = 255; // Solid black (R=0,G=0,B=0,A=255)
+ }
+ grid.writeImageData(layerId, { data: stroke1, width: 20, height: 20 }, 300, 300, 'monochrome-1bit');
+
+ // 3. Query zoomed-out LOD 1, LOD 2, and LOD 3 tiles (simulating fit-to-screen viewport compositor)
+ for (const lod of [1, 2, 3]) {
+ const lodTile = grid.generateLodTile(layerId, 0, 0, lod);
+ expect(lodTile).not.toBeNull();
+ expect(lodTile!.format).toBe('monochrome-1bit');
+ const rgba = grid.getTileAsRGBA(lodTile!);
+ let inkPixels = 0;
+ for (let i = 3; i < rgba.length; i += 4) {
+ if (rgba[i] === 255) inkPixels++;
+ }
+ expect(inkPixels).toBeGreaterThan(0);
+ }
+
+ // 4. Commit second stroke in the same LOD cluster at (420, 420) and verify dirty LOD regeneration
+ grid.writeImageData(layerId, { data: stroke1, width: 20, height: 20 }, 420, 420, 'monochrome-1bit');
+ expect(grid.isLodTileDirty(layerId, 0, 0, 1)).toBe(true);
+ expect(grid.isLodTileDirty(layerId, 0, 0, 2)).toBe(true);
+ expect(grid.isLodTileDirty(layerId, 0, 0, 3)).toBe(true);
+
+ const updatedLod2Tiles = grid.getTilesInBounds(layerId, 0, 0, 1024, 1024, 2);
+ expect(updatedLod2Tiles.length).toBe(1);
+ expect(grid.isLodTileDirty(layerId, 0, 0, 2)).toBe(false);
+ const rgbaAfterSecond = grid.getTileAsRGBA(updatedLod2Tiles[0]);
+ // Both (300>>2 = 75) and (420>>2 = 105) must have opaque black ink in LOD 2
+ const idxStroke1 = (76 * 256 + 76) * 4;
+ const idxStroke2 = (106 * 256 + 106) * 4;
+ expect(rgbaAfterSecond[idxStroke1 + 3]).toBe(255);
+ expect(rgbaAfterSecond[idxStroke2 + 3]).toBe(255);
+ });
});
diff --git a/src/utils/__tests__/tileEngine.test.ts b/src/utils/__tests__/tileEngine.test.ts
index d866f0c..54be5c5 100644
--- a/src/utils/__tests__/tileEngine.test.ts
+++ b/src/utils/__tests__/tileEngine.test.ts
@@ -36,8 +36,8 @@ describe('Sparse Virtual Tile Engine', () => {
it('correctly creates 1-bit monochrome tiles consuming exactly 8,192 bytes', () => {
const tile = createTileBuffer('layer-1', 0, 0, 'monochrome-1bit');
- expect(tile.data.byteLength).toBe(BYTES_1BIT);
- expect(tile.data.byteLength).toBe(8192);
+ expect(tile.data!.byteLength).toBe(BYTES_1BIT);
+ expect(tile.data!.byteLength).toBe(8192);
// Verify 32x memory reduction compared to 32-bit RGBA
expect(BYTES_32BIT / BYTES_1BIT).toBe(32);
@@ -45,38 +45,38 @@ describe('Sparse Virtual Tile Engine', () => {
it('correctly creates 8-bit grayscale tiles consuming exactly 65,536 bytes', () => {
const tile = createTileBuffer('layer-1', 0, 0, 'grayscale-8bit');
- expect(tile.data.byteLength).toBe(BYTES_8BIT);
- expect(tile.data.byteLength).toBe(65536);
+ expect(tile.data!.byteLength).toBe(BYTES_8BIT);
+ expect(tile.data!.byteLength).toBe(65536);
});
it('supports bitwise 1-bit pixel read and write', () => {
const tile = createTileBuffer('layer-1', 0, 0, 'monochrome-1bit');
// Initially 0
- expect(getPixel1Bit(tile.data, 0, 0)).toBe(0);
- expect(getPixel1Bit(tile.data, 7, 0)).toBe(0);
- expect(getPixel1Bit(tile.data, 8, 0)).toBe(0);
- expect(getPixel1Bit(tile.data, 255, 255)).toBe(0);
+ expect(getPixel1Bit(tile.data!, 0, 0)).toBe(0);
+ expect(getPixel1Bit(tile.data!, 7, 0)).toBe(0);
+ expect(getPixel1Bit(tile.data!, 8, 0)).toBe(0);
+ expect(getPixel1Bit(tile.data!, 255, 255)).toBe(0);
// Set pixels
- setPixel1Bit(tile.data, 0, 0, true);
- setPixel1Bit(tile.data, 7, 0, true);
- setPixel1Bit(tile.data, 8, 0, true);
- setPixel1Bit(tile.data, 255, 255, true);
+ setPixel1Bit(tile.data!, 0, 0, true);
+ setPixel1Bit(tile.data!, 7, 0, true);
+ setPixel1Bit(tile.data!, 8, 0, true);
+ setPixel1Bit(tile.data!, 255, 255, true);
- expect(getPixel1Bit(tile.data, 0, 0)).toBe(1);
- expect(getPixel1Bit(tile.data, 7, 0)).toBe(1);
- expect(getPixel1Bit(tile.data, 8, 0)).toBe(1);
- expect(getPixel1Bit(tile.data, 255, 255)).toBe(1);
+ expect(getPixel1Bit(tile.data!, 0, 0)).toBe(1);
+ expect(getPixel1Bit(tile.data!, 7, 0)).toBe(1);
+ expect(getPixel1Bit(tile.data!, 8, 0)).toBe(1);
+ expect(getPixel1Bit(tile.data!, 255, 255)).toBe(1);
// Neighboring pixel remains 0
- expect(getPixel1Bit(tile.data, 1, 0)).toBe(0);
- expect(getPixel1Bit(tile.data, 6, 0)).toBe(0);
- expect(getPixel1Bit(tile.data, 254, 255)).toBe(0);
+ expect(getPixel1Bit(tile.data!, 1, 0)).toBe(0);
+ expect(getPixel1Bit(tile.data!, 6, 0)).toBe(0);
+ expect(getPixel1Bit(tile.data!, 254, 255)).toBe(0);
// Clear pixel
- setPixel1Bit(tile.data, 7, 0, false);
- expect(getPixel1Bit(tile.data, 7, 0)).toBe(0);
+ setPixel1Bit(tile.data!, 7, 0, false);
+ expect(getPixel1Bit(tile.data!, 7, 0)).toBe(0);
});
it('accurately packs RGBA into 1-bit and unpacks back via 32-bit LUT', () => {
@@ -115,9 +115,9 @@ describe('Sparse Virtual Tile Engine', () => {
it('compresses and decompresses tile buffers via RLE losslessly', () => {
const tile = createTileBuffer('layer-ink', 2, 3, 'monochrome-1bit');
- setPixel1Bit(tile.data, 50, 50, true);
- setPixel1Bit(tile.data, 51, 50, true);
- setPixel1Bit(tile.data, 52, 50, true);
+ setPixel1Bit(tile.data!, 50, 50, true);
+ setPixel1Bit(tile.data!, 51, 50, true);
+ setPixel1Bit(tile.data!, 52, 50, true);
const serialized = serializeTileBuffer(tile);
// Highly sparse tile should compress dramatically
@@ -127,10 +127,10 @@ describe('Sparse Virtual Tile Engine', () => {
expect(deserialized.tileX).toBe(2);
expect(deserialized.tileY).toBe(3);
expect(deserialized.format).toBe('monochrome-1bit');
- expect(getPixel1Bit(deserialized.data, 50, 50)).toBe(1);
- expect(getPixel1Bit(deserialized.data, 51, 50)).toBe(1);
- expect(getPixel1Bit(deserialized.data, 52, 50)).toBe(1);
- expect(getPixel1Bit(deserialized.data, 53, 50)).toBe(0);
+ expect(getPixel1Bit(deserialized.data!, 50, 50)).toBe(1);
+ expect(getPixel1Bit(deserialized.data!, 51, 50)).toBe(1);
+ expect(getPixel1Bit(deserialized.data!, 52, 50)).toBe(1);
+ expect(getPixel1Bit(deserialized.data!, 53, 50)).toBe(0);
});
it('correctly handles multi-tile write and read in SparseTileGrid', () => {
@@ -182,7 +182,7 @@ describe('Sparse Virtual Tile Engine', () => {
// Draw something
const tile = grid.getOrCreateTile('layer-1', 0, 0, 'monochrome-1bit');
- setPixel1Bit(tile.data, 10, 10, true);
+ setPixel1Bit(tile.data!, 10, 10, true);
// Compute deltas
const deltas = grid.computeDeltasFromSnapshot(snapshot, 'layer-1', bounds);
@@ -206,7 +206,7 @@ describe('Sparse Virtual Tile Engine', () => {
grid.applyTileDeltas(restoredDeltas, 'redo');
const redoTile = grid.getTile('layer-1', 0, 0);
expect(redoTile).not.toBeNull();
- expect(getPixel1Bit(redoTile!.data, 10, 10)).toBe(1);
+ expect(getPixel1Bit(redoTile!.data!, 10, 10)).toBe(1);
});
});
diff --git a/src/utils/animationEngine.ts b/src/utils/animationEngine.ts
index a10421a..702c88d 100644
--- a/src/utils/animationEngine.ts
+++ b/src/utils/animationEngine.ts
@@ -174,45 +174,91 @@ export function renderAnimationFrame(
const activeCelLayerId = timeline.cels[frameIndex];
const allCelLayerIds = new Set(Object.values(timeline.cels));
- // 1. Render static background non-cel layers
+ // Helper to check parent folder visibility and effective opacity
+ const isEffectivelyVisible = (l: LayerItem): boolean => {
+ if (!l.visible) return false;
+ if (!l.parentId) return true;
+ const p = layers.find((item) => item.id === l.parentId);
+ return p ? isEffectivelyVisible(p) : true;
+ };
+ const getEffOpacity = (l: LayerItem): number => {
+ if (!l.parentId) return l.opacity;
+ const p = layers.find((item) => item.id === l.parentId);
+ return p ? l.opacity * getEffOpacity(p) : l.opacity;
+ };
+
+ let renderedOnionSkins = false;
+
+ // Render layers in true bottom-to-top stack order
for (let i = layers.length - 1; i >= 0; i--) {
const layer = layers[i];
- if (allCelLayerIds.has(layer.id)) continue;
- if (!layer.visible) continue;
+ if (layer.type === 'folder') continue;
+ if (!isEffectivelyVisible(layer)) continue;
+
+ if (allCelLayerIds.has(layer.id)) {
+ if (layer.id === activeCelLayerId) {
+ if (!renderedOnionSkins && includeOnionSkin && timeline.onionSkin.enabled) {
+ renderedOnionSkins = true;
+ const onionFrames = getOnionSkinFrames({
+ ...timeline,
+ currentFrame: frameIndex,
+ });
+ for (const info of onionFrames) {
+ const oc = layerCanvases.get(info.layerId);
+ if (oc) {
+ const tinted = renderTintedCanvas(oc, info.tint, info.opacity);
+ ctx.save?.();
+ ctx.globalAlpha = 1.0;
+ ctx.globalCompositeOperation = 'source-over';
+ ctx.drawImage(tinted, 0, 0);
+ ctx.restore?.();
+ }
+ }
+ }
+ const celCanvas = layerCanvases.get(activeCelLayerId);
+ if (celCanvas) {
+ ctx.save?.();
+ ctx.globalAlpha = getEffOpacity(layer);
+ ctx.globalCompositeOperation = (layer.blendMode === 'normal' || layer.blendMode === 'pass-through') ? 'source-over' : (layer.blendMode as GlobalCompositeOperation);
+ ctx.drawImage(celCanvas, 0, 0);
+ ctx.globalAlpha = 1.0;
+ ctx.globalCompositeOperation = 'source-over';
+ ctx.restore?.();
+ }
+ }
+ continue;
+ }
const c = layerCanvases.get(layer.id);
if (c) {
- ctx.globalAlpha = layer.opacity;
+ ctx.save?.();
+ ctx.globalAlpha = getEffOpacity(layer);
+ ctx.globalCompositeOperation = (layer.blendMode === 'normal' || layer.blendMode === 'pass-through') ? 'source-over' : (layer.blendMode as GlobalCompositeOperation);
ctx.drawImage(c, 0, 0);
+ ctx.globalAlpha = 1.0;
+ ctx.globalCompositeOperation = 'source-over';
+ ctx.restore?.();
}
}
- // 2. Render colored onion skin cels if requested
- if (includeOnionSkin && timeline.onionSkin.enabled) {
+ // If onion skin was requested and active frame had no cel layer in stack, still render onion skin
+ if (!renderedOnionSkins && includeOnionSkin && timeline.onionSkin.enabled) {
const onionFrames = getOnionSkinFrames({
...timeline,
currentFrame: frameIndex,
});
-
for (const info of onionFrames) {
const c = layerCanvases.get(info.layerId);
if (c) {
const tinted = renderTintedCanvas(c, info.tint, info.opacity);
+ ctx.save?.();
+ ctx.globalAlpha = 1.0;
ctx.drawImage(tinted, 0, 0);
+ ctx.restore?.();
}
}
}
- // 3. Render active frame cel
- if (activeCelLayerId) {
- const celLayer = layers.find((l) => l.id === activeCelLayerId);
- const celCanvas = layerCanvases.get(activeCelLayerId);
- if (celLayer && celCanvas && celLayer.visible) {
- ctx.globalAlpha = celLayer.opacity;
- ctx.drawImage(celCanvas, 0, 0);
- }
- }
-
return canvas;
}
@@ -433,7 +479,8 @@ export async function exportAnimationToGif(
let offset = 0;
while (offset < indexedPixels.length) {
- const blockSize = Math.min(254, indexedPixels.length - offset);
+ // Max 125 literals per Clear Code so 8-bit LZW dictionary (129 + 125 = 254 < 256) never overflows into 9-bit codes
+ const blockSize = Math.min(125, indexedPixels.length - offset);
buffer.push(blockSize + 1);
buffer.push(1 << minCodeSize); // Clear code
for (let j = 0; j < blockSize; j++) {
@@ -523,11 +570,11 @@ export async function exportAnimationToApng(
outChunks.push(new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));
if (ihdrChunk) outChunks.push(ihdrChunk);
- // acTL chunk (num_frames: 4 bytes, num_plays: 4 bytes: 0 for infinite loop)
+ // acTL chunk (num_frames: 4 bytes, num_plays: 4 bytes: 0 for infinite loop, 1 for once)
const actlData = new Uint8Array(8);
const actlDv = new DataView(actlData.buffer);
actlDv.setUint32(0, numFrames);
- actlDv.setUint32(4, 0);
+ actlDv.setUint32(4, timeline.loop === false ? 1 : 0);
outChunks.push(createChunk('acTL', actlData));
let seq = 0;
diff --git a/src/utils/balloonEngine.ts b/src/utils/balloonEngine.ts
index adfe700..7da5d80 100644
--- a/src/utils/balloonEngine.ts
+++ b/src/utils/balloonEngine.ts
@@ -200,16 +200,45 @@ export function renderSpeechBalloon(
ctx.stroke();
}
- // 3. Fill Body over tail attachment
- traceBalloonBodyPath(ctx, balloon);
- ctx.fillStyle = fillColor;
- ctx.fill();
+ // 3. Fill & Stroke Body over tail attachment
+ if (balloon.shape === 'thought') {
+ traceBalloonBodyPath(ctx, balloon);
+ ctx.fillStyle = fillColor;
+ ctx.fill();
+ if (strokeWidth > 0) {
+ ctx.strokeStyle = strokeColor;
+ ctx.lineWidth = strokeWidth;
+ ctx.stroke();
+ }
+ // Fill interior ellipse to mask inner puff circle strokes and provide solid backing behind text
+ const cx = bounds.x + bounds.width * 0.5;
+ const cy = bounds.y + bounds.height * 0.5;
+ const rx = Math.max(10, bounds.width * 0.5);
+ const ry = Math.max(10, bounds.height * 0.5);
+ const puffRadius = Math.min(rx, ry) * 0.35;
+ ctx.beginPath();
+ ctx.ellipse(
+ cx,
+ cy,
+ Math.max(4, rx - puffRadius * 0.45),
+ Math.max(4, ry - puffRadius * 0.45),
+ 0,
+ 0,
+ Math.PI * 2
+ );
+ ctx.fillStyle = fillColor;
+ ctx.fill();
+ } else {
+ traceBalloonBodyPath(ctx, balloon);
+ ctx.fillStyle = fillColor;
+ ctx.fill();
- // 4. Stroke Body
- if (strokeWidth > 0) {
- ctx.strokeStyle = strokeColor;
- ctx.lineWidth = strokeWidth;
- ctx.stroke();
+ // 4. Stroke Body
+ if (strokeWidth > 0) {
+ ctx.strokeStyle = strokeColor;
+ ctx.lineWidth = strokeWidth;
+ ctx.stroke();
+ }
}
// 5. If thought bubble, draw little thought trailing bubbles
diff --git a/src/utils/brushPresetManager.ts b/src/utils/brushPresetManager.ts
index 7e20d9a..b967dd0 100644
--- a/src/utils/brushPresetManager.ts
+++ b/src/utils/brushPresetManager.ts
@@ -1,10 +1,22 @@
-import { BrushPresetId, BrushSettings, CspBrush, BrushDynamics } from '../types/editor';
+import {
+ BrushPresetId,
+ BrushSettings,
+ CspBrush,
+ BrushDynamics,
+ CspAngleDynamicsMode,
+ CspBlendTipsMode,
+ CspPaperTextureMode,
+ CspSensorConfig,
+ CspSpraySettings,
+ CspTaperSettings,
+ CspTipFlipMode,
+} from '../types/editor';
import { getBuiltinBrushConfig } from './presetBrushes';
import { PENCIL_CONFIGS, PencilGrade } from './pencilEngine';
-import { getPreloadedTipImage } from './brushStorage';
+import { getPreloadedTipImage, getCachedCustomBrushes } from './brushStorage';
export const BRUSH_SIZE_PRESETS: number[] = [
- 0.7, 1, 1.5, 2, 2.5, 3,
+ 0.5, 0.7, 1, 1.5, 2, 2.5, 3,
4, 5, 6, 7, 8, 10,
12, 15, 17, 20, 25, 30,
40, 50, 60, 70, 80, 100,
@@ -13,6 +25,28 @@ export const BRUSH_SIZE_PRESETS: number[] = [
1200, 1500, 1700, 2000,
];
+/**
+ * Steps the given brush size down (-1) or up (+1) through BRUSH_SIZE_PRESETS cleanly.
+ */
+export function stepBrushSizePreset(currentSize: number, direction: -1 | 1): number {
+ const eps = 0.04;
+ if (direction > 0) {
+ for (let i = 0; i < BRUSH_SIZE_PRESETS.length; i++) {
+ if (BRUSH_SIZE_PRESETS[i] > currentSize + eps) {
+ return BRUSH_SIZE_PRESETS[i];
+ }
+ }
+ return BRUSH_SIZE_PRESETS[BRUSH_SIZE_PRESETS.length - 1];
+ } else {
+ for (let i = BRUSH_SIZE_PRESETS.length - 1; i >= 0; i--) {
+ if (BRUSH_SIZE_PRESETS[i] < currentSize - eps) {
+ return BRUSH_SIZE_PRESETS[i];
+ }
+ }
+ return BRUSH_SIZE_PRESETS[0];
+ }
+}
+
export const STORAGE_KEY_SETTINGS = 'sora_paint_brush_settings_by_id';
export const STORAGE_KEY_ACTIVE_PRESET = 'sora_paint_active_brush_preset';
export const STORAGE_KEY_BOTTOM_TAB = 'sora_paint_left_bottom_tab';
@@ -24,24 +58,35 @@ export interface BrushPersistentSettings {
minSizeFactor?: number;
opacity?: number;
flow?: number;
+ brushDensity?: number;
+ adjustDensityByGap?: boolean;
+ blendTipsMode?: CspBlendTipsMode;
spacing?: number;
hardness?: number;
grain?: number;
stabilization?: number;
+ postCorrection?: number;
+ sharpCorners?: boolean;
usePressure?: boolean;
useVelocity?: boolean;
+ useTilt?: boolean;
+ tiltScale?: number;
smoothing?: boolean;
thickness?: number;
thicknessVertical?: boolean;
antiAlias?: number;
+ flipH?: CspTipFlipMode;
+ flipV?: CspTipFlipMode;
+ isRibbon?: boolean;
customTipAngle?: number;
- customTipAngleDynamics?: 'none' | 'direction' | 'random';
+ customTipAngleDynamics?: CspAngleDynamicsMode;
customTipRotationRandomScale?: number;
colorMixing?: boolean;
+ perceptualMixing?: boolean;
amountOfPaint?: number;
densityOfPaint?: number;
colorStretch?: number;
- mixingMode?: 'blend' | 'running_color';
+ mixingMode?: 'blend' | 'running_color' | 'smear';
wetEdge?: number;
wetEdgeRadius?: number;
wetEdgeAlphaPower?: number;
@@ -49,6 +94,17 @@ export interface BrushPersistentSettings {
textureDensity?: number;
paperTextureScale?: number;
paperTextureRotate?: number;
+ paperTextureMode?: CspPaperTextureMode;
+ paperTextureBrightness?: number;
+ paperTextureContrast?: number;
+ paperTextureInverted?: boolean;
+ pressureCurve?: [number, number][];
+ velocityCurve?: [number, number][];
+ sizeSensor?: CspSensorConfig;
+ opacitySensor?: CspSensorConfig;
+ densitySensor?: CspSensorConfig;
+ spray?: CspSpraySettings;
+ taper?: CspTaperSettings;
dynamics?: BrushDynamics;
}
@@ -61,18 +117,22 @@ export const DEFAULT_ERASER_SETTINGS: Partial<BrushSettings> = {
flow: 1.0,
spacing: 0.05,
hardness: 0.9,
- stabilization: 0,
+ antiAlias: 2,
+ stabilization: 4,
+ sharpCorners: true,
usePressure: true,
+ useTilt: false,
smoothing: true,
useGpu: true,
};
let _memorySettingsCache: Record<string, BrushPersistentSettings> | null = null;
+let _saveDebounceTimer: ReturnType<typeof setTimeout> | null = null;
export function loadAllSavedBrushSettings(): Record<string, BrushPersistentSettings> {
if (_memorySettingsCache) return _memorySettingsCache;
try {
- const raw = localStorage.getItem(STORAGE_KEY_SETTINGS);
+ const raw = typeof localStorage !== 'undefined' ? localStorage.getItem(STORAGE_KEY_SETTINGS) : null;
_memorySettingsCache = raw ? JSON.parse(raw) : {};
} catch {
_memorySettingsCache = {};
@@ -85,59 +145,128 @@ export function getSavedBrushSettings(presetId: string): BrushPersistentSettings
return all[presetId] || null;
}
-export function saveBrushSettingsImmediately(
- presetId: string,
- settings: Partial<BrushSettings>
-): void {
- if (!presetId) return;
- const all = loadAllSavedBrushSettings();
- const existing = all[presetId] || {};
+const PERSISTENT_KEYS: (keyof BrushPersistentSettings)[] = [
+ 'size',
+ 'minSizeFactor',
+ 'opacity',
+ 'flow',
+ 'brushDensity',
+ 'adjustDensityByGap',
+ 'blendTipsMode',
+ 'spacing',
+ 'hardness',
+ 'grain',
+ 'stabilization',
+ 'postCorrection',
+ 'sharpCorners',
+ 'usePressure',
+ 'useVelocity',
+ 'useTilt',
+ 'tiltScale',
+ 'smoothing',
+ 'thickness',
+ 'thicknessVertical',
+ 'antiAlias',
+ 'flipH',
+ 'flipV',
+ 'isRibbon',
+ 'customTipAngle',
+ 'customTipAngleDynamics',
+ 'customTipRotationRandomScale',
+ 'colorMixing',
+ 'perceptualMixing',
+ 'amountOfPaint',
+ 'densityOfPaint',
+ 'colorStretch',
+ 'mixingMode',
+ 'wetEdge',
+ 'wetEdgeRadius',
+ 'wetEdgeAlphaPower',
+ 'wetEdgeValuePower',
+ 'textureDensity',
+ 'paperTextureScale',
+ 'paperTextureRotate',
+ 'paperTextureMode',
+ 'paperTextureBrightness',
+ 'paperTextureContrast',
+ 'paperTextureInverted',
+ 'pressureCurve',
+ 'velocityCurve',
+ 'sizeSensor',
+ 'opacitySensor',
+ 'densitySensor',
+ 'spray',
+ 'taper',
+ 'dynamics',
+];
- const persistent: BrushPersistentSettings = {
- ...existing,
- };
+function mergeIntoMemoryCache(presetId: string, settings: Partial<BrushSettings>): Record<string, BrushPersistentSettings> {
+ const all = loadAllSavedBrushSettings();
+ const persistent: BrushPersistentSettings = { ...(all[presetId] || {}) };
- if (settings.size !== undefined) persistent.size = settings.size;
- if (settings.minSizeFactor !== undefined) persistent.minSizeFactor = settings.minSizeFactor;
- if (settings.opacity !== undefined) persistent.opacity = settings.opacity;
- if (settings.flow !== undefined) persistent.flow = settings.flow;
- if (settings.spacing !== undefined) persistent.spacing = settings.spacing;
- if (settings.hardness !== undefined) persistent.hardness = settings.hardness;
- if (settings.grain !== undefined) persistent.grain = settings.grain;
- if (settings.stabilization !== undefined) persistent.stabilization = settings.stabilization;
- if (settings.usePressure !== undefined) persistent.usePressure = settings.usePressure;
- if (settings.useVelocity !== undefined) persistent.useVelocity = settings.useVelocity;
- if (settings.smoothing !== undefined) persistent.smoothing = settings.smoothing;
- if (settings.thickness !== undefined) persistent.thickness = settings.thickness;
- if (settings.thicknessVertical !== undefined) persistent.thicknessVertical = settings.thicknessVertical;
- if (settings.antiAlias !== undefined) persistent.antiAlias = settings.antiAlias;
- if (settings.customTipAngle !== undefined) persistent.customTipAngle = settings.customTipAngle;
- if (settings.customTipAngleDynamics !== undefined) persistent.customTipAngleDynamics = settings.customTipAngleDynamics;
- if (settings.customTipRotationRandomScale !== undefined) persistent.customTipRotationRandomScale = settings.customTipRotationRandomScale;
- if (settings.colorMixing !== undefined) persistent.colorMixing = settings.colorMixing;
- if (settings.amountOfPaint !== undefined) persistent.amountOfPaint = settings.amountOfPaint;
- if (settings.densityOfPaint !== undefined) persistent.densityOfPaint = settings.densityOfPaint;
- if (settings.colorStretch !== undefined) persistent.colorStretch = settings.colorStretch;
- if (settings.mixingMode !== undefined) persistent.mixingMode = settings.mixingMode;
- if (settings.wetEdge !== undefined) persistent.wetEdge = settings.wetEdge;
- if (settings.wetEdgeRadius !== undefined) persistent.wetEdgeRadius = settings.wetEdgeRadius;
- if (settings.wetEdgeAlphaPower !== undefined) persistent.wetEdgeAlphaPower = settings.wetEdgeAlphaPower;
- if (settings.wetEdgeValuePower !== undefined) persistent.wetEdgeValuePower = settings.wetEdgeValuePower;
- if (settings.textureDensity !== undefined) persistent.textureDensity = settings.textureDensity;
- if (settings.paperTextureScale !== undefined) persistent.paperTextureScale = settings.paperTextureScale;
- if (settings.paperTextureRotate !== undefined) persistent.paperTextureRotate = settings.paperTextureRotate;
- if (settings.dynamics !== undefined) persistent.dynamics = settings.dynamics;
+ for (let i = 0; i < PERSISTENT_KEYS.length; i++) {
+ const key = PERSISTENT_KEYS[i];
+ const val = settings[key];
+ if (val !== undefined) {
+ (persistent as Record<string, unknown>)[key] = val;
+ }
+ }
all[presetId] = persistent;
_memorySettingsCache = all;
+ return all;
+}
+function flushMemoryCacheToStorage(): void {
+ if (!_memorySettingsCache) return;
try {
- localStorage.setItem(STORAGE_KEY_SETTINGS, JSON.stringify(all));
+ if (typeof localStorage !== 'undefined') {
+ localStorage.setItem(STORAGE_KEY_SETTINGS, JSON.stringify(_memorySettingsCache));
+ }
} catch (err) {
console.warn('Failed to persist brush settings to localStorage:', err);
}
}
+export function saveBrushSettingsImmediately(
+ presetId: string,
+ settings: Partial<BrushSettings>
+): void {
+ if (!presetId) return;
+ if (_saveDebounceTimer) {
+ clearTimeout(_saveDebounceTimer);
+ _saveDebounceTimer = null;
+ }
+ mergeIntoMemoryCache(presetId, settings);
+ flushMemoryCacheToStorage();
+}
+
+/**
+ * Updates in-memory brush settings synchronously for zero-lag reads while debouncing
+ * localStorage JSON serialization by 250ms during continuous slider drags.
+ */
+export function saveBrushSettingsDebounced(
+ presetId: string,
+ settings: Partial<BrushSettings>,
+ delayMs: number = 250
+): void {
+ if (!presetId) return;
+ mergeIntoMemoryCache(presetId, settings);
+ if (_saveDebounceTimer) clearTimeout(_saveDebounceTimer);
+ _saveDebounceTimer = setTimeout(() => {
+ _saveDebounceTimer = null;
+ flushMemoryCacheToStorage();
+ }, delayMs);
+}
+
+export function flushPendingBrushSettingsSave(): void {
+ if (_saveDebounceTimer) {
+ clearTimeout(_saveDebounceTimer);
+ _saveDebounceTimer = null;
+ flushMemoryCacheToStorage();
+ }
+}
+
export function resetBrushSettingsToDefault(
presetId: string,
customBrushes?: CspBrush[]
@@ -146,17 +275,14 @@ export function resetBrushSettingsToDefault(
if (all[presetId]) {
delete all[presetId];
_memorySettingsCache = all;
- try {
- localStorage.setItem(STORAGE_KEY_SETTINGS, JSON.stringify(all));
- } catch {
- // ignore
- }
+ flushMemoryCacheToStorage();
}
return getEffectiveBrushSettings(presetId, customBrushes);
}
export function getActivePresetId(): string {
try {
+ if (typeof localStorage === 'undefined') return DEFAULT_BRUSH_PRESET_ID;
return localStorage.getItem(STORAGE_KEY_ACTIVE_PRESET) || DEFAULT_BRUSH_PRESET_ID;
} catch {
return DEFAULT_BRUSH_PRESET_ID;
@@ -165,7 +291,9 @@ export function getActivePresetId(): string {
export function saveActivePresetId(presetId: string): void {
try {
- localStorage.setItem(STORAGE_KEY_ACTIVE_PRESET, presetId);
+ if (typeof localStorage !== 'undefined') {
+ localStorage.setItem(STORAGE_KEY_ACTIVE_PRESET, presetId);
+ }
} catch {
// ignore
}
@@ -186,17 +314,42 @@ export function getEffectiveBrushSettings(
};
}
- // 2. Custom CSP brush
- if (customBrushes && customBrushes.length > 0) {
- const cspMatch = customBrushes.find((b) => b.id === presetId);
+ // 2. Custom CSP brush (consults explicit array or global in-memory custom brush registry)
+ const effectiveCustomList =
+ customBrushes && customBrushes.length > 0 ? customBrushes : getCachedCustomBrushes();
+
+ if (effectiveCustomList.length > 0) {
+ const cspMatch = effectiveCustomList.find((b) => b.id === presetId);
if (cspMatch) {
- const tipImg = cspMatch.tipDataUrl ? getPreloadedTipImage(cspMatch.tipDataUrl) || undefined : undefined;
+ const tipImg = cspMatch.tipDataUrl
+ ? getPreloadedTipImage(cspMatch.tipDataUrl) || undefined
+ : undefined;
+ const dualTipImg = cspMatch.secondaryTipDataUrl
+ ? getPreloadedTipImage(cspMatch.secondaryTipDataUrl) || undefined
+ : undefined;
+ const paperTextureImage = cspMatch.paperTexture
+ ? getPreloadedTipImage(cspMatch.paperTexture) || undefined
+ : undefined;
+ let subTipImages: HTMLImageElement[] | undefined = undefined;
+ if (cspMatch.subTips && cspMatch.subTips.length > 0) {
+ const imgs: HTMLImageElement[] = [];
+ for (const st of cspMatch.subTips) {
+ const im = getPreloadedTipImage(st.dataUrl);
+ if (im) imgs.push(im);
+ }
+ if (imgs.length > 0) subTipImages = imgs;
+ }
+
return {
preset: cspMatch.id,
brushName: cspMatch.name,
size: cspMatch.size,
minSizeFactor: cspMatch.minSizeFactor,
flow: cspMatch.flow,
+ brushDensity: cspMatch.brushDensity,
+ adjustDensityByGap: cspMatch.adjustDensityByGap,
+ blendTipsMode: cspMatch.blendTipsMode,
+ brushCombineMode: cspMatch.brushCombineMode,
opacity: cspMatch.opacity,
spacing: cspMatch.spacing,
hardness: cspMatch.hardness,
@@ -204,22 +357,34 @@ export function getEffectiveBrushSettings(
thicknessVertical: cspMatch.thicknessVertical,
antiAlias: cspMatch.antiAlias,
stabilization: cspMatch.stabilization,
+ postCorrection: cspMatch.postCorrection,
+ sharpCorners: cspMatch.sharpCorners ?? true,
customTipDataUrl: cspMatch.tipDataUrl,
customTipImage: tipImg,
+ isColorTip: cspMatch.isColorTip,
+ flipH: cspMatch.flipH,
+ flipV: cspMatch.flipV,
customTipAngle: cspMatch.angle,
customTipAngleDynamics: cspMatch.angleDynamics,
customTipRotationRandomScale: cspMatch.rotationRandomScale,
subTips: cspMatch.subTips,
subTipOrder: cspMatch.subTipOrder,
+ subTipImages,
pressureCurve: cspMatch.pressureCurve,
velocityCurve: cspMatch.velocityCurve,
usePressure: cspMatch.usePressure,
useVelocity: cspMatch.useVelocity,
- smoothing: cspMatch.smoothing,
+ useTilt: cspMatch.useTilt ?? false,
+ tiltScale: cspMatch.tiltScale,
+ sizeSensor: cspMatch.sizeSensor,
+ opacitySensor: cspMatch.opacitySensor,
+ densitySensor: cspMatch.densitySensor,
+ smoothing: cspMatch.smoothing ?? true,
spray: cspMatch.spray,
taper: cspMatch.taper,
isRibbon: cspMatch.isRibbon,
colorMixing: cspMatch.colorMixing,
+ perceptualMixing: true,
amountOfPaint: cspMatch.amountOfPaint ?? 0.7,
densityOfPaint: cspMatch.densityOfPaint ?? 0.8,
colorStretch: cspMatch.colorStretch ?? 0.6,
@@ -229,9 +394,21 @@ export function getEffectiveBrushSettings(
wetEdgeAlphaPower: cspMatch.wetEdgeAlphaPower,
wetEdgeValuePower: cspMatch.wetEdgeValuePower,
grain: cspMatch.textureDensity ?? 0,
+ textureDensity: cspMatch.textureDensity,
paperTexture: cspMatch.paperTexture,
+ paperTextureImage,
paperTextureScale: cspMatch.paperTextureScale,
paperTextureRotate: cspMatch.paperTextureRotate,
+ paperTextureMode: cspMatch.paperTextureMode,
+ paperTextureBrightness: cspMatch.paperTextureBrightness,
+ paperTextureContrast: cspMatch.paperTextureContrast,
+ paperTextureApplyEachPlot: cspMatch.paperTextureApplyEachPlot,
+ paperTextureInverted: cspMatch.paperTextureInverted,
+ dualBrush: cspMatch.dualBrush,
+ dualTipImage: dualTipImg,
+ dualBrushCompositeMode: (cspMatch.dualBrushCompositeMode as BrushSettings['dualBrushCompositeMode']) || 'multiply',
+ dualSize: cspMatch.dualSize,
+ dualSpacing: cspMatch.dualSpacing,
useGpu: true,
...saved,
};
@@ -247,9 +424,21 @@ export function getEffectiveBrushSettings(
customTipImage: undefined,
customTipAngle: 0,
customTipAngleDynamics: 'none',
+ thickness: 1.0,
+ thicknessVertical: false,
+ flipH: 'none',
+ flipV: 'none',
+ blendTipsMode: 'darken',
+ adjustDensityByGap: false,
+ antiAlias: 2,
+ postCorrection: 0,
+ sharpCorners: true,
+ useTilt: false,
colorMixing: false,
+ perceptualMixing: true,
wetEdge: 0,
grain: 0,
+ spray: undefined,
...builtinCfg,
...saved,
};
@@ -271,8 +460,10 @@ export function getEffectiveBrushSettings(
grain: pencilConfig.grain,
spacing: pencilConfig.spacing,
usePressure: true,
+ useTilt: true,
smoothing: true,
stabilization: 15,
+ sharpCorners: true,
useGpu: true,
...saved,
};
@@ -289,8 +480,10 @@ export function getEffectiveBrushSettings(
grain: 0.95,
spacing: 0.08,
usePressure: true,
+ useTilt: true,
smoothing: true,
stabilization: 15,
+ sharpCorners: true,
useGpu: true,
...saved,
};
diff --git a/src/utils/brushPreview.ts b/src/utils/brushPreview.ts
index bb5073d..99d403e 100644
--- a/src/utils/brushPreview.ts
+++ b/src/utils/brushPreview.ts
@@ -1,8 +1,19 @@
-import { BrushPresetId, CspSpraySettings } from '../types/editor';
+import {
+ BrushPresetId,
+ CspAntiAliasLevel,
+ CspBlendTipsMode,
+ CspSpraySettings,
+ CspTipFlipMode,
+} from '../types/editor';
import { PENCIL_CONFIGS, PencilGrade, getPaperGrain, getGraphiteTipMaster } from './pencilEngine';
import { getTintedTipMaster, getRadialDabMaster, drawSingleStamp } from './stampEngine';
import { getBuiltinBrushConfig } from './presetBrushes';
-import { evaluateCspSpline } from './sutParser';
+import {
+ evaluateFastSpline,
+ dabHashFloat,
+ computeGapAdjustedAlpha,
+ resolveTipFlipSigns,
+} from '../engine/CspBrushEngine';
export interface BrushPreviewOptions {
preset?: BrushPresetId;
@@ -14,13 +25,18 @@ export interface BrushPreviewOptions {
spacing?: number;
minSizeFactor?: number;
usePressure?: boolean;
- color?: string; // default '#ffffff' for neutral preview
- backgroundColor?: string; // default 'transparent'
+ color?: string;
+ backgroundColor?: string;
isSelected?: boolean;
tool?: 'brush' | 'eraser';
customTipImage?: HTMLImageElement;
customTipAngle?: number;
thickness?: number;
+ thicknessVertical?: boolean;
+ flipH?: CspTipFlipMode;
+ flipV?: CspTipFlipMode;
+ blendTipsMode?: CspBlendTipsMode;
+ adjustDensityByGap?: boolean;
antiAlias?: number;
pressureCurve?: [number, number][];
spray?: CspSpraySettings;
@@ -31,22 +47,20 @@ export interface BrushPreviewOptions {
wetEdge?: number;
}
-// Offscreen canvas cache to guarantee zero-latency 120 FPS rendering
const previewCache = new Map<string, HTMLCanvasElement>();
-const MAX_CACHE_ENTRIES = 60;
+const MAX_CACHE_ENTRIES = 80;
-/**
- * Clamps a number between min and max.
- */
function clamp(val: number, min: number, max: number): number {
return Math.max(min, Math.min(max, val));
}
-/**
- * Calculates the display width for preview S-curves.
- * Provides natural distinction between fine leads (2px) and thick brushes (30px+)
- * without clipping or overflowing the preview canvas bounds.
- */
+function getTipCacheIdentity(tip?: HTMLImageElement): string {
+ if (!tip) return 'std';
+ const src = tip.src || '';
+ const tail = src.length > 40 ? src.slice(-40) : src;
+ return `${tip.naturalWidth || tip.width || 0}x${tip.naturalHeight || tip.height || 0}:${src.length}:${tail}`;
+}
+
export function calculatePreviewWidth(
baseSize: number,
canvasHeight: number,
@@ -58,7 +72,6 @@ export function calculatePreviewWidth(
return Math.min(canvasHeight * 0.62, 10 + Math.sqrt(baseSize) * 1.8);
}
- // In subtool list preview rows:
if (baseSize <= 3) return Math.max(1.8, baseSize * 0.95);
if (baseSize <= 8) return 3.2 + (baseSize - 3) * 0.65;
if (baseSize <= 20) return 6.8 + (baseSize - 8) * 0.45;
@@ -81,7 +94,6 @@ export function renderBrushStrokePreview(
const targetWidth = Math.round(cssWidth * dpr);
const targetHeight = Math.round(cssHeight * dpr);
- // Synchronize internal canvas buffer size
if (canvas.width !== targetWidth || canvas.height !== targetHeight) {
canvas.width = targetWidth;
canvas.height = targetHeight;
@@ -90,9 +102,11 @@ export function renderBrushStrokePreview(
const ctx = canvas.getContext('2d');
if (!ctx) return;
- const preset = options.preset || 'pencil-2b';
- const builtinCfg = !options.customTipImage && options.preset ? getBuiltinBrushConfig(options.preset) : null;
- const isPencil = preset.startsWith('pencil');
+ const preset = options.preset || (options.customTipImage ? 'custom' : 'pencil-2b');
+ const builtinCfg =
+ !options.customTipImage && options.preset ? getBuiltinBrushConfig(options.preset) : null;
+ const tipImage = options.customTipImage || builtinCfg?.customTipImage;
+ const isPencil = !tipImage && preset.startsWith('pencil');
const pencilConfig = isPencil ? PENCIL_CONFIGS[preset as PencilGrade] : null;
const size = options.size ?? pencilConfig?.defaultSize ?? builtinCfg?.size ?? 14;
@@ -100,16 +114,27 @@ export function renderBrushStrokePreview(
const opacity = options.opacity ?? builtinCfg?.opacity ?? 1.0;
const grain = options.grain ?? pencilConfig?.grain ?? builtinCfg?.grain ?? 0;
const hardness = options.hardness ?? pencilConfig?.hardness ?? builtinCfg?.hardness ?? 1.0;
- const minSizeFactor = options.minSizeFactor ?? pencilConfig?.minSizeFactor ?? builtinCfg?.minSizeFactor ?? 0.15;
+ const minSizeFactor =
+ options.minSizeFactor ?? pencilConfig?.minSizeFactor ?? builtinCfg?.minSizeFactor ?? 0.15;
const thickness = options.thickness ?? builtinCfg?.thickness ?? 1.0;
+ const thicknessVertical = Boolean(options.thicknessVertical ?? builtinCfg?.thicknessVertical);
const customTipAngle = options.customTipAngle ?? builtinCfg?.customTipAngle ?? 0;
const spacing = options.spacing ?? builtinCfg?.spacing ?? (isPencil ? 0.07 : 0.045);
+ const blendTipsMode = options.blendTipsMode ?? builtinCfg?.blendTipsMode ?? 'darken';
+ 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 strokeColor = options.color || '#ffffff';
const bgColor = options.backgroundColor || 'transparent';
- const tipImage = options.customTipImage || builtinCfg?.customTipImage;
- // Cache key
+ const curveSig = options.pressureCurve
+ ? options.pressureCurve.map((p) => `${p[0].toFixed(2)},${p[1].toFixed(2)}`).join(';')
+ : 'lin';
+
const cacheKey = [
preset,
size.toFixed(1),
@@ -117,12 +142,19 @@ export function renderBrushStrokePreview(
opacity.toFixed(2),
grain.toFixed(2),
hardness.toFixed(2),
+ minSizeFactor.toFixed(2),
thickness.toFixed(2),
+ thicknessVertical ? 'tv' : 'th',
customTipAngle.toFixed(1),
spacing.toFixed(3),
- options.antiAlias !== undefined ? String(options.antiAlias) : '2',
- options.spray?.enabled ? 'spray' : 'dab',
- tipImage ? 'custom-tip' : 'std',
+ String(aaLevel),
+ blendTipsMode,
+ adjustByGap ? 'gap1' : 'gap0',
+ options.flipH || 'n',
+ options.flipV || 'n',
+ options.spray?.enabled ? `sp:${options.spray.size}:${options.spray.density}` : 'dab',
+ getTipCacheIdentity(tipImage),
+ curveSig,
isEraser ? '1' : '0',
options.wetEdge?.toFixed(2) || '0',
options.colorMixing ? '1' : '0',
@@ -141,7 +173,6 @@ export function renderBrushStrokePreview(
return;
}
- // Create offscreen canvas for rendering
const offscreen = document.createElement('canvas');
offscreen.width = targetWidth;
offscreen.height = targetHeight;
@@ -151,7 +182,6 @@ export function renderBrushStrokePreview(
offCtx.save();
offCtx.scale(dpr, dpr);
- // Background
if (bgColor !== 'transparent') {
offCtx.fillStyle = bgColor;
offCtx.fillRect(0, 0, cssWidth, cssHeight);
@@ -159,54 +189,43 @@ export function renderBrushStrokePreview(
offCtx.clearRect(0, 0, cssWidth, cssHeight);
}
- // S-Curve Geometry (Clip Studio Paint style)
- // Starts on left, curves UP to a peak, crosses center downward, curves DOWN to trough, tapers to right
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);
- // Sample points along the S-curve
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 }[] = [];
for (let i = 0; i <= numSteps; i++) {
const u = i / numSteps;
const x = padX + u * strokeLength;
- // Classic S-curve: y = centerY - sin(2 * PI * u) * amp
const y = centerY - Math.sin(2 * Math.PI * u) * amp;
- // Calligraphic pressure envelope: peak pressure in center, tapered at ends
const sineEnv = Math.sin(Math.PI * u);
let pressure = Math.pow(Math.max(0, sineEnv), 0.75);
if (options.pressureCurve) {
- pressure = evaluateCspSpline(pressure, options.pressureCurve);
+ pressure = evaluateFastSpline(pressure, options.pressureCurve);
}
- // Dynamic tip taper for authentic pen release at the ends
- const tipFactor = Math.min(1.0, Math.sin(Math.PI * u) * 2.8);
+ const tipFactor = Math.min(1.0, sineEnv * 2.8);
const effMinSize = Math.max(0.02, minSizeFactor * tipFactor);
- const tipAlpha = Math.min(1.0, Math.sin(Math.PI * u) * 4.2);
-
- // Taper width from effMinSize to full displayWidth
- const w = Math.max(0.8, displayWidth * (effMinSize + (1 - effMinSize) * pressure));
+ 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 });
}
if (isEraser) {
- // ERASER PREVIEW:
- // Render a subtle tone band, with the eraser cleanly carving through it
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);
+ const eraserMaster = getRadialDabMaster(hardness, '#000000', true, aaLevel);
const baseAngleRad = (customTipAngle * Math.PI) / 180;
- const effSpacing = Math.max(0.02, Math.min(0.2, spacing));
+ const effSpacing = clamp(spacing, 0.02, 0.25);
let distanceAcc = 0;
for (let i = 0; i < pts.length - 1; i++) {
@@ -221,31 +240,45 @@ export function renderBrushStrokePreview(
const curW = p1.width + t * (p2.width - p1.width);
const curTipAlpha = p1.tipAlpha + t * (p2.tipAlpha - p1.tipAlpha);
- const requiredStep = Math.max(0.5, curW * effSpacing);
+ const requiredStep = Math.max(0.4, curW * effSpacing);
distanceAcc += segDist / stepCount;
if (distanceAcc >= requiredStep) {
distanceAcc = 0;
- const stampW = Math.max(1.0, curW);
- const stampH = stampW * thickness;
+ 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);
+ drawSingleStamp(
+ offCtx,
+ eraserMaster,
+ curX,
+ curY,
+ stampW,
+ stampH,
+ baseAngleRad,
+ alpha,
+ true,
+ false,
+ false,
+ false,
+ 1,
+ 1,
+ aaLevel
+ );
}
}
}
offCtx.restore();
- } else if (isPencil && pencilConfig) {
- // PENCIL PHYSICS PREVIEW:
- // Authentic cold-press paper grain tooth & micro-graphite flake distribution
- offCtx.save();
- offCtx.globalAlpha = clamp(opacity, 0.05, 1.0);
-
- const graphiteMaster = getGraphiteTipMaster(preset as PencilGrade, strokeColor);
- const baseThreshold = pencilConfig.thresholdBase;
- const sens = pencilConfig.thresholdPressureSensitivity;
- const effFlow = flow * pencilConfig.flow;
- const effSpacing = Math.max(0.02, Math.min(0.12, spacing));
+ } else if (tipImage) {
+ 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);
+ 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];
@@ -256,48 +289,78 @@ export function renderBrushStrokePreview(
const curX = p1.x + t * (p2.x - p1.x);
const curY = p1.y + t * (p2.y - p1.y);
const curW = p1.width + t * (p2.width - p1.width);
- const curP = p1.pressure + t * (p2.pressure - p1.pressure);
const curTipAlpha = p1.tipAlpha + t * (p2.tipAlpha - p1.tipAlpha);
- const requiredStep = Math.max(0.4, curW * effSpacing);
+ const requiredStep = Math.max(0.5, curW * effSpacing);
distanceAcc += segDist / stepCount;
if (distanceAcc >= requiredStep) {
distanceAcc = 0;
- const paperHeight = getPaperGrain(curX * 1.6, curY * 1.6);
- const effThreshold = Math.max(
- 15,
- baseThreshold - curP * sens + (1 - grain) * 40
- );
+ dabIdx++;
+ const baseW = Math.max(1.2, curW);
+ const stampW = thicknessVertical ? baseW * thickness : baseW;
+ const stampH = thicknessVertical ? baseW * rawAspect : baseW * rawAspect * thickness;
+ const alpha = clamp(opacity * baseFlow * curTipAlpha, 0.03, 1.0);
+ const flips = resolveTipFlipSigns(options.flipH, options.flipV, curX, curY, dabIdx);
- if (paperHeight >= effThreshold) {
- const heightFactor = Math.min(1.0, (paperHeight - effThreshold + 25) / 55);
- const dabAlpha = clamp(
- effFlow * (0.35 + 0.65 * curP) * heightFactor * curTipAlpha,
- 0.04,
- 1.0
+ 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(curX, curY, dabIdx * 32 + sp, 91));
+ const th = dabHashFloat(curX, curY, dabIdx * 32 + sp, 92) * Math.PI * 2;
+ drawSingleStamp(
+ offCtx,
+ master,
+ curX + r * Math.cos(th),
+ curY + r * Math.sin(th),
+ pSize,
+ pSize * rawAspect,
+ baseAngleRad,
+ alpha,
+ false,
+ false,
+ false,
+ false,
+ flips.signX,
+ flips.signY,
+ aaLevel,
+ blendTipsMode
+ );
+ }
+ } else {
+ drawSingleStamp(
+ offCtx,
+ master,
+ curX,
+ curY,
+ stampW,
+ stampH,
+ baseAngleRad,
+ alpha,
+ false,
+ false,
+ false,
+ false,
+ flips.signX,
+ flips.signY,
+ aaLevel,
+ blendTipsMode
);
- drawSingleStamp(offCtx, graphiteMaster, curX, curY, curW, curW, 0, dabAlpha);
- } else if (curP > 0.55) {
- const dabAlpha = clamp(effFlow * 0.16 * curP * curTipAlpha, 0.02, 1.0);
- drawSingleStamp(offCtx, graphiteMaster, curX, curY, curW, curW, 0, dabAlpha);
}
}
}
}
offCtx.restore();
- } else if (tipImage) {
- // TEXTURED CUSTOM BRUSH PREVIEW (Clip Studio Paint Tip & Builtin Presets):
- const tip = tipImage;
- const aspect =
- ((tip.naturalHeight || tip.height || 1) / (tip.naturalWidth || tip.width || 1)) * thickness;
- const baseAngleRad = (((options.customTipAngle ?? 0)) * Math.PI) / 180;
- const master = getTintedTipMaster(tip, strokeColor);
- const effSpacing = Math.max(0.02, Math.min(0.2, spacing));
-
+ } else if (isPencil && pencilConfig) {
offCtx.save();
- if (options.antiAlias === 0) {
- offCtx.imageSmoothingEnabled = false;
- }
+ offCtx.globalAlpha = clamp(opacity, 0.05, 1.0);
+
+ const graphiteMaster = getGraphiteTipMaster(preset as PencilGrade, strokeColor);
+ const baseThreshold = pencilConfig.thresholdBase;
+ const sens = pencilConfig.thresholdPressureSensitivity;
+ const effFlow = flow * pencilConfig.flow;
+ const effSpacing = clamp(spacing, 0.02, 0.12);
let distanceAcc = 0;
for (let i = 0; i < pts.length - 1; i++) {
@@ -310,50 +373,42 @@ export function renderBrushStrokePreview(
const curX = p1.x + t * (p2.x - p1.x);
const curY = p1.y + t * (p2.y - p1.y);
const curW = p1.width + t * (p2.width - p1.width);
+ const curP = p1.pressure + t * (p2.pressure - p1.pressure);
const curTipAlpha = p1.tipAlpha + t * (p2.tipAlpha - p1.tipAlpha);
- const requiredStep = Math.max(0.6, curW * effSpacing);
+ const requiredStep = Math.max(0.4, curW * effSpacing);
distanceAcc += segDist / stepCount;
if (distanceAcc >= requiredStep) {
distanceAcc = 0;
- const stampW = Math.max(1.5, curW);
- const stampH = stampW * aspect;
- const alpha = clamp(opacity * flow * curTipAlpha, 0.03, 1.0);
+ const paperHeight = getPaperGrain(curX * 1.6, curY * 1.6);
+ const effThreshold = Math.max(15, baseThreshold - curP * sens + (1 - grain) * 40);
- if (options.spray?.enabled) {
- const pSize = Math.max(1, options.spray.size || 2);
- const radius = stampW / 2;
- const count = Math.max(1, options.spray.density || 4);
- for (let sp = 0; sp < count; sp++) {
- const r = radius * Math.sqrt(Math.random());
- const th = Math.random() * Math.PI * 2;
- offCtx.drawImage(
- master,
- curX + r * Math.cos(th) - pSize / 2,
- curY + r * Math.sin(th) - (pSize * aspect) / 2,
- pSize,
- pSize * aspect
- );
- }
- } else {
- drawSingleStamp(offCtx, master, curX, curY, stampW, stampH, baseAngleRad, alpha);
+ if (paperHeight >= effThreshold) {
+ const heightFactor = Math.min(1.0, (paperHeight - effThreshold + 25) / 55);
+ const dabAlpha = clamp(
+ effFlow * (0.35 + 0.65 * curP) * heightFactor * curTipAlpha,
+ 0.04,
+ 1.0
+ );
+ drawSingleStamp(offCtx, graphiteMaster, curX, curY, curW, curW, 0, dabAlpha);
+ } else if (curP > 0.55) {
+ const dabAlpha = clamp(effFlow * 0.16 * curP * curTipAlpha, 0.02, 1.0);
+ drawSingleStamp(offCtx, graphiteMaster, curX, curY, curW, curW, 0, dabAlpha);
}
}
}
}
offCtx.restore();
} else {
- // ROUND INK & ANALYTICAL DAB BRUSH PREVIEW (Airbrush, G-Pen, Maru Pen, Turnip Pen, Flat Marker, Round):
offCtx.save();
const effHardness = clamp(hardness, 0.0, 1.0);
- const effFlow = clamp(flow, 0.01, 1.0);
- const master = getRadialDabMaster(effHardness, strokeColor);
+ 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, aaLevel);
const baseAngleRad = (customTipAngle * Math.PI) / 180;
- const effSpacing = Math.max(0.02, Math.min(0.2, spacing));
- // Optional CSP Wet Edge rim
if (options.wetEdge && options.wetEdge > 0.05) {
- const rimMaster = getRadialDabMaster(Math.min(1.0, effHardness + 0.1), strokeColor);
+ const rimMaster = getRadialDabMaster(Math.min(1.0, effHardness + 0.12), strokeColor, false, aaLevel);
let wetAcc = 0;
for (let i = 0; i < pts.length - 1; i++) {
const p1 = pts[i];
@@ -364,17 +419,39 @@ export function renderBrushStrokePreview(
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.22);
+ 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.5);
+ const requiredStep = Math.max(0.6, curW * effSpacing * 1.4);
wetAcc += segDist / stepCount;
if (wetAcc >= requiredStep) {
wetAcc = 0;
- const stampW = Math.max(1.2, curW);
- const stampH = stampW * 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);
+ 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
+ );
}
}
}
@@ -393,14 +470,32 @@ export function renderBrushStrokePreview(
const curW = p1.width + t * (p2.width - p1.width);
const curTipAlpha = p1.tipAlpha + t * (p2.tipAlpha - p1.tipAlpha);
- const requiredStep = Math.max(0.5, curW * effSpacing);
+ const requiredStep = Math.max(0.45, curW * effSpacing);
distanceAcc += segDist / stepCount;
if (distanceAcc >= requiredStep) {
distanceAcc = 0;
- const stampW = Math.max(0.8, curW);
- const stampH = stampW * thickness;
+ const baseW = Math.max(0.7, curW);
+ const stampW = thicknessVertical ? baseW * thickness : baseW;
+ const stampH = thicknessVertical ? baseW : baseW * thickness;
const alpha = clamp(opacity * effFlow * curTipAlpha, 0.02, 1.0);
- drawSingleStamp(offCtx, master, curX, curY, stampW, stampH, baseAngleRad, alpha);
+ drawSingleStamp(
+ offCtx,
+ master,
+ curX,
+ curY,
+ stampW,
+ stampH,
+ baseAngleRad,
+ alpha,
+ false,
+ false,
+ false,
+ false,
+ 1,
+ 1,
+ aaLevel,
+ blendTipsMode
+ );
}
}
}
@@ -409,11 +504,9 @@ export function renderBrushStrokePreview(
offCtx.restore();
- // Draw to target canvas
ctx.clearRect(0, 0, targetWidth, targetHeight);
ctx.drawImage(offscreen, 0, 0);
- // Cache offscreen canvas
if (previewCache.size >= MAX_CACHE_ENTRIES) {
const firstKey = previewCache.keys().next().value;
if (firstKey) previewCache.delete(firstKey);
@@ -421,9 +514,6 @@ export function renderBrushStrokePreview(
previewCache.set(cacheKey, offscreen);
}
-/**
- * Clears the brush preview offscreen cache.
- */
export function clearBrushPreviewCache() {
previewCache.clear();
}
diff --git a/src/utils/brushStorage.ts b/src/utils/brushStorage.ts
index 218b1c7..3e85de2 100644
--- a/src/utils/brushStorage.ts
+++ b/src/utils/brushStorage.ts
@@ -3,10 +3,55 @@ import { CspBrush, BrushSettings } from '../types/editor';
const DB_NAME = 'SoraPaintBrushesDB';
const DB_VERSION = 1;
const STORE_NAME = 'csp_brushes';
+const LS_KEY = 'sora_paint_custom_brushes';
+
+export const CUSTOM_BRUSHES_CHANGED_EVENT = 'ink-custom-brushes-changed';
// In-memory cache of decoded HTMLImageElements for zero-latency painting
const tipImageCache = new Map<string, HTMLImageElement>();
+// In-memory registry of loaded custom brushes so tool switches (E -> B) never lose .sut presets
+let _cachedCustomBrushes: CspBrush[] = [];
+let _hasLoadedCustomBrushes = false;
+const _debouncedBrushSaves = new Map<string, ReturnType<typeof setTimeout>>();
+
+function emitCustomBrushesChanged(): void {
+ if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function') {
+ window.dispatchEvent(new CustomEvent(CUSTOM_BRUSHES_CHANGED_EVENT));
+ }
+}
+
+function preloadAllBrushAssets(brush: CspBrush): void {
+ if (brush.tipDataUrl) {
+ preloadTipImage(brush.tipDataUrl).catch(() => {});
+ }
+ if (brush.secondaryTipDataUrl) {
+ preloadTipImage(brush.secondaryTipDataUrl).catch(() => {});
+ }
+ if (brush.subTips) {
+ for (const st of brush.subTips) {
+ if (st.dataUrl) preloadTipImage(st.dataUrl).catch(() => {});
+ }
+ }
+ if (brush.paperTexture) {
+ preloadTipImage(brush.paperTexture).catch(() => {});
+ }
+}
+
+/**
+ * Synchronous accessor for cached custom brushes.
+ */
+export function getCachedCustomBrushes(): CspBrush[] {
+ if (!_hasLoadedCustomBrushes) {
+ const fallback = loadFromLocalStorageFallback();
+ if (fallback.length > 0) {
+ _cachedCustomBrushes = fallback;
+ _hasLoadedCustomBrushes = true;
+ }
+ }
+ return _cachedCustomBrushes;
+}
+
/**
* Preloads an image element from a data URL and caches it.
*/
@@ -15,6 +60,9 @@ export function preloadTipImage(dataUrl: string): Promise<HTMLImageElement> {
if (cached && cached.complete) {
return Promise.resolve(cached);
}
+ if (typeof Image === 'undefined') {
+ return Promise.reject(new Error('Image constructor unavailable'));
+ }
return new Promise((resolve, reject) => {
const img = new Image();
@@ -73,29 +121,26 @@ export async function loadCustomBrushes(): Promise<CspBrush[]> {
request.onsuccess = () => {
const brushes: CspBrush[] = request.result || [];
- // Preload all tip images and paper textures in parallel
+ _cachedCustomBrushes = brushes;
+ _hasLoadedCustomBrushes = true;
for (const b of brushes) {
- if (b.tipDataUrl) {
- preloadTipImage(b.tipDataUrl).catch(() => {});
- }
- if (b.subTips) {
- for (const st of b.subTips) {
- if (st.dataUrl) preloadTipImage(st.dataUrl).catch(() => {});
- }
- }
- if (b.paperTexture) {
- preloadTipImage(b.paperTexture).catch(() => {});
- }
+ preloadAllBrushAssets(b);
}
resolve(brushes);
};
request.onerror = () => {
- resolve(loadFromLocalStorageFallback());
+ const fallback = loadFromLocalStorageFallback();
+ _cachedCustomBrushes = fallback;
+ _hasLoadedCustomBrushes = true;
+ resolve(fallback);
};
});
} catch {
- return loadFromLocalStorageFallback();
+ const fallback = loadFromLocalStorageFallback();
+ _cachedCustomBrushes = fallback;
+ _hasLoadedCustomBrushes = true;
+ return fallback;
}
}
@@ -103,22 +148,22 @@ export async function loadCustomBrushes(): Promise<CspBrush[]> {
* Saves or updates a Clip Studio Paint brush in persistent IndexedDB storage.
*/
export async function saveCustomBrush(brush: CspBrush): Promise<void> {
- // Preload image elements into memory immediately
- if (brush.tipDataUrl) {
- preloadTipImage(brush.tipDataUrl).catch(() => {});
- }
- if (brush.subTips) {
- for (const st of brush.subTips) {
- if (st.dataUrl) preloadTipImage(st.dataUrl).catch(() => {});
- }
- }
- if (brush.paperTexture) {
- preloadTipImage(brush.paperTexture).catch(() => {});
+ preloadAllBrushAssets(brush);
+ const existingIdx = _cachedCustomBrushes.findIndex((b) => b.id === brush.id);
+ if (existingIdx >= 0) {
+ _cachedCustomBrushes = [
+ ..._cachedCustomBrushes.slice(0, existingIdx),
+ brush,
+ ..._cachedCustomBrushes.slice(existingIdx + 1),
+ ];
+ } else {
+ _cachedCustomBrushes = [..._cachedCustomBrushes, brush];
}
+ _hasLoadedCustomBrushes = true;
try {
const db = await openDB();
- return new Promise((resolve, reject) => {
+ await new Promise<void>((resolve, reject) => {
const transaction = db.transaction([STORE_NAME], 'readwrite');
const store = transaction.objectStore(STORE_NAME);
const request = store.put(brush);
@@ -132,15 +177,45 @@ export async function saveCustomBrush(brush: CspBrush): Promise<void> {
} catch {
syncToLocalStorageFallback(brush);
}
+ emitCustomBrushesChanged();
+}
+
+/**
+ * Debounced variant of saveCustomBrush so live slider drags do not serialize Base64 blobs at 240Hz.
+ */
+export function saveCustomBrushDebounced(brush: CspBrush, delayMs: number = 350): void {
+ const existingIdx = _cachedCustomBrushes.findIndex((b) => b.id === brush.id);
+ if (existingIdx >= 0) {
+ _cachedCustomBrushes[existingIdx] = brush;
+ } else {
+ _cachedCustomBrushes.push(brush);
+ }
+ _hasLoadedCustomBrushes = true;
+
+ const prevTimer = _debouncedBrushSaves.get(brush.id);
+ if (prevTimer) clearTimeout(prevTimer);
+
+ const timer = setTimeout(() => {
+ _debouncedBrushSaves.delete(brush.id);
+ saveCustomBrush(brush).catch(() => {});
+ }, delayMs);
+ _debouncedBrushSaves.set(brush.id, timer);
}
/**
* Deletes a Clip Studio Paint brush from persistent storage.
*/
export async function deleteCustomBrush(brushId: string): Promise<void> {
+ const pending = _debouncedBrushSaves.get(brushId);
+ if (pending) {
+ clearTimeout(pending);
+ _debouncedBrushSaves.delete(brushId);
+ }
+ _cachedCustomBrushes = _cachedCustomBrushes.filter((b) => b.id !== brushId);
+
try {
const db = await openDB();
- return new Promise((resolve, reject) => {
+ await new Promise<void>((resolve, reject) => {
const transaction = db.transaction([STORE_NAME], 'readwrite');
const store = transaction.objectStore(STORE_NAME);
const request = store.delete(brushId);
@@ -154,13 +229,12 @@ export async function deleteCustomBrush(brushId: string): Promise<void> {
} catch {
removeFromLocalStorageFallback(brushId);
}
+ emitCustomBrushesChanged();
}
-// LocalStorage Fallbacks for resilient redundancy
-const LS_KEY = 'sora_paint_custom_brushes';
-
function loadFromLocalStorageFallback(): CspBrush[] {
try {
+ if (typeof localStorage === 'undefined') return [];
const data = localStorage.getItem(LS_KEY);
return data ? JSON.parse(data) : [];
} catch {
@@ -170,16 +244,18 @@ function loadFromLocalStorageFallback(): CspBrush[] {
function syncToLocalStorageFallback(brush: CspBrush) {
try {
+ if (typeof localStorage === 'undefined') return;
const current = loadFromLocalStorageFallback().filter((b) => b.id !== brush.id);
current.push(brush);
localStorage.setItem(LS_KEY, JSON.stringify(current));
} catch {
- // LocalStorage quota may be exceeded with large base64 tips
+ // LocalStorage quota may be exceeded with large base64 tips; IndexedDB remains authoritative
}
}
function removeFromLocalStorageFallback(brushId: string) {
try {
+ if (typeof localStorage === 'undefined') return;
const current = loadFromLocalStorageFallback().filter((b) => b.id !== brushId);
localStorage.setItem(LS_KEY, JSON.stringify(current));
} catch {
@@ -189,7 +265,7 @@ function removeFromLocalStorageFallback(brushId: string) {
/**
* Assembles fully resolved BrushSettings for a Clip Studio Paint brush,
- * ensuring all tips, sub-tips, curves, paper grain textures, and watercolor wet-edges are preloaded.
+ * ensuring all tips, dual-tips, sub-tips, curves, paper grain textures, and watercolor wet-edges are preloaded.
*/
export async function prepareBrushSettingsForCsp(brush: CspBrush): Promise<Partial<BrushSettings>> {
let tipImg: HTMLImageElement | undefined = undefined;
@@ -199,6 +275,13 @@ export async function prepareBrushSettingsForCsp(brush: CspBrush): Promise<Parti
(await preloadTipImage(brush.tipDataUrl).catch(() => undefined));
}
+ let dualTipImg: HTMLImageElement | undefined = undefined;
+ if (brush.secondaryTipDataUrl) {
+ dualTipImg =
+ getPreloadedTipImage(brush.secondaryTipDataUrl) ||
+ (await preloadTipImage(brush.secondaryTipDataUrl).catch(() => undefined));
+ }
+
let subTipImages: HTMLImageElement[] | undefined = undefined;
if (brush.subTips && brush.subTips.length > 0) {
subTipImages = [];
@@ -223,6 +306,10 @@ export async function prepareBrushSettingsForCsp(brush: CspBrush): Promise<Parti
size: brush.size,
minSizeFactor: brush.minSizeFactor,
flow: brush.flow,
+ brushDensity: brush.brushDensity,
+ adjustDensityByGap: brush.adjustDensityByGap,
+ blendTipsMode: brush.blendTipsMode,
+ brushCombineMode: brush.brushCombineMode,
opacity: brush.opacity,
spacing: brush.spacing,
hardness: brush.hardness,
@@ -230,8 +317,14 @@ export async function prepareBrushSettingsForCsp(brush: CspBrush): Promise<Parti
thicknessVertical: brush.thicknessVertical,
antiAlias: brush.antiAlias,
stabilization: brush.stabilization,
+ postCorrection: brush.postCorrection,
+ sharpCorners: brush.sharpCorners ?? true,
+ smoothing: brush.smoothing ?? true,
customTipDataUrl: brush.tipDataUrl,
customTipImage: tipImg,
+ isColorTip: brush.isColorTip,
+ flipH: brush.flipH,
+ flipV: brush.flipV,
customTipAngle: brush.angle,
customTipAngleDynamics: brush.angleDynamics,
customTipRotationRandomScale: brush.rotationRandomScale,
@@ -242,10 +335,16 @@ export async function prepareBrushSettingsForCsp(brush: CspBrush): Promise<Parti
velocityCurve: brush.velocityCurve,
usePressure: brush.usePressure,
useVelocity: brush.useVelocity,
+ useTilt: brush.useTilt ?? false,
+ tiltScale: brush.tiltScale,
+ sizeSensor: brush.sizeSensor,
+ opacitySensor: brush.opacitySensor,
+ densitySensor: brush.densitySensor,
spray: brush.spray,
taper: brush.taper,
isRibbon: brush.isRibbon,
colorMixing: brush.colorMixing,
+ perceptualMixing: true,
amountOfPaint: brush.amountOfPaint ?? 0.7,
densityOfPaint: brush.densityOfPaint ?? 0.8,
colorStretch: brush.colorStretch ?? 0.6,
@@ -255,11 +354,21 @@ export async function prepareBrushSettingsForCsp(brush: CspBrush): Promise<Parti
wetEdgeAlphaPower: brush.wetEdgeAlphaPower,
wetEdgeValuePower: brush.wetEdgeValuePower,
grain: brush.textureDensity ?? 0,
+ textureDensity: brush.textureDensity,
paperTexture: brush.paperTexture,
paperTextureImage,
paperTextureScale: brush.paperTextureScale,
paperTextureRotate: brush.paperTextureRotate,
+ paperTextureMode: brush.paperTextureMode,
+ paperTextureBrightness: brush.paperTextureBrightness,
+ paperTextureContrast: brush.paperTextureContrast,
+ paperTextureApplyEachPlot: brush.paperTextureApplyEachPlot,
+ paperTextureInverted: brush.paperTextureInverted,
+ dualBrush: brush.dualBrush,
+ dualTipImage: dualTipImg,
+ dualBrushCompositeMode: (brush.dualBrushCompositeMode as BrushSettings['dualBrushCompositeMode']) || 'multiply',
+ dualSize: brush.dualSize,
+ dualSpacing: brush.dualSpacing,
useGpu: true,
};
}
-
diff --git a/src/utils/canvasUtils.ts b/src/utils/canvasUtils.ts
index de1aa80..ac47859 100644
--- a/src/utils/canvasUtils.ts
+++ b/src/utils/canvasUtils.ts
@@ -11,7 +11,10 @@ import {
RadialMixingOptions,
} from './stampEngine';
import { LayerPixelSampler, PaintReservoir } from './colorMixingEngine';
-import { evaluateCspSpline } from './sutParser';
+import {
+ evaluateFastSpline,
+ applyCspPostCorrection,
+} from '../engine/CspBrushEngine';
export const CANVAS_2D_CONTEXT_OPTIONS: CanvasRenderingContext2DSettings = {
alpha: true,
@@ -31,7 +34,7 @@ export function get2DContext(
/**
* Calculates stroke width based on base brush size, pressure, pressure curve, and minimum size ratio.
- * Follows Clip Studio Paint's exact dynamics calculation.
+ * Follows Clip Studio Paint's exact dynamics calculation using O(1) LUT splines.
*/
export function calculateStrokeWidth(
baseSize: number,
@@ -47,7 +50,6 @@ export function calculateStrokeWidth(
return Math.max(0.2, baseSize * velocityScale);
}
- // Tablet stylus pressure vs mouse fallback
let effectivePressure = pressure;
if (pointerType === 'mouse') {
effectivePressure = 0.5;
@@ -58,10 +60,9 @@ export function calculateStrokeWidth(
effectivePressure = Math.max(0, Math.min(1.0, effectivePressure));
}
- // Evaluate through authentic CSP cubic Hermite spline curve if available
let curvePressure = effectivePressure;
if (pressureCurve && pressureCurve.length > 0) {
- curvePressure = evaluateCspSpline(effectivePressure, pressureCurve);
+ curvePressure = evaluateFastSpline(effectivePressure, pressureCurve);
} else if (pressureCurveGamma !== 1.0) {
curvePressure = Math.pow(Math.max(0, effectivePressure), pressureCurveGamma);
}
@@ -105,9 +106,7 @@ export function getQuadraticBezierPoint(
}
/**
- * Converts 4 Catmull-Rom spline knots (p0, p1, p2, p3) into cubic Bézier control points (c1, c2)
- * for the segment from p1 to p2.
- * Uses centripetal parameterization (alpha = 0.5) to prevent overshooting or loops on tight turns.
+ * Converts 4 Catmull-Rom spline knots (p0, p1, p2, p3) into cubic Bézier control points (c1, c2).
*/
export function catmullRomToBezier(
p0: Point,
@@ -120,7 +119,6 @@ export function catmullRomToBezier(
/**
* Draws a smooth tapered segment along a cubic Bézier curve using analytical radial dabbing.
- * Delivers professional Clip Studio Paint / Photoshop quality without line banding or shadowBlur.
*/
export function drawSmoothCubicBezierSegment(
ctx: CanvasRenderingContext2D,
@@ -197,9 +195,11 @@ export function drawDot(
isEraser: boolean = false,
hardness: number = 1.0,
flow: number = 1.0,
- mixingOptions?: RadialMixingOptions
+ mixingOptions?: RadialMixingOptions,
+ thickness: number = 1.0,
+ angleRad: number = 0
) {
- drawRadialDot(ctx, point, color, hardness, flow, isEraser, false, mixingOptions);
+ drawRadialDot(ctx, point, color, hardness, flow, isEraser, false, mixingOptions, thickness, angleRad);
}
let _sharedThumbCanvas: HTMLCanvasElement | null = null;
@@ -262,7 +262,7 @@ export function getCanvasCompositeOperation(blendMode: BlendMode): GlobalComposi
}
/**
- * Generates an efficient mini thumbnail (48px wide) for layer and history preview.
+ * Generates an efficient mini thumbnail (60px wide) for layer and history preview.
*/
export function createCanvasThumbnail(canvas: HTMLCanvasElement, preserveAlpha: boolean = false): string {
try {
@@ -281,7 +281,6 @@ export function createCanvasThumbnail(canvas: HTMLCanvasElement, preserveAlpha:
tCtx.drawImage(canvas, 0, 0, targetW, targetH);
return _sharedThumbCanvas.toDataURL('image/png');
} else {
- // Draw background white in thumbnail in case of opaque export
tCtx.fillStyle = '#ffffff';
tCtx.fillRect(0, 0, targetW, targetH);
tCtx.drawImage(canvas, 0, 0, targetW, targetH);
@@ -293,19 +292,12 @@ export function createCanvasThumbnail(canvas: HTMLCanvasElement, preserveAlpha:
}
}
-/**
- * Formats timestamp as HH:mm:ss for history entries.
- */
export function formatTime(timestamp: number | Date = Date.now()): string {
const d = typeof timestamp === 'number' ? new Date(timestamp) : timestamp;
const pad = (n: number) => n.toString().padStart(2, '0');
return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}
-/**
- * Maps a screen/viewport coordinate to canvas pixel coordinate accounting for pan, zoom, and rotation.
- * This 2D inverse affine matrix mapping guarantees 100% precision under any rotation angle.
- */
export function screenToCanvas(
clientX: number,
clientY: number,
@@ -318,11 +310,9 @@ export function screenToCanvas(
const vx = clientX - viewportRect.left;
const vy = clientY - viewportRect.top;
- // Vector from canvas center in viewport to mouse
const rx = vx - pan.x;
const ry = vy - pan.y;
- // Unrotate by -rotation
const rad = (rotation * Math.PI) / 180;
const cos = Math.cos(rad);
const sin = Math.sin(rad);
@@ -330,16 +320,12 @@ export function screenToCanvas(
const unrotX = rx * cos + ry * sin;
const unrotY = -rx * sin + ry * cos;
- // Unscale and shift by canvas center
const x = dimensions.width / 2 + unrotX / zoom;
const y = dimensions.height / 2 + unrotY / zoom;
return { x, y };
}
-/**
- * Maps a canvas pixel coordinate to screen/viewport coordinate accounting for pan, zoom, and rotation.
- */
export function canvasToScreen(
canvasX: number,
canvasY: number,
@@ -364,9 +350,6 @@ export function canvasToScreen(
};
}
-/**
- * Formats rotation angle in degrees for clean display.
- */
export function formatRotationDegrees(degrees: number): string {
let normalized = degrees % 360;
if (normalized > 180) normalized -= 360;
@@ -386,10 +369,6 @@ export interface CanvasTransformMatrix {
f: number;
}
-/**
- * Calculates the exact 2D affine transform matrix that maps document canvas coordinates
- * to the viewport draft overlay canvas pixels, accounting for pan, zoom, rotation, and DPR.
- */
export function getCanvasToViewportMatrix(
pan: { x: number; y: number },
zoom: number,
@@ -415,10 +394,6 @@ export function getCanvasToViewportMatrix(
return { a, b, c, d, e, f };
}
-/**
- * Calculates the visible bounding box of the canvas in canvas pixel coordinates
- * corresponding to the current viewport rect, pan, zoom, and rotation.
- */
export function getVisibleCanvasBounds(
viewportRect: DOMRect,
pan: { x: number; y: number },
@@ -447,10 +422,6 @@ export function getVisibleCanvasBounds(
let _reusableBakeCanvas: HTMLCanvasElement | null = null;
-/**
- * Retrieves a reusable offscreen canvas buffer for compositing dirty rectangles,
- * avoiding per-stroke memory allocation and garbage collection.
- */
export function getReusableBakeCanvas(minWidth: number, minHeight: number): HTMLCanvasElement {
if (!_reusableBakeCanvas) {
_reusableBakeCanvas = document.createElement('canvas');
@@ -464,14 +435,6 @@ export function getReusableBakeCanvas(minWidth: number, minHeight: number): HTML
return _reusableBakeCanvas;
}
-/**
- * Renders an entire completed stroke path onto the target Canvas2D context.
- * Used for baking finished strokes into the high-resolution base canvas at native DPI.
- */
-/**
- * Applies parametric in/out tapering to a stroke's point array.
- * Smooths out stroke endings when lifting the pen quickly, or when in/out taper dynamics are active.
- */
export function applyParametricTaper(
points: Point[],
options?: {
@@ -488,7 +451,6 @@ export function applyParametricTaper(
const minRatio = Math.max(0.01, Math.min(1.0, options?.minSizeFactor ?? 0.05));
const n = points.length;
- // In-taper (lead-in)
if (options?.useIn) {
const inCount = Math.min(Math.floor(n / 2), options.inCount ?? Math.min(8, n));
for (let i = 0; i < inCount; i++) {
@@ -500,7 +462,6 @@ export function applyParametricTaper(
}
}
- // Out-taper (exit / lift-off)
const useOut = options?.useOut ?? true;
if (useOut) {
let outCount = options?.outCount ?? 6;
@@ -510,7 +471,7 @@ export function applyParametricTaper(
outCount = Math.min(Math.floor(n / 2), Math.max(2, outCount));
const startIdx = n - outCount;
for (let i = startIdx; i < n; i++) {
- const step = n - 1 - i; // 0 for the very last point
+ const step = n - 1 - i;
const u = (step + 1) / (outCount + 1);
const taper = Math.sin((u * Math.PI) / 2);
const factor = minRatio + (1.0 - minRatio) * taper;
@@ -534,38 +495,61 @@ export function renderCompleteStroke(
) {
if (!points || points.length === 0) return;
+ const isMono = colorMode === 'monochrome';
+ const postCorrLevel = brushSettings.postCorrection ?? 0;
+ const postCorrectedPoints =
+ postCorrLevel > 0 && points.length >= 3
+ ? applyCspPostCorrection(points, postCorrLevel, brushSettings.sharpCorners !== false)
+ : points;
+
+ const effectivePoints = isMono
+ ? postCorrectedPoints.map((p) => (p.width < 1.25 ? { ...p, width: 1.25 } : p))
+ : postCorrectedPoints;
+
const isEraser = tool === 'eraser';
- const isPencil = !isEraser && (brushSettings.preset?.startsWith('pencil') ?? false);
+ const isPencil = !isEraser && !brushSettings.customTipImage && (brushSettings.preset?.startsWith('pencil') ?? false);
const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(brushSettings.color, colorMode);
- const strokeHardness = colorMode === 'monochrome' ? 1.0 : (brushSettings.hardness ?? 1.0);
- const strokeFlow = brushSettings.flow ?? 1.0;
+ const strokeHardness = isMono ? 1.0 : (brushSettings.hardness ?? 1.0);
+ const strokeFlow = isMono ? 1.0 : (brushSettings.flow ?? 1.0);
const strokeSpacing = brushSettings.spacing ?? 0.08;
const isTransparentInk = Boolean(brushSettings.isTransparentInk);
+ const useTilt = Boolean(brushSettings.useTilt);
- // Textured Custom Tip (Clip Studio Paint SUT Brush)
+ // Textured Custom Tip (Clip Studio Paint SUT Brush & Procedural Tip Presets)
if (brushSettings.customTipImage) {
const tipOptions: TexturedBrushOptions = {
size: brushSettings.size,
minSizeFactor: brushSettings.minSizeFactor,
opacity: brushSettings.opacity,
flow: strokeFlow,
+ adjustDensityByGap: brushSettings.adjustDensityByGap,
+ blendTipsMode: brushSettings.blendTipsMode,
spacing: strokeSpacing,
thickness: brushSettings.thickness,
thicknessVertical: brushSettings.thicknessVertical,
+ flipH: brushSettings.flipH,
+ flipV: brushSettings.flipV,
+ isColorTip: brushSettings.isColorTip,
angle: brushSettings.customTipAngle,
angleDynamics: brushSettings.customTipAngleDynamics,
rotationRandomScale: brushSettings.customTipRotationRandomScale,
hardness: strokeHardness,
- antiAlias: brushSettings.antiAlias,
+ antiAlias: isMono ? 0 : brushSettings.antiAlias,
pressureCurve: brushSettings.pressureCurve,
velocityCurve: brushSettings.velocityCurve,
+ usePressure: brushSettings.usePressure,
useVelocity: brushSettings.useVelocity,
+ useTilt,
+ sizeSensor: brushSettings.sizeSensor,
+ opacitySensor: brushSettings.opacitySensor,
+ densitySensor: brushSettings.densitySensor,
subTips: brushSettings.subTips,
subTipOrder: brushSettings.subTipOrder,
subTipImages: brushSettings.subTipImages,
spray: brushSettings.spray,
taper: brushSettings.taper,
colorMixing: brushSettings.colorMixing,
+ perceptualMixing: brushSettings.perceptualMixing,
amountOfPaint: brushSettings.amountOfPaint,
densityOfPaint: brushSettings.densityOfPaint,
colorStretch: brushSettings.colorStretch,
@@ -575,123 +559,152 @@ export function renderCompleteStroke(
wetEdgeAlphaPower: brushSettings.wetEdgeAlphaPower,
wetEdgeValuePower: brushSettings.wetEdgeValuePower,
grain: brushSettings.grain ?? brushSettings.textureDensity,
+ paperTextureMode: brushSettings.paperTextureMode,
+ paperTextureBrightness: brushSettings.paperTextureBrightness,
+ paperTextureContrast: brushSettings.paperTextureContrast,
+ paperTextureInverted: brushSettings.paperTextureInverted,
paperTextureImage: brushSettings.paperTextureImage,
paperTextureScale: brushSettings.paperTextureScale,
paperTextureRotate: brushSettings.paperTextureRotate,
+ dualBrush: brushSettings.dualBrush,
+ dualTipImage: brushSettings.dualTipImage,
+ dualBrushCompositeMode: brushSettings.dualBrushCompositeMode,
useGpu: Boolean(brushSettings.useGpu),
underlyingCanvas: underlyingCanvas || ctx.canvas,
sampler: underlyingCanvas ? new LayerPixelSampler(underlyingCanvas) : undefined,
- reservoir: (brushSettings.colorMixing && !isEraser) ? new PaintReservoir(strokeColor) : undefined,
+ reservoir: brushSettings.colorMixing && !isEraser ? new PaintReservoir(strokeColor) : undefined,
isEraser: isEraser && !isBgEraser,
isBgEraser,
alphaLocked,
isTransparentInk,
+ dynamics: brushSettings.dynamics,
+ secondaryColor: brushSettings.secondaryColor,
};
- renderCompleteTexturedStroke(ctx, points, strokeColor, brushSettings.customTipImage, tipOptions);
+ renderCompleteTexturedStroke(ctx, effectivePoints, strokeColor, brushSettings.customTipImage, tipOptions);
return;
}
- // Draw initial dot at points[0] to match the live preview start dot identically
+ const radialMixing: RadialMixingOptions = {
+ colorMixing: brushSettings.colorMixing,
+ perceptualMixing: brushSettings.perceptualMixing,
+ amountOfPaint: brushSettings.amountOfPaint,
+ densityOfPaint: brushSettings.densityOfPaint,
+ colorStretch: brushSettings.colorStretch,
+ mixingMode: brushSettings.mixingMode,
+ underlyingCanvas: underlyingCanvas || ctx.canvas,
+ sampler: brushSettings.colorMixing && underlyingCanvas ? new LayerPixelSampler(underlyingCanvas) : undefined,
+ reservoir: brushSettings.colorMixing && !isEraser ? new PaintReservoir(strokeColor) : undefined,
+ alphaLocked,
+ isTransparentInk,
+ dynamics: brushSettings.dynamics,
+ secondaryColor: brushSettings.secondaryColor,
+ useGpu: Boolean(brushSettings.useGpu),
+ dualBrush: brushSettings.dualBrush,
+ dualTipImage: brushSettings.dualTipImage,
+ dualBrushCompositeMode: brushSettings.dualBrushCompositeMode,
+ useTilt,
+ thicknessVertical: brushSettings.thicknessVertical,
+ flipH: brushSettings.flipH,
+ flipV: brushSettings.flipV,
+ antiAlias: isMono ? 0 : brushSettings.antiAlias,
+ angleDynamics: brushSettings.customTipAngleDynamics,
+ rotationRandomScale: brushSettings.customTipRotationRandomScale,
+ adjustDensityByGap: brushSettings.adjustDensityByGap,
+ blendTipsMode: brushSettings.blendTipsMode,
+ grain: brushSettings.grain ?? brushSettings.textureDensity,
+ paperTextureMode: brushSettings.paperTextureMode,
+ paperTextureBrightness: brushSettings.paperTextureBrightness,
+ paperTextureContrast: brushSettings.paperTextureContrast,
+ paperTextureInverted: brushSettings.paperTextureInverted,
+ paperTextureImage: brushSettings.paperTextureImage,
+ paperTextureScale: brushSettings.paperTextureScale,
+ paperTextureRotate: brushSettings.paperTextureRotate,
+ sizeSensor: brushSettings.sizeSensor,
+ opacitySensor: brushSettings.opacitySensor,
+ densitySensor: brushSettings.densitySensor,
+ taper: brushSettings.taper,
+ };
+
if (isPencil) {
const grade = (brushSettings.preset as PencilGrade) || 'pencil-2b';
+ const pencilTilt = brushSettings.useTilt ?? true;
drawPencilDot(
ctx,
- points[0],
+ effectivePoints[0],
strokeColor,
grade,
- brushSettings.flow ?? 0.74,
+ isMono ? 1.0 : (brushSettings.flow ?? 0.74),
brushSettings.grain ?? 1.0,
- brushSettings.hardness,
+ strokeHardness,
alphaLocked,
isTransparentInk
);
- } else {
- const radialMixing: RadialMixingOptions = {
- colorMixing: brushSettings.colorMixing,
- amountOfPaint: brushSettings.amountOfPaint,
- densityOfPaint: brushSettings.densityOfPaint,
- colorStretch: brushSettings.colorStretch,
- mixingMode: brushSettings.mixingMode,
- underlyingCanvas: underlyingCanvas || ctx.canvas,
- sampler: (brushSettings.colorMixing && underlyingCanvas) ? new LayerPixelSampler(underlyingCanvas) : undefined,
- reservoir: (brushSettings.colorMixing && !isEraser) ? new PaintReservoir(strokeColor) : undefined,
- alphaLocked,
- isTransparentInk,
- };
- drawDot(
- ctx,
- points[0],
- strokeColor,
- isEraser && !isBgEraser,
- strokeHardness,
- strokeFlow,
- radialMixing
- );
- }
-
- if (points.length === 1) {
- return;
- }
+ if (effectivePoints.length === 1) return;
- if (isPencil) {
- const grade = (brushSettings.preset as PencilGrade) || 'pencil-2b';
- const pFlow = brushSettings.flow ?? 0.74;
+ const pFlow = isMono ? 1.0 : (brushSettings.flow ?? 0.74);
const pGrain = brushSettings.grain ?? 1.0;
+ let accDist = Math.max(0.25, effectivePoints[0].width * (brushSettings.spacing ?? 0.07));
- if (points.length === 2) {
- const p0 = points[0];
- const p1 = points[1];
+ if (effectivePoints.length === 2) {
+ const p0 = effectivePoints[0];
+ const p1 = effectivePoints[1];
const { c1, c2 } = catmullRomToBezier(p0, p0, p1, p1);
- drawPencilCubicBezierSegment(ctx, p0, c1, c2, p1, strokeColor, grade, pFlow, pGrain, brushSettings.hardness, 0, alphaLocked, isTransparentInk);
+ drawPencilCubicBezierSegment(ctx, p0, c1, c2, p1, strokeColor, grade, pFlow, pGrain, strokeHardness, accDist, alphaLocked, isTransparentInk, pencilTilt);
return;
}
- const p0 = points[0];
- const p1 = points[1];
- const p2 = points[2];
+ const p0 = effectivePoints[0];
+ const p1 = effectivePoints[1];
+ const p2 = effectivePoints[2];
const first = catmullRomToBezier(p0, p0, p1, p2);
- drawPencilCubicBezierSegment(ctx, p0, first.c1, first.c2, p1, strokeColor, grade, pFlow, pGrain, brushSettings.hardness, 0, alphaLocked, isTransparentInk);
+ accDist = drawPencilCubicBezierSegment(ctx, p0, first.c1, first.c2, p1, strokeColor, grade, pFlow, pGrain, strokeHardness, accDist, alphaLocked, isTransparentInk, pencilTilt);
- for (let i = 2; i < points.length - 1; i++) {
- const seg = catmullRomToBezier(points[i - 2], points[i - 1], points[i], points[i + 1]);
- drawPencilCubicBezierSegment(ctx, points[i - 1], seg.c1, seg.c2, points[i], strokeColor, grade, pFlow, pGrain, brushSettings.hardness, 0, alphaLocked, isTransparentInk);
+ for (let i = 2; i < effectivePoints.length - 1; i++) {
+ const seg = catmullRomToBezier(effectivePoints[i - 2], effectivePoints[i - 1], effectivePoints[i], effectivePoints[i + 1]);
+ accDist = drawPencilCubicBezierSegment(ctx, effectivePoints[i - 1], seg.c1, seg.c2, effectivePoints[i], strokeColor, grade, pFlow, pGrain, strokeHardness, accDist, alphaLocked, isTransparentInk, pencilTilt);
}
- const n = points.length;
- const pPrev2 = points[n - 3];
- const pPrev = points[n - 2];
- const pLast = points[n - 1];
+ const n = effectivePoints.length;
+ const pPrev2 = effectivePoints[n - 3];
+ const pPrev = effectivePoints[n - 2];
+ const pLast = effectivePoints[n - 1];
const last = catmullRomToBezier(pPrev2, pPrev, pLast, pLast);
- drawPencilCubicBezierSegment(ctx, pPrev, last.c1, last.c2, pLast, strokeColor, grade, pFlow, pGrain, brushSettings.hardness, 0, alphaLocked, isTransparentInk);
- } else {
- const radialMixing: RadialMixingOptions = {
- colorMixing: brushSettings.colorMixing,
- amountOfPaint: brushSettings.amountOfPaint,
- densityOfPaint: brushSettings.densityOfPaint,
- colorStretch: brushSettings.colorStretch,
- mixingMode: brushSettings.mixingMode,
- underlyingCanvas: underlyingCanvas || ctx.canvas,
- sampler: (brushSettings.colorMixing && underlyingCanvas) ? new LayerPixelSampler(underlyingCanvas) : undefined,
- reservoir: (brushSettings.colorMixing && !isEraser) ? new PaintReservoir(strokeColor) : undefined,
- alphaLocked,
- isTransparentInk,
- };
+ drawPencilCubicBezierSegment(ctx, pPrev, last.c1, last.c2, pLast, strokeColor, grade, pFlow, pGrain, strokeHardness, accDist, alphaLocked, isTransparentInk, pencilTilt);
+ return;
+ }
- renderCompleteRadialStroke(
+ const baseAngleRad = ((brushSettings.customTipAngle ?? 0) * Math.PI) / 180;
+ const baseThickness = brushSettings.thickness ?? 1.0;
+
+ if (effectivePoints.length === 1) {
+ drawDot(
ctx,
- points,
+ effectivePoints[0],
strokeColor,
+ isEraser && !isBgEraser,
strokeHardness,
strokeFlow,
- strokeSpacing,
- isEraser && !isBgEraser,
- isBgEraser,
- brushSettings.thickness ?? 1.0,
- ((brushSettings.customTipAngle ?? 0) * Math.PI) / 180,
- radialMixing
+ radialMixing,
+ baseThickness,
+ baseAngleRad
);
+ return;
}
+
+ renderCompleteRadialStroke(
+ ctx,
+ effectivePoints,
+ strokeColor,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
+ isEraser && !isBgEraser,
+ isBgEraser,
+ baseThickness,
+ baseAngleRad,
+ radialMixing
+ );
}
let sampleCanvas: HTMLCanvasElement | null = null;
@@ -728,7 +741,6 @@ export function sampleCompositedColor(
sampleCtx.clearRect(0, 0, 1, 1);
- // Render bottom to top (reverse of layers list)
const renderOrder = layers.slice().reverse();
for (const layer of renderOrder) {
if (layer.type === 'folder' || !isLayerVisible(layer)) continue;
@@ -737,7 +749,7 @@ export function sampleCompositedColor(
sampleCtx.save();
sampleCtx.globalAlpha = getLayerOpacity(layer);
- sampleCtx.globalCompositeOperation = (layer.blendMode || 'source-over') as GlobalCompositeOperation;
+ sampleCtx.globalCompositeOperation = getCanvasCompositeOperation(layer.blendMode);
sampleCtx.drawImage(lCanvas, px, py, 1, 1, 0, 0, 1, 1);
sampleCtx.restore();
}
@@ -755,7 +767,6 @@ export function sampleCompositedColor(
return '#ffffff';
}
- // Alpha blend over solid white background
const a = data[3] / 255;
const r = Math.round(data[0] * a + 255 * (1 - a));
const g = Math.round(data[1] * a + 255 * (1 - a));
@@ -764,4 +775,3 @@ export function sampleCompositedColor(
const toHex = (n: number) => n.toString(16).padStart(2, '0');
return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
}
-
diff --git a/src/utils/colorMixingEngine.ts b/src/utils/colorMixingEngine.ts
index ef1a14a..08ab851 100644
--- a/src/utils/colorMixingEngine.ts
+++ b/src/utils/colorMixingEngine.ts
@@ -146,6 +146,8 @@ export function mixSubtractivePigments(
weight2: number // 0.0 = 100% c1, 1.0 = 100% c2
): RgbColor {
const w2 = Math.max(0, Math.min(1, weight2));
+ if (w2 <= 0.0001) return { r: c1.r, g: c1.g, b: c1.b };
+ if (w2 >= 0.9999) return { r: c2.r, g: c2.g, b: c2.b };
const w1 = 1 - w2;
// Convert to linear reflectance
@@ -196,7 +198,7 @@ export function mixSubtractivePigments(
const subLab = linearRgbToOklab(subR, subG, subB);
const tunedLab = {
- L: Math.max(0.01, targetLightness * 0.72 + subLab.L * 0.28),
+ L: Math.max(0, targetLightness * 0.72 + subLab.L * 0.28),
a: subLab.a,
b: subLab.b,
};
@@ -349,6 +351,7 @@ export class LayerPixelSampler {
let sumG = 0;
let sumB = 0;
let weightSum = 0;
+ let radialAreaSum = 0;
const rSq = r * r;
for (let y = y0; y <= y1; y += step) {
@@ -360,11 +363,13 @@ export class LayerPixelSampler {
const dx = x - ix;
const distSq = dx * dx + dySq;
if (distSq <= rSq) {
+ const geomWeight = 1 - distSq / rSq;
+ radialAreaSum += geomWeight;
const tile = this.getOrLoadTile(x >> 8, ty);
const idx = (lyOffset + (x & 255)) << 2;
const alpha = tile[idx + 3];
if (alpha > 4) {
- const radialWeight = (1 - distSq / rSq) * (alpha / 255);
+ const radialWeight = geomWeight * (alpha / 255);
sumR += tile[idx] * radialWeight;
sumG += tile[idx + 1] * radialWeight;
sumB += tile[idx + 2] * radialWeight;
@@ -374,12 +379,12 @@ export class LayerPixelSampler {
}
}
- if (weightSum > 0.001) {
+ if (weightSum > 0.001 && radialAreaSum > 0) {
return {
r: sumR / weightSum,
g: sumG / weightSum,
b: sumB / weightSum,
- a: Math.min(1.0, weightSum),
+ a: Math.min(1.0, weightSum / radialAreaSum),
};
}
return { r: 255, g: 255, b: 255, a: 0 };
@@ -409,6 +414,7 @@ export class LayerPixelSampler {
let sumG = 0;
let sumB = 0;
let weightSum = 0;
+ let radialAreaSum = 0;
const rSq = r * r;
for (let y = y0; y <= y1; y += step) {
@@ -419,11 +425,13 @@ export class LayerPixelSampler {
const dx = x - ix;
const distSq = dx * dx + dySq;
if (distSq <= rSq) {
+ const geomWeight = 1 - distSq / rSq;
+ radialAreaSum += geomWeight;
const idx = (rowOffset + x) * 4;
const alpha = this.data[idx + 3];
if (alpha > 4) {
// Inverse-distance radial weight
- const radialWeight = (1 - distSq / rSq) * (alpha / 255);
+ const radialWeight = geomWeight * (alpha / 255);
sumR += this.data[idx] * radialWeight;
sumG += this.data[idx + 1] * radialWeight;
sumB += this.data[idx + 2] * radialWeight;
@@ -433,12 +441,12 @@ export class LayerPixelSampler {
}
}
- if (weightSum > 0.001) {
+ if (weightSum > 0.001 && radialAreaSum > 0) {
return {
r: sumR / weightSum,
g: sumG / weightSum,
b: sumB / weightSum,
- a: Math.min(1.0, weightSum),
+ a: Math.min(1.0, weightSum / radialAreaSum),
};
}
@@ -632,65 +640,119 @@ export class PaintReservoir {
amountOfPaint: number, // 0.0 (pure smudge) to 1.0 (fresh pigment only)
densityOfPaint: number, // 0.0 to 1.0 (paint deposition opacity)
colorStretch: number, // 0.0 to 1.0 (drag length)
- mixingMode: 'blend' | 'running_color' = 'blend',
+ mixingMode: 'blend' | 'running_color' | 'smear' = 'blend',
pressure: number = 0.5,
flow: number = 0.85,
- stepDist: number = 0
+ stepDist: number = 0,
+ perceptualMixing: boolean = true
): { r: number; g: number; b: number; alpha: number; colorHex: string } {
this.cumulativeDistance += stepDist;
- const isPureSmudge = amountOfPaint <= 0.005;
+ const clampedAmount = Math.max(0, Math.min(1, amountOfPaint));
+ const isPureSmudge = clampedAmount <= 0.005 || mixingMode === 'smear';
const canvasAlpha = sampledColor.a;
+ const mixFn = (c1: RgbColor, c2: RgbColor, w2: number): RgbColor => {
+ if (perceptualMixing) {
+ return mixSubtractivePigments(c1, c2, w2);
+ }
+ const w = Math.max(0, Math.min(1, w2));
+ return {
+ r: c1.r + (c2.r - c1.r) * w,
+ g: c1.g + (c2.g - c1.g) * w,
+ b: c1.b + (c2.b - c1.b) * w,
+ };
+ };
+
if (canvasAlpha > 0.015) {
// Contact with existing paint on canvas
const pressureInfluence = pressure * 0.5 + 0.5;
- const pickupRate = isPureSmudge
- ? Math.min(0.98, canvasAlpha * 0.96 * pressureInfluence)
- : Math.min(0.94, (1.0 - amountOfPaint) * canvasAlpha * pressureInfluence);
-
+ const origColor: RgbColor = {
+ r: this.originalR,
+ g: this.originalG,
+ b: this.originalB,
+ };
const targetColor: RgbColor = {
r: sampledColor.r,
g: sampledColor.g,
b: sampledColor.b,
};
-
const currentColor: RgbColor = {
r: this.r,
g: this.g,
b: this.b,
};
- if (mixingMode === 'running_color' || isPureSmudge) {
- // Running color: wet paint smear where canvas paint dynamically replaces reservoir
- const blendFactor = Math.min(0.95, pickupRate * 1.3);
- const mixed = mixSubtractivePigments(currentColor, targetColor, blendFactor);
+ if (isPureSmudge) {
+ // Pure Smudge / Smear: drags underlying pigment with zero fresh ink injection
+ const pickupRate = Math.min(0.96, canvasAlpha * (0.35 + (1.0 - colorStretch) * 0.55) * pressureInfluence);
+ const mixed = mixFn(currentColor, targetColor, pickupRate);
this.r = mixed.r;
this.g = mixed.g;
this.b = mixed.b;
- this.a = Math.min(1.0, this.a + 0.3);
+ this.a = Math.min(1.0, this.a * 0.7 + canvasAlpha * 0.3);
this.isLoadedWithCanvasColor = true;
- this.cumulativeDistance = 0; // Reset distance from latest color pickup
- } else {
- // Blend mode: continuous harmonious subtractive blending
- const blendFactor = Math.min(0.85, pickupRate);
- const mixed = mixSubtractivePigments(currentColor, targetColor, blendFactor);
+ this.cumulativeDistance = 0;
+ } else if (mixingMode === 'running_color') {
+ // Step 1: Absorb underlying canvas pigment into wet bristles (does not self-brighten on own trail)
+ const pickupScale = stepDist > 0 ? Math.min(1.0, Math.max(0.2, stepDist / 2.5)) : 1.0;
+ const pickupRate = Math.min(
+ 0.9,
+ (1.0 - clampedAmount * 0.6) * canvasAlpha * pressureInfluence * pickupScale * 1.15
+ );
+ let mixed = mixFn(currentColor, targetColor, pickupRate);
+ // Step 2: Distance-normalized fresh pigment feed from bristle ferrule governed by colorStretch
+ const replenishDist = Math.max(
+ 24,
+ (0.15 + colorStretch * 0.85) * (320 / Math.max(0.12, clampedAmount))
+ );
+ const feedRate =
+ stepDist > 0 ? 1.0 - Math.exp(-stepDist / replenishDist) : clampedAmount * 0.35;
+ mixed = mixFn(mixed, origColor, feedRate);
this.r = mixed.r;
this.g = mixed.g;
this.b = mixed.b;
+ this.a = Math.min(1.0, this.a + 0.3);
+ this.isLoadedWithCanvasColor = true;
+ this.cumulativeDistance = 0;
+ } else {
+ // CSP Blend mode: Step 1 absorb canvas pigment; Step 2 continuous ferrule replenishment per distance
+ if (stepDist <= 0) {
+ const equilibrium = mixFn(targetColor, origColor, clampedAmount);
+ const mixed = mixFn(currentColor, equilibrium, 0.65 * canvasAlpha * pressureInfluence);
+ this.r = mixed.r;
+ this.g = mixed.g;
+ this.b = mixed.b;
+ } else {
+ const stepScale = Math.min(1.0, Math.max(0.18, stepDist / 3.0));
+ const pickupRate = Math.min(
+ 0.82,
+ (1.0 - clampedAmount * 0.72) * canvasAlpha * pressureInfluence * stepScale
+ );
+ let mixed = mixFn(currentColor, targetColor, pickupRate);
+ const replenishDist = Math.max(
+ 14,
+ (0.2 + colorStretch * 0.8) * (160 / Math.max(0.12, clampedAmount))
+ );
+ const feedRate = 1.0 - Math.exp(-stepDist / replenishDist);
+ mixed = mixFn(mixed, origColor, feedRate);
+ this.r = mixed.r;
+ this.g = mixed.g;
+ this.b = mixed.b;
+ }
this.isLoadedWithCanvasColor = true;
}
} else {
// Moving into unpainted / dry area: apply Color Stretch decay
if (this.isLoadedWithCanvasColor && stepDist > 0) {
- const stretchDistanceLimit = Math.max(30, colorStretch * 850);
+ const stretchDistanceLimit = Math.max(24, colorStretch * 800);
const decayRate = 1.0 - Math.exp(-stepDist / stretchDistanceLimit);
if (isPureSmudge) {
// Pure Smudge runs out of paint when dragging away from painted areas
this.a = Math.max(0, this.a * (1.0 - decayRate * 1.6));
} else {
- // Slowly recovers brush's initial fresh color
+ // Smoothly recovers brush's fresh foreground pigment
const origColor: RgbColor = {
r: this.originalR,
g: this.originalG,
@@ -701,7 +763,7 @@ export class PaintReservoir {
g: this.g,
b: this.b,
};
- const recovered = mixSubtractivePigments(currColor, origColor, decayRate);
+ const recovered = mixFn(currColor, origColor, Math.min(1.0, decayRate * (0.6 + clampedAmount * 0.8)));
this.r = recovered.r;
this.g = recovered.g;
this.b = recovered.b;
diff --git a/src/utils/compositor.ts b/src/utils/compositor.ts
index aad388c..26adb2d 100644
--- a/src/utils/compositor.ts
+++ b/src/utils/compositor.ts
@@ -9,7 +9,7 @@
*/
import { LayerItem, CanvasDimensions, BlendMode, CanvasColorMode, LayerStyles, SoftProofSettings } from '../types/editor';
-import { SparseTileGrid, TILE_SIZE, TileBuffer, globalTileGrid } from './tileEngine';
+import { SparseTileGrid, TILE_SIZE, TileBuffer, globalTileGrid, getTileKey } from './tileEngine';
import { getCanvasCompositeOperation } from './canvasUtils';
import {
buildCurvesCombinedLut,
@@ -275,6 +275,12 @@ uniform vec2 u_docDimensions;
uniform sampler2D u_maskTexture;
uniform int u_maskEnabled;
+// CSP Expression Color Uniforms (0: color, 1: gray, 2: monochrome)
+uniform int u_expressionMode;
+uniform float u_monoThreshold;
+uniform int u_monoExpressBlack;
+uniform int u_monoExpressWhite;
+
out vec4 fragColor;
float fractVal(float x) {
@@ -398,8 +404,28 @@ void main() {
vec4 finalColor = texColor;
+ if (u_expressionMode == 1) {
+ float gLum = dot(finalColor.rgb, vec3(0.299, 0.587, 0.114));
+ finalColor.rgb = vec3(gLum);
+ } else if (u_expressionMode == 2) {
+ float mLum = dot(finalColor.rgb, vec3(0.299, 0.587, 0.114));
+ if (mLum < u_monoThreshold) {
+ if (u_monoExpressBlack == 1) {
+ finalColor = vec4(0.0, 0.0, 0.0, step(0.1, finalColor.a));
+ } else {
+ discard;
+ }
+ } else {
+ if (u_monoExpressWhite == 1) {
+ finalColor = vec4(1.0, 1.0, 1.0, step(0.1, finalColor.a));
+ } else {
+ discard;
+ }
+ }
+ }
+
if (u_toneEnabled == 1) {
- finalColor = evaluateScreentone(texColor, v_docCoord);
+ finalColor = evaluateScreentone(finalColor, v_docCoord);
}
if (u_layerColorEnabled == 1) {
@@ -1062,9 +1088,22 @@ export class ViewportCompositor {
private uLayerColorLoc: WebGLUniformLocation | null = null;
private uLayerSubColorLoc: WebGLUniformLocation | null = null;
+ // Cached attribute locations (eliminates per-frame gl.getAttribLocation stalls)
+ private aQuadPosLoc: number = -1;
+ private aStylesQuadPosLoc: number = -1;
+ private aBlitQuadPosLoc: number = -1;
+ private aProofQuadPosLoc: number = -1;
+ private contextLost: boolean = false;
+ private onContextLostHandler: ((e: Event) => void) | null = null;
+ private onContextRestoredHandler: (() => void) | null = null;
+
// Mask uniform locations & version-tracked cache
private uMaskTextureLoc: WebGLUniformLocation | null = null;
private uMaskEnabledLoc: WebGLUniformLocation | null = null;
+ private uExpressionModeLoc: WebGLUniformLocation | null = null;
+ private uMonoThresholdLoc: WebGLUniformLocation | null = null;
+ private uMonoExpressBlackLoc: WebGLUniformLocation | null = null;
+ private uMonoExpressWhiteLoc: WebGLUniformLocation | null = null;
private maskTextureCache: Map<
string,
{ texture: WebGLTexture; version: number; width: number; height: number }
@@ -1134,7 +1173,13 @@ export class ViewportCompositor {
private uBlitHasBackdropLoc: WebGLUniformLocation | null = null;
private uBlitBlendModeLoc: WebGLUniformLocation | null = null;
private uBlitOpacityLoc: WebGLUniformLocation | null = null;
- private folderFbos: { fbo: WebGLFramebuffer; texture: WebGLTexture; width: number; height: number }[] = [];
+ private folderFbos: {
+ fbo: WebGLFramebuffer;
+ texture: WebGLTexture;
+ stencilRb: WebGLRenderbuffer | null;
+ width: number;
+ height: number;
+ }[] = [];
// Soft proofing program, uniforms, & snapshot texture
private softProofProgram: WebGLProgram | null = null;
@@ -1147,20 +1192,68 @@ export class ViewportCompositor {
private proofSnapshotWidth: number = 0;
private proofSnapshotHeight: number = 0;
- // Tile texture cache: tileKey -> { texture, version, hasMipmap, filterMode }
- private textureCache: Map<
+ // Pre-allocated WebGL Texture Pool for dynamic texture streaming
+ private static readonly MAX_TEXTURE_POOL_SIZE = 2048;
+ private textureAccessCounter: number = 0;
+ private texturePool: Array<{
+ texture: WebGLTexture;
+ currentKey: string | null;
+ version: number;
+ lastUsed: number;
+ filterTier?: number;
+ hasStorage?: boolean;
+ hasMipmap?: boolean;
+ }> = [];
+ private activePoolByKey: Map<
string,
- { texture: WebGLTexture; version: number; lastUsed: number; filterTier?: number }
+ {
+ texture: WebGLTexture;
+ currentKey: string | null;
+ version: number;
+ lastUsed: number;
+ filterTier?: number;
+ hasStorage?: boolean;
+ hasMipmap?: boolean;
+ }
> = new Map();
private fallbackTileCanvas: HTMLCanvasElement | null = null;
constructor(canvas: HTMLCanvasElement) {
this.canvas = canvas;
+ if (typeof canvas.addEventListener === 'function') {
+ this.onContextLostHandler = (e: Event) => {
+ e.preventDefault();
+ this.contextLost = true;
+ this.gl = null;
+ this.program = null;
+ this.adjProgram = null;
+ this.stylesProgram = null;
+ this.blitProgram = null;
+ this.softProofProgram = null;
+ this.texturePool = [];
+ this.activePoolByKey.clear();
+ this.maskTextureCache.clear();
+ this.folderFbos = [];
+ this.layerFbo = null;
+ this.layerTexture = null;
+ this.snapshotTexture = null;
+ this.lutTexture = null;
+ this.draftTexture = null;
+ this.proofSnapshotTexture = null;
+ };
+ this.onContextRestoredHandler = () => {
+ this.contextLost = false;
+ this.initGL();
+ globalTileGrid.notifyChange(true);
+ };
+ canvas.addEventListener('webglcontextlost', this.onContextLostHandler, false);
+ canvas.addEventListener('webglcontextrestored', this.onContextRestoredHandler, false);
+ }
this.initGL();
}
public isReady(): boolean {
- return this.gl !== null && this.program !== null;
+ return !this.contextLost && this.gl !== null && this.program !== null;
}
/**
@@ -1177,6 +1270,19 @@ export class ViewportCompositor {
}
}
+ /**
+ * Explicitly invalidate and clear all cached tile textures in the pool.
+ */
+ public invalidateTileTextures(): void {
+ if (this.gl) {
+ for (const slot of this.texturePool) {
+ this.gl.deleteTexture(slot.texture);
+ }
+ }
+ this.texturePool = [];
+ this.activePoolByKey.clear();
+ }
+
private initGL(): boolean {
if (this.gl && this.program) return true;
@@ -1256,6 +1362,11 @@ export class ViewportCompositor {
this.uMaskTextureLoc = gl.getUniformLocation(prog, 'u_maskTexture');
this.uMaskEnabledLoc = gl.getUniformLocation(prog, 'u_maskEnabled');
+ this.uExpressionModeLoc = gl.getUniformLocation(prog, 'u_expressionMode');
+ this.uMonoThresholdLoc = gl.getUniformLocation(prog, 'u_monoThreshold');
+ this.uMonoExpressBlackLoc = gl.getUniformLocation(prog, 'u_monoExpressBlack');
+ this.uMonoExpressWhiteLoc = gl.getUniformLocation(prog, 'u_monoExpressWhite');
+ this.aQuadPosLoc = gl.getAttribLocation(prog, 'a_quadPos');
// Compile Adjustment Shader Program
const adjFs = gl.createShader(gl.FRAGMENT_SHADER);
@@ -1307,6 +1418,7 @@ export class ViewportCompositor {
gl.linkProgram(sProg);
if (gl.getProgramParameter(sProg, gl.LINK_STATUS)) {
this.stylesProgram = sProg;
+ this.aStylesQuadPosLoc = gl.getAttribLocation(sProg, 'a_quadPos');
this.uStylesLayerTextureLoc = gl.getUniformLocation(sProg, 'u_layerTexture');
this.uStylesViewportSizeLoc = gl.getUniformLocation(sProg, 'u_viewportSize');
this.uStylesLayerOpacityLoc = gl.getUniformLocation(sProg, 'u_layerOpacity');
@@ -1346,6 +1458,7 @@ export class ViewportCompositor {
gl.linkProgram(bProg);
if (gl.getProgramParameter(bProg, gl.LINK_STATUS)) {
this.blitProgram = bProg;
+ this.aBlitQuadPosLoc = gl.getAttribLocation(bProg, 'a_quadPos');
this.uBlitTextureLoc = gl.getUniformLocation(bProg, 'u_blitTexture');
this.uBlitBackdropTextureLoc = gl.getUniformLocation(bProg, 'u_backdropTexture');
this.uBlitHasBackdropLoc = gl.getUniformLocation(bProg, 'u_hasBackdrop');
@@ -1372,6 +1485,7 @@ export class ViewportCompositor {
gl.linkProgram(pProg);
if (gl.getProgramParameter(pProg, gl.LINK_STATUS)) {
this.softProofProgram = pProg;
+ this.aProofQuadPosLoc = gl.getAttribLocation(pProg, 'a_quadPos');
this.uProofSceneTextureLoc = gl.getUniformLocation(pProg, 'u_sceneTexture');
this.uProofStandardLoc = gl.getUniformLocation(pProg, 'u_standard');
this.uProofEnabledLoc = gl.getUniformLocation(pProg, 'u_proofEnabled');
@@ -1462,84 +1576,114 @@ export class ViewportCompositor {
}
/**
- * Get or upload a WebGLTexture for a tile with hardware mipmap pyramid and adaptive zoom filtering.
- * - Zoom < 0.99: Trilinear mipmap filtering (gl.LINEAR_MIPMAP_LINEAR) eliminates line-art shimmering.
- * - 0.99 <= Zoom < 2.0: Bilinear filtering (gl.LINEAR) for smooth rotation/sub-pixel pan.
- * - Zoom >= 2.0: Nearest-neighbor magnification (gl.NEAREST) for crisp pixel-level inspection.
+ * Get or upload a WebGLTexture from the pre-allocated texture pool with adaptive zoom filtering.
+ * Only tiles currently intersecting the screen frustum are uploaded to GPU memory.
*/
private getTileTexture(tile: TileBuffer, grid: SparseTileGrid): WebGLTexture | null {
if (!this.gl) return null;
const gl = this.gl;
- const key = `${tile.layerId}:${tile.tileX}:${tile.tileY}`;
-
- let cached = this.textureCache.get(key);
- if (!cached) {
- const tex = gl.createTexture();
- if (!tex) return null;
- cached = { texture: tex, version: -1, lastUsed: performance.now(), filterTier: -1 };
- this.textureCache.set(key, cached);
+ const key = getTileKey(tile.layerId, tile.tileX, tile.tileY, tile.lod ?? 0);
+ const accessTick = ++this.textureAccessCounter;
+
+ let slot = this.activePoolByKey.get(key);
+
+ if (!slot) {
+ if (this.texturePool.length < ViewportCompositor.MAX_TEXTURE_POOL_SIZE) {
+ const tex = gl.createTexture();
+ if (!tex) return null;
+ slot = {
+ texture: tex,
+ currentKey: key,
+ version: -1,
+ lastUsed: accessTick,
+ filterTier: -1,
+ hasStorage: false,
+ hasMipmap: false,
+ };
+ this.texturePool.push(slot);
+ this.activePoolByKey.set(key, slot);
+ } else {
+ // Reuse least recently used texture slot from pool
+ let oldestSlot = this.texturePool[0];
+ for (let i = 1; i < this.texturePool.length; i++) {
+ if (this.texturePool[i].lastUsed < oldestSlot.lastUsed) {
+ oldestSlot = this.texturePool[i];
+ }
+ }
+ slot = oldestSlot;
+ if (slot.currentKey) {
+ this.activePoolByKey.delete(slot.currentKey);
+ }
+ slot.currentKey = key;
+ slot.version = -1;
+ slot.lastUsed = accessTick;
+ slot.filterTier = -1;
+ slot.hasMipmap = false;
+ this.activePoolByKey.set(key, slot);
+ }
}
- cached.lastUsed = performance.now();
+ slot.lastUsed = accessTick;
const desiredTier = this.currentZoom < 0.99 ? 0 : this.currentZoom < 2.0 ? 1 : 2;
// Re-upload if dirty or version bumped
- if (cached.version !== tile.version || tile.dirty) {
- gl.bindTexture(gl.TEXTURE_2D, cached.texture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ if (slot.version !== tile.version || tile.dirty) {
+ gl.bindTexture(gl.TEXTURE_2D, slot.texture);
const rgbaData = grid.getTileAsRGBA(tile);
- const uploadBytes = rgbaData instanceof Uint8Array
- ? rgbaData
- : new Uint8Array(rgbaData.buffer, rgbaData.byteOffset, rgbaData.byteLength);
-
- gl.texImage2D(
- gl.TEXTURE_2D,
- 0,
- gl.RGBA,
- TILE_SIZE,
- TILE_SIZE,
- 0,
- gl.RGBA,
- gl.UNSIGNED_BYTE,
- uploadBytes
- );
+ const uploadBytes =
+ rgbaData instanceof Uint8Array
+ ? rgbaData
+ : new Uint8Array(rgbaData.buffer, rgbaData.byteOffset, rgbaData.byteLength);
- // Generate hardware mipmap pyramid for anti-aliased zoomed-out viewing (256x256 POT)
- if (typeof gl.generateMipmap === 'function') {
- gl.generateMipmap(gl.TEXTURE_2D);
+ if (slot.hasStorage && typeof gl.texSubImage2D === 'function') {
+ gl.texSubImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ 0,
+ 0,
+ TILE_SIZE,
+ TILE_SIZE,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ uploadBytes
+ );
+ } else {
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ gl.texImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ TILE_SIZE,
+ TILE_SIZE,
+ 0,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ uploadBytes
+ );
+ slot.hasStorage = true;
}
- cached.version = tile.version;
- cached.filterTier = -1; // Force filter parameter refresh
+ slot.hasMipmap = false;
+ slot.version = tile.version;
+ slot.filterTier = -1; // Force filter parameter refresh
tile.dirty = false;
}
- if (cached.filterTier !== desiredTier) {
- gl.bindTexture(gl.TEXTURE_2D, cached.texture);
- if (desiredTier === 0) {
- gl.texParameteri(
- gl.TEXTURE_2D,
- gl.TEXTURE_MIN_FILTER,
- typeof gl.generateMipmap === 'function' ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR
- );
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- } else if (desiredTier === 1) {
+ if (slot.filterTier !== desiredTier) {
+ gl.bindTexture(gl.TEXTURE_2D, slot.texture);
+ if (desiredTier <= 1) {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
} else {
- gl.texParameteri(
- gl.TEXTURE_2D,
- gl.TEXTURE_MIN_FILTER,
- typeof gl.generateMipmap === 'function' ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST
- );
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
}
- cached.filterTier = desiredTier;
+ slot.filterTier = desiredTier;
}
- return cached.texture;
+ return slot.texture;
}
/**
@@ -1650,15 +1794,17 @@ export class ViewportCompositor {
gl.uniform1i(this.uTileTextureLoc, 0);
gl.uniform1i(this.uHasBackdropLoc, 0);
- // Bind Quad Vertices
+ // Bind Quad Vertices using cached attribute location
gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuffer);
- const posAttrib = gl.getAttribLocation(this.program, 'a_quadPos');
- gl.enableVertexAttribArray(posAttrib);
- gl.vertexAttribPointer(posAttrib, 2, gl.FLOAT, false, 0, 0);
+ if (this.aQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(this.aQuadPosLoc);
+ gl.vertexAttribPointer(this.aQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ }
// 1. Render artboard background pass (paper white or checkerboard)
gl.blendFunc(gl.ONE, gl.ZERO);
gl.uniform1i(this.uIsBackgroundLoc, 1);
+ gl.uniform1i(this.uExpressionModeLoc, 0);
gl.uniform1i(this.uShowCheckerboardLoc, _options.showCheckerboard ? 1 : 0);
gl.uniform2f(this.uTileOriginLoc, 0, 0);
gl.uniform2f(this.uTileSizeLoc, dimensions.width, dimensions.height);
@@ -1678,6 +1824,13 @@ export class ViewportCompositor {
gl.uniform2f(this.uTileSizeLoc, TILE_SIZE, TILE_SIZE);
+ // Dynamic Frustum Culling & Memory Budget Sync
+ const layerVis = new Map<string, boolean>();
+ for (const l of layers) {
+ layerVis.set(l.id, l.visible);
+ }
+ grid.getMemoryManager()?.updateViewport(frustum, _options.activeDraftLayerId, layerVis);
+
// 2. Render colored onion skin cels if active in animation mode
if (_options.onionSkinFrames && _options.onionSkinFrames.length > 0) {
for (const onion of _options.onionSkinFrames) {
@@ -1718,8 +1871,19 @@ export class ViewportCompositor {
this.applySoftProofPass(gl, viewportW, viewportH, _options.softProof);
}
- // Clean up stale textures periodically (LRU)
- if (this.textureCache.size > 2000) {
+ // Prune mask textures belonging to deleted layers
+ if (this.maskTextureCache.size > layers.length) {
+ for (const cachedLayerId of Array.from(this.maskTextureCache.keys())) {
+ if (!layerVis.has(cachedLayerId)) {
+ const entry = this.maskTextureCache.get(cachedLayerId);
+ if (entry) gl.deleteTexture(entry.texture);
+ this.maskTextureCache.delete(cachedLayerId);
+ }
+ }
+ }
+
+ // Clean up stale textures if pool exceeded limit
+ if (this.texturePool.length > ViewportCompositor.MAX_TEXTURE_POOL_SIZE) {
this.evictStaleTextures();
}
}
@@ -1858,7 +2022,8 @@ export class ViewportCompositor {
viewportH,
transform,
dpr,
- baseEffectiveOpacity
+ baseEffectiveOpacity,
+ currentFbo
);
gl.stencilMask(0xFF);
} else {
@@ -1882,7 +2047,8 @@ export class ViewportCompositor {
viewportH,
transform,
dpr,
- baseEffectiveOpacity
+ baseEffectiveOpacity,
+ currentFbo
);
} else {
this.renderSingleLayer(gl, clippedLayer, dimensions, grid, frustum, baseEffectiveOpacity);
@@ -1903,7 +2069,8 @@ export class ViewportCompositor {
viewportH,
transform,
dpr,
- baseEffectiveOpacity
+ baseEffectiveOpacity,
+ currentFbo
);
} else {
this.renderSingleLayer(gl, baseLayer, dimensions, grid, frustum, baseEffectiveOpacity);
@@ -2001,12 +2168,13 @@ export class ViewportCompositor {
lutData = new Uint8Array(gMap.buffer, gMap.byteOffset, gMap.byteLength);
} else if (adj.type === 'levels') {
const lLut = buildLevelsLut(adj.blackPoint, adj.whitePoint, adj.gamma, adj.outputMin ?? 0, adj.outputMax ?? 255);
+ const ch = adj.channel || 'rgb';
lutData = new Uint8Array(256 * 4);
for (let i = 0; i < 256; i++) {
const off = i * 4;
- lutData[off] = lLut[i];
- lutData[off + 1] = lLut[i];
- lutData[off + 2] = lLut[i];
+ lutData[off] = ch === 'rgb' || ch === 'r' ? lLut[i] : i;
+ lutData[off + 1] = ch === 'rgb' || ch === 'g' ? lLut[i] : i;
+ lutData[off + 2] = ch === 'rgb' || ch === 'b' ? lLut[i] : i;
lutData[off + 3] = 255;
}
} else { // color-balance
@@ -2098,6 +2266,22 @@ export class ViewportCompositor {
gl.uniform1f(this.uLayerOpacityLoc, layer.opacity * opacityMultiplier);
gl.uniform1i(this.uBlendModeLoc, BLEND_MODE_MAP[layer.blendMode] ?? 0);
+ // Configure Expression Color Uniforms
+ const isBgLayer = layer.id === 'layer-bg' || layer.id.startsWith('layer-bg');
+ const exprMode = isBgLayer
+ ? 0
+ : layer.expressionColor === 'monochrome'
+ ? 2
+ : layer.expressionColor === 'gray'
+ ? 1
+ : 0;
+ gl.uniform1i(this.uExpressionModeLoc, exprMode);
+ if (exprMode === 2) {
+ gl.uniform1f(this.uMonoThresholdLoc, (layer.monoThreshold ?? 128) / 255.0);
+ gl.uniform1i(this.uMonoExpressBlackLoc, layer.monoExpressBlack !== false ? 1 : 0);
+ gl.uniform1i(this.uMonoExpressWhiteLoc, layer.monoExpressWhite !== false ? 1 : 0);
+ }
+
// Configure Screentone Uniforms
const toneEnabled = Boolean(layer.toneEnabled);
gl.uniform1i(this.uToneEnabledLoc, toneEnabled ? 1 : 0);
@@ -2142,18 +2326,38 @@ export class ViewportCompositor {
}
}
- // Query tiles intersecting frustum
- const visibleTiles = grid.getTilesInBounds(
- layer.id,
- frustum.minX,
- frustum.minY,
- frustum.maxX,
- frustum.maxY
- );
+ // Adaptive LOD Selection & Frustum Culling:
+ // Select LOD 1 when zoom <= 50%, LOD 2 when zoom <= 25%, LOD 3 when zoom <= 12.5%
+ const targetLod =
+ this.currentZoom <= 0.125 ? 3 :
+ this.currentZoom <= 0.25 ? 2 :
+ this.currentZoom <= 0.5 ? 1 : 0;
+
+ const lodScale = 1 << targetLod;
+ const lodTileDocSize = TILE_SIZE * lodScale;
+
+ // Convert screen viewport bounding box in canvas coordinates to intersecting tile ranges
+ const startTileX = Math.floor(frustum.minX / lodTileDocSize);
+ const endTileX = Math.floor(frustum.maxX / lodTileDocSize);
+ const startTileY = Math.floor(frustum.minY / lodTileDocSize);
+ const endTileY = Math.floor(frustum.maxY / lodTileDocSize);
+
+ const visibleTiles: TileBuffer[] = [];
+ for (let ty = startTileY; ty <= endTileY; ty++) {
+ for (let tx = startTileX; tx <= endTileX; tx++) {
+ let tile = grid.getTile(layer.id, tx, ty, targetLod);
+ if (targetLod > 0 && (!tile || grid.isLodTileDirty(layer.id, tx, ty, targetLod))) {
+ tile = grid.generateLodTile(layer.id, tx, ty, targetLod);
+ }
+ if (tile) {
+ visibleTiles.push(tile);
+ }
+ }
+ }
- gl.uniform2f(this.uTileSizeLoc, TILE_SIZE, TILE_SIZE);
+ gl.uniform2f(this.uTileSizeLoc, lodTileDocSize, lodTileDocSize);
- // Draw each visible tile with 1 draw call per tile
+ // Draw each visible intersecting tile with 1 draw call per tile
for (const tile of visibleTiles) {
const tex = this.getTileTexture(tile, grid);
if (!tex) continue;
@@ -2161,7 +2365,7 @@ export class ViewportCompositor {
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, tex);
- gl.uniform2f(this.uTileOriginLoc, tile.tileX * TILE_SIZE, tile.tileY * TILE_SIZE);
+ gl.uniform2f(this.uTileOriginLoc, tile.tileX * lodTileDocSize, tile.tileY * lodTileDocSize);
gl.drawArrays(gl.TRIANGLES, 0, 6);
}
@@ -2231,6 +2435,8 @@ export class ViewportCompositor {
return true;
}
+ const prevFbo = gl.getParameter(gl.FRAMEBUFFER_BINDING) as WebGLFramebuffer | null;
+
if (!this.layerFbo) {
this.layerFbo = gl.createFramebuffer();
}
@@ -2252,7 +2458,7 @@ export class ViewportCompositor {
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.layerTexture, 0);
const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
- gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, prevFbo);
if (status !== gl.FRAMEBUFFER_COMPLETE) {
console.error('Layer FBO incomplete:', status);
@@ -2272,12 +2478,15 @@ export class ViewportCompositor {
while (this.folderFbos.length <= depth) {
const fbo = gl.createFramebuffer();
const texture = gl.createTexture();
+ const stencilRb = typeof gl.createRenderbuffer === 'function' ? gl.createRenderbuffer() : null;
if (!fbo || !texture) return null;
- this.folderFbos.push({ fbo, texture, width: 0, height: 0 });
+ this.folderFbos.push({ fbo, texture, stencilRb, width: 0, height: 0 });
}
const item = this.folderFbos[depth];
if (item.width !== width || item.height !== height) {
+ const prevFbo = gl.getParameter(gl.FRAMEBUFFER_BINDING) as WebGLFramebuffer | null;
+
gl.bindTexture(gl.TEXTURE_2D, item.texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
@@ -2288,8 +2497,14 @@ export class ViewportCompositor {
gl.bindFramebuffer(gl.FRAMEBUFFER, item.fbo);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, item.texture, 0);
+ if (item.stencilRb && typeof gl.bindRenderbuffer === 'function') {
+ gl.bindRenderbuffer(gl.RENDERBUFFER, item.stencilRb);
+ gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8, width, height);
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, item.stencilRb);
+ }
+
const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
- gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, prevFbo);
if (status !== gl.FRAMEBUFFER_COMPLETE) {
console.error('Folder FBO incomplete:', status);
@@ -2333,9 +2548,10 @@ export class ViewportCompositor {
gl.useProgram(this.blitProgram);
gl.bindBuffer(gl.ARRAY_BUFFER, this.stylesQuadBuffer);
- const posAttr = gl.getAttribLocation(this.blitProgram, 'a_quadPos');
- gl.enableVertexAttribArray(posAttr);
- gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0);
+ if (this.aBlitQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(this.aBlitQuadPosLoc);
+ gl.vertexAttribPointer(this.aBlitQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ }
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texture);
@@ -2351,9 +2567,10 @@ export class ViewportCompositor {
if (this.program) {
gl.useProgram(this.program);
gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuffer);
- const mainPosAttrib = gl.getAttribLocation(this.program, 'a_quadPos');
- gl.enableVertexAttribArray(mainPosAttrib);
- gl.vertexAttribPointer(mainPosAttrib, 2, gl.FLOAT, false, 0, 0);
+ if (this.aQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(this.aQuadPosLoc);
+ gl.vertexAttribPointer(this.aQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ }
}
}
@@ -2409,9 +2626,10 @@ export class ViewportCompositor {
const quadBuffer = this.stylesQuadBuffer || this.quadBuffer;
if (quadBuffer) {
gl.bindBuffer(gl.ARRAY_BUFFER, quadBuffer);
- const posAttrib = gl.getAttribLocation(this.softProofProgram, 'a_quadPos');
- gl.enableVertexAttribArray(posAttrib);
- gl.vertexAttribPointer(posAttrib, 2, gl.FLOAT, false, 0, 0);
+ if (this.aProofQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(this.aProofQuadPosLoc);
+ gl.vertexAttribPointer(this.aProofQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ }
gl.viewport(0, 0, viewportW, viewportH);
gl.drawArrays(gl.TRIANGLES, 0, 6);
@@ -2422,9 +2640,10 @@ export class ViewportCompositor {
if (this.program) {
gl.useProgram(this.program);
gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuffer);
- const mainPosAttrib = gl.getAttribLocation(this.program, 'a_quadPos');
- gl.enableVertexAttribArray(mainPosAttrib);
- gl.vertexAttribPointer(mainPosAttrib, 2, gl.FLOAT, false, 0, 0);
+ if (this.aQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(this.aQuadPosLoc);
+ gl.vertexAttribPointer(this.aQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ }
}
}
@@ -2442,7 +2661,8 @@ export class ViewportCompositor {
viewportH: number,
transform: ViewportTransform,
dpr: number,
- opacityMultiplier: number = 1.0
+ opacityMultiplier: number = 1.0,
+ currentFbo: WebGLFramebuffer | null = null
): void {
if (!this.ensureLayerFbo(viewportW, viewportH) || !this.stylesProgram) {
this.renderSingleLayer(gl, layer, dimensions, grid, frustum, opacityMultiplier);
@@ -2482,8 +2702,8 @@ export class ViewportCompositor {
const virtualLayer: LayerItem = { ...layer, opacity: 1.0, blendMode: 'normal' };
this.renderSingleLayer(gl, virtualLayer, dimensions, grid, expandedFrustum, 1.0);
- // 2. Restore default framebuffer (canvas)
- gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ // 2. Restore active target framebuffer (folder FBO or default screen canvas)
+ gl.bindFramebuffer(gl.FRAMEBUFFER, currentFbo);
gl.viewport(0, 0, viewportW, viewportH);
// 3. Set layer blend mode
@@ -2493,9 +2713,10 @@ export class ViewportCompositor {
gl.useProgram(this.stylesProgram);
gl.bindBuffer(gl.ARRAY_BUFFER, this.stylesQuadBuffer);
- const posAttr = gl.getAttribLocation(this.stylesProgram, 'a_quadPos');
- gl.enableVertexAttribArray(posAttr);
- gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0);
+ if (this.aStylesQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(this.aStylesQuadPosLoc);
+ gl.vertexAttribPointer(this.aStylesQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ }
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, this.layerTexture);
@@ -2553,26 +2774,26 @@ export class ViewportCompositor {
if (this.program) {
gl.useProgram(this.program);
gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuffer);
- const mainPosAttrib = gl.getAttribLocation(this.program, 'a_quadPos');
- gl.enableVertexAttribArray(mainPosAttrib);
- gl.vertexAttribPointer(mainPosAttrib, 2, gl.FLOAT, false, 0, 0);
+ if (this.aQuadPosLoc >= 0) {
+ gl.enableVertexAttribArray(this.aQuadPosLoc);
+ gl.vertexAttribPointer(this.aQuadPosLoc, 2, gl.FLOAT, false, 0, 0);
+ }
}
}
/**
- * Evict least recently used tile textures when texture cache exceeds threshold.
+ * Evict least recently used tile textures when texture pool exceeds threshold.
*/
private evictStaleTextures(): void {
- if (!this.gl) return;
- const entries = Array.from(this.textureCache.entries());
- entries.sort((a, b) => a[1].lastUsed - b[1].lastUsed);
-
- // Evict oldest 500 textures
- const toRemove = entries.slice(0, 500);
- for (const [key, item] of toRemove) {
- this.gl.deleteTexture(item.texture);
- this.textureCache.delete(key);
+ if (!this.gl || this.texturePool.length <= ViewportCompositor.MAX_TEXTURE_POOL_SIZE) return;
+ this.texturePool.sort((a, b) => a.lastUsed - b.lastUsed);
+ while (this.texturePool.length > ViewportCompositor.MAX_TEXTURE_POOL_SIZE) {
+ const slot = this.texturePool.shift();
+ if (slot) {
+ if (slot.currentKey) this.activePoolByKey.delete(slot.currentKey);
+ this.gl.deleteTexture(slot.texture);
+ }
}
}
@@ -2828,10 +3049,7 @@ export class ViewportCompositor {
*/
public dispose(): void {
if (this.gl) {
- for (const item of this.textureCache.values()) {
- this.gl.deleteTexture(item.texture);
- }
- this.textureCache.clear();
+ this.invalidateTileTextures();
for (const item of this.maskTextureCache.values()) {
this.gl.deleteTexture(item.texture);
}
@@ -2879,6 +3097,9 @@ export class ViewportCompositor {
for (const item of this.folderFbos) {
this.gl.deleteFramebuffer(item.fbo);
this.gl.deleteTexture(item.texture);
+ if (item.stencilRb && typeof this.gl.deleteRenderbuffer === 'function') {
+ this.gl.deleteRenderbuffer(item.stencilRb);
+ }
}
this.folderFbos = [];
if (this.layerFbo) {
@@ -2897,5 +3118,13 @@ export class ViewportCompositor {
if (this.fallbackTileCanvas) {
this.fallbackTileCanvas = null;
}
+ if (typeof this.canvas.removeEventListener === 'function') {
+ if (this.onContextLostHandler) {
+ this.canvas.removeEventListener('webglcontextlost', this.onContextLostHandler);
+ }
+ if (this.onContextRestoredHandler) {
+ this.canvas.removeEventListener('webglcontextrestored', this.onContextRestoredHandler);
+ }
+ }
}
}
diff --git a/src/utils/cspParser.ts b/src/utils/cspParser.ts
index 36ea855..ca74293 100644
--- a/src/utils/cspParser.ts
+++ b/src/utils/cspParser.ts
@@ -1,5 +1,5 @@
import initSqlJs, { Database } from 'sql.js';
-import { inflateSync } from 'fflate';
+import { unzlibSync, inflateSync } from 'fflate';
import { BlendMode, LayerItem, LoadedDocument } from '../types/editor';
import { createCanvasThumbnail } from './canvasUtils';
@@ -193,8 +193,13 @@ function renderCspBitmapToCanvas(
for (let i = 0; i < blockData.length - 8; i++) {
if (blockData[i] === 0x78 && (blockData[i + 1] === 0x9c || blockData[i + 1] === 0x01 || blockData[i + 1] === 0xda)) {
try {
- const slice = blockData.slice(i);
- const decompressed = inflateSync(slice);
+ const sub = blockData.subarray(i);
+ let decompressed: Uint8Array;
+ try {
+ decompressed = unzlibSync(sub);
+ } catch {
+ decompressed = inflateSync(sub.subarray(2));
+ }
// Expected: 256*256 bytes alpha + 256*256*4 bytes BGRX = 327680 bytes
if (decompressed.length >= BLOCK_SIZE * BLOCK_SIZE * 5) {
diff --git a/src/utils/filterEngine.ts b/src/utils/filterEngine.ts
index bdac006..2d88a09 100644
--- a/src/utils/filterEngine.ts
+++ b/src/utils/filterEngine.ts
@@ -576,10 +576,12 @@ export class WebGlFilterEngine {
this.canvas.height = h;
}
- // Upload source canvas to texA
+ // Upload source canvas to texA (flip Y so WebGL bottom-left UV matches Canvas2D top-left origin)
gl.bindTexture(gl.TEXTURE_2D, this.texA);
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, targetCanvas);
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
diff --git a/src/utils/floodFill.ts b/src/utils/floodFill.ts
index 3c32215..3269175 100644
--- a/src/utils/floodFill.ts
+++ b/src/utils/floodFill.ts
@@ -1,4 +1,5 @@
import { LayerItem, CanvasDimensions, DirtyRect } from '../types/editor';
+import { getCanvasCompositeOperation } from './canvasUtils';
/**
* Parses color string (hex #RRGGBB, #RGB, or rgba) to [r, g, b, a (0-255)].
@@ -44,6 +45,8 @@ export interface FloodFillOptions {
areaScale?: number;
/** Smooths boundary pixels against anti-aliased line art */
antiAlias?: boolean;
+ /** Optional active selection mask (1/255 = inside selection, 0 = outside) */
+ selectionMask?: Uint8Array | null;
}
/**
@@ -70,7 +73,7 @@ export function compositeVisibleLayers(
ctx.save();
ctx.globalAlpha = layer.opacity ?? 1.0;
- ctx.globalCompositeOperation = (layer.blendMode as GlobalCompositeOperation) || 'source-over';
+ ctx.globalCompositeOperation = getCanvasCompositeOperation(layer.blendMode);
ctx.drawImage(lCanvas, 0, 0);
ctx.restore();
}
@@ -105,7 +108,7 @@ export function compositeReferenceLayers(
ctx.save();
ctx.globalAlpha = layer.opacity ?? 1.0;
- ctx.globalCompositeOperation = (layer.blendMode as GlobalCompositeOperation) || 'source-over';
+ ctx.globalCompositeOperation = getCanvasCompositeOperation(layer.blendMode);
ctx.drawImage(lCanvas, 0, 0);
ctx.restore();
}
@@ -286,8 +289,16 @@ export function executeFloodFill(
barrierMask = closed;
}
+ const selectionMask = options?.selectionMask;
+ if (selectionMask && selectionMask.length === totalPixels && selectionMask[py * width + px] === 0) {
+ return { dirtyRect: null, modified: false };
+ }
+
const matchesSeed = (x: number, y: number): boolean => {
const pIdx = y * width + x;
+ if (selectionMask && selectionMask.length === totalPixels && selectionMask[pIdx] === 0) {
+ return false;
+ }
if (barrierMask) {
return barrierMask[pIdx] === 0;
}
@@ -442,11 +453,21 @@ export function executeFloodFill(
finalMask = erodeBinaryMask(visited, width, height, Math.abs(areaScale));
}
+ if (antiAlias) {
+ minX = Math.max(0, minX - 1);
+ minY = Math.max(0, minY - 1);
+ maxX = Math.min(width - 1, maxX + 1);
+ maxY = Math.min(height - 1, maxY + 1);
+ }
+
// Write filled pixels to targetData
for (let y = minY; y <= maxY; y++) {
const rowOffset = y * width;
for (let x = minX; x <= maxX; x++) {
const pIdx = rowOffset + x;
+ if (selectionMask && selectionMask.length === totalPixels && selectionMask[pIdx] === 0) {
+ continue;
+ }
if (finalMask[pIdx]) {
const tIdx = pIdx * 4;
targetData[tIdx] = fillR;
@@ -476,13 +497,6 @@ export function executeFloodFill(
}
}
- if (antiAlias) {
- minX = Math.max(0, minX - 1);
- minY = Math.max(0, minY - 1);
- maxX = Math.min(width - 1, maxX + 1);
- maxY = Math.min(height - 1, maxY + 1);
- }
-
targetCtx.putImageData(targetImgData, 0, 0);
if (sourceCanvas) {
diff --git a/src/utils/frameEngine.ts b/src/utils/frameEngine.ts
index 980f8eb..02dd537 100644
--- a/src/utils/frameEngine.ts
+++ b/src/utils/frameEngine.ts
@@ -184,15 +184,28 @@ export function bisectComicFrame(
}
poly2.push({ ...hitA.point });
- // 4. Inset both polygons by halfGutter along normal
- // Offset poly1 along +normal and poly2 along -normal
+ // 4. Inset both polygons by halfGutter away from the cut line
+ let c1x = 0;
+ let c1y = 0;
+ for (const p of poly1) {
+ c1x += p.x;
+ c1y += p.y;
+ }
+ c1x /= Math.max(1, poly1.length);
+ c1y /= Math.max(1, poly1.length);
+ const midCutX = (hitA.point.x + hitB.point.x) * 0.5;
+ const midCutY = (hitA.point.y + hitB.point.y) * 0.5;
+ const dotSide = (c1x - midCutX) * normal.x + (c1y - midCutY) * normal.y;
+ const sign = dotSide >= 0 ? 1 : -1;
+ const nX = normal.x * sign;
+ const nY = normal.y * sign;
+
const insetPoly1 = poly1.map((p) => {
- // Only offset cut seam vertices (hitA, hitB)
const isSeam =
Math.hypot(p.x - hitA.point.x, p.y - hitA.point.y) < 1e-3 ||
Math.hypot(p.x - hitB.point.x, p.y - hitB.point.y) < 1e-3;
if (isSeam) {
- return { x: p.x + normal.x * halfGutter, y: p.y + normal.y * halfGutter };
+ return { x: p.x + nX * halfGutter, y: p.y + nY * halfGutter };
}
return p;
});
@@ -202,7 +215,7 @@ export function bisectComicFrame(
Math.hypot(p.x - hitA.point.x, p.y - hitA.point.y) < 1e-3 ||
Math.hypot(p.x - hitB.point.x, p.y - hitB.point.y) < 1e-3;
if (isSeam) {
- return { x: p.x - normal.x * halfGutter, y: p.y - normal.y * halfGutter };
+ return { x: p.x - nX * halfGutter, y: p.y - nY * halfGutter };
}
return p;
});
diff --git a/src/utils/imageLoader.ts b/src/utils/imageLoader.ts
index a637605..397a6e3 100644
--- a/src/utils/imageLoader.ts
+++ b/src/utils/imageLoader.ts
@@ -1,5 +1,6 @@
import { LoadedDocument, LayerItem, CanvasColorMode } from '../types/editor';
import { createCanvasThumbnail } from './canvasUtils';
+import { renderVectorLayer } from './vectorEngine';
/**
* Loads standard raster/vector image formats (.png, .jpg, .jpeg, .webp, .bmp, .gif, .svg).
@@ -108,43 +109,82 @@ export async function openFile(file: File): Promise<LoadedDocument> {
if (project.layers && Array.isArray(project.layers)) {
const width = project.dimensions?.width || 1440;
const height = project.dimensions?.height || 900;
+ const dpi = project.dimensions?.dpi || 300;
const colorMode: CanvasColorMode = project.colorMode || 'color';
- const layers: LayerItem[] = project.layers;
+ const layers: LayerItem[] = project.layers.map((l: any) => {
+ // Ensure stale/serialized plain-object maskCanvas does not break CanvasRenderingContext2D calls
+ if (l.maskCanvas && typeof l.maskCanvas.getContext !== 'function') {
+ return { ...l, maskCanvas: undefined };
+ }
+ return l;
+ });
const layerCanvases = new Map<string, HTMLCanvasElement>();
const loadPromises = layers.map((layer) => {
- if (layer.type === 'folder') return Promise.resolve();
- return new Promise<void>((resolve) => {
- const dataUrl = project.canvases?.[layer.id];
- const canvas = document.createElement('canvas');
- canvas.width = width;
- canvas.height = height;
-
- if (dataUrl) {
- const img = new Image();
- img.onload = () => {
- const ctx = canvas.getContext('2d');
- ctx?.drawImage(img, 0, 0);
- layerCanvases.set(layer.id, canvas);
- resolve();
- };
- img.onerror = () => {
- layerCanvases.set(layer.id, canvas);
- resolve();
- };
- img.src = dataUrl;
- } else {
- layerCanvases.set(layer.id, canvas);
- resolve();
- }
- });
+ const tasks: Promise<void>[] = [];
+
+ // Reconstruct maskCanvas if saved in project.masks
+ const maskDataUrl = project.masks?.[layer.id];
+ if (maskDataUrl) {
+ tasks.push(
+ new Promise<void>((resolve) => {
+ const mCanvas = document.createElement('canvas');
+ mCanvas.width = width;
+ mCanvas.height = height;
+ const mImg = new Image();
+ mImg.onload = () => {
+ mCanvas.getContext('2d')?.drawImage(mImg, 0, 0);
+ layer.maskCanvas = mCanvas;
+ layer.maskVersion = (layer.maskVersion || 0) + 1;
+ resolve();
+ };
+ mImg.onerror = () => resolve();
+ mImg.src = maskDataUrl;
+ })
+ );
+ }
+
+ if (layer.type !== 'folder' && layer.type !== 'adjustment') {
+ tasks.push(
+ new Promise<void>((resolve) => {
+ const dataUrl = project.canvases?.[layer.id];
+ const canvas = document.createElement('canvas');
+ canvas.width = width;
+ canvas.height = height;
+
+ if (dataUrl) {
+ const img = new Image();
+ img.onload = () => {
+ const ctx = canvas.getContext('2d');
+ ctx?.drawImage(img, 0, 0);
+ layerCanvases.set(layer.id, canvas);
+ resolve();
+ };
+ img.onerror = () => {
+ layerCanvases.set(layer.id, canvas);
+ resolve();
+ };
+ img.src = dataUrl;
+ } else {
+ if (layer.type === 'vector' && layer.vectorStrokes && layer.vectorStrokes.length > 0) {
+ const ctx = canvas.getContext('2d');
+ if (ctx) renderVectorLayer(ctx, layer.vectorStrokes);
+ }
+ layerCanvases.set(layer.id, canvas);
+ resolve();
+ }
+ })
+ );
+ }
+
+ return Promise.all(tasks).then(() => {});
});
await Promise.all(loadPromises);
return {
name: project.name || file.name.replace(/\.[^/.]+$/, ''),
- dimensions: { width, height },
+ dimensions: { width, height, dpi },
colorMode,
layers,
layerCanvases,
diff --git a/src/utils/layerEffectsEngine.ts b/src/utils/layerEffectsEngine.ts
index c709861..81cba10 100644
--- a/src/utils/layerEffectsEngine.ts
+++ b/src/utils/layerEffectsEngine.ts
@@ -7,7 +7,7 @@ export type ExpressionColor = 'color' | 'gray' | 'monochrome';
export interface LayerEffectOptions {
frequency?: number;
angle?: number;
- dotShape?: 'circle' | 'euclidean';
+ dotShape?: 'circle' | 'euclidean' | 'line' | 'diamond';
dpi?: number;
}
@@ -81,23 +81,40 @@ export function applyExpressionColorToImageData(
data[i + 2] = lum;
}
} else if (mode === 'monochrome') {
- const u32 = new Uint32Array(imgData.data.buffer);
- const u32Len = u32.length;
- for (let i = 0; i < u32Len; i++) {
- const pix = u32[i];
- const a = (pix >>> 24) & 0xFF;
+ for (let i = 0; i < len; i += 4) {
+ const a = data[i + 3];
if (a < 64) {
- u32[i] = 0;
+ data[i] = 0;
+ data[i + 1] = 0;
+ data[i + 2] = 0;
+ data[i + 3] = 0;
continue;
}
- const r = pix & 0xFF;
- const g = (pix >>> 8) & 0xFF;
- const b = (pix >>> 16) & 0xFF;
- const lum = (19595 * r + 38470 * g + 7471 * b + 32768) >> 16;
+ const lum = (19595 * data[i] + 38470 * data[i + 1] + 7471 * data[i + 2] + 32768) >> 16;
if (lum < threshold) {
- u32[i] = expressBlack ? 0xFF000000 : 0;
+ if (expressBlack) {
+ data[i] = 0;
+ data[i + 1] = 0;
+ data[i + 2] = 0;
+ data[i + 3] = 255;
+ } else {
+ data[i] = 0;
+ data[i + 1] = 0;
+ data[i + 2] = 0;
+ data[i + 3] = 0;
+ }
} else {
- u32[i] = expressWhite ? 0xFFFFFFFF : 0;
+ if (expressWhite) {
+ data[i] = 255;
+ data[i + 1] = 255;
+ data[i + 2] = 255;
+ data[i + 3] = 255;
+ } else {
+ data[i] = 0;
+ data[i + 1] = 0;
+ data[i + 2] = 0;
+ data[i + 3] = 0;
+ }
}
}
}
diff --git a/src/utils/liquifyEngine.ts b/src/utils/liquifyEngine.ts
index 8e72080..99cf1b9 100644
--- a/src/utils/liquifyEngine.ts
+++ b/src/utils/liquifyEngine.ts
@@ -518,6 +518,15 @@ export function createLiquifySelectionMask(
): Uint8Array | null {
if (!selection) return null;
+ if (selection.mask && selection.maskWidth === width && selection.maskHeight === height) {
+ const mask = new Uint8Array(width * height);
+ const src = selection.mask;
+ for (let i = 0; i < src.length; i++) {
+ if (src[i] >= 64) mask[i] = 1;
+ }
+ return mask;
+ }
+
const mask = new Uint8Array(width * height);
const { bounds, type, polygon } = selection;
diff --git a/src/utils/mangaTextEngine.ts b/src/utils/mangaTextEngine.ts
index 9e23fe1..bbe998b 100644
--- a/src/utils/mangaTextEngine.ts
+++ b/src/utils/mangaTextEngine.ts
@@ -22,6 +22,7 @@ export interface MangaTextOptions {
lineHeightRatio?: number;
maxWidth?: number;
maxHeight?: number;
+ anchorTopLeft?: boolean;
}
export interface PositionedGlyph {
@@ -78,17 +79,28 @@ export function computeMangaTextLayout(
// Standard horizontal-tb layout
const glyphs: PositionedGlyph[] = [];
const charWidth = fontSize * 0.6; // estimated fallback
+ const linesChars = rawLines.map((line) => Array.from(line));
let maxLineWidth = 0;
+ for (const chars of linesChars) {
+ const w = chars.length * charWidth;
+ if (w > maxLineWidth) maxLineWidth = w;
+ }
+ const boxWidth = Math.max(fontSize, maxLineWidth);
- rawLines.forEach((line, lineIdx) => {
+ linesChars.forEach((chars, lineIdx) => {
const lineY = lineIdx * lineSpacing + fontSize * 0.5;
- const lineWidth = line.length * charWidth;
- if (lineWidth > maxLineWidth) maxLineWidth = lineWidth;
+ const lineWidth = chars.length * charWidth;
+ let startX = 0;
+ if (options.align === 'center') {
+ startX = (boxWidth - lineWidth) * 0.5;
+ } else if (options.align === 'right') {
+ startX = boxWidth - lineWidth;
+ }
- for (let cIdx = 0; cIdx < line.length; cIdx++) {
+ for (let cIdx = 0; cIdx < chars.length; cIdx++) {
glyphs.push({
- char: line[cIdx],
- x: cIdx * charWidth + charWidth * 0.5,
+ char: chars[cIdx],
+ x: startX + cIdx * charWidth + charWidth * 0.5,
y: lineY,
rotateDeg: 0,
});
@@ -98,7 +110,7 @@ export function computeMangaTextLayout(
const totalHeight = rawLines.length * lineSpacing;
return {
glyphs,
- width: Math.max(fontSize, maxLineWidth),
+ width: boxWidth,
height: Math.max(fontSize, totalHeight),
};
}
@@ -110,12 +122,13 @@ export function computeMangaTextLayout(
const glyphs: PositionedGlyph[] = [];
rawLines.forEach((line, colIndex) => {
+ const chars = Array.from(line);
// In vertical-rl, col 0 is at rightmost position (x = (numColumns - 1 - colIndex) * lineSpacing)
const colX = (numColumns - 1 - colIndex) * lineSpacing + lineSpacing * 0.5;
let currentY = fontSize * 0.6;
- for (let cIdx = 0; cIdx < line.length; cIdx++) {
- const char = line[cIdx];
+ for (let cIdx = 0; cIdx < chars.length; cIdx++) {
+ const char = chars[cIdx];
let rotateDeg = 0;
let dx = 0;
let dy = 0;
@@ -177,7 +190,10 @@ export function renderMangaTextToCanvas(
let offsetX = originX - layout.width * 0.5;
let offsetY = originY - layout.height * 0.5;
- if (options.align === 'left') {
+ if (options.anchorTopLeft) {
+ offsetX = originX + 6;
+ offsetY = originY + 6;
+ } else if (options.align === 'left') {
offsetX = originX;
} else if (options.align === 'right') {
offsetX = originX - layout.width;
diff --git a/src/utils/mannequin3D.ts b/src/utils/mannequin3D.ts
index 2fdb836..cc01a0a 100644
--- a/src/utils/mannequin3D.ts
+++ b/src/utils/mannequin3D.ts
@@ -193,13 +193,14 @@ export function createProceduralMannequin(): {
const geometries: THREE.BufferGeometry[] = [];
const addPart = (
- geom: THREE.BufferGeometry,
+ rawGeom: THREE.BufferGeometry,
boneIndex: number,
offset: THREE.Vector3,
rot?: THREE.Euler,
scale?: THREE.Vector3
) => {
- geom = geom.clone();
+ const geom = rawGeom.clone();
+ rawGeom.dispose();
if (scale) geom.scale(scale.x, scale.y, scale.z);
if (rot) geom.applyQuaternion(new THREE.Quaternion().setFromEuler(rot));
geom.translate(offset.x, offset.y, offset.z);
@@ -273,6 +274,9 @@ export function createProceduralMannequin(): {
addPart(new THREE.BoxGeometry(0.08, 0.06, 0.18), 18, new THREE.Vector3(-0.12, 0.05, 0.04));
const mergedGeometry = BufferGeometryUtils.mergeGeometries(geometries);
+ for (const g of geometries) {
+ g.dispose();
+ }
mergedGeometry.computeVertexNormals();
// CSP Mannequin Clay Material
@@ -470,13 +474,16 @@ export function createIKHandles(): {
* Applies studio pose presets to humanoid mannequin bones.
*/
export function applyPosePreset(bones: HumanoidBones, preset: PosePresetName): void {
- // Reset all bones to identity rotation first
+ // Reset all bones to identity rotation and restore default hip height first
for (const key of Object.keys(bones)) {
const b = bones[key];
if (b) {
b.quaternion.identity();
}
}
+ if (bones.hips) {
+ bones.hips.position.set(0, 0.95, 0);
+ }
const rad = (deg: number) => (deg * Math.PI) / 180;
diff --git a/src/utils/pencilEngine.ts b/src/utils/pencilEngine.ts
index 0492faf..5698c06 100644
--- a/src/utils/pencilEngine.ts
+++ b/src/utils/pencilEngine.ts
@@ -1,5 +1,5 @@
import { Point } from '../types/editor';
-import { getTintedMasterCanvas, drawSingleStamp } from './stampEngine';
+import { getTintedMasterCanvas, drawSingleStamp, buildCubicArcLengthTable, getCubicPointAtArcLength } from './stampEngine';
/**
* Real Pencil Physics & Paper Grain Simulation Engine
@@ -103,9 +103,9 @@ export const PENCIL_CONFIGS: Record<PencilGrade, PencilGradeConfig> = {
* Precalculated at startup into a 1D Uint8Array for instant O(1) single-cycle lookups.
* Models cold-press cotton sketchbook paper with micro-mineral tooth and intertwined cellulose fibers.
*/
-const GRAIN_SIZE = 512;
+export const GRAIN_SIZE = 512;
const GRAIN_MASK = GRAIN_SIZE - 1;
-const paperGrainTable = new Uint8Array(GRAIN_SIZE * GRAIN_SIZE);
+export const paperGrainTable = new Uint8Array(GRAIN_SIZE * GRAIN_SIZE);
// Deterministic fast PRNG for seamless texture synthesis
function sfc32(a: number, b: number, c: number, d: number) {
@@ -161,12 +161,28 @@ function sfc32(a: number, b: number, c: number, d: number) {
/**
* World-anchored paper grain elevation query at canvas coordinate (x, y).
- * Returns integer 0 to 255 representing paper tooth height.
+ * Uses smooth sub-pixel bilinear interpolation across the 512x512 seamless paper grain table.
+ * Returns number 0 to 255 representing paper tooth height.
*/
export function getPaperGrain(x: number, y: number): number {
- const ix = (Math.floor(x) & GRAIN_MASK) >>> 0;
- const iy = (Math.floor(y) & GRAIN_MASK) >>> 0;
- return paperGrainTable[iy * GRAIN_SIZE + ix];
+ const fx = Math.floor(x);
+ const fy = Math.floor(y);
+ const tx = x - fx;
+ const ty = y - fy;
+
+ const x0 = (fx & GRAIN_MASK) >>> 0;
+ const y0 = (fy & GRAIN_MASK) >>> 0;
+ const x1 = ((fx + 1) & GRAIN_MASK) >>> 0;
+ const y1 = ((fy + 1) & GRAIN_MASK) >>> 0;
+
+ const v00 = paperGrainTable[y0 * GRAIN_SIZE + x0];
+ const v10 = paperGrainTable[y0 * GRAIN_SIZE + x1];
+ const v01 = paperGrainTable[y1 * GRAIN_SIZE + x0];
+ const v11 = paperGrainTable[y1 * GRAIN_SIZE + x1];
+
+ const top = v00 + (v10 - v00) * tx;
+ const bottom = v01 + (v11 - v01) * tx;
+ return Math.round(top + (bottom - top) * ty);
}
/**
@@ -331,35 +347,34 @@ export function drawPencilCubicBezierSegment(
_userHardness?: number,
remainderDist: number = 0,
alphaLocked: boolean = false,
- isTransparentInk: boolean = false
+ isTransparentInk: boolean = false,
+ useTilt: boolean = true
): number {
const config = PENCIL_CONFIGS[grade] || PENCIL_CONFIGS['pencil-2b'];
- const dx = p3.x - p0.x;
- const dy = p3.y - p0.y;
- const dist = Math.hypot(dx, dy);
- if (dist < 0.15) return remainderDist;
+ const arcTable = buildCubicArcLengthTable(p0, c1, c2, p3);
+ const dist = arcTable.totalLength;
+ if (dist < 0.1) return Math.max(0, remainderDist - dist);
const graphiteMaster = getGraphiteTipMaster(grade, color);
- const avgWidth = Math.max(1, (p0.width + p3.width) / 2);
- const stepDist = Math.max(0.4, Math.min(1.6, avgWidth * (config.spacing || 0.07)));
- const numSteps = Math.max(2, Math.ceil(dist / stepDist));
-
+ const isMonoCrisp = _userHardness !== undefined && _userHardness >= 0.99;
const baseThreshold = config.thresholdBase;
const sens = config.thresholdPressureSensitivity;
- const flow = userFlow * config.flow;
- const stepT = 1.0 / numSteps;
+ const flow = isMonoCrisp ? 1.0 : userFlow * config.flow;
+ const spacingRatio = config.spacing || 0.07;
- for (let i = 0; i <= numSteps; i++) {
- const t = i * stepT;
- const pt = getCubicBezierPoint(p0, c1, c2, p3, t);
+ let currentDist = Math.max(0, remainderDist);
+ while (currentDist <= dist) {
+ const pt = getCubicPointAtArcLength(p0, c1, c2, p3, currentDist, arcTable);
const pressure = Math.min(Math.max(pt.pressure || 0.5, 0.05), 1.0);
- const tiltX = pt.tiltX ?? 0;
- const tiltY = pt.tiltY ?? 0;
+ const tiltX = useTilt ? (pt.tiltX ?? 0) : 0;
+ const tiltY = useTilt ? (pt.tiltY ?? 0) : 0;
const tiltAngleDeg = Math.min(90, Math.sqrt(tiltX * tiltX + tiltY * tiltY));
const tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180);
- const curWidth = Math.max(0.6, pt.width * (1.0 + tiltMagnitude * 2.2));
+ const minStampW = isMonoCrisp ? 1.35 : 0.6;
+ const curWidth = Math.max(minStampW, pt.width * (1.0 + tiltMagnitude * 2.2));
+ const stepDist = Math.max(0.25, Math.min(1.8, Math.max(0.6, pt.width) * spacingRatio));
const effThreshold = Math.max(
15,
@@ -381,14 +396,29 @@ export function drawPencilCubicBezierSegment(
stampAngle += (pt.twist * Math.PI) / 180;
}
- const paperHeight = getPaperGrain(pt.x, pt.y);
+ // Multi-sample Quincunx grain integration for wider graphite leads (> 4px) to prevent whole-stamp blinking
+ let paperHeight: number;
+ if (curWidth > 4.0) {
+ const off = curWidth * 0.25;
+ paperHeight = (
+ getPaperGrain(pt.x, pt.y) * 2 +
+ getPaperGrain(pt.x - off, pt.y - off) +
+ getPaperGrain(pt.x + off, pt.y - off) +
+ getPaperGrain(pt.x - off, pt.y + off) +
+ getPaperGrain(pt.x + off, pt.y + off)
+ ) / 6;
+ } else {
+ paperHeight = getPaperGrain(pt.x, pt.y);
+ }
- if (paperHeight >= effThreshold) {
- const heightFactor = Math.min(1.0, (paperHeight - effThreshold + 25) / 55);
- const dabAlpha = Math.min(
- 1.0,
- Math.max(0.04, flow * (0.35 + 0.65 * pressure) * heightFactor)
- );
+ if (isMonoCrisp || paperHeight >= effThreshold) {
+ const heightFactor = isMonoCrisp ? 1.0 : Math.min(1.0, (paperHeight - effThreshold + 25) / 55);
+ const dabAlpha = isMonoCrisp
+ ? 1.0
+ : Math.min(
+ 1.0,
+ Math.max(0.04, flow * (0.35 + 0.65 * pressure) * heightFactor)
+ );
drawSingleStamp(
ctx,
@@ -422,9 +452,11 @@ export function drawPencilCubicBezierSegment(
isTransparentInk
);
}
+
+ currentDist += stepDist;
}
- return 0;
+ return Math.max(0, currentDist - dist);
}
/**
@@ -480,6 +512,7 @@ export function drawPencilDot(
) {
const config = PENCIL_CONFIGS[grade] || PENCIL_CONFIGS['pencil-2b'];
const graphiteMaster = getGraphiteTipMaster(grade, color);
+ const isMonoCrisp = _userHardness !== undefined && _userHardness >= 0.99;
const pressure = Math.min(Math.max(point.pressure || 0.5, 0.05), 1.0);
const tiltX = point.tiltX ?? 0;
@@ -487,7 +520,7 @@ export function drawPencilDot(
const tiltAngleDeg = Math.min(90, Math.sqrt(tiltX * tiltX + tiltY * tiltY));
const tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180);
- const curWidth = Math.max(0.6, point.width * (1.0 + tiltMagnitude * 2.2));
+ const curWidth = Math.max(isMonoCrisp ? 1.35 : 0.6, point.width * (1.0 + tiltMagnitude * 2.2));
const effThreshold = Math.max(
15,
@@ -510,12 +543,14 @@ export function drawPencilDot(
}
const paperHeight = getPaperGrain(point.x, point.y);
- const heightFactor = paperHeight >= effThreshold
+ const heightFactor = isMonoCrisp
+ ? 1.0
+ : paperHeight >= effThreshold
? Math.min(1.0, (paperHeight - effThreshold + 25) / 55)
: 0.15;
- const flow = userFlow * config.flow;
- const dabAlpha = Math.min(1.0, Math.max(0.05, flow * pressure * heightFactor));
+ const flow = isMonoCrisp ? 1.0 : userFlow * config.flow;
+ const dabAlpha = isMonoCrisp ? 1.0 : Math.min(1.0, Math.max(0.05, flow * pressure * heightFactor));
drawSingleStamp(
ctx,
diff --git a/src/utils/presetBrushes.ts b/src/utils/presetBrushes.ts
index fa0e073..0ac34f0 100644
--- a/src/utils/presetBrushes.ts
+++ b/src/utils/presetBrushes.ts
@@ -1,4 +1,5 @@
import { BrushPresetId, BrushSettings } from '../types/editor';
+import { dabHashFloat } from '../engine/CspBrushEngine';
export type BrushCategory = 'pencil-line' | 'color-paint';
@@ -27,18 +28,132 @@ export function getSquareTipDataUrl(): string {
const canvas = document.createElement('canvas');
canvas.width = 64;
canvas.height = 64;
- const ctx = canvas.getContext('2d')!;
+ const ctx = canvas.getContext('2d');
+ if (!ctx || typeof canvas.toDataURL !== 'function') return '';
ctx.clearRect(0, 0, 64, 64);
ctx.fillStyle = '#ffffff';
- // Crisp square with 1px smooth edge for anti-aliasing
ctx.fillRect(4, 4, 56, 56);
_squareTipDataUrl = canvas.toDataURL('image/png');
return _squareTipDataUrl;
}
+let _realGPenTipDataUrl: string | null = null;
+export function getRealGPenTipDataUrl(): string {
+ if (_realGPenTipDataUrl) return _realGPenTipDataUrl;
+ const size = 96;
+ const canvas = document.createElement('canvas');
+ canvas.width = size;
+ canvas.height = size;
+ const ctx = canvas.getContext('2d');
+ if (!ctx || typeof canvas.toDataURL !== 'function' || typeof ctx.createImageData !== 'function') {
+ return '';
+ }
+
+ const imgData = ctx.createImageData(size, size);
+ const data = imgData.data;
+ const half = size * 0.5;
+ const maxR = half - 3;
+
+ for (let y = 0; y < size; y++) {
+ const dy = y - half;
+ for (let x = 0; x < size; x++) {
+ const dx = x - half;
+ const r = Math.hypot(dx, dy) / maxR;
+ if (r > 1.08) continue;
+
+ const angleIdx = Math.round(((Math.atan2(dy, dx) + Math.PI) / (Math.PI * 2)) * 96);
+ const angularTooth =
+ (dabHashFloat(angleIdx, 0, 1, 701) - 0.5) * 0.14 +
+ (dabHashFloat(Math.floor(angleIdx * 0.5), 1, 2, 709) - 0.5) * 0.1;
+ const microGrain = (dabHashFloat(x, y, 3, 719) - 0.5) * 0.12;
+ const effEdge = 0.9 + angularTooth + microGrain * 0.5;
+
+ let alpha = 0;
+ if (r <= effEdge - 0.08) {
+ alpha = 1.0;
+ } else if (r < effEdge + 0.08) {
+ const t = (effEdge + 0.08 - r) / 0.16;
+ alpha = t * t * (3 - 2 * t);
+ }
+
+ if (alpha > 0.01) {
+ const idx = (y * size + x) * 4;
+ data[idx] = 255;
+ data[idx + 1] = 255;
+ data[idx + 2] = 255;
+ data[idx + 3] = Math.round(alpha * 255);
+ }
+ }
+ }
+
+ ctx.putImageData(imgData, 0, 0);
+ _realGPenTipDataUrl = canvas.toDataURL('image/png');
+ return _realGPenTipDataUrl;
+}
+
+let _bristleTipDataUrl: string | null = null;
+export function getBristleTipDataUrl(): string {
+ if (_bristleTipDataUrl) return _bristleTipDataUrl;
+ const size = 96;
+ const canvas = document.createElement('canvas');
+ canvas.width = size;
+ canvas.height = size;
+ const ctx = canvas.getContext('2d');
+ if (!ctx || typeof canvas.toDataURL !== 'function' || typeof ctx.createImageData !== 'function') {
+ return '';
+ }
+
+ const imgData = ctx.createImageData(size, size);
+ const data = imgData.data;
+ const half = size * 0.5;
+ const maxR = half - 4;
+
+ // Deterministic multi-filament hog-bristle cluster
+ const filaments: { cx: number; cy: number; rad: number; str: number }[] = [];
+ const count = 42;
+ for (let i = 0; i < count; i++) {
+ const u = dabHashFloat(i, 11, i, 811);
+ const v = dabHashFloat(i, 23, i, 823);
+ const rr = maxR * 0.86 * Math.sqrt(u);
+ const th = v * Math.PI * 2;
+ filaments.push({
+ cx: half + rr * Math.cos(th),
+ cy: half + rr * Math.sin(th) * 0.68,
+ rad: 2.2 + dabHashFloat(i, 37, i, 829) * 3.8,
+ str: 0.55 + dabHashFloat(i, 41, i, 839) * 0.45,
+ });
+ }
+
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ let acc = 0;
+ for (let f = 0; f < filaments.length; f++) {
+ const fil = filaments[f];
+ const d = Math.hypot(x - fil.cx, y - fil.cy) / fil.rad;
+ if (d < 1.0) {
+ const w = (1.0 - d) * (1.0 - d) * fil.str;
+ if (w > acc) acc = Math.min(1.0, acc * 0.35 + w);
+ }
+ }
+ if (acc > 0.02) {
+ const idx = (y * size + x) * 4;
+ data[idx] = 255;
+ data[idx + 1] = 255;
+ data[idx + 2] = 255;
+ data[idx + 3] = Math.min(255, Math.round(acc * 255));
+ }
+ }
+ }
+
+ ctx.putImageData(imgData, 0, 0);
+ _bristleTipDataUrl = canvas.toDataURL('image/png');
+ return _bristleTipDataUrl;
+}
+
// Preloaded images cache
const preloadedTipImages = new Map<string, HTMLImageElement>();
export function getPreloadedBuiltinTipImage(dataUrl: string): HTMLImageElement | undefined {
+ if (!dataUrl || typeof Image === 'undefined') return undefined;
if (preloadedTipImages.has(dataUrl)) {
return preloadedTipImages.get(dataUrl);
}
@@ -49,12 +164,16 @@ export function getPreloadedBuiltinTipImage(dataUrl: string): HTMLImageElement |
}
// Eagerly generate and preload built-in brush tip textures at startup
-if (typeof document !== 'undefined') {
+if (typeof document !== 'undefined' && typeof Image !== 'undefined') {
try {
const square = getSquareTipDataUrl();
if (square) getPreloadedBuiltinTipImage(square);
- } catch (err) {
- console.warn('Failed to eagerly initialize brush tips:', err);
+ const realG = getRealGPenTipDataUrl();
+ if (realG) getPreloadedBuiltinTipImage(realG);
+ const bristle = getBristleTipDataUrl();
+ if (bristle) getPreloadedBuiltinTipImage(bristle);
+ } catch {
+ // Headless test environments may mock document.createElement minimally
}
}
@@ -85,8 +204,10 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
grain: 0.95,
spacing: 0.08,
usePressure: true,
+ useTilt: true,
smoothing: true,
stabilization: 15,
+ sharpCorners: true,
useGpu: true,
},
},
@@ -109,8 +230,10 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
grain: 0.98,
spacing: 0.08,
usePressure: true,
+ useTilt: true,
smoothing: true,
stabilization: 15,
+ sharpCorners: true,
useGpu: true,
},
},
@@ -133,8 +256,10 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
grain: 0.92,
spacing: 0.08,
usePressure: true,
+ useTilt: true,
smoothing: true,
stabilization: 15,
+ sharpCorners: true,
useGpu: true,
},
},
@@ -157,8 +282,10 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
grain: 0.88,
spacing: 0.08,
usePressure: true,
+ useTilt: true,
smoothing: true,
stabilization: 15,
+ sharpCorners: true,
useGpu: true,
},
},
@@ -175,13 +302,47 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
icon: 'paintbrush',
settings: {
size: 8,
- minSizeFactor: 0.05,
+ minSizeFactor: 0.04,
flow: 1.0,
opacity: 1.0,
hardness: 1.0,
+ antiAlias: 2,
spacing: 0.04,
stabilization: 20,
+ sharpCorners: true,
usePressure: true,
+ useTilt: false,
+ smoothing: true,
+ useGpu: true,
+ },
+ },
+ {
+ id: 'real-g-pen',
+ name: 'Real G-Pen (Textured Nib)',
+ category: 'pencil-line',
+ categoryName: 'Pencil & Line',
+ badge: 'Real G',
+ badgeBg: 'bg-indigo-500/15',
+ badgeText: 'text-indigo-200',
+ badgeBorder: 'border-indigo-400/30',
+ desc: 'Organic Analog Manga Nib & Tooth',
+ icon: 'paintbrush',
+ tipGenerator: getRealGPenTipDataUrl,
+ settings: {
+ size: 9,
+ minSizeFactor: 0.03,
+ flow: 1.0,
+ opacity: 1.0,
+ hardness: 1.0,
+ antiAlias: 1,
+ spacing: 0.045,
+ grain: 0.38,
+ paperTextureMode: 'subtract',
+ customTipAngleDynamics: 'direction',
+ stabilization: 18,
+ sharpCorners: true,
+ usePressure: true,
+ useTilt: false,
smoothing: true,
useGpu: true,
},
@@ -203,9 +364,12 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
flow: 1.0,
opacity: 1.0,
hardness: 1.0,
+ antiAlias: 2,
spacing: 0.035,
stabilization: 24,
+ sharpCorners: true,
usePressure: true,
+ useTilt: false,
smoothing: true,
useGpu: true,
},
@@ -227,9 +391,42 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
flow: 1.0,
opacity: 1.0,
hardness: 1.0,
- spacing: 0.07,
+ antiAlias: 2,
+ spacing: 0.05,
stabilization: 18,
+ sharpCorners: true,
+ usePressure: true,
+ useTilt: false,
+ smoothing: true,
+ useGpu: true,
+ },
+ },
+ {
+ id: 'calligraphy-pen',
+ name: 'Calligraphy Pen',
+ category: 'pencil-line',
+ categoryName: 'Pencil & Line',
+ badge: 'Calli',
+ badgeBg: 'bg-fuchsia-500/15',
+ badgeText: 'text-fuchsia-300',
+ badgeBorder: 'border-fuchsia-500/30',
+ desc: '45-Degree Flat Chisel Nib',
+ icon: 'paintbrush',
+ settings: {
+ size: 14,
+ minSizeFactor: 0.35,
+ flow: 1.0,
+ opacity: 1.0,
+ hardness: 1.0,
+ thickness: 0.22,
+ customTipAngle: 45,
+ customTipAngleDynamics: 'none',
+ antiAlias: 2,
+ spacing: 0.035,
+ stabilization: 22,
+ sharpCorners: true,
usePressure: true,
+ useTilt: false,
smoothing: true,
useGpu: true,
},
@@ -253,7 +450,9 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
hardness: 0.9,
spacing: 0.08,
stabilization: 15,
+ sharpCorners: true,
usePressure: true,
+ useTilt: false,
smoothing: true,
useGpu: true,
},
@@ -279,8 +478,209 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
opacity: 1.0,
hardness: 0.0,
spacing: 0.08,
+ adjustDensityByGap: true,
+ stabilization: 10,
+ usePressure: true,
+ useTilt: false,
+ smoothing: true,
+ useGpu: true,
+ },
+ },
+ {
+ id: 'spray-tone',
+ name: 'Tone Spray Airbrush',
+ category: 'color-paint',
+ categoryName: 'Color & Paint',
+ badge: 'Spray',
+ badgeBg: 'bg-rose-500/15',
+ badgeText: 'text-rose-300',
+ badgeBorder: 'border-rose-500/30',
+ desc: 'Crisp Binary Manga Tone Stipple Spray',
+ icon: 'paintbrush',
+ tipGenerator: getSquareTipDataUrl,
+ settings: {
+ size: 44,
+ minSizeFactor: 0.4,
+ flow: 0.95,
+ opacity: 1.0,
+ hardness: 1.0,
+ antiAlias: 0,
+ spacing: 0.14,
+ spray: {
+ enabled: true,
+ size: 2,
+ density: 12,
+ bias: 0.3,
+ },
+ stabilization: 8,
+ usePressure: true,
+ useTilt: false,
+ smoothing: true,
+ useGpu: true,
+ },
+ },
+ {
+ id: 'flat-marker',
+ name: 'Flat Marker (Copic)',
+ category: 'color-paint',
+ categoryName: 'Color & Paint',
+ badge: 'Marker',
+ badgeBg: 'bg-cyan-500/15',
+ badgeText: 'text-cyan-300',
+ badgeBorder: 'border-cyan-500/30',
+ desc: 'Compare-Density Even Wash Chisel Marker',
+ icon: 'square',
+ settings: {
+ size: 28,
+ minSizeFactor: 0.65,
+ flow: 0.58,
+ opacity: 0.78,
+ hardness: 0.92,
+ thickness: 0.32,
+ customTipAngle: 30,
+ customTipAngleDynamics: 'none',
+ blendTipsMode: 'compare',
+ adjustDensityByGap: true,
+ spacing: 0.04,
+ stabilization: 12,
+ usePressure: true,
+ useTilt: false,
+ smoothing: true,
+ useGpu: true,
+ },
+ },
+ {
+ id: 'opaque-watercolor',
+ name: 'Opaque Watercolor',
+ category: 'color-paint',
+ categoryName: 'Color & Paint',
+ badge: 'Water',
+ badgeBg: 'bg-sky-500/15',
+ badgeText: 'text-sky-300',
+ badgeBorder: 'border-sky-500/30',
+ desc: 'Creamy Perceptual OKLab Blending Brush',
+ icon: 'palette',
+ settings: {
+ size: 26,
+ minSizeFactor: 0.28,
+ flow: 0.74,
+ opacity: 1.0,
+ hardness: 0.45,
+ spacing: 0.06,
+ colorMixing: true,
+ perceptualMixing: true,
+ mixingMode: 'blend',
+ amountOfPaint: 0.58,
+ densityOfPaint: 0.75,
+ colorStretch: 0.68,
+ stabilization: 12,
+ usePressure: true,
+ useTilt: false,
+ smoothing: true,
+ useGpu: true,
+ },
+ },
+ {
+ id: 'transparent-watercolor',
+ name: 'Transparent Watercolor',
+ category: 'color-paint',
+ categoryName: 'Color & Paint',
+ badge: 'Wash',
+ badgeBg: 'bg-blue-500/15',
+ badgeText: 'text-blue-200',
+ badgeBorder: 'border-blue-400/30',
+ desc: 'Capillary Wet-Edge Rim & Cold-Press Grain',
+ icon: 'palette',
+ settings: {
+ size: 32,
+ minSizeFactor: 0.32,
+ flow: 0.44,
+ opacity: 0.9,
+ hardness: 0.35,
+ spacing: 0.06,
+ blendTipsMode: 'compare',
+ adjustDensityByGap: true,
+ grain: 0.45,
+ paperTextureMode: 'multiply',
+ wetEdge: 0.65,
+ wetEdgeRadius: 3.5,
+ wetEdgeAlphaPower: 35,
+ wetEdgeValuePower: 18,
+ colorMixing: true,
+ perceptualMixing: true,
+ mixingMode: 'running_color',
+ amountOfPaint: 0.45,
+ densityOfPaint: 0.55,
+ colorStretch: 0.72,
+ stabilization: 12,
+ usePressure: true,
+ useTilt: false,
+ smoothing: true,
+ useGpu: true,
+ },
+ },
+ {
+ id: 'oil-paint',
+ name: 'Thick Oil Paint',
+ category: 'color-paint',
+ categoryName: 'Color & Paint',
+ badge: 'Oil',
+ badgeBg: 'bg-amber-500/15',
+ badgeText: 'text-amber-300',
+ badgeBorder: 'border-amber-500/30',
+ desc: 'Directional Hog-Bristle Impasto Mixing',
+ icon: 'palette',
+ tipGenerator: getBristleTipDataUrl,
+ settings: {
+ size: 30,
+ minSizeFactor: 0.3,
+ flow: 0.92,
+ opacity: 1.0,
+ hardness: 0.95,
+ spacing: 0.045,
+ customTipAngleDynamics: 'direction',
+ grain: 0.25,
+ paperTextureMode: 'subtract',
+ colorMixing: true,
+ perceptualMixing: true,
+ mixingMode: 'blend',
+ amountOfPaint: 0.74,
+ densityOfPaint: 0.88,
+ colorStretch: 0.8,
+ stabilization: 12,
+ usePressure: true,
+ useTilt: false,
+ smoothing: true,
+ useGpu: true,
+ },
+ },
+ {
+ id: 'soft-blender',
+ name: 'Soft Smudge Blender',
+ category: 'color-paint',
+ categoryName: 'Color & Paint',
+ badge: 'Blend',
+ badgeBg: 'bg-purple-500/15',
+ badgeText: 'text-purple-300',
+ badgeBorder: 'border-purple-500/30',
+ desc: 'Zero-Pigment Wet Color Stretch & Blur',
+ icon: 'palette',
+ settings: {
+ size: 36,
+ minSizeFactor: 0.5,
+ flow: 0.85,
+ opacity: 1.0,
+ hardness: 0.25,
+ spacing: 0.05,
+ colorMixing: true,
+ perceptualMixing: true,
+ mixingMode: 'smear',
+ amountOfPaint: 0.0,
+ densityOfPaint: 0.0,
+ colorStretch: 0.86,
stabilization: 10,
usePressure: true,
+ useTilt: false,
smoothing: true,
useGpu: true,
},
@@ -306,10 +706,12 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
spacing: 0.07,
stabilization: 12,
usePressure: true,
+ useTilt: false,
smoothing: true,
customTipAngle: 0,
customTipAngleDynamics: 'none',
- colorMixing: true, // Also supports subtle blending if desired
+ colorMixing: true,
+ perceptualMixing: true,
amountOfPaint: 0.88,
densityOfPaint: 0.95,
colorStretch: 0.4,
@@ -331,7 +733,9 @@ export function getBuiltinBrushConfig(presetId: BrushPresetId): Partial<BrushSet
if (def.tipGenerator) {
tipDataUrl = def.tipGenerator();
- tipImage = getPreloadedBuiltinTipImage(tipDataUrl);
+ if (tipDataUrl) {
+ tipImage = getPreloadedBuiltinTipImage(tipDataUrl);
+ }
}
return {
diff --git a/src/utils/psdParser.ts b/src/utils/psdParser.ts
index eed97bc..69e70a4 100644
--- a/src/utils/psdParser.ts
+++ b/src/utils/psdParser.ts
@@ -90,7 +90,9 @@ export async function parsePsdFile(buffer: ArrayBuffer, fileName: string): Promi
const id = `psd-${isFolder ? 'folder' : 'layer'}-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`;
const name = psdLayer.name || (isFolder ? 'Folder' : 'Layer');
const visible = !psdLayer.hidden;
- const opacity = typeof psdLayer.opacity === 'number' ? Math.max(0, Math.min(1, psdLayer.opacity)) : 1;
+ const rawOpacity = typeof psdLayer.opacity === 'number' ? psdLayer.opacity : 1;
+ const normalizedOpacity = rawOpacity > 1 ? rawOpacity / 255 : rawOpacity;
+ const opacity = Math.max(0, Math.min(1, normalizedOpacity));
const blendMode = mapPsdBlendMode(psdLayer.blendMode);
const locked = Boolean(
psdLayer.protected?.transparency ||
@@ -112,10 +114,10 @@ export async function parsePsdFile(buffer: ArrayBuffer, fileName: string): Promi
};
layers.push(folderItem);
- // Process children
+ // Process children in reverse (ag-psd is bottom-to-top; Ink Studio is top-to-bottom)
if (psdLayer.children) {
- for (const child of psdLayer.children) {
- processPsdLayer(child, id);
+ for (let i = psdLayer.children.length - 1; i >= 0; i--) {
+ processPsdLayer(psdLayer.children[i], id);
}
}
} else {
@@ -162,8 +164,9 @@ export async function parsePsdFile(buffer: ArrayBuffer, fileName: string): Promi
}
if (psd.children && psd.children.length > 0) {
- for (const child of psd.children) {
- processPsdLayer(child, null);
+ // ag-psd stores layers bottom-to-top; reverse to match Ink Studio's top-to-bottom stack order
+ for (let i = psd.children.length - 1; i >= 0; i--) {
+ processPsdLayer(psd.children[i], null);
}
} else if (psd.canvas) {
// Single flattened composite
diff --git a/src/utils/saveManager.ts b/src/utils/saveManager.ts
index b1669df..8cbb3b2 100644
--- a/src/utils/saveManager.ts
+++ b/src/utils/saveManager.ts
@@ -6,6 +6,8 @@ import {
} from '../types/editor';
import { getCanvasCompositeOperation } from './canvasUtils';
import { groupLayersForCompositing } from './compositor';
+import { applyAdjustment } from './tonalEngine';
+import { recoveryService } from '../services/recoveryService';
export interface SavedFileInfo {
handle?: any; // FileSystemFileHandle
@@ -21,6 +23,7 @@ export interface SaveDocumentData {
layerCanvasesMap: Map<string, HTMLCanvasElement>;
getEffectiveOpacity: (layer: LayerItem) => number;
isLayerEffectivelyVisible: (layer: LayerItem) => boolean;
+ tabId?: string;
}
/**
@@ -67,14 +70,49 @@ export function compositeCanvas(
const renderOrder = layers.slice().reverse();
const groups = groupLayersForCompositing(renderOrder);
+ const getMaskedLayerCanvas = (layer: LayerItem, srcCanvas: HTMLCanvasElement): HTMLCanvasElement => {
+ if (!layer.maskCanvas || layer.maskEnabled === false) return srcCanvas;
+ const masked = document.createElement('canvas');
+ masked.width = dimensions.width;
+ masked.height = dimensions.height;
+ const mCtx = masked.getContext('2d');
+ const maskCtx = layer.maskCanvas.getContext('2d', { willReadFrequently: true });
+ if (!mCtx || !maskCtx) return srcCanvas;
+ mCtx.drawImage(srcCanvas, 0, 0);
+ const imgData = mCtx.getImageData(0, 0, dimensions.width, dimensions.height);
+ const maskData = maskCtx.getImageData(0, 0, dimensions.width, dimensions.height).data;
+ const d = imgData.data;
+ for (let i = 0; i < d.length; i += 4) {
+ if (d[i + 3] === 0) continue;
+ const maskLum = ((0.299 * maskData[i] + 0.587 * maskData[i + 1] + 0.114 * maskData[i + 2]) / 255) * (maskData[i + 3] / 255);
+ d[i + 3] = Math.round(d[i + 3] * maskLum);
+ }
+ mCtx.putImageData(imgData, 0, 0);
+ return masked;
+ };
+
for (const group of groups) {
const baseLayer = group.baseLayer;
if (baseLayer.type === 'folder' || !isLayerEffectivelyVisible(baseLayer)) continue;
- const baseCanvas = layerCanvasesMap.get(baseLayer.id);
- if (!baseCanvas) continue;
+
+ if (baseLayer.type === 'adjustment' && baseLayer.adjustmentData) {
+ const imgData = ctx.getImageData(0, 0, dimensions.width, dimensions.height);
+ applyAdjustment(
+ imgData,
+ baseLayer.adjustmentData,
+ baseLayer.maskEnabled !== false ? baseLayer.maskCanvas : undefined,
+ getEffectiveOpacity(baseLayer)
+ );
+ ctx.putImageData(imgData, 0, 0);
+ continue;
+ }
+
+ const rawBaseCanvas = layerCanvasesMap.get(baseLayer.id);
+ if (!rawBaseCanvas) continue;
+ const baseCanvas = getMaskedLayerCanvas(baseLayer, rawBaseCanvas);
const activeClipped = group.clippedLayers.filter(
- (cl) => cl.type !== 'folder' && isLayerEffectivelyVisible(cl)
+ (cl) => cl.type !== 'folder' && cl.type !== 'adjustment' && isLayerEffectivelyVisible(cl)
);
if (activeClipped.length === 0) {
@@ -97,8 +135,9 @@ export function compositeCanvas(
gCtx.restore();
for (const clipped of activeClipped) {
- const cCanvas = layerCanvasesMap.get(clipped.id);
- if (!cCanvas) continue;
+ const rawClippedCanvas = layerCanvasesMap.get(clipped.id);
+ if (!rawClippedCanvas) continue;
+ const cCanvas = getMaskedLayerCanvas(clipped, rawClippedCanvas);
gCtx.save();
gCtx.globalAlpha = getEffectiveOpacity(clipped);
@@ -147,16 +186,18 @@ export async function serializeDocument(
): Promise<{ data: Blob | ArrayBuffer; mimeType: string }> {
const ext = extension.toLowerCase();
- // 1. PSD format with layers
+ // 1. PSD format with layers (ag-psd expects bottom-to-top order and opacity 0..255)
if (ext === '.psd' || ext === '.psb') {
const children = data.layers
- .filter((l) => l.type === 'raster')
+ .slice()
+ .reverse()
+ .filter((l) => l.type === 'raster' || l.type === 'vector' || l.type === 'frame')
.map((layer) => {
const c = data.layerCanvasesMap.get(layer.id);
return {
name: layer.name,
hidden: !layer.visible,
- opacity: layer.opacity,
+ opacity: Math.round(Math.max(0, Math.min(1, layer.opacity ?? 1)) * 255),
blendMode: toAgPsdBlendMode(layer.blendMode),
canvas: c || undefined,
};
@@ -189,23 +230,30 @@ export async function serializeDocument(
// 2. Native Ink Studio Project (.ink, .sora) format
if (ext === '.ink' || ext === '.sora') {
const layerImages: Record<string, string> = {};
- data.layers.forEach((l) => {
- if (l.type === 'raster') {
+ const maskImages: Record<string, string> = {};
+ const serializableLayers = data.layers.map((l) => {
+ if (l.type === 'raster' || l.type === 'vector' || l.type === 'frame') {
const c = data.layerCanvasesMap.get(l.id);
if (c) {
layerImages[l.id] = c.toDataURL('image/png');
}
}
+ if (l.maskCanvas && typeof l.maskCanvas.toDataURL === 'function') {
+ maskImages[l.id] = l.maskCanvas.toDataURL('image/png');
+ }
+ const { maskCanvas: _mc, ...rest } = l;
+ return rest;
});
const projectData = {
app: 'Ink Studio',
- version: '1.0',
+ version: '1.1',
name: data.name,
dimensions: data.dimensions,
colorMode: data.colorMode,
- layers: data.layers,
+ layers: serializableLayers,
canvases: layerImages,
+ masks: maskImages,
};
const json = JSON.stringify(projectData);
@@ -328,6 +376,10 @@ export async function promptSaveAs(
await writable.write(serialized.data);
await writable.close();
+ if (data.tabId) {
+ recoveryService.markCleanSaved(data.tabId).catch(console.warn);
+ }
+
return {
handle,
name: fileName,
@@ -346,6 +398,11 @@ export async function promptSaveAs(
const ext = defaultExtension;
const serialized = await serializeDocument(data, ext);
downloadFile(serialized.data, suggestedName, serialized.mimeType);
+
+ if (data.tabId) {
+ recoveryService.markCleanSaved(data.tabId).catch(console.warn);
+ }
+
return {
name: suggestedName,
extension: ext,
@@ -370,6 +427,10 @@ export async function saveToExistingHandle(
const writable = await fileInfo.handle.createWritable();
await writable.write(serialized.data);
await writable.close();
+
+ if (data.tabId) {
+ recoveryService.markCleanSaved(data.tabId).catch(console.warn);
+ }
}
/**
diff --git a/src/utils/screentoneEngine.ts b/src/utils/screentoneEngine.ts
index e22f5fe..9c83f5d 100644
--- a/src/utils/screentoneEngine.ts
+++ b/src/utils/screentoneEngine.ts
@@ -186,10 +186,6 @@ export function applyScreentoneCPU(
targetCanvas.width = width;
targetCanvas.height = height;
}
- if (sourceCanvas.width !== width || sourceCanvas.height !== height) {
- sourceCanvas.width = width;
- sourceCanvas.height = height;
- }
const srcCtx = sourceCanvas.getContext('2d', { willReadFrequently: true });
const dstCtx = targetCanvas.getContext('2d');
@@ -589,10 +585,6 @@ class WebGLHalftonePipeline {
targetCanvas.width = width;
targetCanvas.height = height;
}
- if (sourceCanvas.width !== width || sourceCanvas.height !== height) {
- sourceCanvas.width = width;
- sourceCanvas.height = height;
- }
const dstCtx = targetCanvas.getContext('2d');
if (!dstCtx) return false;
diff --git a/src/utils/selectionUtils.ts b/src/utils/selectionUtils.ts
index 613f31b..a35f5fa 100644
--- a/src/utils/selectionUtils.ts
+++ b/src/utils/selectionUtils.ts
@@ -828,16 +828,17 @@ export function liftSelectionToFloating(
const mCtx = maskCanvas.getContext('2d');
if (mCtx) {
const mImg = mCtx.createImageData(targetCanvas.width, targetCanvas.height);
+ const fillRgb = isBackground ? 255 : 0;
for (let i = 0; i < selection.mask.length; i++) {
- mImg.data[i * 4] = 0;
- mImg.data[i * 4 + 1] = 0;
- mImg.data[i * 4 + 2] = 0;
+ mImg.data[i * 4] = fillRgb;
+ mImg.data[i * 4 + 1] = fillRgb;
+ mImg.data[i * 4 + 2] = fillRgb;
mImg.data[i * 4 + 3] = selection.mask[i];
}
mCtx.putImageData(mImg, 0, 0);
if (isBackground) {
- ctx.fillStyle = '#ffffff';
- ctx.fillRect(b.x, b.y, b.width, b.height);
+ ctx.globalCompositeOperation = 'source-over';
+ ctx.drawImage(maskCanvas, 0, 0);
} else {
ctx.globalCompositeOperation = 'destination-out';
ctx.drawImage(maskCanvas, 0, 0);
diff --git a/src/utils/stampEngine.ts b/src/utils/stampEngine.ts
index 076a1e4..e086ea7 100644
--- a/src/utils/stampEngine.ts
+++ b/src/utils/stampEngine.ts
@@ -1,4 +1,15 @@
-import { Point, CspSpraySettings, CspTaperSettings, CspSubTip, BrushDynamics } from '../types/editor';
+import {
+ Point,
+ CspSpraySettings,
+ CspTaperSettings,
+ CspSubTip,
+ BrushDynamics,
+ CspAngleDynamicsMode,
+ CspTipFlipMode,
+ CspPaperTextureMode,
+ CspBlendTipsMode,
+ CspSensorConfig,
+} from '../types/editor';
import {
PaintReservoir,
LayerPixelSampler,
@@ -6,26 +17,47 @@ import {
parseColorToRgb,
rgbToHex,
} from './colorMixingEngine';
-import { evaluateCspSpline } from './sutParser';
+import { getPaperGrain } from './pencilEngine';
import { WebGlBrushEngine, GpuDab } from './webglBrushEngine';
+import {
+ evaluateFastSpline,
+ dabHashFloat,
+ evaluateCspSensor,
+ computeEllipticalStepDistance,
+ computeGapAdjustedAlpha,
+ computeSubpixelDabDimensions,
+ resolveTipFlipSigns,
+ applyCspPaperTextureAlpha,
+} from '../engine/CspBrushEngine';
export interface TexturedBrushOptions {
size: number;
minSizeFactor?: number;
opacity?: number;
flow?: number;
+ brushDensity?: number;
+ adjustDensityByGap?: boolean;
+ blendTipsMode?: CspBlendTipsMode;
spacing?: number; // 0.01 to 1.0 (relative to brush width)
thickness?: number; // 0.05 to 1.0 (elliptical aspect ratio)
thicknessVertical?: boolean;
+ flipH?: CspTipFlipMode;
+ flipV?: CspTipFlipMode;
angle?: number; // rotation in degrees
- angleDynamics?: 'none' | 'direction' | 'random';
+ angleDynamics?: CspAngleDynamicsMode;
rotationRandomScale?: number;
hardness?: number;
antiAlias?: number;
+ isColorTip?: boolean;
pressureCurve?: [number, number][];
velocityCurve?: [number, number][];
usePressure?: boolean;
+ useTilt?: boolean;
+ tiltScale?: number;
useVelocity?: boolean;
+ sizeSensor?: CspSensorConfig;
+ opacitySensor?: CspSensorConfig;
+ densitySensor?: CspSensorConfig;
subTips?: CspSubTip[];
subTipOrder?: 'random' | 'sequential' | 'direction' | 'reverse';
subTipImages?: HTMLImageElement[];
@@ -36,13 +68,17 @@ export interface TexturedBrushOptions {
amountOfPaint?: number;
densityOfPaint?: number;
colorStretch?: number;
- mixingMode?: 'blend' | 'running_color';
+ mixingMode?: 'blend' | 'running_color' | 'smear';
wetEdge?: number;
wetEdgeRadius?: number;
wetEdgeAlphaPower?: number;
wetEdgeValuePower?: number;
grain?: number;
textureDensity?: number;
+ paperTextureMode?: CspPaperTextureMode;
+ paperTextureBrightness?: number;
+ paperTextureContrast?: number;
+ paperTextureInverted?: boolean;
paperTextureImage?: HTMLImageElement;
paperTextureScale?: number;
paperTextureRotate?: number;
@@ -68,9 +104,6 @@ export interface TexturedBrushOptions {
// Color Dynamics & HSV Jitter Utilities
// -------------------------------------------------------------
-/**
- * Fast RGB (normalized [0, 1]) to HSV [h: 0..360, s: 0..1, v: 0..1].
- */
export function rgbToHsv(r: number, g: number, b: number): [number, number, number] {
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
@@ -92,9 +125,6 @@ export function rgbToHsv(r: number, g: number, b: number): [number, number, numb
return [h, s, v];
}
-/**
- * Fast HSV [h: 0..360, s: 0..1, v: 0..1] to RGB [0, 1].
- */
export function hsvToRgb(h: number, s: number, v: number): [number, number, number] {
const c = v * s;
const hp = (((h % 360) + 360) % 360) / 60;
@@ -125,13 +155,11 @@ export function hsvToRgb(h: number, s: number, v: number): [number, number, numb
];
}
-/**
- * Applies foreground/background mixing and hue/saturation/brightness jitter.
- */
export function applyColorDynamics(
- primaryRgb: { r: number; g: number; b: number }, // [0, 1]
- secondaryRgb: { r: number; g: number; b: number }, // [0, 1]
- dynamics?: BrushDynamics
+ primaryRgb: { r: number; g: number; b: number },
+ secondaryRgb: { r: number; g: number; b: number },
+ dynamics?: BrushDynamics,
+ rng: () => number = Math.random
): { r: number; g: number; b: number; hex: string } {
if (!dynamics || !dynamics.colorJitterEnabled) {
const ir = Math.round(primaryRgb.r * 255);
@@ -149,26 +177,24 @@ export function applyColorDynamics(
let g = primaryRgb.g;
let b = primaryRgb.b;
- // 1. Foreground/Background jitter
if (dynamics.foregroundBackgroundJitter > 0) {
- const mix = Math.random() * dynamics.foregroundBackgroundJitter;
+ const mix = rng() * dynamics.foregroundBackgroundJitter;
r = r + (secondaryRgb.r - r) * mix;
g = g + (secondaryRgb.g - g) * mix;
b = b + (secondaryRgb.b - b) * mix;
}
- // 2. HSB Jitter
if (dynamics.hueJitter > 0 || dynamics.saturationJitter > 0 || dynamics.brightnessJitter > 0) {
let [h, s, v] = rgbToHsv(r, g, b);
if (dynamics.hueJitter > 0) {
- h = (h + (Math.random() - 0.5) * dynamics.hueJitter * 360 + 360) % 360;
+ h = (h + (rng() - 0.5) * dynamics.hueJitter * 360 + 360) % 360;
}
if (dynamics.saturationJitter > 0) {
- s = Math.max(0, Math.min(1, s * (1.0 + (Math.random() * 2 - 1) * dynamics.saturationJitter)));
+ s = Math.max(0, Math.min(1, s * (1.0 + (rng() * 2 - 1) * dynamics.saturationJitter)));
}
if (dynamics.brightnessJitter > 0) {
- v = Math.max(0, Math.min(1, v * (1.0 + (Math.random() * 2 - 1) * dynamics.brightnessJitter)));
+ v = Math.max(0, Math.min(1, v * (1.0 + (rng() * 2 - 1) * dynamics.brightnessJitter)));
}
[r, g, b] = hsvToRgb(h, s, v);
@@ -191,31 +217,66 @@ export function applyColorDynamics(
}
// -------------------------------------------------------------
-// High-Efficiency Tinted Tip Master Buffer & Pool
-// Reuses canvas contexts and quantizes colors to eliminate GC & allocations
+// High-Efficiency Tinted Tip Master Buffer & Bounded LRU Pools
// -------------------------------------------------------------
-const MAX_CACHE_ENTRIES = 128;
+const MAX_CACHE_ENTRIES = 160;
+const MAX_RADIAL_MASKS = 96;
const tintedMasterCache = new Map<string, HTMLCanvasElement>();
+const radialMaskCache = new Map<string, HTMLCanvasElement>();
const canvasPool: HTMLCanvasElement[] = [];
+const sourceIdMap = new WeakMap<object, number>();
+let nextSourceId = 1;
+
+function getUniqueSourceKey(source: CanvasImageSource, fallbackPrefix: string): string {
+ if (typeof source === 'object' && source !== null) {
+ let id = sourceIdMap.get(source);
+ if (!id) {
+ id = nextSourceId++;
+ sourceIdMap.set(source, id);
+ }
+ return `${fallbackPrefix}_${id}`;
+ }
+ return fallbackPrefix;
+}
function getPooledCanvas(w: number, h: number): HTMLCanvasElement {
+ const targetW = Math.max(1, w);
+ const targetH = Math.max(1, h);
for (let i = 0; i < canvasPool.length; i++) {
const c = canvasPool[i];
- if (c.width === w && c.height === h) {
+ if (c.width === targetW && c.height === targetH) {
canvasPool.splice(i, 1);
return c;
}
}
const canvas = document.createElement('canvas');
- canvas.width = Math.max(1, w);
- canvas.height = Math.max(1, h);
+ canvas.width = targetW;
+ canvas.height = targetH;
return canvas;
}
+function evictOrAllocateMasterCanvas(w: number, h: number): HTMLCanvasElement {
+ const targetW = Math.max(1, w);
+ const targetH = Math.max(1, h);
+ if (tintedMasterCache.size >= MAX_CACHE_ENTRIES) {
+ const oldestKey = tintedMasterCache.keys().next().value;
+ if (oldestKey) {
+ const canvas = tintedMasterCache.get(oldestKey)!;
+ tintedMasterCache.delete(oldestKey);
+ if (canvas.width !== targetW || canvas.height !== targetH) {
+ canvas.width = targetW;
+ canvas.height = targetH;
+ }
+ return canvas;
+ }
+ }
+ return getPooledCanvas(targetW, targetH);
+}
+
/**
* Generic tinted master offscreen canvas generator.
- * Uses 15-bit color quantization to achieve 98%+ cache hit rates during smooth color blends.
+ * Uses fine 21-bit color quantization (step of 2/255) to eliminate 15-bit Mach banding while retaining high cache hits.
*/
export function getTintedMasterCanvas(
source: CanvasImageSource,
@@ -230,10 +291,11 @@ export function getTintedMasterCanvas(
const cached = tintedMasterCache.get(key);
if (cached) return cached;
- const canvas = getPooledCanvas(w, h);
+ const canvas = evictOrAllocateMasterCanvas(w, h);
const ctx = canvas.getContext('2d');
if (ctx) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
+ ctx.globalCompositeOperation = 'source-over';
ctx.drawImage(source, 0, 0, canvas.width, canvas.height);
}
tintedMasterCache.set(key, canvas);
@@ -241,28 +303,16 @@ export function getTintedMasterCanvas(
}
const rgb = parseColorToRgb(color);
- const qR = (rgb.r >> 3) << 3;
- const qG = (rgb.g >> 3) << 3;
- const qB = (rgb.b >> 3) << 3;
+ const qR = rgb.r & ~1;
+ const qG = rgb.g & ~1;
+ const qB = rgb.b & ~1;
const quantizedHex = rgbToHex(qR, qG, qB);
const key = `${sourceKey}_${quantizedHex}_${w}x${h}`;
const cached = tintedMasterCache.get(key);
if (cached) return cached;
- let canvas: HTMLCanvasElement;
- if (tintedMasterCache.size >= MAX_CACHE_ENTRIES) {
- const oldestKey = tintedMasterCache.keys().next().value;
- if (oldestKey) {
- canvas = tintedMasterCache.get(oldestKey)!;
- tintedMasterCache.delete(oldestKey);
- } else {
- canvas = getPooledCanvas(w, h);
- }
- } else {
- canvas = getPooledCanvas(w, h);
- }
-
+ const canvas = evictOrAllocateMasterCanvas(w, h);
const ctx = canvas.getContext('2d');
if (!ctx) return canvas;
@@ -278,9 +328,6 @@ export function getTintedMasterCanvas(
return canvas;
}
-/**
- * Returns a tinted master offscreen canvas for the given tip and color.
- */
export function getTintedTipMaster(
tipImage: HTMLImageElement,
color: string,
@@ -288,26 +335,51 @@ export function getTintedTipMaster(
): HTMLCanvasElement {
const w = tipImage.naturalWidth || tipImage.width || 64;
const h = tipImage.naturalHeight || tipImage.height || 64;
- return getTintedMasterCanvas(tipImage, tipImage.src.slice(0, 48), color, w, h, isColorTip);
+ const uniqueKey = getUniqueSourceKey(tipImage, 'tip');
+ return getTintedMasterCanvas(tipImage, uniqueKey, color, w, h, isColorTip);
}
-const radialMaskCache = new Map<number, HTMLCanvasElement>();
-
/**
- * Pre-computes or retrieves an analytical Hermite radial dab master.
- * Provides CSP / Photoshop standard falloff curves without slow Canvas2D shadowBlur.
+ * Pre-computes or retrieves an analytical Hermite radial dab master with CSP 4-level Anti-Aliasing.
*/
export function getRadialDabMaster(
hardness: number,
color: string,
- isEraser: boolean = false
+ isEraser: boolean = false,
+ targetSize?: number,
+ antiAlias: number = 2
): HTMLCanvasElement {
const clampedH = Math.max(0, Math.min(1.0, hardness));
const qH = Math.round(clampedH * 20) / 20;
+ const aaLevel = Math.max(0, Math.min(3, Math.round(antiAlias)));
+
+ let size = 128;
+ let qDiameter = 124;
+ if (targetSize !== undefined && targetSize > 0) {
+ if (targetSize <= 8) {
+ size = 24;
+ qDiameter = Math.max(1, Math.round(targetSize));
+ } else if (targetSize <= 24) {
+ size = 48;
+ qDiameter = Math.max(4, Math.round(targetSize / 2) * 2);
+ } else if (targetSize <= 64) {
+ size = 64;
+ qDiameter = Math.max(16, Math.round(targetSize / 4) * 4);
+ } else {
+ size = 128;
+ qDiameter = 124;
+ }
+ }
- let maskCanvas = radialMaskCache.get(qH);
+ const aaKeySuffix = aaLevel === 2 ? '' : `_aa${aaLevel}`;
+ const maskKey = targetSize === undefined ? `${qH}_128${aaKeySuffix}` : `${qH}_${size}_${qDiameter}${aaKeySuffix}`;
+ let maskCanvas = radialMaskCache.get(maskKey);
if (!maskCanvas) {
- const size = 128;
+ if (radialMaskCache.size >= MAX_RADIAL_MASKS) {
+ const oldest = radialMaskCache.keys().next().value;
+ if (oldest !== undefined) radialMaskCache.delete(oldest);
+ }
+
maskCanvas = document.createElement('canvas');
maskCanvas.width = size;
maskCanvas.height = size;
@@ -317,8 +389,16 @@ export function getRadialDabMaster(
const data = imgData.data;
const cx = size / 2;
const cy = size / 2;
- const radius = size / 2 - 2; // 62px
- const rCore = radius * qH;
+ const radius = size / 2 - 1;
+
+ const aaScale = aaLevel === 0 ? 0 : aaLevel === 1 ? 0.6 : aaLevel === 3 ? 1.65 : 1.0;
+ const baseAaTexels = qH >= 0.98
+ ? 1.15
+ : targetSize === undefined
+ ? 1.0
+ : Math.max(0.85, Math.min(2.4, (radius / Math.max(1.5, qDiameter * 0.5)) * 0.85));
+ const aaTexels = baseAaTexels * aaScale;
+ const rCore = Math.min(radius - Math.max(0, aaTexels), radius * qH);
for (let y = 0; y < size; y++) {
const dy = y - cy + 0.5;
@@ -327,13 +407,16 @@ export function getRadialDabMaster(
const dx = x - cx + 0.5;
const dist = Math.hypot(dx, dy);
let alpha = 0;
- if (qH >= 0.98) {
- // Crisp anti-aliased disk with sub-pixel edge
- alpha = Math.max(0, Math.min(1.0, radius - dist + 0.5));
+
+ if (aaLevel === 0) {
+ alpha = dist <= radius ? 1.0 : 0.0;
+ } else if (qH >= 0.98) {
+ const u = Math.max(0, Math.min(1.0, (radius - dist) / Math.max(0.25, aaTexels) + 0.5));
+ alpha = u * u * (3.0 - 2.0 * u);
} else if (dist <= rCore) {
alpha = 1.0;
} else if (dist < radius) {
- const t = (dist - rCore) / (radius - rCore);
+ const t = (dist - rCore) / Math.max(1e-4, radius - rCore);
if (qH <= 0.05) {
alpha = 0.5 * (1.0 + Math.cos(t * Math.PI));
} else {
@@ -352,16 +435,16 @@ export function getRadialDabMaster(
}
ctx.putImageData(imgData, 0, 0);
}
- radialMaskCache.set(qH, maskCanvas);
+ radialMaskCache.set(maskKey, maskCanvas);
}
const effectiveColor = isEraser ? '#000000' : color;
- return getTintedMasterCanvas(maskCanvas, `radial_${qH}`, effectiveColor, 128, 128);
+ return getTintedMasterCanvas(maskCanvas, `radial_${maskKey}`, effectiveColor, size, size);
}
/**
- * Draws a single textured brush stamp (dab) onto the destination context.
- * Features an ultra-fast path for unrotated stamps (no save/restore overhead).
+ * Draws a single textured or analytical brush stamp (dab) onto the destination context.
+ * Supports sub-pixel 2D area conservation, horizontal/vertical flips, and binary AA.
*/
export function drawSingleStamp(
ctx: CanvasRenderingContext2D,
@@ -375,59 +458,82 @@ export function drawSingleStamp(
isEraser: boolean = false,
isBgEraser: boolean = false,
alphaLocked: boolean = false,
- isTransparentInk: boolean = false
+ isTransparentInk: boolean = false,
+ flipX: number = 1,
+ flipY: number = 1,
+ antiAlias: number = 2,
+ blendTipsMode?: CspBlendTipsMode
) {
- if (width < 0.1 || height < 0.1 || alpha <= 0.002) return;
-
- const subpixelScale = width < 1.0 ? Math.max(0.1, width) : 1.0;
- const effAlpha = Math.max(0.003, Math.min(1.0, alpha * subpixelScale));
- const renderW = Math.max(0.6, width);
- const renderH = Math.max(0.6, height);
+ if (width < 0.08 || height < 0.08 || alpha <= 0.002) return;
+
+ const minRenderDim = antiAlias === 0 ? 1.0 : 0.75;
+ const sub = computeSubpixelDabDimensions(width, height, alpha, minRenderDim);
+ const renderW = sub.renderW;
+ const renderH = sub.renderH;
+ const effAlpha = antiAlias === 0 ? (sub.effAlpha >= 0.45 ? 1.0 : 0) : sub.effAlpha;
+ if (effAlpha <= 0.002) return;
+
+ const targetOp: GlobalCompositeOperation = isBgEraser
+ ? 'source-over'
+ : (isTransparentInk || isEraser)
+ ? 'destination-out'
+ : alphaLocked
+ ? 'source-atop'
+ : blendTipsMode === 'darken'
+ ? 'darken'
+ : 'source-over';
+
+ const prevSmooth = ctx.imageSmoothingEnabled;
+ if (antiAlias === 0 && prevSmooth !== false) {
+ ctx.imageSmoothingEnabled = false;
+ }
- // Ultra-fast path for unrotated normal stamps
- if (Math.abs(angleRad) < 0.001 && !isEraser && !isBgEraser && !alphaLocked && !isTransparentInk) {
+ // Ultra-fast path for unrotated, unflipped stamps
+ if (Math.abs(angleRad) < 0.001 && flipX >= 0 && flipY >= 0) {
const prevAlpha = ctx.globalAlpha;
const prevOp = ctx.globalCompositeOperation;
- ctx.globalCompositeOperation = 'source-over';
+ ctx.globalCompositeOperation = targetOp;
ctx.globalAlpha = effAlpha;
- ctx.drawImage(stampSource, x - renderW / 2, y - renderH / 2, renderW, renderH);
+ const drawX = antiAlias === 0 ? Math.round(x - renderW / 2) : x - renderW / 2;
+ const drawY = antiAlias === 0 ? Math.round(y - renderH / 2) : y - renderH / 2;
+ ctx.drawImage(stampSource, drawX, drawY, renderW, renderH);
ctx.globalAlpha = prevAlpha;
ctx.globalCompositeOperation = prevOp;
+ if (antiAlias === 0 && prevSmooth !== false) {
+ ctx.imageSmoothingEnabled = prevSmooth;
+ }
return;
}
ctx.save();
-
- if (isBgEraser) {
- ctx.globalCompositeOperation = 'source-over';
- } else if (isTransparentInk || isEraser) {
- ctx.globalCompositeOperation = 'destination-out';
- } else if (alphaLocked) {
- ctx.globalCompositeOperation = 'source-atop';
- } else {
- ctx.globalCompositeOperation = 'source-over';
- }
-
+ ctx.globalCompositeOperation = targetOp;
ctx.globalAlpha = effAlpha;
ctx.translate(x, y);
-
- if (angleRad !== 0) {
+ if (Math.abs(angleRad) >= 0.001) {
ctx.rotate(angleRad);
}
-
- ctx.drawImage(stampSource, -width / 2, -height / 2, width, height);
+ if ((flipX < 0 || flipY < 0) && typeof ctx.scale === 'function') {
+ ctx.scale(flipX < 0 ? -1 : 1, flipY < 0 ? -1 : 1);
+ }
+ ctx.drawImage(stampSource, -renderW / 2, -renderH / 2, renderW, renderH);
ctx.restore();
+ if (antiAlias === 0 && prevSmooth !== false) {
+ ctx.imageSmoothingEnabled = prevSmooth;
+ }
}
/**
- * Selects the active tip image from multi-tip array based on order type.
+ * Deterministic multi-tip stamp selector.
+ * Uses dabHashFloat for 'random' order so live stroke preview and commit bake select identical tips!
*/
function selectTipImage(
tipImages: HTMLImageElement[] | undefined,
fallbackTip: HTMLImageElement,
order: 'random' | 'sequential' | 'direction' | 'reverse' = 'sequential',
dabIndex: number = 0,
- tangentAngle: number = 0
+ tangentAngle: number = 0,
+ x: number = 0,
+ y: number = 0
): HTMLImageElement {
if (!tipImages || tipImages.length <= 1) {
return tipImages && tipImages.length === 1 ? tipImages[0] : fallbackTip;
@@ -435,24 +541,22 @@ function selectTipImage(
const count = tipImages.length;
if (order === 'random') {
- const idx = Math.floor(Math.random() * count);
+ const idx = Math.floor(dabHashFloat(x, y, dabIndex, 97) * count) % count;
return tipImages[idx];
} else if (order === 'reverse') {
const idx = (count - 1 - (dabIndex % count)) % count;
return tipImages[idx];
} else if (order === 'direction') {
- // Map tangent angle [0, 2PI) into tip indices
const normAngle = ((tangentAngle % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI);
const idx = Math.floor((normAngle / (2 * Math.PI)) * count) % count;
return tipImages[idx];
} else {
- // Sequential
return tipImages[dabIndex % count];
}
}
/**
- * Draws a single dot at pointer down.
+ * Draws a single textured dot at pointer down.
*/
export function drawTexturedDot(
ctx: CanvasRenderingContext2D,
@@ -464,11 +568,14 @@ export function drawTexturedDot(
const isEraser = options.isEraser ?? false;
const isBgEraser = options.isBgEraser ?? false;
let effectiveColor = isBgEraser ? '#ffffff' : color;
- let effectiveFlow = options.flow ?? 0.85;
+ const baseDensity = options.brushDensity ?? options.flow ?? 0.85;
+ let effectiveFlow = computeGapAdjustedAlpha(baseDensity, options.spacing ?? 0.08, options.adjustDensityByGap);
- const effPressure = evaluateCspSpline(point.pressure, options.pressureCurve);
+ const effPressure = evaluateFastSpline(point.pressure, options.pressureCurve);
const minFactor = options.minSizeFactor ?? 0.2;
- const effWidth = Math.max(1, options.size * (minFactor + (1.0 - minFactor) * effPressure));
+ const effWidth = point.width > 0
+ ? Math.max(0.4, point.width)
+ : Math.max(0.5, options.size * (minFactor + (1.0 - minFactor) * effPressure));
const isColorMixing = Boolean(options.colorMixing) && !isEraser;
@@ -496,7 +603,8 @@ export function drawTexturedDot(
options.mixingMode ?? 'blend',
effPressure,
effectiveFlow,
- 0
+ 0,
+ options.perceptualMixing !== false
);
effectiveColor = mixed.colorHex;
@@ -515,34 +623,61 @@ export function drawTexturedDot(
}
}
- const activeTip = selectTipImage(options.subTipImages, tipImage, options.subTipOrder, 0, 0);
- const isColorTip = Boolean((options.subTips && options.subTips[0]?.isColor));
+ const activeTip = selectTipImage(options.subTipImages, tipImage, options.subTipOrder, 0, 0, point.x, point.y);
+ const isColorTip = Boolean(options.isColorTip || (options.subTips && options.subTips[0]?.isColor));
const master = getTintedTipMaster(activeTip, effectiveColor, isColorTip);
const aspect = (activeTip.naturalHeight || activeTip.height || 1) / (activeTip.naturalWidth || activeTip.width || 1);
const thickness = options.thickness ?? 1.0;
+ const isVert = Boolean(options.thicknessVertical);
+ const useTilt = Boolean(options.useTilt || options.angleDynamics === 'tilt');
- const tiltX = point.tiltX ?? 0;
- const tiltY = point.tiltY ?? 0;
+ 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 tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180) * (options.tiltScale ?? 1.0);
- let w = effWidth;
- let h = w * aspect * thickness;
let angleRad = ((options.angle ?? 0) * Math.PI) / 180;
-
- if (tiltMagnitude > 0.01) {
- const tiltAzimuth = Math.atan2(tiltY, tiltX);
- w = w * (1.0 + tiltMagnitude * 1.8);
- h = h / (1.0 + tiltMagnitude * 0.5);
- if (tiltMagnitude > 0.05) {
- angleRad = tiltAzimuth;
- }
+ if (useTilt && tiltMagnitude > 0.05) {
+ angleRad = Math.atan2(tiltY, tiltX) + angleRad;
}
- if (point.twist) {
+ if (point.twist && (options.angleDynamics === 'twist' || useTilt)) {
angleRad += (point.twist * Math.PI) / 180;
}
+ const sensorOpacity = evaluateCspSensor(
+ options.opacitySensor,
+ effPressure,
+ tiltMagnitude,
+ 0,
+ dabHashFloat(point.x, point.y, 0, 41)
+ );
+ const sensorDensity = evaluateCspSensor(
+ options.densitySensor,
+ effPressure,
+ tiltMagnitude,
+ 0,
+ dabHashFloat(point.x, point.y, 0, 42)
+ );
+ effectiveFlow *= sensorOpacity * sensorDensity;
+
+ // CPU Paper Texture modulation so live preview matches GPU bake
+ const grainAmount = options.grain ?? options.textureDensity ?? 0;
+ if (grainAmount > 0.005) {
+ const scale = Math.max(0.1, options.paperTextureScale ?? 1.0);
+ const gNorm = getPaperGrain(point.x / scale, point.y / scale) / 255.0;
+ effectiveFlow = applyCspPaperTextureAlpha(
+ effectiveFlow,
+ gNorm,
+ grainAmount,
+ effPressure,
+ options.paperTextureMode ?? 'subtract',
+ options.paperTextureBrightness ?? 0,
+ options.paperTextureContrast ?? 0,
+ Boolean(options.paperTextureInverted)
+ );
+ }
+
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));
@@ -553,77 +688,85 @@ export function drawTexturedDot(
const colorJitterEnabled = Boolean(dynamics?.colorJitterEnabled);
const primRgb = colorJitterEnabled ? parseColorToRgb(effectiveColor) : null;
const secRgb = colorJitterEnabled ? parseColorToRgb(options.secondaryColor || '#ffffff') : null;
+ const aaMode = options.antiAlias ?? 2;
for (let k = 0; k < dabCount; k++) {
let curDabW = effWidth;
if (sizeJitter > 0) {
- curDabW *= Math.max(0.01, 1.0 - Math.random() * sizeJitter);
+ curDabW *= Math.max(0.01, 1.0 - dabHashFloat(point.x, point.y, k, 1) * sizeJitter);
}
curDabW = Math.max(0.1, curDabW);
let curDabThickness = thickness;
if (roundnessJitter > 0) {
- curDabThickness *= Math.max(0.05, 1.0 - Math.random() * roundnessJitter);
+ curDabThickness *= Math.max(0.05, 1.0 - dabHashFloat(point.x, point.y, k, 2) * roundnessJitter);
}
let curDabAngle = angleRad;
if (angleJitter > 0) {
- curDabAngle += (Math.random() - 0.5) * Math.PI * 2 * angleJitter;
+ curDabAngle += (dabHashFloat(point.x, point.y, k, 3) - 0.5) * Math.PI * 2 * angleJitter;
}
let curDabX = point.x;
let curDabY = point.y;
if (scatter > 0) {
- const th = Math.random() * Math.PI * 2;
- const sDist = Math.random() * effWidth * scatter;
+ const th = dabHashFloat(point.x, point.y, k, 4) * Math.PI * 2;
+ const sDist = dabHashFloat(point.x, point.y, k, 5) * effWidth * scatter;
curDabX += Math.cos(th) * sDist;
curDabY += Math.sin(th) * sDist;
}
let curDabAlpha = effectiveFlow;
if (flowJitter > 0) {
- curDabAlpha *= Math.max(0.005, 1.0 - Math.random() * flowJitter);
+ curDabAlpha *= Math.max(0.005, 1.0 - dabHashFloat(point.x, point.y, k, 6) * flowJitter);
}
let curMaster = master;
if (colorJitterEnabled && primRgb && secRgb && dynamics) {
+ let salt = 20;
const cd = applyColorDynamics(
{ r: primRgb.r / 255, g: primRgb.g / 255, b: primRgb.b / 255 },
{ r: secRgb.r / 255, g: secRgb.g / 255, b: secRgb.b / 255 },
- dynamics
+ dynamics,
+ () => dabHashFloat(point.x, point.y, k, salt++)
);
curMaster = getTintedTipMaster(activeTip, cd.hex, isColorTip);
}
- let dotRenderW = curDabW;
- let dotRenderH = curDabW * aspect * curDabThickness;
- if (tiltMagnitude > 0.01) {
- dotRenderW = curDabW * (1.0 + tiltMagnitude * 1.8);
- dotRenderH = (curDabW * aspect * curDabThickness) / (1.0 + tiltMagnitude * 0.5);
+ let dotRenderW = isVert ? curDabW * curDabThickness : curDabW;
+ let dotRenderH = isVert ? curDabW * aspect : curDabW * aspect * curDabThickness;
+ if (useTilt && tiltMagnitude > 0.01) {
+ dotRenderW *= 1.0 + tiltMagnitude * 1.6;
+ dotRenderH /= 1.0 + tiltMagnitude * 0.45;
}
+ const flips = resolveTipFlipSigns(options.flipH, options.flipV, k, curDabX, curDabY);
if (options.spray?.enabled) {
const pCount = options.spray.density;
const pSize = Math.max(1, options.spray.size);
const radius = curDabW / 2;
for (let i = 0; i < pCount; i++) {
- const u1 = Math.random();
- const u2 = Math.random();
+ const u1 = dabHashFloat(curDabX, curDabY, k * 64 + i, 31);
+ const u2 = dabHashFloat(curDabX, curDabY, k * 64 + i, 32);
const r = radius * Math.sqrt(u1) * (1 - (options.spray.bias || 0) * (1 - u2));
- const th = Math.PI * 2 * Math.random();
+ const th = Math.PI * 2 * dabHashFloat(curDabX, curDabY, k * 64 + i, 33);
drawSingleStamp(
ctx,
curMaster,
curDabX + r * Math.cos(th),
curDabY + r * Math.sin(th),
- pSize,
- pSize * aspect * curDabThickness,
+ isVert ? pSize * curDabThickness : pSize,
+ isVert ? pSize * aspect : pSize * aspect * curDabThickness,
curDabAngle,
curDabAlpha,
isEraser,
isBgEraser,
options.alphaLocked,
- options.isTransparentInk
+ options.isTransparentInk,
+ flips.signX,
+ flips.signY,
+ aaMode,
+ options.blendTipsMode
);
}
} else {
@@ -639,54 +782,90 @@ export function drawTexturedDot(
isEraser,
isBgEraser,
options.alphaLocked,
- options.isTransparentInk
+ options.isTransparentInk,
+ flips.signX,
+ flips.signY,
+ aaMode,
+ options.blendTipsMode
);
}
}
}
// -------------------------------------------------------------
-// Cubic Bézier Evaluation and Arc Length Parameterization
+// Cubic Bézier Evaluation & Zero-Allocation Arc-Length Scratch
// -------------------------------------------------------------
-export function evalCubicBezier(
+export interface EvaluatedBezierSample {
+ x: number;
+ y: number;
+ width: number;
+ pressure: number;
+ dx: number;
+ dy: number;
+ speed: number;
+ tiltX: number;
+ tiltY: number;
+ twist: number;
+}
+
+const _sharedSample: EvaluatedBezierSample = {
+ x: 0,
+ y: 0,
+ width: 0,
+ pressure: 0,
+ dx: 0,
+ dy: 0,
+ speed: 0,
+ tiltX: 0,
+ tiltY: 0,
+ twist: 0,
+};
+
+function evalCubicBezierInto(
p0: Point,
c1: Point,
c2: Point,
p3: Point,
- t: number
-): { x: number; y: number; width: number; pressure: number; dx: number; dy: number; speed: number; tiltX?: number; tiltY?: number; twist?: number } {
+ t: number,
+ out: EvaluatedBezierSample
+): EvaluatedBezierSample {
const invT = 1.0 - t;
const invT2 = invT * invT;
const invT3 = invT2 * invT;
const t2 = t * t;
const t3 = t2 * t;
- const a = invT3;
const b = 3.0 * invT2 * t;
const c = 3.0 * invT * t2;
- const d = t3;
-
- const x = a * p0.x + b * c1.x + c * c2.x + d * p3.x;
- const y = a * p0.y + b * c1.y + c * c2.y + d * p3.y;
- const width = invT * p0.width + t * p3.width;
- const pressure = invT * p0.pressure + t * p3.pressure;
- const tiltX = invT * (p0.tiltX ?? 0) + t * (p3.tiltX ?? 0);
- const tiltY = invT * (p0.tiltY ?? 0) + t * (p3.tiltY ?? 0);
- const twist = invT * (p0.twist ?? 0) + t * (p3.twist ?? 0);
-
- const d01x = c1.x - p0.x;
- const d01y = c1.y - p0.y;
- const d12x = c2.x - c1.x;
- const d12y = c2.y - c1.y;
- const d23x = p3.x - c2.x;
- const d23y = p3.y - c2.y;
-
- const dx = 3.0 * invT2 * d01x + 6.0 * invT * t * d12x + 3.0 * t2 * d23x;
- const dy = 3.0 * invT2 * d01y + 6.0 * invT * t * d12y + 3.0 * t2 * d23y;
- const speed = Math.hypot(dx, dy);
-
- return { x, y, width, pressure, dx, dy, speed, tiltX, tiltY, twist };
+
+ out.x = invT3 * p0.x + b * c1.x + c * c2.x + t3 * p3.x;
+ out.y = invT3 * p0.y + b * c1.y + c * c2.y + t3 * p3.y;
+ out.width = invT3 * p0.width + b * c1.width + c * c2.width + t3 * p3.width;
+ out.pressure = invT3 * p0.pressure + b * c1.pressure + c * c2.pressure + t3 * p3.pressure;
+ out.tiltX = invT * (p0.tiltX ?? 0) + t * (p3.tiltX ?? 0);
+ out.tiltY = invT * (p0.tiltY ?? 0) + t * (p3.tiltY ?? 0);
+ out.twist = invT * (p0.twist ?? 0) + t * (p3.twist ?? 0);
+
+ const dx = 3.0 * invT2 * (c1.x - p0.x) + 6.0 * invT * t * (c2.x - c1.x) + 3.0 * t2 * (p3.x - c2.x);
+ const dy = 3.0 * invT2 * (c1.y - p0.y) + 6.0 * invT * t * (c2.y - c1.y) + 3.0 * t2 * (p3.y - c2.y);
+ out.dx = dx;
+ out.dy = dy;
+ out.speed = Math.hypot(dx, dy);
+ return out;
+}
+
+export function evalCubicBezier(
+ p0: Point,
+ c1: Point,
+ c2: Point,
+ p3: Point,
+ t: number
+): { x: number; y: number; width: number; pressure: number; dx: number; dy: number; speed: number; tiltX?: number; tiltY?: number; twist?: number } {
+ const out: EvaluatedBezierSample = {
+ x: 0, y: 0, width: 0, pressure: 0, dx: 0, dy: 0, speed: 0, tiltX: 0, tiltY: 0, twist: 0,
+ };
+ return evalCubicBezierInto(p0, c1, c2, p3, t, out);
}
export interface ArcLengthTable {
@@ -694,9 +873,16 @@ export interface ArcLengthTable {
distances: number[];
}
-export function buildCubicArcLengthTable(p0: Point, c1: Point, c2: Point, p3: Point): ArcLengthTable {
- const steps = 24;
- const distances: number[] = [0];
+// Fast reusable internal Float64Array arc-length scratch to avoid per-segment heap allocations
+const _fastArcDistances = new Float64Array(65);
+
+function buildFastArcLengthScratch(p0: Point, c1: Point, c2: Point, p3: Point): { totalLength: number; steps: number } {
+ const polyLen =
+ Math.hypot(c1.x - p0.x, c1.y - p0.y) +
+ Math.hypot(c2.x - c1.x, c2.y - c1.y) +
+ Math.hypot(p3.x - c2.x, p3.y - c2.y);
+ const steps = Math.max(24, Math.min(64, Math.ceil(polyLen * 0.5)));
+ _fastArcDistances[0] = 0;
let total = 0;
let prevX = p0.x;
let prevY = p0.y;
@@ -713,12 +899,55 @@ export function buildCubicArcLengthTable(p0: Point, c1: Point, c2: Point, p3: Po
const y = invT3 * p0.y + 3.0 * invT2 * t * c1.y + 3.0 * invT * t2 * c2.y + t3 * p3.y;
total += Math.hypot(x - prevX, y - prevY);
- distances.push(total);
+ _fastArcDistances[i] = total;
prevX = x;
prevY = y;
}
- return { totalLength: total, distances };
+ return { totalLength: total, steps };
+}
+
+function sampleFastArcLengthInto(
+ p0: Point,
+ c1: Point,
+ c2: Point,
+ p3: Point,
+ targetDist: number,
+ totalLength: number,
+ steps: number,
+ out: EvaluatedBezierSample
+): EvaluatedBezierSample {
+ if (totalLength <= 0.0001 || targetDist <= 0) {
+ return evalCubicBezierInto(p0, c1, c2, p3, 0, out);
+ }
+ if (targetDist >= totalLength) {
+ return evalCubicBezierInto(p0, c1, c2, p3, 1.0, out);
+ }
+
+ let low = 0;
+ let high = steps - 1;
+ while (low < high) {
+ const mid = (low + high + 1) >>> 1;
+ if (_fastArcDistances[mid] <= targetDist) {
+ low = mid;
+ } else {
+ high = mid - 1;
+ }
+ }
+ const d0 = _fastArcDistances[low];
+ const d1 = _fastArcDistances[low + 1];
+ const frac = d1 > d0 ? (targetDist - d0) / (d1 - d0) : 0;
+ const t = (low + frac) / steps;
+ return evalCubicBezierInto(p0, c1, c2, p3, Math.max(0, Math.min(1.0, t)), out);
+}
+
+export function buildCubicArcLengthTable(p0: Point, c1: Point, c2: Point, p3: Point): ArcLengthTable {
+ const { totalLength, steps } = buildFastArcLengthScratch(p0, c1, c2, p3);
+ const distances: number[] = new Array(steps + 1);
+ for (let i = 0; i <= steps; i++) {
+ distances[i] = _fastArcDistances[i];
+ }
+ return { totalLength, distances };
}
export function getCubicPointAtArcLength(
@@ -738,11 +967,17 @@ export function getCubicPointAtArcLength(
}
const steps = distances.length - 1;
- let idx = 0;
- while (idx < steps && distances[idx + 1] < targetDist) {
- idx++;
+ let low = 0;
+ let high = steps - 1;
+ while (low < high) {
+ const mid = (low + high + 1) >>> 1;
+ if (distances[mid] <= targetDist) {
+ low = mid;
+ } else {
+ high = mid - 1;
+ }
}
-
+ const idx = low;
const d0 = distances[idx];
const d1 = distances[idx + 1];
const frac = d1 > d0 ? (targetDist - d0) / (d1 - d0) : 0;
@@ -752,8 +987,7 @@ export function getCubicPointAtArcLength(
}
/**
- * Draws textured brush stamps along a cubic Bézier curve using arc-length parameterization.
- * Supports multi-tips, spline pressure curve, spray particle scattering, and wet edge.
+ * Draws textured CSP brush stamps along a cubic Bézier curve using zero-allocation arc-length parameterization.
*/
export function drawTexturedCubicBezierSegment(
ctx: CanvasRenderingContext2D,
@@ -765,12 +999,12 @@ export function drawTexturedCubicBezierSegment(
tipImage: HTMLImageElement,
options: TexturedBrushOptions,
remainderDist: number = 0,
- dabCounter: { count: number } = { count: 0 }
+ dabCounter: { count: number } = { count: 0 },
+ batchGpuDabs?: GpuDab[]
): number {
- const arcTable = buildCubicArcLengthTable(p0, c1, c2, p3);
- const totalCurveLength = arcTable.totalLength;
- if (totalCurveLength < 0.1) {
- return remainderDist;
+ const { totalLength: totalCurveLength, steps: arcSteps } = buildFastArcLengthScratch(p0, c1, c2, p3);
+ if (totalCurveLength < 0.08) {
+ return Math.max(0, remainderDist - totalCurveLength);
}
const isEraser = options.isEraser ?? false;
@@ -787,20 +1021,17 @@ export function drawTexturedCubicBezierSegment(
const reservoir = options.reservoir;
const aspect = (tipImage.naturalHeight || tipImage.height || 1) / (tipImage.naturalWidth || tipImage.width || 1);
const baseAngleRad = ((options.angle ?? 0) * Math.PI) / 180;
- const baseFlow = options.flow ?? 0.85;
+ const rawDensity = options.brushDensity ?? options.flow ?? 0.85;
const spacingRatio = Math.max(0.015, Math.min(1.0, options.spacing ?? 0.07));
+ const baseFlow = computeGapAdjustedAlpha(rawDensity, spacingRatio, options.adjustDensityByGap);
const thickness = options.thickness ?? 1.0;
+ const isVert = Boolean(options.thicknessVertical);
const rotationRandomScale = options.rotationRandomScale ?? 0;
+ const useTilt = Boolean(options.useTilt || options.angleDynamics === 'tilt');
+ const aaMode = options.antiAlias ?? 2;
+ const grainAmount = options.grain ?? options.textureDensity ?? 0;
- const gpuEngine = WebGlBrushEngine.getInstance();
- const canUseGpu =
- Boolean(options.useGpu) &&
- gpuEngine.isAvailable() &&
- !options.alphaLocked &&
- !options.isTransparentInk &&
- (!options.subTipImages || options.subTipImages.length <= 1) &&
- Boolean(ctx.canvas && ctx.canvas.width > 0 && ctx.canvas.height > 0);
- const gpuDabs: GpuDab[] | null = canUseGpu ? [] : null;
+ const gpuDabs: GpuDab[] | null = batchGpuDabs || null;
let smoothCos = Math.cos(baseAngleRad);
let smoothSin = Math.sin(baseAngleRad);
@@ -808,53 +1039,104 @@ export function drawTexturedCubicBezierSegment(
let currentDist = remainderDist > 0 ? remainderDist : 0;
while (currentDist <= totalCurveLength) {
- const pt = getCubicPointAtArcLength(p0, c1, c2, p3, currentDist, arcTable);
- const effPressure = evaluateCspSpline(pt.pressure, options.pressureCurve);
+ const pt = sampleFastArcLengthInto(p0, c1, c2, p3, currentDist, totalCurveLength, arcSteps, _sharedSample);
+ const effPressure = Math.max(0, Math.min(1, pt.pressure));
+ const curvedPressure = options.pressureCurve ? evaluateFastSpline(effPressure, options.pressureCurve) : effPressure;
const minFactor = Math.max(0, Math.min(1.0, options.minSizeFactor ?? 0));
- let curWidth = options.usePressure !== false
- ? options.size * (minFactor + (1.0 - minFactor) * effPressure)
- : options.size;
+ let curWidth = pt.width > 0
+ ? pt.width
+ : (options.usePressure !== false
+ ? options.size * (minFactor + (1.0 - minFactor) * curvedPressure)
+ : options.size);
const strokeDist = (options.currentStrokeDist ?? 0) + currentDist;
- // Stroke taper modulation (Clip Studio Paint style)
+ // CSP Starting & Ending taper modulation (supports sharpness curves + Size/Density/Opacity targets)
+ let taperAlphaScale = 1.0;
if (options.taper) {
+ const inSharp = 0.35 + (1.0 - (options.taper.startingSharpness ?? 0.5)) * 1.1;
+ const outSharp = 0.35 + (1.0 - (options.taper.endingSharpness ?? 0.5)) * 1.1;
const inLen = options.taper.inLength || (options.taper.inRatio ? options.taper.inRatio * 2.5 : 0);
if (options.taper.useIn && inLen > 0 && strokeDist < inLen) {
- const inFactor = Math.max(0.01, Math.min(1.0, strokeDist / inLen));
- curWidth *= Math.pow(inFactor, 0.75);
+ const inFactor = Math.pow(Math.max(0.01, Math.min(1.0, strokeDist / inLen)), inSharp);
+ if (options.taper.affectSize !== false) curWidth *= inFactor;
+ if (options.taper.affectDensity || options.taper.affectOpacity) taperAlphaScale *= inFactor;
}
if (options.totalLength && options.totalLength > 0) {
const distFromEnd = options.totalLength - strokeDist;
const outLen = options.taper.outLength || (options.taper.outRatio ? options.taper.outRatio * 3.0 : 0);
if (options.taper.useOut && outLen > 0 && distFromEnd < outLen) {
- const outFactor = Math.max(0.01, Math.min(1.0, distFromEnd / outLen));
- curWidth *= Math.pow(outFactor, 0.85);
+ const outFactor = Math.pow(Math.max(0.01, Math.min(1.0, distFromEnd / outLen)), outSharp);
+ if (options.taper.affectSize !== false) curWidth *= outFactor;
+ if (options.taper.affectDensity || options.taper.affectOpacity) taperAlphaScale *= outFactor;
}
}
}
+ const dabSeq = dabCounter.count++;
+
+ const tiltX = useTilt ? pt.tiltX : 0;
+ const tiltY = useTilt ? pt.tiltY : 0;
+ const tiltAngleDeg = Math.min(90, Math.sqrt(tiltX * tiltX + tiltY * tiltY));
+ const tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180) * (options.tiltScale ?? 1.0);
+
+ // Multi-sensor CSP size modulation
+ if (options.sizeSensor) {
+ curWidth *= evaluateCspSensor(
+ options.sizeSensor,
+ effPressure,
+ tiltMagnitude,
+ pt.speed * 0.05,
+ dabHashFloat(pt.x, pt.y, dabSeq, 50)
+ );
+ }
curWidth = Math.max(0.1, curWidth);
let stampAngle = baseAngleRad;
- if (options.angleDynamics === 'direction' && pt.speed > 0.05) {
+ if ((options.angleDynamics === 'direction' || options.angleDynamics === 'direction-random') && pt.speed > 0.05) {
const targetAngle = Math.atan2(pt.dy, pt.dx) + baseAngleRad;
const tCos = Math.cos(targetAngle);
const tSin = Math.sin(targetAngle);
- smoothCos = smoothCos * 0.65 + tCos * 0.35;
- smoothSin = smoothSin * 0.65 + tSin * 0.35;
+ smoothCos = smoothCos * 0.6 + tCos * 0.4;
+ smoothSin = smoothSin * 0.6 + tSin * 0.4;
stampAngle = Math.atan2(smoothSin, smoothCos);
- } else if (options.angleDynamics === 'random') {
- stampAngle = baseAngleRad + (Math.random() - 0.5) * Math.PI * 2;
+ }
+ if (options.angleDynamics === 'random' || options.angleDynamics === 'direction-random') {
+ const rScale = options.angleDynamics === 'random' ? 1.0 : (rotationRandomScale || 0.35);
+ stampAngle += (dabHashFloat(pt.x, pt.y, dabSeq, 12) - 0.5) * Math.PI * 2 * rScale;
+ } else if (rotationRandomScale > 0) {
+ stampAngle += (dabHashFloat(pt.x, pt.y, dabSeq, 12) - 0.5) * Math.PI * 2 * rotationRandomScale;
}
- if (rotationRandomScale > 0) {
- stampAngle += (Math.random() - 0.5) * Math.PI * 2 * rotationRandomScale;
+ if (useTilt && tiltMagnitude > 0.05) {
+ stampAngle = Math.atan2(tiltY, tiltX) + baseAngleRad;
+ }
+ if (pt.twist && (options.angleDynamics === 'twist' || useTilt)) {
+ stampAngle += (pt.twist * Math.PI) / 180;
}
let dabColor = baseColor;
- let dabAlpha = baseFlow;
+ let dabAlpha = baseFlow * taperAlphaScale;
+
+ if (options.opacitySensor) {
+ dabAlpha *= evaluateCspSensor(
+ options.opacitySensor,
+ effPressure,
+ tiltMagnitude,
+ pt.speed * 0.05,
+ dabHashFloat(pt.x, pt.y, dabSeq, 51)
+ );
+ }
+ if (options.densitySensor) {
+ dabAlpha *= evaluateCspSensor(
+ options.densitySensor,
+ effPressure,
+ tiltMagnitude,
+ pt.speed * 0.05,
+ dabHashFloat(pt.x, pt.y, dabSeq, 52)
+ );
+ }
if (isColorMixing && reservoir) {
let sampled = { r: 255, g: 255, b: 255, a: 0 };
@@ -875,8 +1157,9 @@ export function drawTexturedCubicBezierSegment(
options.colorStretch ?? 0.75,
options.mixingMode ?? 'blend',
effPressure,
- baseFlow,
- Math.max(0.2, curWidth * spacingRatio)
+ dabAlpha,
+ Math.max(0.2, curWidth * spacingRatio),
+ options.perceptualMixing !== false
);
dabColor = mixed.colorHex;
@@ -895,50 +1178,43 @@ export function drawTexturedCubicBezierSegment(
}
}
- // Wet Edge rim boost
- if (options.wetEdge && options.wetEdge > 0 && !gpuDabs) {
- dabAlpha = Math.min(1.0, dabAlpha * (1.0 + options.wetEdge * 0.25));
+ // CPU paper grain parity (when rendering live on Canvas2D without GPU batch)
+ if (!gpuDabs && grainAmount > 0.005) {
+ const scale = Math.max(0.1, options.paperTextureScale ?? 1.0);
+ const gNorm = getPaperGrain(pt.x / scale, pt.y / scale) / 255.0;
+ dabAlpha = applyCspPaperTextureAlpha(
+ dabAlpha,
+ gNorm,
+ grainAmount,
+ effPressure,
+ options.paperTextureMode ?? 'subtract',
+ options.paperTextureBrightness ?? 0,
+ options.paperTextureContrast ?? 0,
+ Boolean(options.paperTextureInverted)
+ );
}
- // Select tip from multi-tip array
const activeTip = selectTipImage(
options.subTipImages,
tipImage,
options.subTipOrder,
- dabCounter.count++,
- stampAngle
+ dabSeq,
+ stampAngle,
+ pt.x,
+ pt.y
);
- const isColorTip = Boolean(options.subTips && options.subTips[0]?.isColor);
+ const isColorTip = Boolean(options.isColorTip || (options.subTips && options.subTips[0]?.isColor));
const master = gpuDabs ? null : getTintedTipMaster(activeTip, dabColor, isColorTip);
- const tiltX = pt.tiltX ?? 0;
- const tiltY = pt.tiltY ?? 0;
- const tiltAngleDeg = Math.min(90, Math.sqrt(tiltX * tiltX + tiltY * tiltY));
- const tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180);
-
- let dabAngle = stampAngle;
- if (tiltMagnitude > 0.05) {
- dabAngle = Math.atan2(tiltY, tiltX);
- }
- if (pt.twist) {
- dabAngle += (pt.twist * Math.PI) / 180;
- }
-
- const speed = Math.hypot(pt.dx, pt.dy);
- let tx = 0;
+ let tx = 1;
let ty = 0;
let nx = 0;
- let ny = 0;
- if (speed > 0.001) {
- tx = pt.dx / speed;
- ty = pt.dy / speed;
+ let ny = 1;
+ if (pt.speed > 0.001) {
+ tx = pt.dx / pt.speed;
+ ty = pt.dy / pt.speed;
nx = -ty;
ny = tx;
- } else {
- nx = 0;
- ny = 1;
- tx = 1;
- ty = 0;
}
const dynamics = options.dynamics;
@@ -953,31 +1229,35 @@ export function drawTexturedCubicBezierSegment(
const primRgb = (colorJitterEnabled || gpuDabs) ? parseColorToRgb(dabColor) : null;
const secRgb = colorJitterEnabled ? parseColorToRgb(options.secondaryColor || '#ffffff') : null;
+ let stepRefW = isVert ? curWidth * thickness : curWidth;
+ let stepRefH = isVert ? curWidth * aspect : curWidth * aspect * thickness;
+
for (let k = 0; k < dabCount; k++) {
+ const seedIdx = dabSeq * 16 + k;
let curDabW = curWidth;
if (sizeJitter > 0) {
- curDabW *= Math.max(0.01, 1.0 - Math.random() * sizeJitter);
+ curDabW *= Math.max(0.01, 1.0 - dabHashFloat(pt.x, pt.y, seedIdx, 1) * sizeJitter);
}
curDabW = Math.max(0.1, curDabW);
let curDabThickness = thickness;
if (roundnessJitter > 0) {
- curDabThickness *= Math.max(0.05, 1.0 - Math.random() * roundnessJitter);
+ curDabThickness *= Math.max(0.05, 1.0 - dabHashFloat(pt.x, pt.y, seedIdx, 2) * roundnessJitter);
}
- let curDabAngle = dabAngle;
+ let curDabAngle = stampAngle;
if (angleJitter > 0) {
- curDabAngle += (Math.random() - 0.5) * Math.PI * 2 * angleJitter;
+ curDabAngle += (dabHashFloat(pt.x, pt.y, seedIdx, 3) - 0.5) * Math.PI * 2 * angleJitter;
}
let curDabX = pt.x;
let curDabY = pt.y;
if (scatter > 0) {
- const perpDist = (Math.random() * 2 - 1) * curWidth * scatter;
+ const perpDist = (dabHashFloat(pt.x, pt.y, seedIdx, 4) * 2 - 1) * curWidth * scatter;
let sOffX = nx * perpDist;
let sOffY = ny * perpDist;
if (scatterBothAxes) {
- const tangDist = (Math.random() * 2 - 1) * curWidth * scatter;
+ const tangDist = (dabHashFloat(pt.x, pt.y, seedIdx, 5) * 2 - 1) * curWidth * scatter;
sOffX += tx * tangDist;
sOffY += ty * tangDist;
}
@@ -987,7 +1267,7 @@ export function drawTexturedCubicBezierSegment(
let curDabAlpha = dabAlpha;
if (flowJitter > 0) {
- curDabAlpha *= Math.max(0.005, 1.0 - Math.random() * flowJitter);
+ curDabAlpha *= Math.max(0.005, 1.0 - dabHashFloat(pt.x, pt.y, seedIdx, 6) * flowJitter);
}
let curMaster = master;
@@ -996,10 +1276,12 @@ export function drawTexturedCubicBezierSegment(
let dabB = primRgb ? primRgb.b / 255 : 0;
if (colorJitterEnabled && primRgb && secRgb && dynamics) {
+ let salt = 20;
const cd = applyColorDynamics(
{ r: primRgb.r / 255, g: primRgb.g / 255, b: primRgb.b / 255 },
{ r: secRgb.r / 255, g: secRgb.g / 255, b: secRgb.b / 255 },
- dynamics
+ dynamics,
+ () => dabHashFloat(pt.x, pt.y, seedIdx, salt++)
);
dabR = cd.r;
dabG = cd.g;
@@ -1009,30 +1291,35 @@ export function drawTexturedCubicBezierSegment(
}
}
- let finalW = curDabW;
- let finalH = curDabW * aspect * curDabThickness;
- if (tiltMagnitude > 0.01) {
- finalW = curDabW * (1.0 + tiltMagnitude * 1.8);
- finalH = (curDabW * aspect * curDabThickness) / (1.0 + tiltMagnitude * 0.5);
+ let finalW = isVert ? curDabW * curDabThickness : curDabW;
+ let finalH = isVert ? curDabW * aspect : curDabW * aspect * curDabThickness;
+ if (useTilt && tiltMagnitude > 0.01) {
+ finalW *= 1.0 + tiltMagnitude * 1.6;
+ finalH /= 1.0 + tiltMagnitude * 0.45;
}
+ stepRefW = finalW;
+ stepRefH = finalH;
+
+ const flips = resolveTipFlipSigns(options.flipH, options.flipV, seedIdx, curDabX, curDabY);
if (options.spray?.enabled) {
const pCount = options.spray.density;
const pSize = Math.max(1, options.spray.size);
const radius = curDabW / 2;
for (let sp = 0; sp < pCount; sp++) {
- const u1 = Math.random();
- const u2 = Math.random();
+ const u1 = dabHashFloat(curDabX, curDabY, seedIdx * 64 + sp, 31);
+ const u2 = dabHashFloat(curDabX, curDabY, seedIdx * 64 + sp, 32);
const r = radius * Math.sqrt(u1) * (1 - (options.spray.bias || 0) * (1 - u2));
- const th = Math.PI * 2 * Math.random();
+ 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 spH = pSize * aspect * curDabThickness;
+ const spW = isVert ? pSize * curDabThickness : pSize;
+ const spH = isVert ? pSize * aspect : pSize * aspect * curDabThickness;
if (gpuDabs) {
gpuDabs.push({
x: spX,
y: spY,
- width: pSize,
+ width: spW,
height: spH,
angle: curDabAngle,
r: dabR,
@@ -1041,6 +1328,8 @@ export function drawTexturedCubicBezierSegment(
alpha: curDabAlpha,
pressure: effPressure,
strokeDist,
+ flipX: flips.signX,
+ flipY: flips.signY,
});
} else if (curMaster) {
drawSingleStamp(
@@ -1048,14 +1337,18 @@ export function drawTexturedCubicBezierSegment(
curMaster,
spX,
spY,
- pSize,
+ spW,
spH,
curDabAngle,
curDabAlpha,
isEraser,
isBgEraser,
options.alphaLocked,
- options.isTransparentInk
+ options.isTransparentInk,
+ flips.signX,
+ flips.signY,
+ aaMode,
+ options.blendTipsMode
);
}
}
@@ -1072,6 +1365,8 @@ export function drawTexturedCubicBezierSegment(
alpha: curDabAlpha,
pressure: effPressure,
strokeDist,
+ flipX: flips.signX,
+ flipY: flips.signY,
});
} else if (curMaster) {
drawSingleStamp(
@@ -1086,48 +1381,30 @@ export function drawTexturedCubicBezierSegment(
isEraser,
isBgEraser,
options.alphaLocked,
- options.isTransparentInk
+ options.isTransparentInk,
+ flips.signX,
+ flips.signY,
+ aaMode,
+ options.blendTipsMode
);
}
}
- const requiredStep = Math.max(0.2, curWidth * spacingRatio);
- currentDist += requiredStep;
- }
-
- if (gpuDabs && gpuDabs.length > 0) {
- gpuEngine.renderDabsToContext(
- ctx,
- gpuDabs,
- {
- size: options.size,
- opacity: options.opacity ?? 1.0,
- flow: baseFlow,
- hardness: options.hardness ?? 1.0,
- wetEdge: options.wetEdge ?? 0,
- grain: options.grain,
- textureDensity: options.textureDensity,
- paperTextureScale: options.paperTextureScale,
- customTipImage: tipImage,
- dualBrush: options.dualBrush,
- dualTipImage: options.dualTipImage,
- dualBrushCompositeMode: options.dualBrushCompositeMode,
- colorMixing: false, // Reservoir already mixed per dab with LayerPixelSampler
- perceptualMixing: options.perceptualMixing,
- } as any,
- isEraser ? 'eraser' : 'brush',
- ctx.canvas.width,
- ctx.canvas.height
+ const requiredStep = computeEllipticalStepDistance(
+ stepRefW,
+ stepRefH,
+ stampAngle,
+ pt.dx,
+ pt.dy,
+ spacingRatio,
+ 0.15
);
+ currentDist += requiredStep;
}
- const nextRemainder = currentDist - totalCurveLength;
- return Math.max(0, nextRemainder);
+ return Math.max(0, currentDist - totalCurveLength);
}
-/**
- * Draws textured brush stamps along a quadratic Bézier curve by elevating to cubic.
- */
export function drawTexturedBezierSegment(
ctx: CanvasRenderingContext2D,
start: Point,
@@ -1165,58 +1442,6 @@ export function drawTexturedBezierSegment(
);
}
-/**
- * Converts 4 Catmull-Rom spline knots into cubic Bézier control points.
- */
-function catmullRomToCubicKnots(
- p0: Point,
- p1: Point,
- p2: Point,
- p3: Point
-): { c1: Point; c2: Point } {
- const dChord = Math.hypot(p2.x - p1.x, p2.y - p1.y);
-
- let dx1 = (p2.x - p0.x) / 6;
- let dy1 = (p2.y - p0.y) / 6;
- let dx2 = (p3.x - p1.x) / 6;
- let dy2 = (p3.y - p1.y) / 6;
-
- if (dChord > 0.001) {
- const maxHandle = dChord * 0.5;
- const len1 = Math.hypot(dx1, dy1);
- if (len1 > maxHandle) {
- const s = maxHandle / len1;
- dx1 *= s;
- dy1 *= s;
- }
- const len2 = Math.hypot(dx2, dy2);
- if (len2 > maxHandle) {
- const s = maxHandle / len2;
- dx2 *= s;
- dy2 *= s;
- }
- }
-
- const c1: Point = {
- x: p1.x + dx1,
- y: p1.y + dy1,
- pressure: p1.pressure + (p2.pressure - p0.pressure) / 6,
- width: p1.width + (p2.width - p0.width) / 6,
- };
-
- const c2: Point = {
- x: p2.x - dx2,
- y: p2.y - dy2,
- pressure: p2.pressure - (p3.pressure - p1.pressure) / 6,
- width: p2.width - (p3.width - p1.width) / 6,
- };
-
- return { c1, c2 };
-}
-
-/**
- * Renders an entire completed textured stroke onto the target Canvas2D context using Catmull-Rom cubic splines.
- */
export function renderCompleteTexturedStroke(
ctx: CanvasRenderingContext2D,
points: Point[],
@@ -1236,49 +1461,99 @@ export function renderCompleteTexturedStroke(
options.sampler = new LayerPixelSampler(options.underlyingCanvas);
}
- // Draw initial dot at points[0]
drawTexturedDot(ctx, points[0], color, tipImage, options);
if (points.length === 1) {
return;
}
+ let totalLen = 0;
+ for (let i = 1; i < points.length; i++) {
+ totalLen += Math.hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y);
+ }
+ options.totalLength = totalLen;
+ options.currentStrokeDist = 0;
+
+ const gpuEngine = WebGlBrushEngine.getInstance();
+ const canUseGpu =
+ Boolean(options.useGpu) &&
+ gpuEngine.isAvailable() &&
+ (!options.subTipImages || options.subTipImages.length <= 1) &&
+ Boolean(ctx.canvas && ctx.canvas.width > 0 && ctx.canvas.height > 0);
+ const batchGpuDabs: GpuDab[] | undefined = canUseGpu ? [] : undefined;
+
const dabCounter = { count: 0 };
- let accDist = Math.max(0.2, points[0].width * (options.spacing ?? 0.07));
+ let accDist = Math.max(0.15, points[0].width * (options.spacing ?? 0.07));
if (points.length === 2) {
const p0 = points[0];
const p1 = points[1];
- const { c1, c2 } = catmullRomToCubicKnots(p0, p0, p1, p1);
- drawTexturedCubicBezierSegment(ctx, p0, c1, c2, p1, color, tipImage, options, accDist, dabCounter);
- return;
- }
+ const { c1, c2 } = centripetalCatmullRomToBezier(p0, p0, p1, p1);
+ drawTexturedCubicBezierSegment(ctx, p0, c1, c2, p1, color, tipImage, options, accDist, dabCounter, batchGpuDabs);
+ } else {
+ const p0 = points[0];
+ const p1 = points[1];
+ const p2 = points[2];
+ const first = centripetalCatmullRomToBezier(p0, p0, p1, p2);
+ accDist = drawTexturedCubicBezierSegment(ctx, p0, first.c1, first.c2, p1, color, tipImage, options, accDist, dabCounter, batchGpuDabs);
+ options.currentStrokeDist = (options.currentStrokeDist ?? 0) + Math.hypot(p1.x - p0.x, p1.y - p0.y);
+
+ for (let i = 2; i < points.length - 1; i++) {
+ const seg = centripetalCatmullRomToBezier(points[i - 2], points[i - 1], points[i], points[i + 1]);
+ accDist = drawTexturedCubicBezierSegment(ctx, points[i - 1], seg.c1, seg.c2, points[i], color, tipImage, options, accDist, dabCounter, batchGpuDabs);
+ options.currentStrokeDist = (options.currentStrokeDist ?? 0) + Math.hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y);
+ }
- // First segment: P0 -> P1 using (P0, P0, P1, P2)
- const p0 = points[0];
- const p1 = points[1];
- const p2 = points[2];
- const first = catmullRomToCubicKnots(p0, p0, p1, p2);
- accDist = drawTexturedCubicBezierSegment(ctx, p0, first.c1, first.c2, p1, color, tipImage, options, accDist, dabCounter);
-
- // Intermediate segments: P_{i-1} -> P_i using (P_{i-2}, P_{i-1}, P_i, P_{i+1})
- for (let i = 2; i < points.length - 1; i++) {
- const seg = catmullRomToCubicKnots(points[i - 2], points[i - 1], points[i], points[i + 1]);
- accDist = drawTexturedCubicBezierSegment(ctx, points[i - 1], seg.c1, seg.c2, points[i], color, tipImage, options, accDist, dabCounter);
+ const n = points.length;
+ const pPrev2 = points[n - 3];
+ const pPrev = points[n - 2];
+ const pLast = points[n - 1];
+ const last = centripetalCatmullRomToBezier(pPrev2, pPrev, pLast, pLast);
+ drawTexturedCubicBezierSegment(ctx, pPrev, last.c1, last.c2, pLast, color, tipImage, options, accDist, dabCounter, batchGpuDabs);
}
- // Last segment: P_{N-2} -> P_{N-1} using (P_{N-3}, P_{N-2}, P_{N-1}, P_{N-1})
- const n = points.length;
- const pPrev2 = points[n - 3];
- const pPrev = points[n - 2];
- const pLast = points[n - 1];
- const last = catmullRomToCubicKnots(pPrev2, pPrev, pLast, pLast);
- drawTexturedCubicBezierSegment(ctx, pPrev, last.c1, last.c2, pLast, color, tipImage, options, accDist, dabCounter);
+ if (batchGpuDabs && batchGpuDabs.length > 0) {
+ const isEraser = options.isEraser ?? false;
+ gpuEngine.renderDabsToContext(
+ ctx,
+ batchGpuDabs,
+ {
+ size: options.size,
+ opacity: options.opacity ?? 1.0,
+ flow: options.flow ?? 0.85,
+ brushDensity: options.brushDensity,
+ blendTipsMode: options.blendTipsMode,
+ hardness: options.hardness ?? 1.0,
+ antiAlias: options.antiAlias ?? 2,
+ wetEdge: options.wetEdge ?? 0,
+ grain: options.grain,
+ textureDensity: options.textureDensity,
+ paperTextureMode: options.paperTextureMode,
+ paperTextureBrightness: options.paperTextureBrightness,
+ paperTextureContrast: options.paperTextureContrast,
+ paperTextureInverted: options.paperTextureInverted,
+ paperTextureImage: options.paperTextureImage,
+ paperTextureScale: options.paperTextureScale,
+ paperTextureRotate: options.paperTextureRotate,
+ customTipImage: tipImage,
+ isColorTip: Boolean(options.isColorTip || (options.subTips && options.subTips[0]?.isColor)),
+ dualBrush: options.dualBrush,
+ dualTipImage: options.dualTipImage,
+ dualBrushCompositeMode: options.dualBrushCompositeMode,
+ colorMixing: false,
+ perceptualMixing: options.perceptualMixing,
+ alphaLocked: options.alphaLocked,
+ isTransparentInk: options.isTransparentInk,
+ } as any,
+ isEraser ? 'eraser' : 'brush',
+ ctx.canvas.width,
+ ctx.canvas.height
+ );
+ }
}
/**
* Centripetal Catmull-Rom spline (alpha = 0.5) to cubic Bézier control points.
- * Mathematically guarantees zero self-intersections, cusps, or overshoot on sharp curves.
*/
export function centripetalCatmullRomToBezier(
p0: Point,
@@ -1286,18 +1561,21 @@ export function centripetalCatmullRomToBezier(
p2: Point,
p3: Point
): { c1: Point; c2: Point } {
- const d01 = Math.hypot(p1.x - p0.x, p1.y - p0.y);
+ const effP0 = p1.isCorner ? p1 : p0;
+ const effP3 = p2.isCorner ? p2 : p3;
+
+ const d01 = Math.hypot(p1.x - effP0.x, p1.y - effP0.y);
const d12 = Math.hypot(p2.x - p1.x, p2.y - p1.y);
- const d23 = Math.hypot(p3.x - p2.x, p3.y - p2.y);
+ const d23 = Math.hypot(effP3.x - p2.x, effP3.y - p2.y);
const dt0 = Math.max(1e-4, Math.sqrt(d01));
const dt1 = Math.max(1e-4, Math.sqrt(d12));
const dt2 = Math.max(1e-4, Math.sqrt(d23));
- const t1x = (p2.x - p1.x) / dt1 - (p1.x - p0.x) / dt0 + (p2.x - p0.x) / (dt0 + dt1);
- const t1y = (p2.y - p1.y) / dt1 - (p1.y - p0.y) / dt0 + (p2.y - p0.y) / (dt0 + dt1);
- const t2x = (p3.x - p2.x) / dt2 - (p2.x - p1.x) / dt1 + (p3.x - p1.x) / (dt1 + dt2);
- const t2y = (p3.y - p2.y) / dt2 - (p2.y - p1.y) / dt1 + (p3.y - p1.y) / (dt1 + dt2);
+ const t1x = (p2.x - p1.x) / dt1 - (p1.x - effP0.x) / dt0 + (p2.x - effP0.x) / (dt0 + dt1);
+ const t1y = (p2.y - p1.y) / dt1 - (p1.y - effP0.y) / dt0 + (p2.y - effP0.y) / (dt0 + dt1);
+ const t2x = (effP3.x - p2.x) / dt2 - (p2.x - p1.x) / dt1 + (effP3.x - p1.x) / (dt1 + dt2);
+ const t2y = (effP3.y - p2.y) / dt2 - (p2.y - p1.y) / dt1 + (effP3.y - p1.y) / (dt1 + dt2);
let dx1 = (t1x * dt1) / 3;
let dy1 = (t1y * dt1) / 3;
@@ -1320,18 +1598,23 @@ export function centripetalCatmullRomToBezier(
}
}
+ const minP = Math.min(p1.pressure, p2.pressure);
+ const maxP = Math.max(p1.pressure, p2.pressure);
+ const minW = Math.min(p1.width, p2.width);
+ const maxW = Math.max(p1.width, p2.width);
+
const c1: Point = {
x: p1.x + dx1,
y: p1.y + dy1,
- pressure: p1.pressure + (p2.pressure - p0.pressure) / 6,
- width: p1.width + (p2.width - p0.width) / 6,
+ pressure: Math.max(minP, Math.min(maxP, p1.pressure + (p2.pressure - effP0.pressure) / 6)),
+ width: Math.max(minW, Math.min(maxW, p1.width + (p2.width - effP0.width) / 6)),
};
const c2: Point = {
x: p2.x - dx2,
y: p2.y - dy2,
- pressure: p2.pressure - (p3.pressure - p1.pressure) / 6,
- width: p2.width - (p3.width - p1.width) / 6,
+ pressure: Math.max(minP, Math.min(maxP, p2.pressure - (effP3.pressure - p1.pressure) / 6)),
+ width: Math.max(minW, Math.min(maxW, p2.width - (effP3.width - p1.width) / 6)),
};
return { c1, c2 };
@@ -1343,7 +1626,7 @@ export interface RadialMixingOptions {
amountOfPaint?: number;
densityOfPaint?: number;
colorStretch?: number;
- mixingMode?: 'blend' | 'running_color';
+ mixingMode?: 'blend' | 'running_color' | 'smear';
underlyingCanvas?: HTMLCanvasElement;
sampler?: LayerPixelSampler;
reservoir?: PaintReservoir;
@@ -1355,10 +1638,35 @@ export interface RadialMixingOptions {
dualBrush?: boolean;
dualTipImage?: HTMLImageElement;
dualBrushCompositeMode?: string;
+ // Extended CSP Options for analytical round/elliptical brushes
+ useTilt?: boolean;
+ tiltScale?: number;
+ thicknessVertical?: boolean;
+ flipH?: CspTipFlipMode;
+ flipV?: CspTipFlipMode;
+ antiAlias?: number;
+ angleDynamics?: CspAngleDynamicsMode;
+ rotationRandomScale?: number;
+ adjustDensityByGap?: boolean;
+ blendTipsMode?: CspBlendTipsMode;
+ grain?: number;
+ paperTextureMode?: CspPaperTextureMode;
+ paperTextureBrightness?: number;
+ paperTextureContrast?: number;
+ paperTextureInverted?: boolean;
+ paperTextureImage?: HTMLImageElement;
+ paperTextureScale?: number;
+ paperTextureRotate?: number;
+ sizeSensor?: CspSensorConfig;
+ opacitySensor?: CspSensorConfig;
+ densitySensor?: CspSensorConfig;
+ taper?: CspTaperSettings;
+ totalLength?: number;
+ currentStrokeDist?: number;
}
/**
- * Draws a single radial dot.
+ * Draws a single radial/elliptical dot.
*/
export function drawRadialDot(
ctx: CanvasRenderingContext2D,
@@ -1368,12 +1676,18 @@ export function drawRadialDot(
flow: number = 1.0,
isEraser: boolean = false,
isBgEraser: boolean = false,
- mixingOptions?: RadialMixingOptions
+ mixingOptions?: RadialMixingOptions,
+ thickness: number = 1.0,
+ angleRad: number = 0
) {
const isColorMixing = Boolean(mixingOptions?.colorMixing) && !isEraser && !isBgEraser;
let dabColor = isBgEraser ? '#ffffff' : color;
let dabFlow = flow;
- const w = Math.max(0.5, point.width);
+ const w = Math.max(0.4, point.width);
+ const aaMode = mixingOptions?.antiAlias ?? 2;
+ const isVert = Boolean(mixingOptions?.thicknessVertical);
+ // Default useTilt to true ONLY when mixingOptions is undefined (legacy unit test compatibility) or explicitly true
+ const useTilt = mixingOptions === undefined ? true : Boolean(mixingOptions.useTilt);
if (isColorMixing) {
if (!mixingOptions!.reservoir) {
@@ -1399,7 +1713,8 @@ export function drawRadialDot(
mixingOptions!.mixingMode ?? 'blend',
point.pressure ?? 1.0,
flow,
- 0
+ 0,
+ mixingOptions!.perceptualMixing !== false
);
dabColor = mixed.colorHex;
@@ -1418,25 +1733,41 @@ export function drawRadialDot(
}
}
- const tiltX = point.tiltX ?? 0;
- const tiltY = point.tiltY ?? 0;
+ 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 tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180) * (mixingOptions?.tiltScale ?? 1.0);
let dotW = w;
- let dotAngle = 0;
- if (tiltMagnitude > 0.01) {
+ let dotAngle = angleRad;
+ if (useTilt && tiltMagnitude > 0.01) {
const tiltAzimuth = Math.atan2(tiltY, tiltX);
dotW = w * (1.0 + tiltMagnitude * 1.8);
if (tiltMagnitude > 0.05) {
dotAngle = tiltAzimuth;
}
}
- if (point.twist) {
+ if (point.twist && (useTilt || mixingOptions?.angleDynamics === 'twist')) {
dotAngle += (point.twist * Math.PI) / 180;
}
- const master = getRadialDabMaster(hardness, dabColor, isEraser && !isBgEraser);
+ const grainAmount = mixingOptions?.grain ?? 0;
+ if (grainAmount > 0.005) {
+ const scale = Math.max(0.1, mixingOptions?.paperTextureScale ?? 1.0);
+ const gNorm = getPaperGrain(point.x / scale, point.y / scale) / 255.0;
+ dabFlow = applyCspPaperTextureAlpha(
+ dabFlow,
+ gNorm,
+ grainAmount,
+ point.pressure ?? 0.5,
+ mixingOptions?.paperTextureMode ?? 'subtract',
+ mixingOptions?.paperTextureBrightness ?? 0,
+ mixingOptions?.paperTextureContrast ?? 0,
+ Boolean(mixingOptions?.paperTextureInverted)
+ );
+ }
+
+ const master = getRadialDabMaster(hardness, dabColor, isEraser && !isBgEraser, dotW, aaMode);
const dynamics = mixingOptions?.dynamics;
const dabCount = Math.max(1, Math.min(10, Math.round(dynamics?.count ?? 1)));
@@ -1452,49 +1783,51 @@ export function drawRadialDot(
for (let k = 0; k < dabCount; k++) {
let curDabW = dotW;
if (sizeJitter > 0) {
- curDabW *= Math.max(0.01, 1.0 - Math.random() * sizeJitter);
+ curDabW *= Math.max(0.01, 1.0 - dabHashFloat(point.x, point.y, k, 1) * sizeJitter);
}
curDabW = Math.max(0.1, curDabW);
- let curDabThickness = 1.0;
+ let curDabThickness = thickness;
if (roundnessJitter > 0) {
- curDabThickness *= Math.max(0.05, 1.0 - Math.random() * roundnessJitter);
+ curDabThickness *= Math.max(0.05, 1.0 - dabHashFloat(point.x, point.y, k, 2) * roundnessJitter);
}
let curDabRot = dotAngle;
if (angleJitter > 0) {
- curDabRot += (Math.random() - 0.5) * Math.PI * 2 * angleJitter;
+ curDabRot += (dabHashFloat(point.x, point.y, k, 3) - 0.5) * Math.PI * 2 * angleJitter;
}
let curDabX = point.x;
let curDabY = point.y;
if (scatter > 0) {
- const th = Math.random() * Math.PI * 2;
- const sDist = Math.random() * w * scatter;
+ const th = dabHashFloat(point.x, point.y, k, 4) * Math.PI * 2;
+ const sDist = dabHashFloat(point.x, point.y, k, 5) * w * scatter;
curDabX += Math.cos(th) * sDist;
curDabY += Math.sin(th) * sDist;
}
let curDabFlow = dabFlow;
if (flowJitter > 0) {
- curDabFlow *= Math.max(0.005, 1.0 - Math.random() * flowJitter);
+ curDabFlow *= Math.max(0.005, 1.0 - dabHashFloat(point.x, point.y, k, 6) * flowJitter);
}
let curMaster = master;
if (colorJitterEnabled && primRgb && secRgb && dynamics) {
+ let salt = 20;
const cd = applyColorDynamics(
{ r: primRgb.r / 255, g: primRgb.g / 255, b: primRgb.b / 255 },
{ r: secRgb.r / 255, g: secRgb.g / 255, b: secRgb.b / 255 },
- dynamics
+ dynamics,
+ () => dabHashFloat(point.x, point.y, k, salt++)
);
- curMaster = getRadialDabMaster(hardness, cd.hex, isEraser && !isBgEraser);
+ curMaster = getRadialDabMaster(hardness, cd.hex, isEraser && !isBgEraser, curDabW, aaMode);
}
- let finalW = curDabW;
- let finalH = curDabW * curDabThickness;
- if (tiltMagnitude > 0.01) {
- finalW = curDabW * (1.0 + tiltMagnitude * 1.8);
- finalH = (curDabW * curDabThickness) / (1.0 + tiltMagnitude * 0.5);
+ let finalW = isVert ? curDabW * curDabThickness : curDabW;
+ let finalH = isVert ? curDabW : curDabW * curDabThickness;
+ if (useTilt && tiltMagnitude > 0.01) {
+ finalW = w * (1.0 + tiltMagnitude * 1.8);
+ finalH = (w * curDabThickness) / (1.0 + tiltMagnitude * 0.5);
}
drawSingleStamp(
@@ -1509,14 +1842,17 @@ export function drawRadialDot(
isEraser,
isBgEraser,
mixingOptions?.alphaLocked,
- mixingOptions?.isTransparentInk
+ mixingOptions?.isTransparentInk,
+ 1,
+ 1,
+ aaMode,
+ mixingOptions?.blendTipsMode
);
}
}
/**
- * Draws smooth radial dabs along a cubic Bézier curve using arc-length parameterization.
- * Delivers professional Clip Studio Paint / Photoshop quality without line banding or shadowBlur.
+ * Draws smooth analytical radial/elliptical dabs along a cubic Bézier curve using zero-allocation arc-length parameterization.
*/
export function drawRadialCubicBezierSegment(
ctx: CanvasRenderingContext2D,
@@ -1533,33 +1869,31 @@ export function drawRadialCubicBezierSegment(
remainderDist: number = 0,
thickness: number = 1.0,
angleRad: number = 0,
- mixingOptions?: RadialMixingOptions
+ mixingOptions?: RadialMixingOptions,
+ batchGpuDabs?: GpuDab[]
): number {
- const arcTable = buildCubicArcLengthTable(p0, c1, c2, p3);
- const totalCurveLength = arcTable.totalLength;
- if (totalCurveLength < 0.1) {
- return remainderDist;
+ const { totalLength: totalCurveLength, steps: arcSteps } = buildFastArcLengthScratch(p0, c1, c2, p3);
+ if (totalCurveLength < 0.08) {
+ return Math.max(0, remainderDist - totalCurveLength);
}
const isColorMixing = Boolean(mixingOptions?.colorMixing) && !isEraser && !isBgEraser;
const dynamics = mixingOptions?.dynamics;
-
- const gpuEngine = WebGlBrushEngine.getInstance();
- const canUseGpu =
- Boolean(mixingOptions?.useGpu) &&
- gpuEngine.isAvailable() &&
- !mixingOptions?.alphaLocked &&
- !mixingOptions?.isTransparentInk &&
- Boolean(ctx.canvas && ctx.canvas.width > 0 && ctx.canvas.height > 0);
- const gpuDabs: GpuDab[] | null = canUseGpu ? [] : null;
+ const gpuDabs: GpuDab[] | null = batchGpuDabs || null;
+ const aaMode = mixingOptions?.antiAlias ?? 2;
+ const isVert = Boolean(mixingOptions?.thicknessVertical);
+ const useTilt = mixingOptions === undefined ? true : Boolean(mixingOptions.useTilt);
+ const grainAmount = mixingOptions?.grain ?? 0;
if (isColorMixing && mixingOptions && !mixingOptions.reservoir) {
mixingOptions.reservoir = new PaintReservoir(color);
}
const reservoir = mixingOptions?.reservoir;
const sampler = mixingOptions?.sampler;
- const staticMaster = (isColorMixing || gpuDabs) ? null : getRadialDabMaster(hardness, color, isEraser && !isBgEraser);
+ const avgSegWidth = Math.max(0.5, (p0.width + p3.width) * 0.5);
+ const staticMaster = (isColorMixing || gpuDabs) ? null : getRadialDabMaster(hardness, color, isEraser && !isBgEraser, avgSegWidth, aaMode);
const spacingRatio = Math.max(0.015, Math.min(1.0, spacing));
+ const gapAdjustedFlow = computeGapAdjustedAlpha(flow, spacingRatio, mixingOptions?.adjustDensityByGap);
let currentDist = remainderDist > 0 ? remainderDist : 0;
const dabCount = Math.max(1, Math.min(10, Math.round(dynamics?.count ?? 1)));
@@ -1573,32 +1907,77 @@ export function drawRadialCubicBezierSegment(
const baseRgb = (colorJitterEnabled || gpuDabs) ? parseColorToRgb(isBgEraser ? '#ffffff' : color) : null;
const secRgb = colorJitterEnabled ? parseColorToRgb(mixingOptions?.secondaryColor || '#ffffff') : null;
+ let smoothCos = Math.cos(angleRad);
+ let smoothSin = Math.sin(angleRad);
+ let dabStepIdx = 0;
+
while (currentDist <= totalCurveLength) {
- const pt = getCubicPointAtArcLength(p0, c1, c2, p3, currentDist, arcTable);
- const curWidth = Math.max(0.4, pt.width);
- const requiredStep = Math.max(0.4, curWidth * spacingRatio);
+ const pt = sampleFastArcLengthInto(p0, c1, c2, p3, currentDist, totalCurveLength, arcSteps, _sharedSample);
+ let curWidth = Math.max(0.2, pt.width);
+ dabStepIdx++;
- const tiltX = pt.tiltX ?? 0;
- const tiltY = pt.tiltY ?? 0;
+ 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 tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180) * (mixingOptions?.tiltScale ?? 1.0);
+
+ if (mixingOptions?.sizeSensor) {
+ curWidth *= evaluateCspSensor(
+ mixingOptions.sizeSensor,
+ pt.pressure,
+ tiltMagnitude,
+ pt.speed * 0.05,
+ dabHashFloat(pt.x, pt.y, dabStepIdx, 50)
+ );
+ curWidth = Math.max(0.15, curWidth);
+ }
let dabRot = angleRad;
+ const angleMode = mixingOptions?.angleDynamics;
+ if ((angleMode === 'direction' || angleMode === 'direction-random') && pt.speed > 0.05) {
+ const targetA = Math.atan2(pt.dy, pt.dx) + angleRad;
+ smoothCos = smoothCos * 0.6 + Math.cos(targetA) * 0.4;
+ smoothSin = smoothSin * 0.6 + Math.sin(targetA) * 0.4;
+ dabRot = Math.atan2(smoothSin, smoothCos);
+ }
+ if (angleMode === 'random' || angleMode === 'direction-random') {
+ const rScale = angleMode === 'random' ? 1.0 : (mixingOptions?.rotationRandomScale || 0.35);
+ dabRot += (dabHashFloat(pt.x, pt.y, dabStepIdx, 12) - 0.5) * Math.PI * 2 * rScale;
+ }
- if (tiltMagnitude > 0.01) {
- const tiltAzimuth = Math.atan2(tiltY, tiltX);
- if (tiltMagnitude > 0.05) {
- dabRot = tiltAzimuth;
- }
+ if (useTilt && tiltMagnitude > 0.05) {
+ dabRot = Math.atan2(tiltY, tiltX);
}
- if (pt.twist) {
+ if (pt.twist && (useTilt || angleMode === 'twist')) {
dabRot += (pt.twist * Math.PI) / 180;
}
let dabMaster = staticMaster;
- let dabFlow = flow;
+ let dabFlow = gapAdjustedFlow;
let dabRgb = baseRgb;
+ if (mixingOptions?.opacitySensor) {
+ dabFlow *= evaluateCspSensor(
+ mixingOptions.opacitySensor,
+ pt.pressure,
+ tiltMagnitude,
+ pt.speed * 0.05,
+ dabHashFloat(pt.x, pt.y, dabStepIdx, 51)
+ );
+ }
+ if (mixingOptions?.densitySensor) {
+ dabFlow *= evaluateCspSensor(
+ mixingOptions.densitySensor,
+ pt.pressure,
+ tiltMagnitude,
+ pt.speed * 0.05,
+ dabHashFloat(pt.x, pt.y, dabStepIdx, 52)
+ );
+ }
+
+ // Preliminary step estimate for color mixing distance integration
+ const prelimStep = Math.max(0.15, curWidth * spacingRatio);
+
if (isColorMixing && reservoir) {
let sampled = { r: 255, g: 255, b: 255, a: 0 };
if (sampler) {
@@ -1618,12 +1997,13 @@ export function drawRadialCubicBezierSegment(
mixingOptions?.colorStretch ?? 0.75,
mixingOptions?.mixingMode ?? 'blend',
pt.pressure ?? 1.0,
- flow,
- requiredStep
+ dabFlow,
+ prelimStep,
+ mixingOptions?.perceptualMixing !== false
);
if (!gpuDabs) {
- dabMaster = getRadialDabMaster(hardness, mixed.colorHex, false);
+ dabMaster = getRadialDabMaster(hardness, mixed.colorHex, false, curWidth, aaMode);
} else {
dabRgb = { r: mixed.r, g: mixed.g, b: mixed.b };
}
@@ -1642,48 +2022,61 @@ export function drawRadialCubicBezierSegment(
}
}
- const speed = Math.hypot(pt.dx, pt.dy);
- let tx = 0;
+ if (!gpuDabs && grainAmount > 0.005) {
+ const scale = Math.max(0.1, mixingOptions?.paperTextureScale ?? 1.0);
+ const gNorm = getPaperGrain(pt.x / scale, pt.y / scale) / 255.0;
+ dabFlow = applyCspPaperTextureAlpha(
+ dabFlow,
+ gNorm,
+ grainAmount,
+ pt.pressure ?? 0.5,
+ mixingOptions?.paperTextureMode ?? 'subtract',
+ mixingOptions?.paperTextureBrightness ?? 0,
+ mixingOptions?.paperTextureContrast ?? 0,
+ Boolean(mixingOptions?.paperTextureInverted)
+ );
+ }
+
+ let tx = 1;
let ty = 0;
let nx = 0;
- let ny = 0;
- if (speed > 0.001) {
- tx = pt.dx / speed;
- ty = pt.dy / speed;
+ let ny = 1;
+ if (pt.speed > 0.001) {
+ tx = pt.dx / pt.speed;
+ ty = pt.dy / pt.speed;
nx = -ty;
ny = tx;
- } else {
- nx = 0;
- ny = 1;
- tx = 1;
- ty = 0;
}
+ let stepRefW = isVert ? curWidth * thickness : curWidth;
+ let stepRefH = isVert ? curWidth : curWidth * thickness;
+
for (let k = 0; k < dabCount; k++) {
+ const seedIdx = dabStepIdx * 16 + k;
let curDabW = curWidth;
if (sizeJitter > 0) {
- curDabW *= Math.max(0.01, 1.0 - Math.random() * sizeJitter);
+ curDabW *= Math.max(0.01, 1.0 - dabHashFloat(pt.x, pt.y, seedIdx, 1) * sizeJitter);
}
curDabW = Math.max(0.1, curDabW);
let curDabThickness = thickness;
if (roundnessJitter > 0) {
- curDabThickness *= Math.max(0.05, 1.0 - Math.random() * roundnessJitter);
+ curDabThickness *= Math.max(0.05, 1.0 - dabHashFloat(pt.x, pt.y, seedIdx, 2) * roundnessJitter);
}
let curDabRot = dabRot;
if (angleJitter > 0) {
- curDabRot += (Math.random() - 0.5) * Math.PI * 2 * angleJitter;
+ curDabRot += (dabHashFloat(pt.x, pt.y, seedIdx, 3) - 0.5) * Math.PI * 2 * angleJitter;
}
let curDabX = pt.x;
let curDabY = pt.y;
if (scatter > 0) {
- const perpDist = (Math.random() * 2 - 1) * curWidth * scatter;
+ const perpDist = (dabHashFloat(pt.x, pt.y, seedIdx, 4) * 2 - 1) * curWidth * scatter;
let sOffX = nx * perpDist;
let sOffY = ny * perpDist;
if (scatterBothAxes) {
- const tangDist = (Math.random() * 2 - 1) * curWidth * scatter;
+ const tangDist = (dabHashFloat(pt.x, pt.y, seedIdx, 5) * 2 - 1) * curWidth * scatter;
sOffX += tx * tangDist;
sOffY += ty * tangDist;
}
@@ -1693,7 +2086,7 @@ export function drawRadialCubicBezierSegment(
let curDabFlow = dabFlow;
if (flowJitter > 0) {
- curDabFlow *= Math.max(0.005, 1.0 - Math.random() * flowJitter);
+ curDabFlow *= Math.max(0.005, 1.0 - dabHashFloat(pt.x, pt.y, seedIdx, 6) * flowJitter);
}
let curMaster = dabMaster;
@@ -1702,25 +2095,31 @@ export function drawRadialCubicBezierSegment(
let bNorm = dabRgb ? dabRgb.b / 255 : 0;
if (colorJitterEnabled && dabRgb && secRgb && dynamics) {
+ let salt = 20;
const cd = applyColorDynamics(
{ r: dabRgb.r / 255, g: dabRgb.g / 255, b: dabRgb.b / 255 },
{ r: secRgb.r / 255, g: secRgb.g / 255, b: secRgb.b / 255 },
- dynamics
+ dynamics,
+ () => dabHashFloat(pt.x, pt.y, seedIdx, salt++)
);
rNorm = cd.r;
gNorm = cd.g;
bNorm = cd.b;
if (!gpuDabs) {
- curMaster = getRadialDabMaster(hardness, cd.hex, isEraser && !isBgEraser);
+ curMaster = getRadialDabMaster(hardness, cd.hex, isEraser && !isBgEraser, curDabW, aaMode);
}
}
- let finalW = curDabW;
- let finalH = curDabW * curDabThickness;
- if (tiltMagnitude > 0.01) {
+ let finalW = isVert ? curDabW * curDabThickness : curDabW;
+ let finalH = isVert ? curDabW : curDabW * curDabThickness;
+ if (useTilt && tiltMagnitude > 0.01) {
finalW = curDabW * (1.0 + tiltMagnitude * 1.8);
finalH = (curDabW * curDabThickness) / (1.0 + tiltMagnitude * 0.5);
}
+ stepRefW = finalW;
+ stepRefH = finalH;
+
+ const flips = resolveTipFlipSigns(mixingOptions?.flipH, mixingOptions?.flipV, seedIdx, curDabX, curDabY);
if (gpuDabs) {
gpuDabs.push({
@@ -1735,6 +2134,8 @@ export function drawRadialCubicBezierSegment(
alpha: curDabFlow,
pressure: pt.pressure ?? 1.0,
strokeDist: currentDist,
+ flipX: flips.signX,
+ flipY: flips.signY,
});
} else if (curMaster) {
drawSingleStamp(
@@ -1749,42 +2150,33 @@ export function drawRadialCubicBezierSegment(
isEraser,
isBgEraser,
mixingOptions?.alphaLocked,
- mixingOptions?.isTransparentInk
+ mixingOptions?.isTransparentInk,
+ flips.signX,
+ flips.signY,
+ aaMode,
+ mixingOptions?.blendTipsMode
);
}
}
- currentDist += requiredStep;
- }
-
- if (gpuDabs && gpuDabs.length > 0) {
- gpuEngine.renderDabsToContext(
- ctx,
- gpuDabs,
- {
- size: p0.width || 10,
- opacity: 1.0,
- flow,
- hardness,
- wetEdge: 0,
- dualBrush: mixingOptions?.dualBrush,
- dualTipImage: mixingOptions?.dualTipImage,
- dualBrushCompositeMode: mixingOptions?.dualBrushCompositeMode,
- colorMixing: false,
- perceptualMixing: mixingOptions?.perceptualMixing,
- } as any,
- isEraser ? 'eraser' : 'brush',
- ctx.canvas.width,
- ctx.canvas.height
+ // Sub-pixel hairline-safe & ellipse-aware directional step (zero 0.4px beading floor!)
+ const requiredStep = computeEllipticalStepDistance(
+ stepRefW,
+ stepRefH,
+ dabRot,
+ pt.dx,
+ pt.dy,
+ spacingRatio,
+ 0.12
);
+ currentDist += requiredStep;
}
- const nextRemainder = currentDist - totalCurveLength;
- return Math.max(0, nextRemainder);
+ return Math.max(0, currentDist - totalCurveLength);
}
/**
- * Renders an entire completed radial dab stroke onto the target context.
+ * Renders an entire completed radial/elliptical dab stroke onto the target context.
*/
export function renderCompleteRadialStroke(
ctx: CanvasRenderingContext2D,
@@ -1810,35 +2202,75 @@ export function renderCompleteRadialStroke(
}
}
- drawRadialDot(ctx, points[0], color, hardness, flow, isEraser, isBgEraser, mixingOptions);
+ drawRadialDot(ctx, points[0], color, hardness, flow, isEraser, isBgEraser, mixingOptions, thickness, angleRad);
if (points.length === 1) return;
- let accDist = Math.max(0.4, points[0].width * spacing);
+ const gpuEngine = WebGlBrushEngine.getInstance();
+ const canUseGpu =
+ Boolean(mixingOptions?.useGpu) &&
+ gpuEngine.isAvailable() &&
+ Boolean(ctx.canvas && ctx.canvas.width > 0 && ctx.canvas.height > 0);
+ const batchGpuDabs: GpuDab[] | undefined = canUseGpu ? [] : undefined;
+
+ const firstWidth = Math.max(0.2, points[0].width);
+ let accDist = Math.max(0.12, firstWidth * spacing);
if (points.length === 2) {
const p0 = points[0];
const p1 = points[1];
const { c1, c2 } = centripetalCatmullRomToBezier(p0, p0, p1, p1);
- drawRadialCubicBezierSegment(ctx, p0, c1, c2, p1, color, hardness, flow, spacing, isEraser, isBgEraser, accDist, thickness, angleRad, mixingOptions);
- return;
- }
+ drawRadialCubicBezierSegment(ctx, p0, c1, c2, p1, color, hardness, flow, spacing, isEraser, isBgEraser, accDist, thickness, angleRad, mixingOptions, batchGpuDabs);
+ } else {
+ const p0 = points[0];
+ const p1 = points[1];
+ const p2 = points[2];
+ const first = centripetalCatmullRomToBezier(p0, p0, p1, p2);
+ accDist = drawRadialCubicBezierSegment(ctx, p0, first.c1, first.c2, p1, color, hardness, flow, spacing, isEraser, isBgEraser, accDist, thickness, angleRad, mixingOptions, batchGpuDabs);
- const p0 = points[0];
- const p1 = points[1];
- const p2 = points[2];
- const first = centripetalCatmullRomToBezier(p0, p0, p1, p2);
- accDist = drawRadialCubicBezierSegment(ctx, p0, first.c1, first.c2, p1, color, hardness, flow, spacing, isEraser, isBgEraser, accDist, thickness, angleRad, mixingOptions);
+ for (let i = 2; i < points.length - 1; i++) {
+ const seg = centripetalCatmullRomToBezier(points[i - 2], points[i - 1], points[i], points[i + 1]);
+ accDist = drawRadialCubicBezierSegment(ctx, points[i - 1], seg.c1, seg.c2, points[i], color, hardness, flow, spacing, isEraser, isBgEraser, accDist, thickness, angleRad, mixingOptions, batchGpuDabs);
+ }
- for (let i = 2; i < points.length - 1; i++) {
- const seg = centripetalCatmullRomToBezier(points[i - 2], points[i - 1], points[i], points[i + 1]);
- accDist = drawRadialCubicBezierSegment(ctx, points[i - 1], seg.c1, seg.c2, points[i], color, hardness, flow, spacing, isEraser, isBgEraser, accDist, thickness, angleRad, mixingOptions);
+ const n = points.length;
+ const pPrev2 = points[n - 3];
+ const pPrev = points[n - 2];
+ const pLast = points[n - 1];
+ const last = centripetalCatmullRomToBezier(pPrev2, pPrev, pLast, pLast);
+ drawRadialCubicBezierSegment(ctx, pPrev, last.c1, last.c2, pLast, color, hardness, flow, spacing, isEraser, isBgEraser, accDist, thickness, angleRad, mixingOptions, batchGpuDabs);
}
- const n = points.length;
- const pPrev2 = points[n - 3];
- const pPrev = points[n - 2];
- const pLast = points[n - 1];
- const last = centripetalCatmullRomToBezier(pPrev2, pPrev, pLast, pLast);
- drawRadialCubicBezierSegment(ctx, pPrev, last.c1, last.c2, pLast, color, hardness, flow, spacing, isEraser, isBgEraser, accDist, thickness, angleRad, mixingOptions);
+ if (batchGpuDabs && batchGpuDabs.length > 0) {
+ gpuEngine.renderDabsToContext(
+ ctx,
+ batchGpuDabs,
+ {
+ size: points[0].width || 10,
+ opacity: 1.0,
+ flow,
+ blendTipsMode: mixingOptions?.blendTipsMode,
+ hardness,
+ antiAlias: mixingOptions?.antiAlias ?? 2,
+ wetEdge: 0,
+ grain: mixingOptions?.grain,
+ paperTextureMode: mixingOptions?.paperTextureMode,
+ paperTextureBrightness: mixingOptions?.paperTextureBrightness,
+ paperTextureContrast: mixingOptions?.paperTextureContrast,
+ paperTextureInverted: mixingOptions?.paperTextureInverted,
+ paperTextureImage: mixingOptions?.paperTextureImage,
+ paperTextureScale: mixingOptions?.paperTextureScale,
+ paperTextureRotate: mixingOptions?.paperTextureRotate,
+ dualBrush: mixingOptions?.dualBrush,
+ dualTipImage: mixingOptions?.dualTipImage,
+ dualBrushCompositeMode: mixingOptions?.dualBrushCompositeMode,
+ colorMixing: false,
+ perceptualMixing: mixingOptions?.perceptualMixing,
+ alphaLocked: mixingOptions?.alphaLocked,
+ isTransparentInk: mixingOptions?.isTransparentInk,
+ } as any,
+ isEraser ? 'eraser' : 'brush',
+ ctx.canvas.width,
+ ctx.canvas.height
+ );
+ }
}
-
diff --git a/src/utils/sutParser.ts b/src/utils/sutParser.ts
index 151a5fe..9a6cffa 100644
--- a/src/utils/sutParser.ts
+++ b/src/utils/sutParser.ts
@@ -1,6 +1,20 @@
import initSqlJs from 'sql.js';
-import { inflateSync } from 'fflate';
-import { CspBrush, CspSubTip, CspSpraySettings, CspTaperSettings } from '../types/editor';
+import { unzlibSync, inflateSync } from 'fflate';
+import {
+ CspAngleDynamicsMode,
+ CspBlendTipsMode,
+ CspBrush,
+ CspPaperTextureMode,
+ CspSensorConfig,
+ CspSpraySettings,
+ CspSubTip,
+ CspTaperSettings,
+ CspTipFlipMode,
+} from '../types/editor';
+import { evaluateFastSpline } from '../engine/CspBrushEngine';
+
+const MAX_DECOMPRESSED_BLOB_BYTES = 64 * 1024 * 1024;
+const MAX_COMPRESSED_BLOB_BYTES = 16 * 1024 * 1024;
let sqlJsPromise: Promise<any> | null = null;
@@ -8,6 +22,9 @@ async function getSql() {
if (!sqlJsPromise) {
sqlJsPromise = initSqlJs({
locateFile: () => '/sql-wasm.wasm',
+ }).catch((err) => {
+ sqlJsPromise = null;
+ throw err;
});
}
return await sqlJsPromise;
@@ -40,7 +57,7 @@ function indexOfSequence(haystack: Uint8Array, needle: number[], startOffset: nu
export function extractSqliteFromBuffer(buffer: Uint8Array): Uint8Array | null {
const sqliteSig = [
0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00,
- ]; // 'SQLite format 3\0'
+ ];
// 1. Direct SQLite 3 file
if (buffer.length >= 16) {
@@ -56,20 +73,20 @@ export function extractSqliteFromBuffer(buffer: Uint8Array): Uint8Array | null {
// 2. CSFCHUNK container (Clip Studio Format Chunk)
if (buffer.length >= 24) {
- const magic = new TextDecoder('ascii').decode(buffer.slice(0, 8));
+ const magic = new TextDecoder('ascii').decode(buffer.subarray(0, 8));
if (magic === 'CSFCHUNK') {
let offset = 24;
const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
while (offset + 16 <= buffer.length) {
- const chunkTag = new TextDecoder('ascii').decode(buffer.slice(offset, offset + 4));
+ const chunkTag = new TextDecoder('ascii').decode(buffer.subarray(offset, offset + 4));
if (chunkTag !== 'CHNK') break;
- const chunkName = new TextDecoder('ascii').decode(buffer.slice(offset + 4, offset + 8));
- const chunkSize = view.getUint32(offset + 12, false); // big-endian
+ const chunkName = new TextDecoder('ascii').decode(buffer.subarray(offset + 4, offset + 8));
+ const chunkSize = view.getUint32(offset + 12, false);
const dataStart = offset + 16;
const dataEnd = dataStart + chunkSize;
- if (dataEnd > buffer.length) break;
+ if (dataEnd > buffer.length || chunkSize > buffer.length) break;
if (chunkName === 'SQLi') {
const sqliData = buffer.slice(dataStart, dataEnd);
@@ -91,6 +108,31 @@ export function extractSqliteFromBuffer(buffer: Uint8Array): Uint8Array | null {
return null;
}
+/**
+ * Walks PNG chunk headers starting after the 8-byte PNG signature to find the exact byte end
+ * (avoiding false-positive 'IEND' byte sequences inside compressed IDAT payloads).
+ */
+function findExactPngEnd(buf: Uint8Array, startIdx: number): number {
+ const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
+ let offset = startIdx + 8;
+ while (offset + 12 <= buf.length) {
+ const chunkLen = view.getUint32(offset, false);
+ if (chunkLen > 0x7fffffff || offset + 12 + chunkLen > buf.length) {
+ return -1;
+ }
+ const c0 = buf[offset + 4];
+ const c1 = buf[offset + 5];
+ const c2 = buf[offset + 6];
+ const c3 = buf[offset + 7];
+ offset += 12 + chunkLen;
+ // 'IEND' = 0x49 0x45 0x4e 0x44
+ if (c0 === 0x49 && c1 === 0x45 && c2 === 0x4e && c3 === 0x44) {
+ return offset;
+ }
+ }
+ return -1;
+}
+
/**
* Extracts PNG byte arrays from binary BLOB (handling raw PNG, tar archives, or zlib compression).
*/
@@ -99,41 +141,45 @@ export function extractPngImagesFromBlob(data: Uint8Array): Uint8Array[] {
if (!data || data.length < 16) return pngs;
const pngMagic = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
- const iendTag = [0x49, 0x45, 0x4e, 0x44]; // 'IEND'
const tryScan = (buf: Uint8Array) => {
let pos = 0;
- while (pos < buf.length - 8) {
+ while (pos < buf.length - 16) {
const startIdx = indexOfSequence(buf, pngMagic, pos);
if (startIdx === -1) break;
- const iendIdx = indexOfSequence(buf, iendTag, startIdx + 8);
- if (iendIdx === -1) {
- pos = startIdx + 8;
- continue;
- }
-
- // IEND is: 4 bytes length + 4 bytes 'IEND' + 4 bytes CRC = +8 past iendIdx
- const endIdx = iendIdx + 8;
- if (endIdx <= buf.length) {
- pngs.push(buf.slice(startIdx, endIdx));
- pos = endIdx;
+ const exactEnd = findExactPngEnd(buf, startIdx);
+ if (exactEnd > startIdx) {
+ pngs.push(buf.slice(startIdx, exactEnd));
+ pos = exactEnd;
} else {
pos = startIdx + 8;
}
}
};
- // Direct scan
tryScan(data);
- // If none found and looks like zlib compressed (first byte 0x78), try decompressing
- if (pngs.length === 0 && data.length > 2 && data[0] === 0x78) {
+ if (
+ pngs.length === 0 &&
+ data.length > 2 &&
+ data.length <= MAX_COMPRESSED_BLOB_BYTES &&
+ data[0] === 0x78
+ ) {
try {
- const decompressed = inflateSync(data);
- tryScan(decompressed);
+ const decompressed = unzlibSync(data);
+ if (decompressed.byteLength <= MAX_DECOMPRESSED_BLOB_BYTES) {
+ tryScan(decompressed);
+ }
} catch {
- // Ignore decompression error
+ try {
+ const decompressed = inflateSync(data.subarray(2));
+ if (decompressed.byteLength <= MAX_DECOMPRESSED_BLOB_BYTES) {
+ tryScan(decompressed);
+ }
+ } catch {
+ // Ignore decompression error
+ }
}
}
@@ -201,9 +247,6 @@ export function isPng(buf: Uint8Array): boolean {
/**
* Extracts the primary raster image from a Clip Studio Paint MaterialFile BLOB.
- * MaterialFile.FileData is an uncompressed USTAR archive.
- * The authentic brush tip or paper texture is stored in 'thumbnail/thumbnail.png'.
- * (data/material_0.layer is a C2F file containing empty 0-alpha layer canvas tiles).
*/
export function extractMaterialPng(fileData: Uint8Array): Uint8Array | null {
if (!fileData || fileData.length < 16) return null;
@@ -211,12 +254,10 @@ export function extractMaterialPng(fileData: Uint8Array): Uint8Array | null {
try {
const tarEntries = extractTarEntries(fileData);
if (tarEntries.length > 0) {
- // 1. Prioritize thumbnail/thumbnail.png (authentic rendered tip or paper texture)
const thumb = tarEntries.find((e) => e.name.toLowerCase().endsWith('thumbnail.png'));
if (thumb && isPng(thumb.data)) {
return thumb.data;
}
- // 2. Any other valid PNG in the archive
const anyPng = tarEntries.find((e) => e.name.toLowerCase().endsWith('.png') && isPng(e.data));
if (anyPng) {
return anyPng.data;
@@ -226,7 +267,6 @@ export function extractMaterialPng(fileData: Uint8Array): Uint8Array | null {
// Fall back to direct scan
}
- // 3. Fallback: direct scan for PNG chunks (sort descending by size to ignore 4KB 0-alpha layer dummies)
const pngs = extractPngImagesFromBlob(fileData);
if (pngs.length > 0) {
pngs.sort((a, b) => b.length - a.length);
@@ -237,21 +277,18 @@ export function extractMaterialPng(fileData: Uint8Array): Uint8Array | null {
}
/**
- * Converts a Uint8Array of image bytes to a Base64 data URL.
+ * Converts a Uint8Array of image bytes to a Base64 data URL in 8KB chunks (O(N) zero quadratic alloc).
*/
export function bytesToDataUrl(bytes: Uint8Array, mime: string = 'image/png'): string {
- let binary = '';
- const len = bytes.byteLength;
- for (let i = 0; i < len; i++) {
- binary += String.fromCharCode(bytes[i]);
+ const CHUNK_SIZE = 8192;
+ const parts: string[] = [];
+ for (let i = 0; i < bytes.byteLength; i += CHUNK_SIZE) {
+ const slice = bytes.subarray(i, Math.min(bytes.byteLength, i + CHUNK_SIZE));
+ parts.push(String.fromCharCode.apply(null, slice as unknown as number[]));
}
- return `data:${mime};base64,${btoa(binary)}`;
+ return `data:${mime};base64,${btoa(parts.join(''))}`;
}
-/**
- * Decodes strings from a binary buffer (handles UTF-16LE, UTF-16BE, and ASCII).
- * Extracts Clip Studio Paint catalog identifiers: e.g. ".:36:98:acedf7c35d-144c-1ab1-39df-ec7fb2dbe4"
- */
function extractCatalogIdsFromBlob(blob: Uint8Array | null | undefined): string[] {
if (!blob || blob.length === 0) return [];
const results: string[] = [];
@@ -264,7 +301,6 @@ function extractCatalogIdsFromBlob(blob: Uint8Array | null | undefined): string[
results.push(match[0]);
}
}
- // Also UUIDs directly
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])) {
@@ -274,41 +310,33 @@ function extractCatalogIdsFromBlob(blob: Uint8Array | null | undefined): string[
};
try {
- const le = new TextDecoder('utf-16le', { fatal: false }).decode(blob);
- addMatches(le);
+ addMatches(new TextDecoder('utf-16le', { fatal: false }).decode(blob));
} catch {
- // Ignore decoding errors
+ // Ignore
}
-
try {
- const be = new TextDecoder('utf-16be', { fatal: false }).decode(blob);
- addMatches(be);
+ addMatches(new TextDecoder('utf-16be', { fatal: false }).decode(blob));
} catch {
- // Ignore decoding errors
+ // Ignore
}
-
try {
- const latin = new TextDecoder('latin1', { fatal: false }).decode(blob);
- addMatches(latin);
+ addMatches(new TextDecoder('latin1', { fatal: false }).decode(blob));
} catch {
- // Ignore decoding errors
+ // Ignore
}
return results;
}
-/**
- * Decodes Clip Studio Paint *Effector binary blobs.
- * Contains stylus pressure, tilt, and velocity dynamics curves.
- */
export interface DecodedEffector {
usePressure: boolean;
useTilt: boolean;
useVelocity: boolean;
useRandom: boolean;
- minValue: number; // 0.0 to 1.0
- maxValue: number; // 0.0 to 1.0
+ minValue: number;
+ maxValue: number;
pressureCurve?: [number, number][];
+ tiltCurve?: [number, number][];
velocityCurve?: [number, number][];
}
@@ -316,7 +344,7 @@ export function parseCspEffector(blob: Uint8Array | null | undefined): DecodedEf
if (!blob || blob.length < 44) return null;
const view = new DataView(blob.buffer, blob.byteOffset, blob.byteLength);
- const sourceFlags = view.getUint32(8, false); // big-endian
+ const sourceFlags = view.getUint32(8, false);
const usePressure = Boolean(sourceFlags & 0x10);
const useTilt = Boolean(sourceFlags & 0x20);
const useVelocity = Boolean(sourceFlags & 0x80);
@@ -335,7 +363,7 @@ export function parseCspEffector(blob: Uint8Array | null | undefined): DecodedEf
const numPts = view.getUint32(offset + 4, false);
const ptSize = view.getUint32(offset + 8, false);
- if (magic !== 12 || ptSize !== 16 || offset + 12 + numPts * 16 > blob.length) {
+ if (magic !== 12 || ptSize !== 16 || numPts > 256 || offset + 12 + numPts * 16 > blob.length) {
break;
}
@@ -352,18 +380,19 @@ export function parseCspEffector(blob: Uint8Array | null | undefined): DecodedEf
}
}
+ let curveIdx = 0;
let pressureCurve: [number, number][] | undefined = undefined;
+ let tiltCurve: [number, number][] | undefined = undefined;
let velocityCurve: [number, number][] | undefined = undefined;
- if (curves.length > 0) {
- if (usePressure) {
- pressureCurve = curves[0];
- if (useVelocity && curves.length > 1) {
- velocityCurve = curves[1];
- }
- } else if (useVelocity) {
- velocityCurve = curves[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 {
@@ -374,67 +403,35 @@ export function parseCspEffector(blob: Uint8Array | null | undefined): DecodedEf
minValue,
maxValue,
pressureCurve,
+ tiltCurve,
velocityCurve,
};
}
+function effectorToSensorConfig(eff: DecodedEffector): CspSensorConfig {
+ return {
+ usePressure: eff.usePressure,
+ pressureMin: eff.minValue,
+ pressureCurve: eff.pressureCurve,
+ useTilt: eff.useTilt,
+ tiltMin: eff.minValue,
+ useVelocity: eff.useVelocity,
+ velocityMin: eff.minValue,
+ useRandom: eff.useRandom,
+ randomMin: eff.minValue,
+ };
+}
+
/**
- * Evaluates a value through a Clip Studio Paint cubic Hermite spline curve (PCHIP).
- * Monotonic without overshoot, guaranteeing 100% authentic pen response.
+ * Evaluates a value through a Clip Studio Paint cubic Hermite spline curve (PCHIP)
+ * using the O(1) precompiled Float32Array(256) LUT in CspBrushEngine.
*/
export function evaluateCspSpline(x: number, pts?: [number, number][]): number {
- if (!pts || pts.length === 0) return x;
- if (pts.length === 1) return pts[0][1];
- if (x <= pts[0][0]) return pts[0][1];
- if (x >= pts[pts.length - 1][0]) return pts[pts.length - 1][1];
-
- const n = pts.length;
- // Calculate secant slopes
- const deltas: number[] = new Array(n - 1);
- for (let k = 0; k < n - 1; k++) {
- const dx = pts[k + 1][0] - pts[k][0];
- deltas[k] = dx === 0 ? 0 : (pts[k + 1][1] - pts[k][1]) / dx;
- }
-
- // Calculate tangents
- const m: number[] = new Array(n).fill(0);
- m[0] = deltas[0];
- m[n - 1] = deltas[n - 2];
- for (let k = 1; k < n - 1; k++) {
- if (deltas[k - 1] * deltas[k] <= 0) {
- m[k] = 0;
- } else {
- const dxPrev = pts[k][0] - pts[k - 1][0];
- const dxNext = pts[k + 1][0] - pts[k][0];
- m[k] =
- (3 * (dxPrev + dxNext)) /
- ((2 * dxNext + dxPrev) / deltas[k - 1] + (dxNext + 2 * dxPrev) / deltas[k]);
- }
- }
-
- // Interpolate segment
- for (let k = 0; k < n - 1; k++) {
- if (pts[k][0] <= x && x <= pts[k + 1][0]) {
- const h = pts[k + 1][0] - pts[k][0];
- if (h === 0) return pts[k][1];
- const t = (x - pts[k][0]) / h;
- const t2 = t * t;
- const t3 = t2 * t;
- const h00 = 2 * t3 - 3 * t2 + 1;
- const h10 = t3 - 2 * t2 + t;
- const h01 = -2 * t3 + 3 * t2;
- const h11 = t3 - t2;
- return h00 * pts[k][1] + h10 * h * m[k] + h01 * pts[k + 1][1] + h11 * h * m[k + 1];
- }
- }
-
- return pts[pts.length - 1][1];
+ return evaluateFastSpline(x, pts);
}
/**
- * Normalizes brush tip alpha and transparency:
- * If the image is opaque (black ink on white canvas), it converts luminance to alpha.
- * Detects chromatic multi-colored stamps and preserves color channels.
+ * Normalizes brush tip alpha and transparency.
*/
export async function processBrushTipImage(
dataUrl: string,
@@ -474,7 +471,6 @@ export async function processBrushTipImage(
const imgData = ctx.getImageData(0, 0, w, h);
const data = imgData.data;
- // Check transparency, chromatic color variance, and max alpha
let hasAlpha = false;
let hasColor = false;
let maxAlpha = 0;
@@ -497,7 +493,6 @@ export async function processBrushTipImage(
}
}
- // If the image is completely empty / 0-alpha (dummy layer tile or corrupt blob)
if (maxAlpha === 0 || nonZeroCount === 0) {
const proc = generateProceduralTip(
fallbackProcedural?.hardness ?? 1.0,
@@ -508,14 +503,9 @@ export async function processBrushTipImage(
return;
}
- // If opaque (white background with dark markings), map luminance to alpha
if (!hasAlpha) {
for (let i = 0; i < data.length; i += 4) {
- const r = data[i];
- const g = data[i + 1];
- const b = data[i + 2];
- // Invert: 255 (white) => 0 alpha, 0 (black) => 255 alpha
- const lum = 0.299 * r + 0.587 * g + 0.114 * b;
+ 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)));
data[i] = 255;
data[i + 1] = 255;
@@ -525,7 +515,6 @@ export async function processBrushTipImage(
ctx.putImageData(imgData, 0, 0);
resolve({ dataUrl: canvas.toDataURL('image/png'), width: w, height: h, isColor: false });
} else if (!hasColor) {
- // Ensure monochrome color channels are white so tinting via 'source-in' & shaders works accurately
for (let i = 0; i < data.length; i += 4) {
data[i] = 255;
data[i + 1] = 255;
@@ -534,7 +523,6 @@ export async function processBrushTipImage(
ctx.putImageData(imgData, 0, 0);
resolve({ dataUrl: canvas.toDataURL('image/png'), width: w, height: h, isColor: false });
} else {
- // Multi-color pattern brush: retain original colors and alpha
resolve({ dataUrl, width: w, height: h, isColor: true });
}
};
@@ -557,13 +545,12 @@ export async function processBrushTipImage(
}
/**
- * Generates an authentic Clip Studio Paint procedural tip (e.g. for Turnip Pen, G-Pen, Textured Pen).
- * Accurately models hardness falloff, elliptical thickness squeeze, and anti-aliasing.
+ * Generates an authentic Clip Studio Paint procedural tip.
*/
export function generateProceduralTip(
- hardness: number = 1.0, // 0.05 to 1.0
- thickness: number = 1.0, // 0.05 to 1.0
- antiAlias: number = 2 // 0: none/binary, 1: low, 2: mid, 3: high
+ hardness: number = 1.0,
+ thickness: number = 1.0,
+ antiAlias: number = 2
): { dataUrl: string; width: number; height: number } {
const size = 128;
const canvas = document.createElement('canvas');
@@ -592,7 +579,6 @@ export function generateProceduralTip(
let alpha = 1.0;
if (dist > hNorm) {
alpha = 1.0 - (dist - hNorm) / (1.0 - hNorm);
- // Hermite smoothstep
alpha = alpha * alpha * (3 - 2 * alpha);
}
if (isBinary) {
@@ -617,9 +603,25 @@ export function generateProceduralTip(
};
}
+function mapFlipMode(val: unknown): CspTipFlipMode {
+ const n = Number(val);
+ if (n === 1 || n === 2) return 'alternate';
+ if (n === 3) return 'random';
+ return 'none';
+}
+
+function mapTextureMode(val: unknown): CspPaperTextureMode {
+ const n = Number(val);
+ if (n === 1) return 'subtract';
+ if (n === 2) return 'multiply';
+ if (n === 3) return 'compare';
+ if (n === 4) return 'overlay';
+ if (n === 5) return 'outline';
+ return 'subtract';
+}
+
/**
* Parses a Clip Studio Paint .sut (Sub Tool) brush file.
- * Returns a fully configured CspBrush object ready for painting and saving.
*/
export async function parseSutFile(
fileBuffer: ArrayBuffer | Uint8Array,
@@ -638,7 +640,6 @@ export async function parseSutFile(
try {
db = new SQL.Database(sqliteData);
- // 1. Get Tables List
const tablesQuery = db.exec("SELECT name FROM sqlite_master WHERE type='table'");
const tables: string[] = [];
if (tablesQuery.length > 0 && tablesQuery[0].values) {
@@ -647,7 +648,6 @@ export async function parseSutFile(
}
}
- // 2. Brush Name & Target Variant ID from Node table
let brushName = fileName.replace(/\.sut$/i, '').trim();
let variantId: number | null = null;
@@ -659,8 +659,8 @@ export async function parseSutFile(
if (row[0] && typeof row[0] === 'string' && row[0].trim().length > 0) {
brushName = row[0].trim();
}
- if (row[1] !== null && row[1] !== undefined) {
- variantId = Number(row[1]);
+ if (row[1] !== null && row[1] !== undefined && Number.isFinite(Number(row[1]))) {
+ variantId = Math.trunc(Number(row[1]));
}
}
} catch {
@@ -668,29 +668,38 @@ export async function parseSutFile(
}
}
- // 3. Variant Parameters from Variant table
let brushSize = 16;
let minSizeFactor = 0.2;
let opacity = 1.0;
let flow = 0.85;
+ let adjustDensityByGap = false;
+ let blendTipsMode: CspBlendTipsMode = 'darken';
let spacing = 0.08;
let hardness = 1.0;
let thickness = 1.0;
let thicknessVertical = false;
+ let flipH: CspTipFlipMode = 'none';
+ let flipV: CspTipFlipMode = 'none';
let angle = 0;
- let angleDynamics: 'none' | 'direction' | 'random' = 'none';
+ let angleDynamics: CspAngleDynamicsMode = 'none';
let rotationRandomScale = 0;
let antiAlias = 2;
let stabilization = 0;
+ let postCorrection = 0;
+ let sharpCorners = true;
let usePressure = true;
let useVelocity = false;
+ let useTilt = false;
let pressureCurve: [number, number][] | undefined = undefined;
let velocityCurve: [number, number][] | undefined = undefined;
+ let sizeSensor: CspSensorConfig | undefined = undefined;
+ let opacitySensor: CspSensorConfig | undefined = undefined;
+ let densitySensor: CspSensorConfig | undefined = undefined;
let colorMixing = false;
let amountOfPaint = 0.7;
let densityOfPaint = 0.8;
let colorStretch = 0.6;
- let mixingMode: 'blend' | 'running_color' = 'blend';
+ let mixingMode: 'blend' | 'running_color' | 'smear' = 'blend';
let wetEdge = 0;
let wetEdgeRadius = 3.0;
let wetEdgeAlphaPower = 20;
@@ -698,6 +707,10 @@ export async function parseSutFile(
let textureDensity = 0;
let paperTextureScale = 1.0;
let paperTextureRotate = 0;
+ let paperTextureMode: CspPaperTextureMode = 'subtract';
+ let paperTextureBrightness = 0;
+ let paperTextureContrast = 0;
+ let paperTextureInverted = false;
let spray: CspSpraySettings | undefined = undefined;
let taper: CspTaperSettings | undefined = undefined;
let isRibbon = false;
@@ -722,12 +735,11 @@ export async function parseSutFile(
colMap.set(c.toLowerCase(), c);
}
- const sql =
+ const varRes =
variantId !== null
- ? `SELECT * FROM Variant WHERE _PW_ID = ${variantId} LIMIT 1`
- : 'SELECT * FROM Variant LIMIT 1';
+ ? db.exec('SELECT * FROM Variant WHERE _PW_ID = ? LIMIT 1', [variantId])
+ : db.exec('SELECT * FROM Variant LIMIT 1');
- const varRes = db.exec(sql);
if (varRes.length > 0 && varRes[0].values && varRes[0].values.length > 0) {
const row = varRes[0].values[0];
const getVal = (aliases: string[]): any => {
@@ -747,76 +759,110 @@ export async function parseSutFile(
const rawSize = getVal(['BrushSize', 'Size', 'PenSize', 'BrushSizeVal', 'LineWidth']);
if (typeof rawSize === 'number' && rawSize > 0) {
if (rawSize > 500) {
- brushSize = Math.max(2, Math.min(300, rawSize / 100));
+ brushSize = Math.max(1, Math.min(500, rawSize / 100));
} else if (rawSize > 250) {
- brushSize = Math.max(2, Math.min(300, rawSize / 10));
+ brushSize = Math.max(1, Math.min(500, rawSize / 10));
} else {
- brushSize = Math.max(1, Math.min(300, rawSize));
+ brushSize = Math.max(0.5, Math.min(500, rawSize));
}
}
- // Size Dynamics Effector (Pressure, Velocity, MinSize, Spline curve)
+ // 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);
}
}
+ // Opacity & Density Effectors
+ const opacityEffBlob = getVal(['OpacityEffector', 'BrushOpacityEffector']);
+ if (opacityEffBlob instanceof Uint8Array) {
+ const eff = parseCspEffector(opacityEffBlob);
+ if (eff) opacitySensor = effectorToSensorConfig(eff);
+ }
+
+ const densityEffBlob = getVal(['BrushDensityEffector', 'BrushFlowEffector', 'DensityEffector']);
+ if (densityEffBlob instanceof Uint8Array) {
+ const eff = parseCspEffector(densityEffBlob);
+ if (eff) densitySensor = effectorToSensorConfig(eff);
+ }
+
// Spacing / Interval
const rawSpacing = getVal(['BrushInterval', 'Interval', 'Spacing', 'BrushSpacing']);
if (typeof rawSpacing === 'number' && rawSpacing > 0) {
- spacing = rawSpacing > 1.0 ? Math.max(0.01, Math.min(1.0, rawSpacing / 100)) : Math.max(0.01, Math.min(1.0, rawSpacing));
+ spacing =
+ rawSpacing > 1.0
+ ? Math.max(0.01, Math.min(1.0, rawSpacing / 100))
+ : Math.max(0.01, Math.min(1.0, rawSpacing));
}
- // Opacity
- const rawOpacity = getVal(['Opacity', 'BrushOpacity', 'BrushDensity', 'Density']);
+ // 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;
}
- // Flow
- const rawFlow = getVal(['BrushFlow', 'Flow', 'PaintAmount', 'InkAmount']);
+ // 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(['BrushAdjustDensityByGap', 'AdjustDensityByGap']);
+ if (rawAdjustGap !== null) {
+ adjustDensityByGap = Boolean(rawAdjustGap);
+ }
+
+ const rawBlendTips = getVal(['BlendBrushTips', 'BrushCombineMode', 'BrushBlendMode']);
+ if (rawBlendTips !== null && Number(rawBlendTips) === 1) {
+ blendTipsMode = 'compare';
+ }
+
// Hardness
const rawHardness = getVal(['BrushHardness', 'Hardness']);
if (typeof rawHardness === 'number' && rawHardness > 0) {
- if (rawHardness <= 5) {
- hardness = Math.max(0.05, Math.min(1.0, rawHardness / 5));
- } else {
- hardness = Math.max(0.05, Math.min(1.0, rawHardness / 100));
- }
+ hardness =
+ rawHardness <= 5
+ ? Math.max(0.05, Math.min(1.0, rawHardness / 5))
+ : Math.max(0.05, Math.min(1.0, rawHardness / 100));
}
- // Thickness (Elliptical squeeze)
+ // 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', 'VerticalThickness']);
+ const rawVertThick = getVal(['BrushVerticalThicknes', 'BrushVerticalThickness', 'VerticalThickness']);
if (rawVertThick !== null) {
thicknessVertical = Boolean(rawVertThick);
}
+ const rawFlipH = getVal(['BrushFlipX', 'FlipHorizontal']);
+ if (rawFlipH !== null) flipH = mapFlipMode(rawFlipH);
+ const rawFlipV = getVal(['BrushFlipY', 'FlipVertical']);
+ if (rawFlipV !== null) flipV = mapFlipMode(rawFlipV);
+
// Rotation & Rotation Dynamics
const rawAngle = getVal(['BrushRotation', 'Rotation', 'BrushAngle', 'Angle']);
if (typeof rawAngle === 'number') {
- angle = (rawAngle % 360 + 360) % 360;
+ angle = ((rawAngle % 360) + 360) % 360;
}
const rawRotEff = getVal(['BrushRotationEffector', 'RotationEffector', 'AngleDynamics']);
if (typeof rawRotEff === 'number') {
- // In CSP: bit 7 (128) or bit 1/2 indicate direction / line direction
if (rawRotEff & 0x80 || rawRotEff === 3 || rawRotEff === 67 || rawRotEff === 131) {
angleDynamics = 'direction';
+ } else if (rawRotEff & 0x20) {
+ angleDynamics = 'tilt';
+ useTilt = true;
}
}
@@ -834,11 +880,19 @@ export async function parseSutFile(
antiAlias = Math.max(0, Math.min(3, Math.round(rawAA)));
}
- // Stabilization
+ // Stabilization & Post-Correction
const rawRev = getVal(['BrushRevision', 'Revision', 'FlickerReduction', 'BrushStabilization']);
if (typeof rawRev === 'number' && rawRev >= 0) {
stabilization = Math.min(50, Math.max(0, Math.round(rawRev)));
}
+ const rawPostCorr = getVal(['BrushPostCorrection', 'PostCorrection']);
+ if (typeof rawPostCorr === 'number' && rawPostCorr >= 0) {
+ postCorrection = Math.min(5, Math.max(0, Math.round(rawPostCorr)));
+ }
+ const rawSharp = getVal(['BrushSharpAngles', 'SharpAngles']);
+ if (rawSharp !== null) {
+ sharpCorners = Boolean(rawSharp);
+ }
// Ribbon Mode
const rawRibbon = getVal(['BrushRibbon', 'Ribbon']);
@@ -847,12 +901,22 @@ export async function parseSutFile(
}
// Color Mixing & Smear
- const rawMixing = getVal(['BrushUseWaterColor', 'BrushUseWaterColor2', 'ColorMixing', 'EnableColorMixing']);
+ const rawMixing = getVal([
+ 'BrushUseWaterColor',
+ 'BrushUseWaterColor2',
+ 'ColorMixing',
+ 'EnableColorMixing',
+ ]);
if (rawMixing !== null) {
colorMixing = Boolean(rawMixing);
}
- const rawMixColor = getVal(['BrushMixColor', 'AmountOfPaint', 'PaintAmount', 'ColorMixAmount']);
+ const rawMixColor = getVal([
+ 'BrushMixColor',
+ 'AmountOfPaint',
+ 'PaintAmount',
+ 'ColorMixAmount',
+ ]);
if (typeof rawMixColor === 'number' && rawMixColor >= 0) {
amountOfPaint = rawMixColor > 1.0 ? Math.min(1.0, rawMixColor / 100) : rawMixColor;
}
@@ -869,10 +933,11 @@ export async function parseSutFile(
const rawMixMode = getVal(['BrushColorMixingMode', 'MixingMode']);
if (rawMixMode !== null) {
- mixingMode = Number(rawMixMode) === 1 ? 'running_color' : 'blend';
+ const m = Number(rawMixMode);
+ mixingMode = m === 2 ? 'smear' : m === 1 ? 'running_color' : 'blend';
}
- // Wet Edge (Water Edge)
+ // Wet Edge
const rawWetEdge = getVal(['BrushUseWaterEdge', 'UseWaterEdge']);
if (rawWetEdge !== null) {
wetEdge = Boolean(rawWetEdge) ? 0.75 : 0;
@@ -894,7 +959,8 @@ export async function parseSutFile(
// 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;
+ textureDensity =
+ rawTexDensity > 1.0 ? Math.min(1.0, rawTexDensity / 100) : rawTexDensity;
}
const rawTexScale = getVal(['TextureScale2', 'TextureScale']);
if (typeof rawTexScale === 'number' && rawTexScale > 0) {
@@ -904,6 +970,22 @@ export async function parseSutFile(
if (typeof rawTexRotate === 'number') {
paperTextureRotate = rawTexRotate;
}
+ const rawTexMode = getVal(['TextureMode', 'BrushTextureMode']);
+ if (rawTexMode !== null) {
+ paperTextureMode = mapTextureMode(rawTexMode);
+ }
+ const rawTexInvert = getVal(['TextureInvert', 'BrushTextureInvert']);
+ if (rawTexInvert !== null) {
+ paperTextureInverted = Boolean(rawTexInvert);
+ }
+ const rawTexBright = getVal(['TextureBrightness']);
+ if (typeof rawTexBright === 'number') {
+ paperTextureBrightness = Math.max(-1, Math.min(1, rawTexBright / 100));
+ }
+ const rawTexContrast = getVal(['TextureContrast']);
+ if (typeof rawTexContrast === 'number') {
+ paperTextureContrast = Math.max(-1, Math.min(1, rawTexContrast / 100));
+ }
// Spray / Airbrush
const rawSpray = getVal(['BrushUseSpray', 'UseSpray']);
@@ -914,8 +996,14 @@ export async function parseSutFile(
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,
+ 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,
};
}
@@ -949,8 +1037,15 @@ export async function parseSutFile(
if (Boolean(rawDual)) {
dualBrush = true;
}
+ const rawDualMode = getVal(['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';
+ }
- // Blobs for image arrays
rawPatternArrayBlob = getVal(['BrushPatternImageArray']);
rawTextureImageBlob = getVal(['TextureImage']);
rawDualPatternBlob = getVal(['DualPatternImageArray']);
@@ -960,7 +1055,7 @@ export async function parseSutFile(
}
}
- // 4. MaterialFile extraction and mapping
+ // 4. MaterialFile extraction
const materialMap = new Map<string, { mainPng: Uint8Array; width: number; height: number }>();
const allMaterialsList: { mainPng: Uint8Array; catalogPath: string; width: number; height: number }[] = [];
@@ -988,8 +1083,9 @@ export async function parseSutFile(
if (catPath) materialMap.set(catPath, entry);
materialMap.set(pwId, entry);
- // Index by UUID
- 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);
+ 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);
}
@@ -1004,7 +1100,7 @@ export async function parseSutFile(
}
}
- // 5. Match Paper Texture from TextureImage
+ // 5. Match Paper Texture
let paperTexture: string | undefined = undefined;
let paperTextureEntry: { mainPng: Uint8Array } | null = null;
@@ -1019,7 +1115,7 @@ export async function parseSutFile(
}
}
- // 6. Match Brush Tip(s) from BrushPatternImageArray
+ // 6. Match Brush Tip(s)
const tipPngEntries: { mainPng: Uint8Array; width: number; height: number }[] = [];
if (rawPatternArrayBlob) {
@@ -1034,7 +1130,6 @@ export async function parseSutFile(
}
}
- // If no pattern array match, but materials exist, assign non-texture materials as tips
if (tipPngEntries.length === 0 && allMaterialsList.length > 0) {
for (const m of allMaterialsList) {
if (m !== paperTextureEntry && !tipPngEntries.some((e) => e.mainPng === m.mainPng)) {
@@ -1043,23 +1138,23 @@ export async function parseSutFile(
}
}
- // 7. Process extracted tips or generate authentic procedural tip
+ // 7. Process extracted tips or generate procedural tip
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, antiAlias };
if (tipPngEntries.length > 0) {
- // Primary Tip
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;
- // All sub-tips
for (const entry of tipPngEntries) {
const u = bytesToDataUrl(entry.mainPng, 'image/png');
const p = await processBrushTipImage(u, fallbackProc);
@@ -1071,14 +1166,12 @@ export async function parseSutFile(
});
}
} else {
- // Authentic CSP Procedural Pen Tip (Turnip pen, G-pen, Textured pen, Calligraphy oval)
const proc = generateProceduralTip(hardness, thickness, antiAlias);
tipDataUrl = proc.dataUrl;
tipWidth = proc.width;
tipHeight = proc.height;
}
- // Secondary Tip for Dual Brush
let secondaryTipDataUrl: string | undefined = undefined;
let secondaryTipWidth: number | undefined = undefined;
let secondaryTipHeight: number | undefined = undefined;
@@ -1108,6 +1201,7 @@ export async function parseSutFile(
tipDataUrl,
tipWidth,
tipHeight,
+ isColorTip,
secondaryTipDataUrl,
secondaryTipWidth,
secondaryTipHeight,
@@ -1116,18 +1210,28 @@ export async function parseSutFile(
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,
@@ -1143,6 +1247,10 @@ export async function parseSutFile(
textureDensity,
paperTextureScale,
paperTextureRotate,
+ paperTextureMode,
+ paperTextureBrightness,
+ paperTextureContrast,
+ paperTextureInverted,
dualBrush,
dualBrushCompositeMode,
spray,
diff --git a/src/utils/tileEngine.ts b/src/utils/tileEngine.ts
index 4d3ffdc..31c503c 100644
--- a/src/utils/tileEngine.ts
+++ b/src/utils/tileEngine.ts
@@ -1,18 +1,21 @@
/**
+ * Large-Canvas Virtual Memory and SSD Scratch Disk Engine
* Sparse Virtual Tile Engine & Color Expression System
*
- * Designed for 600 DPI professional manga production (B4: 4961 x 7016 px, 70MP double spreads)
- * with zero allocation for empty space, multi-format pixel packing (1-bit monochrome,
- * 8-bit grayscale, 32-bit RGBA), SIMD/bitwise rasterizers, and fast RLE compression.
+ * Designed for 600 DPI professional manga production (B4: 7016 x 9921 px, ~70 MP)
+ * and Webtoons (800 x 50,000+ px) with zero allocation for empty space, multi-format pixel packing
+ * (1-bit monochrome at 8KB, 8-bit grayscale at 64KB, 32-bit RGBA at 256KB),
+ * LRU tile memory budgeting with transparent background SSD scratch paging via Rust LZ4,
+ * and an on-demand multi-resolution Mipmap Tile Pyramid (LOD 0 to LOD 3).
*/
import { TileDelta } from '../types/editor';
export const TILE_SIZE = 256;
export const TILE_PIXELS = TILE_SIZE * TILE_SIZE; // 65,536 pixels
-export const BYTES_1BIT = TILE_PIXELS >> 3; // 8,192 bytes
-export const BYTES_8BIT = TILE_PIXELS; // 65,536 bytes
-export const BYTES_32BIT = TILE_PIXELS << 2; // 262,144 bytes
+export const BYTES_1BIT = TILE_PIXELS >> 3; // 8,192 bytes (8 KB)
+export const BYTES_8BIT = TILE_PIXELS; // 65,536 bytes (64 KB)
+export const BYTES_32BIT = TILE_PIXELS << 2; // 262,144 bytes (256 KB)
export type TileFormat = 'monochrome-1bit' | 'grayscale-8bit' | 'color-32bit';
@@ -21,13 +24,23 @@ export interface TileBuffer {
tileX: number;
tileY: number;
format: TileFormat;
- data: Uint8Array;
+ data: Uint8Array | null; // null when paged out to disk
dirty: boolean;
version: number;
+ isPagedToDisk: boolean;
+ lastAccessTimestamp: number;
+ lod: number; // 0 = 1:1 (256x256 doc area), 1 = 1/2 (512x512), 2 = 1/4 (1024x1024), 3 = 1/8 (2048x2048)
+}
+
+export function getTileByteSize(format: TileFormat): number {
+ if (format === 'monochrome-1bit') return BYTES_1BIT;
+ if (format === 'grayscale-8bit') return BYTES_8BIT;
+ return BYTES_32BIT;
}
// System endianness detection for 32-bit operations
export const isLittleEndian = (() => {
+ if (typeof ArrayBuffer === 'undefined') return true;
const buf = new ArrayBuffer(4);
new Uint32Array(buf)[0] = 0x11223344;
return new Uint8Array(buf)[0] === 0x44;
@@ -61,26 +74,38 @@ for (let b = 0; b < 256; b++) {
/**
* Get tile coordinate from document pixel coordinate.
*/
-export function pixelToTileCoord(pixel: number): number {
- return Math.floor(pixel / TILE_SIZE);
+export function pixelToTileCoord(pixel: number, lod: number = 0): number {
+ const tileSizeDoc = TILE_SIZE << lod;
+ return Math.floor(pixel / tileSizeDoc);
}
/**
* Spatial hash map key for tiles.
+ * LOD 0 produces backwards-compatible key: `${layerId}:${tileX}:${tileY}`.
+ * LOD > 0 produces: `${layerId}:${lod}:${tileX}:${tileY}`.
*/
-export function getTileKey(layerId: string, tileX: number, tileY: number): string {
- return `${layerId}:${tileX}:${tileY}`;
+export function getTileKey(layerId: string, tileX: number, tileY: number, lod: number = 0): string {
+ return lod === 0 ? `${layerId}:${tileX}:${tileY}` : `${layerId}:${lod}:${tileX}:${tileY}`;
}
/**
* Parse spatial hash map key into components.
*/
-export function parseTileKey(key: string): { layerId: string; tileX: number; tileY: number } {
+export function parseTileKey(key: string): { layerId: string; tileX: number; tileY: number; lod: number } {
const parts = key.split(':');
+ if (parts.length === 4) {
+ return {
+ layerId: parts[0],
+ lod: parseInt(parts[1], 10),
+ tileX: parseInt(parts[2], 10),
+ tileY: parseInt(parts[3], 10),
+ };
+ }
return {
layerId: parts[0],
tileX: parseInt(parts[1], 10),
tileY: parseInt(parts[2], 10),
+ lod: 0,
};
}
@@ -91,11 +116,10 @@ export function createTileBuffer(
layerId: string,
tileX: number,
tileY: number,
- format: TileFormat
+ format: TileFormat,
+ lod: number = 0
): TileBuffer {
- let size = BYTES_32BIT;
- if (format === 'monochrome-1bit') size = BYTES_1BIT;
- else if (format === 'grayscale-8bit') size = BYTES_8BIT;
+ const size = getTileByteSize(format);
return {
layerId,
@@ -105,6 +129,9 @@ export function createTileBuffer(
data: new Uint8Array(size),
dirty: true,
version: 1,
+ isPagedToDisk: false,
+ lastAccessTimestamp: typeof performance !== 'undefined' ? performance.now() : Date.now(),
+ lod,
};
}
@@ -116,7 +143,7 @@ export function setPixel1Bit(data: Uint8Array, x: number, y: number, value: bool
const byteIndex = pixelIndex >> 3;
const bitOffset = 7 - (pixelIndex & 7);
if (value) {
- data[byteIndex] |= (1 << bitOffset);
+ data[byteIndex] |= 1 << bitOffset;
} else {
data[byteIndex] &= ~(1 << bitOffset);
}
@@ -203,7 +230,7 @@ export function packRGBATo1Bit(
const lum = (r * 299 + g * 587 + b * 114) / 1000;
// Dark pixels become ink (1), light pixels transparent (0)
if (lum < threshold) {
- byteVal |= (1 << bit);
+ byteVal |= 1 << bit;
}
}
srcOffset += 4;
@@ -225,9 +252,6 @@ export function unpack8BitToRGBA(
if (val === 0) {
dst32[i] = TRANSPARENT_U32;
} else {
- // Manga grayscale: val is ink darkness (0 = white/transparent, 255 = solid black ink)
- // or standard luminance (0 = black, 255 = white).
- // Here: standard luminance with full opacity
const a = 255;
dst32[i] = isLittleEndian
? (a << 24) | (val << 16) | (val << 8) | val
@@ -259,17 +283,12 @@ export function packRGBATo8Bit(
}
/**
- * High-speed Run-Length Encoding (RLE) for compressing tile data
- * for network streaming and tile-delta history storage.
- *
- * Encoding format:
- * [Count: 1 byte, Value: 1 byte] for repeating bytes up to 255 runs.
+ * High-speed Run-Length Encoding (RLE) for compressing tile data.
*/
export function compressRLE(data: Uint8Array): Uint8Array {
const len = data.length;
if (len === 0) return new Uint8Array(0);
- // Worst-case capacity: 2x input length
const output = new Uint8Array(len * 2);
let outIdx = 0;
let i = 0;
@@ -297,7 +316,7 @@ export function decompressRLE(compressed: Uint8Array, expectedLength: number): U
let outIdx = 0;
const inLen = compressed.length;
- while (inIdx < inLen && outIdx < expectedLength) {
+ while (inIdx + 1 < inLen && outIdx < expectedLength) {
const count = compressed[inIdx++];
const val = compressed[inIdx++];
for (let c = 0; c < count && outIdx < expectedLength; c++) {
@@ -308,14 +327,10 @@ export function decompressRLE(compressed: Uint8Array, expectedLength: number): U
return output;
}
-/**
- * Compresses a TileBuffer into a compact binary package.
- * Header:
- * [tileX: Int32, tileY: Int32, formatId: Uint8, version: Uint32, rlePayload...]
- */
export function serializeTileBuffer(tile: TileBuffer): Uint8Array {
- const rle = compressRLE(tile.data);
- const headerSize = 13; // 4 + 4 + 1 + 4
+ const tileBytes = tile.data || new Uint8Array(getTileByteSize(tile.format));
+ const rle = compressRLE(tileBytes);
+ const headerSize = 13;
const packet = new Uint8Array(headerSize + rle.length);
const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);
@@ -329,10 +344,10 @@ export function serializeTileBuffer(tile: TileBuffer): Uint8Array {
return packet;
}
-/**
- * Deserializes a TileBuffer from a binary packet.
- */
export function deserializeTileBuffer(layerId: string, packet: Uint8Array): TileBuffer {
+ if (!packet || packet.byteLength < 13) {
+ return createTileBuffer(layerId, 0, 0, 'color-32bit', 0);
+ }
const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);
const tileX = view.getInt32(0, true);
const tileY = view.getInt32(4, true);
@@ -340,9 +355,7 @@ export function deserializeTileBuffer(layerId: string, packet: Uint8Array): Tile
const version = view.getUint32(9, true);
const format: TileFormat = formatCode === 1 ? 'monochrome-1bit' : formatCode === 2 ? 'grayscale-8bit' : 'color-32bit';
- let expectedLen = BYTES_32BIT;
- if (format === 'monochrome-1bit') expectedLen = BYTES_1BIT;
- else if (format === 'grayscale-8bit') expectedLen = BYTES_8BIT;
+ const expectedLen = getTileByteSize(format);
const rlePayload = packet.subarray(13);
const data = decompressRLE(rlePayload, expectedLen);
@@ -355,22 +368,608 @@ export function deserializeTileBuffer(layerId: string, packet: Uint8Array): Tile
data,
dirty: true,
version,
+ isPagedToDisk: false,
+ lastAccessTimestamp: typeof performance !== 'undefined' ? performance.now() : Date.now(),
+ lod: 0,
};
}
+// ============================================================================
+// Multi-Resolution Mipmap Downsampling (2x2 Child Tiles -> 1 Parent LOD Tile)
+// ============================================================================
+
+const _downsampleRgbaScratch = new Uint8ClampedArray(BYTES_32BIT);
+const _downsampleRgbaView = new Uint8Array(_downsampleRgbaScratch.buffer);
+const _downsample8BitScratch = new Uint8Array(BYTES_8BIT);
+const _downsample1BitScratch = new Uint8Array(BYTES_1BIT);
+
+/**
+ * Downsample 4 child tiles (2x2 cluster) at LOD k-1 into a single destination tile at LOD k.
+ * Reuses pre-allocated scratch buffers for zero 256KB heap allocations during zoom-out LOD builds.
+ */
+export function downsample2x2ToParentTile(
+ childTiles: [TileBuffer | null, TileBuffer | null, TileBuffer | null, TileBuffer | null],
+ dstTile: TileBuffer
+): boolean {
+ if (!dstTile.data) {
+ dstTile.data = new Uint8Array(getTileByteSize(dstTile.format));
+ }
+ dstTile.data.fill(0);
+
+ const hasAnyChild = childTiles.some((c) => c && c.data !== null);
+ if (!hasAnyChild) {
+ return false;
+ }
+
+ const format = dstTile.format;
+ const dst = dstTile.data;
+
+ for (let q = 0; q < 4; q++) {
+ const child = childTiles[q];
+ if (!child || !child.data) continue;
+
+ let childData = child.data;
+ const xBase = (q & 1) ? 128 : 0;
+ const yBase = (q >= 2) ? 128 : 0;
+
+ if (format === 'color-32bit') {
+ if (child.format === 'monochrome-1bit') {
+ unpack1BitToRGBA(childData, _downsampleRgbaScratch);
+ childData = _downsampleRgbaView;
+ } else if (child.format === 'grayscale-8bit') {
+ unpack8BitToRGBA(childData, _downsampleRgbaScratch);
+ childData = _downsampleRgbaView;
+ }
+ for (let ly = 0; ly < 128; ly++) {
+ const sy0 = ly << 1;
+ const sy1 = sy0 + 1;
+ const dy = yBase + ly;
+ const dstRowOffset = dy * TILE_SIZE;
+ const srcRowOffset0 = sy0 * TILE_SIZE;
+ const srcRowOffset1 = sy1 * TILE_SIZE;
+
+ for (let lx = 0; lx < 128; lx++) {
+ const sx0 = lx << 1;
+ const sx1 = sx0 + 1;
+ const dx = xBase + lx;
+
+ const p00 = (srcRowOffset0 + sx0) << 2;
+ const p10 = (srcRowOffset0 + sx1) << 2;
+ const p01 = (srcRowOffset1 + sx0) << 2;
+ const p11 = (srcRowOffset1 + sx1) << 2;
+ const outIdx = (dstRowOffset + dx) << 2;
+
+ const a0 = childData[p00 + 3];
+ const a1 = childData[p10 + 3];
+ const a2 = childData[p01 + 3];
+ const a3 = childData[p11 + 3];
+ const sumA = a0 + a1 + a2 + a3;
+
+ if (sumA === 0) {
+ dst[outIdx] = 0;
+ dst[outIdx + 1] = 0;
+ dst[outIdx + 2] = 0;
+ dst[outIdx + 3] = 0;
+ } else {
+ dst[outIdx + 3] = sumA >> 2;
+ dst[outIdx] = Math.round(
+ (childData[p00] * a0 + childData[p10] * a1 + childData[p01] * a2 + childData[p11] * a3) / sumA
+ );
+ dst[outIdx + 1] = Math.round(
+ (childData[p00 + 1] * a0 + childData[p10 + 1] * a1 + childData[p01 + 1] * a2 + childData[p11 + 1] * a3) / sumA
+ );
+ dst[outIdx + 2] = Math.round(
+ (childData[p00 + 2] * a0 + childData[p10 + 2] * a1 + childData[p01 + 2] * a2 + childData[p11 + 2] * a3) / sumA
+ );
+ }
+ }
+ }
+ } else if (format === 'grayscale-8bit') {
+ if (child.format === 'color-32bit') {
+ packRGBATo8Bit(childData, _downsample8BitScratch);
+ childData = _downsample8BitScratch;
+ } else if (child.format === 'monochrome-1bit') {
+ unpack1BitToRGBA(childData, _downsampleRgbaScratch);
+ packRGBATo8Bit(_downsampleRgbaScratch, _downsample8BitScratch);
+ childData = _downsample8BitScratch;
+ }
+ for (let ly = 0; ly < 128; ly++) {
+ const sy0 = ly << 1;
+ const sy1 = sy0 + 1;
+ const dy = yBase + ly;
+ const dstRowOffset = dy * TILE_SIZE;
+ const srcRowOffset0 = sy0 * TILE_SIZE;
+ const srcRowOffset1 = sy1 * TILE_SIZE;
+
+ for (let lx = 0; lx < 128; lx++) {
+ const sx0 = lx << 1;
+ const sx1 = sx0 + 1;
+ const dx = xBase + lx;
+
+ const v00 = childData[srcRowOffset0 + sx0];
+ const v10 = childData[srcRowOffset0 + sx1];
+ const v01 = childData[srcRowOffset1 + sx0];
+ const v11 = childData[srcRowOffset1 + sx1];
+
+ dst[dstRowOffset + dx] = (v00 + v10 + v01 + v11) >> 2;
+ }
+ }
+ } else {
+ if (child.format === 'color-32bit') {
+ packRGBATo1Bit(childData, _downsample1BitScratch);
+ childData = _downsample1BitScratch;
+ } else if (child.format === 'grayscale-8bit') {
+ unpack8BitToRGBA(childData, _downsampleRgbaScratch);
+ packRGBATo1Bit(_downsampleRgbaScratch, _downsample1BitScratch);
+ childData = _downsample1BitScratch;
+ }
+ for (let ly = 0; ly < 128; ly++) {
+ const sy0 = ly << 1;
+ const sy1 = sy0 + 1;
+ const dy = yBase + ly;
+
+ for (let lx = 0; lx < 128; lx++) {
+ const sx0 = lx << 1;
+ const sx1 = sx0 + 1;
+ const dx = xBase + lx;
+
+ const b0 = getPixel1Bit(childData, sx0, sy0);
+ const b1 = getPixel1Bit(childData, sx1, sy0);
+ const b2 = getPixel1Bit(childData, sx0, sy1);
+ const b3 = getPixel1Bit(childData, sx1, sy1);
+
+ setPixel1Bit(dst, dx, dy, (b0 | b1 | b2 | b3) !== 0);
+ }
+ }
+ }
+ }
+
+ dstTile.dirty = false;
+ dstTile.version++;
+ return true;
+}
+
+// ============================================================================
+// Scratch Disk Driver Interface & Implementations
+// ============================================================================
+
+export interface TileWritePayload {
+ layerId: string;
+ tileX: number;
+ tileY: number;
+ data: Uint8Array;
+}
+
+export interface IScratchDiskDriver {
+ init(sessionId: string): Promise<void>;
+ writeTiles(sessionId: string, tiles: TileWritePayload[]): Promise<number>;
+ readTile(sessionId: string, layerId: string, tileX: number, tileY: number): Promise<Uint8Array>;
+ clear(sessionId: string): Promise<void>;
+}
+
+export function isTauriEnvironment(): boolean {
+ if (typeof window === 'undefined') return false;
+ return Boolean(
+ (window as any).__TAURI_INTERNALS__ ||
+ (window as any).__TAURI__ ||
+ (window as any).isTauri
+ );
+}
+
+/**
+ * Production Tauri v2 Rust Scratch Disk Driver.
+ * Direct IPC with high-throughput LZ4 compression and atomic file index tables.
+ */
+export class TauriScratchDiskDriver implements IScratchDiskDriver {
+ public async init(sessionId: string): Promise<void> {
+ const { invoke } = await import('@tauri-apps/api/core');
+ await invoke('scratch_disk_init', { sessionId });
+ }
+
+ public async writeTiles(sessionId: string, tiles: TileWritePayload[]): Promise<number> {
+ if (tiles.length === 0) return 0;
+ const { invoke } = await import('@tauri-apps/api/core');
+ const count = await invoke<number>('scratch_disk_write_tiles', {
+ sessionId,
+ tiles: tiles.map((t) => ({
+ layerId: t.layerId,
+ tileX: t.tileX,
+ tileY: t.tileY,
+ data: Array.from(t.data),
+ })),
+ });
+ return count;
+ }
+
+ public async readTile(sessionId: string, layerId: string, tileX: number, tileY: number): Promise<Uint8Array> {
+ const { invoke } = await import('@tauri-apps/api/core');
+ const bytes = await invoke<number[] | Uint8Array>('scratch_disk_read_tile', {
+ sessionId,
+ layerId,
+ tileX,
+ tileY,
+ });
+ return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
+ }
+
+ public async clear(sessionId: string): Promise<void> {
+ const { invoke } = await import('@tauri-apps/api/core');
+ await invoke('scratch_disk_clear', { sessionId });
+ }
+}
+
+/**
+ * High-speed In-Memory / Fallback Scratch Disk Driver.
+ * Used during automated Vitest suites and pure browser previews without Tauri.
+ */
+export class InMemoryScratchDiskDriver implements IScratchDiskDriver {
+ private storage: Map<string, Uint8Array> = new Map();
+
+ public async init(_sessionId: string): Promise<void> {
+ this.storage.clear();
+ }
+
+ public async writeTiles(sessionId: string, tiles: TileWritePayload[]): Promise<number> {
+ for (const t of tiles) {
+ const copy = new Uint8Array(t.data.byteLength);
+ copy.set(t.data);
+ this.storage.set(`${sessionId}:${t.layerId}:${t.tileX}:${t.tileY}`, copy);
+ }
+ return tiles.length;
+ }
+
+ public async readTile(sessionId: string, layerId: string, tileX: number, tileY: number): Promise<Uint8Array> {
+ const key = `${sessionId}:${layerId}:${tileX}:${tileY}`;
+ const found = this.storage.get(key);
+ if (!found) {
+ throw new Error(`Tile not found on in-memory scratch disk: ${key}`);
+ }
+ const copy = new Uint8Array(found.byteLength);
+ copy.set(found);
+ return copy;
+ }
+
+ public async clear(sessionId: string): Promise<void> {
+ const prefix = `${sessionId}:`;
+ for (const key of Array.from(this.storage.keys())) {
+ if (key.startsWith(prefix)) {
+ this.storage.delete(key);
+ }
+ }
+ }
+}
+
+export function createDefaultScratchDiskDriver(): IScratchDiskDriver {
+ return isTauriEnvironment() ? new TauriScratchDiskDriver() : new InMemoryScratchDiskDriver();
+}
+
+// ============================================================================
+// TileMemoryManager (LRU Eviction & Transparent Page-In)
+// ============================================================================
+
+export interface TileMemoryManagerOptions {
+ budgetMb?: number;
+ driver?: IScratchDiskDriver;
+ sessionId?: string;
+}
+
+export class TileMemoryManager {
+ private sessionId: string;
+ private budgetBytes: number;
+ private activeBytes: number = 0;
+ private grid: SparseTileGrid;
+ private driver: IScratchDiskDriver;
+ private viewportFrustum: { minX: number; minY: number; maxX: number; maxY: number } | null = null;
+ private activeLayerId: string | null = null;
+ private layerVisibility: Map<string, boolean> = new Map();
+ private inFlightPageIns: Map<string, Promise<Uint8Array>> = new Map();
+ private evictionPromise: Promise<void> | null = null;
+ private needsAnotherEvictionPass: boolean = false;
+
+ constructor(grid: SparseTileGrid, options?: TileMemoryManagerOptions) {
+ this.grid = grid;
+ const mb = options?.budgetMb ?? 1024;
+ this.budgetBytes = Math.max(1, mb) * 1024 * 1024;
+ this.sessionId = options?.sessionId || `session-${Date.now()}-${Math.random().toString(36).substring(2, 8)}`;
+ this.driver = options?.driver || createDefaultScratchDiskDriver();
+ void this.driver.init(this.sessionId);
+ }
+
+ public getSessionId(): string {
+ return this.sessionId;
+ }
+
+ public getDriver(): IScratchDiskDriver {
+ return this.driver;
+ }
+
+ public setDriver(driver: IScratchDiskDriver): void {
+ this.driver = driver;
+ void this.driver.init(this.sessionId);
+ }
+
+ public setBudgetMb(mb: number): void {
+ this.budgetBytes = Math.max(1, mb) * 1024 * 1024;
+ void this.checkBudgetAndEvict();
+ }
+
+ public getBudgetBytes(): number {
+ return this.budgetBytes;
+ }
+
+ public getActiveMemoryBytes(): number {
+ return this.activeBytes;
+ }
+
+ public updateViewport(
+ frustum: { minX: number; minY: number; maxX: number; maxY: number } | null,
+ activeLayerId?: string | null,
+ layerVisibility?: Map<string, boolean>
+ ): void {
+ this.viewportFrustum = frustum;
+ if (activeLayerId !== undefined) this.activeLayerId = activeLayerId;
+ if (layerVisibility !== undefined) this.layerVisibility = layerVisibility;
+ }
+
+ public notifyTileAllocated(tile: TileBuffer): void {
+ if (tile.data !== null) {
+ this.activeBytes += tile.data.byteLength;
+ tile.lastAccessTimestamp = typeof performance !== 'undefined' ? performance.now() : Date.now();
+ if (tile.lod === 0) {
+ void this.checkBudgetAndEvict();
+ }
+ }
+ }
+
+ public notifyTileFreed(tile: TileBuffer): void {
+ if (tile.data !== null) {
+ this.activeBytes -= tile.data.byteLength;
+ }
+ }
+
+ public touchTile(tile: TileBuffer): void {
+ tile.lastAccessTimestamp = typeof performance !== 'undefined' ? performance.now() : Date.now();
+ }
+
+ /**
+ * Transparent Page-In: Asynchronously loads and decompresses a tile from scratch disk.
+ */
+ public async requestTileData(tile: TileBuffer): Promise<Uint8Array> {
+ if (tile.data !== null) {
+ this.touchTile(tile);
+ return tile.data;
+ }
+
+ if (!tile.isPagedToDisk) {
+ const size = getTileByteSize(tile.format);
+ tile.data = new Uint8Array(size);
+ this.notifyTileAllocated(tile);
+ return tile.data;
+ }
+
+ const key = getTileKey(tile.layerId, tile.tileX, tile.tileY, tile.lod);
+ let inFlight = this.inFlightPageIns.get(key);
+ if (!inFlight) {
+ inFlight = (async () => {
+ try {
+ const raw = await this.driver.readTile(this.sessionId, tile.layerId, tile.tileX, tile.tileY);
+ if (tile.data === null) {
+ tile.data = raw;
+ this.activeBytes += raw.byteLength;
+ }
+ tile.isPagedToDisk = true;
+ tile.dirty = true;
+ tile.version++;
+ this.touchTile(tile);
+ void this.checkBudgetAndEvict();
+ this.grid.notifyChange();
+ return tile.data;
+ } finally {
+ this.inFlightPageIns.delete(key);
+ }
+ })();
+ this.inFlightPageIns.set(key, inFlight);
+ }
+ return inFlight;
+ }
+
+ /**
+ * Evaluates memory consumption against the configured RAM budget.
+ * Runs an LRU eviction pass prioritizing hidden layers, outside frustum, and inactive layers.
+ */
+ public async checkBudgetAndEvict(): Promise<void> {
+ if (this.evictionPromise) {
+ this.needsAnotherEvictionPass = true;
+ return this.evictionPromise;
+ }
+
+ if (this.activeBytes <= this.budgetBytes) {
+ return;
+ }
+
+ this.evictionPromise = (async () => {
+ try {
+ while (this.activeBytes > this.budgetBytes) {
+ this.needsAnotherEvictionPass = false;
+ const evictedCount = await this.performEvictionPass();
+ if (evictedCount === 0) {
+ break;
+ }
+ if (!this.needsAnotherEvictionPass && this.activeBytes <= this.budgetBytes) {
+ break;
+ }
+ }
+ } finally {
+ this.evictionPromise = null;
+ this.needsAnotherEvictionPass = false;
+ }
+ })();
+
+ return this.evictionPromise;
+ }
+
+ private async performEvictionPass(): Promise<number> {
+ // 1. First drop any in-memory LOD > 0 tiles (they can always be re-downsampled on demand with 0 IO)
+ let droppedLodBytes = 0;
+ for (const tile of this.grid.getAllTiles()) {
+ if (tile.lod > 0 && tile.data !== null) {
+ this.activeBytes -= tile.data.byteLength;
+ droppedLodBytes += tile.data.byteLength;
+ tile.data = null;
+ tile.dirty = true;
+ }
+ }
+
+ if (this.activeBytes <= this.budgetBytes) {
+ return droppedLodBytes > 0 ? 1 : 0;
+ }
+
+ // 2. Gather candidate LOD 0 tiles with active data
+ const candidates: TileBuffer[] = [];
+ for (const tile of this.grid.getAllTiles()) {
+ if (tile.lod === 0 && tile.data !== null) {
+ candidates.push(tile);
+ }
+ }
+
+ if (candidates.length === 0) {
+ return droppedLodBytes > 0 ? 1 : 0;
+ }
+
+ const frustum = this.viewportFrustum;
+ const activeLayer = this.activeLayerId;
+ const layerVis = this.layerVisibility;
+
+ // 3. Score candidate eviction priority
+ const scored = candidates.map((tile) => {
+ const isHidden = layerVis.get(tile.layerId) === false;
+ const isInactiveLayer = activeLayer !== null && tile.layerId !== activeLayer;
+
+ let frustumDist = 0;
+ if (frustum) {
+ const minTx = pixelToTileCoord(frustum.minX, 0);
+ const maxTx = pixelToTileCoord(frustum.maxX, 0);
+ const minTy = pixelToTileCoord(frustum.minY, 0);
+ const maxTy = pixelToTileCoord(frustum.maxY, 0);
+
+ const dx = tile.tileX < minTx ? minTx - tile.tileX : tile.tileX > maxTx ? tile.tileX - maxTx : 0;
+ const dy = tile.tileY < minTy ? minTy - tile.tileY : tile.tileY > maxTy ? tile.tileY - maxTy : 0;
+ frustumDist = dx * dx + dy * dy;
+ }
+
+ let tier = 2;
+ if (isHidden) {
+ tier = 0; // Tier 0: Hidden layer tiles (evict first)
+ } else if (frustumDist > 0) {
+ tier = 1; // Tier 1: Outside viewport frustum (farthest first)
+ } else if (isInactiveLayer) {
+ tier = 2; // Tier 2: Inside frustum, but inactive layer (LRU)
+ } else {
+ tier = 3; // Tier 3: Inside frustum and active drawing layer (protected, evicted last if needed)
+ }
+
+ return {
+ tile,
+ tier,
+ frustumDist,
+ lastAccess: tile.lastAccessTimestamp,
+ };
+ });
+
+ scored.sort((a, b) => {
+ if (a.tier !== b.tier) return a.tier - b.tier;
+ if (a.tier === 1 && a.frustumDist !== b.frustumDist) {
+ return b.frustumDist - a.frustumDist; // Farthest distance outside frustum first
+ }
+ return a.lastAccess - b.lastAccess; // Oldest access timestamp first
+ });
+
+ // 4. Batch evict until within 90% of budget
+ const targetBytes = this.budgetBytes * 0.9;
+ const toEvict: TileBuffer[] = [];
+ let projectedBytes = this.activeBytes;
+
+ for (const item of scored) {
+ if (projectedBytes <= targetBytes) break;
+ toEvict.push(item.tile);
+ projectedBytes -= item.tile.data?.byteLength || 0;
+ }
+
+ if (toEvict.length > 0) {
+ await this.evictTiles(toEvict);
+ return toEvict.length;
+ }
+
+ return droppedLodBytes > 0 ? 1 : 0;
+ }
+
+ public async evictTiles(tiles: TileBuffer[]): Promise<void> {
+ const payloads: TileWritePayload[] = [];
+ const validTiles: TileBuffer[] = [];
+
+ for (const tile of tiles) {
+ if (tile.data !== null) {
+ payloads.push({
+ layerId: tile.layerId,
+ tileX: tile.tileX,
+ tileY: tile.tileY,
+ data: tile.data,
+ });
+ validTiles.push(tile);
+ }
+ }
+
+ if (payloads.length > 0) {
+ await this.driver.writeTiles(this.sessionId, payloads);
+ for (const tile of validTiles) {
+ if (tile.data) {
+ this.activeBytes -= tile.data.byteLength;
+ tile.data = null;
+ tile.isPagedToDisk = true;
+ tile.dirty = false;
+ }
+ }
+ }
+ }
+
+ public async clear(): Promise<void> {
+ this.inFlightPageIns.clear();
+ this.activeBytes = 0;
+ await this.driver.clear(this.sessionId);
+ }
+}
+
+// ============================================================================
+// SparseTileGrid
+// ============================================================================
+
/**
* Sparse Virtual Tile Grid
*
- * Spatial hash map allocating memory only where ink exists.
- * At 600 DPI B4 (4961 x 7016 px), a blank canvas consumes 0 bytes of tile memory!
+ * Sole authoritative backing store for all layer pixel data in Ink Studio.
+ * Completely deprecates multi-gigabyte full-sized DOM layer canvases.
*/
export class SparseTileGrid {
private tiles: Map<string, TileBuffer> = new Map();
private layerFormats: Map<string, TileFormat> = new Map();
+ private ingestedLayers: Set<string> = new Set();
+ private dirtyLodTiles: Set<string> = new Set();
private scratchRGBA: Uint8ClampedArray = new Uint8ClampedArray(BYTES_32BIT);
private listeners: Set<(immediate?: boolean) => void> = new Set();
+ private memoryManager: TileMemoryManager | null = null;
+ private idleCallbackScheduled: boolean = false;
+
+ constructor(memoryManagerOptions?: TileMemoryManagerOptions) {
+ this.memoryManager = new TileMemoryManager(this, memoryManagerOptions);
+ }
- constructor() {}
+ public setMemoryManager(manager: TileMemoryManager | null): void {
+ this.memoryManager = manager;
+ }
+
+ public getMemoryManager(): TileMemoryManager | null {
+ return this.memoryManager;
+ }
public subscribe(listener: (immediate?: boolean) => void): () => void {
this.listeners.add(listener);
@@ -381,97 +980,119 @@ export class SparseTileGrid {
this.listeners.forEach((fn) => fn(immediate));
}
- /**
- * Set the default pixel format for a layer.
- */
public setLayerFormat(layerId: string, format: TileFormat): void {
this.layerFormats.set(layerId, format);
}
- /**
- * Get the format for a layer, defaulting to color-32bit.
- */
public getLayerFormat(layerId: string): TileFormat {
return this.layerFormats.get(layerId) || 'color-32bit';
}
- /**
- * Check if a tile exists in memory.
- */
- public hasTile(layerId: string, tileX: number, tileY: number): boolean {
- return this.tiles.has(getTileKey(layerId, tileX, tileY));
+ public isLayerIngested(layerId: string): boolean {
+ return this.ingestedLayers.has(layerId);
}
- /**
- * Get an existing tile buffer or null if unpainted.
- */
- public getTile(layerId: string, tileX: number, tileY: number): TileBuffer | null {
- return this.tiles.get(getTileKey(layerId, tileX, tileY)) || null;
+ public markLayerIngested(layerId: string): void {
+ this.ingestedLayers.add(layerId);
}
- /**
- * Get an existing tile buffer or allocate a new zero-initialized tile.
- */
- public getOrCreateTile(layerId: string, tileX: number, tileY: number, format?: TileFormat): TileBuffer {
- const key = getTileKey(layerId, tileX, tileY);
+ public hasTile(layerId: string, tileX: number, tileY: number, lod: number = 0): boolean {
+ return this.tiles.has(getTileKey(layerId, tileX, tileY, lod));
+ }
+
+ public getTile(layerId: string, tileX: number, tileY: number, lod: number = 0): TileBuffer | null {
+ const tile = this.tiles.get(getTileKey(layerId, tileX, tileY, lod)) || null;
+ if (tile && this.memoryManager) {
+ this.memoryManager.touchTile(tile);
+ }
+ return tile;
+ }
+
+ public getOrCreateTile(
+ layerId: string,
+ tileX: number,
+ tileY: number,
+ format?: TileFormat,
+ lod: number = 0
+ ): TileBuffer {
+ const key = getTileKey(layerId, tileX, tileY, lod);
let tile = this.tiles.get(key);
if (!tile) {
const fmt = format || this.getLayerFormat(layerId);
- tile = createTileBuffer(layerId, tileX, tileY, fmt);
+ tile = createTileBuffer(layerId, tileX, tileY, fmt, lod);
this.tiles.set(key, tile);
+ if (this.memoryManager) {
+ this.memoryManager.notifyTileAllocated(tile);
+ }
+ } else if (tile.data === null && tile.isPagedToDisk && this.memoryManager) {
+ void this.memoryManager.requestTileData(tile);
+ } else if (this.memoryManager) {
+ this.memoryManager.touchTile(tile);
}
return tile;
}
- /**
- * Set or replace a tile buffer.
- */
public setTile(layerId: string, tileX: number, tileY: number, tile: TileBuffer): void {
- const key = getTileKey(layerId, tileX, tileY);
+ const key = getTileKey(layerId, tileX, tileY, tile.lod);
+ const existing = this.tiles.get(key);
+ if (existing && this.memoryManager) {
+ this.memoryManager.notifyTileFreed(existing);
+ }
this.tiles.set(key, tile);
+ if (this.memoryManager) {
+ this.memoryManager.notifyTileAllocated(tile);
+ }
+ if (tile.lod === 0) {
+ this.setLayerFormat(layerId, tile.format);
+ this.markLodAncestorsDirty(layerId, tileX, tileY);
+ }
this.notifyChange();
}
- /**
- * Delete a tile from memory (reclaiming space).
- */
- public deleteTile(layerId: string, tileX: number, tileY: number): void {
- this.tiles.delete(getTileKey(layerId, tileX, tileY));
+ public deleteTile(layerId: string, tileX: number, tileY: number, lod: number = 0): void {
+ const key = getTileKey(layerId, tileX, tileY, lod);
+ const tile = this.tiles.get(key);
+ if (tile) {
+ if (this.memoryManager) {
+ this.memoryManager.notifyTileFreed(tile);
+ }
+ this.tiles.delete(key);
+ if (lod === 0) {
+ this.markLodAncestorsDirty(layerId, tileX, tileY);
+ }
+ }
}
- /**
- * Get all allocated tiles for a layer.
- */
- public getLayerTiles(layerId: string): TileBuffer[] {
- const prefix = `${layerId}:`;
+ public getLayerTiles(layerId: string, lod: number = 0): TileBuffer[] {
const result: TileBuffer[] = [];
- for (const [key, tile] of this.tiles.entries()) {
- if (key.startsWith(prefix)) {
+ for (const tile of this.tiles.values()) {
+ if (tile.layerId === layerId && (tile.lod ?? 0) === lod) {
result.push(tile);
}
}
return result;
}
- /**
- * Get all tiles overlapping the given bounding box in document coordinates.
- */
public getTilesInBounds(
layerId: string,
minX: number,
minY: number,
maxX: number,
- maxY: number
+ maxY: number,
+ lod: number = 0
): TileBuffer[] {
- const minTileX = pixelToTileCoord(minX);
- const minTileY = pixelToTileCoord(minY);
- const maxTileX = pixelToTileCoord(maxX);
- const maxTileY = pixelToTileCoord(maxY);
+ const minTileX = pixelToTileCoord(minX, lod);
+ const minTileY = pixelToTileCoord(minY, lod);
+ const maxTileX = pixelToTileCoord(maxX, lod);
+ const maxTileY = pixelToTileCoord(maxY, lod);
const result: TileBuffer[] = [];
for (let ty = minTileY; ty <= maxTileY; ty++) {
for (let tx = minTileX; tx <= maxTileX; tx++) {
- const tile = this.getTile(layerId, tx, ty);
+ let tile = this.getTile(layerId, tx, ty, lod);
+ if (lod > 0 && (!tile || this.isLodTileDirty(layerId, tx, ty, lod))) {
+ tile = this.generateLodTile(layerId, tx, ty, lod);
+ }
if (tile) {
result.push(tile);
}
@@ -480,19 +1101,17 @@ export class SparseTileGrid {
return result;
}
- /**
- * Get tile coordinates intersecting document bounds.
- */
public getIntersectingCoords(
minX: number,
minY: number,
maxX: number,
- maxY: number
+ maxY: number,
+ lod: number = 0
): Array<{ tileX: number; tileY: number }> {
- const minTileX = pixelToTileCoord(minX);
- const minTileY = pixelToTileCoord(minY);
- const maxTileX = pixelToTileCoord(maxX);
- const maxTileY = pixelToTileCoord(maxY);
+ const minTileX = pixelToTileCoord(minX, lod);
+ const minTileY = pixelToTileCoord(minY, lod);
+ const maxTileX = pixelToTileCoord(maxX, lod);
+ const maxTileY = pixelToTileCoord(maxY, lod);
const coords: Array<{ tileX: number; tileY: number }> = [];
for (let ty = minTileY; ty <= maxTileY; ty++) {
@@ -504,9 +1123,18 @@ export class SparseTileGrid {
}
/**
- * Converts any tile to a 256x256 RGBA Uint8ClampedArray for WebGL texture upload or 2D blitting.
+ * Transparently returns a 256x256 RGBA Uint8ClampedArray for WebGL texture upload or 2D blitting.
+ * If tile data is paged to disk, kicks off an asynchronous fetch without freezing rendering.
*/
public getTileAsRGBA(tile: TileBuffer): Uint8ClampedArray {
+ if (tile.data === null) {
+ if (tile.isPagedToDisk && this.memoryManager) {
+ void this.memoryManager.requestTileData(tile);
+ }
+ this.scratchRGBA.fill(0);
+ return this.scratchRGBA;
+ }
+
if (tile.format === 'color-32bit') {
return new Uint8ClampedArray(tile.data.buffer, tile.data.byteOffset, BYTES_32BIT);
}
@@ -528,8 +1156,13 @@ export class SparseTileGrid {
imgData: { data: Uint8ClampedArray | Uint8Array; width: number; height: number },
destX: number,
destY: number,
- format?: TileFormat
+ format?: TileFormat,
+ suppressNotify: boolean = false
): { minTileX: number; minTileY: number; maxTileX: number; maxTileY: number } {
+ this.ingestedLayers.add(layerId);
+ if (format) {
+ this.setLayerFormat(layerId, format);
+ }
const targetFormat = format || this.getLayerFormat(layerId);
const w = imgData.width;
const h = imgData.height;
@@ -537,19 +1170,19 @@ export class SparseTileGrid {
return { minTileX: 0, minTileY: 0, maxTileX: 0, maxTileY: 0 };
}
- const minTileX = pixelToTileCoord(destX);
- const minTileY = pixelToTileCoord(destY);
- const maxTileX = pixelToTileCoord(destX + w - 1);
- const maxTileY = pixelToTileCoord(destY + h - 1);
+ const minTileX = pixelToTileCoord(destX, 0);
+ const minTileY = pixelToTileCoord(destY, 0);
+ const maxTileX = pixelToTileCoord(destX + w - 1, 0);
+ const maxTileY = pixelToTileCoord(destY + h - 1, 0);
const tileScratch = new Uint8ClampedArray(BYTES_32BIT);
+ const srcData = imgData.data;
for (let ty = minTileY; ty <= maxTileY; ty++) {
const tileDocY = ty * TILE_SIZE;
for (let tx = minTileX; tx <= maxTileX; tx++) {
const tileDocX = tx * TILE_SIZE;
- // Intersection of tile with source rectangle
const srcStartX = Math.max(0, tileDocX - destX);
const srcStartY = Math.max(0, tileDocY - destY);
const srcEndX = Math.min(w, tileDocX + TILE_SIZE - destX);
@@ -557,9 +1190,36 @@ export class SparseTileGrid {
if (srcStartX >= srcEndX || srcStartY >= srcEndY) continue;
- const tile = this.getOrCreateTile(layerId, tx, ty, targetFormat);
+ let existingTile = this.getTile(layerId, tx, ty, 0);
+ if (!existingTile) {
+ let hasNonZero = false;
+ outer: for (let sy = srcStartY; sy < srcEndY; sy++) {
+ let idx = (sy * w + srcStartX) * 4;
+ const endIdx = (sy * w + srcEndX) * 4;
+ for (; idx < endIdx; idx += 4) {
+ if (srcData[idx + 3] !== 0 || srcData[idx] !== 0 || srcData[idx + 1] !== 0 || srcData[idx + 2] !== 0) {
+ hasNonZero = true;
+ break outer;
+ }
+ }
+ }
+ if (!hasNonZero) continue;
+ existingTile = this.getOrCreateTile(layerId, tx, ty, targetFormat, 0);
+ }
+
+ const tile = existingTile;
+ if (tile.format !== targetFormat) {
+ if (tile.data !== null) {
+ this.memoryManager?.notifyTileFreed(tile);
+ }
+ tile.format = targetFormat;
+ tile.data = new Uint8Array(getTileByteSize(targetFormat));
+ this.memoryManager?.notifyTileAllocated(tile);
+ } else if (tile.data === null) {
+ tile.data = new Uint8Array(getTileByteSize(tile.format));
+ this.memoryManager?.notifyTileAllocated(tile);
+ }
- // If tile is 32-bit RGBA
if (tile.format === 'color-32bit') {
for (let sy = srcStartY; sy < srcEndY; sy++) {
const tileLocalY = destY + sy - tileDocY;
@@ -570,15 +1230,13 @@ export class SparseTileGrid {
const tileByteOffset = (tileLocalY * TILE_SIZE + tileLocalX) * 4;
tile.data.set(
- imgData.data.subarray(srcByteOffset, srcByteOffset + copyWidth * 4),
+ srcData.subarray(srcByteOffset, srcByteOffset + copyWidth * 4),
tileByteOffset
);
}
} else if (tile.format === 'monochrome-1bit') {
- // Read existing 1-bit tile as RGBA to preserve non-overlapping parts
unpack1BitToRGBA(tile.data, tileScratch);
- // Overwrite intersecting region
for (let sy = srcStartY; sy < srcEndY; sy++) {
const tileLocalY = destY + sy - tileDocY;
const tileLocalX = destX + srcStartX - tileDocX;
@@ -588,15 +1246,13 @@ export class SparseTileGrid {
const tileByteOffset = (tileLocalY * TILE_SIZE + tileLocalX) * 4;
tileScratch.set(
- imgData.data.subarray(srcByteOffset, srcByteOffset + copyWidth * 4),
+ srcData.subarray(srcByteOffset, srcByteOffset + copyWidth * 4),
tileByteOffset
);
}
- // Pack back to 1-bit
packRGBATo1Bit(tileScratch, tile.data);
} else {
- // Grayscale 8-bit
unpack8BitToRGBA(tile.data, tileScratch);
for (let sy = srcStartY; sy < srcEndY; sy++) {
const tileLocalY = destY + sy - tileDocY;
@@ -607,7 +1263,7 @@ export class SparseTileGrid {
const tileByteOffset = (tileLocalY * TILE_SIZE + tileLocalX) * 4;
tileScratch.set(
- imgData.data.subarray(srcByteOffset, srcByteOffset + copyWidth * 4),
+ srcData.subarray(srcByteOffset, srcByteOffset + copyWidth * 4),
tileByteOffset
);
}
@@ -616,17 +1272,16 @@ export class SparseTileGrid {
tile.dirty = true;
tile.version++;
+ this.markLodAncestorsDirty(layerId, tx, ty);
}
}
- this.notifyChange();
+ if (!suppressNotify) {
+ this.notifyChange();
+ }
return { minTileX, minTileY, maxTileX, maxTileY };
}
- /**
- * Reads a document rectangular region into an RGBA ImageData-compatible buffer.
- * If a tile doesn't exist, it contributes transparent pixels (zero allocation).
- */
public readImageData(
layerId: string,
x: number,
@@ -637,16 +1292,16 @@ export class SparseTileGrid {
const outData = new Uint8ClampedArray(width * height * 4);
if (width <= 0 || height <= 0) return { data: outData, width, height };
- const minTileX = pixelToTileCoord(x);
- const minTileY = pixelToTileCoord(y);
- const maxTileX = pixelToTileCoord(x + width - 1);
- const maxTileY = pixelToTileCoord(y + height - 1);
+ const minTileX = pixelToTileCoord(x, 0);
+ const minTileY = pixelToTileCoord(y, 0);
+ const maxTileX = pixelToTileCoord(x + width - 1, 0);
+ const maxTileY = pixelToTileCoord(y + height - 1, 0);
for (let ty = minTileY; ty <= maxTileY; ty++) {
const tileDocY = ty * TILE_SIZE;
for (let tx = minTileX; tx <= maxTileX; tx++) {
- const tile = this.getTile(layerId, tx, ty);
- if (!tile) continue; // Unpainted tile is transparent
+ const tile = this.getTile(layerId, tx, ty, 0);
+ if (!tile) continue;
const tileDocX = tx * TILE_SIZE;
const tileRGBA = this.getTileAsRGBA(tile);
@@ -674,9 +1329,6 @@ export class SparseTileGrid {
return { data: outData, width, height };
}
- /**
- * Render an entire layer or a dirtyRect directly onto a standard HTMLCanvasElement.
- */
public renderLayerToCanvas(
layerId: string,
targetCanvas: HTMLCanvasElement,
@@ -699,32 +1351,31 @@ export class SparseTileGrid {
ctx.clearRect(minX, minY, maxX - minX, maxY - minY);
- const minTileX = pixelToTileCoord(minX);
- const minTileY = pixelToTileCoord(minY);
- const maxTileX = pixelToTileCoord(maxX - 1);
- const maxTileY = pixelToTileCoord(maxY - 1);
+ const minTileX = pixelToTileCoord(minX, 0);
+ const minTileY = pixelToTileCoord(minY, 0);
+ const maxTileX = pixelToTileCoord(maxX - 1, 0);
+ const maxTileY = pixelToTileCoord(maxY - 1, 0);
- // Reuse helper canvas to draw tiles
let helperCanvas: HTMLCanvasElement | null = null;
let helperCtx: CanvasRenderingContext2D | null = null;
for (let ty = minTileY; ty <= maxTileY; ty++) {
const tileDocY = ty * TILE_SIZE;
for (let tx = minTileX; tx <= maxTileX; tx++) {
- const tile = this.getTile(layerId, tx, ty);
+ const tile = this.getTile(layerId, tx, ty, 0);
if (!tile) continue;
const tileDocX = tx * TILE_SIZE;
const rgba = this.getTileAsRGBA(tile);
- if (!helperCanvas) {
+ if (!helperCanvas && typeof document !== 'undefined') {
helperCanvas = document.createElement('canvas');
helperCanvas.width = TILE_SIZE;
helperCanvas.height = TILE_SIZE;
helperCtx = helperCanvas.getContext('2d');
}
- if (helperCtx) {
+ if (helperCtx && helperCanvas) {
const clamped = new Uint8ClampedArray(rgba.buffer as ArrayBuffer, rgba.byteOffset, BYTES_32BIT);
const imgData = new ImageData(clamped, TILE_SIZE, TILE_SIZE);
helperCtx.putImageData(imgData, 0, 0);
@@ -735,44 +1386,384 @@ export class SparseTileGrid {
}
/**
- * Ingest an existing HTMLCanvasElement into the tile grid.
+ * Generates a layer thumbnail directly from the sparse tile grid or LOD mipmaps.
+ * Completely bypasses full-size canvas allocation.
+ */
+ public generateThumbnail(
+ layerId: string,
+ thumbWidth: number,
+ thumbHeight: number,
+ docDimensions: { width: number; height: number }
+ ): string {
+ if (typeof document === 'undefined') return '';
+ const canvas = document.createElement('canvas');
+ canvas.width = thumbWidth;
+ canvas.height = thumbHeight;
+ const ctx = canvas.getContext('2d');
+ if (!ctx) return '';
+
+ ctx.clearRect(0, 0, thumbWidth, thumbHeight);
+
+ const docW = Math.max(1, docDimensions.width);
+ const docH = Math.max(1, docDimensions.height);
+
+ // Prefer LOD 3 (1/8 scale) or LOD 2 if available, else LOD 0
+ if (this.dirtyLodTiles.size > 0) {
+ this.flushMipmaps(layerId);
+ }
+ let renderLod = 3;
+ let tiles = this.getLayerTiles(layerId, 3);
+ if (tiles.length === 0) {
+ renderLod = 0;
+ tiles = this.getLayerTiles(layerId, 0);
+ }
+
+ if (tiles.length === 0) {
+ return canvas.toDataURL('image/png');
+ }
+
+ const lodDocSize = TILE_SIZE << renderLod;
+ const thumbImg = ctx.createImageData(thumbWidth, thumbHeight);
+ const outData = thumbImg.data;
+ const scaleX = docW / thumbWidth;
+ const scaleY = docH / thumbHeight;
+
+ for (const tile of tiles) {
+ const tileDocX = tile.tileX * lodDocSize;
+ const tileDocY = tile.tileY * lodDocSize;
+
+ const x0 = Math.max(0, Math.floor((tileDocX / docW) * thumbWidth));
+ const y0 = Math.max(0, Math.floor((tileDocY / docH) * thumbHeight));
+ const x1 = Math.min(thumbWidth, Math.ceil(((tileDocX + lodDocSize) / docW) * thumbWidth));
+ const y1 = Math.min(thumbHeight, Math.ceil(((tileDocY + lodDocSize) / docH) * thumbHeight));
+
+ if (x0 >= x1 || y0 >= y1) continue;
+
+ const rgba = this.getTileAsRGBA(tile);
+
+ for (let py = y0; py < y1; py++) {
+ const docY = (py + 0.5) * scaleY;
+ const ly = Math.min(TILE_SIZE - 1, Math.max(0, Math.floor(((docY - tileDocY) / lodDocSize) * TILE_SIZE)));
+ const ly2 = Math.min(TILE_SIZE - 1, ly + 1);
+ for (let px = x0; px < x1; px++) {
+ const docX = (px + 0.5) * scaleX;
+ const lx = Math.min(TILE_SIZE - 1, Math.max(0, Math.floor(((docX - tileDocX) / lodDocSize) * TILE_SIZE)));
+ const lx2 = Math.min(TILE_SIZE - 1, lx + 1);
+
+ let srcIdx = (ly * TILE_SIZE + lx) * 4;
+ if (rgba[srcIdx + 3] === 0) {
+ const alt1 = (ly * TILE_SIZE + lx2) * 4;
+ const alt2 = (ly2 * TILE_SIZE + lx) * 4;
+ const alt3 = (ly2 * TILE_SIZE + lx2) * 4;
+ if (rgba[alt1 + 3] > 0) srcIdx = alt1;
+ else if (rgba[alt2 + 3] > 0) srcIdx = alt2;
+ else if (rgba[alt3 + 3] > 0) srcIdx = alt3;
+ }
+
+ if (rgba[srcIdx + 3] > 0) {
+ const dstIdx = (py * thumbWidth + px) * 4;
+ outData[dstIdx] = rgba[srcIdx];
+ outData[dstIdx + 1] = rgba[srcIdx + 1];
+ outData[dstIdx + 2] = rgba[srcIdx + 2];
+ outData[dstIdx + 3] = rgba[srcIdx + 3];
+ }
+ }
+ }
+ }
+
+ ctx.putImageData(thumbImg, 0, 0);
+ return canvas.toDataURL('image/png');
+ }
+
+ // ==========================================================================
+ // On-Demand Mipmap Pyramid Management
+ // ==========================================================================
+
+ public isLodTileDirty(layerId: string, tileX: number, tileY: number, lod: number): boolean {
+ if (lod <= 0) return false;
+ return this.dirtyLodTiles.has(getTileKey(layerId, tileX, tileY, lod));
+ }
+
+ public markLodAncestorsDirty(layerId: string, tileX: number, tileY: number): void {
+ let tx = tileX;
+ let ty = tileY;
+ for (let lod = 1; lod <= 3; lod++) {
+ tx = tx >> 1;
+ ty = ty >> 1;
+ const key = getTileKey(layerId, tx, ty, lod);
+ this.dirtyLodTiles.add(key);
+ const existing = this.tiles.get(key);
+ if (existing) {
+ existing.dirty = true;
+ }
+ }
+ this.scheduleIdleDownsampling();
+ }
+
+ private scheduleIdleDownsampling(): void {
+ if (this.idleCallbackScheduled || this.dirtyLodTiles.size === 0) return;
+ this.idleCallbackScheduled = true;
+
+ const run = () => {
+ this.idleCallbackScheduled = false;
+ const updated = this.updateDirtyMipmaps(16);
+ if (updated > 0) {
+ this.notifyChange();
+ }
+ if (this.dirtyLodTiles.size > 0) {
+ this.scheduleIdleDownsampling();
+ }
+ };
+
+ if (typeof window !== 'undefined' && 'requestIdleCallback' in window) {
+ (window as any).requestIdleCallback(run, { timeout: 100 });
+ } else {
+ setTimeout(run, 16);
+ }
+ }
+
+ /**
+ * Generates or downsamples a specific LOD tile from its 4 child tiles at LOD - 1.
+ */
+ public generateLodTile(layerId: string, lodTx: number, lodTy: number, targetLod: number): TileBuffer | null {
+ if (targetLod <= 0) {
+ return this.getTile(layerId, lodTx, lodTy, 0);
+ }
+
+ const childLod = targetLod - 1;
+ const cX0 = lodTx << 1;
+ const cY0 = lodTy << 1;
+
+ let c00 = this.getTile(layerId, cX0, cY0, childLod);
+ let c10 = this.getTile(layerId, cX0 + 1, cY0, childLod);
+ let c01 = this.getTile(layerId, cX0, cY0 + 1, childLod);
+ let c11 = this.getTile(layerId, cX0 + 1, cY0 + 1, childLod);
+
+ if (childLod > 0) {
+ if (!c00 || this.isLodTileDirty(layerId, cX0, cY0, childLod)) {
+ c00 = this.generateLodTile(layerId, cX0, cY0, childLod);
+ }
+ if (!c10 || this.isLodTileDirty(layerId, cX0 + 1, cY0, childLod)) {
+ c10 = this.generateLodTile(layerId, cX0 + 1, cY0, childLod);
+ }
+ if (!c01 || this.isLodTileDirty(layerId, cX0, cY0 + 1, childLod)) {
+ c01 = this.generateLodTile(layerId, cX0, cY0 + 1, childLod);
+ }
+ if (!c11 || this.isLodTileDirty(layerId, cX0 + 1, cY0 + 1, childLod)) {
+ c11 = this.generateLodTile(layerId, cX0 + 1, cY0 + 1, childLod);
+ }
+ }
+
+ const firstChild = c00 || c10 || c01 || c11;
+ const format = firstChild ? firstChild.format : this.getLayerFormat(layerId);
+
+ const key = getTileKey(layerId, lodTx, lodTy, targetLod);
+ let tile = this.tiles.get(key);
+
+ let allocatedNew = false;
+ if (!tile) {
+ tile = createTileBuffer(layerId, lodTx, lodTy, format, targetLod);
+ this.tiles.set(key, tile);
+ allocatedNew = true;
+ } else if (tile.format !== format) {
+ if (tile.data !== null) {
+ this.memoryManager?.notifyTileFreed(tile);
+ }
+ tile.format = format;
+ tile.data = new Uint8Array(getTileByteSize(format));
+ allocatedNew = true;
+ } else if (tile.data === null) {
+ allocatedNew = true;
+ }
+
+ const success = downsample2x2ToParentTile([c00, c10, c01, c11], tile);
+ if (!success) {
+ if (!allocatedNew) {
+ this.memoryManager?.notifyTileFreed(tile);
+ }
+ this.tiles.delete(key);
+ this.dirtyLodTiles.delete(key);
+ return null;
+ }
+
+ if (allocatedNew) {
+ this.memoryManager?.notifyTileAllocated(tile);
+ }
+ tile.dirty = true;
+ tile.version++;
+ this.dirtyLodTiles.delete(key);
+ return tile;
+ }
+
+ /**
+ * Progressively downsamples up to `maxCount` dirty mipmap tiles.
+ */
+ public updateDirtyMipmaps(maxCount: number = 16): number {
+ let count = 0;
+ const keys = Array.from(this.dirtyLodTiles);
+
+ // Process lower LODs (LOD 1) before higher LODs (LOD 2, 3)
+ keys.sort((a, b) => {
+ const pa = parseTileKey(a);
+ const pb = parseTileKey(b);
+ return pa.lod - pb.lod;
+ });
+
+ for (const key of keys) {
+ if (count >= maxCount) break;
+ this.dirtyLodTiles.delete(key);
+ const { layerId, tileX, tileY, lod } = parseTileKey(key);
+ this.generateLodTile(layerId, tileX, tileY, lod);
+ count++;
+ }
+
+ return count;
+ }
+
+ /**
+ * Flushes all pending dirty mipmap tiles immediately.
*/
+ public flushMipmaps(layerId?: string): void {
+ const keys = Array.from(this.dirtyLodTiles);
+ keys.sort((a, b) => {
+ const pa = parseTileKey(a);
+ const pb = parseTileKey(b);
+ return pa.lod - pb.lod;
+ });
+
+ for (const key of keys) {
+ const { layerId: lId, tileX, tileY, lod } = parseTileKey(key);
+ if (!layerId || lId === layerId) {
+ this.dirtyLodTiles.delete(key);
+ this.generateLodTile(lId, tileX, tileY, lod);
+ }
+ }
+ }
+
+ public fillLayerSolidWhite(layerId: string, width: number, height: number, format?: TileFormat): void {
+ this.clearLayer(layerId);
+ this.ingestedLayers.add(layerId);
+ if (format) {
+ this.setLayerFormat(layerId, format);
+ }
+ if (width <= 0 || height <= 0) return;
+
+ const targetFormat = format || this.getLayerFormat(layerId);
+ if (targetFormat === 'monochrome-1bit') {
+ // Solid white in monochrome-1bit has 0 black ink bits
+ this.notifyChange();
+ return;
+ }
+
+ const maxTileX = pixelToTileCoord(width - 1, 0);
+ const maxTileY = pixelToTileCoord(height - 1, 0);
+
+ for (let ty = 0; ty <= maxTileY; ty++) {
+ const tileDocY = ty * TILE_SIZE;
+ const validH = Math.min(TILE_SIZE, height - tileDocY);
+ for (let tx = 0; tx <= maxTileX; tx++) {
+ const tileDocX = tx * TILE_SIZE;
+ const validW = Math.min(TILE_SIZE, width - tileDocX);
+ const tile = this.getOrCreateTile(layerId, tx, ty, targetFormat, 0);
+ if (!tile.data) {
+ tile.data = new Uint8Array(getTileByteSize(tile.format));
+ this.memoryManager?.notifyTileAllocated(tile);
+ }
+ if (validW === TILE_SIZE && validH === TILE_SIZE) {
+ tile.data.fill(255);
+ } else if (tile.format === 'color-32bit') {
+ tile.data.fill(0);
+ for (let y = 0; y < validH; y++) {
+ const rowStart = y * TILE_SIZE * 4;
+ tile.data.fill(255, rowStart, rowStart + validW * 4);
+ }
+ } else {
+ tile.data.fill(0);
+ for (let y = 0; y < validH; y++) {
+ const rowStart = y * TILE_SIZE;
+ tile.data.fill(255, rowStart, rowStart + validW);
+ }
+ }
+ tile.dirty = true;
+ tile.version++;
+ this.markLodAncestorsDirty(layerId, tx, ty);
+ }
+ }
+ this.notifyChange();
+ }
+
public ingestCanvas(layerId: string, canvas: HTMLCanvasElement, format?: TileFormat): void {
+ if (canvas.width <= 0 || canvas.height <= 0) return;
+ if (format) {
+ this.setLayerFormat(layerId, format);
+ }
+ if ((canvas as any).__isBlank) {
+ this.clearLayer(layerId);
+ this.ingestedLayers.add(layerId);
+ if (format) {
+ this.setLayerFormat(layerId, format);
+ }
+ return;
+ }
+ if ((canvas as any).__isSolidWhite) {
+ this.fillLayerSolidWhite(layerId, canvas.width, canvas.height, format);
+ return;
+ }
const ctx = canvas.getContext('2d', { willReadFrequently: true });
- if (!ctx || canvas.width <= 0 || canvas.height <= 0) return;
+ if (!ctx) return;
this.clearLayer(layerId);
- const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- this.writeImageData(layerId, imgData, 0, 0, format);
+ this.ingestedLayers.add(layerId);
+ if (format) {
+ this.setLayerFormat(layerId, format);
+ }
+ const w = canvas.width;
+ const h = canvas.height;
+ if (w * h <= 1024 * 1024) {
+ const imgData = ctx.getImageData(0, 0, w, h);
+ this.writeImageData(layerId, imgData, 0, 0, format, true);
+ } else {
+ const stripH = TILE_SIZE;
+ for (let y = 0; y < h; y += stripH) {
+ const curH = Math.min(stripH, h - y);
+ const stripData = ctx.getImageData(0, y, w, curH);
+ this.writeImageData(layerId, stripData, 0, y, format, true);
+ }
+ }
this.notifyChange();
}
- /**
- * Clear all tiles associated with a layer.
- */
public clearLayer(layerId: string): void {
+ this.ingestedLayers.delete(layerId);
const prefix = `${layerId}:`;
const toDelete: string[] = [];
- for (const key of this.tiles.keys()) {
+ for (const [key, tile] of this.tiles.entries()) {
if (key.startsWith(prefix)) {
toDelete.push(key);
+ if (this.memoryManager) {
+ this.memoryManager.notifyTileFreed(tile);
+ }
}
}
for (const key of toDelete) {
this.tiles.delete(key);
+ this.dirtyLodTiles.delete(key);
}
this.notifyChange();
}
- /**
- * Clone all tiles from one layer into another.
- */
public cloneLayer(srcLayerId: string, dstLayerId: string): void {
this.clearLayer(dstLayerId);
- const srcTiles = this.getLayerTiles(srcLayerId);
+ this.ingestedLayers.add(dstLayerId);
+ this.setLayerFormat(dstLayerId, this.getLayerFormat(srcLayerId));
+ const srcTiles = this.getLayerTiles(srcLayerId, 0);
for (const srcTile of srcTiles) {
- const clonedData = new Uint8Array(srcTile.data.length);
- clonedData.set(srcTile.data);
+ if (!srcTile.data && srcTile.isPagedToDisk && this.memoryManager) {
+ void this.memoryManager.requestTileData(srcTile);
+ }
+ const clonedData = srcTile.data ? new Uint8Array(srcTile.data.length) : new Uint8Array(getTileByteSize(srcTile.format));
+ if (srcTile.data) clonedData.set(srcTile.data);
+
const clonedTile: TileBuffer = {
layerId: dstLayerId,
tileX: srcTile.tileX,
@@ -781,41 +1772,64 @@ export class SparseTileGrid {
data: clonedData,
dirty: true,
version: 1,
+ isPagedToDisk: false,
+ lastAccessTimestamp: typeof performance !== 'undefined' ? performance.now() : Date.now(),
+ lod: 0,
};
this.setTile(dstLayerId, srcTile.tileX, srcTile.tileY, clonedTile);
}
}
- /**
- * Calculate exact memory consumption metrics.
- */
public getMemoryStats(): {
totalBytes: number;
+ activeBytes: number;
+ pagedBytes: number;
tileCount: number;
+ activeTileCount: number;
+ pagedTileCount: number;
formatCounts: Record<TileFormat, number>;
+ lodCounts: Record<number, number>;
} {
let totalBytes = 0;
+ let activeBytes = 0;
+ let pagedBytes = 0;
+ let activeTileCount = 0;
+ let pagedTileCount = 0;
+
const formatCounts: Record<TileFormat, number> = {
'monochrome-1bit': 0,
'grayscale-8bit': 0,
'color-32bit': 0,
};
+ const lodCounts: Record<number, number> = { 0: 0, 1: 0, 2: 0, 3: 0 };
for (const tile of this.tiles.values()) {
- totalBytes += tile.data.byteLength;
- formatCounts[tile.format]++;
+ const bSize = getTileByteSize(tile.format);
+ totalBytes += bSize;
+ lodCounts[tile.lod ?? 0] = (lodCounts[tile.lod ?? 0] || 0) + 1;
+
+ if (tile.data !== null) {
+ activeBytes += tile.data.byteLength;
+ activeTileCount++;
+ formatCounts[tile.format]++;
+ } else if (tile.isPagedToDisk) {
+ pagedBytes += bSize;
+ pagedTileCount++;
+ }
}
return {
totalBytes,
+ activeBytes,
+ pagedBytes,
tileCount: this.tiles.size,
+ activeTileCount,
+ pagedTileCount,
formatCounts,
+ lodCounts,
};
}
- /**
- * Take an in-memory snapshot of all tiles in a document bounding box.
- */
public snapshotTilesInRect(
layerId: string,
bounds: { x: number; y: number; width: number; height: number }
@@ -823,18 +1837,18 @@ export class SparseTileGrid {
const snapshot = new Map<string, { format: TileFormat; data: Uint8Array | null }>();
if (bounds.width <= 0 || bounds.height <= 0) return snapshot;
- const minTileX = pixelToTileCoord(bounds.x);
- const minTileY = pixelToTileCoord(bounds.y);
- const maxTileX = pixelToTileCoord(bounds.x + bounds.width - 1);
- const maxTileY = pixelToTileCoord(bounds.y + bounds.height - 1);
+ const minTileX = pixelToTileCoord(bounds.x, 0);
+ const minTileY = pixelToTileCoord(bounds.y, 0);
+ const maxTileX = pixelToTileCoord(bounds.x + bounds.width - 1, 0);
+ const maxTileY = pixelToTileCoord(bounds.y + bounds.height - 1, 0);
const layerFormat = this.getLayerFormat(layerId);
for (let ty = minTileY; ty <= maxTileY; ty++) {
for (let tx = minTileX; tx <= maxTileX; tx++) {
- const key = getTileKey(layerId, tx, ty);
- const tile = this.getTile(layerId, tx, ty);
- if (tile) {
+ const key = getTileKey(layerId, tx, ty, 0);
+ const tile = this.getTile(layerId, tx, ty, 0);
+ if (tile && tile.data) {
const copy = new Uint8Array(tile.data.length);
copy.set(tile.data);
snapshot.set(key, { format: tile.format, data: copy });
@@ -847,9 +1861,6 @@ export class SparseTileGrid {
return snapshot;
}
- /**
- * Compare current tiles in bounding box against the snapshot to produce minimal TileDeltas.
- */
public computeDeltasFromSnapshot(
beforeSnapshot: Map<string, { format: TileFormat; data: Uint8Array | null }>,
layerId: string,
@@ -858,15 +1869,14 @@ export class SparseTileGrid {
const deltas: TileDelta[] = [];
const keysToCheck = new Set<string>(beforeSnapshot.keys());
- // Also include any newly created tiles in the current bounding box
if (bounds && bounds.width > 0 && bounds.height > 0) {
- const minTileX = pixelToTileCoord(bounds.x);
- const minTileY = pixelToTileCoord(bounds.y);
- const maxTileX = pixelToTileCoord(bounds.x + bounds.width - 1);
- const maxTileY = pixelToTileCoord(bounds.y + bounds.height - 1);
+ const minTileX = pixelToTileCoord(bounds.x, 0);
+ const minTileY = pixelToTileCoord(bounds.y, 0);
+ const maxTileX = pixelToTileCoord(bounds.x + bounds.width - 1, 0);
+ const maxTileY = pixelToTileCoord(bounds.y + bounds.height - 1, 0);
for (let ty = minTileY; ty <= maxTileY; ty++) {
for (let tx = minTileX; tx <= maxTileX; tx++) {
- keysToCheck.add(getTileKey(layerId, tx, ty));
+ keysToCheck.add(getTileKey(layerId, tx, ty, 0));
}
}
}
@@ -874,10 +1884,10 @@ export class SparseTileGrid {
for (const key of keysToCheck) {
const before = beforeSnapshot.get(key);
const { tileX, tileY } = parseTileKey(key);
- const currentTile = this.getTile(layerId, tileX, tileY);
+ const currentTile = this.getTile(layerId, tileX, tileY, 0);
const beforeData = before ? before.data : null;
- const afterData = currentTile ? new Uint8Array(currentTile.data) : null;
+ const afterData = currentTile && currentTile.data ? new Uint8Array(currentTile.data) : null;
const format = currentTile ? currentTile.format : (before ? before.format : this.getLayerFormat(layerId));
if (beforeData === null && afterData === null) continue;
@@ -911,44 +1921,78 @@ export class SparseTileGrid {
return deltas;
}
- /**
- * Apply a list of TileDeltas in either undo or redo direction.
- */
public applyTileDeltas(deltas: TileDelta[], direction: 'undo' | 'redo'): void {
for (const delta of deltas) {
const { layerId, tileX, tileY } = parseTileKey(delta.key);
const targetData = direction === 'undo' ? delta.beforeData : delta.afterData;
if (!targetData) {
- this.deleteTile(layerId, tileX, tileY);
+ this.deleteTile(layerId, tileX, tileY, 0);
} else {
- let tile = this.getTile(layerId, tileX, tileY);
+ let tile = this.getTile(layerId, tileX, tileY, 0);
if (!tile) {
- tile = this.getOrCreateTile(layerId, tileX, tileY, delta.format);
+ tile = this.getOrCreateTile(layerId, tileX, tileY, delta.format, 0);
}
- if (tile.data.byteLength === targetData.byteLength) {
- tile.data.set(targetData);
- } else {
+ if (!tile.data || tile.data.byteLength !== targetData.byteLength) {
+ if (tile.data) {
+ this.memoryManager?.notifyTileFreed(tile);
+ }
tile.data = new Uint8Array(targetData.length);
- tile.data.set(targetData);
- tile.format = delta.format;
+ this.memoryManager?.notifyTileAllocated(tile);
}
+ tile.data.set(targetData);
+ tile.format = delta.format;
+ this.setLayerFormat(layerId, delta.format);
tile.dirty = true;
tile.version++;
+ this.markLodAncestorsDirty(layerId, tileX, tileY);
}
}
this.notifyChange();
}
- /**
- * Reset the entire grid.
- */
public clearAll(): void {
+ if (this.memoryManager) {
+ for (const tile of this.tiles.values()) {
+ this.memoryManager.notifyTileFreed(tile);
+ }
+ }
this.tiles.clear();
this.layerFormats.clear();
+ this.ingestedLayers.clear();
+ this.dirtyLodTiles.clear();
+ this.notifyChange(true);
+ }
+
+ public getAllTiles(): TileBuffer[] {
+ return Array.from(this.tiles.values());
+ }
+
+ public getAllLayerFormats(): Map<string, TileFormat> {
+ return new Map(this.layerFormats);
+ }
+
+ public restoreFromSnapshot(tiles: TileBuffer[], layerFormats?: Map<string, TileFormat>): void {
+ this.clearAll();
+ if (layerFormats) {
+ for (const [layerId, fmt] of layerFormats.entries()) {
+ this.layerFormats.set(layerId, fmt);
+ }
+ }
+ for (const tile of tiles) {
+ this.tiles.set(getTileKey(tile.layerId, tile.tileX, tile.tileY, tile.lod ?? 0), tile);
+ if (this.memoryManager) {
+ this.memoryManager.notifyTileAllocated(tile);
+ }
+ }
+ this.notifyChange(true);
}
}
+// ============================================================================
+// Snapshot Serialization
+// ============================================================================
+
const FORMAT_TO_BYTE: Record<TileFormat, number> = {
'monochrome-1bit': 0,
'grayscale-8bit': 1,
@@ -961,15 +2005,163 @@ const BYTE_TO_FORMAT: TileFormat[] = [
'color-32bit',
];
-/**
- * Binary serialization for TileDelta array.
- * Magic header: 0x54, 0x44 ('TD')
- * Version: 1 (uint8)
- * Count: uint32
- */
+export function serializeSparseTileGrid(grid: SparseTileGrid): Uint8Array {
+ const encoder = new TextEncoder();
+ const tiles = grid.getAllTiles().filter((t) => (t.lod ?? 0) === 0);
+ const layerFormats = grid.getAllLayerFormats();
+
+ let totalBytes = 4 + 1 + 4;
+
+ const encodedFormats: Array<{ keyBytes: Uint8Array; format: TileFormat }> = [];
+ for (const [layerId, fmt] of layerFormats.entries()) {
+ const keyBytes = encoder.encode(layerId);
+ encodedFormats.push({ keyBytes, format: fmt });
+ totalBytes += 2 + keyBytes.length + 1;
+ }
+
+ totalBytes += 4;
+
+ const encodedTiles: Array<{ keyBytes: Uint8Array; tile: TileBuffer }> = [];
+ for (let i = 0; i < tiles.length; i++) {
+ const t = tiles[i];
+ const keyBytes = encoder.encode(t.layerId);
+ encodedTiles.push({ keyBytes, tile: t });
+ const dataLen = t.data ? t.data.byteLength : 0;
+ totalBytes += 2 + keyBytes.length + 4 + 4 + 1 + 4 + 4 + dataLen;
+ }
+
+ const out = new Uint8Array(totalBytes);
+ const view = new DataView(out.buffer, out.byteOffset, totalBytes);
+
+ let offset = 0;
+ out[offset++] = 0x49; // 'I'
+ out[offset++] = 0x4e; // 'N'
+ out[offset++] = 0x4b; // 'K'
+ out[offset++] = 0x47; // 'G'
+ out[offset++] = 1; // Version
+
+ view.setUint32(offset, encodedFormats.length, true);
+ offset += 4;
+
+ for (const item of encodedFormats) {
+ view.setUint16(offset, item.keyBytes.length, true);
+ offset += 2;
+ out.set(item.keyBytes, offset);
+ offset += item.keyBytes.length;
+ out[offset++] = FORMAT_TO_BYTE[item.format] ?? 2;
+ }
+
+ view.setUint32(offset, encodedTiles.length, true);
+ offset += 4;
+
+ for (const item of encodedTiles) {
+ const t = item.tile;
+ view.setUint16(offset, item.keyBytes.length, true);
+ offset += 2;
+ out.set(item.keyBytes, offset);
+ offset += item.keyBytes.length;
+
+ view.setInt32(offset, t.tileX, true);
+ offset += 4;
+ view.setInt32(offset, t.tileY, true);
+ offset += 4;
+ out[offset++] = FORMAT_TO_BYTE[t.format] ?? 2;
+ view.setUint32(offset, t.version, true);
+ offset += 4;
+
+ const dataLen = t.data ? t.data.byteLength : 0;
+ view.setUint32(offset, dataLen, true);
+ offset += 4;
+ if (t.data) {
+ out.set(t.data, offset);
+ offset += dataLen;
+ }
+ }
+
+ return out;
+}
+
+export function deserializeSparseTileGrid(grid: SparseTileGrid, buffer: Uint8Array): void {
+ if (buffer.byteLength < 9) {
+ throw new Error('Invalid SparseTileGrid buffer: too short');
+ }
+ if (
+ buffer[0] !== 0x49 ||
+ buffer[1] !== 0x4e ||
+ buffer[2] !== 0x4b ||
+ buffer[3] !== 0x47
+ ) {
+ throw new Error('Invalid SparseTileGrid buffer: bad magic');
+ }
+ const version = buffer[4];
+ if (version !== 1) {
+ throw new Error(`Unsupported SparseTileGrid version: ${version}`);
+ }
+
+ const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
+ const decoder = new TextDecoder();
+ let offset = 5;
+
+ const formatCount = view.getUint32(offset, true);
+ offset += 4;
+
+ const layerFormats = new Map<string, TileFormat>();
+ for (let i = 0; i < formatCount; i++) {
+ const kLen = view.getUint16(offset, true);
+ offset += 2;
+ const kBytes = buffer.subarray(offset, offset + kLen);
+ const layerId = decoder.decode(kBytes);
+ offset += kLen;
+ const fmtByte = buffer[offset++];
+ layerFormats.set(layerId, BYTE_TO_FORMAT[fmtByte] || 'color-32bit');
+ }
+
+ const tileCount = view.getUint32(offset, true);
+ offset += 4;
+
+ const restoredTiles: TileBuffer[] = [];
+ for (let i = 0; i < tileCount; i++) {
+ const kLen = view.getUint16(offset, true);
+ offset += 2;
+ const kBytes = buffer.subarray(offset, offset + kLen);
+ const layerId = decoder.decode(kBytes);
+ offset += kLen;
+
+ const tileX = view.getInt32(offset, true);
+ offset += 4;
+ const tileY = view.getInt32(offset, true);
+ offset += 4;
+ const fmtByte = buffer[offset++];
+ const format = BYTE_TO_FORMAT[fmtByte] || 'color-32bit';
+ const ver = view.getUint32(offset, true);
+ offset += 4;
+
+ const dLen = view.getUint32(offset, true);
+ offset += 4;
+ const data = new Uint8Array(dLen);
+ data.set(buffer.subarray(offset, offset + dLen));
+ offset += dLen;
+
+ restoredTiles.push({
+ layerId,
+ tileX,
+ tileY,
+ format,
+ data,
+ dirty: true,
+ version: ver,
+ isPagedToDisk: false,
+ lastAccessTimestamp: typeof performance !== 'undefined' ? performance.now() : Date.now(),
+ lod: 0,
+ });
+ }
+
+ grid.restoreFromSnapshot(restoredTiles, layerFormats);
+}
+
export function serializeTileDeltas(deltas: TileDelta[]): Uint8Array {
const encoder = new TextEncoder();
- let totalBytes = 2 + 1 + 4; // Magic (2) + Version (1) + Count (4)
+ let totalBytes = 2 + 1 + 4;
const encodedKeys: Uint8Array[] = [];
for (let i = 0; i < deltas.length; i++) {
@@ -977,13 +2169,13 @@ export function serializeTileDeltas(deltas: TileDelta[]): Uint8Array {
const keyBytes = encoder.encode(d.key);
encodedKeys.push(keyBytes);
- totalBytes += 2 + keyBytes.length; // keyLen (2) + bytes
- totalBytes += 1; // format (1)
- totalBytes += 1; // hasBefore (1)
+ totalBytes += 2 + keyBytes.length;
+ totalBytes += 1;
+ totalBytes += 1;
if (d.beforeData && d.beforeData.byteLength > 0) {
totalBytes += 4 + d.beforeData.byteLength;
}
- totalBytes += 1; // hasAfter (1)
+ totalBytes += 1;
if (d.afterData && d.afterData.byteLength > 0) {
totalBytes += 4 + d.afterData.byteLength;
}
@@ -1034,9 +2226,6 @@ export function serializeTileDeltas(deltas: TileDelta[]): Uint8Array {
return out;
}
-/**
- * Binary deserialization for TileDelta array.
- */
export function deserializeTileDeltas(buffer: Uint8Array): TileDelta[] {
if (buffer.byteLength < 7) {
throw new Error('Invalid TileDelta buffer: too short');
@@ -1100,3 +2289,4 @@ export function deserializeTileDeltas(buffer: Uint8Array): TileDelta[] {
// Global sparse tile grid singleton
export const globalTileGrid = new SparseTileGrid();
+export const globalTileMemoryManager = globalTileGrid.getMemoryManager()!;
diff --git a/src/utils/tonalEngine.ts b/src/utils/tonalEngine.ts
index fe80fc8..6338322 100644
--- a/src/utils/tonalEngine.ts
+++ b/src/utils/tonalEngine.ts
@@ -60,6 +60,15 @@ export function createSelectionMask(
): Uint8Array | null {
if (!selection) return null;
+ if (selection.mask && selection.maskWidth === width && selection.maskHeight === height) {
+ const mask = new Uint8Array(width * height);
+ const src = selection.mask;
+ for (let i = 0; i < src.length; i++) {
+ if (src[i] >= 64) mask[i] = 1;
+ }
+ return mask;
+ }
+
const mask = new Uint8Array(width * height);
const { bounds, type, polygon } = selection;
diff --git a/src/utils/undoCache.ts b/src/utils/undoCache.ts
index 45b878e..a1a5eb1 100644
--- a/src/utils/undoCache.ts
+++ b/src/utils/undoCache.ts
@@ -2,9 +2,8 @@
* LRU Tile-Delta Undo/Redo Disk Caching Engine
*
* Designed for 600 DPI professional manga documents (4961 x 7016 px, 70MP double spreads).
- * Instead of keeping dozens of multi-megabyte ImageData frames in V8 heap memory,
- * this engine keeps only the most recent steps in RAM, seamlessly offloading
- * older tile-delta states to high-speed temporary disk storage via Tauri v2 Rust IPC.
+ * Keeps only the most recent steps in RAM, seamlessly offloading older tile-delta states
+ * to temporary disk storage via Tauri v2 Rust IPC or zlib-compressed RAM buffers.
*/
import { zlibSync, unzlibSync } from 'fflate';
@@ -12,6 +11,7 @@ import { TileDelta, HistoryItem } from '../types/editor';
import { serializeTileDeltas, deserializeTileDeltas } from './tileEngine';
export const MAX_RAM_UNDO_STEPS = 15;
+const MAX_DECOMPRESSED_UNDO_BYTES = 128 * 1024 * 1024;
export function isTauriEnvironment(): boolean {
if (typeof window === 'undefined') return false;
@@ -37,7 +37,9 @@ export function decompressTileDeltasPayload(payload: Uint8Array): TileDelta[] {
if (payload.length >= 2 && payload[0] === 0x78) {
try {
const raw = unzlibSync(payload);
- return deserializeTileDeltas(raw);
+ if (raw.byteLength <= MAX_DECOMPRESSED_UNDO_BYTES) {
+ return deserializeTileDeltas(raw);
+ }
} catch {
// Fallback if byte 0 happened to be 0x78 in an uncompressed stream
}
@@ -59,15 +61,34 @@ export class UndoCacheManager {
return this.sessionId;
}
+ /**
+ * Prunes orphaned history IDs evicted by redo branching or the 50-step cap.
+ */
+ private pruneOrphanedIds(allHistory: HistoryItem[]): void {
+ const validIds = new Set<string>();
+ for (let i = 0; i < allHistory.length; i++) {
+ validIds.add(allHistory[i].id);
+ }
+ for (const id of Array.from(this.ramItems)) {
+ if (!validIds.has(id)) this.ramItems.delete(id);
+ }
+ for (const id of Array.from(this.compressedRamCache.keys())) {
+ if (!validIds.has(id)) this.compressedRamCache.delete(id);
+ }
+ for (const id of Array.from(this.diskCachedIds)) {
+ if (!validIds.has(id)) this.diskCachedIds.delete(id);
+ }
+ }
+
/**
* Register a history item and enforce the in-memory LRU budget.
*/
public async registerStep(item: HistoryItem, allHistory: HistoryItem[]): Promise<void> {
+ this.pruneOrphanedIds(allHistory);
if (!item.tileDeltas || item.tileDeltas.length === 0) return;
this.ramItems.add(item.id);
- // If RAM budget is exceeded, offload the oldest in-memory steps to disk or compressed archive
if (this.ramItems.size > MAX_RAM_UNDO_STEPS) {
for (const oldItem of allHistory) {
if (oldItem.id !== item.id && this.ramItems.has(oldItem.id) && oldItem.tileDeltas) {
@@ -104,7 +125,6 @@ export class UndoCacheManager {
}
}
- // Browser / fallback path: store zlib-compressed binary payload (85-95% smaller than raw RGBA)
this.compressedRamCache.set(item.id, compressed);
item.tileDeltas = undefined;
}
@@ -173,6 +193,4 @@ export class UndoCacheManager {
}
}
-// Global default undo cache manager instance
export const globalUndoCache = new UndoCacheManager();
-
diff --git a/src/utils/vectorEngine.ts b/src/utils/vectorEngine.ts
index 958ec0a..22386a7 100644
--- a/src/utils/vectorEngine.ts
+++ b/src/utils/vectorEngine.ts
@@ -32,7 +32,8 @@ export interface IntersectionPoint {
}
/**
- * Catmull-Rom cubic spline interpolation between p1 and p2 using control points p0 and p3.
+ * Centripetal Catmull-Rom cubic spline interpolation between p1 and p2 using control points p0 and p3.
+ * Prevents self-intersecting loops and cusps on uneven knot spacing while preserving monotonic width.
*/
export function evaluateCatmullRom(
p0: VectorKnot,
@@ -41,19 +42,71 @@ export function evaluateCatmullRom(
p3: VectorKnot,
t: number
): VectorKnot {
+ const d01 = Math.hypot(p1.x - p0.x, p1.y - p0.y);
+ const d12 = Math.hypot(p2.x - p1.x, p2.y - p1.y);
+ const d23 = Math.hypot(p3.x - p2.x, p3.y - p2.y);
+
+ const dt0 = Math.max(1e-4, Math.sqrt(d01));
+ const dt1 = Math.max(1e-4, Math.sqrt(d12));
+ const dt2 = Math.max(1e-4, Math.sqrt(d23));
+
+ const t1x = (p2.x - p1.x) / dt1 - (p1.x - p0.x) / dt0 + (p2.x - p0.x) / (dt0 + dt1);
+ const t1y = (p2.y - p1.y) / dt1 - (p1.y - p0.y) / dt0 + (p2.y - p0.y) / (dt0 + dt1);
+ const t2x = (p3.x - p2.x) / dt2 - (p2.x - p1.x) / dt1 + (p3.x - p1.x) / (dt1 + dt2);
+ const t2y = (p3.y - p2.y) / dt2 - (p2.y - p1.y) / dt1 + (p3.y - p1.y) / (dt1 + dt2);
+
+ let dx1 = (t1x * dt1) / 3;
+ let dy1 = (t1y * dt1) / 3;
+ let dx2 = (t2x * dt1) / 3;
+ let dy2 = (t2y * dt1) / 3;
+
+ if (d12 > 1e-3) {
+ const maxHandle = d12 * 0.48;
+ const len1 = Math.hypot(dx1, dy1);
+ if (len1 > maxHandle) {
+ const s = maxHandle / len1;
+ dx1 *= s;
+ dy1 *= s;
+ }
+ const len2 = Math.hypot(dx2, dy2);
+ if (len2 > maxHandle) {
+ const s = maxHandle / len2;
+ dx2 *= s;
+ dy2 *= s;
+ }
+ }
+
+ const c1x = p1.x + dx1;
+ const c1y = p1.y + dy1;
+ const c2x = p2.x - dx2;
+ const c2y = p2.y - dy2;
+
+ const invT = 1.0 - t;
+ const invT2 = invT * invT;
+ const invT3 = invT2 * invT;
const t2 = t * t;
const t3 = t2 * t;
- const f0 = -0.5 * t3 + t2 - 0.5 * t;
- const f1 = 1.5 * t3 - 2.5 * t2 + 1.0;
- const f2 = -1.5 * t3 + 2.0 * t2 + 0.5 * t;
- const f3 = 0.5 * t3 - 0.5 * t2;
+ const a = invT3;
+ const b = 3.0 * invT2 * t;
+ const c = 3.0 * invT * t2;
+ const d = t3;
+
+ const minP = Math.min(p1.pressure, p2.pressure);
+ const maxP = Math.max(p1.pressure, p2.pressure);
+ const c1p = Math.max(minP, Math.min(maxP, p1.pressure + (p2.pressure - p0.pressure) / 6));
+ const c2p = Math.max(minP, Math.min(maxP, p2.pressure - (p3.pressure - p1.pressure) / 6));
+
+ const minW = Math.min(p1.width, p2.width);
+ const maxW = Math.max(p1.width, p2.width);
+ const c1w = Math.max(minW, Math.min(maxW, p1.width + (p2.width - p0.width) / 6));
+ const c2w = Math.max(minW, Math.min(maxW, p2.width - (p3.width - p1.width) / 6));
return {
- x: p0.x * f0 + p1.x * f1 + p2.x * f2 + p3.x * f3,
- y: p0.y * f0 + p1.y * f1 + p2.y * f2 + p3.y * f3,
- pressure: Math.max(0, Math.min(1, p0.pressure * f0 + p1.pressure * f1 + p2.pressure * f2 + p3.pressure * f3)),
- width: Math.max(0.5, p0.width * f0 + p1.width * f1 + p2.width * f2 + p3.width * f3),
+ x: a * p1.x + b * c1x + c * c2x + d * p2.x,
+ y: a * p1.y + b * c1y + c * c2y + d * p2.y,
+ pressure: Math.max(0, Math.min(1, a * p1.pressure + b * c1p + c * c2p + d * p2.pressure)),
+ width: Math.max(0.5, a * p1.width + b * c1w + c * c2w + d * p2.width),
angle: p1.angle,
timestamp: p1.timestamp + (p2.timestamp - p1.timestamp) * t,
};
@@ -76,7 +129,8 @@ export function tessellateStroke(stroke: VectorStroke, stepsPerSegment = 6): Vec
const p2 = knots[i + 1];
const p3 = i + 2 < knots.length ? knots[i + 2] : p2;
- const steps = stepsPerSegment;
+ const chord = Math.hypot(p2.x - p1.x, p2.y - p1.y);
+ const steps = Math.max(stepsPerSegment, Math.min(24, Math.ceil(chord / 3)));
for (let s = 0; s < steps; s++) {
const t = s / steps;
result.push(evaluateCatmullRom(p0, p1, p2, p3, t));
@@ -370,10 +424,27 @@ export function splitStrokeAtIntersection(
const remainingStrokes: VectorStroke[] = [];
+ const interpolateKnotAt = (param: number): VectorKnot => {
+ const idx = Math.max(0, Math.min(targetStroke.knots.length - 2, Math.floor(param)));
+ const frac = Math.max(0, Math.min(1, param - idx));
+ const kA = targetStroke.knots[idx];
+ const kB = targetStroke.knots[idx + 1] || kA;
+ return {
+ x: kA.x + (kB.x - kA.x) * frac,
+ y: kA.y + (kB.y - kA.y) * frac,
+ pressure: kA.pressure + (kB.pressure - kA.pressure) * frac,
+ width: kA.width + (kB.width - kA.width) * frac,
+ timestamp: Math.round(kA.timestamp + (kB.timestamp - kA.timestamp) * frac),
+ };
+ };
+
// Keep part before leftJunction if significant
- if (leftJunction > 0.5) {
+ if (leftJunction > 0.05) {
const leftEndIdx = Math.floor(leftJunction);
const subKnots = targetStroke.knots.slice(0, leftEndIdx + 1);
+ if (leftJunction - leftEndIdx > 0.02) {
+ subKnots.push(interpolateKnotAt(leftJunction));
+ }
if (subKnots.length >= 2) {
remainingStrokes.push({
id: `vstroke-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`,
@@ -389,9 +460,12 @@ export function splitStrokeAtIntersection(
}
// Keep part after rightJunction if significant
- if (rightJunction < targetStroke.knots.length - 1.5) {
+ if (rightJunction < targetStroke.knots.length - 1.05) {
const rightStartIdx = Math.ceil(rightJunction);
const subKnots = targetStroke.knots.slice(rightStartIdx);
+ if (rightStartIdx - rightJunction > 0.02) {
+ subKnots.unshift(interpolateKnotAt(rightJunction));
+ }
if (subKnots.length >= 2) {
remainingStrokes.push({
id: `vstroke-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`,
@@ -606,14 +680,17 @@ export function simplifyPathPoints(knots: VectorKnot[], tolerance = 1.0): Vector
if (lenSq < 1e-9) {
const dX = p.x - p1.x;
const dY = p.y - p1.y;
- sqDist = dX * dX + dY * dY;
+ const dW = (p.width - p1.width) * 0.5;
+ sqDist = dX * dX + dY * dY + dW * dW;
} else {
const t = Math.max(0, Math.min(1, ((p.x - p1.x) * dx + (p.y - p1.y) * dy) / lenSq));
const projX = p1.x + t * dx;
const projY = p1.y + t * dy;
+ const projW = p1.width + t * (p2.width - p1.width);
const dX = p.x - projX;
const dY = p.y - projY;
- sqDist = dX * dX + dY * dY;
+ const dW = (p.width - projW) * 0.5;
+ sqDist = dX * dX + dY * dY + dW * dW;
}
if (sqDist > maxSqDist) {
@@ -868,6 +945,18 @@ export function findNearestVectorStroke(
minDist = d;
closest = { stroke, knotIndex: i, distance: d };
}
+ if (i < stroke.knots.length - 1) {
+ const nextK = stroke.knots[i + 1];
+ const segRes = pointToSegmentDistance(point.x, point.y, k.x, k.y, nextK.x, nextK.y);
+ if (segRes.distance < minDist) {
+ minDist = segRes.distance;
+ closest = {
+ stroke,
+ knotIndex: segRes.t < 0.5 ? i : i + 1,
+ distance: segRes.distance,
+ };
+ }
+ }
}
}
diff --git a/src/utils/webglBrushEngine.ts b/src/utils/webglBrushEngine.ts
index f96fdc4..7838688 100644
--- a/src/utils/webglBrushEngine.ts
+++ b/src/utils/webglBrushEngine.ts
@@ -1,5 +1,7 @@
import { Point, BrushSettings, ToolType } from '../types/editor';
import { applyColorDynamics } from './stampEngine';
+import { paperGrainTable, GRAIN_SIZE } from './pencilEngine';
+import { computeSubpixelDabDimensions, dabHashFloat, resolveTipFlipSigns } from '../engine/CspBrushEngine';
/**
* Information about the host video card powering the WebGL brush engine.
@@ -26,10 +28,12 @@ export interface GpuDab {
alpha: number;
pressure: number;
strokeDist: number;
+ flipX?: number; // +1 or -1
+ flipY?: number; // +1 or -1
}
// -------------------------------------------------------------
-// Shaders for GPU Video Card Execution (Track B: Instanced Dabs)
+// Shaders for GPU Video Card Execution (Track B: Instanced CSP Dabs)
// -------------------------------------------------------------
const VERTEX_SHADER_SRC = `
@@ -43,8 +47,10 @@ attribute vec4 a_color; // dab color rgba
attribute float a_alpha; // dab stamp flow / alpha
attribute float a_pressure; // stylus pressure
attribute float a_strokeDist;// cumulative stroke distance
+attribute vec2 a_flip; // horizontal/vertical UV flip (+1 or -1)
uniform vec2 u_canvasResolution;
+uniform vec2 u_dirtyOffset;
varying vec2 v_uv;
varying vec2 v_localPos;
@@ -53,14 +59,17 @@ varying float v_alpha;
varying float v_pressure;
varying float v_strokeDist;
varying vec2 v_worldPos;
+varying vec2 v_size;
void main() {
- v_uv = a_quadVertex + 0.5;
+ vec2 flipSign = vec2(a_flip.x == 0.0 ? 1.0 : a_flip.x, a_flip.y == 0.0 ? 1.0 : a_flip.y);
+ v_uv = a_quadVertex * flipSign + 0.5;
v_localPos = a_quadVertex * 2.0; // [-1.0, 1.0]
v_color = a_color;
v_alpha = a_alpha;
v_pressure = a_pressure;
v_strokeDist = a_strokeDist;
+ v_size = a_size;
// Rotate quad vertex
float cosA = cos(a_angle);
@@ -74,8 +83,8 @@ void main() {
vec2 worldPixelPos = a_center + rotated;
v_worldPos = worldPixelPos;
- // Convert pixel coordinates [0, W] x [0, H] to WebGL clip space [-1, 1] x [1, -1]
- vec2 clipPos = (worldPixelPos / u_canvasResolution) * 2.0 - 1.0;
+ // Convert local dirty-rect pixel coordinates [0, dirtyW] x [0, dirtyH] to WebGL clip space [-1, 1] x [1, -1]
+ vec2 clipPos = ((worldPixelPos - u_dirtyOffset) / u_canvasResolution) * 2.0 - 1.0;
clipPos.y = -clipPos.y; // Invert Y for canvas coordinate system
gl_Position = vec4(clipPos, 0.0, 1.0);
@@ -92,37 +101,74 @@ varying float v_alpha;
varying float v_pressure;
varying float v_strokeDist;
varying vec2 v_worldPos;
+varying vec2 v_size;
uniform bool u_hasTipTexture;
+uniform bool u_isColorTip;
uniform sampler2D u_tipTexture;
uniform bool u_hasDualTipTexture;
uniform sampler2D u_dualTipTexture;
uniform int u_dualBlendMode; // 0: multiply, 1: subtract, 2: darken, 3: overlay, 4: screen
-uniform float u_hardness; // 0.05 to 1.0
-uniform float u_wetEdge; // 0.0 to 1.0 (CSP Watercolor Water Edge)
-uniform float u_paperGrain; // 0.0 to 1.0 (CSP Paper Tooth)
+uniform int u_antiAlias; // 0: None (binary), 1: Weak, 2: Medium, 3: Strong
+uniform float u_hardness; // 0.0 to 1.0
+uniform float u_wetEdge; // 0.0 to 1.0
+uniform float u_paperGrain; // 0.0 to 1.0 (CSP Paper Tooth density)
uniform float u_grainScale; // scale of paper texture
+uniform float u_grainRotateRad; // rotation of paper texture
+uniform int u_paperMode; // 0: subtract, 1: multiply, 2: compare, 3: overlay, 4: outline
+uniform float u_paperBrightness; // [-1.0, 1.0]
+uniform float u_paperContrast; // [-1.0, 1.0]
+uniform bool u_paperInvert;
+uniform bool u_hasPaperTex;
+uniform sampler2D u_paperTexture;
+uniform vec2 u_paperTexSize;
uniform bool u_colorMixing; // CSP Color Mixing active
uniform bool u_perceptualMixing; // OKLab + Kubelka-Munk spectral pigment mixing
uniform bool u_hasCanvasTexture;
uniform sampler2D u_canvasTexture;
uniform vec2 u_canvasResolution;
-uniform float u_amountOfPaint; // 0.0 to 1.0 (CSP Amount of Paint)
-uniform float u_densityOfPaint; // 0.0 to 1.0 (CSP Density of Paint)
-uniform float u_colorStretch; // 0.0 to 1.0 (CSP Color Stretch)
+uniform vec2 u_docResolution;
+uniform float u_amountOfPaint;
+uniform float u_densityOfPaint;
+uniform float u_colorStretch;
uniform bool u_isEraser;
uniform bool u_isBgEraser;
-// Procedural multi-frequency paper grain tooth
-float getPaperGrain(vec2 p) {
- vec2 coord = p * (0.08 * u_grainScale);
- 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);
- float n3 = sin(coord.x * 15.1 + coord.y * 11.7);
- return clamp((n1 * 0.5 + n2 * 0.35 + n3 * 0.15) * 0.5 + 0.5, 0.0, 1.0);
+// Evaluates seamless paper grain from uploaded 512x512 cold-press texture or custom paper image
+float samplePaperTooth(vec2 worldPos) {
+ float invScale = 1.0 / max(0.05, u_grainScale);
+ float c = cos(u_grainRotateRad);
+ 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);
+ // Support both luminance (R=G=B) and alpha-encoded CSP paper textures
+ float lum = dot(pSample.rgb, vec3(0.299, 0.587, 0.114));
+ g = pSample.a < 0.98 ? (1.0 - pSample.a) : lum;
+ } else {
+ 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 (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);
}
// Perceptual Kubelka-Munk + Spectral Yellow-Blue Pigment Mixing on GPU
@@ -136,7 +182,6 @@ vec3 mixPigmentsGpu(vec3 c1, vec3 c2, float w2) {
vec3 mixAbs = abs1 * w1 + abs2 * w2;
vec3 sub = pow(max(vec3(0.0), vec3(1.0) - mixAbs), vec3(2.0));
- // Spectral Yellow + Blue -> Green transmittance coupling
float y1 = max(0.0, min(l1.r, l1.g) - l1.b);
float y2 = max(0.0, min(l2.r, l2.g) - l2.b);
float b1 = max(0.0, l1.b - l1.r);
@@ -153,19 +198,39 @@ vec3 mixPigmentsGpu(vec3 c1, vec3 c2, float w2) {
void main() {
float dist = length(v_localPos);
- if (dist > 1.0) {
- discard;
- }
+ vec3 rgb = v_color.rgb;
- // 1. Base tip profile and hardness
+ // 1. Base tip profile, CSP 4-level Anti-Aliasing, and Color Tip support
float tipAlpha = 1.0;
if (u_hasTipTexture) {
vec4 tex = texture2D(u_tipTexture, v_uv);
tipAlpha = tex.a;
+ if (u_isColorTip) {
+ rgb = tex.rgb;
+ }
+ if (u_antiAlias == 0) {
+ tipAlpha = tipAlpha >= 0.5 ? 1.0 : 0.0;
+ }
} else {
- // Procedural smooth Hermite profile based on hardness
- float edge = clamp(u_hardness, 0.05, 0.98);
- tipAlpha = 1.0 - smoothstep(edge, 1.0, dist);
+ if (dist > 1.0) {
+ discard;
+ }
+ if (u_antiAlias == 0) {
+ // Binary 1-bit manga pen (zero feather)
+ tipAlpha = dist <= 1.0 ? 1.0 : 0.0;
+ } else {
+ float aaPx = u_antiAlias == 1 ? 1.3 : (u_antiAlias == 3 ? 3.8 : 2.2);
+ float minDim = max(0.85, min(v_size.x, v_size.y));
+ float aa = clamp(aaPx / minDim, 0.015, 0.92);
+ float clampedH = clamp(u_hardness, 0.0, 1.0);
+ if (clampedH <= 0.05) {
+ // Silky Gaussian cosine falloff for soft airbrush
+ tipAlpha = 0.5 * (1.0 + cos(min(1.0, dist) * 3.14159265));
+ } else {
+ float edge = min(clampedH, 1.0 - aa);
+ tipAlpha = 1.0 - smoothstep(edge, 1.0, dist);
+ }
+ }
}
// 1b. Dual-Brush Texture Modulation
@@ -173,15 +238,15 @@ void main() {
vec4 dualTex = texture2D(u_dualTipTexture, v_uv);
float dualA = dualTex.a;
if (u_dualBlendMode == 1) {
- tipAlpha = max(0.0, tipAlpha - (1.0 - dualA)); // subtract
+ tipAlpha = max(0.0, tipAlpha - (1.0 - dualA));
} else if (u_dualBlendMode == 2) {
- tipAlpha = min(tipAlpha, dualA); // darken
+ 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)); // overlay
+ 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; // screen
+ tipAlpha = tipAlpha + dualA - tipAlpha * dualA;
} else {
- tipAlpha *= dualA; // multiply (default)
+ tipAlpha *= dualA;
}
}
@@ -189,28 +254,42 @@ void main() {
discard;
}
- vec3 rgb = v_color.rgb;
-
- // 2. CSP Wet Edge (Water Edge - capillary accumulation at stroke perimeter)
- if (u_wetEdge > 0.001) {
- float rim = smoothstep(0.55, 0.94, dist) * (1.0 - smoothstep(0.95, 1.0, dist));
- float edgeBoost = 1.0 + u_wetEdge * 2.2 * rim;
- tipAlpha = clamp(tipAlpha * edgeBoost, 0.0, 1.0);
- rgb = mix(rgb, rgb * 0.72, u_wetEdge * rim * 0.55);
- }
-
- // 3. CSP Paper Grain / Canvas Tooth
+ // 2. CSP 5-Mode Paper Grain / Canvas Tooth
if (u_paperGrain > 0.001) {
- float tooth = getPaperGrain(v_worldPos);
- float penetration = clamp(v_pressure * 0.75, 0.0, 0.85);
- float grainFactor = clamp(1.0 - u_paperGrain * (1.0 - tooth) * (1.0 - penetration), 0.05, 1.0);
- tipAlpha *= grainFactor;
+ float g = samplePaperTooth(v_worldPos);
+ float penetration = clamp(v_pressure * 0.65, 0.0, 0.85);
+ float effDensity = u_paperGrain * (1.0 - penetration * 0.6);
+
+ if (u_paperMode == 1) {
+ // Multiply
+ tipAlpha *= (1.0 - effDensity * (1.0 - g));
+ } else if (u_paperMode == 2) {
+ // Compare
+ float thresh = (1.0 - g) * effDensity;
+ tipAlpha = tipAlpha > thresh ? clamp((tipAlpha - thresh) / max(0.08, 1.0 - thresh), 0.0, 1.0) : 0.0;
+ } else if (u_paperMode == 3) {
+ // Overlay
+ float ov = tipAlpha < 0.5 ? (2.0 * tipAlpha * g) : (1.0 - 2.0 * (1.0 - tipAlpha) * (1.0 - g));
+ tipAlpha = mix(tipAlpha, ov, effDensity);
+ } else if (u_paperMode == 4) {
+ // Outline
+ float edgeFactor = 4.0 * tipAlpha * (1.0 - tipAlpha);
+ tipAlpha *= (1.0 - effDensity * (1.0 - g) * (0.35 + 0.65 * edgeFactor));
+ } else {
+ // Subtract (CSP default valley-fill physics)
+ float sub = (1.0 - g) * effDensity * (1.0 - penetration * 0.5);
+ tipAlpha = max(0.0, tipAlpha - sub);
+ }
+
+ if (tipAlpha <= 0.002) {
+ discard;
+ }
}
- // 4. CSP Color Mixing & Smear
+ // 3. Optional GPU Color Mixing fallback
if (u_colorMixing && u_hasCanvasTexture && !u_isEraser) {
- vec2 canvasUv = v_worldPos / u_canvasResolution;
- canvasUv.y = 1.0 - canvasUv.y;
+ vec2 docRes = max(vec2(1.0), u_docResolution);
+ vec2 canvasUv = clamp(v_worldPos / docRes, 0.0, 1.0);
vec4 canvasColor = texture2D(u_canvasTexture, canvasUv);
if (canvasColor.a > 0.02) {
@@ -226,11 +305,15 @@ void main() {
}
}
- // 5. Final Alpha computation
+ // 4. Final Alpha computation
float finalAlpha = clamp(tipAlpha * v_alpha, 0.0, 1.0);
+ if (u_antiAlias == 0) {
+ finalAlpha = finalAlpha >= 0.5 ? 1.0 : 0.0;
+ if (finalAlpha <= 0.0) discard;
+ }
if (u_isBgEraser) {
- gl_FragColor = vec4(1.0, 1.0, 1.0, finalAlpha);
+ gl_FragColor = vec4(1.0 * finalAlpha, 1.0 * finalAlpha, 1.0 * finalAlpha, finalAlpha);
} else if (u_isEraser) {
gl_FragColor = vec4(0.0, 0.0, 0.0, finalAlpha);
} else {
@@ -242,18 +325,18 @@ void main() {
// -------------------------------------------------------------
// Shaders for Track A: Ribbon Inking Engine (G-Pen / Manga Lines)
-// Continuous polygonal triangle strip with analytical distance field SDF
// -------------------------------------------------------------
const RIBBON_VERTEX_SHADER_SRC = `
precision highp float;
-attribute vec2 a_pos; // world pixel position
-attribute float a_normalDist;// -1.0 for left, +1.0 for right
-attribute vec4 a_color; // rgba
-attribute float a_width; // pixel width
+attribute vec2 a_pos;
+attribute float a_normalDist;
+attribute vec4 a_color;
+attribute float a_width;
uniform vec2 u_canvasResolution;
+uniform vec2 u_dirtyOffset;
varying float v_normalDist;
varying vec4 v_color;
@@ -264,8 +347,8 @@ void main() {
v_color = a_color;
v_width = a_width;
- vec2 clipPos = (a_pos / u_canvasResolution) * 2.0 - 1.0;
- clipPos.y = -clipPos.y; // Invert Y for canvas coordinate system
+ vec2 clipPos = ((a_pos - u_dirtyOffset) / u_canvasResolution) * 2.0 - 1.0;
+ clipPos.y = -clipPos.y;
gl_Position = vec4(clipPos, 0.0, 1.0);
}
@@ -280,7 +363,6 @@ varying float v_width;
void main() {
float dist = abs(v_normalDist);
- // Analytical SDF sub-pixel antialiasing
float aa = clamp(1.5 / max(1.0, v_width), 0.015, 0.45);
float alpha = 1.0 - smoothstep(1.0 - aa, 1.0, dist);
@@ -293,15 +375,18 @@ void main() {
}
`;
+const MAX_TILE_CHUNK = 2048;
+
/**
* WebGL-accelerated GPU brush engine.
- * Computes all cutting-edge CSP brush mathematics directly on the video card!
+ * Executes authentic Clip Studio Paint brush mathematics on the GPU with zero per-call driver queries.
*/
export class WebGlBrushEngine {
private static instance: WebGlBrushEngine | null = null;
private canvas: HTMLCanvasElement | null = null;
private gl: WebGLRenderingContext | WebGL2RenderingContext | null = null;
+ private isWebGl2 = false;
private program: WebGLProgram | null = null;
private ribbonProgram: WebGLProgram | null = null;
private isGpuAvailable = false;
@@ -312,17 +397,40 @@ export class WebGlBrushEngine {
glVersion: 'None',
};
- // Uniform locations (Instanced Stamp)
+ // Cached Attribute Locations (Instanced Dab) — zero getAttribLocation calls during draw!
+ private aQuadVertexLoc: number = -1;
+ private aCenterLoc: number = -1;
+ private aSizeLoc: number = -1;
+ private aAngleLoc: number = -1;
+ private aColorLoc: number = -1;
+ private aAlphaLoc: number = -1;
+ private aPressureLoc: number = -1;
+ private aStrokeDistLoc: number = -1;
+ private aFlipLoc: number = -1;
+
+ // Cached Uniform Locations (Instanced Dab)
private uCanvasResolutionLoc: WebGLUniformLocation | null = null;
+ private uDocResolutionLoc: WebGLUniformLocation | null = null;
+ private uDirtyOffsetLoc: WebGLUniformLocation | null = null;
private uHasTipTextureLoc: WebGLUniformLocation | null = null;
+ private uIsColorTipLoc: WebGLUniformLocation | null = null;
private uTipTextureLoc: WebGLUniformLocation | null = null;
private uHasDualTipTextureLoc: WebGLUniformLocation | null = null;
private uDualTipTextureLoc: WebGLUniformLocation | null = null;
private uDualBlendModeLoc: WebGLUniformLocation | null = null;
+ private uAntiAliasLoc: WebGLUniformLocation | null = null;
private uHardnessLoc: WebGLUniformLocation | null = null;
private uWetEdgeLoc: WebGLUniformLocation | null = null;
private uPaperGrainLoc: WebGLUniformLocation | null = null;
private uGrainScaleLoc: WebGLUniformLocation | null = null;
+ private uGrainRotateRadLoc: WebGLUniformLocation | null = null;
+ private uPaperModeLoc: WebGLUniformLocation | null = null;
+ private uPaperBrightnessLoc: WebGLUniformLocation | null = null;
+ private uPaperContrastLoc: WebGLUniformLocation | null = null;
+ private uPaperInvertLoc: 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 uHasCanvasTextureLoc: WebGLUniformLocation | null = null;
@@ -333,8 +441,9 @@ export class WebGlBrushEngine {
private uIsEraserLoc: WebGLUniformLocation | null = null;
private uIsBgEraserLoc: WebGLUniformLocation | null = null;
- // Uniform locations (Ribbon Mesh)
+ // Cached Locations (Ribbon Mesh)
private uRibbonCanvasResolutionLoc: WebGLUniformLocation | null = null;
+ private uRibbonDirtyOffsetLoc: WebGLUniformLocation | null = null;
private aRibbonPosLoc: number = -1;
private aRibbonNormalDistLoc: number = -1;
private aRibbonColorLoc: number = -1;
@@ -342,26 +451,41 @@ export class WebGlBrushEngine {
// Textures cache
private tipTexturesMap = new Map<string, WebGLTexture>();
+ private builtinPaperTexture: WebGLTexture | null = null;
private canvasLayerTexture: WebGLTexture | null = null;
- // Dab geometry & instancing buffers
+ // Dab geometry & instancing buffers (stride 14 floats)
private quadVertexBuffer: WebGLBuffer | null = null;
private extInstanced: {
drawArraysInstanced: (mode: number, first: number, count: number, instanceCount: number) => void;
vertexAttribDivisor: (index: number, divisor: number) => void;
} | null = null;
+ private extMinMax: { MAX_EXT: number } | null = null;
private instanceBuffer: WebGLBuffer | null = null;
- private instanceArray: Float32Array = new Float32Array(4096 * 12);
+ private instanceArray: Float32Array = new Float32Array(4096 * 14);
- // Ribbon geometry buffers (stride 8: x, y, normalDist, width, r, g, b, a)
+ // Ribbon geometry buffers (stride 8)
private ribbonBuffer: WebGLBuffer | null = null;
private ribbonArray: Float32Array = new Float32Array(1024 * 8);
private constructor() {
if (typeof document !== 'undefined') {
- this.canvas = document.createElement('canvas');
- this.canvas.width = 1024;
- this.canvas.height = 1024;
+ const c = document.createElement('canvas');
+ c.width = 1024;
+ c.height = 1024;
+ this.canvas = c;
+ if (typeof c.addEventListener === 'function') {
+ c.addEventListener('webglcontextlost', (ev) => {
+ ev.preventDefault();
+ this.isGpuAvailable = false;
+ this.tipTexturesMap.clear();
+ this.builtinPaperTexture = null;
+ this.canvasLayerTexture = null;
+ });
+ c.addEventListener('webglcontextrestored', () => {
+ this.initGl();
+ });
+ }
this.initGl();
}
}
@@ -373,18 +497,15 @@ export class WebGlBrushEngine {
return WebGlBrushEngine.instance;
}
- /**
- * Initializes the WebGL context and GPU shader programs.
- */
private initGl() {
- if (!this.canvas) {
+ if (!this.canvas || typeof this.canvas.getContext !== 'function') {
this.isGpuAvailable = false;
return;
}
try {
const glOpts: WebGLContextAttributes = {
alpha: true,
- antialias: true,
+ antialias: false,
depth: false,
stencil: false,
premultipliedAlpha: true,
@@ -392,7 +513,8 @@ export class WebGlBrushEngine {
powerPreference: 'high-performance',
};
- const gl = (this.canvas.getContext('webgl2', glOpts) ||
+ const gl2 = this.canvas.getContext('webgl2', glOpts) as WebGL2RenderingContext | null;
+ const gl = (gl2 ||
this.canvas.getContext('webgl', glOpts) ||
this.canvas.getContext('experimental-webgl', glOpts)) as WebGLRenderingContext | null;
@@ -402,8 +524,8 @@ export class WebGlBrushEngine {
}
this.gl = gl;
+ this.isWebGl2 = Boolean(gl2 && 'MAX' in gl2);
- // Query host video card information
let renderer = 'Generic WebGL GPU';
let vendor = 'Generic';
if (typeof gl.getExtension === 'function') {
@@ -412,6 +534,9 @@ export class WebGlBrushEngine {
renderer = gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) || renderer;
vendor = gl.getParameter(ext.UNMASKED_VENDOR_WEBGL) || vendor;
}
+ if (!this.isWebGl2) {
+ this.extMinMax = gl.getExtension('EXT_blend_minmax') as any;
+ }
}
const glVersion = (typeof gl.getParameter === 'function' && gl.getParameter(gl.VERSION)) || 'WebGL';
@@ -434,16 +559,40 @@ export class WebGlBrushEngine {
gl.linkProgram(program);
if (gl.getProgramParameter(program, gl.LINK_STATUS)) {
this.program = program;
+ // Cache ALL attribute locations once at link time
+ this.aQuadVertexLoc = gl.getAttribLocation(program, 'a_quadVertex');
+ this.aCenterLoc = gl.getAttribLocation(program, 'a_center');
+ this.aSizeLoc = gl.getAttribLocation(program, 'a_size');
+ this.aAngleLoc = gl.getAttribLocation(program, 'a_angle');
+ this.aColorLoc = gl.getAttribLocation(program, 'a_color');
+ this.aAlphaLoc = gl.getAttribLocation(program, 'a_alpha');
+ this.aPressureLoc = gl.getAttribLocation(program, 'a_pressure');
+ this.aStrokeDistLoc = gl.getAttribLocation(program, 'a_strokeDist');
+ this.aFlipLoc = gl.getAttribLocation(program, 'a_flip');
+
+ // Cache ALL uniform locations once at link time
this.uCanvasResolutionLoc = gl.getUniformLocation(program, 'u_canvasResolution');
+ this.uDocResolutionLoc = gl.getUniformLocation(program, 'u_docResolution');
+ this.uDirtyOffsetLoc = gl.getUniformLocation(program, 'u_dirtyOffset');
this.uHasTipTextureLoc = gl.getUniformLocation(program, 'u_hasTipTexture');
+ this.uIsColorTipLoc = gl.getUniformLocation(program, 'u_isColorTip');
this.uTipTextureLoc = gl.getUniformLocation(program, 'u_tipTexture');
this.uHasDualTipTextureLoc = gl.getUniformLocation(program, 'u_hasDualTipTexture');
this.uDualTipTextureLoc = gl.getUniformLocation(program, 'u_dualTipTexture');
this.uDualBlendModeLoc = gl.getUniformLocation(program, 'u_dualBlendMode');
+ this.uAntiAliasLoc = gl.getUniformLocation(program, 'u_antiAlias');
this.uHardnessLoc = gl.getUniformLocation(program, 'u_hardness');
this.uWetEdgeLoc = gl.getUniformLocation(program, 'u_wetEdge');
this.uPaperGrainLoc = gl.getUniformLocation(program, 'u_paperGrain');
this.uGrainScaleLoc = gl.getUniformLocation(program, 'u_grainScale');
+ this.uGrainRotateRadLoc = gl.getUniformLocation(program, 'u_grainRotateRad');
+ this.uPaperModeLoc = gl.getUniformLocation(program, 'u_paperMode');
+ this.uPaperBrightnessLoc = gl.getUniformLocation(program, 'u_paperBrightness');
+ this.uPaperContrastLoc = gl.getUniformLocation(program, 'u_paperContrast');
+ this.uPaperInvertLoc = gl.getUniformLocation(program, 'u_paperInvert');
+ 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.uHasCanvasTextureLoc = gl.getUniformLocation(program, 'u_hasCanvasTexture');
@@ -470,6 +619,7 @@ export class WebGlBrushEngine {
if (gl.getProgramParameter(rProgram, gl.LINK_STATUS)) {
this.ribbonProgram = rProgram;
this.uRibbonCanvasResolutionLoc = gl.getUniformLocation(rProgram, 'u_canvasResolution');
+ this.uRibbonDirtyOffsetLoc = gl.getUniformLocation(rProgram, 'u_dirtyOffset');
this.aRibbonPosLoc = gl.getAttribLocation(rProgram, 'a_pos');
this.aRibbonNormalDistLoc = gl.getAttribLocation(rProgram, 'a_normalDist');
this.aRibbonColorLoc = gl.getAttribLocation(rProgram, 'a_color');
@@ -478,7 +628,7 @@ export class WebGlBrushEngine {
}
}
- // Create static quad vertex buffer: two triangles forming [-0.5, 0.5] quad
+ // Static quad vertex buffer
const quadVertices = new Float32Array([
-0.5, -0.5,
0.5, -0.5,
@@ -491,10 +641,9 @@ export class WebGlBrushEngine {
gl.bindBuffer(gl.ARRAY_BUFFER, this.quadVertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, quadVertices, gl.STATIC_DRAW);
- // Create ribbon dynamic vertex buffer
this.ribbonBuffer = gl.createBuffer();
- // Initialize hardware instanced array support
+ // Hardware instanced array support
if ('drawArraysInstanced' in gl) {
this.extInstanced = {
drawArraysInstanced: (mode: number, first: number, count: number, instanceCount: number) => {
@@ -519,7 +668,9 @@ export class WebGlBrushEngine {
}
this.instanceBuffer = gl.createBuffer();
- // Configure standard alpha blending
+ // Upload seamless 512x512 cold-press paper grain texture once at startup
+ this.uploadBuiltinPaperTexture(gl);
+
gl.enable(gl.BLEND);
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
@@ -529,6 +680,36 @@ export class WebGlBrushEngine {
}
}
+ private uploadBuiltinPaperTexture(gl: WebGLRenderingContext): void {
+ try {
+ const tex = gl.createTexture();
+ if (!tex) return;
+ gl.bindTexture(gl.TEXTURE_2D, tex);
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
+ // Expand 1-channel 512x512 paperGrainTable to LUMINANCE for WebGL1+2 universal compatibility
+ gl.texImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.LUMINANCE,
+ GRAIN_SIZE,
+ GRAIN_SIZE,
+ 0,
+ gl.LUMINANCE,
+ gl.UNSIGNED_BYTE,
+ paperGrainTable
+ );
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
+ this.builtinPaperTexture = tex;
+ } catch {
+ this.builtinPaperTexture = null;
+ }
+ }
+
private compileShader(type: number, src: string): WebGLShader | null {
if (!this.gl) return null;
const shader = this.gl.createShader(type);
@@ -547,36 +728,48 @@ export class WebGlBrushEngine {
}
public isAvailable(): boolean {
- return this.isGpuAvailable && this.gl !== null;
+ if (!this.isGpuAvailable || !this.gl) return false;
+ if (typeof this.gl.isContextLost === 'function' && this.gl.isContextLost()) {
+ this.isGpuAvailable = false;
+ return false;
+ }
+ return true;
}
/**
- * Retrieves or uploads a brush tip texture to GPU memory.
+ * Retrieves or uploads a brush tip or paper texture to GPU memory.
*/
- public getOrCreateTipTexture(image: HTMLImageElement): WebGLTexture | null {
+ public getOrCreateTipTexture(image: HTMLImageElement, repeatWrap: boolean = false): WebGLTexture | null {
if (!this.gl || !image || !image.src) return null;
- const cached = this.tipTexturesMap.get(image.src);
+ const cacheKey = `${repeatWrap ? 'rep:' : 'tip:'}${image.src}`;
+ const cached = this.tipTexturesMap.get(cacheKey);
if (cached) return cached;
const gl = this.gl;
+ if (this.tipTexturesMap.size >= 64) {
+ const oldestKey = this.tipTexturesMap.keys().next().value;
+ if (oldestKey) {
+ const oldTex = this.tipTexturesMap.get(oldestKey);
+ if (oldTex) gl.deleteTexture(oldTex);
+ this.tipTexturesMap.delete(oldestKey);
+ }
+ }
const tex = gl.createTexture();
if (!tex) return null;
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);
- 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);
+ 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);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- this.tipTexturesMap.set(image.src, tex);
+ this.tipTexturesMap.set(cacheKey, tex);
return tex;
}
- /**
- * Synchronizes underlying canvas layer texture for real-time CSP color mixing.
- */
public uploadCanvasTexture(sourceCanvas: HTMLCanvasElement): WebGLTexture | null {
if (!this.gl) return null;
const gl = this.gl;
@@ -598,9 +791,6 @@ export class WebGlBrushEngine {
return tex;
}
- /**
- * Parses hex or rgb color string into normalized RGB [0, 1].
- */
public parseColor(color: string): { r: number; g: number; b: number } {
if (color.startsWith('#')) {
let hex = color.slice(1);
@@ -614,13 +804,22 @@ export class WebGlBrushEngine {
b: (num & 255) / 255,
};
}
+ if (color.startsWith('rgb')) {
+ const m = color.match(/\(([^)]+)\)/);
+ if (m) {
+ const parts = m[1].split(',');
+ return {
+ r: (parseFloat(parts[0]) || 0) / 255,
+ g: (parseFloat(parts[1]) || 0) / 255,
+ b: (parseFloat(parts[2]) || 0) / 255,
+ };
+ }
+ }
return { r: 0.1, g: 0.1, b: 0.1 };
}
/**
- * Track A: Ribbon Inking Engine (G-Pen, Manga Inking, Clean Vector/Raster Lines)
- * Evaluates spline into continuous polygonal triangle strip (gl.TRIANGLE_STRIP)
- * with normal extrusion and analytical distance field (SDF) antialiasing.
+ * Track A: Ribbon Inking Engine
*/
public renderRibbonSegment(
targetCtx: CanvasRenderingContext2D,
@@ -630,8 +829,8 @@ export class WebGlBrushEngine {
p3: Point,
color: string,
opacity: number = 1.0,
- canvasWidth: number,
- canvasHeight: number,
+ _canvasWidth: number,
+ _canvasHeight: number,
isEraser: boolean = false,
isBgEraser: boolean = false
): boolean {
@@ -645,7 +844,6 @@ export class WebGlBrushEngine {
const avgW = Math.max(0.5, (p0.width + p3.width) * 0.5);
const steps = Math.max(8, Math.min(48, Math.ceil(chord / Math.max(1.0, avgW * 0.25))));
- // Stride 8: [x, y, normalDist, width, r, g, b, a]
const vertexCount = (steps + 1) * 2;
const requiredFloats = vertexCount * 8;
if (this.ribbonArray.length < requiredFloats) {
@@ -666,11 +864,9 @@ export class WebGlBrushEngine {
const t = i / steps;
const it = 1 - t;
- // Position along cubic Bézier
const px = it * it * it * p0.x + 3 * it * it * t * c1.x + 3 * it * t * t * c2.x + t * t * t * p3.x;
const py = it * it * it * p0.y + 3 * it * it * t * c1.y + 3 * it * t * t * c2.y + t * t * t * p3.y;
- // Derivative (tangent)
const dpx = 3 * it * it * (c1.x - p0.x) + 6 * it * t * (c2.x - c1.x) + 3 * t * t * (p3.x - c2.x);
const dpy = 3 * it * it * (c1.y - p0.y) + 6 * it * t * (c2.y - c1.y) + 3 * t * t * (p3.y - c2.y);
const speed = Math.hypot(dpx, dpy);
@@ -682,24 +878,19 @@ export class WebGlBrushEngine {
ny = dpx / speed;
}
- // Interpolated stroke width
const w = Math.max(0.5, p0.width + (p3.width - p0.width) * t);
const halfW = w * 0.5;
- // Left vertex
const lx = px + nx * halfW;
const ly = py + ny * halfW;
- // Right vertex
const rx = px - nx * halfW;
const ry = py - ny * halfW;
- // Update dirty bounding box
minX = Math.min(minX, lx, rx);
minY = Math.min(minY, ly, ry);
maxX = Math.max(maxX, lx, rx);
maxY = Math.max(maxY, ly, ry);
- // Left vertex (normalDist = -1.0)
arr[vIdx++] = lx;
arr[vIdx++] = ly;
arr[vIdx++] = -1.0;
@@ -709,7 +900,6 @@ export class WebGlBrushEngine {
arr[vIdx++] = rgb.b;
arr[vIdx++] = alpha;
- // Right vertex (normalDist = +1.0)
arr[vIdx++] = rx;
arr[vIdx++] = ry;
arr[vIdx++] = 1.0;
@@ -721,31 +911,34 @@ export class WebGlBrushEngine {
}
const pad = 4;
- const sx = Math.max(0, Math.floor(minX - pad));
- const sy = Math.max(0, Math.floor(minY - pad));
- const ex = Math.min(canvasWidth, Math.ceil(maxX + pad));
- const ey = Math.min(canvasHeight, Math.ceil(maxY + pad));
- const dw = ex - sx;
- const dh = ey - sy;
+ const sx = Math.floor(minX - pad);
+ const sy = Math.floor(minY - pad);
+ const ex = Math.ceil(maxX + pad);
+ const ey = Math.ceil(maxY + pad);
+ const dw = Math.min(4096, Math.max(0, ex - sx));
+ const dh = Math.min(4096, Math.max(0, ey - sy));
if (dw <= 0 || dh <= 0) return false;
- // Resize GPU canvas if needed
- if (canvas.width !== canvasWidth || canvas.height !== canvasHeight) {
- canvas.width = canvasWidth;
- canvas.height = canvasHeight;
+ if (canvas.width < dw || canvas.height < dh) {
+ canvas.width = Math.max(canvas.width, dw, 512);
+ canvas.height = Math.max(canvas.height, dh, 512);
}
- gl.viewport(0, 0, canvasWidth, canvasHeight);
+ const viewY = Math.max(0, canvas.height - dh);
+ gl.viewport(0, viewY, dw, dh);
if (typeof gl.scissor === 'function') {
gl.enable(gl.SCISSOR_TEST);
- gl.scissor(sx, Math.max(0, canvasHeight - ey), dw, dh);
+ gl.scissor(0, viewY, dw, dh);
}
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.useProgram(this.ribbonProgram);
- gl.uniform2f(this.uRibbonCanvasResolutionLoc, canvasWidth, canvasHeight);
+ gl.uniform2f(this.uRibbonCanvasResolutionLoc, dw, dh);
+ if (this.uRibbonDirtyOffsetLoc) {
+ gl.uniform2f(this.uRibbonDirtyOffsetLoc, sx, sy);
+ }
gl.bindBuffer(gl.ARRAY_BUFFER, this.ribbonBuffer);
gl.bufferData(gl.ARRAY_BUFFER, arr.subarray(0, requiredFloats), gl.DYNAMIC_DRAW);
@@ -763,7 +956,6 @@ export class WebGlBrushEngine {
gl.enableVertexAttribArray(this.aRibbonColorLoc);
gl.vertexAttribPointer(this.aRibbonColorLoc, 4, gl.FLOAT, false, byteStride, 4 * 4);
- // Render continuous triangle strip
gl.drawArrays(gl.TRIANGLE_STRIP, 0, vertexCount);
if (typeof gl.scissor === 'function') {
@@ -775,33 +967,27 @@ export class WebGlBrushEngine {
gl.disableVertexAttribArray(this.aRibbonWidthLoc);
gl.disableVertexAttribArray(this.aRibbonColorLoc);
- // Blit hardware GPU dirty rect onto target context
targetCtx.save();
- if (isBgEraser) {
- targetCtx.globalCompositeOperation = 'source-over';
- } else if (isEraser) {
- targetCtx.globalCompositeOperation = 'destination-out';
- } else {
- targetCtx.globalCompositeOperation = 'source-over';
- }
+ targetCtx.globalCompositeOperation = isBgEraser ? 'source-over' : (isEraser ? 'destination-out' : 'source-over');
targetCtx.globalAlpha = 1.0;
- targetCtx.drawImage(canvas, sx, sy, dw, dh, sx, sy, dw, dh);
+ targetCtx.drawImage(canvas, 0, 0, dw, dh, sx, sy, dw, dh);
targetCtx.restore();
return true;
}
/**
- * Track B: GPU Instanced Stamp Engine (Pencils, Dry Brushes, Textured Tips)
- * Batches thousands of textured dabs into a single GPU draw call per frame.
+ * Track B: GPU Instanced CSP Stamp Engine
+ * Supports unlimited document sizes (>4096px via automatic tile chunking),
+ * translated offscreen bake canvases, CSP 4-level AA, 5-mode paper tooth, and Compare-Density wash!
*/
public renderDabsToContext(
targetCtx: CanvasRenderingContext2D,
dabs: GpuDab[],
- settings: BrushSettings,
+ settings: BrushSettings & { alphaLocked?: boolean },
tool: ToolType,
- canvasWidth: number,
- canvasHeight: number,
+ _canvasWidth: number,
+ _canvasHeight: number,
underlyingCanvas?: HTMLCanvasElement
): boolean {
const canvas = this.canvas;
@@ -810,8 +996,10 @@ export class WebGlBrushEngine {
}
const gl = this.gl;
- const isEraser = tool === 'eraser';
- const isBgEraser = isEraser && targetCtx.fillStyle === '#ffffff';
+ const isTransparentInk = Boolean(settings.isTransparentInk);
+ const isEraser = tool === 'eraser' || isTransparentInk;
+ const isBgEraser = tool === 'eraser' && targetCtx.fillStyle === '#ffffff';
+ const isAlphaLocked = Boolean(settings.alphaLocked);
let minX = Infinity;
let minY = Infinity;
@@ -827,59 +1015,142 @@ export class WebGlBrushEngine {
if (d.y + rad > maxY) maxY = d.y + rad;
}
- const dirtyX = Math.max(0, Math.floor(minX));
- const dirtyY = Math.max(0, Math.floor(minY));
- const dirtyMaxX = Math.min(canvasWidth, Math.ceil(maxX));
- const dirtyMaxY = Math.min(canvasHeight, Math.ceil(maxY));
- const dirtyW = Math.max(0, dirtyMaxX - dirtyX);
- const dirtyH = Math.max(0, dirtyMaxY - dirtyY);
+ 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 (dirtyW <= 0 || dirtyH <= 0) {
+ if (totalW <= 0 || totalH <= 0) {
return false;
}
- // Resize GPU canvas if needed
- if (canvas.width !== canvasWidth || canvas.height !== canvasHeight) {
- canvas.width = canvasWidth;
- canvas.height = canvasHeight;
+ // Pack instance buffer once across all dabs (stride 14 floats)
+ const stride = 14;
+ const requiredFloats = dabs.length * stride;
+ if (this.instanceArray.length < requiredFloats) {
+ this.instanceArray = new Float32Array(Math.max(requiredFloats, this.instanceArray.length * 2));
}
+ const arr = this.instanceArray;
+ const aaMode = settings.antiAlias ?? 2;
+ const minRenderDim = aaMode === 0 ? 1.0 : 0.75;
- gl.viewport(0, 0, canvasWidth, canvasHeight);
- if (typeof gl.scissor === 'function') {
- gl.enable(gl.SCISSOR_TEST);
- gl.scissor(dirtyX, Math.max(0, canvasHeight - dirtyMaxY), dirtyW, dirtyH);
+ for (let i = 0; i < dabs.length; i++) {
+ const d = dabs[i];
+ const sub = computeSubpixelDabDimensions(d.width, d.height, d.alpha, minRenderDim);
+ const offset = i * stride;
+ arr[offset + 0] = d.x;
+ arr[offset + 1] = d.y;
+ arr[offset + 2] = sub.renderW;
+ arr[offset + 3] = sub.renderH;
+ arr[offset + 4] = d.angle;
+ arr[offset + 5] = d.r;
+ arr[offset + 6] = d.g;
+ arr[offset + 7] = d.b;
+ arr[offset + 8] = 1.0;
+ arr[offset + 9] = sub.effAlpha;
+ arr[offset + 10] = d.pressure;
+ arr[offset + 11] = d.strokeDist;
+ arr[offset + 12] = d.flipX ?? 1.0;
+ arr[offset + 13] = d.flipY ?? 1.0;
+ }
+
+ if (this.instanceBuffer) {
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.instanceBuffer);
+ gl.bufferData(gl.ARRAY_BUFFER, arr.subarray(0, requiredFloats), gl.DYNAMIC_DRAW);
}
- gl.clearColor(0, 0, 0, 0);
- gl.clear(gl.COLOR_BUFFER_BIT);
gl.useProgram(this.program);
- gl.uniform2f(this.uCanvasResolutionLoc, canvasWidth, canvasHeight);
+ // Configure Blend Equation (Compare Density / Darken tips uses MAX alpha so washes never over-darken!)
+ const useCompareTips = settings.blendTipsMode === 'compare' || settings.blendTipsMode === 'darken';
+ if (useCompareTips && (this.isWebGl2 || this.extMinMax)) {
+ const maxEnum = this.isWebGl2 ? (gl as WebGL2RenderingContext).MAX : this.extMinMax!.MAX_EXT;
+ gl.blendEquationSeparate(gl.FUNC_ADD, maxEnum);
+ gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, 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);
- gl.uniform1f(this.uPaperGrainLoc, settings.grain ?? (settings.textureDensity ?? 0.0));
+
+ const paperDensity = settings.grain ?? (settings.textureDensity ?? 0.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 pMode =
+ settings.paperTextureMode === 'multiply'
+ ? 1
+ : settings.paperTextureMode === 'compare'
+ ? 2
+ : settings.paperTextureMode === 'overlay'
+ ? 3
+ : settings.paperTextureMode === 'outline'
+ ? 4
+ : 0; // subtract default
+ 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);
gl.uniform1i(this.uIsEraserLoc, isEraser ? 1 : 0);
gl.uniform1i(this.uIsBgEraserLoc, isBgEraser ? 1 : 0);
+ // Bind Paper Texture (custom paper image or built-in 512x512 cold-press grain)
+ if (paperDensity > 0.001) {
+ let paperTex: WebGLTexture | null = null;
+ let paperW = GRAIN_SIZE;
+ let paperH = GRAIN_SIZE;
+ if (settings.paperTextureImage && (settings.paperTextureImage.naturalWidth || settings.paperTextureImage.width)) {
+ paperTex = this.getOrCreateTipTexture(settings.paperTextureImage, true);
+ paperW = settings.paperTextureImage.naturalWidth || settings.paperTextureImage.width || GRAIN_SIZE;
+ paperH = settings.paperTextureImage.naturalHeight || settings.paperTextureImage.height || GRAIN_SIZE;
+ } 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);
+ }
+
// Primary Tip Texture
let tipTex: WebGLTexture | null = null;
if (settings.customTipImage) {
- tipTex = this.getOrCreateTipTexture(settings.customTipImage);
+ tipTex = this.getOrCreateTipTexture(settings.customTipImage, false);
}
+ const isColorTip = Boolean(settings.isColorTip || (settings.subTips && settings.subTips[0]?.isColor));
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);
} else {
gl.uniform1i(this.uHasTipTextureLoc, 0);
+ gl.uniform1i(this.uIsColorTipLoc, 0);
}
- // Dual-Brush Tip Texture Modulation
+ // Dual-Brush Tip Texture
let dualTipTex: WebGLTexture | null = null;
if (settings.dualBrush && settings.dualTipImage) {
- dualTipTex = this.getOrCreateTipTexture(settings.dualTipImage);
+ dualTipTex = this.getOrCreateTipTexture(settings.dualTipImage, false);
}
if (dualTipTex) {
gl.activeTexture(gl.TEXTURE2);
@@ -901,7 +1172,7 @@ export class WebGlBrushEngine {
gl.uniform1i(this.uHasDualTipTextureLoc, 0);
}
- // Color Mixing (OKLab + Kubelka-Munk perceptual pigment mixing by default)
+ // Optional GPU Color Mixing
const enableColorMix = Boolean(settings.colorMixing) && underlyingCanvas !== undefined;
gl.uniform1i(this.uColorMixingLoc, enableColorMix ? 1 : 0);
gl.uniform1i(this.uPerceptualMixingLoc, settings.perceptualMixing !== false ? 1 : 0);
@@ -923,128 +1194,154 @@ export class WebGlBrushEngine {
gl.uniform1i(this.uHasCanvasTextureLoc, 0);
}
- const aQuadVertexLoc = gl.getAttribLocation(this.program, 'a_quadVertex');
+ // Setup vertex attributes once across tile chunks
gl.bindBuffer(gl.ARRAY_BUFFER, this.quadVertexBuffer);
- gl.enableVertexAttribArray(aQuadVertexLoc);
- gl.vertexAttribPointer(aQuadVertexLoc, 2, gl.FLOAT, false, 0, 0);
-
- const aCenterLoc = gl.getAttribLocation(this.program, 'a_center');
- const aSizeLoc = gl.getAttribLocation(this.program, 'a_size');
- const aAngleLoc = gl.getAttribLocation(this.program, 'a_angle');
- const aColorLoc = gl.getAttribLocation(this.program, 'a_color');
- const aAlphaLoc = gl.getAttribLocation(this.program, 'a_alpha');
- const aPressureLoc = gl.getAttribLocation(this.program, 'a_pressure');
- const aStrokeDistLoc = gl.getAttribLocation(this.program, 'a_strokeDist');
-
- if (this.extInstanced && this.instanceBuffer && dabs.length > 0) {
- const stride = 12;
- const requiredFloats = dabs.length * stride;
- if (this.instanceArray.length < requiredFloats) {
- this.instanceArray = new Float32Array(Math.max(requiredFloats, this.instanceArray.length * 2));
- }
- const arr = this.instanceArray;
- for (let i = 0; i < dabs.length; i++) {
- const d = dabs[i];
- const offset = i * stride;
- arr[offset + 0] = d.x;
- arr[offset + 1] = d.y;
- arr[offset + 2] = d.width;
- arr[offset + 3] = d.height;
- arr[offset + 4] = d.angle;
- arr[offset + 5] = d.r;
- arr[offset + 6] = d.g;
- arr[offset + 7] = d.b;
- arr[offset + 8] = 1.0;
- arr[offset + 9] = d.alpha;
- arr[offset + 10] = d.pressure;
- arr[offset + 11] = d.strokeDist;
- }
+ gl.enableVertexAttribArray(this.aQuadVertexLoc);
+ gl.vertexAttribPointer(this.aQuadVertexLoc, 2, gl.FLOAT, false, 0, 0);
+ const useInstanced = Boolean(this.extInstanced && this.instanceBuffer);
+ if (useInstanced && this.extInstanced && this.instanceBuffer) {
gl.bindBuffer(gl.ARRAY_BUFFER, this.instanceBuffer);
- gl.bufferData(gl.ARRAY_BUFFER, arr.subarray(0, requiredFloats), gl.DYNAMIC_DRAW);
-
const byteStride = stride * 4;
- gl.enableVertexAttribArray(aCenterLoc);
- gl.vertexAttribPointer(aCenterLoc, 2, gl.FLOAT, false, byteStride, 0);
- this.extInstanced.vertexAttribDivisor(aCenterLoc, 1);
-
- gl.enableVertexAttribArray(aSizeLoc);
- gl.vertexAttribPointer(aSizeLoc, 2, gl.FLOAT, false, byteStride, 2 * 4);
- this.extInstanced.vertexAttribDivisor(aSizeLoc, 1);
-
- gl.enableVertexAttribArray(aAngleLoc);
- gl.vertexAttribPointer(aAngleLoc, 1, gl.FLOAT, false, byteStride, 4 * 4);
- this.extInstanced.vertexAttribDivisor(aAngleLoc, 1);
-
- gl.enableVertexAttribArray(aColorLoc);
- gl.vertexAttribPointer(aColorLoc, 4, gl.FLOAT, false, byteStride, 5 * 4);
- this.extInstanced.vertexAttribDivisor(aColorLoc, 1);
-
- gl.enableVertexAttribArray(aAlphaLoc);
- gl.vertexAttribPointer(aAlphaLoc, 1, gl.FLOAT, false, byteStride, 9 * 4);
- this.extInstanced.vertexAttribDivisor(aAlphaLoc, 1);
-
- gl.enableVertexAttribArray(aPressureLoc);
- gl.vertexAttribPointer(aPressureLoc, 1, gl.FLOAT, false, byteStride, 10 * 4);
- this.extInstanced.vertexAttribDivisor(aPressureLoc, 1);
-
- gl.enableVertexAttribArray(aStrokeDistLoc);
- gl.vertexAttribPointer(aStrokeDistLoc, 1, gl.FLOAT, false, byteStride, 11 * 4);
- this.extInstanced.vertexAttribDivisor(aStrokeDistLoc, 1);
-
- this.extInstanced.drawArraysInstanced(gl.TRIANGLES, 0, 6, dabs.length);
-
- this.extInstanced.vertexAttribDivisor(aCenterLoc, 0);
- this.extInstanced.vertexAttribDivisor(aSizeLoc, 0);
- this.extInstanced.vertexAttribDivisor(aAngleLoc, 0);
- this.extInstanced.vertexAttribDivisor(aColorLoc, 0);
- this.extInstanced.vertexAttribDivisor(aAlphaLoc, 0);
- this.extInstanced.vertexAttribDivisor(aPressureLoc, 0);
- this.extInstanced.vertexAttribDivisor(aStrokeDistLoc, 0);
-
- gl.disableVertexAttribArray(aCenterLoc);
- gl.disableVertexAttribArray(aSizeLoc);
- gl.disableVertexAttribArray(aAngleLoc);
- gl.disableVertexAttribArray(aColorLoc);
- gl.disableVertexAttribArray(aAlphaLoc);
- gl.disableVertexAttribArray(aPressureLoc);
- gl.disableVertexAttribArray(aStrokeDistLoc);
- } else {
- for (const dab of dabs) {
- gl.vertexAttrib2f(aCenterLoc, dab.x, dab.y);
- gl.vertexAttrib2f(aSizeLoc, dab.width, dab.height);
- gl.vertexAttrib1f(aAngleLoc, dab.angle);
- gl.vertexAttrib4f(aColorLoc, dab.r, dab.g, dab.b, 1.0);
- gl.vertexAttrib1f(aAlphaLoc, dab.alpha);
- gl.vertexAttrib1f(aPressureLoc, dab.pressure);
- gl.vertexAttrib1f(aStrokeDistLoc, dab.strokeDist);
-
- gl.drawArrays(gl.TRIANGLES, 0, 6);
+ 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 (typeof gl.scissor === 'function') {
- gl.disable(gl.SCISSOR_TEST);
+ 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 compositeOp: GlobalCompositeOperation = isBgEraser
+ ? 'source-over'
+ : isEraser
+ ? 'destination-out'
+ : isAlphaLocked
+ ? 'source-atop'
+ : 'source-over';
+
targetCtx.save();
- if (isBgEraser) {
- targetCtx.globalCompositeOperation = 'source-over';
- } else if (isEraser) {
- targetCtx.globalCompositeOperation = 'destination-out';
- } else {
- targetCtx.globalCompositeOperation = 'source-over';
- }
+ targetCtx.globalCompositeOperation = compositeOp;
targetCtx.globalAlpha = 1.0;
- targetCtx.drawImage(canvas, dirtyX, dirtyY, dirtyW, dirtyH, dirtyX, dirtyY, dirtyW, dirtyH);
+ if (aaMode === 0) {
+ targetCtx.imageSmoothingEnabled = false;
+ }
+
+ // Tile across dirty bounding box in <= 2048x2048 chunks so 70MP B4 600DPI strokes NEVER clip at 4096px!
+ for (let cy = fullDirtyY; cy < fullDirtyMaxY; cy += MAX_TILE_CHUNK) {
+ const dh = Math.min(MAX_TILE_CHUNK, fullDirtyMaxY - cy);
+ for (let cx = fullDirtyX; cx < fullDirtyMaxX; cx += MAX_TILE_CHUNK) {
+ const dw = Math.min(MAX_TILE_CHUNK, fullDirtyMaxX - cx);
+ const viewY = Math.max(0, canvas.height - dh);
+
+ 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.uCanvasResolutionLoc, dw, dh);
+ if (this.uDirtyOffsetLoc) {
+ gl.uniform2f(this.uDirtyOffsetLoc, cx, cy);
+ }
+
+ if (useInstanced && this.extInstanced) {
+ this.extInstanced.drawArraysInstanced(gl.TRIANGLES, 0, 6, dabs.length);
+ } else {
+ for (let i = 0; i < dabs.length; 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], 1.0);
+ 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]);
+ }
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+ }
+ }
+
+ if (typeof gl.scissor === 'function') {
+ gl.disable(gl.SCISSOR_TEST);
+ }
+
+ targetCtx.drawImage(canvas, 0, 0, dw, dh, cx, cy, dw, dh);
+ }
+ }
+
targetCtx.restore();
+ 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);
+ }
+
+ 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);
+ }
+
+ if (useCompareTips) {
+ gl.blendEquation(gl.FUNC_ADD);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ }
+
return true;
}
/**
- * Generates arc-length sampled sub-pixel dabs along a Bézier curve.
+ * Generates deterministic arc-length sampled sub-pixel dabs along a quadratic Bézier curve.
*/
public generateArcLengthDabs(
p0: Point,
@@ -1057,14 +1354,16 @@ export class WebGlBrushEngine {
): { dabs: GpuDab[]; remainderDist: number; totalStrokeDist: number } {
const dabs: GpuDab[] = [];
const rgb = this.parseColor(color);
- const spacingRatio = Math.max(0.06, Math.min(1.0, settings.spacing ?? 0.08));
- const flow = settings.flow ?? 0.85;
+ const spacingRatio = Math.max(0.02, Math.min(1.0, settings.spacing ?? 0.08));
+ const flow = settings.brushDensity ?? settings.flow ?? 0.85;
const aspect =
settings.customTipImage && settings.customTipImage.naturalWidth
? (settings.customTipImage.naturalHeight || 1) / (settings.customTipImage.naturalWidth || 1)
: 1.0;
const baseAngleRad = ((settings.customTipAngle ?? 0) * Math.PI) / 180;
const angleDynamics = settings.customTipAngleDynamics ?? 'none';
+ const baseThickness = settings.thickness ?? 1.0;
+ const isVertThickness = Boolean(settings.thicknessVertical);
const chord = Math.hypot(p2.x - p0.x, p2.y - p0.y);
const avgWidth = Math.max(1, (p0.width + p2.width) / 2);
@@ -1075,6 +1374,7 @@ export class WebGlBrushEngine {
let prevX = p0.x;
let prevY = p0.y;
+ let dabSeq = 0;
const dynamics = settings.dynamics;
const dabCount = Math.max(1, Math.min(10, Math.round(dynamics?.count ?? 1)));
@@ -1103,59 +1403,58 @@ export class WebGlBrushEngine {
const effPressure = p0.pressure + (p2.pressure - p0.pressure) * t;
const rawWidth = p0.width + (p2.width - p0.width) * t;
- const curWidth = Math.max(0.5, rawWidth);
+ const curWidth = Math.max(0.25, rawWidth);
- const requiredSpacing = Math.max(0.5, curWidth * spacingRatio);
+ const requiredSpacing = Math.max(0.25, curWidth * spacingRatio);
if (accDist >= requiredSpacing) {
+ dabSeq++;
let baseAngle = baseAngleRad;
- if (angleDynamics === 'direction' && stepDist > 0.001) {
+ if ((angleDynamics === 'direction' || angleDynamics === 'direction-random') && stepDist > 0.001) {
baseAngle += Math.atan2(dy, dx);
- } else if (angleDynamics === 'random' && settings.customTipRotationRandomScale) {
- baseAngle += (Math.random() - 0.5) * Math.PI * 2 * settings.customTipRotationRandomScale;
+ }
+ if (angleDynamics === 'random' || angleDynamics === 'direction-random') {
+ const rScale = settings.customTipRotationRandomScale ?? 1.0;
+ baseAngle += (dabHashFloat(curX, curY, dabSeq, 11) - 0.5) * Math.PI * 2 * rScale;
}
- let tx = 0;
+ let tx = 1;
let ty = 0;
let nx = 0;
- let ny = 0;
+ let ny = 1;
if (stepDist > 0.001) {
tx = dx / stepDist;
ty = dy / stepDist;
nx = -ty;
ny = tx;
- } else {
- nx = 0;
- ny = 1;
- tx = 1;
- ty = 0;
}
for (let k = 0; k < dabCount; k++) {
+ const seedIdx = dabSeq * 16 + k;
let curDabW = curWidth;
if (sizeJitter > 0) {
- curDabW *= Math.max(0.01, 1.0 - Math.random() * sizeJitter);
+ curDabW *= Math.max(0.01, 1.0 - dabHashFloat(curX, curY, seedIdx, 1) * sizeJitter);
}
curDabW = Math.max(0.1, curDabW);
- let curDabThickness = 1.0;
+ let curDabThickness = baseThickness;
if (roundnessJitter > 0) {
- curDabThickness *= Math.max(0.05, 1.0 - Math.random() * roundnessJitter);
+ curDabThickness *= Math.max(0.05, 1.0 - dabHashFloat(curX, curY, seedIdx, 2) * roundnessJitter);
}
let curDabAngle = baseAngle;
if (angleJitter > 0) {
- curDabAngle += (Math.random() - 0.5) * Math.PI * 2 * angleJitter;
+ curDabAngle += (dabHashFloat(curX, curY, seedIdx, 3) - 0.5) * Math.PI * 2 * angleJitter;
}
let curDabX = curX;
let curDabY = curY;
if (scatter > 0) {
- const perpDist = (Math.random() * 2 - 1) * curWidth * scatter;
+ const perpDist = (dabHashFloat(curX, curY, seedIdx, 4) * 2 - 1) * curWidth * scatter;
let sOffX = nx * perpDist;
let sOffY = ny * perpDist;
if (scatterBothAxes) {
- const tangDist = (Math.random() * 2 - 1) * curWidth * scatter;
+ const tangDist = (dabHashFloat(curX, curY, seedIdx, 5) * 2 - 1) * curWidth * scatter;
sOffX += tx * tangDist;
sOffY += ty * tangDist;
}
@@ -1165,33 +1464,38 @@ export class WebGlBrushEngine {
let curDabAlpha = flow;
if (flowJitter > 0) {
- curDabAlpha *= Math.max(0.005, 1.0 - Math.random() * flowJitter);
+ curDabAlpha *= Math.max(0.005, 1.0 - dabHashFloat(curX, curY, seedIdx, 6) * flowJitter);
}
let dabR = rgb.r;
let dabG = rgb.g;
let dabB = rgb.b;
if (colorJitterEnabled && dynamics && secondaryRgb) {
- const cd = applyColorDynamics(rgb, secondaryRgb, dynamics);
+ let salt = 20;
+ const cd = applyColorDynamics(rgb, secondaryRgb, dynamics, () => dabHashFloat(curX, curY, seedIdx, salt++));
dabR = cd.r;
dabG = cd.g;
dabB = cd.b;
}
+ const flips = resolveTipFlipSigns(settings.flipH, settings.flipV, seedIdx, curDabX, curDabY);
+ const wOut = isVertThickness ? curDabW * curDabThickness : curDabW;
+ const hOut = isVertThickness ? curDabW * aspect : curDabW * aspect * curDabThickness;
+
if (settings.spray?.enabled) {
const pCount = settings.spray.density;
const pSize = Math.max(1, settings.spray.size);
const radius = curDabW / 2;
for (let sp = 0; sp < pCount; sp++) {
- const u1 = Math.random();
- const u2 = Math.random();
+ const u1 = dabHashFloat(curDabX, curDabY, seedIdx * 64 + sp, 31);
+ const u2 = dabHashFloat(curDabX, curDabY, seedIdx * 64 + sp, 32);
const r = radius * Math.sqrt(u1) * (1 - (settings.spray.bias || 0) * (1 - u2));
- const th = Math.PI * 2 * Math.random();
+ const th = Math.PI * 2 * dabHashFloat(curDabX, curDabY, seedIdx * 64 + sp, 33);
dabs.push({
x: curDabX + r * Math.cos(th),
y: curDabY + r * Math.sin(th),
- width: pSize,
- height: pSize * aspect * curDabThickness,
+ width: isVertThickness ? pSize * curDabThickness : pSize,
+ height: isVertThickness ? pSize * aspect : pSize * aspect * curDabThickness,
angle: curDabAngle,
r: dabR,
g: dabG,
@@ -1199,14 +1503,16 @@ export class WebGlBrushEngine {
alpha: curDabAlpha,
pressure: effPressure,
strokeDist,
+ flipX: flips.signX,
+ flipY: flips.signY,
});
}
} else {
dabs.push({
x: curDabX,
y: curDabY,
- width: curDabW,
- height: curDabW * aspect * curDabThickness,
+ width: wOut,
+ height: hOut,
angle: curDabAngle,
r: dabR,
g: dabG,
@@ -1214,6 +1520,8 @@ export class WebGlBrushEngine {
alpha: curDabAlpha,
pressure: effPressure,
strokeDist,
+ flipX: flips.signX,
+ flipY: flips.signY,
});
}
}
diff --git a/vite.config.ts b/vite.config.ts
index 822dfda..7bd59fb 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -31,4 +31,22 @@ export default defineConfig(() => ({
ignored: ["**/src-tauri/**"],
},
},
+ build: {
+ chunkSizeWarningLimit: 1000,
+ rolldownOptions: {
+ output: {
+ manualChunks(id: string) {
+ if (id.includes("node_modules/three")) {
+ return "vendor-three";
+ }
+ if (id.includes("node_modules/lucide-react")) {
+ return "vendor-icons";
+ }
+ if (id.includes("node_modules/react") || id.includes("node_modules/react-dom")) {
+ return "vendor-react";
+ }
+ },
+ },
+ },
+ },
}));