Skip to content

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

small big

sorad8f86fec36d0
diff --git a/package-lock.json b/package-lock.json
index 72ee40e..462ba47 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,11 +1,11 @@
{
- "name": "tauri-app",
+ "name": "ink-studio",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
- "name": "tauri-app",
+ "name": "ink-studio",
"version": "0.1.0",
"dependencies": {
"@tailwindcss/vite": "^4.3.3",
@@ -23,12 +23,13 @@
"three": "^0.186.1"
},
"devDependencies": {
- "@tauri-apps/cli": "^2",
+ "@tauri-apps/cli": "^2.12.0",
"@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6",
"@vitejs/plugin-react": "^6.0.2",
"typescript": "~6.0.3",
- "vite": "^8.0.16"
+ "vite": "^8.0.16",
+ "vitest": "^5.0.2"
}
},
"node_modules/@dimforge/rapier3d-compat": {
@@ -635,9 +636,9 @@
}
},
"node_modules/@tauri-apps/cli": {
- "version": "2.11.5",
- "resolved": "https://registry.npmjs.org/@tauri-apps/cli/-/cli-2.11.5.tgz",
- "integrity": "sha512-YbeJ6tctNoo40purO4u3Eeo3RVqmsjJr0NoKQRu+4pvO4gMLzkjta7x0k96SxSLmx+rQ+8um1ThOlw+HLpgFug==",
+ "version": "2.12.0",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli/-/cli-2.12.0.tgz",
+ "integrity": "sha512-GIShnAR4C16kSTA8NO02fo8fOw/I5z5sAUEB5S2HlPHFnBkbihL4c9a/MpkxOm1+q5S+tFd3X4QUjHWxfyGzpQ==",
"dev": true,
"license": "Apache-2.0 OR MIT",
"bin": {
@@ -651,23 +652,23 @@
"url": "https://opencollective.com/tauri"
},
"optionalDependencies": {
- "@tauri-apps/cli-darwin-arm64": "2.11.5",
- "@tauri-apps/cli-darwin-x64": "2.11.5",
- "@tauri-apps/cli-linux-arm-gnueabihf": "2.11.5",
- "@tauri-apps/cli-linux-arm64-gnu": "2.11.5",
- "@tauri-apps/cli-linux-arm64-musl": "2.11.5",
- "@tauri-apps/cli-linux-riscv64-gnu": "2.11.5",
- "@tauri-apps/cli-linux-x64-gnu": "2.11.5",
- "@tauri-apps/cli-linux-x64-musl": "2.11.5",
- "@tauri-apps/cli-win32-arm64-msvc": "2.11.5",
- "@tauri-apps/cli-win32-ia32-msvc": "2.11.5",
- "@tauri-apps/cli-win32-x64-msvc": "2.11.5"
+ "@tauri-apps/cli-darwin-arm64": "2.12.0",
+ "@tauri-apps/cli-darwin-x64": "2.12.0",
+ "@tauri-apps/cli-linux-arm-gnueabihf": "2.12.0",
+ "@tauri-apps/cli-linux-arm64-gnu": "2.12.0",
+ "@tauri-apps/cli-linux-arm64-musl": "2.12.0",
+ "@tauri-apps/cli-linux-riscv64-gnu": "2.12.0",
+ "@tauri-apps/cli-linux-x64-gnu": "2.12.0",
+ "@tauri-apps/cli-linux-x64-musl": "2.12.0",
+ "@tauri-apps/cli-win32-arm64-msvc": "2.12.0",
+ "@tauri-apps/cli-win32-ia32-msvc": "2.12.0",
+ "@tauri-apps/cli-win32-x64-msvc": "2.12.0"
}
},
"node_modules/@tauri-apps/cli-darwin-arm64": {
- "version": "2.11.5",
- "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.11.5.tgz",
- "integrity": "sha512-tggOiVOohjIHdiElbjeBfB41s6cmfsq+ZQ0PX0fEtCdsDdZ9cCi54e5gNK7tdPbR6JbdDe7RA4kbQdyyBUUk/Q==",
+ "version": "2.12.0",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.12.0.tgz",
+ "integrity": "sha512-v5J+jISihLGtih1+3yWagbsL+5dbLZORu4vaSI0vhY0Heb+MAW+T/1s1RyKxrQrwEPGBG5kqwfDDTnSbmVkuqA==",
"cpu": [
"arm64"
],
@@ -682,9 +683,9 @@
}
},
"node_modules/@tauri-apps/cli-darwin-x64": {
- "version": "2.11.5",
- "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.11.5.tgz",
- "integrity": "sha512-SrO+KCbqvG1IvVPdlzQX4GEGZRQDISrmDY9bGcW68DLVFBCC06H+Loz6oyUZETUxsSMR6B4oDfvbQVgD4hxsqQ==",
+ "version": "2.12.0",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.12.0.tgz",
+ "integrity": "sha512-g27I07pfW/dMS8vcNqB9lamgKF0TqLlcy8e7t9qDGsB1iaeyjJWb2TgBF4tM9ZwLqPAZUXbsz28oXljO12WC4g==",
"cpu": [
"x64"
],
@@ -699,9 +700,9 @@
}
},
"node_modules/@tauri-apps/cli-linux-arm-gnueabihf": {
- "version": "2.11.5",
- "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.11.5.tgz",
- "integrity": "sha512-qLrOaCa8hLD5QVPQRjAgOXvhlTFKXmTliVF773GgvADYcWZSdmncnF5zBFAkdu1uQK8KfQbDlBUwqQYZqBfBRQ==",
+ "version": "2.12.0",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.12.0.tgz",
+ "integrity": "sha512-gXyQ710fNc99YuxFxNyeX9PLSrIpbtgBBj7GQo9tSeRT6fIK40q3/gm7X5jqZo7mWLR2m0R/2ALd3vAWo0Z32Q==",
"cpu": [
"arm"
],
@@ -716,9 +717,9 @@
}
},
"node_modules/@tauri-apps/cli-linux-arm64-gnu": {
- "version": "2.11.5",
- "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.11.5.tgz",
- "integrity": "sha512-Tq32xpQjiQEdIrvwDq7lwHhXemn070CXWdbCvr9rdi9rsv9NFTbQ6izVSIfNE+59QaerxuwtUtZ5IxDNWaoYBw==",
+ "version": "2.12.0",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.12.0.tgz",
+ "integrity": "sha512-H9cyXuq9WgxoHh2NZ+R+oN+W78x5UwaBDEp0/fmqUUkaBoioCuOZErM9xKiIV6bpNAhmw1RoWZ49u37q/vaiAg==",
"cpu": [
"arm64"
],
@@ -736,9 +737,9 @@
}
},
"node_modules/@tauri-apps/cli-linux-arm64-musl": {
- "version": "2.11.5",
- "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.11.5.tgz",
- "integrity": "sha512-+OdWKj5Aq+C8HXypQ4t926V8cpVnc0ZcJIdhTXWjVAJHkaNuo8EuQR6KRZKHWIbJJgKdMPCDosvwzIFaBBqHKQ==",
+ "version": "2.12.0",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.12.0.tgz",
+ "integrity": "sha512-5tFuk3JKMBa1M/iN4gN32OYlSfhY3aqb5PO3zCugxaT+sfecyMKpc3EM9VDbhmwWBE9QD4Tfj7wGhlqx2yy2pQ==",
"cpu": [
"arm64"
],
@@ -756,9 +757,9 @@
}
},
"node_modules/@tauri-apps/cli-linux-riscv64-gnu": {
- "version": "2.11.5",
- "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.11.5.tgz",
- "integrity": "sha512-Q0V2hjpllyDW8dWQZSsITuQDfcY9BpBZuhXkMa2T5AFLZAn+FJPXQSyvnxWNVxRowdQ59Xn0QVtGm6HEHNUEvw==",
+ "version": "2.12.0",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.12.0.tgz",
+ "integrity": "sha512-LOrMyV+nb7pKq8P0BZtTBQuyzm1ORjn16R9MlupmxuT5LqxtuYJlw3VMwbaeXCToJ8jbP5u9JnkfmbqDlvETXw==",
"cpu": [
"riscv64"
],
@@ -776,9 +777,9 @@
}
},
"node_modules/@tauri-apps/cli-linux-x64-gnu": {
- "version": "2.11.5",
- "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.11.5.tgz",
- "integrity": "sha512-Xz1s87gFjZJZMQKAhLa77YeiCJM6yVog3f9OxDgVd/KxDIoB1dA5V2xOnMM+SRkOGk9juwIBqesVAjV0kUB0DA==",
+ "version": "2.12.0",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.12.0.tgz",
+ "integrity": "sha512-aMIkI+X9qvD2+k80QZB3tuOYT41/cEheikC510CwAIZ31KLXORsRASYYzM4mi1/58ICmtzSLFhCC08keir7COw==",
"cpu": [
"x64"
],
@@ -796,9 +797,9 @@
}
},
"node_modules/@tauri-apps/cli-linux-x64-musl": {
- "version": "2.11.5",
- "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.11.5.tgz",
- "integrity": "sha512-6A88wqAZXZHgMaBrGiy/Bpa4GgUnftXM7uquKOeOXCuK78/XdBxEECicK/1oHgrT179XBFOaA6lQEHysjRmGig==",
+ "version": "2.12.0",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.12.0.tgz",
+ "integrity": "sha512-9gl3NhUbfuGhSKjeGCypKSdtoezOQRcDUrkhTWtLQEjnajets6peO6NadgI2DF0OzbiiFOzrnnIGMwBS+Ap6Iw==",
"cpu": [
"x64"
],
@@ -816,9 +817,9 @@
}
},
"node_modules/@tauri-apps/cli-win32-arm64-msvc": {
- "version": "2.11.5",
- "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.11.5.tgz",
- "integrity": "sha512-sRGgF/ObRfLcS3PtUdyTbJtkGq3E+PNZTknvAURwMNUtHw9DU/BF6S5si43y9lS5yEO9bWJCA+GGYvnn6cphQw==",
+ "version": "2.12.0",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.12.0.tgz",
+ "integrity": "sha512-1W+v86wsYLuyBDN0iDessD4CD9o+yNyO0m8Dp3+/vfjiZrJ/v7R7/aTRBeikaq2tLGgxeag0gxnFggBNBGw91A==",
"cpu": [
"arm64"
],
@@ -833,9 +834,9 @@
}
},
"node_modules/@tauri-apps/cli-win32-ia32-msvc": {
- "version": "2.11.5",
- "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.11.5.tgz",
- "integrity": "sha512-bHOv/yxqfKpI7ioIFQi5wOfZ7jkbPzJD/UhXY52I/hrmE3qNh71cohIPyqZB5GQn3LZeJWdCUOqmIg/w6XX+Wg==",
+ "version": "2.12.0",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.12.0.tgz",
+ "integrity": "sha512-SsBjvq4f7YaBGqcWoE3cycoItPf0SrQeqFqWWgfxoeZWAIz01E31LDSeZ2p/etJiIY0R9oi045chkFfb0O7WGw==",
"cpu": [
"ia32"
],
@@ -850,9 +851,9 @@
}
},
"node_modules/@tauri-apps/cli-win32-x64-msvc": {
- "version": "2.11.5",
- "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.11.5.tgz",
- "integrity": "sha512-vaaOmavqdCeS7oMib2banBZemgrC5v54tSkwoBV+bxrXQZhQZrOwE2EO2i4x+CHNtvQUM/6bSs3iymZMAsycWg==",
+ "version": "2.12.0",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.12.0.tgz",
+ "integrity": "sha512-9zzDKYUH4TKKBgRdDdVQX8fiRO5gJ8hD1nGsHU9DOHG5Jpm3arjbu9Xg1frR20EusG3Sl8X0dppoO/4EoUXUGg==",
"cpu": [
"x64"
],
@@ -881,12 +882,37 @@
"integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==",
"license": "MIT"
},
+ "node_modules/@types/chai": {
+ "version": "5.2.3",
+ "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
+ "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/deep-eql": "*",
+ "assertion-error": "^2.0.1"
+ }
+ },
+ "node_modules/@types/deep-eql": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
+ "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/emscripten": {
"version": "1.41.6",
"resolved": "https://registry.npmjs.org/@types/emscripten/-/emscripten-1.41.6.tgz",
"integrity": "sha512-uN+9i8bFT5CUcZfyIEYDrSueACEyKGbUs5kC/72DGlZZoinh84sJfVV0i8UOJD1asdzkvLPBRrKs41kZ8MdEXg==",
"license": "MIT"
},
+ "node_modules/@types/estree": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/node": {
"version": "26.6.2",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.2.tgz",
@@ -982,6 +1008,54 @@
}
}
},
+ "node_modules/@vitest/mocker": {
+ "version": "5.0.2",
+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.2.tgz",
+ "integrity": "sha512-Z5FS00Q1SJHkB35xATsmWGdQ5WA1/0MV3CDjqyv7GavHv1OfOj145MNfHOlHk7QLes21dKFDHr8EO2zvL+9WGA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/trace-mapping": "0.3.31",
+ "@vitest/spy": "5.0.2",
+ "estree-walker": "^3.0.3",
+ "magic-string": "^1.2.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "msw": "^2.4.9",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "msw": {
+ "optional": true
+ },
+ "vite": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@vitest/mocker/node_modules/magic-string": {
+ "version": "1.4.2",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.2.tgz",
+ "integrity": "sha512-vG+rjFRj1PqdIBozIxAGMjPlOhaVe+GXpbttY/iSK7rGcJRMlwNJO7dcUwmUqkymsFLJiNGI06t4D7Fr7yRC9g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.6.0"
+ }
+ },
+ "node_modules/@vitest/spy": {
+ "version": "5.0.2",
+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.2.tgz",
+ "integrity": "sha512-Ijc7T1nT9efNb5LxvjaBrEqw3f/QwUv5EE0nKqZxgqsaV/FxAAZ8baGylA8X/Z2oS4Lp+K74Jr6dTJsDKxJDeg==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
"node_modules/ag-psd": {
"version": "31.0.2",
"resolved": "https://registry.npmjs.org/ag-psd/-/ag-psd-31.0.2.tgz",
@@ -992,6 +1066,16 @@
"pako": "2.1.0"
}
},
+ "node_modules/assertion-error": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
+ "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
@@ -1012,6 +1096,16 @@
],
"license": "MIT"
},
+ "node_modules/chai": {
+ "version": "6.2.2",
+ "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",
+ "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
@@ -1041,6 +1135,33 @@
"node": ">=10.13.0"
}
},
+ "node_modules/es-module-lexer": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz",
+ "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/estree-walker": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0"
+ }
+ },
+ "node_modules/expect-type": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
+ "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
"node_modules/fdir": {
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
@@ -1396,6 +1517,20 @@
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
+ "node_modules/obug": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/obug/-/obug-2.2.1.tgz",
+ "integrity": "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==",
+ "dev": true,
+ "funding": [
+ "https://github.com/sponsors/sxzz",
+ "https://opencollective.com/debug"
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
"node_modules/pako": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/pako/-/pako-2.1.0.tgz",
@@ -1523,6 +1658,13 @@
"integrity": "sha512-3ZGPovObMFrdw79zrUHbfdE/DLIsy8jdNdssmMSQuRAymedU6q84asPt0kgiqrdMYlPegDItiIMfmIXzZnYFcw==",
"license": "MIT"
},
+ "node_modules/std-env": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz",
+ "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/tailwindcss": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.3.tgz",
@@ -1548,6 +1690,26 @@
"integrity": "sha512-blFeqb49wRCSGUGj7gtpfnSGHy2lwDk94RhUmS1c/hTby70kvChbWpkJ4Pm1390LqzzvTmzgXKHPEafJwCb8jA==",
"license": "MIT"
},
+ "node_modules/tinybench": {
+ "version": "6.2.0",
+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.0.tgz",
+ "integrity": "sha512-78U2TlB2CnVenajOFzf3BKSm0J6oz5L0NV7g32LCPccvYc0lbWvys4d3uUUCS2B1N8PAf2+aekR8i1KbC3HO7Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/tinyexec": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz",
+ "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
@@ -1921,6 +2083,112 @@
"type": "opencollective",
"url": "https://opencollective.com/parcel"
}
+ },
+ "node_modules/vitest": {
+ "version": "5.0.2",
+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.2.tgz",
+ "integrity": "sha512-7MQrx9pDv5aHiUcovIb/70Ys3tgtkUVgCtledvKdCmEO+/1Dicq5ZqoSxOW034m03oqC+oHOKui2dM6qtMLoJg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/chai": "^5.2.2",
+ "@vitest/mocker": "5.0.2",
+ "chai": "^6.2.2",
+ "es-module-lexer": "^2.3.2",
+ "expect-type": "^1.4.0",
+ "magic-string": "^1.2.3",
+ "obug": "^2.1.4",
+ "picomatch": "^4.0.7",
+ "std-env": "^4.2.0",
+ "tinybench": "^6.1.4",
+ "tinyexec": "^1.3.0",
+ "tinyglobby": "^0.2.17",
+ "why-is-node-running": "^3.2.1"
+ },
+ "bin": {
+ "vitest": "vitest.mjs"
+ },
+ "engines": {
+ "node": "^22.12.0 || ^24.0.0 || >=26.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "@edge-runtime/vm": "*",
+ "@opentelemetry/api": "^1.9.0",
+ "@types/node": "^22.0.0 || >=24.0.0",
+ "@vitest/browser-playwright": "5.0.2",
+ "@vitest/browser-preview": "5.0.2",
+ "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0",
+ "@vitest/coverage-istanbul": "5.0.2",
+ "@vitest/coverage-v8": "5.0.2",
+ "@vitest/ui": "5.0.2",
+ "happy-dom": "*",
+ "jsdom": "*",
+ "vite": "^6.4.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@edge-runtime/vm": {
+ "optional": true
+ },
+ "@opentelemetry/api": {
+ "optional": true
+ },
+ "@types/node": {
+ "optional": true
+ },
+ "@vitest/browser-playwright": {
+ "optional": true
+ },
+ "@vitest/browser-preview": {
+ "optional": true
+ },
+ "@vitest/browser-webdriverio": {
+ "optional": true
+ },
+ "@vitest/coverage-istanbul": {
+ "optional": true
+ },
+ "@vitest/coverage-v8": {
+ "optional": true
+ },
+ "@vitest/ui": {
+ "optional": true
+ },
+ "happy-dom": {
+ "optional": true
+ },
+ "jsdom": {
+ "optional": true
+ },
+ "vite": {
+ "optional": false
+ }
+ }
+ },
+ "node_modules/vitest/node_modules/magic-string": {
+ "version": "1.4.2",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.2.tgz",
+ "integrity": "sha512-vG+rjFRj1PqdIBozIxAGMjPlOhaVe+GXpbttY/iSK7rGcJRMlwNJO7dcUwmUqkymsFLJiNGI06t4D7Fr7yRC9g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.6.0"
+ }
+ },
+ "node_modules/why-is-node-running": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.2.tgz",
+ "integrity": "sha512-NKUzAelcoCXhXL4dJzKIwXeR8iEVqsA0Lq6Vnd0UXvgaKbzVo4ZTHROF2Jidrv+SgxOQ03fMinnNhzZATxOD3A==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "why-is-node-running": "cli.js"
+ },
+ "engines": {
+ "node": ">=20.11"
+ }
}
}
}
diff --git a/package.json b/package.json
index 7fd3119..667ce79 100644
--- a/package.json
+++ b/package.json
@@ -25,11 +25,12 @@
"three": "^0.186.1"
},
"devDependencies": {
- "@tauri-apps/cli": "^2",
+ "@tauri-apps/cli": "^2.12.0",
"@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6",
"@vitejs/plugin-react": "^6.0.2",
"typescript": "~6.0.3",
- "vite": "^8.0.16"
+ "vite": "^8.0.16",
+ "vitest": "^5.0.2"
}
}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 80ccdee..9a3cd2d 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -29,6 +29,67 @@ fn get_local_lan_ip() -> String {
get_local_ip()
}
+#[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);
+ tokio::fs::create_dir_all(&temp_dir)
+ .await
+ .map_err(|e| e.to_string())?;
+ let file_path = temp_dir.join(format!("{}.bin", state_id));
+ tokio::fs::write(&file_path, data)
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(())
+}
+
+#[tauri::command]
+async fn load_undo_tile_cache(
+ session_id: String,
+ state_id: String,
+) -> Result<Vec<u8>, String> {
+ let file_path = std::env::temp_dir()
+ .join("inkstudio_undo")
+ .join(&session_id)
+ .join(format!("{}.bin", state_id));
+ let data = tokio::fs::read(&file_path)
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(data)
+}
+
+#[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);
+ if temp_dir.exists() {
+ let _ = tokio::fs::remove_dir_all(&temp_dir).await;
+ }
+ Ok(())
+}
+
+#[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);
+ }
+ }
+ Ok(false)
+}
+
+#[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())
+}
+
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
@@ -37,7 +98,12 @@ pub fn run() {
start_collab_server,
stop_collab_server,
get_collab_server_status,
- get_local_lan_ip
+ get_local_lan_ip,
+ save_undo_tile_cache,
+ load_undo_tile_cache,
+ clear_undo_tile_cache,
+ delete_file_from_disk,
+ read_file_from_disk
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
diff --git a/src/App.tsx b/src/App.tsx
index 30b8e55..be485ce 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -1,4 +1,4 @@
-import { useState, useCallback, useEffect, useRef } from 'react';
+import { useState, useCallback, useEffect, useRef, useMemo } from 'react';
import {
ToolType,
BrushSettings,
@@ -55,6 +55,9 @@ import { multiplayerService } from './services/multiplayerService';
import { HostModal } from './components/HostModal';
import { ClipboardInviteToast } from './components/ClipboardInviteToast';
import { WebLandingModal } from './components/WebLandingModal';
+import { WelcomeScreen } from './components/WelcomeScreen';
+import { FirstTimeNameModal } from './components/FirstTimeNameModal';
+import { saveRecentDocument, RecentDocument } from './utils/recentDocumentsManager';
import {
renderCompleteStroke,
drawDot,
@@ -65,6 +68,7 @@ import {
screenToCanvas,
sampleCompositedColor,
} from './utils/canvasUtils';
+import { globalTileGrid } from './utils/tileEngine';
import { getNextCollabLayerName } from './hooks/useLayerManager';
import { drawPencilDot, drawPencilBezierSegment, PencilGrade } from './utils/pencilEngine';
import { Point } from './types/editor';
@@ -74,8 +78,16 @@ import {
StrokeFinishMessage,
MultiplayerMessage,
} from './types/multiplayer';
+import { renderVectorStroke } from './utils/vectorEngine';
-import { AppSettings, loadAppSettings, saveAppSettings, ResizeCanvasOptions } from './types/settings';
+import {
+ AppSettings,
+ loadAppSettings,
+ saveAppSettings,
+ ResizeCanvasOptions,
+ resolveModernAccentColor,
+ hexToRgb,
+} from './types/settings';
import {
FilePlus,
FolderOpen,
@@ -89,7 +101,7 @@ import {
RotateCcw,
Plus,
Loader2,
- Sparkles,
+ Info as InfoIcon,
CheckCircle2,
Copy,
ClipboardPaste,
@@ -279,7 +291,30 @@ export function App() {
useEffect(() => {
const theme = appSettings.themePreset || 'vintage-manga';
document.documentElement.setAttribute('data-theme', theme);
- }, [appSettings.themePreset]);
+
+ 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 [isNewCanvasModalOpen, setIsNewCanvasModalOpen] = useState<boolean>(false);
const [isResizeCanvasModalOpen, setIsResizeCanvasModalOpen] = useState<boolean>(false);
@@ -423,6 +458,8 @@ export function App() {
setLayerMonoExpressMode,
applyExpressionColorOfPreview,
applyLayerColorPermanently,
+ toggleClipping,
+ toggleAlphaLock,
convertLayer,
fillScreentoneSelection,
} = useLayerManager({ dimensions });
@@ -655,44 +692,103 @@ export function App() {
}
if (targetCanvas && strokeState.points.length > 0) {
- const ctx = get2DContext(targetCanvas);
- if (ctx) {
- const isEraser = strokeState.tool === 'eraser';
- const isBgEraser = isEraser && (targetLayerId === 'layer-bg' || targetLayerId.startsWith('layer-bg'));
- const bs = strokeState.brushSettings;
- const isTranslucentBrush = !isEraser && (bs.opacity ?? 1.0) < 0.999;
-
- if (isTranslucentBrush) {
- const bakeCanvas = getReusableBakeCanvas(targetCanvas.width, targetCanvas.height);
- const bCtx = get2DContext(bakeCanvas);
- if (bCtx) {
- bCtx.clearRect(0, 0, targetCanvas.width, targetCanvas.height);
+ const targetLayer = layersRef.current.find((l) => l.id === targetLayerId);
+ const isMono = colorMode === 'monochrome' || targetLayer?.expressionColor === 'monochrome';
+ const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
+
+ if (msg.vectorStroke && targetLayer?.type === 'vector') {
+ targetLayer.vectorStrokes = [...(targetLayer.vectorStrokes || []), msg.vectorStroke];
+ const ctx = get2DContext(targetCanvas);
+ if (ctx) {
+ renderVectorStroke(ctx, msg.vectorStroke);
+ const fullData = ctx.getImageData(0, 0, targetCanvas.width, targetCanvas.height);
+ globalTileGrid.writeImageData(targetLayerId, fullData, 0, 0, targetFormat);
+ }
+ globalTileGrid.notifyChange(true);
+ updateLayerThumbnail(targetLayerId, true);
+ } else {
+ const ctx = get2DContext(targetCanvas);
+ if (ctx) {
+ const isEraser = strokeState.tool === 'eraser';
+ const isBgEraser = isEraser && (targetLayerId === 'layer-bg' || targetLayerId.startsWith('layer-bg'));
+ const bs = strokeState.brushSettings;
+ const isTranslucentBrush = !isEraser && (bs.opacity ?? 1.0) < 0.999;
+ const isAlphaLocked = Boolean(targetLayer?.alphaLocked);
+ const isTransparentInk = Boolean(bs.isTransparentInk);
+
+ if (isTranslucentBrush || isTransparentInk || isAlphaLocked) {
+ const bakeCanvas = getReusableBakeCanvas(targetCanvas.width, targetCanvas.height);
+ const bCtx = get2DContext(bakeCanvas);
+ if (bCtx) {
+ bCtx.clearRect(0, 0, targetCanvas.width, targetCanvas.height);
+ renderCompleteStroke(
+ bCtx,
+ strokeState.points,
+ bs,
+ strokeState.tool,
+ colorMode,
+ isBgEraser,
+ targetCanvas,
+ isAlphaLocked
+ );
+ ctx.save();
+ ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
+ if (isTransparentInk) {
+ ctx.globalCompositeOperation = 'destination-out';
+ } else if (isAlphaLocked) {
+ ctx.globalCompositeOperation = 'source-atop';
+ } else {
+ ctx.globalCompositeOperation = 'source-over';
+ }
+ ctx.drawImage(bakeCanvas, 0, 0);
+ ctx.restore();
+ }
+ } else {
renderCompleteStroke(
- bCtx,
+ ctx,
strokeState.points,
bs,
strokeState.tool,
colorMode,
- isBgEraser
+ isBgEraser,
+ targetCanvas,
+ isAlphaLocked
);
- ctx.save();
- ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
- ctx.globalCompositeOperation = 'source-over';
- ctx.drawImage(bakeCanvas, 0, 0);
- ctx.restore();
}
- } else {
- renderCompleteStroke(
- ctx,
- strokeState.points,
- bs,
- strokeState.tool,
- colorMode,
- isBgEraser
- );
- }
- updateLayerThumbnail(targetLayerId, true);
+ const pad = Math.ceil(Math.max(32, (bs.size || 10) * 1.5));
+ let dirtyX = 0;
+ let dirtyY = 0;
+ let dirtyW = targetCanvas.width;
+ let dirtyH = targetCanvas.height;
+
+ if (msg.dirtyRect) {
+ dirtyX = Math.max(0, Math.floor(msg.dirtyRect.x));
+ dirtyY = Math.max(0, Math.floor(msg.dirtyRect.y));
+ dirtyW = Math.min(targetCanvas.width - dirtyX, Math.ceil(msg.dirtyRect.width));
+ dirtyH = Math.min(targetCanvas.height - dirtyY, Math.ceil(msg.dirtyRect.height));
+ } else if (strokeState.points.length > 0) {
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
+ for (const pt of strokeState.points) {
+ if (pt.x < minX) minX = pt.x;
+ if (pt.y < minY) minY = pt.y;
+ if (pt.x > maxX) maxX = pt.x;
+ if (pt.y > maxY) maxY = pt.y;
+ }
+ dirtyX = Math.max(0, Math.floor(minX - pad));
+ dirtyY = Math.max(0, Math.floor(minY - pad));
+ dirtyW = Math.min(targetCanvas.width - dirtyX, Math.ceil(maxX + pad) - dirtyX);
+ dirtyH = Math.min(targetCanvas.height - dirtyY, Math.ceil(maxY + pad) - dirtyY);
+ }
+
+ if (dirtyW > 0 && dirtyH > 0) {
+ const afterData = ctx.getImageData(dirtyX, dirtyY, dirtyW, dirtyH);
+ globalTileGrid.writeImageData(targetLayerId, afterData, dirtyX, dirtyY, targetFormat);
+ }
+
+ globalTileGrid.notifyChange(true);
+ updateLayerThumbnail(targetLayerId, true);
+ }
}
}
@@ -801,6 +897,8 @@ export function App() {
}
}, [addRemoteLayer, deleteRemoteLayer, layerCanvasesRef, updateLayerThumbnail, renameLayer, toggleVisibility, setOpacity]);
+ const selectiveUndoRef = useRef<(peerId?: string | number) => void>(() => {});
+
const {
isConnected: isCollabConnected,
isHost: isCollabHost,
@@ -832,6 +930,9 @@ export function App() {
onRemoteJoinRequest: handleRemoteJoinRequest,
onRemoteAssignedLayer: handleRemoteAssignedLayer,
onRemoteLayerAction: handleRemoteLayerAction,
+ onRemoteSelectiveUndo: (_strokeId, peerId) => {
+ selectiveUndoRef.current(peerId);
+ },
showToast,
});
@@ -944,6 +1045,7 @@ export function App() {
jumpToHistoryIndex,
clearCanvas,
resetHistory,
+ selectiveUndo,
cursorPos,
currentPressure,
isHovering,
@@ -976,9 +1078,9 @@ export function App() {
multiplayerService.sendStrokeChunk(strokeId, pts);
}
},
- onCollabStrokeFinish: (strokeId, layerId, endPt, dirty) => {
+ onCollabStrokeFinish: (strokeId, layerId, endPt, dirty, vectorStroke) => {
if (multiplayerService.isConnected()) {
- multiplayerService.sendStrokeFinish(strokeId, layerId, endPt, dirty);
+ multiplayerService.sendStrokeFinish(strokeId, layerId, endPt, dirty, vectorStroke);
}
},
onCollabCursorMove: (x, y, isDrawing, t) => {
@@ -990,6 +1092,17 @@ export function App() {
onActiveConstraintAxisChange: setActiveLockedAxis,
});
+ selectiveUndoRef.current = selectiveUndo;
+
+ const handleUndo = useCallback(() => {
+ if (isCollabConnected && collabMyPeer.id) {
+ selectiveUndo(collabMyPeer.id);
+ multiplayerService.sendSelectiveUndo(collabMyPeer.id.toString());
+ } else {
+ undo();
+ }
+ }, [isCollabConnected, collabMyPeer.id, selectiveUndo, undo]);
+
const handleSelectTool = useCallback((newTool: ToolType) => {
const prevTool = toolRef.current;
@@ -1044,11 +1157,23 @@ export function App() {
});
}, []);
+ const [isTransparentColor, setIsTransparentColor] = useState<boolean>(false);
+
+ const toggleTransparentColor = useCallback(() => {
+ setIsTransparentColor((prev) => {
+ const next = !prev;
+ updateBrushSettings({ isTransparentInk: next });
+ showToast(next ? 'Transparent ink mode active' : 'Color ink mode active');
+ return next;
+ });
+ }, [updateBrushSettings, showToast]);
+
const handlePrimaryColorChange = useCallback(
(color: string, commit = true) => {
const effective = enforceColorMode(color, colorMode);
setPrimaryColor(effective);
- updateBrushSettings({ color: effective });
+ setIsTransparentColor(false);
+ updateBrushSettings({ color: effective, isTransparentInk: false });
if (commit) {
addRecentColor(effective);
}
@@ -1071,10 +1196,11 @@ export function App() {
);
const handleSwapColors = useCallback(() => {
+ setIsTransparentColor(false);
setPrimaryColor((prevPrim) => {
setSecondaryColor(prevPrim);
const effective = enforceColorMode(secondaryColor, colorMode);
- updateBrushSettings({ color: effective });
+ updateBrushSettings({ color: effective, isTransparentInk: false });
addRecentColor(effective);
return effective;
});
@@ -2684,6 +2810,18 @@ export function App() {
setPerspectiveRuler(null);
setDocuments((prev) => [...prev, newDoc]);
setActiveDocumentId(newDocId);
+
+ // Track in recent documents
+ saveRecentDocument({
+ id: newDocId,
+ title: name.replace(/\*+$/, ''),
+ path: `InkStudio\\${name.replace(/\*+$/, '')}.sora`,
+ size: 524288,
+ coverUrl: initialLayers[0]?.thumbnailUrl,
+ isStarred: false,
+ fileType: '.sora',
+ }).catch(console.warn);
+
showToast(`Created ${name}`);
},
[primaryColor, resetHistory, resetToNewCanvas, resetZoomAndCenter, showToast, updateBrushSettings]
@@ -2857,6 +2995,18 @@ export function App() {
setPerspectiveRuler(null);
setDocuments((prev) => [...prev, newDoc]);
setActiveDocumentId(newDocId);
+
+ // Track in recent documents
+ saveRecentDocument({
+ id: newDocId,
+ title: file.name,
+ path: (file as any).path || `C:\\Users\\Artist\\Documents\\InkStudio\\${file.name}`,
+ size: file.size || 1048576,
+ coverUrl: doc.layers[0]?.thumbnailUrl,
+ isStarred: false,
+ fileType: file.name.slice(file.name.lastIndexOf('.')),
+ }).catch(console.warn);
+
showToast(`Opened ${file.name}`);
} catch (err: unknown) {
console.error('Failed to open file:', err);
@@ -3027,6 +3177,15 @@ export function App() {
setDocuments((prev) =>
prev.map((d) => (d.id === activeDocumentId ? { ...d, name: info.name, savedFileInfo: info } : d))
);
+ saveRecentDocument({
+ id: activeDocumentId || `doc-${Date.now()}`,
+ title: info.name,
+ path: `InkStudio\\${info.name}`,
+ size: 1572864,
+ coverUrl: layers[0]?.thumbnailUrl,
+ isStarred: false,
+ fileType: info.extension,
+ }).catch(console.warn);
showToast(`Saved to ${info.name}`);
} catch (err: any) {
if (err.message !== 'Save canceled') {
@@ -3041,6 +3200,15 @@ export function App() {
setDocuments((prev) =>
prev.map((d) => (d.id === activeDocumentId ? { ...d, name: savedFileInfo.name } : d))
);
+ saveRecentDocument({
+ id: activeDocumentId || `doc-${Date.now()}`,
+ title: savedFileInfo.name,
+ path: `InkStudio\\${savedFileInfo.name}`,
+ size: 1572864,
+ coverUrl: layers[0]?.thumbnailUrl,
+ isStarred: false,
+ fileType: savedFileInfo.extension,
+ }).catch(console.warn);
showToast(`Saved to ${savedFileInfo.name}`);
} catch (err: any) {
console.warn('Direct handle save failed, prompting with Save As:', err);
@@ -3051,6 +3219,15 @@ export function App() {
setDocuments((prev) =>
prev.map((d) => (d.id === activeDocumentId ? { ...d, name: info.name, savedFileInfo: info } : d))
);
+ saveRecentDocument({
+ id: activeDocumentId || `doc-${Date.now()}`,
+ title: info.name,
+ path: `InkStudio\\${info.name}`,
+ size: 1572864,
+ coverUrl: layers[0]?.thumbnailUrl,
+ isStarred: false,
+ fileType: info.extension,
+ }).catch(console.warn);
showToast(`Saved to ${info.name}`);
} catch (e: any) {
if (e.message !== 'Save canceled') {
@@ -3093,6 +3270,15 @@ export function App() {
setDocuments((prev) =>
prev.map((d) => (d.id === activeDocumentId ? { ...d, name: info.name, savedFileInfo: info } : d))
);
+ saveRecentDocument({
+ id: activeDocumentId || `doc-${Date.now()}`,
+ title: info.name,
+ path: `InkStudio\\${info.name}`,
+ size: 1572864,
+ coverUrl: layers[0]?.thumbnailUrl,
+ isStarred: false,
+ fileType: info.extension,
+ }).catch(console.warn);
showToast(`Saved as ${info.name}`);
} catch (err: any) {
if (err.message !== 'Save canceled') {
@@ -3159,7 +3345,7 @@ export function App() {
if (!e.shiftKey && (key === 'z' || e.code === 'KeyZ')) {
if (!hasOpenDocument) return;
e.preventDefault();
- undo();
+ handleUndo();
return;
}
// Redo: Ctrl+Shift+Z or Ctrl+Y
@@ -3304,6 +3490,8 @@ export function App() {
handleSelectTool('liquify');
} else if (key === 'x') {
handleSwapColors();
+ } else if (key === 'c') {
+ toggleTransparentColor();
} else if (key === '[') {
setIsLeftPanelHidden((prev) => !prev);
} else if (key === 'delete') {
@@ -3344,11 +3532,12 @@ export function App() {
handleSave,
handleSaveAs,
handleSwapColors,
+ toggleTransparentColor,
handleTriggerOpenFile,
hasOpenDocument,
activeLayer,
redo,
- undo,
+ handleUndo,
handleStartTransform,
handleDeselect,
handleInvertSelection,
@@ -3596,7 +3785,7 @@ export function App() {
shortcut: 'Ctrl+Z',
icon: <Undo2 className="w-3.5 h-3.5" />,
disabled: !hasOpenDocument || !canUndo,
- onClick: undo,
+ onClick: handleUndo,
},
{
id: 'edit-redo',
@@ -4142,7 +4331,7 @@ export function App() {
{
id: 'help-about',
label: 'About Ink Studio',
- icon: <Sparkles className="w-3.5 h-3.5 text-amber-400" />,
+ icon: <InfoIcon className="w-3.5 h-3.5 text-[#93c5fd]" />,
onClick: () => {
alert(
'Ink Studio — Professional Digital Painting & Manga Studio\n\n' +
@@ -4160,10 +4349,85 @@ export function App() {
},
];
+ 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]
+ );
+
+ const handleSelectWelcomeDocument = useCallback(
+ async (doc: RecentDocument) => {
+ // 1. If running in Tauri, attempt to read directly from PC disk
+ if (typeof window !== 'undefined' && (window as any).__TAURI_INTERNALS__) {
+ try {
+ const { invoke } = await import('@tauri-apps/api/core');
+ const bytes = await invoke<number[]>('read_file_from_disk', { path: doc.path });
+ if (bytes && bytes.length > 0) {
+ const uint8 = new Uint8Array(bytes);
+ const file = new File([uint8], doc.title, { type: 'application/octet-stream' });
+ await handleProcessFile(file);
+ return;
+ }
+ } catch (err) {
+ console.warn('Direct disk read via Tauri failed, fallback:', err);
+ }
+ }
+
+ // 2. Fallback: Initialize new canvas with the document title and standard dimensions
+ handleCreateNewCanvas({
+ width: 1920,
+ height: 1080,
+ dpi: 300,
+ colorMode: 'color',
+ name: doc.title,
+ backgroundColor: '#ffffff',
+ aspectRatioPreset: '16:9',
+ aspectRatioX: 16,
+ aspectRatioY: 9,
+ lockAspectRatio: true,
+ });
+ showToast(`Loaded workspace for "${doc.title}"`);
+ },
+ [handleCreateNewCanvas, handleProcessFile, showToast]
+ );
+
+ const isModernTheme = appSettings.themePreset === 'modern';
+ const modernAccent = appSettings.modernAccent || 'blue';
+ 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]);
+
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}
+ style={modernStyleVars}
>
{/* Hidden File Input for Native File Picker */}
<input
@@ -4201,7 +4465,7 @@ export function App() {
onBrushSizeChange={handleBrushSizeChange}
canUndo={hasOpenDocument && canUndo}
canRedo={hasOpenDocument && canRedo}
- onUndo={undo}
+ onUndo={handleUndo}
onRedo={redo}
zoom={zoom}
onZoomIn={zoomIn}
@@ -4221,15 +4485,28 @@ export function App() {
/>
- {/* Main Workspace: Left Panel + Center Canvas Column + Right Sidebar */}
+ {/* Main Workspace */}
<div className="flex flex-1 overflow-hidden relative">
- <LeftPanel
+ {!hasOpenDocument ? (
+ <WelcomeScreen
+ userName={appSettings.userName}
+ onNewDocument={() => setIsNewCanvasModalOpen(true)}
+ onOpenFile={handleTriggerOpenFile}
+ onSelectRecentDocument={handleSelectWelcomeDocument}
+ showToast={showToast}
+ themePreset={appSettings.themePreset}
+ />
+ ) : (
+ <>
+ <LeftPanel
currentTool={tool}
onSelectTool={handleSelectTool}
brushSettings={brushSettings}
onUpdateBrushSettings={updateBrushSettings}
primaryColor={primaryColor}
secondaryColor={secondaryColor}
+ isTransparentColor={isTransparentColor}
+ onToggleTransparentColor={toggleTransparentColor}
onPrimaryColorChange={handlePrimaryColorChange}
onSecondaryColorChange={handleSecondaryColorChange}
onSwapColors={handleSwapColors}
@@ -4287,6 +4564,7 @@ export function App() {
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
layers={layers}
+ layerCanvasesRef={layerCanvasesRef}
registerLayerCanvas={registerLayerCanvas}
getEffectiveOpacity={getEffectiveOpacity}
isLayerEffectivelyVisible={isLayerEffectivelyVisible}
@@ -4353,7 +4631,7 @@ export function App() {
onJumpToHistory={jumpToHistoryIndex}
canUndo={hasOpenDocument && canUndo}
canRedo={hasOpenDocument && canRedo}
- onUndo={undo}
+ onUndo={handleUndo}
onRedo={redo}
layers={hasOpenDocument ? layers : []}
activeLayerId={hasOpenDocument ? activeLayerId : ''}
@@ -4366,6 +4644,8 @@ export function App() {
onSetOpacity={handleSetOpacity}
onSetBlendMode={setBlendMode}
onToggleLock={toggleLock}
+ onToggleAlphaLock={toggleAlphaLock}
+ onToggleClipping={toggleClipping}
onToggleCollapse={toggleCollapse}
onRenameLayer={handleRenameLayer}
onMoveLayer={moveLayer}
@@ -4388,6 +4668,8 @@ export function App() {
width={rightSidebarWidth}
onWidthChange={handleRightSidebarWidthChange}
/>
+ </>
+ )}
</div>
{/* Bottom Status Bar */}
@@ -4506,6 +4788,12 @@ export function App() {
<span className="font-medium">{toastMessage}</span>
</div>
)}
+
+ {/* First Time Setup Name Modal */}
+ <FirstTimeNameModal
+ isOpen={!appSettings.hasPromptedName && !appSettings.userName}
+ onSaveName={handleSaveFirstTimeName}
+ />
</div>
);
}
diff --git a/src/components/BrushPreview.tsx b/src/components/BrushPreview.tsx
index f70bf98..f368d2e 100644
--- a/src/components/BrushPreview.tsx
+++ b/src/components/BrushPreview.tsx
@@ -103,6 +103,7 @@ export const BrushPreview: React.FC<BrushPreviewProps> = React.memo(({
opacity: settings?.opacity,
grain: settings?.grain,
hardness: settings?.hardness,
+ spacing: settings?.spacing,
minSizeFactor: settings?.minSizeFactor,
thickness: settings?.thickness,
antiAlias: settings?.antiAlias,
@@ -137,7 +138,9 @@ export const BrushPreview: React.FC<BrushPreviewProps> = React.memo(({
settings?.opacity,
settings?.grain,
settings?.hardness,
+ settings?.spacing,
settings?.minSizeFactor,
+ settings?.thickness,
settings?.usePressure,
settings?.customTipImage,
settings?.customTipAngle,
diff --git a/src/components/BrushSizePalette.tsx b/src/components/BrushSizePalette.tsx
index de36d17..2a60f61 100644
--- a/src/components/BrushSizePalette.tsx
+++ b/src/components/BrushSizePalette.tsx
@@ -3,7 +3,6 @@ import {
Menu,
Pencil,
Paintbrush,
- Palette,
Square,
Eraser,
RotateCcw,
@@ -57,9 +56,6 @@ export const BrushSizePalette: React.FC<BrushSizePaletteProps> = ({
if (presetId?.startsWith('pencil')) {
return <Pencil className="w-3.5 h-3.5 text-amber-400 shrink-0" />;
}
- if (presetId === 'oil-thick' || presetId === 'oil-glaze' || presetId === 'blend-smudge') {
- return <Palette className="w-3.5 h-3.5 text-emerald-400 shrink-0" />;
- }
if (presetId === 'square-digital') {
return <Square className="w-3.5 h-3.5 text-teal-400 shrink-0" />;
}
diff --git a/src/components/CanvasArea.tsx b/src/components/CanvasArea.tsx
index 94e1487..ce03cc0 100644
--- a/src/components/CanvasArea.tsx
+++ b/src/components/CanvasArea.tsx
@@ -16,6 +16,10 @@ import { TextEditorOverlay } from './TextEditorOverlay';
import { PerspectiveRulerOverlay } from './PerspectiveRulerOverlay';
import { PerspectiveRuler, ConstraintAxis } from '../types/perspective';
import { Local3DContainer } from './Local3DContainer';
+import { ViewportCompositor } from '../utils/compositor';
+import { globalTileGrid } from '../utils/tileEngine';
+import { getBrushTipOutline, resolveBrushTipImage, TipOutline } from '../utils/brushOutline';
+import { preloadTipImage } from '../utils/brushStorage';
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`;
@@ -42,6 +46,7 @@ interface CanvasAreaProps {
onPointerEnter: () => void;
onPointerLeave: () => void;
layers: LayerItem[];
+ layerCanvasesRef?: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
registerLayerCanvas: (id: string, canvas: HTMLCanvasElement | null) => void;
getEffectiveOpacity: (layer: LayerItem) => number;
isLayerEffectivelyVisible: (layer: LayerItem) => boolean;
@@ -104,9 +109,10 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
onPointerEnter,
onPointerLeave,
layers,
+ layerCanvasesRef,
registerLayerCanvas,
- getEffectiveOpacity,
- isLayerEffectivelyVisible,
+ getEffectiveOpacity: _getEffectiveOpacity,
+ isLayerEffectivelyVisible: _isLayerEffectivelyVisible,
interactionRef,
showCheckerboard = true,
hasOpenDocument = true,
@@ -145,9 +151,73 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
}) => {
const effectiveDraftCanvasRef = draftCanvasRef || strokeCanvasRef;
- // Cursor preview diameter scaled to screen pixels
+
+ // Resolve tip image and extract vector outline silhouette
+ const activeTipImage = resolveBrushTipImage(brushSettings);
+ const [tipOutline, setTipOutline] = useState<TipOutline | null>(() => {
+ return activeTipImage ? getBrushTipOutline(activeTipImage) : null;
+ });
+
+ useEffect(() => {
+ let isCancelled = false;
+
+ if (activeTipImage) {
+ if (activeTipImage.complete && activeTipImage.naturalWidth > 0) {
+ setTipOutline(getBrushTipOutline(activeTipImage));
+ } else {
+ const handleLoad = () => {
+ if (!isCancelled) {
+ setTipOutline(getBrushTipOutline(activeTipImage));
+ }
+ };
+ activeTipImage.addEventListener('load', handleLoad, { once: true });
+ }
+ return () => {
+ isCancelled = true;
+ };
+ }
+
+ if (brushSettings.customTipDataUrl) {
+ preloadTipImage(brushSettings.customTipDataUrl)
+ .then((img) => {
+ if (!isCancelled) {
+ setTipOutline(getBrushTipOutline(img));
+ }
+ })
+ .catch(() => {
+ if (!isCancelled) {
+ setTipOutline(null);
+ }
+ });
+ return () => {
+ isCancelled = true;
+ };
+ }
+
+ setTipOutline(null);
+ }, [activeTipImage, brushSettings.customTipDataUrl, brushSettings.preset]);
+
+ // Dynamic cursor dimensions according to brush tip shape, aspect ratio, and thickness
+ const isCustomTip = Boolean(tipOutline && (tool === 'brush' || tool === 'eraser'));
+ const isSquare = brushSettings.preset === 'square-digital' && !tipOutline;
+ const tipAspect = isCustomTip && tipOutline ? tipOutline.height / tipOutline.width : 1.0;
+
const activeToolSize = tool === 'liquify' && liquifySettings ? liquifySettings.size : brushSettings.size;
- const cursorDiameter = Math.max(4, activeToolSize * zoom);
+ const cursorBaseWidth = Math.max(4, activeToolSize * zoom);
+ const thicknessRatio = tool === 'brush' ? (brushSettings.thickness ?? 1.0) : 1.0;
+
+ const cursorWidth = brushSettings.thicknessVertical && tool === 'brush'
+ ? Math.max(2, cursorBaseWidth * thicknessRatio)
+ : cursorBaseWidth;
+ const cursorHeight = brushSettings.thicknessVertical && tool === 'brush'
+ ? Math.max(2, cursorBaseWidth * tipAspect)
+ : Math.max(2, cursorBaseWidth * tipAspect * thicknessRatio);
+
+ // Brush tip rotation: tip angle relative to canvas + viewport canvas rotation
+ const totalAngleDeg = (tool === 'brush' ? (brushSettings.customTipAngle ?? 0) : 0) + rotation;
+ const totalAngleRef = useRef(totalAngleDeg);
+ totalAngleRef.current = totalAngleDeg;
+ const lastPointerPosRef = useRef<{ x: number; y: number } | null>(null);
// Dynamic on-canvas brush resizing via Ctrl + Alt + Drag
const [isCtrlAltDown, setIsCtrlAltDown] = useState(false);
@@ -158,9 +228,18 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
hardness: brushSettings.hardness ?? 1.0,
});
- // Zero-latency direct DOM cursor preview ring
+ // Zero-latency direct DOM cursor preview element
const cursorRingRef = useRef<HTMLDivElement | null>(null);
+ // Update cursor rotation in-place when viewport rotates or brush tip angle changes while hovering
+ useEffect(() => {
+ const ring = cursorRingRef.current;
+ const pos = lastPointerPosRef.current;
+ if (ring && pos && ring.style.display !== 'none') {
+ ring.style.transform = `translate3d(${pos.x}px, ${pos.y}px, 0) translate(-50%, -50%) rotate(${totalAngleDeg}deg)`;
+ }
+ }, [totalAngleDeg]);
+
useEffect(() => {
const viewport = viewportRef.current;
if (!viewport) return;
@@ -199,13 +278,16 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
return;
}
- ring.style.transform = `translate3d(${x}px, ${y}px, 0) translate(-50%, -50%)`;
+ lastPointerPosRef.current = { x, y };
+ const currentAngle = totalAngleRef.current;
+ ring.style.transform = `translate3d(${x}px, ${y}px, 0) translate(-50%, -50%) rotate(${currentAngle}deg)`;
if (ring.style.display !== 'block') {
ring.style.display = 'block';
}
};
const handlePointerLeave = () => {
+ lastPointerPosRef.current = null;
if (cursorRingRef.current) {
cursorRingRef.current.style.display = 'none';
}
@@ -219,28 +301,134 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
viewport.removeEventListener('pointermove', handleWindowPointerMove);
viewport.removeEventListener('pointerleave', handlePointerLeave);
};
- }, [isSpaceDown, isPanning, isRotating, isRotateModifier, isResizingBrush, viewportRef]);
+ }, [isSpaceDown, isPanning, isRotating, isRotateModifier, isResizingBrush, viewportRef, tool]);
+
+ // Unified GPU Viewport Compositor
+ const viewportCanvasRef = useRef<HTMLCanvasElement | null>(null);
+ const compositorRef = useRef<ViewportCompositor | null>(null);
- // Synchronize draft overlay canvas resolution with the screen viewport
+ // Synchronize viewport and draft overlay canvas resolution with the screen viewport
useEffect(() => {
- const updateDraftCanvasSize = () => {
+ const updateCanvasSizes = () => {
const viewport = viewportRef.current;
- const draftCanvas = effectiveDraftCanvasRef?.current;
- if (!viewport || !draftCanvas) return;
+ if (!viewport) return;
const rect = viewport.getBoundingClientRect();
const dpr = window.devicePixelRatio || 1;
const w = Math.max(1, Math.ceil(rect.width * dpr));
const h = Math.max(1, Math.ceil(rect.height * dpr));
- if (draftCanvas.width !== w || draftCanvas.height !== h) {
+
+ const vCanvas = viewportCanvasRef.current;
+ if (vCanvas && (vCanvas.width !== w || vCanvas.height !== h)) {
+ vCanvas.width = w;
+ vCanvas.height = h;
+ if (!compositorRef.current) {
+ compositorRef.current = new ViewportCompositor(vCanvas);
+ }
+ compositorRef.current.resize(w, h);
+ compositorRef.current.render(
+ layers,
+ { pan, zoom, rotation },
+ dimensions,
+ globalTileGrid,
+ { dimensions, showCheckerboard, devicePixelRatio: dpr }
+ );
+ }
+
+ const draftCanvas = effectiveDraftCanvasRef?.current;
+ if (draftCanvas && (draftCanvas.width !== w || draftCanvas.height !== h)) {
draftCanvas.width = w;
draftCanvas.height = h;
}
};
- updateDraftCanvasSize();
- window.addEventListener('resize', updateDraftCanvasSize);
- return () => window.removeEventListener('resize', updateDraftCanvasSize);
- }, [viewportRef, effectiveDraftCanvasRef]);
+ updateCanvasSizes();
+ window.addEventListener('resize', updateCanvasSizes);
+ return () => window.removeEventListener('resize', updateCanvasSizes);
+ }, [viewportRef, effectiveDraftCanvasRef, layers, pan, zoom, rotation, dimensions, showCheckerboard]);
+
+ // Render scene using Unified GPU Viewport Compositor
+ useEffect(() => {
+ if (!viewportCanvasRef.current) return;
+ if (!compositorRef.current) {
+ compositorRef.current = new ViewportCompositor(viewportCanvasRef.current);
+ }
+
+ // Ingest unindexed layer canvases into globalTileGrid
+ if (layerCanvasesRef?.current) {
+ for (const layer of layers) {
+ if (layer.type === 'raster' || layer.type === 'vector' || layer.type === 'frame') {
+ let c = layerCanvasesRef.current.get(layer.id);
+ if (!c) {
+ c = document.createElement('canvas');
+ c.width = dimensions.width;
+ 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';
+ globalTileGrid.ingestCanvas(layer.id, c, isMono ? 'monochrome-1bit' : 'color-32bit');
+ }
+ }
+ }
+ }
+
+ const dpr = window.devicePixelRatio || 1;
+ compositorRef.current.render(
+ layers,
+ { pan, zoom, rotation },
+ dimensions,
+ globalTileGrid,
+ { dimensions, showCheckerboard, devicePixelRatio: dpr }
+ );
+ }, [layers, pan, zoom, rotation, dimensions, showCheckerboard, layerCanvasesRef, registerLayerCanvas]);
+
+ // Event-Driven Compositor Invalidation via SparseTileGrid subscription
+ useEffect(() => {
+ let rafId: number | null = null;
+ const renderCompositor = () => {
+ if (compositorRef.current) {
+ const dpr = window.devicePixelRatio || 1;
+ compositorRef.current.render(
+ layers,
+ { pan, zoom, rotation },
+ dimensions,
+ globalTileGrid,
+ { dimensions, showCheckerboard, devicePixelRatio: dpr }
+ );
+ }
+ };
+
+ const handleGridChange = (immediate?: boolean) => {
+ if (immediate) {
+ if (rafId !== null) {
+ cancelAnimationFrame(rafId);
+ rafId = null;
+ }
+ renderCompositor();
+ return;
+ }
+ if (rafId !== null) return;
+ rafId = requestAnimationFrame(() => {
+ rafId = null;
+ renderCompositor();
+ });
+ };
+
+ const unsubscribe = globalTileGrid.subscribe(handleGridChange);
+ return () => {
+ unsubscribe();
+ if (rafId !== null) cancelAnimationFrame(rafId);
+ };
+ }, [layers, pan, zoom, rotation, dimensions, showCheckerboard]);
+
+ useEffect(() => {
+ return () => {
+ if (compositorRef.current) {
+ compositorRef.current.dispose();
+ compositorRef.current = null;
+ }
+ };
+ }, []);
// Track Ctrl + Alt key combinations globally
useEffect(() => {
@@ -399,11 +587,14 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
return { cursor: 'crosshair' };
}
if (tool === 'liquify') {
- return { cursor: 'crosshair' };
+ return { cursor: isOverCanvas ? 'none' : 'default' };
}
if (tool === 'transform') {
return { cursor: 'default' };
}
+ if (tool === 'brush' || tool === 'eraser') {
+ return { cursor: isOverCanvas ? 'none' : 'default' };
+ }
return { cursor: isOverCanvas ? 'crosshair' : 'default' };
};
@@ -426,9 +617,6 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
);
}
- // Render order: bottom-to-top (reverse of UI list)
- const renderOrderLayers = layers.slice().reverse();
-
return (
<main
ref={viewportRef}
@@ -439,6 +627,17 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
...getCursorStyle(false),
}}
>
+ {/* Unified GPU Viewport Canvas (WebGL2 with Frustum Culling & Shaders) */}
+ <canvas
+ ref={viewportCanvasRef}
+ className="absolute inset-0 pointer-events-none z-10"
+ style={{
+ width: '100%',
+ height: '100%',
+ display: 'block',
+ }}
+ />
+
{/* Artboard Container with 2D Affine Transformation (Pan, Zoom, and Rotation) */}
<div
className="absolute origin-top-left select-none"
@@ -450,53 +649,24 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
boxShadow: '0 0 0 1px #161616, 0 10px 40px rgba(0, 0, 0, 0.55)',
willChange: 'transform',
imageRendering: zoom > 1 ? 'pixelated' : 'auto',
- backgroundColor: '#1c1c1c',
- backgroundImage: showCheckerboard
- ? `conic-gradient(#282828 90deg, #202020 90deg 180deg, #282828 180deg 270deg, #202020 270deg)`
- : 'none',
- backgroundSize: '16px 16px',
+ backgroundColor: 'transparent',
+ backgroundImage: 'none',
}}
>
- {/* Layer Canvas Stack rendered from Bottom to Top */}
- {renderOrderLayers.map((layer) => {
- if (layer.type === 'folder') return null;
-
- return (
- <canvas
- key={layer.id}
- ref={(el) => registerLayerCanvas(layer.id, el)}
- width={dimensions.width}
- height={dimensions.height}
- className="absolute inset-0 block pointer-events-none"
- style={{
- opacity: getEffectiveOpacity(layer),
- mixBlendMode: layer.blendMode,
- display: isLayerEffectivelyVisible(layer) ? 'block' : 'none',
- imageRendering: zoom > 1 ? 'pixelated' : 'auto',
- }}
- />
- );
- })}
-
- {/* Remote Peer Draft Canvases (rendered per active peer while peer is drawing) */}
+ {/* Remote Peer Live Stroke Draft Overlay Canvases */}
{peers.map((peer) => (
<canvas
key={`peer-canvas-${peer.id}`}
ref={(el) => {
if (remoteDraftCanvasesRef) {
- if (el) {
- remoteDraftCanvasesRef.current.set(peer.id, el);
- } else {
- remoteDraftCanvasesRef.current.delete(peer.id);
- }
+ if (el) remoteDraftCanvasesRef.current.set(peer.id, el);
+ else remoteDraftCanvasesRef.current.delete(peer.id);
}
}}
width={dimensions.width}
height={dimensions.height}
className="absolute inset-0 block pointer-events-none z-15"
- style={{
- imageRendering: zoom > 1 ? 'pixelated' : 'auto',
- }}
+ style={{ imageRendering: zoom > 1 ? 'pixelated' : 'auto' }}
/>
))}
@@ -653,58 +823,158 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
/>
)}
- {/* Dynamic Dual-Tone Brush Size Outline Ring (CSP / Photoshop style) */}
+ {/* Dynamic Dual-Tone Brush Silhouette Outline Cursor (CSP / Photoshop style) */}
<div
ref={cursorRingRef}
- className="pointer-events-none absolute top-0 left-0 rounded-full z-30 select-none"
+ className="pointer-events-none absolute top-0 left-0 z-30 select-none"
style={{
display: 'none',
- width: `${cursorDiameter}px`,
- height: `${cursorDiameter}px`,
- border: '1px solid rgba(0, 0, 0, 0.75)',
- boxShadow: '0 0 0 1px rgba(255, 255, 255, 0.75)',
+ width: `${cursorWidth}px`,
+ height: `${cursorHeight}px`,
willChange: 'transform',
+ transformOrigin: 'center center',
}}
- />
+ >
+ <svg
+ viewBox={isCustomTip && tipOutline ? tipOutline.viewBox : '0 0 100 100'}
+ className="w-full h-full overflow-visible pointer-events-none select-none"
+ style={{ display: 'block' }}
+ >
+ {isCustomTip && tipOutline ? (
+ <>
+ <path
+ d={tipOutline.path}
+ fill="none"
+ stroke="rgba(255, 255, 255, 0.85)"
+ strokeWidth="2.5"
+ strokeLinejoin="round"
+ strokeLinecap="round"
+ vectorEffect="non-scaling-stroke"
+ />
+ <path
+ d={tipOutline.path}
+ fill="none"
+ stroke="rgba(0, 0, 0, 0.85)"
+ strokeWidth="1"
+ strokeLinejoin="round"
+ strokeLinecap="round"
+ vectorEffect="non-scaling-stroke"
+ />
+ </>
+ ) : isSquare ? (
+ <>
+ <rect
+ x="1"
+ y="1"
+ width="98"
+ height="98"
+ fill="none"
+ stroke="rgba(255, 255, 255, 0.85)"
+ strokeWidth="2.5"
+ vectorEffect="non-scaling-stroke"
+ />
+ <rect
+ x="1"
+ y="1"
+ width="98"
+ height="98"
+ fill="none"
+ stroke="rgba(0, 0, 0, 0.85)"
+ strokeWidth="1"
+ vectorEffect="non-scaling-stroke"
+ />
+ </>
+ ) : (
+ <>
+ <ellipse
+ cx="50"
+ cy="50"
+ rx="49.5"
+ ry="49.5"
+ fill="none"
+ stroke="rgba(255, 255, 255, 0.85)"
+ strokeWidth="2.5"
+ vectorEffect="non-scaling-stroke"
+ />
+ <ellipse
+ cx="50"
+ cy="50"
+ rx="49.5"
+ ry="49.5"
+ fill="none"
+ stroke="rgba(0, 0, 0, 0.85)"
+ strokeWidth="1"
+ vectorEffect="non-scaling-stroke"
+ />
+ </>
+ )}
+ </svg>
+ </div>
- {/* Floating Visual Preview Circle for On-Canvas Brush Resizing (Ctrl + Alt + Drag) */}
+ {/* Floating Visual Preview for On-Canvas Brush Resizing (Ctrl + Alt + Drag) */}
{isResizingBrush && (
<div
className="pointer-events-none absolute -translate-x-1/2 -translate-y-1/2 z-50 flex items-center justify-center"
style={{
left: `${resizePreviewX}px`,
top: `${resizePreviewY}px`,
- width: `${cursorDiameter}px`,
- height: `${cursorDiameter}px`,
+ width: `${cursorWidth}px`,
+ height: `${cursorHeight}px`,
+ transform: `translate(-50%, -50%) rotate(${totalAngleDeg}deg)`,
+ transformOrigin: 'center center',
}}
>
- {/* Outer diameter & hardness preview circle */}
- <div
- className="w-full h-full rounded-full border-2 border-white shadow-[0_0_0_1px_rgba(0,0,0,0.8),0_4px_16px_rgba(0,0,0,0.5)] transition-[width,height] duration-75"
- style={{
- background:
- (brushSettings.hardness ?? 1.0) < 0.98
- ? `radial-gradient(circle, rgba(239, 68, 68, 0.45) 0%, rgba(239, 68, 68, 0.45) ${Math.round(
- (brushSettings.hardness ?? 1.0) * 100
- )}%, rgba(239, 68, 68, 0.05) 100%)`
- : 'rgba(239, 68, 68, 0.38)',
- }}
- />
+ {isCustomTip && tipOutline ? (
+ <svg
+ viewBox={tipOutline.viewBox}
+ className="w-full h-full overflow-visible pointer-events-none"
+ style={{ display: 'block' }}
+ >
+ <path
+ d={tipOutline.path}
+ fill="rgba(239, 68, 68, 0.35)"
+ stroke="rgba(255, 255, 255, 0.95)"
+ strokeWidth="2.5"
+ strokeLinejoin="round"
+ vectorEffect="non-scaling-stroke"
+ />
+ <path
+ d={tipOutline.path}
+ fill="none"
+ stroke="rgba(0, 0, 0, 0.9)"
+ strokeWidth="1"
+ strokeLinejoin="round"
+ vectorEffect="non-scaling-stroke"
+ />
+ </svg>
+ ) : (
+ <>
+ {/* Outer diameter & hardness preview circle */}
+ <div
+ className={`w-full h-full ${isSquare ? 'rounded-none' : 'rounded-full'} border-2 border-white shadow-[0_0_0_1px_rgba(0,0,0,0.8),0_4px_16px_rgba(0,0,0,0.5)] transition-[width,height] duration-75`}
+ style={{
+ background:
+ (brushSettings.hardness ?? 1.0) < 0.98
+ ? `radial-gradient(circle, rgba(239, 68, 68, 0.45) 0%, rgba(239, 68, 68, 0.45) ${Math.round(
+ (brushSettings.hardness ?? 1.0) * 100
+ )}%, rgba(239, 68, 68, 0.05) 100%)`
+ : 'rgba(239, 68, 68, 0.38)',
+ }}
+ />
- {/* Inner hardness boundary indicator if soft brush */}
- {(brushSettings.hardness ?? 1.0) < 0.98 && (
- <div
- className="absolute rounded-full border border-dashed border-white/80 pointer-events-none"
- style={{
- width: `${Math.max(2, cursorDiameter * (brushSettings.hardness ?? 1.0))}px`,
- height: `${Math.max(2, cursorDiameter * (brushSettings.hardness ?? 1.0))}px`,
- }}
- />
+ {/* Inner hardness boundary indicator if soft brush */}
+ {(brushSettings.hardness ?? 1.0) < 0.98 && (
+ <div
+ className={`absolute ${isSquare ? 'rounded-none' : 'rounded-full'} border border-dashed border-white/80 pointer-events-none`}
+ style={{
+ width: `${Math.max(2, cursorWidth * (brushSettings.hardness ?? 1.0))}px`,
+ height: `${Math.max(2, cursorHeight * (brushSettings.hardness ?? 1.0))}px`,
+ }}
+ />
+ )}
+ </>
)}
- {/* Anchor center crosshair */}
- <div className="absolute w-2 h-2 rounded-full bg-white border border-black pointer-events-none shadow-sm" />
-
{/* 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"
diff --git a/src/components/ColorPanel.tsx b/src/components/ColorPanel.tsx
index f2cecde..5a142fc 100644
--- a/src/components/ColorPanel.tsx
+++ b/src/components/ColorPanel.tsx
@@ -20,6 +20,7 @@ export interface ColorPanelProps {
onSelectTool?: (tool: ToolType) => void;
recentColors?: string[];
containerWidth?: number;
+ containerHeight?: number;
}
// Clip Studio Paint style 3-slider horizontal icon
@@ -45,6 +46,7 @@ export const ColorPanel: React.FC<ColorPanelProps> = ({
onSelectTool,
recentColors = [],
containerWidth = 320,
+ containerHeight,
}) => {
// Active palette tab: 'wheel' | 'slider'
const [activeTab, setActiveTab] = useState<'wheel' | 'slider'>(() => {
@@ -91,11 +93,12 @@ export const ColorPanel: React.FC<ColorPanelProps> = ({
// Determine if tab labels should be compact icon-only when narrow
const isNarrow = containerWidth < 275;
+ const contentHeight = containerHeight ? Math.max(80, containerHeight - 30) : undefined;
return (
- <div className="flex flex-col select-none text-[#cccccc] text-xs">
+ <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] relative">
+ <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 */}
@@ -241,48 +244,9 @@ export const ColorPanel: React.FC<ColorPanelProps> = ({
</div>
{/* Palette Content Area */}
- {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}
- 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}
- 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>
+ <div className="flex-1 min-h-0 overflow-y-auto">
+ {viewMode === 'tabbed' ? (
+ activeTab === 'wheel' ? (
<ColorWheel
primaryColor={primaryColor}
secondaryColor={secondaryColor}
@@ -292,19 +256,14 @@ export const ColorPanel: React.FC<ColorPanelProps> = ({
colorMode={colorMode}
currentTool={currentTool}
onSelectTool={onSelectTool}
- recentColors={[]}
+ recentColors={recentColors}
containerWidth={containerWidth}
+ containerHeight={contentHeight}
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}
@@ -316,13 +275,63 @@ export const ColorPanel: React.FC<ColorPanelProps> = ({
onSelectTool={onSelectTool}
recentColors={recentColors}
containerWidth={containerWidth}
+ containerHeight={contentHeight}
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>
- </div>
- )}
+ )}
+ </div>
</div>
);
};
diff --git a/src/components/ColorSlider.tsx b/src/components/ColorSlider.tsx
index d6885e2..57ee814 100644
--- a/src/components/ColorSlider.tsx
+++ b/src/components/ColorSlider.tsx
@@ -31,6 +31,7 @@ export interface ColorSliderProps {
onSelectTool?: (tool: ToolType) => void;
recentColors?: string[];
containerWidth?: number;
+ containerHeight?: number;
activeTarget?: 'primary' | 'secondary';
onActiveTargetChange?: (target: 'primary' | 'secondary') => void;
hideHeader?: boolean;
@@ -58,7 +59,8 @@ export const ColorSlider: React.FC<ColorSliderProps> = ({
currentTool = 'brush',
onSelectTool,
recentColors = [],
- containerWidth: _containerWidth = 320,
+ containerWidth = 320,
+ containerHeight,
activeTarget: controlledActiveTarget,
onActiveTargetChange,
hideHeader = false,
@@ -92,6 +94,34 @@ export const ColorSlider: React.FC<ColorSliderProps> = ({
const [hsvValues, setHsvValues] = useState(() => hexToHsv(activeColor));
const [cmykValues, setCmykValues] = useState(() => hexToCmyk(activeColor));
+ // Container sizing
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const [measuredSize, setMeasuredSize] = useState<{ width: number; height: number }>({
+ width: containerWidth,
+ height: containerHeight || 0,
+ });
+
+ useEffect(() => {
+ const el = containerRef.current;
+ if (!el) return;
+ 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),
+ });
+ }
+ });
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, [containerWidth, containerHeight]);
+
+ const effectiveHeight = containerHeight || measuredSize.height || 0;
+ const trackHeight = effectiveHeight > 340 ? 12 : effectiveHeight > 260 ? 10 : 8;
+ const swatchHeight = effectiveHeight > 300 ? 'h-7' : 'h-6';
+ const spacingClass = effectiveHeight > 320 ? 'space-y-3' : effectiveHeight > 240 ? 'space-y-2' : 'space-y-1';
+
// Sync color representation when external activeColor changes (if not dragging)
useEffect(() => {
if (draggingChannelRef.current) return;
@@ -338,10 +368,10 @@ export const ColorSlider: React.FC<ColorSliderProps> = ({
};
return (
- <div className="flex flex-col select-none text-[#cccccc] text-xs">
+ <div ref={containerRef} className="flex flex-col select-none text-[#cccccc] text-xs h-full justify-between">
{/* Optional Standalone Header if rendered outside ColorPanel */}
{!hideHeader && (
- <div className="bg-[#2a2a2a] px-3 py-1.5 border-b border-[#333333] flex items-center justify-between">
+ <div className="bg-[#2a2a2a] px-3 py-1.5 border-b border-[#333333] flex items-center justify-between shrink-0">
<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">
@@ -364,7 +394,7 @@ export const ColorSlider: React.FC<ColorSliderProps> = ({
)}
{/* Main Slider Area matching Clip Studio Paint Photo 2 */}
- <div className="p-3 space-y-3">
+ <div className="p-2.5 flex-1 flex flex-col justify-between space-y-2">
{/* Sliders Container with Left Vertical Mode Selector Strip */}
<div className="flex items-stretch">
{/* Vertical Color Model Selector (CMYK, HSV, RGB rotated -90deg matching screenshot) */}
@@ -416,7 +446,7 @@ export const ColorSlider: React.FC<ColorSliderProps> = ({
</div>
{/* Main Slider Box */}
- <div className="flex-1 bg-[#2b2b2e] border border-[#3e3e42] rounded-r-[3px] p-2.5 space-y-2">
+ <div className={`flex-1 bg-[#2b2b2e] border border-[#3e3e42] rounded-r-[3px] p-2.5 ${spacingClass}`}>
{channels.map((channel) => (
<div key={channel.id} className="flex items-center space-x-2">
{/* Channel Label (R, G, B, H, S, V, C, M, Y, K) */}
@@ -432,13 +462,13 @@ export const ColorSlider: React.FC<ColorSliderProps> = ({
onPointerUp={(e) => handlePointerUp(channel.id, e)}
onPointerCancel={(e) => handlePointerUp(channel.id, e)}
>
- {/* Track Bar (h-2, rounded-[1px], dynamic gradient) */}
+ {/* Track Bar (dynamic height, rounded-[1px], dynamic gradient) */}
<div
ref={(el) => {
trackRefs.current[channel.id] = el;
}}
- style={{ background: channel.gradient }}
- className="relative h-2 w-full rounded-[1px] border border-[#1b1b1b] shadow-inner"
+ style={{ background: channel.gradient, height: trackHeight }}
+ className="relative w-full rounded-[1px] border border-[#1b1b1b] shadow-inner"
/>
{/* Caret Row (triangle pointing straight UP into the track matching Photo 2) */}
@@ -506,7 +536,7 @@ export const ColorSlider: React.FC<ColorSliderProps> = ({
if (currentTool === 'eraser' && onSelectTool) onSelectTool('brush');
}}
title={`Primary Color: ${primaryColor} (Click to select & edit)`}
- className={`flex-1 h-6 rounded-[3px] cursor-pointer transition-all relative overflow-hidden ${
+ className={`flex-1 ${swatchHeight} rounded-[3px] cursor-pointer transition-all relative overflow-hidden ${
activeTarget === 'primary' && !isTransparentActive
? 'ring-2 ring-[#7c91c0] ring-offset-1 ring-offset-[#252526] border border-black/80 shadow-sm z-10 scale-[1.02]'
: 'border border-[#555555] hover:border-[#888888]'
@@ -521,7 +551,7 @@ export const ColorSlider: React.FC<ColorSliderProps> = ({
if (currentTool === 'eraser' && onSelectTool) onSelectTool('brush');
}}
title={`Secondary Color: ${secondaryColor} (Click to select & edit)`}
- className={`flex-1 h-6 rounded-[3px] cursor-pointer transition-all relative overflow-hidden ${
+ className={`flex-1 ${swatchHeight} rounded-[3px] cursor-pointer transition-all relative overflow-hidden ${
activeTarget === 'secondary' && !isTransparentActive
? 'ring-2 ring-[#7c91c0] ring-offset-1 ring-offset-[#252526] border border-black/80 shadow-sm z-10 scale-[1.02]'
: 'border border-[#555555] hover:border-[#888888]'
@@ -533,7 +563,7 @@ export const ColorSlider: React.FC<ColorSliderProps> = ({
<button
onClick={handleToggleTransparent}
title="Transparent Color / Eraser Mode (C)"
- className={`flex-1 h-6 rounded-[3px] cursor-pointer transition-all relative overflow-hidden ${
+ className={`flex-1 ${swatchHeight} rounded-[3px] cursor-pointer transition-all relative overflow-hidden ${
isTransparentActive
? 'ring-2 ring-[#7c91c0] ring-offset-1 ring-offset-[#252526] border border-black/80 shadow-sm z-10 scale-[1.02]'
: 'border border-[#555555] hover:border-[#888888]'
diff --git a/src/components/ColorWheel.tsx b/src/components/ColorWheel.tsx
index 8911362..879b496 100644
--- a/src/components/ColorWheel.tsx
+++ b/src/components/ColorWheel.tsx
@@ -32,6 +32,7 @@ export interface ColorWheelProps {
onSelectTool?: (tool: ToolType) => void;
recentColors?: string[];
containerWidth?: number;
+ containerHeight?: number;
activeTarget?: 'primary' | 'secondary';
onActiveTargetChange?: (target: 'primary' | 'secondary') => void;
hideHeader?: boolean;
@@ -51,6 +52,7 @@ export const ColorWheel: React.FC<ColorWheelProps> = ({
onSelectTool,
recentColors = [],
containerWidth = 320,
+ containerHeight,
activeTarget: controlledActiveTarget,
onActiveTargetChange,
hideHeader = false,
@@ -107,38 +109,50 @@ export const ColorWheel: React.FC<ColorWheelProps> = ({
}
}, [activeColor]);
- const [measuredWidth, setMeasuredWidth] = useState<number>(containerWidth);
+ const [measuredSize, setMeasuredSize] = useState<{ width: number; height: number }>({
+ width: containerWidth,
+ height: containerHeight || 0,
+ });
useEffect(() => {
const el = containerRef.current;
if (!el) return;
const ro = new ResizeObserver((entries) => {
for (const entry of entries) {
- const w = entry.contentRect.width;
- if (w > 0) {
- setMeasuredWidth(Math.round(w));
- }
+ const { width: w, height: h } = entry.contentRect;
+ setMeasuredSize({
+ width: w > 0 ? Math.round(w) : containerWidth,
+ height: h > 0 ? Math.round(h) : (containerHeight || 0),
+ });
}
});
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;
- // Dynamically compute canvas diameter to fit sidebar neatly
- const effectiveWidth = measuredWidth || containerWidth;
const wheelSize = useMemo(() => {
- const pad = 28;
- const available = effectiveWidth > 0 ? effectiveWidth - pad : 250;
- return Math.max(180, Math.min(270, available));
- }, [effectiveWidth]);
+ 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]);
// Dimensions & radiuses
const cx = wheelSize / 2;
const cy = wheelSize / 2;
- const outerRadius = wheelSize / 2 - 8;
- const ringThickness = Math.max(18, Math.round(wheelSize * 0.088));
+ const outerRadius = Math.max(20, wheelSize / 2 - 8);
+ const ringThickness = Math.max(14, Math.round(wheelSize * 0.088));
const innerRadius = outerRadius - ringThickness;
- const squareSize = Math.floor((innerRadius - 10) * Math.SQRT2);
+ const squareSize = Math.max(10, Math.floor((innerRadius - 8) * Math.SQRT2));
const sqX = cx - squareSize / 2;
const sqY = cy - squareSize / 2;
@@ -218,7 +232,7 @@ export const ColorWheel: React.FC<ColorWheelProps> = ({
const midRadius = (outerRadius + innerRadius) / 2;
const indicatorSpan = ringThickness + 6;
- const indicatorWidth = 10;
+ const indicatorWidth = Math.max(6, Math.min(14, Math.round(wheelSize * 0.045)));
const indX = midRadius - indicatorSpan / 2;
const indY = -indicatorWidth / 2;
@@ -270,15 +284,16 @@ export const ColorWheel: React.FC<ColorWheelProps> = ({
const curX = sqX + hsv.s * squareSize;
const curY = sqY + (1 - hsv.v) * squareSize;
+ 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, 5.5, 0, Math.PI * 2);
+ ctx.arc(curX, curY, cursorRadius, 0, Math.PI * 2);
ctx.strokeStyle = '#000000';
ctx.lineWidth = 2.5;
ctx.stroke();
ctx.beginPath();
- ctx.arc(curX, curY, 5.5, 0, Math.PI * 2);
+ ctx.arc(curX, curY, cursorRadius, 0, Math.PI * 2);
ctx.strokeStyle = '#ffffff';
ctx.lineWidth = 1.5;
ctx.stroke();
@@ -357,14 +372,15 @@ export const ColorWheel: React.FC<ColorWheelProps> = ({
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, 5.5, 0, Math.PI * 2);
+ ctx.arc(curX, curY, cursorRadius, 0, Math.PI * 2);
ctx.strokeStyle = '#000000';
ctx.lineWidth = 2.5;
ctx.stroke();
ctx.beginPath();
- ctx.arc(curX, curY, 5.5, 0, Math.PI * 2);
+ ctx.arc(curX, curY, cursorRadius, 0, Math.PI * 2);
ctx.strokeStyle = '#ffffff';
ctx.lineWidth = 1.5;
ctx.stroke();
@@ -585,7 +601,7 @@ export const ColorWheel: React.FC<ColorWheelProps> = ({
};
return (
- <div ref={containerRef} className="flex flex-col select-none text-[#cccccc] text-xs">
+ <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">
@@ -630,7 +646,7 @@ export const ColorWheel: React.FC<ColorWheelProps> = ({
{/* Clip Studio Paint Bottom Controls: Dual Swatches + Transparent Swatch + H S V Readout + Mode Toggle */}
<div
- style={{ width: wheelSize }}
+ 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 */}
diff --git a/src/components/DeleteDocumentModal.tsx b/src/components/DeleteDocumentModal.tsx
new file mode 100644
index 0000000..97fd8fa
--- /dev/null
+++ b/src/components/DeleteDocumentModal.tsx
@@ -0,0 +1,123 @@
+import React from 'react';
+import { Trash2, EyeOff, AlertTriangle, X, FileText } from 'lucide-react';
+import { RecentDocument, formatFileSize } from '../utils/recentDocumentsManager';
+
+interface DeleteDocumentModalProps {
+ isOpen: boolean;
+ document: RecentDocument | null;
+ onClose: () => void;
+ onHideFromApp: (doc: RecentDocument) => void;
+ onPermanentlyDelete: (doc: RecentDocument) => void;
+}
+
+export const DeleteDocumentModal: React.FC<DeleteDocumentModalProps> = ({
+ isOpen,
+ document,
+ onClose,
+ onHideFromApp,
+ onPermanentlyDelete,
+}) => {
+ if (!isOpen || !document) return null;
+
+ return (
+ <div
+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 select-none"
+ 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-md overflow-hidden text-[#d6d6da]">
+ {/* Title Bar */}
+ <div className="px-3.5 py-2 border-b border-[#242426] bg-gradient-to-b from-[#525255] to-[#3e3e40] flex items-center justify-between">
+ <div className="flex items-center space-x-2">
+ <Trash2 className="w-3.5 h-3.5 text-rose-400" />
+ <span className="text-xs font-semibold text-[#f0f0f4] tracking-wide">
+ Delete Document
+ </span>
+ </div>
+ <button
+ onClick={onClose}
+ className="p-0.5 rounded-[2px] text-[#a0a0a5] hover:text-white hover:bg-[#525255] transition-colors"
+ >
+ <X className="w-3.5 h-3.5" />
+ </button>
+ </div>
+
+ {/* Content */}
+ <div className="p-4 space-y-3.5 text-xs">
+ {/* Target File Info */}
+ <div className="bg-[#2b2b2e] border border-[#1e1e20] rounded-[2px] p-2.5 flex items-center space-x-3 shadow-[inset_1px_1px_2px_rgba(0,0,0,0.4)]">
+ <div className="w-10 h-10 bg-[#202022] border border-[#1a1a1c] overflow-hidden shrink-0 flex items-center justify-center rounded-[1px]">
+ {document.coverUrl ? (
+ <img
+ src={document.coverUrl}
+ alt={document.title}
+ className="w-full h-full object-cover"
+ />
+ ) : (
+ <FileText className="w-5 h-5 text-[#6c6c72]" />
+ )}
+ </div>
+ <div className="flex-1 min-w-0">
+ <div className="font-medium text-[#f0f0f4] truncate" title={document.title}>
+ {document.title}
+ </div>
+ <div className="text-[10px] text-[#8c8c92] font-mono truncate" title={document.path}>
+ {formatFileSize(document.size)} • {document.path}
+ </div>
+ </div>
+ </div>
+
+ <p className="text-[11px] text-[#a0a0a5]">
+ Select action:
+ </p>
+
+ {/* Action 1: Remove from list */}
+ <button
+ type="button"
+ onClick={() => onHideFromApp(document)}
+ className="w-full flex items-start space-x-2.5 p-2.5 rounded-[2px] border border-[#2b2b2e] bg-[#3a3a3d] hover:bg-[#46464a] hover:border-[#525256] text-left transition-colors cursor-pointer"
+ >
+ <EyeOff className="w-4 h-4 text-[#93c5fd] shrink-0 mt-0.5" />
+ <div>
+ <div className="font-medium text-[#f0f0f4]">
+ Remove from Recent List
+ </div>
+ <div className="text-[10px] text-[#8c8c92] mt-0.5">
+ Removes entry from the studio. Keeps the file intact on disk.
+ </div>
+ </div>
+ </button>
+
+ {/* Action 2: Permanently delete */}
+ <button
+ type="button"
+ onClick={() => onPermanentlyDelete(document)}
+ className="w-full flex items-start space-x-2.5 p-2.5 rounded-[2px] border border-rose-900/50 bg-[#3d2c2f] hover:bg-[#4a3438] hover:border-rose-700/60 text-left transition-colors cursor-pointer"
+ >
+ <AlertTriangle className="w-4 h-4 text-rose-400 shrink-0 mt-0.5" />
+ <div>
+ <div className="font-medium text-rose-200">
+ Permanently Delete from Disk
+ </div>
+ <div className="text-[10px] text-rose-300/70 mt-0.5">
+ Erases file permanently from storage. Cannot be undone.
+ </div>
+ </div>
+ </button>
+ </div>
+
+ {/* Footer */}
+ <div className="px-4 py-2 bg-[#3a3a3d] border-t border-[#242426] flex justify-end">
+ <button
+ type="button"
+ onClick={onClose}
+ className="px-3 py-1 rounded-[2px] text-xs font-medium bg-gradient-to-b from-[#56565a] to-[#424245] hover:from-[#626266] hover:to-[#4b4b4e] border border-[#242426] text-[#d6d6da] shadow-[inset_0_1px_0_rgba(255,255,255,0.18)] cursor-pointer"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/src/components/DocumentTabBar.tsx b/src/components/DocumentTabBar.tsx
index a980669..6f8e05b 100644
--- a/src/components/DocumentTabBar.tsx
+++ b/src/components/DocumentTabBar.tsx
@@ -38,6 +38,85 @@ export const DocumentTabBar: React.FC<DocumentTabBarProps> = React.memo(({
setEditingId(null);
};
+ if (_themePreset === 'modern') {
+ return (
+ <div className="h-8 flex items-center px-2 select-none z-20 shrink-0 overflow-x-auto no-scrollbar bg-[#0f1015] border-b border-white/[0.08]">
+ {/* List of Document Tabs */}
+ <div className="flex items-center space-x-1.5 h-full py-1">
+ {documents.map((doc) => {
+ const isActive = doc.id === activeDocumentId;
+
+ 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-full flex items-center space-x-2 px-2.5 rounded-md text-xs cursor-pointer transition-all ${
+ isActive
+ ? 'bg-[#181920] text-white font-medium border border-white/[0.1] shadow-xs'
+ : 'text-white/60 hover:text-white/90 hover:bg-white/[0.04] border border-transparent'
+ }`}
+ >
+ {/* Document Icon */}
+ <File className={`w-3.5 h-3.5 shrink-0 ${isActive ? 'text-[var(--modern-accent)]' : 'text-white/40'}`} />
+
+ {/* Document Name / Inline Rename Input */}
+ {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-[#101116] text-white text-xs px-1.5 py-0.5 rounded-sm outline-none border border-[var(--modern-accent)] w-28"
+ />
+ ) : (
+ <span className="truncate max-w-[160px] tracking-normal">{doc.name}</span>
+ )}
+
+ {/* Close Button */}
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ onCloseDocument(doc.id);
+ }}
+ title="Close file"
+ className={`p-0.5 rounded transition-colors ${
+ isActive
+ ? 'text-white/50 hover:text-white hover:bg-white/10'
+ : 'text-transparent group-hover:text-white/40 hover:!text-white hover:bg-white/10'
+ }`}
+ >
+ <X className="w-3 h-3" />
+ </button>
+
+ {/* Active Tab Accent Underline */}
+ {isActive && (
+ <div className="absolute bottom-0 left-2 right-2 h-[2px] bg-[var(--modern-accent)] rounded-full" />
+ )}
+ </div>
+ );
+ })}
+ </div>
+
+ {/* New File (+) Button */}
+ <button
+ onClick={onNewDocument}
+ title="Create New File (Ctrl+N)"
+ className="ml-1 p-1 rounded-md transition-colors flex items-center justify-center shrink-0 cursor-pointer text-white/50 hover:text-white hover:bg-white/[0.08]"
+ >
+ <Plus className="w-3.5 h-3.5" />
+ </button>
+ </div>
+ );
+ }
+
return (
<div className="h-8 flex items-center px-2 select-none z-20 shrink-0 overflow-x-auto no-scrollbar transition-colors bg-[#333336] border-b border-[#232325]">
{/* List of Document Tabs */}
diff --git a/src/components/FirstTimeNameModal.tsx b/src/components/FirstTimeNameModal.tsx
new file mode 100644
index 0000000..70d9290
--- /dev/null
+++ b/src/components/FirstTimeNameModal.tsx
@@ -0,0 +1,67 @@
+import React, { useState } from 'react';
+import { User, Check } from 'lucide-react';
+
+interface FirstTimeNameModalProps {
+ isOpen: boolean;
+ onSaveName: (name: string) => void;
+}
+
+export const FirstTimeNameModal: React.FC<FirstTimeNameModalProps> = ({
+ isOpen,
+ onSaveName,
+}) => {
+ const [name, setName] = useState('');
+
+ if (!isOpen) return null;
+
+ const handleSubmit = (e: React.FormEvent) => {
+ e.preventDefault();
+ const finalName = name.trim() || 'Artist';
+ onSaveName(finalName);
+ };
+
+ return (
+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 select-none">
+ <div className="bg-[#444447] border border-[#242426] rounded-[2px] shadow-[0_8px_24px_rgba(0,0,0,0.7)] w-full max-w-sm overflow-hidden text-[#d6d6da]">
+ {/* Title Bar */}
+ <div className="px-4 py-2 border-b border-[#242426] bg-gradient-to-b from-[#525255] to-[#3e3e40] flex items-center space-x-2">
+ <User className="w-3.5 h-3.5 text-[#93c5fd]" />
+ <h2 className="text-xs font-semibold text-[#f0f0f4] tracking-wide">
+ Artist Profile
+ </h2>
+ </div>
+
+ <form onSubmit={handleSubmit} className="p-4 space-y-4">
+ <div className="space-y-1.5">
+ <label htmlFor="user-name-input" className="block text-xs font-medium text-[#cccccc]">
+ Display Name
+ </label>
+ <input
+ id="user-name-input"
+ type="text"
+ autoFocus
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder="Artist"
+ maxLength={40}
+ className="w-full px-2.5 py-1.5 bg-[#2b2b2e] border border-[#1e1e20] rounded-[2px] text-xs text-[#f0f0f4] placeholder-[#707075] outline-none focus:border-[#4a8fc7] shadow-[inset_1px_1px_2px_rgba(0,0,0,0.5)]"
+ />
+ <p className="text-[10px] text-[#8c8c92]">
+ Configures session metadata. Editable anytime in Preferences.
+ </p>
+ </div>
+
+ <div className="flex items-center justify-end space-x-2 pt-2 border-t border-[#363639]">
+ <button
+ type="submit"
+ className="flex items-center space-x-1 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"
+ >
+ <Check className="w-3.5 h-3.5 text-emerald-400" />
+ <span>Continue</span>
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+ );
+};
diff --git a/src/components/Header.tsx b/src/components/Header.tsx
index 80ce2b7..19c618f 100644
--- a/src/components/Header.tsx
+++ b/src/components/Header.tsx
@@ -70,6 +70,186 @@ export const Header: React.FC<HeaderProps> = React.memo(({
themePreset = 'vintage-manga',
activeDocumentTitle,
}) => {
+ 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-[#121318] border-b border-white/[0.08] text-[#e0e0e3]"
+ >
+ {/* Brand, Menus & 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} />
+
+ {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>
+ </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>
+
+ <span className="text-white/15">|</span>
+
+ {/* 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>
+
+ {/* Desktop Native Window Controls (Minimize, Maximize, Close) */}
+ <WindowControls themePreset={themePreset} />
+ </div>
+ </header>
+ );
+ }
+
return (
<header
data-tauri-drag-region
diff --git a/src/components/LeftPanel.tsx b/src/components/LeftPanel.tsx
index 7a9a452..d4f3def 100644
--- a/src/components/LeftPanel.tsx
+++ b/src/components/LeftPanel.tsx
@@ -83,6 +83,8 @@ interface LeftPanelProps {
onPrimaryColorChange?: (color: string) => void;
onSecondaryColorChange?: (color: string) => void;
onSwapColors: () => void;
+ isTransparentColor?: boolean;
+ onToggleTransparentColor?: () => void;
recentColors?: string[];
width: number;
onWidthChange: (newWidth: number) => void;
@@ -110,6 +112,8 @@ export const LeftPanel: React.FC<LeftPanelProps> = React.memo(({
primaryColor,
secondaryColor,
onSwapColors,
+ isTransparentColor = false,
+ onToggleTransparentColor,
width,
onWidthChange,
isHidden,
@@ -1101,20 +1105,30 @@ export const LeftPanel: React.FC<LeftPanelProps> = React.memo(({
{/* Primary Color Swatch (top-left) */}
<div
- onClick={onSwapColors}
- title={`Primary Active Color: ${primaryColor} (Click to swap)`}
- className="absolute top-0 left-0 w-5 h-5 rounded-[1px] border border-white cursor-pointer shadow-md z-10"
+ onClick={() => {
+ 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 ${
+ !isTransparentColor
+ ? 'border border-white ring-1 ring-white/40'
+ : 'border border-[#44464c] hover:border-white opacity-80'
+ }`}
style={{ backgroundColor: primaryColor }}
/>
</div>
- {/* Transparent / Erasing Color Swatch (Classic Manga Studio / CSP style) */}
+ {/* Transparent Color Swatch (Clip Studio Paint style 'C' key toggle) */}
<div
- onClick={() => onSelectTool('eraser')}
- title="Transparent Color / Eraser (C / E)"
+ 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 ${
- currentTool === 'eraser'
- ? 'border-[#38bdf8] ring-1 ring-[#38bdf8] shadow-xs'
+ isTransparentColor
+ ? 'border-[#38bdf8] ring-1 ring-[#38bdf8] shadow-xs scale-105'
: 'border-[#44464c] hover:border-white opacity-80 hover:opacity-100'
}`}
style={{
@@ -1354,7 +1368,7 @@ export const LeftPanel: React.FC<LeftPanelProps> = React.memo(({
</div>
)}
- {/* Category: Color & Paint (Oil, Chalk, Square Color Brush) */}
+ {/* 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' && (
diff --git a/src/components/LeftSidebar.tsx b/src/components/LeftSidebar.tsx
index 0b3eb54..2384660 100644
--- a/src/components/LeftSidebar.tsx
+++ b/src/components/LeftSidebar.tsx
@@ -9,6 +9,8 @@ interface LeftSidebarProps {
primaryColor: string;
secondaryColor: string;
onSwapColors: () => void;
+ isTransparentColor?: boolean;
+ onToggleTransparentColor?: () => void;
}
export const LeftSidebar: React.FC<LeftSidebarProps> = ({
@@ -17,6 +19,8 @@ export const LeftSidebar: React.FC<LeftSidebarProps> = ({
primaryColor,
secondaryColor,
onSwapColors,
+ isTransparentColor = false,
+ onToggleTransparentColor,
}) => {
// Keyboard shortcuts: B for Brush, E for Eraser, I for Pipette, J for Liquify, X for swap colors
useEffect(() => {
@@ -38,12 +42,14 @@ export const LeftSidebar: React.FC<LeftSidebarProps> = ({
onSelectTool('liquify');
} else if (key === 'x') {
onSwapColors();
+ } else if (key === 'c') {
+ onToggleTransparentColor?.();
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
- }, [onSelectTool, onSwapColors]);
+ }, [onSelectTool, onSwapColors, onToggleTransparentColor]);
return (
<aside className="w-14 bg-[#252526] border-r border-[#333333] flex flex-col items-center py-3 select-none z-10 shrink-0">
@@ -129,13 +135,41 @@ export const LeftSidebar: React.FC<LeftSidebarProps> = ({
{/* Primary Color Swatch (top-left) */}
<div
- onClick={onSwapColors}
- title={`Primary Active Color: ${primaryColor}`}
- className="absolute top-0 left-0 w-6 h-6 rounded-[2px] border border-white cursor-pointer shadow-md z-10"
+ onClick={() => {
+ if (isTransparentColor) {
+ onToggleTransparentColor?.();
+ } else {
+ onSwapColors();
+ }
+ }}
+ title={`Primary Active Color: ${primaryColor} (Click to select/swap)`}
+ className={`absolute top-0 left-0 w-6 h-6 rounded-[2px] cursor-pointer transition-all z-10 ${
+ !isTransparentColor
+ ? 'border border-white shadow-md ring-1 ring-white/40'
+ : 'border border-[#555555] hover:border-white opacity-80'
+ }`}
style={{ backgroundColor: primaryColor }}
/>
</div>
+ {/* Transparent Color Swatch (Clip Studio Paint 'C' key toggle) */}
+ <div
+ onClick={onToggleTransparentColor}
+ title="Transparent Ink / Color (C) - Brush as textured eraser"
+ className={`w-7 h-3.5 rounded-[2px] border cursor-pointer relative overflow-hidden transition-all ${
+ isTransparentColor
+ ? 'border-[#38bdf8] ring-2 ring-[#38bdf8] shadow-md scale-105'
+ : 'border-[#555555] hover:border-white opacity-80 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%)',
+ backgroundSize: '4px 4px',
+ backgroundPosition: '0 0, 0 2px, 2px -2px, -2px 0px',
+ backgroundColor: '#bbb',
+ }}
+ />
+
{/* Swap button */}
<button
onClick={onSwapColors}
@@ -145,8 +179,8 @@ export const LeftSidebar: React.FC<LeftSidebarProps> = ({
<ArrowLeftRight className="w-3.5 h-3.5" />
</button>
- <span className="text-[10px] text-[#777777] font-mono">
- X
+ <span className="text-[9px] text-[#777777] font-mono">
+ X / C
</span>
</div>
</aside>
diff --git a/src/components/RightSidebar.tsx b/src/components/RightSidebar.tsx
index 42bfde5..4452ad9 100644
--- a/src/components/RightSidebar.tsx
+++ b/src/components/RightSidebar.tsx
@@ -23,6 +23,7 @@ import {
FolderInput,
FolderOutput,
Box,
+ GripVertical,
} from 'lucide-react';
import { HistoryItemMeta, LayerItem, BlendMode, ToolType, CanvasColorMode, ExpressionColor } from '../types/editor';
import { BLEND_MODES } from '../utils/canvasUtils';
@@ -54,9 +55,11 @@ interface RightSidebarProps {
onSetOpacity: (id: string, opacity: number) => void;
onSetBlendMode: (id: string, blendMode: BlendMode) => void;
onToggleLock: (id: string) => void;
+ onToggleAlphaLock?: (id: string) => void;
+ onToggleClipping?: (id: string) => void;
onToggleCollapse: (id: string) => void;
onRenameLayer: (id: string, name: string) => void;
- onMoveLayer: (id: string, direction: 'up' | 'down') => void;
+ onMoveLayer?: (id: string, direction: 'up' | 'down') => void;
onMoveLayerToFolder: (id: string, targetFolderId: string | null) => void;
onReorderLayers?: (draggedId: string, targetId: string, position: 'above' | 'below' | 'inside') => void;
// Tone (Screentone) Effect Props
@@ -132,6 +135,32 @@ export const CspLayerColorIcon: React.FC<{ className?: string; color?: string }>
</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' }) => (
+ <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"
+ />
+ </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' }) => (
+ <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="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" />
+ </svg>
+);
+
export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
primaryColor,
secondaryColor,
@@ -160,9 +189,10 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
onSetOpacity,
onSetBlendMode,
onToggleLock,
+ onToggleAlphaLock,
+ onToggleClipping,
onToggleCollapse,
onRenameLayer,
- onMoveLayer,
onMoveLayerToFolder,
onReorderLayers,
onToggleTone,
@@ -295,6 +325,195 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
setEditingLayerId(null);
};
+ const layerListContainerRef = useRef<HTMLDivElement>(null);
+ const dragRef = useRef<{
+ active: boolean;
+ layerId: string | null;
+ startX: number;
+ startY: number;
+ }>({
+ active: false,
+ layerId: null,
+ startX: 0,
+ startY: 0,
+ });
+ const dropIndicatorRef = useRef<{ id: string; position: 'above' | 'below' | 'inside' } | null>(null);
+ const justDraggedRef = useRef<boolean>(false);
+
+ useEffect(() => {
+ return () => {
+ document.body.style.userSelect = '';
+ document.body.style.cursor = '';
+ };
+ }, []);
+
+ const handleLayerPointerDown = (e: React.PointerEvent<HTMLDivElement>, layerId: string) => {
+ if (e.button !== 0) return;
+ if (editingLayerId !== null) return;
+ const target = e.target as HTMLElement | null;
+ 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,
+ };
+ dropIndicatorRef.current = null;
+
+ let autoScrollTimer: number | null = null;
+ const stopAutoScroll = () => {
+ if (autoScrollTimer !== null) {
+ window.clearInterval(autoScrollTimer);
+ autoScrollTimer = null;
+ }
+ };
+
+ const handlePointerMove = (moveEvt: PointerEvent) => {
+ const dx = moveEvt.clientX - dragRef.current.startX;
+ const dy = moveEvt.clientY - dragRef.current.startY;
+
+ if (!dragRef.current.active) {
+ if (dx * dx + dy * dy >= 16) {
+ dragRef.current.active = true;
+ setDraggedLayerId(layerId);
+ document.body.style.userSelect = 'none';
+ document.body.style.cursor = 'grabbing';
+ } else {
+ return;
+ }
+ }
+
+ // 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) {
+ autoScrollTimer = window.setInterval(() => {
+ container.scrollTop += 7;
+ }, 16);
+ }
+ }
+
+ 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;
+ setDropIndicator(null);
+ }
+ return;
+ }
+
+ const targetId = row.dataset.layerId;
+ if (!targetId || targetId === layerId) {
+ if (dropIndicatorRef.current) {
+ dropIndicatorRef.current = null;
+ setDropIndicator(null);
+ }
+ return;
+ }
+
+ const targetLayer = layers.find((l) => l.id === targetId);
+ if (!targetLayer) {
+ if (dropIndicatorRef.current) {
+ dropIndicatorRef.current = null;
+ setDropIndicator(null);
+ }
+ return;
+ }
+
+ // Prevent dragging a folder into its own subtree
+ const draggedItem = layers.find((l) => l.id === layerId);
+ if (draggedItem?.type === 'folder') {
+ let isDescendant = false;
+ let curr: LayerItem | undefined = targetLayer;
+ while (curr) {
+ if (curr.id === layerId) {
+ isDescendant = true;
+ break;
+ }
+ curr = layers.find((l) => l.id === curr?.parentId);
+ }
+ if (isDescendant) {
+ if (dropIndicatorRef.current) {
+ dropIndicatorRef.current = null;
+ setDropIndicator(null);
+ }
+ 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';
+ }
+ } else {
+ if (yRatio <= 0.5) {
+ position = 'above';
+ } else {
+ position = 'below';
+ }
+ }
+
+ const nextIndicator = { id: targetId, position };
+ dropIndicatorRef.current = nextIndicator;
+ setDropIndicator(nextIndicator);
+ };
+
+ const handlePointerUp = () => {
+ window.removeEventListener('pointermove', handlePointerMove);
+ window.removeEventListener('pointerup', handlePointerUp);
+ window.removeEventListener('pointercancel', handlePointerUp);
+ stopAutoScroll();
+
+ document.body.style.userSelect = '';
+ document.body.style.cursor = '';
+
+ if (dragRef.current.active) {
+ justDraggedRef.current = true;
+ setTimeout(() => {
+ justDraggedRef.current = false;
+ }, 100);
+
+ const currentIndicator = dropIndicatorRef.current;
+ if (currentIndicator && currentIndicator.id !== layerId && onReorderLayers) {
+ onReorderLayers(layerId, currentIndicator.id, currentIndicator.position);
+ }
+ }
+
+ dragRef.current = { active: false, layerId: null, startX: 0, startY: 0 };
+ dropIndicatorRef.current = null;
+ setDraggedLayerId(null);
+ setDropIndicator(null);
+ };
+
+ window.addEventListener('pointermove', handlePointerMove);
+ window.addEventListener('pointerup', handlePointerUp);
+ window.addEventListener('pointercancel', handlePointerUp);
+ };
+
return (
<aside
style={{ width }}
@@ -311,7 +530,7 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
{/* 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]">
+ <section className="bg-[#252526] h-full">
<ColorPanel
primaryColor={primaryColor}
secondaryColor={secondaryColor}
@@ -323,6 +542,7 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
onSelectTool={onSelectTool}
recentColors={recentColors}
containerWidth={width}
+ containerHeight={topHeight}
/>
</section>
</div>
@@ -1001,23 +1221,43 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
<Copy className="w-3.5 h-3.5 text-emerald-400" />
</button>
- {/* Move Up */}
- <button
- onClick={() => onMoveLayer(activeLayerId, 'up')}
- title="Move Layer Up"
- className="p-1 text-[#888888] hover:text-white hover:bg-[#333333] rounded-[2px] transition-colors"
- >
- <ChevronUp className="w-3.5 h-3.5" />
- </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>
+ )}
- {/* Move Down */}
- <button
- onClick={() => onMoveLayer(activeLayerId, 'down')}
- title="Move Layer Down"
- className="p-1 text-[#888888] hover:text-white hover:bg-[#333333] rounded-[2px] transition-colors"
- >
- <ChevronDown 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 Lock */}
{activeLayer && (
@@ -1048,7 +1288,7 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
</div>
{/* Scrollable Layer Stack List */}
- <div className="flex-1 overflow-y-auto p-1.5 space-y-1 min-h-0">
+ <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) {
@@ -1065,69 +1305,46 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
const isDropInside = isTarget && dropIndicator.position === 'inside';
const isDropAbove = isTarget && dropIndicator.position === 'above';
const isDropBelow = isTarget && dropIndicator.position === 'below';
+ const isBeingDragged = draggedLayerId === layer.id;
return (
<div
key={layer.id}
- draggable={editingLayerId !== layer.id}
- onDragStart={(e) => {
- e.dataTransfer.setData('text/plain', layer.id);
- e.dataTransfer.effectAllowed = 'move';
- setDraggedLayerId(layer.id);
- }}
- onDragEnd={() => {
- setDraggedLayerId(null);
- setDropIndicator(null);
+ data-layer-id={layer.id}
+ onPointerDown={(e) => handleLayerPointerDown(e, layer.id)}
+ onClick={() => {
+ if (justDraggedRef.current) return;
+ onSelectLayer(layer.id);
}}
- onDragOver={(e) => {
- e.preventDefault();
- e.stopPropagation();
- if (!draggedLayerId || draggedLayerId === layer.id) return;
- const rect = e.currentTarget.getBoundingClientRect();
- const yRatio = (e.clientY - rect.top) / rect.height;
-
- if (isFolder) {
- if (yRatio > 0.25 && yRatio < 0.75) {
- setDropIndicator({ id: layer.id, position: 'inside' });
- } else if (yRatio <= 0.25) {
- setDropIndicator({ id: layer.id, position: 'above' });
- } else {
- setDropIndicator({ id: layer.id, position: 'below' });
- }
- } else {
- if (yRatio <= 0.5) {
- setDropIndicator({ id: layer.id, position: 'above' });
- } else {
- setDropIndicator({ id: layer.id, position: 'below' });
- }
- }
- }}
- onDrop={(e) => {
- e.preventDefault();
- e.stopPropagation();
- const sourceId = e.dataTransfer.getData('text/plain') || draggedLayerId;
- if (!sourceId || sourceId === layer.id || !dropIndicator) return;
- if (onReorderLayers) {
- onReorderLayers(sourceId, layer.id, dropIndicator.position);
- }
- setDropIndicator(null);
- setDraggedLayerId(null);
- }}
- onClick={() => onSelectLayer(layer.id)}
- className={`group relative flex items-center space-x-1.5 px-2 py-1.5 rounded-[2px] cursor-pointer transition-colors border ${
+ 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'
- : isDropAbove
- ? 'border-t-2 border-t-blue-500 border-x-transparent border-b-transparent'
- : isDropBelow
- ? 'border-b-2 border-b-blue-500 border-x-transparent border-t-transparent'
: isActive
? 'bg-[#383838] border-[#555555] 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) => {
@@ -1148,6 +1365,24 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
)}
</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
@@ -1209,6 +1444,14 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
}}
/>
)}
+
+ {/* 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>
)}
@@ -1300,6 +1543,21 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
)}
</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>
+ )}
+
{/* Lock Indicator */}
{layer.locked && (
<Lock className="w-3 h-3 text-[#777777] shrink-0" />
diff --git a/src/components/SelectionOverlay.tsx b/src/components/SelectionOverlay.tsx
index 013bfa4..ec6249f 100644
--- a/src/components/SelectionOverlay.tsx
+++ b/src/components/SelectionOverlay.tsx
@@ -1,4 +1,5 @@
import React, { useEffect, useRef } from 'react';
+import { createPortal } from 'react-dom';
import {
CanvasSelection,
CanvasDimensions,
@@ -113,70 +114,73 @@ export const SelectionOverlay: React.FC<SelectionOverlayProps> = ({
</svg>
{/* 3. CSP-Style Selection Launcher Bar (Fixed at bottom center of viewport) */}
- <div
- className="fixed bottom-10 left-1/2 -translate-x-1/2 z-50 bg-[#1e1f22] border border-[#383a40] rounded shadow-2xl px-2 py-1.5 flex items-center space-x-1.5 select-none animate-in fade-in slide-in-from-bottom-2 duration-150"
- onPointerDown={(e) => e.stopPropagation()}
- >
- {/* Deselect */}
- <button
- onClick={onDeselect}
- title="Deselect (Ctrl+D)"
- className="p-1.5 text-[#999999] hover:text-white hover:bg-[#2b2d31] rounded transition-colors cursor-pointer flex items-center space-x-1 text-xs"
- >
- <X className="w-4 h-4 text-red-400" />
- <span className="hidden sm:inline">Deselect</span>
- </button>
-
- <div className="w-px h-4 bg-[#383a40]" />
-
- {/* Screen Tone Fill (CSP Halftone Fill) */}
- <button
- onClick={onFillScreentone}
- title="Fill Screentone into New Layer (CSP Tone Effect)"
- className="p-1.5 bg-[#293d45] hover:bg-[#344d57] text-[#5ce1e6] border border-[#3e5e6b] rounded transition-colors cursor-pointer flex items-center space-x-1.5 text-xs font-medium shadow-xs"
- >
- <Sparkles className="w-4 h-4 text-[#5ce1e6]" />
- <span>Screentone Fill</span>
- </button>
-
- {/* Transform Selection (Ctrl+T) */}
- <button
- onClick={onTransformSelection}
- title="Transform Selection (Ctrl+T)"
- className="p-1.5 text-[#cccccc] hover:text-white hover:bg-[#2b2d31] rounded transition-colors cursor-pointer flex items-center space-x-1 text-xs"
- >
- <Scaling className="w-4 h-4 text-cyan-400" />
- <span>Transform</span>
- </button>
-
- {/* Fill with Foreground Color */}
- <button
- onClick={onFillColor}
- title="Fill with Foreground Color (Alt+Del)"
- className="p-1.5 text-[#cccccc] hover:text-white hover:bg-[#2b2d31] rounded transition-colors cursor-pointer flex items-center space-x-1 text-xs"
- >
- <PaintBucket className="w-4 h-4 text-amber-400" />
- <span className="hidden sm:inline">Fill</span>
- </button>
-
- {/* Clear Selection Pixels */}
- <button
- onClick={onClearSelection}
- title="Clear / Delete Selected Pixels (Del)"
- className="p-1.5 text-[#cccccc] hover:text-red-400 hover:bg-[#2b2d31] rounded transition-colors cursor-pointer flex items-center space-x-1 text-xs"
- >
- <Trash2 className="w-4 h-4" />
- </button>
-
- {/* Invert Selection */}
- <button
- onClick={onInvertSelection}
- title="Invert Selection (Ctrl+Shift+I)"
- className="p-1.5 text-[#cccccc] hover:text-white hover:bg-[#2b2d31] rounded transition-colors cursor-pointer flex items-center space-x-1 text-xs"
+ {createPortal(
+ <div
+ className="fixed bottom-10 left-1/2 -translate-x-1/2 z-50 bg-[#1e1f22] border border-[#383a40] rounded shadow-2xl px-2 py-1.5 flex items-center space-x-1.5 select-none animate-in fade-in slide-in-from-bottom-2 duration-150"
+ onPointerDown={(e) => e.stopPropagation()}
>
- <RotateCcw className="w-4 h-4" />
- </button>
- </div>
+ {/* Deselect */}
+ <button
+ onClick={onDeselect}
+ title="Deselect (Ctrl+D)"
+ className="p-1.5 text-[#999999] hover:text-white hover:bg-[#2b2d31] rounded transition-colors cursor-pointer flex items-center space-x-1 text-xs"
+ >
+ <X className="w-4 h-4 text-red-400" />
+ <span className="hidden sm:inline">Deselect</span>
+ </button>
+
+ <div className="w-px h-4 bg-[#383a40]" />
+
+ {/* Screen Tone Fill (CSP Halftone Fill) */}
+ <button
+ onClick={onFillScreentone}
+ title="Fill Screentone into New Layer (CSP Tone Effect)"
+ className="p-1.5 bg-[#293d45] hover:bg-[#344d57] text-[#5ce1e6] border border-[#3e5e6b] rounded transition-colors cursor-pointer flex items-center space-x-1.5 text-xs font-medium shadow-xs"
+ >
+ <Sparkles className="w-4 h-4 text-[#5ce1e6]" />
+ <span>Screentone Fill</span>
+ </button>
+
+ {/* Transform Selection (Ctrl+T) */}
+ <button
+ onClick={onTransformSelection}
+ title="Transform Selection (Ctrl+T)"
+ className="p-1.5 text-[#cccccc] hover:text-white hover:bg-[#2b2d31] rounded transition-colors cursor-pointer flex items-center space-x-1 text-xs"
+ >
+ <Scaling className="w-4 h-4 text-cyan-400" />
+ <span>Transform</span>
+ </button>
+
+ {/* Fill with Foreground Color */}
+ <button
+ onClick={onFillColor}
+ title="Fill with Foreground Color (Alt+Del)"
+ className="p-1.5 text-[#cccccc] hover:text-white hover:bg-[#2b2d31] rounded transition-colors cursor-pointer flex items-center space-x-1 text-xs"
+ >
+ <PaintBucket className="w-4 h-4 text-amber-400" />
+ <span className="hidden sm:inline">Fill</span>
+ </button>
+
+ {/* Clear Selection Pixels */}
+ <button
+ onClick={onClearSelection}
+ title="Clear / Delete Selected Pixels (Del)"
+ className="p-1.5 text-[#cccccc] hover:text-red-400 hover:bg-[#2b2d31] rounded transition-colors cursor-pointer flex items-center space-x-1 text-xs"
+ >
+ <Trash2 className="w-4 h-4" />
+ </button>
+
+ {/* Invert Selection */}
+ <button
+ onClick={onInvertSelection}
+ title="Invert Selection (Ctrl+Shift+I)"
+ className="p-1.5 text-[#cccccc] hover:text-white hover:bg-[#2b2d31] rounded transition-colors cursor-pointer flex items-center space-x-1 text-xs"
+ >
+ <RotateCcw className="w-4 h-4" />
+ </button>
+ </div>,
+ document.body
+ )}
</>
);
};
diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsx
index b7427d9..366ab1d 100644
--- a/src/components/SettingsModal.tsx
+++ b/src/components/SettingsModal.tsx
@@ -1,17 +1,25 @@
-import React, { useState } from 'react';
+import React, { useState, useEffect } from 'react';
import {
X,
Palette,
Layers,
Paintbrush,
Keyboard,
- Sparkles,
+ Info,
RotateCcw,
Check,
Search,
+ User,
Settings as SettingsIcon,
+ Sparkles,
} from 'lucide-react';
-import { AppSettings, DEFAULT_APP_SETTINGS } from '../types/settings';
+import {
+ AppSettings,
+ DEFAULT_APP_SETTINGS,
+ ModernAccentColor,
+ MODERN_ACCENTS,
+ resolveModernAccentColor,
+} from '../types/settings';
import { CanvasColorMode } from '../types/editor';
import { DPI_PRESETS } from './NewCanvasModal';
@@ -73,6 +81,10 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
const [localSettings, setLocalSettings] = useState<AppSettings>(settings);
const [searchQuery, setSearchQuery] = useState<string>('');
+ useEffect(() => {
+ setLocalSettings(settings);
+ }, [settings]);
+
if (!isOpen) return null;
const handleChange = <K extends keyof AppSettings>(key: K, value: AppSettings[K]) => {
@@ -102,18 +114,16 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
if (e.key === 'Escape') onClose();
}}
>
- <div className="bg-[#222224] border border-[#3e3e42] rounded-lg shadow-2xl w-full max-w-3xl flex flex-col overflow-hidden text-xs text-[#cccccc] h-[580px]">
+ <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]">
{/* Header */}
- <div className="flex items-center justify-between px-5 py-3.5 bg-[#2a2a2d] border-b border-[#38383a] shrink-0">
- <div className="flex items-center space-x-2.5">
- <div className="w-5 h-5 rounded-[3px] bg-[#007acc]/20 border border-[#007acc]/40 flex items-center justify-center text-[#38bdf8]">
- <SettingsIcon className="w-3.5 h-3.5" />
- </div>
- <h2 className="text-sm font-semibold text-white tracking-wide">Application Settings</h2>
+ <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>
<button
onClick={onClose}
- className="p-1 rounded hover:bg-[#38383a] text-[#888888] hover:text-white transition-colors"
+ className="p-1 rounded-[2px] hover:bg-[#525255] text-[#a0a0a5] hover:text-white transition-colors"
title="Close (Esc)"
>
<X className="w-4 h-4" />
@@ -123,75 +133,75 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
{/* Body: Left Tabs + Right Content */}
<div className="flex flex-1 overflow-hidden">
{/* Left Tabs Bar */}
- <div className="w-48 bg-[#1a1a1c] border-r border-[#333336] p-2 space-y-1 shrink-0 flex flex-col justify-between">
+ <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.5 px-3 py-2 rounded text-left transition-colors ${
+ 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-[#007acc] text-white font-medium shadow-xs'
- : 'text-[#aaaaaa] hover:bg-[#252528] hover:text-white'
+ ? '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-4 h-4 shrink-0" />
+ <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.5 px-3 py-2 rounded text-left transition-colors ${
+ 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-[#007acc] text-white font-medium shadow-xs'
- : 'text-[#aaaaaa] hover:bg-[#252528] hover:text-white'
+ ? '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-4 h-4 shrink-0" />
+ <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.5 px-3 py-2 rounded text-left transition-colors ${
+ 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-[#007acc] text-white font-medium shadow-xs'
- : 'text-[#aaaaaa] hover:bg-[#252528] hover:text-white'
+ ? '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-4 h-4 shrink-0" />
+ <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.5 px-3 py-2 rounded text-left transition-colors ${
+ 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-[#007acc] text-white font-medium shadow-xs'
- : 'text-[#aaaaaa] hover:bg-[#252528] hover:text-white'
+ ? '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-4 h-4 shrink-0" />
+ <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.5 px-3 py-2 rounded text-left transition-colors ${
+ 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-[#007acc] text-white font-medium shadow-xs'
- : 'text-[#aaaaaa] hover:bg-[#252528] hover:text-white'
+ ? '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'
}`}
>
- <Sparkles className="w-4 h-4 shrink-0 text-amber-400" />
+ <Info className="w-3.5 h-3.5 shrink-0" />
<span>About</span>
</button>
</div>
- <div className="pt-2 border-t border-[#2e2e32]">
+ <div className="pt-2 border-t border-[#2a2a2d]">
<button
type="button"
onClick={handleResetDefaults}
@@ -210,27 +220,249 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
{activeTab === 'appearance' && (
<div className="space-y-5">
<div>
- <h3 className="text-sm font-semibold text-white">Appearance & Interface</h3>
- <p className="text-[11px] text-[#888888]">Choose interface styling and workspace overlays</p>
+ <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>
- {/* Interface Theme Switcher */}
+ {/* User Profile */}
<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">
- Theme Preset
- </span>
+ <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">
+ <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-center space-x-2 py-2.5 px-3 rounded text-xs font-medium border transition-colors cursor-pointer bg-[#293d45] border-[#5ce1e6] text-[#5ce1e6] shadow-xs"
+ 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'
+ }`}
>
- <Check className="w-3.5 h-3.5 shrink-0" />
- <span>Old Studio</span>
+ <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>
+
+ <div className="grid grid-cols-3 gap-2">
+ {(Object.keys(MODERN_ACCENTS) as Array<Exclude<ModernAccentColor, 'custom'>>).map((accKey) => {
+ const acc = MODERN_ACCENTS[accKey];
+ const isSelected = localSettings.modernAccent === accKey;
+ return (
+ <button
+ 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 ${
+ 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'
+ }`}
+ >
+ <span
+ className="w-3.5 h-3.5 rounded-full shrink-0 shadow-xs border border-black/20"
+ style={{ backgroundColor: acc.hex }}
+ />
+ <span className="truncate">{acc.label}</span>
+ {isSelected && <Check className="w-3 h-3 ml-auto text-white shrink-0" />}
+ </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>
+ </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">
@@ -575,14 +807,14 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
</div>
{/* Footer */}
- <div className="flex items-center justify-between px-5 py-3 bg-[#2a2a2d] border-t border-[#38383a] shrink-0">
- <span className="text-[11px] text-[#777777]">Changes save automatically</span>
+ <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-5 py-1.5 rounded bg-[#007acc] hover:bg-[#008be5] active:bg-[#006bb3] text-white font-medium shadow-sm transition-colors ml-auto"
+ 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-4 h-4" />
+ <Check className="w-3.5 h-3.5 text-emerald-400" />
<span>Close</span>
</button>
</div>
diff --git a/src/components/StatusBar.tsx b/src/components/StatusBar.tsx
index 8537c56..af7693d 100644
--- a/src/components/StatusBar.tsx
+++ b/src/components/StatusBar.tsx
@@ -66,6 +66,94 @@ export const StatusBar: React.FC<StatusBarProps> = React.memo(({
};
}, []);
+ if (_themePreset === 'modern') {
+ return (
+ <footer className="h-7 bg-[#0f1015] border-t border-white/[0.08] px-3 text-white/70 flex items-center justify-between text-xs select-none z-20 shrink-0">
+ {/* Tool & Smoothing Status */}
+ <div className="flex items-center space-x-2">
+ <div className="bg-white/[0.04] border border-white/[0.06] px-2 py-0.5 rounded-md flex items-center space-x-2">
+ <span className="text-white capitalize font-medium text-[11px]">{tool}</span>
+ <span className="text-white/20">|</span>
+ {hasOpenDocument ? (
+ <span
+ className={`font-mono text-[10px] font-medium ${
+ colorMode === 'monochrome'
+ ? 'text-amber-400'
+ : colorMode === 'grayscale'
+ ? 'text-slate-300'
+ : 'text-[var(--modern-accent)]'
+ }`}
+ title={`Active Document Color Mode: ${colorMode}`}
+ >
+ {colorMode === 'monochrome' ? '1-bit Manga' : colorMode === 'grayscale' ? 'Grayscale' : 'Color RGB'}
+ </span>
+ ) : (
+ <span className="text-white/30 italic text-[10px]">No active document</span>
+ )}
+ <span className="text-white/20">|</span>
+ <span className="text-[10px] font-mono text-white/60">
+ {brushSettings.smoothing ? 'Bézier' : 'Direct'}
+ </span>
+ <span className="text-white/20">|</span>
+ <span className="text-[var(--modern-accent)] font-mono text-[10px]">
+ Stab: {brushSettings.stabilization ?? 0}
+ </span>
+ </div>
+ </div>
+
+ {/* Real-time Pointer Stats */}
+ <div className="flex items-center space-x-2 font-mono text-xs">
+ {/* Coordinates */}
+ {showCursorCoordinates && (
+ <div className="bg-white/[0.04] border border-white/[0.06] px-2 py-0.5 rounded-md flex items-center space-x-1.5">
+ <span className="text-white/40 text-[10px]">Pos:</span>
+ <span ref={posTextRef} className="text-white/90 text-[11px]">
+ — , —
+ </span>
+ </div>
+ )}
+
+ {/* Stylus Pressure Bar */}
+ {showPressureInStatusBar && (
+ <div className="bg-white/[0.04] border border-white/[0.06] px-2 py-0.5 rounded-md flex items-center space-x-2">
+ <span className="text-white/40 text-[10px]">Pressure:</span>
+ <div className="w-14 h-1.5 bg-white/10 rounded-full overflow-hidden">
+ <div
+ ref={pressureBarRef}
+ className="h-full bg-[var(--modern-accent)] transition-all duration-75"
+ style={{ width: `0%` }}
+ />
+ </div>
+ <span ref={pressureTextRef} className="w-7 text-right text-white/80 text-[10px]">0%</span>
+ </div>
+ )}
+
+ {/* Rotation */}
+ <div
+ onClick={hasOpenDocument ? onResetRotation : undefined}
+ onDoubleClick={hasOpenDocument ? onResetRotation : undefined}
+ className={`bg-white/[0.04] border border-white/[0.06] px-2 py-0.5 rounded-md flex items-center space-x-1.5 ${
+ hasOpenDocument ? 'cursor-pointer hover:bg-white/[0.08] text-white/90 hover:text-white' : 'opacity-40 pointer-events-none'
+ }`}
+ title="Canvas Rotation (Click or Double-click to Reset 0°)"
+ >
+ <span className="text-white/40 text-[10px]">Angle:</span>
+ <span className="text-white/90 font-medium text-[11px]">{hasOpenDocument ? formatRotationDegrees(rotation) : '0°'}</span>
+ </div>
+
+ {/* Zoom */}
+ <div
+ className={`bg-white/[0.04] border border-white/[0.06] px-2 py-0.5 rounded-md flex items-center space-x-1.5 ${hasOpenDocument ? '' : 'opacity-40'}`}
+ title="Canvas Zoom Level"
+ >
+ <span className="text-white/40 text-[10px]">Zoom:</span>
+ <span className="text-white/90 font-medium text-[11px]">{hasOpenDocument ? formatZoomPercent(zoom) : '—'}</span>
+ </div>
+ </div>
+ </footer>
+ );
+ }
+
return (
<footer className="h-7 bg-gradient-to-b from-[#464649] to-[#363638] border-t border-[#232325] px-2.5 text-[#b0b0b6] flex items-center justify-between text-xs select-none z-20 shrink-0 transition-colors">
{/* Tool & Smoothing Status */}
diff --git a/src/components/TextEditorOverlay.tsx b/src/components/TextEditorOverlay.tsx
index 81a15db..a337068 100644
--- a/src/components/TextEditorOverlay.tsx
+++ b/src/components/TextEditorOverlay.tsx
@@ -116,7 +116,13 @@ export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({
</div>
{/* Floating Tool Panel */}
- <div className="w-80 bg-[#1e1f22] border border-[#383a40] rounded-md shadow-2xl overflow-hidden flex flex-col">
+ <div
+ className="w-80 bg-[#1e1f22] border border-[#383a40] rounded-md shadow-2xl overflow-hidden flex flex-col"
+ style={{
+ transform: `scale(${zoom > 0 ? 1 / zoom : 1})`,
+ transformOrigin: 'top left',
+ }}
+ >
{/* Header Draggable Bar */}
<div
onPointerDown={handleDragDown}
diff --git a/src/components/TransformOverlay.tsx b/src/components/TransformOverlay.tsx
index b6815b2..edd4158 100644
--- a/src/components/TransformOverlay.tsx
+++ b/src/components/TransformOverlay.tsx
@@ -221,6 +221,7 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({
}));
};
+ const invZoom = zoom > 0 ? 1 / zoom : 1;
const handleSize = 8;
return (
@@ -255,7 +256,11 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({
{/* Rotation Stem & Handle */}
<div
- className="absolute left-1/2 -top-6 -translate-x-1/2 flex flex-col items-center pointer-events-auto"
+ className="absolute left-1/2 top-0 flex flex-col items-center pointer-events-auto"
+ style={{
+ transform: `translateX(-50%) translateY(calc(-100% - ${4 * invZoom}px)) scale(${invZoom})`,
+ transformOrigin: 'bottom center',
+ }}
onPointerDown={(e) => startDrag('rotate', e)}
title="Drag to Rotate (Shift snaps to 15°)"
>
@@ -264,61 +269,127 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({
</div>
{/* Center Pivot Point */}
- <div className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 w-2 h-2 rounded-full border border-cyan-400 bg-white pointer-events-none shadow-xs" />
+ <div
+ className="absolute left-1/2 top-1/2 w-2 h-2 rounded-full border border-cyan-400 bg-white pointer-events-none shadow-xs"
+ style={{
+ transform: `translate(-50%, -50%) scale(${invZoom})`,
+ transformOrigin: 'center',
+ }}
+ />
{/* 8 Resize Scale Handles */}
{/* Top-Left */}
<div
onPointerDown={(e) => startDrag('scale', e, 'nw')}
- className="absolute -top-1.5 -left-1.5 bg-white border border-cyan-500 shadow-sm cursor-nwse-resize hover:scale-125 pointer-events-auto"
- style={{ width: `${handleSize}px`, height: `${handleSize}px` }}
+ className="absolute bg-white border border-cyan-500 shadow-sm cursor-nwse-resize hover:scale-125 pointer-events-auto"
+ style={{
+ left: 0,
+ top: 0,
+ width: `${handleSize}px`,
+ height: `${handleSize}px`,
+ transform: `translate(-50%, -50%) scale(${invZoom})`,
+ transformOrigin: 'center',
+ }}
/>
{/* Top-Middle */}
<div
onPointerDown={(e) => startDrag('scale', e, 'n')}
- className="absolute -top-1.5 left-1/2 -translate-x-1/2 bg-white border border-cyan-500 shadow-sm cursor-ns-resize hover:scale-125 pointer-events-auto"
- style={{ width: `${handleSize}px`, height: `${handleSize}px` }}
+ className="absolute bg-white border border-cyan-500 shadow-sm cursor-ns-resize hover:scale-125 pointer-events-auto"
+ style={{
+ left: '50%',
+ top: 0,
+ width: `${handleSize}px`,
+ height: `${handleSize}px`,
+ transform: `translate(-50%, -50%) scale(${invZoom})`,
+ transformOrigin: 'center',
+ }}
/>
{/* Top-Right */}
<div
onPointerDown={(e) => startDrag('scale', e, 'ne')}
- className="absolute -top-1.5 -right-1.5 bg-white border border-cyan-500 shadow-sm cursor-nesw-resize hover:scale-125 pointer-events-auto"
- style={{ width: `${handleSize}px`, height: `${handleSize}px` }}
+ className="absolute bg-white border border-cyan-500 shadow-sm cursor-nesw-resize hover:scale-125 pointer-events-auto"
+ style={{
+ left: '100%',
+ top: 0,
+ width: `${handleSize}px`,
+ height: `${handleSize}px`,
+ transform: `translate(-50%, -50%) scale(${invZoom})`,
+ transformOrigin: 'center',
+ }}
/>
{/* Right-Middle */}
<div
onPointerDown={(e) => startDrag('scale', e, 'e')}
- className="absolute top-1/2 -right-1.5 -translate-y-1/2 bg-white border border-cyan-500 shadow-sm cursor-ew-resize hover:scale-125 pointer-events-auto"
- style={{ width: `${handleSize}px`, height: `${handleSize}px` }}
+ className="absolute bg-white border border-cyan-500 shadow-sm cursor-ew-resize hover:scale-125 pointer-events-auto"
+ style={{
+ left: '100%',
+ top: '50%',
+ width: `${handleSize}px`,
+ height: `${handleSize}px`,
+ transform: `translate(-50%, -50%) scale(${invZoom})`,
+ transformOrigin: 'center',
+ }}
/>
{/* Bottom-Right */}
<div
onPointerDown={(e) => startDrag('scale', e, 'se')}
- className="absolute -bottom-1.5 -right-1.5 bg-white border border-cyan-500 shadow-sm cursor-nwse-resize hover:scale-125 pointer-events-auto"
- style={{ width: `${handleSize}px`, height: `${handleSize}px` }}
+ className="absolute bg-white border border-cyan-500 shadow-sm cursor-nwse-resize hover:scale-125 pointer-events-auto"
+ style={{
+ left: '100%',
+ top: '100%',
+ width: `${handleSize}px`,
+ height: `${handleSize}px`,
+ transform: `translate(-50%, -50%) scale(${invZoom})`,
+ transformOrigin: 'center',
+ }}
/>
{/* Bottom-Middle */}
<div
onPointerDown={(e) => startDrag('scale', e, 's')}
- className="absolute -bottom-1.5 left-1/2 -translate-x-1/2 bg-white border border-cyan-500 shadow-sm cursor-ns-resize hover:scale-125 pointer-events-auto"
- style={{ width: `${handleSize}px`, height: `${handleSize}px` }}
+ className="absolute bg-white border border-cyan-500 shadow-sm cursor-ns-resize hover:scale-125 pointer-events-auto"
+ style={{
+ left: '50%',
+ top: '100%',
+ width: `${handleSize}px`,
+ height: `${handleSize}px`,
+ transform: `translate(-50%, -50%) scale(${invZoom})`,
+ transformOrigin: 'center',
+ }}
/>
{/* Bottom-Left */}
<div
onPointerDown={(e) => startDrag('scale', e, 'sw')}
- className="absolute -bottom-1.5 -left-1.5 bg-white border border-cyan-500 shadow-sm cursor-nesw-resize hover:scale-125 pointer-events-auto"
- style={{ width: `${handleSize}px`, height: `${handleSize}px` }}
+ className="absolute bg-white border border-cyan-500 shadow-sm cursor-nesw-resize hover:scale-125 pointer-events-auto"
+ style={{
+ left: 0,
+ top: '100%',
+ width: `${handleSize}px`,
+ height: `${handleSize}px`,
+ transform: `translate(-50%, -50%) scale(${invZoom})`,
+ transformOrigin: 'center',
+ }}
/>
{/* Left-Middle */}
<div
onPointerDown={(e) => startDrag('scale', e, 'w')}
- className="absolute top-1/2 -left-1.5 -translate-y-1/2 bg-white border border-cyan-500 shadow-sm cursor-ew-resize hover:scale-125 pointer-events-auto"
- style={{ width: `${handleSize}px`, height: `${handleSize}px` }}
+ className="absolute bg-white border border-cyan-500 shadow-sm cursor-ew-resize hover:scale-125 pointer-events-auto"
+ style={{
+ left: 0,
+ top: '50%',
+ width: `${handleSize}px`,
+ height: `${handleSize}px`,
+ transform: `translate(-50%, -50%) scale(${invZoom})`,
+ transformOrigin: 'center',
+ }}
/>
{/* Floating Action Bar (Directly below transform box) */}
<div
- className="absolute left-1/2 -bottom-12 -translate-x-1/2 bg-[#1b1c1e] border border-[#33353b] rounded shadow-xl px-2 py-1 flex items-center space-x-1.5 z-40 whitespace-nowrap"
+ className="absolute left-1/2 top-full bg-[#1b1c1e] border border-[#33353b] rounded shadow-xl px-2 py-1 flex items-center space-x-1.5 z-40 whitespace-nowrap"
+ style={{
+ transform: `translateX(-50%) translateY(${16 * invZoom}px) scale(${invZoom})`,
+ transformOrigin: 'top center',
+ }}
onPointerDown={(e) => e.stopPropagation()}
>
{/* Confirm (Enter) */}
diff --git a/src/components/WebLandingModal.tsx b/src/components/WebLandingModal.tsx
index 14dec41..c1acd65 100644
--- a/src/components/WebLandingModal.tsx
+++ b/src/components/WebLandingModal.tsx
@@ -1,5 +1,5 @@
import React, { useState } from 'react';
-import { Sparkles, Globe, Monitor, ArrowRight, X } from 'lucide-react';
+import { Users, Globe, Monitor, ArrowRight, X } from 'lucide-react';
import { isTauriEnvironment } from '../hooks/useMultiplayer';
interface WebLandingModalProps {
@@ -41,76 +41,76 @@ export const WebLandingModal: React.FC<WebLandingModalProps> = ({
};
return (
- <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/75 backdrop-blur-sm p-4">
- <div className="relative w-full max-w-md rounded-xl border border-[#444444] bg-[#1e1e1e] p-6 shadow-2xl text-white">
+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4 select-none">
+ <div className="relative w-full max-w-md rounded-[2px] border border-[#242426] bg-[#444447] p-5 shadow-[0_8px_24px_rgba(0,0,0,0.8)] text-[#d6d6da]">
<button
onClick={onDismiss}
- className="absolute top-4 right-4 rounded p-1 text-[#888888] hover:bg-[#333333] hover:text-white transition-colors cursor-pointer"
+ className="absolute top-3 right-3 rounded-[2px] p-1 text-[#99999e] hover:bg-[#525255] hover:text-white transition-colors cursor-pointer"
>
<X className="w-4 h-4" />
</button>
{/* Header Icon */}
- <div className="flex items-center space-x-3 mb-5">
- <div className="flex items-center justify-center w-10 h-10 rounded-xl bg-[#2a2a2a] border border-[#3e3e3e] shadow-md">
- <Sparkles className="w-5 h-5 text-[#cccccc]" />
+ <div className="flex items-center space-x-2.5 mb-4">
+ <div className="flex items-center justify-center w-8 h-8 rounded-[2px] bg-[#363639] border border-[#242426] shadow-xs">
+ <Users className="w-4 h-4 text-[#93c5fd]" />
</div>
<div>
- <h2 className="text-base font-bold text-white">Ink Studio Collab</h2>
- <p className="text-xs text-[#999999]">Real-time collaborative drawing</p>
+ <h2 className="text-sm font-semibold text-[#f0f0f4]">Ink Studio Collab</h2>
+ <p className="text-[11px] text-[#8c8c92]">Real-time canvas session</p>
</div>
</div>
{/* Room Info Card */}
- <div className="rounded-lg border border-[#333333] bg-[#282828] p-3.5 mb-5 space-y-1">
- <div className="text-[11px] font-medium text-[#aaaaaa]">Connecting to canvas:</div>
- <div className="text-sm font-semibold text-white">"{invite.roomName}"</div>
- <div className="text-[11px] text-[#777777] font-mono">
+ <div className="rounded-[2px] border border-[#242426] bg-[#2b2b2e] p-3 mb-4 space-y-1 shadow-[inset_1px_1px_2px_rgba(0,0,0,0.5)]">
+ <div className="text-[11px] font-medium text-[#99999e]">Connecting to canvas:</div>
+ <div className="text-xs font-semibold text-[#f0f0f4]">"{invite.roomName}"</div>
+ <div className="text-[10px] text-[#808085] font-mono">
Host: {invite.host}{invite.port && invite.port !== 443 && invite.port !== 80 ? `:${invite.port}` : ''}
</div>
</div>
{/* Name input */}
- <div className="mb-5">
- <label className="block text-xs font-medium text-[#cccccc] mb-1.5">
- Your nickname on canvas:
+ <div className="mb-4 space-y-1">
+ <label className="block text-xs font-medium text-[#cccccc]">
+ Artist Nickname:
</label>
<input
type="text"
value={userName}
onChange={(e) => setUserName(e.target.value)}
- placeholder="Enter nickname..."
- className="w-full rounded-md border border-[#3e3e3e] bg-[#141414] px-3.5 py-2 text-sm text-white focus:border-[#007acc] focus:outline-hidden"
+ placeholder="Artist..."
+ className="w-full rounded-[2px] border border-[#1e1e20] bg-[#2b2b2e] px-2.5 py-1.5 text-xs text-[#f0f0f4] placeholder-[#707075] outline-none focus:border-[#4a8fc7] shadow-[inset_1px_1px_2px_rgba(0,0,0,0.5)]"
/>
</div>
{/* Action Buttons */}
- <div className="space-y-2.5">
+ <div className="space-y-2">
<button
onClick={handleJoinBrowser}
- className="w-full flex items-center justify-between rounded-lg border border-[#3e3e3e] bg-[#2a2a2a] hover:bg-[#333333] hover:border-[#4e4e4e] px-4 py-3 text-sm font-semibold text-white transition-colors shadow-sm cursor-pointer"
+ className="w-full flex items-center justify-between rounded-[2px] border border-[#242426] bg-gradient-to-b from-[#56565a] to-[#424245] hover:from-[#626266] hover:to-[#4b4b4e] px-3.5 py-2 text-xs font-medium text-[#f0f0f4] transition-colors shadow-[inset_0_1px_0_rgba(255,255,255,0.18),0_1px_1px_rgba(0,0,0,0.3)] cursor-pointer"
>
- <div className="flex items-center space-x-2.5">
- <Globe className="w-4 h-4" />
- <span>Continue directly in browser</span>
+ <div className="flex items-center space-x-2">
+ <Globe className="w-3.5 h-3.5 text-[#93c5fd]" />
+ <span>Connect in Web Browser</span>
</div>
- <ArrowRight className="w-4 h-4" />
+ <ArrowRight className="w-3.5 h-3.5" />
</button>
<button
onClick={handleOpenInApp}
- className="w-full flex items-center justify-between rounded-lg border border-[#3e3e3e] bg-[#2a2a2a] hover:bg-[#333333] px-4 py-2.5 text-xs font-medium text-[#e0e0e0] transition-colors cursor-pointer"
+ className="w-full flex items-center justify-between rounded-[2px] border border-[#242426] bg-gradient-to-b from-[#48484c] to-[#38383b] hover:from-[#525256] hover:to-[#404043] px-3.5 py-2 text-xs font-medium text-[#d0d0d5] transition-colors shadow-[inset_0_1px_0_rgba(255,255,255,0.12)] cursor-pointer"
>
- <div className="flex items-center space-x-2.5">
- <Monitor className="w-4 h-4 text-emerald-400" />
- <span>Open in Ink Studio App (.exe)</span>
+ <div className="flex items-center space-x-2">
+ <Monitor className="w-3.5 h-3.5 text-emerald-400" />
+ <span>Launch Desktop Client (.exe)</span>
</div>
</button>
</div>
- <div className="mt-4 text-center">
- <span className="text-[11px] text-[#777777]">
- Drawing in browser requires no installation and supports graphic tablets and styluses!
+ <div className="mt-3.5 text-center">
+ <span className="text-[10px] text-[#808085]">
+ Supports graphic tablets, stylus pressure, and real-time synchronization.
</span>
</div>
</div>
diff --git a/src/components/WelcomeScreen.tsx b/src/components/WelcomeScreen.tsx
new file mode 100644
index 0000000..135b75a
--- /dev/null
+++ b/src/components/WelcomeScreen.tsx
@@ -0,0 +1,535 @@
+import React, { useState, useEffect } from 'react';
+import {
+ FilePlus,
+ FolderOpen,
+ Search,
+ X,
+ Star,
+ Trash2,
+ FileText,
+} from 'lucide-react';
+import {
+ RecentDocument,
+ loadRecentDocuments,
+ toggleStarDocument,
+ removeRecentDocument,
+ permanentlyDeleteDocument,
+ formatFileSize,
+} from '../utils/recentDocumentsManager';
+import { DeleteDocumentModal } from './DeleteDocumentModal';
+import { ThemePreset } from '../types/settings';
+
+interface WelcomeScreenProps {
+ userName: string;
+ onNewDocument: () => void;
+ onOpenFile: () => void;
+ onSelectRecentDocument?: (doc: RecentDocument) => void;
+ showToast: (msg: string) => void;
+ themePreset?: ThemePreset;
+}
+
+export const WelcomeScreen: React.FC<WelcomeScreenProps> = ({
+ userName,
+ onNewDocument,
+ 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);
+ const [isDeleteModalOpen, setIsDeleteModalOpen] = useState<boolean>(false);
+
+ useEffect(() => {
+ let isMounted = true;
+ loadRecentDocuments().then((docs) => {
+ if (isMounted) setDocuments(docs);
+ });
+ return () => {
+ isMounted = false;
+ };
+ }, []);
+
+ const handleToggleStar = async (doc: RecentDocument, e: React.MouseEvent) => {
+ e.stopPropagation();
+ const newStarred = await toggleStarDocument(doc.id);
+ setDocuments((prev) =>
+ prev.map((d) => (d.id === doc.id ? { ...d, isStarred: newStarred } : d))
+ );
+ showToast(newStarred ? `Starred: ${doc.title}` : `Unstarred: ${doc.title}`);
+ };
+
+ const handleOpenDelete = (doc: RecentDocument, e: React.MouseEvent) => {
+ e.stopPropagation();
+ setDeleteTargetDoc(doc);
+ setIsDeleteModalOpen(true);
+ };
+
+ const handleHideFromApp = async (doc: RecentDocument) => {
+ setIsDeleteModalOpen(false);
+ await removeRecentDocument(doc.id);
+ setDocuments((prev) => prev.filter((d) => d.id !== doc.id));
+ setDeleteTargetDoc(null);
+ showToast(`Removed "${doc.title}"`);
+ };
+
+ const handlePermanentDelete = async (doc: RecentDocument) => {
+ setIsDeleteModalOpen(false);
+ 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)`
+ );
+ };
+
+ const cleanQuery = searchQuery.trim().toLowerCase();
+ const filtered = documents.filter((doc) => {
+ if (!cleanQuery) return true;
+ return (
+ doc.title.toLowerCase().includes(cleanQuery) ||
+ doc.path.toLowerCase().includes(cleanQuery)
+ );
+ });
+
+ const starredDocs = filtered.filter((d) => d.isStarred);
+ const regularDocs = filtered;
+
+ if (themePreset === 'modern') {
+ return (
+ <div className="flex-1 flex flex-col h-full bg-[#0c0d12] text-white/90 overflow-y-auto select-none font-sans">
+ {/* Top Utility Header */}
+ <div className="border-b border-white/[0.08] bg-[#121318]/90 backdrop-blur-md px-8 py-3.5 shrink-0">
+ <div className="max-w-6xl mx-auto flex items-center justify-between gap-4">
+ <div className="flex items-center space-x-3">
+ <span className="w-2.5 h-2.5 rounded-full bg-[var(--modern-accent)] shadow-[0_0_8px_var(--modern-accent)]" />
+ <span className="text-sm font-semibold tracking-tight text-white">
+ Ink Studio
+ </span>
+ <span className="text-white/20">/</span>
+ <span className="text-xs text-white/50">Recent Documents</span>
+ </div>
+
+ <div className="flex items-center space-x-2.5">
+ <button
+ type="button"
+ onClick={onNewDocument}
+ className="flex items-center space-x-1.5 px-3.5 py-1.5 rounded-lg bg-[var(--modern-accent)] hover:brightness-110 active:scale-[0.98] text-xs font-medium text-white shadow-sm transition-all cursor-pointer"
+ >
+ <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.5 py-1.5 rounded-lg bg-white/[0.05] hover:bg-white/[0.1] active:scale-[0.98] border border-white/10 text-xs font-medium text-white/90 transition-all cursor-pointer"
+ >
+ <FolderOpen className="w-3.5 h-3.5 text-white/70" />
+ <span>Open File...</span>
+ </button>
+ </div>
+ </div>
+ </div>
+
+ {/* Main Container */}
+ <div className="max-w-6xl w-full mx-auto p-8 space-y-8 flex-1">
+ <div>
+ <h1 className="text-xl font-semibold tracking-tight text-white">
+ Welcome back, {displayName}
+ </h1>
+ </div>
+
+ {/* Search Bar */}
+ <div className="flex items-center justify-between gap-4 pb-3 border-b border-white/[0.06]">
+ <div className="relative w-80">
+ <Search className="w-3.5 h-3.5 text-white/40 absolute left-3 top-2.5 pointer-events-none" />
+ <input
+ type="text"
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ placeholder="Filter files..."
+ className="w-full pl-9 pr-8 py-1.5 text-xs bg-white/[0.04] border border-white/[0.08] rounded-lg text-white placeholder-white/40 outline-none focus:border-[var(--modern-accent)] focus:ring-1 focus:ring-[var(--modern-accent)] transition-all"
+ />
+ {searchQuery && (
+ <button
+ type="button"
+ onClick={() => setSearchQuery('')}
+ className="absolute right-2.5 top-2 text-white/40 hover:text-white"
+ >
+ <X className="w-3 h-3" />
+ </button>
+ )}
+ </div>
+
+ <div className="text-[11px] font-mono text-white/40">
+ {filtered.length} {filtered.length === 1 ? 'file' : 'files'}
+ </div>
+ </div>
+
+ {/* Starred Section */}
+ {starredDocs.length > 0 && (
+ <section className="space-y-3">
+ <div className="flex items-center space-x-2 text-xs font-semibold text-white/70 uppercase tracking-wider">
+ <Star className="w-3.5 h-3.5 text-amber-400 fill-amber-400" />
+ <span>Favorites ({starredDocs.length})</span>
+ </div>
+
+ <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3.5">
+ {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>
+ </section>
+ )}
+
+ {/* Recent Section */}
+ <section className="space-y-3">
+ <div className="text-xs font-semibold text-white/70 uppercase tracking-wider">
+ All Documents ({regularDocs.length})
+ </div>
+
+ {regularDocs.length === 0 ? (
+ <div className="border border-dashed border-white/10 bg-white/[0.02] p-10 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 lg:grid-cols-5 gap-3.5">
+ {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>
+ )}
+ </section>
+ </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>
+
+ <div className="flex items-center space-x-2">
+ <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"
+ >
+ <FilePlus className="w-3.5 h-3.5 text-[#93c5fd]" />
+ <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"
+ >
+ <FolderOpen className="w-3.5 h-3.5 text-[#facc15]" />
+ <span>Open File...</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>
+ </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>
+
+ <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
+ {starredDocs.map((doc) => (
+ <VintageDocCard
+ key={`starred-${doc.id}`}
+ doc={doc}
+ onSelect={() =>
+ onSelectRecentDocument ? onSelectRecentDocument(doc) : onOpenFile()
+ }
+ onToggleStar={(e) => handleToggleStar(doc, e)}
+ onDelete={(e) => handleOpenDelete(doc, e)}
+ />
+ ))}
+ </div>
+ </section>
+ )}
+
+ {/* Recent Section */}
+ <section className="space-y-3">
+ <div className="text-xs font-semibold text-[#c8c8cc] uppercase tracking-wider">
+ All Documents ({regularDocs.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.'}
+ </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
+ key={`recent-${doc.id}`}
+ doc={doc}
+ onSelect={() =>
+ onSelectRecentDocument ? onSelectRecentDocument(doc) : onOpenFile()
+ }
+ onToggleStar={(e) => handleToggleStar(doc, e)}
+ onDelete={(e) => handleOpenDelete(doc, e)}
+ />
+ ))}
+ </div>
+ )}
+ </section>
+ </div>
+
+ {/* Delete Confirmation Modal */}
+ <DeleteDocumentModal
+ isOpen={isDeleteModalOpen}
+ document={deleteTargetDoc}
+ onClose={() => {
+ setIsDeleteModalOpen(false);
+ setDeleteTargetDoc(null);
+ }}
+ onHideFromApp={handleHideFromApp}
+ onPermanentlyDelete={handlePermanentDelete}
+ />
+ </div>
+ );
+};
+
+interface VintageDocCardProps {
+ 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>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+const ModernDocCard: React.FC<VintageDocCardProps> = ({
+ doc,
+ onSelect,
+ onToggleStar,
+ onDelete,
+}) => {
+ return (
+ <div
+ onClick={onSelect}
+ className="group relative flex flex-col bg-[#14151b] hover:bg-[#1a1b24] border border-white/[0.08] hover:border-[var(--modern-accent-border)] rounded-xl p-3 cursor-pointer transition-all duration-150 shadow-xs hover:shadow-lg hover:-translate-y-0.5"
+ title={`${doc.title}\n${doc.path}`}
+ >
+ {/* Thumbnail Area */}
+ <div className="relative aspect-[4/3] bg-[#0c0d12] border border-white/[0.04] overflow-hidden flex items-center justify-center rounded-lg mb-2.5">
+ {doc.coverUrl ? (
+ <img
+ src={doc.coverUrl}
+ alt={doc.title}
+ className="w-full h-full object-cover select-none pointer-events-none group-hover:scale-105 transition-transform duration-300"
+ />
+ ) : (
+ <div className="flex flex-col items-center justify-center text-white/30 space-y-1">
+ <FileText className="w-6 h-6 stroke-[1.5]" />
+ <span className="text-[9px] font-mono uppercase tracking-wider text-white/40">{doc.fileType || 'CANVAS'}</span>
+ </div>
+ )}
+
+ {/* Quick Actions (top corners) */}
+ <div className="absolute top-1.5 left-1.5 flex items-center space-x-1">
+ <button
+ type="button"
+ onClick={onToggleStar}
+ title={doc.isStarred ? 'Remove favorite' : 'Add favorite'}
+ className={`w-6 h-6 rounded-md flex items-center justify-center transition-all cursor-pointer ${
+ doc.isStarred
+ ? 'bg-black/60 text-amber-400 backdrop-blur-xs'
+ : 'bg-black/50 text-white/40 opacity-0 group-hover:opacity-100 hover:text-amber-400 backdrop-blur-xs'
+ }`}
+ >
+ <Star className={`w-3.5 h-3.5 ${doc.isStarred ? 'fill-amber-400' : ''}`} />
+ </button>
+ </div>
+
+ <div className="absolute top-1.5 right-1.5">
+ <button
+ type="button"
+ onClick={onDelete}
+ title="Delete file options"
+ className="w-6 h-6 rounded-md bg-black/50 hover:bg-rose-950/80 text-white/40 hover:text-rose-300 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all backdrop-blur-xs cursor-pointer"
+ >
+ <Trash2 className="w-3.5 h-3.5" />
+ </button>
+ </div>
+ </div>
+
+ {/* Meta */}
+ <div className="min-w-0 space-y-1">
+ <div className="text-xs font-medium text-white/90 truncate group-hover:text-[var(--modern-accent)] transition-colors">
+ {doc.title}
+ </div>
+ <div className="flex items-center justify-between text-[10px] text-white/40 font-mono">
+ <span>{formatFileSize(doc.size)}</span>
+ <span className="uppercase text-[9px] px-1.5 py-0.5 bg-white/[0.05] border border-white/[0.06] rounded font-mono text-white/60">
+ {doc.fileType || 'CANVAS'}
+ </span>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/src/components/WindowControls.tsx b/src/components/WindowControls.tsx
index 7f36504..4c45d02 100644
--- a/src/components/WindowControls.tsx
+++ b/src/components/WindowControls.tsx
@@ -93,6 +93,53 @@ export const WindowControls: React.FC<WindowControlsProps> = ({ themePreset: _th
}
}, [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>
+ );
+ }
+
// Japanese Manga Studio / ComicStudio rounded capsule control pod (Old Studio)
return (
<div
diff --git a/src/hooks/useCanvasDrawing.ts b/src/hooks/useCanvasDrawing.ts
index 0138912..1bdade4 100644
--- a/src/hooks/useCanvasDrawing.ts
+++ b/src/hooks/useCanvasDrawing.ts
@@ -10,7 +10,19 @@ import {
CanvasColorMode,
DirtyRect,
LayerItem,
+ TileDelta,
+ VectorStroke,
+ VectorKnot,
} from '../types/editor';
+import { globalTileGrid } from '../utils/tileEngine';
+import { globalUndoCache } from '../utils/undoCache';
+import {
+ applyVectorEraser,
+ renderVectorLayer,
+ renderVectorStroke,
+ computeStrokeBounds,
+ simplifyPathPoints,
+} from '../utils/vectorEngine';
import {
calculateStrokeWidth,
drawSmoothCubicBezierSegment,
@@ -23,6 +35,7 @@ import {
getCanvasToViewportMatrix,
getReusableBakeCanvas,
renderCompleteStroke,
+ applyParametricTaper,
} from '../utils/canvasUtils';
import { enforceColorMode, binarizeCanvasRect } from '../utils/colorUtils';
import { drawPencilCubicBezierSegment, drawPencilDot, PencilGrade } from '../utils/pencilEngine';
@@ -30,6 +43,7 @@ import {
drawTexturedCubicBezierSegment,
drawTexturedDot,
TexturedBrushOptions,
+ RadialMixingOptions,
} from '../utils/stampEngine';
import { PaintReservoir, LayerPixelSampler } from '../utils/colorMixingEngine';
import { applyLayerEffects } from '../utils/layerEffectsEngine';
@@ -57,7 +71,7 @@ interface UseCanvasDrawingProps {
strokeCanvasRef?: React.RefObject<HTMLCanvasElement | null>;
onCollabStrokeStart?: (strokeId: string, layerId: string, brushSettings: BrushSettings, tool: ToolType, startPoint: Point) => void;
onCollabStrokeChunk?: (strokeId: string, points: Point[]) => void;
- onCollabStrokeFinish?: (strokeId: string, layerId: string, endPoint: Point, dirtyRect?: DirtyRect) => void;
+ onCollabStrokeFinish?: (strokeId: string, layerId: string, endPoint: Point, dirtyRect?: DirtyRect, vectorStroke?: VectorStroke) => void;
onCollabCursorMove?: (x: number, y: number, isDrawing: boolean, tool: ToolType) => void;
perspectiveRuler?: PerspectiveRuler | null;
onActiveConstraintAxisChange?: (axis: ConstraintAxis | null) => void;
@@ -171,7 +185,7 @@ export function useCanvasDrawing({
const strokePointsRef = useRef<Point[]>([]);
// Raw points window buffer for symmetric Gaussian FIR stabilization
- const rawPointsBufferRef = useRef<{ x: number; y: number; pressure: number; pointerType: string }[]>([]);
+ const rawPointsBufferRef = useRef<{ x: number; y: number; pressure: number; pointerType: string; tiltX?: number; tiltY?: number; twist?: number }[]>([]);
// Stabilizer tracking ref
const stabilizedPointRef = useRef<Point | null>(null);
@@ -208,7 +222,7 @@ export function useCanvasDrawing({
const lastProcessedPointRef = useRef<{ x: number; y: number } | null>(null);
// Queue of incoming pointer coordinates to be batched and processed via requestAnimationFrame (rAF)
- const pendingPointsQueueRef = useRef<{ x: number; y: number; pressure: number; pointerType: string }[]>([]);
+ const pendingPointsQueueRef = useRef<{ x: number; y: number; pressure: number; pointerType: string; tiltX?: number; tiltY?: number; twist?: number }[]>([]);
const drawRafIdRef = useRef<number | null>(null);
const clearDraftRafRef = useRef<number | null>(null);
@@ -306,6 +320,9 @@ export function useCanvasDrawing({
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 initialItem: HistoryItem = {
id: `hist-init-${now}`,
type: 'initial',
@@ -334,11 +351,36 @@ export function useCanvasDrawing({
beforeData: ImageData | null,
afterData: ImageData | null,
targetLayerId: string,
- dirtyRect?: DirtyRect
+ dirtyRect?: DirtyRect,
+ explicitTileDeltas?: TileDelta[],
+ vectorDelta?: { before: VectorStroke[]; after: VectorStroke[] },
+ peerId?: string | number,
+ strokeId?: string
) => {
const now = Date.now();
const canvas = layerCanvasesRef.current.get(targetLayerId) || getActiveCanvas();
+ let tileDeltas = explicitTileDeltas;
+
+ 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)) {
+ const activeLayer = layersRef.current?.find((l) => l.id === targetLayerId);
+ const isMono = colorModeRef.current === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
+ const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
+
+ const beforeSnapshot = globalTileGrid.snapshotTilesInRect(targetLayerId, effectiveDirtyRect);
+
+ if (afterData) {
+ globalTileGrid.writeImageData(targetLayerId, afterData, effectiveDirtyRect.x, effectiveDirtyRect.y, targetFormat);
+ } else if (actionType === 'clear') {
+ globalTileGrid.clearLayer(targetLayerId);
+ }
+
+ tileDeltas = globalTileGrid.computeDeltasFromSnapshot(beforeSnapshot, targetLayerId, effectiveDirtyRect);
+ }
+
const item: HistoryItem = {
id: `hist-${now}-${Math.random().toString(36).substring(2, 7)}`,
type: actionType,
@@ -347,10 +389,15 @@ export function useCanvasDrawing({
timeFormatted: formatTime(now),
thumbnailUrl: '',
layerId: targetLayerId,
- beforeImageData: beforeData,
- afterImageData: afterData,
- imageData: afterData || undefined,
- dirtyRect,
+ // 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),
+ dirtyRect: effectiveDirtyRect,
+ tileDeltas,
+ vectorStrokesDelta: vectorDelta,
+ peerId,
+ strokeId,
};
// Branching: truncate any future redo steps
@@ -366,6 +413,13 @@ export function useCanvasDrawing({
historyIndexRef.current = newHistory.length - 1;
syncHistoryState();
+ // Seamless LRU disk cache offloading via Tauri v2 Rust IPC
+ if (tileDeltas && tileDeltas.length > 0) {
+ globalUndoCache.registerStep(item, historyRef.current).catch((err) => {
+ console.warn('[History] LRU cache registration failed:', err);
+ });
+ }
+
// Defer thumbnail generation so stroke release is 100% instant
requestAnimationFrame(() => {
if (canvas) {
@@ -425,7 +479,7 @@ export function useCanvasDrawing({
// Jump directly to any past or future history step
const jumpToHistoryIndex = useCallback(
- (targetIndex: number) => {
+ async (targetIndex: number) => {
if (isDrawingRef.current) {
abortActiveStroke();
}
@@ -443,8 +497,40 @@ export function useCanvasDrawing({
const sourceCanvas = layerSourceCanvasesRef?.current?.get(targetLayerId);
const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);
const isToneStep = Boolean(targetLayer?.toneEnabled && sourceCanvas);
-
- if (isToneStep && sourceCanvas) {
+ const deltas = await globalUndoCache.resolveDeltas(item);
+
+ // Restore vector strokes if vector delta exists
+ if (item.vectorStrokesDelta && targetLayer && canvas) {
+ targetLayer.vectorStrokes = item.vectorStrokesDelta.before;
+ const cCtx = get2DContext(canvas);
+ if (cCtx) {
+ cCtx.clearRect(0, 0, canvas.width, canvas.height);
+ renderVectorLayer(cCtx, targetLayer.vectorStrokes);
+ const fullData = cCtx.getImageData(0, 0, canvas.width, canvas.height);
+ const isMono = targetLayer.expressionColor === 'monochrome';
+ globalTileGrid.writeImageData(targetLayerId, fullData, 0, 0, isMono ? 'monochrome-1bit' : 'color-32bit');
+ }
+ } else if (deltas && deltas.length > 0) {
+ globalTileGrid.applyTileDeltas(deltas, 'undo');
+
+ if (isToneStep && sourceCanvas) {
+ globalTileGrid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
+ if (canvas && targetLayer) {
+ applyLayerEffects(
+ sourceCanvas,
+ canvas,
+ targetLayer,
+ dimensionsRef.current.dpi ?? 600,
+ item.dirtyRect
+ );
+ }
+ } else if (canvas) {
+ globalTileGrid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
+ if (sourceCanvas) {
+ globalTileGrid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
+ }
+ }
+ } else if (isToneStep && sourceCanvas) {
const sCtx = get2DContext(sourceCanvas);
if (sCtx) {
if (item.dirtyRect && item.beforeImageData) {
@@ -526,8 +612,40 @@ export function useCanvasDrawing({
const sourceCanvas = layerSourceCanvasesRef?.current?.get(targetLayerId);
const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);
const isToneStep = Boolean(targetLayer?.toneEnabled && sourceCanvas);
-
- if (isToneStep && sourceCanvas) {
+ const deltas = await globalUndoCache.resolveDeltas(item);
+
+ // Restore vector strokes if vector delta exists
+ if (item.vectorStrokesDelta && targetLayer && canvas) {
+ targetLayer.vectorStrokes = item.vectorStrokesDelta.after;
+ const cCtx = get2DContext(canvas);
+ if (cCtx) {
+ cCtx.clearRect(0, 0, canvas.width, canvas.height);
+ renderVectorLayer(cCtx, targetLayer.vectorStrokes);
+ const fullData = cCtx.getImageData(0, 0, canvas.width, canvas.height);
+ const isMono = targetLayer.expressionColor === 'monochrome';
+ globalTileGrid.writeImageData(targetLayerId, fullData, 0, 0, isMono ? 'monochrome-1bit' : 'color-32bit');
+ }
+ } else if (deltas && deltas.length > 0) {
+ globalTileGrid.applyTileDeltas(deltas, 'redo');
+
+ if (isToneStep && sourceCanvas) {
+ globalTileGrid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
+ if (canvas && targetLayer) {
+ applyLayerEffects(
+ sourceCanvas,
+ canvas,
+ targetLayer,
+ dimensionsRef.current.dpi ?? 600,
+ item.dirtyRect
+ );
+ }
+ } else if (canvas) {
+ globalTileGrid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
+ if (sourceCanvas) {
+ globalTileGrid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
+ }
+ }
+ } else if (isToneStep && sourceCanvas) {
const sCtx = get2DContext(sourceCanvas);
if (sCtx) {
if (item.dirtyRect && dataToApply) {
@@ -602,8 +720,9 @@ export function useCanvasDrawing({
historyIndexRef.current = targetIndex;
syncHistoryState();
+ globalTileGrid.notifyChange(true);
},
- [abortActiveStroke, activeLayerId, getActiveCanvas, layerCanvasesRef, onUpdateLayerThumbnail, syncHistoryState]
+ [abortActiveStroke, activeLayerId, getActiveCanvas, layerCanvasesRef, layerSourceCanvasesRef, onUpdateLayerThumbnail, syncHistoryState]
);
// Undo action
@@ -624,6 +743,78 @@ export function useCanvasDrawing({
jumpToHistoryIndex(historyIndexRef.current + 1);
}, [abortActiveStroke, jumpToHistoryIndex]);
+ // Selective Undo per Peer
+ const selectiveUndo = useCallback(
+ async (peerIdToUndo?: string | number) => {
+ if (isDrawingRef.current) {
+ abortActiveStroke();
+ }
+
+ const history = historyRef.current;
+ const currIdx = historyIndexRef.current;
+ if (currIdx < 0 || history.length === 0) return;
+
+ // Find the most recent history item matching the requested peerId (or local)
+ let targetItemIdx = -1;
+ for (let i = currIdx; i >= 0; i--) {
+ const item = history[i];
+ if (!peerIdToUndo || item.peerId === peerIdToUndo || (peerIdToUndo === 'local' && !item.peerId)) {
+ targetItemIdx = i;
+ break;
+ }
+ }
+
+ if (targetItemIdx === -1) return;
+
+ const item = history[targetItemIdx];
+ const targetLayerId = item.layerId || activeLayerId;
+ const canvas = layerCanvasesRef.current.get(targetLayerId) || getActiveCanvas();
+ const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);
+
+ // Revert vector strokes if vector delta exists
+ if (item.vectorStrokesDelta && targetLayer && canvas) {
+ targetLayer.vectorStrokes = item.vectorStrokesDelta.before;
+ const cCtx = get2DContext(canvas);
+ if (cCtx) {
+ cCtx.clearRect(0, 0, canvas.width, canvas.height);
+ renderVectorLayer(cCtx, targetLayer.vectorStrokes);
+ const fullData = cCtx.getImageData(0, 0, canvas.width, canvas.height);
+ const isMono = targetLayer.expressionColor === 'monochrome';
+ globalTileGrid.writeImageData(targetLayerId, fullData, 0, 0, isMono ? 'monochrome-1bit' : 'color-32bit');
+ }
+ } else {
+ // Revert tile deltas or image data
+ const deltas = await globalUndoCache.resolveDeltas(item);
+ if (deltas && deltas.length > 0) {
+ globalTileGrid.applyTileDeltas(deltas, 'undo');
+ if (canvas) {
+ globalTileGrid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
+ }
+ } else if (canvas && item.beforeImageData) {
+ const cCtx = get2DContext(canvas);
+ if (cCtx) {
+ if (item.dirtyRect) {
+ cCtx.putImageData(item.beforeImageData, item.dirtyRect.x, item.dirtyRect.y);
+ } else {
+ cCtx.putImageData(item.beforeImageData, 0, 0);
+ }
+ }
+ }
+ }
+
+ // Remove the undone item from history
+ historyRef.current.splice(targetItemIdx, 1);
+ historyIndexRef.current = Math.min(historyIndexRef.current - 1, historyRef.current.length - 1);
+ syncHistoryState();
+
+ if (canvas) {
+ onUpdateLayerThumbnail(targetLayerId);
+ }
+ globalTileGrid.notifyChange(true);
+ },
+ [abortActiveStroke, activeLayerId, getActiveCanvas, layerCanvasesRef, onUpdateLayerThumbnail, syncHistoryState]
+ );
+
// Clear active layer action
const clearCanvas = useCallback(() => {
const canvas = getActiveCanvas();
@@ -632,6 +823,14 @@ export function useCanvasDrawing({
if (!ctx) return;
const beforeData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ const activeLayer = layersRef.current?.find((l) => l.id === activeLayerId);
+
+ let vectorDelta: { before: VectorStroke[]; after: VectorStroke[] } | undefined;
+ if (activeLayer?.type === 'vector') {
+ const beforeStrokes = [...(activeLayer.vectorStrokes || [])];
+ activeLayer.vectorStrokes = [];
+ vectorDelta = { before: beforeStrokes, after: [] };
+ }
if (activeLayerId === 'layer-bg') {
ctx.fillStyle = '#ffffff';
@@ -655,12 +854,22 @@ export function useCanvasDrawing({
const afterData = ctx.getImageData(0, 0, canvas.width, canvas.height);
onUpdateLayerThumbnail(activeLayerId);
- pushHistoryStep('clear', 'Clear Layer', beforeData, afterData, activeLayerId, {
- x: 0,
- y: 0,
- width: canvas.width,
- height: canvas.height,
- });
+ pushHistoryStep(
+ 'clear',
+ 'Clear Layer',
+ beforeData,
+ afterData,
+ activeLayerId,
+ {
+ x: 0,
+ y: 0,
+ width: canvas.width,
+ height: canvas.height,
+ },
+ undefined,
+ vectorDelta
+ );
+ globalTileGrid.notifyChange(true);
}, [activeLayerId, activeLayerLocked, getActiveCanvas, layerSourceCanvasesRef, onUpdateLayerThumbnail, pushHistoryStep]);
// Initialize canvas first history state as soon as canvas is mounted
@@ -713,7 +922,11 @@ export function useCanvasDrawing({
bs.pressureCurve
);
- return { x, y, pressure, width };
+ const tiltX = e.tiltX ?? 0;
+ const tiltY = e.tiltY ?? 0;
+ const twist = e.twist ?? 0;
+
+ return { x, y, pressure, width, tiltX, tiltY, twist };
},
[getViewportRect]
);
@@ -764,27 +977,68 @@ export function useCanvasDrawing({
const isMonochrome = mode === 'monochrome' || isMonoLayer;
const isTone = isToneStrokeRef.current;
const sourceCanvas = isTone ? layerSourceCanvasesRef?.current?.get(currentLayerId) : null;
- const isWetColor = isWetColorStrokeRef.current;
- const isTranslucentBrush = !isEraser && !isMonochrome && (bs.opacity ?? 1.0) < 0.999;
- const isDirectRender = isMonochrome || isWetColor || isEraser || (!isTranslucentBrush && !isToneLayer);
-
- let targetCtx: CanvasRenderingContext2D | null = null;
- if (isToneLayer && sourceCanvas) {
- targetCtx = get2DContext(sourceCanvas);
- drewDirectlyOnLayerCanvasRef.current = true;
- } else if (isDirectRender && canvas) {
- targetCtx = get2DContext(canvas);
- drewDirectlyOnLayerCanvasRef.current = true;
- } else {
- targetCtx = draftCtx;
- }
- if (!targetCtx) return;
const 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;
+ 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
+ );
+ }
+ }
+
+ // Simultaneously render eraser's path preview on draftCtx with dashed outline for immediate visual feedback
+ 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, (segStart.width + segEnd.width) / 2);
+ draftCtx.beginPath();
+ draftCtx.moveTo(segStart.x, segStart.y);
+ draftCtx.bezierCurveTo(c1.x, c1.y, c2.x, c2.y, segEnd.x, segEnd.y);
+ draftCtx.stroke();
+ draftCtx.restore();
+ return;
+ }
+
+ // Always render the live stroke onto the draft canvas overlay for zero-latency 120 FPS feedback
+ const targetCtx = draftCtx;
+ drewDirectlyOnLayerCanvasRef.current = false;
+
if (bs.customTipImage) {
const tipOptions: TexturedBrushOptions = {
size: bs.size,
@@ -827,6 +1081,8 @@ export function useCanvasDrawing({
reservoir: activeReservoirRef.current || undefined,
isEraser: isEraser && !isBgEraser,
isBgEraser,
+ alphaLocked: Boolean(activeLayer?.alphaLocked),
+ isTransparentInk: Boolean(bs.isTransparentInk),
currentStrokeDist: strokeTotalDistanceRef.current,
};
@@ -846,7 +1102,7 @@ export function useCanvasDrawing({
const pFlow = bs.flow ?? 0.74;
const pGrain = bs.grain ?? 1.0;
- drawPencilCubicBezierSegment(
+ stampRemainderDistRef.current = drawPencilCubicBezierSegment(
targetCtx,
segStart,
c1,
@@ -856,10 +1112,25 @@ export function useCanvasDrawing({
grade,
pFlow,
pGrain,
- bs.hardness
+ bs.hardness,
+ stampRemainderDistRef.current,
+ Boolean(activeLayer?.alphaLocked),
+ Boolean(bs.isTransparentInk)
);
} else {
- drawSmoothCubicBezierSegment(
+ 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),
+ };
+ stampRemainderDistRef.current = drawSmoothCubicBezierSegment(
targetCtx,
segStart,
c1,
@@ -869,14 +1140,18 @@ export function useCanvasDrawing({
isEraser && !isBgEraser,
strokeHardness,
strokeFlow,
- strokeSpacing
+ strokeSpacing,
+ stampRemainderDistRef.current,
+ bs.thickness ?? 1.0,
+ ((bs.customTipAngle ?? 0) * Math.PI) / 180,
+ radialMixingOptions
);
}
}, [getActiveCanvas]);
// Stabilize and render point onto draft canvas
const applyStabilizedPointAndRender = useCallback(
- (draftCtx: CanvasRenderingContext2D, rawX: number, rawY: number, rawPressure: number, pointerType: string) => {
+ (draftCtx: CanvasRenderingContext2D, rawX: number, rawY: number, rawPressure: number, pointerType: string, rawTiltX: number = 0, rawTiltY: number = 0, rawTwist: number = 0) => {
const bs = brushSettingsRef.current;
const dims = dimensionsRef.current;
const stab = Math.min(50, Math.max(0, bs.stabilization ?? 0));
@@ -892,7 +1167,7 @@ export function useCanvasDrawing({
velocityScale = Math.max(0.65, Math.min(1.0, 1.0 - Math.max(0, speed - 0.5) * 0.12));
}
- rawPointsBufferRef.current.push({ x: rawX, y: rawY, pressure: rawPressure, pointerType });
+ rawPointsBufferRef.current.push({ x: rawX, y: rawY, pressure: rawPressure, pointerType, tiltX: rawTiltX, tiltY: rawTiltY, twist: rawTwist });
let pt: Point;
if (stab <= 0) {
@@ -907,29 +1182,34 @@ export function useCanvasDrawing({
velocityScale,
bs.pressureCurve
);
- pt = { x: rawX, y: rawY, pressure: rawPressure, width };
+ pt = { x: rawX, y: rawY, pressure: rawPressure, width, tiltX: rawTiltX, tiltY: rawTiltY, twist: rawTwist };
stabilizedPointRef.current = pt;
} else {
- const W = Math.min(9, Math.max(3, 1 + 2 * Math.floor(stab / 7)));
- if (rawPointsBufferRef.current.length < W) {
- return;
+ const buf = rawPointsBufferRef.current;
+ const maxW = Math.min(8, Math.max(3, 1 + 2 * Math.floor(stab / 8)));
+ if (buf.length > maxW) {
+ buf.shift();
}
- const buf = rawPointsBufferRef.current;
- const mid = Math.floor(W / 2);
- let sumX = 0, sumY = 0, sumP = 0, sumW = 0;
- for (let i = 0; i < W; i++) {
- const w = Math.pow(2, mid - Math.abs(i - mid));
+ const len = buf.length;
+ let sumX = 0, sumY = 0, sumP = 0, sumTiltX = 0, sumTiltY = 0, sumTwist = 0, sumW = 0;
+ for (let i = 0; i < len; i++) {
+ const w = Math.pow(1.65, i);
sumX += buf[i].x * w;
sumY += buf[i].y * w;
sumP += buf[i].pressure * w;
+ sumTiltX += (buf[i].tiltX ?? 0) * w;
+ sumTiltY += (buf[i].tiltY ?? 0) * w;
+ sumTwist += (buf[i].twist ?? 0) * w;
sumW += w;
}
- buf.shift();
const smoothX = sumX / sumW;
const smoothY = sumY / sumW;
const smoothPressure = sumP / sumW;
+ const smoothTiltX = sumTiltX / sumW;
+ const smoothTiltY = sumTiltY / sumW;
+ const smoothTwist = sumTwist / sumW;
const smoothWidth = calculateStrokeWidth(
bs.size,
smoothPressure,
@@ -940,7 +1220,7 @@ export function useCanvasDrawing({
velocityScale,
bs.pressureCurve
);
- pt = { x: smoothX, y: smoothY, pressure: smoothPressure, width: smoothWidth };
+ pt = { x: smoothX, y: smoothY, pressure: smoothPressure, width: smoothWidth, tiltX: smoothTiltX, tiltY: smoothTiltY, twist: smoothTwist };
stabilizedPointRef.current = pt;
}
@@ -993,7 +1273,7 @@ export function useCanvasDrawing({
for (let i = 0; i < batch.length; i++) {
const item = batch[i];
- applyStabilizedPointAndRender(draftCtx, item.x, item.y, item.pressure, item.pointerType);
+ applyStabilizedPointAndRender(draftCtx, item.x, item.y, item.pressure, item.pointerType, item.tiltX, item.tiltY, item.twist);
if (allStrokePointsRef.current.length > 0) {
const lastPt = allStrokePointsRef.current[allStrokePointsRef.current.length - 1];
chunkPts.push(lastPt);
@@ -1188,6 +1468,9 @@ export function useCanvasDrawing({
y: startPoint.y,
pressure: startPoint.pressure,
pointerType: e.pointerType,
+ tiltX: startPoint.tiltX ?? 0,
+ tiltY: startPoint.tiltY ?? 0,
+ twist: startPoint.twist ?? 0,
}];
stabilizedPointRef.current = { ...startPoint };
lastProcessedPointRef.current = { x: startPoint.x, y: startPoint.y };
@@ -1214,12 +1497,10 @@ export function useCanvasDrawing({
const 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 isWetColor = !isEraser && Boolean(bs.colorMixing) && Boolean(bs.customTipImage);
+ const isWetColor = !isEraser && Boolean(bs.colorMixing);
isWetColorStrokeRef.current = isWetColor;
-
- const isTranslucentBrush = !isEraser && !isMonochrome && (bs.opacity ?? 1.0) < 0.999;
- const isDirectRender = isMonochrome || isWetColor || isEraser || (!isTranslucentBrush && !isToneLayer);
drewDirectlyOnLayerCanvasRef.current = false;
if (isToneLayer && sourceCanvas) {
@@ -1232,7 +1513,7 @@ export function useCanvasDrawing({
}
layerPixelSamplerRef.current = null;
activeReservoirRef.current = null;
- } else if ((isDirectRender || isWetColor) && canvas) {
+ } else if (isEraser && canvas) {
const backupCanvas = getDedicatedBackupCanvas(canvas.width, canvas.height);
const backupCtx = get2DContext(backupCanvas);
if (backupCtx) {
@@ -1240,17 +1521,17 @@ export function useCanvasDrawing({
backupCtx.drawImage(canvas, 0, 0);
strokeBackupCanvasRef.current = backupCanvas;
}
- if (isWetColor) {
+ layerPixelSamplerRef.current = null;
+ activeReservoirRef.current = null;
+ } else {
+ strokeBackupCanvasRef.current = null;
+ if (isWetColor && canvas) {
layerPixelSamplerRef.current = new LayerPixelSampler(canvas);
activeReservoirRef.current = new PaintReservoir(strokeColor);
} else {
layerPixelSamplerRef.current = null;
activeReservoirRef.current = null;
}
- } else {
- strokeBackupCanvasRef.current = null;
- layerPixelSamplerRef.current = null;
- activeReservoirRef.current = null;
}
const strokeId = `stroke-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`;
@@ -1259,85 +1540,114 @@ export function useCanvasDrawing({
stampRemainderDistRef.current = Math.max(0.2, startPoint.width * (bs.spacing ?? 0.08));
- const targetStartCtx = isToneLayer && sourceCanvas
- ? get2DContext(sourceCanvas)
- : (isDirectRender && canvas ? get2DContext(canvas) : draftCtx);
- if (targetStartCtx && targetStartCtx !== draftCtx) {
+ if (isEraser) {
drewDirectlyOnLayerCanvasRef.current = true;
- }
-
- 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,
- 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,
- isBgEraser,
- };
- if (targetStartCtx) {
- drawTexturedDot(targetStartCtx, startPoint, strokeColor, bs.customTipImage, tipOptions);
+ if (canvas) {
+ const cCtx = get2DContext(canvas);
+ if (cCtx) {
+ drawDot(cCtx, startPoint, strokeColor, !isBgEraser, strokeHardness, strokeFlow);
+ }
}
- } else if (isPencil) {
- const grade = (bs.preset as PencilGrade) || 'pencil-2b';
- if (targetStartCtx) {
+ 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;
+ 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,
+ 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: false,
+ isBgEraser: false,
+ alphaLocked: Boolean(activeLayer?.alphaLocked),
+ isTransparentInk: Boolean(bs.isTransparentInk),
+ };
+ drawTexturedDot(draftCtx, startPoint, strokeColor, bs.customTipImage, tipOptions);
+ } else if (isPencil) {
+ const grade = (bs.preset as PencilGrade) || 'pencil-2b';
drawPencilDot(
- targetStartCtx,
+ draftCtx,
startPoint,
strokeColor,
grade,
bs.flow ?? 0.74,
bs.grain ?? 1.0,
- bs.hardness
+ bs.hardness,
+ Boolean(activeLayer?.alphaLocked),
+ Boolean(bs.isTransparentInk)
);
- }
- } else {
- if (targetStartCtx) {
+ } 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),
+ };
drawDot(
- targetStartCtx,
+ draftCtx,
startPoint,
strokeColor,
- isEraser && !isBgEraser,
+ false,
strokeHardness,
- bs.flow ?? 1.0
+ bs.flow ?? 1.0,
+ radialMixingOptions
);
}
}
- if (isMonochrome && canvas && dirtyRectRef.current) {
+ if (isEraser && isMonochrome && canvas && dirtyRectRef.current) {
const dotDirty = dirtyRectRef.current;
const dw = dotDirty.maxX - dotDirty.minX;
const dh = dotDirty.maxY - dotDirty.minY;
@@ -1349,7 +1659,7 @@ export function useCanvasDrawing({
activeLayer?.monoExpressBlack ?? true,
activeLayer?.monoExpressWhite ?? true
);
- if (sourceCanvas && targetStartCtx !== get2DContext(sourceCanvas)) {
+ if (sourceCanvas) {
const sCtx = get2DContext(sourceCanvas);
sCtx?.drawImage(canvas, dotDirty.minX, dotDirty.minY, dw, dh, dotDirty.minX, dotDirty.minY, dw, dh);
}
@@ -1435,6 +1745,9 @@ export function useCanvasDrawing({
y: cy,
pressure: cPressure,
pointerType: cEvent.pointerType,
+ tiltX: cEvent.tiltX ?? 0,
+ tiltY: cEvent.tiltY ?? 0,
+ twist: cEvent.twist ?? 0,
});
}
@@ -1467,6 +1780,9 @@ export function useCanvasDrawing({
y: finalY,
pressure: point.pressure,
pointerType: e.pointerType,
+ tiltX: point.tiltX ?? e.tiltX ?? 0,
+ tiltY: point.tiltY ?? e.tiltY ?? 0,
+ twist: point.twist ?? e.twist ?? 0,
});
if (drawRafIdRef.current === null) {
@@ -1509,12 +1825,15 @@ export function useCanvasDrawing({
const buf = rawPointsBufferRef.current;
const len = buf.length;
const mid = Math.floor(len / 2);
- let sumX = 0, sumY = 0, sumP = 0, sumW = 0;
+ let sumX = 0, sumY = 0, sumP = 0, sumTiltX = 0, sumTiltY = 0, sumTwist = 0, sumW = 0;
for (let i = 0; i < len; i++) {
const w = Math.pow(2, mid - Math.abs(i - mid));
sumX += buf[i].x * w;
sumY += buf[i].y * w;
sumP += buf[i].pressure * w;
+ sumTiltX += (buf[i].tiltX ?? 0) * w;
+ sumTiltY += (buf[i].tiltY ?? 0) * w;
+ sumTwist += (buf[i].twist ?? 0) * w;
sumW += w;
}
const ptType = buf[0].pointerType;
@@ -1533,7 +1852,7 @@ export function useCanvasDrawing({
1.0,
bs.pressureCurve
);
- const pt: Point = { x: sX, y: sY, pressure: sP, width: sW };
+ const pt: Point = { x: sX, y: sY, pressure: sP, width: sW, tiltX: sumTiltX / sumW, tiltY: sumTiltY / sumW, twist: sumTwist / sumW };
allStrokePointsRef.current.push(pt);
if (draftCtx) {
renderDraftSegment(draftCtx, pt);
@@ -1559,6 +1878,9 @@ export function useCanvasDrawing({
? get2DContext(sourceCanvas)
: (drewDirectlyOnLayerCanvasRef.current && canvas ? get2DContext(canvas) : draftCtx);
+ const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, isMonochrome ? 'monochrome' : mode);
+ const strokeHardness = isMonochrome ? 1.0 : (bs.hardness ?? 1.0);
+
if (targetTailCtx && pts.length >= 2) {
const pLast = pts[pts.length - 1];
const pPrev = pts[pts.length - 2];
@@ -1571,8 +1893,6 @@ export function useCanvasDrawing({
}
const { c1, c2 } = catmullRomToBezier(pPrev2, pPrev, pLast, pLast);
- const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, isMonochrome ? 'monochrome' : mode);
- const strokeHardness = isMonochrome ? 1.0 : (bs.hardness ?? 1.0);
if (bs.customTipImage) {
const tipOptions: TexturedBrushOptions = {
@@ -1616,6 +1936,8 @@ export function useCanvasDrawing({
reservoir: activeReservoirRef.current || undefined,
isEraser: isEraser && !isBgEraser,
isBgEraser,
+ alphaLocked: Boolean(activeLayer?.alphaLocked),
+ isTransparentInk: Boolean(bs.isTransparentInk),
currentStrokeDist: strokeTotalDistanceRef.current,
};
drawTexturedCubicBezierSegment(
@@ -1641,9 +1963,24 @@ export function useCanvasDrawing({
grade,
bs.flow ?? 0.74,
bs.grain ?? 1.0,
- bs.hardness
+ bs.hardness,
+ stampRemainderDistRef.current,
+ Boolean(activeLayer?.alphaLocked),
+ Boolean(bs.isTransparentInk)
);
- } else if (bs.smoothing) {
+ } 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),
+ };
drawSmoothCubicBezierSegment(
targetTailCtx,
pPrev,
@@ -1654,9 +1991,27 @@ export function useCanvasDrawing({
isEraser && !isBgEraser,
strokeHardness,
bs.flow ?? 1.0,
- bs.spacing ?? 0.08
+ 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();
+ }
}
if (pts.length >= 2) {
@@ -1675,7 +2030,7 @@ export function useCanvasDrawing({
dirtyRectRef.current.maxY = Math.max(dirtyRectRef.current.maxY, tMaxY);
}
- if (isMonochrome && canvas) {
+ if (isEraser && isMonochrome && canvas) {
const tW = tMaxX - tMinX;
const tH = tMaxY - tMinY;
if (tW > 0 && tH > 0) {
@@ -1700,7 +2055,7 @@ export function useCanvasDrawing({
// BAKE STROKE INTO HIGH-RESOLUTION BASE CANVAS (Dirty Rect only)
const dirty = dirtyRectRef.current;
- if (isToneLayer && sourceCanvas && canvas) {
+ if (isEraser && isToneLayer && sourceCanvas && canvas) {
if (activeLayer) {
const freq = activeLayer?.toneFrequency ?? 60;
const cellSize = Math.max(3.5, (dimensionsRef.current.dpi ?? 600) / freq);
@@ -1719,9 +2074,118 @@ export function useCanvasDrawing({
);
}
}
+ let exitSpeed = 0;
+ if (recentPointsTrailRef.current.length >= 2) {
+ const trail = recentPointsTrailRef.current;
+ const pA = trail[0];
+ 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);
+ exitSpeed = dist / dt;
+ }
+
+ const shouldTaperOut = (bs.usePressure && e.pointerType === 'pen') || exitSpeed > 0.5 || Boolean(bs.taper?.useOut) || Boolean(bs.velocityDynamics);
+ if (shouldTaperOut && allStrokePointsRef.current.length >= 3) {
+ applyParametricTaper(allStrokePointsRef.current, {
+ useIn: Boolean(bs.taper?.useIn),
+ useOut: true,
+ minSizeFactor: bs.minSizeFactor,
+ exitSpeed,
+ });
+ }
+
const allPoints = allStrokePointsRef.current;
+ let createdVectorStroke: VectorStroke | undefined;
+
+ if (activeLayer?.type === 'vector' && canvas && allPoints.length > 0) {
+ const knots: VectorKnot[] = allPoints.map((pt, idx) => ({
+ x: pt.x,
+ y: pt.y,
+ pressure: pt.pressure,
+ width: pt.width || Math.max(0.5, (bs.size || 10) * pt.pressure),
+ timestamp: Date.now() + idx,
+ }));
+ const prevStrokes = [...(activeLayer.vectorStrokes || [])];
+
+ if (isEraser) {
+ const eraserRadius = Math.max(1, (bs.size || 10) * 0.5);
+ const eraserPath = allPoints.map((p) => ({ x: p.x, y: p.y }));
+ const eraserResult = applyVectorEraser(eraserPath, eraserRadius, prevStrokes, 'intersection');
+ const updatedStrokes = eraserResult.updatedStrokes;
+ activeLayer.vectorStrokes = updatedStrokes;
+
+ const ctx = get2DContext(canvas);
+ if (ctx) {
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ renderVectorLayer(ctx, updatedStrokes);
+ const fullData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ globalTileGrid.writeImageData(
+ currentLayerId,
+ fullData,
+ 0,
+ 0,
+ isMonochrome ? 'monochrome-1bit' : 'color-32bit'
+ );
+ }
- if (canvas && dirty && allPoints.length > 0) {
+ pushHistoryStep(
+ 'eraser',
+ 'Vector Eraser',
+ null,
+ null,
+ currentLayerId,
+ { x: 0, y: 0, width: canvas.width, height: canvas.height },
+ undefined,
+ { before: prevStrokes, after: updatedStrokes },
+ undefined,
+ currentStrokeIdRef.current || undefined
+ );
+ } else {
+ const simplifiedKnots = simplifyPathPoints(knots, 0.5);
+ const strokeKnots = simplifiedKnots.length >= 2 ? simplifiedKnots : knots;
+ const bounds = computeStrokeBounds(strokeKnots);
+ const newStroke: VectorStroke = {
+ id: currentStrokeIdRef.current || `vec-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`,
+ layerId: currentLayerId,
+ tool: isPencil ? 'pencil' : 'brush',
+ knots: strokeKnots,
+ color: strokeColor,
+ baseWidth: bs.size || 10,
+ opacity: bs.opacity ?? 1.0,
+ bounds,
+ };
+ createdVectorStroke = newStroke;
+
+ const updatedStrokes = [...prevStrokes, newStroke];
+ activeLayer.vectorStrokes = updatedStrokes;
+
+ const ctx = get2DContext(canvas);
+ if (ctx) {
+ renderVectorStroke(ctx, newStroke);
+ const fullData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ globalTileGrid.writeImageData(
+ currentLayerId,
+ fullData,
+ 0,
+ 0,
+ isMonochrome ? 'monochrome-1bit' : 'color-32bit'
+ );
+ }
+
+ pushHistoryStep(
+ isPencil ? 'pencil' : 'brush',
+ bs.brushName || (isPencil ? 'Vector Pencil' : 'Vector Pen'),
+ null,
+ null,
+ currentLayerId,
+ { x: 0, y: 0, width: canvas.width, height: canvas.height },
+ undefined,
+ { before: prevStrokes, after: updatedStrokes },
+ undefined,
+ currentStrokeIdRef.current || undefined
+ );
+ }
+ } else if (canvas && dirty && allPoints.length > 0) {
const pad = Math.ceil(Math.max(32, (bs.size || 10) * 1.5));
const sx = Math.max(0, Math.floor(dirty.minX - pad));
const sy = Math.max(0, Math.floor(dirty.minY - pad));
@@ -1736,14 +2200,7 @@ export function useCanvasDrawing({
let beforeData: ImageData | null = null;
let afterData: ImageData | null = null;
- if (isToneLayer && strokeBackupCanvasRef.current && sourceCanvas) {
- const bCtx = get2DContext(strokeBackupCanvasRef.current);
- beforeData = bCtx ? bCtx.getImageData(sx, sy, dw, dh) : null;
- const sCtx = get2DContext(sourceCanvas);
- afterData = sCtx ? sCtx.getImageData(sx, sy, dw, dh) : null;
- } else if (drewDirectlyOnLayerCanvasRef.current && strokeBackupCanvasRef.current) {
- // Direct render: stroke is ALREADY drawn on canvas with real-time binarization/effects!
- // Zero re-rendering, zero delay, zero lag, zero flicker!
+ if (isEraser && strokeBackupCanvasRef.current) {
const bCtx = get2DContext(strokeBackupCanvasRef.current);
beforeData = bCtx ? bCtx.getImageData(sx, sy, dw, dh) : null;
afterData = ctx.getImageData(sx, sy, dw, dh);
@@ -1759,8 +2216,49 @@ export function useCanvasDrawing({
}
}
}
+ } else if (isToneLayer && sourceCanvas) {
+ const bCtx = strokeBackupCanvasRef.current ? get2DContext(strokeBackupCanvasRef.current) : null;
+ beforeData = bCtx ? bCtx.getImageData(sx, sy, dw, dh) : null;
+
+ const bakeCanvas = getReusableBakeCanvas(dw, dh);
+ const bCtxBake = bakeCanvas.getContext('2d', { alpha: true });
+ if (bCtxBake) {
+ bCtxBake.clearRect(0, 0, bakeCanvas.width, bakeCanvas.height);
+ bCtxBake.save();
+ bCtxBake.translate(-sx, -sy);
+ renderCompleteStroke(bCtxBake, allPoints, bs, currentTool, mode, isBgEraser, sourceCanvas, Boolean(activeLayer?.alphaLocked));
+ bCtxBake.restore();
+
+ const sCtx = get2DContext(sourceCanvas);
+ 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';
+ }
+ sCtx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
+ sCtx.restore();
+ afterData = sCtx.getImageData(sx, sy, dw, dh);
+ }
+ }
+ if (activeLayer) {
+ applyLayerEffects(
+ sourceCanvas,
+ canvas,
+ activeLayer,
+ dimensionsRef.current.dpi ?? 600,
+ { x: sx, y: sy, width: dw, height: dh }
+ );
+ }
} else {
- // Translucent brushes drawn onto draft canvas overlay:
+ // Translucent and opaque brushes / pencils drawn onto draft canvas overlay:
beforeData = ctx.getImageData(sx, sy, dw, dh);
ctx.save();
@@ -1774,21 +2272,53 @@ export function useCanvasDrawing({
bCtx.clearRect(0, 0, bakeCanvas.width, bakeCanvas.height);
bCtx.save();
bCtx.translate(-sx, -sy);
- renderCompleteStroke(bCtx, allPoints, bs, currentTool, mode, isBgEraser);
+ renderCompleteStroke(bCtx, allPoints, bs, currentTool, mode, isBgEraser, canvas, Boolean(activeLayer?.alphaLocked));
bCtx.restore();
ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
- ctx.globalCompositeOperation = 'source-over';
+ if (bs.isTransparentInk) {
+ ctx.globalCompositeOperation = 'destination-out';
+ } else if (activeLayer?.alphaLocked) {
+ ctx.globalCompositeOperation = 'source-atop';
+ } else {
+ ctx.globalCompositeOperation = 'source-over';
+ }
ctx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
}
+ if (isMonochrome) {
+ binarizeCanvasRect(
+ ctx,
+ { x: sx, y: sy, width: dw, height: dh },
+ activeLayer?.monoThreshold ?? 128,
+ activeLayer?.monoExpressBlack ?? true,
+ activeLayer?.monoExpressWhite ?? true
+ );
+ }
+
ctx.restore();
afterData = ctx.getImageData(sx, sy, dw, dh);
+
+ 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 targetFormat = isMonochrome ? 'monochrome-1bit' : 'color-32bit';
+ const dirtyRect = { x: sx, y: sy, width: dw, height: dh };
+
let label = 'Brush Stroke';
- if (currentTool === 'eraser') {
+ if (bs.isTransparentInk) {
+ label = 'Transparent Ink';
+ } else if (currentTool === 'eraser') {
label = 'Eraser';
} else if (bs.brushName) {
label = bs.brushName;
@@ -1800,12 +2330,6 @@ export function useCanvasDrawing({
label = 'Pencil (4B)';
} else if (bs.preset === 'pencil-hb') {
label = 'Pencil (HB)';
- } else if (bs.preset === 'oil-thick') {
- label = 'Thick Oil Paint';
- } else if (bs.preset === 'oil-glaze') {
- label = 'Oil Glaze Brush';
- } else if (bs.preset === 'blend-smudge') {
- label = 'Smudge & Blender';
} else {
label = isMonochrome ? 'Monochrome Pen' : 'Round Brush';
}
@@ -1817,13 +2341,18 @@ export function useCanvasDrawing({
beforeData,
afterData,
currentLayerId,
- { x: sx, y: sy, width: dw, height: dh }
+ dirtyRect
);
+ } else if (afterData) {
+ globalTileGrid.writeImageData(currentLayerId, afterData, dirtyRect.x, dirtyRect.y, targetFormat);
}
}
}
}
+ // Synchronously notify tile grid compositor BEFORE clearing draft canvas to guarantee zero flicker
+ globalTileGrid.notifyChange(true);
+
// Synchronously clear draftCanvas immediately in the exact same render turn to guarantee zero flicker
if (clearDraftRafRef.current !== null) {
cancelAnimationFrame(clearDraftRafRef.current);
@@ -1850,7 +2379,8 @@ export function useCanvasDrawing({
y: Math.max(0, Math.floor(dirty.minY)),
width: Math.max(1, Math.ceil(dirty.maxX) - Math.max(0, Math.floor(dirty.minX))),
height: Math.max(1, Math.ceil(dirty.maxY) - Math.max(0, Math.floor(dirty.minY))),
- } : undefined
+ } : undefined,
+ createdVectorStroke
);
currentStrokeIdRef.current = null;
}
@@ -1982,6 +2512,7 @@ export function useCanvasDrawing({
jumpToHistoryIndex,
clearCanvas,
resetHistory,
+ selectiveUndo,
cursorPos: null as { x: number; y: number } | null,
currentPressure: 0,
isHovering: false,
diff --git a/src/hooks/useLayerManager.ts b/src/hooks/useLayerManager.ts
index c96a205..a7d01e3 100644
--- a/src/hooks/useLayerManager.ts
+++ b/src/hooks/useLayerManager.ts
@@ -4,6 +4,7 @@ import { ResizeCanvasOptions } from '../types/settings';
import { createCanvasThumbnail, get2DContext } from '../utils/canvasUtils';
import { applyLayerEffects, applyExpressionColorToImageData } from '../utils/layerEffectsEngine';
import { HalftoneDotShape } from '../utils/screentoneEngine';
+import { globalTileGrid } from '../utils/tileEngine';
interface UseLayerManagerProps {
dimensions: CanvasDimensions;
@@ -48,6 +49,8 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
// Default initial layers: starts empty until a document is created or opened
const [layers, setLayers] = useState<LayerItem[]>([]);
const [activeLayerId, setActiveLayerId] = useState<string>('');
+ const layersRef = useRef(layers);
+ layersRef.current = layers;
// Register or unregister canvas element for a layer
const registerLayerCanvas = useCallback((id: string, canvas: HTMLCanvasElement | null) => {
@@ -97,6 +100,13 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
}
}
+ // Ingest into globalTileGrid if unindexed
+ if (!globalTileGrid.hasTile(id, 0, 0) && globalTileGrid.getLayerTiles(id).length === 0) {
+ const layer = layersRef.current.find((l) => l.id === id);
+ const isMono = layer?.expressionColor === 'monochrome';
+ globalTileGrid.ingestCanvas(id, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ }
+
// Defer initial thumbnail generation to avoid triggering re-render during ref attachment
requestAnimationFrame(() => {
const c = layerCanvasesRef.current.get(id);
@@ -109,9 +119,31 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
});
} else {
layerCanvasesRef.current.delete(id);
+ globalTileGrid.clearLayer(id);
}
}, []);
+ // Automatically instantiate and manage offscreen backing canvases for all layers
+ useEffect(() => {
+ layers.forEach((layer) => {
+ if ((layer.type === 'raster' || layer.type === 'vector' || layer.type === 'frame') && !layerCanvasesRef.current.has(layer.id)) {
+ const offscreen = document.createElement('canvas');
+ offscreen.width = _dimensions.width;
+ offscreen.height = _dimensions.height;
+ registerLayerCanvas(layer.id, offscreen);
+ }
+ });
+
+ // When a layer is removed, delete its canvas from layerCanvasesRef.current
+ const currentLayerIds = new Set(layers.map((l) => l.id));
+ for (const id of Array.from(layerCanvasesRef.current.keys())) {
+ if (!currentLayerIds.has(id)) {
+ layerCanvasesRef.current.delete(id);
+ globalTileGrid.clearLayer(id);
+ }
+ }
+ }, [layers, _dimensions, registerLayerCanvas]);
+
const thumbDebounceTimersRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map());
// Update a single layer's thumbnail after drawing or editing (debounced to avoid React re-renders during rapid sketching)
@@ -144,7 +176,7 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
// Add a new raster layer or folder
const addLayer = useCallback(
(
- type: 'raster' | 'folder' = 'raster',
+ type: 'raster' | 'folder' | 'vector' | 'frame' = 'raster',
explicitParentId?: string | null,
customName?: string,
customId?: string
@@ -171,7 +203,10 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
let name = customName;
if (!name) {
let count = 1;
- const prefix = type === 'folder' ? 'Folder ' : 'Layer ';
+ const prefix =
+ type === 'folder' ? 'Folder ' :
+ type === 'vector' ? 'Vector ' :
+ type === 'frame' ? 'Frame ' : 'Layer ';
prev.forEach((l) => {
if (l.type === type && l.name.startsWith(prefix)) {
const num = parseInt(l.name.replace(prefix, ''), 10);
@@ -436,6 +471,24 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
);
}, []);
+ // Toggle clipping mask state (Clip to Layer Below)
+ const toggleClipping = useCallback((id: string) => {
+ setLayers((prev) => {
+ const idx = prev.findIndex((l) => l.id === id);
+ if (idx === -1 || idx === prev.length - 1 || id === 'layer-bg') {
+ return prev;
+ }
+ return prev.map((l) => (l.id === id ? { ...l, clipped: !l.clipped } : l));
+ });
+ }, []);
+
+ // Toggle alpha locked state (Lock Transparent Pixels)
+ const toggleAlphaLock = useCallback((id: string) => {
+ setLayers((prev) =>
+ prev.map((l) => (l.id === id ? { ...l, alphaLocked: !l.alphaLocked } : l))
+ );
+ }, []);
+
// Ensure offscreen source canvas exists for non-destructive operations
const ensureSourceCanvas = useCallback(
(id: string, copyFromDisplay = true, forceCopy = false) => {
@@ -950,26 +1003,55 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
const draggedItem = { ...prev[draggedIdx] };
const targetItem = prev[targetIdx];
+ // Prevent dropping a folder into itself or its descendants
+ if (draggedItem.type === 'folder') {
+ let curr: LayerItem | undefined = targetItem;
+ while (curr) {
+ if (curr.id === draggedId) return prev;
+ curr = prev.find((l) => l.id === curr?.parentId);
+ }
+ }
+
+ // Collect all descendant IDs of the dragged item
+ const getDescendantIds = (parentId: string): string[] => {
+ const ids: string[] = [];
+ for (const item of prev) {
+ if (item.parentId === parentId) {
+ ids.push(item.id);
+ ids.push(...getDescendantIds(item.id));
+ }
+ }
+ return ids;
+ };
+
+ const movingIds = new Set([draggedId, ...getDescendantIds(draggedId)]);
+
if (position === 'inside' && targetItem.type === 'folder') {
draggedItem.parentId = targetItem.id;
} else {
draggedItem.parentId = targetItem.parentId;
}
- const next = [...prev];
- next.splice(draggedIdx, 1);
+ // Extract moving items preserving their relative order
+ const movingItems = prev
+ .filter((l) => movingIds.has(l.id))
+ .map((l) => (l.id === draggedId ? draggedItem : l));
- const newTargetIdx = next.findIndex((l) => l.id === targetId);
- let insertIdx = newTargetIdx;
+ // Remaining items without the moving items
+ const remaining = prev.filter((l) => !movingIds.has(l.id));
+
+ const newTargetIdx = remaining.findIndex((l) => l.id === targetId);
+ if (newTargetIdx < 0) return prev;
+ let insertIdx = newTargetIdx;
if (position === 'above') {
insertIdx = newTargetIdx;
} else if (position === 'below' || position === 'inside') {
insertIdx = newTargetIdx + 1;
}
- next.splice(insertIdx, 0, draggedItem);
- return next;
+ remaining.splice(insertIdx, 0, ...movingItems);
+ return remaining;
});
}, []);
@@ -1117,7 +1199,7 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
// Internal Layer Clipboard
const layerClipboardRef = useRef<{
name: string;
- type: 'raster' | 'folder';
+ type: LayerItem['type'];
blendMode: BlendMode;
opacity: number;
canvas: HTMLCanvasElement;
@@ -1606,6 +1688,8 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
setOpacity,
setBlendMode,
toggleLock,
+ toggleAlphaLock,
+ toggleClipping,
toggleCollapse,
renameLayer,
moveLayer,
diff --git a/src/hooks/useMultiplayer.ts b/src/hooks/useMultiplayer.ts
index fbab457..83feed9 100644
--- a/src/hooks/useMultiplayer.ts
+++ b/src/hooks/useMultiplayer.ts
@@ -8,9 +8,12 @@ import {
StrokeFinishMessage,
CursorMoveMessage,
JoinAcceptedMessage,
+ TileStreamMessage,
+ SelectiveUndoMessage,
} from '../types/multiplayer';
import { multiplayerService } from '../services/multiplayerService';
import { LayerItem, CanvasDimensions, CanvasColorMode } from '../types/editor';
+import { globalTileGrid, TILE_SIZE, TileBuffer } from '../utils/tileEngine';
const PEER_COLORS = [
'#f43f5e', // Rose
@@ -44,6 +47,7 @@ export interface UseMultiplayerProps {
onRemoteDocSync?: (dimensions: CanvasDimensions, colorMode: CanvasColorMode, layers: LayerItem[], dataUrls: Record<string, string>) => void;
onRemoteJoinRequest?: (peer: CollabPeer) => { assignedLayerId: string; updatedLayers: LayerItem[] } | void;
onRemoteAssignedLayer?: (layerId: string) => void;
+ onRemoteSelectiveUndo?: (strokeId: string, peerId: string | number) => void;
showToast: (msg: string) => void;
}
@@ -59,6 +63,7 @@ export function useMultiplayer({
onRemoteDocSync,
onRemoteJoinRequest,
onRemoteAssignedLayer,
+ onRemoteSelectiveUndo,
showToast,
}: UseMultiplayerProps) {
const [isConnected, setIsConnected] = useState(false);
@@ -120,6 +125,7 @@ export function useMultiplayer({
const onRemoteDocSyncRef = useRef(onRemoteDocSync);
const onRemoteJoinRequestRef = useRef(onRemoteJoinRequest);
const onRemoteAssignedLayerRef = useRef(onRemoteAssignedLayer);
+ const onRemoteSelectiveUndoRef = useRef(onRemoteSelectiveUndo);
const showToastRef = useRef(showToast);
onRemoteStrokeStartRef.current = onRemoteStrokeStart;
@@ -129,6 +135,7 @@ export function useMultiplayer({
onRemoteDocSyncRef.current = onRemoteDocSync;
onRemoteJoinRequestRef.current = onRemoteJoinRequest;
onRemoteAssignedLayerRef.current = onRemoteAssignedLayer;
+ onRemoteSelectiveUndoRef.current = onRemoteSelectiveUndo;
showToastRef.current = showToast;
// Handle incoming messages
@@ -167,16 +174,6 @@ export function useMultiplayer({
}
}
- // Snapshot all canvases for initial synchronization
- const layerDataUrls: Record<string, string> = {};
- layerCanvasesRef.current.forEach((canvas, id) => {
- try {
- layerDataUrls[id] = canvas.toDataURL('image/png');
- } catch (e) {
- console.warn('Failed to snapshot canvas for layer', id, e);
- }
- });
-
// Send JOIN_ACCEPTED to the joining guest
const joinAcceptedMsg: JoinAcceptedMessage = {
type: 'JOIN_ACCEPTED',
@@ -197,9 +194,17 @@ export function useMultiplayer({
dimensions: dimensionsRef.current,
colorMode: colorModeRef.current,
layers: effectiveLayers,
- layerDataUrls,
+ 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);
+ }
+ }
+
// Broadcast PEER_JOINED to other already connected peers
multiplayerService.sendMessage({
type: 'PEER_JOINED',
@@ -358,6 +363,36 @@ export function useMultiplayer({
}, 2400);
break;
}
+
+ case 'BINARY_TILE': {
+ const tMsg = msg as TileStreamMessage;
+ const tile: TileBuffer = {
+ layerId: tMsg.layerId,
+ tileX: tMsg.tileX,
+ tileY: tMsg.tileY,
+ format: tMsg.format,
+ version: tMsg.version,
+ data: tMsg.data,
+ dirty: true,
+ };
+ globalTileGrid.setTile(tMsg.layerId, tMsg.tileX, tMsg.tileY, tile);
+ const canvas = layerCanvasesRef.current.get(tMsg.layerId);
+ if (canvas) {
+ globalTileGrid.renderLayerToCanvas(tMsg.layerId, canvas, {
+ x: tMsg.tileX * TILE_SIZE,
+ y: tMsg.tileY * TILE_SIZE,
+ width: TILE_SIZE,
+ height: TILE_SIZE,
+ });
+ }
+ break;
+ }
+
+ case 'SELECTIVE_UNDO': {
+ const uMsg = msg as SelectiveUndoMessage;
+ onRemoteSelectiveUndoRef.current?.(uMsg.strokeId, uMsg.peerId);
+ break;
+ }
}
});
diff --git a/src/index.css b/src/index.css
index 9da7116..559fad7 100644
--- a/src/index.css
+++ b/src/index.css
@@ -313,3 +313,460 @@ input[type="range"]:active::-moz-range-thumb {
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 - Default Slate */
+ --modern-bg-base: #0c0d12;
+ --modern-bg-surface: #13141b;
+ --modern-bg-elevated: #1a1b24;
+ --modern-bg-input: #111217;
+ --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: #0c0d12;
+ --modern-bg-surface: #13141b;
+ --modern-bg-elevated: #1a1b24;
+ --modern-bg-input: #111217;
+ --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: #111215;
+ --modern-bg-surface: #18191d;
+ --modern-bg-elevated: #212228;
+ --modern-bg-input: #141518;
+ --modern-border: rgba(255, 255, 255, 0.07);
+ --modern-border-subtle: rgba(255, 255, 255, 0.035);
+}
+
+[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);
+ 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;
+}
+
+[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;
+}
+
+[data-theme="modern"] ::-webkit-scrollbar-track {
+ background: transparent;
+}
+
+[data-theme="modern"] ::-webkit-scrollbar-thumb {
+ background: rgba(255, 255, 255, 0.14);
+ border-radius: 9999px;
+ border: 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;
+}
+
+
+
diff --git a/src/services/multiplayerService.ts b/src/services/multiplayerService.ts
index 604cbca..4cb6316 100644
--- a/src/services/multiplayerService.ts
+++ b/src/services/multiplayerService.ts
@@ -7,11 +7,25 @@ import {
CursorMoveMessage,
LayerActionMessage,
CanvasPingMessage,
+ TileStreamMessage,
+ SelectiveUndoMessage,
} from '../types/multiplayer';
-import { Point, BrushSettings, ToolType, DirtyRect, LayerItem } from '../types/editor';
+import { Point, BrushSettings, ToolType, DirtyRect, LayerItem, VectorStroke } from '../types/editor';
+import { TileBuffer, serializeTileBuffer, deserializeTileBuffer } from '../utils/tileEngine';
type MessageHandler = (msg: MultiplayerMessage) => void;
+// Binary Message Codes
+export const BINARY_MAGIC_0 = 0x49; // 'I'
+export const BINARY_MAGIC_1 = 0x4e; // 'N'
+
+export const CODE_STROKE_START = 0x01;
+export const CODE_STROKE_CHUNK = 0x02;
+export const CODE_STROKE_FINISH = 0x03;
+export const CODE_TILE_DELTA = 0x04;
+export const CODE_CURSOR_MOVE = 0x05;
+export const CODE_SELECTIVE_UNDO = 0x06;
+
class MultiplayerService {
private ws: WebSocket | null = null;
private messageHandlers: Set<MessageHandler> = new Set();
@@ -19,11 +33,22 @@ class MultiplayerService {
private errorHandlers: Set<(err: Event) => void> = new Set();
private currentPeer: CollabPeer | null = null;
+ // Lamport Logical Clock for Vector CRDT and deterministic ordering
+ private lamportClock = 0;
+
// Throttling for cursor movement (max 60fps)
private lastCursorSendTime = 0;
private pendingCursor: { x: number; y: number; isDrawing: boolean; tool: ToolType } | null = null;
private cursorThrottleRaf: number | null = null;
+ public getNextLamport(): number {
+ return ++this.lamportClock;
+ }
+
+ public updateLamport(remoteLamport: number): void {
+ this.lamportClock = Math.max(this.lamportClock, remoteLamport) + 1;
+ }
+
public isConnected(): boolean {
return this.ws !== null && this.ws.readyState === WebSocket.OPEN;
}
@@ -39,6 +64,7 @@ class MultiplayerService {
try {
const ws = new WebSocket(url);
+ ws.binaryType = 'arraybuffer';
this.ws = ws;
ws.onopen = () => {
@@ -50,12 +76,25 @@ class MultiplayerService {
resolve();
};
- ws.onmessage = (event) => {
+ ws.onmessage = async (event) => {
try {
- const data: MultiplayerMessage = JSON.parse(event.data);
- this.notifyHandlers(data);
+ if (event.data instanceof ArrayBuffer) {
+ const parsed = this.decodeBinaryPacket(event.data);
+ if (parsed) {
+ this.notifyHandlers(parsed);
+ }
+ } else if (event.data instanceof Blob) {
+ const buf = await event.data.arrayBuffer();
+ const parsed = this.decodeBinaryPacket(buf);
+ if (parsed) {
+ this.notifyHandlers(parsed);
+ }
+ } else {
+ const data: MultiplayerMessage = JSON.parse(event.data);
+ this.notifyHandlers(data);
+ }
} catch (err) {
- console.error('[Multiplayer] Failed to parse message JSON:', err, event.data);
+ console.error('[Multiplayer] Failed to parse message:', err, event.data);
}
};
@@ -116,11 +155,165 @@ class MultiplayerService {
}
}
+ public sendBinary(buffer: ArrayBuffer | Uint8Array) {
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
+ this.ws.send(buffer as any);
+ }
+ }
+
private notifyHandlers(msg: MultiplayerMessage) {
this.messageHandlers.forEach((handler) => handler(msg));
}
- // --- Drawing Events ---
+ // --- Binary Packet Encoding & Decoding ---
+
+ private decodeBinaryPacket(buf: ArrayBuffer): MultiplayerMessage | null {
+ if (buf.byteLength < 11) return null;
+ const view = new DataView(buf);
+
+ // Verify magic
+ if (view.getUint8(0) !== BINARY_MAGIC_0 || view.getUint8(1) !== BINARY_MAGIC_1) {
+ return null;
+ }
+
+ const code = view.getUint8(2);
+ const lamport = view.getUint32(3, true);
+ this.updateLamport(lamport);
+
+ const payloadLen = view.getUint32(7, true);
+ const payloadBytes = new Uint8Array(buf, 11, payloadLen);
+ const decoder = new TextDecoder();
+
+ switch (code) {
+ case CODE_STROKE_START: {
+ const jsonStr = decoder.decode(payloadBytes);
+ const data = JSON.parse(jsonStr);
+ return {
+ type: 'STROKE_START',
+ strokeId: data.strokeId,
+ peerId: data.peerId,
+ peerName: data.peerName,
+ peerColor: data.peerColor,
+ layerId: data.layerId,
+ brushSettings: data.brushSettings,
+ tool: data.tool,
+ startPoint: data.startPoint,
+ } as StrokeStartMessage;
+ }
+
+ case CODE_STROKE_CHUNK: {
+ // Format: [strokeIdLen: uint16, strokeIdStr, peerIdLen: uint16, peerIdStr, pointCount: uint16, points...]
+ let offset = 0;
+ const pView = new DataView(payloadBytes.buffer, payloadBytes.byteOffset, payloadBytes.byteLength);
+
+ const sIdLen = pView.getUint16(offset, true);
+ offset += 2;
+ const strokeId = decoder.decode(payloadBytes.subarray(offset, offset + sIdLen));
+ offset += sIdLen;
+
+ const pIdLen = pView.getUint16(offset, true);
+ offset += 2;
+ const peerId = decoder.decode(payloadBytes.subarray(offset, offset + pIdLen));
+ offset += pIdLen;
+
+ const pointCount = pView.getUint16(offset, true);
+ offset += 2;
+
+ const points: Point[] = [];
+ for (let i = 0; i < pointCount; i++) {
+ const x = pView.getFloat32(offset, true);
+ const y = pView.getFloat32(offset + 4, true);
+ const pressure = pView.getFloat32(offset + 8, true);
+ const width = pView.getFloat32(offset + 12, true);
+ offset += 16;
+ points.push({ x, y, pressure, width });
+ }
+
+ return {
+ type: 'STROKE_CHUNK',
+ strokeId,
+ peerId,
+ points,
+ } as StrokeChunkMessage;
+ }
+
+ case CODE_STROKE_FINISH: {
+ const jsonStr = decoder.decode(payloadBytes);
+ const data = JSON.parse(jsonStr);
+ return {
+ type: 'STROKE_FINISH',
+ strokeId: data.strokeId,
+ peerId: data.peerId,
+ layerId: data.layerId,
+ endPoint: data.endPoint,
+ dirtyRect: data.dirtyRect,
+ } as StrokeFinishMessage;
+ }
+
+ case CODE_TILE_DELTA: {
+ // Format: [layerIdLen: uint16, layerIdStr, serializedTileBuffer...]
+ let offset = 0;
+ const pView = new DataView(payloadBytes.buffer, payloadBytes.byteOffset, payloadBytes.byteLength);
+ const layerIdLen = pView.getUint16(offset, true);
+ offset += 2;
+ const layerId = decoder.decode(payloadBytes.subarray(offset, offset + layerIdLen));
+ offset += layerIdLen;
+
+ const tilePacket = payloadBytes.subarray(offset);
+ const tile = deserializeTileBuffer(layerId, tilePacket);
+
+ return {
+ type: 'BINARY_TILE',
+ layerId,
+ tileX: tile.tileX,
+ tileY: tile.tileY,
+ format: tile.format,
+ version: tile.version,
+ data: tile.data,
+ } as TileStreamMessage;
+ }
+
+ case CODE_CURSOR_MOVE: {
+ const pView = new DataView(payloadBytes.buffer, payloadBytes.byteOffset, payloadBytes.byteLength);
+ let offset = 0;
+ const pIdLen = pView.getUint16(offset, true);
+ offset += 2;
+ const peerId = decoder.decode(payloadBytes.subarray(offset, offset + pIdLen));
+ offset += pIdLen;
+
+ const x = pView.getFloat32(offset, true);
+ const y = pView.getFloat32(offset + 4, true);
+ const isDrawing = pView.getUint8(offset + 8) === 1;
+ const toolCode = pView.getUint8(offset + 9);
+ const tool: ToolType = toolCode === 1 ? 'eraser' : 'brush';
+
+ return {
+ type: 'CURSOR_MOVE',
+ peerId,
+ x,
+ y,
+ isDrawing,
+ tool,
+ } as CursorMoveMessage;
+ }
+
+ case CODE_SELECTIVE_UNDO: {
+ const jsonStr = decoder.decode(payloadBytes);
+ const data = JSON.parse(jsonStr);
+ return {
+ type: 'SELECTIVE_UNDO',
+ strokeId: data.strokeId,
+ peerId: data.peerId,
+ lamport: data.lamport,
+ } as SelectiveUndoMessage;
+ }
+
+ default:
+ return null;
+ }
+ }
+
+ // --- Drawing Events via Compact Binary Packets ---
public sendStrokeStart(
strokeId: string,
@@ -131,8 +324,8 @@ class MultiplayerService {
) {
if (!this.isConnected() || !this.currentPeer) return;
- const msg: StrokeStartMessage = {
- type: 'STROKE_START',
+ const encoder = new TextEncoder();
+ const payloadStr = JSON.stringify({
strokeId,
peerId: this.currentPeer.id,
peerName: this.currentPeer.name,
@@ -141,34 +334,151 @@ class MultiplayerService {
brushSettings,
tool,
startPoint,
- };
- this.sendMessage(msg);
+ });
+ const payloadBytes = encoder.encode(payloadStr);
+
+ const header = new Uint8Array(11 + payloadBytes.length);
+ const view = new DataView(header.buffer);
+ view.setUint8(0, BINARY_MAGIC_0);
+ view.setUint8(1, BINARY_MAGIC_1);
+ view.setUint8(2, CODE_STROKE_START);
+ view.setUint32(3, this.getNextLamport(), true);
+ view.setUint32(7, payloadBytes.length, true);
+ header.set(payloadBytes, 11);
+
+ this.sendBinary(header);
}
public sendStrokeChunk(strokeId: string, points: Point[]) {
if (!this.isConnected() || !this.currentPeer || points.length === 0) return;
- const msg: StrokeChunkMessage = {
- type: 'STROKE_CHUNK',
- strokeId,
- peerId: this.currentPeer.id,
- points,
- };
- this.sendMessage(msg);
+ const encoder = new TextEncoder();
+ const strokeIdBytes = encoder.encode(strokeId);
+ const peerIdBytes = encoder.encode(String(this.currentPeer.id));
+
+ // Size: 2 + strokeIdBytes.length + 2 + peerIdBytes.length + 2 + (points.length * 16)
+ const payloadSize = 6 + strokeIdBytes.length + peerIdBytes.length + points.length * 16;
+ const packet = new Uint8Array(11 + payloadSize);
+ const view = new DataView(packet.buffer);
+
+ view.setUint8(0, BINARY_MAGIC_0);
+ view.setUint8(1, BINARY_MAGIC_1);
+ view.setUint8(2, CODE_STROKE_CHUNK);
+ view.setUint32(3, this.getNextLamport(), true);
+ view.setUint32(7, payloadSize, true);
+
+ let offset = 11;
+ view.setUint16(offset, strokeIdBytes.length, true);
+ offset += 2;
+ packet.set(strokeIdBytes, offset);
+ offset += strokeIdBytes.length;
+
+ view.setUint16(offset, peerIdBytes.length, true);
+ offset += 2;
+ packet.set(peerIdBytes, offset);
+ offset += peerIdBytes.length;
+
+ view.setUint16(offset, points.length, true);
+ offset += 2;
+
+ for (let i = 0; i < points.length; i++) {
+ const pt = points[i];
+ view.setFloat32(offset, pt.x, true);
+ view.setFloat32(offset + 4, pt.y, true);
+ view.setFloat32(offset + 8, pt.pressure, true);
+ view.setFloat32(offset + 12, pt.width, true);
+ offset += 16;
+ }
+
+ this.sendBinary(packet);
}
- public sendStrokeFinish(strokeId: string, layerId: string, endPoint: Point, dirtyRect?: DirtyRect) {
+ public sendStrokeFinish(
+ strokeId: string,
+ layerId: string,
+ endPoint: Point,
+ dirtyRect?: DirtyRect,
+ vectorStroke?: VectorStroke
+ ) {
if (!this.isConnected() || !this.currentPeer) return;
- const msg: StrokeFinishMessage = {
- type: 'STROKE_FINISH',
+ const encoder = new TextEncoder();
+ const payloadStr = JSON.stringify({
strokeId,
peerId: this.currentPeer.id,
layerId,
endPoint,
dirtyRect,
- };
- this.sendMessage(msg);
+ vectorStroke,
+ });
+ const payloadBytes = encoder.encode(payloadStr);
+
+ const header = new Uint8Array(11 + payloadBytes.length);
+ const view = new DataView(header.buffer);
+ view.setUint8(0, BINARY_MAGIC_0);
+ view.setUint8(1, BINARY_MAGIC_1);
+ view.setUint8(2, CODE_STROKE_FINISH);
+ view.setUint32(3, this.getNextLamport(), true);
+ view.setUint32(7, payloadBytes.length, true);
+ header.set(payloadBytes, 11);
+
+ this.sendBinary(header);
+ }
+
+ /**
+ * Stream a single sparse tile delta (e.g. from flood fill or progressive document sync).
+ */
+ public sendTileDelta(layerId: string, tile: TileBuffer) {
+ if (!this.isConnected()) return;
+
+ const encoder = new TextEncoder();
+ const layerIdBytes = encoder.encode(layerId);
+ const tileBytes = serializeTileBuffer(tile);
+
+ const payloadSize = 2 + layerIdBytes.length + tileBytes.length;
+ const packet = new Uint8Array(11 + payloadSize);
+ const view = new DataView(packet.buffer);
+
+ view.setUint8(0, BINARY_MAGIC_0);
+ view.setUint8(1, BINARY_MAGIC_1);
+ view.setUint8(2, CODE_TILE_DELTA);
+ view.setUint32(3, this.getNextLamport(), true);
+ view.setUint32(7, payloadSize, true);
+
+ let offset = 11;
+ view.setUint16(offset, layerIdBytes.length, true);
+ offset += 2;
+ packet.set(layerIdBytes, offset);
+ offset += layerIdBytes.length;
+
+ packet.set(tileBytes, offset);
+ this.sendBinary(packet);
+ }
+
+ /**
+ * Broadcast a selective collaborative undo command (undoing a stroke without reverting peer strokes).
+ */
+ public sendSelectiveUndo(strokeId: string) {
+ if (!this.isConnected() || !this.currentPeer) return;
+
+ const encoder = new TextEncoder();
+ const payloadStr = JSON.stringify({
+ strokeId,
+ peerId: this.currentPeer.id,
+ lamport: this.getNextLamport(),
+ });
+ const payloadBytes = encoder.encode(payloadStr);
+
+ const packet = new Uint8Array(11 + payloadBytes.length);
+ const view = new DataView(packet.buffer);
+ view.setUint8(0, BINARY_MAGIC_0);
+ view.setUint8(1, BINARY_MAGIC_1);
+ view.setUint8(2, CODE_SELECTIVE_UNDO);
+ view.setUint32(3, this.lamportClock, true);
+ view.setUint32(7, payloadBytes.length, true);
+ packet.set(payloadBytes, 11);
+
+ this.sendBinary(packet);
}
// --- Real-time Cursor Throttling (30-60 Hz) ---
@@ -193,17 +503,31 @@ class MultiplayerService {
if (!this.pendingCursor || !this.currentPeer || !this.isConnected()) return;
this.lastCursorSendTime = performance.now();
- const msg: CursorMoveMessage = {
- type: 'CURSOR_MOVE',
- peerId: this.currentPeer.id,
- peerName: this.currentPeer.name,
- peerColor: this.currentPeer.color,
- x: this.pendingCursor.x,
- y: this.pendingCursor.y,
- isDrawing: this.pendingCursor.isDrawing,
- tool: this.pendingCursor.tool,
- };
- this.sendMessage(msg);
+ const encoder = new TextEncoder();
+ const peerIdBytes = encoder.encode(String(this.currentPeer.id));
+
+ const payloadSize = 2 + peerIdBytes.length + 10;
+ const packet = new Uint8Array(11 + payloadSize);
+ const view = new DataView(packet.buffer);
+
+ view.setUint8(0, BINARY_MAGIC_0);
+ view.setUint8(1, BINARY_MAGIC_1);
+ view.setUint8(2, CODE_CURSOR_MOVE);
+ view.setUint32(3, this.getNextLamport(), true);
+ view.setUint32(7, payloadSize, true);
+
+ let offset = 11;
+ view.setUint16(offset, peerIdBytes.length, true);
+ offset += 2;
+ packet.set(peerIdBytes, offset);
+ offset += peerIdBytes.length;
+
+ 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);
+
+ this.sendBinary(packet);
this.pendingCursor = null;
}
diff --git a/src/types/editor.ts b/src/types/editor.ts
index 07a1142..fc50f81 100644
--- a/src/types/editor.ts
+++ b/src/types/editor.ts
@@ -17,21 +17,22 @@ export interface Point {
y: number;
pressure: number;
width: number;
+ tiltX?: number;
+ tiltY?: number;
+ twist?: number;
}
export type BrushPresetId =
| 'round'
| 'g-pen'
+ | 'maru-pen'
+ | 'turnip-pen'
+ | 'airbrush-soft'
| 'pencil-f'
| 'pencil-hb'
| 'pencil-2b'
| 'pencil-4b'
- | 'oil-thick'
- | 'oil-glaze'
- | 'chalk-rough'
- | 'chalk-pastel'
| 'square-digital'
- | 'blend-smudge'
| string;
export interface CspEffectorCurvePoint {
@@ -173,6 +174,7 @@ export interface BrushSettings {
pressureCurveGamma?: number; // 0.4 (soft) to 2.5 (hard) response curve
velocityDynamics?: boolean;
useGpu?: boolean; // Run brush mathematics on GPU video card by default
+ isTransparentInk?: boolean; // Transparent Ink mode (CSP 'C' key toggle)
}
export interface DocumentTab {
@@ -318,12 +320,58 @@ export interface DirtyRect {
height: number;
}
+export interface VectorKnot {
+ x: number;
+ y: number;
+ pressure: number;
+ width: number;
+ angle?: number;
+ timestamp: number;
+}
+
+export interface VectorStroke {
+ id: string;
+ layerId: string;
+ tool: 'brush' | 'pencil' | 'eraser';
+ knots: VectorKnot[];
+ color: string;
+ baseWidth: number;
+ opacity: number;
+ bounds: { minX: number; minY: number; maxX: number; maxY: number };
+ deleted?: boolean;
+}
+
+export interface ComicFrame {
+ id: string;
+ layerId: string;
+ polygon: Array<{ x: number; y: number }>;
+ borderWidth: number;
+ gutterVertical: number;
+ gutterHorizontal: number;
+ clipChildren: boolean;
+}
+
+export interface TileDelta {
+ key: string; // layerId:tileX:tileY
+ format: 'monochrome-1bit' | 'grayscale-8bit' | 'color-32bit';
+ beforeData?: Uint8Array | null;
+ afterData?: Uint8Array | null;
+}
+
export interface HistoryItem extends HistoryItemMeta {
imageData?: ImageData;
beforeImageData?: ImageData | null;
afterImageData?: ImageData | null;
layerId?: string;
dirtyRect?: DirtyRect;
+ // Tile-delta history support (drastically reduces undo memory at 600 DPI)
+ tileDeltas?: TileDelta[];
+ vectorStrokesDelta?: {
+ before: VectorStroke[];
+ after: VectorStroke[];
+ };
+ peerId?: string | number;
+ strokeId?: string;
}
export type ExpressionColor = 'color' | 'gray' | 'monochrome';
@@ -331,11 +379,13 @@ export type ExpressionColor = 'color' | 'gray' | 'monochrome';
export interface LayerItem {
id: string;
name: string;
- type: 'raster' | 'folder';
+ type: 'raster' | 'folder' | 'vector' | 'frame';
visible: boolean;
opacity: number; // 0.0 to 1.0
blendMode: BlendMode;
locked: boolean;
+ alphaLocked?: boolean; // Lock Transparent Pixels
+ clipped?: boolean; // Clip to Layer Below (Clipping Mask)
collapsed?: boolean;
parentId: string | null; // null for root, or folder id
thumbnailUrl?: string; // live layer thumbnail data URL
@@ -343,7 +393,7 @@ export interface LayerItem {
toneEnabled?: boolean;
toneFrequency?: number; // Lines / LPI (20 to 85, default: 60)
toneAngle?: number; // Angle in degrees (0 to 90, default: 45)
- toneDotShape?: 'circle' | 'euclidean' | 'line'; // Default: circle
+ toneDotShape?: 'circle' | 'euclidean' | 'line' | 'diamond'; // Default: circle
toneDensity?: number; // Density percentage (1 to 100, default: 40)
toneDensityType?: 'specified' | 'image'; // 'specified' ("Use specified density") or 'image' ("Use image brightness")
// Clip Studio Paint Style Layer Color (Tint Effect)
@@ -355,6 +405,13 @@ export interface LayerItem {
monoThreshold?: number; // 1 to 255 (default: 128)
monoExpressBlack?: boolean; // Express black in monochrome (default: true)
monoExpressWhite?: boolean; // Express white in monochrome (default: true)
+ // Vector Layer Data
+ vectorStrokes?: VectorStroke[];
+ // Comic Frame Data
+ comicFrames?: ComicFrame[];
+ // Collaborative Layer Soft-Locking
+ reservedByPeerId?: string | number;
+ reservedByPeerName?: string;
}
export type Layer = LayerItem;
diff --git a/src/types/multiplayer.ts b/src/types/multiplayer.ts
index b3061af..53795fb 100644
--- a/src/types/multiplayer.ts
+++ b/src/types/multiplayer.ts
@@ -1,4 +1,4 @@
-import { Point, BrushSettings, ToolType, DirtyRect, CanvasDimensions, CanvasColorMode, LayerItem } from './editor';
+import { Point, BrushSettings, ToolType, DirtyRect, CanvasDimensions, CanvasColorMode, LayerItem, VectorStroke } from './editor';
export interface CollabPeer {
id: string | number;
@@ -31,7 +31,9 @@ export type MultiplayerMessageType =
| 'LAYER_OPACITY'
| 'DOC_SYNC_REQUEST'
| 'DOC_SYNC_RESPONSE'
- | 'CANVAS_PING';
+ | 'CANVAS_PING'
+ | 'BINARY_TILE'
+ | 'SELECTIVE_UNDO';
export interface BaseMultiplayerMessage {
type: MultiplayerMessageType;
@@ -70,6 +72,11 @@ export interface PeerLeftMessage extends BaseMultiplayerMessage {
peerId: string | number;
}
+export interface PeerDisconnectedMessage extends BaseMultiplayerMessage {
+ type: 'PEER_DISCONNECTED';
+ peerId: string | number;
+}
+
export interface CursorMoveMessage extends BaseMultiplayerMessage {
type: 'CURSOR_MOVE';
peerId: string | number;
@@ -107,6 +114,7 @@ export interface StrokeFinishMessage extends BaseMultiplayerMessage {
layerId: string;
endPoint: Point;
dirtyRect?: DirtyRect;
+ vectorStroke?: VectorStroke;
}
export interface LayerActionMessage extends BaseMultiplayerMessage {
@@ -141,9 +149,21 @@ export interface CanvasPingMessage extends BaseMultiplayerMessage {
timestamp: number;
}
-export interface PeerDisconnectedMessage extends BaseMultiplayerMessage {
- type: 'PEER_DISCONNECTED';
- clientId: number;
+export interface TileStreamMessage extends BaseMultiplayerMessage {
+ type: 'BINARY_TILE';
+ layerId: string;
+ tileX: number;
+ tileY: number;
+ format: 'monochrome-1bit' | 'grayscale-8bit' | 'color-32bit';
+ version: number;
+ data: Uint8Array;
+}
+
+export interface SelectiveUndoMessage extends BaseMultiplayerMessage {
+ type: 'SELECTIVE_UNDO';
+ strokeId: string;
+ peerId: string | number;
+ lamport: number;
}
export type MultiplayerMessage =
@@ -160,7 +180,9 @@ export type MultiplayerMessage =
| LayerActionMessage
| DocSyncRequestMessage
| DocSyncResponseMessage
- | CanvasPingMessage;
+ | CanvasPingMessage
+ | TileStreamMessage
+ | SelectiveUndoMessage;
export interface SessionHostInfo {
diff --git a/src/types/settings.ts b/src/types/settings.ts
index 1296842..1562191 100644
--- a/src/types/settings.ts
+++ b/src/types/settings.ts
@@ -20,11 +20,57 @@ export interface ResizeCanvasOptions {
backgroundColor?: string;
}
-export type ThemePreset = 'vintage-manga';
+export type ThemePreset = 'vintage-manga' | 'modern';
+
+export type ModernAccentColor = 'blue' | 'burgundy' | 'green' | 'purple' | 'orange' | 'custom';
+
+export interface ModernAccentConfig {
+ id: ModernAccentColor;
+ label: string;
+ hex: string;
+}
+
+export const MODERN_ACCENTS: Record<Exclude<ModernAccentColor, 'custom'>, ModernAccentConfig> = {
+ 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' },
+};
+
+export function resolveModernAccentColor(accent: ModernAccentColor, customColor?: string): string {
+ if (accent === 'custom') {
+ return customColor && /^#[0-9a-fA-F]{6}$/i.test(customColor) ? customColor : '#3b82f6';
+ }
+ return MODERN_ACCENTS[accent]?.hex || '#3b82f6';
+}
+
+export function hexToRgb(hex: string): { r: number; g: number; b: number } | null {
+ const clean = hex.replace('#', '').trim();
+ if (clean.length === 3) {
+ const r = parseInt(clean[0] + clean[0], 16);
+ const g = parseInt(clean[1] + clean[1], 16);
+ const b = parseInt(clean[2] + clean[2], 16);
+ return isNaN(r) || isNaN(g) || isNaN(b) ? null : { r, g, b };
+ }
+ if (clean.length === 6) {
+ const r = parseInt(clean.substring(0, 2), 16);
+ const g = parseInt(clean.substring(2, 4), 16);
+ const b = parseInt(clean.substring(4, 6), 16);
+ return isNaN(r) || isNaN(g) || isNaN(b) ? null : { r, g, b };
+ }
+ return null;
+}
export interface AppSettings {
+ // User Profile
+ userName: string;
+ hasPromptedName: boolean;
+
// Appearance & Theme
themePreset: ThemePreset;
+ modernAccent: ModernAccentColor;
+ modernCustomColor: string;
uiTone?: 'slate' | 'oled' | 'charcoal';
showCheckerboard: boolean;
showCursorCoordinates: boolean;
@@ -47,7 +93,11 @@ export interface AppSettings {
}
export const DEFAULT_APP_SETTINGS: AppSettings = {
+ userName: '',
+ hasPromptedName: false,
themePreset: 'vintage-manga',
+ modernAccent: 'blue',
+ modernCustomColor: '#3b82f6',
uiTone: 'slate',
showCheckerboard: true,
showCursorCoordinates: true,
@@ -72,12 +122,34 @@ const SETTINGS_KEY = 'sora_paint_app_settings';
export function loadAppSettings(): AppSettings {
try {
const raw = localStorage.getItem(SETTINGS_KEY);
+ 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)
+ ? parsed.modernAccent
+ : 'blue';
+ const validCustomColor: string = typeof parsed.modernCustomColor === 'string' && /^#[0-9a-fA-F]{6}$/i.test(parsed.modernCustomColor)
+ ? parsed.modernCustomColor
+ : '#3b82f6';
+ const validTone: 'slate' | 'oled' | 'charcoal' = ['slate', 'oled', 'charcoal'].includes(parsed.uiTone)
+ ? parsed.uiTone
+ : 'slate';
return {
...DEFAULT_APP_SETTINGS,
...parsed,
- themePreset: 'vintage-manga',
+ userName: parsed.userName !== undefined ? parsed.userName : legacyName,
+ hasPromptedName: parsed.hasPromptedName !== undefined ? parsed.hasPromptedName : Boolean(legacyName),
+ themePreset: validTheme,
+ modernAccent: validAccent,
+ modernCustomColor: validCustomColor,
+ uiTone: validTone,
+ };
+ } else if (legacyName) {
+ return {
+ ...DEFAULT_APP_SETTINGS,
+ userName: legacyName,
+ hasPromptedName: true,
};
}
} catch (err) {
diff --git a/src/utils/__tests__/brushEngine.test.ts b/src/utils/__tests__/brushEngine.test.ts
new file mode 100644
index 0000000..c7d2564
--- /dev/null
+++ b/src/utils/__tests__/brushEngine.test.ts
@@ -0,0 +1,705 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import {
+ centripetalCatmullRomToBezier,
+ buildCubicArcLengthTable,
+ getCubicPointAtArcLength,
+ getRadialDabMaster,
+ drawRadialCubicBezierSegment,
+ drawSingleStamp,
+ RadialMixingOptions,
+} from '../stampEngine';
+import {
+ renderCompleteStroke,
+ applyParametricTaper,
+} from '../canvasUtils';
+import {
+ PaintReservoir,
+ LayerPixelSampler,
+} from '../colorMixingEngine';
+import {
+ getPaperGrain,
+ PENCIL_CONFIGS,
+ PencilGrade,
+ drawPencilDot,
+} from '../pencilEngine';
+import { calculatePreviewWidth } from '../brushPreview';
+import { Point, BrushSettings } from '../../types/editor';
+
+// Lightweight Canvas2D mock environment for headless Node.js Vitest runs
+function createMockCanvas(width: number = 128, height: number = 128) {
+ const pixelBuffer = new Uint8ClampedArray(width * height * 4);
+ const drawnDabs: { x: number; y: number; width: number; height: number; alpha: number; op?: string }[] = [];
+
+ const ctx: any = {
+ canvas: { width, height },
+ globalAlpha: 1.0,
+ globalCompositeOperation: 'source-over',
+ imageSmoothingEnabled: true,
+ clearRect: () => {
+ pixelBuffer.fill(0);
+ },
+ fillRect: () => {},
+ createImageData: (w: number, h: number) => ({
+ width: w,
+ height: h,
+ data: new Uint8ClampedArray(w * h * 4),
+ }),
+ putImageData: (imgData: any) => {
+ pixelBuffer.set(imgData.data);
+ },
+ getImageData: (sx: number, sy: number, sw: number, sh: number) => {
+ const data = new Uint8ClampedArray(sw * sh * 4);
+ for (let y = 0; y < sh; y++) {
+ const srcY = sy + y;
+ if (srcY < 0 || srcY >= height) continue;
+ for (let x = 0; x < sw; x++) {
+ const srcX = sx + x;
+ if (srcX < 0 || srcX >= width) continue;
+ const srcIdx = (srcY * width + srcX) * 4;
+ const dstIdx = (y * sw + x) * 4;
+ data[dstIdx] = pixelBuffer[srcIdx];
+ data[dstIdx + 1] = pixelBuffer[srcIdx + 1];
+ data[dstIdx + 2] = pixelBuffer[srcIdx + 2];
+ data[dstIdx + 3] = pixelBuffer[srcIdx + 3];
+ }
+ }
+ return { width: sw, height: sh, data };
+ },
+ drawImage: (_source: any, dx: number, dy: number, dw?: number, dh?: number) => {
+ drawnDabs.push({
+ x: dx + (dw ? dw / 2 : 0),
+ y: dy + (dh ? dh / 2 : 0),
+ width: dw || 0,
+ height: dh || 0,
+ alpha: ctx.globalAlpha,
+ op: ctx.globalCompositeOperation,
+ });
+ },
+ save: () => {},
+ restore: () => {},
+ translate: () => {},
+ rotate: () => {},
+ scale: () => {},
+ beginPath: () => {},
+ moveTo: () => {},
+ lineTo: () => {},
+ stroke: () => {},
+ };
+
+ const mockObj = {
+ width,
+ height,
+ canvas: { width, height },
+ getContext: (type: string) => (type === '2d' ? ctx : null),
+ pixelBuffer,
+ drawnDabs,
+ };
+ return mockObj;
+}
+
+describe('Brush & Spline Engine (CSP / Photoshop Architectural Parity)', () => {
+ beforeEach(() => {
+ (globalThis as any).document = {
+ createElement: (tag: string) => {
+ if (tag === 'canvas') {
+ return createMockCanvas();
+ }
+ return {};
+ },
+ };
+ });
+
+ describe('1. Centripetal Catmull-Rom Spline & Chord Bounding', () => {
+ it('bounds control points within 0.5x chord length to prevent overshoot cusps', () => {
+ const p0: Point = { x: 0, y: 0, pressure: 0.5, width: 10 };
+ const p1: Point = { x: 50, y: 0, pressure: 0.5, width: 10 };
+ const p2: Point = { x: 100, y: 100, pressure: 0.5, width: 10 }; // Sharp right turn
+ const p3: Point = { x: 150, y: 100, pressure: 0.5, width: 10 };
+
+ const { c1, c2 } = centripetalCatmullRomToBezier(p0, p1, p2, p3);
+
+ const chordLen = Math.hypot(p2.x - p1.x, p2.y - p1.y);
+ const dist1 = Math.hypot(c1.x - p1.x, c1.y - p1.y);
+ const dist2 = Math.hypot(c2.x - p2.x, c2.y - p2.y);
+
+ expect(dist1).toBeLessThanOrEqual(chordLen * 0.5 + 1e-4);
+ expect(dist2).toBeLessThanOrEqual(chordLen * 0.5 + 1e-4);
+ });
+
+ it('places control points strictly on the chord for collinear input points', () => {
+ const p0: Point = { x: 0, y: 0, pressure: 0.5, width: 10 };
+ const p1: Point = { x: 100, y: 0, pressure: 0.5, width: 10 };
+ const p2: Point = { x: 200, y: 0, pressure: 0.5, width: 10 };
+ const p3: Point = { x: 300, y: 0, pressure: 0.5, width: 10 };
+
+ const { c1, c2 } = centripetalCatmullRomToBezier(p0, p1, p2, p3);
+
+ expect(c1.y).toBeCloseTo(0, 5);
+ expect(c2.y).toBeCloseTo(0, 5);
+ expect(c1.x).toBeGreaterThan(p1.x);
+ expect(c2.x).toBeLessThan(p2.x);
+ expect(c1.x).toBeLessThan(c2.x);
+ });
+
+ it('safely handles duplicated endpoints at start and end of strokes without NaN', () => {
+ const p0: Point = { x: 42, y: 84, pressure: 0.3, width: 6 };
+ const p1: Point = { x: 120, y: 150, pressure: 0.8, width: 12 };
+
+ // Stroke start: p0 is repeated
+ const startResult = centripetalCatmullRomToBezier(p0, p0, p1, p1);
+ expect(Number.isFinite(startResult.c1.x)).toBe(true);
+ expect(Number.isFinite(startResult.c1.y)).toBe(true);
+ expect(Number.isFinite(startResult.c2.x)).toBe(true);
+ expect(Number.isFinite(startResult.c2.y)).toBe(true);
+ });
+ });
+
+ describe('2. Sub-Pixel Arc-Length Parameterization', () => {
+ it('computes exact arc length for a linear cubic segment', () => {
+ const p0: Point = { x: 0, y: 0, pressure: 0.5, width: 10 };
+ const c1: Point = { x: 33.333, y: 0, pressure: 0.5, width: 10 };
+ const c2: Point = { x: 66.666, y: 0, pressure: 0.5, width: 10 };
+ const p3: Point = { x: 100, y: 0, pressure: 0.5, width: 10 };
+
+ const table = buildCubicArcLengthTable(p0, c1, c2, p3);
+ expect(table.totalLength).toBeCloseTo(100, 1);
+ });
+
+ it('produces strictly monotonic cumulative distances along the curve', () => {
+ const p0: Point = { x: 10, y: 20, pressure: 0.2, width: 4 };
+ const c1: Point = { x: 50, y: 120, pressure: 0.5, width: 8 };
+ const c2: Point = { x: 150, y: -40, pressure: 0.8, width: 14 };
+ const p3: Point = { x: 200, y: 60, pressure: 1.0, width: 18 };
+
+ const table = buildCubicArcLengthTable(p0, c1, c2, p3);
+ for (let i = 1; i < table.distances.length; i++) {
+ expect(table.distances[i]).toBeGreaterThan(table.distances[i - 1]);
+ }
+ });
+
+ it('evaluates points along arc-length with correct boundary and midpoint interpolation', () => {
+ const p0: Point = { x: 0, y: 0, pressure: 0.2, width: 4 };
+ const c1: Point = { x: 50, y: 0, pressure: 0.4, width: 8 };
+ const c2: Point = { x: 50, y: 100, pressure: 0.6, width: 12 };
+ const p3: Point = { x: 100, y: 100, pressure: 0.8, width: 16 };
+
+ const table = buildCubicArcLengthTable(p0, c1, c2, p3);
+
+ const ptStart = getCubicPointAtArcLength(p0, c1, c2, p3, 0, table);
+ expect(ptStart.x).toBeCloseTo(p0.x, 3);
+ expect(ptStart.y).toBeCloseTo(p0.y, 3);
+ expect(ptStart.pressure).toBeCloseTo(0.2, 3);
+
+ const ptEnd = getCubicPointAtArcLength(p0, c1, c2, p3, table.totalLength, table);
+ expect(ptEnd.x).toBeCloseTo(p3.x, 3);
+ expect(ptEnd.y).toBeCloseTo(p3.y, 3);
+ expect(ptEnd.pressure).toBeCloseTo(0.8, 3);
+
+ const ptMid = getCubicPointAtArcLength(p0, c1, c2, p3, table.totalLength * 0.5, table);
+ expect(ptMid.pressure).toBeCloseTo(0.5, 1);
+ expect(ptMid.width).toBeCloseTo(10, 1);
+ });
+ });
+
+ describe('3. Analytical Hermite Radial Dab Masters', () => {
+ it('generates crisp anti-aliased dab at hardness 1.0', () => {
+ const master = getRadialDabMaster(1.0, '#000000');
+ expect(master).toBeDefined();
+ expect(master.width).toBe(128);
+ expect(master.height).toBe(128);
+ });
+
+ it('generates soft airbrush falloff at hardness 0.0 without errors', () => {
+ const airbrushMaster = getRadialDabMaster(0.0, '#ff0000');
+ expect(airbrushMaster).toBeDefined();
+ });
+
+ it('quantizes hardness levels into shared master caches', () => {
+ const master1 = getRadialDabMaster(0.81, '#000000');
+ const master2 = getRadialDabMaster(0.82, '#000000');
+ // Both quantize to 0.80 (step of 0.05) and share the underlying mask
+ expect(master1).toBeDefined();
+ expect(master2).toBeDefined();
+ });
+ });
+
+ describe('4. Graphite Physics & Cold-Press Paper Grain', () => {
+ it('evaluates deterministic paper grain height within [0, 255]', () => {
+ const h1 = getPaperGrain(100.5, 200.3);
+ const h2 = getPaperGrain(100.5, 200.3);
+ expect(h1).toBe(h2);
+ expect(h1).toBeGreaterThanOrEqual(0);
+ expect(h1).toBeLessThanOrEqual(255);
+ });
+
+ it('exhibits spatial coherence (not uncorrelated white noise)', () => {
+ const h1 = getPaperGrain(100.0, 100.0);
+ const h2 = getPaperGrain(100.1, 100.0); // 0.1 px offset
+ expect(Math.abs(h1 - h2)).toBeLessThan(15);
+ });
+
+ it('preserves hardness and density ordering across pencil grades', () => {
+ const grades: PencilGrade[] = ['pencil-f', 'pencil-hb', 'pencil-2b', 'pencil-4b'];
+ for (let i = 0; i < grades.length - 1; i++) {
+ const harder = PENCIL_CONFIGS[grades[i]];
+ const softer = PENCIL_CONFIGS[grades[i + 1]];
+ expect(harder.hardness).toBeGreaterThanOrEqual(softer.hardness);
+ expect(softer.particleDensity).toBeGreaterThanOrEqual(harder.particleDensity);
+ }
+ });
+ });
+
+ describe('5. Distance Remainder Continuity Across Stroke Segments', () => {
+ it('maintains continuous dab spacing across adjacent cubic segments', () => {
+ const mockCanvas = createMockCanvas(500, 500);
+ const ctx = mockCanvas.getContext('2d') as unknown as CanvasRenderingContext2D;
+
+ const p0: Point = { x: 0, y: 100, pressure: 1.0, width: 10 };
+ const p1: Point = { x: 100, y: 100, pressure: 1.0, width: 10 };
+ const p2: Point = { x: 200, y: 100, pressure: 1.0, width: 10 };
+
+ const seg1 = centripetalCatmullRomToBezier(p0, p0, p1, p2);
+ const seg2 = centripetalCatmullRomToBezier(p0, p1, p2, p2);
+
+ const spacing = 0.05; // required step = 10 * 0.05 = 0.5px
+ const remainder1 = drawRadialCubicBezierSegment(
+ ctx,
+ p0,
+ seg1.c1,
+ seg1.c2,
+ p1,
+ '#000000',
+ 1.0,
+ 1.0,
+ spacing,
+ false,
+ false,
+ 0
+ );
+
+ expect(remainder1).toBeGreaterThanOrEqual(0);
+ expect(remainder1).toBeLessThanOrEqual(0.6);
+
+ const dabCountBefore = mockCanvas.drawnDabs.length;
+ expect(dabCountBefore).toBeGreaterThan(150);
+
+ // Thread remainder1 into segment 2
+ const remainder2 = drawRadialCubicBezierSegment(
+ ctx,
+ p1,
+ seg2.c1,
+ seg2.c2,
+ p2,
+ '#000000',
+ 1.0,
+ 1.0,
+ spacing,
+ false,
+ false,
+ remainder1
+ );
+
+ expect(remainder2).toBeGreaterThanOrEqual(0);
+ expect(remainder2).toBeLessThanOrEqual(0.6);
+
+ // Verify dab spacing across the joint between segment 1 and 2
+ const lastDabSeg1 = mockCanvas.drawnDabs[dabCountBefore - 1];
+ const firstDabSeg2 = mockCanvas.drawnDabs[dabCountBefore];
+
+ const jointGap = Math.hypot(firstDabSeg2.x - lastDabSeg1.x, firstDabSeg2.y - lastDabSeg1.y);
+ const expectedStep = Math.max(0.4, 10 * spacing);
+ expect(jointGap).toBeCloseTo(expectedStep, 1);
+ });
+
+ it('correctly defers stamps on micro-segments shorter than the spacing step', () => {
+ const mockCanvas = createMockCanvas(500, 500);
+ const ctx = mockCanvas.getContext('2d') as unknown as CanvasRenderingContext2D;
+
+ const p0: Point = { x: 0, y: 0, pressure: 1.0, width: 20 };
+ const p1: Point = { x: 0.2, y: 0, pressure: 1.0, width: 20 }; // Very short move (0.2px)
+
+ const spacing = 0.1; // required step = 2.0px
+ const remainder = drawRadialCubicBezierSegment(
+ ctx,
+ p0,
+ p0,
+ p1,
+ p1,
+ '#000000',
+ 1.0,
+ 1.0,
+ spacing,
+ false,
+ false,
+ 1.0
+ );
+
+ // No new dabs placed, remainder increases by 0.2px
+ expect(mockCanvas.drawnDabs.length).toBe(0);
+ expect(remainder).toBeCloseTo(0.8, 1);
+ });
+ });
+
+ describe('6. Brush Preview S-Curve Dimension Bounds', () => {
+ it('bounds hairline leads to crisp visible minimums', () => {
+ const w1 = calculatePreviewWidth(1.0, 34, false);
+ const w2 = calculatePreviewWidth(2.0, 34, false);
+ expect(w1).toBeGreaterThanOrEqual(0.9);
+ expect(w2).toBeGreaterThan(w1);
+ });
+
+ it('bounds large brushes to avoid vertical canvas clipping', () => {
+ const h = 40;
+ const wThick = calculatePreviewWidth(120, h, false);
+ expect(wThick).toBeLessThanOrEqual(h * 0.54);
+ });
+
+ it('monotonically increases preview width with brush size up to bounding cap', () => {
+ const sizes = [1, 2, 4, 8, 14, 24];
+ for (let i = 1; i < sizes.length; i++) {
+ const prevW = calculatePreviewWidth(sizes[i - 1], 34, false);
+ const curW = calculatePreviewWidth(sizes[i], 34, false);
+ expect(curW).toBeGreaterThan(prevW);
+ }
+
+ // Beyond cap: clamped at max bound without overflowing
+ const cap = 34 * 0.54;
+ expect(calculatePreviewWidth(48, 34, false)).toBeLessThanOrEqual(cap);
+ expect(calculatePreviewWidth(80, 34, false)).toBeLessThanOrEqual(cap);
+ });
+ });
+
+ describe('7. Real-Time Color Mixing & Bake Commit Parity', () => {
+ it('picks up canvas paint dynamically along the stroke path', () => {
+ const underCanvas = createMockCanvas(200, 200);
+ // Place a black patch from x: 40 to 60, y: 0 to 200
+ for (let y = 0; y < 200; y++) {
+ for (let x = 40; x <= 60; x++) {
+ const idx = (y * 200 + x) * 4;
+ underCanvas.pixelBuffer[idx] = 0; // R
+ underCanvas.pixelBuffer[idx + 1] = 0; // G
+ underCanvas.pixelBuffer[idx + 2] = 0; // B
+ underCanvas.pixelBuffer[idx + 3] = 255; // A
+ }
+ }
+
+ const sampler = new LayerPixelSampler(underCanvas as unknown as HTMLCanvasElement);
+ const reservoir = new PaintReservoir('#ff0000'); // Pure red fresh paint
+
+ const destCanvas = createMockCanvas(200, 200);
+ const dCtx = destCanvas.getContext('2d') as unknown as CanvasRenderingContext2D;
+
+ const p0: Point = { x: 10, y: 100, pressure: 1.0, width: 10 };
+ const p1: Point = { x: 30, y: 100, pressure: 1.0, width: 10 };
+ const p2: Point = { x: 80, y: 100, pressure: 1.0, width: 10 };
+ const p3: Point = { x: 120, y: 100, pressure: 1.0, width: 10 };
+
+ const mixingOptions: RadialMixingOptions = {
+ colorMixing: true,
+ amountOfPaint: 0.5,
+ densityOfPaint: 1.0,
+ colorStretch: 0.8,
+ mixingMode: 'running_color',
+ sampler,
+ reservoir,
+ };
+
+ // Before crossing black patch: reservoir is pure red (255, 0, 0)
+ expect(reservoir.r).toBe(255);
+ expect(reservoir.g).toBe(0);
+ expect(reservoir.b).toBe(0);
+
+ // Draw segment crossing from x=30 to x=80 (traversing the black patch at 40..60)
+ drawRadialCubicBezierSegment(
+ dCtx,
+ p0,
+ p1,
+ p2,
+ p3,
+ '#ff0000',
+ 1.0,
+ 1.0,
+ 0.05,
+ false,
+ false,
+ 0,
+ 1.0,
+ 0,
+ mixingOptions
+ );
+
+ // After crossing black patch: reservoir must have mixed and darkened significantly
+ expect(reservoir.isLoadedWithCanvasColor).toBe(true);
+ expect(reservoir.r).toBeLessThan(200); // Red channel darkened by black absorption
+ });
+
+ it('bakes completed stroke into underlying canvas with color mixing preserved', () => {
+ const targetCanvas = createMockCanvas(200, 200);
+ // Place a blue patch from x: 40 to 60
+ for (let y = 0; y < 200; y++) {
+ for (let x = 40; x <= 60; x++) {
+ const idx = (y * 200 + x) * 4;
+ targetCanvas.pixelBuffer[idx] = 0; // R
+ targetCanvas.pixelBuffer[idx + 1] = 0; // G
+ targetCanvas.pixelBuffer[idx + 2] = 255; // B: Blue
+ targetCanvas.pixelBuffer[idx + 3] = 255; // A
+ }
+ }
+
+ const points: Point[] = [
+ { x: 10, y: 100, pressure: 1.0, width: 10 },
+ { x: 50, y: 100, pressure: 1.0, width: 10 }, // Directly over blue patch
+ { x: 90, y: 100, pressure: 1.0, width: 10 },
+ ];
+
+ const settings: BrushSettings = {
+ size: 10,
+ minSizeFactor: 0.2,
+ usePressure: true,
+ smoothing: true,
+ stabilization: 10,
+ color: '#ffff00', // Yellow + Blue = Subtractive Green
+ flow: 1.0,
+ opacity: 1.0,
+ hardness: 1.0,
+ spacing: 0.05,
+ colorMixing: true,
+ amountOfPaint: 0.5,
+ densityOfPaint: 1.0,
+ colorStretch: 0.8,
+ mixingMode: 'blend',
+ };
+
+ const bakeCanvas = createMockCanvas(200, 200);
+ const bCtx = bakeCanvas.getContext('2d') as unknown as CanvasRenderingContext2D;
+
+ // Render complete stroke passing targetCanvas as underlyingCanvas
+ renderCompleteStroke(
+ bCtx,
+ points,
+ settings,
+ 'brush',
+ 'color',
+ false,
+ targetCanvas as unknown as HTMLCanvasElement
+ );
+
+ // Dabs were deposited during bake
+ expect(bakeCanvas.drawnDabs.length).toBeGreaterThan(10);
+ });
+ });
+
+ describe('Alpha Lock (Lock Transparent Pixels) & Transparent Ink Mode', () => {
+ it('sets composite operation to source-atop when alphaLocked is true in drawSingleStamp', () => {
+ const mockCanvas = createMockCanvas(100, 100);
+ const ctx = mockCanvas.getContext('2d') as unknown as CanvasRenderingContext2D;
+ const dummyStamp = createMockCanvas(16, 16).canvas as unknown as CanvasImageSource;
+
+ drawSingleStamp(
+ ctx,
+ dummyStamp,
+ 50,
+ 50,
+ 20,
+ 20,
+ 0,
+ 1.0,
+ false,
+ false,
+ true, // alphaLocked
+ false // isTransparentInk
+ );
+
+ expect(mockCanvas.drawnDabs.length).toBe(1);
+ expect(mockCanvas.drawnDabs[0].op).toBe('source-atop');
+ });
+
+ it('sets composite operation to destination-out when isTransparentInk is true in drawSingleStamp', () => {
+ const mockCanvas = createMockCanvas(100, 100);
+ const ctx = mockCanvas.getContext('2d') as unknown as CanvasRenderingContext2D;
+ const dummyStamp = createMockCanvas(16, 16).canvas as unknown as CanvasImageSource;
+
+ drawSingleStamp(
+ ctx,
+ dummyStamp,
+ 50,
+ 50,
+ 20,
+ 20,
+ 0,
+ 1.0,
+ false,
+ false,
+ false, // alphaLocked
+ true // isTransparentInk
+ );
+
+ expect(mockCanvas.drawnDabs.length).toBe(1);
+ expect(mockCanvas.drawnDabs[0].op).toBe('destination-out');
+ });
+
+ it('renderCompleteStroke uses destination-out when brushSettings.isTransparentInk is true', () => {
+ const bakeCanvas = createMockCanvas(200, 200);
+ const bCtx = bakeCanvas.getContext('2d') as unknown as CanvasRenderingContext2D;
+
+ const points: Point[] = [
+ { x: 10, y: 10, pressure: 0.8, width: 12 },
+ { x: 30, y: 20, pressure: 0.8, width: 12 },
+ { x: 60, y: 30, pressure: 0.8, width: 12 },
+ ];
+
+ const settings: BrushSettings = {
+ size: 12,
+ minSizeFactor: 0.2,
+ opacity: 1.0,
+ color: '#000000',
+ flow: 1.0,
+ spacing: 0.08,
+ smoothing: false,
+ stabilization: 0,
+ hardness: 1.0,
+ usePressure: true,
+ isTransparentInk: true,
+ };
+
+ renderCompleteStroke(bCtx, points, settings, 'brush', 'color', false);
+
+ expect(bakeCanvas.drawnDabs.length).toBeGreaterThan(0);
+ // All dabs drawn in transparent ink mode must be destination-out
+ for (const dab of bakeCanvas.drawnDabs) {
+ expect(dab.op).toBe('destination-out');
+ }
+ });
+
+ it('renderCompleteStroke uses source-atop when alphaLocked parameter is true', () => {
+ const bakeCanvas = createMockCanvas(200, 200);
+ const bCtx = bakeCanvas.getContext('2d') as unknown as CanvasRenderingContext2D;
+
+ const points: Point[] = [
+ { x: 10, y: 10, pressure: 0.8, width: 12 },
+ { x: 30, y: 20, pressure: 0.8, width: 12 },
+ { x: 60, y: 30, pressure: 0.8, width: 12 },
+ ];
+
+ const settings: BrushSettings = {
+ size: 12,
+ minSizeFactor: 0.2,
+ opacity: 1.0,
+ color: '#ff0000',
+ flow: 1.0,
+ spacing: 0.08,
+ smoothing: false,
+ stabilization: 0,
+ hardness: 1.0,
+ usePressure: true,
+ };
+
+ renderCompleteStroke(bCtx, points, settings, 'brush', 'color', false, undefined, true);
+
+ expect(bakeCanvas.drawnDabs.length).toBeGreaterThan(0);
+ for (const dab of bakeCanvas.drawnDabs) {
+ expect(dab.op).toBe('source-atop');
+ }
+ });
+ });
+
+ describe('Stylus Tilt & Taper Dynamics', () => {
+ it('stretches stamp aspect ratio when stylus is tilted flat', () => {
+ const canvasUpright = createMockCanvas(200, 200);
+ const ctxUpright = canvasUpright.getContext('2d') as unknown as CanvasRenderingContext2D;
+ const canvasTilted = createMockCanvas(200, 200);
+ const ctxTilted = canvasTilted.getContext('2d') as unknown as CanvasRenderingContext2D;
+
+ const p0Upright: Point = { x: 10, y: 50, pressure: 1.0, width: 20, tiltX: 0, tiltY: 0 };
+ const c1Upright: Point = { x: 30, y: 50, pressure: 1.0, width: 20, tiltX: 0, tiltY: 0 };
+ const c2Upright: Point = { x: 70, y: 50, pressure: 1.0, width: 20, tiltX: 0, tiltY: 0 };
+ const p3Upright: Point = { x: 90, y: 50, pressure: 1.0, width: 20, tiltX: 0, tiltY: 0 };
+
+ drawRadialCubicBezierSegment(ctxUpright, p0Upright, c1Upright, c2Upright, p3Upright, '#000000', 1.0, 1.0, 0.1);
+
+ // Tilted flat along X axis (tiltX = 65 degrees)
+ const p0Tilted: Point = { x: 10, y: 50, pressure: 1.0, width: 20, tiltX: 65, tiltY: 0 };
+ const c1Tilted: Point = { x: 30, y: 50, pressure: 1.0, width: 20, tiltX: 65, tiltY: 0 };
+ const c2Tilted: Point = { x: 70, y: 50, pressure: 1.0, width: 20, tiltX: 65, tiltY: 0 };
+ const p3Tilted: Point = { x: 90, y: 50, pressure: 1.0, width: 20, tiltX: 65, tiltY: 0 };
+
+ drawRadialCubicBezierSegment(ctxTilted, p0Tilted, c1Tilted, c2Tilted, p3Tilted, '#000000', 1.0, 1.0, 0.1);
+
+ expect(canvasUpright.drawnDabs.length).toBeGreaterThan(0);
+ expect(canvasTilted.drawnDabs.length).toBeGreaterThan(0);
+
+ // When tilted flat, the width of the dab expands significantly due to tilt stretch
+ const avgUprightW = canvasUpright.drawnDabs.reduce((acc, d) => acc + d.width, 0) / canvasUpright.drawnDabs.length;
+ const avgTiltedW = canvasTilted.drawnDabs.reduce((acc, d) => acc + d.width, 0) / canvasTilted.drawnDabs.length;
+
+ expect(avgTiltedW).toBeGreaterThan(avgUprightW * 1.5);
+ });
+
+ it('widens pencil footprint when stylus is tilted flat', () => {
+ const canvasUpright = createMockCanvas(200, 200);
+ const ctxUpright = canvasUpright.getContext('2d') as unknown as CanvasRenderingContext2D;
+ const canvasTilted = createMockCanvas(200, 200);
+ const ctxTilted = canvasTilted.getContext('2d') as unknown as CanvasRenderingContext2D;
+
+ const pUpright: Point = { x: 50, y: 50, pressure: 0.7, width: 10, tiltX: 0, tiltY: 0 };
+ drawPencilDot(ctxUpright, pUpright, '#222326', 'pencil-2b');
+
+ const pTilted: Point = { x: 50, y: 50, pressure: 0.7, width: 10, tiltX: 70, tiltY: 0 };
+ drawPencilDot(ctxTilted, pTilted, '#222326', 'pencil-2b');
+
+ expect(canvasUpright.drawnDabs.length).toBe(1);
+ expect(canvasTilted.drawnDabs.length).toBe(1);
+ expect(canvasTilted.drawnDabs[0].width).toBeGreaterThan(canvasUpright.drawnDabs[0].width * 2.0);
+ });
+
+ it('applies parametric out-taper to smooth out stroke endings', () => {
+ const points: Point[] = [
+ { x: 0, y: 0, pressure: 1.0, width: 20 },
+ { x: 20, y: 0, pressure: 1.0, width: 20 },
+ { x: 40, y: 0, pressure: 1.0, width: 20 },
+ { x: 60, y: 0, pressure: 1.0, width: 20 },
+ { x: 80, y: 0, pressure: 1.0, width: 20 },
+ { x: 100, y: 0, pressure: 1.0, width: 20 },
+ ];
+
+ applyParametricTaper(points, {
+ useOut: true,
+ outCount: 3,
+ minSizeFactor: 0.1,
+ });
+
+ // Earlier points remain unchanged
+ expect(points[0].width).toBe(20);
+ expect(points[1].width).toBe(20);
+
+ // Tail points are progressively tapered down
+ expect(points[4].width).toBeLessThan(points[3].width);
+ expect(points[5].width).toBeLessThan(points[4].width);
+ expect(points[5].pressure).toBeLessThan(0.5);
+ });
+
+ it('modulates out-taper length when lifting pen with high exit velocity', () => {
+ const slowPoints: Point[] = Array.from({ length: 12 }, (_, i) => ({
+ x: i * 10,
+ y: 0,
+ pressure: 1.0,
+ width: 20,
+ }));
+ const fastPoints: Point[] = Array.from({ length: 12 }, (_, i) => ({
+ x: i * 10,
+ y: 0,
+ pressure: 1.0,
+ width: 20,
+ }));
+
+ applyParametricTaper(slowPoints, { useOut: true, outCount: 3, exitSpeed: 0.2 });
+ applyParametricTaper(fastPoints, { useOut: true, outCount: 3, exitSpeed: 1.8 });
+
+ // Fast exit speed extends the taper window across more knots
+ const slowTaperedCount = slowPoints.filter((p) => p.width < 19.9).length;
+ const fastTaperedCount = fastPoints.filter((p) => p.width < 19.9).length;
+
+ expect(fastTaperedCount).toBeGreaterThan(slowTaperedCount);
+ });
+ });
+});
diff --git a/src/utils/__tests__/compositor.test.ts b/src/utils/__tests__/compositor.test.ts
new file mode 100644
index 0000000..3eb8be3
--- /dev/null
+++ b/src/utils/__tests__/compositor.test.ts
@@ -0,0 +1,113 @@
+import { describe, it, expect } from 'vitest';
+import {
+ calculateVisibleDocumentBounds,
+ ViewportTransform,
+ COMPOSITOR_VERTEX_SHADER,
+ COMPOSITOR_FRAGMENT_SHADER,
+ groupLayersForCompositing,
+} from '../compositor';
+import { LayerItem } from '../../types/editor';
+
+describe('Unified GPU Viewport Compositor', () => {
+ it('accurately calculates frustum culling document bounds under pan and zoom', () => {
+ const transform: ViewportTransform = {
+ pan: { x: 960, y: 540 }, // Centered in viewport
+ zoom: 1.0,
+ rotation: 0,
+ };
+
+ const docW = 4961;
+ const docH = 7016;
+
+ const bounds = calculateVisibleDocumentBounds(
+ 1920,
+ 1080,
+ transform,
+ docW,
+ docH
+ );
+
+ // Visible width should cover at least 1920 px and height at least 1080 px (with conservative ceil/floor)
+ expect(bounds.maxX - bounds.minX).toBeGreaterThanOrEqual(1920);
+ expect(bounds.maxX - bounds.minX).toBeLessThanOrEqual(1922);
+ expect(bounds.maxY - bounds.minY).toBeGreaterThanOrEqual(1080);
+ expect(bounds.maxY - bounds.minY).toBeLessThanOrEqual(1082);
+
+ const centerX = (bounds.minX + bounds.maxX) / 2;
+ const centerY = (bounds.minY + bounds.maxY) / 2;
+
+ expect(centerX).toBeCloseTo(docW / 2, 0);
+ expect(centerY).toBeCloseTo(docH / 2, 0);
+ });
+
+ it('contracts frustum bounds when zooming in (culling more tiles)', () => {
+ const transformZoom2: ViewportTransform = {
+ pan: { x: 960, y: 540 },
+ zoom: 2.0, // Zoomed in 2x
+ rotation: 0,
+ };
+
+ const bounds = calculateVisibleDocumentBounds(
+ 1920,
+ 1080,
+ transformZoom2,
+ 4961,
+ 7016
+ );
+
+ // When zoomed in 2x, visible document area is half as wide and half as tall
+ expect(bounds.maxX - bounds.minX).toBeGreaterThanOrEqual(960);
+ expect(bounds.maxX - bounds.minX).toBeLessThanOrEqual(962);
+ expect(bounds.maxY - bounds.minY).toBeGreaterThanOrEqual(540);
+ expect(bounds.maxY - bounds.minY).toBeLessThanOrEqual(542);
+ });
+
+ it('correctly maps quad texture coordinates without vertical inversion', () => {
+ // Top-left of quad must map to top-left of tile buffer (v_texCoord = a_quadPos)
+ expect(COMPOSITOR_VERTEX_SHADER).toContain('v_texCoord = a_quadPos;');
+ expect(COMPOSITOR_VERTEX_SHADER).not.toContain('1.0 - a_quadPos.y');
+ });
+
+ it('outputs premultiplied alpha in fragment shader for standard GL blend compatibility', () => {
+ expect(COMPOSITOR_FRAGMENT_SHADER).toContain('fragColor = vec4(finalColor.rgb * finalColor.a, finalColor.a);');
+ });
+
+ it('groups successive clipped layers under their immediate non-clipped base layer', () => {
+ const makeLayer = (id: string, clipped: boolean = false): LayerItem => ({
+ id,
+ name: id,
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ clipped,
+ });
+
+ // Stack bottom-to-top: [Base1, Clip1A, Clip1B, Base2, Clip2A, Base3]
+ const layers = [
+ makeLayer('base-1', false),
+ makeLayer('clip-1a', true),
+ makeLayer('clip-1b', true),
+ makeLayer('base-2', false),
+ makeLayer('clip-2a', true),
+ makeLayer('base-3', false),
+ ];
+
+ const groups = groupLayersForCompositing(layers);
+ expect(groups).toHaveLength(3);
+
+ // Group 1: base-1 with [clip-1a, clip-1b]
+ expect(groups[0].baseLayer.id).toBe('base-1');
+ expect(groups[0].clippedLayers.map((l) => l.id)).toEqual(['clip-1a', 'clip-1b']);
+
+ // Group 2: base-2 with [clip-2a]
+ expect(groups[1].baseLayer.id).toBe('base-2');
+ expect(groups[1].clippedLayers.map((l) => l.id)).toEqual(['clip-2a']);
+
+ // Group 3: base-3 with no clipped layers
+ expect(groups[2].baseLayer.id).toBe('base-3');
+ expect(groups[2].clippedLayers).toHaveLength(0);
+ });
+});
diff --git a/src/utils/__tests__/frameEngine.test.ts b/src/utils/__tests__/frameEngine.test.ts
new file mode 100644
index 0000000..2810d8c
--- /dev/null
+++ b/src/utils/__tests__/frameEngine.test.ts
@@ -0,0 +1,74 @@
+import { describe, it, expect } from 'vitest';
+import {
+ mmToPixels,
+ pixelsToMm,
+ createDefaultPageFrame,
+ bisectComicFrame,
+ isPointInsidePolygon,
+} from '../frameEngine';
+
+describe('Comic Frame Engine (Koma-wari)', () => {
+ it('converts millimeters to pixels accurately at 600 DPI', () => {
+ // 1 inch = 25.4mm = 600 pixels
+ expect(mmToPixels(25.4, 600)).toBeCloseTo(600);
+ // 3mm manga gutter at 600 DPI: (3 * 600) / 25.4 = ~70.866 px
+ expect(mmToPixels(3, 600)).toBeCloseTo(70.866, 2);
+ // 5mm manga gutter at 600 DPI: (5 * 600) / 25.4 = ~118.11 px
+ expect(mmToPixels(5, 600)).toBeCloseTo(118.11, 2);
+
+ expect(pixelsToMm(600, 600)).toBeCloseTo(25.4);
+ });
+
+ it('creates default page frame fitting within document bounds', () => {
+ const frame = createDefaultPageFrame('layer-frame', 4961, 7016, 600, 20);
+ expect(frame.polygon.length).toBe(4);
+ expect(frame.polygon[0].x).toBeGreaterThan(0);
+ expect(frame.polygon[1].x).toBeLessThan(4961);
+ expect(frame.clipChildren).toBe(true);
+ });
+
+ it('bisects a rectangular frame horizontally into top and bottom child frames', () => {
+ const frame = {
+ id: 'frame-test',
+ layerId: 'layer-frame',
+ polygon: [
+ { x: 100, y: 100 },
+ { x: 900, y: 100 },
+ { x: 900, y: 900 },
+ { x: 100, y: 900 },
+ ],
+ borderWidth: 4,
+ gutterVertical: 70,
+ gutterHorizontal: 118,
+ clipChildren: true,
+ };
+
+ // Horizontal slash at y = 500
+ const result = bisectComicFrame(frame, { x: 50, y: 500 }, { x: 950, y: 500 }, 600);
+ expect(result).not.toBeNull();
+ if (!result) return;
+
+ const [child1, child2] = result;
+ expect(child1.polygon.length).toBeGreaterThanOrEqual(4);
+ expect(child2.polygon.length).toBeGreaterThanOrEqual(4);
+
+ // One child should be above the cut and one below
+ const center1Y = child1.polygon.reduce((acc, p) => acc + p.y, 0) / child1.polygon.length;
+ const center2Y = child2.polygon.reduce((acc, p) => acc + p.y, 0) / child2.polygon.length;
+
+ expect(Math.abs(center1Y - center2Y)).toBeGreaterThan(100);
+ });
+
+ it('correctly determines whether a point is inside a frame polygon', () => {
+ const poly = [
+ { x: 0, y: 0 },
+ { x: 100, y: 0 },
+ { x: 100, y: 100 },
+ { x: 0, y: 100 },
+ ];
+
+ expect(isPointInsidePolygon({ x: 50, y: 50 }, poly)).toBe(true);
+ expect(isPointInsidePolygon({ x: 150, y: 50 }, poly)).toBe(false);
+ expect(isPointInsidePolygon({ x: -10, y: 50 }, poly)).toBe(false);
+ });
+});
diff --git a/src/utils/__tests__/recentDocumentsManager.test.ts b/src/utils/__tests__/recentDocumentsManager.test.ts
new file mode 100644
index 0000000..d1de432
--- /dev/null
+++ b/src/utils/__tests__/recentDocumentsManager.test.ts
@@ -0,0 +1,106 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import {
+ loadRecentDocuments,
+ saveRecentDocument,
+ toggleStarDocument,
+ removeRecentDocument,
+ permanentlyDeleteDocument,
+ formatFileSize,
+ RecentDocument,
+} from '../recentDocumentsManager';
+
+describe('recentDocumentsManager', () => {
+ beforeEach(() => {
+ const storage: Record<string, string> = {};
+ (globalThis as any).localStorage = {
+ getItem: (k: string) => storage[k] || null,
+ setItem: (k: string, v: string) => {
+ storage[k] = String(v);
+ },
+ removeItem: (k: string) => {
+ delete storage[k];
+ },
+ clear: () => {
+ Object.keys(storage).forEach((k) => delete storage[k]);
+ },
+ };
+ });
+
+ it('formats file sizes accurately', () => {
+ expect(formatFileSize(0)).toBe('0 B');
+ expect(formatFileSize(512)).toBe('512 B');
+ expect(formatFileSize(1024)).toBe('1.0 KB');
+ expect(formatFileSize(1048576)).toBe('1.0 MB');
+ expect(formatFileSize(4404019)).toBe('4.2 MB');
+ });
+
+ it('returns empty array when no documents are stored', async () => {
+ const docs = await loadRecentDocuments();
+ expect(Array.isArray(docs)).toBe(true);
+ expect(docs.length).toBe(0);
+ });
+
+ it('saves and updates recent documents correctly', async () => {
+ const newDoc: RecentDocument = {
+ id: 'test-doc-123',
+ title: 'Manga_Test.sora',
+ path: 'C:\\Users\\Test\\Manga_Test.sora',
+ size: 2048000,
+ isStarred: false,
+ lastOpened: Date.now(),
+ };
+
+ await saveRecentDocument(newDoc);
+ const docs = await loadRecentDocuments();
+ const found = docs.find((d) => d.id === 'test-doc-123');
+ expect(found).toBeDefined();
+ expect(found?.title).toBe('Manga_Test.sora');
+ });
+
+ it('toggles star state of documents', async () => {
+ const testDoc: RecentDocument = {
+ id: 'star-toggle-doc',
+ title: 'Star_Test.sora',
+ path: 'C:\\Users\\Test\\Star_Test.sora',
+ size: 1024,
+ isStarred: false,
+ lastOpened: Date.now(),
+ };
+ await saveRecentDocument(testDoc);
+ const newStarred = await toggleStarDocument(testDoc.id);
+ expect(newStarred).toBe(true);
+ const unstarred = await toggleStarDocument(testDoc.id);
+ expect(unstarred).toBe(false);
+ });
+
+ it('removes documents from app list', async () => {
+ const testDoc: RecentDocument = {
+ id: 'doc-to-remove',
+ title: 'Remove_Test.sora',
+ path: 'C:\\Users\\Test\\Remove_Test.sora',
+ size: 1024,
+ isStarred: false,
+ lastOpened: Date.now(),
+ };
+ await saveRecentDocument(testDoc);
+ await removeRecentDocument(testDoc.id);
+ const docs = await loadRecentDocuments();
+ expect(docs.find((d) => d.id === testDoc.id)).toBeUndefined();
+ });
+
+ it('handles permanent delete calls gracefully', async () => {
+ const testDoc: RecentDocument = {
+ id: 'doc-to-perm-delete',
+ title: 'Temp.sora',
+ path: 'C:\\Invalid\\NonExistent\\Temp.sora',
+ size: 1024,
+ isStarred: false,
+ lastOpened: Date.now(),
+ };
+ await saveRecentDocument(testDoc);
+ const res = await permanentlyDeleteDocument(testDoc);
+ expect(res.success).toBe(true);
+ const docs = await loadRecentDocuments();
+ expect(docs.find((d) => d.id === testDoc.id)).toBeUndefined();
+ });
+});
diff --git a/src/utils/__tests__/screentoneEngine.test.ts b/src/utils/__tests__/screentoneEngine.test.ts
new file mode 100644
index 0000000..d60839d
--- /dev/null
+++ b/src/utils/__tests__/screentoneEngine.test.ts
@@ -0,0 +1,30 @@
+import { describe, it, expect } from 'vitest';
+import {
+ evaluateHalftoneDot,
+ fract,
+} from '../screentoneEngine';
+
+describe('Anti-Moiré Manga Screentone GPU & CPU Pipeline', () => {
+ it('evaluates Euclidean manga dot spot formula correctly', () => {
+ const cosA = Math.cos(Math.PI / 4);
+ const sinA = Math.sin(Math.PI / 4);
+ const cellSize = 10; // 600 DPI / 60 LPI
+
+ // Center of a cell (xr = cellSize * 0.5) with 50% density should be black ink
+ const centerX = cellSize * 0.5 * cosA;
+ const centerY = cellSize * 0.5 * sinA;
+ const isInk = evaluateHalftoneDot(centerX, centerY, 0.5, cellSize, cosA, sinA, 'circle');
+ expect(isInk).toBe(true);
+
+ // Far corner of cell (u = 0.5, v = 0.5) with 10% density should be white paper
+ const isInkCorner = evaluateHalftoneDot(0, 0, 0.1, cellSize, cosA, sinA, 'circle');
+ expect(isInkCorner).toBe(false);
+ });
+
+ it('fract function strictly yields [0.0, 1.0)', () => {
+ expect(fract(0.5)).toBeCloseTo(0.5);
+ expect(fract(1.0)).toBeCloseTo(0.0);
+ expect(fract(-0.25)).toBeCloseTo(0.75);
+ expect(fract(-1.5)).toBeCloseTo(0.5);
+ });
+});
diff --git a/src/utils/__tests__/settings.test.ts b/src/utils/__tests__/settings.test.ts
new file mode 100644
index 0000000..49c0ea7
--- /dev/null
+++ b/src/utils/__tests__/settings.test.ts
@@ -0,0 +1,79 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import {
+ DEFAULT_APP_SETTINGS,
+ loadAppSettings,
+ saveAppSettings,
+ resolveModernAccentColor,
+ hexToRgb,
+ MODERN_ACCENTS,
+} from '../../types/settings';
+
+describe('settings theme & accent system', () => {
+ beforeEach(() => {
+ const storage: Record<string, string> = {};
+ (globalThis as any).localStorage = {
+ getItem: (k: string) => storage[k] || null,
+ setItem: (k: string, v: string) => {
+ storage[k] = String(v);
+ },
+ removeItem: (k: string) => {
+ delete storage[k];
+ },
+ clear: () => {
+ Object.keys(storage).forEach((k) => delete storage[k]);
+ },
+ };
+ });
+
+ it('loads default settings when storage is empty', () => {
+ const settings = loadAppSettings();
+ expect(settings.themePreset).toBe('vintage-manga');
+ expect(settings.modernAccent).toBe('blue');
+ expect(settings.modernCustomColor).toBe('#3b82f6');
+ });
+
+ it('correctly loads and persists modern theme with presets', () => {
+ saveAppSettings({
+ ...DEFAULT_APP_SETTINGS,
+ themePreset: 'modern',
+ modernAccent: 'burgundy',
+ });
+
+ const loaded = loadAppSettings();
+ expect(loaded.themePreset).toBe('modern');
+ expect(loaded.modernAccent).toBe('burgundy');
+ });
+
+ it('correctly resolves preset accent hex codes', () => {
+ expect(resolveModernAccentColor('blue')).toBe(MODERN_ACCENTS.blue.hex);
+ expect(resolveModernAccentColor('burgundy')).toBe(MODERN_ACCENTS.burgundy.hex);
+ expect(resolveModernAccentColor('green')).toBe(MODERN_ACCENTS.green.hex);
+ expect(resolveModernAccentColor('purple')).toBe(MODERN_ACCENTS.purple.hex);
+ expect(resolveModernAccentColor('orange')).toBe(MODERN_ACCENTS.orange.hex);
+ });
+
+ it('handles custom accent color with validation fallback', () => {
+ expect(resolveModernAccentColor('custom', '#123456')).toBe('#123456');
+ expect(resolveModernAccentColor('custom', 'invalid-hex')).toBe('#3b82f6');
+ });
+
+ it('converts hex strings to valid RGB objects', () => {
+ expect(hexToRgb('#3b82f6')).toEqual({ r: 59, g: 130, b: 246 });
+ expect(hexToRgb('#fff')).toEqual({ r: 255, g: 255, b: 255 });
+ expect(hexToRgb('invalid')).toBeNull();
+ });
+
+ it('correctly loads and validates uiTone setting with fallbacks', () => {
+ saveAppSettings({
+ ...DEFAULT_APP_SETTINGS,
+ uiTone: 'oled',
+ });
+ expect(loadAppSettings().uiTone).toBe('oled');
+
+ saveAppSettings({
+ ...DEFAULT_APP_SETTINGS,
+ uiTone: 'invalid-tone' as any,
+ });
+ expect(loadAppSettings().uiTone).toBe('slate');
+ });
+});
diff --git a/src/utils/__tests__/tileEngine.test.ts b/src/utils/__tests__/tileEngine.test.ts
new file mode 100644
index 0000000..d866f0c
--- /dev/null
+++ b/src/utils/__tests__/tileEngine.test.ts
@@ -0,0 +1,212 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import {
+ SparseTileGrid,
+ TILE_SIZE,
+ BYTES_1BIT,
+ BYTES_8BIT,
+ BYTES_32BIT,
+ createTileBuffer,
+ setPixel1Bit,
+ getPixel1Bit,
+ packRGBATo1Bit,
+ unpack1BitToRGBA,
+ serializeTileBuffer,
+ deserializeTileBuffer,
+ serializeTileDeltas,
+ deserializeTileDeltas,
+} from '../tileEngine';
+
+describe('Sparse Virtual Tile Engine', () => {
+ let grid: SparseTileGrid;
+
+ beforeEach(() => {
+ grid = new SparseTileGrid();
+ });
+
+ it('allocates zero memory for unpainted canvas space', () => {
+ // Canvas is B4 @ 600 DPI: 4961 x 7016 px
+ const stats = grid.getMemoryStats();
+ expect(stats.tileCount).toBe(0);
+ expect(stats.totalBytes).toBe(0);
+
+ // Query unpainted tile
+ const tile = grid.getTile('layer-1', 10, 15);
+ expect(tile).toBeNull();
+ });
+
+ 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);
+
+ // Verify 32x memory reduction compared to 32-bit RGBA
+ expect(BYTES_32BIT / BYTES_1BIT).toBe(32);
+ });
+
+ 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);
+ });
+
+ 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);
+
+ // 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);
+
+ 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);
+
+ // Clear pixel
+ 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', () => {
+ const rgba = new Uint8ClampedArray(BYTES_32BIT);
+ // Draw black ink at (10, 20) and (11, 20)
+ const idx1 = (20 * TILE_SIZE + 10) * 4;
+ rgba[idx1] = 0; // R
+ rgba[idx1 + 1] = 0; // G
+ rgba[idx1 + 2] = 0; // B
+ rgba[idx1 + 3] = 255; // A
+
+ const idx2 = (20 * TILE_SIZE + 11) * 4;
+ rgba[idx2] = 0;
+ rgba[idx2 + 1] = 0;
+ rgba[idx2 + 2] = 0;
+ rgba[idx2 + 3] = 255;
+
+ const bit1Data = new Uint8Array(BYTES_1BIT);
+ packRGBATo1Bit(rgba, bit1Data, 128);
+
+ expect(getPixel1Bit(bit1Data, 10, 20)).toBe(1);
+ expect(getPixel1Bit(bit1Data, 11, 20)).toBe(1);
+ expect(getPixel1Bit(bit1Data, 12, 20)).toBe(0);
+
+ const unpackedRGBA = new Uint8ClampedArray(BYTES_32BIT);
+ unpack1BitToRGBA(bit1Data, unpackedRGBA);
+
+ // Unpacked pixel at (10, 20) should have alpha 255 and black color
+ expect(unpackedRGBA[idx1 + 3]).toBe(255);
+ expect(unpackedRGBA[idx1]).toBe(0);
+
+ // Transparent pixel at (12, 20) should have alpha 0
+ const idx3 = (20 * TILE_SIZE + 12) * 4;
+ expect(unpackedRGBA[idx3 + 3]).toBe(0);
+ });
+
+ 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);
+
+ const serialized = serializeTileBuffer(tile);
+ // Highly sparse tile should compress dramatically
+ expect(serialized.length).toBeLessThan(100);
+
+ const deserialized = deserializeTileBuffer('layer-ink', serialized);
+ 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);
+ });
+
+ it('correctly handles multi-tile write and read in SparseTileGrid', () => {
+ grid.setLayerFormat('layer-test', 'color-32bit');
+
+ // Create a 100x100 patch spanning across tile boundaries (e.g. from x=200 to 300, y=200 to 300)
+ // This touches tiles (0,0), (1,0), (0,1), (1,1)
+ const patchWidth = 100;
+ const patchHeight = 100;
+ const patch = new Uint8ClampedArray(patchWidth * patchHeight * 4);
+ patch.fill(128); // Fill with gray
+
+ const bounds = grid.writeImageData(
+ 'layer-test',
+ { data: patch, width: patchWidth, height: patchHeight },
+ 200,
+ 200
+ );
+
+ expect(bounds.minTileX).toBe(0);
+ expect(bounds.maxTileX).toBe(1);
+ expect(bounds.minTileY).toBe(0);
+ expect(bounds.maxTileY).toBe(1);
+
+ // Exactly 4 tiles should now be allocated
+ expect(grid.getLayerTiles('layer-test').length).toBe(4);
+
+ // Reading back from document space
+ const read = grid.readImageData('layer-test', 200, 200, 10, 10);
+ expect(read.width).toBe(10);
+ expect(read.height).toBe(10);
+ expect(read.data[0]).toBe(128);
+ expect(read.data[1]).toBe(128);
+ expect(read.data[2]).toBe(128);
+ expect(read.data[3]).toBe(128);
+
+ // Reading unpainted region outside patch should yield zero / transparent
+ const emptyRead = grid.readImageData('layer-test', 500, 500, 10, 10);
+ expect(emptyRead.data[3]).toBe(0);
+ });
+
+ it('correctly tracks tile deltas for undo/redo with snapshot and application', () => {
+ grid.setLayerFormat('layer-1', 'monochrome-1bit');
+
+ // Snapshot before drawing (empty)
+ const bounds = { x: 10, y: 10, width: 50, height: 50 };
+ const snapshot = grid.snapshotTilesInRect('layer-1', bounds);
+ expect(snapshot.size).toBe(1);
+
+ // Draw something
+ const tile = grid.getOrCreateTile('layer-1', 0, 0, 'monochrome-1bit');
+ setPixel1Bit(tile.data, 10, 10, true);
+
+ // Compute deltas
+ const deltas = grid.computeDeltasFromSnapshot(snapshot, 'layer-1', bounds);
+ expect(deltas.length).toBe(1);
+ expect(deltas[0].beforeData).toBeNull();
+ expect(deltas[0].afterData).not.toBeNull();
+
+ // Serialize and deserialize deltas
+ const bytes = serializeTileDeltas(deltas);
+ expect(bytes.length).toBeGreaterThan(0);
+ const restoredDeltas = deserializeTileDeltas(bytes);
+ expect(restoredDeltas.length).toBe(1);
+ expect(restoredDeltas[0].key).toBe('layer-1:0:0');
+ expect(restoredDeltas[0].format).toBe('monochrome-1bit');
+
+ // Undo: should revert to beforeData (which is null -> tile deleted)
+ grid.applyTileDeltas(restoredDeltas, 'undo');
+ expect(grid.getTile('layer-1', 0, 0)).toBeNull();
+
+ // Redo: should re-apply afterData
+ grid.applyTileDeltas(restoredDeltas, 'redo');
+ const redoTile = grid.getTile('layer-1', 0, 0);
+ expect(redoTile).not.toBeNull();
+ expect(getPixel1Bit(redoTile!.data, 10, 10)).toBe(1);
+ });
+});
+
diff --git a/src/utils/__tests__/vectorEngine.test.ts b/src/utils/__tests__/vectorEngine.test.ts
new file mode 100644
index 0000000..8a0be04
--- /dev/null
+++ b/src/utils/__tests__/vectorEngine.test.ts
@@ -0,0 +1,235 @@
+import { describe, it, expect } from 'vitest';
+import {
+ evaluateCatmullRom,
+ findSegmentIntersection,
+ VectorSpatialGrid,
+ applyVectorEraser,
+ splitStrokeAtIntersection,
+ simplifyPathPoints,
+ adjustVectorStrokeWidth,
+ reshapeVectorLine,
+} from '../vectorEngine';
+import { VectorKnot, VectorStroke } from '../../types/editor';
+
+describe('Vector Inking Engine & Vector Eraser', () => {
+ it('smoothly interpolates Catmull-Rom splines with variable pressure', () => {
+ const k0: VectorKnot = { x: 0, y: 0, pressure: 0.2, width: 2, timestamp: 0 };
+ const k1: VectorKnot = { x: 10, y: 0, pressure: 0.5, width: 5, timestamp: 10 };
+ const k2: VectorKnot = { x: 20, y: 10, pressure: 0.8, width: 8, timestamp: 20 };
+ const k3: VectorKnot = { x: 30, y: 10, pressure: 1.0, width: 10, timestamp: 30 };
+
+ const mid = evaluateCatmullRom(k0, k1, k2, k3, 0.5);
+ expect(mid.x).toBeGreaterThan(10);
+ expect(mid.x).toBeLessThan(20);
+ expect(mid.width).toBeGreaterThan(5);
+ expect(mid.width).toBeLessThan(8);
+ });
+
+ it('accurately detects segment intersections', () => {
+ // Horizontal line: (0, 5) to (10, 5)
+ // Vertical line: (5, 0) to (5, 10)
+ const hit = findSegmentIntersection(
+ { x: 0, y: 5 },
+ { x: 10, y: 5 },
+ { x: 5, y: 0 },
+ { x: 5, y: 10 }
+ );
+
+ expect(hit).not.toBeNull();
+ expect(hit?.point.x).toBeCloseTo(5);
+ expect(hit?.point.y).toBeCloseTo(5);
+ expect(hit?.tA).toBeCloseTo(0.5);
+ expect(hit?.tB).toBeCloseTo(0.5);
+ });
+
+ it('spatial grid indexes and retrieves intersecting stroke segments', () => {
+ const grid = new VectorSpatialGrid(128);
+
+ const stroke1: VectorStroke = {
+ id: 'stroke-1',
+ layerId: 'vector-1',
+ tool: 'brush',
+ knots: [
+ { x: 0, y: 50, pressure: 0.5, width: 4, timestamp: 0 },
+ { x: 200, y: 50, pressure: 0.5, width: 4, timestamp: 10 },
+ ],
+ color: '#000000',
+ baseWidth: 4,
+ opacity: 1,
+ bounds: { minX: 0, minY: 48, maxX: 200, maxY: 52 },
+ };
+
+ grid.insertStroke(stroke1);
+
+ // Query box overlapping the segment
+ const hits = grid.queryBox(40, 40, 60, 60);
+ expect(hits.length).toBe(1);
+ expect(hits[0].strokeId).toBe('stroke-1');
+
+ // Query box away from the segment
+ const misses = grid.queryBox(300, 300, 400, 400);
+ expect(misses.length).toBe(0);
+ });
+
+ it('performs authentic "Erase Up to Intersection" (koma-wari style)', () => {
+ // Cross strokes:
+ // Stroke A: horizontal line from (0, 50) to (100, 50)
+ // Stroke B: vertical line from (50, 0) to (50, 100)
+ // They intersect at (50, 50).
+ const strokeA: VectorStroke = {
+ id: 'stroke-A',
+ layerId: 'v1',
+ tool: 'brush',
+ knots: [
+ { x: 0, y: 50, pressure: 0.5, width: 4, timestamp: 0 },
+ { x: 25, y: 50, pressure: 0.5, width: 4, timestamp: 5 },
+ { x: 50, y: 50, pressure: 0.5, width: 4, timestamp: 10 },
+ { x: 75, y: 50, pressure: 0.5, width: 4, timestamp: 15 },
+ { x: 100, y: 50, pressure: 0.5, width: 4, timestamp: 20 },
+ ],
+ color: '#000000',
+ baseWidth: 4,
+ opacity: 1,
+ bounds: { minX: 0, minY: 48, maxX: 100, maxY: 52 },
+ };
+
+ const strokeB: VectorStroke = {
+ id: 'stroke-B',
+ layerId: 'v1',
+ tool: 'brush',
+ knots: [
+ { x: 50, y: 0, pressure: 0.5, width: 4, timestamp: 0 },
+ { x: 50, y: 25, pressure: 0.5, width: 4, timestamp: 5 },
+ { x: 50, y: 50, pressure: 0.5, width: 4, timestamp: 10 },
+ { x: 50, y: 75, pressure: 0.5, width: 4, timestamp: 15 },
+ { x: 50, y: 100, pressure: 0.5, width: 4, timestamp: 20 },
+ ],
+ color: '#000000',
+ baseWidth: 4,
+ opacity: 1,
+ bounds: { minX: 48, minY: 0, maxX: 52, maxY: 100 },
+ };
+
+ const strokes = [strokeA, strokeB];
+
+ // Erase right branch of Stroke A (touching x=80, y=50)
+ const eraserKnots = [{ x: 80, y: 50 }];
+ const res = applyVectorEraser(eraserKnots, 5, strokes, 'intersection');
+
+ expect(res.deletedIds).toContain('stroke-A');
+ expect(res.deletedIds).not.toContain('stroke-B');
+
+ // The left portion (0 to 50) before the intersection should remain!
+ expect(res.createdStrokes.length).toBeGreaterThanOrEqual(1);
+ const retained = res.createdStrokes[0];
+ expect(retained.knots[0].x).toBe(0);
+ expect(retained.knots[retained.knots.length - 1].x).toBeLessThanOrEqual(60);
+ });
+
+ it('splitStrokeAtIntersection prunes branch up to crossing intersection point', () => {
+ const strokeA: VectorStroke = {
+ id: 'stroke-A',
+ layerId: 'v1',
+ tool: 'brush',
+ knots: [
+ { x: 0, y: 50, pressure: 0.5, width: 4, timestamp: 0 },
+ { x: 50, y: 50, pressure: 0.5, width: 4, timestamp: 10 },
+ { x: 100, y: 50, pressure: 0.5, width: 4, timestamp: 20 },
+ ],
+ color: '#000000',
+ baseWidth: 4,
+ opacity: 1,
+ bounds: { minX: 0, minY: 48, maxX: 100, maxY: 52 },
+ };
+
+ const strokeB: VectorStroke = {
+ id: 'stroke-B',
+ layerId: 'v1',
+ tool: 'brush',
+ knots: [
+ { x: 50, y: 0, pressure: 0.5, width: 4, timestamp: 0 },
+ { x: 50, y: 100, pressure: 0.5, width: 4, timestamp: 20 },
+ ],
+ color: '#000000',
+ baseWidth: 4,
+ opacity: 1,
+ bounds: { minX: 48, minY: 0, maxX: 52, maxY: 100 },
+ };
+
+ // Hit parameter t = 1.5 (on the right side of the intersection at t = 1.0)
+ const result = splitStrokeAtIntersection(strokeA, 1.5, [strokeA, strokeB]);
+ expect(result.remainingStrokes.length).toBe(1);
+ // Preserved segment should be from start to intersection at ~50
+ expect(result.remainingStrokes[0].knots[0].x).toBe(0);
+ expect(result.remainingStrokes[0].knots[result.remainingStrokes[0].knots.length - 1].x).toBeCloseTo(50, 0);
+ });
+
+ it('simplifyPathPoints reduces redundant collinear knots using Ramer-Douglas-Peucker', () => {
+ const knots: VectorKnot[] = [
+ { x: 0, y: 0, pressure: 0.5, width: 2, timestamp: 0 },
+ { x: 10, y: 0.1, pressure: 0.5, width: 2, timestamp: 10 },
+ { x: 20, y: -0.1, pressure: 0.5, width: 2, timestamp: 20 },
+ { x: 30, y: 0.05, pressure: 0.5, width: 2, timestamp: 30 },
+ { x: 40, y: 0, pressure: 0.5, width: 2, timestamp: 40 },
+ { x: 50, y: 25, pressure: 0.8, width: 4, timestamp: 50 },
+ { x: 60, y: 50, pressure: 0.5, width: 2, timestamp: 60 },
+ ];
+
+ const simplified = simplifyPathPoints(knots, 1.0);
+ expect(simplified.length).toBeLessThan(knots.length);
+ expect(simplified[0].x).toBe(0);
+ expect(simplified[simplified.length - 1].x).toBe(60);
+ });
+
+ it('adjustVectorStrokeWidth scales knot widths and updates bounding box', () => {
+ const stroke: VectorStroke = {
+ id: 'stroke-scale',
+ layerId: 'v1',
+ tool: 'brush',
+ knots: [
+ { x: 10, y: 10, pressure: 0.5, width: 4, timestamp: 0 },
+ { x: 50, y: 50, pressure: 0.5, width: 4, timestamp: 10 },
+ ],
+ color: '#000000',
+ baseWidth: 4,
+ opacity: 1,
+ bounds: { minX: 8, minY: 8, maxX: 52, maxY: 52 },
+ };
+
+ const thickened = adjustVectorStrokeWidth(stroke, 2);
+ expect(thickened.baseWidth).toBe(6);
+ expect(thickened.knots[0].width).toBe(6);
+ expect(thickened.bounds.minX).toBeLessThan(stroke.bounds.minX);
+ });
+
+ it('reshapeVectorLine applies pinch/pull transformations to knots near cursor', () => {
+ const stroke: VectorStroke = {
+ id: 'stroke-reshape',
+ layerId: 'v1',
+ tool: 'brush',
+ knots: [
+ { x: 0, y: 50, pressure: 0.5, width: 4, timestamp: 0 },
+ { x: 50, y: 50, pressure: 0.5, width: 4, timestamp: 10 },
+ { x: 100, y: 50, pressure: 0.5, width: 4, timestamp: 20 },
+ ],
+ color: '#000000',
+ baseWidth: 4,
+ opacity: 1,
+ bounds: { minX: 0, minY: 48, maxX: 100, maxY: 52 },
+ };
+
+ const reshaped = reshapeVectorLine(stroke, {
+ cursorPos: { x: 50, y: 50 },
+ delta: { x: 0, y: 30 },
+ radius: 40,
+ });
+
+ // Middle knot near (50, 50) should be pulled downward towards y = 80
+ expect(reshaped.knots[1].y).toBeGreaterThan(50);
+ // Endpoints outside radius should remain unchanged
+ expect(reshaped.knots[0].x).toBe(0);
+ expect(reshaped.knots[0].y).toBe(50);
+ expect(reshaped.knots[2].x).toBe(100);
+ expect(reshaped.knots[2].y).toBe(50);
+ });
+});
diff --git a/src/utils/brushOutline.ts b/src/utils/brushOutline.ts
new file mode 100644
index 0000000..cb11920
--- /dev/null
+++ b/src/utils/brushOutline.ts
@@ -0,0 +1,306 @@
+import { BrushSettings } from '../types/editor';
+import { getBuiltinBrushConfig } from './presetBrushes';
+import { getPreloadedTipImage } from './brushStorage';
+
+export interface TipOutline {
+ path: string;
+ viewBox: string;
+ width: number;
+ height: number;
+}
+
+// Memory cache to guarantee zero-latency synchronous access
+const outlineCache = new Map<string, TipOutline>();
+const MAX_CACHE_ENTRIES = 120;
+
+/**
+ * Resolves the active HTMLImageElement for a brush if one exists.
+ */
+export function resolveBrushTipImage(settings: Partial<BrushSettings>): HTMLImageElement | undefined {
+ if (settings.customTipImage) return settings.customTipImage;
+ if (settings.preset) {
+ const builtin = getBuiltinBrushConfig(settings.preset);
+ if (builtin?.customTipImage) return builtin.customTipImage;
+ }
+ if (settings.customTipDataUrl) {
+ const preloaded = getPreloadedTipImage(settings.customTipDataUrl);
+ if (preloaded) return preloaded;
+ }
+ return undefined;
+}
+
+/**
+ * Extracts and caches the vector SVG silhouette contour of a brush tip texture.
+ * Uses adaptive thresholding and Marching Squares with RDP polygon reduction.
+ */
+export function getBrushTipOutline(image: HTMLImageElement): TipOutline | null {
+ if (!image || !image.complete) return null;
+
+ const w = image.naturalWidth || image.width;
+ const h = image.naturalHeight || image.height;
+ if (w <= 0 || h <= 0) return null;
+
+ const cacheKey = image.src || `${w}x${h}`;
+ if (outlineCache.has(cacheKey)) {
+ return outlineCache.get(cacheKey)!;
+ }
+
+ // Downsample to max 160px grid to guarantee sub-millisecond execution while preserving fine bristle details
+ const maxDim = Math.max(w, h);
+ const scale = maxDim > 160 ? 160 / maxDim : 1;
+ const gridW = Math.max(8, Math.round(w * scale));
+ const gridH = Math.max(8, Math.round(h * scale));
+
+ const canvas = document.createElement('canvas');
+ canvas.width = gridW;
+ canvas.height = gridH;
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
+ if (!ctx) return null;
+
+ ctx.drawImage(image, 0, 0, gridW, gridH);
+ const imgData = ctx.getImageData(0, 0, gridW, gridH);
+ const data = imgData.data;
+
+ // Check transparency vs opaque black-on-white
+ let hasAlpha = false;
+ let maxAlpha = 0;
+ for (let i = 0; i < data.length; i += 4) {
+ const a = data[i + 3];
+ if (a < 240) hasAlpha = true;
+ if (a > maxAlpha) maxAlpha = a;
+ }
+
+ const alphaGrid = new Uint8Array(gridW * gridH);
+ if (!hasAlpha) {
+ let maxLumAlpha = 0;
+ for (let i = 0, p = 0; i < data.length; i += 4, p++) {
+ const lum = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
+ const a = Math.max(0, Math.min(255, Math.round(255 - lum)));
+ alphaGrid[p] = a;
+ if (a > maxLumAlpha) maxLumAlpha = a;
+ }
+ maxAlpha = maxLumAlpha;
+ } else {
+ for (let i = 3, p = 0; i < data.length; i += 4, p++) {
+ alphaGrid[p] = data[i];
+ }
+ }
+
+ if (maxAlpha < 10) return null;
+
+ // Adaptive thresholding: captures faint bristle marks while ignoring low noise
+ const threshold = Math.max(16, Math.round(maxAlpha * 0.15));
+
+ const padW = gridW + 2;
+ const padH = gridH + 2;
+ const grid = new Uint8Array(padW * padH);
+
+ let opaqueCount = 0;
+ for (let y = 0; y < gridH; y++) {
+ const rowOffset = (y + 1) * padW + 1;
+ const imgOffset = y * gridW;
+ for (let x = 0; x < gridW; x++) {
+ if (alphaGrid[imgOffset + x] >= threshold) {
+ grid[rowOffset + x] = 1;
+ opaqueCount++;
+ }
+ }
+ }
+
+ if (opaqueCount === 0) return null;
+
+ // Marching Squares contour segment generation
+ const segments: [[number, number], [number, number]][] = [];
+
+ for (let cy = 0; cy < padH - 1; cy++) {
+ const row0 = cy * padW;
+ const row1 = (cy + 1) * padW;
+ for (let cx = 0; cx < padW - 1; cx++) {
+ const tl = grid[row0 + cx];
+ const tr = grid[row0 + cx + 1];
+ const br = grid[row1 + cx + 1];
+ const bl = grid[row1 + cx];
+
+ const mask = (tl << 3) | (tr << 2) | (br << 1) | bl;
+ if (mask === 0 || mask === 15) continue;
+
+ const p0: [number, number] = [2 * cx + 1, 2 * cy];
+ const p1: [number, number] = [2 * cx + 2, 2 * cy + 1];
+ const p2: [number, number] = [2 * cx + 1, 2 * cy + 2];
+ const p3: [number, number] = [2 * cx, 2 * cy + 1];
+
+ switch (mask) {
+ case 1: segments.push([p3, p2]); break;
+ case 2: segments.push([p2, p1]); break;
+ case 3: segments.push([p3, p1]); break;
+ case 4: segments.push([p1, p0]); break;
+ case 5: segments.push([p3, p0], [p2, p1]); break;
+ case 6: segments.push([p2, p0]); break;
+ case 7: segments.push([p3, p0]); break;
+ case 8: segments.push([p0, p3]); break;
+ case 9: segments.push([p0, p2]); break;
+ case 10: segments.push([p0, p1], [p2, p3]); break;
+ case 11: segments.push([p0, p1]); break;
+ case 12: segments.push([p1, p3]); break;
+ case 13: segments.push([p1, p2]); break;
+ case 14: segments.push([p2, p3]); break;
+ }
+ }
+ }
+
+ // Build vertex adjacency map
+ const adj = new Map<number, { pt: [number, number]; neighbors: number[] }>();
+ function addEdge(a: [number, number], b: [number, number]) {
+ const ka = (a[0] << 16) | a[1];
+ const kb = (b[0] << 16) | b[1];
+ let na = adj.get(ka);
+ if (!na) { na = { pt: a, neighbors: [] }; adj.set(ka, na); }
+ let nb = adj.get(kb);
+ if (!nb) { nb = { pt: b, neighbors: [] }; adj.set(kb, nb); }
+ na.neighbors.push(kb);
+ nb.neighbors.push(ka);
+ }
+
+ for (let i = 0; i < segments.length; i++) {
+ addEdge(segments[i][0], segments[i][1]);
+ }
+
+ const visitedEdges = new Set<string>();
+ function edgeKey(u: number, v: number): string {
+ return u < v ? `${u}_${v}` : `${v}_${u}`;
+ }
+
+ const loops: { x: number; y: number }[][] = [];
+
+ for (const [startK, node] of adj.entries()) {
+ for (let ni = 0; ni < node.neighbors.length; ni++) {
+ const nextK = node.neighbors[ni];
+ const eK = edgeKey(startK, nextK);
+ if (visitedEdges.has(eK)) continue;
+
+ const loop: [number, number][] = [node.pt];
+ visitedEdges.add(eK);
+ let prevK = startK;
+ let currK = nextK;
+
+ while (currK !== startK) {
+ const currNode = adj.get(currK);
+ if (!currNode) break;
+ loop.push(currNode.pt);
+ let foundNext: number | null = null;
+ for (let j = 0; j < currNode.neighbors.length; j++) {
+ const nK = currNode.neighbors[j];
+ if (nK === prevK) continue;
+ const neK = edgeKey(currK, nK);
+ if (!visitedEdges.has(neK)) {
+ foundNext = nK;
+ visitedEdges.add(neK);
+ break;
+ }
+ }
+ if (foundNext === null) break;
+ prevK = currK;
+ currK = foundNext;
+ }
+
+ if (loop.length >= 4) {
+ // Map back to unpadded image grid coordinates
+ const floatLoop = loop.map(p => ({
+ x: p[0] * 0.5 - 1,
+ y: p[1] * 0.5 - 1,
+ }));
+
+ // Shoelace polygon area: filter out negligible micro-noise (< 3px² area)
+ let area = 0;
+ for (let i = 0; i < floatLoop.length; i++) {
+ const next = (i + 1) % floatLoop.length;
+ area += floatLoop[i].x * floatLoop[next].y - floatLoop[next].x * floatLoop[i].y;
+ }
+ if (Math.abs(area) * 0.5 >= 3) {
+ loops.push(floatLoop);
+ }
+ }
+ }
+ }
+
+ if (loops.length === 0) return null;
+
+ // Simplify and generate SVG path
+ const pathParts: string[] = [];
+ for (let l = 0; l < loops.length; l++) {
+ const simplified = simplifyLoop(loops[l], 0.65);
+ if (simplified.length < 3) continue;
+
+ let part = `M ${simplified[0].x.toFixed(1)} ${simplified[0].y.toFixed(1)}`;
+ for (let p = 1; p < simplified.length; p++) {
+ part += ` L ${simplified[p].x.toFixed(1)} ${simplified[p].y.toFixed(1)}`;
+ }
+ part += ' Z';
+ pathParts.push(part);
+ }
+
+ if (pathParts.length === 0) return null;
+
+ const result: TipOutline = {
+ path: pathParts.join(' '),
+ viewBox: `0 0 ${gridW} ${gridH}`,
+ width: gridW,
+ height: gridH,
+ };
+
+ if (outlineCache.size >= MAX_CACHE_ENTRIES) {
+ const firstKey = outlineCache.keys().next().value;
+ if (firstKey) outlineCache.delete(firstKey);
+ }
+ outlineCache.set(cacheKey, result);
+
+ return result;
+}
+
+function simplifyLoop(points: { x: number; y: number }[], epsilon: number): { x: number; y: number }[] {
+ if (points.length <= 3) return points;
+ return rdp(points, 0, points.length - 1, epsilon);
+}
+
+function rdp(
+ points: { x: number; y: number }[],
+ start: number,
+ end: number,
+ epsilon: number
+): { x: number; y: number }[] {
+ if (end <= start + 1) return [points[start], points[end]];
+
+ let maxDist = 0;
+ let index = start;
+ const p1 = points[start];
+ const p2 = points[end];
+ const dx = p2.x - p1.x;
+ const dy = p2.y - p1.y;
+ const lenSq = dx * dx + dy * dy;
+
+ for (let i = start + 1; i < end; i++) {
+ const p = points[i];
+ let dist: number;
+ if (lenSq === 0) {
+ dist = Math.hypot(p.x - p1.x, p.y - p1.y);
+ } else {
+ const t = Math.max(0, Math.min(1, ((p.x - p1.x) * dx + (p.y - p1.y) * dy) / lenSq));
+ dist = Math.hypot(p.x - (p1.x + t * dx), p.y - (p1.y + t * dy));
+ }
+ if (dist > maxDist) {
+ maxDist = dist;
+ index = i;
+ }
+ }
+
+ if (maxDist > epsilon) {
+ const left = rdp(points, start, index, epsilon);
+ const right = rdp(points, index, end, epsilon);
+ return left.slice(0, -1).concat(right);
+ }
+ return [points[start], points[end]];
+}
+
+export function clearTipOutlineCache() {
+ outlineCache.clear();
+}
diff --git a/src/utils/brushPreview.ts b/src/utils/brushPreview.ts
index 2af8484..bb5073d 100644
--- a/src/utils/brushPreview.ts
+++ b/src/utils/brushPreview.ts
@@ -1,6 +1,6 @@
import { BrushPresetId, CspSpraySettings } from '../types/editor';
-import { PENCIL_CONFIGS, PencilGrade, getPaperGrain, parseRgba } from './pencilEngine';
-import { getTintedTipMaster } from './stampEngine';
+import { PENCIL_CONFIGS, PencilGrade, getPaperGrain, getGraphiteTipMaster } from './pencilEngine';
+import { getTintedTipMaster, getRadialDabMaster, drawSingleStamp } from './stampEngine';
import { getBuiltinBrushConfig } from './presetBrushes';
import { evaluateCspSpline } from './sutParser';
@@ -11,6 +11,7 @@ export interface BrushPreviewOptions {
opacity?: number;
grain?: number;
hardness?: number;
+ spacing?: number;
minSizeFactor?: number;
usePressure?: boolean;
color?: string; // default '#ffffff' for neutral preview
@@ -34,31 +35,6 @@ export interface BrushPreviewOptions {
const previewCache = new Map<string, HTMLCanvasElement>();
const MAX_CACHE_ENTRIES = 60;
-/**
- * Deterministic pseudo-random generator (mulberry32)
- * Ensures paper grain and flake distribution never flickers across re-renders.
- */
-function createPrng(seed: number) {
- let s = seed >>> 0;
- return function () {
- s = (s + 0x6d2b79f5) >>> 0;
- let t = Math.imul(s ^ (s >>> 15), 1 | s);
- t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
- };
-}
-
-/**
- * Generates an integer seed from a string identifier.
- */
-function hashString(str: string): number {
- let hash = 5381;
- for (let i = 0; i < str.length; i++) {
- hash = ((hash << 5) + hash + str.charCodeAt(i)) >>> 0;
- }
- return hash;
-}
-
/**
* Clamps a number between min and max.
*/
@@ -115,19 +91,22 @@ export function renderBrushStrokePreview(
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 pencilConfig = isPencil ? PENCIL_CONFIGS[preset as PencilGrade] : null;
- const size = options.size ?? (pencilConfig ? pencilConfig.defaultSize : 14);
- const flow = options.flow ?? (pencilConfig ? pencilConfig.flow : 0.85);
- const opacity = options.opacity ?? 1.0;
- const grain = options.grain ?? (pencilConfig ? pencilConfig.grain : 0);
- const hardness = options.hardness ?? (pencilConfig ? pencilConfig.hardness : 1.0);
- const minSizeFactor = options.minSizeFactor ?? (pencilConfig ? pencilConfig.minSizeFactor : 0.15);
+ const size = options.size ?? pencilConfig?.defaultSize ?? builtinCfg?.size ?? 14;
+ const flow = options.flow ?? pencilConfig?.flow ?? builtinCfg?.flow ?? 0.85;
+ const opacity = options.opacity ?? builtinCfg?.opacity ?? 1.0;
+ const grain = options.grain ?? pencilConfig?.grain ?? builtinCfg?.grain ?? 0;
+ const hardness = options.hardness ?? pencilConfig?.hardness ?? builtinCfg?.hardness ?? 1.0;
+ const minSizeFactor = options.minSizeFactor ?? pencilConfig?.minSizeFactor ?? builtinCfg?.minSizeFactor ?? 0.15;
+ const thickness = options.thickness ?? builtinCfg?.thickness ?? 1.0;
+ const customTipAngle = options.customTipAngle ?? builtinCfg?.customTipAngle ?? 0;
+ const spacing = options.spacing ?? builtinCfg?.spacing ?? (isPencil ? 0.07 : 0.045);
const isEraser = options.tool === 'eraser';
const strokeColor = options.color || '#ffffff';
const bgColor = options.backgroundColor || 'transparent';
- const builtinCfg = !options.customTipImage && options.preset ? getBuiltinBrushConfig(options.preset) : null;
const tipImage = options.customTipImage || builtinCfg?.customTipImage;
// Cache key
@@ -138,10 +117,11 @@ export function renderBrushStrokePreview(
opacity.toFixed(2),
grain.toFixed(2),
hardness.toFixed(2),
- (options.thickness ?? 1.0).toFixed(2),
+ thickness.toFixed(2),
+ customTipAngle.toFixed(1),
+ spacing.toFixed(3),
options.antiAlias !== undefined ? String(options.antiAlias) : '2',
options.spray?.enabled ? 'spray' : 'dab',
- options.customTipAngle?.toFixed(1) || '0',
tipImage ? 'custom-tip' : 'std',
isEraser ? '1' : '0',
options.wetEdge?.toFixed(2) || '0',
@@ -188,7 +168,6 @@ export function renderBrushStrokePreview(
const amp = Math.max(4, maxAmp);
const displayWidth = calculatePreviewWidth(size, cssHeight, isLiveCard);
- const [rCol, gCol, bCol] = parseRgba(strokeColor);
// Sample points along the S-curve
const numSteps = Math.min(120, Math.max(60, Math.round(cssWidth * 0.65)));
@@ -209,7 +188,7 @@ export function renderBrushStrokePreview(
// Dynamic tip taper for authentic pen release at the ends
const tipFactor = Math.min(1.0, Math.sin(Math.PI * u) * 2.8);
- const effMinSize = Math.max(0.08, minSizeFactor * tipFactor);
+ 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
@@ -220,115 +199,88 @@ export function renderBrushStrokePreview(
if (isEraser) {
// ERASER PREVIEW:
- // Render a subtle tone band or grid, with the eraser cleanly carving through it
+ // Render a subtle tone band, with the eraser cleanly carving through it
offCtx.save();
- offCtx.fillStyle = 'rgba(255, 255, 255, 0.15)';
+ offCtx.fillStyle = 'rgba(255, 255, 255, 0.18)';
offCtx.fillRect(padX - 4, centerY - amp - 4, strokeLength + 8, (amp + 4) * 2);
- offCtx.globalCompositeOperation = 'destination-out';
- offCtx.lineCap = 'round';
- offCtx.lineJoin = 'round';
- offCtx.strokeStyle = 'rgba(0, 0, 0, 1)';
+ const eraserMaster = getRadialDabMaster(hardness, '#000000', true);
+ const baseAngleRad = (customTipAngle * Math.PI) / 180;
+ const effSpacing = Math.max(0.02, Math.min(0.2, spacing));
+ let distanceAcc = 0;
for (let i = 0; i < pts.length - 1; i++) {
const p1 = pts[i];
const p2 = pts[i + 1];
- offCtx.beginPath();
- offCtx.lineWidth = (p1.width + p2.width) / 2;
- offCtx.moveTo(p1.x, p1.y);
- offCtx.lineTo(p2.x, p2.y);
- offCtx.stroke();
+ const segDist = Math.hypot(p2.x - p1.x, p2.y - p1.y);
+ const stepCount = Math.max(1, Math.ceil(segDist / 0.5));
+ for (let s = 0; s < stepCount; s++) {
+ const t = s / stepCount;
+ const curX = p1.x + t * (p2.x - p1.x);
+ const curY = p1.y + t * (p2.y - p1.y);
+ const curW = p1.width + t * (p2.width - p1.width);
+ const curTipAlpha = p1.tipAlpha + t * (p2.tipAlpha - p1.tipAlpha);
+
+ const requiredStep = Math.max(0.5, curW * effSpacing);
+ distanceAcc += segDist / stepCount;
+ if (distanceAcc >= requiredStep) {
+ distanceAcc = 0;
+ const stampW = Math.max(1.0, curW);
+ const stampH = stampW * thickness;
+ const alpha = clamp(opacity * flow * curTipAlpha, 0.05, 1.0);
+ drawSingleStamp(offCtx, eraserMaster, curX, curY, stampW, stampH, baseAngleRad, alpha, true, false);
+ }
+ }
}
offCtx.restore();
} else if (isPencil && pencilConfig) {
// PENCIL PHYSICS PREVIEW:
// Authentic cold-press paper grain tooth & micro-graphite flake distribution
- const seed = hashString(preset) ^ (Math.round(size * 10) << 8);
- const rand = createPrng(seed);
+ 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 pDensity = pencilConfig.particleDensity;
- const pSize = Math.max(1, pencilConfig.particleSize);
- const effectiveFlow = flow * pencilConfig.flow;
- const effectiveGrain = grain;
-
- offCtx.save();
- offCtx.globalAlpha = clamp(opacity, 0.05, 1.0);
+ const effFlow = flow * pencilConfig.flow;
+ const effSpacing = Math.max(0.02, Math.min(0.12, spacing));
- // 1. Soft underlying graphite lead tone for rich core
+ let distanceAcc = 0;
for (let i = 0; i < pts.length - 1; i++) {
const p1 = pts[i];
const p2 = pts[i + 1];
- const avgP = (p1.pressure + p2.pressure) / 2;
- const avgW = Math.max(0.8, (p1.width + p2.width) * 0.45);
- const segTipAlpha = (p1.tipAlpha + p2.tipAlpha) / 2;
- const coreAlpha = clamp(
- effectiveFlow * avgP * 0.35 * (1.1 - effectiveGrain * 0.3) * segTipAlpha,
- 0.02,
- 0.7
- );
-
- offCtx.beginPath();
- offCtx.lineCap = 'round';
- offCtx.lineJoin = 'round';
- offCtx.lineWidth = avgW;
- offCtx.strokeStyle = `rgba(${rCol}, ${gCol}, ${bCol}, ${coreAlpha.toFixed(3)})`;
- offCtx.moveTo(p1.x, p1.y);
- offCtx.lineTo(p2.x, p2.y);
- offCtx.stroke();
- }
-
- // 2. Cold-press paper tooth ridges catching micro-graphite flakes
- const stampStep = Math.max(1, Math.round(pts.length / 55));
- for (let i = 0; i < pts.length; i += stampStep) {
- const pt = pts[i];
- const radius = Math.max(0.8, pt.width / 2);
- const pressure = clamp(pt.pressure, 0.05, 1.0);
-
- const effectiveThreshold = Math.max(
- 15,
- baseThreshold - pressure * sens + (1 - effectiveGrain) * 45
- );
-
- // Flake count scales with pencil grade density and pressure
- const count = Math.max(
- 3,
- Math.round(radius * 3.6 * (pDensity / 12) * (0.55 + pressure * 0.65))
- );
-
- for (let p = 0; p < count; p++) {
- // Gaussian radial dispersion
- const u1 = Math.max(0.0001, rand());
- const u2 = rand();
- const r = radius * Math.sqrt(-2.0 * Math.log(u1)) * 0.46;
- const theta = 2.0 * Math.PI * u2;
-
- const flakeSize = Math.max(0.9, pSize);
- const px = pt.x + r * Math.cos(theta);
- const py = pt.y + r * Math.sin(theta);
-
- // World-anchored cold-press paper grain lookup
- // Coords scaled by 1.6 so paper tooth is clearly visible in preview
- const paperHeight = getPaperGrain(px * 1.6, py * 1.6);
-
- if (paperHeight >= effectiveThreshold) {
- const heightFactor = Math.min(1.0, (paperHeight - effectiveThreshold + 24) / 52);
- const distFactor = Math.max(0.12, 1 - r / (radius * 1.25));
- const flakeJitter = 0.86 + rand() * 0.28;
- const alpha = clamp(
- effectiveFlow * pressure * heightFactor * distFactor * flakeJitter * 0.95 * pt.tipAlpha,
- 0.03,
- 1.0
+ const segDist = Math.hypot(p2.x - p1.x, p2.y - p1.y);
+ const stepCount = Math.max(1, Math.ceil(segDist / 0.6));
+ for (let s = 0; s < stepCount; s++) {
+ const t = s / stepCount;
+ const curX = p1.x + t * (p2.x - p1.x);
+ const curY = p1.y + t * (p2.y - p1.y);
+ const curW = p1.width + t * (p2.width - p1.width);
+ const curP = p1.pressure + t * (p2.pressure - p1.pressure);
+ const curTipAlpha = p1.tipAlpha + t * (p2.tipAlpha - p1.tipAlpha);
+
+ const requiredStep = Math.max(0.4, curW * effSpacing);
+ distanceAcc += segDist / stepCount;
+ if (distanceAcc >= requiredStep) {
+ distanceAcc = 0;
+ const paperHeight = getPaperGrain(curX * 1.6, curY * 1.6);
+ const effThreshold = Math.max(
+ 15,
+ baseThreshold - curP * sens + (1 - grain) * 40
);
- offCtx.fillStyle = `rgba(${rCol}, ${gCol}, ${bCol}, ${alpha.toFixed(3)})`;
- offCtx.fillRect(
- px - flakeSize / 2,
- py - flakeSize / 2,
- flakeSize,
- flakeSize
- );
+ 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);
+ }
}
}
}
@@ -336,104 +288,121 @@ export function renderBrushStrokePreview(
} else if (tipImage) {
// TEXTURED CUSTOM BRUSH PREVIEW (Clip Studio Paint Tip & Builtin Presets):
const tip = tipImage;
- const thickness = options.thickness ?? 1.0;
const aspect =
((tip.naturalHeight || tip.height || 1) / (tip.naturalWidth || tip.width || 1)) * thickness;
- const effFlow = clamp(flow, 0.05, 1.0);
const baseAngleRad = (((options.customTipAngle ?? 0)) * Math.PI) / 180;
const master = getTintedTipMaster(tip, strokeColor);
+ const effSpacing = Math.max(0.02, Math.min(0.2, spacing));
offCtx.save();
if (options.antiAlias === 0) {
offCtx.imageSmoothingEnabled = false;
}
- const stepInterval = Math.max(1, Math.round(pts.length / 45));
-
- for (let i = 0; i < pts.length; i += stepInterval) {
- const pt = pts[i];
- const stampW = Math.max(1.5, pt.width);
- const stampH = stampW * aspect;
- const alpha = clamp(opacity * effFlow * pt.tipAlpha, 0.03, 1.0);
-
- offCtx.save();
- offCtx.globalAlpha = alpha;
-
- 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,
- pt.x + r * Math.cos(th) - pSize / 2,
- pt.y + r * Math.sin(th) - (pSize * aspect) / 2,
- pSize,
- pSize * aspect
- );
- }
- } else {
- offCtx.translate(pt.x, pt.y);
- if (baseAngleRad !== 0) {
- offCtx.rotate(baseAngleRad);
+
+ let distanceAcc = 0;
+ for (let i = 0; i < pts.length - 1; i++) {
+ const p1 = pts[i];
+ const p2 = pts[i + 1];
+ const segDist = Math.hypot(p2.x - p1.x, p2.y - p1.y);
+ const stepCount = Math.max(1, Math.ceil(segDist / 0.6));
+ for (let s = 0; s < stepCount; s++) {
+ const t = s / stepCount;
+ const curX = p1.x + t * (p2.x - p1.x);
+ const curY = p1.y + t * (p2.y - p1.y);
+ const curW = p1.width + t * (p2.width - p1.width);
+ const curTipAlpha = p1.tipAlpha + t * (p2.tipAlpha - p1.tipAlpha);
+
+ const requiredStep = Math.max(0.6, 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);
+
+ 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);
+ }
}
- offCtx.drawImage(master, -stampW / 2, -stampH / 2, stampW, stampH);
}
- offCtx.restore();
}
offCtx.restore();
} else {
- // ROUND INK BRUSH PREVIEW:
- // Smooth, solid, clean line with tapered ends and hardness falloff
+ // ROUND INK & ANALYTICAL DAB BRUSH PREVIEW (Airbrush, G-Pen, Maru Pen, Turnip Pen, Flat Marker, Round):
offCtx.save();
- offCtx.lineCap = 'round';
- offCtx.lineJoin = 'round';
-
- const effHardness = clamp(hardness, 0.05, 1.0);
- const effFlow = clamp(flow, 0.05, 1.0);
- offCtx.globalAlpha = clamp(opacity * effFlow, 0.05, 1.0);
-
- if (effHardness < 0.96) {
- // Soft / feathered edge (airbrush-like)
- offCtx.shadowBlur = (1 - effHardness) * Math.max(1, displayWidth * 0.6);
- offCtx.shadowColor = `rgba(${rCol}, ${gCol}, ${bCol}, ${(effFlow * 0.9).toFixed(3)})`;
- }
+ const effHardness = clamp(hardness, 0.0, 1.0);
+ const effFlow = clamp(flow, 0.01, 1.0);
+ const master = getRadialDabMaster(effHardness, strokeColor);
+ const baseAngleRad = (customTipAngle * Math.PI) / 180;
+ const effSpacing = Math.max(0.02, Math.min(0.2, spacing));
- offCtx.strokeStyle = strokeColor;
-
- // CSP Wet Edge (Water Edge) rim effect in preview
+ // Optional CSP Wet Edge rim
if (options.wetEdge && options.wetEdge > 0.05) {
- offCtx.save();
- offCtx.strokeStyle = `rgba(${Math.round(rCol * 0.6)}, ${Math.round(gCol * 0.6)}, ${Math.round(bCol * 0.6)}, ${(clamp(opacity * effFlow, 0.1, 1.0) * (0.35 + options.wetEdge * 0.55)).toFixed(3)})`;
+ const rimMaster = getRadialDabMaster(Math.min(1.0, effHardness + 0.1), strokeColor);
+ let wetAcc = 0;
for (let i = 0; i < pts.length - 1; i++) {
const p1 = pts[i];
const p2 = pts[i + 1];
- const avgW = (p1.width + p2.width) / 2;
- offCtx.beginPath();
- offCtx.lineWidth = avgW + 1.2;
- offCtx.moveTo(p1.x, p1.y);
- offCtx.lineTo(p2.x, p2.y);
- offCtx.stroke();
+ const segDist = Math.hypot(p2.x - p1.x, p2.y - p1.y);
+ const stepCount = Math.max(1, Math.ceil(segDist / 0.6));
+ for (let s = 0; s < stepCount; s++) {
+ const t = s / stepCount;
+ const curX = p1.x + t * (p2.x - p1.x);
+ const curY = p1.y + t * (p2.y - p1.y);
+ const curW = (p1.width + t * (p2.width - p1.width)) * (1.0 + options.wetEdge * 0.22);
+ const curTipAlpha = p1.tipAlpha + t * (p2.tipAlpha - p1.tipAlpha);
+
+ const requiredStep = Math.max(0.6, curW * effSpacing * 1.5);
+ 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);
+ }
+ }
}
- offCtx.restore();
}
- // Draw tapered segments with calligraphic tip alpha
+ let distanceAcc = 0;
for (let i = 0; i < pts.length - 1; i++) {
const p1 = pts[i];
const p2 = pts[i + 1];
- const avgW = (p1.width + p2.width) / 2;
- const segTipAlpha = (p1.tipAlpha + p2.tipAlpha) / 2;
-
- offCtx.save();
- offCtx.globalAlpha = clamp(opacity * effFlow * segTipAlpha, 0.05, 1.0);
- offCtx.beginPath();
- offCtx.lineWidth = avgW;
- offCtx.moveTo(p1.x, p1.y);
- offCtx.lineTo(p2.x, p2.y);
- offCtx.stroke();
- offCtx.restore();
+ const segDist = Math.hypot(p2.x - p1.x, p2.y - p1.y);
+ const stepCount = Math.max(1, Math.ceil(segDist / 0.6));
+ for (let s = 0; s < stepCount; s++) {
+ const t = s / stepCount;
+ const curX = p1.x + t * (p2.x - p1.x);
+ const curY = p1.y + t * (p2.y - p1.y);
+ const curW = p1.width + t * (p2.width - p1.width);
+ const curTipAlpha = p1.tipAlpha + t * (p2.tipAlpha - p1.tipAlpha);
+
+ const requiredStep = Math.max(0.5, curW * effSpacing);
+ distanceAcc += segDist / stepCount;
+ if (distanceAcc >= requiredStep) {
+ distanceAcc = 0;
+ const stampW = Math.max(0.8, curW);
+ const stampH = stampW * thickness;
+ const alpha = clamp(opacity * effFlow * curTipAlpha, 0.02, 1.0);
+ drawSingleStamp(offCtx, master, curX, curY, stampW, stampH, baseAngleRad, alpha);
+ }
+ }
}
offCtx.restore();
}
diff --git a/src/utils/canvasUtils.ts b/src/utils/canvasUtils.ts
index cbe2a2f..f667561 100644
--- a/src/utils/canvasUtils.ts
+++ b/src/utils/canvasUtils.ts
@@ -1,7 +1,16 @@
import { Point, CanvasDimensions, BlendMode, ToolType, BrushSettings, CanvasColorMode, LayerItem } from '../types/editor';
import { enforceColorMode } from './colorUtils';
import { drawPencilCubicBezierSegment, drawPencilDot, PencilGrade } from './pencilEngine';
-import { renderCompleteTexturedStroke, TexturedBrushOptions } from './stampEngine';
+import {
+ renderCompleteTexturedStroke,
+ TexturedBrushOptions,
+ drawRadialCubicBezierSegment,
+ drawRadialDot,
+ centripetalCatmullRomToBezier,
+ renderCompleteRadialStroke,
+ RadialMixingOptions,
+} from './stampEngine';
+import { LayerPixelSampler, PaintReservoir } from './colorMixingEngine';
import { evaluateCspSpline } from './sutParser';
export const CANVAS_2D_CONTEXT_OPTIONS: CanvasRenderingContext2DSettings = {
@@ -98,7 +107,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.
- * Includes centripetal chord bounding to prevent overshooting or loops on tight turns.
+ * Uses centripetal parameterization (alpha = 0.5) to prevent overshooting or loops on tight turns.
*/
export function catmullRomToBezier(
p0: Point,
@@ -106,50 +115,12 @@ export function catmullRomToBezier(
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;
-
- // Prevent overshoot on tight turns or uneven knot spacing
- 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 };
+ return centripetalCatmullRomToBezier(p0, p1, p2, p3);
}
/**
- * Draws a smooth tapered segment along a cubic Bézier curve.
- * Gives 120+ FPS instantaneous rendering like Clip Studio Paint.
+ * 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,
@@ -161,76 +132,29 @@ export function drawSmoothCubicBezierSegment(
isEraser: boolean = false,
hardness: number = 1.0,
flow: number = 1.0,
- _spacing: number = 0.1
-) {
- const dx = p3.x - p0.x;
- const dy = p3.y - p0.y;
- const dist = Math.hypot(dx, dy);
-
- if (dist < 0.15) return;
-
- const avgWidth = (p0.width + p3.width) / 2;
- const widthDiff = Math.abs(p3.width - p0.width);
-
- ctx.save();
- ctx.lineCap = 'round';
- ctx.lineJoin = 'round';
-
- if (flow < 0.999) {
- ctx.globalAlpha = Math.max(0.01, Math.min(1.0, flow));
- }
-
- if (isEraser) {
- ctx.globalCompositeOperation = 'destination-out';
- ctx.strokeStyle = 'rgba(0, 0, 0, 1)';
- } else {
- ctx.globalCompositeOperation = 'source-over';
- ctx.strokeStyle = color;
- }
-
- const effectiveHardness = Math.min(Math.max(hardness, 0.05), 1.0);
- if (effectiveHardness < 0.98) {
- ctx.shadowBlur = (1 - effectiveHardness) * Math.max(1, avgWidth * 0.45);
- ctx.shadowColor = isEraser ? 'rgba(0, 0, 0, 1)' : color;
- }
-
- // Fast-path: native cubic Bézier when width change is small
- if (widthDiff <= 1.5 || dist <= 12) {
- ctx.beginPath();
- ctx.lineWidth = avgWidth;
- ctx.moveTo(p0.x, p0.y);
- ctx.bezierCurveTo(c1.x, c1.y, c2.x, c2.y, p3.x, p3.y);
- ctx.stroke();
- ctx.restore();
- return;
- }
-
- // Tapered stroke when width changes significantly: adaptive cubic steps
- const steps = dist > 32 ? 4 : 2;
- let prevPt = { x: p0.x, y: p0.y, width: p0.width };
-
- for (let i = 1; i <= steps; i++) {
- const t = i / steps;
- const invT = 1.0 - t;
- const invT2 = invT * invT;
- const invT3 = invT2 * invT;
- const t2 = t * t;
- const t3 = t2 * t;
-
- const currX = invT3 * p0.x + 3.0 * invT2 * t * c1.x + 3.0 * invT * t2 * c2.x + t3 * p3.x;
- const currY = invT3 * p0.y + 3.0 * invT2 * t * c1.y + 3.0 * invT * t2 * c2.y + t3 * p3.y;
- const currWidth = invT * p0.width + t * p3.width;
-
- ctx.beginPath();
- ctx.lineWidth = (prevPt.width + currWidth) / 2;
- ctx.moveTo(prevPt.x, prevPt.y);
- ctx.lineTo(currX, currY);
- ctx.stroke();
-
- prevPt = { x: currX, y: currY, width: currWidth };
- }
-
- ctx.restore();
+ spacing: number = 0.06,
+ remainderDist: number = 0,
+ thickness: number = 1.0,
+ angleRad: number = 0,
+ mixingOptions?: RadialMixingOptions
+): number {
+ return drawRadialCubicBezierSegment(
+ ctx,
+ p0,
+ c1,
+ c2,
+ p3,
+ color,
+ hardness,
+ flow,
+ spacing,
+ isEraser,
+ false,
+ remainderDist,
+ thickness,
+ angleRad,
+ mixingOptions
+ );
}
/**
@@ -245,8 +169,9 @@ export function drawSmoothBezierSegment(
isEraser: boolean = false,
hardness: number = 1.0,
flow: number = 1.0,
- spacing: number = 0.1
-) {
+ spacing: number = 0.06,
+ remainderDist: number = 0
+): number {
const c1: Point = {
x: start.x + (2.0 / 3.0) * (control.x - start.x),
y: start.y + (2.0 / 3.0) * (control.y - start.y),
@@ -259,7 +184,7 @@ export function drawSmoothBezierSegment(
pressure: end.pressure + (2.0 / 3.0) * (control.pressure - end.pressure),
width: end.width + (2.0 / 3.0) * (control.width - end.width),
};
- drawSmoothCubicBezierSegment(ctx, start, c1, c2, end, color, isEraser, hardness, flow, spacing);
+ return drawSmoothCubicBezierSegment(ctx, start, c1, c2, end, color, isEraser, hardness, flow, spacing, remainderDist);
}
/**
@@ -271,30 +196,10 @@ export function drawDot(
color: string,
isEraser: boolean = false,
hardness: number = 1.0,
- flow: number = 1.0
+ flow: number = 1.0,
+ mixingOptions?: RadialMixingOptions
) {
- ctx.save();
- if (flow < 0.999) {
- ctx.globalAlpha = Math.max(0.01, Math.min(1.0, flow));
- }
- if (isEraser) {
- ctx.globalCompositeOperation = 'destination-out';
- ctx.fillStyle = 'rgba(0, 0, 0, 1)';
- } else {
- ctx.globalCompositeOperation = 'source-over';
- ctx.fillStyle = color;
- }
-
- const effectiveHardness = Math.min(Math.max(hardness, 0.05), 1.0);
- if (effectiveHardness < 0.98) {
- ctx.shadowBlur = (1 - effectiveHardness) * Math.max(1, point.width * 0.45);
- ctx.shadowColor = isEraser ? 'rgba(0, 0, 0, 1)' : color;
- }
-
- ctx.beginPath();
- ctx.arc(point.x, point.y, Math.max(0.5, point.width / 2), 0, Math.PI * 2);
- ctx.fill();
- ctx.restore();
+ drawRadialDot(ctx, point, color, hardness, flow, isEraser, false, mixingOptions);
}
let _sharedThumbCanvas: HTMLCanvasElement | null = null;
@@ -552,13 +457,69 @@ export function getReusableBakeCanvas(minWidth: number, minHeight: number): HTML
* 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?: {
+ useIn?: boolean;
+ useOut?: boolean;
+ inCount?: number;
+ outCount?: number;
+ minSizeFactor?: number;
+ exitSpeed?: number;
+ }
+): Point[] {
+ if (points.length < 2) return points;
+
+ 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++) {
+ const u = (i + 1) / (inCount + 1);
+ const taper = Math.sin((u * Math.PI) / 2);
+ const factor = minRatio + (1.0 - minRatio) * taper;
+ points[i].width *= factor;
+ points[i].pressure *= factor;
+ }
+ }
+
+ // Out-taper (exit / lift-off)
+ const useOut = options?.useOut ?? true;
+ if (useOut) {
+ let outCount = options?.outCount ?? 6;
+ if (options?.exitSpeed && options.exitSpeed > 0.8) {
+ outCount = Math.min(Math.floor(n / 2), Math.round(outCount * Math.min(2.5, options.exitSpeed)));
+ }
+ 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 u = (step + 1) / (outCount + 1);
+ const taper = Math.sin((u * Math.PI) / 2);
+ const factor = minRatio + (1.0 - minRatio) * taper;
+ points[i].width *= factor;
+ points[i].pressure *= factor;
+ }
+ }
+
+ return points;
+}
+
export function renderCompleteStroke(
ctx: CanvasRenderingContext2D,
points: Point[],
brushSettings: BrushSettings,
tool: ToolType,
colorMode: CanvasColorMode = 'color',
- isBgEraser: boolean = false
+ isBgEraser: boolean = false,
+ underlyingCanvas?: HTMLCanvasElement,
+ alphaLocked: boolean = false
) {
if (!points || points.length === 0) return;
@@ -568,6 +529,7 @@ export function renderCompleteStroke(
const strokeHardness = colorMode === 'monochrome' ? 1.0 : (brushSettings.hardness ?? 1.0);
const strokeFlow = brushSettings.flow ?? 1.0;
const strokeSpacing = brushSettings.spacing ?? 0.08;
+ const isTransparentInk = Boolean(brushSettings.isTransparentInk);
// Textured Custom Tip (Clip Studio Paint SUT Brush)
if (brushSettings.customTipImage) {
@@ -606,9 +568,13 @@ export function renderCompleteStroke(
paperTextureScale: brushSettings.paperTextureScale,
paperTextureRotate: brushSettings.paperTextureRotate,
useGpu: false,
- underlyingCanvas: ctx.canvas,
+ underlyingCanvas: underlyingCanvas || ctx.canvas,
+ sampler: underlyingCanvas ? new LayerPixelSampler(underlyingCanvas) : undefined,
+ reservoir: (brushSettings.colorMixing && !isEraser) ? new PaintReservoir(strokeColor) : undefined,
isEraser: isEraser && !isBgEraser,
isBgEraser,
+ alphaLocked,
+ isTransparentInk,
};
renderCompleteTexturedStroke(ctx, points, strokeColor, brushSettings.customTipImage, tipOptions);
return;
@@ -624,16 +590,32 @@ export function renderCompleteStroke(
grade,
brushSettings.flow ?? 0.74,
brushSettings.grain ?? 1.0,
- brushSettings.hardness
+ brushSettings.hardness,
+ 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: underlyingCanvas ? new LayerPixelSampler(underlyingCanvas) : undefined,
+ reservoir: (brushSettings.colorMixing && !isEraser) ? new PaintReservoir(strokeColor) : undefined,
+ alphaLocked,
+ isTransparentInk,
+ };
+
drawDot(
ctx,
points[0],
strokeColor,
isEraser && !isBgEraser,
strokeHardness,
- strokeFlow
+ strokeFlow,
+ radialMixing
);
}
@@ -650,7 +632,7 @@ export function renderCompleteStroke(
const p0 = points[0];
const p1 = points[1];
const { c1, c2 } = catmullRomToBezier(p0, p0, p1, p1);
- drawPencilCubicBezierSegment(ctx, p0, c1, c2, p1, strokeColor, grade, pFlow, pGrain, brushSettings.hardness);
+ drawPencilCubicBezierSegment(ctx, p0, c1, c2, p1, strokeColor, grade, pFlow, pGrain, brushSettings.hardness, 0, alphaLocked, isTransparentInk);
return;
}
@@ -658,11 +640,11 @@ export function renderCompleteStroke(
const p1 = points[1];
const p2 = points[2];
const first = catmullRomToBezier(p0, p0, p1, p2);
- drawPencilCubicBezierSegment(ctx, p0, first.c1, first.c2, p1, strokeColor, grade, pFlow, pGrain, brushSettings.hardness);
+ drawPencilCubicBezierSegment(ctx, p0, first.c1, first.c2, p1, strokeColor, grade, pFlow, pGrain, brushSettings.hardness, 0, alphaLocked, isTransparentInk);
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);
+ drawPencilCubicBezierSegment(ctx, points[i - 1], seg.c1, seg.c2, points[i], strokeColor, grade, pFlow, pGrain, brushSettings.hardness, 0, alphaLocked, isTransparentInk);
}
const n = points.length;
@@ -670,61 +652,34 @@ export function renderCompleteStroke(
const pPrev = points[n - 2];
const pLast = points[n - 1];
const last = catmullRomToBezier(pPrev2, pPrev, pLast, pLast);
- drawPencilCubicBezierSegment(ctx, pPrev, last.c1, last.c2, pLast, strokeColor, grade, pFlow, pGrain, brushSettings.hardness);
- } else if (brushSettings.smoothing) {
- if (points.length === 2) {
- const p0 = points[0];
- const p1 = points[1];
- const { c1, c2 } = catmullRomToBezier(p0, p0, p1, p1);
- drawSmoothCubicBezierSegment(ctx, p0, c1, c2, p1, strokeColor, isEraser && !isBgEraser, strokeHardness, strokeFlow, strokeSpacing);
- return;
- }
-
- const p0 = points[0];
- const p1 = points[1];
- const p2 = points[2];
- const first = catmullRomToBezier(p0, p0, p1, p2);
- drawSmoothCubicBezierSegment(ctx, p0, first.c1, first.c2, p1, strokeColor, isEraser && !isBgEraser, strokeHardness, strokeFlow, strokeSpacing);
-
- for (let i = 2; i < points.length - 1; i++) {
- const seg = catmullRomToBezier(points[i - 2], points[i - 1], points[i], points[i + 1]);
- drawSmoothCubicBezierSegment(ctx, points[i - 1], seg.c1, seg.c2, points[i], strokeColor, isEraser && !isBgEraser, strokeHardness, strokeFlow, strokeSpacing);
- }
-
- const n = points.length;
- const pPrev2 = points[n - 3];
- const pPrev = points[n - 2];
- const pLast = points[n - 1];
- const last = catmullRomToBezier(pPrev2, pPrev, pLast, pLast);
- drawSmoothCubicBezierSegment(ctx, pPrev, last.c1, last.c2, pLast, strokeColor, isEraser && !isBgEraser, strokeHardness, strokeFlow, strokeSpacing);
+ drawPencilCubicBezierSegment(ctx, pPrev, last.c1, last.c2, pLast, strokeColor, grade, pFlow, pGrain, brushSettings.hardness, 0, alphaLocked, isTransparentInk);
} else {
- ctx.save();
- ctx.lineCap = 'round';
- ctx.lineJoin = 'round';
- if (strokeFlow < 0.999) {
- ctx.globalAlpha = Math.max(0.01, Math.min(1.0, strokeFlow));
- }
- if (isBgEraser) {
- ctx.globalCompositeOperation = 'source-over';
- ctx.strokeStyle = '#ffffff';
- } else if (isEraser) {
- ctx.globalCompositeOperation = 'destination-out';
- ctx.strokeStyle = 'rgba(0, 0, 0, 1)';
- } else {
- ctx.globalCompositeOperation = 'source-over';
- ctx.strokeStyle = strokeColor;
- }
+ const radialMixing: RadialMixingOptions = {
+ colorMixing: brushSettings.colorMixing,
+ amountOfPaint: brushSettings.amountOfPaint,
+ densityOfPaint: brushSettings.densityOfPaint,
+ colorStretch: brushSettings.colorStretch,
+ mixingMode: brushSettings.mixingMode,
+ underlyingCanvas: underlyingCanvas || ctx.canvas,
+ sampler: underlyingCanvas ? new LayerPixelSampler(underlyingCanvas) : undefined,
+ reservoir: (brushSettings.colorMixing && !isEraser) ? new PaintReservoir(strokeColor) : undefined,
+ alphaLocked,
+ isTransparentInk,
+ };
- for (let i = 1; i < points.length; i++) {
- const pPrev = points[i - 1];
- const pCurr = points[i];
- ctx.lineWidth = (pPrev.width + pCurr.width) / 2;
- ctx.beginPath();
- ctx.moveTo(pPrev.x, pPrev.y);
- ctx.lineTo(pCurr.x, pCurr.y);
- ctx.stroke();
- }
- ctx.restore();
+ renderCompleteRadialStroke(
+ ctx,
+ points,
+ strokeColor,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
+ isEraser && !isBgEraser,
+ isBgEraser,
+ brushSettings.thickness ?? 1.0,
+ ((brushSettings.customTipAngle ?? 0) * Math.PI) / 180,
+ radialMixing
+ );
}
}
diff --git a/src/utils/compositor.ts b/src/utils/compositor.ts
new file mode 100644
index 0000000..8fa6ed8
--- /dev/null
+++ b/src/utils/compositor.ts
@@ -0,0 +1,941 @@
+/**
+ * Unified GPU Viewport Compositor
+ *
+ * Replaces the multi-canvas DOM stack with a single viewport-sized GPU canvas.
+ * Performs frustum culling to only render tiles overlapping the screen frustum,
+ * executes all 12 Photoshop/CSP blend modes in fragment shaders, applies document affine
+ * transforms (pan, zoom, rotation) directly in vertex shaders, and integrates
+ * anti-moiré screentones, vector layers, and comic frame clipping.
+ */
+
+import { LayerItem, CanvasDimensions, BlendMode, CanvasColorMode } from '../types/editor';
+import { SparseTileGrid, TILE_SIZE, TileBuffer, globalTileGrid } from './tileEngine';
+
+export interface ViewportTransform {
+ pan: { x: number; y: number };
+ zoom: number;
+ rotation: number; // in degrees
+}
+
+export const BLEND_MODE_MAP: Record<BlendMode, number> = {
+ normal: 0,
+ multiply: 1,
+ screen: 2,
+ overlay: 3,
+ darken: 4,
+ lighten: 5,
+ 'color-dodge': 6,
+ 'color-burn': 7,
+ 'hard-light': 8,
+ 'soft-light': 9,
+ difference: 10,
+ exclusion: 11,
+};
+
+export interface LayerRenderGroup {
+ baseLayer: LayerItem;
+ clippedLayers: LayerItem[];
+}
+
+/**
+ * Groups consecutive clipped layers under their immediate non-clipped base layer underneath.
+ * Layers are provided in bottom-to-top rendering order.
+ */
+export function groupLayersForCompositing(layersBottomToTop: LayerItem[]): LayerRenderGroup[] {
+ const groups: LayerRenderGroup[] = [];
+ let currentGroup: LayerRenderGroup | null = null;
+
+ for (const layer of layersBottomToTop) {
+ if (layer.clipped && currentGroup) {
+ currentGroup.clippedLayers.push(layer);
+ } else {
+ currentGroup = {
+ baseLayer: layer,
+ clippedLayers: [],
+ };
+ groups.push(currentGroup);
+ }
+ }
+
+ return groups;
+}
+
+// Vertex Shader: Affine transformation in document space mapped to WebGL clip space
+export const COMPOSITOR_VERTEX_SHADER = `#version 300 es
+precision highp float;
+
+in vec2 a_quadPos; // [0, 1] x [0, 1]
+uniform vec2 u_tileOrigin; // tile position in document space
+uniform vec2 u_tileSize; // tile or quad size in document space
+uniform vec2 u_docDimensions; // canvas width, height
+uniform vec2 u_viewportSize; // viewport width, height
+uniform vec2 u_pan;
+uniform float u_zoom;
+uniform float u_rotationRad;
+uniform float u_dpr;
+
+out vec2 v_texCoord;
+out vec2 v_docCoord;
+
+void main() {
+ v_texCoord = a_quadPos;
+
+ // Position within document space
+ vec2 docPos = u_tileOrigin + a_quadPos * u_tileSize;
+ v_docCoord = docPos;
+
+ // Center document around (0, 0)
+ vec2 centered = docPos - u_docDimensions * 0.5;
+
+ // Rotate
+ float cosR = cos(u_rotationRad);
+ float sinR = sin(u_rotationRad);
+ vec2 rotated = vec2(
+ centered.x * cosR - centered.y * sinR,
+ centered.x * sinR + centered.y * cosR
+ );
+
+ // Scale and translate: convert CSS screen coordinates to physical device pixels
+ vec2 screenPos = (u_pan + rotated * u_zoom) * u_dpr;
+
+ // Convert physical device pixels to WebGL clip coordinates [-1, 1]
+ vec2 clipPos = vec2(
+ (2.0 * screenPos.x / u_viewportSize.x) - 1.0,
+ 1.0 - (2.0 * screenPos.y / u_viewportSize.y)
+ );
+
+ gl_Position = vec4(clipPos, 0.0, 1.0);
+}
+`;
+
+// Fragment Shader: Layer Blending, Screentones with Anti-Moiré, and Layer Color Tinting
+export const COMPOSITOR_FRAGMENT_SHADER = `#version 300 es
+precision highp float;
+
+in vec2 v_texCoord;
+in vec2 v_docCoord;
+
+uniform sampler2D u_tileTexture;
+uniform float u_layerOpacity;
+uniform int u_blendMode;
+
+// Background Uniforms
+uniform int u_isBackground;
+uniform int u_showCheckerboard;
+
+// Screentone Uniforms
+uniform int u_toneEnabled;
+uniform float u_toneFrequency;
+uniform float u_toneAngleRad;
+uniform float u_toneDpi;
+uniform int u_toneDotShape;
+uniform float u_toneDensity;
+uniform int u_toneDensityType;
+uniform float u_zoom;
+
+// Layer Tint Uniforms
+uniform int u_layerColorEnabled;
+uniform vec3 u_layerColor;
+uniform vec3 u_layerSubColor;
+
+out vec4 fragColor;
+
+float fractVal(float x) {
+ return x - floor(x);
+}
+
+vec4 evaluateScreentone(vec4 srcColor, vec2 docCoord) {
+ if (srcColor.a < 0.0039) {
+ return vec4(0.0);
+ }
+
+ float density;
+ if (u_toneDensityType == 0) {
+ // Specified density
+ density = clamp(u_toneDensity * srcColor.a, 0.0, 1.0);
+ } else {
+ // Luminance
+ float lum = dot(srcColor.rgb, vec3(0.299, 0.587, 0.114));
+ density = clamp((1.0 - lum) * srcColor.a, 0.0, 1.0);
+ }
+
+ if (density <= 0.001) return vec4(0.0);
+ if (density >= 0.999) return vec4(0.0, 0.0, 0.0, 1.0);
+
+ float cellSize = max(3.5, u_toneDpi / max(1.0, u_toneFrequency));
+ float cosA = cos(u_toneAngleRad);
+ float sinA = sin(u_toneAngleRad);
+
+ float xr = docCoord.x * cosA - docCoord.y * sinA;
+ float yr = docCoord.x * sinA + docCoord.y * cosA;
+
+ float u = fractVal(xr / cellSize) - 0.5;
+ float v = fractVal(yr / cellSize) - 0.5;
+
+ float spot;
+ if (u_toneDotShape == 2) {
+ // Line
+ spot = 1.0 - 2.0 * abs(u);
+ } else if (u_toneDotShape == 3) {
+ // Diamond
+ spot = 1.0 - (abs(u) + abs(v));
+ } else {
+ // Euclidean circle
+ float absU = abs(u);
+ float absV = abs(v);
+ if (absU + absV <= 0.5) {
+ spot = 1.0 - 2.0 * (u * u + v * v);
+ } else {
+ float uc = absU - 0.5;
+ float vc = absV - 0.5;
+ spot = 2.0 * (uc * uc + vc * vc);
+ }
+ }
+
+ float diff = spot - (1.0 - density);
+ float halfSpan = min(0.25, 0.75 / cellSize);
+ float coverage = clamp(diff / (2.0 * halfSpan) + 0.5, 0.0, 1.0);
+ vec4 halftoneColor = vec4(0.0, 0.0, 0.0, coverage);
+
+ // Anti-moiré smoothstep crossfading
+ float moireBlend = smoothstep(0.35, 0.95, u_zoom);
+ vec4 contColor = vec4(0.0, 0.0, 0.0, density);
+ return mix(contColor, halftoneColor, moireBlend);
+}
+
+vec4 applyLayerTint(vec4 color) {
+ if (u_layerColorEnabled == 0) return color;
+ float lum = dot(color.rgb, vec3(0.299, 0.587, 0.114));
+ vec3 tinted = mix(u_layerColor, u_layerSubColor, lum);
+ return vec4(tinted, color.a);
+}
+
+void main() {
+ if (u_isBackground == 1) {
+ if (u_showCheckerboard == 1) {
+ vec2 checkCoord = floor(v_docCoord / 16.0);
+ float check = mod(checkCoord.x + checkCoord.y, 2.0);
+ vec3 checkColor = check > 0.5 ? vec3(0.157, 0.157, 0.157) : vec3(0.125, 0.125, 0.125);
+ fragColor = vec4(checkColor, 1.0);
+ } else {
+ fragColor = vec4(1.0, 1.0, 1.0, 1.0);
+ }
+ return;
+ }
+
+ vec4 texColor = texture(u_tileTexture, v_texCoord);
+
+ if (texColor.a < 0.002) {
+ discard;
+ }
+
+ vec4 finalColor = texColor;
+
+ if (u_toneEnabled == 1) {
+ finalColor = evaluateScreentone(texColor, v_docCoord);
+ }
+
+ if (u_layerColorEnabled == 1) {
+ finalColor = applyLayerTint(finalColor);
+ }
+
+ finalColor.a *= u_layerOpacity;
+
+ if (finalColor.a < 0.002) {
+ discard;
+ }
+
+ fragColor = vec4(finalColor.rgb * finalColor.a, finalColor.a);
+}
+`;
+
+export interface CompositorOptions {
+ dimensions: CanvasDimensions;
+ colorMode?: CanvasColorMode;
+ showCheckerboard?: boolean;
+ devicePixelRatio?: number;
+}
+
+/**
+ * Calculates the document-space bounding box visible in the current camera viewport.
+ * Performs frustum culling.
+ */
+export function calculateVisibleDocumentBounds(
+ viewportW: number,
+ viewportH: number,
+ transform: ViewportTransform,
+ docW: number,
+ docH: number
+): { minX: number; minY: number; maxX: number; maxY: number } {
+ const { pan, zoom, rotation } = transform;
+ const rad = (-rotation * Math.PI) / 180;
+ const cosR = Math.cos(rad);
+ const sinR = Math.sin(rad);
+
+ // Screen corners relative to screen center/pan
+ const corners = [
+ { x: 0, y: 0 },
+ { x: viewportW, y: 0 },
+ { x: viewportW, y: viewportH },
+ { x: 0, y: viewportH },
+ ];
+
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+
+ for (const c of corners) {
+ // Invert translate
+ const dx = c.x - pan.x;
+ const dy = c.y - pan.y;
+
+ // Invert zoom
+ const sx = dx / Math.max(0.001, zoom);
+ const sy = dy / Math.max(0.001, zoom);
+
+ // Invert rotation
+ const rx = sx * cosR - sy * sinR;
+ const ry = sx * sinR + sy * cosR;
+
+ // Invert center offset
+ const docX = rx + docW * 0.5;
+ const docY = ry + docH * 0.5;
+
+ if (docX < minX) minX = docX;
+ if (docY < minY) minY = docY;
+ if (docX > maxX) maxX = docX;
+ if (docY > maxY) maxY = docY;
+ }
+
+ return {
+ minX: Math.max(0, Math.floor(minX)),
+ minY: Math.max(0, Math.floor(minY)),
+ maxX: Math.min(docW, Math.ceil(maxX)),
+ maxY: Math.min(docH, Math.ceil(maxY)),
+ };
+}
+
+/**
+ * High-performance WebGL2 Viewport Compositor
+ */
+export class ViewportCompositor {
+ private canvas: HTMLCanvasElement;
+ private gl: WebGL2RenderingContext | null = null;
+ private program: WebGLProgram | null = null;
+ private quadBuffer: WebGLBuffer | null = null;
+
+ // Uniform locations
+ private uTileOriginLoc: WebGLUniformLocation | null = null;
+ private uTileSizeLoc: WebGLUniformLocation | null = null;
+ private uDocDimensionsLoc: WebGLUniformLocation | null = null;
+ private uViewportSizeLoc: WebGLUniformLocation | null = null;
+ private uPanLoc: WebGLUniformLocation | null = null;
+ private uZoomLoc: WebGLUniformLocation | null = null;
+ private uRotationRadLoc: WebGLUniformLocation | null = null;
+ private uDprLoc: WebGLUniformLocation | null = null;
+ private uIsBackgroundLoc: WebGLUniformLocation | null = null;
+ private uShowCheckerboardLoc: WebGLUniformLocation | null = null;
+ private uTileTextureLoc: WebGLUniformLocation | null = null;
+ private uLayerOpacityLoc: WebGLUniformLocation | null = null;
+ private uBlendModeLoc: WebGLUniformLocation | null = null;
+
+ // Tone uniform locations
+ private uToneEnabledLoc: WebGLUniformLocation | null = null;
+ private uToneFrequencyLoc: WebGLUniformLocation | null = null;
+ private uToneAngleRadLoc: WebGLUniformLocation | null = null;
+ private uToneDpiLoc: WebGLUniformLocation | null = null;
+ private uToneDotShapeLoc: WebGLUniformLocation | null = null;
+ private uToneDensityLoc: WebGLUniformLocation | null = null;
+ private uToneDensityTypeLoc: WebGLUniformLocation | null = null;
+
+ // Tint uniform locations
+ private uLayerColorEnabledLoc: WebGLUniformLocation | null = null;
+ private uLayerColorLoc: WebGLUniformLocation | null = null;
+ private uLayerSubColorLoc: WebGLUniformLocation | null = null;
+
+ // Tile texture cache: tileKey -> { texture, version }
+ private textureCache: Map<string, { texture: WebGLTexture; version: number; lastUsed: number }> = new Map();
+ private fallbackTileCanvas: HTMLCanvasElement | null = null;
+
+ constructor(canvas: HTMLCanvasElement) {
+ this.canvas = canvas;
+ this.initGL();
+ }
+
+ public isReady(): boolean {
+ return this.gl !== null && this.program !== null;
+ }
+
+ private initGL(): boolean {
+ if (this.gl && this.program) return true;
+
+ try {
+ const gl = this.canvas.getContext('webgl2', {
+ alpha: true,
+ premultipliedAlpha: true,
+ antialias: false,
+ depth: false,
+ stencil: true,
+ });
+
+ if (!gl) return false;
+ this.gl = gl;
+
+ // Compile vertex shader
+ const vs = gl.createShader(gl.VERTEX_SHADER);
+ if (!vs) return false;
+ gl.shaderSource(vs, COMPOSITOR_VERTEX_SHADER);
+ gl.compileShader(vs);
+ if (!gl.getShaderParameter(vs, gl.COMPILE_STATUS)) {
+ console.error('Compositor VS error:', gl.getShaderInfoLog(vs));
+ return false;
+ }
+
+ // Compile fragment shader
+ const fs = gl.createShader(gl.FRAGMENT_SHADER);
+ if (!fs) return false;
+ gl.shaderSource(fs, COMPOSITOR_FRAGMENT_SHADER);
+ gl.compileShader(fs);
+ if (!gl.getShaderParameter(fs, gl.COMPILE_STATUS)) {
+ console.error('Compositor FS error:', gl.getShaderInfoLog(fs));
+ return false;
+ }
+
+ // Link program
+ const prog = gl.createProgram();
+ if (!prog) return false;
+ gl.attachShader(prog, vs);
+ gl.attachShader(prog, fs);
+ gl.linkProgram(prog);
+ if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {
+ console.error('Compositor link error:', gl.getProgramInfoLog(prog));
+ return false;
+ }
+ this.program = prog;
+
+ // Cache uniforms
+ this.uTileOriginLoc = gl.getUniformLocation(prog, 'u_tileOrigin');
+ this.uTileSizeLoc = gl.getUniformLocation(prog, 'u_tileSize');
+ this.uDocDimensionsLoc = gl.getUniformLocation(prog, 'u_docDimensions');
+ this.uViewportSizeLoc = gl.getUniformLocation(prog, 'u_viewportSize');
+ this.uPanLoc = gl.getUniformLocation(prog, 'u_pan');
+ this.uZoomLoc = gl.getUniformLocation(prog, 'u_zoom');
+ this.uRotationRadLoc = gl.getUniformLocation(prog, 'u_rotationRad');
+ this.uDprLoc = gl.getUniformLocation(prog, 'u_dpr');
+ this.uIsBackgroundLoc = gl.getUniformLocation(prog, 'u_isBackground');
+ this.uShowCheckerboardLoc = gl.getUniformLocation(prog, 'u_showCheckerboard');
+ this.uTileTextureLoc = gl.getUniformLocation(prog, 'u_tileTexture');
+ this.uLayerOpacityLoc = gl.getUniformLocation(prog, 'u_layerOpacity');
+ this.uBlendModeLoc = gl.getUniformLocation(prog, 'u_blendMode');
+
+ this.uToneEnabledLoc = gl.getUniformLocation(prog, 'u_toneEnabled');
+ this.uToneFrequencyLoc = gl.getUniformLocation(prog, 'u_toneFrequency');
+ this.uToneAngleRadLoc = gl.getUniformLocation(prog, 'u_toneAngleRad');
+ this.uToneDpiLoc = gl.getUniformLocation(prog, 'u_toneDpi');
+ this.uToneDotShapeLoc = gl.getUniformLocation(prog, 'u_toneDotShape');
+ this.uToneDensityLoc = gl.getUniformLocation(prog, 'u_toneDensity');
+ this.uToneDensityTypeLoc = gl.getUniformLocation(prog, 'u_toneDensityType');
+
+ this.uLayerColorEnabledLoc = gl.getUniformLocation(prog, 'u_layerColorEnabled');
+ this.uLayerColorLoc = gl.getUniformLocation(prog, 'u_layerColor');
+ this.uLayerSubColorLoc = gl.getUniformLocation(prog, 'u_layerSubColor');
+
+ // Create Unit Quad Buffer [0, 1]
+ const quad = gl.createBuffer();
+ if (!quad) return false;
+ gl.bindBuffer(gl.ARRAY_BUFFER, quad);
+ gl.bufferData(
+ gl.ARRAY_BUFFER,
+ new Float32Array([
+ 0.0, 0.0,
+ 1.0, 0.0,
+ 0.0, 1.0,
+ 0.0, 1.0,
+ 1.0, 0.0,
+ 1.0, 1.0,
+ ]),
+ gl.STATIC_DRAW
+ );
+ this.quadBuffer = quad;
+
+ // Enable blending
+ gl.enable(gl.BLEND);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+
+ return true;
+ } catch (err) {
+ console.warn('WebGL2 not available for compositor:', err);
+ return false;
+ }
+ }
+
+ /**
+ * Resize viewport canvas to physical screen pixels.
+ */
+ public resize(width: number, height: number): void {
+ if (this.canvas.width !== width || this.canvas.height !== height) {
+ this.canvas.width = Math.max(1, width);
+ this.canvas.height = Math.max(1, height);
+ if (this.gl) {
+ this.gl.viewport(0, 0, this.canvas.width, this.canvas.height);
+ }
+ }
+ }
+
+ /**
+ * Calculates the document-space bounding box visible in the current camera viewport.
+ * Performs frustum culling.
+ */
+ public calculateVisibleDocumentBounds(
+ viewportW: number,
+ viewportH: number,
+ transform: ViewportTransform,
+ docW: number,
+ docH: number
+ ): { minX: number; minY: number; maxX: number; maxY: number } {
+ return calculateVisibleDocumentBounds(viewportW, viewportH, transform, docW, docH);
+ }
+
+ /**
+ * Get or upload a WebGLTexture for a tile.
+ */
+ 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() };
+ this.textureCache.set(key, cached);
+ }
+
+ cached.lastUsed = performance.now();
+
+ // 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);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
+
+ 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
+ );
+
+ cached.version = tile.version;
+ tile.dirty = false;
+ }
+
+ return cached.texture;
+ }
+
+ /**
+ * Set WebGL blend mode according to standard layer blend modes.
+ */
+ private setGLBlendMode(blendMode: BlendMode): void {
+ if (!this.gl) return;
+ const gl = this.gl;
+
+ switch (blendMode) {
+ case 'multiply':
+ // dstRGB * srcRGB
+ gl.blendFuncSeparate(gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ break;
+ case 'screen':
+ // 1 - (1 - dst) * (1 - src)
+ gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ break;
+ case 'normal':
+ default:
+ // Premultiplied alpha standard over
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ break;
+ }
+ }
+
+ /**
+ * Hex color parser to RGB normalized float array [r, g, b].
+ */
+ private parseHexColor(hex: string): [number, number, number] {
+ let clean = hex.replace('#', '');
+ if (clean.length === 3) {
+ clean = clean.split('').map((c) => c + c).join('');
+ }
+ const num = parseInt(clean, 16);
+ if (isNaN(num)) return [0, 0, 0];
+ return [
+ ((num >> 16) & 255) / 255,
+ ((num >> 8) & 255) / 255,
+ (num & 255) / 255,
+ ];
+ }
+
+ /**
+ * Main Render Pass: Composite all visible layers onto the viewport canvas.
+ */
+ public render(
+ layers: LayerItem[],
+ transform: ViewportTransform,
+ dimensions: CanvasDimensions,
+ grid: SparseTileGrid = globalTileGrid,
+ _options: CompositorOptions = { dimensions }
+ ): void {
+ const gl = this.gl;
+ if (!gl || !this.program) {
+ this.render2DFallback(layers, transform, dimensions, grid, _options);
+ return;
+ }
+
+ const viewportW = this.canvas.width;
+ const viewportH = this.canvas.height;
+ gl.viewport(0, 0, viewportW, viewportH);
+
+ // Clear viewport with transparency or dark workspace
+ gl.clearColor(0.0, 0.0, 0.0, 0.0);
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
+
+ gl.useProgram(this.program);
+
+ const dpr = _options.devicePixelRatio ?? (typeof window !== 'undefined' ? window.devicePixelRatio : 1) ?? 1;
+
+ // Set Viewport and Document Uniforms
+ gl.uniform2f(this.uViewportSizeLoc, viewportW, viewportH);
+ gl.uniform2f(this.uDocDimensionsLoc, dimensions.width, dimensions.height);
+ gl.uniform2f(this.uPanLoc, transform.pan.x, transform.pan.y);
+ gl.uniform1f(this.uZoomLoc, transform.zoom);
+ const rotRad = (transform.rotation * Math.PI) / 180;
+ gl.uniform1f(this.uRotationRadLoc, rotRad);
+ gl.uniform1f(this.uDprLoc, dpr);
+ gl.uniform1i(this.uTileTextureLoc, 0);
+
+ // Bind Quad Vertices
+ 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);
+
+ // 1. Render artboard background pass (paper white or checkerboard)
+ gl.blendFunc(gl.ONE, gl.ZERO);
+ gl.uniform1i(this.uIsBackgroundLoc, 1);
+ gl.uniform1i(this.uShowCheckerboardLoc, _options.showCheckerboard ? 1 : 0);
+ gl.uniform2f(this.uTileOriginLoc, 0, 0);
+ gl.uniform2f(this.uTileSizeLoc, dimensions.width, dimensions.height);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+ gl.uniform1i(this.uIsBackgroundLoc, 0);
+
+ // Calculate Frustum Culling document bounds
+ const viewportCssW = viewportW / dpr;
+ const viewportCssH = viewportH / dpr;
+ const frustum = this.calculateVisibleDocumentBounds(
+ viewportCssW,
+ viewportCssH,
+ transform,
+ dimensions.width,
+ dimensions.height
+ );
+
+ gl.uniform2f(this.uTileSizeLoc, TILE_SIZE, TILE_SIZE);
+
+ // Render layers in bottom-to-top order grouped by clipping masks
+ const renderOrder = layers.slice().reverse();
+ const groups = groupLayersForCompositing(renderOrder);
+
+ for (const group of groups) {
+ const baseLayer = group.baseLayer;
+ if (!baseLayer.visible || baseLayer.opacity <= 0.001 || baseLayer.type === 'folder') {
+ continue;
+ }
+
+ const activeClippedLayers = group.clippedLayers.filter(
+ (cl) => cl.visible && cl.opacity > 0.001 && cl.type !== 'folder'
+ );
+
+ if (activeClippedLayers.length > 0) {
+ // Group successive clipped layers: record base silhouette in stencil buffer
+ gl.enable(gl.STENCIL_TEST);
+ gl.clear(gl.STENCIL_BUFFER_BIT);
+ gl.stencilMask(0xFF);
+ gl.stencilFunc(gl.ALWAYS, 1, 0xFF);
+ gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);
+ } else {
+ gl.disable(gl.STENCIL_TEST);
+ }
+
+ // Draw base layer
+ this.renderSingleLayer(gl, baseLayer, dimensions, grid, frustum);
+
+ if (activeClippedLayers.length > 0) {
+ // Render clipped layers: only draw over the opaque pixels of the base layer
+ gl.stencilMask(0x00);
+ gl.stencilFunc(gl.EQUAL, 1, 0xFF);
+ gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
+
+ for (const clippedLayer of activeClippedLayers) {
+ this.renderSingleLayer(gl, clippedLayer, dimensions, grid, frustum);
+ }
+
+ gl.disable(gl.STENCIL_TEST);
+ }
+ }
+
+ // Clean up stale textures periodically (LRU)
+ if (this.textureCache.size > 2000) {
+ this.evictStaleTextures();
+ }
+ }
+
+ /**
+ * Renders all visible tiles of a single layer onto WebGL2 context.
+ */
+ private renderSingleLayer(
+ gl: WebGL2RenderingContext,
+ layer: LayerItem,
+ dimensions: CanvasDimensions,
+ grid: SparseTileGrid,
+ frustum: { minX: number; minY: number; maxX: number; maxY: number }
+ ): void {
+ // Configure Layer Blend Mode & Opacity
+ this.setGLBlendMode(layer.blendMode);
+ gl.uniform1f(this.uLayerOpacityLoc, layer.opacity);
+ gl.uniform1i(this.uBlendModeLoc, BLEND_MODE_MAP[layer.blendMode] ?? 0);
+
+ // Configure Screentone Uniforms
+ const toneEnabled = Boolean(layer.toneEnabled);
+ gl.uniform1i(this.uToneEnabledLoc, toneEnabled ? 1 : 0);
+ if (toneEnabled) {
+ gl.uniform1f(this.uToneFrequencyLoc, layer.toneFrequency || 60);
+ gl.uniform1f(this.uToneAngleRadLoc, ((layer.toneAngle || 45) * Math.PI) / 180);
+ gl.uniform1f(this.uToneDpiLoc, dimensions.dpi || 600);
+ const dotShapeCode =
+ layer.toneDotShape === 'line'
+ ? 2
+ : layer.toneDotShape === 'diamond'
+ ? 3
+ : layer.toneDotShape === 'euclidean'
+ ? 1
+ : 0;
+ gl.uniform1i(this.uToneDotShapeLoc, dotShapeCode);
+ gl.uniform1f(this.uToneDensityLoc, (layer.toneDensity ?? 40) / 100);
+ gl.uniform1i(this.uToneDensityTypeLoc, layer.toneDensityType === 'image' ? 1 : 0);
+ }
+
+ // Configure Layer Tint Uniforms
+ const tintEnabled = Boolean(layer.layerColorEnabled);
+ gl.uniform1i(this.uLayerColorEnabledLoc, tintEnabled ? 1 : 0);
+ if (tintEnabled) {
+ const prim = this.parseHexColor(layer.layerColor || '#1c73c2');
+ const sub = this.parseHexColor(layer.layerSubColor || '#ffffff');
+ gl.uniform3f(this.uLayerColorLoc, prim[0], prim[1], prim[2]);
+ gl.uniform3f(this.uLayerSubColorLoc, sub[0], sub[1], sub[2]);
+ }
+
+ // Query tiles intersecting frustum
+ const visibleTiles = grid.getTilesInBounds(
+ layer.id,
+ frustum.minX,
+ frustum.minY,
+ frustum.maxX,
+ frustum.maxY
+ );
+
+ // Draw each visible tile with 1 draw call per tile
+ for (const tile of visibleTiles) {
+ const tex = this.getTileTexture(tile, grid);
+ if (!tex) continue;
+
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, tex);
+
+ gl.uniform2f(this.uTileOriginLoc, tile.tileX * TILE_SIZE, tile.tileY * TILE_SIZE);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+ }
+ }
+
+ /**
+ * Evict least recently used tile textures when texture cache 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);
+ }
+ }
+
+ /**
+ * Helper to render a single layer onto a 2D canvas context.
+ */
+ private render2DSingleLayer(
+ targetCtx: CanvasRenderingContext2D,
+ layer: LayerItem,
+ grid: SparseTileGrid,
+ tileCtx: CanvasRenderingContext2D | null | undefined
+ ): void {
+ targetCtx.save();
+ targetCtx.globalAlpha = layer.opacity;
+ targetCtx.globalCompositeOperation =
+ layer.blendMode === 'multiply' ? 'multiply' :
+ layer.blendMode === 'screen' ? 'screen' :
+ 'source-over';
+
+ const tiles = grid.getLayerTiles(layer.id);
+ for (const tile of tiles) {
+ if (!tileCtx || !this.fallbackTileCanvas) continue;
+ const rgba = grid.getTileAsRGBA(tile);
+ const imgData = tileCtx.createImageData(TILE_SIZE, TILE_SIZE);
+ imgData.data.set(rgba);
+ tileCtx.putImageData(imgData, 0, 0);
+ targetCtx.drawImage(this.fallbackTileCanvas, tile.tileX * TILE_SIZE, tile.tileY * TILE_SIZE);
+ }
+ targetCtx.restore();
+ }
+
+ /**
+ * 2D Canvas Fallback Pass: Blits tiles when WebGL2 context is unavailable.
+ */
+ private render2DFallback(
+ layers: LayerItem[],
+ transform: ViewportTransform,
+ dimensions: CanvasDimensions,
+ grid: SparseTileGrid,
+ _options: CompositorOptions
+ ): void {
+ const ctx = this.canvas.getContext('2d');
+ if (!ctx) return;
+
+ const viewportW = this.canvas.width;
+ const viewportH = this.canvas.height;
+ const dpr = _options.devicePixelRatio ?? (typeof window !== 'undefined' ? window.devicePixelRatio : 1) ?? 1;
+
+ ctx.save();
+ ctx.clearRect(0, 0, viewportW, viewportH);
+
+ ctx.scale(dpr, dpr);
+ ctx.translate(transform.pan.x, transform.pan.y);
+ ctx.rotate((transform.rotation * Math.PI) / 180);
+ ctx.scale(transform.zoom, transform.zoom);
+ ctx.translate(-dimensions.width / 2, -dimensions.height / 2);
+
+ if (_options.showCheckerboard) {
+ ctx.fillStyle = '#1e1e1e';
+ } else {
+ ctx.fillStyle = '#ffffff';
+ }
+ ctx.fillRect(0, 0, dimensions.width, dimensions.height);
+
+ if (!this.fallbackTileCanvas && typeof document !== 'undefined') {
+ this.fallbackTileCanvas = document.createElement('canvas');
+ this.fallbackTileCanvas.width = TILE_SIZE;
+ this.fallbackTileCanvas.height = TILE_SIZE;
+ }
+ const tileCtx = this.fallbackTileCanvas?.getContext('2d', { willReadFrequently: true });
+
+ const renderOrder = layers.slice().reverse();
+ const groups = groupLayersForCompositing(renderOrder);
+
+ for (const group of groups) {
+ const baseLayer = group.baseLayer;
+ if (!baseLayer.visible || baseLayer.opacity <= 0.001 || baseLayer.type === 'folder') continue;
+
+ const activeClipped = group.clippedLayers.filter(
+ (cl) => cl.visible && cl.opacity > 0.001 && cl.type !== 'folder'
+ );
+
+ if (activeClipped.length === 0) {
+ this.render2DSingleLayer(ctx, baseLayer, grid, tileCtx);
+ } else {
+ // Group isolated canvas for base + clipped layers
+ let groupCanvas: HTMLCanvasElement | null = null;
+ if (typeof document !== 'undefined') {
+ groupCanvas = document.createElement('canvas');
+ groupCanvas.width = dimensions.width;
+ groupCanvas.height = dimensions.height;
+ }
+ const gCtx = groupCanvas?.getContext('2d');
+ if (!gCtx || !groupCanvas) {
+ this.render2DSingleLayer(ctx, baseLayer, grid, tileCtx);
+ continue;
+ }
+
+ // Render baseLayer to groupCanvas
+ this.render2DSingleLayer(gCtx, baseLayer, grid, tileCtx);
+
+ // Render each clipped layer with source-atop to constrain strictly to baseLayer's silhouette
+ for (const clipped of activeClipped) {
+ gCtx.save();
+ gCtx.globalAlpha = clipped.opacity;
+ gCtx.globalCompositeOperation = 'source-atop';
+
+ const tiles = grid.getLayerTiles(clipped.id);
+ for (const tile of tiles) {
+ if (!tileCtx || !this.fallbackTileCanvas) continue;
+ const rgba = grid.getTileAsRGBA(tile);
+ const imgData = tileCtx.createImageData(TILE_SIZE, TILE_SIZE);
+ imgData.data.set(rgba);
+ tileCtx.putImageData(imgData, 0, 0);
+ gCtx.drawImage(this.fallbackTileCanvas, tile.tileX * TILE_SIZE, tile.tileY * TILE_SIZE);
+ }
+ gCtx.restore();
+ }
+
+ // Composite isolated group back to main canvas without affecting root blending
+ ctx.save();
+ ctx.globalAlpha = 1.0;
+ ctx.globalCompositeOperation =
+ baseLayer.blendMode === 'multiply' ? 'multiply' :
+ baseLayer.blendMode === 'screen' ? 'screen' :
+ 'source-over';
+ ctx.drawImage(groupCanvas, 0, 0);
+ ctx.restore();
+ }
+ }
+
+ ctx.restore();
+ }
+
+ /**
+ * Clear all allocated WebGL textures.
+ */
+ public dispose(): void {
+ if (this.gl) {
+ for (const item of this.textureCache.values()) {
+ this.gl.deleteTexture(item.texture);
+ }
+ this.textureCache.clear();
+ if (this.quadBuffer) {
+ this.gl.deleteBuffer(this.quadBuffer);
+ this.quadBuffer = null;
+ }
+ if (this.program) {
+ this.gl.deleteProgram(this.program);
+ this.program = null;
+ }
+ }
+ if (this.fallbackTileCanvas) {
+ this.fallbackTileCanvas = null;
+ }
+ }
+}
diff --git a/src/utils/frameEngine.ts b/src/utils/frameEngine.ts
new file mode 100644
index 0000000..980f8eb
--- /dev/null
+++ b/src/utils/frameEngine.ts
@@ -0,0 +1,305 @@
+/**
+ * Comic Panel / Frame Border Tool (Koma-wari)
+ *
+ * Implements Clip Studio Paint-grade vector frame borders, polygon bisection (koma-cutting),
+ * standard manga gutters (3mm vertical, 5mm horizontal at 600 DPI), and polygon clipping masks.
+ */
+
+import { ComicFrame } from '../types/editor';
+
+export interface Point2D {
+ x: number;
+ y: number;
+}
+
+/**
+ * Standard Manga Gutter Presets (in millimeters)
+ */
+export const MANGA_GUTTER_VERTICAL_MM = 3.0; // 3mm vertical gutter (tate-koma)
+export const MANGA_GUTTER_HORIZONTAL_MM = 5.0; // 5mm horizontal gutter (yoko-koma)
+
+/**
+ * Convert millimeters to document pixels at a specified DPI.
+ */
+export function mmToPixels(mm: number, dpi = 600): number {
+ return (mm * dpi) / 25.4;
+}
+
+/**
+ * Convert pixels to millimeters at a specified DPI.
+ */
+export function pixelsToMm(pixels: number, dpi = 600): number {
+ return (pixels * 25.4) / dpi;
+}
+
+/**
+ * Creates a default outer manga comic frame fitting within document margins.
+ */
+export function createDefaultPageFrame(
+ layerId: string,
+ docWidth: number,
+ docHeight: number,
+ dpi = 600,
+ marginMm = 20
+): ComicFrame {
+ const marginPx = mmToPixels(marginMm, dpi);
+ const left = Math.max(10, marginPx);
+ const top = Math.max(10, marginPx);
+ const right = Math.min(docWidth - 10, docWidth - marginPx);
+ const bottom = Math.min(docHeight - 10, docHeight - marginPx);
+
+ return {
+ id: `frame-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`,
+ layerId,
+ polygon: [
+ { x: left, y: top },
+ { x: right, y: top },
+ { x: right, y: bottom },
+ { x: left, y: bottom },
+ ],
+ borderWidth: Math.max(2, Math.round(mmToPixels(0.5, dpi))), // ~0.5mm line
+ gutterVertical: mmToPixels(MANGA_GUTTER_VERTICAL_MM, dpi),
+ gutterHorizontal: mmToPixels(MANGA_GUTTER_HORIZONTAL_MM, dpi),
+ clipChildren: true,
+ };
+}
+
+/**
+ * Line-segment intersection test between an infinite cut line (p1 -> p2) and a segment (s1 -> s2).
+ */
+export function intersectCutLineWithSegment(
+ p1: Point2D,
+ p2: Point2D,
+ s1: Point2D,
+ s2: Point2D
+): { point: Point2D; edgeIndexParam: number } | null {
+ const cutDx = p2.x - p1.x;
+ const cutDy = p2.y - p1.y;
+ const segDx = s2.x - s1.x;
+ const segDy = s2.y - s1.y;
+
+ const denom = cutDx * segDy - cutDy * segDx;
+ if (Math.abs(denom) < 1e-9) return null; // Collinear or parallel
+
+ const dX = s1.x - p1.x;
+ const dY = s1.y - p1.y;
+
+ const tSeg = (dX * cutDy - dY * cutDx) / denom;
+
+ // We require tSeg to be strictly along the edge segment [0, 1]
+ if (tSeg >= 0 && tSeg <= 1) {
+ return {
+ point: {
+ x: s1.x + tSeg * segDx,
+ y: s1.y + tSeg * segDy,
+ },
+ edgeIndexParam: tSeg,
+ };
+ }
+
+ return null;
+}
+
+/**
+ * Bisect a comic frame polygon along a user-drawn slash line into two child polygon frames.
+ * Automatically separates child frames by the manga gutter width (vertical vs horizontal).
+ */
+export function bisectComicFrame(
+ frame: ComicFrame,
+ cutStart: Point2D,
+ cutEnd: Point2D,
+ dpi = 600
+): [ComicFrame, ComicFrame] | null {
+ const poly = frame.polygon;
+ if (poly.length < 3) return null;
+
+ // 1. Find intersections of cut line with all edges of the polygon
+ const hits: Array<{ edgeIndex: number; tSeg: number; point: Point2D }> = [];
+
+ for (let i = 0; i < poly.length; i++) {
+ const s1 = poly[i];
+ const s2 = poly[(i + 1) % poly.length];
+ const hit = intersectCutLineWithSegment(cutStart, cutEnd, s1, s2);
+ if (hit) {
+ hits.push({
+ edgeIndex: i,
+ tSeg: hit.edgeIndexParam,
+ point: hit.point,
+ });
+ }
+ }
+
+ // Must intersect polygon boundary at exactly 2 points for a clean bisection
+ if (hits.length < 2) return null;
+
+ // Sort hits along the cut line direction
+ const cutVec = { x: cutEnd.x - cutStart.x, y: cutEnd.y - cutStart.y };
+ hits.sort((a, b) => {
+ const dotA = (a.point.x - cutStart.x) * cutVec.x + (a.point.y - cutStart.y) * cutVec.y;
+ const dotB = (b.point.x - cutStart.x) * cutVec.x + (b.point.y - cutStart.y) * cutVec.y;
+ return dotA - dotB;
+ });
+
+ const hitA = hits[0];
+ const hitB = hits[hits.length - 1];
+
+ // 2. Determine Gutter distance and normal offset direction
+ const isMoreVertical = Math.abs(cutVec.y) >= Math.abs(cutVec.x);
+ const gutterDistance = isMoreVertical
+ ? frame.gutterVertical || mmToPixels(MANGA_GUTTER_VERTICAL_MM, dpi)
+ : frame.gutterHorizontal || mmToPixels(MANGA_GUTTER_HORIZONTAL_MM, dpi);
+
+ const halfGutter = gutterDistance * 0.5;
+
+ // Cut normal unit vector (perpendicular to cut line)
+ const cutLen = Math.hypot(cutVec.x, cutVec.y) || 1;
+ const normal = {
+ x: -cutVec.y / cutLen,
+ y: cutVec.x / cutLen,
+ };
+
+ // 3. Assemble child polygon 1 and child polygon 2
+ // Child 1: from hitA along poly edges to hitB, then back to hitA
+ const poly1: Point2D[] = [];
+ const poly2: Point2D[] = [];
+
+ const eA = hitA.edgeIndex;
+ const eB = hitB.edgeIndex;
+
+ // Polygon 1
+ poly1.push({ ...hitA.point });
+ let curr = (eA + 1) % poly.length;
+ while (curr !== (eB + 1) % poly.length) {
+ poly1.push({ ...poly[curr] });
+ curr = (curr + 1) % poly.length;
+ }
+ poly1.push({ ...hitB.point });
+
+ // Polygon 2
+ poly2.push({ ...hitB.point });
+ curr = (eB + 1) % poly.length;
+ while (curr !== (eA + 1) % poly.length) {
+ poly2.push({ ...poly[curr] });
+ curr = (curr + 1) % poly.length;
+ }
+ poly2.push({ ...hitA.point });
+
+ // 4. Inset both polygons by halfGutter along normal
+ // Offset poly1 along +normal and poly2 along -normal
+ 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 p;
+ });
+
+ const insetPoly2 = poly2.map((p) => {
+ 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 p;
+ });
+
+ const child1: ComicFrame = {
+ id: `frame-${Date.now()}-1`,
+ layerId: frame.layerId,
+ polygon: insetPoly1,
+ borderWidth: frame.borderWidth,
+ gutterVertical: frame.gutterVertical,
+ gutterHorizontal: frame.gutterHorizontal,
+ clipChildren: frame.clipChildren,
+ };
+
+ const child2: ComicFrame = {
+ id: `frame-${Date.now()}-2`,
+ layerId: frame.layerId,
+ polygon: insetPoly2,
+ borderWidth: frame.borderWidth,
+ gutterVertical: frame.gutterVertical,
+ gutterHorizontal: frame.gutterHorizontal,
+ clipChildren: frame.clipChildren,
+ };
+
+ return [child1, child2];
+}
+
+/**
+ * Checks if a point is inside a polygon using ray casting.
+ */
+export function isPointInsidePolygon(point: Point2D, polygon: Point2D[]): boolean {
+ let inside = false;
+ for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
+ const xi = polygon[i].x;
+ const yi = polygon[i].y;
+ const xj = polygon[j].x;
+ const yj = polygon[j].y;
+
+ const intersect = yi > point.y !== yj > point.y && point.x < ((xj - xi) * (point.y - yi)) / (yj - yi) + xi;
+ if (intersect) inside = !inside;
+ }
+ return inside;
+}
+
+/**
+ * Apply polygon clipping path to a Canvas 2D context.
+ */
+export function applyFrameClip(ctx: CanvasRenderingContext2D, frame: ComicFrame): void {
+ const poly = frame.polygon;
+ if (poly.length < 3) return;
+
+ ctx.beginPath();
+ ctx.moveTo(poly[0].x, poly[0].y);
+ for (let i = 1; i < poly.length; i++) {
+ ctx.lineTo(poly[i].x, poly[i].y);
+ }
+ ctx.closePath();
+ ctx.clip();
+}
+
+/**
+ * Render black manga frame borders and optional paper white background.
+ */
+export function renderFrameBorder(
+ ctx: CanvasRenderingContext2D,
+ frame: ComicFrame,
+ fillBackground = true,
+ fillColor = '#ffffff'
+): void {
+ const poly = frame.polygon;
+ if (poly.length < 3) return;
+
+ ctx.save();
+
+ if (fillBackground) {
+ ctx.fillStyle = fillColor;
+ ctx.beginPath();
+ ctx.moveTo(poly[0].x, poly[0].y);
+ for (let i = 1; i < poly.length; i++) {
+ ctx.lineTo(poly[i].x, poly[i].y);
+ }
+ ctx.closePath();
+ ctx.fill();
+ }
+
+ // Draw crisp border stroke
+ ctx.strokeStyle = '#000000';
+ ctx.lineWidth = frame.borderWidth || 3;
+ ctx.lineJoin = 'miter';
+ ctx.miterLimit = 4;
+ ctx.beginPath();
+ ctx.moveTo(poly[0].x, poly[0].y);
+ for (let i = 1; i < poly.length; i++) {
+ ctx.lineTo(poly[i].x, poly[i].y);
+ }
+ ctx.closePath();
+ ctx.stroke();
+
+ ctx.restore();
+}
diff --git a/src/utils/pencilEngine.ts b/src/utils/pencilEngine.ts
index 5f41c70..0492faf 100644
--- a/src/utils/pencilEngine.ts
+++ b/src/utils/pencilEngine.ts
@@ -1,4 +1,5 @@
import { Point } from '../types/editor';
+import { getTintedMasterCanvas, drawSingleStamp } from './stampEngine';
/**
* Real Pencil Physics & Paper Grain Simulation Engine
@@ -224,7 +225,7 @@ export function getQuadraticBezierPoint(
* Fast deterministic pseudo-random float generator in [0, 1).
* Ensures graphite micro-flakes land on identical coordinates for live preview and committed strokes.
*/
-function getPencilNoise(seed: number): number {
+export function getPencilNoise(seed: number): number {
let t = (seed + 0x6d2b79f5) | 0;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
@@ -252,11 +253,70 @@ export function getCubicBezierPoint(
y: invT3 * p0.y + 3.0 * invT2 * t * c1.y + 3.0 * invT * t2 * c2.y + t3 * p3.y,
pressure: invT * p0.pressure + t * p3.pressure,
width: invT * p0.width + t * p3.width,
+ tiltX: invT * (p0.tiltX ?? 0) + t * (p3.tiltX ?? 0),
+ tiltY: invT * (p0.tiltY ?? 0) + t * (p3.tiltY ?? 0),
+ twist: invT * (p0.twist ?? 0) + t * (p3.twist ?? 0),
};
}
+const graphiteMaskCache = new Map<PencilGrade, HTMLCanvasElement>();
+
/**
- * Draws a real pencil mark along a cubic Bézier curve.
+ * Pre-renders and caches high-resolution graphite particle masks for each pencil grade.
+ * Features microscopic graphite flake distribution and porous core voids.
+ */
+export function getGraphiteTipMaster(grade: PencilGrade, color: string): HTMLCanvasElement {
+ let maskCanvas = graphiteMaskCache.get(grade);
+ if (!maskCanvas) {
+ const config = PENCIL_CONFIGS[grade] || PENCIL_CONFIGS['pencil-2b'];
+ const size = 64;
+ maskCanvas = document.createElement('canvas');
+ maskCanvas.width = size;
+ maskCanvas.height = size;
+ const ctx = maskCanvas.getContext('2d');
+ if (ctx) {
+ const imgData = ctx.createImageData(size, size);
+ const data = imgData.data;
+ const cx = size / 2;
+ const cy = size / 2;
+ const radius = size / 2 - 2; // 30px
+ const rand = sfc32(0x9e3779b9, 0x243f6a88, 0xb7e15162, 0x8aed2a6b);
+
+ for (let y = 0; y < size; y++) {
+ const dy = y - cy + 0.5;
+ const rowOffset = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ const dx = x - cx + 0.5;
+ const dist = Math.hypot(dx, dy);
+ if (dist < radius) {
+ const normDist = dist / radius;
+ const coreFalloff = Math.pow(Math.max(0, 1.0 - normDist), config.hardness > 0.7 ? 0.65 : 1.2);
+ // Graphite micro-flakes and porous grain voids
+ const flakeNoise = rand();
+ const microVoid = flakeNoise > (0.15 + (1 - config.grain) * 0.1) ? 1.0 : 0.25;
+ const alpha = Math.min(1.0, coreFalloff * (0.65 + flakeNoise * 0.35) * microVoid);
+
+ if (alpha > 0.005) {
+ const idx = rowOffset + x * 4;
+ data[idx] = 255;
+ data[idx + 1] = 255;
+ data[idx + 2] = 255;
+ data[idx + 3] = Math.round(alpha * 255);
+ }
+ }
+ }
+ }
+ ctx.putImageData(imgData, 0, 0);
+ }
+ graphiteMaskCache.set(grade, maskCanvas);
+ }
+
+ return getTintedMasterCanvas(maskCanvas, `pencil_${grade}`, color, 64, 64);
+}
+
+/**
+ * Draws a real pencil mark along a cubic Bézier curve using arc-length stepping and paper tooth modulation.
+ * Delivers authentic graphite tooth on cold-press paper at a locked 120 FPS without string allocations.
*/
export function drawPencilCubicBezierSegment(
ctx: CanvasRenderingContext2D,
@@ -268,90 +328,103 @@ export function drawPencilCubicBezierSegment(
grade: PencilGrade = 'pencil-2b',
userFlow: number = 0.75,
grainIntensity: number = 1.0,
- _userHardness?: number
-) {
+ _userHardness?: number,
+ remainderDist: number = 0,
+ alphaLocked: boolean = false,
+ isTransparentInk: boolean = false
+): 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;
+ if (dist < 0.15) return remainderDist;
- const [cr, cg, cb] = parseRgba(color);
-
- // Dynamic spacing: smaller width = tighter micro-stamps for silky continuity
+ const graphiteMaster = getGraphiteTipMaster(grade, color);
const avgWidth = Math.max(1, (p0.width + p3.width) / 2);
- const stepDist = Math.max(0.45, Math.min(1.8, avgWidth * 0.18));
+ const stepDist = Math.max(0.4, Math.min(1.6, avgWidth * (config.spacing || 0.07)));
const numSteps = Math.max(2, Math.ceil(dist / stepDist));
- ctx.save();
- ctx.globalCompositeOperation = 'source-over';
-
- const particleDensity = config.particleDensity;
- const pSize = config.particleSize;
const baseThreshold = config.thresholdBase;
const sens = config.thresholdPressureSensitivity;
const flow = userFlow * config.flow;
+ const stepT = 1.0 / numSteps;
for (let i = 0; i <= numSteps; i++) {
- const t = i / numSteps;
+ const t = i * stepT;
const pt = getCubicBezierPoint(p0, c1, c2, p3, t);
-
- const radius = Math.max(0.6, pt.width / 2);
const pressure = Math.min(Math.max(pt.pressure || 0.5, 0.05), 1.0);
- // Pressure directly modulates paper tooth contact threshold
- // Light pressure: high threshold -> only highest ridges catch graphite
- // Firm pressure: lower threshold -> fills into the valleys
- const effectiveThreshold = Math.max(
- 15,
- baseThreshold - pressure * sens + (1 - grainIntensity) * 40
- );
+ 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);
+
+ const curWidth = Math.max(0.6, pt.width * (1.0 + tiltMagnitude * 2.2));
- // Number of micro-particles per stamp
- const count = Math.max(
- 3,
- Math.round(radius * 3.2 * (particleDensity / 12) * (0.6 + pressure * 0.6))
+ const effThreshold = Math.max(
+ 15,
+ baseThreshold - pressure * sens + (1 - grainIntensity) * 40 - tiltMagnitude * 35
);
- for (let p = 0; p < count; p++) {
- // Deterministic particle distribution seeded by coordinate and particle index
- const baseSeed = ((Math.round(pt.x * 64) * 73856093) ^ (Math.round(pt.y * 64) * 19349663) ^ (p * 83492791)) | 0;
- const u1 = Math.max(0.0001, getPencilNoise(baseSeed));
- const u2 = getPencilNoise(baseSeed + 1);
- const r = radius * Math.sqrt(-2.0 * Math.log(u1)) * 0.48;
- const theta = 2.0 * Math.PI * u2;
-
- const px = pt.x + r * Math.cos(theta);
- const py = pt.y + r * Math.sin(theta);
-
- // World-anchored paper tooth height check
- const paperHeight = getPaperGrain(px, py);
-
- if (paperHeight >= effectiveThreshold) {
- // Graphite flake opacity: stronger on peak ridges, modulated by pressure & flow
- const heightFactor = Math.min(1.0, (paperHeight - effectiveThreshold + 25) / 55);
- const distFactor = Math.max(0.1, 1 - r / (radius * 1.25));
-
- // Slight natural graphite micro-darkness variation
- const flakeJitter = 0.88 + getPencilNoise(baseSeed + 2) * 0.24;
- const alpha = Math.min(
- 1.0,
- Math.max(0.02, flow * pressure * heightFactor * distFactor * flakeJitter * 0.82)
- );
-
- ctx.fillStyle = `rgba(${cr}, ${cg}, ${cb}, ${alpha.toFixed(3)})`;
- ctx.fillRect(
- Math.floor(px),
- Math.floor(py),
- Math.max(1, pSize),
- Math.max(1, pSize)
- );
+ let stampW = curWidth;
+ let stampH = curWidth;
+ let stampAngle = 0;
+ if (tiltMagnitude > 0.01) {
+ const tiltAzimuth = Math.atan2(tiltY, tiltX);
+ stampW = curWidth;
+ stampH = curWidth * (1.0 + tiltMagnitude * 1.5);
+ if (tiltMagnitude > 0.05) {
+ stampAngle = tiltAzimuth;
}
}
+ if (pt.twist) {
+ stampAngle += (pt.twist * Math.PI) / 180;
+ }
+
+ const 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)
+ );
+
+ drawSingleStamp(
+ ctx,
+ graphiteMaster,
+ pt.x,
+ pt.y,
+ stampW,
+ stampH,
+ stampAngle,
+ dabAlpha,
+ false,
+ false,
+ alphaLocked,
+ isTransparentInk
+ );
+ } else if (pressure > 0.55) {
+ // Firm pressure pushing into troughs
+ const dabAlpha = Math.min(1.0, flow * 0.15 * pressure);
+ drawSingleStamp(
+ ctx,
+ graphiteMaster,
+ pt.x,
+ pt.y,
+ stampW,
+ stampH,
+ stampAngle,
+ dabAlpha,
+ false,
+ false,
+ alphaLocked,
+ isTransparentInk
+ );
+ }
}
- ctx.restore();
+ return 0;
}
/**
@@ -366,21 +439,29 @@ export function drawPencilBezierSegment(
grade: PencilGrade = 'pencil-2b',
userFlow: number = 0.75,
grainIntensity: number = 1.0,
- userHardness?: number
+ userHardness?: number,
+ alphaLocked: boolean = false,
+ isTransparentInk: boolean = false
) {
const c1: Point = {
x: start.x + (2.0 / 3.0) * (control.x - start.x),
y: start.y + (2.0 / 3.0) * (control.y - start.y),
pressure: start.pressure + (2.0 / 3.0) * (control.pressure - start.pressure),
width: start.width + (2.0 / 3.0) * (control.width - start.width),
+ tiltX: start.tiltX !== undefined && control.tiltX !== undefined ? start.tiltX + (2.0 / 3.0) * (control.tiltX - start.tiltX) : undefined,
+ tiltY: start.tiltY !== undefined && control.tiltY !== undefined ? start.tiltY + (2.0 / 3.0) * (control.tiltY - start.tiltY) : undefined,
+ twist: start.twist !== undefined && control.twist !== undefined ? start.twist + (2.0 / 3.0) * (control.twist - start.twist) : undefined,
};
const c2: Point = {
x: end.x + (2.0 / 3.0) * (control.x - end.x),
y: end.y + (2.0 / 3.0) * (control.y - end.y),
pressure: end.pressure + (2.0 / 3.0) * (control.pressure - end.pressure),
width: end.width + (2.0 / 3.0) * (control.width - end.width),
+ tiltX: end.tiltX !== undefined && control.tiltX !== undefined ? end.tiltX + (2.0 / 3.0) * (control.tiltX - end.tiltX) : undefined,
+ tiltY: end.tiltY !== undefined && control.tiltY !== undefined ? end.tiltY + (2.0 / 3.0) * (control.tiltY - end.tiltY) : undefined,
+ twist: end.twist !== undefined && control.twist !== undefined ? end.twist + (2.0 / 3.0) * (control.twist - end.twist) : undefined,
};
- drawPencilCubicBezierSegment(ctx, start, c1, c2, end, color, grade, userFlow, grainIntensity, userHardness);
+ drawPencilCubicBezierSegment(ctx, start, c1, c2, end, color, grade, userFlow, grainIntensity, userHardness, 0, alphaLocked, isTransparentInk);
}
/**
@@ -393,54 +474,61 @@ export function drawPencilDot(
grade: PencilGrade = 'pencil-2b',
userFlow: number = 0.75,
grainIntensity: number = 1.0,
- _userHardness?: number
+ _userHardness?: number,
+ alphaLocked: boolean = false,
+ isTransparentInk: boolean = false
) {
const config = PENCIL_CONFIGS[grade] || PENCIL_CONFIGS['pencil-2b'];
- const [cr, cg, cb] = parseRgba(color);
-
- const radius = Math.max(0.8, point.width / 2);
+ const graphiteMaster = getGraphiteTipMaster(grade, color);
const pressure = Math.min(Math.max(point.pressure || 0.5, 0.05), 1.0);
- const effectiveThreshold = Math.max(
- 15,
- config.thresholdBase - pressure * config.thresholdPressureSensitivity + (1 - grainIntensity) * 40
- );
-
- const count = Math.max(6, Math.round(radius * 8 * (config.particleDensity / 12) * pressure));
- const flow = userFlow * config.flow;
-
- ctx.save();
- ctx.globalCompositeOperation = 'source-over';
+ const tiltX = point.tiltX ?? 0;
+ const tiltY = point.tiltY ?? 0;
+ const tiltAngleDeg = Math.min(90, Math.sqrt(tiltX * tiltX + tiltY * tiltY));
+ const tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180);
- for (let p = 0; p < count; p++) {
- const baseSeed = ((Math.round(point.x * 64) * 73856093) ^ (Math.round(point.y * 64) * 19349663) ^ (p * 83492791)) | 0;
- const u1 = Math.max(0.0001, getPencilNoise(baseSeed));
- const u2 = getPencilNoise(baseSeed + 1);
- const r = radius * Math.sqrt(-2.0 * Math.log(u1)) * 0.48;
- const theta = 2.0 * Math.PI * u2;
+ const curWidth = Math.max(0.6, point.width * (1.0 + tiltMagnitude * 2.2));
- const px = point.x + r * Math.cos(theta);
- const py = point.y + r * Math.sin(theta);
-
- const paperHeight = getPaperGrain(px, py);
-
- if (paperHeight >= effectiveThreshold) {
- const heightFactor = Math.min(1.0, (paperHeight - effectiveThreshold + 25) / 55);
- const distFactor = Math.max(0.1, 1 - r / (radius * 1.25));
- const alpha = Math.min(
- 1.0,
- Math.max(0.02, flow * pressure * heightFactor * distFactor * 0.85)
- );
+ const effThreshold = Math.max(
+ 15,
+ config.thresholdBase - pressure * config.thresholdPressureSensitivity + (1 - grainIntensity) * 40 - tiltMagnitude * 35
+ );
- ctx.fillStyle = `rgba(${cr}, ${cg}, ${cb}, ${alpha.toFixed(3)})`;
- ctx.fillRect(
- Math.floor(px),
- Math.floor(py),
- Math.max(1, config.particleSize),
- Math.max(1, config.particleSize)
- );
+ let stampW = curWidth;
+ let stampH = curWidth;
+ let stampAngle = 0;
+ if (tiltMagnitude > 0.01) {
+ const tiltAzimuth = Math.atan2(tiltY, tiltX);
+ stampW = curWidth;
+ stampH = curWidth * (1.0 + tiltMagnitude * 1.5);
+ if (tiltMagnitude > 0.05) {
+ stampAngle = tiltAzimuth;
}
}
+ if (point.twist) {
+ stampAngle += (point.twist * Math.PI) / 180;
+ }
+
+ const paperHeight = getPaperGrain(point.x, point.y);
+ const heightFactor = paperHeight >= effThreshold
+ ? Math.min(1.0, (paperHeight - effThreshold + 25) / 55)
+ : 0.15;
- ctx.restore();
+ const flow = userFlow * config.flow;
+ const dabAlpha = Math.min(1.0, Math.max(0.05, flow * pressure * heightFactor));
+
+ drawSingleStamp(
+ ctx,
+ graphiteMaster,
+ point.x,
+ point.y,
+ stampW,
+ stampH,
+ stampAngle,
+ dabAlpha,
+ false,
+ false,
+ alphaLocked,
+ isTransparentInk
+ );
}
diff --git a/src/utils/presetBrushes.ts b/src/utils/presetBrushes.ts
index 98fadc6..e18772c 100644
--- a/src/utils/presetBrushes.ts
+++ b/src/utils/presetBrushes.ts
@@ -36,195 +36,6 @@ export function getSquareTipDataUrl(): string {
return _squareTipDataUrl;
}
-let _oilThickTipDataUrl: string | null = null;
-export function getOilThickTipDataUrl(): string {
- if (_oilThickTipDataUrl) return _oilThickTipDataUrl;
- const canvas = document.createElement('canvas');
- canvas.width = 96;
- canvas.height = 96;
- const ctx = canvas.getContext('2d')!;
- ctx.clearRect(0, 0, 96, 96);
-
- // Synthesize realistic hog bristle head with distinct, separated bristle tracks
- // Bristle strands run along X (direction of motion), spaced along Y
- const strandOffsets = [-32, -26, -20, -15, -10, -5, 0, 5, 10, 15, 20, 26, 32];
-
- strandOffsets.forEach((yOff, idx) => {
- const yCenter = 48 + yOff;
- const strandRadius = Math.abs(yOff) / 36;
- if (strandRadius >= 1.0) return;
-
- // Outer strands are slightly shorter and thinner
- const lengthFactor = Math.sqrt(1.0 - strandRadius * strandRadius);
- const strandLength = Math.max(16, 52 * lengthFactor);
- const xStart = 48 - strandLength / 2;
- const xEnd = 48 + strandLength / 2;
-
- const bristleWidth = idx % 2 === 0 ? 3.0 : 2.2;
- const alpha = (0.75 + (idx % 3) * 0.1) * (1.0 - strandRadius * 0.25);
-
- ctx.save();
- ctx.strokeStyle = `rgba(255, 255, 255, ${alpha.toFixed(3)})`;
- ctx.lineWidth = bristleWidth;
- ctx.lineCap = 'round';
-
- ctx.beginPath();
- // Subtle natural jitter along the fiber
- const wave1 = Math.sin(idx * 1.7) * 1.5;
- ctx.moveTo(xStart, yCenter - wave1);
- ctx.bezierCurveTo(
- 48 - 10,
- yCenter + wave1,
- 48 + 10,
- yCenter - wave1 * 0.8,
- xEnd,
- yCenter + wave1 * 0.5
- );
- ctx.stroke();
-
- // Secondary sub-hair for dense natural impasto texture
- if (idx % 2 === 0) {
- ctx.strokeStyle = `rgba(255, 255, 255, ${(alpha * 0.6).toFixed(3)})`;
- ctx.lineWidth = 1.2;
- ctx.beginPath();
- ctx.moveTo(xStart + 4, yCenter + 1.8);
- ctx.lineTo(xEnd - 4, yCenter + 1.8);
- ctx.stroke();
- }
- ctx.restore();
- });
-
- _oilThickTipDataUrl = canvas.toDataURL('image/png');
- return _oilThickTipDataUrl;
-}
-
-let _oilGlazeTipDataUrl: string | null = null;
-export function getOilGlazeTipDataUrl(): string {
- if (_oilGlazeTipDataUrl) return _oilGlazeTipDataUrl;
- const canvas = document.createElement('canvas');
- canvas.width = 96;
- canvas.height = 96;
- const ctx = canvas.getContext('2d')!;
- ctx.clearRect(0, 0, 96, 96);
-
- // Soft filbert oval bristle with fine striations
- const grad = ctx.createRadialGradient(48, 48, 2, 48, 48, 42);
- grad.addColorStop(0, 'rgba(255, 255, 255, 0.88)');
- grad.addColorStop(0.55, 'rgba(255, 255, 255, 0.6)');
- grad.addColorStop(0.85, 'rgba(255, 255, 255, 0.2)');
- grad.addColorStop(1, 'rgba(255, 255, 255, 0)');
-
- ctx.fillStyle = grad;
- ctx.beginPath();
- ctx.ellipse(48, 48, 42, 30, 0, 0, Math.PI * 2);
- ctx.fill();
-
- // Fine bristle striations aligned horizontally
- for (let y = 20; y <= 76; y += 3.2) {
- const yNorm = Math.abs(y - 48) / 30;
- if (yNorm < 0.95) {
- const len = Math.sqrt(1 - yNorm * yNorm) * 36;
- ctx.strokeStyle = `rgba(255, 255, 255, ${(0.18 + (y % 5 === 0 ? 0.22 : 0.06)).toFixed(3)})`;
- ctx.lineWidth = 1.2;
- ctx.beginPath();
- ctx.moveTo(48 - len, y);
- ctx.lineTo(48 + len, y);
- ctx.stroke();
- }
- }
-
- _oilGlazeTipDataUrl = canvas.toDataURL('image/png');
- return _oilGlazeTipDataUrl;
-}
-
-let _chalkRoughTipDataUrl: string | null = null;
-export function getChalkRoughTipDataUrl(): string {
- if (_chalkRoughTipDataUrl) return _chalkRoughTipDataUrl;
- const canvas = document.createElement('canvas');
- canvas.width = 64;
- canvas.height = 64;
- const ctx = canvas.getContext('2d')!;
- ctx.clearRect(0, 0, 64, 64);
-
- const cx = 32;
- const cy = 32;
- const radius = 25;
-
- // Porous powdery crumbly chalk texture with deep tooth voids
- for (let x = 4; x < 60; x += 2.2) {
- for (let y = 4; y < 60; y += 2.2) {
- const d = Math.hypot(x - cx, y - cy);
- if (d <= radius) {
- const noise = (Math.sin(x * 12.3 + y * 7.1) * Math.cos(y * 11.2 - x * 5.4) * 0.5 + 0.5);
- if (noise > 0.32) {
- const edgeFalloff = 1.0 - (d / radius) * 0.65;
- const a = Math.min(1.0, noise * edgeFalloff * 1.4);
- ctx.fillStyle = `rgba(255, 255, 255, ${a.toFixed(3)})`;
- ctx.fillRect(x, y, 2.2, 2.2);
- }
- }
- }
- }
-
- _chalkRoughTipDataUrl = canvas.toDataURL('image/png');
- return _chalkRoughTipDataUrl;
-}
-
-let _chalkPastelTipDataUrl: string | null = null;
-export function getChalkPastelTipDataUrl(): string {
- if (_chalkPastelTipDataUrl) return _chalkPastelTipDataUrl;
- const canvas = document.createElement('canvas');
- canvas.width = 64;
- canvas.height = 64;
- const ctx = canvas.getContext('2d')!;
- ctx.clearRect(0, 0, 64, 64);
-
- // Soft rounded chalk stick shape
- ctx.fillStyle = 'rgba(255, 255, 255, 0.72)';
- ctx.beginPath();
- ctx.roundRect(8, 8, 48, 48, 12);
- ctx.fill();
-
- // Internal porous powder texture
- for (let x = 10; x < 54; x += 2.8) {
- for (let y = 10; y < 54; y += 2.8) {
- const n = (Math.sin(x * 9.1 + y * 6.3) * 0.5 + 0.5);
- if (n > 0.38) {
- ctx.fillStyle = `rgba(255, 255, 255, ${(n * 0.7).toFixed(2)})`;
- ctx.fillRect(x, y, 2.6, 2.6);
- }
- }
- }
-
- _chalkPastelTipDataUrl = canvas.toDataURL('image/png');
- return _chalkPastelTipDataUrl;
-}
-
-let _smudgeTipDataUrl: string | null = null;
-export function getSmudgeTipDataUrl(): string {
- if (_smudgeTipDataUrl) return _smudgeTipDataUrl;
- const canvas = document.createElement('canvas');
- canvas.width = 64;
- canvas.height = 64;
- const ctx = canvas.getContext('2d')!;
- ctx.clearRect(0, 0, 64, 64);
-
- // Feathered blender tip with soft Gaussian core for creamy paint smearing
- const grad = ctx.createRadialGradient(32, 32, 2, 32, 32, 29);
- grad.addColorStop(0, 'rgba(255, 255, 255, 0.95)');
- grad.addColorStop(0.4, 'rgba(255, 255, 255, 0.75)');
- grad.addColorStop(0.75, 'rgba(255, 255, 255, 0.3)');
- grad.addColorStop(1, 'rgba(255, 255, 255, 0)');
-
- ctx.fillStyle = grad;
- ctx.beginPath();
- ctx.arc(32, 32, 29, 0, Math.PI * 2);
- ctx.fill();
-
- _smudgeTipDataUrl = canvas.toDataURL('image/png');
- return _smudgeTipDataUrl;
-}
-
// Preloaded images cache
const preloadedTipImages = new Map<string, HTMLImageElement>();
export function getPreloadedBuiltinTipImage(dataUrl: string): HTMLImageElement | undefined {
@@ -237,18 +48,11 @@ export function getPreloadedBuiltinTipImage(dataUrl: string): HTMLImageElement |
return img;
}
-// Eagerly generate and preload all built-in brush tip textures at startup
+// Eagerly generate and preload built-in brush tip textures at startup
if (typeof document !== 'undefined') {
try {
const square = getSquareTipDataUrl();
- const oilThick = getOilThickTipDataUrl();
- const oilGlaze = getOilGlazeTipDataUrl();
- const chalkRough = getChalkRoughTipDataUrl();
- const chalkPastel = getChalkPastelTipDataUrl();
- const smudge = getSmudgeTipDataUrl();
- [square, oilThick, oilGlaze, chalkRough, chalkPastel, smudge].forEach((url) => {
- if (url) getPreloadedBuiltinTipImage(url);
- });
+ if (square) getPreloadedBuiltinTipImage(square);
} catch (err) {
console.warn('Failed to eagerly initialize brush tips:', err);
}
@@ -371,11 +175,11 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
icon: 'paintbrush',
settings: {
size: 8,
- minSizeFactor: 0.08,
+ minSizeFactor: 0.05,
flow: 1.0,
opacity: 1.0,
hardness: 1.0,
- spacing: 0.03,
+ spacing: 0.035,
stabilization: 20,
usePressure: true,
smoothing: true,
@@ -383,196 +187,101 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
},
},
{
- id: 'round',
- name: 'Round Brush',
+ id: 'maru-pen',
+ name: 'Maru Pen (Mapping Pen)',
category: 'pencil-line',
categoryName: 'Pencil & Line',
- badge: 'Ink',
- badgeBg: 'bg-blue-500/15',
- badgeText: 'text-blue-300',
- badgeBorder: 'border-blue-500/30',
- desc: 'Smooth Digital Inking',
+ badge: 'Maru',
+ badgeBg: 'bg-violet-500/15',
+ badgeText: 'text-violet-300',
+ badgeBorder: 'border-violet-500/30',
+ desc: 'Delicate Manga Crosshatching & Hairlines',
icon: 'paintbrush',
settings: {
- size: 14,
- minSizeFactor: 0.15,
- flow: 0.85,
+ size: 4.5,
+ minSizeFactor: 0.02,
+ flow: 1.0,
opacity: 1.0,
hardness: 1.0,
- spacing: 0.06,
- stabilization: 15,
+ spacing: 0.03,
+ stabilization: 24,
usePressure: true,
smoothing: true,
useGpu: true,
},
},
-
- // ============================================================
- // CATEGORY 2: COLOR & PAINT (Oil, Chalk, Smudge, Square Coloring)
- // ============================================================
{
- id: 'oil-thick',
- name: 'Thick Oil Paint',
- category: 'color-paint',
- categoryName: 'Color & Paint',
- badge: 'Oil',
- badgeBg: 'bg-rose-500/15',
- badgeText: 'text-rose-300',
- badgeBorder: 'border-rose-500/30',
- desc: 'Authentic Impasto with Natural Bristle Lines',
- icon: 'palette',
- tipGenerator: getOilThickTipDataUrl,
+ id: 'turnip-pen',
+ name: 'Turnip Pen (Kabura Pen)',
+ category: 'pencil-line',
+ categoryName: 'Pencil & Line',
+ badge: 'Turnip',
+ badgeBg: 'bg-teal-500/15',
+ badgeText: 'text-teal-300',
+ badgeBorder: 'border-teal-500/30',
+ desc: 'Uniform Contours & Manga Character Lineart',
+ icon: 'paintbrush',
settings: {
- size: 28,
- minSizeFactor: 0.35,
- flow: 0.92,
+ size: 9.0,
+ minSizeFactor: 0.28,
+ flow: 1.0,
opacity: 1.0,
- hardness: 0.9,
- spacing: 0.07, // Optimal spacing for crisp individual bristle tracks
- stabilization: 12,
- usePressure: true,
- smoothing: true,
- customTipAngle: 0,
- customTipAngleDynamics: 'direction', // Bristles curve naturally with stroke!
- colorMixing: true,
- amountOfPaint: 0.65,
- densityOfPaint: 0.92,
- colorStretch: 0.78,
- mixingMode: 'running_color',
- wetEdge: 0.12,
- grain: 0.15,
- useGpu: true,
- },
- },
- {
- id: 'oil-glaze',
- name: 'Oil Glazing Brush',
- category: 'color-paint',
- categoryName: 'Color & Paint',
- badge: 'Glaze',
- badgeBg: 'bg-purple-500/15',
- badgeText: 'text-purple-300',
- badgeBorder: 'border-purple-500/30',
- desc: 'Wet Blending & Silky Translucent Striations',
- icon: 'palette',
- tipGenerator: getOilGlazeTipDataUrl,
- settings: {
- size: 34,
- minSizeFactor: 0.4,
- flow: 0.72,
- opacity: 0.85,
- hardness: 0.75,
- spacing: 0.06,
- stabilization: 10,
+ hardness: 1.0,
+ spacing: 0.04,
+ stabilization: 18,
usePressure: true,
smoothing: true,
- customTipAngle: 0,
- customTipAngleDynamics: 'direction',
- colorMixing: true,
- amountOfPaint: 0.38,
- densityOfPaint: 0.62,
- colorStretch: 0.86,
- mixingMode: 'running_color',
- wetEdge: 0.2,
- grain: 0.08,
useGpu: true,
},
},
{
- id: 'blend-smudge',
- name: 'Smooth Smudge & Blender',
- category: 'color-paint',
- categoryName: 'Color & Paint',
- badge: 'Smudge',
- badgeBg: 'bg-cyan-500/15',
- badgeText: 'text-cyan-300',
- badgeBorder: 'border-cyan-500/30',
- desc: 'CSP Wet Paint Smear & Seamless Edge Blending',
- icon: 'palette',
- tipGenerator: getSmudgeTipDataUrl,
+ id: 'round',
+ name: 'Round Brush',
+ category: 'pencil-line',
+ categoryName: 'Pencil & Line',
+ badge: 'Ink',
+ badgeBg: 'bg-blue-500/15',
+ badgeText: 'text-blue-300',
+ badgeBorder: 'border-blue-500/30',
+ desc: 'Smooth Digital Inking',
+ icon: 'paintbrush',
settings: {
- size: 32,
- minSizeFactor: 0.3,
+ size: 14,
+ minSizeFactor: 0.15,
flow: 0.85,
opacity: 1.0,
- hardness: 0.65,
- spacing: 0.045,
- stabilization: 12,
- usePressure: true,
- smoothing: true,
- customTipAngle: 0,
- customTipAngleDynamics: 'none',
- colorMixing: true,
- amountOfPaint: 0.0, // PURE SMUDGE: zero fresh pigment, drags existing paint!
- densityOfPaint: 0.88,
- colorStretch: 0.88,
- mixingMode: 'running_color',
- useGpu: true,
- },
- },
- {
- id: 'chalk-rough',
- name: 'Rough Chalk',
- category: 'color-paint',
- categoryName: 'Color & Paint',
- badge: 'Chalk',
- badgeBg: 'bg-yellow-500/15',
- badgeText: 'text-yellow-300',
- badgeBorder: 'border-yellow-500/30',
- desc: 'Powdery Texture on Heavy Tooth',
- icon: 'paintbrush',
- tipGenerator: getChalkRoughTipDataUrl,
- settings: {
- size: 24,
- minSizeFactor: 0.35,
- flow: 0.8,
- opacity: 0.9,
- hardness: 0.92,
- spacing: 0.075,
- stabilization: 8,
+ hardness: 0.9,
+ spacing: 0.05,
+ stabilization: 15,
usePressure: true,
smoothing: true,
- customTipAngle: 0,
- customTipAngleDynamics: 'direction',
- grain: 0.88,
- colorMixing: true,
- amountOfPaint: 0.68,
- densityOfPaint: 0.82,
- colorStretch: 0.55,
- mixingMode: 'blend',
useGpu: true,
},
},
+ // ============================================================
+ // CATEGORY 2: COLOR & PAINT
+ // ============================================================
{
- id: 'chalk-pastel',
- name: 'Pastel Chalk',
+ id: 'airbrush-soft',
+ name: 'Soft Airbrush',
category: 'color-paint',
categoryName: 'Color & Paint',
- badge: 'Pastel',
- badgeBg: 'bg-lime-500/15',
- badgeText: 'text-lime-300',
- badgeBorder: 'border-lime-500/30',
- desc: 'Soft Pigment for Organic Smudge & Blending',
+ badge: 'Air',
+ badgeBg: 'bg-pink-500/15',
+ badgeText: 'text-pink-300',
+ badgeBorder: 'border-pink-500/30',
+ desc: 'Silky Gaussian Radial Falloff & Delicate Glaze',
icon: 'paintbrush',
- tipGenerator: getChalkPastelTipDataUrl,
settings: {
- size: 26,
+ size: 48,
minSizeFactor: 0.35,
- flow: 0.84,
- opacity: 0.92,
- hardness: 0.78,
- spacing: 0.065,
+ flow: 0.28,
+ opacity: 1.0,
+ hardness: 0.0,
+ spacing: 0.05,
stabilization: 10,
usePressure: true,
smoothing: true,
- customTipAngle: 0,
- customTipAngleDynamics: 'direction',
- grain: 0.65,
- colorMixing: true,
- amountOfPaint: 0.45,
- densityOfPaint: 0.78,
- colorStretch: 0.72,
- mixingMode: 'running_color',
useGpu: true,
},
},
diff --git a/src/utils/recentDocumentsManager.ts b/src/utils/recentDocumentsManager.ts
new file mode 100644
index 0000000..11c9574
--- /dev/null
+++ b/src/utils/recentDocumentsManager.ts
@@ -0,0 +1,189 @@
+// Recent & Starred Documents Manager with IndexedDB persistence and disk removal
+
+export interface RecentDocument {
+ id: string;
+ title: string;
+ path: string;
+ size: number; // in bytes
+ coverUrl?: string;
+ lastOpened: number; // unix timestamp ms
+ isStarred: boolean;
+ fileType?: string;
+}
+
+const DB_NAME = 'InkStudioRecentDocsDB';
+const DB_VERSION = 1;
+const STORE_NAME = 'recent_documents';
+const LS_BACKUP_KEY = 'inkstudio_recent_docs_backup';
+
+function openDB(): Promise<IDBDatabase> {
+ return new Promise((resolve, reject) => {
+ if (typeof window === 'undefined' || !window.indexedDB) {
+ reject(new Error('IndexedDB not available'));
+ return;
+ }
+ const req = indexedDB.open(DB_NAME, DB_VERSION);
+ req.onupgradeneeded = (e) => {
+ const db = (e.target as IDBOpenDBRequest).result;
+ if (!db.objectStoreNames.contains(STORE_NAME)) {
+ const store = db.createObjectStore(STORE_NAME, { keyPath: 'id' });
+ store.createIndex('lastOpened', 'lastOpened', { unique: false });
+ store.createIndex('isStarred', 'isStarred', { unique: false });
+ }
+ };
+ req.onsuccess = () => resolve(req.result);
+ req.onerror = () => reject(req.error);
+ });
+}
+
+export async function loadRecentDocuments(): Promise<RecentDocument[]> {
+ // Purge any legacy sample docs from localStorage
+ try {
+ const raw = localStorage.getItem(LS_BACKUP_KEY);
+ if (raw) {
+ const parsed = JSON.parse(raw);
+ if (Array.isArray(parsed)) {
+ const cleaned = parsed.filter((d: RecentDocument) => !d.id.startsWith('sample-doc-'));
+ localStorage.setItem(LS_BACKUP_KEY, JSON.stringify(cleaned));
+ }
+ }
+ } catch {
+ // ignore
+ }
+
+ try {
+ const db = await openDB();
+ return new Promise((resolve) => {
+ const tx = db.transaction(STORE_NAME, 'readwrite');
+ const store = tx.objectStore(STORE_NAME);
+ const req = store.getAll();
+ req.onsuccess = () => {
+ let docs = (req.result as RecentDocument[]) || [];
+ // Clean out any legacy sample documents from IDB
+ const sampleDocs = docs.filter((d) => d.id.startsWith('sample-doc-'));
+ if (sampleDocs.length > 0) {
+ for (const s of sampleDocs) {
+ store.delete(s.id);
+ }
+ docs = docs.filter((d) => !d.id.startsWith('sample-doc-'));
+ }
+ docs.sort((a, b) => b.lastOpened - a.lastOpened);
+ resolve(docs);
+ };
+ req.onerror = () => {
+ resolve(getFallbackDocs());
+ };
+ });
+ } catch {
+ return getFallbackDocs();
+ }
+}
+
+function getFallbackDocs(): RecentDocument[] {
+ try {
+ const raw = localStorage.getItem(LS_BACKUP_KEY);
+ if (raw) {
+ const parsed = JSON.parse(raw);
+ if (Array.isArray(parsed)) {
+ return parsed.filter((d: RecentDocument) => !d.id.startsWith('sample-doc-'));
+ }
+ }
+ } catch {
+ // ignore
+ }
+ return [];
+}
+
+export async function saveRecentDocument(
+ doc: Omit<RecentDocument, 'lastOpened'> & { lastOpened?: number }
+): Promise<void> {
+ const fullDoc: RecentDocument = {
+ ...doc,
+ lastOpened: doc.lastOpened ?? Date.now(),
+ };
+
+ try {
+ const db = await openDB();
+ const tx = db.transaction(STORE_NAME, 'readwrite');
+ tx.objectStore(STORE_NAME).put(fullDoc);
+ } catch {
+ // fallback to localStorage
+ const current = getFallbackDocs().filter((d) => d.id !== fullDoc.id);
+ localStorage.setItem(LS_BACKUP_KEY, JSON.stringify([fullDoc, ...current]));
+ }
+}
+
+export async function toggleStarDocument(id: string): Promise<boolean> {
+ try {
+ const db = await openDB();
+ return new Promise((resolve) => {
+ const tx = db.transaction(STORE_NAME, 'readwrite');
+ const store = tx.objectStore(STORE_NAME);
+ const req = store.get(id);
+ req.onsuccess = () => {
+ const item = req.result as RecentDocument | undefined;
+ if (item) {
+ item.isStarred = !item.isStarred;
+ store.put(item);
+ tx.oncomplete = () => resolve(item.isStarred);
+ } else {
+ resolve(false);
+ }
+ };
+ req.onerror = () => resolve(false);
+ });
+ } catch {
+ const current = getFallbackDocs();
+ const target = current.find((d) => d.id === id);
+ if (target) {
+ target.isStarred = !target.isStarred;
+ localStorage.setItem(LS_BACKUP_KEY, JSON.stringify(current));
+ return target.isStarred;
+ }
+ return false;
+ }
+}
+
+export async function removeRecentDocument(id: string): Promise<void> {
+ try {
+ const db = await openDB();
+ const tx = db.transaction(STORE_NAME, 'readwrite');
+ tx.objectStore(STORE_NAME).delete(id);
+ } catch {
+ // ignore
+ }
+ const current = getFallbackDocs().filter((d) => d.id !== id);
+ localStorage.setItem(LS_BACKUP_KEY, JSON.stringify(current));
+}
+
+export async function permanentlyDeleteDocument(
+ doc: RecentDocument
+): Promise<{ success: boolean; error?: string }> {
+ let diskSuccess = true;
+ let diskError: string | undefined;
+
+ // 1. If running in Tauri, delete file from host PC storage
+ if (typeof window !== 'undefined' && (window as any).__TAURI_INTERNALS__) {
+ try {
+ const { invoke } = await import('@tauri-apps/api/core');
+ await invoke('delete_file_from_disk', { path: doc.path });
+ } catch (err: any) {
+ console.warn('Failed to delete file from disk via Tauri:', err);
+ diskSuccess = false;
+ diskError = err?.message || String(err);
+ }
+ }
+
+ // 2. Remove from app database
+ await removeRecentDocument(doc.id);
+
+ return { success: diskSuccess, error: diskError };
+}
+
+export function formatFileSize(bytes: number): string {
+ if (!bytes || bytes <= 0) return '0 B';
+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];
+ const i = Math.floor(Math.log(bytes) / Math.log(1024));
+ const val = bytes / Math.pow(1024, i);
+ return `${val.toFixed(i === 0 ? 0 : 1)} ${units[i]}`;
+}
diff --git a/src/utils/saveManager.ts b/src/utils/saveManager.ts
index 0adc3a4..ea1190d 100644
--- a/src/utils/saveManager.ts
+++ b/src/utils/saveManager.ts
@@ -5,6 +5,7 @@ import {
BlendMode,
} from '../types/editor';
import { getCanvasCompositeOperation } from './canvasUtils';
+import { groupLayersForCompositing } from './compositor';
export interface SavedFileInfo {
handle?: any; // FileSystemFileHandle
@@ -62,18 +63,56 @@ export function compositeCanvas(
ctx.fillRect(0, 0, dimensions.width, dimensions.height);
}
- // Render layers bottom-to-top
+ // Render layers bottom-to-top grouped by clipping masks
const renderOrder = layers.slice().reverse();
- for (const layer of renderOrder) {
- if (layer.type === 'folder' || !isLayerEffectivelyVisible(layer)) continue;
- const lCanvas = layerCanvasesMap.get(layer.id);
- if (!lCanvas) continue;
-
- ctx.save();
- ctx.globalAlpha = getEffectiveOpacity(layer);
- ctx.globalCompositeOperation = getCanvasCompositeOperation(layer.blendMode);
- ctx.drawImage(lCanvas, 0, 0);
- ctx.restore();
+ const groups = groupLayersForCompositing(renderOrder);
+
+ 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;
+
+ const activeClipped = group.clippedLayers.filter(
+ (cl) => cl.type !== 'folder' && isLayerEffectivelyVisible(cl)
+ );
+
+ if (activeClipped.length === 0) {
+ ctx.save();
+ ctx.globalAlpha = getEffectiveOpacity(baseLayer);
+ ctx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);
+ ctx.drawImage(baseCanvas, 0, 0);
+ ctx.restore();
+ } else {
+ // Group isolated offscreen canvas for base + clipped layers
+ const groupCanvas = document.createElement('canvas');
+ groupCanvas.width = dimensions.width;
+ groupCanvas.height = dimensions.height;
+ const gCtx = groupCanvas.getContext('2d');
+ if (!gCtx) continue;
+
+ gCtx.save();
+ gCtx.globalAlpha = getEffectiveOpacity(baseLayer);
+ gCtx.drawImage(baseCanvas, 0, 0);
+ gCtx.restore();
+
+ for (const clipped of activeClipped) {
+ const cCanvas = layerCanvasesMap.get(clipped.id);
+ if (!cCanvas) continue;
+
+ gCtx.save();
+ gCtx.globalAlpha = getEffectiveOpacity(clipped);
+ gCtx.globalCompositeOperation = 'source-atop';
+ gCtx.drawImage(cCanvas, 0, 0);
+ gCtx.restore();
+ }
+
+ ctx.save();
+ ctx.globalAlpha = 1.0;
+ ctx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);
+ ctx.drawImage(groupCanvas, 0, 0);
+ ctx.restore();
+ }
}
return exportCanvas;
diff --git a/src/utils/screentoneEngine.ts b/src/utils/screentoneEngine.ts
index 04d6235..e22f5fe 100644
--- a/src/utils/screentoneEngine.ts
+++ b/src/utils/screentoneEngine.ts
@@ -1,6 +1,6 @@
import { DirtyRect } from '../types/editor';
-export type HalftoneDotShape = 'circle' | 'euclidean' | 'line';
+export type HalftoneDotShape = 'circle' | 'euclidean' | 'line' | 'diamond';
export interface ScreentoneOptions {
/**
@@ -60,6 +60,12 @@ export interface ScreentoneOptions {
* Specified density normalized to [0.0, 1.0], where 0.4 = 40% (default: 0.4)
*/
specifiedDensity?: number;
+
+ /**
+ * Viewport zoom scale. When zoom < 1.0, automatically crossfades into equivalent
+ * continuous grayscale luminance to eliminate spatial aliasing and moiré patterns.
+ */
+ zoom?: number;
}
// Runtime system endianness check for ultra-fast 32-bit pixel writes
@@ -127,6 +133,11 @@ export function evaluateHalftoneDot(
return spot >= (1.0 - density);
}
+ if (dotShape === 'diamond') {
+ const spot = 1.0 - (Math.abs(u) + Math.abs(v));
+ return spot >= (1.0 - density);
+ }
+
// Authentic Manga / Clip Studio Euclidean Round Dot Spot Function
const absU = Math.abs(u);
const absV = Math.abs(v);
@@ -221,6 +232,7 @@ export function applyScreentoneCPU(
const invCellSize = 1.0 / cellSize;
const dotShape = options.dotShape ?? 'circle';
const isLine = dotShape === 'line';
+ const isDiamond = dotShape === 'diamond';
const solidBlackAtMax = options.solidBlackAtMax !== false;
const antiAliasing = options.antiAliasing !== false;
const isSpecified = options.densityType !== 'image';
@@ -234,6 +246,10 @@ export function applyScreentoneCPU(
let srcIdx = 0;
let dstIdx = 0;
+ const zoom = options.zoom ?? 1.0;
+ const isDownscaled = zoom < 0.95;
+ const moireBlend = isDownscaled ? Math.max(0, Math.min(1, (zoom - 0.35) / 0.6)) : 1.0;
+
for (let y = minY; y < maxY; y++) {
const ySinT = y * sinT;
const yCosT = y * cosT;
@@ -302,6 +318,8 @@ export function applyScreentoneCPU(
let spot: number;
if (isLine) {
spot = 1.0 - 2.0 * Math.abs(u);
+ } else if (isDiamond) {
+ spot = 1.0 - (Math.abs(u) + Math.abs(v));
} else {
const absU = Math.abs(u);
const absV = Math.abs(v);
@@ -317,7 +335,11 @@ export function applyScreentoneCPU(
const diff = spot - oneMinusDensity;
if (antiAliasing) {
- const coverage = diff * invTwoAaHalfSpan + 0.5;
+ let coverage = Math.max(0, Math.min(1, diff * invTwoAaHalfSpan + 0.5));
+ if (isDownscaled) {
+ const contDensity = 1.0 - oneMinusDensity;
+ coverage = contDensity * (1.0 - moireBlend) + coverage * moireBlend;
+ }
if (coverage <= 0.0) {
dstData32[dstIdx] = TRANSPARENT_U32;
} else if (coverage >= 1.0) {
@@ -361,6 +383,7 @@ uniform int u_solidBlackAtMax;
uniform int u_antiAliasing;
uniform int u_densityType;
uniform float u_specifiedDensity;
+uniform float u_zoom;
varying vec2 v_texCoord;
@@ -406,6 +429,8 @@ void main() {
float spot;
if (u_dotShape == 2) {
spot = 1.0 - 2.0 * abs(u);
+ } else if (u_dotShape == 3) {
+ spot = 1.0 - (abs(u) + abs(v));
} else {
float absU = abs(u);
float absV = abs(v);
@@ -419,17 +444,26 @@ void main() {
}
float diff = spot - (1.0 - density);
+ vec4 halftoneColor;
+
if (u_antiAliasing == 1) {
float halfSpan = min(0.25, 0.75 / u_cellSize);
float coverage = clamp(diff / (2.0 * halfSpan) + 0.5, 0.0, 1.0);
- gl_FragColor = vec4(0.0, 0.0, 0.0, coverage);
+ halftoneColor = vec4(0.0, 0.0, 0.0, coverage);
} else {
if (diff >= 0.0) {
- gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);
+ halftoneColor = vec4(0.0, 0.0, 0.0, 1.0);
} else {
- gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);
+ halftoneColor = vec4(0.0, 0.0, 0.0, 0.0);
}
}
+
+ // Clip Studio Paint style Anti-Moiré Viewport Downsampling:
+ // When viewport zoom Z < 1.0, high-frequency dots alias against screen pixels.
+ // Smoothstep crossfade from discrete dot pattern to continuous grayscale luminance.
+ float moireBlend = smoothstep(0.35, 0.95, u_zoom);
+ vec4 contColor = vec4(0.0, 0.0, 0.0, density);
+ gl_FragColor = mix(contColor, halftoneColor, moireBlend);
}
`;
@@ -525,6 +559,7 @@ class WebGLHalftonePipeline {
this.uAntiAliasingLoc = gl.getUniformLocation(prog, 'u_antiAliasing');
this.uDensityTypeLoc = gl.getUniformLocation(prog, 'u_densityType');
this.uSpecifiedDensityLoc = gl.getUniformLocation(prog, 'u_specifiedDensity');
+ this.uZoomLoc = gl.getUniformLocation(prog, 'u_zoom');
this.texture = gl.createTexture();
return true;
@@ -533,6 +568,8 @@ class WebGLHalftonePipeline {
}
}
+ private uZoomLoc: WebGLUniformLocation | null = null;
+
public render(
sourceCanvas: HTMLCanvasElement,
targetCanvas: HTMLCanvasElement,
@@ -636,12 +673,15 @@ class WebGLHalftonePipeline {
gl.uniform2f(this.uRegionSizeLoc, regionW, regionH);
gl.uniform1f(this.uAngleRadLoc, rad);
gl.uniform1f(this.uCellSizeLoc, cellSize);
- const dotShapeVal = options.dotShape === 'line' ? 2 : (options.dotShape === 'euclidean' ? 1 : 0);
+ const dotShapeVal = options.dotShape === 'line' ? 2 : options.dotShape === 'diamond' ? 3 : (options.dotShape === 'euclidean' ? 1 : 0);
gl.uniform1i(this.uDotShapeLoc, dotShapeVal);
gl.uniform1i(this.uSolidBlackAtMaxLoc, options.solidBlackAtMax !== false ? 1 : 0);
gl.uniform1i(this.uAntiAliasingLoc, options.antiAliasing !== false ? 1 : 0);
gl.uniform1i(this.uDensityTypeLoc, options.densityType === 'image' ? 1 : 0);
gl.uniform1f(this.uSpecifiedDensityLoc, Math.max(0, Math.min(1, options.specifiedDensity ?? 0.4)));
+ if (this.uZoomLoc) {
+ gl.uniform1f(this.uZoomLoc, options.zoom ?? 1.0);
+ }
// Render to GL canvas
gl.drawArrays(gl.TRIANGLES, 0, 6);
diff --git a/src/utils/stampEngine.ts b/src/utils/stampEngine.ts
index 32f4d18..a4d1ddc 100644
--- a/src/utils/stampEngine.ts
+++ b/src/utils/stampEngine.ts
@@ -50,6 +50,8 @@ export interface TexturedBrushOptions {
reservoir?: PaintReservoir;
isEraser?: boolean;
isBgEraser?: boolean;
+ alphaLocked?: boolean;
+ isTransparentInk?: boolean;
strokeIndex?: number;
totalLength?: number;
currentStrokeDist?: number;
@@ -79,20 +81,19 @@ function getPooledCanvas(w: number, h: number): HTMLCanvasElement {
}
/**
- * Returns a tinted master offscreen canvas for the given tip and color.
+ * Generic tinted master offscreen canvas generator.
* Uses 15-bit color quantization to achieve 98%+ cache hit rates during smooth color blends.
*/
-export function getTintedTipMaster(
- tipImage: HTMLImageElement,
+export function getTintedMasterCanvas(
+ source: CanvasImageSource,
+ sourceKey: string,
color: string,
+ w: number,
+ h: number,
isColorTip: boolean = false
): HTMLCanvasElement {
- const w = tipImage.naturalWidth || tipImage.width || 64;
- const h = tipImage.naturalHeight || tipImage.height || 64;
-
if (isColorTip) {
- // Retain multi-color tip pixels directly
- const key = `color_${tipImage.src.slice(0, 48)}_${w}x${h}`;
+ const key = `color_${sourceKey}_${w}x${h}`;
const cached = tintedMasterCache.get(key);
if (cached) return cached;
@@ -100,7 +101,7 @@ export function getTintedTipMaster(
const ctx = canvas.getContext('2d');
if (ctx) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
- ctx.drawImage(tipImage, 0, 0, canvas.width, canvas.height);
+ ctx.drawImage(source, 0, 0, canvas.width, canvas.height);
}
tintedMasterCache.set(key, canvas);
return canvas;
@@ -112,8 +113,7 @@ export function getTintedTipMaster(
const qB = (rgb.b >> 3) << 3;
const quantizedHex = rgbToHex(qR, qG, qB);
- const key = `${tipImage.src.slice(0, 48)}_${quantizedHex}_${w}x${h}`;
-
+ const key = `${sourceKey}_${quantizedHex}_${w}x${h}`;
const cached = tintedMasterCache.get(key);
if (cached) return cached;
@@ -135,7 +135,7 @@ export function getTintedTipMaster(
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.globalCompositeOperation = 'source-over';
- ctx.drawImage(tipImage, 0, 0, canvas.width, canvas.height);
+ ctx.drawImage(source, 0, 0, canvas.width, canvas.height);
ctx.globalCompositeOperation = 'source-in';
ctx.fillStyle = quantizedHex;
@@ -145,6 +145,87 @@ export function getTintedTipMaster(
return canvas;
}
+/**
+ * Returns a tinted master offscreen canvas for the given tip and color.
+ */
+export function getTintedTipMaster(
+ tipImage: HTMLImageElement,
+ color: string,
+ isColorTip: boolean = false
+): HTMLCanvasElement {
+ const w = tipImage.naturalWidth || tipImage.width || 64;
+ const h = tipImage.naturalHeight || tipImage.height || 64;
+ return getTintedMasterCanvas(tipImage, tipImage.src.slice(0, 48), 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.
+ */
+export function getRadialDabMaster(
+ hardness: number,
+ color: string,
+ isEraser: boolean = false
+): HTMLCanvasElement {
+ const clampedH = Math.max(0, Math.min(1.0, hardness));
+ const qH = Math.round(clampedH * 20) / 20;
+
+ let maskCanvas = radialMaskCache.get(qH);
+ if (!maskCanvas) {
+ const size = 128;
+ maskCanvas = document.createElement('canvas');
+ maskCanvas.width = size;
+ maskCanvas.height = size;
+ const ctx = maskCanvas.getContext('2d');
+ if (ctx) {
+ const imgData = ctx.createImageData(size, size);
+ const data = imgData.data;
+ const cx = size / 2;
+ const cy = size / 2;
+ const radius = size / 2 - 2; // 62px
+ const rCore = radius * qH;
+
+ for (let y = 0; y < size; y++) {
+ const dy = y - cy + 0.5;
+ const rowOffset = y * size * 4;
+ for (let x = 0; x < size; x++) {
+ const dx = x - cx + 0.5;
+ const dist = Math.hypot(dx, dy);
+ let alpha = 0;
+ if (qH >= 0.98) {
+ // Crisp anti-aliased disk with sub-pixel edge
+ alpha = Math.max(0, Math.min(1.0, radius - dist + 0.5));
+ } else if (dist <= rCore) {
+ alpha = 1.0;
+ } else if (dist < radius) {
+ const t = (dist - rCore) / (radius - rCore);
+ if (qH <= 0.05) {
+ alpha = 0.5 * (1.0 + Math.cos(t * Math.PI));
+ } else {
+ alpha = 1.0 - (3.0 * t * t - 2.0 * t * t * t);
+ }
+ }
+
+ if (alpha > 0.002) {
+ const idx = rowOffset + x * 4;
+ data[idx] = 255;
+ data[idx + 1] = 255;
+ data[idx + 2] = 255;
+ data[idx + 3] = Math.round(alpha * 255);
+ }
+ }
+ }
+ ctx.putImageData(imgData, 0, 0);
+ }
+ radialMaskCache.set(qH, maskCanvas);
+ }
+
+ const effectiveColor = isEraser ? '#000000' : color;
+ return getTintedMasterCanvas(maskCanvas, `radial_${qH}`, effectiveColor, 128, 128);
+}
+
/**
* Draws a single textured brush stamp (dab) onto the destination context.
* Features an ultra-fast path for unrotated stamps (no save/restore overhead).
@@ -159,7 +240,9 @@ export function drawSingleStamp(
angleRad: number,
alpha: number,
isEraser: boolean = false,
- isBgEraser: boolean = false
+ isBgEraser: boolean = false,
+ alphaLocked: boolean = false,
+ isTransparentInk: boolean = false
) {
if (width < 0.1 || height < 0.1 || alpha <= 0.002) return;
@@ -169,7 +252,7 @@ export function drawSingleStamp(
const renderH = Math.max(0.6, height);
// Ultra-fast path for unrotated normal stamps
- if (Math.abs(angleRad) < 0.001 && !isEraser && !isBgEraser) {
+ if (Math.abs(angleRad) < 0.001 && !isEraser && !isBgEraser && !alphaLocked && !isTransparentInk) {
const prevAlpha = ctx.globalAlpha;
const prevOp = ctx.globalCompositeOperation;
ctx.globalCompositeOperation = 'source-over';
@@ -184,8 +267,10 @@ export function drawSingleStamp(
if (isBgEraser) {
ctx.globalCompositeOperation = 'source-over';
- } else if (isEraser) {
+ } else if (isTransparentInk || isEraser) {
ctx.globalCompositeOperation = 'destination-out';
+ } else if (alphaLocked) {
+ ctx.globalCompositeOperation = 'source-atop';
} else {
ctx.globalCompositeOperation = 'source-over';
}
@@ -303,9 +388,27 @@ export function drawTexturedDot(
const aspect = (activeTip.naturalHeight || activeTip.height || 1) / (activeTip.naturalWidth || activeTip.width || 1);
const thickness = options.thickness ?? 1.0;
- const w = effWidth;
- const h = w * aspect * thickness;
- const angleRad = ((options.angle ?? 0) * Math.PI) / 180;
+
+ const tiltX = point.tiltX ?? 0;
+ const tiltY = point.tiltY ?? 0;
+ const tiltAngleDeg = Math.min(90, Math.sqrt(tiltX * tiltX + tiltY * tiltY));
+ const tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180);
+
+ 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 (point.twist) {
+ angleRad += (point.twist * Math.PI) / 180;
+ }
if (options.spray?.enabled) {
const pCount = options.spray.density;
@@ -326,11 +429,26 @@ export function drawTexturedDot(
angleRad,
effectiveFlow,
isEraser,
- isBgEraser
+ isBgEraser,
+ options.alphaLocked,
+ options.isTransparentInk
);
}
} else {
- drawSingleStamp(ctx, master, point.x, point.y, w, h, angleRad, effectiveFlow, isEraser, isBgEraser);
+ drawSingleStamp(
+ ctx,
+ master,
+ point.x,
+ point.y,
+ w,
+ h,
+ angleRad,
+ effectiveFlow,
+ isEraser,
+ isBgEraser,
+ options.alphaLocked,
+ options.isTransparentInk
+ );
}
}
@@ -344,7 +462,7 @@ export function evalCubicBezier(
c2: Point,
p3: Point,
t: number
-): { x: number; y: number; width: number; pressure: number; dx: number; dy: number; speed: number } {
+): { x: number; y: number; width: number; pressure: number; dx: number; dy: number; speed: number; tiltX?: number; tiltY?: number; twist?: number } {
const invT = 1.0 - t;
const invT2 = invT * invT;
const invT3 = invT2 * invT;
@@ -360,6 +478,9 @@ export function evalCubicBezier(
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;
@@ -372,16 +493,16 @@ export function evalCubicBezier(
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 };
+ return { x, y, width, pressure, dx, dy, speed, tiltX, tiltY, twist };
}
-interface ArcLengthTable {
+export interface ArcLengthTable {
totalLength: number;
distances: number[];
}
-function buildCubicArcLengthTable(p0: Point, c1: Point, c2: Point, p3: Point): ArcLengthTable {
- const steps = 8;
+export function buildCubicArcLengthTable(p0: Point, c1: Point, c2: Point, p3: Point): ArcLengthTable {
+ const steps = 24;
const distances: number[] = [0];
let total = 0;
let prevX = p0.x;
@@ -407,14 +528,14 @@ function buildCubicArcLengthTable(p0: Point, c1: Point, c2: Point, p3: Point): A
return { totalLength: total, distances };
}
-function getCubicPointAtArcLength(
+export function getCubicPointAtArcLength(
p0: Point,
c1: Point,
c2: Point,
p3: Point,
targetDist: number,
table: ArcLengthTable
-): { x: number; y: number; width: number; pressure: number; dx: number; dy: number; speed: number } {
+): { x: number; y: number; width: number; pressure: number; dx: number; dy: number; speed: number; tiltX?: number; tiltY?: number; twist?: number } {
const { totalLength, distances } = table;
if (totalLength <= 0.0001 || targetDist <= 0) {
return evalCubicBezier(p0, c1, c2, p3, 0);
@@ -423,15 +544,16 @@ function getCubicPointAtArcLength(
return evalCubicBezier(p0, c1, c2, p3, 1.0);
}
+ const steps = distances.length - 1;
let idx = 0;
- while (idx < 8 && distances[idx + 1] < targetDist) {
+ while (idx < steps && distances[idx + 1] < targetDist) {
idx++;
}
const d0 = distances[idx];
const d1 = distances[idx + 1];
const frac = d1 > d0 ? (targetDist - d0) / (d1 - d0) : 0;
- const t = (idx + frac) / 8.0;
+ const t = (idx + frac) / steps;
return evalCubicBezier(p0, c1, c2, p3, Math.max(0, Math.min(1.0, t)));
}
@@ -585,8 +707,26 @@ export function drawTexturedCubicBezierSegment(
const isColorTip = Boolean(options.subTips && options.subTips[0]?.isColor);
const master = getTintedTipMaster(activeTip, dabColor, isColorTip);
- const stampW = curWidth;
- const stampH = curWidth * aspect * thickness;
+ 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 stampW = curWidth;
+ let stampH = curWidth * aspect * thickness;
+ let dabAngle = stampAngle;
+
+ if (tiltMagnitude > 0.01) {
+ const tiltAzimuth = Math.atan2(tiltY, tiltX);
+ stampW = curWidth * (1.0 + tiltMagnitude * 1.8);
+ stampH = (curWidth * aspect * thickness) / (1.0 + tiltMagnitude * 0.5);
+ if (tiltMagnitude > 0.05) {
+ dabAngle = tiltAzimuth;
+ }
+ }
+ if (pt.twist) {
+ dabAngle += (pt.twist * Math.PI) / 180;
+ }
if (options.spray?.enabled) {
const pCount = options.spray.density;
@@ -604,10 +744,12 @@ export function drawTexturedCubicBezierSegment(
pt.y + r * Math.sin(th),
pSize,
pSize * aspect * thickness,
- stampAngle,
+ dabAngle,
dabAlpha,
isEraser,
- isBgEraser
+ isBgEraser,
+ options.alphaLocked,
+ options.isTransparentInk
);
}
} else {
@@ -618,10 +760,12 @@ export function drawTexturedCubicBezierSegment(
pt.y,
stampW,
stampH,
- stampAngle,
+ dabAngle,
dabAlpha,
isEraser,
- isBgEraser
+ isBgEraser,
+ options.alphaLocked,
+ options.isTransparentInk
);
}
@@ -783,3 +927,365 @@ export function renderCompleteTexturedStroke(
const last = catmullRomToCubicKnots(pPrev2, pPrev, pLast, pLast);
drawTexturedCubicBezierSegment(ctx, pPrev, last.c1, last.c2, pLast, color, tipImage, options, accDist, dabCounter);
}
+
+/**
+ * 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,
+ p1: Point,
+ p2: Point,
+ p3: Point
+): { c1: Point; c2: Point } {
+ 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 > 0.001) {
+ const maxHandle = d12 * 0.48;
+ const len1 = Math.hypot(dx1, dy1);
+ if (len1 > maxHandle) {
+ const s = maxHandle / len1;
+ dx1 *= s;
+ dy1 *= s;
+ }
+ const len2 = Math.hypot(dx2, dy2);
+ if (len2 > maxHandle) {
+ const s = maxHandle / len2;
+ dx2 *= s;
+ dy2 *= s;
+ }
+ }
+
+ const 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 };
+}
+
+export interface RadialMixingOptions {
+ colorMixing?: boolean;
+ amountOfPaint?: number;
+ densityOfPaint?: number;
+ colorStretch?: number;
+ mixingMode?: 'blend' | 'running_color';
+ underlyingCanvas?: HTMLCanvasElement;
+ sampler?: LayerPixelSampler;
+ reservoir?: PaintReservoir;
+ alphaLocked?: boolean;
+ isTransparentInk?: boolean;
+}
+
+/**
+ * Draws a single radial dot.
+ */
+export function drawRadialDot(
+ ctx: CanvasRenderingContext2D,
+ point: Point,
+ color: string,
+ hardness: number = 1.0,
+ flow: number = 1.0,
+ isEraser: boolean = false,
+ isBgEraser: boolean = false,
+ mixingOptions?: RadialMixingOptions
+) {
+ const isColorMixing = Boolean(mixingOptions?.colorMixing) && !isEraser && !isBgEraser;
+ let dabColor = isBgEraser ? '#ffffff' : color;
+ let dabFlow = flow;
+ const w = Math.max(0.5, point.width);
+
+ if (isColorMixing) {
+ if (!mixingOptions!.reservoir) {
+ mixingOptions!.reservoir = new PaintReservoir(dabColor);
+ }
+ const reservoir = mixingOptions!.reservoir;
+ let sampled = { r: 255, g: 255, b: 255, a: 0 };
+ if (mixingOptions!.sampler) {
+ sampled = mixingOptions!.sampler.sampleColor(point.x, point.y, Math.max(1, w / 2));
+ } else {
+ const sampleCanvas = mixingOptions!.underlyingCanvas || ctx.canvas;
+ const sampleCtx = sampleCanvas ? sampleCanvas.getContext('2d') : null;
+ if (sampleCtx) {
+ sampled = sampleCanvasColor(sampleCtx, point.x, point.y, Math.max(1, w / 2));
+ }
+ }
+
+ const mixed = reservoir.mixWithCanvas(
+ sampled,
+ mixingOptions!.amountOfPaint ?? 0.65,
+ mixingOptions!.densityOfPaint ?? 0.9,
+ mixingOptions!.colorStretch ?? 0.75,
+ mixingOptions!.mixingMode ?? 'blend',
+ point.pressure ?? 1.0,
+ flow,
+ 0
+ );
+
+ dabColor = mixed.colorHex;
+ dabFlow = mixed.alpha;
+
+ if (mixingOptions!.sampler) {
+ mixingOptions!.sampler.depositDab(
+ point.x,
+ point.y,
+ w * 0.5,
+ mixed.r,
+ mixed.g,
+ mixed.b,
+ mixed.alpha
+ );
+ }
+ }
+
+ const tiltX = point.tiltX ?? 0;
+ const tiltY = point.tiltY ?? 0;
+ const tiltAngleDeg = Math.min(90, Math.sqrt(tiltX * tiltX + tiltY * tiltY));
+ const tiltMagnitude = Math.sin((tiltAngleDeg * Math.PI) / 180);
+
+ let dotW = w;
+ let dotH = w;
+ let dotAngle = 0;
+ if (tiltMagnitude > 0.01) {
+ const tiltAzimuth = Math.atan2(tiltY, tiltX);
+ dotW = w * (1.0 + tiltMagnitude * 1.8);
+ dotH = w / (1.0 + tiltMagnitude * 0.5);
+ if (tiltMagnitude > 0.05) {
+ dotAngle = tiltAzimuth;
+ }
+ }
+ if (point.twist) {
+ dotAngle += (point.twist * Math.PI) / 180;
+ }
+
+ const master = getRadialDabMaster(hardness, dabColor, isEraser && !isBgEraser);
+ drawSingleStamp(
+ ctx,
+ master,
+ point.x,
+ point.y,
+ dotW,
+ dotH,
+ dotAngle,
+ dabFlow,
+ isEraser,
+ isBgEraser,
+ mixingOptions?.alphaLocked,
+ mixingOptions?.isTransparentInk
+ );
+}
+
+/**
+ * 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.
+ */
+export function drawRadialCubicBezierSegment(
+ ctx: CanvasRenderingContext2D,
+ p0: Point,
+ c1: Point,
+ c2: Point,
+ p3: Point,
+ color: string,
+ hardness: number = 1.0,
+ flow: number = 1.0,
+ spacing: number = 0.06,
+ isEraser: boolean = false,
+ isBgEraser: boolean = false,
+ remainderDist: number = 0,
+ thickness: number = 1.0,
+ angleRad: number = 0,
+ mixingOptions?: RadialMixingOptions
+): number {
+ const arcTable = buildCubicArcLengthTable(p0, c1, c2, p3);
+ const totalCurveLength = arcTable.totalLength;
+ if (totalCurveLength < 0.1) {
+ return remainderDist;
+ }
+
+ const isColorMixing = Boolean(mixingOptions?.colorMixing) && !isEraser && !isBgEraser;
+ if (isColorMixing && mixingOptions && !mixingOptions.reservoir) {
+ mixingOptions.reservoir = new PaintReservoir(color);
+ }
+ const reservoir = mixingOptions?.reservoir;
+ const sampler = mixingOptions?.sampler;
+ const staticMaster = isColorMixing ? null : getRadialDabMaster(hardness, color, isEraser && !isBgEraser);
+ const spacingRatio = Math.max(0.015, Math.min(1.0, spacing));
+ let currentDist = remainderDist > 0 ? remainderDist : 0;
+
+ while (currentDist <= totalCurveLength) {
+ const pt = getCubicPointAtArcLength(p0, c1, c2, p3, currentDist, arcTable);
+ const curWidth = Math.max(0.4, pt.width);
+ const curHeight = curWidth * thickness;
+ const requiredStep = Math.max(0.4, curWidth * spacingRatio);
+
+ 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 dabW = curWidth;
+ let dabH = curHeight;
+ let dabRot = angleRad;
+
+ if (tiltMagnitude > 0.01) {
+ const tiltAzimuth = Math.atan2(tiltY, tiltX);
+ dabW = curWidth * (1.0 + tiltMagnitude * 1.8);
+ dabH = curHeight / (1.0 + tiltMagnitude * 0.5);
+ if (tiltMagnitude > 0.05) {
+ dabRot = tiltAzimuth;
+ }
+ }
+ if (pt.twist) {
+ dabRot += (pt.twist * Math.PI) / 180;
+ }
+
+ let dabMaster = staticMaster;
+ let dabFlow = flow;
+
+ if (isColorMixing && reservoir) {
+ let sampled = { r: 255, g: 255, b: 255, a: 0 };
+ if (sampler) {
+ sampled = sampler.sampleColor(pt.x, pt.y, curWidth * 0.45);
+ } else {
+ const sampleCanvas = mixingOptions?.underlyingCanvas || ctx.canvas;
+ const sampleCtx = sampleCanvas ? sampleCanvas.getContext('2d') : null;
+ if (sampleCtx) {
+ sampled = sampleCanvasColor(sampleCtx, pt.x, pt.y, curWidth * 0.45);
+ }
+ }
+
+ const mixed = reservoir.mixWithCanvas(
+ sampled,
+ mixingOptions?.amountOfPaint ?? 0.65,
+ mixingOptions?.densityOfPaint ?? 0.9,
+ mixingOptions?.colorStretch ?? 0.75,
+ mixingOptions?.mixingMode ?? 'blend',
+ pt.pressure ?? 1.0,
+ flow,
+ requiredStep
+ );
+
+ dabMaster = getRadialDabMaster(hardness, mixed.colorHex, false);
+ dabFlow = mixed.alpha;
+
+ if (sampler) {
+ sampler.depositDab(
+ pt.x,
+ pt.y,
+ curWidth * 0.45,
+ mixed.r,
+ mixed.g,
+ mixed.b,
+ mixed.alpha
+ );
+ }
+ }
+
+ if (dabMaster) {
+ drawSingleStamp(
+ ctx,
+ dabMaster,
+ pt.x,
+ pt.y,
+ dabW,
+ dabH,
+ dabRot,
+ dabFlow,
+ isEraser,
+ isBgEraser,
+ mixingOptions?.alphaLocked,
+ mixingOptions?.isTransparentInk
+ );
+ }
+
+ currentDist += requiredStep;
+ }
+
+ const nextRemainder = currentDist - totalCurveLength;
+ return Math.max(0, nextRemainder);
+}
+
+/**
+ * Renders an entire completed radial dab stroke onto the target context.
+ */
+export function renderCompleteRadialStroke(
+ ctx: CanvasRenderingContext2D,
+ points: Point[],
+ color: string,
+ hardness: number = 1.0,
+ flow: number = 1.0,
+ spacing: number = 0.06,
+ isEraser: boolean = false,
+ isBgEraser: boolean = false,
+ thickness: number = 1.0,
+ angleRad: number = 0,
+ mixingOptions?: RadialMixingOptions
+) {
+ if (!points || points.length === 0) return;
+
+ if (mixingOptions?.colorMixing && !isEraser && !isBgEraser) {
+ if (!mixingOptions.reservoir) {
+ mixingOptions.reservoir = new PaintReservoir(color);
+ }
+ if (!mixingOptions.sampler && mixingOptions.underlyingCanvas) {
+ mixingOptions.sampler = new LayerPixelSampler(mixingOptions.underlyingCanvas);
+ }
+ }
+
+ drawRadialDot(ctx, points[0], color, hardness, flow, isEraser, isBgEraser, mixingOptions);
+ if (points.length === 1) return;
+
+ let accDist = Math.max(0.4, points[0].width * 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;
+ }
+
+ 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);
+ }
+
+ 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);
+}
+
diff --git a/src/utils/tileEngine.ts b/src/utils/tileEngine.ts
new file mode 100644
index 0000000..4d3ffdc
--- /dev/null
+++ b/src/utils/tileEngine.ts
@@ -0,0 +1,1102 @@
+/**
+ * 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.
+ */
+
+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 type TileFormat = 'monochrome-1bit' | 'grayscale-8bit' | 'color-32bit';
+
+export interface TileBuffer {
+ layerId: string;
+ tileX: number;
+ tileY: number;
+ format: TileFormat;
+ data: Uint8Array;
+ dirty: boolean;
+ version: number;
+}
+
+// System endianness detection for 32-bit operations
+export const isLittleEndian = (() => {
+ const buf = new ArrayBuffer(4);
+ new Uint32Array(buf)[0] = 0x11223344;
+ return new Uint8Array(buf)[0] === 0x44;
+})();
+
+// Default binary colors in system byte order
+// Black ink: RGBA(0, 0, 0, 255)
+export const INK_BLACK_U32 = isLittleEndian ? 0xff000000 : 0x000000ff;
+// Transparent: RGBA(0, 0, 0, 0)
+export const TRANSPARENT_U32 = 0x00000000;
+// Paper white: RGBA(255, 255, 255, 255)
+export const PAPER_WHITE_U32 = 0xffffffff;
+
+/**
+ * 256-entry lookup table mapping a 1-bit byte (8 pixels)
+ * into eight 32-bit pixel values for ultra-fast zero-loop unpacking.
+ */
+const LUT_1BIT_TO_RGBA_BLACK = new Uint32Array(256 * 8);
+const LUT_1BIT_TO_RGBA_WHITE = new Uint32Array(256 * 8);
+
+for (let b = 0; b < 256; b++) {
+ const offset = b * 8;
+ for (let bit = 0; bit < 8; bit++) {
+ // MSB first: bit 7 is the leftmost pixel
+ const isSet = (b & (1 << (7 - bit))) !== 0;
+ LUT_1BIT_TO_RGBA_BLACK[offset + bit] = isSet ? INK_BLACK_U32 : TRANSPARENT_U32;
+ LUT_1BIT_TO_RGBA_WHITE[offset + bit] = isSet ? PAPER_WHITE_U32 : TRANSPARENT_U32;
+ }
+}
+
+/**
+ * Get tile coordinate from document pixel coordinate.
+ */
+export function pixelToTileCoord(pixel: number): number {
+ return Math.floor(pixel / TILE_SIZE);
+}
+
+/**
+ * Spatial hash map key for tiles.
+ */
+export function getTileKey(layerId: string, tileX: number, tileY: number): string {
+ return `${layerId}:${tileX}:${tileY}`;
+}
+
+/**
+ * Parse spatial hash map key into components.
+ */
+export function parseTileKey(key: string): { layerId: string; tileX: number; tileY: number } {
+ const parts = key.split(':');
+ return {
+ layerId: parts[0],
+ tileX: parseInt(parts[1], 10),
+ tileY: parseInt(parts[2], 10),
+ };
+}
+
+/**
+ * Allocate a new TileBuffer with zero-initialized memory.
+ */
+export function createTileBuffer(
+ layerId: string,
+ tileX: number,
+ tileY: number,
+ format: TileFormat
+): TileBuffer {
+ let size = BYTES_32BIT;
+ if (format === 'monochrome-1bit') size = BYTES_1BIT;
+ else if (format === 'grayscale-8bit') size = BYTES_8BIT;
+
+ return {
+ layerId,
+ tileX,
+ tileY,
+ format,
+ data: new Uint8Array(size),
+ dirty: true,
+ version: 1,
+ };
+}
+
+/**
+ * Set a single 1-bit pixel (MSB first packing).
+ */
+export function setPixel1Bit(data: Uint8Array, x: number, y: number, value: boolean | number): void {
+ const pixelIndex = y * TILE_SIZE + x;
+ const byteIndex = pixelIndex >> 3;
+ const bitOffset = 7 - (pixelIndex & 7);
+ if (value) {
+ data[byteIndex] |= (1 << bitOffset);
+ } else {
+ data[byteIndex] &= ~(1 << bitOffset);
+ }
+}
+
+/**
+ * Get a single 1-bit pixel (MSB first packing). Returns 0 or 1.
+ */
+export function getPixel1Bit(data: Uint8Array, x: number, y: number): number {
+ const pixelIndex = y * TILE_SIZE + x;
+ const byteIndex = pixelIndex >> 3;
+ const bitOffset = 7 - (pixelIndex & 7);
+ return (data[byteIndex] >> bitOffset) & 1;
+}
+
+/**
+ * Unpacks an 8,192-byte 1-bit tile into a 262,144-byte RGBA buffer
+ * using the precomputed 32-bit LUT.
+ */
+export function unpack1BitToRGBA(
+ src1Bit: Uint8Array,
+ dstRGBA: Uint8ClampedArray | Uint8Array,
+ inkColorU32: number = INK_BLACK_U32,
+ paperColorU32: number = TRANSPARENT_U32
+): void {
+ const dst32 = new Uint32Array(dstRGBA.buffer, dstRGBA.byteOffset, TILE_PIXELS);
+
+ if (inkColorU32 === INK_BLACK_U32 && paperColorU32 === TRANSPARENT_U32) {
+ // Fast path: direct copy from black ink LUT
+ let dstOffset = 0;
+ for (let i = 0; i < BYTES_1BIT; i++) {
+ const lutOffset = src1Bit[i] * 8;
+ dst32[dstOffset] = LUT_1BIT_TO_RGBA_BLACK[lutOffset];
+ dst32[dstOffset + 1] = LUT_1BIT_TO_RGBA_BLACK[lutOffset + 1];
+ dst32[dstOffset + 2] = LUT_1BIT_TO_RGBA_BLACK[lutOffset + 2];
+ dst32[dstOffset + 3] = LUT_1BIT_TO_RGBA_BLACK[lutOffset + 3];
+ dst32[dstOffset + 4] = LUT_1BIT_TO_RGBA_BLACK[lutOffset + 4];
+ dst32[dstOffset + 5] = LUT_1BIT_TO_RGBA_BLACK[lutOffset + 5];
+ dst32[dstOffset + 6] = LUT_1BIT_TO_RGBA_BLACK[lutOffset + 6];
+ dst32[dstOffset + 7] = LUT_1BIT_TO_RGBA_BLACK[lutOffset + 7];
+ dstOffset += 8;
+ }
+ } else {
+ // General path with custom colors
+ let dstOffset = 0;
+ for (let i = 0; i < BYTES_1BIT; i++) {
+ const b = src1Bit[i];
+ dst32[dstOffset] = (b & 0x80) ? inkColorU32 : paperColorU32;
+ dst32[dstOffset + 1] = (b & 0x40) ? inkColorU32 : paperColorU32;
+ dst32[dstOffset + 2] = (b & 0x20) ? inkColorU32 : paperColorU32;
+ dst32[dstOffset + 3] = (b & 0x10) ? inkColorU32 : paperColorU32;
+ dst32[dstOffset + 4] = (b & 0x08) ? inkColorU32 : paperColorU32;
+ dst32[dstOffset + 5] = (b & 0x04) ? inkColorU32 : paperColorU32;
+ dst32[dstOffset + 6] = (b & 0x02) ? inkColorU32 : paperColorU32;
+ dst32[dstOffset + 7] = (b & 0x01) ? inkColorU32 : paperColorU32;
+ dstOffset += 8;
+ }
+ }
+}
+
+/**
+ * Packs a 256x256 RGBA buffer (262,144 bytes) into an 8,192-byte 1-bit tile.
+ * Applies perceptual ITU-R BT.601 luminance thresholding and alpha checking.
+ */
+export function packRGBATo1Bit(
+ srcRGBA: Uint8ClampedArray | Uint8Array,
+ dst1Bit: Uint8Array,
+ threshold: number = 128
+): void {
+ dst1Bit.fill(0);
+ let srcOffset = 0;
+ let dstByte = 0;
+
+ for (let i = 0; i < BYTES_1BIT; i++) {
+ let byteVal = 0;
+ for (let bit = 7; bit >= 0; bit--) {
+ const r = srcRGBA[srcOffset];
+ const g = srcRGBA[srcOffset + 1];
+ const b = srcRGBA[srcOffset + 2];
+ const a = srcRGBA[srcOffset + 3];
+
+ if (a >= 24) {
+ // Luminance: 0.299*R + 0.587*G + 0.114*B
+ const lum = (r * 299 + g * 587 + b * 114) / 1000;
+ // Dark pixels become ink (1), light pixels transparent (0)
+ if (lum < threshold) {
+ byteVal |= (1 << bit);
+ }
+ }
+ srcOffset += 4;
+ }
+ dst1Bit[dstByte++] = byteVal;
+ }
+}
+
+/**
+ * Unpacks an 8-bit grayscale tile into RGBA.
+ */
+export function unpack8BitToRGBA(
+ src8Bit: Uint8Array,
+ dstRGBA: Uint8ClampedArray | Uint8Array
+): void {
+ const dst32 = new Uint32Array(dstRGBA.buffer, dstRGBA.byteOffset, TILE_PIXELS);
+ for (let i = 0; i < TILE_PIXELS; i++) {
+ const val = src8Bit[i];
+ if (val === 0) {
+ dst32[i] = TRANSPARENT_U32;
+ } else {
+ // 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
+ : (val << 24) | (val << 16) | (val << 8) | a;
+ }
+ }
+}
+
+/**
+ * Packs RGBA to 8-bit grayscale using perceptual ITU-R BT.601 luminance.
+ */
+export function packRGBATo8Bit(
+ srcRGBA: Uint8ClampedArray | Uint8Array,
+ dst8Bit: Uint8Array
+): void {
+ let srcOffset = 0;
+ for (let i = 0; i < TILE_PIXELS; i++) {
+ const a = srcRGBA[srcOffset + 3];
+ if (a < 10) {
+ dst8Bit[i] = 0;
+ } else {
+ const r = srcRGBA[srcOffset];
+ const g = srcRGBA[srcOffset + 1];
+ const b = srcRGBA[srcOffset + 2];
+ dst8Bit[i] = Math.round((r * 299 + g * 587 + b * 114) / 1000);
+ }
+ srcOffset += 4;
+ }
+}
+
+/**
+ * High-speed Run-Length Encoding (RLE) for compressing tile data
+ * for network streaming and tile-delta history storage.
+ *
+ * Encoding format:
+ * [Count: 1 byte, Value: 1 byte] for repeating bytes up to 255 runs.
+ */
+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;
+
+ while (i < len) {
+ const val = data[i];
+ let run = 1;
+ while (i + run < len && data[i + run] === val && run < 255) {
+ run++;
+ }
+ output[outIdx++] = run;
+ output[outIdx++] = val;
+ i += run;
+ }
+
+ return output.subarray(0, outIdx);
+}
+
+/**
+ * Decompresses RLE-encoded byte buffer back to target length.
+ */
+export function decompressRLE(compressed: Uint8Array, expectedLength: number): Uint8Array {
+ const output = new Uint8Array(expectedLength);
+ let inIdx = 0;
+ let outIdx = 0;
+ const inLen = compressed.length;
+
+ while (inIdx < inLen && outIdx < expectedLength) {
+ const count = compressed[inIdx++];
+ const val = compressed[inIdx++];
+ for (let c = 0; c < count && outIdx < expectedLength; c++) {
+ output[outIdx++] = val;
+ }
+ }
+
+ return output;
+}
+
+/**
+ * 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 packet = new Uint8Array(headerSize + rle.length);
+ const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);
+
+ view.setInt32(0, tile.tileX, true);
+ view.setInt32(4, tile.tileY, true);
+ const formatCode = tile.format === 'monochrome-1bit' ? 1 : tile.format === 'grayscale-8bit' ? 2 : 4;
+ view.setUint8(8, formatCode);
+ view.setUint32(9, tile.version, true);
+
+ packet.set(rle, headerSize);
+ return packet;
+}
+
+/**
+ * Deserializes a TileBuffer from a binary packet.
+ */
+export function deserializeTileBuffer(layerId: string, packet: Uint8Array): TileBuffer {
+ const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);
+ const tileX = view.getInt32(0, true);
+ const tileY = view.getInt32(4, true);
+ const formatCode = view.getUint8(8);
+ const version = view.getUint32(9, true);
+
+ const format: TileFormat = formatCode === 1 ? 'monochrome-1bit' : formatCode === 2 ? 'grayscale-8bit' : 'color-32bit';
+ let expectedLen = BYTES_32BIT;
+ if (format === 'monochrome-1bit') expectedLen = BYTES_1BIT;
+ else if (format === 'grayscale-8bit') expectedLen = BYTES_8BIT;
+
+ const rlePayload = packet.subarray(13);
+ const data = decompressRLE(rlePayload, expectedLen);
+
+ return {
+ layerId,
+ tileX,
+ tileY,
+ format,
+ data,
+ dirty: true,
+ version,
+ };
+}
+
+/**
+ * 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!
+ */
+export class SparseTileGrid {
+ private tiles: Map<string, TileBuffer> = new Map();
+ private layerFormats: Map<string, TileFormat> = new Map();
+ private scratchRGBA: Uint8ClampedArray = new Uint8ClampedArray(BYTES_32BIT);
+ private listeners: Set<(immediate?: boolean) => void> = new Set();
+
+ constructor() {}
+
+ public subscribe(listener: (immediate?: boolean) => void): () => void {
+ this.listeners.add(listener);
+ return () => this.listeners.delete(listener);
+ }
+
+ public notifyChange(immediate?: boolean): void {
+ 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));
+ }
+
+ /**
+ * 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;
+ }
+
+ /**
+ * 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);
+ let tile = this.tiles.get(key);
+ if (!tile) {
+ const fmt = format || this.getLayerFormat(layerId);
+ tile = createTileBuffer(layerId, tileX, tileY, fmt);
+ this.tiles.set(key, 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);
+ this.tiles.set(key, tile);
+ 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));
+ }
+
+ /**
+ * Get all allocated tiles for a layer.
+ */
+ public getLayerTiles(layerId: string): TileBuffer[] {
+ const prefix = `${layerId}:`;
+ const result: TileBuffer[] = [];
+ for (const [key, tile] of this.tiles.entries()) {
+ if (key.startsWith(prefix)) {
+ 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
+ ): TileBuffer[] {
+ const minTileX = pixelToTileCoord(minX);
+ const minTileY = pixelToTileCoord(minY);
+ const maxTileX = pixelToTileCoord(maxX);
+ const maxTileY = pixelToTileCoord(maxY);
+
+ const result: TileBuffer[] = [];
+ for (let ty = minTileY; ty <= maxTileY; ty++) {
+ for (let tx = minTileX; tx <= maxTileX; tx++) {
+ const tile = this.getTile(layerId, tx, ty);
+ if (tile) {
+ result.push(tile);
+ }
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Get tile coordinates intersecting document bounds.
+ */
+ public getIntersectingCoords(
+ minX: number,
+ minY: number,
+ maxX: number,
+ maxY: number
+ ): Array<{ tileX: number; tileY: number }> {
+ const minTileX = pixelToTileCoord(minX);
+ const minTileY = pixelToTileCoord(minY);
+ const maxTileX = pixelToTileCoord(maxX);
+ const maxTileY = pixelToTileCoord(maxY);
+
+ const coords: Array<{ tileX: number; tileY: number }> = [];
+ for (let ty = minTileY; ty <= maxTileY; ty++) {
+ for (let tx = minTileX; tx <= maxTileX; tx++) {
+ coords.push({ tileX: tx, tileY: ty });
+ }
+ }
+ return coords;
+ }
+
+ /**
+ * Converts any tile to a 256x256 RGBA Uint8ClampedArray for WebGL texture upload or 2D blitting.
+ */
+ public getTileAsRGBA(tile: TileBuffer): Uint8ClampedArray {
+ if (tile.format === 'color-32bit') {
+ return new Uint8ClampedArray(tile.data.buffer, tile.data.byteOffset, BYTES_32BIT);
+ }
+ if (tile.format === 'monochrome-1bit') {
+ unpack1BitToRGBA(tile.data, this.scratchRGBA);
+ return this.scratchRGBA;
+ }
+ // 8-bit grayscale
+ unpack8BitToRGBA(tile.data, this.scratchRGBA);
+ return this.scratchRGBA;
+ }
+
+ /**
+ * Writes an ImageData or RGBA buffer into the sparse tile grid.
+ * Only allocates tiles that actually intersect the drawn rectangle.
+ */
+ public writeImageData(
+ layerId: string,
+ imgData: { data: Uint8ClampedArray | Uint8Array; width: number; height: number },
+ destX: number,
+ destY: number,
+ format?: TileFormat
+ ): { minTileX: number; minTileY: number; maxTileX: number; maxTileY: number } {
+ const targetFormat = format || this.getLayerFormat(layerId);
+ const w = imgData.width;
+ const h = imgData.height;
+ if (w <= 0 || h <= 0) {
+ return { minTileX: 0, minTileY: 0, maxTileX: 0, maxTileY: 0 };
+ }
+
+ const minTileX = pixelToTileCoord(destX);
+ const minTileY = pixelToTileCoord(destY);
+ const maxTileX = pixelToTileCoord(destX + w - 1);
+ const maxTileY = pixelToTileCoord(destY + h - 1);
+
+ const tileScratch = new Uint8ClampedArray(BYTES_32BIT);
+
+ 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);
+ const srcEndY = Math.min(h, tileDocY + TILE_SIZE - destY);
+
+ if (srcStartX >= srcEndX || srcStartY >= srcEndY) continue;
+
+ const tile = this.getOrCreateTile(layerId, tx, ty, targetFormat);
+
+ // If tile is 32-bit RGBA
+ if (tile.format === 'color-32bit') {
+ for (let sy = srcStartY; sy < srcEndY; sy++) {
+ const tileLocalY = destY + sy - tileDocY;
+ const tileLocalX = destX + srcStartX - tileDocX;
+ const copyWidth = srcEndX - srcStartX;
+
+ const srcByteOffset = (sy * w + srcStartX) * 4;
+ const tileByteOffset = (tileLocalY * TILE_SIZE + tileLocalX) * 4;
+
+ tile.data.set(
+ imgData.data.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;
+ const copyWidth = srcEndX - srcStartX;
+
+ const srcByteOffset = (sy * w + srcStartX) * 4;
+ const tileByteOffset = (tileLocalY * TILE_SIZE + tileLocalX) * 4;
+
+ tileScratch.set(
+ imgData.data.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;
+ const tileLocalX = destX + srcStartX - tileDocX;
+ const copyWidth = srcEndX - srcStartX;
+
+ const srcByteOffset = (sy * w + srcStartX) * 4;
+ const tileByteOffset = (tileLocalY * TILE_SIZE + tileLocalX) * 4;
+
+ tileScratch.set(
+ imgData.data.subarray(srcByteOffset, srcByteOffset + copyWidth * 4),
+ tileByteOffset
+ );
+ }
+ packRGBATo8Bit(tileScratch, tile.data);
+ }
+
+ tile.dirty = true;
+ tile.version++;
+ }
+ }
+
+ 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,
+ y: number,
+ width: number,
+ height: number
+ ): { data: Uint8ClampedArray; width: number; height: number } {
+ const outData = new Uint8ClampedArray(width * height * 4);
+ if (width <= 0 || height <= 0) return { data: outData, width, height };
+
+ const minTileX = pixelToTileCoord(x);
+ const minTileY = pixelToTileCoord(y);
+ const maxTileX = pixelToTileCoord(x + width - 1);
+ const maxTileY = pixelToTileCoord(y + height - 1);
+
+ 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 tileDocX = tx * TILE_SIZE;
+ const tileRGBA = this.getTileAsRGBA(tile);
+
+ const interStartX = Math.max(x, tileDocX);
+ const interStartY = Math.max(y, tileDocY);
+ const interEndX = Math.min(x + width, tileDocX + TILE_SIZE);
+ const interEndY = Math.min(y + height, tileDocY + TILE_SIZE);
+
+ for (let py = interStartY; py < interEndY; py++) {
+ const tileLocalY = py - tileDocY;
+ const tileLocalX = interStartX - tileDocX;
+ const outLocalY = py - y;
+ const outLocalX = interStartX - x;
+ const copyWidth = interEndX - interStartX;
+
+ const tileOffset = (tileLocalY * TILE_SIZE + tileLocalX) * 4;
+ const outOffset = (outLocalY * width + outLocalX) * 4;
+
+ outData.set(tileRGBA.subarray(tileOffset, tileOffset + copyWidth * 4), outOffset);
+ }
+ }
+ }
+
+ return { data: outData, width, height };
+ }
+
+ /**
+ * Render an entire layer or a dirtyRect directly onto a standard HTMLCanvasElement.
+ */
+ public renderLayerToCanvas(
+ layerId: string,
+ targetCanvas: HTMLCanvasElement,
+ dirtyRect?: { x: number; y: number; width: number; height: number }
+ ): void {
+ const ctx = targetCanvas.getContext('2d');
+ if (!ctx) return;
+
+ let minX = 0;
+ let minY = 0;
+ let maxX = targetCanvas.width;
+ let maxY = targetCanvas.height;
+
+ if (dirtyRect) {
+ minX = Math.max(0, Math.floor(dirtyRect.x));
+ minY = Math.max(0, Math.floor(dirtyRect.y));
+ maxX = Math.min(targetCanvas.width, Math.ceil(dirtyRect.x + dirtyRect.width));
+ maxY = Math.min(targetCanvas.height, Math.ceil(dirtyRect.y + dirtyRect.height));
+ }
+
+ 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);
+
+ // 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);
+ if (!tile) continue;
+
+ const tileDocX = tx * TILE_SIZE;
+ const rgba = this.getTileAsRGBA(tile);
+
+ if (!helperCanvas) {
+ helperCanvas = document.createElement('canvas');
+ helperCanvas.width = TILE_SIZE;
+ helperCanvas.height = TILE_SIZE;
+ helperCtx = helperCanvas.getContext('2d');
+ }
+
+ if (helperCtx) {
+ 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);
+ ctx.drawImage(helperCanvas, tileDocX, tileDocY);
+ }
+ }
+ }
+ }
+
+ /**
+ * Ingest an existing HTMLCanvasElement into the tile grid.
+ */
+ public ingestCanvas(layerId: string, canvas: HTMLCanvasElement, format?: TileFormat): void {
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
+ if (!ctx || canvas.width <= 0 || canvas.height <= 0) return;
+
+ this.clearLayer(layerId);
+ const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ this.writeImageData(layerId, imgData, 0, 0, format);
+ this.notifyChange();
+ }
+
+ /**
+ * Clear all tiles associated with a layer.
+ */
+ public clearLayer(layerId: string): void {
+ const prefix = `${layerId}:`;
+ const toDelete: string[] = [];
+ for (const key of this.tiles.keys()) {
+ if (key.startsWith(prefix)) {
+ toDelete.push(key);
+ }
+ }
+ for (const key of toDelete) {
+ this.tiles.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);
+ for (const srcTile of srcTiles) {
+ const clonedData = new Uint8Array(srcTile.data.length);
+ clonedData.set(srcTile.data);
+ const clonedTile: TileBuffer = {
+ layerId: dstLayerId,
+ tileX: srcTile.tileX,
+ tileY: srcTile.tileY,
+ format: srcTile.format,
+ data: clonedData,
+ dirty: true,
+ version: 1,
+ };
+ this.setTile(dstLayerId, srcTile.tileX, srcTile.tileY, clonedTile);
+ }
+ }
+
+ /**
+ * Calculate exact memory consumption metrics.
+ */
+ public getMemoryStats(): {
+ totalBytes: number;
+ tileCount: number;
+ formatCounts: Record<TileFormat, number>;
+ } {
+ let totalBytes = 0;
+ const formatCounts: Record<TileFormat, number> = {
+ 'monochrome-1bit': 0,
+ 'grayscale-8bit': 0,
+ 'color-32bit': 0,
+ };
+
+ for (const tile of this.tiles.values()) {
+ totalBytes += tile.data.byteLength;
+ formatCounts[tile.format]++;
+ }
+
+ return {
+ totalBytes,
+ tileCount: this.tiles.size,
+ formatCounts,
+ };
+ }
+
+ /**
+ * 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 }
+ ): Map<string, { format: TileFormat; data: Uint8Array | null }> {
+ const snapshot = new Map<string, { format: TileFormat; data: Uint8Array | null }>();
+ if (bounds.width <= 0 || bounds.height <= 0) return snapshot;
+
+ const minTileX = pixelToTileCoord(bounds.x);
+ const minTileY = pixelToTileCoord(bounds.y);
+ const maxTileX = pixelToTileCoord(bounds.x + bounds.width - 1);
+ const maxTileY = pixelToTileCoord(bounds.y + bounds.height - 1);
+
+ 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 copy = new Uint8Array(tile.data.length);
+ copy.set(tile.data);
+ snapshot.set(key, { format: tile.format, data: copy });
+ } else {
+ snapshot.set(key, { format: layerFormat, data: null });
+ }
+ }
+ }
+
+ return snapshot;
+ }
+
+ /**
+ * 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,
+ bounds?: { x: number; y: number; width: number; height: number }
+ ): TileDelta[] {
+ 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);
+ for (let ty = minTileY; ty <= maxTileY; ty++) {
+ for (let tx = minTileX; tx <= maxTileX; tx++) {
+ keysToCheck.add(getTileKey(layerId, tx, ty));
+ }
+ }
+ }
+
+ for (const key of keysToCheck) {
+ const before = beforeSnapshot.get(key);
+ const { tileX, tileY } = parseTileKey(key);
+ const currentTile = this.getTile(layerId, tileX, tileY);
+
+ const beforeData = before ? before.data : null;
+ const afterData = currentTile ? new Uint8Array(currentTile.data) : null;
+ const format = currentTile ? currentTile.format : (before ? before.format : this.getLayerFormat(layerId));
+
+ if (beforeData === null && afterData === null) continue;
+
+ let changed = false;
+ if ((beforeData === null) !== (afterData === null)) {
+ changed = true;
+ } else if (beforeData && afterData) {
+ if (beforeData.byteLength !== afterData.byteLength) {
+ changed = true;
+ } else {
+ for (let i = 0; i < beforeData.byteLength; i++) {
+ if (beforeData[i] !== afterData[i]) {
+ changed = true;
+ break;
+ }
+ }
+ }
+ }
+
+ if (changed) {
+ deltas.push({
+ key,
+ format,
+ beforeData,
+ afterData,
+ });
+ }
+ }
+
+ 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);
+ } else {
+ let tile = this.getTile(layerId, tileX, tileY);
+ if (!tile) {
+ tile = this.getOrCreateTile(layerId, tileX, tileY, delta.format);
+ }
+ if (tile.data.byteLength === targetData.byteLength) {
+ tile.data.set(targetData);
+ } else {
+ tile.data = new Uint8Array(targetData.length);
+ tile.data.set(targetData);
+ tile.format = delta.format;
+ }
+ tile.dirty = true;
+ tile.version++;
+ }
+ }
+ this.notifyChange();
+ }
+
+ /**
+ * Reset the entire grid.
+ */
+ public clearAll(): void {
+ this.tiles.clear();
+ this.layerFormats.clear();
+ }
+}
+
+const FORMAT_TO_BYTE: Record<TileFormat, number> = {
+ 'monochrome-1bit': 0,
+ 'grayscale-8bit': 1,
+ 'color-32bit': 2,
+};
+
+const BYTE_TO_FORMAT: TileFormat[] = [
+ 'monochrome-1bit',
+ 'grayscale-8bit',
+ 'color-32bit',
+];
+
+/**
+ * Binary serialization for TileDelta array.
+ * Magic header: 0x54, 0x44 ('TD')
+ * Version: 1 (uint8)
+ * Count: uint32
+ */
+export function serializeTileDeltas(deltas: TileDelta[]): Uint8Array {
+ const encoder = new TextEncoder();
+ let totalBytes = 2 + 1 + 4; // Magic (2) + Version (1) + Count (4)
+ const encodedKeys: Uint8Array[] = [];
+
+ for (let i = 0; i < deltas.length; i++) {
+ const d = deltas[i];
+ const keyBytes = encoder.encode(d.key);
+ encodedKeys.push(keyBytes);
+
+ totalBytes += 2 + keyBytes.length; // keyLen (2) + bytes
+ totalBytes += 1; // format (1)
+ totalBytes += 1; // hasBefore (1)
+ if (d.beforeData && d.beforeData.byteLength > 0) {
+ totalBytes += 4 + d.beforeData.byteLength;
+ }
+ totalBytes += 1; // hasAfter (1)
+ if (d.afterData && d.afterData.byteLength > 0) {
+ totalBytes += 4 + d.afterData.byteLength;
+ }
+ }
+
+ const out = new Uint8Array(totalBytes);
+ const view = new DataView(out.buffer, out.byteOffset, totalBytes);
+
+ let offset = 0;
+ out[offset++] = 0x54; // 'T'
+ out[offset++] = 0x44; // 'D'
+ out[offset++] = 1; // Version
+ view.setUint32(offset, deltas.length, true);
+ offset += 4;
+
+ for (let i = 0; i < deltas.length; i++) {
+ const d = deltas[i];
+ const keyBytes = encodedKeys[i];
+
+ view.setUint16(offset, keyBytes.length, true);
+ offset += 2;
+ out.set(keyBytes, offset);
+ offset += keyBytes.length;
+
+ out[offset++] = FORMAT_TO_BYTE[d.format] ?? 2;
+
+ if (d.beforeData && d.beforeData.byteLength > 0) {
+ out[offset++] = 1;
+ view.setUint32(offset, d.beforeData.byteLength, true);
+ offset += 4;
+ out.set(d.beforeData, offset);
+ offset += d.beforeData.byteLength;
+ } else {
+ out[offset++] = 0;
+ }
+
+ if (d.afterData && d.afterData.byteLength > 0) {
+ out[offset++] = 1;
+ view.setUint32(offset, d.afterData.byteLength, true);
+ offset += 4;
+ out.set(d.afterData, offset);
+ offset += d.afterData.byteLength;
+ } else {
+ out[offset++] = 0;
+ }
+ }
+
+ return out;
+}
+
+/**
+ * Binary deserialization for TileDelta array.
+ */
+export function deserializeTileDeltas(buffer: Uint8Array): TileDelta[] {
+ if (buffer.byteLength < 7) {
+ throw new Error('Invalid TileDelta buffer: too short');
+ }
+ if (buffer[0] !== 0x54 || buffer[1] !== 0x44) {
+ throw new Error('Invalid TileDelta buffer: bad magic');
+ }
+ const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
+ const version = buffer[2];
+ if (version !== 1) {
+ throw new Error(`Unsupported TileDelta version: ${version}`);
+ }
+
+ let offset = 3;
+ const count = view.getUint32(offset, true);
+ offset += 4;
+
+ const decoder = new TextDecoder();
+ const deltas: TileDelta[] = [];
+
+ for (let i = 0; i < count; i++) {
+ const keyLen = view.getUint16(offset, true);
+ offset += 2;
+ const keyBytes = buffer.subarray(offset, offset + keyLen);
+ const key = decoder.decode(keyBytes);
+ offset += keyLen;
+
+ const formatByte = buffer[offset++];
+ const format = BYTE_TO_FORMAT[formatByte] || 'color-32bit';
+
+ const hasBefore = buffer[offset++];
+ let beforeData: Uint8Array | null = null;
+ if (hasBefore === 1) {
+ const bLen = view.getUint32(offset, true);
+ offset += 4;
+ beforeData = new Uint8Array(bLen);
+ beforeData.set(buffer.subarray(offset, offset + bLen));
+ offset += bLen;
+ }
+
+ const hasAfter = buffer[offset++];
+ let afterData: Uint8Array | null = null;
+ if (hasAfter === 1) {
+ const aLen = view.getUint32(offset, true);
+ offset += 4;
+ afterData = new Uint8Array(aLen);
+ afterData.set(buffer.subarray(offset, offset + aLen));
+ offset += aLen;
+ }
+
+ deltas.push({
+ key,
+ format,
+ beforeData,
+ afterData,
+ });
+ }
+
+ return deltas;
+}
+
+// Global sparse tile grid singleton
+export const globalTileGrid = new SparseTileGrid();
diff --git a/src/utils/undoCache.ts b/src/utils/undoCache.ts
new file mode 100644
index 0000000..649683a
--- /dev/null
+++ b/src/utils/undoCache.ts
@@ -0,0 +1,131 @@
+/**
+ * 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.
+ */
+
+import { TileDelta, HistoryItem } from '../types/editor';
+import { serializeTileDeltas, deserializeTileDeltas } from './tileEngine';
+
+export const MAX_RAM_UNDO_STEPS = 15;
+
+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
+ );
+}
+
+export class UndoCacheManager {
+ private sessionId: string;
+ private ramItems: Set<string> = new Set();
+ private diskCachedIds: Set<string> = new Set();
+
+ constructor(sessionId?: string) {
+ this.sessionId = sessionId || `session-${Date.now()}-${Math.random().toString(36).substring(2, 8)}`;
+ }
+
+ public getSessionId(): string {
+ return this.sessionId;
+ }
+
+ /**
+ * Register a history item and enforce the in-memory LRU budget.
+ */
+ public async registerStep(item: HistoryItem, allHistory: HistoryItem[]): Promise<void> {
+ 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
+ if (this.ramItems.size > MAX_RAM_UNDO_STEPS) {
+ // Find oldest items in allHistory that are still in ramItems
+ for (const oldItem of allHistory) {
+ if (oldItem.id !== item.id && this.ramItems.has(oldItem.id) && oldItem.tileDeltas) {
+ await this.offloadToDisk(oldItem);
+ this.ramItems.delete(oldItem.id);
+ if (this.ramItems.size <= MAX_RAM_UNDO_STEPS) break;
+ }
+ }
+ }
+ }
+
+ /**
+ * Offload a single history item's tile deltas to disk via Tauri IPC.
+ */
+ public async offloadToDisk(item: HistoryItem): Promise<void> {
+ if (!item.tileDeltas || item.tileDeltas.length === 0) return;
+
+ if (isTauriEnvironment()) {
+ try {
+ const { invoke } = await import('@tauri-apps/api/core');
+ const serialized = serializeTileDeltas(item.tileDeltas);
+ await invoke('save_undo_tile_cache', {
+ sessionId: this.sessionId,
+ stateId: item.id,
+ data: Array.from(serialized),
+ });
+ this.diskCachedIds.add(item.id);
+ // Free memory in RAM
+ item.tileDeltas = undefined;
+ } catch (err) {
+ console.warn('[UndoCache] Failed to offload tile deltas to disk:', err);
+ }
+ }
+ }
+
+ /**
+ * Retrieve tile deltas for a history item, restoring from disk if necessary.
+ */
+ public async resolveDeltas(item: HistoryItem): Promise<TileDelta[] | null> {
+ if (item.tileDeltas && item.tileDeltas.length > 0) {
+ return item.tileDeltas;
+ }
+
+ if (this.diskCachedIds.has(item.id) && isTauriEnvironment()) {
+ try {
+ const { invoke } = await import('@tauri-apps/api/core');
+ const rawData = await invoke<number[]>('load_undo_tile_cache', {
+ sessionId: this.sessionId,
+ stateId: item.id,
+ });
+ if (rawData && rawData.length > 0) {
+ const u8 = new Uint8Array(rawData);
+ const deltas = deserializeTileDeltas(u8);
+ // Re-populate item
+ item.tileDeltas = deltas;
+ this.ramItems.add(item.id);
+ return deltas;
+ }
+ } catch (err) {
+ console.warn('[UndoCache] Failed to restore tile deltas from disk:', err);
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Clear all disk cached states for this session.
+ */
+ public async clearCache(): Promise<void> {
+ this.ramItems.clear();
+ this.diskCachedIds.clear();
+ if (isTauriEnvironment()) {
+ try {
+ const { invoke } = await import('@tauri-apps/api/core');
+ await invoke('clear_undo_tile_cache', { sessionId: this.sessionId });
+ } catch (err) {
+ console.warn('[UndoCache] Failed to clear disk cache:', err);
+ }
+ }
+ }
+}
+
+// Global default undo cache manager instance
+export const globalUndoCache = new UndoCacheManager();
diff --git a/src/utils/vectorEngine.ts b/src/utils/vectorEngine.ts
new file mode 100644
index 0000000..d4376a4
--- /dev/null
+++ b/src/utils/vectorEngine.ts
@@ -0,0 +1,704 @@
+/**
+ * Vector Inking Engine & Vector Eraser
+ *
+ * Implements Clip Studio Paint-grade vector inking with parametric Catmull-Rom splines,
+ * variable-width pressure ribbons, spatial segment indexing, and authentic
+ * "Erase Up to Intersection" vector erasing.
+ */
+
+import { VectorKnot, VectorStroke } from '../types/editor';
+
+export interface Point2D {
+ x: number;
+ y: number;
+}
+
+export interface SegmentRef {
+ strokeId: string;
+ segIndex: number;
+ p1: VectorKnot;
+ p2: VectorKnot;
+ bounds: { minX: number; minY: number; maxX: number; maxY: number };
+}
+
+export interface IntersectionPoint {
+ point: Point2D;
+ strokeIdA: string;
+ segIndexA: number;
+ tA: number; // 0..1 along segment A
+ strokeIdB: string;
+ segIndexB: number;
+ tB: number; // 0..1 along segment B
+}
+
+/**
+ * Catmull-Rom cubic spline interpolation between p1 and p2 using control points p0 and p3.
+ */
+export function evaluateCatmullRom(
+ p0: VectorKnot,
+ p1: VectorKnot,
+ p2: VectorKnot,
+ p3: VectorKnot,
+ t: number
+): VectorKnot {
+ 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;
+
+ 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),
+ angle: p1.angle,
+ timestamp: p1.timestamp + (p2.timestamp - p1.timestamp) * t,
+ };
+}
+
+/**
+ * Discretize a spline stroke into fine polyline segments for accurate rendering and intersection checks.
+ */
+export function tessellateStroke(stroke: VectorStroke, stepsPerSegment = 6): VectorKnot[] {
+ const knots = stroke.knots;
+ if (knots.length === 0) return [];
+ if (knots.length === 1) return [knots[0]];
+ if (knots.length === 2) return [knots[0], knots[1]];
+
+ const result: VectorKnot[] = [];
+
+ for (let i = 0; i < knots.length - 1; i++) {
+ const p0 = i > 0 ? knots[i - 1] : knots[0];
+ const p1 = knots[i];
+ const p2 = knots[i + 1];
+ const p3 = i + 2 < knots.length ? knots[i + 2] : p2;
+
+ const steps = stepsPerSegment;
+ for (let s = 0; s < steps; s++) {
+ const t = s / steps;
+ result.push(evaluateCatmullRom(p0, p1, p2, p3, t));
+ }
+ }
+
+ result.push(knots[knots.length - 1]);
+ return result;
+}
+
+/**
+ * Compute axis-aligned bounding box of a list of knots.
+ */
+export function computeStrokeBounds(knots: VectorKnot[]): {
+ minX: number;
+ minY: number;
+ maxX: number;
+ maxY: number;
+} {
+ if (knots.length === 0) {
+ return { minX: 0, minY: 0, maxX: 0, maxY: 0 };
+ }
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+
+ for (const k of knots) {
+ const r = (k.width || 2) * 0.5;
+ if (k.x - r < minX) minX = k.x - r;
+ if (k.y - r < minY) minY = k.y - r;
+ if (k.x + r > maxX) maxX = k.x + r;
+ if (k.y + r > maxY) maxY = k.y + r;
+ }
+
+ return { minX, minY, maxX, maxY };
+}
+
+/**
+ * Segment intersection test between A(p1, p2) and B(p3, p4).
+ * Returns intersection parameter tA, tB in [0, 1] if intersecting, or null.
+ */
+export function findSegmentIntersection(
+ p1: Point2D,
+ p2: Point2D,
+ p3: Point2D,
+ p4: Point2D
+): { point: Point2D; tA: number; tB: number } | null {
+ const dX_A = p2.x - p1.x;
+ const dY_A = p2.y - p1.y;
+ const dX_B = p4.x - p3.x;
+ const dY_B = p4.y - p3.y;
+
+ const denom = dX_A * dY_B - dY_A * dX_B;
+ if (Math.abs(denom) < 1e-9) {
+ return null; // Parallel or collinear
+ }
+
+ const dX_C = p1.x - p3.x;
+ const dY_C = p1.y - p3.y;
+
+ const tA = (dX_B * dY_C - dY_B * dX_C) / denom;
+ const tB = (dX_A * dY_C - dY_A * dX_C) / denom;
+
+ if (tA >= 0 && tA <= 1 && tB >= 0 && tB <= 1) {
+ return {
+ point: {
+ x: p1.x + tA * dX_A,
+ y: p1.y + tA * dY_A,
+ },
+ tA,
+ tB,
+ };
+ }
+
+ return null;
+}
+
+/**
+ * Spatial Grid index for high-speed collision and intersection queries on vector strokes.
+ */
+export class VectorSpatialGrid {
+ private cellSize = 128;
+ private cells: Map<string, SegmentRef[]> = new Map();
+
+ constructor(cellSize = 128) {
+ this.cellSize = cellSize;
+ }
+
+ private cellKey(cx: number, cy: number): string {
+ return `${cx}:${cy}`;
+ }
+
+ public clear(): void {
+ this.cells.clear();
+ }
+
+ public insertStroke(stroke: VectorStroke): void {
+ if (stroke.deleted || stroke.knots.length < 2) return;
+
+ for (let i = 0; i < stroke.knots.length - 1; i++) {
+ const p1 = stroke.knots[i];
+ const p2 = stroke.knots[i + 1];
+ const r = Math.max(p1.width, p2.width) * 0.5;
+
+ const minX = Math.min(p1.x, p2.x) - r;
+ const minY = Math.min(p1.y, p2.y) - r;
+ const maxX = Math.max(p1.x, p2.x) + r;
+ const maxY = Math.max(p1.y, p2.y) + r;
+
+ const segRef: SegmentRef = {
+ strokeId: stroke.id,
+ segIndex: i,
+ p1,
+ p2,
+ bounds: { minX, minY, maxX, maxY },
+ };
+
+ const minCX = Math.floor(minX / this.cellSize);
+ const minCY = Math.floor(minY / this.cellSize);
+ const maxCX = Math.floor(maxX / this.cellSize);
+ const maxCY = Math.floor(maxY / this.cellSize);
+
+ for (let cy = minCY; cy <= maxCY; cy++) {
+ for (let cx = minCX; cx <= maxCX; cx++) {
+ const key = this.cellKey(cx, cy);
+ let list = this.cells.get(key);
+ if (!list) {
+ list = [];
+ this.cells.set(key, list);
+ }
+ list.push(segRef);
+ }
+ }
+ }
+ }
+
+ public queryBox(minX: number, minY: number, maxX: number, maxY: number): SegmentRef[] {
+ const minCX = Math.floor(minX / this.cellSize);
+ const minCY = Math.floor(minY / this.cellSize);
+ const maxCX = Math.floor(maxX / this.cellSize);
+ const maxCY = Math.floor(maxY / this.cellSize);
+
+ const seen = new Set<string>();
+ const results: SegmentRef[] = [];
+
+ for (let cy = minCY; cy <= maxCY; cy++) {
+ for (let cx = minCX; cx <= maxCX; cx++) {
+ const list = this.cells.get(this.cellKey(cx, cy));
+ if (list) {
+ for (const item of list) {
+ const id = `${item.strokeId}:${item.segIndex}`;
+ if (!seen.has(id)) {
+ seen.add(id);
+ // Quick AABB overlap check
+ if (
+ item.bounds.maxX >= minX &&
+ item.bounds.minX <= maxX &&
+ item.bounds.maxY >= minY &&
+ item.bounds.minY <= maxY
+ ) {
+ results.push(item);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return results;
+ }
+}
+
+/**
+ * Finds all intersections of a given stroke with all other strokes in the layer.
+ */
+export function findStrokeIntersections(
+ targetStroke: VectorStroke,
+ allStrokes: VectorStroke[]
+): IntersectionPoint[] {
+ const intersections: IntersectionPoint[] = [];
+ const tKnots = targetStroke.knots;
+ if (tKnots.length < 2) return intersections;
+
+ const otherStrokes = allStrokes.filter((s) => s.id !== targetStroke.id && !s.deleted);
+ if (otherStrokes.length === 0) return intersections;
+
+ const grid = new VectorSpatialGrid(128);
+ for (const s of otherStrokes) {
+ grid.insertStroke(s);
+ }
+
+ for (let i = 0; i < tKnots.length - 1; i++) {
+ const p1 = tKnots[i];
+ const p2 = tKnots[i + 1];
+
+ const minX = Math.min(p1.x, p2.x);
+ const minY = Math.min(p1.y, p2.y);
+ const maxX = Math.max(p1.x, p2.x);
+ const maxY = Math.max(p1.y, p2.y);
+
+ const candidates = grid.queryBox(minX, minY, maxX, maxY);
+
+ for (const cand of candidates) {
+ const hit = findSegmentIntersection(p1, p2, cand.p1, cand.p2);
+ if (hit) {
+ intersections.push({
+ point: hit.point,
+ strokeIdA: targetStroke.id,
+ segIndexA: i,
+ tA: hit.tA,
+ strokeIdB: cand.strokeId,
+ segIndexB: cand.segIndex,
+ tB: hit.tB,
+ });
+ }
+ }
+ }
+
+ return intersections;
+}
+
+/**
+ * Distance between point (px, py) and segment (x1, y1)-(x2, y2).
+ */
+export function pointToSegmentDistance(
+ px: number,
+ py: number,
+ x1: number,
+ y1: number,
+ x2: number,
+ y2: number
+): { distance: number; t: number; projX: number; projY: number } {
+ const dx = x2 - x1;
+ const dy = y2 - y1;
+ const lenSq = dx * dx + dy * dy;
+
+ if (lenSq < 1e-9) {
+ const d = Math.hypot(px - x1, py - y1);
+ return { distance: d, t: 0, projX: x1, projY: y1 };
+ }
+
+ let t = ((px - x1) * dx + (py - y1) * dy) / lenSq;
+ t = Math.max(0, Math.min(1, t));
+
+ const projX = x1 + t * dx;
+ const projY = y1 + t * dy;
+ const distance = Math.hypot(px - projX, py - projY);
+
+ return { distance, t, projX, projY };
+}
+
+export type VectorEraserMode = 'intersection' | 'touch' | 'portion';
+
+/**
+ * Splits a target stroke at its intersections with other strokes,
+ * removing the sub-segment that contains the hit point / continuous parameter.
+ * Returns the surviving strokes (e.g. before the left intersection and/or after the right intersection).
+ */
+export function splitStrokeAtIntersection(
+ targetStroke: VectorStroke,
+ hitContinuousParam: number,
+ allStrokes: VectorStroke[]
+): { remainingStrokes: VectorStroke[]; deletedStrokeId: string } {
+ const allIntersections = findStrokeIntersections(targetStroke, allStrokes);
+
+ // Map intersections to continuous curve parameter: idx + t
+ const junctionParams: number[] = [0]; // Start of stroke
+ for (const inter of allIntersections) {
+ junctionParams.push(inter.segIndexA + inter.tA);
+ }
+ junctionParams.push(targetStroke.knots.length - 1); // End of stroke
+
+ // Sort unique junction parameters
+ junctionParams.sort((a, b) => a - b);
+ const uniqueJunctions = junctionParams.filter(
+ (val, idx, arr) => idx === 0 || val - arr[idx - 1] > 0.05
+ );
+
+ // Find which segment interval contains the hit point
+ let leftJunction = 0;
+ let rightJunction = targetStroke.knots.length - 1;
+
+ for (let j = 0; j < uniqueJunctions.length - 1; j++) {
+ if (hitContinuousParam >= uniqueJunctions[j] && hitContinuousParam <= uniqueJunctions[j + 1]) {
+ leftJunction = uniqueJunctions[j];
+ rightJunction = uniqueJunctions[j + 1];
+ break;
+ }
+ }
+
+ const remainingStrokes: VectorStroke[] = [];
+
+ // Keep part before leftJunction if significant
+ if (leftJunction > 0.5) {
+ const leftEndIdx = Math.floor(leftJunction);
+ const subKnots = targetStroke.knots.slice(0, leftEndIdx + 1);
+ if (subKnots.length >= 2) {
+ remainingStrokes.push({
+ id: `vstroke-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`,
+ layerId: targetStroke.layerId,
+ tool: targetStroke.tool,
+ knots: subKnots,
+ color: targetStroke.color,
+ baseWidth: targetStroke.baseWidth,
+ opacity: targetStroke.opacity,
+ bounds: computeStrokeBounds(subKnots),
+ });
+ }
+ }
+
+ // Keep part after rightJunction if significant
+ if (rightJunction < targetStroke.knots.length - 1.5) {
+ const rightStartIdx = Math.ceil(rightJunction);
+ const subKnots = targetStroke.knots.slice(rightStartIdx);
+ if (subKnots.length >= 2) {
+ remainingStrokes.push({
+ id: `vstroke-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`,
+ layerId: targetStroke.layerId,
+ tool: targetStroke.tool,
+ knots: subKnots,
+ color: targetStroke.color,
+ baseWidth: targetStroke.baseWidth,
+ opacity: targetStroke.opacity,
+ bounds: computeStrokeBounds(subKnots),
+ });
+ }
+ }
+
+ return { remainingStrokes, deletedStrokeId: targetStroke.id };
+}
+
+/**
+ * Execute vector erasing operation across strokes in a layer.
+ *
+ * In "intersection" mode (Clip Studio Paint style):
+ * When eraser hits a stroke, it locates the two nearest bounding intersections
+ * (or curve endpoints) and deletes exactly that branch/junction segment!
+ */
+export function applyVectorEraser(
+ eraserKnots: Point2D[],
+ eraserRadius: number,
+ strokes: VectorStroke[],
+ mode: VectorEraserMode = 'intersection'
+): { updatedStrokes: VectorStroke[]; deletedIds: string[]; createdStrokes: VectorStroke[] } {
+ if (eraserKnots.length === 0 || strokes.length === 0) {
+ return { updatedStrokes: strokes, deletedIds: [], createdStrokes: [] };
+ }
+
+ const resultStrokes: VectorStroke[] = [];
+ const deletedIds: string[] = [];
+ const createdStrokes: VectorStroke[] = [];
+
+ for (const stroke of strokes) {
+ if (stroke.deleted || stroke.knots.length < 2) {
+ if (!stroke.deleted) resultStrokes.push(stroke);
+ continue;
+ }
+
+ // Check if eraser trajectory hits this stroke
+ let hitSegIndex = -1;
+ let hitParam = 0;
+
+ for (let i = 0; i < stroke.knots.length - 1; i++) {
+ const p1 = stroke.knots[i];
+ const p2 = stroke.knots[i + 1];
+
+ for (const ePt of eraserKnots) {
+ const { distance, t } = pointToSegmentDistance(ePt.x, ePt.y, p1.x, p1.y, p2.x, p2.y);
+ const strokeRadius = (p1.width * (1 - t) + p2.width * t) * 0.5;
+ if (distance <= eraserRadius + strokeRadius) {
+ hitSegIndex = i;
+ hitParam = t;
+ break;
+ }
+ }
+ if (hitSegIndex >= 0) break;
+ }
+
+ if (hitSegIndex === -1) {
+ // Not touched
+ resultStrokes.push(stroke);
+ continue;
+ }
+
+ // Touched!
+ if (mode === 'touch') {
+ deletedIds.push(stroke.id);
+ continue;
+ }
+
+ if (mode === 'intersection') {
+ const { remainingStrokes, deletedStrokeId } = splitStrokeAtIntersection(
+ stroke,
+ hitSegIndex + hitParam,
+ strokes
+ );
+ deletedIds.push(deletedStrokeId);
+ for (const rem of remainingStrokes) {
+ createdStrokes.push(rem);
+ resultStrokes.push(rem);
+ }
+ } else {
+ // Portion mode: delete touched slice
+ deletedIds.push(stroke.id);
+ // Cut stroke at hitSegIndex
+ if (hitSegIndex >= 2) {
+ const leftKnots = stroke.knots.slice(0, hitSegIndex);
+ const newStroke: VectorStroke = {
+ id: `vstroke-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`,
+ layerId: stroke.layerId,
+ tool: stroke.tool,
+ knots: leftKnots,
+ color: stroke.color,
+ baseWidth: stroke.baseWidth,
+ opacity: stroke.opacity,
+ bounds: computeStrokeBounds(leftKnots),
+ };
+ createdStrokes.push(newStroke);
+ resultStrokes.push(newStroke);
+ }
+ if (hitSegIndex + 2 < stroke.knots.length) {
+ const rightKnots = stroke.knots.slice(hitSegIndex + 2);
+ const newStroke: VectorStroke = {
+ id: `vstroke-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`,
+ layerId: stroke.layerId,
+ tool: stroke.tool,
+ knots: rightKnots,
+ color: stroke.color,
+ baseWidth: stroke.baseWidth,
+ opacity: stroke.opacity,
+ bounds: computeStrokeBounds(rightKnots),
+ };
+ createdStrokes.push(newStroke);
+ resultStrokes.push(newStroke);
+ }
+ }
+ }
+
+ return { updatedStrokes: resultStrokes, deletedIds, createdStrokes };
+}
+
+/**
+ * Render a single vector stroke to a Canvas 2D context using Catmull-Rom tessellation
+ * with pressure-sensitive stroke width and smooth round caps.
+ */
+export function renderVectorStroke(
+ ctx: CanvasRenderingContext2D,
+ stroke: VectorStroke
+): void {
+ if (stroke.deleted || stroke.knots.length < 2) return;
+
+ const tessellated = tessellateStroke(stroke);
+ if (tessellated.length < 2) return;
+
+ ctx.save();
+ ctx.lineCap = 'round';
+ ctx.lineJoin = 'round';
+ ctx.strokeStyle = stroke.color;
+ ctx.fillStyle = stroke.color;
+ ctx.globalAlpha = stroke.opacity ?? 1.0;
+
+ for (let i = 0; i < tessellated.length - 1; i++) {
+ const k1 = tessellated[i];
+ const k2 = tessellated[i + 1];
+ const w = (k1.width + k2.width) * 0.5;
+
+ ctx.lineWidth = Math.max(0.5, w);
+ ctx.beginPath();
+ ctx.moveTo(k1.x, k1.y);
+ ctx.lineTo(k2.x, k2.y);
+ ctx.stroke();
+ }
+
+ ctx.restore();
+}
+
+/**
+ * Render all vector strokes belonging to a layer.
+ */
+export function renderVectorLayer(
+ ctx: CanvasRenderingContext2D,
+ strokes: VectorStroke[],
+ viewportBounds?: { minX: number; minY: number; maxX: number; maxY: number }
+): void {
+ for (const stroke of strokes) {
+ if (stroke.deleted) continue;
+ // Frustum culling for vector strokes
+ if (viewportBounds) {
+ if (
+ stroke.bounds.maxX < viewportBounds.minX ||
+ stroke.bounds.minX > viewportBounds.maxX ||
+ stroke.bounds.maxY < viewportBounds.minY ||
+ stroke.bounds.minY > viewportBounds.maxY
+ ) {
+ continue;
+ }
+ }
+ renderVectorStroke(ctx, stroke);
+ }
+}
+
+/**
+ * Simplify a list of vector knots using the Ramer-Douglas-Peucker algorithm.
+ * Removes redundant points along straight or smooth curves while preserving pressure and corner details.
+ */
+export function simplifyPathPoints(knots: VectorKnot[], tolerance = 1.0): VectorKnot[] {
+ if (knots.length <= 2) return [...knots];
+
+ const sqTolerance = tolerance * tolerance;
+
+ function simplifySection(startIdx: number, endIdx: number): VectorKnot[] {
+ let maxSqDist = 0;
+ let index = startIdx;
+
+ const p1 = knots[startIdx];
+ const p2 = knots[endIdx];
+
+ const dx = p2.x - p1.x;
+ const dy = p2.y - p1.y;
+ const lenSq = dx * dx + dy * dy;
+
+ for (let i = startIdx + 1; i < endIdx; i++) {
+ const p = knots[i];
+ let sqDist: number;
+
+ if (lenSq < 1e-9) {
+ const dX = p.x - p1.x;
+ const dY = p.y - p1.y;
+ sqDist = dX * dX + dY * dY;
+ } 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 dX = p.x - projX;
+ const dY = p.y - projY;
+ sqDist = dX * dX + dY * dY;
+ }
+
+ if (sqDist > maxSqDist) {
+ maxSqDist = sqDist;
+ index = i;
+ }
+ }
+
+ if (maxSqDist > sqTolerance) {
+ const left = simplifySection(startIdx, index);
+ const right = simplifySection(index, endIdx);
+ return left.slice(0, left.length - 1).concat(right);
+ } else {
+ return [knots[startIdx], knots[endIdx]];
+ }
+ }
+
+ return simplifySection(0, knots.length - 1);
+}
+
+/**
+ * Adjust line thickness of a vector stroke (thicken or narrow).
+ */
+export function adjustVectorStrokeWidth(stroke: VectorStroke, deltaWidth: number): VectorStroke {
+ const updatedKnots = stroke.knots.map((k) => ({
+ ...k,
+ width: Math.max(0.5, k.width + deltaWidth),
+ }));
+
+ const newBaseWidth = Math.max(0.5, stroke.baseWidth + deltaWidth);
+
+ return {
+ ...stroke,
+ baseWidth: newBaseWidth,
+ knots: updatedKnots,
+ bounds: computeStrokeBounds(updatedKnots),
+ };
+}
+
+/**
+ * Reshape vector line by simplifying path points, adjusting thickness, or applying pinch/pull deformation.
+ */
+export function reshapeVectorLine(
+ stroke: VectorStroke,
+ options: {
+ simplifyTolerance?: number;
+ deltaWidth?: number;
+ cursorPos?: Point2D;
+ delta?: Point2D;
+ radius?: number;
+ }
+): VectorStroke {
+ let knots = stroke.knots;
+ if (options.simplifyTolerance && options.simplifyTolerance > 0) {
+ knots = simplifyPathPoints(knots, options.simplifyTolerance);
+ }
+
+ let baseWidth = stroke.baseWidth;
+ if (options.deltaWidth !== undefined && options.deltaWidth !== 0) {
+ const deltaW = options.deltaWidth;
+ knots = knots.map((k) => ({
+ ...k,
+ width: Math.max(0.5, k.width + deltaW),
+ }));
+ baseWidth = Math.max(0.5, baseWidth + deltaW);
+ }
+
+ if (options.cursorPos && options.delta && options.radius && options.radius > 0) {
+ const { cursorPos, delta, radius } = options;
+ knots = knots.map((k) => {
+ const dist = Math.hypot(k.x - cursorPos.x, k.y - cursorPos.y);
+ if (dist >= radius) return k;
+ const factor = Math.cos((dist / radius) * (Math.PI / 2)); // Smooth cosine falloff
+ return {
+ ...k,
+ x: k.x + delta.x * factor,
+ y: k.y + delta.y * factor,
+ };
+ });
+ }
+
+ return {
+ ...stroke,
+ baseWidth,
+ knots,
+ bounds: computeStrokeBounds(knots),
+ };
+}