-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
435 lines (372 loc) · 19.6 KB
/
Copy pathindex.html
File metadata and controls
435 lines (372 loc) · 19.6 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Iridescent Glass & Light Reflections</title>
<style>
/* Basic CSS to make the canvas full screen and hide scrollbars */
body {
margin: 0;
overflow: hidden;
background-color: #050505;
font-family: sans-serif;
}
/* Styling for the UI overlay text */
#info {
position: absolute;
top: 15px;
width: 100%;
text-align: center;
color: rgba(255, 255, 255, 0.7);
pointer-events: none;
z-index: 10;
font-size: 14px;
letter-spacing: 1px;
}
</style>
<!--
Use Import Maps to load modern Three.js ES Modules directly from CDN.
This avoids needing a build step (like Webpack/Vite) for a single file.
-->
<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>
<!-- UI Overlay -->
<div id="info">Drag to rotate • Scroll/Pan to zoom</div>
<script type="module">
/**
* ============================================================================
* IRIDESCENT GLASS & DYNAMIC CAUSTIC PROJECTION SCENE
* ============================================================================
* * INTRODUCTION:
* This Three.js scene simulates a collection of thin, iridescent PVC glass sheets
* in a dark studio environment. As a central point light moves, the light passes
* through the sheets and projects vibrant, colored shadows (caustics) onto the
* floor beneath them.
* * KEY FEATURES:
* 1. Lifecycle Management: Maintains exactly 12 glass sheets. Sheets smoothly fade
* in and out over a 10-second lifespan, and randomly respawn without overlapping.
* 2. Custom Canvas Textures: Generates rich gradients via HTML5 Canvas API and
* injects them directly into the 3D materials.
* 3. Ray-Traced Shadow Projection: Uses custom BufferGeometry to dynamically calculate
* and project the top corners of the glass onto the floor based on the light's
* exact 3D position. This ensures the base of the shadow stays perfectly locked
* to the glass, solving rotation detachment issues.
* ============================================================================
*/
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// ==========================================
// 1. SCENE & RENDERER SETUP
// ==========================================
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0a0a0c); // Dark studio environment
scene.fog = new THREE.Fog(0x0a0a0c, 10, 30); // Fades far objects into darkness
// Set up the camera (Field of View, Aspect Ratio, Near plane, Far plane)
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 100);
camera.position.set(0, 4, 12);
// Configure the WebGL Renderer for high quality output
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); // Support retina displays
renderer.shadowMap.enabled = true; // Enable shadows
renderer.shadowMap.type = THREE.PCFSoftShadowMap; // Soft edges for standard shadows
renderer.toneMapping = THREE.ACESFilmicToneMapping; // Cinematic color mapping
renderer.toneMappingExposure = 1.2;
document.body.appendChild(renderer.domElement);
// Add orbit controls so the user can interact with the scene
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; // Smooth camera movement
controls.dampingFactor = 0.05;
controls.minDistance = 3; // Prevent zooming too close
controls.maxDistance = 20; // Prevent zooming too far
controls.maxPolarAngle = Math.PI / 2 - 0.05; // Prevent camera from going under the floor
// ==========================================
// 2. TEXTURE GENERATION
// ==========================================
// Dynamically creates the rainbow gradients for the glass and reflections
function createGradientTexture(isCaustic = false) {
const canvas = document.createElement('canvas');
canvas.width = 512;
canvas.height = 1024;
const ctx = canvas.getContext('2d');
// Draw a linear gradient from Y=0 to Y=1024
const grd = ctx.createLinearGradient(0, 0, 0, 1024);
if (!isCaustic) {
// Glass Surface Gradient: Vivid, opaque stops
grd.addColorStop(0.00, '#1E40AF'); // Deep Blue
grd.addColorStop(0.20, '#60A5FA'); // Light Blue
grd.addColorStop(0.40, '#FDE047'); // Yellow/Gold
grd.addColorStop(0.60, '#F97316'); // Orange
grd.addColorStop(0.80, '#EC4899'); // Pink
grd.addColorStop(1.00, '#A21CAF'); // Purple
} else {
// Caustic Projection Gradient: Fades to transparent
// Note: UV maps map V=1 to top (y=0), V=0 to bottom (y=1024)
grd.addColorStop(0.00, 'rgba(162, 28, 175, 0.9)'); // Solid Purple at base
grd.addColorStop(0.20, 'rgba(236, 72, 153, 0.8)'); // Pink
grd.addColorStop(0.40, 'rgba(249, 115, 22, 0.7)'); // Orange
grd.addColorStop(0.60, 'rgba(253, 224, 71, 0.5)'); // Yellow
grd.addColorStop(0.80, 'rgba(96, 165, 250, 0.2)'); // Light Blue fading
grd.addColorStop(1.00, 'rgba(30, 64, 175, 0.0)'); // Completely transparent far edge
}
ctx.fillStyle = grd;
ctx.fillRect(0, 0, 512, 1024);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace; // Ensure correct color rendering in modern ThreeJS
return texture;
}
const glassTexture = createGradientTexture(false);
const causticTexture = createGradientTexture(true);
// ==========================================
// 3. BASE MATERIALS
// ==========================================
// Physical material for the shiny, transparent glass pieces
const baseGlassMaterial = new THREE.MeshPhysicalMaterial({
map: glassTexture,
color: 0xffffff,
metalness: 0.1,
roughness: 0.05, // Smooth surface
clearcoat: 1.0, // Extra reflective layer simulating polished glass
clearcoatRoughness: 0.05,
transparent: true,
side: THREE.DoubleSide, // Render both sides of the glass plane
depthWrite: false // Prevents transparent objects from occluding each other weirdly
});
// Basic additive material for the glowing projected reflection on the floor
const baseCausticMaterial = new THREE.MeshBasicMaterial({
map: causticTexture,
transparent: true,
blending: THREE.AdditiveBlending, // Makes colors add up to create light
side: THREE.DoubleSide, // Ensure visibility regardless of vertex winding order
depthWrite: false
});
// ==========================================
// 4. ENVIRONMENT & LIGHTING
// ==========================================
// The solid white floor
const floorGeo = new THREE.PlaneGeometry(50, 50);
const floorMat = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.1,
metalness: 0.1
});
const floor = new THREE.Mesh(floorGeo, floorMat);
floor.rotation.x = -Math.PI / 2; // Lay flat
floor.receiveShadow = true; // Let the main light cast standard shadows on it
scene.add(floor);
// Ambient Light: Fills the dark room with very weak baseline illumination
const ambientLight = new THREE.AmbientLight(0xffffff, 0.3);
scene.add(ambientLight);
// Main Point Light: This drives the entire caustic projection simulation
const pointLight = new THREE.PointLight(0xffffff, 150, 50);
pointLight.position.set(0, 5, 4);
pointLight.castShadow = true;
pointLight.shadow.mapSize.width = 2048;
pointLight.shadow.mapSize.height = 2048;
pointLight.shadow.bias = -0.001;
scene.add(pointLight);
// Fill Light: A secondary weak blue light to illuminate the dark sides of objects
const fillLight = new THREE.PointLight(0xa0b0ff, 40, 50);
fillLight.position.set(-5, 2, -5);
scene.add(fillLight);
// ==========================================
// 5. DYNAMIC GLASS MANAGER
// ==========================================
const activeGlasses = [];
const EXACT_GLASSES = 12; // Maintain exactly 12 pieces
const FADE_TIME = 6; // Seconds it takes to fade in/out
const LIFESPAN = 20.0; // How long a piece lives before despawning
// Spawns a single glass sheet and its corresponding reflection geometry
function spawnGlassPiece(time) {
// Determine random dimensions (Rectangles vs Squares)
const isSquare = Math.random() > 0.6;
const width = isSquare ? (Math.random() * 1.5 + 1.0) : (Math.random() * 1.5 + 0.8);
const height = isSquare ? width : (Math.random() * 3.0 + 1.5);
let x, z, rotationY;
let validPosition = false;
let attempts = 0;
// Collision Detection Loop: Find a spot that doesn't intersect existing glasses
while (!validPosition && attempts < 50) {
x = (Math.random() - 0.5) * 13;
z = (Math.random() - 0.5) * 9;
rotationY = Math.random() * Math.PI;
validPosition = true;
for (let i = 0; i < activeGlasses.length; i++) {
const other = activeGlasses[i];
const dx = x - other.mesh.position.x;
const dz = z - other.mesh.position.z;
const dist = Math.sqrt(dx * dx + dz * dz);
// Safe distance based on object widths
const safeDist = (width / 2) + (other.width / 2) + 0.3;
if (dist < safeDist) {
validPosition = false; // Overlap detected, retry
break;
}
}
attempts++;
}
// A. Create the physical 3D Glass Object
const geometry = new THREE.BoxGeometry(width, height, 0.05);
const material = baseGlassMaterial.clone(); // Clone so we can fade independently
material.opacity = 0;
const glassMesh = new THREE.Mesh(geometry, material);
glassMesh.position.set(x, height / 2, z);
glassMesh.rotation.y = rotationY;
scene.add(glassMesh);
// B. Create the Custom Projected Caustic Geometry
// We use a raw BufferGeometry because we need to manually move the 4 corners every frame
const causticGeo = new THREE.BufferGeometry();
// 4 vertices (Bottom-Left, Bottom-Right, Top-Left, Top-Right) * 3 coords (x,y,z)
const vertices = new Float32Array(12);
// Texture coordinates matching the canvas gradient
const uvs = new Float32Array([
0, 1, // Bottom Left (Base of gradient)
1, 1, // Bottom Right (Base of gradient)
0, 0, // Top Left (Transparent tip)
1, 0 // Top Right (Transparent tip)
]);
// Define two triangles to make the plane
const indices = [
0, 2, 1,
2, 3, 1
];
causticGeo.setAttribute('position', new THREE.BufferAttribute(vertices, 3));
causticGeo.setAttribute('uv', new THREE.BufferAttribute(uvs, 2));
causticGeo.setIndex(indices);
const causticMat = baseCausticMaterial.clone();
causticMat.opacity = 0;
const causticMesh = new THREE.Mesh(causticGeo, causticMat);
scene.add(causticMesh);
// Save all reference data for the animation loop
activeGlasses.push({
mesh: glassMesh,
cMesh: causticMesh,
mat: material,
cMat: causticMat,
geo: geometry,
cGeo: causticGeo,
width: width,
height: height,
createdAt: time,
lifespan: LIFESPAN,
baseOpacity: 0.55,
baseCausticOpacity: 0.85
});
}
// Initialize scene with staggered glasses to prevent synchronized blinking
for(let i = 0; i < EXACT_GLASSES; i++) {
// Negative time means they are already partially through their lifespan
spawnGlassPiece(0 - (i * (LIFESPAN / EXACT_GLASSES)));
}
// ==========================================
// 6. MAIN ANIMATION LOOP
// ==========================================
const clock = new THREE.Clock();
const tempVec = new THREE.Vector3(); // Reusable vector for math
function animate() {
requestAnimationFrame(animate);
const elapsedTime = clock.getElapsedTime();
// Move the main light source in a wide looping figure-8 pattern
pointLight.position.x = Math.sin(elapsedTime * 0.4) * 8;
pointLight.position.z = Math.cos(elapsedTime * 0.25) * 6 + 2;
// Iterate backwards through active objects to safely remove items if they expire
for (let i = activeGlasses.length - 1; i >= 0; i--) {
const item = activeGlasses[i];
const age = elapsedTime - item.createdAt;
// --- 1. LIFECYCLE MANAGEMENT ---
if (age >= item.lifespan) {
scene.remove(item.mesh);
scene.remove(item.cMesh);
// Crucial WebGL memory cleanup!
item.geo.dispose();
item.cGeo.dispose();
item.mat.dispose();
item.cMat.dispose();
activeGlasses.splice(i, 1);
continue;
}
// --- 2. OPACITY FADING LOGIC ---
let fade = 1.0;
if (age < FADE_TIME) {
fade = age / FADE_TIME; // Fading in
} else if (age > item.lifespan - FADE_TIME) {
fade = (item.lifespan - age) / FADE_TIME; // Fading out
}
// Smoothstep interpolation for a softer fade
fade = Math.max(0, Math.min(1, fade));
const smoothFade = fade * fade * (3 - 2 * fade);
item.mat.opacity = item.baseOpacity * smoothFade;
item.cMat.opacity = item.baseCausticOpacity * smoothFade;
// --- 3. GLASS FLOATING ANIMATION ---
// Makes the glass slowly hover up and down
item.mesh.position.y = (item.height / 2) + Math.sin(elapsedTime * 1.5 + item.createdAt) * 0.05;
// --- 4. DYNAMIC CAUSTIC PROJECTION (The Math Fixing Alignment) ---
// We calculate exactly where the shadow should cast based on light position
item.mesh.updateMatrixWorld();
const hw = item.width / 2;
const hh = item.height / 2;
const FLOOR_Y = 0.01; // Slightly above 0 to prevent Z-fighting flickering
// Step A: Calculate the world coordinates of the glass's Bottom Left/Right corners
// By dropping these straight to FLOOR_Y, the shadow's base perfectly locks to the glass base
tempVec.set(-hw, -hh, 0).applyMatrix4(item.mesh.matrixWorld);
const bl_x = tempVec.x; const bl_z = tempVec.z;
tempVec.set(hw, -hh, 0).applyMatrix4(item.mesh.matrixWorld);
const br_x = tempVec.x; const br_z = tempVec.z;
// Step B: Calculate the Ray-Traced projection of the Top Left/Right corners
// Shoots a line from the Point Light through the top corners down to the floor
const projectPoint = (localX, localY) => {
tempVec.set(localX, localY, 0).applyMatrix4(item.mesh.matrixWorld);
// Calculate direction vector from light to corner
const dx = tempVec.x - pointLight.position.x;
let dy = tempVec.y - pointLight.position.y;
const dz = tempVec.z - pointLight.position.z;
// Prevent math errors if light goes lower than the glass
if (dy >= -0.001) dy = -0.001;
// Find intersection distance (t) with the floor plane
const t = (FLOOR_Y - pointLight.position.y) / dy;
return {
x: pointLight.position.x + t * dx,
z: pointLight.position.z + t * dz
};
};
const proj_tl = projectPoint(-hw, hh); // Projected Top-Left
const proj_tr = projectPoint(hw, hh); // Projected Top-Right
// Step C: Apply new coordinates to the BufferGeometry
const positions = item.cGeo.getAttribute('position');
positions.setXYZ(0, bl_x, FLOOR_Y, bl_z); // Vertex 0
positions.setXYZ(1, br_x, FLOOR_Y, br_z); // Vertex 1
positions.setXYZ(2, proj_tl.x, FLOOR_Y, proj_tl.z); // Vertex 2
positions.setXYZ(3, proj_tr.x, FLOOR_Y, proj_tr.z); // Vertex 3
positions.needsUpdate = true; // Tell ThreeJS to redraw this geometry
}
// --- 5. SPAWN LOGIC ---
// If pieces died and we dipped below the limit, spawn new ones instantly
while (activeGlasses.length < EXACT_GLASSES) {
spawnGlassPiece(elapsedTime);
}
// Render Frame
controls.update();
renderer.render(scene, camera);
}
// Start animation loop
animate();
// ==========================================
// 7. WINDOW RESIZE HANDLER
// ==========================================
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
</script>
</body>
</html>