roamwright 0.61.15 → 0.61.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,408 @@
1
+ /**
2
+ * Floating 3D world-space place-name sprites with staggered canvas creation and next-frame GPU
3
+ * texture upload (preventing first-frame hitches), priority + distance sorting with zero per-frame
4
+ * allocations, HUD-margin and other-label avoidance, terrain/skyline occlusion, and smooth opacity fading.
5
+ * @module
6
+ */
7
+ import * as THREE from 'three';
8
+ import { clamp, sstep } from '../math/scalar.js';
9
+ import { DEFAULT_MAP_FONT } from './map-glyphs.js';
10
+
11
+ /**
12
+ * Default `[maxRange, minRange, heightAboveGround, scale, priority]` tuples for open-land place kinds.
13
+ * @type {Readonly<Record<string, readonly [number, number, number, number, number]>>}
14
+ */
15
+ export const DEFAULT_PLACE_TAG_STYLES = Object.freeze({
16
+ city: [6000, 150, 78, 1.2, 0],
17
+ region: [760, 240, 110, 1.1, 1],
18
+ landmark: [260, 34, 30, 0.95, 2],
19
+ district: [230, 60, 40, 0.9, 3],
20
+ });
21
+
22
+ /**
23
+ * Default `[maxRange, minRange, heightAboveGround, scale, priority]` tuples inside compact spaces.
24
+ * @type {Readonly<Record<string, readonly [number, number, number, number, number]>>}
25
+ */
26
+ export const DEFAULT_SMALL_TAG_STYLES = Object.freeze({
27
+ landmark: [150, 4, 7, 0.9, 2],
28
+ district: [170, 22, 13, 0.9, 3],
29
+ });
30
+
31
+ const HALO = 'rgba(4,6,8,.9)';
32
+ const TEXT_W = 468;
33
+
34
+ function edged(ctx, stroke) {
35
+ ctx.shadowBlur = 22;
36
+ ctx.strokeStyle = 'rgba(4,6,8,.7)';
37
+ ctx.lineWidth = 18;
38
+ stroke();
39
+ ctx.shadowBlur = 4;
40
+ ctx.strokeStyle = 'rgba(4,6,8,1)';
41
+ ctx.lineWidth = 6;
42
+ stroke();
43
+ ctx.shadowBlur = 0;
44
+ }
45
+
46
+ function drawDoorwayMark(ctx, x, y) {
47
+ const trace = () => {
48
+ ctx.beginPath();
49
+ ctx.moveTo(x - 9, y + 15);
50
+ ctx.lineTo(x - 9, y - 4);
51
+ ctx.arc(x, y - 4, 9, Math.PI, 0);
52
+ ctx.lineTo(x + 9, y + 15);
53
+ };
54
+ edged(ctx, () => {
55
+ trace();
56
+ ctx.stroke();
57
+ });
58
+ ctx.strokeStyle = '#ffc27a';
59
+ ctx.lineWidth = 3.5;
60
+ trace();
61
+ ctx.stroke();
62
+ }
63
+
64
+ const goesAfter = (a, b) => a.pr > b.pr || (a.pr === b.pr && a.d > b.d);
65
+
66
+ /**
67
+ * Creates a world-space place-name sprite controller.
68
+ *
69
+ * @param {object} options
70
+ * @param {THREE.PerspectiveCamera} options.camera Active world camera.
71
+ * @param {THREE.WebGLRenderer} options.renderer Active WebGL renderer (for next-frame `initTexture`).
72
+ * @param {() => ReadonlyArray<object>} options.getLocations Returns all world locations.
73
+ * @param {() => object} options.getSpace Returns the active space (`{ id, flyable, ground(x, z), origin }`).
74
+ * @param {() => Record<string, object>} options.getSpaces Returns the map of all spaces by id.
75
+ * @param {(id: string) => boolean} options.isBuilt Returns true when space `id` is built.
76
+ * @param {() => number} [options.getNight] Night factor `0..1` (0 = full day, 1 = night).
77
+ * @param {() => boolean} options.isShown Returns true when place names should be visible.
78
+ * @param {() => { width: number, height: number }} options.getViewport Live stage viewport in CSS pixels.
79
+ * @param {() => { top: number, rightLeft: number, rightBottom: number }} options.getHudBounds HUD exclusion bounds in CSS pixels.
80
+ * @param {(x0: number, y0: number, x1: number, y1: number) => boolean} [options.isBlocked] Extra screen-space occlusion test (page pixels: left, top, right, bottom).
81
+ * @param {(x: number, z: number, space: object) => number} [options.skylineBoost] Extra roofline height in metres along sight lines (e.g. inside a city).
82
+ * @param {(sprite: THREE.Sprite) => void} [options.onSpriteCreated] Called when a sprite is created (for example to attach it to an overlay scene).
83
+ * @param {string} [options.font=DEFAULT_MAP_FONT]
84
+ * @param {Record<string, readonly [number, number, number, number, number]>} [options.tagStyles=DEFAULT_PLACE_TAG_STYLES]
85
+ * @param {Record<string, readonly [number, number, number, number, number]>} [options.smallTagStyles=DEFAULT_SMALL_TAG_STYLES]
86
+ * @param {string} [options.defaultSpaceId='world']
87
+ * @param {number} [options.maxVisible=6] Maximum simultaneous visible names.
88
+ * @param {number} [options.tagsPerFrame=4] New tag sprites built per frame during warm-up.
89
+ * @param {number} [options.nameHeight=0.036] Sprite height as a share of unit frustum height.
90
+ * @param {number} [options.nameMinPx=28] Minimum height in CSS pixels.
91
+ * @param {number} [options.dayLift=0.7] Luminance boost by day so white lettering reads against a bright sky.
92
+ * @param {number} [options.hudLeftPx=120] Left HUD margin in CSS pixels.
93
+ * @param {object} [options.host=globalThis]
94
+ * @returns {{ tags: Array<object>, update: (dt: number) => void, refresh: () => void, dispose: () => void }}
95
+ */
96
+ export function createPlaceNames({
97
+ camera,
98
+ renderer,
99
+ getLocations,
100
+ getSpace,
101
+ getSpaces,
102
+ isBuilt,
103
+ getNight = () => 0,
104
+ isShown,
105
+ getViewport,
106
+ getHudBounds,
107
+ isBlocked = () => false,
108
+ skylineBoost = () => 0,
109
+ onSpriteCreated = () => {},
110
+ font = DEFAULT_MAP_FONT,
111
+ tagStyles = DEFAULT_PLACE_TAG_STYLES,
112
+ smallTagStyles = DEFAULT_SMALL_TAG_STYLES,
113
+ defaultSpaceId = 'world',
114
+ maxVisible = 6,
115
+ tagsPerFrame = 4,
116
+ nameHeight = 0.036,
117
+ nameMinPx = 28,
118
+ dayLift = 0.7,
119
+ hudLeftPx = 120,
120
+ host = globalThis,
121
+ }) {
122
+ const _v = new THREE.Vector3();
123
+ const tags = [];
124
+ const tagBox = new Float32Array(maxVisible * 2);
125
+ const named = new Set();
126
+ let measure = null;
127
+ let drawnLast = null;
128
+ let unnamed = [];
129
+ let listed = false;
130
+
131
+ function tagText(loc) {
132
+ const cap = loc.kind === 'region' || loc.kind === 'city';
133
+ const text = cap ? loc.name.toUpperCase().split('').join('\u200a') : loc.name;
134
+ const f = (loc.kind === 'district' ? 'italic ' : '') + (cap ? '400 38px ' : '400 44px ') + font;
135
+ measure ??= host.document.createElement('canvas').getContext('2d');
136
+ measure.font = f;
137
+ return { text, font: f, w: measure.measureText(text).width };
138
+ }
139
+
140
+ function tagKind(loc, small) {
141
+ if (!small) {
142
+ const T = tagStyles[loc.kind];
143
+ return loc.kind === 'landmark' && loc.h ? [T[0], T[1], loc.h, T[3], T[4]] : T;
144
+ }
145
+ const [range, nearest, h, size, pr] = smallTagStyles[loc.kind];
146
+ return [loc.range ?? range, nearest, loc.h ?? h, size, pr];
147
+ }
148
+
149
+ function nameable(loc) {
150
+ const landId = loc.space ?? defaultSpaceId;
151
+ if (!isBuilt(landId)) return false;
152
+ const own = getSpaces()[landId];
153
+ return own.flyable ? !!(tagStyles[loc.kind] && loc.x !== undefined) : !!(smallTagStyles[loc.kind] && loc.off);
154
+ }
155
+
156
+ function drawTag(t) {
157
+ const loc = t.loc;
158
+ const c = t.sp.material.map.image;
159
+ const g = c.getContext('2d');
160
+ const { text, font: f, w } = tagText(loc);
161
+ g.textAlign = 'center';
162
+ g.textBaseline = 'middle';
163
+ g.lineJoin = 'round';
164
+ g.shadowColor = HALO;
165
+ g.font = f;
166
+ g.save();
167
+ g.translate(256, 44);
168
+ if (w > TEXT_W) g.scale(TEXT_W / w, 1);
169
+ edged(g, () => g.strokeText(text, 0, 0));
170
+ g.fillStyle = loc.kind === 'landmark' ? '#f3ecd9' : loc.kind === 'district' ? '#cfe9e2' : '#ffffff';
171
+ g.fillText(text, 0, 0);
172
+ g.restore();
173
+ if (loc.enter) drawDoorwayMark(g, Math.max(18, 256 - Math.min(w, TEXT_W) / 2 - 26), 44);
174
+ if (loc.kind === 'landmark') {
175
+ edged(g, () => g.strokeRect(256 - 1.5, 74, 3, 18));
176
+ g.fillStyle = '#62e6cb';
177
+ g.fillRect(256 - 1.5, 74, 3, 18);
178
+ }
179
+ t.sp.material.map.needsUpdate = true;
180
+ t.drawn = true;
181
+ drawnLast = t;
182
+ }
183
+
184
+ function toCard() {
185
+ if (!drawnLast) return;
186
+ renderer.initTexture(drawnLast.sp.material.map);
187
+ drawnLast.onCard = true;
188
+ drawnLast = null;
189
+ }
190
+
191
+ function makeTag(loc) {
192
+ const land = loc.space ?? defaultSpaceId;
193
+ const own = getSpaces()[land];
194
+ const small = !own.flyable;
195
+ const T = tagKind(loc, small);
196
+ const c = host.document.createElement('canvas');
197
+ c.width = 512;
198
+ c.height = 96;
199
+ loc.tw = Math.min(1, tagText(loc).w / TEXT_W);
200
+ const tex = new THREE.CanvasTexture(c);
201
+ tex.colorSpace = THREE.SRGBColorSpace;
202
+ tex.anisotropy = 4;
203
+ const sp = new THREE.Sprite(
204
+ new THREE.SpriteMaterial({
205
+ map: tex,
206
+ transparent: true,
207
+ depthWrite: false,
208
+ depthTest: small,
209
+ fog: false,
210
+ opacity: 0,
211
+ sizeAttenuation: false,
212
+ }),
213
+ );
214
+ sp.center.set(0.5, 0);
215
+ sp.scale.set((nameHeight * T[3] * 512) / 96, nameHeight * T[3], 1);
216
+ sp.renderOrder = 19;
217
+ sp.visible = false;
218
+ onSpriteCreated(sp);
219
+ const x = small ? own.origin.x + loc.off[0] : loc.x;
220
+ const z = small ? own.origin.z + loc.off[1] : loc.z;
221
+ return {
222
+ loc,
223
+ sp,
224
+ land,
225
+ T,
226
+ x,
227
+ z,
228
+ a: 0,
229
+ want: 0,
230
+ d: 0,
231
+ tw: loc.tw,
232
+ y: own.ground(x, z) + T[2],
233
+ pr: T[4],
234
+ drawn: false,
235
+ onCard: false,
236
+ };
237
+ }
238
+
239
+ function isHidden(t, sp) {
240
+ const cx = camera.position.x;
241
+ const cy = camera.position.y;
242
+ const cz = camera.position.z;
243
+ const tx = t.x;
244
+ const tz = t.z;
245
+ const ty = t.y - t.T[2] + 6;
246
+ const dx = tx - cx;
247
+ const dz = tz - cz;
248
+ const L = Math.sqrt(dx * dx + dz * dz);
249
+ const n = Math.min(24, Math.ceil(L / 25));
250
+ for (let i = 1; i < n; i++) {
251
+ const u = i / n;
252
+ if (u * L > L - 45) break;
253
+ const x = cx + (tx - cx) * u;
254
+ const z = cz + (tz - cz) * u;
255
+ const sky = sp.ground(x, z) + skylineBoost(x, z, sp);
256
+ if (cy + (ty - cy) * u < sky) return true;
257
+ }
258
+ return false;
259
+ }
260
+
261
+ function listUnnamed() {
262
+ const cx = camera.position.x;
263
+ const cz = camera.position.z;
264
+ const far = loc => Math.hypot((loc.x ?? cx) - cx, (loc.z ?? cz) - cz);
265
+ unnamed = getLocations()
266
+ .filter(loc => !named.has(loc) && nameable(loc))
267
+ .sort((a, b) => far(b) - far(a));
268
+ listed = true;
269
+ }
270
+
271
+ function addTags() {
272
+ for (let k = 0; k < tagsPerFrame && unnamed.length; k++) {
273
+ const loc = unnamed.pop();
274
+ named.add(loc);
275
+ tags.push(makeTag(loc));
276
+ }
277
+ }
278
+
279
+ function sortTags() {
280
+ for (let i = 1; i < tags.length; i++) {
281
+ const t = tags[i];
282
+ let j = i - 1;
283
+ for (; j >= 0 && goesAfter(tags[j], t); j--) tags[j + 1] = tags[j];
284
+ tags[j + 1] = t;
285
+ }
286
+ }
287
+
288
+ function update(dt) {
289
+ const show = isShown();
290
+ if (!listed) {
291
+ if (!show) return;
292
+ listUnnamed();
293
+ }
294
+ if (unnamed.length) addTags();
295
+ const sp = getSpace();
296
+ const cx = camera.position.x;
297
+ const cy = camera.position.y;
298
+ const cz = camera.position.z;
299
+ const asp = camera.aspect;
300
+ const vp = getViewport();
301
+ const hud = getHudBounds();
302
+ const halfW = vp.width / 2;
303
+ const halfH = vp.height / 2;
304
+ const hudTop = 1 - (2 * hud.top) / vp.height;
305
+ const hudLeft = -1 + (2 * hudLeftPx) / vp.width;
306
+ const hudRight = -1 + (2 * hud.rightLeft) / vp.width;
307
+ const hudRightBottom = 1 - (2 * hud.rightBottom) / vp.height;
308
+ const lens = 2 * Math.tan((camera.fov * Math.PI) / 360);
309
+ const grow = Math.max(1, nameMinPx / ((nameHeight / lens) * vp.height));
310
+ toCard();
311
+ let n = 0;
312
+ let drawnNow = false;
313
+ for (let i = 0; i < tags.length; i++) {
314
+ const t = tags[i];
315
+ const T = t.T;
316
+ const dx = t.x - cx;
317
+ const dy = t.y - cy;
318
+ const dz = t.z - cz;
319
+ const d = (t.d = Math.sqrt(dx * dx + dy * dy + dz * dz));
320
+ t.want = show && t.land === sp.id ? sstep(T[1] * 0.6, T[1], d) * (1 - sstep(T[0] * 0.72, T[0], d)) : 0;
321
+ }
322
+ if (show) {
323
+ sortTags();
324
+ for (let i = 0; i < tags.length; i++) {
325
+ const t = tags[i];
326
+ if (t.want < 0.02) continue;
327
+ _v.set(t.x, t.y, t.z).project(camera);
328
+ const tall = (2 * nameHeight * t.T[3] * grow) / lens;
329
+ const half = (nameHeight * t.T[3] * grow * t.tw * TEXT_W) / 96 / (lens * asp);
330
+ if (
331
+ _v.z > 1 ||
332
+ Math.abs(_v.x) > 1.1 ||
333
+ Math.abs(_v.y) > 1.1 ||
334
+ _v.y + tall > hudTop ||
335
+ (_v.x < hudLeft && _v.y > -0.25) ||
336
+ (_v.x + half > hudRight && _v.y + tall > hudRightBottom)
337
+ ) {
338
+ t.want = 0;
339
+ continue;
340
+ }
341
+ if (t.pr >= 2 && t.d > 120 && isHidden(t, sp)) {
342
+ t.want = 0;
343
+ continue;
344
+ }
345
+ const bx0 = (_v.x - half + 1) * halfW;
346
+ const by0 = (1 - (_v.y + tall)) * halfH;
347
+ const bx1 = (_v.x + half + 1) * halfW;
348
+ const by1 = (1 - _v.y) * halfH;
349
+ let ok = n < maxVisible && !isBlocked(bx0, by0, bx1, by1);
350
+ for (let j = 0; j < n && ok; j++) {
351
+ if (Math.abs(tagBox[j * 2] - _v.x) * Math.max(asp, 0.9) < 0.36 * grow && Math.abs(tagBox[j * 2 + 1] - _v.y) < 0.11 * grow) {
352
+ ok = false;
353
+ }
354
+ }
355
+ if (!ok) {
356
+ t.want = 0;
357
+ continue;
358
+ }
359
+ tagBox[n * 2] = _v.x;
360
+ tagBox[n * 2 + 1] = _v.y;
361
+ n++;
362
+ if (!t.onCard) {
363
+ t.want = 0;
364
+ if (!t.drawn && !drawnNow) {
365
+ drawTag(t);
366
+ drawnNow = true;
367
+ }
368
+ }
369
+ }
370
+ }
371
+ const lift = 1 + dayLift * (1 - getNight());
372
+ const k = Math.min(1, dt * 5);
373
+ const fit = clamp(asp / 0.95, 0.72, 1);
374
+ for (let i = 0; i < tags.length; i++) {
375
+ const t = tags[i];
376
+ t.a += (t.want - t.a) * k;
377
+ const vis = t.a > 0.02;
378
+ if (t.sp.visible !== vis) t.sp.visible = vis;
379
+ if (vis) {
380
+ const h = nameHeight * t.T[3] * fit * grow;
381
+ t.sp.material.opacity = t.a;
382
+ t.sp.material.color.setScalar(lift);
383
+ t.sp.position.set(t.x, t.y, t.z);
384
+ t.sp.scale.set((h * 512) / 96, h, 1);
385
+ }
386
+ }
387
+ }
388
+
389
+ return {
390
+ tags,
391
+ update,
392
+ refresh() {
393
+ if (listed) listUnnamed();
394
+ },
395
+ dispose() {
396
+ for (let i = 0; i < tags.length; i++) {
397
+ tags[i].sp.material.map?.dispose();
398
+ tags[i].sp.material.dispose();
399
+ tags[i].sp.parent?.remove(tags[i].sp);
400
+ }
401
+ tags.length = 0;
402
+ named.clear();
403
+ unnamed.length = 0;
404
+ drawnLast = null;
405
+ listed = false;
406
+ },
407
+ };
408
+ }
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Offscreen 3D portrait studio for rendering character and creature headshots to cached image data
3
+ * URLs over a soft radial studio backdrop. Preserves and restores the actor's scene parent,
4
+ * transform, visibility, LOD flags, and renderer target/clear state cleanly.
5
+ * @module
6
+ */
7
+ import * as THREE from 'three';
8
+
9
+ /**
10
+ * Default radial backdrop gradient `[centreColor, edgeColor]` for studio portraits.
11
+ * @type {readonly [string, string]}
12
+ */
13
+ export const DEFAULT_PORTRAIT_GROUND = Object.freeze(['#d6d0c6', '#8e8984']);
14
+
15
+ /**
16
+ * Flips WebGL bottom-up linear premultiplied RGBA pixels into top-down sRGB `Uint8ClampedArray`
17
+ * data, returning the count of visible (`alpha > 8`) pixels.
18
+ *
19
+ * @param {Uint8Array} pixels Raw bottom-up WebGL readback RGBA bytes (`size * size * 4`).
20
+ * @param {number} size Square texture side in pixels.
21
+ * @param {Uint8ClampedArray} out Target top-down sRGB RGBA buffer (`size * size * 4`).
22
+ * @param {object} [options]
23
+ * @param {number} [options.exposureBoost=1.45] Linear gain before gamma encoding.
24
+ * @param {number} [options.gamma=2.2] Display gamma exponent.
25
+ * @returns {number} Number of pixels with `alpha > 8`.
26
+ */
27
+ export function convertPortraitPixels(pixels, size, out, { exposureBoost = 1.45, gamma = 2.2 } = {}) {
28
+ let lit = 0;
29
+ const invGamma = 1 / gamma;
30
+ for (let y = 0; y < size; y++) {
31
+ for (let x = 0; x < size; x++) {
32
+ const src = ((size - 1 - y) * size + x) * 4;
33
+ const dst = (y * size + x) * 4;
34
+ const alpha = pixels[src + 3];
35
+ if (alpha > 8) lit++;
36
+ if (alpha) {
37
+ for (let k = 0; k < 3; k++) {
38
+ out[dst + k] = 255 * Math.pow(Math.min(1, (pixels[src + k] / alpha) * exposureBoost), invGamma);
39
+ }
40
+ }
41
+ out[dst + 3] = alpha;
42
+ }
43
+ }
44
+ return lit;
45
+ }
46
+
47
+ /**
48
+ * Default humanoid portrait framing targeting `actor.head` in local space.
49
+ *
50
+ * @param {object} actor
51
+ * @param {THREE.PerspectiveCamera} camera
52
+ * @param {THREE.Vector3} eyeScratch
53
+ * @param {THREE.Vector3} lookScratch
54
+ */
55
+ function defaultFrameActor(actor, camera, eyeScratch, lookScratch) {
56
+ eyeScratch.set(0.37, 0.03, 0.74);
57
+ lookScratch.set(0, 0.125, 0.012);
58
+ camera.position.copy(actor.head.localToWorld(eyeScratch));
59
+ camera.lookAt(actor.head.localToWorld(lookScratch));
60
+ }
61
+
62
+ /**
63
+ * Creates a reusable offscreen 3D portrait studio.
64
+ *
65
+ * @param {object} options
66
+ * @param {THREE.WebGLRenderer} options.renderer Active WebGL renderer.
67
+ * @param {number} [options.size=168] Portrait width and height in pixels.
68
+ * @param {number} [options.samples=4] MSAA sample count for the offscreen render target.
69
+ * @param {readonly [string, string]} [options.ground=DEFAULT_PORTRAIT_GROUND] Radial backdrop gradient stops.
70
+ * @param {string} [options.filter='saturate(0.72) contrast(0.94) blur(0.35px)'] Canvas 2D compositing filter.
71
+ * @param {string} [options.format='image/webp'] Output data URL MIME type.
72
+ * @param {number} [options.quality=0.88] Encoder quality (`0..1`).
73
+ * @param {number} [options.minLitShare=0.04] Minimum fraction of visible pixels required to accept a portrait.
74
+ * @param {number} [options.exposureBoost=1.45] Linear brightness boost before gamma encoding.
75
+ * @param {number} [options.gamma=2.2] Gamma exponent.
76
+ * @param {(actor: object, camera: THREE.PerspectiveCamera) => boolean | void} [options.frameActor] Optional custom framing hook; return `true` if handled, else falls back to `actor.head`.
77
+ * @param {(actor: object) => void} [options.raiseActor] Optional hook ensuring `actor`'s 3D rig is built before rendering.
78
+ * @param {object} [options.host=globalThis] Host exposing `document`.
79
+ * @returns {{ renderPixels: (actor: object) => Uint8Array, renderDataUrl: (actor: object) => string,
80
+ * getCached: (id: string, actor: object | null) => string, clearCache: () => void, dispose: () => void }}
81
+ */
82
+ export function createPortraitStudio({
83
+ renderer,
84
+ size = 168,
85
+ samples = 4,
86
+ ground = DEFAULT_PORTRAIT_GROUND,
87
+ filter = 'saturate(0.72) contrast(0.94) blur(0.35px)',
88
+ format = 'image/webp',
89
+ quality = 0.88,
90
+ minLitShare = 0.04,
91
+ exposureBoost = 1.45,
92
+ gamma = 2.2,
93
+ frameActor,
94
+ raiseActor,
95
+ host = globalThis,
96
+ }) {
97
+ const rendered = new Map();
98
+ const savedPos = new THREE.Vector3();
99
+ const savedQuat = new THREE.Quaternion();
100
+ const savedClear = new THREE.Color();
101
+ const eyeScratch = new THREE.Vector3();
102
+ const lookScratch = new THREE.Vector3();
103
+ let studio = null;
104
+
105
+ function ensureStudio() {
106
+ if (studio) return studio;
107
+ const scene = new THREE.Scene();
108
+ const camera = new THREE.PerspectiveCamera(20, 1, 0.05, 80);
109
+ const key = new THREE.DirectionalLight(0xfff0de, 2.2);
110
+ const rim = new THREE.DirectionalLight(0xc8d8ff, 0.9);
111
+ key.position.set(-1.3, 1.6, 2.3);
112
+ rim.position.set(1.6, 1.3, -2);
113
+ scene.add(new THREE.HemisphereLight(0xe4e6ee, 0x4a4038, 1.7), key, rim);
114
+ camera.layers.enable(1);
115
+ studio = { scene, camera, target: new THREE.WebGLRenderTarget(size, size, { samples }) };
116
+ return studio;
117
+ }
118
+
119
+ function renderPixels(actor) {
120
+ const { scene, camera, target } = ensureStudio();
121
+ raiseActor?.(actor);
122
+ const { group: g, hi, lo } = actor;
123
+ const parent = g.parent;
124
+ const visible = g.visible;
125
+ savedPos.copy(g.position);
126
+ savedQuat.copy(g.quaternion);
127
+ const showHi = hi?.visible;
128
+ const showLo = lo?.visible;
129
+ const previousTarget = renderer.getRenderTarget();
130
+ renderer.getClearColor(savedClear);
131
+ const alpha = renderer.getClearAlpha();
132
+ const pixels = new Uint8Array(size * size * 4);
133
+ try {
134
+ scene.add(g);
135
+ g.visible = true;
136
+ g.position.set(0, 0, 0);
137
+ g.quaternion.identity();
138
+ if (hi) hi.visible = true;
139
+ if (lo) lo.visible = false;
140
+ g.updateMatrixWorld(true);
141
+ if (!frameActor?.(actor, camera)) defaultFrameActor(actor, camera, eyeScratch, lookScratch);
142
+ renderer.setRenderTarget(target);
143
+ renderer.setClearColor(0x000000, 0);
144
+ renderer.clear();
145
+ renderer.render(scene, camera);
146
+ renderer.readRenderTargetPixels(target, 0, 0, size, size, pixels);
147
+ } finally {
148
+ if (parent) parent.add(g);
149
+ else scene.remove(g);
150
+ g.visible = visible;
151
+ g.position.copy(savedPos);
152
+ g.quaternion.copy(savedQuat);
153
+ if (hi) hi.visible = showHi;
154
+ if (lo) lo.visible = showLo;
155
+ g.updateMatrixWorld(true);
156
+ renderer.setRenderTarget(previousTarget);
157
+ renderer.setClearColor(savedClear, alpha);
158
+ }
159
+ return pixels;
160
+ }
161
+
162
+ function compositeOnGround(figureCanvas) {
163
+ const canvas = host.document.createElement('canvas');
164
+ canvas.width = canvas.height = size;
165
+ const ctx = canvas.getContext('2d');
166
+ const grad = ctx.createRadialGradient(size * 0.42, size * 0.36, size * 0.06, size * 0.5, size * 0.5, size * 0.74);
167
+ grad.addColorStop(0, ground[0]);
168
+ grad.addColorStop(1, ground[1]);
169
+ ctx.fillStyle = grad;
170
+ ctx.fillRect(0, 0, size, size);
171
+ if (filter) ctx.filter = filter;
172
+ ctx.drawImage(figureCanvas, 0, 0);
173
+ return canvas.toDataURL(format, quality);
174
+ }
175
+
176
+ function renderDataUrl(actor) {
177
+ const pixels = renderPixels(actor);
178
+ const canvas = host.document.createElement('canvas');
179
+ canvas.width = canvas.height = size;
180
+ const ctx = canvas.getContext('2d');
181
+ const image = ctx.createImageData(size, size);
182
+ const lit = convertPortraitPixels(pixels, size, image.data, { exposureBoost, gamma });
183
+ if (lit <= size * size * minLitShare) return '';
184
+ ctx.putImageData(image, 0, 0);
185
+ return compositeOnGround(canvas);
186
+ }
187
+
188
+ function getCached(id, actor) {
189
+ if (rendered.has(id)) return rendered.get(id);
190
+ if (!actor) return '';
191
+ try {
192
+ const url = renderDataUrl(actor);
193
+ if (url) rendered.set(id, url);
194
+ return url;
195
+ } catch {
196
+ return '';
197
+ }
198
+ }
199
+
200
+ function dispose() {
201
+ studio?.target?.dispose();
202
+ studio = null;
203
+ rendered.clear();
204
+ }
205
+
206
+ return {
207
+ renderPixels,
208
+ renderDataUrl,
209
+ getCached,
210
+ clearCache: () => rendered.clear(),
211
+ dispose,
212
+ };
213
+ }
@@ -38,6 +38,9 @@ function createDefaultFoliageMaterial(roughness) {
38
38
  * @param {boolean} [options.castShadow=true] - Whether each instanced mesh casts shadows.
39
39
  * @param {boolean} [options.receiveShadow=true] - Whether each instanced mesh receives shadows.
40
40
  * @param {boolean} [options.stopWhenFull=false] - Stop sampling early once every variant bucket is full.
41
+ * @param {((color: THREE.Color, x: number, y: number, z: number, index: number, bucket: number) => void) | null} [options.colorAt=null]
42
+ * - Writes each placed instance's colour into `color` (from where it stands, its index in its variant and the variant),
43
+ * multiplied into the material's colour; without it the instances carry no colour of their own.
41
44
  * @returns {{ meshes: THREE.InstancedMesh[], material: THREE.Material, total: number, dispose: () => void }}
42
45
  */
43
46
  export function scatterInstances({
@@ -55,6 +58,7 @@ export function scatterInstances({
55
58
  castShadow = true,
56
59
  receiveShadow = true,
57
60
  stopWhenFull = false,
61
+ colorAt = null,
58
62
  } = {}) {
59
63
  if (!Array.isArray(geometries) || geometries.length === 0) {
60
64
  throw new RangeError('geometries must be a non-empty array of BufferGeometry');
@@ -74,6 +78,7 @@ export function scatterInstances({
74
78
  stopWhenFull,
75
79
  });
76
80
 
81
+ const color = new THREE.Color();
77
82
  const meshes = geometries.map((geometry, index) => {
78
83
  const { count, matrices } = plan.buckets[index];
79
84
  const mesh = new THREE.InstancedMesh(geometry, mat, 0);
@@ -81,6 +86,13 @@ export function scatterInstances({
81
86
  mesh.count = count;
82
87
  mesh.castShadow = castShadow;
83
88
  mesh.receiveShadow = receiveShadow;
89
+ if (colorAt && count > 0) {
90
+ mesh.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array((matrices.length / 16) * 3), 3);
91
+ for (let i = 0; i < count; i++) {
92
+ colorAt(color, matrices[i * 16 + 12], matrices[i * 16 + 13], matrices[i * 16 + 14], i, index);
93
+ mesh.setColorAt(i, color);
94
+ }
95
+ }
84
96
  if (count > 0) mesh.computeBoundingSphere();
85
97
  if (parent) parent.add(mesh);
86
98
  return mesh;