Repository navigation
Expand file tree
/
Copy pathindex.html
More file actions
819 lines (693 loc) · 34.4 KB
/
Copy pathindex.html
File metadata and controls
819 lines (693 loc) · 34.4 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
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Magic Christmas Tree - Hand Interaction</title>
<style>
body {
margin: 0; overflow: hidden; background-color: #000;
font-family: 'Helvetica Neue', Arial, sans-serif;
display: flex; justify-content: center; align-items: center;
height: 100vh; user-select: none;
}
/* 4:3 容器 */
#canvas-wrapper {
position: relative;
box-shadow: 0 0 80px rgba(212, 175, 55, 0.15);
background: #000;
overflow: hidden;
border-radius: 4px;
}
#canvas-container { width: 100%; height: 100%; display: block; }
/* 摄像头窗口 */
#video-container {
position: absolute; top: 20px; right: 20px; width: 160px; height: 120px; z-index: 2;
border: 1px solid rgba(255, 255, 255, 0.2); border-radius: 12px; overflow: hidden;
transform: scaleX(-1); /* 镜像翻转 */
box-shadow: 0 4px 20px rgba(0,0,0,0.6);
background: rgba(0,0,0,0.8);
transition: opacity 0.5s ease;
}
#input-video {
width: 100%; height: 100%; object-fit: cover; opacity: 0.5;
position: absolute; top: 0; left: 0;
}
#skeleton-canvas {
position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 10;
}
/* UI 层 */
#ui-layer {
position: absolute; top: 40px; left: 40px; z-index: 3; pointer-events: none;
color: #fff; text-shadow: 0 2px 10px rgba(0,0,0,0.9);
transition: opacity 0.5s;
}
h1 {
font-weight: 200; letter-spacing: 6px; text-transform: uppercase; font-size: 2rem; margin: 0 0 15px 0;
background: linear-gradient(to right, #fff, #ffd700, #fff);
-webkit-background-clip: text; -webkit-text-fill-color: transparent;
}
.instructions {
font-size: 0.85rem; color: #ccc; line-height: 1.8; max-width: 300px;
background: rgba(10, 10, 10, 0.6); padding: 20px; border-radius: 12px;
border-left: 2px solid #d4af37; backdrop-filter: blur(8px);
border-top: 1px solid rgba(255, 255, 255, 0.05);
}
.highlight { color: #d4af37; font-weight: 600; padding: 0 4px; }
#status-text { margin-bottom: 12px; font-size: 1.1rem; color: #fff; font-weight: 500; display: flex; align-items: center; gap: 8px;}
.status-dot { width: 8px; height: 8px; border-radius: 50%; background: #555; display: inline-block;}
/* 按钮 */
#upload-btn {
pointer-events: auto;
background: rgba(255,255,255,0.1);
border: 1px solid rgba(255,255,255,0.2);
color: #fff; padding: 12px 28px; cursor: pointer; text-transform: uppercase;
font-size: 0.75rem; margin-top: 25px; transition: all 0.3s ease;
letter-spacing: 2px; border-radius: 30px;
}
#upload-btn:hover { background: #fff; color: #000; box-shadow: 0 0 25px rgba(255,255,255,0.4); }
#file-input { display: none; }
#loading {
position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);
color: #d4af37; font-size: 1rem; letter-spacing: 4px; z-index: 10;
pointer-events: none; transition: opacity 0.5s; font-weight: 300;
}
/* 沉浸模式切换 */
#fullscreen-btn {
position: absolute; bottom: 30px; right: 30px; z-index: 20;
background: rgba(0,0,0,0.3); color: #d4af37; border: 1px solid rgba(212, 175, 55, 0.3);
width: 44px; height: 44px; border-radius: 50%; cursor: pointer;
display: flex; align-items: center; justify-content: center;
font-size: 1.2rem; transition: all 0.3s;
backdrop-filter: blur(4px);
}
#fullscreen-btn:hover { background: #d4af37; color: #000; border-color: #d4af37; }
/* 隐藏 UI 状态 */
.hide-ui #ui-layer,
.hide-ui #video-container {
opacity: 0; pointer-events: none;
}
.hide-ui #fullscreen-btn { opacity: 0.5; }
.hide-ui #fullscreen-btn:hover { opacity: 1; }
</style>
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/"
}
}
</script>
</head>
<body>
<div id="canvas-wrapper">
<div id="canvas-container"></div>
<div id="video-container">
<video id="input-video" autoplay playsinline muted></video>
<canvas id="skeleton-canvas"></canvas>
</div>
<button id="fullscreen-btn" onclick="toggleUI()" title="切换沉浸模式">⛶</button>
<div id="ui-layer">
<h1>Merry Christmas</h1>
<div id="status-text"><span class="status-dot" id="status-dot"></span><span id="status-msg">初始化引擎...</span></div>
<div class="instructions">
• <span class="highlight">握拳</span> : 聚合圣诞树<br/>
• <span class="highlight">张手</span> : 星云散开<br/>
• <span class="highlight">挥动</span> : 旋转视图 (仅散开时)<br/>
• <span class="highlight">捏合</span> : 抓取照片 (需上传)
</div>
<button id="upload-btn" onclick="document.getElementById('file-input').click()">上传纪念照片</button>
<input type="file" id="file-input" multiple accept="image/*">
</div>
<div id="loading">CRAFTING MAGIC...</div>
</div>
<script type="module">
import * as THREE from 'three';
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import { FilesetResolver, HandLandmarker } from 'https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.0';
// --- 全局配置 ---
const CONFIG = {
goldCount: 500,
silverCount: 500,
gemCount: 300,
emeraldCount: 300,
dustCount: 1000,
treeHeight: 75,
maxRadius: 30,
camDistance: 110,
bloomStrength: 0.7,
bloomThreshold: 0.35,
bloomRadius: 0.6
};
const STATE = { TREE: 'tree', SCATTER: 'scatter', ZOOM: 'zoom' };
let currentState = STATE.TREE;
let targetState = STATE.TREE;
// --- Three.js 变量 ---
let scene, camera, renderer, composer;
let mainGroup = new THREE.Group();
let goldMesh, silverMesh, gemMesh, emeraldMesh, dustSystem;
let photoMeshes = [];
let zoomTargetIndex = -1;
// --- 逻辑变量 ---
let logicData = { gold: [], silver: [], gem: [], emerald: [], dust: [], star: null };
const dummy = new THREE.Object3D();
const _tempVec3 = new THREE.Vector3(); // 复用变量,减少GC
const _tempEuler = new THREE.Euler();
let time = 0;
// --- 交互变量 ---
let handPos = { x: 0, y: 0 };
let lastHandPos = { x: 0, y: 0 };
let isHandPresent = false;
let rotationVelocity = { x: 0, y: 0 }; // 物理惯性
// --- UI 控制 ---
window.toggleUI = function() {
document.getElementById('canvas-wrapper').classList.toggle('hide-ui');
};
function updateStatus(msg, color = '#fff') {
document.getElementById('status-msg').innerHTML = msg;
document.getElementById('status-dot').style.background = color;
}
// --- 初始化场景 ---
function initThree() {
const wrapper = document.getElementById('canvas-wrapper');
const container = document.getElementById('canvas-container');
scene = new THREE.Scene();
scene.background = new THREE.Color(0x050505);
scene.fog = new THREE.FogExp2(0x050505, 0.002);
updateDimensions(); // 计算初始尺寸
camera = new THREE.PerspectiveCamera(50, wrapper.clientWidth / wrapper.clientHeight, 0.1, 1000);
camera.position.set(0, 0, CONFIG.camDistance);
renderer = new THREE.WebGLRenderer({ antialias: false, powerPreference: "high-performance", stencil: false });
renderer.setSize(wrapper.clientWidth, wrapper.clientHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.5)); // 限制DPR以优化性能
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.1;
container.appendChild(renderer.domElement);
const pmremGenerator = new THREE.PMREMGenerator(renderer);
scene.environment = pmremGenerator.fromScene(new RoomEnvironment(), 0.04).texture;
// 灯光系统
const ambientLight = new THREE.AmbientLight(0xffffff, 0.2);
scene.add(ambientLight);
const spotLight = new THREE.SpotLight(0xffddaa, 100);
spotLight.position.set(30, 80, 50);
spotLight.angle = Math.PI / 4;
spotLight.penumbra = 1;
scene.add(spotLight);
const blueLight = new THREE.PointLight(0x4488ff, 50, 200);
blueLight.position.set(-40, -20, 40);
scene.add(blueLight);
// 后处理
const renderScene = new RenderPass(scene, camera);
const bloomPass = new UnrealBloomPass(new THREE.Vector2(wrapper.clientWidth, wrapper.clientHeight), 1.5, 0.4, 0.85);
bloomPass.threshold = CONFIG.bloomThreshold;
bloomPass.strength = CONFIG.bloomStrength;
bloomPass.radius = CONFIG.bloomRadius;
composer = new EffectComposer(renderer);
composer.addPass(renderScene);
composer.addPass(bloomPass);
createMaterialsAndMeshes();
createDust();
createStarField();
scene.add(mainGroup);
window.addEventListener('resize', onWindowResize);
}
function updateDimensions() {
const targetAspect = 4 / 3;
const windowAspect = window.innerWidth / window.innerHeight;
let width, height;
if (windowAspect > targetAspect) {
height = window.innerHeight;
width = height * targetAspect;
} else {
width = window.innerWidth;
height = width / targetAspect;
}
const wrapper = document.getElementById('canvas-wrapper');
wrapper.style.width = width + 'px';
wrapper.style.height = height + 'px';
return { width, height };
}
function createMaterialsAndMeshes() {
// 使用 MeshPhysicalMaterial 获得更好的金属质感
const goldMat = new THREE.MeshPhysicalMaterial({
color: 0xffaa00, metalness: 1.0, roughness: 0.15, clearcoat: 1.0, emissive: 0xaa5500, emissiveIntensity: 0.1
});
const silverMat = new THREE.MeshPhysicalMaterial({
color: 0xffffff, metalness: 0.9, roughness: 0.2, clearcoat: 1.0
});
const gemMat = new THREE.MeshPhysicalMaterial({
color: 0xff0044, metalness: 0.1, roughness: 0.0, transmission: 0.6, thickness: 1.5, emissive: 0x550011, emissiveIntensity: 0.4
});
const emeraldMat = new THREE.MeshPhysicalMaterial({
color: 0x00aa55, metalness: 0.2, roughness: 0.1, transmission: 0.5, thickness: 1.5, emissive: 0x002211, emissiveIntensity: 0.3
});
goldMesh = createInstancedMesh(new THREE.SphereGeometry(0.7, 12, 12), goldMat, CONFIG.goldCount, logicData.gold);
silverMesh = createInstancedMesh(new THREE.BoxGeometry(0.8, 0.8, 0.8), silverMat, CONFIG.silverCount, logicData.silver);
gemMesh = createInstancedMesh(new THREE.OctahedronGeometry(0.8, 0), gemMat, CONFIG.gemCount, logicData.gem);
emeraldMesh = createInstancedMesh(new THREE.ConeGeometry(0.5, 1.2, 6), emeraldMat, CONFIG.emeraldCount, logicData.emerald);
// 树顶之星
const starGeo = new THREE.OctahedronGeometry(3.0, 0);
const starMat = new THREE.MeshPhysicalMaterial({
color: 0xffffff, metalness:0.8, roughness:0, emissive:0xffffee, emissiveIntensity:1.5
});
const star = new THREE.Mesh(starGeo, starMat);
star.userData = {
treePos: new THREE.Vector3(0, CONFIG.treeHeight/2 + 2.5, 0),
scatterPos: new THREE.Vector3(0, 60, 0)
};
star.position.copy(star.userData.treePos);
mainGroup.add(star);
logicData.star = star;
}
function createInstancedMesh(geo, mat, count, dataArray) {
const mesh = new THREE.InstancedMesh(geo, mat, count);
mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
mainGroup.add(mesh);
// 预生成每个粒子的逻辑数据
for (let i = 0; i < count; i++) {
const h = Math.random() * CONFIG.treeHeight - CONFIG.treeHeight/2;
const normH = (h + CONFIG.treeHeight/2) / CONFIG.treeHeight;
// 树形:下宽上窄
const rMax = CONFIG.maxRadius * (1 - normH) * 1.1;
const r = Math.sqrt(Math.random()) * rMax;
const theta = Math.random() * Math.PI * 2;
const treePos = new THREE.Vector3(r * Math.cos(theta), h, r * Math.sin(theta));
// 散开:球形分布
const scatterPos = randomSpherePoint(40 + Math.random()*50);
dataArray.push({
treePos: treePos,
scatterPos: scatterPos,
currentPos: treePos.clone(),
scale: 0.5 + Math.random() * 0.9,
// 存储独立的旋转速度
rotSpeed: new THREE.Euler(Math.random()*0.02, Math.random()*0.02, 0),
rotation: new THREE.Euler(Math.random()*Math.PI, Math.random()*Math.PI, 0)
});
}
return mesh;
}
function randomSpherePoint(r) {
const u = Math.random(), v = Math.random();
const theta = 2 * Math.PI * u;
const phi = Math.acos(2 * v - 1);
return new THREE.Vector3(
r * Math.sin(phi) * Math.cos(theta),
r * Math.sin(phi) * Math.sin(theta),
r * Math.cos(phi)
);
}
function createDust() {
const geo = new THREE.BufferGeometry();
const pos = new Float32Array(CONFIG.dustCount * 3);
for(let i=0; i<CONFIG.dustCount; i++) {
const h = Math.random() * CONFIG.treeHeight - CONFIG.treeHeight/2;
const r = Math.random() * CONFIG.maxRadius + 5;
const theta = Math.random() * Math.PI * 2;
const x = r*Math.cos(theta);
const z = r*Math.sin(theta);
pos[i*3] = x; pos[i*3+1] = h; pos[i*3+2] = z;
logicData.dust.push({
treePos: new THREE.Vector3(x, h, z),
scatterPos: randomSpherePoint(70),
currentPos: new THREE.Vector3(x, h, z),
velocity: Math.random() * 0.05 + 0.02
});
}
geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
const mat = new THREE.PointsMaterial({
color: 0xffd700, size: 0.5, transparent: true, opacity: 0.4,
blending: THREE.AdditiveBlending, depthWrite: false
});
dustSystem = new THREE.Points(geo, mat);
mainGroup.add(dustSystem);
}
function createStarField() {
const geo = new THREE.BufferGeometry();
const pos = [];
for(let i=0; i<800; i++) {
pos.push((Math.random()-0.5)*800, (Math.random()-0.5)*800, (Math.random()-0.5)*800);
}
geo.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
const stars = new THREE.Points(geo, new THREE.PointsMaterial({color: 0x666666, size: 1.0, transparent: true, opacity: 0.6}));
scene.add(stars);
}
// --- 核心动画循环 ---
function animate() {
requestAnimationFrame(animate);
time += 0.01;
// 1. 更新实例化网格
updateMeshLogic(goldMesh, logicData.gold);
updateMeshLogic(silverMesh, logicData.silver);
updateMeshLogic(gemMesh, logicData.gem);
updateMeshLogic(emeraldMesh, logicData.emerald);
// 2. 更新粒子与照片
updateDustLogic();
updatePhotoLogic();
// 3. 更新树顶星
if (logicData.star) {
let target = currentState === STATE.TREE ? logicData.star.userData.treePos : logicData.star.userData.scatterPos;
logicData.star.position.lerp(target, 0.05);
logicData.star.rotation.y += 0.01;
}
// 4. 全局旋转与惯性处理
handlePhysicsRotation();
composer.render();
}
function handlePhysicsRotation() {
if (currentState === STATE.ZOOM) {
// 缩放模式下停止旋转,方便观看
rotationVelocity.x *= 0.8;
rotationVelocity.y *= 0.8;
} else if (currentState === STATE.SCATTER) {
if (isHandPresent) {
const deltaX = handPos.x - lastHandPos.x;
const deltaY = handPos.y - lastHandPos.y;
// 增加灵敏度但限制最大速度
if (Math.abs(deltaX) > 0.001) rotationVelocity.y += deltaX * 0.2;
if (Math.abs(deltaY) > 0.001) rotationVelocity.x += deltaY * 0.1;
lastHandPos.x = handPos.x;
lastHandPos.y = handPos.y;
}
// 应用速度
mainGroup.rotation.y += rotationVelocity.y;
mainGroup.rotation.x += rotationVelocity.x;
// 阻尼效果
rotationVelocity.y *= 0.95;
rotationVelocity.x *= 0.95;
// 回正 X 轴
mainGroup.rotation.x *= 0.98;
} else {
// 树形态自动旋转
mainGroup.rotation.y += 0.004;
mainGroup.rotation.x *= 0.95;
}
}
function updateMeshLogic(mesh, dataArray) {
const isZoom = currentState === STATE.ZOOM;
const isTree = currentState === STATE.TREE;
for (let i = 0; i < dataArray.length; i++) {
const item = dataArray[i];
let target = isTree ? item.treePos : item.scatterPos;
if(isZoom) target = item.scatterPos; // 放大时背景保持散开
// 散开时的呼吸效果
if (!isTree) item.currentPos.y += Math.sin(time + i * 0.1) * 0.01;
// 位置插值
item.currentPos.lerp(target, 0.08);
// 自转
item.rotation.x += item.rotSpeed.x;
item.rotation.y += item.rotSpeed.y;
let s = item.scale;
if(isZoom) s *= 0.5; // 聚焦时背景粒子变小,突出照片
dummy.position.copy(item.currentPos);
dummy.rotation.copy(item.rotation);
dummy.scale.setScalar(s);
dummy.updateMatrix();
mesh.setMatrixAt(i, dummy.matrix);
}
mesh.instanceMatrix.needsUpdate = true;
}
function updateDustLogic() {
const positions = dustSystem.geometry.attributes.position.array;
const isTree = currentState === STATE.TREE;
for(let i=0; i<logicData.dust.length; i++) {
const item = logicData.dust[i];
if (isTree) {
// 树形态:粒子向上流动并限制在圆锥内
item.currentPos.y += item.velocity;
if(item.currentPos.y > CONFIG.treeHeight/2) item.currentPos.y = -CONFIG.treeHeight/2;
// 简单的圆柱限制,避免计算过于复杂
const rMax = CONFIG.maxRadius * (1 - (item.currentPos.y + CONFIG.treeHeight/2)/CONFIG.treeHeight) + 5;
const rCurr = Math.sqrt(item.currentPos.x**2 + item.currentPos.z**2);
if(rCurr > rMax) {
item.currentPos.x *= 0.95;
item.currentPos.z *= 0.95;
}
} else {
// 散开形态:飞向随机点
item.currentPos.lerp(item.scatterPos, 0.05);
}
positions[i*3] = item.currentPos.x;
positions[i*3+1] = item.currentPos.y;
positions[i*3+2] = item.currentPos.z;
}
dustSystem.geometry.attributes.position.needsUpdate = true;
}
function updatePhotoLogic() {
// 获取相机在 mainGroup 局部坐标系下的反向位置
// 用于让照片始终朝向屏幕
_tempVec3.copy(camera.position).applyMatrix4(mainGroup.matrixWorld.clone().invert());
photoMeshes.forEach((mesh, idx) => {
let targetPos, targetScale = 2.0;
if (currentState === STATE.ZOOM && idx === zoomTargetIndex) {
// 1. 计算镜头正前方80单位的世界坐标
const worldTarget = new THREE.Vector3(0, 0, 80);
worldTarget.applyMatrix4(camera.matrixWorld); // 转换到世界坐标(如果相机动了)
// 简单做法:直接取相机Z轴前方固定距离
// 由于 mainGroup 在转动,我们需要求这一点的局部坐标
// 实际上让照片飞到 (0,0,80) 相对于相机的点更简单,但为了保持层级,我们转换坐标
// 简化策略:将目标设为相机前方,并应用 group 的逆变换
const camFront = new THREE.Vector3(0, 0, 80); // 相机空间
camFront.applyMatrix4(camera.matrixWorld); // 世界空间
targetPos = mainGroup.worldToLocal(camFront); // 局部空间
targetScale = 5.0;
mesh.lookAt(camera.position); // 始终朝向相机
} else {
targetPos = currentState === STATE.TREE ? mesh.userData.treePos : mesh.userData.scatterPos;
if(currentState !== STATE.TREE) mesh.position.y += Math.sin(time+idx)*0.02;
// 非聚焦状态下,根据基础旋转+公转
if(currentState === STATE.SCATTER) targetScale = 3.0;
if (currentState === STATE.TREE) {
mesh.rotation.copy(mesh.userData.baseRot);
mesh.rotation.y += 0.01;
} else {
mesh.lookAt(camera.position);
}
}
mesh.position.lerp(targetPos, 0.1);
const currentScale = mesh.scale.x;
const newScale = THREE.MathUtils.lerp(currentScale, targetScale, 0.1);
mesh.scale.setScalar(newScale);
});
}
// --- 交互系统 (MediaPipe) ---
async function setupMediaPipe() {
try {
const vision = await FilesetResolver.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.0/wasm");
const handLandmarker = await HandLandmarker.createFromOptions(vision, {
baseOptions: {
modelAssetPath: `https://storage.googleapis.com/mediapipe-models/hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task`,
delegate: "GPU"
},
runningMode: "VIDEO", numHands: 1
});
const video = document.getElementById("input-video");
const stream = await navigator.mediaDevices.getUserMedia({ video: true });
video.srcObject = stream;
video.addEventListener("loadeddata", () => {
document.getElementById('loading').style.display = 'none';
updateStatus("系统就绪,请伸手", "#0f0");
predictWebcam(handLandmarker, video);
});
} catch (error) {
console.error(error);
document.getElementById('loading').innerText = "Camera Access Denied";
updateStatus("无法访问摄像头", "#f00");
}
}
let lastVideoTime = -1;
let lastPredictionTime = 0;
const PREDICTION_INTERVAL = 50; // 限制手势检测频率 (ms) -> 20 FPS
async function predictWebcam(handLandmarker, video) {
const now = performance.now();
// 节流:如果是同一帧或者时间间隔太短,跳过检测
if (video.currentTime !== lastVideoTime && (now - lastPredictionTime > PREDICTION_INTERVAL)) {
lastVideoTime = video.currentTime;
lastPredictionTime = now;
const result = handLandmarker.detectForVideo(video, now);
drawAndProcess(video, result);
}
requestAnimationFrame(() => predictWebcam(handLandmarker, video));
}
function drawAndProcess(video, result) {
const canvas = document.getElementById('skeleton-canvas');
const ctx = canvas.getContext('2d');
// 确保画布尺寸匹配
if(canvas.width !== video.videoWidth) {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (result.landmarks && result.landmarks.length > 0) {
const landmarks = result.landmarks[0];
isHandPresent = true;
drawSkeleton(ctx, landmarks, canvas.width, canvas.height);
handleGesture(landmarks);
} else {
isHandPresent = false;
// 如果没有手,自动回复一点点转速
if(currentState === STATE.SCATTER) {
// rotationVelocity.y = THREE.MathUtils.lerp(rotationVelocity.y, 0.002, 0.05);
}
}
}
function drawSkeleton(ctx, landmarks, w, h) {
ctx.lineWidth = 3; ctx.strokeStyle = '#00ff88'; ctx.fillStyle = '#ff0044';
const connections = [[0,1],[1,2],[2,3],[3,4],[0,5],[5,6],[6,7],[7,8],[5,9],[9,10],[10,11],[11,12],[9,13],[13,14],[14,15],[15,16],[13,17],[17,18],[18,19],[19,20],[0,17]];
ctx.beginPath();
for (let c of connections) {
const s = landmarks[c[0]];
const e = landmarks[c[1]];
ctx.moveTo(s.x * w, s.y * h); ctx.lineTo(e.x * w, e.y * h);
}
ctx.stroke();
// 关键点
for(let p of landmarks) {
ctx.beginPath(); ctx.arc(p.x * w, p.y * h, 3, 0, 2 * Math.PI); ctx.fill();
}
}
function handleGesture(landmarks) {
// 计算手掌中心
const palmX = 1 - (landmarks[0].x + landmarks[9].x) / 2; // 镜像翻转 X
const palmY = (landmarks[0].y + landmarks[9].y) / 2;
// 平滑位置
handPos.x = handPos.x * 0.7 + palmX * 0.3;
handPos.y = handPos.y * 0.7 + palmY * 0.3;
// 简单的手势判定算法
let folded = 0;
const tips = [8,12,16,20];
const bases = [5,9,13,17];
// 指尖到指根距离判定握拳
tips.forEach((tipIdx, i) => {
const d = Math.sqrt(
Math.pow(landmarks[tipIdx].x - landmarks[0].x, 2) +
Math.pow(landmarks[tipIdx].y - landmarks[0].y, 2)
);
if(d < 0.25) folded++;
});
// 捏合检测 (食指拇指距离)
const dPinch = Math.sqrt(
Math.pow(landmarks[4].x - landmarks[8].x, 2) +
Math.pow(landmarks[4].y - landmarks[8].y, 2)
);
const isPinch = dPinch < 0.08;
const isFist = folded >= 3;
const isOpen = !isFist && !isPinch;
// 状态机
if (isPinch && currentState === STATE.SCATTER) {
if (photoMeshes.length > 0) {
switchToZoom();
updateStatus("抓取照片: 聚焦回忆", "#ffd700");
} else {
updateStatus("请先点击右下角上传照片", "#aaa");
}
} else if (isFist) {
currentState = STATE.TREE;
zoomTargetIndex = -1;
rotationVelocity.x = 0; rotationVelocity.y = 0;
updateStatus("握拳: 聚合形态", "#0f0");
} else if (isOpen) {
if (currentState === STATE.ZOOM && !isPinch) {
currentState = STATE.SCATTER;
zoomTargetIndex = -1;
} else if (currentState === STATE.TREE) {
currentState = STATE.SCATTER;
// 重置惯性位置避免跳变
lastHandPos.x = handPos.x; lastHandPos.y = handPos.y;
}
updateStatus("张手: 星云散开 (挥手旋转)", "#00aaff");
}
}
function switchToZoom() {
currentState = STATE.ZOOM;
targetState = STATE.ZOOM;
// 智能选择逻辑:选离镜头最近的照片
if (zoomTargetIndex === -1 && photoMeshes.length > 0) {
let minDist = Infinity;
let bestIdx = 0;
const camPos = camera.position;
const worldPos = new THREE.Vector3();
photoMeshes.forEach((mesh, idx) => {
mesh.getWorldPosition(worldPos);
const d = worldPos.distanceTo(camPos);
if (d < minDist) {
minDist = d;
bestIdx = idx;
}
});
zoomTargetIndex = bestIdx;
}
}
function onWindowResize() {
const dims = updateDimensions();
camera.aspect = dims.width / dims.height;
camera.updateProjectionMatrix();
renderer.setSize(dims.width, dims.height);
composer.setSize(dims.width, dims.height);
}
// --- 照片上传处理 ---
document.getElementById('file-input').addEventListener('change', function(e) {
const files = e.target.files;
if (!files.length) return;
let loadedCount = 0;
for(let i=0; i<files.length; i++) {
const reader = new FileReader();
reader.onload = function(evt) {
const img = new Image();
img.src = evt.target.result;
img.onload = () => {
addPhotoMesh(img);
loadedCount++;
updateStatus(`已加载 ${loadedCount} 张照片`, "#fff");
}
}
reader.readAsDataURL(files[i]);
}
});
function addPhotoMesh(img) {
const tex = new THREE.Texture(img);
tex.needsUpdate = true;
tex.colorSpace = THREE.SRGBColorSpace;
// 保持比例
let w = 4, h = 4;
if(img.width > img.height) h = 4 * (img.height/img.width);
else w = 4 * (img.width/img.height);
const geo = new THREE.PlaneGeometry(w, h);
const mat = new THREE.MeshBasicMaterial({
map: tex, side: THREE.DoubleSide
});
const mesh = new THREE.Mesh(geo, mat);
// 金色边框
const frame = new THREE.Mesh(
new THREE.BoxGeometry(w+0.2, h+0.2, 0.1),
new THREE.MeshPhysicalMaterial({color:0xffd700, roughness:0.2, metalness:1})
);
frame.position.z = -0.06;
mesh.add(frame);
// 随机分布
const h_pos = (Math.random() - 0.5) * CONFIG.treeHeight;
const normH = (h_pos + CONFIG.treeHeight/2) / CONFIG.treeHeight;
const maxR = CONFIG.maxRadius * (1 - normH) + 2;
const r = maxR * (0.6 + 0.4 * Math.random());
const theta = Math.random() * Math.PI * 2;
const treePos = new THREE.Vector3(r * Math.cos(theta), h_pos, r * Math.sin(theta));
const scatterPos = randomSpherePoint(60);
mesh.userData = {
treePos,
scatterPos,
baseRot: new THREE.Euler(0, theta + Math.PI/2, 0) // 面向外部
};
mesh.position.copy(treePos);
mesh.lookAt(new THREE.Vector3(0, h_pos, 0)); // 树状态下初始朝向中心
photoMeshes.push(mesh);
mainGroup.add(mesh);
}
// 启动
initThree();
animate();
setupMediaPipe();
</script>
</body>
</html>