katachi-runtime 0.3.0 → 0.6.1

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/index.js CHANGED
@@ -1,5 +1,877 @@
1
- // src/model.ts
1
+ // src/animation.ts
2
+ import * as THREE2 from "three";
3
+
4
+ // src/bones.ts
5
+ var PED_BONES = {
6
+ SKEL_ROOT: 0,
7
+ SKEL_Pelvis: 11816,
8
+ SKEL_L_Thigh: 58271,
9
+ SKEL_L_Calf: 63931,
10
+ SKEL_L_Foot: 14201,
11
+ SKEL_L_Toe0: 2108,
12
+ IK_L_Foot: 65245,
13
+ PH_L_Foot: 57717,
14
+ MH_L_Knee: 46078,
15
+ SKEL_R_Thigh: 51826,
16
+ SKEL_R_Calf: 36864,
17
+ SKEL_R_Foot: 52301,
18
+ SKEL_R_Toe0: 20781,
19
+ IK_R_Foot: 35502,
20
+ PH_R_Foot: 24806,
21
+ MH_R_Knee: 16335,
22
+ RB_L_ThighRoll: 23639,
23
+ RB_R_ThighRoll: 6442,
24
+ SKEL_Spine_Root: 57597,
25
+ SKEL_Spine0: 23553,
26
+ SKEL_Spine1: 24816,
27
+ SKEL_Spine2: 24817,
28
+ SKEL_Spine3: 24818,
29
+ SKEL_L_Clavicle: 64729,
30
+ SKEL_L_UpperArm: 45509,
31
+ SKEL_L_Forearm: 61163,
32
+ SKEL_L_Hand: 18905,
33
+ SKEL_L_Finger00: 26610,
34
+ SKEL_L_Finger01: 4089,
35
+ SKEL_L_Finger02: 4090,
36
+ SKEL_L_Finger10: 26611,
37
+ SKEL_L_Finger11: 4169,
38
+ SKEL_L_Finger12: 4170,
39
+ SKEL_L_Finger20: 26612,
40
+ SKEL_L_Finger21: 4185,
41
+ SKEL_L_Finger22: 4186,
42
+ SKEL_L_Finger30: 26613,
43
+ SKEL_L_Finger31: 4137,
44
+ SKEL_L_Finger32: 4138,
45
+ SKEL_L_Finger40: 26614,
46
+ SKEL_L_Finger41: 4153,
47
+ SKEL_L_Finger42: 4154,
48
+ PH_L_Hand: 60309,
49
+ IK_L_Hand: 36029,
50
+ RB_L_ForeArmRoll: 61007,
51
+ RB_L_ArmRoll: 5232,
52
+ MH_L_Elbow: 22711,
53
+ SKEL_R_Clavicle: 10706,
54
+ SKEL_R_UpperArm: 40269,
55
+ SKEL_R_Forearm: 28252,
56
+ SKEL_R_Hand: 57005,
57
+ SKEL_R_Finger00: 58866,
58
+ SKEL_R_Finger01: 64016,
59
+ SKEL_R_Finger02: 64017,
60
+ SKEL_R_Finger10: 58867,
61
+ SKEL_R_Finger11: 64096,
62
+ SKEL_R_Finger12: 64097,
63
+ SKEL_R_Finger20: 58868,
64
+ SKEL_R_Finger21: 64112,
65
+ SKEL_R_Finger22: 64113,
66
+ SKEL_R_Finger30: 58869,
67
+ SKEL_R_Finger31: 64064,
68
+ SKEL_R_Finger32: 64065,
69
+ SKEL_R_Finger40: 58870,
70
+ SKEL_R_Finger41: 64080,
71
+ SKEL_R_Finger42: 64081,
72
+ PH_R_Hand: 28422,
73
+ IK_R_Hand: 6286,
74
+ RB_R_ForeArmRoll: 43810,
75
+ RB_R_ArmRoll: 37119,
76
+ MH_R_Elbow: 2992,
77
+ SKEL_Neck_1: 39317,
78
+ SKEL_Head: 31086,
79
+ IK_Head: 12844,
80
+ FACIAL_facialRoot: 65068,
81
+ FB_L_Brow_Out_000: 58331,
82
+ FB_L_Lid_Upper_000: 45750,
83
+ FB_L_Eye_000: 25260,
84
+ FB_L_CheekBone_000: 21550,
85
+ FB_L_Lip_Corner_000: 29868,
86
+ FB_R_Lid_Upper_000: 43536,
87
+ FB_R_Eye_000: 27474,
88
+ FB_R_CheekBone_000: 19336,
89
+ FB_R_Brow_Out_000: 1356,
90
+ FB_R_Lip_Corner_000: 11174,
91
+ FB_Brow_Centre_000: 37193,
92
+ FB_UpperLipRoot_000: 20178,
93
+ FB_UpperLip_000: 61839,
94
+ FB_L_Lip_Top_000: 20279,
95
+ FB_R_Lip_Top_000: 17719,
96
+ FB_Jaw_000: 46240,
97
+ FB_LowerLipRoot_000: 17188,
98
+ FB_LowerLip_000: 20623,
99
+ FB_L_Lip_Bot_000: 47419,
100
+ FB_R_Lip_Bot_000: 49979,
101
+ FB_Tongue_000: 47495,
102
+ RB_Neck_1: 35731,
103
+ IK_Root: 56604
104
+ };
105
+ var NAMES = new Map(Object.entries(PED_BONES).map(([name, tag]) => [tag, name]));
106
+ function boneName(tag) {
107
+ return NAMES.get(tag);
108
+ }
109
+
110
+ // src/clip.ts
2
111
  import * as THREE from "three";
112
+ var TrackKind = {
113
+ boneTranslation: 0,
114
+ boneRotation: 1,
115
+ boneScale: 2,
116
+ moverTranslation: 5,
117
+ moverRotation: 6
118
+ };
119
+ var TrackFormat = { vector3: 0, quaternion: 1, float: 2 };
120
+ var WIDTHS = [3, 4, 1];
121
+ function trackWidth(format) {
122
+ const width = WIDTHS[format];
123
+ if (width === undefined)
124
+ throw new Error(`Unknown track format ${format}`);
125
+ return width;
126
+ }
127
+
128
+ class Track {
129
+ bone;
130
+ kind;
131
+ format;
132
+ values;
133
+ width;
134
+ constructor(bone, kind, format, values) {
135
+ this.bone = bone;
136
+ this.kind = kind;
137
+ this.format = format;
138
+ this.values = values;
139
+ this.width = trackWidth(format);
140
+ }
141
+ get constant() {
142
+ return this.values.length === this.width;
143
+ }
144
+ sample(frame, out, offset = 0) {
145
+ const { width, values } = this;
146
+ if (this.constant) {
147
+ for (let index = 0;index < width; index++)
148
+ out[offset + index] = values[index];
149
+ return;
150
+ }
151
+ const last = values.length / width - 1;
152
+ const position = THREE.MathUtils.clamp(frame, 0, last);
153
+ const first = Math.floor(position);
154
+ const next = Math.min(first + 1, last);
155
+ const amount = position - first;
156
+ if (this.format === TrackFormat.quaternion) {
157
+ THREE.Quaternion.slerpFlat(out, offset, values, first * 4, values, next * 4, amount);
158
+ return;
159
+ }
160
+ for (let index = 0;index < width; index++) {
161
+ const from = values[first * width + index];
162
+ out[offset + index] = from + (values[next * width + index] - from) * amount;
163
+ }
164
+ }
165
+ }
166
+ function joaat(text) {
167
+ let hash = 0;
168
+ for (const char of text.toLowerCase()) {
169
+ hash = hash + char.charCodeAt(0) >>> 0;
170
+ hash = hash + (hash << 10) >>> 0;
171
+ hash = (hash ^ hash >>> 6) >>> 0;
172
+ }
173
+ hash = hash + (hash << 3) >>> 0;
174
+ hash = (hash ^ hash >>> 11) >>> 0;
175
+ return hash + (hash << 15) >>> 0;
176
+ }
177
+
178
+ class Clip {
179
+ dictionary;
180
+ name;
181
+ hash;
182
+ fps;
183
+ frames;
184
+ flags;
185
+ tracks;
186
+ tags;
187
+ constructor(init) {
188
+ if (!(init.fps > 0) || !Number.isFinite(init.fps))
189
+ throw new Error(`${init.name}: fps must be above 0`);
190
+ if (!Number.isInteger(init.frames) || init.frames < 1)
191
+ throw new Error(`${init.name}: frames must be a whole number above 0`);
192
+ for (const track of init.tracks) {
193
+ if (!track.constant && track.values.length !== init.frames * track.width) {
194
+ throw new Error(`${init.name}: the track of bone ${track.bone} holds ${track.values.length / track.width} frames, not ${init.frames}`);
195
+ }
196
+ }
197
+ this.dictionary = init.dictionary;
198
+ this.name = init.name;
199
+ this.hash = init.hash ?? (init.name.startsWith("0x") ? Number.parseInt(init.name, 16) : joaat(init.name));
200
+ this.fps = init.fps;
201
+ this.frames = init.frames;
202
+ this.flags = init.flags ?? 0;
203
+ this.tracks = init.tracks;
204
+ this.tags = init.tags ?? [];
205
+ }
206
+ static fromJSON(data) {
207
+ if (data.version !== 1)
208
+ throw new Error(`Unsupported clip version ${data.version}`);
209
+ return new Clip({ ...data, tracks: data.tracks.map((track) => new Track(track.bone, track.kind, track.format, Float32Array.from(track.values))) });
210
+ }
211
+ toJSON() {
212
+ return {
213
+ version: 1,
214
+ dictionary: this.dictionary,
215
+ name: this.name,
216
+ hash: this.hash,
217
+ fps: this.fps,
218
+ frames: this.frames,
219
+ flags: this.flags,
220
+ tracks: this.tracks.map((track) => ({ bone: track.bone, kind: track.kind, format: track.format, values: Array.from(track.values) })),
221
+ tags: [...this.tags]
222
+ };
223
+ }
224
+ get duration() {
225
+ return (this.frames - 1) / this.fps;
226
+ }
227
+ track(bone, kind) {
228
+ return this.tracks.find((track) => track.bone === bone && track.kind === kind);
229
+ }
230
+ }
231
+
232
+ // src/animation.ts
233
+ var DEFAULT_BLEND = 0.2;
234
+ var GAME_TO_SCENE = new THREE2.Quaternion().setFromAxisAngle(new THREE2.Vector3(1, 0, 0), -Math.PI / 2);
235
+ var SCENE_TO_GAME = GAME_TO_SCENE.clone().invert();
236
+
237
+ class Playback {
238
+ clip;
239
+ missing;
240
+ moved;
241
+ time;
242
+ speed;
243
+ loop;
244
+ paused;
245
+ baseTime = 0;
246
+ base;
247
+ constructor(clip, options, missing, moved) {
248
+ this.clip = clip;
249
+ this.missing = missing;
250
+ this.moved = moved;
251
+ this.time = THREE2.MathUtils.clamp(options.time ?? 0, 0, clip.duration);
252
+ this.speed = options.speed ?? 1;
253
+ this.loop = options.loop ?? true;
254
+ this.paused = options.paused ?? false;
255
+ this.base = options.base ?? null;
256
+ }
257
+ get duration() {
258
+ return this.clip.duration;
259
+ }
260
+ get frame() {
261
+ return this.time * this.clip.fps;
262
+ }
263
+ get finished() {
264
+ return !this.loop && this.time >= this.duration;
265
+ }
266
+ }
267
+ var SLOTS = { [TrackKind.boneTranslation]: "translation", [TrackKind.boneRotation]: "rotation", [TrackKind.boneScale]: "scale" };
268
+ var poseOf = (node) => ({ position: node.position.clone(), quaternion: node.quaternion.clone(), scale: node.scale.clone() });
269
+ function bonesByTag(bones) {
270
+ const byTag = new Map;
271
+ for (const node of bones.values()) {
272
+ const tag = node.userData.tag;
273
+ if (typeof tag === "number")
274
+ byTag.set(tag, node);
275
+ }
276
+ if (byTag.size > 0)
277
+ return byTag;
278
+ for (const [name, node] of bones) {
279
+ const tag = PED_BONES[name];
280
+ if (tag !== undefined)
281
+ byTag.set(tag, node);
282
+ }
283
+ return byTag;
284
+ }
285
+
286
+ class Animator {
287
+ root;
288
+ byTag;
289
+ rest = new Map;
290
+ origin = null;
291
+ bindings = [];
292
+ current = null;
293
+ from = new Map;
294
+ touched = new Set;
295
+ blend = 0;
296
+ blended = 0;
297
+ rootMotion = false;
298
+ carried = new THREE2.Vector3;
299
+ carriedTurn = new THREE2.Quaternion;
300
+ sample = new Float32Array(4);
301
+ target = new THREE2.Quaternion;
302
+ moverPosition = new THREE2.Vector3;
303
+ moverTurn = new THREE2.Quaternion;
304
+ entity;
305
+ entityInverse;
306
+ constructor(root, bones) {
307
+ this.root = root;
308
+ this.byTag = bonesByTag(bones);
309
+ for (const node of this.byTag.values())
310
+ this.rest.set(node, poseOf(node));
311
+ const skeletonRoot = this.byTag.get(0);
312
+ this.entity = skeletonRoot ? skeletonRoot.quaternion.clone() : new THREE2.Quaternion;
313
+ this.entityInverse = this.entity.clone().invert();
314
+ }
315
+ get playback() {
316
+ return this.current;
317
+ }
318
+ play(clip, options = {}) {
319
+ const bindings = new Map;
320
+ const missing = new Set;
321
+ let moved = 0;
322
+ const bind = (source, layer) => {
323
+ for (const track of source.tracks) {
324
+ const slot = SLOTS[track.kind];
325
+ if (!slot)
326
+ continue;
327
+ const node = this.byTag.get(track.bone);
328
+ if (!node) {
329
+ if (layer === "main")
330
+ missing.add(track.bone);
331
+ continue;
332
+ }
333
+ let binding = bindings.get(node);
334
+ if (!binding) {
335
+ binding = { node, main: {}, base: {}, root: track.bone === 0 };
336
+ bindings.set(node, binding);
337
+ }
338
+ if (layer === "main" && Object.keys(binding.main).length === 0)
339
+ moved++;
340
+ binding[layer][slot] = track;
341
+ }
342
+ };
343
+ bind(clip, "main");
344
+ if (options.base)
345
+ bind(options.base, "base");
346
+ this.startBlend(options.blend ?? DEFAULT_BLEND, bindings.keys());
347
+ this.bindings = [...bindings.values()];
348
+ this.current = new Playback(clip, options, [...missing].sort((a, b) => a - b), moved);
349
+ this.setRootMotion(options.rootMotion ?? false);
350
+ this.apply();
351
+ return this.current;
352
+ }
353
+ stop(blend = DEFAULT_BLEND) {
354
+ this.startBlend(blend);
355
+ this.bindings = [];
356
+ this.current = null;
357
+ this.setRootMotion(false);
358
+ this.apply();
359
+ }
360
+ setRootMotion(on) {
361
+ this.rootMotion = on;
362
+ this.carried.set(0, 0, 0);
363
+ this.carriedTurn.identity();
364
+ if (on) {
365
+ this.origin ??= poseOf(this.root);
366
+ return;
367
+ }
368
+ if (!this.origin)
369
+ return;
370
+ this.root.position.copy(this.origin.position);
371
+ this.root.quaternion.copy(this.origin.quaternion);
372
+ this.origin = null;
373
+ }
374
+ update(seconds) {
375
+ const playback = this.current;
376
+ if (!playback && this.blended >= this.blend)
377
+ return;
378
+ if (playback && !playback.paused) {
379
+ this.advance(playback, seconds);
380
+ if (playback.base && playback.base.duration > 0)
381
+ playback.baseTime = THREE2.MathUtils.euclideanModulo(playback.baseTime + seconds * playback.speed, playback.base.duration);
382
+ }
383
+ this.blended = Math.min(this.blended + seconds, this.blend);
384
+ this.apply();
385
+ }
386
+ apply() {
387
+ const playback = this.current;
388
+ const weight = this.blend > 0 ? THREE2.MathUtils.smoothstep(this.blended / this.blend, 0, 1) : 1;
389
+ const driven = new Set;
390
+ const frame = playback?.frame ?? 0;
391
+ const baseFrame = playback?.base ? playback.baseTime * playback.base.fps : 0;
392
+ for (const binding of this.bindings) {
393
+ const { node, main, base, root } = binding;
394
+ driven.add(node);
395
+ const rest = this.rest.get(node);
396
+ const translation = main.translation ?? base.translation;
397
+ if (translation) {
398
+ translation.sample(translation === main.translation ? frame : baseFrame, this.sample);
399
+ node.position.fromArray(this.sample);
400
+ if (root)
401
+ node.position.applyQuaternion(this.entity);
402
+ } else
403
+ node.position.copy(rest.position);
404
+ const rotation = main.rotation ?? base.rotation;
405
+ if (rotation) {
406
+ rotation.sample(rotation === main.rotation ? frame : baseFrame, this.sample);
407
+ node.quaternion.fromArray(this.sample);
408
+ if (root)
409
+ node.quaternion.premultiply(this.entity);
410
+ } else
411
+ node.quaternion.copy(rest.quaternion);
412
+ const scale = main.scale ?? base.scale;
413
+ if (scale) {
414
+ scale.sample(scale === main.scale ? frame : baseFrame, this.sample);
415
+ node.scale.fromArray(this.sample);
416
+ } else
417
+ node.scale.copy(rest.scale);
418
+ this.mix(node, weight);
419
+ }
420
+ for (const node of this.touched) {
421
+ if (driven.has(node))
422
+ continue;
423
+ const rest = this.rest.get(node);
424
+ node.position.copy(rest.position);
425
+ node.quaternion.copy(rest.quaternion);
426
+ node.scale.copy(rest.scale);
427
+ this.mix(node, weight);
428
+ if (weight >= 1)
429
+ this.touched.delete(node);
430
+ }
431
+ for (const node of driven)
432
+ this.touched.add(node);
433
+ if (weight >= 1)
434
+ this.from.clear();
435
+ if (playback && this.rootMotion)
436
+ this.moveRoot(playback);
437
+ }
438
+ dispose() {
439
+ this.bindings = [];
440
+ this.current = null;
441
+ this.from.clear();
442
+ for (const node of this.touched) {
443
+ const rest = this.rest.get(node);
444
+ node.position.copy(rest.position);
445
+ node.quaternion.copy(rest.quaternion);
446
+ node.scale.copy(rest.scale);
447
+ }
448
+ this.touched.clear();
449
+ this.setRootMotion(false);
450
+ }
451
+ startBlend(seconds, moving = []) {
452
+ this.from.clear();
453
+ if (seconds > 0) {
454
+ for (const node of [...this.touched, ...moving])
455
+ this.from.set(node, poseOf(node));
456
+ }
457
+ this.blend = Math.max(seconds, 0);
458
+ this.blended = 0;
459
+ }
460
+ mix(node, weight) {
461
+ const from = this.from.get(node);
462
+ if (!from || weight >= 1)
463
+ return;
464
+ node.position.lerpVectors(from.position, node.position, weight);
465
+ this.target.copy(node.quaternion);
466
+ node.quaternion.copy(from.quaternion).slerp(this.target, weight);
467
+ node.scale.lerpVectors(from.scale, node.scale, weight);
468
+ }
469
+ advance(playback, seconds) {
470
+ const { duration } = playback;
471
+ const next = playback.time + seconds * playback.speed;
472
+ if (duration <= 0) {
473
+ playback.time = 0;
474
+ return;
475
+ }
476
+ if (!playback.loop) {
477
+ playback.time = THREE2.MathUtils.clamp(next, 0, duration);
478
+ return;
479
+ }
480
+ let laps = Math.floor(next / duration);
481
+ playback.time = next - laps * duration;
482
+ if (!this.rootMotion)
483
+ return;
484
+ for (;laps > 0; laps--)
485
+ this.carryLap(playback, 1);
486
+ for (;laps < 0; laps++)
487
+ this.carryLap(playback, -1);
488
+ }
489
+ carryLap(playback, direction) {
490
+ const end = this.mover(playback, playback.duration);
491
+ const turn = direction > 0 ? end.turn : end.turn.clone().invert();
492
+ const step = direction > 0 ? end.position : end.position.clone().applyQuaternion(turn).negate();
493
+ this.carried.add(step.applyQuaternion(this.carriedTurn));
494
+ this.carriedTurn.multiply(turn);
495
+ }
496
+ moverAt(clip, frame, position, turn) {
497
+ position.set(0, 0, 0);
498
+ turn.identity();
499
+ const translation = clip.track(0, TrackKind.moverTranslation);
500
+ const rotation = clip.track(0, TrackKind.moverRotation);
501
+ if (translation) {
502
+ translation.sample(frame, this.sample);
503
+ position.fromArray(this.sample);
504
+ }
505
+ if (rotation) {
506
+ rotation.sample(frame, this.sample);
507
+ turn.fromArray(this.sample).normalize();
508
+ }
509
+ }
510
+ mover(playback, time) {
511
+ const { clip } = playback;
512
+ const startPosition = new THREE2.Vector3;
513
+ const startTurn = new THREE2.Quaternion;
514
+ const position = new THREE2.Vector3;
515
+ const turn = new THREE2.Quaternion;
516
+ this.moverAt(clip, 0, startPosition, startTurn);
517
+ this.moverAt(clip, time * clip.fps, position, turn);
518
+ const back = startTurn.invert();
519
+ return { position: position.sub(startPosition).applyQuaternion(back), turn: back.multiply(turn) };
520
+ }
521
+ moveRoot(playback) {
522
+ const origin = this.origin;
523
+ if (!origin)
524
+ return;
525
+ const { position, turn } = this.mover(playback, playback.time);
526
+ this.moverPosition.copy(position).applyQuaternion(this.carriedTurn).add(this.carried).applyQuaternion(this.entity).applyQuaternion(GAME_TO_SCENE);
527
+ this.moverTurn.copy(GAME_TO_SCENE).multiply(this.entity).multiply(this.carriedTurn).multiply(turn).multiply(this.entityInverse).multiply(SCENE_TO_GAME);
528
+ this.root.position.copy(origin.position).add(this.moverPosition.applyQuaternion(origin.quaternion));
529
+ this.root.quaternion.copy(origin.quaternion).multiply(this.moverTurn);
530
+ }
531
+ }
532
+ // src/character.ts
533
+ import * as THREE6 from "three";
534
+
535
+ // src/material.ts
536
+ import * as THREE3 from "three";
537
+ var VERTEX_HEADER = `
538
+ #ifdef KATACHI_COLOR
539
+ attribute vec4 color;
540
+ varying vec4 vKatachiColor;
541
+ #endif
542
+ #ifdef KATACHI_UV1
543
+ attribute vec2 uv1;
544
+ #endif
545
+ #ifdef KATACHI_UV2
546
+ attribute vec2 uv2;
547
+ #endif
548
+ varying vec2 vKatachiUv[3];
549
+ `;
550
+ var VERTEX_BODY = `
551
+ #ifdef KATACHI_COLOR
552
+ vKatachiColor = color;
553
+ #endif
554
+ vKatachiUv[0] = uv;
555
+ #ifdef KATACHI_UV1
556
+ vKatachiUv[1] = uv1;
557
+ #else
558
+ vKatachiUv[1] = uv;
559
+ #endif
560
+ #ifdef KATACHI_UV2
561
+ vKatachiUv[2] = uv2;
562
+ #else
563
+ vKatachiUv[2] = uv;
564
+ #endif
565
+ `;
566
+ var FRAGMENT_HEADER = `
567
+ uniform vec3 kPaint;
568
+ uniform vec2 kDiffuseTile;
569
+ uniform vec2 kSpecTile;
570
+ uniform float kSpecIntensity;
571
+ uniform float kSpecFalloff;
572
+ uniform float kSpecFresnel;
573
+ uniform vec3 kSpecMask;
574
+ uniform sampler2D kSecondMap;
575
+ uniform sampler2D kSpecMap;
576
+ #ifdef KATACHI_HEAD_BLEND
577
+ uniform sampler2D kHeadMap;
578
+ uniform float kHeadMix;
579
+ uniform sampler2D kHeadNormal;
580
+ uniform float kHeadShape;
581
+ uniform sampler2D kEyePalette;
582
+ uniform vec4 kEyeRect;
583
+ uniform float kEyeColor;
584
+ #endif
585
+ #ifdef KATACHI_OVERLAYS
586
+ uniform sampler2D kOverlayMultiply;
587
+ uniform sampler2D kOverlayAdd;
588
+ #endif
589
+ #ifdef KATACHI_HAIR_TINT
590
+ uniform vec3 kHairColor;
591
+ uniform vec3 kHairHighlight;
592
+ #endif
593
+ #ifdef KATACHI_SKIN_TINT
594
+ uniform vec3 kSkinTint;
595
+ uniform vec3 kSkinReference;
596
+ #endif
597
+ #if defined(KATACHI_SKIN_TINT) || defined(KATACHI_HEAD_BLEND)
598
+ uniform float kSkinSpecular;
599
+ #endif
600
+ float kSkinMask = 0.0;
601
+ #ifdef KATACHI_COLOR
602
+ varying vec4 vKatachiColor;
603
+ #endif
604
+ varying vec2 vKatachiUv[3];
605
+ float kSpecular = 0.0;
606
+ `;
607
+ var FRAGMENT_DIFFUSE = `
608
+ #ifdef USE_MAP
609
+ vec4 kTexel = texture2D(map, vKatachiUv[KATACHI_DIFFUSE_SET] * kDiffuseTile);
610
+ #ifdef KATACHI_HEAD_BLEND
611
+ kTexel = mix(kTexel, texture2D(kHeadMap, vKatachiUv[KATACHI_DIFFUSE_SET] * kDiffuseTile), kHeadMix);
612
+ kSkinMask = 1.0;
613
+ // The eyes are painted in one square of the face's texture: an eye colour swaps in that cell of the game's 8 by 4 palette
614
+ vec2 kEye = (vKatachiUv[KATACHI_DIFFUSE_SET] - kEyeRect.xy) / kEyeRect.zw;
615
+ if (kEyeColor >= 0.0 && all(greaterThanEqual(kEye, vec2(0.0))) && all(lessThanEqual(kEye, vec2(1.0)))) {
616
+ vec2 kCell = vec2(mod(kEyeColor, 8.0), floor(kEyeColor / 8.0));
617
+ vec4 kIris = texture2D(kEyePalette, (kCell + clamp(kEye, 0.02, 0.98)) / vec2(8.0, 4.0));
618
+ kTexel.rgb = kIris.rgb;
619
+ }
620
+ #endif
621
+ #ifdef KATACHI_HAIR_TINT
622
+ // A hair template holds each strand's brightness in green and where highlights show in red
623
+ diffuseColor.rgb *= mix(kHairColor, kHairHighlight, kTexel.r) * kTexel.g * HAIR_GAIN;
624
+ diffuseColor.a *= kTexel.a;
625
+ #else
626
+ diffuseColor *= kTexel;
627
+ #endif
628
+ #endif
629
+ #ifdef KATACHI_SKIN_TINT
630
+ // Texels the colour of the body's own skin take the face's skin tone. A texel's colour, away from neutral grey, is
631
+ // measured along the body skin's own direction: paler or richer skin lies on that line, a little or a lot of the way,
632
+ // while white cloth sits at grey and blue jeans or red cloth stray off it. So freckles and pale patches tint with the rest.
633
+ vec3 kNeutral = vec3(1.0 / 3.0);
634
+ vec3 kChroma = diffuseColor.rgb / max(diffuseColor.r + diffuseColor.g + diffuseColor.b, 1e-4) - kNeutral;
635
+ vec3 kSkinWay = kSkinReference / max(kSkinReference.r + kSkinReference.g + kSkinReference.b, 1e-4) - kNeutral;
636
+ float kAlong = dot(kChroma, kSkinWay) / max(dot(kSkinWay, kSkinWay), 1e-6);
637
+ float kAside = length(kChroma - kAlong * kSkinWay);
638
+ float kBrightness = (diffuseColor.r + diffuseColor.g + diffuseColor.b) / max(kSkinReference.r + kSkinReference.g + kSkinReference.b, 1e-4);
639
+ #ifdef KATACHI_SKIN_PIECE
640
+ // All body: any texel near the skin's line is skin, however pale
641
+ kSkinMask = smoothstep(0.1, 0.3, kAlong) * (1.0 - smoothstep(2.2, 3.2, kAlong)) * (1.0 - smoothstep(0.03, 0.06, kAside));
642
+ #else
643
+ // Skin and cloth in one texture, such as shorts and bare legs: only texels close to the skin itself, so tan cloth stays
644
+ kSkinMask = smoothstep(0.5, 0.8, kAlong) * (1.0 - smoothstep(1.6, 2.2, kAlong)) * (1.0 - smoothstep(0.012, 0.025, kAside));
645
+ #endif
646
+ kSkinMask *= smoothstep(0.05, 0.15, kBrightness) * (1.0 - smoothstep(3.5, 5.0, kBrightness));
647
+ diffuseColor.rgb *= mix(vec3(1.0), kSkinTint, kSkinMask);
648
+ #endif
649
+ #ifdef KATACHI_OVERLAYS
650
+ // Beards, eyebrows, makeup and skin detail, composited on the CPU: the skin times one layer, plus the other
651
+ vec3 kAdded = texture2D(kOverlayAdd, vKatachiUv[KATACHI_DIFFUSE_SET]).rgb;
652
+ diffuseColor.rgb = diffuseColor.rgb * texture2D(kOverlayMultiply, vKatachiUv[KATACHI_DIFFUSE_SET]).rgb * 2.0 + kAdded * kAdded;
653
+ #endif
654
+ diffuseColor.rgb *= kPaint;
655
+ #ifdef KATACHI_SECOND_MAP
656
+ vec4 kSecond = texture2D(kSecondMap, vKatachiUv[KATACHI_SECOND_SET]);
657
+ diffuseColor.rgb = mix(diffuseColor.rgb, kSecond.rgb, kSecond.a);
658
+ #endif
659
+ #if defined(KATACHI_COLOR) && defined(KATACHI_DECAL)
660
+ diffuseColor.a *= vKatachiColor.a;
661
+ #endif
662
+ #ifdef KATACHI_FRINGE
663
+ if (diffuseColor.a >= KATACHI_FRINGE || diffuseColor.a < 0.02) discard;
664
+ #endif
665
+ `;
666
+ var FRAGMENT_ROUGHNESS = `
667
+ #ifdef KATACHI_SPEC_MAP
668
+ vec4 kSpec = texture2D(kSpecMap, vKatachiUv[KATACHI_SPEC_SET] * kSpecTile);
669
+ #else
670
+ vec4 kSpec = vec4(0.1);
671
+ #endif
672
+ kSpec.rg *= kSpec.rg;
673
+ kSpecular = clamp(dot(kSpec.rgb, kSpecMask) * kSpecIntensity, 0.0, 1.0);
674
+ roughnessFactor = clamp(pow(2.0 / (max(kSpec.a * kSpecFalloff, 1.0) + 2.0), 0.25), 0.04, 1.0);
675
+ #if defined(KATACHI_SKIN_TINT) || defined(KATACHI_HEAD_BLEND)
676
+ // Freemode pieces ask for far more shine than skin has: the game tames it in its head blend. A piece that is all
677
+ // body, such as the torso with its painted underwear, is matte all over; elsewhere only the skin-coloured texels are.
678
+ #if defined(KATACHI_HEAD_BLEND) || defined(KATACHI_SKIN_PIECE)
679
+ float kMatte = 1.0;
680
+ #else
681
+ float kMatte = kSkinMask;
682
+ #endif
683
+ kSpecular = mix(kSpecular, min(kSpecular, kSkinSpecular), kMatte);
684
+ roughnessFactor = mix(roughnessFactor, max(roughnessFactor, 0.55), kMatte);
685
+ #endif
686
+ `;
687
+ var FRAGMENT_NORMAL = `
688
+ #ifdef USE_NORMALMAP_TANGENTSPACE
689
+ vec2 kBump = texture2D(normalMap, vNormalMapUv).rg * 2.0 - 1.0;
690
+ #ifdef KATACHI_HEAD_BLEND
691
+ kBump = mix(kBump, texture2D(kHeadNormal, vNormalMapUv).rg * 2.0 - 1.0, kHeadShape);
692
+ #endif
693
+ normal = normalize(tbn * vec3(kBump * normalScale, max(sqrt(abs(1.0 - dot(kBump, kBump))), 0.001)));
694
+ #endif
695
+ `;
696
+ var FRAGMENT_SPECULAR = `
697
+ material.specularColor = vec3(kSpecular);
698
+ #ifdef KATACHI_METAL_SPEC
699
+ float kPeak = max(diffuseColor.r, max(diffuseColor.g, diffuseColor.b));
700
+ material.specularColor *= mix(vec3(1.0), diffuseColor.rgb / max(kPeak, 0.001), smoothstep(0.5, 1.0, kSpecular) * step(0.04, kPeak));
701
+ #endif
702
+ material.specularColorBlended = mix(material.specularColor, diffuseColor.rgb, metalnessFactor);
703
+ material.specularF90 = mix(clamp(kSpecular + 1.0 - kSpecFresnel, 0.0, 1.0), 1.0, metalnessFactor);
704
+ `;
705
+ var FRAGMENT_AMBIENT_OCCLUSION = `
706
+ #ifdef KATACHI_COLOR
707
+ reflectedLight.indirectDiffuse *= vKatachiColor.r;
708
+ reflectedLight.indirectSpecular *= vKatachiColor.r;
709
+ #endif
710
+ #ifdef KATACHI_NO_REFLECTION
711
+ reflectedLight.indirectSpecular = vec3(0.0);
712
+ #endif
713
+ `;
714
+ var PAINT_SLOTS = [1, 2, 3, 4, 5, 6, 7];
715
+ var FIXED_PAINT = 5;
716
+ function createPaints() {
717
+ return new Map(PAINT_SLOTS.map((slot) => [slot, { value: slot === FIXED_PAINT ? new THREE3.Color().setRGB(0.5, 0.5, 0.5) : new THREE3.Color(16777215) }]));
718
+ }
719
+ function paintUniform(parameters, paints) {
720
+ const value = parameters.matDiffuseColor;
721
+ const shared = value?.[0] === 2 ? paints.get(Math.round(value[1])) : undefined;
722
+ if (shared)
723
+ return shared;
724
+ return { value: value ? new THREE3.Color().setRGB(value[0], value[1], value[2]) : new THREE3.Color(16777215) };
725
+ }
726
+ var PAINT_UV_SETS = {
727
+ "3": [0, 1, 1],
728
+ "4": [0, 1, 1],
729
+ "8": [1, 1, 1],
730
+ "9": [2, 1, 2]
731
+ };
732
+ function uvSets(name) {
733
+ return PAINT_UV_SETS[/^vehicle_paint(\d)/.exec(name)?.[1] ?? ""] ?? [0, 1, 0];
734
+ }
735
+ function vec2Parameter(parameters, name) {
736
+ const value = parameters[name];
737
+ return value ? new THREE3.Vector2(value[0], value[1]) : new THREE3.Vector2(1, 1);
738
+ }
739
+ function load(library, path, role) {
740
+ return path ? library.load(path, role) : Promise.resolve(null);
741
+ }
742
+ var PAINT_GLOSS = 16;
743
+ var REFLECTIVE = /^vehicle_|reflect|glass|mirror/;
744
+ function missingDiffuseColor(name) {
745
+ if (name.includes("smallspecmap"))
746
+ return 1;
747
+ return name.includes("tyrewall") || name.includes("black") ? 0.018 : 0.18;
748
+ }
749
+ var HAIR_GAIN = "2.3";
750
+ function install(material, uniforms) {
751
+ const defines = material.defines;
752
+ material.onBeforeCompile = (program) => {
753
+ Object.assign(program.uniforms, uniforms);
754
+ program.vertexShader = program.vertexShader.replace("#include <common>", `#include <common>
755
+ ${VERTEX_HEADER}`).replace("#include <begin_vertex>", `#include <begin_vertex>
756
+ ${VERTEX_BODY}`);
757
+ program.fragmentShader = program.fragmentShader.replace("#include <common>", `#include <common>
758
+ ${FRAGMENT_HEADER}`).replace("#include <map_fragment>", FRAGMENT_DIFFUSE).replace("#include <roughnessmap_fragment>", `#include <roughnessmap_fragment>
759
+ ${FRAGMENT_ROUGHNESS}`).replace("#include <normal_fragment_maps>", `#include <normal_fragment_maps>
760
+ ${FRAGMENT_NORMAL}`).replace("#include <lights_physical_fragment>", `#include <lights_physical_fragment>
761
+ ${FRAGMENT_SPECULAR}`).replace("#include <aomap_fragment>", `#include <aomap_fragment>
762
+ ${FRAGMENT_AMBIENT_OCCLUSION}`);
763
+ };
764
+ material.customProgramCacheKey = () => JSON.stringify(defines);
765
+ }
766
+ var HAIR_CUTOFF = 0.5;
767
+ function isHair(material) {
768
+ return /^ped_hair/.test(material.userData.extras?.shader ?? "");
769
+ }
770
+ function fringeMaterial(base) {
771
+ const material = deriveMaterial(base, { KATACHI_FRINGE: base.alphaTest.toFixed(3) }, {});
772
+ material.alphaTest = 0;
773
+ material.transparent = true;
774
+ material.depthWrite = false;
775
+ return material;
776
+ }
777
+ function deriveMaterial(base, defines, uniforms, map) {
778
+ const userData = base.userData;
779
+ base.userData = {};
780
+ const material = base.clone();
781
+ base.userData = userData;
782
+ material.userData = { ...userData, derived: true };
783
+ material.defines = { ...base.defines, ...defines };
784
+ if (map !== undefined)
785
+ material.map = map;
786
+ install(material, { ...userData.uniforms, ...uniforms });
787
+ return material;
788
+ }
789
+ async function buildMaterial(extras, geometry, paints, library) {
790
+ const { textures, parameters, shader: name, bucket, missingDiffuse } = extras;
791
+ const [map, second, spec, bump] = await Promise.all([
792
+ load(library, textures.DiffuseSampler, "color"),
793
+ load(library, textures.DiffuseSampler2, "color"),
794
+ load(library, textures.SpecSampler, "data"),
795
+ load(library, textures.BumpSampler, "data")
796
+ ]);
797
+ const material = new THREE3.MeshPhysicalMaterial({ name, map, normalMap: bump });
798
+ if (bump)
799
+ material.normalScale.setScalar(parameters.bumpiness?.[0] ?? 1);
800
+ if (!map && missingDiffuse)
801
+ material.color.setScalar(missingDiffuseColor(missingDiffuse));
802
+ const isGlass = name.startsWith("vehicle_vehglass");
803
+ const isPaint = name.startsWith("vehicle_paint") || name === "vehicle_shuts";
804
+ const isDecal = bucket === 2 || name.startsWith("vehicle_badges") || name.startsWith("vehicle_decal");
805
+ if (isPaint) {
806
+ material.clearcoat = 1;
807
+ material.clearcoatRoughness = 0.02;
808
+ material.metalness = 0.4;
809
+ }
810
+ if (isGlass && !map) {
811
+ material.color.setRGB(0.01, 0.012, 0.014);
812
+ material.opacity = name === "vehicle_vehglass" ? 0.42 : 0.2;
813
+ }
814
+ if (isGlass) {
815
+ material.clearcoat = 1;
816
+ material.clearcoatRoughness = 0.02;
817
+ }
818
+ if (bucket === 1 || isDecal) {
819
+ material.transparent = true;
820
+ material.depthWrite = false;
821
+ }
822
+ if (isDecal) {
823
+ material.visible = map !== null;
824
+ material.polygonOffset = true;
825
+ material.polygonOffsetFactor = -1;
826
+ material.polygonOffsetUnits = -2;
827
+ }
828
+ if (bucket === 3)
829
+ material.alphaTest = 0.33;
830
+ if (name.startsWith("ped_hair")) {
831
+ material.side = THREE3.DoubleSide;
832
+ material.alphaTest = HAIR_CUTOFF;
833
+ }
834
+ const [diffuseSet, secondSet, specSet] = uvSets(name);
835
+ const defines = material.defines;
836
+ defines.KATACHI_DIFFUSE_SET = diffuseSet;
837
+ defines.KATACHI_SECOND_SET = secondSet;
838
+ defines.KATACHI_SPEC_SET = specSet;
839
+ if (geometry.hasAttribute("uv1"))
840
+ defines.KATACHI_UV1 = "";
841
+ if (geometry.hasAttribute("uv2"))
842
+ defines.KATACHI_UV2 = "";
843
+ if (second)
844
+ defines.KATACHI_SECOND_MAP = "";
845
+ if (spec)
846
+ defines.KATACHI_SPEC_MAP = "";
847
+ if (isDecal)
848
+ defines.KATACHI_DECAL = "";
849
+ if (geometry.hasAttribute("color"))
850
+ defines.KATACHI_COLOR = "";
851
+ if (!REFLECTIVE.test(name))
852
+ defines.KATACHI_NO_REFLECTION = "";
853
+ if (!name.startsWith("vehicle_"))
854
+ defines.KATACHI_METAL_SPEC = "";
855
+ defines.HAIR_GAIN = HAIR_GAIN;
856
+ const secondMap = { value: second };
857
+ const uniforms = {
858
+ kPaint: paintUniform(parameters, paints),
859
+ kDiffuseTile: { value: vec2Parameter(parameters, "DiffuseTexTileUV") },
860
+ kSpecTile: { value: vec2Parameter(parameters, "specTexTileUV") },
861
+ kSpecIntensity: { value: parameters.specularIntensityMult?.[0] ?? 0.25 },
862
+ kSpecFalloff: { value: (parameters.specularFalloffMult?.[0] ?? 100) * (isPaint ? PAINT_GLOSS : 1) },
863
+ kSpecFresnel: { value: parameters.specularFresnel?.[0] ?? 0.97 },
864
+ kSpecMask: { value: new THREE3.Vector3(...(parameters.specMapIntMask ?? [1, 0, 0]).slice(0, 3)) },
865
+ kSecondMap: secondMap,
866
+ kSpecMap: { value: spec }
867
+ };
868
+ install(material, uniforms);
869
+ material.userData = { extras, secondMap, uniforms };
870
+ return material;
871
+ }
872
+
873
+ // src/model.ts
874
+ import * as THREE4 from "three";
3
875
  function disposeMesh(object) {
4
876
  const mesh = object;
5
877
  mesh.geometry?.dispose();
@@ -10,12 +882,12 @@ function prepareMesh(mesh) {
10
882
  mesh.receiveShadow = true;
11
883
  mesh.frustumCulled = false;
12
884
  }
13
- var IDENTITY = new THREE.Matrix4;
885
+ var IDENTITY = new THREE4.Matrix4;
14
886
  var AT_ORIGIN = 0.0001;
15
887
  function jointCentroids(mesh) {
16
888
  const { position, skinIndex, skinWeight } = mesh.geometry.attributes;
17
889
  const sums = new Map;
18
- const vertex = new THREE.Vector3;
890
+ const vertex = new THREE4.Vector3;
19
891
  for (let index = 0;index < position.count; index++) {
20
892
  let joint = 0;
21
893
  let weight = -1;
@@ -25,7 +897,7 @@ function jointCentroids(mesh) {
25
897
  weight = skinWeight.getComponent(index, slot);
26
898
  joint = skinIndex.getComponent(index, slot);
27
899
  }
28
- const sum = sums.get(joint) ?? { total: new THREE.Vector3, count: 0 };
900
+ const sum = sums.get(joint) ?? { total: new THREE4.Vector3, count: 0 };
29
901
  sum.total.add(vertex.fromBufferAttribute(position, index));
30
902
  sum.count++;
31
903
  sums.set(joint, sum);
@@ -37,7 +909,7 @@ function placedBind(bone, anchor, rest, centroid) {
37
909
  const anchorRest = rest.get(anchor)?.world;
38
910
  if (!centroid || !boneRest || !anchorRest)
39
911
  return null;
40
- const boneInAnchor = new THREE.Vector3().setFromMatrixPosition(anchorRest.clone().invert().multiply(boneRest));
912
+ const boneInAnchor = new THREE4.Vector3().setFromMatrixPosition(anchorRest.clone().invert().multiply(boneRest));
41
913
  return centroid.distanceTo(boneInAnchor) < centroid.length() ? boneRest.clone().invert().multiply(anchorRest) : null;
42
914
  }
43
915
  function attachModel(model, bones, root, anchor, rest) {
@@ -49,7 +921,7 @@ function attachModel(model, bones, root, anchor, rest) {
49
921
  if (!source.isMesh)
50
922
  return;
51
923
  if (source.isSkinnedMesh) {
52
- const mesh = new THREE.SkinnedMesh(source.geometry, source.material);
924
+ const mesh = new THREE4.SkinnedMesh(source.geometry, source.material);
53
925
  const joints = [];
54
926
  let centroids;
55
927
  const inverses = source.skeleton.bones.map((bone, index) => {
@@ -57,17 +929,17 @@ function attachModel(model, bones, root, anchor, rest) {
57
929
  joints.push(known ?? anchor);
58
930
  const inverse = source.skeleton.boneInverses[index];
59
931
  if (!known)
60
- return new THREE.Matrix4().multiplyMatrices(toModel, bone.matrixWorld).multiply(inverse);
61
- if (!rest || known === anchor || new THREE.Vector3().setFromMatrixPosition(inverse).lengthSq() > AT_ORIGIN)
932
+ return new THREE4.Matrix4().multiplyMatrices(toModel, bone.matrixWorld).multiply(inverse);
933
+ if (!rest || known === anchor || new THREE4.Vector3().setFromMatrixPosition(inverse).lengthSq() > AT_ORIGIN)
62
934
  return inverse;
63
935
  centroids ??= jointCentroids(source);
64
936
  return placedBind(known, anchor, rest, centroids.get(index)) ?? inverse;
65
937
  });
66
- mesh.bind(new THREE.Skeleton(joints, inverses), IDENTITY);
938
+ mesh.bind(new THREE4.Skeleton(joints, inverses), IDENTITY);
67
939
  root.add(mesh);
68
940
  attached.push(mesh);
69
941
  } else {
70
- const mesh = new THREE.Mesh(source.geometry, source.material);
942
+ const mesh = new THREE4.Mesh(source.geometry, source.material);
71
943
  anchor.add(mesh);
72
944
  attached.push(mesh);
73
945
  }
@@ -78,16 +950,23 @@ function attachModel(model, bones, root, anchor, rest) {
78
950
  function detach(objects) {
79
951
  for (const object of objects) {
80
952
  object.parent?.remove(object);
81
- object.skeleton?.dispose();
953
+ const mesh = object;
954
+ mesh.skeleton?.dispose();
955
+ if (mesh.geometry?.userData.owned)
956
+ mesh.geometry.dispose();
957
+ for (const material of [mesh.material].flat())
958
+ if (material?.userData.derived)
959
+ material.dispose();
82
960
  }
83
961
  }
84
962
 
85
963
  class Model {
86
964
  name;
87
965
  source;
88
- root = new THREE.Group;
966
+ root = new THREE4.Group;
89
967
  bones = new Map;
90
968
  view = [0.6, 0.35, 0.75];
969
+ animator = null;
91
970
  constructor(name, source) {
92
971
  this.name = name;
93
972
  this.source = source;
@@ -104,18 +983,176 @@ class Model {
104
983
  this.root.position.set(0, 0, 0);
105
984
  this.root.updateMatrixWorld(true);
106
985
  this.root.traverse((object) => object.skeleton?.update());
107
- const box = new THREE.Box3().setFromObject(this.source.scene, true);
108
- const center = box.getCenter(new THREE.Vector3);
109
- const offset = new THREE.Vector3(-center.x, -box.min.y, -center.z);
986
+ const box = new THREE4.Box3().setFromObject(this.source.scene, true);
987
+ const center = box.getCenter(new THREE4.Vector3);
988
+ const offset = new THREE4.Vector3(-center.x, -box.min.y, -center.z);
110
989
  this.root.position.copy(offset);
111
990
  this.root.updateMatrixWorld(true);
112
991
  return box.translate(offset);
113
992
  }
993
+ play(clip, options) {
994
+ this.animator ??= new Animator(this.root, this.bones);
995
+ return this.animator.play(clip, options);
996
+ }
997
+ stop({ blend } = {}) {
998
+ this.animator?.stop(blend);
999
+ }
1000
+ get playback() {
1001
+ return this.animator?.playback ?? null;
1002
+ }
1003
+ setRootMotion(on) {
1004
+ this.animator?.setRootMotion(on);
1005
+ }
1006
+ update(seconds) {
1007
+ this.animator?.update(seconds);
1008
+ }
1009
+ refresh() {
1010
+ this.animator?.apply();
1011
+ }
114
1012
  dispose() {
1013
+ this.animator?.dispose();
115
1014
  this.root.traverse(disposeMesh);
116
1015
  }
117
1016
  }
118
1017
 
1018
+ // src/overlays.ts
1019
+ import * as THREE5 from "three";
1020
+ var OVERLAYS = [
1021
+ ["blemishes", "blemishes"],
1022
+ ["facialHair", "facialHair"],
1023
+ ["eyebrows", "eyebrow"],
1024
+ ["ageing", "aging"],
1025
+ ["makeup", "makeup"],
1026
+ ["blush", "blusher"],
1027
+ ["complexion", "damage"],
1028
+ ["sunDamage", "baseDetail"],
1029
+ ["lipstick", "skinDetail1"],
1030
+ ["freckles", "skinDetail2"],
1031
+ ["chestHair", "bodyOverlay1"],
1032
+ ["bodyBlemishes", "bodyOverlay2"],
1033
+ ["moreBodyBlemishes", "bodyOverlay3"]
1034
+ ];
1035
+ var TINTED = new Set(["facialHair", "eyebrows", "chestHair", "blush", "lipstick"]);
1036
+ var BODY_OVERLAYS = new Set(["chestHair", "bodyBlemishes", "moreBodyBlemishes"]);
1037
+ var FACE_ORDER = [7, 6, 3, 9, 0, 4, 5, 8, 2, 1];
1038
+ var BODY_ORDER = [11, 12, 10];
1039
+ var SIZE = 512;
1040
+ var DETAIL_COVERAGE = 0.9;
1041
+ var MAX_MULTIPLY = 2;
1042
+ var toLinear = Float32Array.from({ length: 256 }, (_, byte) => new THREE5.Color().setRGB(byte / 255, 0, 0, THREE5.SRGBColorSpace).r);
1043
+ function isDetail(pixels) {
1044
+ const { data } = pixels;
1045
+ let solid = 0;
1046
+ for (let index = 3;index < data.length; index += 4)
1047
+ if (data[index] >= 250)
1048
+ solid++;
1049
+ return solid / (data.length / 4) >= DETAIL_COVERAGE;
1050
+ }
1051
+ var luminance = (r, g, b) => 0.2126 * r + 0.7152 * g + 0.0722 * b;
1052
+
1053
+ class OverlayCanvas {
1054
+ uniforms = {
1055
+ kOverlayMultiply: { value: neutral([128, 128, 128, 255]) },
1056
+ kOverlayAdd: { value: neutral([0, 0, 0, 255]) }
1057
+ };
1058
+ multiply = new Float32Array(SIZE * SIZE * 3);
1059
+ add = new Float32Array(SIZE * SIZE * 3);
1060
+ textures = null;
1061
+ compose(layers) {
1062
+ const { multiply, add } = this;
1063
+ multiply.fill(1);
1064
+ add.fill(0);
1065
+ for (const layer of layers)
1066
+ this.draw(layer);
1067
+ const textures = this.textures ??= { multiply: dataTexture(), add: dataTexture() };
1068
+ const multiplied = textures.multiply.image.data;
1069
+ const added = textures.add.image.data;
1070
+ for (let texel = 0, channel = 0;texel < SIZE * SIZE * 4; texel += 4, channel += 3) {
1071
+ for (let offset = 0;offset < 3; offset++) {
1072
+ multiplied[texel + offset] = Math.round(Math.min(multiply[channel + offset] / MAX_MULTIPLY, 1) * 255);
1073
+ added[texel + offset] = Math.round(Math.sqrt(Math.min(add[channel + offset], 1)) * 255);
1074
+ }
1075
+ multiplied[texel + 3] = 255;
1076
+ added[texel + 3] = 255;
1077
+ }
1078
+ textures.multiply.needsUpdate = true;
1079
+ textures.add.needsUpdate = true;
1080
+ this.uniforms.kOverlayMultiply.value = textures.multiply;
1081
+ this.uniforms.kOverlayAdd.value = textures.add;
1082
+ }
1083
+ dispose() {
1084
+ this.textures?.multiply.dispose();
1085
+ this.textures?.add.dispose();
1086
+ this.textures = null;
1087
+ }
1088
+ draw(layer) {
1089
+ const { pixels, opacity } = layer;
1090
+ if (opacity <= 0)
1091
+ return;
1092
+ const detail = isDetail(pixels);
1093
+ const tint = detail ? null : layer.tint;
1094
+ const scale = tint ? tint.clone().multiplyScalar(1 / Math.max(averageCovered(pixels), 0.0001)) : null;
1095
+ const { multiply, add } = this;
1096
+ const factor = Float32Array.from({ length: 256 }, (_, byte) => 1 + (Math.min(2 * byte / 255, MAX_MULTIPLY) ** 2.2 - 1) * opacity);
1097
+ for (let y = 0;y < SIZE; y++) {
1098
+ const sourceRow = Math.min(Math.floor(y * pixels.height / SIZE), pixels.height - 1) * pixels.width;
1099
+ for (let x = 0;x < SIZE; x++) {
1100
+ const source = (sourceRow + Math.min(Math.floor(x * pixels.width / SIZE), pixels.width - 1)) * 4;
1101
+ const target = (y * SIZE + x) * 3;
1102
+ const r = toLinear[pixels.data[source]];
1103
+ const g = toLinear[pixels.data[source + 1]];
1104
+ const b = toLinear[pixels.data[source + 2]];
1105
+ if (detail) {
1106
+ for (let channel = 0;channel < 3; channel++) {
1107
+ const amount = factor[pixels.data[source + channel]];
1108
+ multiply[target + channel] *= amount;
1109
+ add[target + channel] *= amount;
1110
+ }
1111
+ continue;
1112
+ }
1113
+ const alpha = pixels.data[source + 3] / 255 * opacity;
1114
+ if (alpha <= 0)
1115
+ continue;
1116
+ const shade = scale ? luminance(r, g, b) : 1;
1117
+ const keep = 1 - alpha;
1118
+ multiply[target] *= keep;
1119
+ multiply[target + 1] *= keep;
1120
+ multiply[target + 2] *= keep;
1121
+ add[target] = add[target] * keep + Math.min(scale ? scale.r * shade : r, 1) * alpha;
1122
+ add[target + 1] = add[target + 1] * keep + Math.min(scale ? scale.g * shade : g, 1) * alpha;
1123
+ add[target + 2] = add[target + 2] * keep + Math.min(scale ? scale.b * shade : b, 1) * alpha;
1124
+ }
1125
+ }
1126
+ }
1127
+ }
1128
+ function averageCovered(pixels) {
1129
+ const { data } = pixels;
1130
+ let sum = 0;
1131
+ let weight = 0;
1132
+ for (let index = 0;index < data.length; index += 4) {
1133
+ const alpha = data[index + 3] / 255;
1134
+ sum += luminance(toLinear[data[index]], toLinear[data[index + 1]], toLinear[data[index + 2]]) * alpha;
1135
+ weight += alpha;
1136
+ }
1137
+ return weight > 0 ? sum / weight : 1;
1138
+ }
1139
+ function neutral(rgba) {
1140
+ const texture = new THREE5.DataTexture(new Uint8Array(rgba), 1, 1, THREE5.RGBAFormat);
1141
+ texture.needsUpdate = true;
1142
+ return texture;
1143
+ }
1144
+ function dataTexture() {
1145
+ const texture = new THREE5.DataTexture(new Uint8Array(SIZE * SIZE * 4), SIZE, SIZE, THREE5.RGBAFormat);
1146
+ texture.generateMipmaps = true;
1147
+ texture.minFilter = THREE5.LinearMipmapLinearFilter;
1148
+ texture.magFilter = THREE5.LinearFilter;
1149
+ texture.anisotropy = 4;
1150
+ return texture;
1151
+ }
1152
+ function overlayOrder(body) {
1153
+ return body ? BODY_ORDER : FACE_ORDER;
1154
+ }
1155
+
119
1156
  // src/character.ts
120
1157
  var PROP_ANCHORS = {
121
1158
  head: "SKEL_Head",
@@ -130,53 +1167,628 @@ var PROP_ANCHORS = {
130
1167
  lfoot: "SKEL_L_Foot",
131
1168
  rfoot: "SKEL_R_Foot"
132
1169
  };
1170
+ var TOP_ARMS = {
1171
+ mp_m_freemode_01: [0, 0, 2, 14, 14, 5, 14, 14, 8, 0, 14, 15, 12, 11, 12, 15],
1172
+ mp_f_freemode_01: [0, 5, 2, 3, 4, 4, 5, 5, 5, 0, 5, 4, 12, 15, 14, 15]
1173
+ };
1174
+ function readChoice(choice) {
1175
+ if (choice === "none")
1176
+ return { none: true, index: -1 };
1177
+ const [where, variant] = choice.split(":");
1178
+ const slash = where.lastIndexOf("/");
1179
+ return { none: false, collection: slash >= 0 ? where.slice(0, slash) : undefined, index: Number(where.slice(slash + 1)), variant: variant || undefined };
1180
+ }
1181
+ function choose(pieces, component, choice, own) {
1182
+ const matches = pieces.filter((piece) => piece.component === component && piece.index === choice.index && !piece.alternate);
1183
+ if (choice.collection)
1184
+ return matches.find((piece) => piece.collection === choice.collection);
1185
+ return matches.find((piece) => piece.collection === own) ?? matches[0];
1186
+ }
1187
+ function topArms(name, outfit) {
1188
+ if (!outfit.jbib)
1189
+ return;
1190
+ const top = readChoice(outfit.jbib);
1191
+ if (top.none || top.collection && top.collection !== name)
1192
+ return;
1193
+ return TOP_ARMS[name]?.[top.index];
1194
+ }
1195
+ function warm(name, entry, loader, look) {
1196
+ const wanted = [];
1197
+ const outfit = { ...look.outfit };
1198
+ const top = topArms(name, outfit);
1199
+ if (top !== undefined && outfit.uppr === undefined)
1200
+ outfit.uppr = String(top);
1201
+ for (const [slot, text] of Object.entries(outfit)) {
1202
+ const choice = readChoice(text);
1203
+ const prop = slot.startsWith("p_");
1204
+ const piece = choice.none ? undefined : choose(prop ? entry.props : entry.components, prop ? slot.slice(2) : slot, choice, name);
1205
+ if (piece)
1206
+ wanted.push([piece, choice.variant]);
1207
+ }
1208
+ if (look.head) {
1209
+ for (const id of new Set([look.head.shapeFirst, look.head.shapeSecond, look.head.skinFirst, look.head.skinSecond])) {
1210
+ const piece = choose(entry.components, "head", { none: false, index: id }, name);
1211
+ if (piece)
1212
+ wanted.push([piece, undefined]);
1213
+ }
1214
+ }
1215
+ for (const [piece, variant] of wanted) {
1216
+ const chosen = variant ?? Object.keys(piece.diffuse)[0];
1217
+ loader.piece(piece, chosen).catch(() => {});
1218
+ if (chosen && piece.diffuse[chosen])
1219
+ loader.bytes(piece.diffuse[chosen]).catch(() => {});
1220
+ }
1221
+ }
1222
+ var NO_SKIN = new Set(["hair", "head"]);
1223
+ var BODY = new Set(["uppr"]);
1224
+ var FREEMODE = /^mp_[mf]_freemode_01$/;
1225
+ var SKIN_SPECULAR = 0.06;
1226
+ var DEFAULT_HAIR = "#2e221b";
1227
+ var PARTS = {
1228
+ face: { bones: ["SKEL_Head", "FACIAL_facialRoot", "FB_Brow_Centre_000", "FB_Jaw_000"], reach: 0.11 },
1229
+ hands: { bones: ["SKEL_L_Hand", "SKEL_L_Finger22", "SKEL_R_Hand", "SKEL_R_Finger22"], reach: 0.05 },
1230
+ "left-hand": { bones: ["SKEL_L_Hand", "SKEL_L_Finger22", "SKEL_L_Finger02"], reach: 0.05 },
1231
+ "right-hand": { bones: ["SKEL_R_Hand", "SKEL_R_Finger22", "SKEL_R_Finger02"], reach: 0.05 },
1232
+ feet: { bones: ["SKEL_L_Foot", "SKEL_L_Toe0", "SKEL_R_Foot", "SKEL_R_Toe0"], reach: 0.07 }
1233
+ };
1234
+ var EYE_COLORS = ["Green", "Emerald", "Light blue", "Ocean blue", "Light brown", "Dark brown", "Hazel", "Dark gray", "Light gray", "Pink", "Yellow", "Purple", "Blackout", "Shades of gray", "Tequila sunrise", "Atomic", "Warp", "ECola", "Space ranger", "Ying yang", "Bullseye", "Lizard", "Dragon", "Extra terrestrial", "Goat", "Smiley", "Possessed", "Demon", "Infected", "Alien", "Undead", "Zombie"];
1235
+ function eyeRect(mesh) {
1236
+ const skinned = mesh;
1237
+ const geometry = mesh.geometry;
1238
+ const uv = geometry.getAttribute("uv");
1239
+ const index = geometry.getAttribute("skinIndex");
1240
+ const weight = geometry.getAttribute("skinWeight");
1241
+ if (!skinned.isSkinnedMesh || !uv || !index || !weight)
1242
+ return null;
1243
+ const eyes = new Set(skinned.skeleton.bones.flatMap((bone, position) => /^FB_[LR]_Eye_/.test(bone.name) ? [position] : []));
1244
+ if (eyes.size === 0)
1245
+ return null;
1246
+ const bounds = new THREE6.Box2;
1247
+ const point = new THREE6.Vector2;
1248
+ for (let vertex = 0;vertex < uv.count; vertex++) {
1249
+ for (let slot = 0;slot < 4; slot++) {
1250
+ if (eyes.has(index.getComponent(vertex, slot)) && weight.getComponent(vertex, slot) > 0.9)
1251
+ bounds.expandByPoint(point.set(uv.getX(vertex), uv.getY(vertex)));
1252
+ }
1253
+ }
1254
+ if (bounds.isEmpty())
1255
+ return null;
1256
+ const size = bounds.getSize(new THREE6.Vector2);
1257
+ return new THREE6.Vector4(bounds.min.x, bounds.min.y, size.x, size.y);
1258
+ }
1259
+ function toneColor(tone) {
1260
+ return typeof tone === "string" ? new THREE6.Color(tone) : new THREE6.Color().setRGB(tone[0] / 255, tone[1] / 255, tone[2] / 255, THREE6.SRGBColorSpace);
1261
+ }
1262
+ function meshesOf(model) {
1263
+ const meshes = [];
1264
+ model.scene.traverse((object) => {
1265
+ if (object.isMesh)
1266
+ meshes.push(object);
1267
+ });
1268
+ return meshes;
1269
+ }
1270
+ var FACE_FEATURES = [
1271
+ ["noseWidth", "micro_nose_thin", "micro_nose_wide"],
1272
+ ["noseHeight", "micro_nose_up", "micro_nose_down"],
1273
+ ["noseLength", "micro_nose_long", "micro_nose_short"],
1274
+ ["noseProfile", "micro_nose_profile_crooked", "micro_nose_profile_curved"],
1275
+ ["noseTip", "micro_nose_tip_up", "micro_nose_tip_down"],
1276
+ ["noseTwist", "micro_nose_broke_left", "micro_nose_broke_right"],
1277
+ ["browHeight", "micro_brow_up", "micro_brow_down"],
1278
+ ["browDepth", "micro_brow_in", "micro_brow_out"],
1279
+ ["cheekboneHeight", "micro_cheek_up", "micro_cheek_down"],
1280
+ ["cheekboneWidth", "micro_cheek_in", "micro_cheek_out"],
1281
+ ["cheekWidth", "micro_cheek_puffed", "micro_cheek_gaunt"],
1282
+ ["eyeOpening", "micro_eyes_wide", "micro_eyes_squinted"],
1283
+ ["lipThickness", "micro_lips_fat", "micro_lips_thin"],
1284
+ ["jawWidth", "micro_jaw_narrow", "micro_jaw_wide"],
1285
+ ["jawShape", "micro_jaw_round", "micro_jaw_square"],
1286
+ ["chinHeight", "micro_chin_up", "micro_chin_down"],
1287
+ ["chinDepth", "micro_chin_in", "micro_chin_out"],
1288
+ ["chinShape", "micro_chin_pointed", "micro_chin_square"],
1289
+ ["chinCleft", null, "micro_chin_bum"],
1290
+ ["neckThickness", null, "micro_neck_male"]
1291
+ ];
1292
+ function faceGeometry(mesh, second, targets) {
1293
+ const geometry = mesh.geometry;
1294
+ const count = geometry.getAttribute("position").count;
1295
+ const other = second?.geometry;
1296
+ const shared = other && other.getAttribute("position")?.count === count;
1297
+ const usable = targets && [...targets.values()].every((offsets) => offsets.length === count * 3);
1298
+ const slots = new Map;
1299
+ if (!shared && !usable)
1300
+ return slots;
1301
+ const delta = (name) => {
1302
+ const values = new Float32Array(count * 3);
1303
+ const from = geometry.getAttribute(name);
1304
+ const to = other?.getAttribute(name);
1305
+ if (shared && from && to && to.count === count) {
1306
+ for (let index = 0;index < count; index++) {
1307
+ values[index * 3] = to.getX(index) - from.getX(index);
1308
+ values[index * 3 + 1] = to.getY(index) - from.getY(index);
1309
+ values[index * 3 + 2] = to.getZ(index) - from.getZ(index);
1310
+ }
1311
+ }
1312
+ return new THREE6.Float32BufferAttribute(values, 3);
1313
+ };
1314
+ const blended = geometry.clone();
1315
+ blended.userData.owned = true;
1316
+ const positions = [delta("position")];
1317
+ const normals = [delta("normal")];
1318
+ slots.set("parent", 0);
1319
+ if (usable) {
1320
+ const still = new THREE6.Float32BufferAttribute(new Float32Array(count * 3), 3);
1321
+ for (const [name, offsets] of targets) {
1322
+ slots.set(name, positions.length);
1323
+ positions.push(new THREE6.Float32BufferAttribute(offsets, 3));
1324
+ normals.push(still);
1325
+ }
1326
+ }
1327
+ blended.morphAttributes.position = positions;
1328
+ if (geometry.getAttribute("normal"))
1329
+ blended.morphAttributes.normal = normals;
1330
+ blended.morphTargetsRelative = true;
1331
+ mesh.geometry = blended;
1332
+ mesh.updateMorphTargets();
1333
+ return slots;
1334
+ }
1335
+ var SHELL_REACH = 0.05;
1336
+ var SHELL_VERTICES = 0.25;
1337
+ function hairShells(meshes) {
1338
+ const hair = meshes.filter((mesh) => isHair(mesh.material));
1339
+ if (hair.length < 2)
1340
+ return [];
1341
+ const boundsOf = (mesh) => {
1342
+ mesh.geometry.computeBoundingBox();
1343
+ return mesh.geometry.boundingBox.clone();
1344
+ };
1345
+ const strands = boundsOf(hair[0]).expandByScalar(SHELL_REACH);
1346
+ const count = (mesh) => mesh.geometry.getAttribute("position").count;
1347
+ return hair.slice(1).filter((mesh) => count(mesh) < count(hair[0]) * SHELL_VERTICES && strands.containsBox(boundsOf(mesh)));
1348
+ }
1349
+ function fringe(mesh) {
1350
+ const material = fringeMaterial(mesh.material);
1351
+ const skinned = mesh;
1352
+ let twin;
1353
+ if (skinned.isSkinnedMesh) {
1354
+ const copy = new THREE6.SkinnedMesh(skinned.geometry, material);
1355
+ copy.bind(skinned.skeleton, skinned.bindMatrix);
1356
+ twin = copy;
1357
+ } else {
1358
+ twin = new THREE6.Mesh(mesh.geometry, material);
1359
+ }
1360
+ twin.position.copy(mesh.position);
1361
+ twin.quaternion.copy(mesh.quaternion);
1362
+ twin.scale.copy(mesh.scale);
1363
+ mesh.parent?.add(twin);
1364
+ prepareMesh(twin);
1365
+ return twin;
1366
+ }
133
1367
 
134
1368
  class Character extends Model {
135
1369
  entry;
136
1370
  loader;
1371
+ looks;
1372
+ static views = { front: [0, 0.08, 1], back: [0, 0.12, -1], left: [1, 0.08, 0], right: [-1, 0.08, 0], top: [0, 1, 0.02], game: [-0.28, 0.32, -1] };
137
1373
  view = [0.3, 0.08, 0.95];
138
1374
  worn = new Map;
139
1375
  selection = new Map;
140
1376
  revisions = new Map;
141
- constructor(name, entry, skeleton, loader) {
1377
+ hair = { kHairColor: { value: new THREE6.Color(DEFAULT_HAIR) }, kHairHighlight: { value: new THREE6.Color(DEFAULT_HAIR) } };
1378
+ skin = { kSkinTint: { value: new THREE6.Color(1, 1, 1) }, kSkinReference: { value: new THREE6.Color(0.6, 0.45, 0.38) }, kSkinSpecular: { value: SKIN_SPECULAR } };
1379
+ blend = null;
1380
+ face = null;
1381
+ headLoading = 0;
1382
+ defaults = new Map;
1383
+ faceOverlays = new OverlayCanvas;
1384
+ bodyOverlays = new OverlayCanvas;
1385
+ wornOverlays = new Map;
1386
+ overlayRevision = 0;
1387
+ eye = { kEyePalette: { value: null }, kEyeRect: { value: new THREE6.Vector4 }, kEyeColor: { value: -1 } };
1388
+ defaultBlend = null;
1389
+ featureValues = FACE_FEATURES.map(() => 0);
1390
+ featureTargets = null;
1391
+ constructor(name, entry, skeleton, loader, looks) {
142
1392
  super(name, skeleton);
143
1393
  this.entry = entry;
144
1394
  this.loader = loader;
1395
+ this.looks = looks;
145
1396
  }
146
- static async load(name, entry, loader) {
1397
+ static async load(name, entry, loader, looks = null, look) {
147
1398
  if (!entry.skeleton)
148
1399
  throw new Error(`${name} has no skeleton: pass its .yft as an input or use --skeleton`);
149
- const character = new Character(name, entry, await loader.load(entry.skeleton), loader);
150
- await character.wearDefaults();
1400
+ const skeleton = loader.load(entry.skeleton);
1401
+ if (look)
1402
+ warm(name, entry, loader, look);
1403
+ const character = new Character(name, entry, await skeleton, loader, looks);
1404
+ const heads = character.freemode ? character.heads() : [];
1405
+ if (heads.length > 0)
1406
+ character.defaultBlend = { shapeFirst: heads[0], shapeSecond: heads[0], shapeMix: 0, skinFirst: heads[0], skinSecond: heads[0], skinMix: 0 };
1407
+ const taken = new Set(Object.keys(look ? character.outfitOf(look) : {}));
1408
+ if (look?.head)
1409
+ taken.add("head");
1410
+ await Promise.all([
1411
+ character.freemode ? character.readSkin() : null,
1412
+ character.wearDefaults(taken),
1413
+ character.defaultBlend && !look?.head ? character.setHead(character.defaultBlend) : null,
1414
+ look ? character.dress(look) : null
1415
+ ]);
151
1416
  return character;
152
1417
  }
1418
+ static parseOutfit(text) {
1419
+ const outfit = {};
1420
+ for (const part of text.split(",").map((item) => item.trim()).filter(Boolean)) {
1421
+ const [slot, choice, extra] = part.split("=");
1422
+ if (!slot || !choice || extra !== undefined || !/^(none|([\w-]+\/)?\d+(:[a-z])?)$/.test(choice))
1423
+ throw new Error(`An outfit takes slot=[pack/]index[:variant] or slot=none, not ${part}`);
1424
+ outfit[slot] = choice;
1425
+ }
1426
+ return outfit;
1427
+ }
1428
+ static formatOutfit(outfit) {
1429
+ return Object.entries(outfit).map(([slot, choice]) => `${slot}=${choice}`).join(",");
1430
+ }
1431
+ static parseHead(text) {
1432
+ const numbers = text.split(",").map((item) => Number(item.trim()));
1433
+ if (![3, 6].includes(numbers.length) || numbers.some((value) => !Number.isFinite(value)))
1434
+ throw new Error(`A face takes first,second,shapeMix or shapeFirst,shapeSecond,shapeMix,skinFirst,skinSecond,skinMix, not ${text}`);
1435
+ const [shapeFirst, shapeSecond, shapeMix, skinFirst = shapeFirst, skinSecond = shapeSecond, skinMix = shapeMix] = numbers;
1436
+ return { shapeFirst, shapeSecond, shapeMix, skinFirst, skinSecond, skinMix };
1437
+ }
1438
+ static parseOverlays(text) {
1439
+ const overlays = {};
1440
+ for (const part of text.split(",").map((item) => item.trim()).filter(Boolean)) {
1441
+ const [name, style, opacity, color] = part.split(":");
1442
+ const known = OVERLAYS.find(([overlay]) => overlay === name)?.[0];
1443
+ if (!known || !/^\d+$/.test(style ?? "") || opacity !== undefined && opacity !== "" && !Number.isFinite(Number(opacity)))
1444
+ throw new Error(`An overlay takes name:style[:opacity[:color]] with a name of ${OVERLAYS.map(([overlay]) => overlay).join(", ")}, not ${part}`);
1445
+ overlays[known] = { style: Number(style), ...opacity ? { opacity: Number(opacity) } : {}, ...color ? { color } : {} };
1446
+ }
1447
+ return overlays;
1448
+ }
1449
+ static parseFeatures(text) {
1450
+ const values = FACE_FEATURES.map(() => 0);
1451
+ for (const part of text.split(",").map((item) => item.trim()).filter(Boolean)) {
1452
+ const [key, valueText] = part.split(":");
1453
+ const index = /^\d+$/.test(key) ? Number(key) : FACE_FEATURES.findIndex(([name]) => name === key);
1454
+ const value = Number(valueText);
1455
+ if (index < 0 || index >= FACE_FEATURES.length || valueText === undefined || !Number.isFinite(value))
1456
+ throw new Error(`A face feature takes number:value, number 0 to 19 or a name of ${FACE_FEATURES.map(([name]) => name).join(", ")}, not ${part}`);
1457
+ values[index] = value;
1458
+ }
1459
+ return values;
1460
+ }
1461
+ static formatFeatures(values) {
1462
+ return values.flatMap((value, index) => value ? [`${index}:${Math.round(value * 100) / 100}`] : []).join(",");
1463
+ }
1464
+ static formatOverlays(overlays) {
1465
+ return Object.entries(overlays).map(([name, overlay]) => [name, overlay.style, overlay.opacity === undefined || overlay.opacity === 1 ? overlay.color ? "" : undefined : Math.round(overlay.opacity * 100) / 100, overlay.color].filter((part) => part !== undefined).join(":")).join(",");
1466
+ }
1467
+ static formatHead(blend) {
1468
+ const round = (value) => String(Math.round(value * 100) / 100);
1469
+ const shape = [blend.shapeFirst, blend.shapeSecond, round(blend.shapeMix)];
1470
+ const sameSkin = blend.skinFirst === blend.shapeFirst && blend.skinSecond === blend.shapeSecond && round(blend.skinMix) === round(blend.shapeMix);
1471
+ return (sameSkin ? shape : [...shape, blend.skinFirst, blend.skinSecond, round(blend.skinMix)]).join(",");
1472
+ }
1473
+ part(name) {
1474
+ const spec = PARTS[name];
1475
+ if (!spec)
1476
+ throw new Error(`No body part ${name}: use ${Object.keys(PARTS).join(", ")}`);
1477
+ this.root.updateMatrixWorld(true);
1478
+ const points = spec.bones.map((bone) => this.bones.get(bone) ?? [...this.bones.values()].find((node) => node.name.startsWith(bone.replace(/_000$/, "_")))).filter((bone) => bone !== undefined).map((bone) => bone.getWorldPosition(new THREE6.Vector3));
1479
+ if (points.length === 0)
1480
+ throw new Error(`${this.name} has none of the bones of its ${name}`);
1481
+ const bounds = new THREE6.Box3().setFromPoints(points);
1482
+ const center = bounds.getCenter(new THREE6.Vector3);
1483
+ return { center, radius: bounds.getSize(new THREE6.Vector3).length() / 2 + spec.reach };
1484
+ }
1485
+ armsFor(top) {
1486
+ return TOP_ARMS[this.name]?.[top];
1487
+ }
153
1488
  selected(slot) {
154
1489
  return this.selection.get(slot);
155
1490
  }
1491
+ get head() {
1492
+ return this.blend;
1493
+ }
1494
+ get freemode() {
1495
+ return FREEMODE.test(this.name);
1496
+ }
1497
+ heads() {
1498
+ return [...new Set(this.headPieces().map((piece) => piece.index))].sort((a, b) => a - b);
1499
+ }
156
1500
  setComponent(component, piece, variant) {
1501
+ if (component === "head" && piece && this.freemode)
1502
+ return this.setHead({ shapeFirst: piece.index, shapeSecond: piece.index, shapeMix: 0, skinFirst: piece.index, skinSecond: piece.index, skinMix: 0 });
1503
+ if (component === "head") {
1504
+ this.blend = null;
1505
+ this.face = null;
1506
+ this.skin.kSkinTint.value.setRGB(1, 1, 1);
1507
+ }
157
1508
  return this.wear(component, piece, variant, this.source.scene);
158
1509
  }
159
1510
  setProp(component, piece, variant) {
160
1511
  return this.wear(`p_${component}`, piece, variant, this.bones.get(PROP_ANCHORS[component] ?? "SKEL_Head") ?? this.source.scene);
161
1512
  }
1513
+ async setHead(blend) {
1514
+ const clamp = (value) => THREE6.MathUtils.clamp(value, 0, 1);
1515
+ const wanted = { ...blend, shapeMix: clamp(blend.shapeMix), skinMix: clamp(blend.skinMix) };
1516
+ const worn = this.blend;
1517
+ const sameParents = worn && worn.shapeFirst === wanted.shapeFirst && worn.shapeSecond === wanted.shapeSecond && worn.skinFirst === wanted.skinFirst && worn.skinSecond === wanted.skinSecond;
1518
+ if (sameParents && this.face && this.headLoading === 0)
1519
+ return this.mixFace(wanted);
1520
+ const piece = (id) => {
1521
+ const found = this.headPieces().find((candidate) => candidate.index === id);
1522
+ if (!found)
1523
+ throw new Error(`${this.name} has no head ${id}: it has ${this.heads().join(", ")}`);
1524
+ return found;
1525
+ };
1526
+ const [shapeFirst, shapeSecond, skinFirst, skinSecond] = [wanted.shapeFirst, wanted.shapeSecond, wanted.skinFirst, wanted.skinSecond].map(piece);
1527
+ const diffuse = (head) => Object.values(head.diffuse)[0];
1528
+ const revision = this.nextRevision("head");
1529
+ this.headLoading++;
1530
+ try {
1531
+ const [targets, first, second, firstSkin, secondSkin, firstTone, secondTone, restTone] = await Promise.all([
1532
+ this.loadFeatureTargets(),
1533
+ this.loader.piece(shapeFirst, Object.keys(shapeFirst.diffuse)[0]),
1534
+ this.loader.piece(shapeSecond, Object.keys(shapeSecond.diffuse)[0]),
1535
+ this.loader.texture(diffuse(skinFirst)),
1536
+ this.loader.texture(diffuse(skinSecond)),
1537
+ this.loader.averageColor(diffuse(skinFirst)),
1538
+ this.loader.averageColor(diffuse(skinSecond)),
1539
+ this.loader.averageColor(diffuse(this.headPieces()[0]))
1540
+ ]);
1541
+ if (revision !== this.revisions.get("head"))
1542
+ return;
1543
+ detach(this.worn.get("head") ?? []);
1544
+ const meshes = attachModel(first, this.bones, this.source.scene, this.source.scene);
1545
+ const others = meshesOf(second);
1546
+ const mix = { value: wanted.skinMix };
1547
+ const shape = { value: wanted.shapeMix };
1548
+ const rect = meshes.map(eyeRect).find(Boolean);
1549
+ if (rect)
1550
+ this.eye.kEyeRect.value.copy(rect);
1551
+ const slots = meshes.map((mesh, index) => faceGeometry(mesh, others[index], targets));
1552
+ meshes.forEach((mesh, index) => {
1553
+ const base = mesh.material;
1554
+ const secondNormal = others[index]?.material?.normalMap ?? base.normalMap;
1555
+ const uniforms = { kHeadMap: { value: secondSkin }, kHeadMix: mix, kHeadNormal: { value: secondNormal }, kHeadShape: shape, ...this.skin, ...this.eye, ...this.faceOverlays.uniforms };
1556
+ mesh.material = deriveMaterial(base, { KATACHI_HEAD_BLEND: "", KATACHI_OVERLAYS: "" }, uniforms, firstSkin);
1557
+ });
1558
+ this.worn.set("head", meshes);
1559
+ this.selection.set("head", { piece: shapeFirst, variant: Object.keys(shapeFirst.diffuse)[0] });
1560
+ this.face = { meshes, slots, mix, shape, tones: [firstTone, secondTone, restTone] };
1561
+ this.mixFace(wanted);
1562
+ } finally {
1563
+ this.headLoading--;
1564
+ }
1565
+ }
1566
+ faceFeatures() {
1567
+ return [...this.featureValues];
1568
+ }
1569
+ setFaceFeature(feature, value) {
1570
+ const index = typeof feature === "number" ? feature : FACE_FEATURES.findIndex(([name]) => name === feature);
1571
+ if (!Number.isInteger(index) || index < 0 || index >= FACE_FEATURES.length)
1572
+ throw new Error(`Face features are 0 to ${FACE_FEATURES.length - 1} (${FACE_FEATURES.map(([name]) => name).join(", ")}), not ${feature}`);
1573
+ const oneSided = FACE_FEATURES[index][1] === null;
1574
+ this.featureValues[index] = THREE6.MathUtils.clamp(Number.isFinite(value) ? value : 0, oneSided ? 0 : -1, 1);
1575
+ this.applyFeatures();
1576
+ }
1577
+ setFaceFeatures(values) {
1578
+ FACE_FEATURES.forEach((_, index) => this.setFaceFeature(index, values[index] ?? 0));
1579
+ }
1580
+ loadFeatureTargets() {
1581
+ const features = this.looks?.features;
1582
+ if (!features || !this.freemode)
1583
+ return Promise.resolve(null);
1584
+ this.featureTargets ??= this.loader.bytes(features.path).then((bytes) => {
1585
+ const all = new Float32Array(bytes);
1586
+ const size = features.vertices * 3;
1587
+ return new Map(features.targets.map((name, index) => [name, all.subarray(index * size, (index + 1) * size)]));
1588
+ });
1589
+ return this.featureTargets;
1590
+ }
1591
+ applyFeatures() {
1592
+ const face = this.face;
1593
+ if (!face)
1594
+ return;
1595
+ face.meshes.forEach((mesh, index) => {
1596
+ const influences = mesh.morphTargetInfluences;
1597
+ const slots = face.slots[index];
1598
+ if (!influences)
1599
+ return;
1600
+ FACE_FEATURES.forEach(([, negative, positive], feature) => {
1601
+ const value = this.featureValues[feature];
1602
+ const negativeSlot = negative ? slots.get(negative) : undefined;
1603
+ const positiveSlot = slots.get(positive);
1604
+ if (negativeSlot !== undefined)
1605
+ influences[negativeSlot] = Math.max(0, -value);
1606
+ if (positiveSlot !== undefined)
1607
+ influences[positiveSlot] = Math.max(0, value);
1608
+ });
1609
+ });
1610
+ }
1611
+ overlayStyles(name) {
1612
+ const key = OVERLAYS.find(([overlay]) => overlay === name)?.[1];
1613
+ return key ? this.looks?.overlays[key]?.length ?? 0 : 0;
1614
+ }
1615
+ overlays() {
1616
+ return Object.fromEntries(this.wornOverlays);
1617
+ }
1618
+ setOverlay(name, overlay) {
1619
+ return this.setOverlays({ [name]: overlay });
1620
+ }
1621
+ async setOverlays(overlays) {
1622
+ for (const [name, overlay] of Object.entries(overlays)) {
1623
+ if (!OVERLAYS.some(([known]) => known === name))
1624
+ throw new Error(`No overlay ${name}: use ${OVERLAYS.map(([known]) => known).join(", ")}`);
1625
+ if (!overlay) {
1626
+ this.wornOverlays.delete(name);
1627
+ continue;
1628
+ }
1629
+ const styles = this.overlayStyles(name);
1630
+ if (!Number.isInteger(overlay.style) || overlay.style < 0 || overlay.style >= styles)
1631
+ throw new Error(`${name} has styles 0 to ${styles - 1}, not ${overlay.style}`);
1632
+ this.wornOverlays.set(name, { ...overlay, opacity: THREE6.MathUtils.clamp(overlay.opacity ?? 1, 0, 1) });
1633
+ }
1634
+ await this.composeOverlays();
1635
+ }
1636
+ async setEyeColor(color) {
1637
+ if (color !== null && (!Number.isInteger(color) || color < 0 || color >= EYE_COLORS.length))
1638
+ throw new Error(`Eye colours are 0 to ${EYE_COLORS.length - 1}, not ${color}`);
1639
+ if (color !== null && !this.eye.kEyePalette.value) {
1640
+ if (!this.looks?.eyeColors)
1641
+ throw new Error("These assets hold no eye colours: convert the game folder with the freemode characters");
1642
+ this.eye.kEyePalette.value = await this.loader.texture(this.looks.eyeColors);
1643
+ }
1644
+ this.eye.kEyeColor.value = color ?? -1;
1645
+ }
1646
+ get eyeColor() {
1647
+ return this.eye.kEyeColor.value < 0 ? null : this.eye.kEyeColor.value;
1648
+ }
1649
+ async composeOverlays() {
1650
+ const revision = ++this.overlayRevision;
1651
+ const looks = this.looks;
1652
+ const layers = (body) => Promise.all(overlayOrder(body).map(async (number) => {
1653
+ const [name, key] = OVERLAYS[number];
1654
+ const worn = this.wornOverlays.get(name);
1655
+ const entry = worn && looks?.overlays[key]?.[worn.style];
1656
+ if (!worn || !entry)
1657
+ return null;
1658
+ return { pixels: await this.loader.pixels(entry.diffuse), opacity: worn.opacity ?? 1, tint: TINTED.has(name) && worn.color ? new THREE6.Color(worn.color) : null };
1659
+ }));
1660
+ const [face, body] = await Promise.all([layers(false), layers(true)]);
1661
+ if (revision !== this.overlayRevision)
1662
+ return;
1663
+ this.faceOverlays.compose(face.filter((layer) => layer !== null));
1664
+ this.bodyOverlays.compose(body.filter((layer) => layer !== null));
1665
+ }
1666
+ setHairColor(color, highlight = color) {
1667
+ this.hair.kHairColor.value.copy(toneColor(color));
1668
+ this.hair.kHairHighlight.value.copy(toneColor(highlight));
1669
+ }
1670
+ hairColor() {
1671
+ return { color: `#${this.hair.kHairColor.value.getHexString()}`, highlight: `#${this.hair.kHairHighlight.value.getHexString()}` };
1672
+ }
1673
+ async dress(look) {
1674
+ const missing = [];
1675
+ const outfit = this.outfitOf(look);
1676
+ const clothes = Promise.all(Object.entries(outfit).map(([slot, text]) => {
1677
+ const choice = readChoice(text);
1678
+ const prop = slot.startsWith("p_");
1679
+ const component = prop ? slot.slice(2) : slot;
1680
+ const piece = choice.none ? null : choose(prop ? this.entry.props : this.entry.components, component, choice, this.name);
1681
+ const variant = choice.variant;
1682
+ if (piece === undefined || piece && variant && !(variant in piece.diffuse)) {
1683
+ missing.push(`${slot}=${text}`);
1684
+ return;
1685
+ }
1686
+ return prop ? this.setProp(component, piece, variant) : this.setComponent(component, piece, variant);
1687
+ }));
1688
+ if (look.hair)
1689
+ this.setHairColor(look.hair.color, look.hair.highlight);
1690
+ if (look.features)
1691
+ this.setFaceFeatures(look.features);
1692
+ await Promise.all([clothes, look.head ? this.setHead(look.head) : null, look.overlays ? this.setOverlays(look.overlays) : null, look.eyes !== undefined ? this.setEyeColor(look.eyes) : null]);
1693
+ return missing;
1694
+ }
1695
+ outfitOf(look) {
1696
+ const outfit = { ...look.outfit };
1697
+ const top = topArms(this.name, outfit);
1698
+ if (top !== undefined && outfit.uppr === undefined)
1699
+ outfit.uppr = String(top);
1700
+ if (look.head)
1701
+ delete outfit.head;
1702
+ return outfit;
1703
+ }
1704
+ look() {
1705
+ const outfit = {};
1706
+ for (const slot of new Set([...this.defaults.keys(), ...this.selection.keys()])) {
1707
+ const worn = this.selection.get(slot);
1708
+ const original = this.defaults.get(slot);
1709
+ if (worn?.piece === original?.piece && worn?.variant === original?.variant)
1710
+ continue;
1711
+ const pack = worn && worn.piece.collection !== this.name ? `${worn.piece.collection}/` : "";
1712
+ outfit[slot] = worn ? `${pack}${worn.piece.index}${worn.variant ? `:${worn.variant}` : ""}` : "none";
1713
+ }
1714
+ if (this.blend)
1715
+ delete outfit.head;
1716
+ const look = {};
1717
+ if (Object.keys(outfit).length > 0)
1718
+ look.outfit = outfit;
1719
+ const blend = this.blend;
1720
+ const changed = blend && (!this.defaultBlend || Object.keys(blend).some((key) => blend[key] !== this.defaultBlend[key]));
1721
+ if (blend && changed)
1722
+ look.head = { ...blend };
1723
+ if (this.wornOverlays.size > 0)
1724
+ look.overlays = this.overlays();
1725
+ if (this.eyeColor !== null)
1726
+ look.eyes = this.eyeColor;
1727
+ if (this.featureValues.some((value) => value !== 0))
1728
+ look.features = this.faceFeatures();
1729
+ const hair = this.hairColor();
1730
+ if (this.freemode && (hair.color !== DEFAULT_HAIR || hair.highlight !== DEFAULT_HAIR))
1731
+ look.hair = hair.highlight === hair.color ? { color: hair.color } : { color: hair.color, highlight: hair.highlight };
1732
+ return look;
1733
+ }
162
1734
  dispose() {
163
1735
  for (const objects of this.worn.values())
164
1736
  detach(objects);
165
1737
  this.worn.clear();
1738
+ this.faceOverlays.dispose();
1739
+ this.bodyOverlays.dispose();
166
1740
  super.dispose();
167
1741
  }
168
- async wearDefaults() {
1742
+ mixFace(blend) {
1743
+ const face = this.face;
1744
+ face.meshes.forEach((mesh, index) => {
1745
+ const parent = face.slots[index].get("parent");
1746
+ if (mesh.morphTargetInfluences && parent !== undefined)
1747
+ mesh.morphTargetInfluences[parent] = blend.shapeMix;
1748
+ });
1749
+ this.applyFeatures();
1750
+ face.mix.value = blend.skinMix;
1751
+ face.shape.value = blend.shapeMix;
1752
+ const [first, second, rest] = face.tones;
1753
+ const tone = first.clone().lerp(second, blend.skinMix);
1754
+ this.skin.kSkinTint.value.setRGB(tone.r / Math.max(rest.r, 0.0001), tone.g / Math.max(rest.g, 0.0001), tone.b / Math.max(rest.b, 0.0001));
1755
+ this.blend = blend;
1756
+ }
1757
+ headPieces() {
1758
+ const heads = this.entry.components.filter((piece) => piece.component === "head" && !piece.alternate);
1759
+ const own = heads.filter((piece) => piece.collection === this.name);
1760
+ return own.length > 0 ? own : heads;
1761
+ }
1762
+ async readSkin() {
1763
+ const head = this.headPieces()[0];
1764
+ const path = head && Object.values(head.diffuse)[0];
1765
+ if (path)
1766
+ this.skin.kSkinReference.value.copy(await this.loader.averageColor(path));
1767
+ }
1768
+ async wearDefaults(skip = new Set) {
169
1769
  const first = new Map;
170
1770
  for (const piece of this.entry.components) {
1771
+ if (piece.alternate || skip.has(piece.component))
1772
+ continue;
1773
+ if (this.freemode && piece.component === "head")
1774
+ continue;
1775
+ if (this.freemode && piece.index !== 0)
1776
+ continue;
171
1777
  const current = first.get(piece.component);
172
1778
  if (!current || piece.index < current.index)
173
1779
  first.set(piece.component, piece);
174
1780
  }
175
- await Promise.all([...first.values()].map((piece) => this.setComponent(piece.component, piece)));
1781
+ await Promise.all([...first.values()].map((piece) => this.wear(piece.component, piece, undefined, this.source.scene)));
1782
+ for (const piece of first.values())
1783
+ this.defaults.set(piece.component, { piece, variant: Object.keys(piece.diffuse)[0] });
176
1784
  }
177
- async wear(slot, piece, variant, anchor) {
1785
+ nextRevision(slot) {
178
1786
  const revision = (this.revisions.get(slot) ?? 0) + 1;
179
1787
  this.revisions.set(slot, revision);
1788
+ return revision;
1789
+ }
1790
+ async wear(slot, piece, variant, anchor) {
1791
+ const revision = this.nextRevision(slot);
180
1792
  if (!piece) {
181
1793
  detach(this.worn.get(slot) ?? []);
182
1794
  this.worn.delete(slot);
@@ -184,241 +1796,34 @@ class Character extends Model {
184
1796
  return;
185
1797
  }
186
1798
  const chosen = variant ?? Object.keys(piece.diffuse)[0];
187
- const model = await this.loader.piece(piece, chosen);
1799
+ const tinted = slot === "hair" && chosen !== undefined && piece.tint?.includes(chosen);
1800
+ const [model, template] = await Promise.all([this.loader.piece(piece, chosen), tinted ? this.loader.dataTexture(piece.diffuse[chosen]) : null]);
188
1801
  if (revision !== this.revisions.get(slot))
189
1802
  return;
190
1803
  detach(this.worn.get(slot) ?? []);
191
- this.worn.set(slot, attachModel(model, this.bones, this.source.scene, anchor));
1804
+ const attached = attachModel(model, this.bones, this.source.scene, anchor);
1805
+ const shells = new Set(hairShells(attached));
1806
+ detach(shells);
1807
+ const meshes = attached.filter((mesh) => !shells.has(mesh));
1808
+ for (const mesh of meshes) {
1809
+ const material = mesh.material;
1810
+ if (template)
1811
+ mesh.material = deriveMaterial(material, { KATACHI_HAIR_TINT: "" }, this.hair, template);
1812
+ else if (this.freemode && BODY.has(slot))
1813
+ mesh.material = deriveMaterial(material, { KATACHI_SKIN_TINT: "", KATACHI_SKIN_PIECE: "", KATACHI_OVERLAYS: "" }, { ...this.skin, ...this.bodyOverlays.uniforms });
1814
+ else if (this.freemode && !NO_SKIN.has(slot) && !slot.startsWith("p_") && !piece.plain?.includes(chosen))
1815
+ mesh.material = deriveMaterial(material, { KATACHI_SKIN_TINT: "" }, this.skin);
1816
+ }
1817
+ const fringes = meshes.filter((mesh) => isHair(mesh.material)).map(fringe);
1818
+ this.worn.set(slot, [...meshes, ...fringes]);
192
1819
  this.selection.set(slot, { piece, variant: chosen });
193
1820
  }
194
1821
  }
195
1822
 
196
1823
  // src/loader.ts
197
- import * as THREE3 from "three";
1824
+ import * as THREE7 from "three";
198
1825
  import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
199
1826
 
200
- // src/material.ts
201
- import * as THREE2 from "three";
202
- var VERTEX_HEADER = `
203
- #ifdef KATACHI_COLOR
204
- attribute vec4 color;
205
- varying vec4 vKatachiColor;
206
- #endif
207
- #ifdef KATACHI_UV1
208
- attribute vec2 uv1;
209
- #endif
210
- #ifdef KATACHI_UV2
211
- attribute vec2 uv2;
212
- #endif
213
- varying vec2 vKatachiUv[3];
214
- `;
215
- var VERTEX_BODY = `
216
- #ifdef KATACHI_COLOR
217
- vKatachiColor = color;
218
- #endif
219
- vKatachiUv[0] = uv;
220
- #ifdef KATACHI_UV1
221
- vKatachiUv[1] = uv1;
222
- #else
223
- vKatachiUv[1] = uv;
224
- #endif
225
- #ifdef KATACHI_UV2
226
- vKatachiUv[2] = uv2;
227
- #else
228
- vKatachiUv[2] = uv;
229
- #endif
230
- `;
231
- var FRAGMENT_HEADER = `
232
- uniform vec3 kPaint;
233
- uniform vec2 kDiffuseTile;
234
- uniform vec2 kSpecTile;
235
- uniform float kSpecIntensity;
236
- uniform float kSpecFalloff;
237
- uniform float kSpecFresnel;
238
- uniform vec3 kSpecMask;
239
- uniform sampler2D kSecondMap;
240
- uniform sampler2D kSpecMap;
241
- #ifdef KATACHI_COLOR
242
- varying vec4 vKatachiColor;
243
- #endif
244
- varying vec2 vKatachiUv[3];
245
- float kSpecular = 0.0;
246
- `;
247
- var FRAGMENT_DIFFUSE = `
248
- #ifdef USE_MAP
249
- diffuseColor *= texture2D(map, vKatachiUv[KATACHI_DIFFUSE_SET] * kDiffuseTile);
250
- #endif
251
- diffuseColor.rgb *= kPaint;
252
- #ifdef KATACHI_SECOND_MAP
253
- vec4 kSecond = texture2D(kSecondMap, vKatachiUv[KATACHI_SECOND_SET]);
254
- diffuseColor.rgb = mix(diffuseColor.rgb, kSecond.rgb, kSecond.a);
255
- #endif
256
- #if defined(KATACHI_COLOR) && defined(KATACHI_DECAL)
257
- diffuseColor.a *= vKatachiColor.a;
258
- #endif
259
- `;
260
- var FRAGMENT_ROUGHNESS = `
261
- #ifdef KATACHI_SPEC_MAP
262
- vec4 kSpec = texture2D(kSpecMap, vKatachiUv[KATACHI_SPEC_SET] * kSpecTile);
263
- #else
264
- vec4 kSpec = vec4(0.1);
265
- #endif
266
- kSpec.rg *= kSpec.rg;
267
- kSpecular = clamp(dot(kSpec.rgb, kSpecMask) * kSpecIntensity, 0.0, 1.0);
268
- roughnessFactor = clamp(pow(2.0 / (max(kSpec.a * kSpecFalloff, 1.0) + 2.0), 0.25), 0.04, 1.0);
269
- `;
270
- var FRAGMENT_NORMAL = `
271
- #ifdef USE_NORMALMAP_TANGENTSPACE
272
- vec2 kBump = texture2D(normalMap, vNormalMapUv).rg * 2.0 - 1.0;
273
- normal = normalize(tbn * vec3(kBump * normalScale, max(sqrt(abs(1.0 - dot(kBump, kBump))), 0.001)));
274
- #endif
275
- `;
276
- var FRAGMENT_SPECULAR = `
277
- material.specularColor = vec3(kSpecular);
278
- #ifdef KATACHI_METAL_SPEC
279
- float kPeak = max(diffuseColor.r, max(diffuseColor.g, diffuseColor.b));
280
- material.specularColor *= mix(vec3(1.0), diffuseColor.rgb / max(kPeak, 0.001), smoothstep(0.5, 1.0, kSpecular) * step(0.04, kPeak));
281
- #endif
282
- material.specularColorBlended = mix(material.specularColor, diffuseColor.rgb, metalnessFactor);
283
- material.specularF90 = mix(clamp(kSpecular + 1.0 - kSpecFresnel, 0.0, 1.0), 1.0, metalnessFactor);
284
- `;
285
- var FRAGMENT_AMBIENT_OCCLUSION = `
286
- #ifdef KATACHI_COLOR
287
- reflectedLight.indirectDiffuse *= vKatachiColor.r;
288
- reflectedLight.indirectSpecular *= vKatachiColor.r;
289
- #endif
290
- #ifdef KATACHI_NO_REFLECTION
291
- reflectedLight.indirectSpecular = vec3(0.0);
292
- #endif
293
- `;
294
- var PAINT_SLOTS = [1, 2, 3, 4, 5, 6, 7];
295
- var FIXED_PAINT = 5;
296
- function createPaints() {
297
- return new Map(PAINT_SLOTS.map((slot) => [slot, { value: slot === FIXED_PAINT ? new THREE2.Color().setRGB(0.5, 0.5, 0.5) : new THREE2.Color(16777215) }]));
298
- }
299
- function paintUniform(parameters, paints) {
300
- const value = parameters.matDiffuseColor;
301
- const shared = value?.[0] === 2 ? paints.get(Math.round(value[1])) : undefined;
302
- if (shared)
303
- return shared;
304
- return { value: value ? new THREE2.Color().setRGB(value[0], value[1], value[2]) : new THREE2.Color(16777215) };
305
- }
306
- var PAINT_UV_SETS = {
307
- "3": [0, 1, 1],
308
- "4": [0, 1, 1],
309
- "8": [1, 1, 1],
310
- "9": [2, 1, 2]
311
- };
312
- function uvSets(name) {
313
- return PAINT_UV_SETS[/^vehicle_paint(\d)/.exec(name)?.[1] ?? ""] ?? [0, 1, 0];
314
- }
315
- function vec2Parameter(parameters, name) {
316
- const value = parameters[name];
317
- return value ? new THREE2.Vector2(value[0], value[1]) : new THREE2.Vector2(1, 1);
318
- }
319
- function load(library, path, role) {
320
- return path ? library.load(path, role) : Promise.resolve(null);
321
- }
322
- var PAINT_GLOSS = 16;
323
- var REFLECTIVE = /^vehicle_|reflect|glass|mirror/;
324
- function missingDiffuseColor(name) {
325
- if (name.includes("smallspecmap"))
326
- return 1;
327
- return name.includes("tyrewall") || name.includes("black") ? 0.018 : 0.18;
328
- }
329
- async function buildMaterial(extras, geometry, paints, library) {
330
- const { textures, parameters, shader: name, bucket, missingDiffuse } = extras;
331
- const [map, second, spec, bump] = await Promise.all([
332
- load(library, textures.DiffuseSampler, "color"),
333
- load(library, textures.DiffuseSampler2, "color"),
334
- load(library, textures.SpecSampler, "data"),
335
- load(library, textures.BumpSampler, "data")
336
- ]);
337
- const material = new THREE2.MeshPhysicalMaterial({ name, map, normalMap: bump });
338
- if (bump)
339
- material.normalScale.setScalar(parameters.bumpiness?.[0] ?? 1);
340
- if (!map && missingDiffuse)
341
- material.color.setScalar(missingDiffuseColor(missingDiffuse));
342
- const isGlass = name.startsWith("vehicle_vehglass");
343
- const isPaint = name.startsWith("vehicle_paint") || name === "vehicle_shuts";
344
- const isDecal = bucket === 2 || name.startsWith("vehicle_badges") || name.startsWith("vehicle_decal");
345
- if (isPaint) {
346
- material.clearcoat = 1;
347
- material.clearcoatRoughness = 0.02;
348
- material.metalness = 0.4;
349
- }
350
- if (isGlass && !map) {
351
- material.color.setRGB(0.01, 0.012, 0.014);
352
- material.opacity = name === "vehicle_vehglass" ? 0.42 : 0.2;
353
- }
354
- if (isGlass) {
355
- material.clearcoat = 1;
356
- material.clearcoatRoughness = 0.02;
357
- }
358
- if (bucket === 1 || isDecal) {
359
- material.transparent = true;
360
- material.depthWrite = false;
361
- }
362
- if (isDecal) {
363
- material.visible = map !== null;
364
- material.polygonOffset = true;
365
- material.polygonOffsetFactor = -1;
366
- material.polygonOffsetUnits = -2;
367
- }
368
- if (bucket === 3)
369
- material.alphaTest = 0.33;
370
- if (name.startsWith("ped_hair"))
371
- material.side = THREE2.DoubleSide;
372
- const [diffuseSet, secondSet, specSet] = uvSets(name);
373
- const defines = material.defines;
374
- defines.KATACHI_DIFFUSE_SET = diffuseSet;
375
- defines.KATACHI_SECOND_SET = secondSet;
376
- defines.KATACHI_SPEC_SET = specSet;
377
- if (geometry.hasAttribute("uv1"))
378
- defines.KATACHI_UV1 = "";
379
- if (geometry.hasAttribute("uv2"))
380
- defines.KATACHI_UV2 = "";
381
- if (second)
382
- defines.KATACHI_SECOND_MAP = "";
383
- if (spec)
384
- defines.KATACHI_SPEC_MAP = "";
385
- if (isDecal)
386
- defines.KATACHI_DECAL = "";
387
- if (geometry.hasAttribute("color"))
388
- defines.KATACHI_COLOR = "";
389
- if (!REFLECTIVE.test(name))
390
- defines.KATACHI_NO_REFLECTION = "";
391
- if (!name.startsWith("vehicle_"))
392
- defines.KATACHI_METAL_SPEC = "";
393
- const secondMap = { value: second };
394
- const uniforms = {
395
- kPaint: paintUniform(parameters, paints),
396
- kDiffuseTile: { value: vec2Parameter(parameters, "DiffuseTexTileUV") },
397
- kSpecTile: { value: vec2Parameter(parameters, "specTexTileUV") },
398
- kSpecIntensity: { value: parameters.specularIntensityMult?.[0] ?? 0.25 },
399
- kSpecFalloff: { value: (parameters.specularFalloffMult?.[0] ?? 100) * (isPaint ? PAINT_GLOSS : 1) },
400
- kSpecFresnel: { value: parameters.specularFresnel?.[0] ?? 0.97 },
401
- kSpecMask: { value: new THREE2.Vector3(...(parameters.specMapIntMask ?? [1, 0, 0]).slice(0, 3)) },
402
- kSecondMap: secondMap,
403
- kSpecMap: { value: spec }
404
- };
405
- material.onBeforeCompile = (program) => {
406
- Object.assign(program.uniforms, uniforms);
407
- program.vertexShader = program.vertexShader.replace("#include <common>", `#include <common>
408
- ${VERTEX_HEADER}`).replace("#include <begin_vertex>", `#include <begin_vertex>
409
- ${VERTEX_BODY}`);
410
- program.fragmentShader = program.fragmentShader.replace("#include <common>", `#include <common>
411
- ${FRAGMENT_HEADER}`).replace("#include <map_fragment>", FRAGMENT_DIFFUSE).replace("#include <roughnessmap_fragment>", `#include <roughnessmap_fragment>
412
- ${FRAGMENT_ROUGHNESS}`).replace("#include <normal_fragment_maps>", `#include <normal_fragment_maps>
413
- ${FRAGMENT_NORMAL}`).replace("#include <lights_physical_fragment>", `#include <lights_physical_fragment>
414
- ${FRAGMENT_SPECULAR}`).replace("#include <aomap_fragment>", `#include <aomap_fragment>
415
- ${FRAGMENT_AMBIENT_OCCLUSION}`);
416
- };
417
- material.customProgramCacheKey = () => JSON.stringify(defines);
418
- material.userData = { extras, secondMap };
419
- return material;
420
- }
421
-
422
1827
  // src/texture.ts
423
1828
  var IDENTIFIER = [171, 75, 84, 88, 32, 50, 48, 187, 13, 10, 26, 10];
424
1829
  function parseKtx2(buffer) {
@@ -1073,12 +2478,12 @@ function decodeBlocks(format, src, width, height) {
1073
2478
 
1074
2479
  // src/loader.ts
1075
2480
  var COMPRESSED = {
1076
- [133 /* BC1 */]: THREE3.RGBA_S3TC_DXT1_Format,
1077
- [135 /* BC2 */]: THREE3.RGBA_S3TC_DXT3_Format,
1078
- [137 /* BC3 */]: THREE3.RGBA_S3TC_DXT5_Format,
1079
- [139 /* BC4 */]: THREE3.RED_RGTC1_Format,
1080
- [141 /* BC5 */]: THREE3.RED_GREEN_RGTC2_Format,
1081
- [145 /* BC7 */]: THREE3.RGBA_BPTC_Format
2481
+ [133 /* BC1 */]: THREE7.RGBA_S3TC_DXT1_Format,
2482
+ [135 /* BC2 */]: THREE7.RGBA_S3TC_DXT3_Format,
2483
+ [137 /* BC3 */]: THREE7.RGBA_S3TC_DXT5_Format,
2484
+ [139 /* BC4 */]: THREE7.RED_RGTC1_Format,
2485
+ [141 /* BC5 */]: THREE7.RED_GREEN_RGTC2_Format,
2486
+ [145 /* BC7 */]: THREE7.RGBA_BPTC_Format
1082
2487
  };
1083
2488
  var probe;
1084
2489
  function hasExtension(name) {
@@ -1105,10 +2510,10 @@ function decodesNatively(image, role) {
1105
2510
  function createTexture(image, role) {
1106
2511
  const compressed = COMPRESSED[image.format];
1107
2512
  if (compressed !== undefined && decodesNatively(image, role)) {
1108
- return new THREE3.CompressedTexture(image.levels, image.width, image.height, compressed);
2513
+ return new THREE7.CompressedTexture(image.levels, image.width, image.height, compressed);
1109
2514
  }
1110
2515
  const levels = compressed === undefined ? image.levels : image.levels.map((level) => ({ ...level, data: decodeBlocks(image.format, level.data, level.width, level.height) }));
1111
- const texture = new THREE3.DataTexture(levels[0].data, levels[0].width, levels[0].height, THREE3.RGBAFormat, THREE3.UnsignedByteType);
2516
+ const texture = new THREE7.DataTexture(levels[0].data, levels[0].width, levels[0].height, THREE7.RGBAFormat, THREE7.UnsignedByteType);
1112
2517
  texture.mipmaps = levels;
1113
2518
  return texture;
1114
2519
  }
@@ -1125,9 +2530,11 @@ async function fetchBytes(url) {
1125
2530
 
1126
2531
  class TextureLibrary {
1127
2532
  baseUrl;
2533
+ fetch;
1128
2534
  loaded = new Map;
1129
- constructor(baseUrl) {
2535
+ constructor(baseUrl, fetch2 = (path) => fetchBytes(`${baseUrl}${path}`)) {
1130
2536
  this.baseUrl = baseUrl;
2537
+ this.fetch = fetch2;
1131
2538
  }
1132
2539
  load(path, role) {
1133
2540
  const key = `${role}:${path}`;
@@ -1144,32 +2551,99 @@ class TextureLibrary {
1144
2551
  this.loaded.clear();
1145
2552
  }
1146
2553
  async fetchTexture(path, role) {
1147
- const image = parseKtx2(await fetchBytes(`${this.baseUrl}${path}`));
2554
+ const image = parseKtx2(await this.fetch(path));
1148
2555
  const texture = createTexture(image, role);
1149
- texture.wrapS = THREE3.RepeatWrapping;
1150
- texture.wrapT = THREE3.RepeatWrapping;
1151
- texture.magFilter = THREE3.LinearFilter;
1152
- texture.minFilter = image.levels.length > 1 ? THREE3.LinearMipmapLinearFilter : THREE3.LinearFilter;
2556
+ texture.wrapS = THREE7.RepeatWrapping;
2557
+ texture.wrapT = THREE7.RepeatWrapping;
2558
+ texture.magFilter = THREE7.LinearFilter;
2559
+ texture.minFilter = image.levels.length > 1 ? THREE7.LinearMipmapLinearFilter : THREE7.LinearFilter;
1153
2560
  texture.anisotropy = 16;
1154
- texture.colorSpace = role === "color" ? THREE3.SRGBColorSpace : THREE3.NoColorSpace;
2561
+ texture.colorSpace = role === "color" ? THREE7.SRGBColorSpace : THREE7.NoColorSpace;
1155
2562
  texture.needsUpdate = true;
1156
2563
  return texture;
1157
2564
  }
1158
2565
  }
2566
+ var AVERAGE_SIZE = 64;
2567
+ var PIXEL_CACHE = 24;
2568
+ var BYTE_CACHE = 48;
2569
+ function decodeLevel(image, size) {
2570
+ const level = image.levels.find((candidate) => candidate.width <= size && candidate.height <= size) ?? image.levels[image.levels.length - 1];
2571
+ const data = COMPRESSED[image.format] === undefined ? level.data : decodeBlocks(image.format, level.data, level.width, level.height);
2572
+ return { width: level.width, height: level.height, data };
2573
+ }
2574
+ function typicalColor(image) {
2575
+ const rgba = decodeLevel(image, AVERAGE_SIZE).data;
2576
+ const texels = [];
2577
+ for (let at = 0;at + 3 < rgba.length; at += 4) {
2578
+ if (rgba[at + 3] < 128)
2579
+ continue;
2580
+ texels.push([rgba[at], rgba[at + 1], rgba[at + 2], rgba[at] + rgba[at + 1] + rgba[at + 2]]);
2581
+ }
2582
+ texels.sort((a, b) => a[3] - b[3]);
2583
+ const kept = texels.slice(Math.floor(texels.length / 4), Math.ceil(texels.length * 3 / 4));
2584
+ const sum = [0, 0, 0];
2585
+ for (const texel of kept)
2586
+ for (let channel = 0;channel < 3; channel++)
2587
+ sum[channel] += texel[channel];
2588
+ const count = Math.max(kept.length, 1);
2589
+ return new THREE7.Color().setRGB(sum[0] / count / 255, sum[1] / count / 255, sum[2] / count / 255, THREE7.SRGBColorSpace);
2590
+ }
1159
2591
 
1160
2592
  class ModelLoader {
1161
2593
  baseUrl;
1162
2594
  gltf = new GLTFLoader;
1163
2595
  library;
1164
2596
  pieces = new Map;
2597
+ averages = new Map;
2598
+ decoded = new Map;
2599
+ files = new Map;
1165
2600
  sharedPaints = createPaints();
1166
2601
  constructor(baseUrl) {
1167
2602
  this.baseUrl = baseUrl;
1168
- this.library = new TextureLibrary(baseUrl);
2603
+ this.library = new TextureLibrary(baseUrl, (path) => this.bytes(path));
1169
2604
  }
1170
2605
  texture(path) {
1171
2606
  return this.library.load(path, "color");
1172
2607
  }
2608
+ dataTexture(path) {
2609
+ return this.library.load(path, "data");
2610
+ }
2611
+ bytes(path) {
2612
+ let bytes = this.files.get(path);
2613
+ if (bytes) {
2614
+ this.files.delete(path);
2615
+ } else {
2616
+ bytes = fetchBytes(`${this.baseUrl}${path}`);
2617
+ bytes.catch(() => this.files.delete(path));
2618
+ }
2619
+ this.files.set(path, bytes);
2620
+ while (this.files.size > BYTE_CACHE)
2621
+ this.files.delete(this.files.keys().next().value);
2622
+ return bytes;
2623
+ }
2624
+ pixels(path, size = 512) {
2625
+ const key = `${size}:${path}`;
2626
+ let pixels = this.decoded.get(key);
2627
+ if (pixels) {
2628
+ this.decoded.delete(key);
2629
+ } else {
2630
+ pixels = this.bytes(path).then((bytes) => decodeLevel(parseKtx2(bytes), size));
2631
+ pixels.catch(() => this.decoded.delete(key));
2632
+ }
2633
+ this.decoded.set(key, pixels);
2634
+ while (this.decoded.size > PIXEL_CACHE)
2635
+ this.decoded.delete(this.decoded.keys().next().value);
2636
+ return pixels;
2637
+ }
2638
+ averageColor(path) {
2639
+ let average = this.averages.get(path);
2640
+ if (!average) {
2641
+ average = this.bytes(path).then((bytes) => typicalColor(parseKtx2(bytes)));
2642
+ this.averages.set(path, average);
2643
+ average.catch(() => this.averages.delete(path));
2644
+ }
2645
+ return average;
2646
+ }
1173
2647
  async json(path) {
1174
2648
  return JSON.parse(new TextDecoder().decode(await fetchBytes(`${this.baseUrl}${path}`)));
1175
2649
  }
@@ -1212,7 +2686,7 @@ class ModelLoader {
1212
2686
  }
1213
2687
 
1214
2688
  // src/vehicle.ts
1215
- import * as THREE4 from "three";
2689
+ import * as THREE8 from "three";
1216
2690
  var GTA_COLORS = "0d11161c1d2132383d454b4f999da0c2c4c6979a9763738063625c3c3f47444e541d212913181f26282a5155541519211e2429333a3c8c909539434d5062721e232f363a3fa0a199d3d3d3b7bfca778794c00e1ada1918b6111ba51e237b1a228e1b1f6f181849111db60f25d44a17c2944ff78616cf1f21732021f27d20ffc91f9c1016de0f188f1e17a94744b16c51371c25132428122e2b12383c31423f155c2d1b677066b81f22383e1d5a3f2d423f45594b65867f222e46233155304c7e47578f637ba7394762d6e7f176afbe345e720b9cf12f2d52282c4d2354a16ea3c61125521b203e2751906085922446a84271e13b39e01f2852253aa71c35514c5f8158688e74b5d8ffcf20fbe212916532e0e13d98d2239b8c78503218473f2b221b19653f23775c3eac99756c6b4b402e2ba4965f46231a752b19bfae7bdfd5b2f7edd53a2a1b785f33b5a079fffff6eaeaeab0ab944538312a282b726c576a747c3541589ba0a85870a1eae6dedfddd0f2ad2ef9a45883c566f1cc404cc3da4e6443bcac8ff8b658fcf9f1fffffb81844cfffffff21f99fdd6cddf5891f6ae20b0ee6e08e9fa0a0c170c0d180e0d149f9e8a6212760b142111141a6b1f7b1e1d22bc19172d362a6967487a6c55c3b4925a635281827fafd6e47a64407f6a48".match(/.{6}/g).map((hex) => `#${hex}`);
1217
2691
  var WIDTH = 512;
1218
2692
  var HEIGHT = 256;
@@ -1221,8 +2695,8 @@ function createPlate() {
1221
2695
  const canvas = document.createElement("canvas");
1222
2696
  canvas.width = WIDTH;
1223
2697
  canvas.height = HEIGHT;
1224
- const texture = new THREE4.CanvasTexture(canvas);
1225
- texture.colorSpace = THREE4.SRGBColorSpace;
2698
+ const texture = new THREE8.CanvasTexture(canvas);
2699
+ texture.colorSpace = THREE8.SRGBColorSpace;
1226
2700
  texture.flipY = false;
1227
2701
  texture.anisotropy = 8;
1228
2702
  return texture;
@@ -1308,12 +2782,12 @@ var WHEEL_BONE = /^wheel_[lr][fmr]\d?$/;
1308
2782
  var LIGHT_SHADER = "vehicle_lightsemissive";
1309
2783
  var LIGHT_INTENSITY = 16;
1310
2784
  var WINDOW_TINTS = { 1: 0.97, 2: 0.8, 3: 0.55, 5: 0.9, 6: 0.65 };
1311
- var TINT_COLOR = new THREE4.Color(0.01, 0.012, 0.014);
2785
+ var TINT_COLOR = new THREE8.Color(0.01, 0.012, 0.014);
1312
2786
  function setColor(target, color) {
1313
2787
  if (typeof color === "string")
1314
2788
  target.set(color);
1315
2789
  else if (typeof color !== "number")
1316
- target.setRGB(color[0] / 255, color[1] / 255, color[2] / 255, THREE4.SRGBColorSpace);
2790
+ target.setRGB(color[0] / 255, color[1] / 255, color[2] / 255, THREE8.SRGBColorSpace);
1317
2791
  else if (GTA_COLORS[color])
1318
2792
  target.set(GTA_COLORS[color]);
1319
2793
  }
@@ -1326,7 +2800,7 @@ function glowTexture() {
1326
2800
  glow.addColorStop(1, "rgba(255, 255, 255, 0)");
1327
2801
  context.fillStyle = glow;
1328
2802
  context.fillRect(0, 0, 256, 256);
1329
- return new THREE4.CanvasTexture(canvas);
2803
+ return new THREE8.CanvasTexture(canvas);
1330
2804
  }
1331
2805
  var EXTRA_BONE = /^extra_(\d+)$/;
1332
2806
  function farthestFromClosed(min, max) {
@@ -1425,7 +2899,7 @@ class Vehicle extends Model {
1425
2899
  const rest = bone && this.rest.get(bone);
1426
2900
  if (!bone || !rest)
1427
2901
  return;
1428
- const open = THREE4.MathUtils.clamp(amount, 0, 1);
2902
+ const open = THREE8.MathUtils.clamp(amount, 0, 1);
1429
2903
  const limits = bone.userData;
1430
2904
  const turn = farthestFromClosed(limits.rotationMin, limits.rotationMax) ?? fallback;
1431
2905
  const slide = farthestFromClosed(limits.translationMin, limits.translationMax) ?? [0, 0, 0];
@@ -1500,7 +2974,7 @@ class Vehicle extends Model {
1500
2974
  this.fittedWheels = [];
1501
2975
  const meshes = [];
1502
2976
  part?.scene.traverse((object) => object.isMesh && meshes.push(object));
1503
- const bounds = (geometries) => geometries.reduce((box, geometry) => box.union((geometry.computeBoundingBox(), geometry.boundingBox)), new THREE4.Box3).getSize(new THREE4.Vector3);
2977
+ const bounds = (geometries) => geometries.reduce((box, geometry) => box.union((geometry.computeBoundingBox(), geometry.boundingBox)), new THREE8.Box3).getSize(new THREE8.Vector3);
1504
2978
  const size = bounds(meshes.map((mesh) => mesh.geometry));
1505
2979
  for (const [name, bone] of this.bones) {
1506
2980
  if (!WHEEL_BONE.test(name))
@@ -1516,7 +2990,7 @@ class Vehicle extends Model {
1516
2990
  const target = bounds(stockGeometry);
1517
2991
  const radial = target.y / size.y;
1518
2992
  for (const mesh of meshes) {
1519
- const fitted = new THREE4.Mesh(mesh.geometry, mesh.material);
2993
+ const fitted = new THREE8.Mesh(mesh.geometry, mesh.material);
1520
2994
  fitted.position.copy(stock[0].position);
1521
2995
  fitted.quaternion.copy(stock[0].quaternion);
1522
2996
  fitted.scale.set(target.x / size.x, radial, radial);
@@ -1567,10 +3041,10 @@ class Vehicle extends Model {
1567
3041
  return;
1568
3042
  }
1569
3043
  if (!this.neon) {
1570
- const box = new THREE4.Box3().setFromObject(this.source.scene).translate(this.root.position.clone().negate());
1571
- const size = box.getSize(new THREE4.Vector3);
1572
- const center = box.getCenter(new THREE4.Vector3);
1573
- this.neon = new THREE4.Mesh(new THREE4.PlaneGeometry(size.x * 1.7, size.z * 1.35), new THREE4.MeshBasicMaterial({ map: glowTexture(), transparent: true, depthWrite: false }));
3044
+ const box = new THREE8.Box3().setFromObject(this.source.scene).translate(this.root.position.clone().negate());
3045
+ const size = box.getSize(new THREE8.Vector3);
3046
+ const center = box.getCenter(new THREE8.Vector3);
3047
+ this.neon = new THREE8.Mesh(new THREE8.PlaneGeometry(size.x * 1.7, size.z * 1.35), new THREE8.MeshBasicMaterial({ map: glowTexture(), transparent: true, depthWrite: false }));
1574
3048
  this.neon.rotation.x = -Math.PI / 2;
1575
3049
  this.neon.position.set(center.x, box.min.y + size.y * 0.01, center.z);
1576
3050
  this.neon.userData.decoration = true;
@@ -1628,16 +3102,20 @@ class Vehicle extends Model {
1628
3102
  // src/assets.ts
1629
3103
  var SECTIONS = { vehicle: "vehicles", character: "peds", object: "models", map: "map" };
1630
3104
  var VERSIONS = [2, 3];
3105
+ var CLIP_CACHE = 32;
1631
3106
 
1632
3107
  class Assets {
1633
3108
  manifest;
1634
3109
  loader;
1635
3110
  models;
3111
+ dictionaries;
1636
3112
  entries = new Map;
3113
+ loadedClips = new Map;
1637
3114
  constructor(manifest, loader) {
1638
3115
  this.manifest = manifest;
1639
3116
  this.loader = loader;
1640
3117
  this.models = Object.keys(SECTIONS).flatMap((kind) => Object.keys(manifest[SECTIONS[kind]]).sort().map((name) => ({ kind, name })));
3118
+ this.dictionaries = Object.keys(manifest.animations ?? {}).sort();
1641
3119
  }
1642
3120
  static async open(baseUrl) {
1643
3121
  const loader = new ModelLoader(baseUrl);
@@ -1646,13 +3124,13 @@ class Assets {
1646
3124
  throw new Error(`Unsupported manifest version ${manifest.version}`);
1647
3125
  return new Assets(manifest, loader);
1648
3126
  }
1649
- async load(name, props) {
3127
+ async load(name, props, look) {
1650
3128
  const { manifest, loader } = this;
1651
3129
  const kind = this.models.find((entry) => entry.name === name)?.kind;
1652
3130
  if (!kind)
1653
3131
  throw new Error(`${name} is not in these assets`);
1654
3132
  if (kind === "character")
1655
- return Character.load(name, await this.entry(manifest.peds[name]), loader);
3133
+ return Character.load(name, await this.entry(manifest.peds[name]), loader, manifest.freemode ?? null, look);
1656
3134
  if (kind !== "vehicle")
1657
3135
  return new Model(name, await loader.load(manifest[SECTIONS[kind]][name]));
1658
3136
  const vehicle = await Vehicle.load(name, await this.entry(manifest.vehicles[name]), manifest.wheels, loader);
@@ -1660,6 +3138,32 @@ class Assets {
1660
3138
  await vehicle.apply(props);
1661
3139
  return vehicle;
1662
3140
  }
3141
+ async clips(dictionary) {
3142
+ const entry = this.manifest.animations?.[dictionary];
3143
+ if (entry === undefined)
3144
+ throw new Error(`${dictionary} is not in these assets`);
3145
+ return (await this.entry(entry)).clips;
3146
+ }
3147
+ async clip(dictionary, name) {
3148
+ const key = `${dictionary}/${name}`;
3149
+ let loaded = this.loadedClips.get(key);
3150
+ if (loaded) {
3151
+ this.loadedClips.delete(key);
3152
+ this.loadedClips.set(key, loaded);
3153
+ return loaded;
3154
+ }
3155
+ loaded = this.clips(dictionary).then(async (clips) => {
3156
+ const entry = clips[name];
3157
+ if (!entry)
3158
+ throw new Error(`${dictionary} has no clip named ${name}`);
3159
+ return Clip.fromJSON(await this.loader.json(entry.path));
3160
+ });
3161
+ this.loadedClips.set(key, loaded);
3162
+ loaded.catch(() => this.loadedClips.delete(key));
3163
+ while (this.loadedClips.size > CLIP_CACHE)
3164
+ this.loadedClips.delete(this.loadedClips.keys().next().value);
3165
+ return loaded;
3166
+ }
1663
3167
  clear() {
1664
3168
  this.loader.clear();
1665
3169
  }
@@ -1676,11 +3180,11 @@ class Assets {
1676
3180
  }
1677
3181
  }
1678
3182
  // src/stage.ts
1679
- import * as THREE6 from "three";
3183
+ import * as THREE10 from "three";
1680
3184
  import { OrbitControls } from "three/addons/controls/OrbitControls.js";
1681
3185
 
1682
3186
  // src/picker.ts
1683
- import * as THREE5 from "three";
3187
+ import * as THREE9 from "three";
1684
3188
  var CODE_BITS = 8;
1685
3189
  var CODE_MASK = 255;
1686
3190
  var VERTEX = `
@@ -1709,15 +3213,15 @@ function encode(code) {
1709
3213
  }
1710
3214
 
1711
3215
  class Picker {
1712
- target = new THREE5.WebGLRenderTarget(1, 1);
3216
+ target = new THREE9.WebGLRenderTarget(1, 1);
1713
3217
  pixel = new Uint8Array(4);
1714
3218
  codes = new Map;
1715
3219
  nodes = [];
1716
- clearColor = new THREE5.Color;
1717
- material = new THREE5.ShaderMaterial({
3220
+ clearColor = new THREE9.Color;
3221
+ material = new THREE9.ShaderMaterial({
1718
3222
  vertexShader: VERTEX,
1719
3223
  fragmentShader: FRAGMENT,
1720
- uniforms: { objectCode: { value: new THREE5.Vector3 }, perVertex: { value: false } }
3224
+ uniforms: { objectCode: { value: new THREE9.Vector3 }, perVertex: { value: false } }
1721
3225
  });
1722
3226
  constructor() {
1723
3227
  this.material.onBeforeRender = (_renderer, _scene, _camera, geometry, object) => {
@@ -1787,7 +3291,7 @@ class Picker {
1787
3291
  const meshCode = encode(this.codeOf(mesh));
1788
3292
  const codes = new Uint8Array(indices.count * 3);
1789
3293
  const influences = weights.itemSize;
1790
- const read = (attribute, vertex, influence) => attribute instanceof THREE5.BufferAttribute ? attribute.array[vertex * influences + influence] : attribute.getComponent(vertex, influence);
3294
+ const read = (attribute, vertex, influence) => attribute instanceof THREE9.BufferAttribute ? attribute.array[vertex * influences + influence] : attribute.getComponent(vertex, influence);
1791
3295
  for (let vertex = 0;vertex < indices.count; vertex++) {
1792
3296
  let heaviest = 0;
1793
3297
  for (let influence = 1;influence < influences; influence++) {
@@ -1798,7 +3302,7 @@ class Picker {
1798
3302
  codes[vertex * 3] = low;
1799
3303
  codes[vertex * 3 + 1] = high;
1800
3304
  }
1801
- mesh.geometry.setAttribute("pickCode", new THREE5.BufferAttribute(codes, 3, true));
3305
+ mesh.geometry.setAttribute("pickCode", new THREE9.BufferAttribute(codes, 3, true));
1802
3306
  });
1803
3307
  }
1804
3308
  codeOf(node) {
@@ -1813,19 +3317,21 @@ class Picker {
1813
3317
  }
1814
3318
 
1815
3319
  // src/stage.ts
1816
- var KEY_DIRECTION = new THREE6.Vector3(-0.55, 1, 0.35).normalize();
3320
+ var KEY_DIRECTION = new THREE10.Vector3(-0.55, 1, 0.35).normalize();
1817
3321
  var AUTO_ROTATE_SPEED = 0.8;
1818
3322
  var STAGE_MARGIN = 1.12;
1819
3323
  var TURN_SAMPLES = 24;
1820
3324
  var VIEW_DURATION = 900;
3325
+ var FOCUS_MARGIN = 1.15;
1821
3326
  var LIGHTING_DURATION = 1200;
1822
3327
  var ENTRANCE_DURATION = 1800;
1823
3328
  var ENTRANCE_TURN = 0.7;
1824
3329
  var ENTRANCE_DROP = 0.2;
1825
3330
  var ENTRANCE_PULL = 1.5;
3331
+ var MAX_STEP = 0.1;
1826
3332
  var LIGHTINGS = {
1827
- studio: { environment: 1.15, key: 1.9, keyColor: new THREE6.Color(16774118), fill: 0.7, exposure: 0.7, shadow: 0.25 },
1828
- night: { environment: 0.08, key: 0.55, keyColor: new THREE6.Color(9414911), fill: 0.12, exposure: 1, shadow: 0.12 }
3333
+ studio: { environment: 1.15, key: 1.9, keyColor: new THREE10.Color(16774118), fill: 0.7, exposure: 0.7, shadow: 0.25 },
3334
+ night: { environment: 0.08, key: 0.55, keyColor: new THREE10.Color(9414911), fill: 0.12, exposure: 1, shadow: 0.12 }
1829
3335
  };
1830
3336
  var SOFT_BOXES = [
1831
3337
  [0.1, [30, 0.1, 30], [0, -1.3, 0]],
@@ -1841,11 +3347,11 @@ var easeOutQuint = (t) => 1 - (1 - t) ** 5;
1841
3347
  var smoothstep = (t) => t * t * (3 - 2 * t);
1842
3348
  var shortestTurn = (angle) => Math.atan2(Math.sin(angle), Math.cos(angle));
1843
3349
  function studio() {
1844
- const scene = new THREE6.Scene;
1845
- scene.background = new THREE6.Color(0.16, 0.16, 0.16);
1846
- const geometry = new THREE6.BoxGeometry;
3350
+ const scene = new THREE10.Scene;
3351
+ scene.background = new THREE10.Color(0.16, 0.16, 0.16);
3352
+ const geometry = new THREE10.BoxGeometry;
1847
3353
  for (const [brightness, size, position] of SOFT_BOXES) {
1848
- const box = new THREE6.Mesh(geometry, new THREE6.MeshBasicMaterial({ color: new THREE6.Color(brightness, brightness, brightness) }));
3354
+ const box = new THREE10.Mesh(geometry, new THREE10.MeshBasicMaterial({ color: new THREE10.Color(brightness, brightness, brightness) }));
1849
3355
  box.scale.fromArray(size);
1850
3356
  box.position.fromArray(position);
1851
3357
  scene.add(box);
@@ -1856,15 +3362,15 @@ function studio() {
1856
3362
  class Lighting {
1857
3363
  renderer;
1858
3364
  scene;
1859
- key = new THREE6.DirectionalLight;
1860
- fill = new THREE6.DirectionalLight(14674431);
3365
+ key = new THREE10.DirectionalLight;
3366
+ fill = new THREE10.DirectionalLight(14674431);
1861
3367
  environment;
1862
3368
  constructor(renderer, scene, camera) {
1863
3369
  this.renderer = renderer;
1864
3370
  this.scene = scene;
1865
- renderer.toneMapping = THREE6.ACESFilmicToneMapping;
3371
+ renderer.toneMapping = THREE10.ACESFilmicToneMapping;
1866
3372
  renderer.shadowMap.enabled = true;
1867
- const pmrem = new THREE6.PMREMGenerator(renderer);
3373
+ const pmrem = new THREE10.PMREMGenerator(renderer);
1868
3374
  this.environment = pmrem.fromScene(studio(), 0.008, 0.1, 80, { size: 512 });
1869
3375
  pmrem.dispose();
1870
3376
  scene.environment = this.environment.texture;
@@ -1883,7 +3389,14 @@ class Lighting {
1883
3389
  this.key.color.lerpColors(day.keyColor, dark.keyColor, night);
1884
3390
  this.fill.intensity = mix(day.fill, dark.fill, night);
1885
3391
  }
3392
+ moveBy(offset) {
3393
+ this.key.position.add(offset);
3394
+ this.key.target.position.add(offset);
3395
+ this.key.target.updateMatrixWorld();
3396
+ }
1886
3397
  fit(radius) {
3398
+ this.key.target.position.set(0, 0, 0);
3399
+ this.key.target.updateMatrixWorld();
1887
3400
  this.key.position.copy(KEY_DIRECTION).multiplyScalar(radius * 3);
1888
3401
  this.key.shadow.normalBias = radius * 0.005;
1889
3402
  const reach = radius * 1.2;
@@ -1899,26 +3412,29 @@ class Lighting {
1899
3412
  class Stage {
1900
3413
  canvas;
1901
3414
  renderer;
1902
- scene = new THREE6.Scene;
1903
- camera = new THREE6.PerspectiveCamera(30, 1, 0.05, 300);
3415
+ scene = new THREE10.Scene;
3416
+ camera = new THREE10.PerspectiveCamera(30, 1, 0.05, 300);
1904
3417
  controls;
1905
3418
  lighting;
1906
- ground = new THREE6.Mesh(new THREE6.PlaneGeometry(4, 4), new THREE6.ShadowMaterial({ opacity: LIGHTINGS.studio.shadow }));
3419
+ ground = new THREE10.Mesh(new THREE10.PlaneGeometry(4, 4), new THREE10.ShadowMaterial({ opacity: LIGHTINGS.studio.shadow }));
1907
3420
  resizer;
1908
3421
  watcher;
1909
3422
  entrance;
1910
3423
  inset;
1911
3424
  subject = null;
1912
3425
  picker = null;
1913
- size = new THREE6.Vector3;
3426
+ size = new THREE10.Vector3;
1914
3427
  showing = 0;
1915
3428
  visible = true;
1916
3429
  night = 0;
1917
3430
  flight = null;
1918
3431
  fade = null;
3432
+ lastFrame = null;
3433
+ followed = new THREE10.Vector3;
3434
+ framedAt = new THREE10.Vector3;
1919
3435
  constructor(canvas, options = {}) {
1920
3436
  this.canvas = canvas;
1921
- this.renderer = new THREE6.WebGLRenderer({ canvas, antialias: true, alpha: true });
3437
+ this.renderer = new THREE10.WebGLRenderer({ canvas, antialias: true, alpha: true });
1922
3438
  this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
1923
3439
  this.lighting = new Lighting(this.renderer, this.scene, this.camera);
1924
3440
  this.ground.rotation.x = -Math.PI / 2;
@@ -1943,14 +3459,17 @@ class Stage {
1943
3459
  this.resizer.observe(canvas);
1944
3460
  this.resize();
1945
3461
  this.renderer.setAnimationLoop((time) => {
3462
+ const seconds = this.lastFrame === null ? 0 : Math.min((time - this.lastFrame) / 1000, MAX_STEP);
3463
+ this.lastFrame = time;
1946
3464
  if (!this.visible || canvas.clientWidth === 0)
1947
3465
  return;
1948
3466
  this.advance(time);
3467
+ this.animate(seconds);
1949
3468
  this.controls.update();
1950
3469
  this.renderer.render(this.scene, this.camera);
1951
3470
  });
1952
3471
  }
1953
- async show(assets, name, props) {
3472
+ async show(assets, name, props, look) {
1954
3473
  const showing = ++this.showing;
1955
3474
  if (this.subject) {
1956
3475
  this.scene.remove(this.subject.root);
@@ -1960,7 +3479,7 @@ class Stage {
1960
3479
  this.picker = null;
1961
3480
  assets.clear();
1962
3481
  }
1963
- const subject = await assets.load(name, props);
3482
+ const subject = await assets.load(name, props, look);
1964
3483
  const picker = new Picker;
1965
3484
  if (showing === this.showing) {
1966
3485
  await Promise.all([
@@ -1986,7 +3505,17 @@ class Stage {
1986
3505
  if (!this.subject)
1987
3506
  return Promise.resolve(false);
1988
3507
  this.controls.autoRotate = false;
1989
- return this.fly(this.offset(direction ?? this.subject.view), duration, easeInOutCubic);
3508
+ return this.fly(this.offset(direction ?? this.subject.view), duration, easeInOutCubic, this.middle());
3509
+ }
3510
+ focus(sphere, { direction, duration = VIEW_DURATION } = {}) {
3511
+ if (!this.subject)
3512
+ return Promise.resolve(false);
3513
+ this.controls.autoRotate = false;
3514
+ const half = THREE10.MathUtils.degToRad(this.camera.fov / 2);
3515
+ const across = Math.min(half, Math.atan(Math.tan(half) * this.camera.aspect));
3516
+ const toCamera = direction ? new THREE10.Vector3(...direction).normalize() : this.camera.position.clone().sub(this.controls.target).normalize();
3517
+ const offset = toCamera.multiplyScalar(sphere.radius * FOCUS_MARGIN / Math.sin(across));
3518
+ return this.fly(offset, duration, easeInOutCubic, sphere.center.clone());
1990
3519
  }
1991
3520
  setAutoRotate(on) {
1992
3521
  this.controls.autoRotate = on;
@@ -2035,9 +3564,11 @@ class Stage {
2035
3564
  advance(now) {
2036
3565
  const { flight, fade } = this;
2037
3566
  if (flight) {
2038
- const progress = THREE6.MathUtils.clamp((now - flight.start) / flight.duration, 0, 1);
3567
+ const progress = THREE10.MathUtils.clamp((now - flight.start) / flight.duration, 0, 1);
2039
3568
  const eased = flight.ease(progress);
2040
- const { from, to } = flight;
3569
+ const { from, to, target } = flight;
3570
+ if (target)
3571
+ this.controls.target.lerpVectors(target.from, target.to, eased);
2041
3572
  this.camera.position.setFromSphericalCoords(mix(from.radius, to.radius, eased), mix(from.phi, to.phi, eased), mix(from.theta, to.theta, eased)).add(this.controls.target);
2042
3573
  if (progress === 1) {
2043
3574
  this.flight = null;
@@ -2045,7 +3576,7 @@ class Stage {
2045
3576
  }
2046
3577
  }
2047
3578
  if (fade) {
2048
- const progress = THREE6.MathUtils.clamp((now - fade.start) / fade.duration, 0, 1);
3579
+ const progress = THREE10.MathUtils.clamp((now - fade.start) / fade.duration, 0, 1);
2049
3580
  this.night = mix(fade.from, fade.to, smoothstep(progress));
2050
3581
  this.lighting.blend(this.night);
2051
3582
  this.ground.material.opacity = mix(LIGHTINGS.studio.shadow, LIGHTINGS.night.shadow, this.night);
@@ -2053,18 +3584,36 @@ class Stage {
2053
3584
  this.fade = null;
2054
3585
  }
2055
3586
  }
2056
- fly(offset, duration, ease) {
3587
+ animate(seconds) {
3588
+ const subject = this.subject;
3589
+ if (!subject)
3590
+ return;
3591
+ subject.update(seconds);
3592
+ const moved = subject.root.position.clone().sub(this.followed);
3593
+ if (moved.lengthSq() === 0)
3594
+ return;
3595
+ this.followed.copy(subject.root.position);
3596
+ this.camera.position.add(moved);
3597
+ this.controls.target.add(moved);
3598
+ this.ground.position.add(moved.setY(0));
3599
+ this.lighting.moveBy(moved);
3600
+ }
3601
+ fly(offset, duration, ease, target) {
2057
3602
  this.flight?.done(false);
2058
- const from = new THREE6.Spherical().setFromVector3(this.camera.position.clone().sub(this.controls.target));
2059
- const to = new THREE6.Spherical().setFromVector3(offset);
3603
+ const from = new THREE10.Spherical().setFromVector3(this.camera.position.clone().sub(this.controls.target));
3604
+ const to = new THREE10.Spherical().setFromVector3(offset);
2060
3605
  to.theta = from.theta + shortestTurn(to.theta - from.theta);
3606
+ const moves = target && target.distanceToSquared(this.controls.target) > 0 ? { from: this.controls.target.clone(), to: target } : undefined;
2061
3607
  return new Promise((done) => {
2062
- this.flight = { from, to, start: performance.now(), duration: Math.max(duration, 1), ease, done };
3608
+ this.flight = { from, to, target: moves, start: performance.now(), duration: Math.max(duration, 1), ease, done };
2063
3609
  });
2064
3610
  }
3611
+ middle() {
3612
+ return new THREE10.Vector3(0, this.size.y / 2, 0).add(this.followed).sub(this.framedAt);
3613
+ }
2065
3614
  enter() {
2066
3615
  const hero = this.camera.position.clone().sub(this.controls.target);
2067
- const start = new THREE6.Spherical().setFromVector3(hero);
3616
+ const start = new THREE10.Spherical().setFromVector3(hero);
2068
3617
  start.theta += ENTRANCE_TURN;
2069
3618
  start.phi = Math.min(start.phi + ENTRANCE_DROP, this.controls.maxPolarAngle);
2070
3619
  start.radius *= ENTRANCE_PULL;
@@ -2074,13 +3623,13 @@ class Stage {
2074
3623
  }
2075
3624
  offset(direction) {
2076
3625
  const { size } = this;
2077
- const slopeY = Math.tan(THREE6.MathUtils.degToRad(this.camera.fov / 2));
3626
+ const slopeY = Math.tan(THREE10.MathUtils.degToRad(this.camera.fov / 2));
2078
3627
  const slopeX = slopeY * this.camera.aspect;
2079
3628
  const reach = Math.hypot(size.x, size.z) / 2;
2080
- const toCamera = new THREE6.Vector3(...direction).normalize();
2081
- const right = new THREE6.Vector3().crossVectors(new THREE6.Vector3(0, 1, 0), toCamera).normalize();
2082
- const up = new THREE6.Vector3().crossVectors(toCamera, right);
2083
- const point = new THREE6.Vector3;
3629
+ const toCamera = new THREE10.Vector3(...direction).normalize();
3630
+ const right = new THREE10.Vector3().crossVectors(new THREE10.Vector3(0, 1, 0), toCamera).normalize();
3631
+ const up = new THREE10.Vector3().crossVectors(toCamera, right);
3632
+ const point = new THREE10.Vector3;
2084
3633
  let distance = 0;
2085
3634
  for (let turn = 0;turn < TURN_SAMPLES; turn++) {
2086
3635
  const angle = turn / TURN_SAMPLES * Math.PI * 2;
@@ -2093,10 +3642,13 @@ class Stage {
2093
3642
  return toCamera.multiplyScalar(distance);
2094
3643
  }
2095
3644
  frame(subject) {
2096
- this.size = subject.placeAtOrigin().getSize(new THREE6.Vector3);
3645
+ this.size = subject.placeAtOrigin().getSize(new THREE10.Vector3);
2097
3646
  this.scene.add(subject.root);
3647
+ this.followed.copy(subject.root.position);
3648
+ this.framedAt.copy(subject.root.position);
3649
+ this.ground.position.set(0, 0, 0);
2098
3650
  const radius = this.size.length() / 2;
2099
- const target = new THREE6.Vector3(0, this.size.y / 2, 0);
3651
+ const target = new THREE10.Vector3(0, this.size.y / 2, 0);
2100
3652
  this.lighting.fit(radius);
2101
3653
  this.ground.scale.setScalar(radius);
2102
3654
  Object.assign(this.camera, { near: radius * 0.02, far: radius * 20 }).updateProjectionMatrix();
@@ -2130,14 +3682,14 @@ class ThumbnailRenderer {
2130
3682
  size;
2131
3683
  format;
2132
3684
  renderer;
2133
- scene = new THREE6.Scene;
2134
- camera = new THREE6.PerspectiveCamera(FIELD_OF_VIEW, 1);
3685
+ scene = new THREE10.Scene;
3686
+ camera = new THREE10.PerspectiveCamera(FIELD_OF_VIEW, 1);
2135
3687
  lighting;
2136
3688
  pixels;
2137
3689
  constructor(size = 512, format = "png") {
2138
3690
  this.size = size;
2139
3691
  this.format = format;
2140
- this.renderer = new THREE6.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true });
3692
+ this.renderer = new THREE10.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true });
2141
3693
  this.renderer.setSize(size, size, false);
2142
3694
  this.renderer.setClearColor(0, 0);
2143
3695
  this.lighting = new Lighting(this.renderer, this.scene, this.camera);
@@ -2145,15 +3697,15 @@ class ThumbnailRenderer {
2145
3697
  }
2146
3698
  async render(model, view = model.view) {
2147
3699
  const box = model.placeAtOrigin();
2148
- const center = box.getCenter(new THREE6.Vector3);
2149
- const radius = box.getSize(new THREE6.Vector3).length() / 2;
2150
- const toCamera = new THREE6.Vector3(...view).normalize();
2151
- const right = new THREE6.Vector3().crossVectors(new THREE6.Vector3(0, 1, 0), toCamera).normalize();
2152
- const up = new THREE6.Vector3().crossVectors(toCamera, right);
2153
- const slope = Math.tan(THREE6.MathUtils.degToRad(FIELD_OF_VIEW / 2));
3700
+ const center = box.getCenter(new THREE10.Vector3);
3701
+ const radius = box.getSize(new THREE10.Vector3).length() / 2;
3702
+ const toCamera = new THREE10.Vector3(...view).normalize();
3703
+ const right = new THREE10.Vector3().crossVectors(new THREE10.Vector3(0, 1, 0), toCamera).normalize();
3704
+ const up = new THREE10.Vector3().crossVectors(toCamera, right);
3705
+ const slope = Math.tan(THREE10.MathUtils.degToRad(FIELD_OF_VIEW / 2));
2154
3706
  let distance = 0;
2155
3707
  for (let corner = 0;corner < 8; corner++) {
2156
- const point = new THREE6.Vector3(corner & 1 ? box.max.x : box.min.x, corner & 2 ? box.max.y : box.min.y, corner & 4 ? box.max.z : box.min.z).sub(center);
3708
+ const point = new THREE10.Vector3(corner & 1 ? box.max.x : box.min.x, corner & 2 ? box.max.y : box.min.y, corner & 4 ? box.max.z : box.min.z).sub(center);
2157
3709
  const extent = Math.max(Math.abs(point.dot(right)), Math.abs(point.dot(up))) * MARGIN;
2158
3710
  distance = Math.max(distance, point.dot(toCamera) + extent / slope);
2159
3711
  }
@@ -2232,8 +3784,21 @@ class ThumbnailRenderer {
2232
3784
  export {
2233
3785
  Assets,
2234
3786
  Character,
3787
+ Clip,
3788
+ EYE_COLORS,
3789
+ FACE_FEATURES,
2235
3790
  Model,
3791
+ OVERLAYS,
3792
+ PED_BONES,
3793
+ Playback,
2236
3794
  Stage,
3795
+ TINTED,
2237
3796
  ThumbnailRenderer,
2238
- Vehicle
3797
+ Track,
3798
+ TrackFormat,
3799
+ TrackKind,
3800
+ Vehicle,
3801
+ boneName,
3802
+ joaat,
3803
+ trackWidth
2239
3804
  };