-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.txt
More file actions
630 lines (525 loc) · 23 KB
/
script.txt
File metadata and controls
630 lines (525 loc) · 23 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
<!-- 3D Me Particle System - Webflow Embed -->
<style>
/* The canvas overlays the entire screen to allow particles to fly everywhere. */
#canvas-container {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
z-index: 1;
/* Allow clicks to pass through to underlying website content */
pointer-events: none;
overflow: hidden;
}
/* Loading Container */
#loader {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
pointer-events: none;
transition: opacity 0.5s ease;
z-index: 10;
}
/* Spinner Animation */
.spinner {
width: 40px;
height: 40px;
border: 3px solid rgba(127, 127, 127, 0.3);
border-radius: 50%;
border-top-color: #888888;
animation: spin 1s ease-in-out infinite;
margin-bottom: 12px;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.loading-text {
font-family: sans-serif;
font-size: 14px;
font-weight: 600;
color: #888888;
letter-spacing: 1px;
text-transform: uppercase;
}
.hidden { opacity: 0; pointer-events: none; }
</style>
<div id="canvas-container">
<div id="loader">
<div class="spinner"></div>
<div class="loading-text">Initializing...</div>
</div>
</div>
<!-- Import Map -->
<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>
<script type="module">
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
// --- CONFIGURATION ---
const USER = 'BetaNumeric';
const REPO = '3DME';
const BRANCH = 'main';
const MODEL_FILE_NAME = 'model/me.glb';
const MODEL_URL = `https://raw.githubusercontent.com/${USER}/${REPO}/${BRANCH}/${MODEL_FILE_NAME}`;
const TARGET_ELEMENT_ID = '3d-target';
// Start high - the optimizer will reduce this if needed
const PARTICLE_COUNT = 2000000;
// --- SHADERS ---
const vertexShader = `
uniform float uPixelRatio;
uniform vec3 uMouse;
attribute float aRandom;
varying vec2 vUv;
void main() {
vUv = uv;
vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
gl_Position = projectionMatrix * mvPosition;
float size = 1.0 + aRandom * 3.5;
gl_PointSize = (size * uPixelRatio) / -mvPosition.z;
}
`;
const fragmentShader = `
uniform sampler2D uTexture;
uniform bool uUseTexture;
varying vec2 vUv;
void main() {
if (distance(gl_PointCoord, vec2(0.5, 0.5)) > 0.5) discard;
vec3 finalColor;
if (uUseTexture) {
vec4 texColor = texture2D(uTexture, vUv);
finalColor = texColor.rgb * 1.2;
} else {
finalColor = vec3(0.0, 1.0, 1.0);
}
gl_FragColor = vec4(finalColor, 1.0);
}
`;
// --- SETUP ---
const container = document.getElementById('canvas-container');
const loaderElement = document.getElementById('loader');
const scene = new THREE.Scene();
scene.background = null;
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 100);
camera.position.set(0, 0, 3.5);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x000000, 0);
container.appendChild(renderer.domElement);
// --- INTERACTION STATE ---
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2(-100, -100);
const dummyPlane = new THREE.Mesh(
new THREE.PlaneGeometry(100, 100),
new THREE.MeshBasicMaterial({ visible: false })
);
scene.add(dummyPlane);
const mouse3D = new THREE.Vector3(0, 0, 0);
const prevMouse3D = new THREE.Vector3(0, 0, 0);
const mouseVelocity = new THREE.Vector3(0, 0, 0);
let isDragging = false;
let isInteracting = false;
let pulseIntensity = 0;
let swirlDirection = 1.0;
// Rotation Variables
let rotationSpeed = 0;
let dragVelocityX = 0;
const MAX_ROTATION_SPEED = 0.002;
let lastInteractionTime = Date.now();
let previousTouchX = 0;
const customUniforms = {
uMouse: { value: new THREE.Vector3(0, 0, 0) },
uPixelRatio: { value: window.devicePixelRatio },
uTexture: { value: null },
uUseTexture: { value: false }
};
// --- PHYSICS DATA & OPTIMIZATION ---
let particles = null;
let originalPositions, currentPositions, velocities, particleRandoms;
let bufferCount = 0; // Total capacity
let activeParticleCount = 0; // Currently rendered
let modelHeight = 1.0;
// Performance Tracking
let lastFpsCheck = 0;
let frameCount = 0;
let lowFpsStreak = 0;
let highFpsStreak = 0; // Track frames with good performance
// --- HELPER: Position & Scale Sync ---
function updateModelPosition() {
const targetEl = document.getElementById(TARGET_ELEMENT_ID);
if (targetEl) {
const rect = targetEl.getBoundingClientRect();
const cx = rect.left + rect.width / 2;
const cy = rect.top + rect.height / 2;
if (!loaderElement.classList.contains('hidden')) {
loaderElement.style.left = cx + 'px';
loaderElement.style.top = cy + 'px';
}
if (!particles) return;
const ndcX = (cx / window.innerWidth) * 2 - 1;
const ndcY = -(cy / window.innerHeight) * 2 + 1;
const vector = new THREE.Vector3(ndcX, ndcY, 0.5);
vector.unproject(camera);
const dir = vector.sub(camera.position).normalize();
const distance = -camera.position.z / dir.z;
const pos = camera.position.clone().add(dir.multiplyScalar(distance));
particles.position.copy(pos);
const vFOV = THREE.MathUtils.degToRad(camera.fov);
const visibleHeightAtZ0 = 2 * Math.tan(vFOV / 2) * camera.position.z;
const screenPct = rect.height / window.innerHeight;
const desiredHeight3D = visibleHeightAtZ0 * screenPct;
if (modelHeight > 0 && rect.height > 0) {
const scale = desiredHeight3D / modelHeight;
particles.scale.setScalar(scale);
}
}
}
// --- HELPER: Geometry Sampling ---
function sampleGeometry(geometry, count) {
const positions = new Float32Array(count * 3);
const uvs = new Float32Array(count * 2);
const posAttr = geometry.attributes.position;
const uvAttr = geometry.attributes.uv;
const indexAttr = geometry.index;
const getPos = (i, target) => {
const idx = indexAttr ? indexAttr.getX(i) : i;
target.fromBufferAttribute(posAttr, idx);
};
const getUv = (i, target) => {
if (!uvAttr) return target.set(0,0);
const idx = indexAttr ? indexAttr.getX(i) : i;
target.fromBufferAttribute(uvAttr, idx);
};
const faceCount = (indexAttr ? indexAttr.count : posAttr.count) / 3;
const areas = [];
let totalArea = 0;
const a = new THREE.Vector3(), b = new THREE.Vector3(), c = new THREE.Vector3();
for (let i = 0; i < faceCount; i++) {
getPos(i * 3, a); getPos(i * 3 + 1, b); getPos(i * 3 + 2, c);
const area = 0.5 * new THREE.Vector3().crossVectors(new THREE.Vector3().subVectors(b, a), new THREE.Vector3().subVectors(c, a)).length();
areas.push(area);
totalArea += area;
}
let generated = 0;
let cumulative = 0;
const uvA = new THREE.Vector2(), uvB = new THREE.Vector2(), uvC = new THREE.Vector2();
for (let i = 0; i < faceCount; i++) {
cumulative += areas[i];
const target = Math.floor((cumulative / totalArea) * count);
const n = target - generated;
if (n <= 0) continue;
getPos(i * 3, a); getPos(i * 3 + 1, b); getPos(i * 3 + 2, c);
getUv(i * 3, uvA); getUv(i * 3 + 1, uvB); getUv(i * 3 + 2, uvC);
for (let j = 0; j < n; j++) {
const r1 = Math.random(), r2 = Math.random();
const sqrtR1 = Math.sqrt(r1);
const u = 1 - sqrtR1, v = sqrtR1 * (1 - r2), w = sqrtR1 * r2;
positions[generated*3] = a.x*u + b.x*v + c.x*w;
positions[generated*3+1] = a.y*u + b.y*v + c.y*w;
positions[generated*3+2] = a.z*u + b.z*v + c.z*w;
uvs[generated*2] = uvA.x*u + uvB.x*v + uvC.x*w;
uvs[generated*2+1] = uvA.y*u + uvB.y*v + uvC.y*w;
generated++;
}
}
return { positions, uvs };
}
function shuffleIndices(count) {
const indices = new Uint32Array(count);
for (let i = 0; i < count; i++) indices[i] = i;
for (let i = count - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[indices[i], indices[j]] = [indices[j], indices[i]];
}
return indices;
}
// --- LOADING ---
const gltfLoader = new GLTFLoader();
gltfLoader.load(MODEL_URL, (gltf) => {
const model = gltf.scene;
let texture = null;
model.updateMatrixWorld(true);
model.traverse((child) => {
if (child.isMesh && !particles) {
const tempGeo = child.geometry.clone();
tempGeo.applyMatrix4(child.matrixWorld);
tempGeo.computeBoundingBox();
const bbox = tempGeo.boundingBox;
modelHeight = bbox.max.y - bbox.min.y;
const center = new THREE.Vector3();
bbox.getCenter(center);
tempGeo.translate(-center.x, -center.y, -center.z);
if (child.material.map) texture = child.material.map;
const sampled = sampleGeometry(tempGeo, PARTICLE_COUNT);
const indices = shuffleIndices(PARTICLE_COUNT);
const pos = new Float32Array(PARTICLE_COUNT * 3);
const uv = new Float32Array(PARTICLE_COUNT * 2);
for(let i=0; i<PARTICLE_COUNT; i++) {
const src = indices[i];
pos[i*3] = sampled.positions[src*3];
pos[i*3+1] = sampled.positions[src*3+1];
pos[i*3+2] = sampled.positions[src*3+2];
uv[i*2] = sampled.uvs[src*2];
uv[i*2+1] = sampled.uvs[src*2+1];
}
const geo = new THREE.BufferGeometry();
geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
geo.setAttribute('uv', new THREE.BufferAttribute(uv, 2));
bufferCount = PARTICLE_COUNT;
activeParticleCount = PARTICLE_COUNT;
originalPositions = new Float32Array(pos);
currentPositions = geo.attributes.position.array;
velocities = new Float32Array(bufferCount * 3);
particleRandoms = new Float32Array(bufferCount);
for(let i=0; i<bufferCount; i++) particleRandoms[i] = Math.random();
geo.setAttribute('aRandom', new THREE.BufferAttribute(particleRandoms, 1));
if (texture) {
customUniforms.uTexture.value = texture;
customUniforms.uUseTexture.value = true;
}
const mat = new THREE.ShaderMaterial({
uniforms: customUniforms,
vertexShader: vertexShader,
fragmentShader: fragmentShader,
transparent: false, depthWrite: true, blending: THREE.NormalBlending
});
particles = new THREE.Points(geo, mat);
particles.frustumCulled = false;
scene.add(particles);
loaderElement.classList.add('hidden');
lastFpsCheck = performance.now();
updateModelPosition();
}
});
});
// --- INPUT HANDLING ---
function updateMouse(x, y) {
mouse.x = (x / window.innerWidth) * 2 - 1;
mouse.y = -(y / window.innerHeight) * 2 + 1;
}
function interact() {
lastInteractionTime = Date.now();
}
function isInteractiveElement(target) {
return target.closest('a, button, input, textarea, select, [role="button"]');
}
window.addEventListener('contextmenu', (e) => e.preventDefault());
window.addEventListener('mousemove', (e) => {
updateMouse(e.clientX, e.clientY);
if (isDragging) {
dragVelocityX = e.movementX * 0.005;
interact();
}
});
window.addEventListener('mousedown', (e) => {
if (isInteractiveElement(e.target)) return;
isDragging = true;
dragVelocityX = 0;
pulseIntensity = 0.8;
swirlDirection = (e.button === 2) ? -1.0 : 1.0;
interact();
});
window.addEventListener('mouseup', () => { isDragging = false; });
window.addEventListener('touchstart', (e) => {
if (isInteractiveElement(e.target)) return;
if(e.touches.length > 0) {
const tx = e.touches[0].clientX;
const ty = e.touches[0].clientY;
updateMouse(tx, ty);
previousTouchX = tx;
isDragging = true;
pulseIntensity = 0.8;
dragVelocityX = 0;
swirlDirection = 1.0;
interact();
dummyPlane.lookAt(camera.position);
raycaster.setFromCamera(mouse, camera);
const hits = raycaster.intersectObject(dummyPlane);
if(hits.length>0) {
prevMouse3D.copy(hits[0].point);
mouse3D.copy(hits[0].point);
if (particles) mouse3D.sub(particles.position);
if (particles) mouse3D.applyQuaternion(particles.quaternion.clone().invert());
customUniforms.uMouse.value.copy(mouse3D);
}
}
}, {passive: false});
window.addEventListener('touchend', () => { isDragging = false; });
window.addEventListener('touchmove', (e) => {
if(e.touches.length > 0) {
const tx = e.touches[0].clientX;
const ty = e.touches[0].clientY;
updateMouse(tx, ty);
const deltaX = tx - previousTouchX;
dragVelocityX = deltaX * 0.005;
previousTouchX = tx;
}
}, {passive: false});
// --- ANIMATION LOOP ---
function animate() {
requestAnimationFrame(animate);
updateModelPosition();
// --- FAST ADAPTIVE OPTIMIZER ---
const currentTime = performance.now();
frameCount++;
const timeDiff = currentTime - lastFpsCheck;
// Check every 0.5 seconds for faster response
if (timeDiff >= 500) {
const fps = (frameCount / timeDiff) * 1000;
frameCount = 0;
lastFpsCheck = currentTime;
// Downgrade Logic
if (fps < 20) {
lowFpsStreak++;
highFpsStreak = 0;
// Reduce after 2 checks (1 second) of bad performance
if (lowFpsStreak >= 2 && activeParticleCount > 10000) {
const newCount = Math.floor(activeParticleCount * 0.8);
activeParticleCount = newCount;
particles.geometry.setDrawRange(0, activeParticleCount);
// Important: Reset streak to avoid rapid-fire reduction every 0.5s
lowFpsStreak = 0;
}
}
// Upgrade Logic (Recovery)
else if (fps > 58) {
highFpsStreak++;
lowFpsStreak = 0;
// Wait for 4 checks (2 seconds) of smooth sailing before upgrading
// Prevents oscillation between good/bad states
if (highFpsStreak >= 4 && activeParticleCount < bufferCount) {
const newCount = Math.min(bufferCount, Math.floor(activeParticleCount * 1.1));
activeParticleCount = newCount;
particles.geometry.setDrawRange(0, activeParticleCount);
highFpsStreak = 0;
}
} else {
lowFpsStreak = 0;
highFpsStreak = 0;
}
}
if (isDragging) {
rotationSpeed = dragVelocityX;
} else {
if (Date.now() - lastInteractionTime > 3000) {
if (rotationSpeed < MAX_ROTATION_SPEED) rotationSpeed += 0.0001;
} else {
rotationSpeed *= 0.95;
}
}
if (particles) {
if (Math.abs(rotationSpeed) > 0.00001) {
particles.rotation.y += rotationSpeed;
}
}
if (pulseIntensity > 0) {
pulseIntensity *= 0.92;
if (pulseIntensity < 0.01) pulseIntensity = 0;
}
dummyPlane.lookAt(camera.position);
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObject(dummyPlane);
if (intersects.length > 0) {
const point = intersects[0].point;
mouseVelocity.copy(point).sub(prevMouse3D);
prevMouse3D.copy(point);
mouse3D.copy(point);
if (particles) {
mouse3D.sub(particles.position);
mouse3D.applyQuaternion(particles.quaternion.clone().invert());
mouse3D.divide(particles.scale);
mouseVelocity.applyQuaternion(particles.quaternion.clone().invert());
mouseVelocity.divide(particles.scale);
}
customUniforms.uMouse.value.copy(mouse3D);
} else {
mouseVelocity.set(0,0,0);
}
const mouseSpeed = mouseVelocity.length();
const isMoving = mouseSpeed > 0.02;
isInteracting = isDragging || isMoving || pulseIntensity > 0;
let targetRadius = 0.01;
if (isDragging) targetRadius = Math.max(mouseSpeed * 4.0, 0.3 * zoomScale);
else if (isMoving) targetRadius = Math.max(mouseSpeed * 4.0, 0.1 * zoomScale);
if (pulseIntensity > 0) targetRadius = Math.max(targetRadius, pulseIntensity);
targetRadius = Math.min(targetRadius, 0.8);
const interactionRadius = isInteracting ? targetRadius : 0.01;
const interactionRadiusSq = interactionRadius * interactionRadius;
if (particles && originalPositions) {
const now = Date.now() * 0.006;
const localViewAxis = new THREE.Vector3(0, 0, 1).applyQuaternion(particles.quaternion.clone().invert()).normalize();
for (let i = 0; i < activeParticleCount; i++) {
const ix = i * 3; const iy = i * 3 + 1; const iz = i * 3 + 2;
let px = currentPositions[ix];
let py = currentPositions[iy];
let pz = currentPositions[iz];
let vx = velocities[ix]; let vy = velocities[iy]; let vz = velocities[iz];
const r = particleRandoms[i];
vx += (originalPositions[ix] - px) * (0.001 * (0.5 + r));
vy += (originalPositions[iy] - py) * (0.001 * (0.5 + r));
vz += (originalPositions[iz] - pz) * (0.001 * (0.5 + r));
const mDx = px - mouse3D.x;
const mDy = py - mouse3D.y;
const mDz = pz - mouse3D.z;
const distSq = mDx*mDx + mDy*mDy + mDz*mDz;
if (distSq < interactionRadiusSq) {
const dist = Math.sqrt(distSq);
const influence = (1.0 - (distSq / interactionRadiusSq));
if (isInteracting) {
const force = (0.8 + r * 0.4);
vx += mouseVelocity.x * force * influence * 0.2;
vy += mouseVelocity.y * force * influence * 0.2;
vz += mouseVelocity.z * force * influence * 0.2;
if (dist > 0.001) {
const swirl = 0.15 * (0.5 + r) * swirlDirection;
const sx = localViewAxis.y * mDz - localViewAxis.z * mDy;
const sy = localViewAxis.z * mDx - localViewAxis.x * mDz;
const sz = localViewAxis.x * mDy - localViewAxis.y * mDx;
vx += sx * swirl * influence;
vy += sy * swirl * influence;
vz += sz * swirl * influence;
const pulse = Math.sin(now + r * 6.28);
const rad = 0.05 * pulse * force;
vx += (mDx / dist) * rad * influence;
vy += (mDy / dist) * rad * influence;
vz += (mDz / dist) * rad * influence;
}
if (pulseIntensity > 0) {
const pForce = pulseIntensity * 0.05;
vx += (mDx / dist) * pForce * influence;
vy += (mDy / dist) * pForce * influence;
vz += (mDz / dist) * pForce * influence;
}
}
}
vx *= 0.90; vy *= 0.90; vz *= 0.90;
px += vx; py += vy; pz += vz;
currentPositions[ix] = px; currentPositions[iy] = py; currentPositions[iz] = pz;
velocities[ix] = vx; velocities[iy] = vy; velocities[iz] = vz;
}
particles.geometry.attributes.position.needsUpdate = true;
particles.geometry.attributes.position.updateRange.count = activeParticleCount * 3;
}
renderer.render(scene, camera);
}
const zoomScale = 3.5 / 3.0;
animate();
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
customUniforms.uPixelRatio.value = window.devicePixelRatio;
});
</script>