roamwright 0.61.16 → 0.61.18

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.
Files changed (49) hide show
  1. package/README.md +25 -24
  2. package/examples/land-features.js +130 -9
  3. package/examples/land.html +2 -1
  4. package/examples/land.js +17 -2
  5. package/examples/ruins.html +3 -2
  6. package/examples/ruins.js +184 -37
  7. package/examples/world-map.html +162 -0
  8. package/examples/world-map.js +475 -0
  9. package/geometry/farm-props.js +59 -0
  10. package/geometry/field-map.js +147 -0
  11. package/geometry/instances.js +40 -0
  12. package/geometry/plant-tuft.js +138 -0
  13. package/geometry/ruins-breach.js +329 -0
  14. package/geometry/ruins-crater.js +269 -0
  15. package/geometry/ruins-masonry.js +323 -0
  16. package/geometry/ruins-walls.js +272 -0
  17. package/geometry/strata-mesa.js +114 -0
  18. package/geometry/strata-rocks.js +73 -2
  19. package/index.js +109 -1
  20. package/package.json +1 -1
  21. package/rendering/contact-shadows.js +56 -0
  22. package/rendering/crowd-lifecycle.js +80 -0
  23. package/rendering/farm-plough.js +145 -0
  24. package/rendering/map-glyphs.js +494 -0
  25. package/rendering/map-input.js +143 -0
  26. package/rendering/map-labels.js +181 -0
  27. package/rendering/map-relief.js +330 -0
  28. package/rendering/map-signs.js +124 -0
  29. package/rendering/place-names.js +408 -0
  30. package/rendering/plant-tuft.js +190 -0
  31. package/rendering/portrait-studio.js +213 -0
  32. package/rendering/ruins-fittings.js +199 -0
  33. package/rendering/ruins-mound.js +103 -0
  34. package/rendering/screen-pick.js +75 -0
  35. package/runtime/build-freshness.js +133 -0
  36. package/runtime/compass-strip.js +232 -0
  37. package/runtime/context-lost.js +108 -0
  38. package/runtime/doorways.js +98 -0
  39. package/runtime/hud-frame.js +74 -0
  40. package/runtime/map-relief.js +236 -0
  41. package/runtime/map-spot.js +120 -0
  42. package/runtime/map-view.js +229 -0
  43. package/runtime/panel-shell.js +90 -0
  44. package/runtime/relation-graph.js +163 -0
  45. package/runtime/stage-frame.js +263 -0
  46. package/runtime/url-router.js +162 -0
  47. package/runtime/way-back.js +71 -0
  48. package/runtime/whereabouts.js +210 -0
  49. package/runtime/world-controls.js +265 -0
@@ -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
+ }
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Architectural fittings and light/water decals for ruins and courtyards: additive radial ground
3
+ * light pools, dark still water basins, lit brass lamp stands and iron wall lanterns.
4
+ * @module
5
+ */
6
+
7
+ import * as THREE from 'three';
8
+ import { createUnitShapes } from '../geometry/primitives.js';
9
+ import { buildLampStandGeometry, buildWallLanternGeometry } from '../geometry/ruins-masonry.js';
10
+ import { falloffAt, pixelTexture } from './textures.js';
11
+
12
+ /** Default parameters for additive radial ground light pools built by {@link addLightPool}. */
13
+ export const LIGHT_POOL = Object.freeze({
14
+ size: 64,
15
+ falloff: Object.freeze([Object.freeze([0, 1]), Object.freeze([0.35, 0.42]), Object.freeze([1, 0])]),
16
+ hex: 0xffb060,
17
+ strength: 0.75,
18
+ lift: 0.04,
19
+ renderOrder: 4,
20
+ });
21
+
22
+ let defaultPoolTexture = null;
23
+ let fallbackShapes = null;
24
+ const defaultShapes = () => (fallbackShapes ??= createUnitShapes());
25
+
26
+ /**
27
+ * Create a radial white alpha-falloff texture for additive ground light pools.
28
+ *
29
+ * @param {object} [options]
30
+ * @param {number} [options.size=LIGHT_POOL.size] - Texture width and height in pixels.
31
+ * @param {readonly (readonly [number, number])[]} [options.falloff=LIGHT_POOL.falloff] - Radial `[t, alpha]` control stops.
32
+ * @returns {THREE.CanvasTexture}
33
+ */
34
+ export function createLightPoolTexture({ size = LIGHT_POOL.size, falloff = LIGHT_POOL.falloff } = {}) {
35
+ return pixelTexture(
36
+ size,
37
+ (u, v, out) => {
38
+ out[0] = out[1] = out[2] = 255;
39
+ out[3] = 255 * falloffAt(falloff, (Math.hypot(u - 0.5, v - 0.5) * size - 1) / (size / 2 - 2));
40
+ },
41
+ { clamp: true },
42
+ );
43
+ }
44
+
45
+ /**
46
+ * Place a soft additive pool of warm light lying flat on the ground at `(x, y, z)` so unlit street
47
+ * lanterns read warmly without extra dynamic point lights.
48
+ *
49
+ * @param {THREE.Object3D} group - Destination scene or group.
50
+ * @param {number} x - World X position in metres.
51
+ * @param {number} y - Ground elevation in metres.
52
+ * @param {number} z - World Z position in metres.
53
+ * @param {number} radius - Pool radius in metres.
54
+ * @param {object} [options]
55
+ * @param {number} [options.hex=LIGHT_POOL.hex] - Light pool sRGB colour.
56
+ * @param {number} [options.strength=LIGHT_POOL.strength] - Intensity multiplier.
57
+ * @param {number} [options.lift=LIGHT_POOL.lift] - Vertical offset above ground in metres.
58
+ * @param {number} [options.renderOrder=LIGHT_POOL.renderOrder] - Three.js `renderOrder`.
59
+ * @param {boolean} [options.fogFades=false] - Attach `{ FOG_FADES: '' }` define for worlds with custom haze fading.
60
+ * @param {THREE.Texture} [options.texture] - Optional prebuilt radial glow texture.
61
+ * @returns {THREE.Mesh}
62
+ */
63
+ export function addLightPool(group, x, y, z, radius, options = {}) {
64
+ const {
65
+ hex = LIGHT_POOL.hex,
66
+ strength = LIGHT_POOL.strength,
67
+ lift = LIGHT_POOL.lift,
68
+ renderOrder = LIGHT_POOL.renderOrder,
69
+ fogFades = false,
70
+ } = options;
71
+ const map = options.texture ?? (defaultPoolTexture ??= createLightPoolTexture());
72
+ const material = new THREE.MeshBasicMaterial({
73
+ map,
74
+ color: new THREE.Color(hex).multiplyScalar(strength),
75
+ blending: THREE.AdditiveBlending,
76
+ depthWrite: false,
77
+ transparent: true,
78
+ });
79
+ if (fogFades) material.defines = { FOG_FADES: '' };
80
+ const pool = new THREE.Mesh(new THREE.PlaneGeometry(1, 1).rotateX(-Math.PI / 2), material);
81
+ pool.position.set(x, y + lift, z);
82
+ pool.scale.set(radius * 2, 1, radius * 2);
83
+ pool.renderOrder = renderOrder;
84
+ group.add(pool);
85
+ return pool;
86
+ }
87
+
88
+ /**
89
+ * Add a dark, glossy oval or circular pool of still water lying in a courtyard basin or hollow.
90
+ *
91
+ * @param {THREE.Object3D} group - Destination scene or group.
92
+ * @param {object} options
93
+ * @param {{ x: number, z: number }} [options.origin={ x: 0, z: 0 }] - Local frame world origin.
94
+ * @param {number} [options.x=0] - Local X position in metres.
95
+ * @param {number} [options.y=0] - Water surface elevation in metres.
96
+ * @param {number} [options.z=0] - Local Z position in metres.
97
+ * @param {number} [options.width=2] - Pool width in metres.
98
+ * @param {number} [options.depth=2] - Pool depth in metres.
99
+ * @param {number} [options.yaw=0] - Rotation around Y in radians.
100
+ * @param {number} [options.color=0x1c2a2a] - Water base sRGB colour.
101
+ * @param {number} [options.roughness=0.05] - Surface roughness.
102
+ * @param {number} [options.metalness=0.4] - Surface reflectivity factor.
103
+ * @param {number} [options.opacity=0.88] - Water opacity.
104
+ * @param {number} [options.segments=20] - Perimeter circle segments.
105
+ * @returns {THREE.Mesh}
106
+ */
107
+ export function addStillPool(group, options = {}) {
108
+ const {
109
+ origin = { x: 0, z: 0 },
110
+ x = 0,
111
+ y = 0,
112
+ z = 0,
113
+ width = 2,
114
+ depth = 2,
115
+ yaw = 0,
116
+ color = 0x1c2a2a,
117
+ roughness = 0.05,
118
+ metalness = 0.4,
119
+ opacity = 0.88,
120
+ segments = 20,
121
+ } = options;
122
+ const water = new THREE.Mesh(
123
+ new THREE.CircleGeometry(0.5, segments).rotateX(-Math.PI / 2),
124
+ new THREE.MeshStandardMaterial({ color, roughness, metalness, transparent: true, opacity }),
125
+ );
126
+ water.position.set(origin.x + x, y, origin.z + z);
127
+ water.scale.set(width, 1, depth);
128
+ water.rotation.y = yaw;
129
+ group.add(water);
130
+ return water;
131
+ }
132
+
133
+ /**
134
+ * Build a tall brass oil-lamp stand and invoke an optional flame callback at its wick.
135
+ *
136
+ * @param {{ trim: import('../geometry/builder.js').GB, cloth: import('../geometry/builder.js').GB }} kit - Destination builders.
137
+ * @param {object} [options]
138
+ * @param {number} [options.x=0] - Local X position in metres.
139
+ * @param {number} [options.y=0] - Base elevation in metres.
140
+ * @param {number} [options.z=0] - Local Z position in metres.
141
+ * @param {number} [options.height=1.25] - Stand height in metres.
142
+ * @param {object} [options.shapes] - Unit shapes (`createUnitShapes()`).
143
+ * @param {Function} [options.transform] - Transform matrix helper (`TRS`).
144
+ * @param {((x: number, y: number, z: number, size: number) => void) | null} [options.onFlame=null] - Callback receiving the wick position and flame size.
145
+ * @returns {[number, number, number]} Local wick position `[x, y, z]`.
146
+ */
147
+ export function addLampStand(kit, options = {}) {
148
+ const wick = buildLampStandGeometry(kit, options);
149
+ options.onFlame?.(wick[0], wick[1], wick[2], 0.1);
150
+ return wick;
151
+ }
152
+
153
+ /**
154
+ * Build an iron bracketed wall lantern, place its glowing horn panes, emit an optional fire/light
155
+ * site callback, and cast a soft ground light pool below it.
156
+ *
157
+ * @param {{ trim: import('../geometry/builder.js').GB }} kit - Destination builder container.
158
+ * @param {object} options
159
+ * @param {THREE.Object3D} options.group - Group receiving the glowing lantern panes and ground light pool.
160
+ * @param {{ x: number, z: number }} [options.origin={ x: 0, z: 0 }] - Local frame world origin.
161
+ * @param {number} [options.x=0] - Wall anchor local X in metres.
162
+ * @param {number} [options.y=2.5] - Bracket height in metres.
163
+ * @param {number} [options.z=0] - Wall anchor local Z in metres.
164
+ * @param {number} [options.out=0] - Outward bearing in radians.
165
+ * @param {number} [options.ground=0] - Ground elevation below the lantern for its light pool.
166
+ * @param {number} [options.poolRadius=5] - Ground light pool radius in metres.
167
+ * @param {boolean} [options.fogFades=false] - Forwarded to {@link addLightPool}.
168
+ * @param {object} [options.shapes] - Unit shapes (`createUnitShapes()`).
169
+ * @param {Function} [options.transform] - Transform matrix helper (`TRS`).
170
+ * @param {Function} [options.stickFn] - Tapered rod helper (`stick`).
171
+ * @param {((geo: THREE.BufferGeometry, hex: number, boost: number, group: THREE.Object3D) => THREE.Mesh) | null} [options.makeGlowMesh=null] - Custom emissive mesh factory.
172
+ * @param {((x: number, y: number, z: number) => void) | null} [options.onSite=null] - Optional callback receiving world lantern flame coordinates.
173
+ * @returns {{ horn: THREE.Mesh, pool: THREE.Mesh, lantern: { x: number, y: number, z: number } }}
174
+ */
175
+ export function addWallLantern(kit, options) {
176
+ const {
177
+ group,
178
+ origin = { x: 0, z: 0 },
179
+ ground = 0,
180
+ poolRadius = 5,
181
+ fogFades = false,
182
+ shapes = defaultShapes(),
183
+ makeGlowMesh = null,
184
+ onSite = null,
185
+ } = options;
186
+ const lantern = buildWallLanternGeometry(kit, { ...options, shapes });
187
+ const horn = makeGlowMesh
188
+ ? makeGlowMesh(shapes.cyl6, 0xffb860, 1.15, group)
189
+ : (() => {
190
+ const m = new THREE.Mesh(shapes.cyl6, new THREE.MeshBasicMaterial({ color: new THREE.Color(0xffb860).multiplyScalar(1.15) }));
191
+ group.add(m);
192
+ return m;
193
+ })();
194
+ horn.position.set(origin.x + lantern.x, lantern.y - 0.135, origin.z + lantern.z);
195
+ horn.scale.set(0.14, 0.27, 0.14);
196
+ onSite?.(origin.x + lantern.x, lantern.y - 0.05, origin.z + lantern.z);
197
+ const pool = addLightPool(group, origin.x + lantern.x, ground, origin.z + lantern.z, poolRadius, { fogFades });
198
+ return { horn, pool, lantern };
199
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Two-LOD async mound-ruins streamer: raises near (full walls and sherds) and far (lighter walls
3
+ * alone) ruin meshes on approach via a worker pass or synchronous builder, warms their shaders and
4
+ * hands them to the GPU before showing them, aborting cleanly if the parent space unloads mid-build.
5
+ * @module
6
+ */
7
+
8
+ import * as THREE from 'three';
9
+
10
+ /** Default LOD distances (metres beyond each mound's radius) and seed progression for {@link registerMoundRuins}. */
11
+ export const MOUND_RUINS_LOD = Object.freeze({
12
+ nearRange: 300,
13
+ seenRange: 1400,
14
+ seedBase: 5101,
15
+ seedStep: 37,
16
+ });
17
+
18
+ /**
19
+ * Asynchronously build and attach one mound's near or far ruins group into `parent`, warming
20
+ * shaders and handing meshes to the card before revealing them.
21
+ *
22
+ * @param {object} options
23
+ * @param {THREE.Object3D} options.parent - Parent group owning the streamed ruins.
24
+ * @param {{ x: number, z: number, r: number, h: number }} options.mound - Mound descriptor in metres.
25
+ * @param {number} options.seed - Deterministic seed for this mound.
26
+ * @param {boolean} options.far - True for the lighter distant wall mesh alone.
27
+ * @param {(input: { m: { x: number, z: number, r: number, h: number }, seed: number, far: boolean }) => Promise<{ walls: { index: ArrayLike<number> }, sherds?: { position: ArrayLike<number> } | null }>} options.build - Async builder returning `{ walls, sherds }` arrays.
28
+ * @param {(walls: object, far: boolean) => THREE.Object3D} options.buildWallMesh - Converts `walls` arrays to a mesh.
29
+ * @param {(sherds: object, holder: THREE.Group) => void} [options.buildSherdMesh] - Optional converter adding `sherds` to `holder`.
30
+ * @param {(holder: THREE.Group) => Promise<void>} [options.warmShaders] - Optional async shader warmup hook.
31
+ * @param {() => boolean} [options.anyFrameDrawn] - Predicate indicating whether the main loop has drawn a frame yet.
32
+ * @param {(meshes: THREE.Object3D[]) => Promise<void>} [options.handToCard] - Optional async GPU upload handover hook.
33
+ * @returns {THREE.Group} Static group attached to `parent` immediately; meshes appear once ready.
34
+ */
35
+ export function raiseMoundRuins({
36
+ parent,
37
+ mound,
38
+ seed,
39
+ far,
40
+ build,
41
+ buildWallMesh,
42
+ buildSherdMesh = null,
43
+ warmShaders = null,
44
+ anyFrameDrawn = () => false,
45
+ handToCard = null,
46
+ }) {
47
+ const group = new THREE.Group();
48
+ const m = { x: mound.x, z: mound.z, r: mound.r, h: mound.h };
49
+ group.matrixAutoUpdate = false;
50
+ parent.add(group);
51
+ Promise.resolve(build({ m, seed, far })).then(async ({ walls, sherds }) => {
52
+ if (!group.parent) return;
53
+ const holder = new THREE.Group();
54
+ if (walls.index.length) holder.add(buildWallMesh(walls, far));
55
+ if (sherds?.position.length && buildSherdMesh) buildSherdMesh(sherds, holder);
56
+ const made = [...holder.children];
57
+ if (!made.length) return;
58
+ if (warmShaders) await warmShaders(holder);
59
+ if (!group.parent) return;
60
+ for (const mesh of made) {
61
+ mesh.visible = false;
62
+ group.add(mesh);
63
+ }
64
+ if (anyFrameDrawn() && handToCard) await handToCard(made);
65
+ if (!group.parent) return;
66
+ for (const mesh of made) mesh.visible = true;
67
+ });
68
+ return group;
69
+ }
70
+
71
+ /**
72
+ * Register near and far lazy `nearGroups` entries for every mound in `mounds` so ruins stream in
73
+ * only as the camera enters their view band.
74
+ *
75
+ * @param {Array<{ x: number, z: number, r: number, h: number }>} mounds - Mound descriptors.
76
+ * @param {object} options
77
+ * @param {Array<object>} options.nearGroups - Target `nearGroups` list read by `updateNearGroups`.
78
+ * @param {(mound: object, seed: number, far: boolean) => THREE.Group} options.raise - Builder invoked on first approach.
79
+ * @param {number} [options.nearRange=MOUND_RUINS_LOD.nearRange] - Metres beyond `mound.r` for full near detail.
80
+ * @param {number} [options.seenRange=MOUND_RUINS_LOD.seenRange] - Metres beyond `mound.r` for far detail.
81
+ * @param {number} [options.seedBase=MOUND_RUINS_LOD.seedBase] - First mound's seed.
82
+ * @param {number} [options.seedStep=MOUND_RUINS_LOD.seedStep] - Seed increment per mound.
83
+ */
84
+ export function registerMoundRuins(
85
+ mounds,
86
+ {
87
+ nearGroups,
88
+ raise,
89
+ nearRange = MOUND_RUINS_LOD.nearRange,
90
+ seenRange = MOUND_RUINS_LOD.seenRange,
91
+ seedBase = MOUND_RUINS_LOD.seedBase,
92
+ seedStep = MOUND_RUINS_LOD.seedStep,
93
+ },
94
+ ) {
95
+ mounds.forEach((mound, i) => {
96
+ const seed = seedBase + i * seedStep;
97
+ const near = mound.r + nearRange;
98
+ nearGroups.push(
99
+ { group: null, raise: () => raise(mound, seed, false), x: mound.x, z: mound.z, range: near },
100
+ { group: null, raise: () => raise(mound, seed, true), x: mound.x, z: mound.z, from: near, range: mound.r + seenRange },
101
+ );
102
+ });
103
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Screen-space 3D picking for visible character actors and floating place-name sprites.
3
+ * Zero per-frame allocations (reuses one scratch Vector3).
4
+ * @module
5
+ */
6
+ import * as THREE from 'three';
7
+
8
+ const _v = new THREE.Vector3();
9
+
10
+ /**
11
+ * Picks the nearest visible actor whose projected screen hitbox covers `(px, py)`.
12
+ *
13
+ * @template {{ x: number, y: number, z: number, dist: number, height: number, group: { visible: boolean } }} T
14
+ * @param {ReadonlyArray<T>} actors Candidate actors.
15
+ * @param {THREE.PerspectiveCamera} camera Active camera.
16
+ * @param {number} px Tap X in CSS pixels.
17
+ * @param {number} py Tap Y in CSS pixels.
18
+ * @param {number} viewportWidth Stage width in CSS pixels.
19
+ * @param {number} viewportHeight Stage height in CSS pixels.
20
+ * @param {number} [maxDistance=160] Maximum pick distance in metres.
21
+ * @returns {T | null}
22
+ */
23
+ export function pickScreenActor(actors, camera, px, py, viewportWidth, viewportHeight, maxDistance = 160) {
24
+ const proj = viewportHeight / (2 * Math.tan((camera.fov * Math.PI) / 360));
25
+ let best = null;
26
+ let bestDist = 1e9;
27
+ for (let i = 0; i < actors.length; i++) {
28
+ const a = actors[i];
29
+ if (!a.group.visible || a.dist > maxDistance) continue;
30
+ _v.set(a.x, a.y + a.height * 0.55, a.z).project(camera);
31
+ if (_v.z > 1) continue;
32
+ const sx = (_v.x * 0.5 + 0.5) * viewportWidth;
33
+ const sy = (-_v.y * 0.5 + 0.5) * viewportHeight;
34
+ const r = Math.max(30, ((a.height * 0.62) / a.dist) * proj);
35
+ if (Math.hypot(sx - px, sy - py) < r && a.dist < bestDist) {
36
+ bestDist = a.dist;
37
+ best = a;
38
+ }
39
+ }
40
+ return best;
41
+ }
42
+
43
+ /**
44
+ * Picks the nearest visible floating place-name tag sprite covering `(px, py)`.
45
+ *
46
+ * @template {{ x: number, y: number, z: number, d: number, a: number, tw: number, sp: { visible: boolean, scale: { x: number, y: number } } }} T
47
+ * @param {ReadonlyArray<T>} tags Candidate place-name tags.
48
+ * @param {THREE.PerspectiveCamera} camera Active camera.
49
+ * @param {number} px Tap X in CSS pixels.
50
+ * @param {number} py Tap Y in CSS pixels.
51
+ * @param {number} viewportWidth Stage width in CSS pixels.
52
+ * @param {number} viewportHeight Stage height in CSS pixels.
53
+ * @param {number} [minOpacity=0.3] Minimum tag alpha required to be clickable.
54
+ * @returns {T | null}
55
+ */
56
+ export function pickScreenTag(tags, camera, px, py, viewportWidth, viewportHeight, minOpacity = 0.3) {
57
+ const th = 2 * Math.tan((camera.fov * Math.PI) / 360);
58
+ let best = null;
59
+ let bestDist = 1e9;
60
+ for (let i = 0; i < tags.length; i++) {
61
+ const t = tags[i];
62
+ if (t.a < minOpacity || !t.sp.visible) continue;
63
+ _v.set(t.x, t.y, t.z).project(camera);
64
+ if (_v.z > 1) continue;
65
+ const sx = (_v.x * 0.5 + 0.5) * viewportWidth;
66
+ const sy = (-_v.y * 0.5 + 0.5) * viewportHeight;
67
+ const hp = (t.sp.scale.y / th) * viewportHeight;
68
+ const wp = Math.max(70, (t.sp.scale.x / th) * viewportHeight * t.tw + 20);
69
+ if (Math.abs(px - sx) < wp / 2 && py > sy - hp - 8 && py < sy + 10 && t.d < bestDist) {
70
+ bestDist = t.d;
71
+ best = t;
72
+ }
73
+ }
74
+ return best;
75
+ }