-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
3693 lines (3282 loc) · 146 KB
/
Copy pathapp.js
File metadata and controls
3693 lines (3282 loc) · 146 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as THREE from 'three';
import { BVHLoader } from 'three/addons/loaders/BVHLoader.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
const API = 'https://c8sh4j1k8nkzp9-8000.proxy.runpod.net';
const GEMINI_KEY = ''; // Set your Gemini API key here (see .env)
if (!GEMINI_KEY) console.warn('GEMINI_KEY not set — scene generation will not work (see .env)');
const GEMINI_URL = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${GEMINI_KEY}`;
const viewport = document.getElementById('viewport');
// Three.js setup
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xd8d8d0);
const camera = new THREE.PerspectiveCamera(60, viewport.clientWidth / viewport.clientHeight, 1, 10000);
camera.position.set(0, 150, 400);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(viewport.clientWidth, viewport.clientHeight);
renderer.setPixelRatio(window.devicePixelRatio);
viewport.appendChild(renderer.domElement);
const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 100, 0);
controls.update();
// Grid
const grid = new THREE.GridHelper(500, 20, 0xc0c0b8, 0xccccc4);
scene.add(grid);
// Lights — soft key + fill + rim for nice form
scene.add(new THREE.AmbientLight(0x303050, 1.5));
const keyLight = new THREE.DirectionalLight(0xffffff, 2);
keyLight.position.set(100, 200, 150);
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0x8888ff, 0.8);
fillLight.position.set(-100, 100, -50);
scene.add(fillLight);
const rimLight = new THREE.DirectionalLight(0xa78bfa, 1);
rimLight.position.set(0, 50, -200);
scene.add(rimLight);
let mixer = null;
let currentBones = null;
let currentHelper = null;
let characterGroup = null;
let bodyMeshes = [];
// Selection & animation control state
let selectedObject = null, selectedType = null;
let selectionBox = null; // purple wireframe box around selected object
function showSelectionBox(obj) {
removeSelectionBox();
const box = new THREE.Box3().setFromObject(obj);
const size = new THREE.Vector3();
const center = new THREE.Vector3();
box.getSize(size);
box.getCenter(center);
// Add a little padding
size.multiplyScalar(1.08);
const geo = new THREE.BoxGeometry(size.x, size.y, size.z);
const edges = new THREE.EdgesGeometry(geo);
const mat = new THREE.LineBasicMaterial({ color: 0x9b7fd4, transparent: true, opacity: 1 });
selectionBox = new THREE.LineSegments(edges, mat);
selectionBox.position.copy(center);
selectionBox.userData._isSelectionBox = true;
scene.add(selectionBox);
}
function removeSelectionBox() {
if (selectionBox) {
scene.remove(selectionBox);
selectionBox.geometry.dispose();
selectionBox.material.dispose();
selectionBox = null;
}
}
let somaGeometry = null;
let somaSkinData = null;
let somaBindInverses = null;
let skinnedCharMesh = null;
// BVH joint names in the order the skin data references them
const BVH_JOINT_NAMES = ['Hips','Spine1','Spine2','Chest','Neck1','Neck2','Head','HeadEnd','Jaw','LeftEye','RightEye','LeftShoulder','LeftArm','LeftForeArm','LeftHand','RightShoulder','RightArm','RightForeArm','RightHand','LeftLeg','LeftShin','LeftFoot','LeftToeBase','LeftToeEnd','RightLeg','RightShin','RightFoot','RightToeBase','RightToeEnd'];
// Load the SOMA mesh + skin data (cached after first load)
async function loadSomaMesh() {
if (somaGeometry && somaSkinData && somaBindInverses) return;
// Load GLB mesh
const glb = await new Promise((resolve, reject) => {
gltfLoader.load('assets/character/soma_mesh.glb', resolve, undefined, reject);
});
// Find the first Mesh in the GLB (may be nested)
let mesh = null;
glb.scene.traverse(child => { if (!mesh && child.isMesh) mesh = child; });
if (!mesh) throw new Error('No mesh found in GLB');
somaGeometry = mesh.geometry.clone();
// Scale from meters to BVH units (~100x)
const posAttr = somaGeometry.getAttribute('position');
for (let i = 0; i < posAttr.count; i++) {
posAttr.setXYZ(i, posAttr.getX(i) * 100, posAttr.getY(i) * 100, posAttr.getZ(i) * 100);
}
posAttr.needsUpdate = true;
somaGeometry.computeVertexNormals();
// Load skin data binary (4 uint8 indices + 4 float16 weights per vertex)
const resp = await fetch('assets/character/soma_skin.bin');
const buf = await resp.arrayBuffer();
const view = new DataView(buf);
const vertCount = posAttr.count;
const skinIndices = new Uint16Array(vertCount * 4);
const skinWeights = new Float32Array(vertCount * 4);
for (let v = 0; v < vertCount; v++) {
const off = v * 12; // 4 bytes indices + 8 bytes weights
for (let j = 0; j < 4; j++) {
skinIndices[v * 4 + j] = view.getUint8(off + j);
}
for (let j = 0; j < 4; j++) {
// float16 read
skinWeights[v * 4 + j] = readFloat16(view, off + 4 + j * 2);
}
}
somaGeometry.setAttribute('skinIndex', new THREE.Uint16BufferAttribute(skinIndices, 4));
somaGeometry.setAttribute('skinWeight', new THREE.Float32BufferAttribute(skinWeights, 4));
somaSkinData = true;
// Load RAW bind transforms, scale translation, then invert in JS
const bindResp = await fetch('assets/character/soma_bind_raw.bin');
const bindBuf = await bindResp.arrayBuffer();
const bindFloats = new Float32Array(bindBuf); // 29 * 16 = 464 floats
somaBindInverses = [];
for (let i = 0; i < 29; i++) {
const r = bindFloats.subarray(i * 16, (i + 1) * 16);
// NumPy stores row-major: [r0c0, r0c1, r0c2, r0c3, r1c0, r1c1, ...]
// Three.js .elements stores column-major: [c0r0, c0r1, c0r2, c0r3, c1r0, ...]
// So we need to transpose when writing to .elements
const bindMat = new THREE.Matrix4();
bindMat.elements[0] = r[0]; bindMat.elements[1] = r[4]; bindMat.elements[2] = r[8]; bindMat.elements[3] = r[12];
bindMat.elements[4] = r[1]; bindMat.elements[5] = r[5]; bindMat.elements[6] = r[9]; bindMat.elements[7] = r[13];
bindMat.elements[8] = r[2]; bindMat.elements[9] = r[6]; bindMat.elements[10] = r[10]; bindMat.elements[11] = r[14];
bindMat.elements[12] = r[3] * 100; bindMat.elements[13] = r[7] * 100; bindMat.elements[14] = r[11] * 100; bindMat.elements[15] = r[15];
// Invert the bind matrix to get the inverse bind matrix
const invMat = bindMat.clone().invert();
somaBindInverses.push(invMat);
}
}
// Float16 reader
function readFloat16(view, offset) {
const h = view.getUint16(offset, true);
const s = (h >> 15) & 1;
const e = (h >> 10) & 0x1f;
const f = h & 0x3ff;
if (e === 0) return (s ? -1 : 1) * Math.pow(2, -14) * (f / 1024);
if (e === 31) return f ? NaN : (s ? -Infinity : Infinity);
return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + f / 1024);
}
let currentClip = null, currentAction = null;
let isPlaying = true, isScrubbing = false;
let lastBvhText = null;
let timelineClips = [];
let totalDuration = 0;
let groundMesh = null; // Reference to ground plane for dynamic repositioning
const clock = new THREE.Clock();
// Body segments: [fromBone, toBone, radiusTop, radiusBottom]
// Modeled after a wooden drawing mannequin
const BODY_SEGMENTS = [
// Full torso — one smooth piece, broader at top
['Hips', 'Neck1', 10, 7],
// Neck
['Neck1', 'Head', 3, 3],
// Shoulders
['Chest', 'LeftShoulder', 5, 4],
['Chest', 'RightShoulder', 5, 4],
// Left arm
['LeftShoulder', 'LeftArm', 4, 3.5],
['LeftArm', 'LeftForeArm', 3.5, 3],
['LeftForeArm', 'LeftHand', 3, 2],
// Right arm
['RightShoulder', 'RightArm', 4, 3.5],
['RightArm', 'RightForeArm', 3.5, 3],
['RightForeArm', 'RightHand', 3, 2],
// Left leg
['LeftLeg', 'LeftShin', 5.5, 4],
['LeftShin', 'LeftFoot', 4, 3],
['LeftFoot', 'LeftToeBase', 3, 2],
// Right leg
['RightLeg', 'RightShin', 5.5, 4],
['RightShin', 'RightFoot', 4, 3],
['RightFoot', 'RightToeBase', 3, 2],
// Hip to leg — thin peg connectors
['Hips', 'LeftLeg', 3.5, 3.5],
['Hips', 'RightLeg', 3.5, 3.5],
];
const bodyColor = 0xd4b896; // wooden mannequin color
function findBone(root, name) {
if (root.name === name) return root;
for (const child of root.children) {
const found = findBone(child, name);
if (found) return found;
}
return null;
}
function createBodyMeshes(rootBone) {
bodyMeshes.forEach(m => scene.remove(m));
bodyMeshes = [];
const mat = new THREE.MeshStandardMaterial({
color: bodyColor, roughness: 0.75, metalness: 0.0,
});
// Head — elongated sphere
const headBone = findBone(rootBone, 'HeadEnd');
if (headBone) {
const geo = new THREE.SphereGeometry(1, 24, 20);
const mesh = new THREE.Mesh(geo, mat.clone());
mesh.userData.type = 'head';
mesh.userData.bone = headBone;
mesh.userData.baseBone = findBone(rootBone, 'Head');
scene.add(mesh);
bodyMeshes.push(mesh);
}
// Smooth tapered cylinders between bone pairs
const tv1 = new THREE.Vector3();
const tv2 = new THREE.Vector3();
for (const [fromName, toName, rTop, rBot] of BODY_SEGMENTS) {
const fromBone = findBone(rootBone, fromName);
const toBone = findBone(rootBone, toName);
if (!fromBone || !toBone) continue;
fromBone.getWorldPosition(tv1);
toBone.getWorldPosition(tv2);
const dist = tv1.distanceTo(tv2);
// Tapered cylinder with hemisphere caps via LatheGeometry
const height = Math.max(dist, 1);
const segments = 20; // smoother capsules
// Create smooth profile: bottom cap → cylinder → top cap
const points = [];
const capSteps = 8;
// Bottom hemisphere cap
for (let i = 0; i <= capSteps; i++) {
const angle = (Math.PI / 2) * (i / capSteps);
points.push(new THREE.Vector2(
Math.sin(angle) * rBot,
-height / 2 - Math.cos(angle) * rBot + rBot
));
}
// Tapered body
points.push(new THREE.Vector2(rBot, -height / 2 + rBot));
points.push(new THREE.Vector2(rTop, height / 2 - rTop));
// Top hemisphere cap
for (let i = 0; i <= capSteps; i++) {
const angle = (Math.PI / 2) * (i / capSteps);
points.push(new THREE.Vector2(
Math.cos(angle) * rTop,
height / 2 + Math.sin(angle) * rTop - rTop
));
}
const geo = new THREE.LatheGeometry(points, segments);
const mesh = new THREE.Mesh(geo, mat.clone());
mesh.userData.type = 'capsule';
mesh.userData.fromBone = fromBone;
mesh.userData.toBone = toBone;
mesh.castShadow = true;
scene.add(mesh);
bodyMeshes.push(mesh);
}
// Hands — slightly flattened spheres
for (const handName of ['LeftHand', 'RightHand']) {
const bone = findBone(rootBone, handName);
if (bone) {
const geo = new THREE.SphereGeometry(4, 12, 10);
const mesh = new THREE.Mesh(geo, mat.clone());
mesh.userData.type = 'joint';
mesh.userData.bone = bone;
scene.add(mesh);
bodyMeshes.push(mesh);
}
}
}
const _v1 = new THREE.Vector3();
const _v2 = new THREE.Vector3();
const _mid = new THREE.Vector3();
const _up = new THREE.Vector3(0, 1, 0);
const _quat = new THREE.Quaternion();
const _dir = new THREE.Vector3();
function updateBodyMeshes() {
for (const mesh of bodyMeshes) {
if (mesh.userData.type === 'head') {
// Position between Head and HeadEnd, scale as ellipsoid
const base = mesh.userData.baseBone;
const top = mesh.userData.bone;
base.getWorldPosition(_v1);
top.getWorldPosition(_v2);
_mid.lerpVectors(_v1, _v2, 0.5);
mesh.position.copy(_mid);
const h = _v1.distanceTo(_v2);
mesh.scale.set(8, h * 0.6, 8.5);
_dir.subVectors(_v2, _v1).normalize();
if (_dir.lengthSq() > 0.0001) {
_quat.setFromUnitVectors(_up, _dir);
mesh.quaternion.copy(_quat);
}
continue;
}
if (mesh.userData.type === 'joint') {
mesh.userData.bone.getWorldPosition(_v1);
mesh.position.copy(_v1);
continue;
}
// Capsule — position at midpoint, orient along bone axis
const from = mesh.userData.fromBone;
const to = mesh.userData.toBone;
from.getWorldPosition(_v1);
to.getWorldPosition(_v2);
_mid.lerpVectors(_v1, _v2, 0.5);
mesh.position.copy(_mid);
_dir.subVectors(_v2, _v1).normalize();
if (_dir.lengthSq() > 0.0001) {
_quat.setFromUnitVectors(_up, _dir);
mesh.quaternion.copy(_quat);
}
}
}
// Extract the character's root path from a BVH clip (sample every N frames)
// Silently rewrite the user's prompt to produce better, more dynamic motion.
// Always biases toward locomotion (walking/moving forward) and exaggerated body movement.
function enhanceMotionPrompt(userPrompt) {
let p = userPrompt;
// Replace common verbs with more dynamic versions
// Convert terrain-related prompts to actions Kimodo handles better
p = p.replace(/\bclimb(?:s|ing)?\s+(?:a\s+)?(?:hill|mountain|slope|incline|ridge)\b/gi, 'climbs up a long staircase steadily, one step at a time');
p = p.replace(/\b(?:go|goes|going|walk|walks|walking)\s+up(?:hill| a hill| the hill| a slope)\b/gi, 'walks up stairs steadily');
p = p.replace(/\b(?:go|goes|going|walk|walks|walking)\s+down(?:hill| a hill| the hill| a slope)\b/gi, 'walks down stairs carefully');
p = p.replace(/\bhike(?:s|ing)?\b/gi, 'walks up and down stairs while moving forward');
const replacements = {
'walks': 'walks forward confidently with long strides and arm swings',
'walk': 'walk forward with long exaggerated strides, swinging arms',
'runs': 'runs forward fast with high knees, pumping arms, covering ground',
'run': 'run forward fast with high knees, pumping arms, covering distance',
'jogs': 'jogs forward energetically with bouncy steps, moving across the space',
'jog': 'jog forward energetically with bouncy steps covering ground',
'dances': 'dances with large expressive full-body movements, stepping side to side',
'dance': 'dance with big expressive full-body movements, stepping around the space',
'stands': 'shifts weight and moves around slowly while standing',
'stand': 'shift weight and sway while moving slightly forward',
'sits': 'sits down then gets up and moves around',
'sit': 'sit down briefly then stand and walk forward',
'does karate': 'performs karate kicks and punches while stepping forward aggressively',
'does kung fu': 'performs kung fu strikes and kicks moving across the floor',
'fights': 'fights with punches and kicks, advancing forward aggressively',
'trips': 'trips and stumbles forward dramatically, arms flailing',
'falls': 'falls forward dramatically with arms reaching out',
'sneaks': 'sneaks forward in a low crouch, moving carefully across the space',
'sneak': 'sneak forward in a low crouch, tiptoeing across the room',
'explores': 'walks around exploring, looking in different directions while moving',
'relaxes': 'stretches and moves around lazily, shifting positions',
'celebrates': 'jumps and pumps fists while moving around excitedly',
'shops': 'walks forward browsing, stopping briefly then moving on',
};
// Apply replacements (case-insensitive, whole word)
for (const [from, to] of Object.entries(replacements)) {
const regex = new RegExp('\\b' + from + '\\b', 'gi');
p = p.replace(regex, to);
}
// If no movement verb was found, append locomotion bias
const hasMovement = /walk|run|jog|step|move|kick|punch|jump|dance|sneak|strid|crawl/i.test(p);
if (!hasMovement) {
p += '. The person should walk forward while doing this, covering distance across the space';
}
// Always append quality suffix
p += '. Make all movements large, exaggerated, and continuous. The person should travel forward through space, not stay in place.';
return p;
}
function extractPathFromBVH(text) {
const loader = new BVHLoader();
const result = loader.parse(text);
const clip = result.clip;
const root = result.skeleton.bones[0];
// Find the Hips position track (Root stays at 0,0,0 — Hips has the actual movement)
const posTrack = clip.tracks.find(t => t.name.includes('Hips') && t.name.endsWith('.position'))
|| clip.tracks.find(t => t.name.endsWith('.position'));
if (!posTrack) return { path: [[0, 0]], result };
const values = posTrack.values;
const totalFrames = values.length / 3;
const path = [];
const numSamples = Math.min(30, totalFrames); // More samples for smoother path
const step = Math.max(1, Math.floor(totalFrames / numSamples));
for (let i = 0; i < totalFrames; i += step) {
const x = values[i * 3];
const y = values[i * 3 + 1]; // height
const z = values[i * 3 + 2];
path.push([Math.round(x), Math.round(y), Math.round(z)]);
}
if (totalFrames > 0) {
const lx = values[(totalFrames - 1) * 3];
const ly = values[(totalFrames - 1) * 3 + 1];
const lz = values[(totalFrames - 1) * 3 + 2];
path.push([Math.round(lx), Math.round(ly), Math.round(lz)]);
}
return { path, result };
}
// Cache the human GLB model
let humanModelTemplate = null;
async function loadHumanModel() {
if (humanModelTemplate) {
const c = humanModelTemplate.clone();
// Preserve scale from template
c.scale.copy(humanModelTemplate.scale);
return c;
}
const glb = await new Promise((resolve, reject) => {
gltfLoader.load('assets/character/human.glb', resolve, undefined, reject);
});
// Wrap in a container group so we can scale the container
// (the GLB scene may have internal transforms we can't override)
const container = new THREE.Group();
container.add(glb.scene);
// Measure raw size
const box = new THREE.Box3().setFromObject(container);
const size = new THREE.Vector3();
box.getSize(size);
container.scale.setScalar(18.7);
// Center the model at origin and put feet at Y=0 relative to container
const sb = new THREE.Box3().setFromObject(container);
const center = new THREE.Vector3();
sb.getCenter(center);
// When attached to Hips bone (Y~94), we need feet at Y = -94 relative to Hips
container.position.set(-center.x, -sb.min.y - 94, -center.z);
humanModelTemplate = container;
return container;
}
function loadBVH(text) {
// Clear previous
if (characterGroup) scene.remove(characterGroup);
if (currentHelper) scene.remove(currentHelper);
if (skinnedCharMesh) { skinnedCharMesh = null; }
bodyMeshes.forEach(m => scene.remove(m));
bodyMeshes = [];
const loader = new BVHLoader();
const result = loader.parse(text);
characterGroup = new THREE.Group();
currentBones = result.skeleton.bones[0];
characterGroup.add(currentBones);
scene.add(characterGroup);
currentHelper = null;
createBodyMeshes(currentBones);
// Use a SINGLE mixer for both sampling and playback.
// Previous approach (tempMixer + setTime + uncacheRoot) was unreliable.
mixer = new THREE.AnimationMixer(currentBones);
mixer.timeScale = 1.5;
currentClip = result.clip;
currentAction = mixer.clipAction(currentClip);
currentAction.play();
// Sample foot bone positions across the animation to find the lowest Y.
// Use mixer.update(dt) — the standard Three.js way to evaluate tracks —
// instead of setTime() which may not reliably apply all track types.
let globalMinY = Infinity;
const bonePos = new THREE.Vector3();
const clipDuration = result.clip.duration;
const samples = 20;
const dt = clipDuration / samples;
const footNames = ['LeftFoot', 'RightFoot', 'LeftToeBase', 'RightToeBase'];
for (let s = 0; s <= samples; s++) {
mixer.update(s === 0 ? 0.0001 : dt);
characterGroup.updateMatrixWorld(true);
for (const name of footNames) {
const bone = findBone(currentBones, name);
if (bone) {
bone.getWorldPosition(bonePos);
if (bonePos.y < globalMinY) globalMinY = bonePos.y;
}
}
}
// Ground the character: offset so the lowest foot capsule bottom touches Y=0.
// Subtract the foot capsule bottom radius (2) so the visual mesh sits on the ground.
const footCapsuleRadius = 2;
characterGroup.position.y = -(globalMinY - footCapsuleRadius);
// Reset to beginning for clean playback
currentAction.reset();
currentAction.play();
isPlaying = true;
mixer.setTime(0);
clock.getDelta(); // drain clock so first frame gets a small delta
document.getElementById('gen-info').textContent =
`${result.skeleton.bones.length} joints — ${result.clip.duration.toFixed(1)}s @ 30fps`;
}
// ========== GEMINI SCENE AGENT ==========
// Gemini only picks WHAT objects — client code handles WHERE to place them
const SCENE_SYSTEM_PROMPT = `You are a creative 3D scene designer. Given a user prompt, pick objects that belong in the scene. Output ONLY valid JSON (no markdown, no backticks).
You do NOT need to specify positions — the engine handles placement automatically. Just pick the right objects.
JSON structure:
{"scene":{"type":"outdoor"|"indoor","models":[{"keyword":"search term","category":number,"size":"large"|"medium"|"small"}],"ground":{"color":"#hex"},"lights":[{"type":"ambient"|"directional"|"point","intensity":0-3,"color":"#hex","position":[x,y,z]}]},"motion_prompt":"A person ..."}
POLY PIZZA CATEGORIES: 0=Food, 1=Clutter, 3=Transport, 4=Furniture, 5=Objects, 6=Nature, 7=Animals, 8=Buildings, 11=Other
CRITICAL — THEMATIC RELEVANCE:
Every model MUST belong in the scene. "Would this object exist in this real-world location?"
- Living room: sofa, table, lamp, bookshelf, TV, plant. NOT: car, building, tree, hydrant
- City street: building, apartment, car, lamp, bench. NOT: sofa, bed, campfire
- Forest: tree, rock, log, mushroom, campfire. NOT: skyscraper, car, desk
- Beach: palm, umbrella, boat, rock. NOT: building, bookshelf
Think carefully. Every object must make sense for the specific scene.
BANNED KEYWORDS (NEVER use): "fence", "gate", "wall", "barrier", "shelter", "bus stop", "bus shelter", "canopy", "awning", "stop sign", "road barrier", "barricade"
SIZE GUIDE:
- "large": buildings, houses, large trees, skyscrapers (background structures)
- "medium": cars, street lamps, small trees, sofas, bookshelves (mid-sized objects)
- "small": bench, chair, hydrant, trash can, flower, cone, barrel, crate (small props)
RULES:
- 6-8 models. Mix: 2-3 large + 2-3 medium + 2-3 small
- Each keyword must be UNIQUE — no repeats
- Be CREATIVE with keywords! Don't use the same objects every time. Examples:
Buildings: apartment, church, castle, tower, warehouse, factory, hotel, restaurant, bakery, cinema, museum, cottage, cabin
Nature: oak, pine, palm, willow, cactus, bush, boulder, stump, mushroom
Vehicles: sedan, truck, motorcycle, bicycle, taxi, ambulance, van, boat, scooter
Props: lamppost, hydrant, mailbox, barrel, crate, statue, fountain, well, windmill, flag, phone booth, umbrella, trashcan, planter
Furniture: sofa, armchair, bookshelf, desk, bed, dresser, TV, piano, rug, clock
- motion_prompt MUST start with "A person" and describe expressive, continuous motion
- 2-3 lights, always include ambient (0.8-1.5). No fog.`;
async function callGemini(userPrompt, characterPath = null) {
let fullPrompt = SCENE_SYSTEM_PROMPT + '\n\nUser prompt: ' + userPrompt;
if (characterPath && characterPath.length > 0) {
// Send only x,z to Gemini (it doesn't need Y)
const flatPath = characterPath.map(p => [p[0], p[2] || p[1]]);
fullPrompt += `\n\nCHARACTER PATH (the character moves through these [x,z] points — DO NOT place any object within 150 units of this path):\n${JSON.stringify(flatPath)}`;
}
const res = await fetch(GEMINI_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
contents: [{ parts: [{ text: fullPrompt }] }],
generationConfig: { temperature: 0.7 }
})
});
const data = await res.json();
const text = data?.candidates?.[0]?.content?.parts?.[0]?.text;
if (!text) throw new Error('Gemini returned empty response');
// Strip markdown code fences if present
const clean = text.replace(/```json\s*/g, '').replace(/```\s*/g, '').trim();
return JSON.parse(clean);
}
const gltfLoader = new GLTFLoader();
let sceneObjects = [];
let pathLine = null;
let pathVisible = false;
// ========== PROCEDURAL GROUND TEXTURE ==========
function createTexturedGround(size, baseColor) {
const canvas = document.createElement('canvas');
canvas.width = 512; canvas.height = 512;
const ctx = canvas.getContext('2d');
// Parse base color
const tmp = new THREE.Color(baseColor);
const r = Math.floor(tmp.r * 255), g = Math.floor(tmp.g * 255), b = Math.floor(tmp.b * 255);
// Fill base
ctx.fillStyle = baseColor;
ctx.fillRect(0, 0, 512, 512);
// Add noise variation — multiple passes for organic feel
for (let pass = 0; pass < 3; pass++) {
const blockSize = [16, 8, 4][pass];
const strength = [25, 15, 8][pass];
for (let y = 0; y < 512; y += blockSize) {
for (let x = 0; x < 512; x += blockSize) {
const vary = (Math.random() - 0.5) * strength;
const nr = Math.min(255, Math.max(0, r + vary));
const ng = Math.min(255, Math.max(0, g + vary * 0.9));
const nb = Math.min(255, Math.max(0, b + vary * 0.7));
ctx.fillStyle = `rgba(${nr|0},${ng|0},${nb|0},${[0.6, 0.4, 0.3][pass]})`;
ctx.fillRect(x, y, blockSize, blockSize);
}
}
}
// Add subtle grid lines for spatial reference
ctx.strokeStyle = `rgba(${Math.max(0,r-30)},${Math.max(0,g-30)},${Math.max(0,b-30)},0.15)`;
ctx.lineWidth = 1;
for (let i = 0; i <= 512; i += 64) {
ctx.beginPath(); ctx.moveTo(i, 0); ctx.lineTo(i, 512); ctx.stroke();
ctx.beginPath(); ctx.moveTo(0, i); ctx.lineTo(512, i); ctx.stroke();
}
const texture = new THREE.CanvasTexture(canvas);
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(size / 200, size / 200);
const geo = new THREE.PlaneGeometry(size, size, 64, 64); // 64x64 subdivisions for terrain
const mat = new THREE.MeshStandardMaterial({ map: texture, roughness: 0.92 });
const plane = new THREE.Mesh(geo, mat);
plane.rotation.x = -Math.PI / 2;
return plane;
}
// Displace terrain vertices based on path Y values
function applyTerrainFromPath(terrainMesh, pathPoints) {
if (!pathPoints || pathPoints.length < 2) return;
const baseY = pathPoints[0][1] || 94;
// Detect sustained elevation: look at the trend, not spikes (jumps)
// Smooth the Y values first to filter out jumps
const smoothedY = pathPoints.map((p, i) => {
const y = p[1] || 94;
// Average with neighbors (3-point moving average)
const prev = (pathPoints[i - 1]?.[1] || y);
const next = (pathPoints[i + 1]?.[1] || y);
return (prev + y + next) / 3;
});
// Check if there's a sustained trend (not just bouncing)
const maxSmoothedDelta = Math.max(...smoothedY.map(y => Math.abs(y - baseY)));
if (maxSmoothedDelta < 3) return; // No meaningful elevation
const posAttr = terrainMesh.geometry.getAttribute('position');
for (let i = 0; i < posAttr.count; i++) {
// PlaneGeometry is created in XY plane, then rotated -90° on X.
// Before rotation: local X = world X, local Y = world -Z
const vx = posAttr.getX(i); // world X
const vz = -posAttr.getY(i); // world Z (negated!)
// Find two closest path points and interpolate — allows both incline AND decline
let best1 = { d: Infinity, h: 0 }, best2 = { d: Infinity, h: 0 };
for (let j = 0; j < pathPoints.length; j++) {
const p = pathPoints[j];
const px = p[0], pz = p[2] || 0;
const d = Math.sqrt((vx - px) ** 2 + (vz - pz) ** 2);
const h = smoothedY[j] - baseY;
if (d < best1.d) {
best2 = { ...best1 };
best1 = { d, h };
} else if (d < best2.d) {
best2 = { d, h };
}
}
// Interpolate between two nearest for smooth slopes
const totalD = best1.d + best2.d;
const height = totalD > 0.1
? (best1.h * (1 - best1.d / totalD) + best2.h * (1 - best2.d / totalD))
: best1.h;
// Wider falloff near the path, tight enough to look like terrain
const influence = Math.exp(-(best1.d * best1.d) / (120 * 120));
posAttr.setZ(i, height * influence * 1.2);
}
posAttr.needsUpdate = true;
terrainMesh.geometry.computeVertexNormals();
}
// ========== PATH VISUALIZATION ==========
// Extract path from an AnimationClip directly (not BVH text)
function extractPathFromClip(clip) {
const posTrack = clip.tracks.find(t => t.name.includes('Hips') && t.name.endsWith('.position'));
if (!posTrack) return [[0, 0, 0]];
const values = posTrack.values;
const totalFrames = values.length / 3;
const path = [];
const numSamples = Math.min(40, totalFrames);
const step = Math.max(1, Math.floor(totalFrames / numSamples));
for (let i = 0; i < totalFrames; i += step) {
path.push([Math.round(values[i * 3]), Math.round(values[i * 3 + 1]), Math.round(values[i * 3 + 2])]);
}
if (totalFrames > 0) {
path.push([Math.round(values[(totalFrames - 1) * 3]), Math.round(values[(totalFrames - 1) * 3 + 1]), Math.round(values[(totalFrames - 1) * 3 + 2])]);
}
return path;
}
// Spawn fill objects around new path areas that don't have coverage yet
function extendEnvironmentAlongPath(newPath) {
const MIN_DIST = 60;
const existingPositions = [];
sceneObjects.forEach(obj => {
if (obj.userData._isGround) return;
existingPositions.push([obj.position.x, obj.position.z]);
});
const fillKeywords = ['tree', 'pine', 'bush', 'rock'];
let added = 0;
for (const [px, , pz] of newPath) {
// Spawn objects on both sides of the path at this waypoint
for (let attempt = 0; attempt < 8; attempt++) {
const side = attempt % 2 === 0 ? -1 : 1;
const offsetX = side * (120 + Math.random() * 250);
const offsetZ = (Math.random() - 0.5) * 200;
const fx = px + offsetX;
const fz = (pz || 0) + offsetZ;
// Check distance from existing objects
let tooClose = false;
for (const [ex, ez] of existingPositions) {
if (Math.sqrt((fx - ex) ** 2 + (fz - ez) ** 2) < MIN_DIST) {
tooClose = true; break;
}
}
// Check distance from path
for (const [ppx, , ppz] of newPath) {
if (Math.sqrt((fx - ppx) ** 2 + (fz - (ppz||0)) ** 2) < 100) {
tooClose = true; break;
}
}
if (tooClose) continue;
existingPositions.push([fx, fz]);
const kw = fillKeywords[Math.floor(Math.random() * fillKeywords.length)];
const scale = kw === 'rock' ? 15 + Math.random() * 15
: kw === 'bush' ? 25 + Math.random() * 15
: 120 + Math.random() * 40;
const proc = tryProceduralModel(kw, scale);
if (proc) {
proc.position.set(fx, 0, fz);
proc.rotation.y = Math.random() * Math.PI * 2;
scene.add(proc);
sceneObjects.push(proc);
added++;
}
}
}
if (added > 0) log(`Extended environment (${added} objects)`, 'scene');
}
function updatePathVisualization(charPath) {
// Remove old path
if (pathLine) { scene.remove(pathLine); pathLine = null; }
if (!charPath || charPath.length < 2) return;
const group = new THREE.Group();
// Main path line
const baseY = charPath[0]?.[1] || 94;
const points = charPath.map(p => {
const elevation = (p[1] || 94) - baseY; // height relative to baseline
return new THREE.Vector3(p[0], elevation + 3, p[2] || 0); // slightly above terrain
});
const lineGeo = new THREE.BufferGeometry().setFromPoints(points);
const lineMat = new THREE.LineBasicMaterial({ color: 0x7c5cbf });
const line = new THREE.Line(lineGeo, lineMat);
group.add(line);
// Dashed ground shadow of the path
const shadowPoints = charPath.map(p => {
const elevation = (p[1] || 94) - baseY;
return new THREE.Vector3(p[0], elevation + 0.5, p[2] || 0);
});
const shadowGeo = new THREE.BufferGeometry().setFromPoints(shadowPoints);
const shadowMat = new THREE.LineDashedMaterial({ color: 0x7c5cbf, dashSize: 8, gapSize: 6, opacity: 0.3, transparent: true });
const shadowLine = new THREE.Line(shadowGeo, shadowMat);
shadowLine.computeLineDistances();
group.add(shadowLine);
// Waypoint markers
const markerGeo = new THREE.SphereGeometry(3, 8, 6);
const markerMat = new THREE.MeshStandardMaterial({ color: 0x7c5cbf, emissive: 0x4a3080, emissiveIntensity: 0.3 });
charPath.forEach((p, i) => {
const marker = new THREE.Mesh(markerGeo, markerMat);
const elev = (p[1] || 94) - baseY;
marker.position.set(p[0], elev + 3, p[2] || 0);
group.add(marker);
// Start/end labels — larger markers
if (i === 0 || i === charPath.length - 1) {
const big = new THREE.Mesh(
new THREE.SphereGeometry(5, 10, 8),
new THREE.MeshStandardMaterial({
color: i === 0 ? 0x2d8a4e : 0xc53030,
emissive: i === 0 ? 0x1a5530 : 0x801a1a,
emissiveIntensity: 0.4
})
);
const bigElev = (p[1] || 94) - baseY;
big.position.set(p[0], bigElev + 5, p[2] || 0);
group.add(big);
}
});
// Direction arrows along the path
const arrowMat = new THREE.MeshStandardMaterial({ color: 0x7c5cbf });
for (let i = 0; i < points.length - 1; i += 2) {
const from = points[i], to = points[Math.min(i + 1, points.length - 1)];
const dir = new THREE.Vector3().subVectors(to, from);
if (dir.length() < 5) continue;
const mid = new THREE.Vector3().lerpVectors(from, to, 0.5);
const arrow = new THREE.Mesh(new THREE.ConeGeometry(2.5, 8, 4), arrowMat);
arrow.position.copy(mid);
arrow.position.y = 3;
arrow.lookAt(to);
arrow.rotateX(Math.PI / 2);
group.add(arrow);
}
group.visible = pathVisible;
pathLine = group;
scene.add(group);
}
function togglePath() {
pathVisible = !pathVisible;
if (pathLine) pathLine.visible = pathVisible;
const btn = document.getElementById('path-toggle');
btn.classList.toggle('active', pathVisible);
btn.textContent = pathVisible ? 'Hide Path' : 'Show Path';
}
document.getElementById('path-toggle').addEventListener('click', togglePath);
// ========== BOUNDING BOX DEBUG ==========
let bboxHelpers = [];
let bboxVisible = false;
function showBoundingBoxes() {
// Clear old
bboxHelpers.forEach(h => scene.remove(h));
bboxHelpers = [];
for (const obj of sceneObjects) {
if (obj.userData._isGround) continue;
if (!obj.isGroup && !obj.isMesh && !obj.children?.length) continue;
const box = new THREE.Box3().setFromObject(obj);
if (box.isEmpty()) continue;
const helper = new THREE.Box3Helper(box, 0x00ff88);
helper.userData._isBbox = true;
scene.add(helper);
bboxHelpers.push(helper);
}
}
function toggleBBox() {
bboxVisible = !bboxVisible;
if (bboxVisible) {
showBoundingBoxes();
} else {
bboxHelpers.forEach(h => scene.remove(h));
bboxHelpers = [];
}
const bboxBtn = document.getElementById('bbox-toggle');
if (bboxBtn) bboxBtn.classList.toggle('active', bboxVisible);
}
const bboxBtn = document.getElementById('bbox-toggle');
if (bboxBtn) bboxBtn.addEventListener('click', toggleBBox);
// ========== PROCEDURAL FALLBACK MODELS ==========
// Used when Poly Pizza doesn't have a good match
function _mat(color, opts = {}) {
return new THREE.MeshStandardMaterial({ color, roughness: opts.r || 0.8, metalness: opts.m || 0, emissive: opts.e || 0, emissiveIntensity: opts.ei || 0 });
}
function makeTrainingDummy(h) {
const g = new THREE.Group();
const wood = _mat(0x8B6914);
// Base
const base = new THREE.Mesh(new THREE.CylinderGeometry(12, 14, h * 0.05, 12), _mat(0x5C3A1E));
base.position.y = h * 0.025;
g.add(base);
// Main post
const post = new THREE.Mesh(new THREE.CylinderGeometry(4, 5, h * 0.7, 10), wood);
post.position.y = h * 0.4;
g.add(post);
// Head target (padded cylinder)
const head = new THREE.Mesh(new THREE.SphereGeometry(8, 12, 10), _mat(0xcc3333));
head.position.y = h * 0.85;
g.add(head);
// Cross arms at different heights
for (let i = 0; i < 3; i++) {
const arm = new THREE.Mesh(new THREE.CylinderGeometry(2, 2, 25, 8), wood);
arm.rotation.z = Math.PI / 2;
arm.rotation.y = i * 1.2;
arm.position.y = h * 0.4 + i * h * 0.15;
arm.position.x = (i % 2 === 0 ? 1 : -1) * 5;
g.add(arm);
// Pad on arm end
const pad = new THREE.Mesh(new THREE.CylinderGeometry(3.5, 3.5, 6, 8), _mat(0xcc3333));
pad.rotation.z = Math.PI / 2;
pad.rotation.y = i * 1.2;
pad.position.set(arm.position.x + (i % 2 === 0 ? 14 : -14), arm.position.y, 0);
g.add(pad);
}
return g;
}
function makeTatamiMat(h) {
const g = new THREE.Group();
// Large floor mat with tatami texture pattern
const size = 250;
const base = new THREE.Mesh(new THREE.BoxGeometry(size, 3, size), _mat(0xC2B280));
base.position.y = 1.5;
g.add(base);
// Individual tatami rectangles with borders
const matW = size / 3 - 2, matD = size / 3 - 2;
for (let r = 0; r < 3; r++) {
for (let c = 0; c < 3; c++) {
const border = new THREE.Mesh(new THREE.BoxGeometry(matW, 0.5, matD),
_mat(r % 2 === c % 2 ? 0xB8A870 : 0xC4B888));
border.position.set(-size/3 + c * (size/3), 3.5, -size/3 + r * (size/3));
g.add(border);
// Edge trim
const trim = new THREE.Mesh(new THREE.BoxGeometry(matW, 1, 2), _mat(0x2d4a1e));
trim.position.set(border.position.x, 3.5, border.position.z - matD/2);
g.add(trim);
}
}
return g;
}
function makePunchingBag(h) {
const g = new THREE.Group();
// Ceiling mount bracket
const bracket = new THREE.Mesh(new THREE.BoxGeometry(8, 3, 8), _mat(0x555555, {m: 0.8}));
bracket.position.y = h;
g.add(bracket);
// Chains (3 of them)
for (let i = 0; i < 3; i++) {
const angle = (i / 3) * Math.PI * 2;
const chain = new THREE.Mesh(new THREE.CylinderGeometry(0.5, 0.5, h * 0.2, 4), _mat(0x888888, {m: 0.8}));
chain.position.set(Math.cos(angle) * 3, h * 0.88, Math.sin(angle) * 3);
g.add(chain);
}
// Bag body (tapered cylinder + rounded bottom)
const bag = new THREE.Mesh(new THREE.CylinderGeometry(11, 9, h * 0.55, 16), _mat(0x8B1A1A));
bag.position.y = h * 0.52;
g.add(bag);
const bottom = new THREE.Mesh(new THREE.SphereGeometry(9, 16, 8), _mat(0x8B1A1A));
bottom.scale.y = 0.5;
bottom.position.y = h * 0.24;
g.add(bottom);
// Stitching lines
for (let i = 0; i < 4; i++) {
const stitch = new THREE.Mesh(new THREE.BoxGeometry(0.5, h * 0.5, 0.5), _mat(0x440000));
const a = (i / 4) * Math.PI * 2;
stitch.position.set(Math.cos(a) * 10.5, h * 0.52, Math.sin(a) * 10.5);
g.add(stitch);
}
return g;
}
function makeLantern(h) {
const g = new THREE.Group();
// Hanging cord