Okay, this is an exciting and comprehensive Three.js project! We'll build this step-by-step, focusing on modularity, performance, and clear structure.
We'll use lil-gui for the UI as it's a modern and user-friendly alternative to dat.GUI.
Project Structure:
threejs-particle-morph/
├── index.html
├── main.js
└── styles.css (optional, for basic body styling)
index.html
This file sets up the basic HTML structure, including the canvas and a container for our UI.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>3D Particle Morphing System</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="ui-container"></div>
<script type="module" src="main.js"></script>
</body>
</html>
styles.css (Optional, but good for base styling and UI theme)
This will ensure the canvas fills the screen and set up a dark theme for lil-gui.
body {
margin: 0;
overflow: hidden;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #000;
}
canvas {
display: block;
}
#ui-container {
position: absolute;
top: 0;
right: 0;
padding: 10px;
z-index: 100;
/* Basic styling for the UI container, lil-gui handles most of the rest */
}
/* lil-gui dark theme adjustments */
.lil-gui {
--background-color: rgba(0, 0, 0, 0.75) !important;
--text-color: #eee !important;
--title-background-color: #1a1a1a !important;
--title-text-color: #fff !important;
--widget-color: #2a2a2a !important;
--hover-color: #3a3a3a !important;
--focus-color: #007bff !important; /* Blue highlight for focus */
--number-color: #00ccff !important; /* Particle color blue */
--string-color: #99ff99 !important;
--slider-handle-color: #00ccff !important;
--slider-background-color: #4a4a4a !important;
border: 1px solid #333 !important;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5) !important;
}
.lil-gui.root > .lil-gui.main {
top: 10px;
right: 10px;
max-height: calc(100vh - 20px);
overflow-y: auto;
}
.lil-gui li.lil-gui-item {
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}
.lil-gui .lil-gui-label {
color: var(--text-color);
}
main.js
This is the core of our application. It will contain all the Three.js setup, particle logic, morphing animations, and UI controls.
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
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 { AfterimagePass } from 'three/addons/postprocessing/AfterimagePass.js';
import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
// --- Global Variables ---
let scene, camera, renderer, controls;
let particles;
let particleMaterial;
let composer, bloomPass, afterimagePass;
// Morphing related variables
const numParticles = 20000;
let morphStartTime = 0;
const morphDuration = 1500; // 1.5 seconds
let isMorphing = false;
let sourceMorphPositions = new Float32Array(numParticles * 3);
let targetMorphPositions = new Float32Array(numParticles * 3);
let currentShapeName = 'sphere'; // Initial shape
// UI parameters
const params = {
particleSize: 0.1,
rotationSpeed: 0.0005,
particleColor: '#00ccff',
bloomIntensity: 0.5,
motionTrailIntensity: 0.9,
targetShape: 'sphere', // For GUI dropdown
shapes: {} // Stores pre-calculated positions for all shapes
};
// --- Helper Functions ---
/**
* Shuffles an array in place (Fisher-Yates algorithm).
* Used for shuffling target positions for organic morphing.
* @param {Array} array
*/
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
/**
* Normalizes and centers a set of 3D positions.
* Ensures all shapes are roughly the same scale and centered.
* @param {Float32Array} positions - The positions array (x,y,z, x,y,z...)
* @param {number} scaleFactor - Desired approximate max dimension for the normalized shape.
*/
function normalizePositions(positions, scaleFactor = 15) {
if (positions.length === 0) return;
const tempBox = new THREE.Box3();
tempBox.setFromBufferAttribute(new THREE.BufferAttribute(positions, 3));
const center = tempBox.getCenter(new THREE.Vector3());
const size = tempBox.getSize(new THREE.Vector3());
const maxDim = Math.max(size.x, size.y, size.z);
if (maxDim === 0) return; // Avoid division by zero
const normalizationRatio = scaleFactor / maxDim;
for (let i = 0; i < positions.length; i += 3) {
positions[i] = (positions[i] - center.x) * normalizationRatio;
positions[i + 1] = (positions[i + 1] - center.y) * normalizationRatio;
positions[i + 2] = (positions[i + 2] - center.z) * normalizationRatio;
}
}
/**
* Extracts and prepares positions from a Three.js Geometry for the particle system.
* Handles cases where geometry has more or fewer vertices than numParticles.
* @param {THREE.BufferGeometry} geometry - The source geometry.
* @param {number} targetCount - The desired number of particles.
* @returns {Float32Array} The prepared positions array.
*/
function getPositionsFromGeometry(geometry, targetCount) {
const sourcePositions = geometry.attributes.position.array;
const currentVertexCount = sourcePositions.length / 3;
const resultPositions = new Float32Array(targetCount * 3);
if (currentVertexCount === targetCount) {
resultPositions.set(sourcePositions);
} else if (currentVertexCount < targetCount) {
// Duplicate existing points to reach targetCount
for (let i = 0; i < targetCount; i++) {
const sourceIndex = (i % currentVertexCount) * 3;
resultPositions[i * 3] = sourcePositions[sourceIndex];
resultPositions[i * 3 + 1] = sourcePositions[sourceIndex + 1];
resultPositions[i * 3 + 2] = sourcePositions[sourceIndex + 2];
}
} else { // currentVertexCount > targetCount
// Randomly pick unique points from sourcePositions
const indices = Array.from({ length: currentVertexCount }, (_, i) => i);
shuffleArray(indices); // Shuffle to get random picks
for (let i = 0; i < targetCount; i++) {
const sourceIndex = indices[i] * 3;
resultPositions[i * 3] = sourcePositions[sourceIndex];
resultPositions[i * 3 + 1] = sourcePositions[sourceIndex + 1];
resultPositions[i * 3 + 2] = sourcePositions[sourceIndex + 2];
}
}
normalizePositions(resultPositions);
return resultPositions;
}
// --- Shape Generation Functions ---
function getSpherePositions() {
return getPositionsFromGeometry(new THREE.SphereGeometry(10, 64, 64), numParticles);
}
function getCubePositions() {
return getPositionsFromGeometry(new THREE.BoxGeometry(15, 15, 15, 16, 16, 16), numParticles);
}
function getTorusPositions() {
return getPositionsFromGeometry(new THREE.TorusGeometry(10, 3, 30, 100), numParticles);
}
function getIcosahedronPositions() {
// High-detail icosahedron for more points
return getPositionsFromGeometry(new THREE.IcosahedronGeometry(10, 8), numParticles);
}
function getTeapotPositions() {
// Three.js doesn't have a built-in TeapotGeometry in core.
// We'll use a very dense, somewhat organic sphere to represent a "complex object"
// that could be a teapot, as generating actual teapot vertices manually is complex,
// and loading an external model is outside the self-contained scope.
// Let's use a highly subdivided Sphere or Icosahedron.
return getPositionsFromGeometry(new THREE.SphereGeometry(10, 128, 128), numParticles);
}
function getDNAPositions() {
const positions = new Float32Array(numParticles * 3);
const helixRadius = 5;
const helixHeight = 25;
const turns = 8;
const pointsPerStrand = numParticles / 2;
for (let i = 0; i < pointsPerStrand; i++) {
const t = (i / pointsPerStrand) * turns * Math.PI * 2; // Angle
const y = (i / pointsPerStrand) * helixHeight - helixHeight / 2; // Y position
// Strand 1
positions[i * 3] = helixRadius * Math.cos(t);
positions[i * 3 + 1] = y;
positions[i * 3 + 2] = helixRadius * Math.sin(t);
// Strand 2 (offset by PI radians)
positions[(i + pointsPerStrand) * 3] = helixRadius * Math.cos(t + Math.PI);
positions[(i + pointsPerStrand) * 3 + 1] = y;
positions[(i + pointsPerStrand) * 3 + 2] = helixRadius * Math.sin(t + Math.PI);
}
normalizePositions(positions);
return positions;
}
function getWormholePositions() {
const positions = new Float32Array(numParticles * 3);
const maxRadius = 15;
const length = 40;
const turns = 12;
const tubeThickness = 2; // Simulate thickness for the tunnel
for (let i = 0; i < numParticles; i++) {
const t = (i / numParticles) * turns * Math.PI * 2; // Angle along the helix
const currentRadius = (i / numParticles) * maxRadius + 2; // Radius increases along length
const y = (i / numParticles) * length - length / 2; // Along Y axis
// Add some random offset to simulate particles within a tunnel
const angleOffset = Math.random() * Math.PI * 2;
const radiusOffset = Math.random() * tubeThickness;
positions[i * 3] = (currentRadius + radiusOffset) * Math.cos(t + angleOffset);
positions[i * 3 + 1] = y;
positions[i * 3 + 2] = (currentRadius + radiusOffset) * Math.sin(t + angleOffset);
}
normalizePositions(positions); // Scale to fit standard scene size
return positions;
}
// --- Main Functions ---
/**
* Initializes the Three.js scene, camera, renderer, and controls.
*/
function init() {
// Scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0x000000); // Black background
// Camera
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 50;
// Renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// OrbitControls
controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; // For smoother camera movement
controls.dampingFactor = 0.05;
controls.maxDistance = 150;
controls.minDistance = 10;
// Double-click to reset camera
renderer.domElement.addEventListener('dblclick', () => {
controls.reset();
});
// Pre-calculate and store all shape positions
params.shapes.sphere = getSpherePositions();
params.shapes.cube = getCubePositions();
params.shapes.torus = getTorusPositions();
params.shapes.icosahedron = getIcosahedronPositions();
params.shapes.teapot = getTeapotPositions(); // Using a dense sphere as placeholder
params.shapes.dna = getDNAPositions();
params.shapes.wormhole = getWormholePositions();
// Create particles with initial shape
createParticles();
// Setup Post-processing
setupPostProcessing();
// Setup GUI
setupGUI();
// Handle window resize
window.addEventListener('resize', onWindowResize);
// Start animation loop
animate();
}
/**
* Creates the particle system (Points).
*/
function createParticles() {
const geometry = new THREE.BufferGeometry();
// Start with sphere positions as initial state
geometry.setAttribute('position', new THREE.BufferAttribute(params.shapes.sphere, 3));
particleMaterial = new THREE.PointsMaterial({
color: new THREE.Color(params.particleColor),
size: params.particleSize,
sizeAttenuation: true, // Particles closer to camera appear smaller
blending: THREE.AdditiveBlending, // For glowing effect
transparent: true,
depthWrite: false // Important for additive blending with depth test
});
particles = new THREE.Points(geometry, particleMaterial);
scene.add(particles);
// Initialize sourceMorphPositions with the current positions
sourceMorphPositions.set(particles.geometry.attributes.position.array);
targetMorphPositions.set(particles.geometry.attributes.position.array);
}
/**
* Sets up post-processing effects.
*/
function setupPostProcessing() {
composer = new EffectComposer(renderer);
composer.addPass(new RenderPass(scene, camera));
// UnrealBloomPass for glow
bloomPass = new UnrealBloomPass(new THREE.Vector2(window.innerWidth, window.innerHeight), 0.5, 0.4, 0.85);
bloomPass.strength = params.bloomIntensity;
bloomPass.threshold = 0.5; // Only bright areas bloom
bloomPass.radius = 0.5;
composer.addPass(bloomPass);
// AfterimagePass for motion trails
afterimagePass = new AfterimagePass();
afterimagePass.uniforms['damp'].value = params.motionTrailIntensity;
composer.addPass(afterimagePass);
}
/**
* Starts the morphing animation to a new shape.
* @param {string} newShapeName - The name of the target shape.
*/
function startMorph(newShapeName) {
if (isMorphing || newShapeName === currentShapeName) {
return; // Don't interrupt current morph or morph to same shape
}
isMorphing = true;
morphStartTime = performance.now();
currentShapeName = newShapeName;
// Store current positions as source for interpolation
sourceMorphPositions.set(particles.geometry.attributes.position.array);
// Get the target positions for the new shape
const newShapePositions = params.shapes[newShapeName];
// Create an array of indices [0, 1, ..., numParticles-1]
const particleIndices = Array.from({ length: numParticles }, (_, i) => i);
shuffleArray(particleIndices); // Shuffle indices for organic transition
// Map new shape's positions to targetMorphPositions using shuffled indices
for (let i = 0; i < numParticles; i++) {
const targetParticleIndex = particleIndices[i]; // Get the shuffled index for this particle's target
targetMorphPositions[i * 3] = newShapePositions[targetParticleIndex * 3];
targetMorphPositions[i * 3 + 1] = newShapePositions[targetParticleIndex * 3 + 1];
targetMorphPositions[i * 3 + 2] = newShapePositions[targetParticleIndex * 3 + 2];
}
}
/**
* Animation loop.
*/
function animate() {
requestAnimationFrame(animate);
// Update controls
controls.update();
// Rotate the particle system
particles.rotation.y += params.rotationSpeed;
particles.rotation.x += params.rotationSpeed / 2; // Slight tilt
// Morphing logic
if (isMorphing) {
const elapsed = performance.now() - morphStartTime;
let progress = Math.min(1, elapsed / morphDuration);
for (let i = 0; i < numParticles; i++) {
const i3 = i * 3;
particles.geometry.attributes.position.array[i3] = THREE.MathUtils.lerp(
sourceMorphPositions[i3],
targetMorphPositions[i3],
progress
);
particles.geometry.attributes.position.array[i3 + 1] = THREE.MathUtils.lerp(
sourceMorphPositions[i3 + 1],
targetMorphPositions[i3 + 1],
progress
);
particles.geometry.attributes.position[i3 + 2] = THREE.MathUtils.lerp(
sourceMorphPositions[i3 + 2],
targetMorphPositions[i3 + 2],
progress
);
}
particles.geometry.attributes.position.needsUpdate = true; // Tell Three.js positions changed
if (progress >= 1) {
isMorphing = false;
}
}
// Render the scene with post-processing
composer.render();
}
/**
* Sets up the lil-gui UI.
*/
function setupGUI() {
const gui = new GUI({ container: document.getElementById('ui-container') });
gui.title('Particle System Controls');
// Particle Controls
const particleFolder = gui.addFolder('Particles');
particleFolder.add(params, 'particleSize', 0.01, 0.5).onChange(value => {
particleMaterial.size = value;
});
particleFolder.addColor(params, 'particleColor').onChange(value => {
particleMaterial.color.set(value);
});
particleFolder.add(params, 'rotationSpeed', 0, 0.01).name('Rotation Speed');
// Shape Morphing
const shapeFolder = gui.addFolder('Shape Morphing');
shapeFolder.add(params, 'targetShape', Object.keys(params.shapes)).name('Morph To').onChange(value => {
startMorph(value);
});
shapeFolder.add({ morphNow: () => startMorph(params.targetShape) }, 'morphNow').name('Morph Now');
shapeFolder.open();
// Post-processing Controls
const postProcessingFolder = gui.addFolder('Post-Processing');
postProcessingFolder.add(params, 'bloomIntensity', 0, 2).name('Bloom Intensity').onChange(value => {
bloomPass.strength = value;
});
postProcessingFolder.add(params, 'motionTrailIntensity', 0.8, 0.999).name('Motion Trails').onChange(value => {
afterimagePass.uniforms['damp'].value = value;
});
postProcessingFolder.open();
}
/**
* Handles window resizing to maintain aspect ratio and renderer size.
*/
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
composer.setSize(window.innerWidth, window.innerHeight); // Update composer size too
}
// Initialize the application
init();