-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
2361 lines (2160 loc) · 95.9 KB
/
Copy pathmain.js
File metadata and controls
2361 lines (2160 loc) · 95.9 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 './style.css';
import * as THREE from 'three';
import JSZip from 'jszip';
import { AssetLoader } from './core/AssetLoader.js';
import { KeyframeManager } from './core/KeyframeManager.js';
import { ResultPackageExporter } from './core/ResultPackageExporter.js';
import { SceneManager } from './core/SceneManager.js';
import { SelectionManager } from './core/SelectionManager.js';
import { EditorUI } from './ui/EditorUI.js';
import {
collectTemplateContext,
compileTemplate,
buildDefaultRhythm,
FORKLIFT_TEMPLATE,
} from './core/ForkliftTemplate.js';
const appRoot = document.querySelector('#app');
const ui = new EditorUI(appRoot);
const sceneManager = new SceneManager(ui.viewport);
const selectionManager = new SelectionManager(sceneManager);
const keyframeManager = new KeyframeManager();
const packageExporter = new ResultPackageExporter();
const assetLoader = new AssetLoader();
let editableObjects = [];
let sceneTreeNodes = [];
let isPlaying = false;
// PKF 播放模式:true 时播放循环用 PKF 公式驱动关节,覆盖关键帧动画
let pkfPlaybackMode = false;
let lastFrameTime = performance.now();
let sourceInfo = {
fileName: '',
format: '',
rawFile: null,
};
const undoStack = [];
const MAX_UNDO = 80;
function worldToUiVector3(vec) {
return { x: vec.x, y: vec.z, z: vec.y };
}
function uiToWorldVector3(x, y, z) {
return new THREE.Vector3(x, z, y);
}
function findObjectById(id) {
if (!id) return null;
return editableObjects.find((obj) => obj.uuid === id) ?? null;
}
function getSceneNodeById(id) {
if (!id) return null;
let found = null;
sceneManager.sceneRoot?.traverse((obj) => {
if (obj.uuid === id) found = obj;
});
return found;
}
function captureHierarchySnapshot() {
if (!sceneManager.sceneRoot) return [];
return editableObjects.map((obj) => {
const parent = obj.parent;
const parentId = parent && parent !== sceneManager.sceneRoot ? parent.uuid : null;
return {
id: obj.uuid,
parentId,
position: { x: obj.position.x, y: obj.position.y, z: obj.position.z },
quaternion: { x: obj.quaternion.x, y: obj.quaternion.y, z: obj.quaternion.z, w: obj.quaternion.w },
scale: { x: obj.scale.x, y: obj.scale.y, z: obj.scale.z },
};
});
}
function restoreHierarchySnapshot(snapshot) {
if (!sceneManager.sceneRoot || !Array.isArray(snapshot)) return;
const map = new Map();
editableObjects.forEach((obj) => map.set(obj.uuid, obj));
snapshot.forEach((item) => {
const obj = map.get(item.id);
if (!obj) return;
const parent = item.parentId ? map.get(item.parentId) : sceneManager.sceneRoot;
if (parent && obj.parent !== parent) parent.add(obj);
obj.position.set(item.position.x, item.position.y, item.position.z);
obj.quaternion.set(item.quaternion.x, item.quaternion.y, item.quaternion.z, item.quaternion.w);
obj.scale.set(item.scale.x, item.scale.y, item.scale.z);
});
}
function pushUndoSnapshot() {
undoStack.push({
selectedObjectId: selectionManager.selectedObject?.uuid || null,
keyframeState: keyframeManager.serializeState(),
hierarchyState: captureHierarchySnapshot(),
});
if (undoStack.length > MAX_UNDO) undoStack.shift();
}
function undoLastChange() {
const snapshot = undoStack.pop();
if (!snapshot) return;
keyframeManager.restoreState(snapshot.keyframeState);
restoreHierarchySnapshot(snapshot.hierarchyState);
const selected = findObjectById(snapshot.selectedObjectId);
selectionManager.selectObject(selected || null);
keyframeManager.evaluateAllAt(keyframeManager.currentTime, sceneManager.sceneRoot);
keyframeManager.applyAllJointDrives(sceneManager.sceneRoot);
sceneTreeNodes = buildSceneTree(sceneManager.sceneRoot);
ui.setTime(keyframeManager.currentTime);
refreshSelectionUI();
refreshPkfParamsUI(); // Undo 后刷新 PKF 参数列表
refreshPkfStepsUI(); // Undo 后刷新 PKF 步骤列表
refreshReparentEventList(); // Undo 后刷新 reparent 事件列表
refreshMarkerList?.(); // Undo 后刷新 marker 列表
}
function isModelTreeNode(obj) {
if (!obj || !obj.name) return false;
if (obj.isLight || obj.isCamera || obj.isBone || obj.type?.includes('Helper')) return false;
return obj.type === 'Object3D' || obj.type === 'Group' || obj.type === 'Mesh';
}
function collectEditableObjects(root) {
const list = [];
root.traverse((obj) => {
if (isModelTreeNode(obj)) list.push(obj);
});
return list;
}
function buildSceneTree(root) {
if (!root) return [];
const isDimContainerName = (name) => {
const lower = String(name || '').toLowerCase();
return lower === 'scene' || lower === 'world' || lower === 'looks';
};
const walk = (node) => {
const children = node.children
.map((child) => walk(child))
.flat()
.filter(Boolean);
if (!isModelTreeNode(node)) return children;
return [
{
id: node.uuid,
name: node.name,
nodeType: node.type,
isDimContainer: isDimContainerName(node.name),
object: node,
children,
},
];
};
return walk(root);
}
/**
* 在对象被 reparent(场景树层级变化)后,清空其关节零点让下一帧懒捕获
* v5 架构:baseTransform 相对于**关节父级**(不是场景树 parent),
* 但场景树 parent 变了会影响 worldToLocal 的计算路径,需要重新捕获。
* @param {THREE.Object3D} obj - 被 reparent 的对象
*/
function rebindJointBaseTransform(obj) {
if (!obj) return;
const def = keyframeManager.getJointDef(obj.uuid);
if (!def) return;
def.baseTransform = null; // 让 applyJointDrive 在下一帧懒捕获
delete def._driftWarned; // F15 修复:base 换了,旧的 drift 警告失效,允许新 drift 再报
}
function refreshObjectTree() {
ui.renderObjectList(sceneTreeNodes, selectionManager.selectedObject?.uuid, {
onSelect: (obj) => selectionManager.selectObject(obj),
getJointLabel: (nodeId) => keyframeManager.getJointDefLabel(nodeId),
onJointTagClick: (node, event) => {
const rect = event.target.getBoundingClientRect();
const currentDef = keyframeManager.getJointDef(node.id);
// 辅助:根据关节父级 ID 获取对应 THREE 对象
const getJointParentObj = (parentId) => parentId ? getSceneNodeById(parentId) : null;
// 辅助:把世界坐标转成关节父级的 local(UI Z-up)
const worldToJointParentLocal = (worldPoint, jpId) => {
const jp = getJointParentObj(jpId);
if (!jp) return worldToUiVector3(worldPoint); // 无关节父级,直接用世界
jp.updateMatrixWorld(true);
const local = jp.worldToLocal(worldPoint.clone());
return worldToUiVector3(local);
};
ui.showJointConfigPanel(node.id, node.name, currentDef, rect, {
// 提供可选 parent 列表(所有可编辑对象)
getParentOptions: () => editableObjects.map((obj) => ({
id: obj.uuid,
name: obj.name || obj.uuid,
})),
onChange: (patch) => {
pushUndoSnapshot();
const childObj = node.object;
const existingDef = keyframeManager.getJointDef(node.id);
const resolvedParentId = patch.parentId !== undefined ? (patch.parentId || null) : (existingDef?.parentId || null);
const parentChanged = existingDef && existingDef.parentId !== resolvedParentId;
const isFirstCreate = !existingDef || !existingDef.baseTransform;
// ── 在任何修改之前,记录 child 当前的世界位置和旋转(用于调试检查)──
let preWorldPos = null;
let preWorldQuat = null;
if (childObj) {
childObj.updateMatrixWorld(true);
preWorldPos = childObj.getWorldPosition(new THREE.Vector3()).clone();
preWorldQuat = childObj.getWorldQuaternion(new THREE.Quaternion()).clone();
}
// ── 计算 baseTransform ──
const bindPatch = {};
if (isFirstCreate || parentChanged) {
// 不再用懒捕获——立即从 child 当前世界位置算出相对于**新关节父级**的 local
// 同时 reset currentValue=0,保证 joint 应用后 child 世界位置不变
if (childObj) {
childObj.updateMatrixWorld(true);
const cwp = childObj.getWorldPosition(new THREE.Vector3());
const cwq = childObj.getWorldQuaternion(new THREE.Quaternion());
const jp = resolvedParentId ? getSceneNodeById(resolvedParentId) : null;
if (jp) {
jp.updateMatrixWorld(true);
const posInJP = jp.worldToLocal(cwp.clone());
const jpQuatInv = jp.getWorldQuaternion(new THREE.Quaternion()).invert();
const quatInJP = jpQuatInv.multiply(cwq);
// 用四元数存旋转,避免 Euler 万向锁
bindPatch.baseTransform = {
tx: posInJP.x, ty: posInJP.y, tz: posInJP.z,
qx: quatInJP.x, qy: quatInJP.y, qz: quatInJP.z, qw: quatInJP.w,
};
} else {
// 无关节父级 → 用场景树 local(四元数)
bindPatch.baseTransform = {
tx: childObj.position.x, ty: childObj.position.y, tz: childObj.position.z,
qx: childObj.quaternion.x, qy: childObj.quaternion.y,
qz: childObj.quaternion.z, qw: childObj.quaternion.w,
};
}
bindPatch.currentValue = 0; // reset,保证 value=0 时 child 不动
}
}
// 默认 origin = (0,0,0) in joint parent local
if (!patch.origin && !existingDef?.origin) {
bindPatch.origin = { x: 0, y: 0, z: 0 };
}
keyframeManager.setJointDef(node.id, {
...patch,
...bindPatch,
name: node.name || node.id,
parentId: resolvedParentId,
childId: node.id,
});
keyframeManager.applyAllJointDrives(sceneManager.sceneRoot);
// ── 开发期安全检查:操作后世界位置/旋转是否偏移 ──
if (childObj && preWorldPos && preWorldQuat) {
childObj.updateMatrixWorld(true);
const postWorldPos = childObj.getWorldPosition(new THREE.Vector3());
const postWorldQuat = childObj.getWorldQuaternion(new THREE.Quaternion());
const posDrift = preWorldPos.distanceTo(postWorldPos);
const quatDot = Math.abs(preWorldQuat.dot(postWorldQuat));
const rotDrift = Math.acos(Math.min(quatDot, 1.0)) * 2 * (180 / Math.PI);
if (posDrift > 0.01 || rotDrift > 1.0) {
console.warn(
`[Joint] ⚠ 设置关节后 ${node.name} 偏移!pos=${posDrift.toFixed(4)} rot=${rotDrift.toFixed(1)}°`,
`\n pos: (${preWorldPos.x.toFixed(4)},${preWorldPos.y.toFixed(4)},${preWorldPos.z.toFixed(4)}) → (${postWorldPos.x.toFixed(4)},${postWorldPos.y.toFixed(4)},${postWorldPos.z.toFixed(4)})`,
`\n parentId: ${resolvedParentId}, isFirstCreate: ${isFirstCreate}, parentChanged: ${parentChanged}`,
);
}
}
refreshObjectTree();
syncJointGizmo();
syncJointOriginMarker(node.id);
refreshAiJointChips();
},
// parent 下拉变化(emitChange 紧跟其后,onChange 里已处理 baseTransform 重算)
onParentChanged: () => {},
onValueChange: (value) => {
keyframeManager.setJointValue(node.id, value);
keyframeManager.applyJointDrive(node.id, sceneManager.sceneRoot, true);
},
onOriginFromBbox: (callback) => {
const childObj = node.object;
if (!childObj) return;
const def = keyframeManager.getJointDef(node.id);
const box = new THREE.Box3().setFromObject(childObj);
if (box.isEmpty()) return;
const center = box.getCenter(new THREE.Vector3());
const worldBottom = new THREE.Vector3(center.x, box.min.y, center.z);
const uiOrigin = worldToJointParentLocal(worldBottom, def?.parentId);
callback(uiOrigin.x, uiOrigin.y, uiOrigin.z);
syncJointOriginMarker(node.id);
},
onOriginFromCenter: (callback) => {
const childObj = node.object;
if (!childObj) return;
const def = keyframeManager.getJointDef(node.id);
const box = new THREE.Box3().setFromObject(childObj);
if (box.isEmpty()) return;
const worldCenter = box.getCenter(new THREE.Vector3());
const uiOrigin = worldToJointParentLocal(worldCenter, def?.parentId);
callback(uiOrigin.x, uiOrigin.y, uiOrigin.z);
syncJointOriginMarker(node.id);
},
});
syncJointOriginMarker(node.id);
},
onMove: ({ draggedId, targetId, mode }) => {
const dragged = getSceneNodeById(draggedId);
const target = getSceneNodeById(targetId);
if (!dragged || !target || dragged === target) return;
let cursor = target;
while (cursor) {
if (cursor === dragged) return;
cursor = cursor.parent;
}
pushUndoSnapshot();
if (mode === 'child') {
target.attach(dragged);
} else {
const siblingParent = target.parent || sceneManager.sceneRoot;
siblingParent.attach(dragged);
const siblings = siblingParent.children;
const targetIndex = siblings.indexOf(target);
const draggedIndex = siblings.indexOf(dragged);
if (targetIndex >= 0 && draggedIndex >= 0) {
siblings.splice(draggedIndex, 1);
const insertionIndex = mode === 'before' ? targetIndex : targetIndex + 1;
siblings.splice(Math.max(0, insertionIndex), 0, dragged);
}
}
// reparent 后刷新关节零点
rebindJointBaseTransform(dragged);
sceneTreeNodes = buildSceneTree(sceneManager.sceneRoot);
refreshObjectTree();
refreshSelectionUI();
},
onInsertGroup: (obj) => {
if (!obj) return;
pushUndoSnapshot();
const parent = obj.parent || sceneManager.sceneRoot;
const idx = parent.children.indexOf(obj);
// 创建插入的父级 group:**只继承 translation**,rotation 和 scale 留给子对象
// 这样 newGroup 的 local 坐标系和 parent 的 local 坐标系**只差一个平移**,
// 后续 origin 在 newGroup-local 空间下就是世界距离尺度,不会被 scale/rotation 扭曲。
// 数学:newGroup(T) * obj(R*S) = T*R*S = original obj.matrix ✓ 世界变换不变
const newGroup = new THREE.Group();
newGroup.name = `${obj.name || 'node'}_joint_group`;
newGroup.position.copy(obj.position);
// newGroup.quaternion 保持 identity(默认)
// newGroup.scale 保持 (1,1,1)(默认)
// Remove obj from parent, add group in its place
parent.remove(obj);
parent.add(newGroup);
// 把 obj 放到 newGroup 下,**只重置 position 为 (0,0,0)**,
// rotation 和 scale 保留原样,让世界变换跟原来等价
obj.position.set(0, 0, 0);
// obj.quaternion 保留
// obj.scale 保留
newGroup.add(obj);
// Restore sibling order: put newGroup at the original index
if (idx >= 0) {
const siblings = parent.children;
const groupIdx = siblings.indexOf(newGroup);
if (groupIdx >= 0 && groupIdx !== idx) {
siblings.splice(groupIdx, 1);
siblings.splice(Math.min(idx, siblings.length), 0, newGroup);
}
}
// 重要:reparent 后必须刷新关节零点,否则 applyJointDrive 会把对象
// 设到基于旧父节点的 local 坐标,视觉上"飞走"
rebindJointBaseTransform(obj);
editableObjects = collectEditableObjects(sceneManager.sceneRoot);
sceneTreeNodes = buildSceneTree(sceneManager.sceneRoot);
refreshObjectTree();
refreshSelectionUI();
},
onMoveToRoot: (obj) => {
if (!obj || obj.parent === sceneManager.sceneRoot) return;
pushUndoSnapshot();
sceneManager.sceneRoot.attach(obj);
rebindJointBaseTransform(obj); // reparent 后刷新关节零点
sceneTreeNodes = buildSceneTree(sceneManager.sceneRoot);
refreshObjectTree();
refreshSelectionUI();
},
// ── v5: Reparent 事件(时间线驱动的运行时 scene graph 切换)──
// getCurrentTime / getReparentCandidates:UI 渲染右键子菜单时调用
getCurrentTime: () => keyframeManager.currentTime,
getReparentCandidates: (node) => {
// 返回所有命名对象名字(排除自己),作为 attach 候选父级
if (!node?.object) return [];
return editableObjects
.filter((o) => o.name && o !== node.object)
.map((o) => o.name);
},
// 点击子菜单某个候选 → 直接 attach(不再弹输入框)
onReparentAttachTo: (node, targetName) => {
if (!node?.object?.name) {
alert('该对象没有名字,无法添加 reparent 事件(跨 roundtrip 需要 name)');
return;
}
pushUndoSnapshot();
keyframeManager.addReparentEvent(keyframeManager.currentTime, node.object.name, targetName);
keyframeManager.applyReparentEventsAtTime(keyframeManager.currentTime, sceneManager.sceneRoot);
refreshReparentEventList();
refreshObjectTree();
ui.setLoadStatus(`已在 t=${keyframeManager.currentTime.toFixed(2)}s 把 "${node.object.name}" attach 到 "${targetName}"`);
},
onReparentDetach: (node) => {
if (!node?.object?.name) {
alert('该对象没有名字,无法添加 reparent 事件');
return;
}
pushUndoSnapshot();
keyframeManager.addReparentEvent(keyframeManager.currentTime, node.object.name, null);
keyframeManager.applyReparentEventsAtTime(keyframeManager.currentTime, sceneManager.sceneRoot);
refreshReparentEventList();
refreshObjectTree();
},
onReparentClearAll: (node) => {
if (!node?.object?.name) return;
pushUndoSnapshot();
const removed = keyframeManager.removeAllReparentEventsForChild(node.object.name);
if (removed > 0) {
keyframeManager.applyReparentEventsAtTime(keyframeManager.currentTime, sceneManager.sceneRoot);
refreshReparentEventList();
refreshObjectTree();
}
},
});
}
function refreshReparentEventList() {
const events = keyframeManager.getReparentEvents();
ui.renderReparentEvents(events, {
onDelete: (eventId) => {
pushUndoSnapshot();
keyframeManager.removeReparentEvent(eventId);
keyframeManager.applyReparentEventsAtTime(keyframeManager.currentTime, sceneManager.sceneRoot);
refreshReparentEventList();
},
});
}
function getCurrentDuration() {
// 全局 clip 时长,与选择无关
return keyframeManager.getClipDuration();
}
function syncJointGizmo() {
const selected = selectionManager.selectedObject;
if (!selected) {
sceneManager.hideJointGizmo();
return;
}
const def = keyframeManager.getJointDef(selected.uuid);
if (!def || def.type === 'none' || def.type === 'fixed') {
sceneManager.hideJointGizmo();
return;
}
const mode = def.type === 'revolute' ? 'rotate' : 'translate';
const baseValue = def.currentValue;
sceneManager.jointGizmoOnDragStart = () => {
pushUndoSnapshot();
// Protect: prevent applyJointDrive from overwriting gizmo transforms during drag
keyframeManager._gizmoDraggingNodeId = selected.uuid;
};
sceneManager.jointGizmoOnDragEnd = () => {
keyframeManager._gizmoDraggingNodeId = null;
// Re-apply drive to sync final state from currentValue
keyframeManager.applyJointDrive(selected.uuid, sceneManager.sceneRoot);
};
sceneManager.showJointGizmo(selected, mode, def.axis, (deltaValue) => {
const newValue = baseValue + deltaValue;
keyframeManager.setJointValue(selected.uuid, newValue);
// 关键:强制调用 applyJointDrive 覆盖 TransformControls 的 local 写入
// 让 fork 每一帧都处于「绕 def.origin 旋转 currentValue 度」的正确姿态
// 不这样做的话,TransformControls 只会绕 fork 自身 pivot 旋转,视觉上错位,
// 拖动结束才 snap 到正确位置 → 表现为"离散跳变"
keyframeManager.applyJointDrive(selected.uuid, sceneManager.sceneRoot, true);
// 更新关节配置面板的滑条
if (ui.activeJointConfigNodeId === selected.uuid && ui.jointConfigPanel) {
const slider = ui.jointConfigPanel.querySelector('.jc-value-slider');
const numInput = ui.jointConfigPanel.querySelector('.jc-value-number');
const clamped = keyframeManager.getJointDef(selected.uuid)?.currentValue ?? 0;
if (slider) slider.value = clamped;
if (numInput) numInput.value = clamped.toFixed(1);
}
});
}
function syncJointOriginMarker(nodeId) {
const id = nodeId || ui.activeJointConfigNodeId;
if (!id) return;
const def = keyframeManager.getJointDef(id);
if (!def || def.type === 'none' || def.type === 'fixed') return;
// origin 在**关节父级**的 local 空间(UI Z-up),不是场景树 parent
const localOrigin = uiToWorldVector3(
def.origin?.x ?? 0,
def.origin?.y ?? 0,
def.origin?.z ?? 0,
);
const jointParent = def.parentId ? getSceneNodeById(def.parentId) : null;
if (jointParent) {
jointParent.updateMatrixWorld(true);
const worldOrigin = jointParent.localToWorld(localOrigin.clone());
sceneManager.setPivotMarker(worldOrigin);
} else {
// 无关节父级 → origin 当世界坐标
sceneManager.setPivotMarker(localOrigin);
}
}
/**
* 刷新选择相关 UI(变换显示、关节 gizmo、关键帧列表)
* 注意:关键帧现在是全局的,不再依赖当前选中对象。
* 只有 gizmo / 关节配置等是 per-selection 的。
*/
function refreshSelectionUI() {
const selected = selectionManager.selectedObject;
ui.setSelectedObject(selected);
syncJointGizmo();
// 全局 clip 列表(不再 per-object)
const clipNames = keyframeManager.getClipNames();
ui.setClipOptions(clipNames, keyframeManager.activeClipName);
// 全局关键帧列表(不依赖选中对象)
const handleDeleteKeyframe = (keyframe) => {
pushUndoSnapshot();
keyframeManager.removeKeyframe(keyframe.time);
keyframeManager.evaluateAllAt(keyframeManager.currentTime, sceneManager.sceneRoot);
refreshSelectionUI();
};
// 把关节定义传给 UI,让 keyframe 能用 jointDef.name 显示
const jointDefs = keyframeManager.getAllJointDefs();
ui.renderKeyframes(keyframeManager.getKeyframes(), handleDeleteKeyframe, jointDefs);
const duration = getCurrentDuration();
if (keyframeManager.currentTime > duration) {
keyframeManager.currentTime = duration;
ui.setTime(duration);
}
ui.setTimelineRange(duration);
ui.updateTimelineLabel(keyframeManager.currentTime, duration);
ui.durationInput.value = String(duration);
refreshObjectTree();
}
async function handleAssetFile(file) {
if (!file) return;
ui.setLoadStatus(`准备加载 ${file.name}...`);
try {
const root = await assetLoader.loadFromFile(file, (status) => {
ui.setLoadStatus(`${file.name}:${status}`);
});
ui.setLoadStatus(`正在构建场景节点...`);
sceneManager.setSceneRoot(root);
editableObjects = collectEditableObjects(root);
sceneTreeNodes = buildSceneTree(root);
keyframeManager.reset();
// v5: 记录初始 scene graph parent 快照(reparent 事件循环时还原用)
keyframeManager.snapshotOriginalParents(root);
undoStack.length = 0;
sourceInfo = {
fileName: file.name,
format: (file.name.split('.').pop() || '').toLowerCase(),
rawFile: file,
};
selectionManager.clearSelection();
ui.setLoadStatus(`已加载 ${file.name}。可编辑对象:${editableObjects.length}`);
refreshObjectTree();
} catch (error) {
ui.setLoadStatus(`加载失败:${error.message}`);
}
}
async function handleImportPackage(file) {
if (!file) return;
ui.setLoadStatus(`正在读取资产包 ${file.name}...`);
try {
const zipData = await file.arrayBuffer();
const zip = await JSZip.loadAsync(zipData);
const manifestFile =
zip.file('manifest.json') || Object.values(zip.files).find((f) => /^manifest-.*\.json$/i.test(f.name));
if (!manifestFile) throw new Error('资产包中缺少 manifest.json');
const manifest = JSON.parse(await manifestFile.async('string'));
const modelFileName = manifest.files?.model;
const modelZipEntry = modelFileName ? zip.file(modelFileName) : null;
if (!modelZipEntry) throw new Error(`资产包中缺少模型文件: ${modelFileName || '(未指定)'}`);
ui.setLoadStatus('正在加载模型...');
const modelBuffer = await modelZipEntry.async('arraybuffer');
const modelBlob = new Blob([modelBuffer]);
const modelFile = new File([modelBlob], modelFileName, { type: 'application/octet-stream' });
const root = await assetLoader.loadFromFile(modelFile, (status) => {
ui.setLoadStatus(`${modelFileName}:${status}`);
});
// v5 修复:导出时已归零关节 + GLB 存的是自然状态,alignObjectToGround 正常运行即可。
// (之前用 skipAlign:true 是因为 GLB 烘焙了已驱动的 transform + 对齐偏移,现在不需要了)
sceneManager.setSceneRoot(root);
// v5 修复:GLTFExporter 会把根节点改名为 "AuxScene",恢复为原始名字
// 优先用导出时保存的 root_name(如 FBX 源的 "Scene")→ 保证 parent_name="Scene"
// 的关节 roundtrip 后能找到父级。旧 ZIP 没有 root_name → 兜底到文件名
const originalFileName = manifest.source?.file_name || modelFileName;
const originalRootName = manifest.source?.root_name || originalFileName;
if (root.name !== originalRootName) {
root.name = originalRootName;
}
editableObjects = collectEditableObjects(root);
sceneTreeNodes = buildSceneTree(root);
keyframeManager.reset();
// v5: 记录初始 scene graph parent 快照
keyframeManager.snapshotOriginalParents(root);
undoStack.length = 0;
const objectsByName = new Map();
editableObjects.forEach((obj) => {
if (obj.name) objectsByName.set(obj.name, obj);
});
sourceInfo = {
fileName: originalFileName,
format: manifest.source?.format || 'glb',
rawFile: modelFile,
};
// ── 检测老格式 ZIP ──
// v1: joints.json 是关节点空间锚点;joint-definitions.json 是 FK 关节定义
// v2: joints.json 是 FK 关节定义;origin 是世界坐标
// v3: origin 是 parent-local(URDF 风格),motion 是全局 keyframes schema
// v4: model.glb 由 GLTFExporter 序列化,包含运行时插入的 group。
// origin 语义改为「父刚性坐标系」(parent rigid frame,无 scale)
const schemaVersion = manifest.schema_version || 1;
const hasLegacyJointDefsFile = !!manifest.files?.joint_definitions;
// v < 4:origin / 场景树状态都不兼容当前代码,导入后 reset 关节定义
const needsOriginReset = schemaVersion < 4;
if (schemaVersion < 2 || hasLegacyJointDefsFile) {
alert(
'该资产包使用旧版关节格式(v1),新版编辑器不支持自动迁移。\n\n' +
'模型加载正常;请重新在场景树中配置关节定义。'
);
} else if (needsOriginReset) {
alert(
'该资产包是旧版本(v' + schemaVersion + '),关节坐标语义已变更。\n\n' +
'已自动重置所有关节的 origin 和 currentValue 为 0;并且旧版本不包含运行时插入的父级 group,' +
'需要重新插入父级 + 用「子对象底部 / 中心」拾取原点。'
);
}
// Restore joint definitions (FK layer-tree joints) — v2 stored under "joints"
keyframeManager.jointDefinitions.clear();
const jointsFileName = manifest.files?.joints;
// v2 优先:joints-{ts}.json 直接是 FK 关节定义
// v1 兜底:尝试老的 joint-definitions-{ts}.json
let jointsFile = jointsFileName ? zip.file(jointsFileName) : null;
if (!jointsFile) {
jointsFile = Object.values(zip.files).find((f) => /^joints-.*\.json$/i.test(f.name)) || null;
}
if (!jointsFile && hasLegacyJointDefsFile) {
jointsFile = zip.file(manifest.files.joint_definitions)
|| Object.values(zip.files).find((f) => /^joint-definitions.*\.json$/i.test(f.name));
}
if (jointsFile) {
// Build path-based lookup for fallback matching
const objectsByPath = new Map();
editableObjects.forEach((obj) => {
const path = getScenePath(obj);
if (path) objectsByPath.set(path, obj);
});
const data = JSON.parse(await jointsFile.async('string'));
// v2+ 用 definitions 数组;v1 老 joints.json 用 joints 数组(关节点,跳过它)
const definitionsArr = Array.isArray(data.definitions) ? data.definitions : [];
definitionsArr.forEach((d) => {
// Priority: 1) name match, 2) scene_path match, 3) fallback to stored id
let childObj = d.name ? objectsByName.get(d.name) : null;
if (!childObj && d.scene_path) {
childObj = objectsByPath.get(d.scene_path) || null;
}
const nodeId = childObj?.uuid || d.child_id || d.id;
// ── v5 修复:用 parent_name 按名字解析关节父级 ──
// 之前用 childObj.parent(总是 scene parent / 无名包装),会丢失链式关系。
// 现在优先按 parent_name 在 objectsByName 里查找实际逻辑父级。
let resolvedParentObj = null;
if (d.parent_name) {
resolvedParentObj = objectsByName.get(d.parent_name) || null;
}
if (!resolvedParentObj) {
// 兜底:scene parent(无名包装),保持独立关节可用
resolvedParentObj = childObj?.parent || null;
}
// v < 3:origin 是世界坐标,新代码当 parent-local 解读会错位 → 强制 reset
// currentValue 也 reset 为 0,避免一加载就处于奇怪的姿态
const useOrigin = needsOriginReset
? { x: 0, y: 0, z: 0 }
: { x: d.origin?.x ?? 0, y: d.origin?.y ?? 0, z: d.origin?.z ?? 0 };
const useCurrentValue = needsOriginReset ? 0 : (d.current_value ?? 0);
keyframeManager.setJointDef(nodeId, {
name: d.name || '',
type: d.type || 'none',
axis: d.axis || 'y',
role: d.role || '', // 语义角色(v6+ 字段,老 ZIP 没有时为空)
origin: useOrigin,
limits: { min: d.limits?.min ?? -180, max: d.limits?.max ?? 180 },
parentId: resolvedParentObj?.uuid || null,
childId: nodeId,
currentValue: useCurrentValue,
// v5 修复:清空 baseTransform,让 applyJointDrive 懒捕获重建。
// 导出时 GLB 是零位态,懒捕获从零位态建立正确的 base。
baseTransform: null,
});
});
}
// ── 恢复 motion.json(v2 schema:全局 clips + jointValues 关键帧) ──
// 老 schema (v1) 是 per-object channels.translate/rotate/joint,不再支持
const motionFileName = manifest.files?.motion || 'motion.json';
const motionFile = zip.file(motionFileName) || zip.file('motion.json');
let oldMotionDetected = false;
if (motionFile) {
const motionData = JSON.parse(await motionFile.async('string'));
const clipsArr = motionData.clips || [];
// 检测格式:v2 用 keyframes[].joint_values,v1 用 channels.translate/rotate
const isV2 = clipsArr.length > 0 && clipsArr[0].keyframes && Array.isArray(clipsArr[0].keyframes)
&& clipsArr[0].keyframes.length > 0 && clipsArr[0].keyframes[0].joint_values !== undefined;
const isV1 = !isV2 && clipsArr.length > 0 && clipsArr[0].channels !== undefined;
if (isV1) {
oldMotionDetected = true;
}
if (isV2) {
// 清空默认 clip,从导入的数据重建全局 clips
keyframeManager.globalClips.clear();
// 建立 jointDef name → id 的映射,用于把导出时的 name 转回当前 uuid
const jointDefIdByName = new Map();
keyframeManager.getAllJointDefs().forEach((d) => {
if (d.name) jointDefIdByName.set(d.name, d.id);
});
clipsArr.forEach((clipData) => {
const clipName = clipData.clip_name || 'default';
const newClip = {
clipName,
duration: Math.max(0.1, Number(clipData.duration) || 10),
keyframes: (clipData.keyframes || []).map((k) => {
// joint_values 是 { defName: number },转成当前 jointDef id
const jv = {};
const src = k.joint_values || {};
Object.entries(src).forEach(([defName, value]) => {
const id = jointDefIdByName.get(defName);
if (id !== undefined && value !== null && value !== undefined) {
jv[id] = Number(value);
}
});
return { time: Number(k.t ?? k.time ?? 0), jointValues: jv };
}).sort((a, b) => a.time - b.time),
// v5: 恢复 reparent 事件(v4 及以前 ZIP 没有这个字段 → 空数组)
reparentEvents: (clipData.reparent_events || []).map((e) => ({
event_id: e.event_id || `rev_imp_${Math.random().toString(36).slice(2, 8)}`,
t: Number(e.t) || 0,
child_name: String(e.child_name || ''),
new_parent_name: e.new_parent_name === undefined ? null : e.new_parent_name,
})).sort((a, b) => a.t - b.t),
};
keyframeManager.globalClips.set(clipName, newClip);
});
if (!keyframeManager.globalClips.size) {
keyframeManager.globalClips.set('default', { clipName: 'default', duration: 10, keyframes: [], reparentEvents: [] });
}
keyframeManager.activeClipName = clipsArr[0]?.clip_name || keyframeManager.globalClips.keys().next().value;
}
}
// v1 检测到时给一次提示(不阻止其他数据加载)
if (oldMotionDetected) {
alert('该资产包使用旧版 motion.json 格式(per-object channels),已忽略关键帧数据。\n请重新配置关节并重新加关键帧。');
}
// ── 恢复 PKF 数据(向后兼容:旧包无 pkf 字段时跳过)──
const pkfFileName = manifest.files?.pkf;
const pkfFile = pkfFileName
? zip.file(pkfFileName)
: Object.values(zip.files).find((f) => /^pkf-.*\.json$/i.test(f.name));
let restoredPkfParams = 0;
let restoredPkfSteps = 0;
if (pkfFile) {
const pkfData = JSON.parse(await pkfFile.async('string'));
// 恢复参数
(pkfData.parameters || []).forEach((p) => {
keyframeManager.addPkfParameter({
id: p.id,
type: p.type || 'number',
unit: p.unit || '',
desc: p.desc || '',
default: p.default ?? 0,
});
});
restoredPkfParams = (pkfData.parameters || []).length;
// 恢复步骤:用 joint 名字查当前 jointDef,重建 joint_def_id
// pkf.json v4+ 只存 joint 名字;joint_def_id 是运行时 uuid,导入后才填充
const jointDefIdByName = new Map();
keyframeManager.getAllJointDefs().forEach((d) => {
if (d.name) jointDefIdByName.set(d.name, d.id);
});
(pkfData.steps || []).forEach((s) => {
const resolvedDefId = jointDefIdByName.get(s.joint) || s.joint_def_id || '';
keyframeManager.addPkfStep({
id: s.id,
joint: s.joint || '',
joint_def_id: resolvedDefId,
channel: s.channel || 'translate',
axis: s.axis || 'z',
t_start: s.t_start ?? 0,
t_end: s.t_end ?? 1,
value_start: s.value_start ?? '0',
value_end: s.value_end ?? '0',
easing: s.easing || 'linear',
});
});
restoredPkfSteps = (pkfData.steps || []).length;
}
// ── schema v6: 恢复场景标记 metadata ──
// GLB 里已经有 marker 对象(按 name 在 scene 里),这里只要补 type/size/color 元数据
// 旧 ZIP(v4/v5)没有 scene_markers 字段 → 跳过,行为同之前
keyframeManager.sceneMarkers.clear();
(manifest.scene_markers || []).forEach((m) => {
keyframeManager.sceneMarkers.set(m.id, {
id: m.id,
name: m.name,
type: m.type,
size: m.size ? { ...m.size } : null,
color: m.color || null,
});
});
selectionManager.clearSelection();
// ── v5 修复:两阶段应用关节,保证链式关节的 base 在零位捕获 ──
// 问题:如果父级 joint 的 currentValue 非零,拓扑排序会先驱动父级 → 父级移动
// → 子级 lazy capture 捕获的是"父级驱动态"下的相对位置(错误 base)
// → 播放动画时父级回零位,子级相对下沉
// 解决:先把所有 value 清零 → applyDrives 让所有 joint 在零位懒捕获 base
// → 再恢复真实 value → 正常驱动
const savedImportValues = keyframeManager.getAllJointDefs().map((d) => ({
id: d.id,
value: d.currentValue,
}));
savedImportValues.forEach((s) => {
const d = keyframeManager.jointDefinitions.get(s.id);
if (d) d.currentValue = 0;
});
keyframeManager.applyAllJointDrives(sceneManager.sceneRoot);
savedImportValues.forEach((s) => {
const d = keyframeManager.jointDefinitions.get(s.id);
if (d) d.currentValue = s.value;
});
keyframeManager.evaluateAllAt(0, sceneManager.sceneRoot);
keyframeManager.applyAllJointDrives(sceneManager.sceneRoot);
// 全局 clip + 关键帧统计(重构后是项目级,与对象数无关)
const restoredClipCount = keyframeManager.globalClips.size;
let restoredKfCount = 0;
keyframeManager.globalClips.forEach((c) => { restoredKfCount += c.keyframes.length; });
// 状态信息包含 PKF 统计
const pkfInfo = (restoredPkfParams || restoredPkfSteps)
? `,PKF 参数:${restoredPkfParams},PKF 步骤:${restoredPkfSteps}`
: '';
ui.setLoadStatus(
`已导入资产包。对象:${editableObjects.length},片段:${restoredClipCount},关键帧:${restoredKfCount}${pkfInfo}`,
);
refreshObjectTree();
refreshPkfParamsUI(); // 刷新 PKF 参数 UI
refreshPkfStepsUI(); // 刷新 PKF 步骤 UI
refreshReparentEventList(); // 刷新 reparent 事件列表
refreshMarkerList(); // 刷新 marker 列表
refreshAiJointChips(); // 刷新 AI 面板的关节 chips
} catch (error) {
ui.setLoadStatus(`导入资产包失败:${error.message}`);
}
}
/**
* 用 PKF 步骤驱动所有关节定义到指定时间点
* 遍历每一步:求值起止公式,在 [t_start, t_end] 区间内按缓动插值,
* 把结果写入对应 jointDefinition.currentValue。
* 查找策略:优先 joint_def_id(uuid),失败则按 joint 名字 fallback。
* 这样即使 PKF 步骤从 pkf.json 导入后 uuid 变了,只要名字还在就能正确驱动。
*
* @param {number} t - 当前时间(秒)
*/
// PKF 错误"已警告"集合:避免播放时每帧 60 次刷屏
// key 形式:`${step_id}|${reason}` — reason 变了或换步骤会重新警告一次
const _pkfWarnedKeys = new Set();
function applyPkfAtTime(t) {
// 建立 name → def 的索引
const defByName = new Map();
keyframeManager.jointDefinitions.forEach((d) => {
if (d.name) defByName.set(d.name, d);
});
// 循环播放修复:每帧先把所有 PKF 触及的关节重置为 0
// 原因:evaluatePkfAt 对未开始的步骤不输出 result(joint 未触及),
// 如果不重置,循环回到 t=0 时未开始的关节仍保留上一轮末态 → 视觉"卡顿 + 瞬回"
// 之后 results.forEach 按步骤时间顺序覆写:active 的按插值,completed 的保持 value_end
keyframeManager.pkfSteps.forEach((step) => {
let def = step.joint_def_id ? keyframeManager.jointDefinitions.get(step.joint_def_id) : null;
if (!def && step.joint) def = defByName.get(step.joint);
if (def) def.currentValue = 0;
});
const results = keyframeManager.evaluatePkfAt(t);
results.forEach((r) => {
// 公式求值出错:白名单拒绝、参数缺失等 → 警告并跳过
if (r.error) {
const key = `${r.step_id}|formula:${r.error}`;
if (!_pkfWarnedKeys.has(key)) {
_pkfWarnedKeys.add(key);
console.warn(`[PKF] 步骤 "${r.joint || r.step_id}" 公式求值失败:${r.error}`);
}
return;
}
// 先按 uuid 查,失败再按名字
let def = r.joint_def_id ? keyframeManager.jointDefinitions.get(r.joint_def_id) : null;
if (!def && r.joint) def = defByName.get(r.joint);
// 关节查找失败:joint 名拼错、关节被删、AI 输出截断(#10 收紧后会落到这里)
if (!def) {
const key = `${r.step_id}|missing:${r.joint}`;
if (!_pkfWarnedKeys.has(key)) {
_pkfWarnedKeys.add(key);
console.warn(`[PKF] 步骤找不到关节 "${r.joint}"(step_id=${r.step_id}),该步骤将被跳过`);
}
return;
}
def.currentValue = r.value;
});
}
function updateTimeline(deltaSeconds) {
if (!isPlaying) return;
const duration = getCurrentDuration();
const next = (keyframeManager.currentTime + deltaSeconds) % duration;
if (pkfPlaybackMode) {
// PKF 模式:跳过关键帧求值,用 PKF 公式驱动关节
keyframeManager.currentTime = next;
applyPkfAtTime(next);
} else {
// 原有模式:用 motion.json 关键帧求值
keyframeManager.evaluateAllAt(next, sceneManager.sceneRoot);
}
ui.setTime(keyframeManager.currentTime);
ui.updateTimelineLabel(keyframeManager.currentTime, duration);
}
function loop(now) {
const deltaSeconds = (now - lastFrameTime) / 1000;
lastFrameTime = now;
updateTimeline(deltaSeconds);
// v5: reparent 事件先应用(切 scene graph parent),再驱动关节
// 顺序很重要——joint 计算用最新的 scene graph
keyframeManager.applyReparentEventsAtTime(keyframeManager.currentTime, sceneManager.sceneRoot);
keyframeManager.applyAllJointDrives(sceneManager.sceneRoot);