A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.
TypeScript animationcartoonclip-studio-paintcollaborativedesktop-appdigital-paintingdrawing-appillustrationmangamultiplayeropen-sourcerusttaurithreejswebglwebtoon
/**
* Compact pure 8-band spectral Kubelka-Munk + Saunderson pigment color math helpers.
* Used exclusively by non-brush UI/tool modules (PigmentBlendControl swatch preview,
* gradientEngine, retouchEngine, and tileEngine strokeComposite).
* All brush color mixing & canvas pickup execute natively on GPU in `crates/ink-engine`.
*/
import type { CspBrushCombineMode, LayerItem } from '../types/editor';
export const SPECTRAL_STATE_SIZE = 12;
export interface RgbColor {
r: number; // [0, 255]
g: number;
b: number;
}
export type PigmentRgb = RgbColor;
export interface RgbaColor extends RgbColor {
a: number; // [0, 1]
}
const INV_255 = 1 / 255;
const SAUNDERSON_K1 = 0.0052;
const SAUNDERSON_INV_ONE_MINUS_K1 = 1.0 / (1.0 - SAUNDERSON_K1);
const SAUNDERSON_K2 = 0.38;
const SAUNDERSON_ONE_MINUS_K2 = 1.0 - SAUNDERSON_K2;
const REFL_FLOOR = 0.0004;
const REFL_SPAN = 0.999 - REFL_FLOOR;
const INV_REFL_SPAN = 1.0 / REFL_SPAN;
const REFL_CLAMP_MIN = REFL_FLOOR;
const REFL_CLAMP_MAX = 0.9995;
const SCATTER_BASE = 0.04;
const SCATTER_LUM = 0.12;
const SCATTER_MAX = 0.66;
const SCATTER_WHITE = 0.18;
const W_R = new Float32Array([0.0, 0.0, 0.0, 0.0, 0.0, 0.34, 0.48, 0.18]);
const W_G = new Float32Array([0.0, 0.0, 0.06, 0.56, 0.38, 0.0, 0.0, 0.0]);
const W_B = new Float32Array([0.26, 0.66, 0.08, 0.0, 0.0, 0.0, 0.0, 0.0]);
const B_R = new Float32Array([0.24, 0.014, 0.001, 0.001, 0.13, 0.96, 1.0, 1.0]);
const B_G = new Float32Array([0.001, 0.001, 0.08, 0.995, 1.0, 0.65, 0.015, 0.001]);
const B_B = new Float32Array([1.0, 1.0, 0.96, 0.52, 0.028, 0.001, 0.001, 0.06]);
const B_C = new Float32Array([0.85, 0.995, 1.0, 0.995, 0.62, 0.002, 0.001, 0.001]);
const B_M = new Float32Array([1.0, 0.995, 0.08, 0.001, 0.003, 0.85, 1.0, 1.0]);
const B_Y = new Float32Array([0.004, 0.004, 0.02, 0.98, 1.0, 1.0, 1.0, 1.0]);
const SRGB_TO_LINEAR_LUT = new Float32Array(256);
for (let i = 0; i < 256; i++) {
const v = i / 255;
SRGB_TO_LINEAR_LUT[i] = v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
}
const LIN_TO_SRGB_SIZE = 4096;
const LIN_TO_SRGB_LUT = new Float32Array(LIN_TO_SRGB_SIZE + 1);
for (let i = 0; i <= LIN_TO_SRGB_SIZE; i++) {
const v = i / LIN_TO_SRGB_SIZE;
const s = v <= 0.0031308 ? 12.92 * v : 1.055 * Math.pow(v, 1 / 2.4) - 0.055;
LIN_TO_SRGB_LUT[i] = s <= 0 ? 0 : s >= 1 ? 255 : s * 255;
}
function srgbToLinear(c255: number): number {
if (c255 <= 0) return 0;
if (c255 >= 255) return 1;
const idx = c255 | 0;
const frac = c255 - idx;
if (idx >= 255) return 1;
const v0 = SRGB_TO_LINEAR_LUT[idx];
return frac > 0 ? v0 + (SRGB_TO_LINEAR_LUT[idx + 1] - v0) * frac : v0;
}
function linearToSrgb255(c: number): number {
if (c <= 0) return 0;
if (c >= 1) return 255;
if (c <= 0.0031308) return c * (12.92 * 255);
const pos = c * LIN_TO_SRGB_SIZE;
const idx = pos | 0;
const v0 = LIN_TO_SRGB_LUT[idx];
return v0 + (LIN_TO_SRGB_LUT[idx + 1] - v0) * (pos - idx);
}
function clamp255(v: number): number {
return v <= 0 ? 0 : v >= 255 ? 255 : v;
}
function measuredToInternal(rm: number): number {
const x = rm > SAUNDERSON_K1 ? (rm - SAUNDERSON_K1) * SAUNDERSON_INV_ONE_MINUS_K1 : 0;
const ri = x / (SAUNDERSON_ONE_MINUS_K2 + SAUNDERSON_K2 * x);
return REFL_FLOOR + ri * REFL_SPAN;
}
function internalToMeasured(ri: number): number {
const rRaw = (ri - REFL_FLOOR) * INV_REFL_SPAN;
const r = rRaw <= 0 ? 0 : rRaw >= 1 ? 1 : rRaw;
const x = (SAUNDERSON_ONE_MINUS_K2 * r) / (1.0 - SAUNDERSON_K2 * r);
return SAUNDERSON_K1 + (1.0 - SAUNDERSON_K1) * x;
}
const colorRgbCache = new Map<string, RgbColor>();
export function parseColorToRgb(color: string): RgbColor {
const cached = colorRgbCache.get(color);
if (cached) return cached;
let r = 0;
let g = 0;
let b = 0;
if (color.startsWith('#')) {
const hex = color.slice(1);
if (hex.length === 3) {
r = parseInt(hex[0] + hex[0], 16) || 0;
g = parseInt(hex[1] + hex[1], 16) || 0;
b = parseInt(hex[2] + hex[2], 16) || 0;
} else if (hex.length >= 6) {
r = parseInt(hex.slice(0, 2), 16) || 0;
g = parseInt(hex.slice(2, 4), 16) || 0;
b = parseInt(hex.slice(4, 6), 16) || 0;
}
} else if (color.startsWith('rgb')) {
const match = color.match(/\(([^)]+)\)/);
if (match) {
const parts = match[1].split(',').map((p) => parseFloat(p.trim()));
r = parts[0] ?? 0;
g = parts[1] ?? 0;
b = parts[2] ?? 0;
}
}
const result: RgbColor = { r, g, b };
if (colorRgbCache.size < 300) {
colorRgbCache.set(color, result);
}
return result;
}
export function rgbToHex(r: number, g: number, b: number): string {
const cr = Math.max(0, Math.min(255, Math.round(r)));
const cg = Math.max(0, Math.min(255, Math.round(g)));
const cb = Math.max(0, Math.min(255, Math.round(b)));
return `#${((1 << 24) + (cr << 16) + (cg << 8) + cb).toString(16).slice(1)}`;
}
const ENC_CACHE_SIZE = 256;
const ENC_CACHE_MASK = ENC_CACHE_SIZE - 1;
const _encCacheKeys = new Int32Array(ENC_CACHE_SIZE).fill(-1);
const _encCacheVals = new Float32Array(ENC_CACHE_SIZE * SPECTRAL_STATE_SIZE);
const _z1 = new Float32Array(SPECTRAL_STATE_SIZE);
const _z2 = new Float32Array(SPECTRAL_STATE_SIZE);
const _zMix = new Float32Array(SPECTRAL_STATE_SIZE);
const _whiteMixRgb: PigmentRgb = { r: 0, g: 0, b: 0 };
const _compRgb: PigmentRgb = { r: 0, g: 0, b: 0 };
export function srgbToSpectralStateOut(
r255: number,
g255: number,
b255: number,
out: Float32Array,
offset: number
): void {
const cr = r255 <= 0 ? 0 : r255 >= 255 ? 255 : r255;
const cg = g255 <= 0 ? 0 : g255 >= 255 ? 255 : g255;
const cb = b255 <= 0 ? 0 : b255 >= 255 ? 255 : b255;
const lr = srgbToLinear(cr);
const lg = srgbToLinear(cg);
const lb = srgbToLinear(cb);
const rInt = (cr + 0.5) | 0;
const gInt = (cg + 0.5) | 0;
const bInt = (cb + 0.5) | 0;
const key = (rInt << 16) | (gInt << 8) | bInt;
const slot = ((rInt * 73) ^ (gInt * 151) ^ (bInt * 233)) & ENC_CACHE_MASK;
if (_encCacheKeys[slot] === key) {
const base = slot * SPECTRAL_STATE_SIZE;
for (let i = 0; i < 9; i++) out[offset + i] = _encCacheVals[base + i];
out[offset + 9] = lr - _encCacheVals[base + 9];
out[offset + 10] = lg - _encCacheVals[base + 10];
out[offset + 11] = lb - _encCacheVals[base + 11];
return;
}
const qr = SRGB_TO_LINEAR_LUT[rInt];
const qg = SRGB_TO_LINEAR_LUT[gInt];
const qb = SRGB_TO_LINEAR_LUT[bInt];
const rr = measuredToInternal(qr);
const gg = measuredToInternal(qg);
const bb = measuredToInternal(qb);
const lum = 0.2126 * qr + 0.7152 * qg + 0.0722 * qb;
const minQ = qr < qg ? (qr < qb ? qr : qb) : qg < qb ? qg : qb;
const maxQ = qr > qg ? (qr > qb ? qr : qb) : qg > qb ? qg : qb;
const S =
SCATTER_BASE +
SCATTER_LUM * Math.sqrt(lum <= 0 ? 0 : lum >= 1 ? 1 : lum) +
SCATTER_MAX * Math.cbrt(maxQ <= 0 ? 0 : maxQ >= 1 ? 1 : maxQ) +
SCATTER_WHITE * Math.sqrt(minQ <= 0 ? 0 : minQ >= 1 ? 1 : minQ);
let w: number;
let c: number;
let p: number;
let secBasis: Float32Array;
let priBasis: Float32Array;
if (rr <= gg && rr <= bb) {
w = rr;
if (gg <= bb) {
c = gg - rr;
p = bb - gg;
secBasis = B_C;
priBasis = B_B;
} else {
c = bb - rr;
p = gg - bb;
secBasis = B_C;
priBasis = B_G;
}
} else if (gg <= rr && gg <= bb) {
w = gg;
if (rr <= bb) {
c = rr - gg;
p = bb - rr;
secBasis = B_M;
priBasis = B_B;
} else {
c = bb - gg;
p = rr - bb;
secBasis = B_M;
priBasis = B_R;
}
} else {
w = bb;
if (rr <= gg) {
c = rr - bb;
p = gg - rr;
secBasis = B_Y;
priBasis = B_G;
} else {
c = gg - bb;
p = rr - gg;
secBasis = B_Y;
priBasis = B_R;
}
}
const base = slot * SPECTRAL_STATE_SIZE;
let br = 0;
let bg = 0;
let bbAcc = 0;
for (let i = 0; i < 8; i++) {
const sp = w + c * secBasis[i] + p * priBasis[i];
const rc = sp < REFL_CLAMP_MIN ? REFL_CLAMP_MIN : sp > REFL_CLAMP_MAX ? REFL_CLAMP_MAX : sp;
const rm = internalToMeasured(rc);
br += rm * W_R[i];
bg += rm * W_G[i];
bbAcc += rm * W_B[i];
const oneMinusR = 1.0 - rc;
const ks = (oneMinusR * oneMinusR) / (2.0 * rc);
const u = S * Math.cbrt(ks);
out[offset + i] = u;
_encCacheVals[base + i] = u;
}
out[offset + 8] = S;
out[offset + 9] = lr - br;
out[offset + 10] = lg - bg;
out[offset + 11] = lb - bbAcc;
_encCacheKeys[slot] = key;
_encCacheVals[base + 8] = S;
_encCacheVals[base + 9] = br;
_encCacheVals[base + 10] = bg;
_encCacheVals[base + 11] = bbAcc;
}
export function spectralStateToSrgbOut(
state: Float32Array,
offset: number,
out: PigmentRgb
): PigmentRgb {
const s = state[offset + 8];
const invS = 1.0 / (s > 1e-6 ? s : 1e-6);
let mr = 0;
let mg = 0;
let mb = 0;
for (let i = 0; i < 8; i++) {
const u = state[offset + i] * invS;
const ks = u > 0 ? u * u * u : 0;
const rm = internalToMeasured(1.0 + ks - Math.sqrt(ks * ks + 2.0 * ks));
mr += rm * W_R[i];
mg += rm * W_G[i];
mb += rm * W_B[i];
}
out.r = linearToSrgb255(mr + state[offset + 9]);
out.g = linearToSrgb255(mg + state[offset + 10]);
out.b = linearToSrgb255(mb + state[offset + 11]);
return out;
}
export function pigmentMixRgbOut(
r1: number,
g1: number,
b1: number,
r2: number,
g2: number,
b2: number,
weight2: number,
pigmentStrength: number,
out: PigmentRgb
): PigmentRgb {
const t = weight2 <= 0 ? 0 : weight2 >= 1 ? 1 : weight2;
if (t <= 0.0001) {
out.r = clamp255(r1);
out.g = clamp255(g1);
out.b = clamp255(b1);
return out;
}
if (t >= 0.9999) {
out.r = clamp255(r2);
out.g = clamp255(g2);
out.b = clamp255(b2);
return out;
}
const strength = pigmentStrength <= 0 ? 0 : pigmentStrength >= 1 ? 1 : pigmentStrength;
const dr = r2 - r1;
const dg = g2 - g1;
const db = b2 - b1;
const linR = r1 + dr * t;
const linG = g1 + dg * t;
const linB = b1 + db * t;
if (strength <= 0.005 || dr * dr + dg * dg + db * db < 1.0) {
out.r = clamp255(linR);
out.g = clamp255(linG);
out.b = clamp255(linB);
return out;
}
const max1 = r1 > g1 ? (r1 > b1 ? r1 : b1) : g1 > b1 ? g1 : b1;
const min1 = r1 < g1 ? (r1 < b1 ? r1 : b1) : g1 < b1 ? g1 : b1;
const max2 = r2 > g2 ? (r2 > b2 ? r2 : b2) : g2 > b2 ? g2 : b2;
const min2 = r2 < g2 ? (r2 < b2 ? r2 : b2) : g2 < b2 ? g2 : b2;
const maxChroma = Math.max(max1 - min1, max2 - min2);
if (maxChroma <= 1.0) {
out.r = clamp255(linR);
out.g = clamp255(linG);
out.b = clamp255(linB);
return out;
}
srgbToSpectralStateOut(r1, g1, b1, _z1, 0);
srgbToSpectralStateOut(r2, g2, b2, _z2, 0);
const invT = 1.0 - t;
for (let i = 0; i < SPECTRAL_STATE_SIZE; i++) {
_zMix[i] = invT * _z1[i] + t * _z2[i];
}
spectralStateToSrgbOut(_zMix, 0, out);
let effStrength = strength;
if (maxChroma < 8.0) {
const chromaRamp = (maxChroma - 1.0) / 7.0;
effStrength *= chromaRamp * chromaRamp * (3.0 - 2.0 * chromaRamp);
}
if (effStrength >= 0.995) {
return out;
}
out.r = clamp255(linR + (out.r - linR) * effStrength);
out.g = clamp255(linG + (out.g - linG) * effStrength);
out.b = clamp255(linB + (out.b - linB) * effStrength);
return out;
}
export const mixPigmentRgbOut = pigmentMixRgbOut;
export function mixSubtractivePigments(
c1: RgbColor,
c2: RgbColor,
weight2: number
): RgbColor {
const out: RgbColor = { r: c1.r, g: c1.g, b: c1.b };
return pigmentMixRgbOut(c1.r, c1.g, c1.b, c2.r, c2.g, c2.b, weight2, 1.0, out);
}
export function mixPigmentsWithStrength(
c1: RgbColor,
c2: RgbColor,
weight2: number,
pigmentStrength: number = 1.0
): RgbColor {
const out: RgbColor = { r: c1.r, g: c1.g, b: c1.b };
return pigmentMixRgbOut(c1.r, c1.g, c1.b, c2.r, c2.g, c2.b, weight2, pigmentStrength, out);
}
export function encodePigmentOverWhiteOut(
sr: number,
sg: number,
sb: number,
sA: number,
pigmentStrength: number,
out: [number, number, number, number]
): void {
if (sA <= 0.0001) {
out[0] = 0;
out[1] = 0;
out[2] = 0;
out[3] = 0;
return;
}
if (sA >= 0.999) {
out[0] = clamp255(Math.round(sr));
out[1] = clamp255(Math.round(sg));
out[2] = clamp255(Math.round(sb));
out[3] = 255;
return;
}
if (pigmentStrength <= 0.005) {
out[0] = clamp255(Math.round(sr));
out[1] = clamp255(Math.round(sg));
out[2] = clamp255(Math.round(sb));
out[3] = clamp255(Math.round(sA * 255));
return;
}
pigmentMixRgbOut(255, 255, 255, sr, sg, sb, sA, pigmentStrength, _whiteMixRgb);
const pr = _whiteMixRgb.r;
const pg = _whiteMixRgb.g;
const pb = _whiteMixRgb.b;
const minC = pr < pg ? (pr < pb ? pr : pb) : pg < pb ? pg : pb;
const minValidA = 1.0 - minC * INV_255;
const outA = sA > minValidA ? sA : minValidA;
if (outA <= 0.0001) {
out[0] = 0;
out[1] = 0;
out[2] = 0;
out[3] = 0;
return;
}
const bg = 255.0 * (1.0 - outA);
const invOutA = 1.0 / outA;
out[0] = clamp255(Math.round((pr - bg) * invOutA));
out[1] = clamp255(Math.round((pg - bg) * invOutA));
out[2] = clamp255(Math.round((pb - bg) * invOutA));
out[3] = clamp255(Math.round(outA * 255.0));
}
export function isPigmentCompatibleCombineMode(mode?: CspBrushCombineMode): boolean {
return (
!mode ||
mode === 'normal' ||
mode === 'pass-through' ||
mode === 'compare-density' ||
mode === 'behind'
);
}
export function compositePigmentOverPixelInto(
dr: number,
dg: number,
db: number,
da: number,
sr: number,
sg: number,
sb: number,
effA: number,
pigmentStrength: number,
pigmentWhiteGround: boolean,
compositeOp: 'source-over' | 'destination-out' | 'source-atop',
combineMode: CspBrushCombineMode | undefined,
out: [number, number, number, number]
): void {
const mode: CspBrushCombineMode = combineMode ?? 'normal';
const sA = effA * INV_255;
if (compositeOp === 'source-atop') {
if (da === 0) {
out[0] = dr;
out[1] = dg;
out[2] = db;
out[3] = 0;
return;
}
if (mode === 'behind') {
if (da >= 255) {
out[0] = dr;
out[1] = dg;
out[2] = db;
out[3] = da;
return;
}
const dA = da * INV_255;
const rem = (1.0 - dA) * sA;
const denom = dA + rem;
if (denom > 1e-5) {
pigmentMixRgbOut(dr, dg, db, sr, sg, sb, rem / denom, pigmentStrength, _compRgb);
out[0] = clamp255(Math.round(_compRgb.r));
out[1] = clamp255(Math.round(_compRgb.g));
out[2] = clamp255(Math.round(_compRgb.b));
} else {
out[0] = dr;
out[1] = dg;
out[2] = db;
}
out[3] = da;
return;
}
if (effA >= 255) {
out[0] = sr;
out[1] = sg;
out[2] = sb;
out[3] = da;
return;
}
pigmentMixRgbOut(dr, dg, db, sr, sg, sb, sA, pigmentStrength, _compRgb);
out[0] = clamp255(Math.round(_compRgb.r));
out[1] = clamp255(Math.round(_compRgb.g));
out[2] = clamp255(Math.round(_compRgb.b));
out[3] = da;
return;
}
if (mode === 'behind') {
if (da >= 255) {
out[0] = dr;
out[1] = dg;
out[2] = db;
out[3] = da;
return;
}
if (da === 0) {
if (pigmentWhiteGround && effA < 255) {
encodePigmentOverWhiteOut(sr, sg, sb, sA, pigmentStrength, out);
} else {
out[0] = sr;
out[1] = sg;
out[2] = sb;
out[3] = effA;
}
return;
}
const dA = da * INV_255;
const rem = sA * (1.0 - dA);
const compA = dA + rem;
if (compA > 1e-5) {
pigmentMixRgbOut(dr, dg, db, sr, sg, sb, rem / compA, pigmentStrength, _compRgb);
out[0] = clamp255(Math.round(_compRgb.r));
out[1] = clamp255(Math.round(_compRgb.g));
out[2] = clamp255(Math.round(_compRgb.b));
out[3] = clamp255(Math.round(compA * 255));
} else {
out[0] = dr;
out[1] = dg;
out[2] = db;
out[3] = da;
}
return;
}
if (da === 0) {
if (pigmentWhiteGround && effA < 255) {
encodePigmentOverWhiteOut(sr, sg, sb, sA, pigmentStrength, out);
} else {
out[0] = sr;
out[1] = sg;
out[2] = sb;
out[3] = effA;
}
return;
}
if (mode === 'compare-density') {
const dA = da * INV_255;
const dstW = dA * (1.0 - sA);
const denom = sA + dstW;
if (denom <= 1e-5) {
out[0] = dr;
out[1] = dg;
out[2] = db;
out[3] = da;
return;
}
pigmentMixRgbOut(dr, dg, db, sr, sg, sb, sA / denom, pigmentStrength, _compRgb);
out[0] = clamp255(Math.round(_compRgb.r));
out[1] = clamp255(Math.round(_compRgb.g));
out[2] = clamp255(Math.round(_compRgb.b));
out[3] = effA > da ? effA : da;
return;
}
if (effA >= 255) {
out[0] = sr;
out[1] = sg;
out[2] = sb;
out[3] = 255;
return;
}
const dA = da * INV_255;
const compA = sA + dA * (1.0 - sA);
if (compA <= 1e-5) {
out[0] = dr;
out[1] = dg;
out[2] = db;
out[3] = da;
return;
}
if (pigmentWhiteGround && da < 255) {
const invDA = 1.0 - dA;
const visDr = dr * dA + 255.0 * invDA;
const visDg = dg * dA + 255.0 * invDA;
const visDb = db * dA + 255.0 * invDA;
pigmentMixRgbOut(visDr, visDg, visDb, sr, sg, sb, sA, pigmentStrength, _compRgb);
const pr = _compRgb.r;
const pg = _compRgb.g;
const pb = _compRgb.b;
const minC = pr < pg ? (pr < pb ? pr : pb) : pg < pb ? pg : pb;
const minValidA = 1.0 - minC * INV_255;
const outA = compA > minValidA ? compA : minValidA;
if (outA <= 1e-5) {
out[0] = 0;
out[1] = 0;
out[2] = 0;
out[3] = 0;
return;
}
const bg = 255.0 * (1.0 - outA);
const invOutA = 1.0 / outA;
out[0] = clamp255(Math.round((pr - bg) * invOutA));
out[1] = clamp255(Math.round((pg - bg) * invOutA));
out[2] = clamp255(Math.round((pb - bg) * invOutA));
out[3] = clamp255(Math.round(outA * 255.0));
return;
}
const t = sA / compA;
pigmentMixRgbOut(dr, dg, db, sr, sg, sb, t, pigmentStrength, _compRgb);
out[0] = clamp255(Math.round(_compRgb.r));
out[1] = clamp255(Math.round(_compRgb.g));
out[2] = clamp255(Math.round(_compRgb.b));
out[3] = clamp255(Math.round(compA * 255));
}
export function detectWhitePaperGround(
layers: LayerItem[] | undefined,
activeLayerId: string | null | undefined
): boolean {
if (!layers || layers.length === 0) return true;
const isBgId = (id: string) => id === 'layer-bg' || id.startsWith('layer-bg');
if (activeLayerId && isBgId(activeLayerId)) {
return true;
}
const bgLayer = layers.find((l) => isBgId(l.id));
if (!bgLayer) return false;
if (!bgLayer.visible || bgLayer.opacity < 0.5) return false;
return true;
}