roamwright 0.54.0 → 0.56.0
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.
- package/examples/animals.js +27 -15
- package/examples/crowds.js +28 -18
- package/examples/effects.js +13 -11
- package/examples/figure-motion.js +17 -5
- package/examples/figure.js +12 -8
- package/examples/fliers.js +16 -12
- package/examples/fortification.js +31 -18
- package/examples/house-kit.js +17 -10
- package/examples/island.js +25 -12
- package/examples/land.js +14 -8
- package/examples/props-and-plants.js +21 -32
- package/examples/rooms.js +2 -2
- package/examples/ships.js +33 -15
- package/examples/small-world-land.js +3 -3
- package/examples/small-world-life.js +13 -5
- package/examples/small-world-town.js +8 -11
- package/examples/small-world.js +26 -19
- package/examples/soundscape.js +18 -18
- package/examples/stage-kits.js +5 -133
- package/examples/stage.js +1 -324
- package/examples/towns.js +25 -18
- package/examples/viaduct-landscape.js +1 -1
- package/examples/viaduct.js +3 -4
- package/geometry/builder.js +8 -18
- package/geometry/plant-broadleaf.js +10 -4
- package/geometry/plant-trees.js +15 -9
- package/geometry/still-mesh.js +35 -0
- package/index.js +11 -1
- package/motion/cast-actors.js +379 -0
- package/motion/cast-manager.js +321 -0
- package/motion/figure-mount.js +1 -0
- package/package.json +20 -1
- package/rendering/cast-stage.js +299 -0
- package/rendering/crowd-system.js +239 -0
- package/rendering/daylight-sky.js +212 -0
- package/rendering/house-kit-meshes.js +65 -16
- package/rendering/nameplate-groups.js +84 -0
- package/rendering/nameplates.js +386 -0
- package/rendering/orbit-camera.js +216 -0
- package/rendering/water-simple.js +112 -0
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cast manager for a procedural world: enlists actors and multi-home echoes, manages home
|
|
3
|
+
* placement across ground anchors, interior spaces and moving frames, coordinates worker
|
|
4
|
+
* prefetching and LOD switching, emits contact shadows, and drives the per-frame actor loop.
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
import { createHash } from '../math/random.js';
|
|
8
|
+
import { withinDetailRange } from '../rendering/detail-range.js';
|
|
9
|
+
import { pending } from '../runtime/figure-orders.js';
|
|
10
|
+
import { actorNameSeed, createCastActor, homesOf, isActorInPlay, placeActorAtHome, placeCastActor, settleCastPose } from './cast-actors.js';
|
|
11
|
+
|
|
12
|
+
const DEFAULT_HASH = createHash(0);
|
|
13
|
+
const DEFAULT_ORDER_AHEAD = 40; // metres beyond sight distance to order worker bodies
|
|
14
|
+
const DEFAULT_SEEN_WITHIN = 230; // metres within which an outdoor actor is visible
|
|
15
|
+
const DEFAULT_SEEN_IN_SCENE = 420; // metres within which a scene cast member stays visible
|
|
16
|
+
const DEFAULT_BODY_RANGE = Object.freeze([18.8, 21.2]); // near-mesh enter/leave hysteresis (metres at unit lens)
|
|
17
|
+
const DEFAULT_NEAR_RAISE = 32; // metres at unit lens within which a near body is ordered/built
|
|
18
|
+
const DEFAULT_NEAR_DROP = 90; // metres at unit lens beyond which an idle near body is disposed
|
|
19
|
+
const DEFAULT_ORBIT_RISE = 9; // metres a circling flier rises and falls
|
|
20
|
+
|
|
21
|
+
const withGrip = def => ({ ...def, look: { ...def.look, grip: true } });
|
|
22
|
+
|
|
23
|
+
function createHeadlessStage() {
|
|
24
|
+
return {
|
|
25
|
+
standIn(look) {
|
|
26
|
+
const kind = look.kind || 'human',
|
|
27
|
+
size = look.h || 1;
|
|
28
|
+
return { group: { visible: false, scale: { x: size, y: size, z: size } }, kind, height: 1.9 * size };
|
|
29
|
+
},
|
|
30
|
+
orderActor() {},
|
|
31
|
+
orderCast: () => null,
|
|
32
|
+
releaseCast() {},
|
|
33
|
+
raiseActor(actor) {
|
|
34
|
+
actor.built = true;
|
|
35
|
+
},
|
|
36
|
+
raiseNear(actor) {
|
|
37
|
+
actor.nearBuilt = true;
|
|
38
|
+
},
|
|
39
|
+
dropNear(actor) {
|
|
40
|
+
actor.nearBuilt = false;
|
|
41
|
+
},
|
|
42
|
+
prepareCast: () => Promise.resolve(),
|
|
43
|
+
warmDefaultPrograms() {},
|
|
44
|
+
readyWorkerBodies() {},
|
|
45
|
+
buildVisibleActor(actor) {
|
|
46
|
+
actor.built = true;
|
|
47
|
+
},
|
|
48
|
+
buildNearBody(actor) {
|
|
49
|
+
actor.nearBuilt = true;
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Creates a world-scoped cast manager holding the actor dictionary (`actors`), dense array
|
|
56
|
+
* (`actorList`), and moving reference frames, with zero per-frame allocations in `updateActors`.
|
|
57
|
+
*
|
|
58
|
+
* @param {object} config
|
|
59
|
+
* @param {object} [config.stage] - Rendering/GPU staging controller (`createCastStage`), or a headless default.
|
|
60
|
+
* @param {{ position: { x: number, y: number, z: number } }} config.camera - Active world camera.
|
|
61
|
+
* @param {() => number} config.getElapsed - Returns elapsed world time (seconds).
|
|
62
|
+
* @param {() => number} [config.getDetailLens] - Returns current perspective magnification relative to the reference FOV.
|
|
63
|
+
* @param {() => string} [config.getSpaceId] - Returns the active space identifier.
|
|
64
|
+
* @param {(spaceId: string) => object} [config.getSpace] - Looks up a space descriptor by identifier.
|
|
65
|
+
* @param {(spaceId: string) => boolean} [config.isSpaceBuilt] - Reports whether a space has been built.
|
|
66
|
+
* @param {string} [config.worldSpaceId='world'] - Space identifier for outdoor ground homes.
|
|
67
|
+
* @param {(key: string) => any} [config.resolvePlace] - Resolves named place anchors referenced by homes.
|
|
68
|
+
* @param {(x: number, z: number) => number} [config.worldGround] - Samples ground elevation (metres) in `worldSpaceId`.
|
|
69
|
+
* @param {(x: number, y: number, salt?: number) => number} [config.hash] - Seeded 2D hash in `[0, 1)`.
|
|
70
|
+
* @param {number} [config.defaultRange=8] - Default nameplate reading distance (metres).
|
|
71
|
+
* @param {object} config.motion - Pose/locomotion callbacks from `createFigurePose` (`applyActorLinks`, `clearActorLinks`, `faceTo`, `newMove`, `poseActor`, `setAfoot`, `takePose`, `travel`).
|
|
72
|
+
* @param {((x: number, y: number, z: number, size: number, d2: number, intensityScale?: number) => void)|null} [config.onFootShade=null] - Contact shadow callback for visible grounded actors.
|
|
73
|
+
* @param {(actor: object) => string} [config.idlePoseOf] - Resting pose for an outdoor actor (`'idle'` by default).
|
|
74
|
+
* @param {object} [config.sight] - Distance and LOD thresholds (all in metres).
|
|
75
|
+
* @param {number} [config.sight.orderAhead=40] - Margin beyond visibility at which worker bodies are requested.
|
|
76
|
+
* @param {number} [config.sight.seenWithin=230] - Visibility radius for idle actors at home.
|
|
77
|
+
* @param {number} [config.sight.seenInScene=420] - Visibility radius for actors participating in a scene.
|
|
78
|
+
* @param {Record<string, number>} [config.sight.kindRanges] - Per-kind visibility radius overrides (metres).
|
|
79
|
+
* @param {readonly [number, number]} [config.sight.bodyRange=[18.8, 21.2]] - Near-mesh enter/leave hysteresis (metres at unit lens).
|
|
80
|
+
* @param {number} [config.sight.nearRaise=32] - Reach (metres at unit lens) within which near geometry is ordered/raised.
|
|
81
|
+
* @param {number} [config.sight.nearDrop=90] - Reach (metres at unit lens) beyond which idle near geometry is disposed.
|
|
82
|
+
* @param {number} [config.sight.orbitRise=9] - Vertical oscillation amplitude (metres) for orbiting frame homes.
|
|
83
|
+
* @param {object} [config.shadows] - Per-kind contact shadow categories.
|
|
84
|
+
* @param {Iterable<string>} [config.shadows.unshadedKinds] - Airborne/unshaded kinds omitted from ground contact shadows.
|
|
85
|
+
* @param {Iterable<string>} [config.shadows.wideFootKinds] - Large quadruped/beast kinds given a wider contact shadow footprint.
|
|
86
|
+
*/
|
|
87
|
+
export function createCastManager({
|
|
88
|
+
stage = createHeadlessStage(),
|
|
89
|
+
camera,
|
|
90
|
+
getElapsed,
|
|
91
|
+
getDetailLens = () => 1,
|
|
92
|
+
getSpaceId = () => 'world',
|
|
93
|
+
getSpace = () => null,
|
|
94
|
+
isSpaceBuilt = () => true,
|
|
95
|
+
worldSpaceId = 'world',
|
|
96
|
+
resolvePlace = () => null,
|
|
97
|
+
worldGround = () => 0,
|
|
98
|
+
hash = DEFAULT_HASH,
|
|
99
|
+
defaultRange = 8,
|
|
100
|
+
motion,
|
|
101
|
+
onFootShade = null,
|
|
102
|
+
idlePoseOf = () => 'idle',
|
|
103
|
+
sight = {},
|
|
104
|
+
shadows = {},
|
|
105
|
+
}) {
|
|
106
|
+
const actors = {},
|
|
107
|
+
actorList = [],
|
|
108
|
+
frames = {};
|
|
109
|
+
const orderAhead = sight.orderAhead ?? DEFAULT_ORDER_AHEAD,
|
|
110
|
+
seenWithin = sight.seenWithin ?? DEFAULT_SEEN_WITHIN,
|
|
111
|
+
seenInScene = sight.seenInScene ?? DEFAULT_SEEN_IN_SCENE,
|
|
112
|
+
kindRanges = sight.kindRanges ?? {},
|
|
113
|
+
bodyRange = sight.bodyRange ?? DEFAULT_BODY_RANGE,
|
|
114
|
+
nearRaise = sight.nearRaise ?? DEFAULT_NEAR_RAISE,
|
|
115
|
+
nearDrop = sight.nearDrop ?? DEFAULT_NEAR_DROP,
|
|
116
|
+
orbitRise = sight.orbitRise ?? DEFAULT_ORBIT_RISE;
|
|
117
|
+
const unshadedKinds = new Set(shadows.unshadedKinds ?? []),
|
|
118
|
+
wideFootKinds = new Set(shadows.wideFootKinds ?? []);
|
|
119
|
+
|
|
120
|
+
const homeOptions = {
|
|
121
|
+
isSpaceBuilt,
|
|
122
|
+
getSpace,
|
|
123
|
+
resolvePlace,
|
|
124
|
+
worldGround,
|
|
125
|
+
defaultRange,
|
|
126
|
+
worldSpaceId,
|
|
127
|
+
setAfoot: motion.setAfoot,
|
|
128
|
+
idlePoseOf,
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
const sightDistance = actor => kindRanges[actor.kind] ?? (actor.inScene ? seenInScene : seenWithin);
|
|
132
|
+
|
|
133
|
+
function setHomeFrame(name, frame) {
|
|
134
|
+
frames[name] = frame;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function actorHome(actor) {
|
|
138
|
+
placeActorAtHome(actor, homeOptions);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function onSpaceBuilt(spaceId) {
|
|
142
|
+
for (let i = 0; i < actorList.length; i++) {
|
|
143
|
+
const a = actorList[i];
|
|
144
|
+
if (a.home?.in === spaceId && !a.inScene) actorHome(a);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function buildActors(definitions, { hasGrip = () => false } = {}) {
|
|
149
|
+
let n = 0;
|
|
150
|
+
const echoes = [];
|
|
151
|
+
const enlist = (id, def, seed, home) => {
|
|
152
|
+
const a = createCastActor(id, def, stage.standIn(def.look), n++, { hash, defaultRange, defaultSpace: worldSpaceId });
|
|
153
|
+
a.figureSeed = seed;
|
|
154
|
+
a.home = home;
|
|
155
|
+
actorList.push(a);
|
|
156
|
+
return a;
|
|
157
|
+
};
|
|
158
|
+
for (const id in definitions) {
|
|
159
|
+
const own = definitions[id],
|
|
160
|
+
def = hasGrip(id, own) ? withGrip(own) : own,
|
|
161
|
+
homes = homesOf(def),
|
|
162
|
+
a = enlist(id, def, actorNameSeed(id), homes[0] || null);
|
|
163
|
+
actors[id] = a;
|
|
164
|
+
actorHome(a);
|
|
165
|
+
for (let k = 1; k < homes.length; k++) echoes.push([a, homes[k], k]);
|
|
166
|
+
}
|
|
167
|
+
if (actorList.some(a => a.active)) stage.warmDefaultPrograms();
|
|
168
|
+
stage.readyWorkerBodies();
|
|
169
|
+
for (const [person, home, k] of echoes) {
|
|
170
|
+
const e = enlist(person.id + '@' + k, person.def, person.figureSeed, home);
|
|
171
|
+
e.primary = person;
|
|
172
|
+
actorHome(e);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function actorPlace(actor, x, z, yaw, y) {
|
|
177
|
+
placeCastActor(actor, x, z, yaw, y);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function actorMoveTo(actor, x, z, dur, y, how) {
|
|
181
|
+
actor.move = motion.newMove(actor, x, z, dur, y, how);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const turnActor = motion.faceTo;
|
|
185
|
+
|
|
186
|
+
function settlePose(actor) {
|
|
187
|
+
settleCastPose(actor, motion.takePose);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const raiseActor = (actor, near = true) => stage.raiseActor(actor, near);
|
|
191
|
+
const orderCast = ids => stage.orderCast(actors, ids);
|
|
192
|
+
const prepareCast = ids => stage.prepareCast(actors, ids);
|
|
193
|
+
const releaseCast = ids => stage.releaseCast(actors, ids);
|
|
194
|
+
|
|
195
|
+
async function raiseInSight() {
|
|
196
|
+
const lens = getDetailLens(),
|
|
197
|
+
due = actorList.filter(a => !a.built && a.dist < sightDistance(a)),
|
|
198
|
+
near = a => a.dist < nearRaise * lens * a.group.scale.y;
|
|
199
|
+
for (const a of due) stage.orderActor(a, near(a));
|
|
200
|
+
await Promise.all(due.flatMap(a => [a.order?.done, a.nearOrder?.done]));
|
|
201
|
+
for (const a of due) stage.raiseActor(a, near(a));
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function orderSeenFrom(land, x, y, z) {
|
|
205
|
+
const t = getElapsed();
|
|
206
|
+
for (let i = 0; i < actorList.length; i++) {
|
|
207
|
+
const a = actorList[i];
|
|
208
|
+
if (a.built || !isActorInPlay(a, t, land, frames, orbitRise)) continue;
|
|
209
|
+
const reach = Math.hypot(a.x - x, a.y - y, a.z - z);
|
|
210
|
+
if (reach < sightDistance(a)) stage.orderActor(a, reach / a.group.scale.y < nearRaise);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function nearBodyFor(a, reach) {
|
|
215
|
+
if (reach < nearRaise) stage.orderActor(a, true);
|
|
216
|
+
if (a.nearBuilt) {
|
|
217
|
+
if (reach > nearDrop && !a.inScene) stage.dropNear(a);
|
|
218
|
+
} else if (a.nearOrder?.bodies) {
|
|
219
|
+
if (reach > nearDrop) a.nearOrder = a.nearOrder.cast ? a.nearOrder : null;
|
|
220
|
+
else stage.buildNearBody(a);
|
|
221
|
+
} else if (reach < nearRaise && !pending(a.nearOrder)) stage.buildNearBody(a);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function nearOrFar(a, d2, scale) {
|
|
225
|
+
const near = a.nearBuilt && (a.inScene || withinDetailRange(d2, a.hi.visible, scale, bodyRange));
|
|
226
|
+
if (a.hi.visible !== near) {
|
|
227
|
+
a.hi.visible = near;
|
|
228
|
+
a.lo.visible = !near;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function emitContactShadow(a, d2) {
|
|
233
|
+
if (!onFootShade || a.home?.on || (a.link && a.link.kind !== 'holdBack') || unshadedKinds.has(a.kind)) return;
|
|
234
|
+
const sy = a.group.scale.y;
|
|
235
|
+
if (a.mount) {
|
|
236
|
+
const hx = Math.sin(a.yaw) * 0.52,
|
|
237
|
+
hz = Math.cos(a.yaw) * 0.52;
|
|
238
|
+
onFootShade(a.x + hx, a.y, a.z + hz, 1.35, d2, 0.92);
|
|
239
|
+
onFootShade(a.x - hx, a.y, a.z - hz, 1.35, d2, 0.92);
|
|
240
|
+
} else if (a.pose === 'dead' || a.pose === 'lie' || a.pose === 'prone') {
|
|
241
|
+
const dir = (a.fall || 1) * 0.42 * sy,
|
|
242
|
+
bx = Math.sin(a.yaw) * dir,
|
|
243
|
+
bz = Math.cos(a.yaw) * dir;
|
|
244
|
+
onFootShade(a.x - bx * 0.5, a.y, a.z - bz * 0.5, sy * 1.15, d2, 1.05);
|
|
245
|
+
onFootShade(a.x - bx * 1.65, a.y, a.z - bz * 1.65, sy * 1.05, d2, 0.95);
|
|
246
|
+
} else if (wideFootKinds.has(a.kind)) {
|
|
247
|
+
onFootShade(a.x, a.y, a.z, sy * 1.45, d2, 0.95);
|
|
248
|
+
} else {
|
|
249
|
+
onFootShade(a.x, a.y, a.z, sy * (a.pose === 'sit' || a.pose === 'sittalk' ? 1.18 : 1), d2);
|
|
250
|
+
}
|
|
251
|
+
const extraMount = a.loose || a.beside;
|
|
252
|
+
if (extraMount?.H?.mesh?.parent) {
|
|
253
|
+
const mp = extraMount.H.mesh.position;
|
|
254
|
+
onFootShade(mp.x, mp.y, mp.z, 1.55, d2, 0.9);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function updateActors(dt) {
|
|
259
|
+
const t = getElapsed(),
|
|
260
|
+
lens = getDetailLens(),
|
|
261
|
+
currentSpace = getSpaceId(),
|
|
262
|
+
cx = camera.position.x,
|
|
263
|
+
cy = camera.position.y,
|
|
264
|
+
cz = camera.position.z;
|
|
265
|
+
for (let i = 0; i < actorList.length; i++) {
|
|
266
|
+
const a = actorList[i];
|
|
267
|
+
if (!isActorInPlay(a, t, currentSpace, frames, orbitRise)) {
|
|
268
|
+
if (!a.preparing && a.group.visible) a.group.visible = false;
|
|
269
|
+
a.dist = 1e9;
|
|
270
|
+
continue;
|
|
271
|
+
}
|
|
272
|
+
if (a.home && a.home.on && !a.inScene && !a.move) {
|
|
273
|
+
a.px = a.x;
|
|
274
|
+
a.pz = a.z;
|
|
275
|
+
}
|
|
276
|
+
motion.travel(a, dt);
|
|
277
|
+
const dx = a.x - cx,
|
|
278
|
+
dy = a.y - cy,
|
|
279
|
+
dz = a.z - cz,
|
|
280
|
+
d2 = dx * dx + dy * dy + dz * dz,
|
|
281
|
+
d = (a.dist = Math.sqrt(d2)),
|
|
282
|
+
scale = lens * a.group.scale.y,
|
|
283
|
+
reach = d / scale;
|
|
284
|
+
const limit = sightDistance(a),
|
|
285
|
+
seen = d < limit;
|
|
286
|
+
if (!a.built) {
|
|
287
|
+
if (d < limit + orderAhead) stage.orderActor(a, reach < nearRaise);
|
|
288
|
+
if (seen && !pending(a.order)) stage.buildVisibleActor(a, reach < nearRaise && !pending(a.nearOrder));
|
|
289
|
+
}
|
|
290
|
+
if (!a.built) continue;
|
|
291
|
+
if (a.group.visible !== seen) a.group.visible = seen;
|
|
292
|
+
if (!seen) continue;
|
|
293
|
+
emitContactShadow(a, d2);
|
|
294
|
+
if (a.nearLater) nearBodyFor(a, reach);
|
|
295
|
+
if (a.lo) nearOrFar(a, d2, scale);
|
|
296
|
+
motion.poseActor(a, i, dt, t);
|
|
297
|
+
}
|
|
298
|
+
motion.applyActorLinks(dt);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
return {
|
|
302
|
+
actorHome,
|
|
303
|
+
actorList,
|
|
304
|
+
actorMoveTo,
|
|
305
|
+
actorPlace,
|
|
306
|
+
actors,
|
|
307
|
+
buildActors,
|
|
308
|
+
clearActorLinks: motion.clearActorLinks,
|
|
309
|
+
onSpaceBuilt,
|
|
310
|
+
orderCast,
|
|
311
|
+
orderSeenFrom,
|
|
312
|
+
prepareCast,
|
|
313
|
+
raiseActor,
|
|
314
|
+
raiseInSight,
|
|
315
|
+
releaseCast,
|
|
316
|
+
setHomeFrame,
|
|
317
|
+
settlePose,
|
|
318
|
+
turnActor,
|
|
319
|
+
updateActors,
|
|
320
|
+
};
|
|
321
|
+
}
|
package/motion/figure-mount.js
CHANGED
|
@@ -189,6 +189,7 @@ function createFigureMount({ ground = FLAT, hoofbeat = SILENT } = {}) {
|
|
|
189
189
|
horse.yaw = a.yaw;
|
|
190
190
|
mesh.position.set(horse.x, ground(horse.x, horse.z), horse.z);
|
|
191
191
|
mesh.rotation.set(0, horse.yaw, 0);
|
|
192
|
+
mesh.updateMatrixWorld(true);
|
|
192
193
|
a.beside = horse;
|
|
193
194
|
}
|
|
194
195
|
const ends = a.steed.H.rig.bones[BONE.crest];
|
package/package.json
CHANGED
|
@@ -1,7 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "roamwright",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.56.0",
|
|
4
4
|
"description": "A procedural worldbuilding engine built on top of Three.js. Generate landscapes with rivers and changing weather, animate crowds, and explore on foot or in flight.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"threejs",
|
|
7
|
+
"three",
|
|
8
|
+
"procedural",
|
|
9
|
+
"procedural-generation",
|
|
10
|
+
"worldbuilding",
|
|
11
|
+
"world-generation",
|
|
12
|
+
"terrain",
|
|
13
|
+
"landscape",
|
|
14
|
+
"open-world",
|
|
15
|
+
"game-engine",
|
|
16
|
+
"gamedev",
|
|
17
|
+
"webgl",
|
|
18
|
+
"3d",
|
|
19
|
+
"crowd",
|
|
20
|
+
"character-animation",
|
|
21
|
+
"weather",
|
|
22
|
+
"day-night-cycle"
|
|
23
|
+
],
|
|
5
24
|
"type": "module",
|
|
6
25
|
"license": "MIT",
|
|
7
26
|
"author": "Enes TAYLAN",
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Three.js and GPU staging layer for a world's cast: placeholder groups, smooth-shaded
|
|
3
|
+
* shader warm-up, worker body ordering, lazy figure and near-body raising/dropping, and
|
|
4
|
+
* paced zero-drawRange GPU buffer uploads ahead of scene playback.
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
import * as THREE from 'three';
|
|
8
|
+
import { extractFigureParts } from '../motion/cast-actors.js';
|
|
9
|
+
import { FAR_BODY, NEAR_BODY, pending } from '../runtime/figure-orders.js';
|
|
10
|
+
import { NO_SKIN } from './figure-skeleton.js';
|
|
11
|
+
|
|
12
|
+
const DEFAULT_HEIGHTS = Object.freeze({ human: 1.9 });
|
|
13
|
+
const DEFAULT_RIDER_OFFSET = 0.8;
|
|
14
|
+
const DEFAULT_CAST_SLICE_MS = 4.5;
|
|
15
|
+
const DEFAULT_ORDERED_KINDS = Object.freeze(['human']);
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Creates a lightweight Three.js stand-in group with the height and scale a figure will
|
|
19
|
+
* occupy once built, so actors can be placed, named, and picked before spending mesh memory.
|
|
20
|
+
*
|
|
21
|
+
* @param {object} look - Actor appearance descriptor (`{ kind?, h?, horse? }`).
|
|
22
|
+
* @param {object} [options]
|
|
23
|
+
* @param {Record<string, number>} [options.heights] - Base standing height (metres) by figure kind.
|
|
24
|
+
* @param {number} [options.defaultHeight=1.9] - Fallback base height (metres) when a kind is unlisted.
|
|
25
|
+
* @param {number} [options.riderOffset=0.8] - Added height (metres) when `look.horse` is set.
|
|
26
|
+
* @param {Record<string, number>} [options.scaleMultipliers] - Optional per-kind uniform scale factor.
|
|
27
|
+
* @returns {{ group: THREE.Group, kind: string, height: number }}
|
|
28
|
+
*/
|
|
29
|
+
export function createStandIn(
|
|
30
|
+
look,
|
|
31
|
+
{ heights = DEFAULT_HEIGHTS, defaultHeight = 1.9, riderOffset = DEFAULT_RIDER_OFFSET, scaleMultipliers = {} } = {},
|
|
32
|
+
) {
|
|
33
|
+
const kind = look.kind || 'human',
|
|
34
|
+
size = look.h || 1,
|
|
35
|
+
group = new THREE.Group();
|
|
36
|
+
group.scale.setScalar(size * (scaleMultipliers[kind] ?? 1));
|
|
37
|
+
group.visible = false;
|
|
38
|
+
return { group, kind, height: (heights[kind] ?? defaultHeight) * size + (look.horse ? riderOffset : 0) };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Compiles the common skinned and rigid figure shader programs (including shadow casters)
|
|
43
|
+
* using a zero-vertex geometry carrying `position` and `normal` attributes, matching
|
|
44
|
+
* Three.js smooth-shaded program keys without building a full actor first.
|
|
45
|
+
*
|
|
46
|
+
* @param {(root: THREE.Object3D) => Promise<void>|void} warmShaders - Shader warmer callback.
|
|
47
|
+
* @param {THREE.Material} skinnedMaterial - Shared skinned figure material.
|
|
48
|
+
* @param {THREE.Material} [plainMaterial] - Optional rigid twin material for unskinned props/parts.
|
|
49
|
+
* @returns {Promise<void>|void}
|
|
50
|
+
*/
|
|
51
|
+
export function warmFigureShaders(warmShaders, skinnedMaterial, plainMaterial = null) {
|
|
52
|
+
const warmGeo = new THREE.BufferGeometry();
|
|
53
|
+
warmGeo.setAttribute('position', new THREE.Float32BufferAttribute(0, 3));
|
|
54
|
+
warmGeo.setAttribute('normal', new THREE.Float32BufferAttribute(0, 3));
|
|
55
|
+
const programs = new THREE.Group(),
|
|
56
|
+
body = new THREE.SkinnedMesh(warmGeo, skinnedMaterial);
|
|
57
|
+
body.castShadow = true;
|
|
58
|
+
programs.add(body);
|
|
59
|
+
if (plainMaterial) {
|
|
60
|
+
const plain = new THREE.Mesh(warmGeo, plainMaterial);
|
|
61
|
+
plain.castShadow = true;
|
|
62
|
+
programs.add(plain);
|
|
63
|
+
}
|
|
64
|
+
return warmShaders(programs);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Stages newly built cast meshes onto the GPU across frames at zero `drawRange` while
|
|
69
|
+
* keeping them invisible on screen, preventing VBO/skin upload stalls on scene start or
|
|
70
|
+
* mid-scene `show` entrances.
|
|
71
|
+
*
|
|
72
|
+
* @param {Array<[object, boolean]>} fresh - Pairs of `[actor, wasVisible]` newly raised for a scene.
|
|
73
|
+
* @param {object} handOver - Frame byte-budget coordinator (`anyFrameDrawn`, `heldBytes`, `countHanded`, `frameFull`).
|
|
74
|
+
* @param {object} [options]
|
|
75
|
+
* @param {() => Promise<void>} [options.painted] - Resolves after the browser paints one frame.
|
|
76
|
+
* @param {THREE.BufferGeometry} [options.emptyGeometry=NO_SKIN] - Placeholder geometry skipped during upload.
|
|
77
|
+
* @returns {Promise<void>}
|
|
78
|
+
*/
|
|
79
|
+
export async function uploadCastMeshes(fresh, handOver, { painted = () => Promise.resolve(), emptyGeometry = NO_SKIN } = {}) {
|
|
80
|
+
if (!handOver || !handOver.anyFrameDrawn()) return;
|
|
81
|
+
const savedActors = [],
|
|
82
|
+
meshes = [];
|
|
83
|
+
for (const [a, wasVisible] of fresh) {
|
|
84
|
+
a.preparing = true;
|
|
85
|
+
const hidden = [],
|
|
86
|
+
subGroups = [];
|
|
87
|
+
a.group.traverse(o => {
|
|
88
|
+
if (o !== a.group && !o.isMesh && !o.visible) {
|
|
89
|
+
subGroups.push(o);
|
|
90
|
+
o.visible = true;
|
|
91
|
+
}
|
|
92
|
+
if (!o.isMesh || o.geometry === emptyGeometry) return;
|
|
93
|
+
hidden.push([o, o.visible]);
|
|
94
|
+
o.visible = false;
|
|
95
|
+
if (!o.geometry.userData.uploaded && handOver.heldBytes(o.geometry) > 0) meshes.push(o);
|
|
96
|
+
});
|
|
97
|
+
a.group.visible = true;
|
|
98
|
+
savedActors.push([a, wasVisible, hidden, subGroups]);
|
|
99
|
+
}
|
|
100
|
+
const batch = [];
|
|
101
|
+
const restoreBatch = () => {
|
|
102
|
+
for (const [m, range, culled, shadow] of batch) {
|
|
103
|
+
m.geometry.setDrawRange(range.start, range.count);
|
|
104
|
+
m.visible = false;
|
|
105
|
+
m.frustumCulled = culled;
|
|
106
|
+
m.castShadow = shadow;
|
|
107
|
+
m.geometry.userData.uploaded = true;
|
|
108
|
+
}
|
|
109
|
+
batch.length = 0;
|
|
110
|
+
};
|
|
111
|
+
try {
|
|
112
|
+
const seenGeo = new Set();
|
|
113
|
+
for (const m of meshes) {
|
|
114
|
+
if (seenGeo.has(m.geometry)) continue;
|
|
115
|
+
seenGeo.add(m.geometry);
|
|
116
|
+
const range = { ...m.geometry.drawRange };
|
|
117
|
+
batch.push([m, range, m.frustumCulled, m.castShadow]);
|
|
118
|
+
m.geometry.setDrawRange(0, 0);
|
|
119
|
+
m.visible = true;
|
|
120
|
+
m.frustumCulled = false;
|
|
121
|
+
m.castShadow = false;
|
|
122
|
+
handOver.countHanded(handOver.heldBytes(m.geometry));
|
|
123
|
+
if (handOver.frameFull()) {
|
|
124
|
+
await painted();
|
|
125
|
+
restoreBatch();
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (batch.length) {
|
|
129
|
+
await painted();
|
|
130
|
+
restoreBatch();
|
|
131
|
+
}
|
|
132
|
+
} finally {
|
|
133
|
+
if (batch.length) restoreBatch();
|
|
134
|
+
for (const [a, wasVisible, hidden, subGroups] of savedActors) {
|
|
135
|
+
for (const g of subGroups) g.visible = false;
|
|
136
|
+
for (const [o, vis] of hidden) o.visible = vis;
|
|
137
|
+
a.group.visible = wasVisible;
|
|
138
|
+
a.preparing = false;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Creates the Three.js and GPU staging controller used by `createCastManager`:
|
|
145
|
+
* manages stand-in creation, worker body prefetching, scene attachment, near-LOD geometry
|
|
146
|
+
* lifecycle, shader warm-up, and paced scene-cast pre-uploading.
|
|
147
|
+
*
|
|
148
|
+
* @param {object} config
|
|
149
|
+
* @param {THREE.Object3D} config.scene - Scene receiving raised actor groups.
|
|
150
|
+
* @param {(look: object, seed: number, near: boolean, bodies: ?Array<object>) => object} config.buildFigure - Builds an actor's rigged Three.js figure.
|
|
151
|
+
* @param {(look: object, seed: number, parts?: object) => THREE.BufferGeometry} [config.buildNearBody] - Builds a high-detail skinned geometry when promoting a figure from far-only.
|
|
152
|
+
* @param {(actor: object) => void} [config.onFigureRaised] - Optional hook called immediately after a figure is attached (e.g. strapping shields).
|
|
153
|
+
* @param {(look: object, seed: number, lods: number[]) => ?object} [config.orderBodies] - Optional worker body orderer (`createBodyOrders().orderBodies`).
|
|
154
|
+
* @param {() => void} [config.readyBodies] - Optional worker preloader (`createBodyOrders().readyBodies`).
|
|
155
|
+
* @param {Iterable<string>} [config.orderedKinds] - Figure kinds eligible for background worker builds (default `['human']`).
|
|
156
|
+
* @param {string} [config.nearOrderKind='human'] - Figure kind that orders its near LOD separately.
|
|
157
|
+
* @param {(roots: THREE.Object3D | THREE.Object3D[]) => Promise<void>|void} [config.warmShaders] - Shader warm-up hook.
|
|
158
|
+
* @param {() => { skinned: THREE.Material, plain?: THREE.Material } | null} [config.getWarmMaterials] - Supplies materials for {@link warmFigureShaders}.
|
|
159
|
+
* @param {object} [config.handOver] - Frame byte-budget coordinator (`createHandOver`).
|
|
160
|
+
* @param {() => Promise<void>} [config.painted] - Resolves after the next browser paint.
|
|
161
|
+
* @param {() => Promise<void>} [config.nextFrame] - Resolves on the next animation frame.
|
|
162
|
+
* @param {{ task: <T extends Function>(fn: T) => T }} [config.detailBudget] - Optional frame-time task budgeter (`createFrameBudget`).
|
|
163
|
+
* @param {object} [config.standInOptions] - Options forwarded to {@link createStandIn}.
|
|
164
|
+
* @param {number} [config.castSliceMs=4.5] - Per-frame millisecond budget when building scene cast members in `prepareCast`.
|
|
165
|
+
* @param {THREE.BufferGeometry} [config.emptyGeometry=NO_SKIN] - Empty geometry bound when dropping a near body.
|
|
166
|
+
*/
|
|
167
|
+
export function createCastStage({
|
|
168
|
+
scene,
|
|
169
|
+
buildFigure,
|
|
170
|
+
buildNearBody = null,
|
|
171
|
+
onFigureRaised = null,
|
|
172
|
+
orderBodies = null,
|
|
173
|
+
readyBodies = null,
|
|
174
|
+
orderedKinds = DEFAULT_ORDERED_KINDS,
|
|
175
|
+
nearOrderKind = 'human',
|
|
176
|
+
warmShaders = null,
|
|
177
|
+
getWarmMaterials = null,
|
|
178
|
+
handOver = null,
|
|
179
|
+
painted = () => Promise.resolve(),
|
|
180
|
+
nextFrame = () => Promise.resolve(),
|
|
181
|
+
detailBudget = null,
|
|
182
|
+
standInOptions = {},
|
|
183
|
+
castSliceMs = DEFAULT_CAST_SLICE_MS,
|
|
184
|
+
emptyGeometry = NO_SKIN,
|
|
185
|
+
}) {
|
|
186
|
+
const orderedSet = new Set(orderedKinds);
|
|
187
|
+
|
|
188
|
+
const standIn = look => createStandIn(look, standInOptions);
|
|
189
|
+
|
|
190
|
+
function raiseNear(actor) {
|
|
191
|
+
if (actor.nearBuilt || !buildNearBody) return;
|
|
192
|
+
actor.nearBuilt = true;
|
|
193
|
+
const parts = actor.nearOrder?.bodies?.[0].parts;
|
|
194
|
+
actor.nearOrder = null;
|
|
195
|
+
actor.hi.geometry = buildNearBody(actor.def.look, actor.figureSeed, parts);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function dropNear(actor) {
|
|
199
|
+
actor.nearOrder = null;
|
|
200
|
+
actor.nearBuilt = false;
|
|
201
|
+
actor.hi.visible = false;
|
|
202
|
+
actor.lo.visible = true;
|
|
203
|
+
actor.hi.geometry.dispose();
|
|
204
|
+
actor.hi.geometry = emptyGeometry;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function raiseActor(actor, near = true) {
|
|
208
|
+
if (actor.built) {
|
|
209
|
+
if (near) raiseNear(actor);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
actor.built = true;
|
|
213
|
+
const far = actor.order?.bodies?.[0],
|
|
214
|
+
nearOne = actor.nearOrder?.bodies?.[0];
|
|
215
|
+
actor.order = null;
|
|
216
|
+
if (nearOne) actor.nearOrder = null;
|
|
217
|
+
const figure = buildFigure(actor.def.look, actor.figureSeed, near, far || nearOne ? [far, nearOne] : null);
|
|
218
|
+
figure.group.visible = actor.group.visible;
|
|
219
|
+
scene.add(figure.group);
|
|
220
|
+
Object.assign(actor, extractFigureParts(figure));
|
|
221
|
+
if (onFigureRaised) onFigureRaised(actor);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function orderActor(actor, near) {
|
|
225
|
+
if (!orderBodies || !orderedSet.has(actor.kind)) return;
|
|
226
|
+
if (!actor.built && !actor.order) actor.order = orderBodies(actor.def.look, actor.figureSeed, FAR_BODY);
|
|
227
|
+
if (actor.kind !== nearOrderKind) return;
|
|
228
|
+
if (near && (!actor.built || !actor.nearBuilt) && !actor.nearOrder) {
|
|
229
|
+
actor.nearOrder = orderBodies(actor.def.look, actor.figureSeed, NEAR_BODY);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function orderCast(actorsById, ids) {
|
|
234
|
+
const out = [];
|
|
235
|
+
for (const id of ids) {
|
|
236
|
+
const a = actorsById[id];
|
|
237
|
+
orderActor(a, true);
|
|
238
|
+
if (a.nearOrder) a.nearOrder.cast = true;
|
|
239
|
+
for (const order of [a.order, a.nearOrder]) if (pending(order)) out.push(order.done);
|
|
240
|
+
}
|
|
241
|
+
return out.length ? Promise.all(out) : null;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function releaseCast(actorsById, ids) {
|
|
245
|
+
for (const id of ids) if (actorsById[id]?.nearOrder) actorsById[id].nearOrder.cast = false;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async function prepareCast(actorsById, ids) {
|
|
249
|
+
const ordered = orderCast(actorsById, ids);
|
|
250
|
+
if (ordered) await ordered;
|
|
251
|
+
const fresh = [];
|
|
252
|
+
let sliceStart = performance.now();
|
|
253
|
+
for (let i = 0; i < ids.length; i++) {
|
|
254
|
+
const a = actorsById[ids[i]];
|
|
255
|
+
if (!a || (a.built && (!a.nearLater || a.nearBuilt))) continue;
|
|
256
|
+
if (performance.now() - sliceStart > castSliceMs) {
|
|
257
|
+
await nextFrame();
|
|
258
|
+
sliceStart = performance.now();
|
|
259
|
+
}
|
|
260
|
+
const wasVisible = a.group.visible;
|
|
261
|
+
raiseActor(a, true);
|
|
262
|
+
a.group.visible = false;
|
|
263
|
+
fresh.push([a, wasVisible]);
|
|
264
|
+
}
|
|
265
|
+
if (!fresh.length) return;
|
|
266
|
+
const groups = fresh.map(([a]) => a.group);
|
|
267
|
+
if (warmShaders) await warmShaders(groups);
|
|
268
|
+
await uploadCastMeshes(fresh, handOver, { painted, emptyGeometry });
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function warmDefaultPrograms() {
|
|
272
|
+
if (!warmShaders || !getWarmMaterials) return;
|
|
273
|
+
const mats = getWarmMaterials();
|
|
274
|
+
if (!mats) return;
|
|
275
|
+
warmFigureShaders(warmShaders, mats.skinned, mats.plain || null);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function readyWorkerBodies() {
|
|
279
|
+
if (readyBodies) readyBodies();
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const buildVisibleActor = detailBudget ? detailBudget.task(raiseActor) : raiseActor;
|
|
283
|
+
const buildNearBodyTask = detailBudget ? detailBudget.task(raiseNear) : raiseNear;
|
|
284
|
+
|
|
285
|
+
return {
|
|
286
|
+
standIn,
|
|
287
|
+
orderActor,
|
|
288
|
+
orderCast,
|
|
289
|
+
releaseCast,
|
|
290
|
+
raiseActor,
|
|
291
|
+
raiseNear,
|
|
292
|
+
dropNear,
|
|
293
|
+
prepareCast,
|
|
294
|
+
warmDefaultPrograms,
|
|
295
|
+
readyWorkerBodies,
|
|
296
|
+
buildVisibleActor,
|
|
297
|
+
buildNearBody: buildNearBodyTask,
|
|
298
|
+
};
|
|
299
|
+
}
|