diff --git a/src/components/menu/Inspector.svelte b/src/components/menu/Inspector.svelte
index 1c08f58bd..a845b0083 100644
--- a/src/components/menu/Inspector.svelte
+++ b/src/components/menu/Inspector.svelte
@@ -268,6 +268,7 @@
saveSnapAnchorAsOrigin
} from '$lib/snapEngine';
import { peers, inspectorClose, inspectorKind, showToast, inspectorFilter, userdata, closeSelectionInspector } from '../../stores/appStore.js';
+ import { get as getStore } from 'svelte/store'; // 102 M6: the unlink send reads the peer once
// 78-int PL13: "changed by
· time" under the shared Configure Scene sections
import { sceneSectionEdits } from '$lib/sceneEditBy.js';
import { editLine } from '$lib/sceneEditByCore.js';
@@ -615,6 +616,11 @@
if (!uuid) return;
const count = sharedWith.length;
if (!unlinkMaterial(uuid)) return;
+ // 102 M6 (found on the way): the unlink used to stay on this machine, so a peer kept the objects linked
+ // and the next edit of this one changed both over there. An older peer ignores the parameter.
+ /** @type {any} */
+ const peer = getStore(peers);
+ peer?.send({ type: 'objectParameters', parameter: 'materialUnlink', uuid });
showToast(
'This object has its own material now — the other ' +
count +
diff --git a/src/components/ui/Icon.svelte b/src/components/ui/Icon.svelte
index 6130476c2..33fe0ab6f 100644
--- a/src/components/ui/Icon.svelte
+++ b/src/components/ui/Icon.svelte
@@ -122,6 +122,7 @@
Eye,
EyeOff,
FileCode,
+ Eraser,
FileInput,
FilePlus,
FileText,
@@ -376,6 +377,7 @@
'file-input': FileInput,
'file-plus': FilePlus,
'file-text': FileText,
+ eraser: Eraser, // 102 M6 paint eraser
filter: Filter,
flag: Flag,
'flip-horizontal': FlipHorizontal,
diff --git a/src/lib/agentPresenceCore.js b/src/lib/agentPresenceCore.js
index e2968bd84..9ba644d6d 100644
--- a/src/lib/agentPresenceCore.js
+++ b/src/lib/agentPresenceCore.js
@@ -25,6 +25,7 @@ const UUID_EDITS = new Set([
'group',
'lock',
'uvpaint',
+ 'meshpaint',
'splineedit',
'graphcreate', // an object graph's id is its owner's uuid
'graphdelete'
diff --git a/src/lib/commandsHandler.svelte.js b/src/lib/commandsHandler.svelte.js
index 410ddff15..eff43b985 100644
--- a/src/lib/commandsHandler.svelte.js
+++ b/src/lib/commandsHandler.svelte.js
@@ -3,6 +3,7 @@ import * as THREE from 'three';
import { notifyOn } from './notifyPrefs';
import { globalScene, objectsGroup, showGrid, TControls, lockedObjects, selectedObject, globalCamera, peerHands, pokeScene, beginSceneBatch, endSceneBatch } from '../stores/sceneStore.js';
import { receiveMapSlot, receiveTexTransform, receiveNormalStrength } from '$lib/materialMaps';
+import { unlinkMaterial } from '$lib/materialSharing';
import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { createGeometry, createLight, createGroup } from '$lib/geometries.svelte'
@@ -612,6 +613,9 @@ export async function objectParameters(data, from = 'peer') {
if (mesh) applyMap(mesh, data.map, data.slot ?? 0, typeof data.source === 'string' ? data.source : null);
} else if (data.parameter == 'materialParam') {
setMaterialParam(data.uuid, data.key, data.value, false);
+ } else if (data.parameter == 'materialUnlink') {
+ // 102 M6: "this object only" on a shared material — this object gets its own copy here too
+ unlinkMaterial(data.uuid);
} else if (data.parameter == 'mapSlot') {
receiveMapSlot(data); // 72 LK1: normal, roughness, metalness, emissive, AO
} else if (data.parameter == 'texTransform') {
diff --git a/src/lib/debugHooks.js b/src/lib/debugHooks.js
index b9974509e..4c69e0f80 100644
--- a/src/lib/debugHooks.js
+++ b/src/lib/debugHooks.js
@@ -382,6 +382,9 @@ export const DEBUG_HOOKS = [
['moduleGallery', () => import('./moduleGallery')],
['moduleInstallJobs', () => import('./moduleInstallJobs')],
['uvEditor', () => import('./uvEditor')],
+ // 102 M6: paint on meshes (the lazy painter + its prefs leaf)
+ ['meshPaint', () => import('./meshPaint')],
+ ['meshPaintPrefs', () => import('./meshPaintPrefs')],
['uvUnwrap', () => import('./uvUnwrap')],
['meshTopology', () => import('./meshTopology')],
['meshBoolean', () => import('./meshBoolean')],
diff --git a/src/lib/materialMaps.js b/src/lib/materialMaps.js
index 9626430b8..ebbaffac1 100644
--- a/src/lib/materialMaps.js
+++ b/src/lib/materialMaps.js
@@ -123,6 +123,24 @@ export async function setObjectsMapSlot(uuids, key, file, slot = 0) {
return applied;
}
+/**
+ * 102 M6: commit a PAINTED map slot. The brush has been drawing on a canvas installed as the slot's texture, so
+ * the slot's current image is no longer what undo should go back to: the caller passes the image it held when
+ * the stroke began (`before`, null when the stroke made the map). Records, applies and sends (the send fans to a
+ * shared material's other users, `broadcastMaterial`). Inside a caller's history batch when one is open.
+ * @param {string} uuid @param {string} key @param {string | null} before @param {string} url @param {number} [slot]
+ */
+export function commitPaintedMapSlot(uuid, key, before, url, slot = 0) {
+ const object = objectOf(uuid);
+ const material = object && materialAt(object, slot);
+ if (!material || !isMapSlotKey(key) || !(key in material) || !isMapSlotImage(url)) return false;
+ recordEntry({ kind: 'materialmaps', uuid, param: 'slot', key, ...(slot ? { slot } : {}), before: { value: before }, after: { value: url } });
+ applyMapSlotTo(material, key, url, object);
+ material.userData.tpEdited = true;
+ sendSlot(uuid, key, url, slot);
+ return true;
+}
+
/**
* Clear a map slot on many objects, one undo step. A compressed (KTX2) map has no image to keep, so undo
* cannot bring that one back.
diff --git a/src/lib/meshPaint.js b/src/lib/meshPaint.js
new file mode 100644
index 000000000..3fa6d45f8
--- /dev/null
+++ b/src/lib/meshPaint.js
@@ -0,0 +1,1472 @@
+// 102 M6 — PAINT ON MESHES, the painter. A LAZY chunk: the UV editor, the dispatcher and the VR brush import it
+// with `import()` on first use. The brush settings live in meshPaintPrefs.js, the arithmetic in meshPaintCore.js.
+//
+// WHAT IT ADDS TO THE SHIPPED PAINTER (uvEditor.js UV3), which keeps painting exactly as before when nothing new
+// is in use (a default brush on the colour map in the UV canvas still goes through `uvpaint`, byte-unchanged):
+// - four CHANNELS, one map each: colour (`map`, the UV editor's own paint canvas — one image, two painters),
+// roughness, metalness, emission (the 72 LK1 map slots, committed through `mapSlot` + the `materialmaps` undo)
+// - BRUSH KINDS: hardness, flow, opacity, eraser, mirror X, an image stamp
+// - MODEL STROKES: a stroke on the model itself. A dab is a sphere in the object's own space, rasterised into
+// the map through every triangle it touches (each triangle's own 3D -> UV map), with seam PADDING into the
+// empty gutter around each island, so a stroke crosses a UV seam the way it crosses the surface
+// - VERTEX COLOURS when the mesh has no usable UVs (none, or overlapping), with the same brush, committed through
+// the meshgeo path (which already carries `colors`)
+// - a NEW MAP on a slot's first stroke (1k / 2k), filled with the material's own value so nothing changes until
+// you paint; a SHARED material asks "all objects" or "this object only" (the second replicates)
+//
+// THE RASTER IS OURS, NOT THE CANVAS'S. Dabs are written into a per-stroke layer of 64 px TILES in plain JS (pixel
+// centres, one owner triangle per pixel, `L += a * (1 - L)`), then composited over the stroke's base pixels by
+// putImageData. Two reasons: canvas clip paths anti-alias every shared triangle edge into a faint line (the
+// conflation artefact), and plain arithmetic draws the same bytes on every peer. Tiles are read from the canvas
+// only when a dab first reaches them, so a stroke costs the area it touches, not the whole map.
+//
+// THE WIRE: the live stroke is `meshpaint` {id, uuid, slot?, ch?, sp: 'uv'|'obj'|'vtx', c, r, b?, pm?, n?, seg}
+// + `meshpaintend` {id, cancel?} — a PREVIEW, replayed with the same numbers (points travel rounded and the sender
+// paints the rounded point too). The truth is the commit that follows (`map`, `mapSlot`, `meshgeo`), so a late
+// joiner gets the texture, never the path history. Both types are ROOM_SCOPED.
+import * as THREE from 'three';
+import { get, derived } from 'svelte/store';
+import { objectsGroup, pokeScene, globalScene, globalCamera, globalRenderer } from '../stores/sceneStore';
+import { peers, showToast } from '../stores/appStore';
+import { beginHistoryBatch, endHistoryBatch, historyBatchOpen } from './history';
+import { materialAt, applyMap, recordMaterialChange, setMaterialParam, broadcastMaterial, copyTextureParams } from './materialsHandler';
+import { commitPaintedMapSlot } from './materialMaps';
+import { mapSlotUrl, mapSlotKnownUrl } from './materialMapTextures.js';
+import { isSharedMaterial, materialIdOf, objectsSharing, unlinkMaterial } from './materialSharing';
+import { showChoice } from './confirmDialog';
+import { resolveHudImage, shareHudImage } from './hudImages';
+import {
+ openColorSurface,
+ dropColorSurface,
+ encodePaintCanvas,
+ paintPressureFactor,
+ uvPaintTick,
+ uvBrushColor,
+ uvBrushSize,
+ uvPenPressure
+} from './uvEditor';
+import { readTriangles, trisToPositions, trisToGroups, trisToUVs, commitMeshGeoTriple } from './faceEdit';
+import { paintChannel, paintValue, paintMapSize, paintTargetInfo, paintShowChannel, BRUSH_STORES } from './meshPaintPrefs';
+import {
+ channelOf,
+ normalizeBrush,
+ isDefaultBrush,
+ brushWire,
+ brushFromWire,
+ paintStyle,
+ hexToRgb,
+ rgbToHex,
+ falloff,
+ DAB_SPACING,
+ dabsAlong,
+ triFrame,
+ dabOnTri,
+ planeToCanvas,
+ uvToCanvas,
+ padTri,
+ texelDensity,
+ buildTriGrid,
+ trisNear,
+ uvOverlap,
+ paintTarget,
+ vertexDab,
+ blendVertexColors,
+ mirrorX,
+ onMirrorPlane,
+ srgbToLinear,
+ hashBytes
+} from './meshPaintCore.js';
+import { quantizePoint } from './meshPaintWire.js';
+
+// 102 M6 (boot rule): the UV editor reads the brush state through this lazy chunk, so the prefs leaf and the
+// brush panel stay out of the boot bundle. `newBrush` = a channel other than colour or a brush other than the
+// shipped hard round one, which paints through this module instead of uvEditor's own painter.
+export const paintUi = derived(
+ [paintChannel, paintShowChannel, BRUSH_STORES.hardness, BRUSH_STORES.opacity, BRUSH_STORES.flow, BRUSH_STORES.erase, BRUSH_STORES.stamp],
+ ([channel, showChannel, hardness, opacity, flow, erase, stamp]) => ({
+ channel,
+ showChannel: !!showChannel,
+ newBrush: channel !== 'color' || hardness !== 1 || opacity !== 1 || flow !== 1 || !!erase || !!stamp
+ })
+);
+/** forget what the panel says a stroke paints (the editor lost its target) */
+export function clearTargetInfo() {
+ paintTargetInfo.set(null);
+}
+
+const TILE = 64;
+/** seam padding, texture px past an island's edge */
+const PAD = 2;
+/** live-stroke broadcast interval (the shipped painter's cadence) */
+const SEND_MS = 66;
+/** a remote stroke nobody finished is dropped after this */
+const STALE_MS = 5000;
+/** the stamp mask's resolution */
+const STAMP_RES = 64;
+
+/** @param {string} uuid */
+function objectOf(uuid) {
+ /** @type {any} */
+ const group = get(objectsGroup);
+ return uuid ? group?.getObjectByProperty?.('uuid', uuid) ?? null : null;
+}
+
+/** @param {any} image */
+function drawable(image) {
+ if (!image || typeof document === 'undefined') return null;
+ const w = image.width ?? image.videoWidth;
+ const h = image.height ?? image.videoHeight;
+ if (!w || !h || image.data !== undefined) return null;
+ return image;
+}
+
+/** the shipped painter's size rule: the source's own resolution, long side kept in 256..2048 @param {any} image */
+function sizeOf(image) {
+ const sw = image?.width ?? 0;
+ const sh = image?.height ?? 0;
+ if (!sw || !sh) return null;
+ const longest = Math.max(sw, sh);
+ const scale = longest > 2048 ? 2048 / longest : longest < 256 ? Math.min(256 / longest, 8) : 1;
+ return { w: Math.min(Math.max(Math.round(sw * scale), 8), 4096), h: Math.min(Math.max(Math.round(sh * scale), 8), 4096) };
+}
+
+// ---- the mesh model: the slot's triangles in the object's own space, cached per geometry -------------------------
+
+/** @type {WeakMap>} geometry -> slot -> model */
+const models = new WeakMap();
+
+/**
+ * The triangles of one material slot as a flat soup (9 floats each) with their UVs (6 each), a grid to find them,
+ * lazily built frames, and the facts that decide map vs vertex colours. Rebuilt when the geometry is swapped
+ * (applyMeshGeo makes a new one) or its position / uv attribute changes in place.
+ * @param {any} mesh @param {number} slot
+ */
+function meshModel(mesh, slot) {
+ const geometry = mesh?.geometry;
+ const pos = geometry?.attributes?.position;
+ if (!pos) return null;
+ const uvAttr = geometry.attributes.uv;
+ const stamp = pos.version + ':' + (uvAttr?.version ?? -1) + ':' + pos.count;
+ let bySlot = models.get(geometry);
+ if (!bySlot) models.set(geometry, (bySlot = new Map()));
+ const cached = bySlot.get(slot);
+ if (cached && cached.stamp === stamp) return cached;
+ const index = geometry.index;
+ const count = index ? index.count : pos.count;
+ const multi = Array.isArray(mesh.material) && geometry.groups?.length;
+ /** @type {number[]} */
+ const p = [];
+ /** @type {number[]} */
+ const u = [];
+ for (let i = 0; i + 2 < count; i += 3) {
+ if (multi) {
+ const g = geometry.groups.find((/** @type {any} */ gr) => i >= gr.start && i < gr.start + gr.count);
+ if ((g?.materialIndex ?? 0) !== slot) continue;
+ }
+ for (let k = 0; k < 3; k++) {
+ const j = index ? index.getX(i + k) : i + k;
+ p.push(pos.getX(j), pos.getY(j), pos.getZ(j));
+ if (uvAttr) u.push(uvAttr.getX(j), uvAttr.getY(j));
+ }
+ }
+ const positions = new Float32Array(p);
+ const uvs = uvAttr ? new Float32Array(u) : null;
+ geometry.computeBoundingBox?.();
+ const box = geometry.boundingBox;
+ const diag = box ? box.min.distanceTo(box.max) : 1;
+ const model = {
+ stamp,
+ positions,
+ uvs,
+ n: positions.length / 9,
+ diag: diag > 0 ? diag : 1,
+ grid: buildTriGrid(positions, (diag > 0 ? diag : 1) / 48),
+ /** @type {(any | null | undefined)[]} */
+ frames: [],
+ target: paintTarget({ hasUvs: !!uvs, overlap: uvs ? uvOverlap(uvs, 128) : null }),
+ /** @type {Map} canvas size + flip -> which pixels belong to a triangle */
+ coverage: new Map()
+ };
+ bySlot.set(slot, model);
+ return model;
+}
+
+/** @param {any} model @param {number} t */
+function frameOf(model, t) {
+ let f = model.frames[t];
+ if (f === undefined) {
+ const P = model.positions;
+ const U = model.uvs;
+ const o = t * 9;
+ const q = t * 6;
+ f = U
+ ? triFrame([P[o], P[o + 1], P[o + 2]], [P[o + 3], P[o + 4], P[o + 5]], [P[o + 6], P[o + 7], P[o + 8]], [U[q], U[q + 1]], [U[q + 2], U[q + 3]], [U[q + 4], U[q + 5]])
+ : null;
+ model.frames[t] = f;
+ }
+ return f;
+}
+
+/** Edge function sign test, pixel centre inside a canvas-space triangle (inclusive). @param {number[][]} P
+ * @param {number} x @param {number} y */
+function insideTri(P, x, y) {
+ const [a, b, c] = P;
+ const area = (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1]);
+ const w0 = (b[0] - x) * (c[1] - y) - (c[0] - x) * (b[1] - y);
+ const w1 = (c[0] - x) * (a[1] - y) - (a[0] - x) * (c[1] - y);
+ const w2 = (a[0] - x) * (b[1] - y) - (b[0] - x) * (a[1] - y);
+ return area > 0 ? w0 >= 0 && w1 >= 0 && w2 >= 0 : w0 <= 0 && w1 <= 0 && w2 <= 0;
+}
+
+/** Which pixels of a W x H map some triangle owns — the padding pass may only paint the ones nobody does.
+ * @param {any} model @param {number} W @param {number} H @param {boolean} flip */
+function coverageOf(model, W, H, flip) {
+ const key = W + 'x' + H + (flip ? 'f' : '');
+ let cov = model.coverage.get(key);
+ if (cov) return cov;
+ cov = new Uint8Array(W * H);
+ const U = model.uvs;
+ if (U)
+ for (let t = 0; t < model.n; t++) {
+ const q = t * 6;
+ const P = [0, 1, 2].map((k) => uvToCanvas([U[q + k * 2], U[q + k * 2 + 1]], W, H, flip));
+ const x0 = Math.max(0, Math.floor(Math.min(P[0][0], P[1][0], P[2][0])));
+ const x1 = Math.min(W - 1, Math.ceil(Math.max(P[0][0], P[1][0], P[2][0])));
+ const y0 = Math.max(0, Math.floor(Math.min(P[0][1], P[1][1], P[2][1])));
+ const y1 = Math.min(H - 1, Math.ceil(Math.max(P[0][1], P[1][1], P[2][1])));
+ for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) if (insideTri(P, x + 0.5, y + 0.5)) cov[y * W + x] = 1;
+ }
+ // one size per model is the common case; keep at most two (a 2k cover is 4 MB)
+ if (model.coverage.size >= 2) model.coverage.clear();
+ model.coverage.set(key, cov);
+ return cov;
+}
+
+/** Facts for the panel: what a stroke on this object would paint, and why. @param {any} mesh @param {number} slot */
+export function targetFor(mesh, slot = 0) {
+ const model = meshModel(mesh, slot);
+ const info = model ? model.target : null;
+ if (get(paintTargetInfo) !== info) paintTargetInfo.set(info);
+ return info;
+}
+
+// ---- the layer: per-stroke tiles over a canvas --------------------------------------------------------------------
+
+/** @param {any} canvas */
+function makeLayer(canvas) {
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
+ return { canvas, ctx, W: canvas.width, H: canvas.height, /** @type {Map} */ tiles: new Map(), /** @type {Set} */ dirty: new Set(), dab: 0 };
+}
+
+/** @param {any} layer @param {number} tx @param {number} ty */
+function tileAt(layer, tx, ty) {
+ const key = ty * 65536 + tx;
+ let t = layer.tiles.get(key);
+ if (!t) {
+ const x = tx * TILE;
+ const y = ty * TILE;
+ const w = Math.min(TILE, layer.W - x);
+ const h = Math.min(TILE, layer.H - y);
+ const base = layer.ctx.getImageData(x, y, w, h);
+ t = { key, x, y, w, h, base: base.data, img: new ImageData(new Uint8ClampedArray(base.data), w, h), L: new Float32Array(w * h), mark: new Uint32Array(w * h) };
+ layer.tiles.set(key, t);
+ }
+ return t;
+}
+
+/** Add `a` of the stroke at pixel (x, y), once per dab. @param {any} layer @param {number} x @param {number} y @param {number} a */
+function touch(layer, x, y, a) {
+ if (!(a > 0) || x < 0 || y < 0 || x >= layer.W || y >= layer.H) return;
+ const t = tileAt(layer, (x / TILE) | 0, (y / TILE) | 0);
+ const i = (y - t.y) * t.w + (x - t.x);
+ if (t.mark[i] === layer.dab) return;
+ t.mark[i] = layer.dab;
+ const aa = a > 1 ? 1 : a;
+ t.L[i] = t.L[i] + aa * (1 - t.L[i]);
+ layer.dirty.add(t.key);
+}
+
+/** Show the dirty tiles: base blended toward the style by L * opacity. @param {any} layer @param {number[]} rgb 0..255 @param {number} opacity */
+function composite(layer, rgb, opacity) {
+ for (const key of layer.dirty) {
+ const t = layer.tiles.get(key);
+ if (!t) continue;
+ const out = t.img.data;
+ const base = t.base;
+ for (let i = 0, n = t.w * t.h; i < n; i++) {
+ const k = Math.min(1, t.L[i] * opacity);
+ if (k <= 0) continue;
+ const o = i * 4;
+ out[o] = Math.round(base[o] + (rgb[0] - base[o]) * k);
+ out[o + 1] = Math.round(base[o + 1] + (rgb[1] - base[o + 1]) * k);
+ out[o + 2] = Math.round(base[o + 2] + (rgb[2] - base[o + 2]) * k);
+ out[o + 3] = Math.round(base[o + 3] + (255 - base[o + 3]) * k);
+ }
+ layer.ctx.putImageData(t.img, t.x, t.y);
+ }
+ layer.dirty.clear();
+}
+
+/** Put the stroke's base pixels back (a cancel). @param {any} layer */
+function restoreBase(layer) {
+ for (const t of layer.tiles.values()) layer.ctx.putImageData(new ImageData(new Uint8ClampedArray(t.base), t.w, t.h), t.x, t.y);
+}
+
+// ---- dabs ---------------------------------------------------------------------------------------------------------
+
+/** @param {Float32Array | null} mask @param {number} sx -1..1 @param {number} sy -1..1 */
+function sampleMask(mask, sx, sy) {
+ if (!mask) return 1;
+ const fx = ((sx + 1) / 2) * (STAMP_RES - 1);
+ const fy = ((sy + 1) / 2) * (STAMP_RES - 1);
+ if (fx < 0 || fy < 0 || fx > STAMP_RES - 1 || fy > STAMP_RES - 1) return 0;
+ const x0 = Math.floor(fx);
+ const y0 = Math.floor(fy);
+ const x1 = Math.min(x0 + 1, STAMP_RES - 1);
+ const y1 = Math.min(y0 + 1, STAMP_RES - 1);
+ const tx = fx - x0;
+ const ty = fy - y0;
+ const a = mask[y0 * STAMP_RES + x0] * (1 - tx) + mask[y0 * STAMP_RES + x1] * tx;
+ const b = mask[y1 * STAMP_RES + x0] * (1 - tx) + mask[y1 * STAMP_RES + x1] * tx;
+ return a * (1 - ty) + b * ty;
+}
+
+/** A dab in texture px (the UV canvas). @param {any} s the stroke @param {number} cx @param {number} cy @param {number} r @param {number} a */
+function dabUv(s, cx, cy, r, a) {
+ const layer = s.layer;
+ const x0 = Math.max(0, Math.floor(cx - r));
+ const x1 = Math.min(layer.W - 1, Math.ceil(cx + r));
+ const y0 = Math.max(0, Math.floor(cy - r));
+ const y1 = Math.min(layer.H - 1, Math.ceil(cy + r));
+ for (let y = y0; y <= y1; y++)
+ for (let x = x0; x <= x1; x++) {
+ const dx = x + 0.5 - cx;
+ const dy = y + 0.5 - cy;
+ const d = Math.sqrt(dx * dx + dy * dy);
+ if (d > r) continue;
+ const cov = s.mask ? sampleMask(s.mask, dx / r, dy / r) : falloff(d / r, s.brush.hardness);
+ touch(layer, x, y, a * cov);
+ }
+}
+
+/**
+ * A dab on the model: a sphere (centre `c`, radius `R`, object space) painted into the map through every triangle
+ * it touches. Pass 1 paints pixels a touched triangle OWNS; pass 2 pads each into the uncovered gutter.
+ * @param {any} s @param {number[]} c @param {number} R @param {number} a
+ */
+function dabModel(s, c, R, a) {
+ const { layer, model } = s;
+ const W = layer.W;
+ const H = layer.H;
+ const flip = s.flip;
+ const tris = trisNear(model.grid, c, R);
+ /** @type {{f: any, P: number[][], Pp: number[][], inv: number[], T: number[]}[]} */
+ const hits = [];
+ for (const t of tris) {
+ const f = frameOf(model, t);
+ if (!f || !dabOnTri(f, c, R)) continue;
+ const T = planeToCanvas(f, W, H, flip);
+ const det = T[0] * T[3] - T[2] * T[1];
+ if (Math.abs(det) < 1e-18) continue;
+ const inv = [T[3] / det, -T[2] / det, -T[1] / det, T[0] / det];
+ const P = f.uv.map((/** @type {number[]} */ uv) => uvToCanvas(uv, W, H, flip));
+ hits.push({ f, P, Pp: padTri(P, PAD), inv, T });
+ }
+ if (!hits.length) return;
+ const cov = coverageOf(model, W, H, flip);
+ const R2 = R * R;
+ const hard = s.brush.hardness;
+ for (let pass = 0; pass < 2; pass++)
+ for (const h of hits) {
+ const pts = pass ? h.Pp : h.P;
+ const x0 = Math.max(0, Math.floor(Math.min(pts[0][0], pts[1][0], pts[2][0])));
+ const x1 = Math.min(W - 1, Math.ceil(Math.max(pts[0][0], pts[1][0], pts[2][0])));
+ const y0 = Math.max(0, Math.floor(Math.min(pts[0][1], pts[1][1], pts[2][1])));
+ const y1 = Math.min(H - 1, Math.ceil(Math.max(pts[0][1], pts[1][1], pts[2][1])));
+ // keep a huge triangle's scan to the dab's own footprint: the sphere seen through this triangle
+ const foot = footprint(h, c, R, W, H);
+ const fx0 = Math.max(x0, foot[0]);
+ const fx1 = Math.min(x1, foot[1]);
+ const fy0 = Math.max(y0, foot[2]);
+ const fy1 = Math.min(y1, foot[3]);
+ const { f, inv, T } = h;
+ for (let y = fy0; y <= fy1; y++)
+ for (let x = fx0; x <= fx1; x++) {
+ const px = x + 0.5;
+ const py = y + 0.5;
+ if (pass === 0) {
+ if (!insideTri(h.P, px, py)) continue;
+ } else if (cov[y * W + x] || !insideTri(h.Pp, px, py)) continue;
+ // canvas -> plane -> object space
+ const ex = px - T[4];
+ const ey = py - T[5];
+ const qx = inv[0] * ex + inv[1] * ey;
+ const qy = inv[2] * ex + inv[3] * ey;
+ const wx = f.o[0] + f.e1[0] * qx + f.e2[0] * qy - c[0];
+ const wy = f.o[1] + f.e1[1] * qx + f.e2[1] * qy - c[1];
+ const wz = f.o[2] + f.e1[2] * qx + f.e2[2] * qy - c[2];
+ const d2 = wx * wx + wy * wy + wz * wz;
+ if (d2 > R2) continue;
+ let k;
+ if (s.mask) {
+ const st = s.stampFrame;
+ k = sampleMask(s.mask, (wx * st.t[0] + wy * st.t[1] + wz * st.t[2]) / R, (wx * st.b[0] + wy * st.b[1] + wz * st.b[2]) / R);
+ } else k = falloff(Math.sqrt(d2) / R, hard);
+ touch(layer, x, y, a * k);
+ }
+ }
+}
+
+/** The canvas-pixel box the sphere can reach through one triangle's map. @param {any} h @param {number[]} c
+ * @param {number} R @param {number} W @param {number} H @returns {number[]} [x0, x1, y0, y1] */
+function footprint(h, c, R, W, H) {
+ const hit = dabOnTri(h.f, c, R);
+ if (!hit) return [1, 0, 1, 0];
+ const T = h.T;
+ const [qx, qy] = hit.qc;
+ const r = hit.r;
+ // an axis-aligned box of a transformed circle: centre +- r * (|row|)
+ const cx = T[0] * qx + T[2] * qy + T[4];
+ const cy = T[1] * qx + T[3] * qy + T[5];
+ const ex = r * Math.hypot(T[0], T[2]);
+ const ey = r * Math.hypot(T[1], T[3]);
+ return [Math.max(0, Math.floor(cx - ex - 1)), Math.min(W - 1, Math.ceil(cx + ex + 1)), Math.max(0, Math.floor(cy - ey - 1)), Math.min(H - 1, Math.ceil(cy + ey + 1))];
+}
+
+/** A dab on vertex colours. @param {any} s @param {number[]} c @param {number} R @param {number} a */
+function dabVertex(s, c, R, a, mirrored = false) {
+ const v = s.vertex;
+ // the stroke's normal faces the nearest-vertex fallback (a low-poly mesh); the mirrored half faces the mirror way
+ const n = s.n ? (mirrored ? [-s.n[0], s.n[1], s.n[2]] : s.n) : null;
+ const touched = vertexDab(v.positions, c, R, s.brush.hardness, a, v.acc, { normals: v.normals, n });
+ if (!touched.length) return;
+ blendVertexColors(v.base, v.target, v.acc, s.brush.opacity, v.out, touched);
+ v.dirty = true;
+}
+
+/** One stroke point after another: dabs spaced along the path, mirrored when asked. @param {any} s @param {number[]} p */
+function strokePoint(s, p) {
+ const dim = s.sp === 'uv' ? 2 : 3;
+ const last = s.last;
+ if (last && last.length === p.length && last.every((/** @type {number} */ x, /** @type {number} */ i) => x === p[i])) return;
+ // the UV canvas measures in texture px, the model in its own units
+ const metric = s.sp === 'uv' ? [p[0] * s.layer.W, (s.flip ? 1 - p[1] : p[1]) * s.layer.H, p[2] ?? 1] : [p[0], p[1], p[2], p[3] ?? 1];
+ const step = Math.max(DAB_SPACING * 2 * s.r, s.sp === 'uv' ? 0.5 : 1e-6);
+ const from = s.lastMetric ?? metric;
+ const run = s.lastMetric ? dabsAlong(from, metric, dim, step, s.carry) : { dabs: [metric], carry: 0 };
+ s.carry = run.carry;
+ s.last = p;
+ s.lastMetric = metric;
+ for (const d of run.dabs) {
+ const w = d[dim];
+ const factor = s.pm === 'off' ? 1 : paintPressureFactor(Number.isFinite(w) ? w : 1);
+ const r = s.pm === 'opacity' || s.pm === 'off' ? s.r : s.r * factor;
+ const a = s.brush.flow * (s.pm === 'opacity' ? factor : 1);
+ // one mark per dab: a pixel takes a dab once, and the mirrored half is the SAME dab, so where the two halves
+ // meet on the mirror plane they union rather than stack
+ if (s.layer) s.layer.dab++;
+ if (s.sp === 'uv') dabUv(s, d[0], d[1], r, a);
+ else {
+ const c = [d[0], d[1], d[2]];
+ const mirrored = s.brush.mirror && !onMirrorPlane(c, r) ? mirrorX(c) : null;
+ if (s.sp === 'vtx') {
+ // vertex dabs stack per call, so the mirrored half (disjoint off the plane) is its own call
+ dabVertex(s, c, r, a);
+ if (mirrored) dabVertex(s, mirrored, r, a, true);
+ } else {
+ dabModel(s, c, r, a);
+ if (mirrored) dabModel(s, mirrored, r, a);
+ }
+ }
+ s.dabs++;
+ }
+}
+
+/** Show what the dabs did since the last call: composite the tiles, upload, redraw the UV view. @param {any} s */
+function present(s) {
+ if (s.sp === 'vtx') {
+ if (s.vertex.dirty) {
+ s.vertex.attr.needsUpdate = true;
+ s.vertex.dirty = false;
+ }
+ } else if (s.layer.dirty.size) {
+ composite(s.layer, s.rgb, s.brush.opacity);
+ s.surface.texture.needsUpdate = true;
+ uvPaintTick.update((n) => n + 1);
+ }
+ pokeScene();
+}
+
+// ---- surfaces -------------------------------------------------------------------------------------------------------
+
+/** @type {Map} uuid#slot#channel -> a roughness / metalness / emission paint canvas */
+const surfaces = new Map();
+
+/** @param {any} material */
+function firstMapOf(material) {
+ for (const key of ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'emissiveMap', 'aoMap']) if (material?.[key]) return material[key];
+ return null;
+}
+
+/**
+ * The paint canvas for a roughness / metalness / emission slot, seeded from the slot's image (a shared ORM
+ * texture gives its own channel: green for roughness, blue for metalness), or a NEW map at the chosen size,
+ * filled so nothing changes until you paint — the material's own value, which is then lifted to 1 (or a black
+ * emissive colour to white) in the same undo step as the stroke. Installed as the slot's live texture.
+ * @param {any} object @param {number} slot @param {any} ch channelOf(...) @param {boolean} local
+ */
+function channelSurface(object, slot, ch, local) {
+ const material = materialAt(object, slot);
+ if (!material || !(ch.map in material)) return null;
+ const k = object.uuid + '#' + slot + '#' + ch.key;
+ const existing = surfaces.get(k);
+ const known = mapSlotKnownUrl(material, ch.map);
+ if (existing && (material[ch.map] === existing.texture || (existing.seededFrom && known === existing.seededFrom))) {
+ existing.previousMap = material[ch.map] === existing.texture ? existing.previousMap : material[ch.map];
+ install(material, existing);
+ return existing;
+ }
+ const source = material[ch.map] ?? null;
+ const image = drawable(source?.image);
+ const before = source ? mapSlotUrl(material, ch.map, 2048) : null;
+ const canvas = existing?.canvas ?? document.createElement('canvas');
+ const size = (image && sizeOf(image)) || { w: get(paintMapSize), h: get(paintMapSize) };
+ canvas.width = size.w;
+ canvas.height = size.h;
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
+ if (!ctx) return null;
+ /** @type {{param: string, before: any, after: any} | null} */
+ let lift = null;
+ const single = !Array.isArray(object.material);
+ if (image) {
+ ctx.drawImage(image, 0, 0, size.w, size.h);
+ if (ch.gray) {
+ const data = ctx.getImageData(0, 0, size.w, size.h);
+ const px = data.data;
+ const at = ch.key === 'roughness' ? 1 : 2; // three reads roughness from G, metalness from B
+ for (let i = 0; i < px.length; i += 4) px[i] = px[i + 1] = px[i + 2] = px[i + at];
+ ctx.putImageData(data, 0, 0);
+ }
+ } else if (ch.gray) {
+ const scalar = typeof material[ch.param] === 'number' ? material[ch.param] : 1;
+ // a single material can lift its slider to 1 so the map reads true; a slot of an array cannot (the param
+ // message addresses slot 0), so it starts white and multiplies the slider like any map
+ const fill = single ? scalar : 1;
+ ctx.fillStyle = '#' + Math.round(Math.max(0, Math.min(1, fill)) * 255).toString(16).padStart(2, '0').repeat(3);
+ ctx.fillRect(0, 0, size.w, size.h);
+ if (single && scalar !== 1) lift = { param: ch.param, before: scalar, after: 1 };
+ } else {
+ ctx.fillStyle = '#000000';
+ ctx.fillRect(0, 0, size.w, size.h);
+ if (single && material.emissive?.getHex?.() === 0) lift = { param: 'emissive', before: '#000000', after: '#ffffff' };
+ }
+ const texture = existing?.texture ?? new THREE.CanvasTexture(canvas);
+ texture.image = canvas;
+ texture.colorSpace = ch.srgb ? THREE.SRGBColorSpace : THREE.NoColorSpace;
+ const inherit = source ?? firstMapOf(material);
+ if (inherit) copyTextureParams(inherit, texture);
+ texture.needsUpdate = true;
+ const entry = { canvas, texture, ch: ch.key, key: ch.map, uuid: object.uuid, slot, flipY: texture.flipY !== false, before, seededFrom: before, previousMap: source, lift, liftShown: false };
+ surfaces.set(k, entry);
+ install(material, entry);
+ if (lift) showLift(material, entry, true);
+ void local;
+ return entry;
+}
+
+/** @param {any} material @param {any} entry */
+function install(material, entry) {
+ if (material[entry.key] !== entry.texture) {
+ material[entry.key] = entry.texture;
+ material.needsUpdate = true;
+ }
+ entry.texture.needsUpdate = true;
+ pokeScene();
+}
+
+/** Show (or take back) a new map's slider lift locally; the commit records and sends it. @param {any} material
+ * @param {any} entry @param {boolean} on */
+function showLift(material, entry, on) {
+ const lift = entry.lift;
+ if (!lift) return;
+ const value = on ? lift.after : lift.before;
+ if (material[lift.param]?.isColor) material[lift.param].set(value);
+ else material[lift.param] = value;
+ material.needsUpdate = true;
+ entry.liftShown = on;
+}
+
+/** The surface a stroke paints, or null. @param {any} object @param {number} slot @param {string} ch @param {boolean} local */
+async function surfaceFor(object, slot, ch, local) {
+ if (ch === 'color') {
+ const entry = await openColorSurface(object.uuid, slot);
+ return entry ? Object.assign(entry, { key: 'map', ch: 'color' }) : null;
+ }
+ return channelSurface(object, slot, channelOf(ch), local);
+}
+
+// ---- stamps -------------------------------------------------------------------------------------------------------
+
+/** @type {Map} */
+const masks = new Map();
+
+/** The stamp image as a 64 x 64 coverage mask: its alpha where it has any, else darkness (a black shape on white).
+ * Null while the bytes are missing (the stroke paints round meanwhile; the commit is the truth). @param {string} hash */
+async function stampMask(hash) {
+ if (!hash) return null;
+ const cached = masks.get(hash);
+ if (cached) return cached;
+ const url = await resolveHudImage(hash);
+ if (!url) return null;
+ const image = await new Promise((resolve) => {
+ const img = new Image();
+ img.onload = () => resolve(img);
+ img.onerror = () => resolve(null);
+ img.src = url;
+ });
+ if (!image) return null;
+ const canvas = document.createElement('canvas');
+ canvas.width = canvas.height = STAMP_RES;
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
+ if (!ctx) return null;
+ ctx.drawImage(/** @type {any} */ (image), 0, 0, STAMP_RES, STAMP_RES);
+ const px = ctx.getImageData(0, 0, STAMP_RES, STAMP_RES).data;
+ let transparent = false;
+ for (let i = 3; i < px.length; i += 4) if (px[i] < 250) transparent = true;
+ const mask = new Float32Array(STAMP_RES * STAMP_RES);
+ for (let i = 0; i < mask.length; i++) {
+ const o = i * 4;
+ mask[i] = transparent ? px[o + 3] / 255 : 1 - (0.2126 * px[o] + 0.7152 * px[o + 1] + 0.0722 * px[o + 2]) / 255;
+ }
+ masks.set(hash, mask);
+ return mask;
+}
+
+/** A stamp's orientation on the model: two axes perpendicular to the first hit's normal. @param {number[]} n */
+function stampFrameOf(n) {
+ const len = Math.hypot(n[0], n[1], n[2]) || 1;
+ const nn = [n[0] / len, n[1] / len, n[2] / len];
+ const up = Math.abs(nn[1]) > 0.9 ? [1, 0, 0] : [0, 1, 0];
+ const t = [up[1] * nn[2] - up[2] * nn[1], up[2] * nn[0] - up[0] * nn[2], up[0] * nn[1] - up[1] * nn[0]];
+ const tl = Math.hypot(t[0], t[1], t[2]) || 1;
+ const tt = [t[0] / tl, t[1] / tl, t[2] / tl];
+ const b = [nn[1] * tt[2] - nn[2] * tt[1], nn[2] * tt[0] - nn[0] * tt[2], nn[0] * tt[1] - nn[1] * tt[0]];
+ return { t: tt, b };
+}
+
+// ---- strokes --------------------------------------------------------------------------------------------------------
+
+/**
+ * Open a stroke from its SPEC (the fields a `meshpaint` message carries). The same function serves the painter and
+ * every peer replaying it, which is what makes the replay draw the same picture.
+ * @param {{id: string, uuid: string, slot: number, ch: string, sp: 'uv'|'obj'|'vtx', c: string, r: number, b: any, pm: string, n: number[] | null}} spec
+ * @param {boolean} local
+ */
+async function openStroke(spec, local) {
+ const object = objectOf(spec.uuid);
+ if (!object) return null;
+ // spec.b is the brush in its WIRE form, for the painter and every peer alike
+ const brush = brushFromWire(spec.b);
+ /** @type {any} */
+ const s = { ...spec, brush, local, object, dabs: 0, carry: 0, last: null, lastMetric: null, rgb: hexToRgb(spec.c).map((x) => Math.round(x * 255)) };
+ if (spec.sp === 'vtx') {
+ const geometry = object.geometry;
+ const pos = geometry?.attributes?.position;
+ if (!pos) return null;
+ let attr = geometry.attributes.color;
+ const hadColors = !!attr;
+ if (!attr) {
+ attr = new THREE.BufferAttribute(new Float32Array(pos.count * 3).fill(1), 3);
+ geometry.setAttribute('color', attr);
+ }
+ const material = object.material;
+ const wasVertexColors = !!material?.vertexColors;
+ if (material && !Array.isArray(material) && !material.vertexColors) {
+ material.vertexColors = true;
+ material.needsUpdate = true;
+ }
+ const lin = hexToRgb(spec.c).map(srgbToLinear);
+ s.vertex = {
+ positions: pos.array,
+ normals: geometry.attributes.normal?.array ?? null,
+ attr,
+ hadColors,
+ wasVertexColors,
+ base: new Float32Array(attr.array),
+ out: attr.array,
+ acc: new Float32Array(pos.count),
+ target: lin,
+ dirty: false
+ };
+ return s;
+ }
+ const surface = await surfaceFor(object, spec.slot, spec.ch, local);
+ if (!surface) return null;
+ s.surface = surface;
+ s.flip = surface.flipY !== false;
+ s.layer = makeLayer(surface.canvas);
+ if (spec.sp === 'obj') {
+ s.model = meshModel(object, spec.slot);
+ if (!s.model?.uvs) return null;
+ }
+ if (brush.stamp) {
+ s.mask = await stampMask(brush.stamp);
+ if (s.mask && spec.sp !== 'uv') s.stampFrame = stampFrameOf(spec.n ?? [0, 0, 1]);
+ }
+ return s;
+}
+
+/** Free the per-stroke memory (tiles, colour copies). @param {any} s */
+function release(s) {
+ if (s.layer) {
+ s.layer.tiles.clear();
+ s.layer.dirty.clear();
+ }
+ if (s.vertex) {
+ s.vertex.base = null;
+ s.vertex.acc = null;
+ }
+}
+
+let seq = 0;
+/** @type {any} the local stroke */
+let stroke = null;
+let lastSend = 0;
+
+/** is a local stroke open (or opening)? */
+export function stroking() {
+ return !!stroke;
+}
+
+/**
+ * Should a stroke from the UV canvas leave the shipped painter? Only when something new is in use — a channel
+ * other than colour, or a brush other than the shipped hard round one.
+ */
+export function needsMeshPaint() {
+ return get(paintChannel) !== 'color' || !isDefaultBrush(currentBrush());
+}
+
+/** the brush as the panel has it */
+export function currentBrush() {
+ /** @type {Record} */
+ const raw = {};
+ for (const [key, store] of Object.entries(BRUSH_STORES)) raw[key] = get(/** @type {any} */ (store));
+ return normalizeBrush(raw);
+}
+
+/** the shared material question, asked once per material and session @type {Map} */
+const sharedAnswers = new Map();
+
+/**
+ * A shared material: paint every object wearing it, or give this one its own copy first (sent to peers, who
+ * clone it too). False = cancelled. @param {any} object
+ */
+async function settleSharing(object) {
+ if (!isSharedMaterial(object.uuid)) return true;
+ const id = materialIdOf(object);
+ if (sharedAnswers.get(id) === 'all') return true;
+ const others = objectsSharing(id).length - 1;
+ const choice = await showChoice({
+ title: 'This material is shared',
+ message:
+ (others === 1 ? '1 other object wears' : others + ' other objects wear') +
+ ' the same material. Paint all of them, or give this object its own copy first?',
+ choices: [
+ { value: 'all', label: 'All objects that share it' },
+ { value: 'this', label: 'This object only' }
+ ],
+ cancelLabel: 'Cancel'
+ });
+ if (!choice) return false;
+ if (choice === 'all') sharedAnswers.set(id, 'all');
+ else unlinkForEveryone(object.uuid);
+ return true;
+}
+
+/** "This object only": clone the material here and on every peer (an older peer ignores the parameter).
+ * @param {string} uuid */
+export function unlinkForEveryone(uuid) {
+ if (!unlinkMaterial(uuid)) return false;
+ /** @type {any} */
+ const peer = get(peers);
+ peer?.send({ type: 'objectParameters', parameter: 'materialUnlink', uuid });
+ return true;
+}
+
+/** the brush radius in the stroke's own units: texture px / 2 on the map, object units on the model
+ * @param {any} mesh @param {number} slot @param {string} sp @param {any} hit */
+export function strokeRadius(mesh, slot, sp, hit) {
+ const size = get(uvBrushSize);
+ if (sp === 'uv') return size / 2;
+ const model = meshModel(mesh, slot);
+ if (!model) return 0;
+ if (sp === 'vtx') return (model.diag * size) / 512;
+ const dims = mapDims(mesh, slot, get(paintChannel));
+ const t = hit && typeof hit.tri === 'number' ? hit.tri : -1;
+ let f = t >= 0 ? frameOf(model, t) : null;
+ if (!f && hit?.local) {
+ for (const tt of trisNear(model.grid, hit.local, model.diag / 48)) {
+ f = frameOf(model, tt);
+ if (f) break;
+ }
+ }
+ const density = f ? texelDensity(f, dims.w, dims.h) : 0;
+ return density > 0 ? size / 2 / density : (model.diag * size) / 512;
+}
+
+/** the size of the map a stroke would paint @param {any} mesh @param {number} slot @param {string} ch */
+function mapDims(mesh, slot, ch) {
+ const material = materialAt(mesh, slot);
+ const surface = ch === 'color' ? null : surfaces.get(mesh.uuid + '#' + slot + '#' + ch);
+ const image = surface?.canvas ?? drawable(material?.[channelOf(ch).map]?.image);
+ if (image) {
+ const s = sizeOf(image);
+ if (s) return s;
+ }
+ if (ch === 'color') return { w: 1024, h: 1024 };
+ return { w: get(paintMapSize), h: get(paintMapSize) };
+}
+
+/**
+ * Start a stroke. `sp` 'uv' takes [u, v] (the UV canvas), 'obj' takes the object-space hit {local, normal, tri},
+ * and 'obj' becomes 'vtx' by itself on a mesh without usable UVs (said in the panel). Resolves false when nothing
+ * can be painted (said with a toast).
+ * @param {{uuid: string, slot?: number, sp: 'uv'|'obj', at: number[], w?: number, normal?: number[], tri?: number}} opts
+ */
+export async function beginStroke(opts) {
+ if (stroke) endStroke();
+ const object = objectOf(opts.uuid);
+ if (!object?.geometry) return false;
+ const slot = opts.slot ?? 0;
+ const ch = get(paintChannel);
+ /** @type {'uv'|'obj'|'vtx'} */
+ let sp = opts.sp;
+ if (sp === 'obj') {
+ const info = targetFor(object, slot);
+ if (info?.mode === 'vertex') {
+ if (ch !== 'color') {
+ showToast(channelOf(ch).label + ' needs a UV map, and this mesh ' + (info.reason.includes('no UV') ? 'has none' : 'has overlapping UVs') + '. Paint Colour (as vertex colours), or unwrap it in the UV editor first.');
+ return false;
+ }
+ sp = 'vtx';
+ }
+ }
+ const material = materialAt(object, slot);
+ if (!material || (sp !== 'vtx' && !(channelOf(ch).map in material))) {
+ showToast('This material has no ' + channelOf(ch).label.toLowerCase() + ' — switch it to Standard in the Inspector to paint it.');
+ return false;
+ }
+ const pending = { opening: true, queue: /** @type {any[]} */ ([]), ending: false, cancelled: false };
+ stroke = pending;
+ if (!(await settleSharing(object))) {
+ stroke = null;
+ return false;
+ }
+ if (pending.cancelled) return false;
+ const brush = currentBrush();
+ const r = strokeRadius(object, slot, sp, { local: opts.at, tri: opts.tri });
+ const spec = {
+ id: (get(peers)?.peer?.id ?? 'local') + ':m' + ++seq,
+ uuid: opts.uuid,
+ slot,
+ ch,
+ sp,
+ c: paintStyle(ch, get(uvBrushColor), get(paintValue), brush.erase),
+ r: Math.round(r * 1e5) / 1e5 || 1e-5,
+ b: brushWire(brush),
+ pm: get(uvPenPressure),
+ n: opts.normal ? opts.normal.map((x) => Math.round(x * 1e4) / 1e4) : null
+ };
+ // the image before the stroke — what undo goes back to (an imported colour map has no data URL, so it is
+ // encoded once here instead of undo removing the texture)
+ const before = sp === 'vtx' ? null : ch === 'color' ? colourBefore(object, slot) : null;
+ if (brush.stamp) shareHudImage(brush.stamp);
+ const s = await openStroke(spec, true);
+ if (!s || pending.cancelled) {
+ if (s) cancelOpened(s);
+ if (stroke === pending) stroke = null;
+ return false;
+ }
+ s.before = sp === 'vtx' ? null : ch === 'color' ? before : s.surface.before;
+ s.points = [];
+ s.sent = 0;
+ stroke = s;
+ addPoint(s, opts.at, opts.w);
+ for (const q of pending.queue) addPoint(s, q.at, q.w);
+ present(s);
+ if (pending.ending) endStroke();
+ return true;
+}
+
+/** @param {any} object @param {number} slot */
+function colourBefore(object, slot) {
+ const material = materialAt(object, slot);
+ const url = material?.userData?.mapDataUrl ?? null;
+ if (url) return url;
+ const image = drawable(material?.map?.image);
+ if (!image) return null;
+ const size = sizeOf(image);
+ if (!size) return null;
+ const canvas = document.createElement('canvas');
+ canvas.width = size.w;
+ canvas.height = size.h;
+ canvas.getContext('2d')?.drawImage(image, 0, 0, size.w, size.h);
+ return encodePaintCanvas(canvas);
+}
+
+/** @param {any} s @param {number[]} at @param {number | undefined} w */
+function addPoint(s, at, w) {
+ const dim = s.sp === 'uv' ? 2 : 3;
+ const raw = [...at.slice(0, dim)];
+ if (typeof w === 'number' && Number.isFinite(w) && w < 1 && s.pm !== 'off') raw.push(w);
+ const p = quantizePoint(raw, dim);
+ s.points.push(p);
+ strokePoint(s, p);
+}
+
+/**
+ * Extend the stroke: UV [u, v] or the object-space point, with the pen's pressure (undefined for a mouse).
+ * Points that arrive while the stroke is still opening (the canvas seeds, a shared-material question) queue.
+ * @param {number[]} at @param {number} [w]
+ */
+export function strokeTo(at, w) {
+ const s = stroke;
+ if (!s) return false;
+ if (s.opening) {
+ s.queue.push({ at, w });
+ return true;
+ }
+ addPoint(s, at, w);
+ present(s);
+ const now = performance.now();
+ if (now - lastSend >= SEND_MS) {
+ lastSend = now;
+ flush(s);
+ }
+ return true;
+}
+
+/** send the points peers have not seen (from the last one they have, so their path continues) @param {any} s */
+function flush(s) {
+ const start = Math.max(s.sent - 1, 0);
+ const seg = s.points.slice(start);
+ if (!seg.length || (s.sent > 0 && seg.length < 2)) return;
+ s.sent = s.points.length;
+ /** @type {any} */
+ const peer = get(peers);
+ if (!peer) return;
+ const b = s.b && Object.keys(s.b).length ? s.b : undefined;
+ peer.send({
+ type: 'meshpaint',
+ id: s.id,
+ uuid: s.uuid,
+ ...(s.slot ? { slot: s.slot } : {}),
+ ...(s.ch !== 'color' ? { ch: s.ch } : {}),
+ sp: s.sp,
+ c: s.c,
+ r: s.r,
+ ...(b ? { b } : {}),
+ ...(s.pm === 'opacity' || s.pm === 'off' ? { pm: s.pm } : {}),
+ ...(s.n ? { n: s.n } : {}),
+ seg
+ });
+}
+
+/** Finish the stroke and commit it: one undo step, sent through the paths that already save and sync. */
+export function endStroke() {
+ const s = stroke;
+ if (!s) return false;
+ if (s.opening) {
+ s.ending = true;
+ return false;
+ }
+ stroke = null;
+ flush(s);
+ /** @type {any} */
+ const peer = get(peers);
+ peer?.send({ type: 'meshpaintend', id: s.id });
+ present(s);
+ const ok = s.dabs > 0 ? commit(s) : (cancelOpened(s), false);
+ release(s);
+ // the stroke as a peer received it (spec + every rounded point), so a suite can REPLAY it and compare pixels
+ lastStroke = { id: s.id, uuid: s.uuid, slot: s.slot, sp: s.sp, ch: s.ch, c: s.c, r: s.r, b: s.b, pm: s.pm, n: s.n, dabs: s.dabs, committed: ok, points: s.points.length <= 2048 ? s.points.map((/** @type {number[]} */ p) => [...p]) : null };
+ return ok;
+}
+
+/** Abandon the stroke: the model goes back exactly as it was. */
+export function cancelStroke() {
+ const s = stroke;
+ stroke = null;
+ if (!s) return;
+ if (s.opening) {
+ s.cancelled = true;
+ return;
+ }
+ /** @type {any} */
+ const peer = get(peers);
+ peer?.send({ type: 'meshpaintend', id: s.id, cancel: 1 });
+ cancelOpened(s);
+ release(s);
+}
+
+/** Put an opened stroke's target back: base pixels, the previous map, the lift, the colours. @param {any} s */
+function cancelOpened(s) {
+ if (s.vertex) {
+ const v = s.vertex;
+ if (v.base) v.out.set(v.base);
+ v.attr.needsUpdate = true;
+ const material = s.object.material;
+ if (!v.wasVertexColors && material && !Array.isArray(material)) {
+ material.vertexColors = false;
+ material.needsUpdate = true;
+ }
+ if (!v.hadColors) s.object.geometry.deleteAttribute('color');
+ pokeScene();
+ return;
+ }
+ if (s.layer) restoreBase(s.layer);
+ const material = materialAt(s.object, s.slot);
+ const surface = s.surface;
+ if (material && surface && material[surface.key] === surface.texture) {
+ material[surface.key] = surface.previousMap ?? null;
+ material.needsUpdate = true;
+ }
+ if (material && surface?.liftShown) showLift(material, surface, false);
+ if (s.ch === 'color') dropColorSurface(s.uuid, s.slot);
+ else surfaces.delete(s.uuid + '#' + s.slot + '#' + s.ch);
+ pokeScene();
+}
+
+/** @param {any} s */
+function commit(s) {
+ const label = 'Paint ' + channelOf(s.ch).label.toLowerCase();
+ const own = !historyBatchOpen();
+ if (own) beginHistoryBatch();
+ try {
+ if (s.sp === 'vtx') return commitVertex(s);
+ const url = encodePaintCanvas(s.surface.canvas);
+ if (s.ch === 'color') {
+ recordMaterialChange(s.uuid, 'map', null, s.before, url, s.slot);
+ applyMap(s.object, url, s.slot);
+ broadcastMaterial({ type: 'objectParameters', parameter: 'map', uuid: s.uuid, map: url, ...(s.slot ? { slot: s.slot } : {}) });
+ s.surface.seededFrom = url;
+ return true;
+ }
+ const material = materialAt(s.object, s.slot);
+ const surface = s.surface;
+ if (surface.lift && surface.liftShown && material) {
+ // recorded as a real change: put the old value back silently, then set it through the replicated setter
+ showLift(material, surface, false);
+ setMaterialParam(s.uuid, surface.lift.param, surface.lift.after);
+ surface.liftShown = false;
+ surface.lift = null;
+ }
+ const ok = commitPaintedMapSlot(s.uuid, surface.key, s.before, url, s.slot);
+ surface.seededFrom = url;
+ surface.before = url;
+ return ok;
+ } finally {
+ if (own) endHistoryBatch(label);
+ }
+}
+
+/** Vertex colours ride the meshgeo commit (it carries `colors` since mcp-shapes), corner by corner. @param {any} s */
+function commitVertex(s) {
+ const object = s.object;
+ const geometry = object.geometry;
+ const v = s.vertex;
+ const tris = readTriangles(geometry);
+ const expand = (/** @type {Float32Array} */ src) => {
+ const index = geometry.index;
+ const count = index ? index.count : geometry.attributes.position.count;
+ const out = new Array(count * 3);
+ for (let i = 0; i < count; i++) {
+ const j = index ? index.getX(i) : i;
+ out[i * 3] = src[j * 3];
+ out[i * 3 + 1] = src[j * 3 + 1];
+ out[i * 3 + 2] = src[j * 3 + 2];
+ }
+ return out;
+ };
+ const positions = trisToPositions(tris);
+ const groups = trisToGroups(tris);
+ const uvs = trisToUVs(tris);
+ const before = { positions, groups, uvs, colors: expand(v.base) };
+ const after = { positions, groups, uvs, colors: expand(v.out) };
+ const material = object.material;
+ if (!v.wasVertexColors && material && !Array.isArray(material)) {
+ material.vertexColors = false; // so the setter records false -> true
+ setMaterialParam(object.uuid, 'vertexColors', true);
+ }
+ return commitMeshGeoTriple(object.uuid, before, after);
+}
+
+// ---- the receive side ---------------------------------------------------------------------------------------------
+
+/** @type {Map, ts: number}>} */
+const remote = new Map();
+
+/** A peer's live stroke. @param {any} data a `meshpaint` message wireValidate passed */
+export async function applyMeshPaint(data) {
+ let entry = remote.get(data.id);
+ if (!entry) {
+ const spec = { id: data.id, uuid: data.uuid, slot: data.slot ?? 0, ch: data.ch ?? 'color', sp: data.sp, c: data.c, r: data.r, b: brushWire(brushFromWire(data.b)), pm: data.pm ?? 'size', n: data.n ?? null };
+ entry = { ready: openStroke(spec, false), ts: Date.now() };
+ remote.set(data.id, entry);
+ }
+ entry.ts = Date.now();
+ const s = await entry.ready;
+ if (!s) return;
+ for (const p of data.seg) strokePoint(s, p);
+ present(s);
+}
+
+/** A peer finished (or cancelled) a stroke. The commit that follows replaces the preview. @param {any} data */
+export async function applyMeshPaintEnd(data) {
+ const entry = remote.get(data?.id);
+ if (!entry) return;
+ remote.delete(data.id);
+ const s = await entry.ready;
+ if (!s) return;
+ if (data.cancel) cancelOpened(s);
+ else present(s);
+ release(s);
+}
+
+/** @returns {number} live remote strokes (test hook) */
+export function remoteStrokeCount() {
+ return remote.size;
+}
+
+if (typeof window !== 'undefined')
+ setInterval(() => {
+ const now = Date.now();
+ for (const [id, entry] of remote) if (now - entry.ts > STALE_MS) void applyMeshPaintEnd({ id, cancel: 0 });
+ }, STALE_MS);
+
+// ---- colour pick ----------------------------------------------------------------------------------------------------
+
+/**
+ * Take the brush value from the model under the cursor: the colour (or the grey of the channel) at the hit's UV,
+ * or the vertex colour when the mesh paints vertex colours. @param {any} mesh @param {number} slot @param {any} hit a raycast hit
+ */
+export function pickAt(mesh, slot, hit) {
+ const ch = channelOf(get(paintChannel));
+ const info = targetFor(mesh, slot);
+ if (info?.mode === 'vertex' || !hit?.uv) {
+ const color = mesh.geometry?.attributes?.color;
+ if (!color || !hit?.face) return false;
+ const i = hit.face.a;
+ const lin = [color.getX(i), color.getY(i), color.getZ(i)];
+ const srgb = lin.map((c) => (c <= 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 1 / 2.4) - 0.055));
+ uvBrushColor.set(rgbToHex(srgb));
+ return true;
+ }
+ const material = materialAt(mesh, slot);
+ const surface = ch.key === 'color' ? null : surfaces.get(mesh.uuid + '#' + slot + '#' + ch.key);
+ const image = surface && material?.[ch.map] === surface.texture ? surface.canvas : drawable(material?.[ch.map]?.image);
+ if (!image) return false;
+ const flip = material[ch.map]?.flipY !== false;
+ const w = image.width;
+ const h = image.height;
+ const x = Math.min(w - 1, Math.max(0, Math.floor(hit.uv.x * w)));
+ const y = Math.min(h - 1, Math.max(0, Math.floor((flip ? 1 - hit.uv.y : hit.uv.y) * h)));
+ const probe = document.createElement('canvas');
+ probe.width = probe.height = 1;
+ const ctx = probe.getContext('2d', { willReadFrequently: true });
+ if (!ctx) return false;
+ ctx.drawImage(image, x, y, 1, 1, 0, 0, 1, 1);
+ const px = ctx.getImageData(0, 0, 1, 1).data;
+ if (ch.gray) paintValue.set(Math.round((px[ch.key === 'roughness' ? 1 : 2] / 255) * 100) / 100);
+ else uvBrushColor.set(rgbToHex([px[0] / 255, px[1] / 255, px[2] / 255]));
+ return true;
+}
+
+// ---- the channel alone, on the model (LOCAL view) -------------------------------------------------------------------
+
+/** @type {any} */
+let channelProxy = null;
+
+/**
+ * Show one channel by itself on the model: a scene-root proxy sharing the mesh's geometry, drawn over it unlit.
+ * Outside objectsGroup, so no save, sync or undo ever sees it (the colliderHelpers pattern). Null hides it.
+ * @param {any} mesh @param {number} slot @param {string} ch
+ */
+export function showChannelView(mesh, slot, ch) {
+ hideChannelView();
+ const scene = get(globalScene);
+ /** @type {any} */
+ const s = scene;
+ if (!s || !mesh?.geometry) return false;
+ const key = channelOf(ch);
+ const material = materialAt(mesh, slot);
+ const texture = material?.[key.map] ?? null;
+ const view = new THREE.MeshBasicMaterial({ map: texture, color: texture ? 0xffffff : 0x808080, polygonOffset: true, polygonOffsetFactor: -1, polygonOffsetUnits: -1, toneMapped: false });
+ if (key.gray && texture) {
+ // three reads roughness from G and metalness from B: show that channel as grey, whatever the image holds
+ const sw = key.key === 'roughness' ? 'g' : 'b';
+ view.onBeforeCompile = (shader) => {
+ shader.fragmentShader = shader.fragmentShader.replace('#include ', '#ifdef USE_MAP\n\tdiffuseColor.rgb *= vec3(texture2D(map, vMapUv).' + sw + ');\n#endif');
+ };
+ view.customProgramCacheKey = () => 'paint-view-' + sw;
+ }
+ channelProxy = new THREE.Mesh(mesh.geometry, view);
+ channelProxy.name = 'paint-channel-view';
+ channelProxy.frustumCulled = false;
+ channelProxy.matrixAutoUpdate = false;
+ channelProxy.renderOrder = 5;
+ channelProxy.userData.target = mesh;
+ channelProxy.onBeforeRender = () => {
+ channelProxy.matrixWorld.copy(mesh.matrixWorld);
+ const now = materialAt(mesh, slot)?.[key.map] ?? null;
+ if (view.map !== now) {
+ view.map = now;
+ view.needsUpdate = true;
+ }
+ };
+ s.add(channelProxy);
+ pokeScene();
+ return true;
+}
+
+export function hideChannelView() {
+ if (!channelProxy) return;
+ channelProxy.parent?.remove(channelProxy);
+ channelProxy.material.dispose();
+ channelProxy = null;
+ pokeScene();
+}
+
+// ---- the viewport brush (desktop) -----------------------------------------------------------------------------------
+
+/** @type {any} */
+let ring = null;
+
+/** the brush ring on the surface @param {any} point world @param {any} normal world @param {number} radius world */
+export function showRing(point, normal, radius) {
+ const scene = /** @type {any} */ (get(globalScene));
+ if (!scene) return;
+ if (!ring) {
+ ring = new THREE.Mesh(new THREE.RingGeometry(0.92, 1, 48), new THREE.MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0.85, depthTest: false, side: THREE.DoubleSide }));
+ ring.name = 'paint-cursor';
+ ring.renderOrder = 997;
+ }
+ if (ring.parent !== scene) scene.add(ring);
+ ring.visible = true;
+ ring.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), normal);
+ ring.position.copy(point).addScaledVector(normal, radius * 0.02);
+ ring.scale.setScalar(Math.max(radius, 1e-4));
+ pokeScene();
+}
+
+export function hideRing() {
+ if (ring?.visible) {
+ ring.visible = false;
+ pokeScene();
+ }
+}
+
+/** where the ring is, for the suites */
+export function ringDebug() {
+ return ring ? { visible: !!ring.visible, radius: ring.scale.x, pos: ring.position.toArray() } : null;
+}
+
+/**
+ * The object-space facts of a raycast hit: the point, the normal (object space) and the slot's triangle index.
+ * @param {any} mesh @param {any} hit
+ */
+export function localHit(mesh, hit) {
+ const local = mesh.worldToLocal(hit.point.clone());
+ const n = hit.face?.normal ? hit.face.normal.clone() : new THREE.Vector3(0, 0, 1);
+ return { local: [local.x, local.y, local.z], normal: [n.x, n.y, n.z] };
+}
+
+/** The material slot a hit landed on: its face's slot on a multi-material mesh, else 0 (a model stroke paints the
+ * material under the brush, whichever slot the UV editor shows). @param {any} mesh @param {any} hit @param {number} fallback */
+export function slotOfHit(mesh, hit, fallback) {
+ if (!Array.isArray(mesh.material)) return 0;
+ const i = hit?.face?.materialIndex;
+ return Number.isInteger(i) ? i : fallback;
+}
+
+/** a hit's world normal @param {any} hit */
+export function worldNormal(hit) {
+ return hit.face?.normal ? hit.face.normal.clone().transformDirection(hit.object.matrixWorld) : new THREE.Vector3(0, 1, 0);
+}
+
+/** the ring's world radius for a stroke that would start here @param {any} mesh @param {number} slot @param {any} hit */
+export function ringRadius(mesh, slot, hit) {
+ const info = targetFor(mesh, slot);
+ const sp = info?.mode === 'vertex' ? 'vtx' : 'obj';
+ const r = strokeRadius(mesh, slot, sp, { local: localHit(mesh, hit).local });
+ const scale = new THREE.Vector3();
+ mesh.getWorldScale(scale);
+ return r * Math.max(Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z));
+}
+
+/**
+ * Paint on the model in the viewport while the UV editor's Paint tool is armed. Window CAPTURE listeners, so a
+ * stroke is claimed before the viewport's own select and orbit (the weight brush's recipe). Alt+click picks the
+ * value under the cursor; [ and ] size the brush. Returns the detach.
+ * @param {{target: () => any, slot: () => number}} opts
+ */
+export function attachViewportPainting(opts) {
+ const ray = new THREE.Raycaster();
+ let active = false;
+ /** @param {any} e */
+ const hitAt = (e) => {
+ const cam = /** @type {any} */ (get(globalCamera));
+ const canvas = /** @type {any} */ (get(globalRenderer))?.domElement;
+ const mesh = opts.target();
+ if (!cam || !canvas || !mesh?.geometry) return null;
+ const r = canvas.getBoundingClientRect();
+ ray.setFromCamera(new THREE.Vector2(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1), cam);
+ const hit = ray.intersectObject(mesh, false)[0];
+ return hit ? { mesh, hit, canvas } : null;
+ };
+ /** @param {any} e */
+ const pressure = (e) => {
+ if (get(uvPenPressure) === 'off' || e?.pointerType !== 'pen') return undefined;
+ const p = Number(e.pressure);
+ return Number.isFinite(p) ? Math.max(0, Math.min(1, p)) : undefined;
+ };
+ /** @param {PointerEvent} e */
+ const down = (e) => {
+ if (e.button !== 0) return;
+ const canvas = /** @type {any} */ (get(globalRenderer))?.domElement;
+ if (!canvas || e.target !== canvas) return;
+ const found = hitAt(e);
+ if (!found) return;
+ e.stopPropagation();
+ e.stopImmediatePropagation();
+ e.preventDefault();
+ if (e.altKey) {
+ pickAt(found.mesh, slotOfHit(found.mesh, found.hit, opts.slot()), found.hit);
+ return;
+ }
+ active = true;
+ const h = localHit(found.mesh, found.hit);
+ void beginStroke({ uuid: found.mesh.uuid, slot: slotOfHit(found.mesh, found.hit, opts.slot()), sp: 'obj', at: h.local, w: pressure(e), normal: h.normal }).then((ok) => {
+ if (!ok) active = false;
+ });
+ };
+ /** @param {PointerEvent} e */
+ const move = (e) => {
+ if (active) {
+ e.stopPropagation();
+ let samples = [];
+ try {
+ samples = /** @type {any} */ (e).getCoalescedEvents?.() ?? [];
+ } catch {
+ samples = [];
+ }
+ for (const sample of samples.length ? samples : [e]) {
+ const found = hitAt(sample);
+ if (found) strokeTo(localHit(found.mesh, found.hit).local, pressure(sample));
+ }
+ }
+ const found = hitAt(e);
+ if (found) showRing(found.hit.point, worldNormal(found.hit), ringRadius(found.mesh, slotOfHit(found.mesh, found.hit, opts.slot()), found.hit));
+ else hideRing();
+ };
+ /** @param {PointerEvent} e */
+ const up = (e) => {
+ if (!active) return;
+ e.stopPropagation();
+ active = false;
+ endStroke();
+ };
+ /** @param {KeyboardEvent} e */
+ const key = (e) => {
+ const el = /** @type {any} */ (document.activeElement);
+ if (el && (el.isContentEditable || el.tagName === 'TEXTAREA' || (el.tagName === 'INPUT' && !['range', 'checkbox', 'radio', 'button', 'color'].includes(el.type)))) return;
+ if (e.key === '[' || e.key === ']') {
+ uvBrushSize.update((n) => Math.max(1, Math.min(128, Math.round(e.key === ']' ? n * 1.25 + 1 : n / 1.25))));
+ e.preventDefault();
+ } else if (e.key === 'Escape' && stroke) {
+ cancelStroke();
+ active = false;
+ }
+ };
+ window.addEventListener('pointerdown', down, true);
+ window.addEventListener('pointermove', move, true);
+ window.addEventListener('pointerup', up, true);
+ window.addEventListener('keydown', key, true);
+ return () => {
+ window.removeEventListener('pointerdown', down, true);
+ window.removeEventListener('pointermove', move, true);
+ window.removeEventListener('pointerup', up, true);
+ window.removeEventListener('keydown', key, true);
+ if (active) endStroke();
+ active = false;
+ hideRing();
+ };
+}
+
+/**
+ * What the UV canvas shows behind the wire for a roughness / metalness / emission channel: the live paint canvas
+ * while it is installed, else the slot's image, else null (no map yet — the first stroke makes one).
+ * @param {any} mesh @param {number} slot @param {string} ch
+ */
+export function channelBackdrop(mesh, slot, ch) {
+ if (!mesh || ch === 'color') return null;
+ const key = channelOf(ch);
+ const material = materialAt(mesh, slot);
+ const surface = surfaces.get(mesh.uuid + '#' + slot + '#' + key.key);
+ if (surface && material?.[key.map] === surface.texture) return surface.canvas;
+ return drawable(material?.[key.map]?.image);
+}
+
+// ---- the suites' view -----------------------------------------------------------------------------------------------
+
+/** @type {any} */
+let lastStroke = null;
+
+/** A hash of the pixels a slot's channel READS, so a suite can say "both peers (or a reload, or a re-import) show the
+ * same thing": all four bytes for colour and emission, only green for roughness and only blue for metalness (a glTF
+ * round trip merges the two into one image), rows in three's flipY = true order whatever the texture says (the
+ * glTF loader turns flipY off and the exporter flips the image to match). @param {string} uuid @param {number} slot
+ * @param {string} ch */
+export function mapHash(uuid, slot = 0, ch = 'color') {
+ const object = objectOf(uuid);
+ const material = materialAt(object, slot);
+ const key = channelOf(ch);
+ const texture = material?.[key.map];
+ const image = drawable(texture?.image);
+ if (!image) return null;
+ const w = image.width;
+ const h = image.height;
+ const canvas = document.createElement('canvas');
+ canvas.width = w;
+ canvas.height = h;
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
+ if (!ctx) return null;
+ ctx.drawImage(image, 0, 0);
+ const px = ctx.getImageData(0, 0, w, h).data;
+ const flip = texture.flipY === false;
+ const at = key.key === 'roughness' ? 1 : key.key === 'metalness' ? 2 : -1;
+ const out = new Uint8Array(at < 0 ? px.length : w * h);
+ for (let y = 0; y < h; y++) {
+ const sy = flip ? h - 1 - y : y;
+ for (let x = 0; x < w; x++) {
+ const i = (sy * w + x) * 4;
+ if (at < 0) out.set(px.subarray(i, i + 4), (y * w + x) * 4);
+ else out[y * w + x] = px[i + at];
+ }
+ }
+ return { hash: hashBytes(out), w, h };
+}
+
+export function meshPaintDebug() {
+ return {
+ stroking: !!stroke,
+ remote: remote.size,
+ surfaces: surfaces.size,
+ last: lastStroke,
+ target: get(paintTargetInfo),
+ channel: get(paintChannel),
+ brush: currentBrush(),
+ ring: ringDebug(),
+ view: !!channelProxy
+ };
+}
diff --git a/src/lib/meshPaintCore.js b/src/lib/meshPaintCore.js
new file mode 100644
index 000000000..47d5ec04f
--- /dev/null
+++ b/src/lib/meshPaintCore.js
@@ -0,0 +1,552 @@
+// 102 M6 — PAINT ON MESHES, the PURE half (imports NOTHING, so it is unit-testable with no browser, no GL and
+// no scene, and every peer replaying a stroke runs the same arithmetic).
+//
+// The shipped painter (uvEditor.js UV3) paints the base-colour map in the UV editor's 2D canvas with a hard round
+// line. This lane grows it, without a second painter:
+// - CHANNELS: colour, roughness, metalness, emission — one map each (the 72 LK1 map slots for the last three)
+// - BRUSH KINDS: hardness, flow, opacity, eraser, mirror X, an image stamp
+// - MODEL STROKES: painting on the model itself. A dab is a SPHERE in the object's own space, drawn into the
+// map through the UV layout of every triangle it touches (each triangle's own 3D -> UV affine map, clipped to
+// that triangle and padded a little), so a stroke crosses a UV seam the way it crosses the surface
+// - VERTEX COLOURS when there are no usable UVs (none, or overlapping), with the same brush
+//
+// THE STROKE MODEL, shared by the canvas and the vertex paths: dabs build up a STROKE LAYER whose alpha
+// accumulates `L += a * (1 - L)` (source-over), a = falloff * flow; what shows is the base under the stroke
+// blended toward the brush value by L * opacity. So flow is "how much each dab adds" and opacity is "the most the
+// whole stroke can reach" — the usual painter's meaning of the two.
+
+/** @typedef {{hardness: number, opacity: number, flow: number, erase: boolean, mirror: boolean, stamp: string}} Brush */
+
+/** The channels a brush can paint. `map` is the material key; `gray` channels take a 0..1 value, the others a
+ * colour; `erase` is what the eraser paints: the value that leaves the material's own setting showing (a map
+ * MULTIPLIES its slider or colour, so white / 1 = "no map here" for colour, roughness and metalness, and black =
+ * "no glow" for emission). */
+export const CHANNELS = Object.freeze([
+ Object.freeze({ key: 'color', map: 'map', label: 'Colour', gray: false, srgb: true, param: '', erase: '#ffffff' }),
+ Object.freeze({ key: 'roughness', map: 'roughnessMap', label: 'Roughness', gray: true, srgb: false, param: 'roughness', erase: '#ffffff' }),
+ Object.freeze({ key: 'metalness', map: 'metalnessMap', label: 'Metalness', gray: true, srgb: false, param: 'metalness', erase: '#ffffff' }),
+ Object.freeze({ key: 'emissive', map: 'emissiveMap', label: 'Emission', gray: false, srgb: true, param: 'emissive', erase: '#000000' })
+]);
+
+/** @param {any} key */
+export function channelOf(key) {
+ return CHANNELS.find((c) => c.key === key) ?? CHANNELS[0];
+}
+
+/** @param {any} key */
+export const isChannelKey = (key) => CHANNELS.some((c) => c.key === key);
+
+export const BRUSH_DEFAULTS = Object.freeze({ hardness: 1, opacity: 1, flow: 1, erase: false, mirror: false, stamp: '' });
+
+/** the sizes a NEW map is made at (the first stroke on a slot with no image) */
+export const NEW_MAP_SIZES = Object.freeze([1024, 2048]);
+
+/** @param {any} v @param {number} lo @param {number} hi @param {number} fallback */
+function clampNum(v, lo, hi, fallback) {
+ const n = Number(v);
+ return Number.isFinite(n) ? Math.min(hi, Math.max(lo, n)) : fallback;
+}
+
+/** A content hash or library id: short, no markup. @param {any} v */
+function cleanStamp(v) {
+ return typeof v === 'string' && v.length <= 128 && /^[A-Za-z0-9_:.-]*$/.test(v) ? v : '';
+}
+
+/**
+ * Every brush that reaches a canvas or the wire goes through here, so a hostile or older value cannot ask for a
+ * negative flow or a 10 MB stamp id. @param {any} raw @returns {Brush}
+ */
+export function normalizeBrush(raw) {
+ const b = raw && typeof raw === 'object' ? raw : {};
+ return {
+ hardness: clampNum(b.hardness, 0, 1, 1),
+ opacity: clampNum(b.opacity, 0.01, 1, 1),
+ flow: clampNum(b.flow, 0.01, 1, 1),
+ erase: b.erase === true,
+ mirror: b.mirror === true,
+ stamp: cleanStamp(b.stamp)
+ };
+}
+
+/** Is this the shipped brush (hard, full, no eraser, no mirror, no stamp)? Strokes with it stay on the old wire.
+ * @param {any} raw */
+export function isDefaultBrush(raw) {
+ const b = normalizeBrush(raw);
+ return b.hardness === 1 && b.opacity === 1 && b.flow === 1 && !b.erase && !b.mirror && !b.stamp;
+}
+
+/** The brush on the wire: only the fields that differ from the default (rule 6: absent when it does not apply).
+ * @param {any} raw */
+export function brushWire(raw) {
+ const b = normalizeBrush(raw);
+ /** @type {Record} */
+ const out = {};
+ if (b.hardness !== 1) out.h = round3(b.hardness);
+ if (b.opacity !== 1) out.o = round3(b.opacity);
+ if (b.flow !== 1) out.f = round3(b.flow);
+ if (b.erase) out.e = 1;
+ if (b.mirror) out.m = 1;
+ if (b.stamp) out.s = b.stamp;
+ return out;
+}
+
+/** @param {any} w @returns {Brush} */
+export function brushFromWire(w) {
+ const x = w && typeof w === 'object' ? w : {};
+ return normalizeBrush({ hardness: x.h, opacity: x.o, flow: x.f, erase: x.e === 1, mirror: x.m === 1, stamp: x.s });
+}
+
+/** @param {number} n */
+export function round3(n) {
+ return Math.round(n * 1000) / 1000;
+}
+
+/** A 0..1 value as a grey `#rrggbb`. @param {number} v */
+export function grayHex(v) {
+ const c = Math.round(clampNum(v, 0, 1, 0) * 255);
+ const h = c.toString(16).padStart(2, '0');
+ return '#' + h + h + h;
+}
+
+/** A `#rrggbb` as three 0..1 numbers (sRGB, as written). Anything else is white. @param {any} hex */
+export function hexToRgb(hex) {
+ const m = typeof hex === 'string' ? /^#?([0-9a-f]{6})$/i.exec(hex.trim()) : null;
+ if (!m) return [1, 1, 1];
+ const n = parseInt(m[1], 16);
+ return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
+}
+
+/** @param {number[]} rgb 0..1 */
+export function rgbToHex(rgb) {
+ return '#' + rgb.map((c) => Math.round(clampNum(c, 0, 1, 0) * 255).toString(16).padStart(2, '0')).join('');
+}
+
+/** What a stroke paints: the eraser's value, else the brush colour (colour / emission) or the grey of the value.
+ * @param {string} channel @param {string} color @param {number} value @param {boolean} erase */
+export function paintStyle(channel, color, value, erase) {
+ const ch = channelOf(channel);
+ if (erase) return ch.erase;
+ return ch.gray ? grayHex(value) : /^#[0-9a-f]{6}$/i.test(color) ? color.toLowerCase() : '#ffffff';
+}
+
+// ---- falloff and dab spacing ---------------------------------------------------------------------------------
+
+/**
+ * How much a dab covers at `t` = distance / radius: 1 inside the hard core, a smoothstep down to 0 at the rim.
+ * Hardness 1 is the shipped hard edge. @param {number} t @param {number} hardness
+ */
+export function falloff(t, hardness) {
+ if (!(t >= 0) || t > 1) return 0;
+ const h = clampNum(hardness, 0, 1, 1);
+ if (t <= h) return 1;
+ if (h >= 1) return 1;
+ const s = (t - h) / (1 - h);
+ return 1 - s * s * (3 - 2 * s);
+}
+
+/** The falloff as radial-gradient stops ([offset 0..1, alpha 0..1]) — the canvas draws the same curve the
+ * vertex path evaluates. @param {number} hardness */
+export function falloffStops(hardness) {
+ const h = clampNum(hardness, 0, 1, 1);
+ if (h >= 1) return [[0, 1], [1, 1]];
+ /** @type {number[][]} */
+ const stops = [[0, 1], [h, 1]];
+ for (let i = 1; i <= 6; i++) {
+ const t = h + ((1 - h) * i) / 6;
+ stops.push([round3(t), round3(falloff(t, h))]);
+ }
+ return stops;
+}
+
+/** dabs per diameter: 0.2 is the usual painter's spacing (no visible beads, not wasteful) */
+export const DAB_SPACING = 0.2;
+
+/**
+ * The dabs along one segment, spaced `step` apart along its length, carrying the leftover distance into the next
+ * segment so a stroke made of many short moves spaces like one long one. Points are `[...coords, w]` with the
+ * pressure `w` last; it is interpolated. The FIRST point of a stroke is a dab of its own (call with
+ * `carry = step` to get it); after that a dab lands every `step`.
+ * @param {number[]} from @param {number[]} to @param {number} dim how many coordinates (2 or 3)
+ * @param {number} step @param {number} carry distance travelled since the last dab
+ * @returns {{dabs: number[][], carry: number}}
+ */
+export function dabsAlong(from, to, dim, step, carry) {
+ /** @type {number[][]} */
+ const dabs = [];
+ const s = step > 1e-9 ? step : 1e-9;
+ let len = 0;
+ for (let k = 0; k < dim; k++) len += (to[k] - from[k]) ** 2;
+ len = Math.sqrt(len);
+ const wa = Number.isFinite(from[dim]) ? from[dim] : 1;
+ const wb = Number.isFinite(to[dim]) ? to[dim] : 1;
+ let travelled = carry;
+ // the first dab sits `s - carry` along the segment
+ let at = s - carry;
+ if (at < 0) at = 0;
+ let guard = 0;
+ while (at <= len + 1e-9 && guard++ < 100000) {
+ const t = len > 0 ? at / len : 0;
+ const p = [];
+ for (let k = 0; k < dim; k++) p.push(from[k] + (to[k] - from[k]) * t);
+ p.push(wa + (wb - wa) * t);
+ dabs.push(p);
+ at += s;
+ }
+ travelled = len - (at - s);
+ if (!dabs.length) travelled = carry + len;
+ return { dabs, carry: travelled };
+}
+
+// ---- the triangle frame: a dab sphere seen through one triangle's UV layout ------------------------------------
+
+/** @param {number[]} a @param {number[]} b */
+const sub3 = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
+/** @param {number[]} a @param {number[]} b */
+const dot3 = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+/** @param {number[]} a @param {number[]} b */
+const cross3 = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
+/** @param {number[]} a */
+const len3 = (a) => Math.sqrt(dot3(a, a));
+
+/**
+ * One triangle's plane frame and its plane -> UV affine map.
+ * `q` are the corners in plane coordinates (corner 0 at the origin, edge 0-1 along +x); `M` maps a plane offset
+ * to a UV offset (2x2, row-major [m00, m01, m10, m11]) so uv = uv0 + M q. Null for a degenerate triangle in 3D
+ * or in UV space (nothing to paint through).
+ * @param {number[]} p0 @param {number[]} p1 @param {number[]} p2
+ * @param {number[]} uv0 @param {number[]} uv1 @param {number[]} uv2
+ */
+export function triFrame(p0, p1, p2, uv0, uv1, uv2) {
+ const a = sub3(p1, p0);
+ const b = sub3(p2, p0);
+ const la = len3(a);
+ const nRaw = cross3(a, b);
+ const area2 = len3(nRaw);
+ if (la < 1e-12 || area2 < 1e-12) return null;
+ const e1 = [a[0] / la, a[1] / la, a[2] / la];
+ const n = [nRaw[0] / area2, nRaw[1] / area2, nRaw[2] / area2];
+ const e2 = cross3(n, e1);
+ const q1 = [la, 0];
+ const q2 = [dot3(b, e1), dot3(b, e2)];
+ // Dq = [q1 q2] as columns; Duv = [uv1-uv0, uv2-uv0] as columns; M = Duv * Dq^-1
+ const det = q1[0] * q2[1] - q2[0] * q1[1];
+ if (Math.abs(det) < 1e-18) return null;
+ const du1 = uv1[0] - uv0[0];
+ const dv1 = uv1[1] - uv0[1];
+ const du2 = uv2[0] - uv0[0];
+ const dv2 = uv2[1] - uv0[1];
+ const uvArea2 = Math.abs(du1 * dv2 - du2 * dv1);
+ if (uvArea2 < 1e-14) return null;
+ // inverse of [[q1x, q2x], [q1y, q2y]]
+ const i00 = q2[1] / det;
+ const i01 = -q2[0] / det;
+ const i10 = -q1[1] / det;
+ const i11 = q1[0] / det;
+ const M = [du1 * i00 + du2 * i10, du1 * i01 + du2 * i11, dv1 * i00 + dv2 * i10, dv1 * i01 + dv2 * i11];
+ return { o: p0, e1, e2, n, q: [[0, 0], q1, q2], uv: [uv0, uv1, uv2], M, area: area2 / 2, uvArea: uvArea2 / 2 };
+}
+
+/**
+ * Where a dab sphere (centre `c`, radius `r`) cuts one triangle's plane: the circle's centre in plane
+ * coordinates and its radius, or null when the sphere misses the plane or the triangle's neighbourhood.
+ * @param {any} frame triFrame's result @param {number[]} c @param {number} r
+ * @returns {{qc: number[], r: number} | null}
+ */
+export function dabOnTri(frame, c, r) {
+ const d = sub3(c, frame.o);
+ const h = dot3(d, frame.n);
+ if (Math.abs(h) >= r) return null;
+ const rr = Math.sqrt(r * r - h * h);
+ const qc = [dot3(d, frame.e1), dot3(d, frame.e2)];
+ // quick reject: the circle must come within rr of the triangle's plane-space bounding box
+ const q = frame.q;
+ const minX = Math.min(q[0][0], q[1][0], q[2][0]);
+ const maxX = Math.max(q[0][0], q[1][0], q[2][0]);
+ const minY = Math.min(q[0][1], q[1][1], q[2][1]);
+ const maxY = Math.max(q[0][1], q[1][1], q[2][1]);
+ if (qc[0] < minX - rr || qc[0] > maxX + rr || qc[1] < minY - rr || qc[1] > maxY + rr) return null;
+ return { qc, r: rr };
+}
+
+/** The UV of a plane point. @param {any} frame @param {number[]} qp */
+export function planeToUv(frame, qp) {
+ const M = frame.M;
+ return [frame.uv[0][0] + M[0] * qp[0] + M[1] * qp[1], frame.uv[0][1] + M[2] * qp[0] + M[3] * qp[1]];
+}
+
+/**
+ * The canvas transform (setTransform's a, b, c, d, e, f) that takes plane coordinates of `frame` to canvas
+ * pixels of a W x H map. `flipY` is the texture's: true (three's default) puts v = 1 at the image top.
+ * @param {any} frame @param {number} W @param {number} H @param {boolean} flipY
+ */
+export function planeToCanvas(frame, W, H, flipY) {
+ const M = frame.M;
+ const [u0, v0] = frame.uv[0];
+ const sy = flipY ? -H : H;
+ return [W * M[0], sy * M[2], W * M[1], sy * M[3], W * u0, flipY ? H - H * v0 : H * v0];
+}
+
+/** A UV point in canvas pixels. @param {number[]} uv @param {number} W @param {number} H @param {boolean} flipY */
+export function uvToCanvas(uv, W, H, flipY) {
+ return [uv[0] * W, (flipY ? 1 - uv[1] : uv[1]) * H];
+}
+
+/**
+ * A triangle grown by about `pad` pixels (seam PADDING: bilinear and mip sampling at an island's edge read a
+ * pixel or two outside it, so paint has to reach a little past the edge or the seam shows a hairline). Grown
+ * about the incentre; the growth is capped so a sliver cannot balloon over its neighbours.
+ * @param {number[][]} pts three [x, y] @param {number} pad
+ */
+export function padTri(pts, pad) {
+ const [a, b, c] = pts;
+ const la = Math.hypot(b[0] - c[0], b[1] - c[1]);
+ const lb = Math.hypot(a[0] - c[0], a[1] - c[1]);
+ const lc = Math.hypot(a[0] - b[0], a[1] - b[1]);
+ const per = la + lb + lc;
+ if (per < 1e-9 || pad <= 0) return pts.map((p) => [p[0], p[1]]);
+ const ix = (la * a[0] + lb * b[0] + lc * c[0]) / per;
+ const iy = (la * a[1] + lb * b[1] + lc * c[1]) / per;
+ const area = Math.abs((b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])) / 2;
+ const inr = (2 * area) / per;
+ const k = inr > 1e-9 ? Math.min((inr + pad) / inr, 4) : 1;
+ return pts.map((p) => [ix + (p[0] - ix) * k, iy + (p[1] - iy) * k]);
+}
+
+/**
+ * Texture pixels per unit of the object's own space on one triangle — what turns the brush size (texture px,
+ * the UV editor's unit) into a model-space radius, so a stroke on the model is as wide as the same stroke on the
+ * map. @param {any} frame @param {number} W @param {number} H
+ */
+export function texelDensity(frame, W, H) {
+ if (!frame || frame.area <= 0) return 0;
+ return Math.sqrt((frame.uvArea * W * H) / frame.area);
+}
+
+// ---- finding the triangles a dab touches: a uniform grid over the object's own space ---------------------------
+
+/**
+ * Bucket triangles by the grid cells their bounding boxes cover. `positions` is a flat triangle soup
+ * (9 floats per triangle, object space). @param {ArrayLike} positions @param {number} cell
+ */
+export function buildTriGrid(positions, cell) {
+ const size = cell > 1e-9 ? cell : 1;
+ /** @type {Map} */
+ const cells = new Map();
+ const n = Math.floor(positions.length / 9);
+ for (let t = 0; t < n; t++) {
+ const o = t * 9;
+ let x0 = Infinity, y0 = Infinity, z0 = Infinity, x1 = -Infinity, y1 = -Infinity, z1 = -Infinity;
+ for (let k = 0; k < 3; k++) {
+ const x = positions[o + k * 3], y = positions[o + k * 3 + 1], z = positions[o + k * 3 + 2];
+ if (x < x0) x0 = x;
+ if (x > x1) x1 = x;
+ if (y < y0) y0 = y;
+ if (y > y1) y1 = y;
+ if (z < z0) z0 = z;
+ if (z > z1) z1 = z;
+ }
+ if (!Number.isFinite(x0 + y0 + z0 + x1 + y1 + z1)) continue;
+ const ax = Math.floor(x0 / size), bx = Math.floor(x1 / size);
+ const ay = Math.floor(y0 / size), by = Math.floor(y1 / size);
+ const az = Math.floor(z0 / size), bz = Math.floor(z1 / size);
+ // a huge triangle in a fine grid would fill thousands of cells; such a mesh gets a coarser grid instead
+ if ((bx - ax + 1) * (by - ay + 1) * (bz - az + 1) > 4096) return buildTriGrid(positions, size * 4);
+ for (let x = ax; x <= bx; x++)
+ for (let y = ay; y <= by; y++)
+ for (let z = az; z <= bz; z++) {
+ const key = x + ',' + y + ',' + z;
+ const list = cells.get(key);
+ if (list) list.push(t);
+ else cells.set(key, [t]);
+ }
+ }
+ return { cell: size, cells };
+}
+
+/** The triangles whose cells a sphere overlaps, ascending (a deterministic order: two peers draw the same dab in
+ * the same triangle order, so overlapping pads blend identically). @param {any} grid @param {number[]} c @param {number} r */
+export function trisNear(grid, c, r) {
+ const s = grid.cell;
+ /** @type {Set} */
+ const out = new Set();
+ const ax = Math.floor((c[0] - r) / s), bx = Math.floor((c[0] + r) / s);
+ const ay = Math.floor((c[1] - r) / s), by = Math.floor((c[1] + r) / s);
+ const az = Math.floor((c[2] - r) / s), bz = Math.floor((c[2] + r) / s);
+ if ((bx - ax + 1) * (by - ay + 1) * (bz - az + 1) > 32768) {
+ for (const list of grid.cells.values()) for (const t of list) out.add(t);
+ } else
+ for (let x = ax; x <= bx; x++)
+ for (let y = ay; y <= by; y++)
+ for (let z = az; z <= bz; z++) {
+ const list = grid.cells.get(x + ',' + y + ',' + z);
+ if (list) for (const t of list) out.add(t);
+ }
+ return [...out].sort((a, b) => a - b);
+}
+
+// ---- are the UVs usable? -----------------------------------------------------------------------------------------
+
+/**
+ * How much of the UV layout is painted twice: rasterise every UV triangle into a `res` x `res` grid and count
+ * cells covered more than once, as a share of the covered cells. 0 for a clean unwrap; a mirrored model whose
+ * halves share one island reads ~0.5; a primitive whose six sides share one square reads ~0.8. UVs outside 0..1
+ * (tiling) are clamped to the square, so a tiled mesh reads as overlapping, which it is for a painter.
+ * @param {ArrayLike} uvs flat, 6 per triangle @param {number} [res]
+ * @returns {{covered: number, overlap: number, ratio: number, empty: boolean}}
+ */
+export function uvOverlap(uvs, res = 128) {
+ const R = Math.max(8, Math.min(512, Math.floor(res)));
+ const count = new Uint8Array(R * R);
+ const n = Math.floor(uvs.length / 6);
+ let anyArea = false;
+ for (let t = 0; t < n; t++) {
+ const o = t * 6;
+ const ax = uvs[o] * R, ay = uvs[o + 1] * R;
+ const bx = uvs[o + 2] * R, by = uvs[o + 3] * R;
+ const cx = uvs[o + 4] * R, cy = uvs[o + 5] * R;
+ const area = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay);
+ if (!Number.isFinite(area) || Math.abs(area) < 1e-9) continue;
+ anyArea = true;
+ const x0 = Math.max(0, Math.floor(Math.min(ax, bx, cx)));
+ const x1 = Math.min(R - 1, Math.ceil(Math.max(ax, bx, cx)));
+ const y0 = Math.max(0, Math.floor(Math.min(ay, by, cy)));
+ const y1 = Math.min(R - 1, Math.ceil(Math.max(ay, by, cy)));
+ for (let y = y0; y <= y1; y++)
+ for (let x = x0; x <= x1; x++) {
+ const px = x + 0.5, py = y + 0.5;
+ const w0 = (bx - px) * (cy - py) - (cx - px) * (by - py);
+ const w1 = (cx - px) * (ay - py) - (ax - px) * (cy - py);
+ const w2 = (ax - px) * (by - py) - (bx - px) * (ay - py);
+ const inside = area > 0 ? w0 >= 0 && w1 >= 0 && w2 >= 0 : w0 <= 0 && w1 <= 0 && w2 <= 0;
+ if (inside && count[y * R + x] < 255) count[y * R + x]++;
+ }
+ }
+ let covered = 0;
+ let overlap = 0;
+ for (let i = 0; i < count.length; i++) {
+ if (count[i] > 0) covered++;
+ if (count[i] > 1) overlap++;
+ }
+ return { covered, overlap, ratio: covered ? overlap / covered : 0, empty: !anyArea || !covered };
+}
+
+/** above this share of twice-painted texels a mesh's UVs are "overlapping" for a painter */
+export const OVERLAP_LIMIT = 0.05;
+
+/**
+ * Where a model stroke should go: 'map' (paint the texture), or 'vertex' with the reason in words.
+ * @param {{hasUvs: boolean, overlap?: {ratio: number, empty: boolean} | null}} facts
+ * @returns {{mode: 'map' | 'vertex', reason: string}}
+ */
+export function paintTarget(facts) {
+ if (!facts.hasUvs) return { mode: 'vertex', reason: 'This mesh has no UV map, so the brush paints its vertex colours.' };
+ const o = facts.overlap;
+ if (o?.empty) return { mode: 'vertex', reason: 'This mesh’s UV map is empty, so the brush paints its vertex colours.' };
+ if (o && o.ratio > OVERLAP_LIMIT)
+ return {
+ mode: 'vertex',
+ reason: 'Parts of this mesh share the same place on its UV map, so paint would show up twice. The brush paints vertex colours instead (or unwrap it in the UV editor first).'
+ };
+ return { mode: 'map', reason: '' };
+}
+
+// ---- vertex colours -----------------------------------------------------------------------------------------------
+
+/**
+ * One dab on per-vertex data: every vertex within `r` of `c` gets its stroke-layer alpha raised by
+ * falloff * flow (source-over). `acc` is the stroke layer (one float per vertex, 0 at the stroke's start).
+ * Returns the vertex indices it touched, ascending.
+ *
+ * A LOW-POLY mesh is the case this fallback exists for (a default box has four corners per face), and there a dab
+ * between the corners reaches none of them: painted along the middle of a box face, nothing changed. So a dab that
+ * reaches no vertex paints the NEAREST ones at full strength instead, those within 0.1 % of the nearest distance
+ * (a face centre reaches all four corners). With `normals` and the stroke normal `n`, only vertices facing the dab
+ * count, so the same corner of the neighbouring faces (a box keeps its own copy per face) stays clean.
+ * @param {ArrayLike} positions 3 per vertex
+ * @param {number[]} c @param {number} r @param {number} hardness @param {number} flow @param {Float32Array} acc
+ * @param {{normals?: ArrayLike | null, n?: number[] | null}} [facing]
+ */
+export function vertexDab(positions, c, r, hardness, flow, acc, facing) {
+ /** @type {number[]} */
+ const touched = [];
+ if (!(r > 0)) return touched;
+ const n = Math.floor(positions.length / 3);
+ const r2 = r * r;
+ for (let i = 0; i < n; i++) {
+ const dx = positions[i * 3] - c[0];
+ const dy = positions[i * 3 + 1] - c[1];
+ const dz = positions[i * 3 + 2] - c[2];
+ const d2 = dx * dx + dy * dy + dz * dz;
+ if (d2 > r2) continue;
+ const a = falloff(Math.sqrt(d2) / r, hardness) * flow;
+ if (a <= 0) continue;
+ acc[i] = acc[i] + a * (1 - acc[i]);
+ touched.push(i);
+ }
+ if (touched.length || !(flow > 0)) return touched;
+ const N = facing?.normals && facing.n && facing.normals.length >= n * 3 ? facing.normals : null;
+ const fn = N ? /** @type {number[]} */ (facing?.n) : null;
+ /** @param {number} i */
+ const faces = (i) => !N || !fn || N[i * 3] * fn[0] + N[i * 3 + 1] * fn[1] + N[i * 3 + 2] * fn[2] > 0.1;
+ let best = Infinity;
+ for (let i = 0; i < n; i++) {
+ if (!faces(i)) continue;
+ const dx = positions[i * 3] - c[0];
+ const dy = positions[i * 3 + 1] - c[1];
+ const dz = positions[i * 3 + 2] - c[2];
+ const d2 = dx * dx + dy * dy + dz * dz;
+ if (d2 < best) best = d2;
+ }
+ if (!Number.isFinite(best)) return touched;
+ const reach = best * 1.002 + 1e-12;
+ for (let i = 0; i < n; i++) {
+ if (!faces(i)) continue;
+ const dx = positions[i * 3] - c[0];
+ const dy = positions[i * 3 + 1] - c[1];
+ const dz = positions[i * 3 + 2] - c[2];
+ if (dx * dx + dy * dy + dz * dz > reach) continue;
+ acc[i] = acc[i] + flow * (1 - acc[i]);
+ touched.push(i);
+ }
+ return touched;
+}
+
+/**
+ * The colours a stroke shows: base blended toward `target` by layer alpha * opacity, for the given vertices.
+ * All three colour arrays are 3 floats per vertex (linear). @param {Float32Array} base @param {number[]} target
+ * @param {Float32Array} acc @param {number} opacity @param {Float32Array} out @param {Iterable} indices
+ */
+export function blendVertexColors(base, target, acc, opacity, out, indices) {
+ for (const i of indices) {
+ const a = Math.min(1, Math.max(0, acc[i] * opacity));
+ for (let k = 0; k < 3; k++) out[i * 3 + k] = base[i * 3 + k] + (target[k] - base[i * 3 + k]) * a;
+ }
+}
+
+/** Mirror X in the object's own space. @param {number[]} p */
+export function mirrorX(p) {
+ return [-p[0], p[1], p[2], ...p.slice(3)];
+}
+
+/** Is this point on (or within eps of) the mirror plane? A dab there is painted once, not twice.
+ * @param {number[]} p @param {number} r */
+export function onMirrorPlane(p, r) {
+ return Math.abs(p[0]) < Math.max(r * 0.05, 1e-6);
+}
+
+/** sRGB 0..1 -> linear 0..1 (three's vertex colours are linear) @param {number} c */
+export function srgbToLinear(c) {
+ return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
+}
+
+/** A tiny stable hash of a byte array (FNV-1a 32), for the suites' "same pixels on both peers".
+ * @param {ArrayLike} bytes */
+export function hashBytes(bytes) {
+ let h = 0x811c9dc5;
+ for (let i = 0; i < bytes.length; i++) {
+ h ^= bytes[i] & 255;
+ h = Math.imul(h, 0x01000193) >>> 0;
+ }
+ return h.toString(16).padStart(8, '0');
+}
+
diff --git a/src/lib/meshPaintPrefs.js b/src/lib/meshPaintPrefs.js
new file mode 100644
index 000000000..017d38ae2
--- /dev/null
+++ b/src/lib/meshPaintPrefs.js
@@ -0,0 +1,54 @@
+// 102 M6 — PAINT ON MESHES: the brush settings. A LEAF (svelte/store + safeStorage), so the UV editor's panel and
+// the VR brush can read and write them without loading the painter (meshPaint.js, a lazy chunk). Every value is a
+// LOCAL pref, like the shipped colour and size: a brush is a fact about how YOU paint; what a stroke paints is
+// what replicates.
+import { writable } from 'svelte/store';
+import { safeStorage } from './safeStorage';
+
+/**
+ * A persisted store. The stored text is parsed by `read`, which returns undefined for "use the default".
+ * @template T @param {string} key @param {T} fallback @param {(raw: string) => T | undefined} read
+ * @returns {import('svelte/store').Writable}
+ */
+function pref(key, fallback, read) {
+ const raw = safeStorage.getItem(key);
+ const parsed = raw == null ? undefined : read(raw);
+ const store = writable(parsed === undefined ? fallback : parsed);
+ store.subscribe((value) => safeStorage.setItem(key, String(value)));
+ return store;
+}
+
+/** @param {number} lo @param {number} hi */
+const num = (lo, hi) => (/** @type {string} */ raw) => {
+ const n = Number(raw);
+ return Number.isFinite(n) && n >= lo && n <= hi ? n : undefined;
+};
+const bool = (/** @type {string} */ raw) => (raw === 'true' ? true : raw === 'false' ? false : undefined);
+
+/** which map the brush paints: 'color' | 'roughness' | 'metalness' | 'emissive' */
+export const paintChannel = pref('paint:channel', 'color', (raw) =>
+ ['color', 'roughness', 'metalness', 'emissive'].includes(raw) ? raw : undefined
+);
+/** the value a roughness / metalness stroke paints (0..1) */
+export const paintValue = pref('paint:value', 0.5, num(0, 1));
+/** 1 = the shipped hard edge, 0 = soft all the way in */
+export const paintHardness = pref('paint:hardness', 1, num(0, 1));
+/** the most one stroke can reach */
+export const paintOpacity = pref('paint:opacity', 1, num(0.01, 1));
+/** how much each dab adds */
+export const paintFlow = pref('paint:flow', 1, num(0.01, 1));
+/** the eraser: paints the value that lets the material's own setting show (meshPaintCore.CHANNELS `erase`) */
+export const paintErase = pref('paint:erase', false, bool);
+/** mirror X on the model (the object's own X) */
+export const paintMirror = pref('paint:mirror', false, bool);
+/** the stamp brush: an Explorer image's content hash, '' = a round brush */
+export const paintStamp = pref('paint:stamp', '', (raw) => (/^[A-Za-z0-9_:.-]{0,128}$/.test(raw) ? raw : undefined));
+/** the size a NEW map is made at (the first stroke on a slot with no image) */
+export const paintMapSize = pref('paint:mapSize', 1024, (raw) => (raw === '1024' ? 1024 : raw === '2048' ? 2048 : undefined));
+/** LOCAL view: show the painted channel alone on the model (never saved, never sent) */
+export const paintShowChannel = writable(false);
+/** what the brush does on the selected object right now, for the panel: map, or vertex colours and why */
+export const paintTargetInfo = writable(/** @type {{mode: 'map' | 'vertex', reason: string} | null} */ (null));
+
+/** the brush as one plain object (meshPaintCore.normalizeBrush takes it) */
+export const BRUSH_STORES = { hardness: paintHardness, opacity: paintOpacity, flow: paintFlow, erase: paintErase, mirror: paintMirror, stamp: paintStamp };
diff --git a/src/lib/meshPaintWire.js b/src/lib/meshPaintWire.js
new file mode 100644
index 000000000..ebc5d46fa
--- /dev/null
+++ b/src/lib/meshPaintWire.js
@@ -0,0 +1,44 @@
+// 102 M6 — PAINT ON MESHES: the live stroke's WIRE SHAPE. A zero-import leaf on its own so the dispatcher's
+// validator (wireValidate, in the boot chunk) can reach it without pulling the painter, which loads on first use.
+
+/** the channel keys a stroke may name (meshPaintCore.CHANNELS, asserted equal by its unit test) */
+export const CHANNEL_KEYS = Object.freeze(['color', 'roughness', 'metalness', 'emissive']);
+
+// ---- the wire ---------------------------------------------------------------------------------------------------
+
+/** the most points one live `meshpaint` message may carry (a 66 ms throttle sends a handful) */
+export const MAX_SEG_POINTS = 512;
+export const PAINT_SPACES = Object.freeze(['uv', 'obj', 'vtx']);
+
+/**
+ * The shape of a live `meshpaint` message (wireValidate's table). The live stroke is a PREVIEW: the committed
+ * image (`map` / `mapSlot`) or geometry (`meshgeo`) that follows is the truth, so this only has to keep a bad
+ * message from throwing or asking for absurd work. @param {any} d
+ */
+export function validMeshPaint(d) {
+ if (!d || typeof d.id !== 'string' || d.id.length > 64) return false;
+ if (typeof d.uuid !== 'string' || !d.uuid || d.uuid.length > 64) return false;
+ if (d.slot !== undefined && !(Number.isInteger(d.slot) && d.slot >= 0 && d.slot < 64)) return false;
+ if (d.ch !== undefined && !CHANNEL_KEYS.includes(d.ch)) return false;
+ if (!PAINT_SPACES.includes(d.sp)) return false;
+ if (typeof d.c !== 'string' || !/^#[0-9a-f]{6}$/i.test(d.c)) return false;
+ if (!(typeof d.r === 'number' && Number.isFinite(d.r) && d.r > 0 && d.r <= 1e6)) return false;
+ if (d.b !== undefined && (!d.b || typeof d.b !== 'object' || Array.isArray(d.b))) return false;
+ if (d.n !== undefined && !(Array.isArray(d.n) && d.n.length === 3 && d.n.every(Number.isFinite))) return false;
+ if (!Array.isArray(d.seg) || d.seg.length < 1 || d.seg.length > MAX_SEG_POINTS) return false;
+ const dim = d.sp === 'uv' ? 2 : 3;
+ for (const p of d.seg) {
+ if (!Array.isArray(p) || (p.length !== dim && p.length !== dim + 1)) return false;
+ for (const x of p) if (typeof x !== 'number' || !Number.isFinite(x)) return false;
+ }
+ return true;
+}
+
+/** Points travel rounded, and the SENDER paints the rounded point too, so both sides run the same numbers.
+ * @param {number[]} p @param {number} dim */
+export function quantizePoint(p, dim) {
+ const out = [];
+ for (let k = 0; k < dim; k++) out.push(Math.round(p[k] * 1e5) / 1e5);
+ if (Number.isFinite(p[dim]) && p[dim] < 1) out.push(Math.round(Math.max(0, p[dim]) * 1000) / 1000);
+ return out;
+}
diff --git a/src/lib/peerHandler.svelte.js b/src/lib/peerHandler.svelte.js
index 04f04e030..09b650e0d 100644
--- a/src/lib/peerHandler.svelte.js
+++ b/src/lib/peerHandler.svelte.js
@@ -2006,6 +2006,10 @@ export class PeerConnection {
applyUvPaint(data);
} else if(data.type == 'uvpaintend') {
applyUvPaintEnd(data);
+ } else if(data.type == 'meshpaint' || data.type == 'meshpaintend') {
+ // 102 M6: a live mesh-paint stroke (a lazy chunk; import() keeps the messages in order once loaded)
+ const kind = data.type;
+ import('$lib/meshPaint').then((m) => (kind == 'meshpaint' ? m.applyMeshPaint(data) : m.applyMeshPaintEnd(data))).catch(() => {});
} else if(data.type == 'splineedit') {
// 57.3: only the RECORD travels — the receiver rebuilds the tube
applySplineEdit(data.uuid, data.spline);
diff --git a/src/lib/peerScenes.js b/src/lib/peerScenes.js
index e913b0b3d..7c802618d 100644
--- a/src/lib/peerScenes.js
+++ b/src/lib/peerScenes.js
@@ -617,7 +617,7 @@ export const ROOM_SCOPED = new Set([
// object lifecycle & geometry
'create', 'light', 'group', 'object', 'objectfile', 'duplicate', 'delete', 'name',
'move', 'throw', 'hit', 'behavior', 'simulate', 'simvote', 'simhandoff', 'color', 'objectParameters', 'geometry', 'lighttarget',
- 'verts', 'meshgeo', 'uvpaint', 'uvpaintend', 'splineedit', 'drawlive', 'drawend',
+ 'verts', 'meshgeo', 'uvpaint', 'uvpaintend', 'meshpaint', 'meshpaintend', 'splineedit', 'drawlive', 'drawend',
'clearscene', 'loading',
// flow
'nodes', 'nodesync', 'graphcreate', 'graphdelete', 'nodecreate', 'nodemove',
diff --git a/src/lib/uvEditor.js b/src/lib/uvEditor.js
index 1548d3f0a..cabe5d2b9 100644
--- a/src/lib/uvEditor.js
+++ b/src/lib/uvEditor.js
@@ -1189,6 +1189,23 @@ export async function beginPaintStroke(uuid, slot = 0) {
return true;
}
+/**
+ * 102 M6: the base-colour paint surface for meshPaint.js — the SAME canvas this module paints, so a brush stroke
+ * from either painter, the UV editor's live backdrop and the next stroke all see one image. Async for the reason
+ * paintSurface is. @param {string} uuid @param {number} [slot] @returns {Promise}
+ */
+export function openColorSurface(uuid, slot = 0) {
+ return paintSurface(uuid, slot);
+}
+
+/** 102 M6: forget a colour surface (meshPaint cancelled a stroke on it) @param {string} uuid @param {number} [slot] */
+export function dropColorSurface(uuid, slot = 0) {
+ paintCanvases.delete(paintKey(uuid, slot));
+}
+
+/** 102 M6: the shared encoder and pressure curve, so both painters commit and taper alike */
+export { canvasToDataUrl as encodePaintCanvas, pressureFactor as paintPressureFactor };
+
/** is a stroke open? */
export function painting() {
return !!paintStroke;
diff --git a/src/lib/vr/meshPaint.js b/src/lib/vr/meshPaint.js
new file mode 100644
index 000000000..7f11dc427
--- /dev/null
+++ b/src/lib/vr/meshPaint.js
@@ -0,0 +1,280 @@
+// VR controls — 102 M6: PAINT ON MESHES IN THE HEADSET. The desktop brush (meshPaint.js: colour, roughness,
+// metalness, emission; hardness / flow / opacity / eraser / mirror X; vertex colours on a mesh without usable UVs)
+// driven by a controller, the VR sculpt brush's recipe (vr/sculpt.js, 37 R9 / 52 V3):
+// - the POINTER hand aims: its ray puts the brush ring on the object; the trigger held = a stroke
+// - its STICK sizes the brush (left / right) and sets the flow (up / down), a tick at every step; that hand's
+// move / turn stand down while painting (registerStickOwner), the other stick still moves you
+// - a label on the pointer hand says the channel, the size and the flow
+// - the radial opens on the Paint ring while a session is up: Colour · Roughness · Metalness · Glow · Eraser ·
+// Mirror X · Done (Back reaches the usual menu); Selected ▸ Paint starts one
+// The settings are the desktop panel's own stores, so the panel and the headset agree, and a stroke is the
+// desktop's: one commit, one undo entry, the same live wire. Edit mode only. A tracked hand asks for a controller
+// (52 rules: precise tools are controller tools).
+import * as THREE from 'three';
+import { get } from 'svelte/store';
+import { objectsGroup, editorMode, vrMenuHand, vrMenuOpen } from '../../stores/sceneStore';
+import { renderer } from './core.js';
+import { hapticPulse } from './haptics.js';
+import { controllerIndexFor, axesForSlot } from './input.js';
+import { controllerRay } from './pointer.js';
+import { vrHovered } from './panels.js';
+import { registerVRFrameHook, registerVRTriggerHooks, registerStickOwner } from './hooks.js';
+import { controllerRequired } from './handInput.js';
+import { vrPaintActive } from './worldStores.js';
+import { uvBrushSize, meshWithUvs } from '../uvEditor';
+import { paintChannel, paintFlow, paintErase, paintMirror } from '../meshPaintPrefs';
+import { beginStroke, strokeTo, endStroke, cancelStroke, localHit, showRing, hideRing, worldNormal, ringRadius, slotOfHit } from '../meshPaint';
+import { channelOf } from '../meshPaintCore.js';
+import { registerVRMenuEntry } from '../vrRadialMenu';
+import { LUCIDE_NODES } from './iconData.js';
+
+export const SIZE_MIN = 1;
+export const SIZE_MAX = 128;
+export const FLOW_MIN = 0.05;
+export const FLOW_MAX = 1;
+const DEAD = 0.25;
+
+let hooked = false;
+/** @type {string | null} the painted object */
+let paintUuid = null;
+/** @type {{index: number} | null} the trigger stroke in flight */
+let stroke = null;
+let lastFrame = 0;
+let swallowAt = 0;
+const stats = { strokes: 0, moves: 0, ticks: 0, refusals: 0 };
+
+function pointerHand() {
+ return get(vrMenuHand) === 'right' ? 'left' : 'right';
+}
+function pointerIndex() {
+ return controllerIndexFor(pointerHand());
+}
+/** the painted mesh (a group resolves to its textured child, the UV editor's rule) @returns {any} */
+function target() {
+ const object = paintUuid ? get(objectsGroup)?.getObjectByProperty('uuid', paintUuid) : null;
+ return object ? meshWithUvs(object) : null;
+}
+
+/** the Paint ring (the radial opens on it while a session is up; Back = the usual menu). Registered here, on the
+ * first session, so none of it is in the boot bundle. */
+function registerPaintRing() {
+ // the ring's own icons (Lucide, the iconData format), added here rather than in the boot icon table
+ Object.assign(LUCIDE_NODES, {
+ 'eraser': [["path",{"d":"M21 21H8a2 2 0 0 1-1.42-.587l-3.994-3.999a2 2 0 0 1 0-2.828l10-10a2 2 0 0 1 2.829 0l5.999 6a2 2 0 0 1 0 2.828L12.834 21"}],["path",{"d":"m5.082 11.09 8.828 8.828"}]],
+ 'circle-dashed': [["path",{"d":"M10.1 2.182a10 10 0 0 1 3.8 0"}],["path",{"d":"M13.9 21.818a10 10 0 0 1-3.8 0"}],["path",{"d":"M17.609 3.721a10 10 0 0 1 2.69 2.7"}],["path",{"d":"M2.182 13.9a10 10 0 0 1 0-3.8"}],["path",{"d":"M20.279 17.609a10 10 0 0 1-2.7 2.69"}],["path",{"d":"M21.818 10.1a10 10 0 0 1 0 3.8"}],["path",{"d":"M3.721 6.391a10 10 0 0 1 2.7-2.69"}],["path",{"d":"M6.391 20.279a10 10 0 0 1-2.69-2.7"}]],
+ 'flip-horizontal': [["path",{"d":"M8 3H5a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h3"}],["path",{"d":"M16 3h3a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-3"}],["path",{"d":"M12 20v2"}],["path",{"d":"M12 14v2"}],["path",{"d":"M12 8v2"}],["path",{"d":"M12 2v2"}]]
+ });
+ [
+ ['color', 'Colour', 'palette'],
+ ['roughness', 'Roughness', 'circle-dashed'],
+ ['metalness', 'Metalness', 'circle-dot'],
+ ['emissive', 'Glow', 'sun']
+ ].forEach(([ch, label, icon], order) =>
+ registerVRMenuEntry({
+ id: 'paint:' + ch,
+ group: 'paint',
+ label,
+ icon,
+ order,
+ closes: true,
+ active: () => get(paintChannel) === ch,
+ action: () => paintChannel.set(/** @type {any} */ (ch))
+ })
+ );
+ registerVRMenuEntry({ id: 'paint:erase', group: 'paint', label: 'Eraser', icon: 'eraser', order: 4, closes: true, active: () => get(paintErase), action: () => paintErase.update((v) => !v) });
+ registerVRMenuEntry({ id: 'paint:mirror', group: 'paint', label: 'Mirror X', icon: 'flip-horizontal', order: 5, closes: true, active: () => get(paintMirror), action: () => paintMirror.update((v) => !v) });
+ registerVRMenuEntry({ id: 'paint:done', group: 'paint', label: 'Done', icon: 'check', order: 6, closes: true, action: () => stopVRPaint() });
+}
+
+function ensureHooks() {
+ if (hooked) return;
+ hooked = true;
+ registerPaintRing();
+ registerStickOwner(() => (get(vrPaintActive) && !get(vrMenuOpen) ? pointerHand() : null));
+ registerVRTriggerHooks({
+ start: (/** @type {number} */ i) => paintTriggerStart(i),
+ end: (/** @type {number} */ i) => paintTriggerEnd(i),
+ swallow: () => {
+ const pending = swallowAt && Date.now() - swallowAt < 5000;
+ swallowAt = 0;
+ return !!pending;
+ }
+ });
+ registerVRFrameHook(() => tickVRPaint());
+}
+
+/** Start painting `uuid` in the headset (Selected ▸ Paint). @param {string} uuid */
+export function startVRPaint(uuid) {
+ if (!uuid) return false;
+ ensureHooks();
+ paintUuid = uuid;
+ if (!target()?.geometry) {
+ paintUuid = null;
+ return false;
+ }
+ vrPaintActive.set(true);
+ vrMenuOpen.set(false);
+ lastFrame = performance.now();
+ return true;
+}
+
+/** Done: commit a stroke in flight and leave the session */
+export function stopVRPaint() {
+ if (stroke) paintTriggerEnd(stroke.index);
+ stroke = null;
+ paintUuid = null;
+ vrPaintActive.set(false);
+ hideRing();
+ hideLabel();
+}
+
+/** a Paint-ring sector: pick the channel @param {string} ch */
+export function setVRPaintChannel(ch) {
+ if (['color', 'roughness', 'metalness', 'emissive'].includes(ch)) paintChannel.set(/** @type {any} */ (ch));
+}
+
+/** @param {number} index */
+function hitOf(index) {
+ const mesh = target();
+ if (!mesh || index < 0) return null;
+ return controllerRay(index).intersectObject(mesh, false)[0] ?? null;
+}
+
+/** @param {number} index */
+export function paintTriggerStart(index) {
+ if (!get(vrPaintActive) || stroke) return false;
+ if (get(vrMenuOpen) || get(vrHovered)) return false;
+ const hit = hitOf(index);
+ const mesh = target();
+ if (!hit || !mesh) return false; // off the object: an ordinary press (a panel, a ping)
+ swallowAt = Date.now();
+ if (controllerRequired('paint', index)) {
+ stats.refusals++;
+ return true;
+ }
+ const h = localHit(mesh, hit);
+ stroke = { index };
+ stats.strokes++;
+ hapticPulse(0.3, 16, pointerHand(), true);
+ void beginStroke({ uuid: mesh.uuid, slot: slotOfHit(mesh, hit, 0), sp: 'obj', at: h.local, normal: h.normal }).then((ok) => {
+ if (!ok && stroke?.index === index) stroke = null;
+ });
+ return true;
+}
+
+/** @param {number} index */
+export function paintTriggerEnd(index) {
+ if (!stroke || (index >= 0 && index !== stroke.index)) return false;
+ stroke = null;
+ endStroke(); // ONE commit + ONE undo entry, the desktop stroke's own
+ return true;
+}
+
+/** stick -> size (x) and flow (y, up = more); a tick at every 8 px / tenth @param {number} x @param {number} y @param {number} dt */
+export function adjustBrush(x, y, dt) {
+ let ticked = false;
+ if (Math.abs(x) > DEAD) {
+ const s0 = get(uvBrushSize);
+ const s = Math.round(THREE.MathUtils.clamp(s0 * Math.exp(x * dt * 1.4), SIZE_MIN, SIZE_MAX));
+ if (s !== s0) uvBrushSize.set(s);
+ if (Math.floor(s0 / 8) !== Math.floor(s / 8)) ticked = true;
+ }
+ if (Math.abs(y) > DEAD) {
+ const f0 = get(paintFlow);
+ const f = THREE.MathUtils.clamp(f0 - y * dt * 0.7, FLOW_MIN, FLOW_MAX);
+ paintFlow.set(Math.round(f * 1000) / 1000);
+ if (Math.floor(f0 * 10 + 1e-6) !== Math.floor(f * 10 + 1e-6)) ticked = true;
+ }
+ if (ticked) {
+ stats.ticks++;
+ hapticPulse(0.1, 10, pointerHand());
+ }
+ return ticked;
+}
+
+/** per frame: the ring follows the pointer, a held trigger paints, the stick sizes */
+export function tickVRPaint() {
+ if (!get(vrPaintActive)) return;
+ const now = performance.now();
+ const dt = Math.min((now - lastFrame) / 1000, 0.1);
+ lastFrame = now;
+ const mesh = target();
+ if (!mesh || !renderer?.xr?.getSession?.() || get(editorMode) === 'interact') {
+ if (stroke) cancelStroke();
+ stroke = null;
+ stopVRPaint();
+ return;
+ }
+ const index = stroke ? stroke.index : pointerIndex();
+ const hit = get(vrMenuOpen) ? null : hitOf(index);
+ if (hit) {
+ showRing(hit.point, worldNormal(hit), ringRadius(mesh, slotOfHit(mesh, hit, 0), hit));
+ if (stroke) {
+ strokeTo(localHit(mesh, hit).local);
+ stats.moves++;
+ }
+ } else hideRing();
+ if (!get(vrMenuOpen)) {
+ const axes = axesForSlot(pointerIndex());
+ adjustBrush(axes[2] ?? 0, axes[3] ?? 0, dt);
+ }
+ updateLabel();
+}
+
+/** what the hand label says @returns {string} */
+export function paintLabelText() {
+ const ch = channelOf(get(paintChannel)).label;
+ const what = get(paintErase) ? 'Erase ' + ch.toLowerCase() : ch;
+ return what + (get(paintMirror) ? ' (mirror)' : '') + ' · ' + get(uvBrushSize) + ' px · ' + Math.round(get(paintFlow) * 100) + '%';
+}
+
+/** @type {any} */ let label = null;
+/** @type {any} */ let labelCanvas = null;
+let labelText = '';
+
+function updateLabel() {
+ if (typeof document === 'undefined' || !renderer?.xr) return;
+ if (!label) {
+ labelCanvas = document.createElement('canvas');
+ labelCanvas.width = 320;
+ labelCanvas.height = 80;
+ const texture = new THREE.CanvasTexture(labelCanvas);
+ texture.colorSpace = THREE.SRGBColorSpace;
+ label = new THREE.Mesh(new THREE.PlaneGeometry(0.09, 0.0225), new THREE.MeshBasicMaterial({ map: texture, transparent: true, depthWrite: true }));
+ label.name = 'vr-paint-label';
+ label.position.set(0, 0.03, 0.07);
+ label.rotation.set(-1.0, 0, 0);
+ label.renderOrder = 996;
+ }
+ const index = pointerIndex();
+ label.visible = index >= 0;
+ if (index < 0) return;
+ const controller = renderer.xr.getController(index);
+ if (label.parent !== controller) controller.add(label);
+ const text = paintLabelText();
+ if (text === labelText) return;
+ labelText = text;
+ const ctx = labelCanvas.getContext('2d');
+ if (!ctx) return;
+ ctx.clearRect(0, 0, 320, 80);
+ ctx.fillStyle = 'rgba(17, 24, 39, 0.88)';
+ ctx.beginPath();
+ if (ctx.roundRect) ctx.roundRect(4, 4, 312, 72, 18);
+ else ctx.rect(4, 4, 312, 72);
+ ctx.fill();
+ ctx.fillStyle = '#f3f4f6';
+ ctx.font = '600 28px system-ui, sans-serif';
+ ctx.textAlign = 'center';
+ ctx.textBaseline = 'middle';
+ ctx.fillText(text.length > 26 ? text.slice(0, 25) + '…' : text, 160, 41);
+ label.material.map.needsUpdate = true;
+}
+
+function hideLabel() {
+ if (label) label.visible = false;
+}
+
+/** the suites' view */
+export function vrPaintDebug() {
+ return { active: get(vrPaintActive), uuid: paintUuid, stroking: !!stroke, label: labelText, channel: get(paintChannel), size: get(uvBrushSize), flow: get(paintFlow), ...stats };
+}
diff --git a/src/lib/vr/worldStores.js b/src/lib/vr/worldStores.js
index e3f99021b..16e9144af 100644
--- a/src/lib/vr/worldStores.js
+++ b/src/lib/vr/worldStores.js
@@ -6,3 +6,6 @@ import { writable } from 'svelte/store';
export const vrDollhouseOpen = writable(false);
/** a VR sculpt session is up (vr/sculpt.js writes it) */
export const vrSculptActive = writable(false);
+
+/** 102 M6: a VR paint session is up (vr/meshPaint.js writes it) */
+export const vrPaintActive = writable(false);
diff --git a/src/lib/vrRadialMenu.js b/src/lib/vrRadialMenu.js
index 023331494..d29ef3803 100644
--- a/src/lib/vrRadialMenu.js
+++ b/src/lib/vrRadialMenu.js
@@ -17,7 +17,7 @@ import { setMicMode, vrMicMode } from './voiceChat';
import { duplicateSelection, deleteSelection, groupSelection, selectionUuids } from './objectActions';
import { savePrefab, savePrefabSelection } from './prefabs';
import { perfContext } from './perf/perfMarks.js'; // 34 PF: an import-free leaf
-import { vrDollhouseOpen, vrSculptActive } from './vr/worldStores.js'; // 37: a leaf
+import { vrDollhouseOpen, vrSculptActive, vrPaintActive } from './vr/worldStores.js'; // 37: a leaf
import { sculptOp, sculptMode } from './terrainSculpt';
import { paintLayer } from './terrainPaint';
import { registerMeasureRings, registerArrangeRings } from './vr/buildRings.js'; // 52 V1/V2
@@ -517,6 +517,24 @@ function registerBuiltins() {
if (uuid) void import('./vr/sculpt.js').then((m) => m.startVRSculpt(uuid));
}
});
+ // 102 M6: paint the selected mesh (the desktop UV editor's Paint, on the model, with a controller)
+ registerVRMenuEntry({
+ id: 'obj:paint',
+ group: 'object',
+ label: 'Paint',
+ icon: 'brush',
+ order: 1.5,
+ closes: true,
+ visible: () =>
+ selCount() <= 1 &&
+ !isSplineSelection() &&
+ !isTerrainSelection() &&
+ !!(/** @type {any} */ (get(selectedObject))?.uuid),
+ action: () => {
+ const uuid = /** @type {any} */ (get(selectedObject))?.uuid;
+ if (uuid) void import('./vr/meshPaint.js').then((m) => m.startVRPaint(uuid));
+ }
+ });
// 57.4: a SPLINE gets its own editor in the same slot
registerVRMenuEntry({
id: 'obj:editspline',
@@ -610,6 +628,8 @@ function registerBuiltins() {
action: () => deleteSelection()
});
+ // 102 M6: the Paint ring registers itself from vr/meshPaint.js on the first paint session (boot stays small)
+
// 37 R9: the Sculpt ring — the radial opens on it while a VR sculpt session is up (Back = the usual menu)
[
['raise', 'Raise', 'arrow-up'],
@@ -743,4 +763,6 @@ vrMenuOpen.subscribe((open) => {
if (!open) resetRings();
// 37 R9: a sculpt session opens the menu on its own ring (Back pops to the base ring)
else if (get(vrSculptActive) && get(activeRing) === 'root') pushRing('sculpt');
+ // 102 M6: and a paint session on the Paint ring
+ else if (get(vrPaintActive) && get(activeRing) === 'root') pushRing('paint');
});
diff --git a/src/lib/wireValidate.js b/src/lib/wireValidate.js
index 87559109b..4a6a16f2f 100644
--- a/src/lib/wireValidate.js
+++ b/src/lib/wireValidate.js
@@ -28,6 +28,8 @@ import { isPingMessage } from './pingCore.js';
// 101 F2: the object schema's receive verdicts (a pure leaf; the cleaning runs in the appliers)
import { objectJsonVerdict, materialSetVerdict } from './sceneSchema.js';
import { validPhotoRequest, validPhotoResult } from './photo/photoCore.js';
+// 102 M6: the live mesh-paint stroke's shape (a zero-import leaf)
+import { validMeshPaint } from './meshPaintWire.js';
/** @param {unknown} v */
export function isUuid(v) {
@@ -174,6 +176,9 @@ const shortStr = (v) => typeof v === 'string' && v.length > 0 && v.length <= 128
* @type {Record boolean>}
*/
export const VALIDATORS = {
+ // 102 M6: a live mesh-paint stroke (a preview; the committed map / meshgeo is the truth)
+ meshpaint: (d) => validMeshPaint(d),
+ meshpaintend: (d) => typeof d.id === 'string' && d.id.length <= 64,
// 98 P2 (98-photo): Photo mode's hand-off — a view to render, its answer (PNG bytes capped), a stop
photoreq: (d) => validPhotoRequest(d),
photores: (d) => validPhotoResult(d),
@@ -497,6 +502,8 @@ export const VALIDATORS = {
// 101 F2: a slot list + groups — the schema's verdict here, the field-by-field cleaning in applyMaterials
if (d.parameter === 'materials') return isUuid(d.uuid) && materialSetVerdict(d.payload);
if (d.parameter === 'materialParam') return isUuid(d.uuid) && checkMaterialParam(null, d.key, d.value).ok;
+ // 102 M6: "this object only" on a shared material — the peer clones it too
+ if (d.parameter === 'materialUnlink') return isUuid(d.uuid);
// 72 LK1: a texture map slot takes an inline image or null, never a URL a peer could make us fetch
if (d.parameter === 'mapSlot') return isUuid(d.uuid) && isMapSlotKey(d.key) && isMapSlotImage(d.map);
// the base-colour map: an embedded image or null, never an address a peer could make us fetch
diff --git a/tests/e2e/battery.json b/tests/e2e/battery.json
index 798c80254..e40645539 100644
--- a/tests/e2e/battery.json
+++ b/tests/e2e/battery.json
@@ -280,6 +280,7 @@
"window-dock-menu": "red on the GitHub runner (SwiftShader, no retry) with unchanged code: deps-auto run 5, 2026-10-24",
"window-header-ranking": "flaky on the GitHub runner (SwiftShader): red or green-on-retry in deps-auto run 5 or 6 with unchanged code, 2026-10-24",
"window-size-clamp": "red on the GitHub runner (SwiftShader, no retry) with unchanged code: deps-auto run 5, 2026-10-24",
+ "mesh-paint": "102-paint: new, not yet measured on a GitHub runner, so it reports and does not gate until a deps run has seen it green",
"windows-polish": "78 pl-windows (1.64): new, not yet measured on a GitHub runner, so it reports and does not gate until a deps run has seen it green",
"workspace-restore": "joined from the 1.43 desk battery (pipeline-1): not yet measured on a GitHub runner, so it reports and does not gate until a deps run has seen it green"
},
@@ -645,6 +646,7 @@
"menu-mobile-scroll": 98,
"mesh-boolean": 174,
"mesh-knife": 138,
+ "mesh-paint": 240,
"mesh-sculpt": 17,
"mesh-toolbox-redesign": 242,
"mobile-editors": 75,
diff --git a/tests/e2e/mesh-paint.test.cjs b/tests/e2e/mesh-paint.test.cjs
new file mode 100644
index 000000000..7552bf67e
--- /dev/null
+++ b/tests/e2e/mesh-paint.test.cjs
@@ -0,0 +1,386 @@
+// 102 M6 — PAINT ON MESHES: roughness / metalness / emission channels, the new brush kinds, model strokes, the
+// vertex-colour fallback, the live wire to a second peer, undo, reload and GLB export, and the memory gate.
+//
+// What is asserted is PIXELS, by hash (meshPaint.mapHash: the bytes a channel READS — green for roughness, blue for
+// metalness — in one row order), so "the peer sees the same thing" cannot pass on "it has a texture".
+const h = require('./helpers.cjs');
+
+/** create a mesh by command, name it, select it, UV editor open on Paint @returns {Promise} its uuid */
+const make = (page, cmd, name) =>
+ page.evaluate(
+ async ({ cmd, name }) => {
+ const w = window.__tp.test.v1;
+ w.commandsHandler.sceneCommand(cmd);
+ const g = await new Promise((r) => w.objectsGroup.subscribe(r)());
+ const o = g.children[g.children.length - 1];
+ o.name = name;
+ w.objectActions.selectObject(o.uuid);
+ w.uvEditorClose.set(false);
+ w.bottomDock.activateDock('uv');
+ w.uvEditor.uvTool.set('paint');
+ return o.uuid;
+ },
+ { cmd, name }
+ );
+
+/** set the brush through the panel's own stores */
+const brush = (page, b) =>
+ page.evaluate(async (b) => {
+ const w = window.__tp.test.v1;
+ const p = w.meshPaintPrefs;
+ p.paintChannel.set(b.ch ?? 'color');
+ p.paintValue.set(b.value ?? 0.5);
+ p.paintHardness.set(b.hardness ?? 1);
+ p.paintOpacity.set(b.opacity ?? 1);
+ p.paintFlow.set(b.flow ?? 1);
+ p.paintErase.set(!!b.erase);
+ p.paintMirror.set(!!b.mirror);
+ p.paintStamp.set('');
+ p.paintMapSize.set(b.mapSize ?? 1024);
+ w.uvEditor.uvBrushSize.set(b.size ?? 64);
+ if (b.color) w.uvEditor.uvBrushColor.set(b.color);
+ }, b);
+
+/** a model stroke along the equator of a 0.5 sphere (or across a box face), through the painter's own API.
+ * `hold` leaves it OPEN (for the live-wire check). */
+const stroke = (page, uuid, { from = -0.4, to = 0.4, n = 12, y = 0, box = false, hold = false } = {}) =>
+ page.evaluate(
+ async ({ uuid, from, to, n, y, box, hold }) => {
+ const w = window.__tp.test.v1;
+ const at = (/** @type {number} */ i) => {
+ const a = from + ((to - from) * i) / (n - 1);
+ return box ? [a * 0.9, y, 0.5] : [0.5 * Math.sin(a) * Math.cos(y), 0.5 * Math.sin(y), 0.5 * Math.cos(a) * Math.cos(y)];
+ };
+ const ok = await w.meshPaint.beginStroke({ uuid, sp: 'obj', at: at(0), normal: [0, 0, 1] });
+ if (!ok) return { ok };
+ for (let i = 1; i < n; i++) {
+ w.meshPaint.strokeTo(at(i));
+ await new Promise((r) => setTimeout(r, 25));
+ }
+ if (hold) return { ok, open: w.meshPaint.stroking() };
+ return { ok, committed: w.meshPaint.endStroke(), last: w.meshPaint.meshPaintDebug().last };
+ },
+ { uuid, from, to, n, y, box, hold }
+ );
+
+const hashOf = (page, uuid, ch, slot = 0) =>
+ page.evaluate(({ uuid, ch, slot }) => window.__tp.test.v1.meshPaint.mapHash(uuid, slot, ch), { uuid, ch, slot });
+
+/** the material facts a channel touches */
+const mat = (page, uuid) =>
+ page.evaluate(async (uuid) => {
+ const w = window.__tp.test.v1;
+ const g = await new Promise((r) => w.objectsGroup.subscribe(r)());
+ const o = g.getObjectByProperty('uuid', uuid);
+ const m = Array.isArray(o?.material) ? o.material[0] : o?.material;
+ const c = o?.geometry?.attributes?.color;
+ let off = 0;
+ if (c) for (let i = 0; i < c.count; i++) if (c.getX(i) < 0.98 || c.getY(i) < 0.98 || c.getZ(i) < 0.98) off++;
+ return {
+ found: !!o,
+ roughness: m?.roughness,
+ metalness: m?.metalness,
+ emissive: m?.emissive?.getHexString?.(),
+ roughnessMap: !!m?.roughnessMap,
+ emissiveMap: !!m?.emissiveMap,
+ map: !!m?.map,
+ vertexColors: !!m?.vertexColors,
+ colorAttr: !!c,
+ paintedVerts: off
+ };
+ }, uuid);
+
+const undoDepth = (page) =>
+ page.evaluate(() => new Promise((r) => window.__tp.test.v1.history.undoStack.subscribe((v) => r(v.length))()));
+const undo = (page) => page.evaluate(() => window.__tp.test.v1.history.undo());
+const redo = (page) => page.evaluate(() => window.__tp.test.v1.history.redo());
+
+h.run(async () => {
+ const browser = await h.launch();
+ const A = await h.setupPage(browser, 'A');
+ const B = await h.setupPage(browser, 'B');
+ await h.connect(B, A);
+
+ // ---- 1. the panel: every new control is there, with a tooltip --------------------------------------------------
+ const ball = await make(A.page, '/create Sphere 0.5', 'paint-ball');
+ await A.page.waitForTimeout(800);
+ // the panel is a lazy chunk (boot rule) loaded when Paint is armed; a cold dev server compiles it on that first ask
+ await A.page.waitForSelector('#paint-channel', { timeout: 60000 }).catch(() => {});
+ const panel = await A.page.evaluate(() => {
+ const ids = ['paint-channel', 'paint-hardness', 'paint-opacity', 'paint-flow', 'paint-erase', 'paint-mirror', 'paint-stamp', 'paint-map-size', 'paint-show-channel'];
+ const missing = ids.filter((id) => !document.getElementById(id));
+ const untitled = [...document.querySelectorAll('#paint-channel button, #paint-erase, #paint-mirror, #paint-map-size button')].filter((b) => !b.getAttribute('title')).length;
+ return { missing, untitled };
+ });
+ h.check(panel.missing.length === 0, `arming Paint shows the new brush controls (missing: ${panel.missing.join(',') || 'none'})`);
+ h.check(panel.untitled === 0, 'every new brush button has a tooltip');
+
+ // ---- 2. a roughness stroke on the model: a NEW map, one undo step, the slider lifted in the same step ----------
+ await brush(A.page, { ch: 'roughness', value: 0.1, hardness: 0.6, size: 64 });
+ const before = await mat(A.page, ball);
+ h.check(before.found && !before.roughnessMap, 'premise: the sphere has no roughness map');
+ const d0 = await undoDepth(A.page);
+ const live = await stroke(A.page, ball, { hold: true });
+ h.check(live.ok && live.open, 'a model stroke opens on a mesh with clean UVs');
+ await h.eventually(
+ () => B.page.evaluate(() => window.__tp.test.v1.meshPaint?.remoteStrokeCount?.() ?? 0),
+ (n) => n > 0,
+ 'THE WIRE: B is replaying A’s stroke live, before any commit',
+ 15000
+ );
+ const ended = await A.page.evaluate(() => window.__tp.test.v1.meshPaint.endStroke());
+ h.check(ended, 'the stroke commits');
+ const after = await mat(A.page, ball);
+ h.check(after.roughnessMap, 'the first stroke made a roughness map');
+ h.check(after.roughness === 1, `the slider is lifted to 1 so the map reads true (${before.roughness} -> ${after.roughness})`);
+ const d1 = await undoDepth(A.page);
+ h.check(d1 === d0 + 1, `one stroke (map + lift) is ONE undo step (${d0} -> ${d1})`);
+ const hA = await hashOf(A.page, ball, 'roughness');
+ h.check(!!hA, `A's roughness map is readable (${hA?.w}x${hA?.h} ${hA?.hash})`);
+ h.check(hA?.w === 1024, 'a new map is made at the chosen size (1k)');
+ await h.eventually(
+ () => hashOf(B.page, ball, 'roughness'),
+ (x) => !!x && x.hash === hA.hash,
+ 'B shows the SAME roughness pixels (hash)',
+ 25000
+ );
+ await h.eventually(
+ () => mat(B.page, ball),
+ (m) => m.roughness === 1,
+ 'B gets the lifted slider too',
+ 15000
+ );
+
+ // ---- 3. undo / redo, on both peers ------------------------------------------------------------------------------
+ await undo(A.page);
+ const undone = await mat(A.page, ball);
+ h.check(!undone.roughnessMap && undone.roughness === before.roughness, `undo takes the map AND the lift back (${undone.roughness})`);
+ await h.eventually(() => mat(B.page, ball), (m) => !m.roughnessMap, 'B loses the map on undo', 15000);
+ await redo(A.page);
+ await h.eventually(() => hashOf(A.page, ball, 'roughness'), (x) => !!x && x.hash === hA.hash, 'redo puts the same pixels back', 15000);
+ await h.eventually(() => hashOf(B.page, ball, 'roughness'), (x) => !!x && x.hash === hA.hash, 'B follows the redo', 25000);
+
+ // ---- 4. the brush is deterministic: replaying the stroke as a peer would draws the same pixels -----------------
+ await brush(A.page, { ch: 'color', color: '#2255ff', hardness: 0.3, flow: 0.5, opacity: 0.8, mirror: true, size: 48 });
+ const twin = await make(A.page, '/create Sphere 0.5', 'paint-twin');
+ const soft = await make(A.page, '/create Sphere 0.5', 'paint-soft');
+ await A.page.waitForTimeout(600);
+ // held open first: the commit is a webp (lossy), so the bytes a replay must match are the LIVE canvas the sender
+ // painted, which is what a peer's replay shows until that commit lands
+ const held = await stroke(A.page, soft, { from: 0.1, to: 0.9, n: 16, y: 0.2, hold: true });
+ const hSoft = await hashOf(A.page, soft, 'color');
+ const s2 = held.ok
+ ? await A.page.evaluate(() => {
+ const m = window.__tp.test.v1.meshPaint;
+ return { ok: true, committed: m.endStroke(), last: m.meshPaintDebug().last };
+ })
+ : held;
+ h.check(s2.ok && s2.committed, 'a soft, low-flow, mirrored colour stroke commits');
+ h.check((s2.last?.points?.length ?? 0) > 1 && s2.last?.b?.m === 1, 'the stroke carries its brush (mirror) and rounded points');
+ const replay = await A.page.evaluate(
+ async ({ twin, last }) => {
+ const m = window.__tp.test.v1.meshPaint;
+ await m.applyMeshPaint({ type: 'meshpaint', id: 'replay-1', uuid: twin, sp: last.sp, c: last.c, r: last.r, ...(last.b && Object.keys(last.b).length ? { b: last.b } : {}), ...(last.n ? { n: last.n } : {}), seg: last.points });
+ await m.applyMeshPaintEnd({ id: 'replay-1' });
+ return true;
+ },
+ { twin, last: s2.last }
+ );
+ h.check(replay, 'premise: the replay ran');
+ const hTwin = await hashOf(A.page, twin, 'color');
+ h.check(!!hSoft && !!hTwin && hSoft.hash === hTwin.hash, `a replayed stroke draws byte-identical pixels (${hSoft?.hash} vs ${hTwin?.hash})`);
+ const mirrored = await A.page.evaluate(async (uuid) => {
+ // the mirror half: on a three sphere the front (+z) is u = 0.25 and x -> -x maps u -> 0.5 - u, so the stroke
+ // (a = 0.1..0.9 rad toward +x) lands right of u = 0.25 and its mirror left of it
+ const w = window.__tp.test.v1;
+ const g = await new Promise((r) => w.objectsGroup.subscribe(r)());
+ const o = g.getObjectByProperty('uuid', uuid);
+ const img = o.material.map.image;
+ const c = document.createElement('canvas');
+ c.width = img.width;
+ c.height = img.height;
+ const ctx = c.getContext('2d');
+ ctx.drawImage(img, 0, 0);
+ const px = ctx.getImageData(0, 0, c.width, c.height).data;
+ let left = 0;
+ let right = 0;
+ for (let y = 0; y < c.height; y++)
+ for (let x = 0; x < c.width; x++) {
+ const i = (y * c.width + x) * 4;
+ if (px[i + 2] - px[i] > 40 && x < c.width / 2) (x < c.width / 4 ? left++ : right++);
+ }
+ return { left, right };
+ }, soft);
+ h.check(mirrored.left > 50 && mirrored.right > 50, `Mirror X paints both halves (${mirrored.left} / ${mirrored.right} px)`);
+
+ // ---- 5. the eraser goes back to the material's own value ----------------------------------------------------------
+ await brush(A.page, { ch: 'roughness', erase: true, size: 128 });
+ const er = await stroke(A.page, ball, { n: 14 });
+ h.check(er.ok && er.committed, 'an eraser stroke commits');
+ h.check(er.last?.c === '#ffffff', `the roughness eraser paints white (the slider shows through) (${er.last?.c})`);
+ const hErased = await hashOf(A.page, ball, 'roughness');
+ h.check(hErased && hErased.hash !== hA.hash, 'the eraser changed the map');
+
+ // ---- 6. vertex-colour fallback: a box's six faces share one UV square ---------------------------------------------
+ await brush(A.page, { ch: 'color', color: '#ff2200', size: 96 });
+ const box = await make(A.page, '/create Box 1 1 1', 'paint-box');
+ await A.page.waitForTimeout(600);
+ const target = await A.page.evaluate(async (uuid) => {
+ const w = window.__tp.test.v1;
+ const g = await new Promise((r) => w.objectsGroup.subscribe(r)());
+ return w.meshPaint.targetFor(g.getObjectByProperty('uuid', uuid), 0);
+ }, box);
+ h.check(target?.mode === 'vertex', `overlapping UVs paint vertex colours (${target?.mode}: ${target?.reason})`);
+ await A.page.waitForTimeout(300);
+ const note = await A.page.evaluate(() => document.getElementById('paint-target-info')?.textContent?.trim() ?? '');
+ h.check(note.length > 10, `the panel says why (${note.slice(0, 60)})`);
+ const vd0 = await undoDepth(A.page);
+ const vs = await stroke(A.page, box, { box: true, n: 10 });
+ h.check(vs.ok && vs.committed && vs.last?.sp === 'vtx', 'the box stroke paints vertex colours');
+ const vm = await mat(A.page, box);
+ h.check(vm.colorAttr && vm.vertexColors && vm.paintedVerts > 0, `vertex colours are on and painted (${vm.paintedVerts} verts)`);
+ h.check((await undoDepth(A.page)) === vd0 + 1, 'a vertex stroke is one undo step');
+ await h.eventually(() => mat(B.page, box), (m) => m.vertexColors && m.paintedVerts === vm.paintedVerts, 'B gets the same painted vertices', 25000);
+ await undo(A.page);
+ const vu = await mat(A.page, box);
+ h.check(!vu.vertexColors && vu.paintedVerts === 0, 'undo takes the colours and the switch back');
+ const refused = await A.page.evaluate(async (uuid) => {
+ const w = window.__tp.test.v1;
+ w.meshPaintPrefs.paintChannel.set('metalness');
+ return w.meshPaint.beginStroke({ uuid, sp: 'obj', at: [0, 0, 0.5] });
+ }, box);
+ h.check(refused === false, 'a map channel on a mesh without clean UVs is refused (with a toast), not painted wrong');
+ await redo(A.page);
+
+ // ---- 7. reload: the painted map survives ----------------------------------------------------------------------
+ const keep = await hashOf(A.page, ball, 'roughness');
+ await A.page.evaluate(() => window.__tp.test.v1.autosave.saveNow());
+ await h.freshReload(A);
+ // the restore by hand (not h.answerRestore): its click waits only 10 s for the page, and a restore that decodes
+ // several painted maps is measured here instead of timing out
+ const offered = await A.page
+ .waitForFunction(
+ () => {
+ const m = window.__tp?.test.v1?.autosave;
+ if (!m?.restoreAvailable) return false;
+ let v;
+ m.restoreAvailable.subscribe((x) => (v = x))();
+ return !!v;
+ },
+ null,
+ { timeout: 30000, polling: 200 }
+ )
+ .then(() => true)
+ .catch(() => false);
+ h.check(offered, 'after a reload the painted session is offered back');
+ const t0 = Date.now();
+ // a DOM click: a Playwright click gives up after 10 s while the freshly reloaded page is still busy booting
+ await A.page.waitForSelector('#restore-session-restore', { timeout: 30000 });
+ await A.page.evaluate(() => /** @type {HTMLElement} */ (document.querySelector('#restore-session-restore')).click());
+ await A.page.waitForFunction(
+ () => {
+ let v;
+ window.__tp.test.v1.autosave.restoreAvailable.subscribe((x) => (v = x))();
+ return !v && !document.querySelector('#restore-session-modal[open]');
+ },
+ null,
+ { timeout: 60000, polling: 100 }
+ );
+ const restoreMs = Date.now() - t0;
+ // the waitForFunction above IS the gate (60 s); the time swings 10-30 s with machine load, so it is reported, not gated
+ h.check(true, `the restore finishes (${restoreMs} ms)`);
+ console.log(`INFO restore with the painted maps took ${restoreMs} ms`);
+ const reloaded = await h.eventually(
+ () =>
+ A.page.evaluate(async () => {
+ const w = window.__tp.test.v1;
+ const g = await new Promise((r) => w.objectsGroup.subscribe(r)());
+ const o = g.getObjectByName('paint-ball');
+ if (!o) return null;
+ return w.meshPaint.mapHash(o.uuid, 0, 'roughness');
+ }),
+ (x) => !!x && x.hash === keep.hash,
+ `after a reload the roughness pixels are the same (${keep?.hash})`,
+ 40000
+ );
+ void reloaded;
+
+ // ---- 8. GLB export carries the new maps -------------------------------------------------------------------------
+ const gltf = await A.page.evaluate(async () => {
+ const w = window.__tp.test.v1;
+ const g = await new Promise((r) => w.objectsGroup.subscribe(r)());
+ const o = g.getObjectByName('paint-ball');
+ const soft = g.getObjectByName('paint-soft');
+ const out = await w.fileHandler.gltfBytesFor([o, soft], { binary: false });
+ const text = typeof out === 'string' ? out : new TextDecoder().decode(out);
+ const json = JSON.parse(text);
+ const mats = json.materials ?? [];
+ return {
+ metalRough: mats.filter((m) => m.pbrMetallicRoughness?.metallicRoughnessTexture).length,
+ baseColor: mats.filter((m) => m.pbrMetallicRoughness?.baseColorTexture).length,
+ images: (json.images ?? []).length
+ };
+ });
+ h.check(gltf.metalRough >= 1, `the glTF export carries the painted roughness map (${gltf.metalRough} metallicRoughnessTexture)`);
+ h.check(gltf.baseColor >= 1, `and the painted colour map (${gltf.baseColor} baseColorTexture, ${gltf.images} images)`);
+
+ // ---- 9. memory gate: ten 2k strokes grow the heap by no more than one map ---------------------------------------
+ await brush(A.page, { ch: 'metalness', value: 0.9, size: 64, mapSize: 2048 });
+ const mem = await A.page.evaluate(async () => {
+ const w = window.__tp.test.v1;
+ const heap = async () => {
+ for (let i = 0; i < 3; i++) {
+ /** @type {any} */ (window).gc?.();
+ await new Promise((r) => setTimeout(r, 120));
+ }
+ return /** @type {any} */ (performance).memory?.usedJSHeapSize ?? null;
+ };
+ w.commandsHandler.sceneCommand('/create Sphere 0.5');
+ const g = await new Promise((r) => w.objectsGroup.subscribe(r)());
+ const o = g.children[g.children.length - 1];
+ o.name = 'paint-mem';
+ // the first stroke makes the map (that map is the one map the gate allows); measure from after it
+ const one = async (k) => {
+ const a0 = -0.6 + k * 0.05;
+ await w.meshPaint.beginStroke({ uuid: o.uuid, sp: 'obj', at: [0.5 * Math.sin(a0), 0, 0.5 * Math.cos(a0)] });
+ for (let i = 1; i < 12; i++) {
+ const a = a0 + i * 0.06;
+ w.meshPaint.strokeTo([0.5 * Math.sin(a), 0.1 * Math.sin(k + i), 0.5 * Math.cos(a)]);
+ }
+ return w.meshPaint.endStroke();
+ };
+ const h0 = await heap();
+ let ok = 0;
+ for (let k = 0; k < 10; k++) if (await one(k)) ok++;
+ await new Promise((r) => setTimeout(r, 1500)); // the committed images decode
+ const h1 = await heap();
+ // what the ten strokes KEEP: the strings in their undo entries (the before/after images). Deterministic, where
+ // usedJSHeapSize is quantised without --enable-precise-memory-info and moves with whatever else the page does
+ const stack = await new Promise((r) => w.history.undoStack.subscribe(r)());
+ const seen = new Set();
+ /** @param {any} v @param {number} d @returns {number} */
+ const bytes = (v, d) => {
+ if (typeof v === 'string') return v.length;
+ if (!v || typeof v !== 'object' || d > 5 || seen.has(v)) return 0;
+ seen.add(v);
+ if (v.isObject3D || v.isMaterial || v.isTexture || ArrayBuffer.isView(v)) return 0;
+ let n = 0;
+ for (const k of Object.keys(v)) n += bytes(v[k], d + 1);
+ return n;
+ };
+ const last10 = stack.slice(-10);
+ const undoBytes = last10.reduce((n, e) => n + bytes(e, 0), 0);
+ return { ok, h0, h1, undoBytes, entries: last10.length, gc: typeof (/** @type {any} */ (window).gc) === 'function', size: o.material.metalnessMap?.image?.width ?? 0 };
+ });
+ h.check(mem.ok === 10, `ten 2k strokes commit (${mem.ok})`);
+ h.check(mem.size === 2048, `the new map is 2k (${mem.size})`);
+ const ONE_MAP = 2048 * 2048 * 4;
+ h.check(
+ mem.entries === 10 && mem.undoBytes > 0 && mem.undoBytes <= ONE_MAP,
+ `memory gate: ten 2k strokes keep ${(mem.undoBytes / 1048576).toFixed(2)} MB in their ${mem.entries} undo entries, at most one map (${(ONE_MAP / 1048576).toFixed(0)} MB)`
+ );
+ // the heap reading is reported, not gated (quantised in Chromium without precise memory info)
+ if (mem.h0 != null) console.log(`INFO JS heap ${(((mem.h1 - mem.h0) / 1048576)).toFixed(1)} MB over the ten strokes${mem.gc ? '' : ' (no forced GC)'}`);
+
+ await h.finish(browser);
+});
diff --git a/tests/unit/meshPaintCore.test.js b/tests/unit/meshPaintCore.test.js
new file mode 100644
index 000000000..88d3bc098
--- /dev/null
+++ b/tests/unit/meshPaintCore.test.js
@@ -0,0 +1,248 @@
+// @ts-nocheck — plain arrays stand in for geometry
+import { describe, it, expect } from 'vitest';
+import {
+ CHANNELS,
+ channelOf,
+ normalizeBrush,
+ isDefaultBrush,
+ brushWire,
+ brushFromWire,
+ paintStyle,
+ grayHex,
+ falloff,
+ falloffStops,
+ dabsAlong,
+ triFrame,
+ dabOnTri,
+ planeToUv,
+ planeToCanvas,
+ uvToCanvas,
+ padTri,
+ texelDensity,
+ buildTriGrid,
+ trisNear,
+ uvOverlap,
+ paintTarget,
+ vertexDab,
+ blendVertexColors,
+ mirrorX,
+ onMirrorPlane,
+ hashBytes
+} from '../../src/lib/meshPaintCore.js';
+
+// 102 M6: the pure half of painting on meshes.
+
+describe('channels and brush', () => {
+ it('names four channels, colour first', () => {
+ expect(CHANNELS.map((c) => c.key)).toEqual(['color', 'roughness', 'metalness', 'emissive']);
+ expect(channelOf('nope').key).toBe('color');
+ expect(channelOf('roughness').map).toBe('roughnessMap');
+ });
+ it('clamps a hostile brush', () => {
+ const b = normalizeBrush({ hardness: -3, opacity: 9, flow: 0, erase: 'yes', mirror: true, stamp: '