.santa_tree:基于 React 和 Three.js 的 3D 圣诞树可视化项目

用户可用于创建动态 3D 圣诞树场景,支持针叶粒子与装饰物渲染。项目通过 React Three Fiber 实现高效渲染,含Shader视觉效果、动画过渡及环境光效,可交互控制树形态变化。【此简介由AI生成】

Branch1Tags0
FilesLast commitLast update
10 months ago

import React, { useMemo, useRef, useState, useEffect } from 'react'; import { Canvas, useFrame, extend } from '@react-three/fiber'; import * as THREE from 'three'; import { Environment, OrbitControls, ContactShadows, Float } from '@react-three/drei'; import { EffectComposer, Bloom, Vignette } from '@react-three/postprocessing';

// --- 配置参数 --- const CONFIG = { leafCount: 12000, // 针叶粒子数量 ornamentCount: 150, // 装饰物数量 treeHeight: 14, treeRadius: 5, scatterRadius: 25, colors: { leaf: new THREE.Color('#002b16'), // 祖母绿 gold: new THREE.Color('#FFD700'), // 金色 highlight: new THREE.Color('#fffdd0') // 奶油白高光 } };

// --- 1. Shader 定义 (针叶的视觉灵魂) --- const FoliageShaderMaterial = { uniforms: { uTime: { value: 0 }, uProgress: { value: 0 }, uColorLeaf: { value: CONFIG.colors.leaf }, uColorGold: { value: CONFIG.colors.gold } }, vertexShader: ` uniform float uTime; uniform float uProgress; attribute vec3 aScatterPos; attribute vec3 aTreePos; attribute float aRandom; varying float vAlpha; varying float vRandom;

// 缓动函数
float easeInOutCubic(float x) {
  return x < 0.5 ? 4.0 * x * x * x : 1.0 - pow(-2.0 * x + 2.0, 3.0) / 2.0;
}

void main() {
  float t = easeInOutCubic(uProgress);
  vRandom = aRandom;

  // 位置插值
  vec3 pos = mix(aScatterPos, aTreePos, t);

  // 动态呼吸/漂浮
  float drift = mix(2.0, 0.2, t); 
  float speed = mix(0.3, 1.0, t);
  
  pos.x += sin(uTime * speed + aRandom * 10.0) * drift * 0.3;
  pos.y += cos(uTime * speed * 0.8 + aRandom * 20.0) * drift * 0.3;
  pos.z += sin(uTime * speed * 0.5 + aRandom * 30.0) * drift * 0.3;

  // 散落时的旋转混沌感
  if (t < 0.8) {
     pos.x += sin(uTime * 0.2 + aRandom * 100.0) * 2.0 * (1.0 - t);
  }

  vec4 mvPosition = modelViewMatrix * vec4(pos, 1.0);
  gl_Position = projectionMatrix * mvPosition;
  
  // 粒子大小随距离衰减
  gl_PointSize = (60.0 * aRandom + 30.0) * (1.0 / -mvPosition.z);
  vAlpha = 0.6 + 0.4 * sin(uTime * 2.0 + aRandom * 10.0);
}

, fragmentShader: uniform vec3 uColorLeaf; uniform vec3 uColorGold; varying float vAlpha; varying float vRandom;

void main() {
  vec2 center = gl_PointCoord - 0.5;
  float dist = length(center);
  if (dist > 0.5) discard;

  // 颜色混合逻辑
  float edge = smoothstep(0.3, 0.5, dist);
  vec3 finalColor = mix(uColorLeaf, uColorGold * 2.0, edge * 0.6);
  
  // 随机亮星
  if (vRandom > 0.9) {
    finalColor = mix(finalColor, vec3(1.0), 0.8);
  }

  gl_FragColor = vec4(finalColor, vAlpha * (1.0 - dist));
}

` };

// --- 2. 针叶层组件 --- const FoliageLayer = ({ progress }) => { const shaderRef = useRef();

const { positions, scatterPos, treePos, randoms } = useMemo(() => { const count = CONFIG.leafCount; const p = new Float32Array(count * 3); const s = new Float32Array(count * 3); const t = new Float32Array(count * 3); const r = new Float32Array(count);

for(let i=0; i<count; i++) {
  // Tree Shape (Spiral)
  const ratio = i / count;
  const angle = i * 2.4; // Golden angle approx
  const y = -CONFIG.treeHeight/2 + ratio * CONFIG.treeHeight;
  const rad = (1 - ratio) * CONFIG.treeRadius;
  
  // Add randomness to tree shape
  const rx = (Math.random() - 0.5) * 1.5;
  const ry = (Math.random() - 0.5) * 1.5;
  const rz = (Math.random() - 0.5) * 1.5;

  t[i*3] = Math.cos(angle) * rad + rx;
  t[i*3+1] = y + ry;
  t[i*3+2] = Math.sin(angle) * rad + rz;

  // Scatter Shape (Sphere)
  const u = Math.random();
  const v = Math.random();
  const theta = 2 * Math.PI * u;
  const phi = Math.acos(2 * v - 1);
  const radius = CONFIG.scatterRadius * Math.cbrt(Math.random());

  s[i*3] = radius * Math.sin(phi) * Math.cos(theta);
  s[i*3+1] = radius * Math.sin(phi) * Math.sin(theta);
  s[i*3+2] = radius * Math.cos(phi);

  r[i] = Math.random();
  p[i*3] = 0; // Initial pos handled by shader
}
return { positions: p, scatterPos: s, treePos: t, randoms: r };

}, []);

useFrame((state) => { if (shaderRef.current) { shaderRef.current.uniforms.uTime.value = state.clock.elapsedTime; shaderRef.current.uniforms.uProgress.value = progress; } });

return ( ); };

// --- 3. 装饰层组件 --- const OrnamentLayer = ({ progress }) => { const meshRef = useRef(); const dummy = new THREE.Object3D();

const data = useMemo(() => { return new Array(CONFIG.ornamentCount).fill(0).map((_, i) => { const ratio = Math.random(); const y = -CONFIG.treeHeight/2 + ratio * CONFIG.treeHeight; const r = (1 - ratio) * CONFIG.treeRadius + 0.5; // Slightly outside leaves const angle = Math.random() * Math.PI * 2;

  const treeP = new THREE.Vector3(Math.cos(angle)*r, y, Math.sin(angle)*r);
  
  const scatterP = new THREE.Vector3(
    (Math.random()-0.5)*50, 
    (Math.random()-0.5)*50, 
    (Math.random()-0.5)*50
  );
  
  return { treeP, scatterP, scale: 0.5 + Math.random() * 0.5, speed: Math.random() };
});

}, []);

useFrame((state) => { if(!meshRef.current) return;

// Lerp progress for smooth animation
const t = progress; 

data.forEach((d, i) => {
  const pos = new THREE.Vector3().lerpVectors(d.scatterP, d.treeP, t);
  
  // Floating effect
  pos.y += Math.sin(state.clock.elapsedTime * d.speed + i) * 0.2;
  
  dummy.position.copy(pos);
  dummy.scale.setScalar(d.scale * (0.5 + 0.5 * t));
  dummy.rotation.set(
    state.clock.elapsedTime * 0.5, 
    state.clock.elapsedTime * 0.5, 
    0
  );
  dummy.updateMatrix();
  meshRef.current.setMatrixAt(i, dummy.matrix);
});
meshRef.current.instanceMatrix.needsUpdate = true;

});

return ( <instancedMesh ref={meshRef} args={[undefined, undefined, CONFIG.ornamentCount]} castShadow> <sphereGeometry args={[0.3, 16, 16]} /> ); };

// --- 4. 主应用程序 --- export default function App() { const [state, setState] = useState('SCATTERED'); const [progress, setProgress] = useState(0);

// Animation Loop for Smooth Transition useEffect(() => { let frameId; const loop = () => { const target = state === 'TREE_SHAPE' ? 1 : 0; setProgress(prev => { const diff = target - prev; if (Math.abs(diff) < 0.001) return target; return prev + diff * 0.04; // Adjust speed here }); frameId = requestAnimationFrame(loop); }; loop(); return () => cancelAnimationFrame(frameId); }, [state]);

return ( <div style={{ width: '100vw', height: '100vh', background: '#000804' }}> <Canvas shadows camera={{ position: [0, 0, 30], fov: 45 }} dpr={[1, 2]}> {/* Lights & Env */} <spotLight position={[10, 20, 10]} angle={0.3} penumbra={1} intensity={150} castShadow color="#FFD700" />

    {/* Content */}
    <group position={[0, -2, 0]}>
      <Float speed={2} rotationIntensity={0.2} floatIntensity={0.5}>
        <FoliageLayer progress={progress} />
        <OrnamentLayer progress={progress} />
      </Float>
    </group>

    <ContactShadows opacity={0.5} scale={40} blur={2.5} far={10} color="#000" />
    <OrbitControls enablePan={false} autoRotate autoRotateSpeed={0.5} maxPolarAngle={Math.PI/1.6} />

    {/* Post Processing */}
    <EffectComposer disableNormalPass>
      <Bloom luminanceThreshold={0.8} mipmapBlur intensity={1.5} radius={0.5} />
      <Vignette eskil={false} offset={0.1} darkness={0.6} />
    </EffectComposer>
  </Canvas>

  {/* UI Interface */}
  <div style={{
    position: 'absolute', bottom: 50, left: '50%', transform: 'translateX(-50%)',
    textAlign: 'center', zIndex: 10, fontFamily: 'serif'
  }}>
    <h1 style={{ color: '#FFD700', fontSize: '0.8rem', letterSpacing: '0.3em', marginBottom: 20, textTransform: 'uppercase' }}>
      Arix Signature Collection
    </h1>
    <button
      onClick={() => setState(s => s === 'SCATTERED' ? 'TREE_SHAPE' : 'SCATTERED')}
      style={{
        background: 'rgba(0,0,0,0.3)', border: '1px solid #FFD700', color: '#FFD700',
        padding: '12px 30px', cursor: 'pointer', fontSize: '12px', letterSpacing: '2px',
        textTransform: 'uppercase', transition: 'all 0.3s'
      }}
      onMouseEnter={e => e.currentTarget.style.background = '#FFD70022'}
      onMouseLeave={e => e.currentTarget.style.background = 'rgba(0,0,0,0.3)'}
    >
      {state === 'SCATTERED' ? 'Assemble Form' : 'Release Chaos'}
    </button>
  </div>
</div>

); }

Introduction

用户可用于创建动态 3D 圣诞树场景,支持针叶粒子与装饰物渲染。项目通过 React Three Fiber 实现高效渲染,含Shader视觉效果、动画过渡及环境光效,可交互控制树形态变化。【此简介由AI生成】

Customize your domain