Three.js 与 AI 的未来结合:探索无限可能

0 阅读11分钟

引言

Three.js 作为一款强大的 3D JavaScript 库,已经在 WebGL 领域取得了显著成就。而人工智能 (AI) 的快速发展,则为 Three.js 的应用带来了新的可能性。本文将深入探讨 Three.js 与 AI 的可结合性,探索它们在未来可能的发展方向。

1. Three.js 与 AI 的基础结合

1.1 AI 辅助场景生成

通过 AI 算法,我们可以实现 3D 场景的自动生成。例如,利用神经网络分析图像或文本数据,然后生成对应的 3D 模型和场景。以下是一个简单的示例,展示如何使用 AI 生成的参数来创建 Three.js 场景:

// 使用AI生成的参数创建Three.js场景
function createAIGeneratedScene(aiParams) {
  // 创建场景、相机和渲染器
  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
  const renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);
  // 根据AI参数创建几何体
  const geometry = new THREE.BoxGeometry(
    aiParams.boxSize.x, 
    aiParams.boxSize.y, 
    aiParams.boxSize.z
  );
  
  // 根据AI参数创建材质
  const material = new THREE.MeshStandardMaterial({
    color: new THREE.Color(aiParams.color.r, aiParams.color.g, aiParams.color.b),
    roughness: aiParams.roughness,
    metalness: aiParams.metalness
  });
  
  // 创建网格并添加到场景
  const cube = new THREE.Mesh(geometry, material);
  scene.add(cube);
  // 根据AI参数添加光源
  const light = new THREE.DirectionalLight(
    new THREE.Color(aiParams.lightColor.r, aiParams.lightColor.g, aiParams.lightColor.b),
    aiParams.lightIntensity
  );
  light.position.set(aiParams.lightPosition.x, aiParams.lightPosition.y, aiParams.lightPosition.z);
  scene.add(light);
  // 设置相机位置
  camera.position.z = 5;
  // 渲染循环
  function animate() {
    requestAnimationFrame(animate);
    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;
    renderer.render(scene, camera);
  }
  animate();
}
// 模拟AI生成的参数
const aiGeneratedParams = {
  boxSize: { x: 2, y: 2, z: 2 },
  color: { r: 0.5, g: 0.7, b: 0.9 },
  roughness: 0.3,
  metalness: 0.2,
  lightColor: { r: 1, g: 1, b: 1 },
  lightIntensity: 1.5,
  lightPosition: { x: 1, y: 2, z: 3 }
};
// 创建场景
createAIGeneratedScene(aiGeneratedParams);

1.2 AI 驱动的动画和交互

AI 可以用于创建更加智能和自然的动画效果。例如,使用机器学习算法分析人类运动数据,然后应用到 Three.js 中的角色动画上。以下是一个简单的示例,展示如何使用 AI 预测用户行为并做出相应的动画响应:

// AI驱动的交互示例
class AIController {
  constructor(mesh) {
    this.mesh = mesh;
    this.predictions = [];
    this.initAI();
  }
  // 初始化简单的AI预测模型
  initAI() {
    // 在实际应用中,这里可能会加载一个训练好的机器学习模型
    // 为了简化示例,我们使用一个简单的随机预测模型
    this.model = {
      predict: (input) => {
        // 模拟AI预测用户可能的交互
        const actions = ['rotateLeft', 'rotateRight', 'moveForward', 'moveBackward'];
        return actions[Math.floor(Math.random() * actions.length)];
      }
    };
  }
  // 处理用户输入并应用AI预测
  processInput(input) {
    const predictedAction = this.model.predict(input);
    this.applyAction(predictedAction);
    return predictedAction;
  }
  // 根据预测执行相应的动作
  applyAction(action) {
    switch (action) {
      case 'rotateLeft':
        this.mesh.rotation.y += 0.05;
        break;
      case 'rotateRight':
        this.mesh.rotation.y -= 0.05;
        break;
      case 'moveForward':
        this.mesh.position.z -= 0.1;
        break;
      case 'moveBackward':
        this.mesh.position.z += 0.1;
        break;
    }
  }
}
// 使用示例
function createAIInteractiveScene() {
  // 创建场景、相机和渲染器
  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
  const renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);
  // 创建一个简单的几何体
  const geometry = new THREE.SphereGeometry(1, 32, 32);
  const material = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
  const sphere = new THREE.Mesh(geometry, material);
  scene.add(sphere);
  // 创建AI控制器
  const aiController = new AIController(sphere);
  // 设置相机位置
  camera.position.z = 5;
  // 添加光源
  const light = new THREE.PointLight(0xffffff, 1, 100);
  light.position.set(0, 0, 5);
  scene.add(light);
  // 处理用户输入
  document.addEventListener('keydown', (event) => {
    const action = aiController.processInput(event.key);
    console.log(`用户按下 ${event.key}, AI预测动作: ${action}`);
  });
  // 渲染循环
  function animate() {
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
  }
  animate();
}
// 创建场景
createAIInteractiveScene();

2. 高级结合:实时 AI 处理与 Three.js

2.1 实时图像分析与 3D 场景交互

我们可以使用 AI 进行实时图像分析,并将分析结果应用到 Three.js 场景中。例如,通过计算机视觉算法检测用户的手势或表情,然后在 3D 场景中做出相应的反应。以下是一个使用 TensorFlow.js 进行手部检测并控制 Three.js 场景的示例:

// 实时AI图像分析与Three.js交互示例
async function createAIVideoScene() {
  // 创建场景、相机和渲染器
  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
  const renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);
  // 创建视频元素用于捕获摄像头
  const video = document.createElement('video');
  video.width = 640;
  video.height = 480;
  video.style.display = 'none';
  document.body.appendChild(video);
  // 获取摄像头流
  const stream = await navigator.mediaDevices.getUserMedia({ video: true });
  video.srcObject = stream;
  await video.play();
  // 创建视频纹理
  const videoTexture = new THREE.VideoTexture(video);
  
  // 创建平面几何体并应用视频纹理
  const geometry = new THREE.PlaneGeometry(4, 3);
  const material = new THREE.MeshBasicMaterial({ map: videoTexture });
  const videoPlane = new THREE.Mesh(geometry, material);
  scene.add(videoPlane);
  // 创建一些可交互的3D对象
  const cubeGeometry = new THREE.BoxGeometry(0.5, 0.5, 0.5);
  const cubeMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000 });
  const cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
  cube.position.set(0, 0, -1);
  scene.add(cube);
  // 添加光源
  const light = new THREE.DirectionalLight(0xffffff, 1);
  light.position.set(1, 1, 1);
  scene.add(light);
  // 设置相机位置
  camera.position.z = 5;
  // 加载手部检测模型
  const handpose = await window.handPoseDetection.createDetector(
    window.handPoseDetection.SupportedModels.MediaPipeHands,
    {
      runtime: 'mediapipe',
      modelType: 'full',
      maxHands: 1
    }
  );
  // 渲染循环
  async function animate() {
    requestAnimationFrame(animate);
    
    // 检测手部
    const hands = await handpose.estimateHands(video);
    
    if (hands.length > 0) {
      // 获取手部关键点
      const keypoints = hands[0].keypoints;
      
      // 计算手掌中心位置
      const palm = keypoints[0];
      
      // 将2D手掌位置映射到3D场景中
      const x = (palm.x / video.width) * 4 - 2;
      const y = -(palm.y / video.height) * 3 + 1.5;
      
      // 更新立方体位置
      cube.position.set(x, y, -1);
    }
    
    renderer.render(scene, camera);
  }
  animate();
}
// 检查是否已加载TensorFlow.js和手部检测模型
function checkAndLoadDependencies() {
  if (!window.handPoseDetection) {
    const script = document.createElement('script');
    script.src = 'https://cdn.jsdelivr.net/npm/@tensorflow-models/hand-pose-detection@2.0.0/dist/index.min.js';
    script.onload = createAIVideoScene;
    document.body.appendChild(script);
  } else {
    createAIVideoScene();
  }
}
// 启动应用
checkAndLoadDependencies();

2.2 AI 驱动的物理模拟

AI 可以用于优化和控制 Three.js 中的物理模拟。例如,使用强化学习训练一个 AI 模型,使其能够控制 3D 场景中的物理对象,实现更加自然和智能的物理交互。以下是一个简单的示例,展示如何使用 AI 控制物理模拟:

// AI驱动的物理模拟示例
async function createAIPhysicsScene() {
  // 创建场景、相机和渲染器
  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
  const renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);
  // 创建物理引擎
  const physicsWorld = new CANNON.World();
  physicsWorld.gravity.set(0, -9.82, 0); // 设置重力
  // 创建地面
  const groundGeometry = new THREE.PlaneGeometry(10, 10);
  const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x808080 });
  const groundMesh = new THREE.Mesh(groundGeometry, groundMaterial);
  groundMesh.rotation.x = -Math.PI / 2;
  scene.add(groundMesh);
  
  // 创建地面物理体
  const groundShape = new CANNON.Plane();
  const groundBody = new CANNON.Body({ mass: 0 });
  groundBody.addShape(groundShape);
  groundBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2);
  physicsWorld.addBody(groundBody);
  // 创建可控制的球体
  const sphereGeometry = new THREE.SphereGeometry(0.5, 32, 32);
  const sphereMaterial = new THREE.MeshStandardMaterial({ color: 0x0000ff });
  const sphereMesh = new THREE.Mesh(sphereGeometry, sphereMaterial);
  sphereMesh.position.set(0, 5, 0);
  scene.add(sphereMesh);
  
  // 创建球体物理体
  const sphereShape = new CANNON.Sphere(0.5);
  const sphereBody = new CANNON.Body({
    mass: 5,
    position: new CANNON.Vec3(0, 5, 0)
  });
  sphereBody.addShape(sphereShape);
  physicsWorld.addBody(sphereBody);
  // 添加光源
  const light = new THREE.DirectionalLight(0xffffff, 1);
  light.position.set(1, 2, 3);
  scene.add(light);
  // 设置相机位置
  camera.position.set(0, 5, 10);
  camera.lookAt(0, 0, 0);
  // 创建简单的AI控制器
  class PhysicsAIController {
    constructor(body) {
      this.body = body;
      this.targetPosition = new CANNON.Vec3(0, 5, 0);
      this.learningRate = 0.1;
      this.lastError = new CANNON.Vec3();
    }
    // 更新AI控制
    update(deltaTime) {
      // 计算当前位置与目标位置的误差
      const error = new CANNON.Vec3();
      error.copy(this.targetPosition);
      error.vsub(this.body.position);
      
      // 根据误差调整力的大小
      const force = new CANNON.Vec3();
      force.copy(error);
      force.scale(this.learningRate * this.body.mass, force);
      
      // 添加一些随机性,模拟学习过程中的探索
      force.x += (Math.random() - 0.5) * 0.5;
      force.z += (Math.random() - 0.5) * 0.5;
      
      // 应用力
      this.body.applyForce(force, this.body.position);
      
      // 记录上一次的误差
      this.lastError.copy(error);
    }
    // 设置新的目标位置
    setTarget(x, y, z) {
      this.targetPosition.set(x, y, z);
    }
  }
  // 创建AI控制器
  const aiController = new PhysicsAIController(sphereBody);
  // 设置随机目标位置
  function setRandomTarget() {
    const x = (Math.random() - 0.5) * 8;
    const z = (Math.random() - 0.5) * 8;
    aiController.setTarget(x, 5, z);
    setTimeout(setRandomTarget, 3000);
  }
  setRandomTarget();
  // 渲染循环
  let lastTime = 0;
  function animate(time) {
    requestAnimationFrame(animate);
    
    const deltaTime = (time - lastTime) / 1000;
    lastTime = time;
    
    // 更新AI控制
    aiController.update(deltaTime);
    
    // 更新物理世界
    physicsWorld.step(1/60, deltaTime, 3);
    
    // 更新Three.js网格位置和旋转
    sphereMesh.position.copy(sphereBody.position);
    sphereMesh.quaternion.copy(sphereBody.quaternion);
    
    renderer.render(scene, camera);
  }
  animate(0);
}
// 检查是否已加载CANNON.js物理引擎
function checkAndLoadPhysicsEngine() {
  if (!window.CANNON) {
    const script = document.createElement('script');
    script.src = 'https://cdn.jsdelivr.net/npm/cannon-es@0.20.0/dist/cannon-es.min.js';
    script.onload = createAIPhysicsScene;
    document.body.appendChild(script);
  } else {
    createAIPhysicsScene();
  }
}
// 启动应用
checkAndLoadPhysicsEngine();

3. 实际应用案例

3.1 智能 3D 游戏开发

结合 Three.js 和 AI 可以开发出更加智能的游戏。例如,使用 AI 生成游戏关卡、控制非玩家角色 (NPC) 的行为,或者根据玩家的游戏习惯自动调整游戏难度。以下是一个简单的游戏示例,展示了 AI 控制的敌人行为:

// 智能游戏示例:AI控制的敌人
class Enemy {
  constructor(scene, position) {
    this.scene = scene;
    this.position = position;
    this.health = 100;
    this.speed = 0.02;
    this.detectionRange = 5;
    this.attackRange = 1;
    this.state = 'idle';
    this.target = null;
    
    // 创建敌人模型
    this.createModel();
    
    // 创建简单的AI行为树
    this.behaviorTree = this.createBehaviorTree();
  }
  // 创建敌人3D模型
  createModel() {
    const geometry = new THREE.ConeGeometry(0.5, 1, 32);
    const material = new THREE.MeshStandardMaterial({ color: 0xff0000 });
    this.mesh = new THREE.Mesh(geometry, material);
    this.mesh.position.copy(this.position);
    this.mesh.rotation.x = Math.PI / 2; // 使圆锥朝上
    this.scene.add(this.mesh);
  }
  // 创建行为树
  createBehaviorTree() {
    return {
      update: (playerPosition) => {
        // 检测玩家
        const distanceToPlayer = this.position.distanceTo(playerPosition);
        
        if (distanceToPlayer < this.detectionRange) {
          this.target = playerPosition;
          
          if (distanceToPlayer < this.attackRange) {
            this.state = 'attacking';
            this.attack();
          } else {
            this.state = 'chasing';
            this.chase();
          }
        } else {
          this.state = 'idle';
          this.idle();
        }
      }
    };
  }
  // 空闲状态行为
  idle() {
    // 随机移动
    if (Math.random() < 0.01) {
      this.randomDirection = new THREE.Vector3(
        (Math.random() - 0.5) * 2,
        0,
        (Math.random() - 0.5) * 2
      ).normalize();
    }
    
    this.position.add(this.randomDirection.clone().multiplyScalar(this.speed * 0.3));
    this.mesh.position.copy(this.position);
  }
  // 追逐状态行为
  chase() {
    if (!this.target) return;
    
    // 计算朝向目标的方向
    const direction = new THREE.Vector3();
    direction.subVectors(this.target, this.position).normalize();
    
    // 移动向目标
    this.position.add(direction.multiplyScalar(this.speed));
    this.mesh.position.copy(this.position);
    
    // 转向目标
    const angle = Math.atan2(direction.x, direction.z);
    this.mesh.rotation.y = angle;
  }
  // 攻击状态行为
  attack() {
    // 简单的攻击动画
    this.mesh.scale.y = 0.8 + Math.sin(Date.now() * 0.01) * 0.2;
    this.mesh.updateMatrix();
    
    // 这里可以添加实际的攻击逻辑
    if (Math.random() < 0.05) {
      console.log("Enemy attacks player!");
      // 实际应用中这里会减少玩家生命值
    }
  }
  // 更新敌人状态
  update(playerPosition) {
    this.behaviorTree.update(playerPosition);
  }
}
// 游戏主类
class AIGame {
  constructor() {
    this.initThreeJS();
    this.initGame();
    this.animate();
  }
  // 初始化Three.js
  initThreeJS() {
    // 创建场景、相机和渲染器
    this.scene = new THREE.Scene();
    this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    this.renderer = new THREE.WebGLRenderer();
    this.renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(this.renderer.domElement);
    
    // 添加光源
    const ambientLight = new THREE.AmbientLight(0x404040);
    this.scene.add(ambientLight);
    
    const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
    directionalLight.position.set(1, 1, 1);
    this.scene.add(directionalLight);
    
    // 设置相机位置
    this.camera.position.z = 5;
  }
  // 初始化游戏
  initGame() {
    // 创建地面
    const groundGeometry = new THREE.PlaneGeometry(20, 20);
    const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x808080 });
    this.ground = new THREE.Mesh(groundGeometry, groundMaterial);
    this.ground.rotation.x = -Math.PI / 2;
    this.scene.add(this.ground);
    
    // 创建玩家
    const playerGeometry = new THREE.SphereGeometry(0.5, 32, 32);
    const playerMaterial = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
    this.player = new THREE.Mesh(playerGeometry, playerMaterial);
    this.player.position.y = 0.5;
    this.scene.add(this.player);
    
    // 玩家控制
    this.playerPosition = new THREE.Vector3(0, 0.5, 0);
    this.keys = {
      w: false,
      a: false,
      s: false,
      d: false
    };
    
    // 监听键盘事件
    window.addEventListener('keydown', (e) => this.onKeyDown(e));
    window.addEventListener('keyup', (e) => this.onKeyUp(e));
    
    // 创建敌人
    this.enemies = [];
    for (let i = 0; i < 5; i++) {
      const position = new THREE.Vector3(
        (Math.random() - 0.5) * 15,
        0.5,
        (Math.random() - 0.5) * 15
      );
      const enemy = new Enemy(this.scene, position);
      this.enemies.push(enemy);
    }
  }
  // 键盘事件处理
  onKeyDown(event) {
    switch (event.key.toLowerCase()) {
      case 'w': this.keys.w = true; break;
      case 'a': this.keys.a = true; break;
      case 's': this.keys.s = true; break;
      case 'd': this.keys.d = true; break;
    }
  }
  onKeyUp(event) {
    switch (event.key.toLowerCase()) {
      case 'w': this.keys.w = false; break;
      case 'a': this.keys.a = false; break;
      case 's': this.keys.s = false; break;
      case 'd': this.keys.d = false; break;
    }
  }
  // 更新玩家位置
  updatePlayer() {
    const speed = 0.1;
    const direction = new THREE.Vector3();
    
    if (this.keys.w) direction.z -= speed;
    if (this.keys.s) direction.z += speed;
    if (this.keys.a) direction.x -= speed;
    if (this.keys.d) direction.x += speed;
    
    // 限制玩家在地面范围内
    this.playerPosition.add(direction);
    this.playerPosition.x = Math.max(-9.5, Math.min(9.5, this.playerPosition.x));
    this.playerPosition.z = Math.max(-9.5, Math.min(9.5, this.playerPosition.z));
    
    // 更新玩家网格位置
    this.player.position.copy(this.playerPosition);
    
    // 更新相机跟随
    this.camera.position.x = this.playerPosition.x;
    this.camera.position.z = this.playerPosition.z + 5;
    this.camera.lookAt(this.playerPosition);
  }
  // 更新敌人
  updateEnemies() {
    this.enemies.forEach(enemy => {
      enemy.update(this.playerPosition);
    });
  }
  // 动画循环
  animate() {
    requestAnimationFrame(() => this.animate());
    
    this.updatePlayer();
    this.updateEnemies();
    
    this.renderer.render(this.scene, this.camera);
  }
}
// 启动游戏
window.addEventListener('load', () => {
  new AIGame();
});

3.2 智能数据可视化

结合 Three.js 和 AI 可以创建更加智能的数据可视化。例如,使用机器学习算法分析大量数据,然后自动生成最佳的 3D 可视化方式。以下是一个示例,展示了如何使用 AI 对数据进行聚类并在 Three.js 中进行可视化:

// 智能数据可视化示例
async function createAIDataVisualization() {
  // 创建场景、相机和渲染器
  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
  const renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);
  // 添加光源
  const ambientLight = new THREE.AmbientLight(0x404040);
  scene.add(ambientLight);
  
  const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
  directionalLight.position.set(1, 1, 1);
  scene.add(directionalLight);
  // 设置相机位置
  camera.position.z = 10;
  // 生成随机数据点
  const dataPoints = generateRandomData(100);
  
  // 使用K-means算法对数据进行聚类
  const clusters = await kmeansClustering(dataPoints, 3);
  
  // 创建数据可视化
  createDataVisualization(scene, clusters);
  // 添加轨道控制器
  const controls = new THREE.OrbitControls(camera, renderer.domElement);
  controls.enableDamping = true;
  // 渲染循环
  function animate() {
    requestAnimationFrame(animate);
    controls.update();
    renderer.render(scene, camera);
  }
  animate();
}
// 生成随机数据点
function generateRandomData(count) {
  const data = [];
  for (let i = 0; i < count; i++) {
    // 生成三组不同分布的数据点,模拟三个不同的聚类
    const group = Math.floor(Math.random() * 3);
    let x, y, z;
    
    if (group === 0) {
      x = 3 + Math.random() * 2;
      y = 3 + Math.random() * 2;
      z = 3 + Math.random() * 2;
    } else if (group === 1) {
      x = -3 + Math.random() * 2;
      y = 3 + Math.random() * 2;
      z = -3 + Math.random() * 2;
    } else {
      x = 0 + Math.random() * 2;
      y = -3 + Math.random() * 2;
      z = 0 + Math.random() * 2;
    }
    
    data.push({
      position: { x, y, z },
      group
    });
  }
  return data;
}
// 简单的K-means聚类算法实现
async function kmeansClustering(data, k) {
  // 初始化中心点
  const centroids = [];
  for (let i = 0; i < k; i++) {
    const randomIndex = Math.floor(Math.random() * data.length);
    centroids.push({
      position: { ...data[randomIndex].position },
      points: []
    });
  }
  // K-means迭代
  let changed = true;
  let iterations = 0;
  
  while (changed && iterations < 20) {
    // 清空每个中心点的点集
    centroids.forEach(centroid => {
      centroid.points = [];
    });
    
    // 将每个点分配给最近的中心点
    data.forEach(point => {
      let minDistance = Infinity;
      let closestCentroidIndex = 0;
      
      centroids.forEach((centroid, index) => {
        const distance = Math.sqrt(
          Math.pow(point.position.x - centroid.position.x, 2) +
          Math.pow(point.position.y - centroid.position.y, 2) +
          Math.pow(point.position.z - centroid.position.z, 2)
        );
        
        if (distance < minDistance) {
          minDistance = distance;
          closestCentroidIndex = index;
        }
      });
      
      centroids[closestCentroidIndex].points.push(point);
    });
    
    // 更新中心点位置
    changed = false;
    centroids.forEach(centroid => {
      if (centroid.points.length === 0) return;
      
      const sumX = centroid.points.reduce((sum, point) => sum + point.position.x, 0);
      const sumY = centroid.points.reduce((sum, point) => sum + point.position.y, 0);
      const sumZ = centroid.points.reduce((sum, point) => sum + point.position.z, 0);
      
      const newX = sumX / centroid.points.length;
      const newY = sumY / centroid.points.length;
      const newZ = sumZ / centroid.points.length;
      
      if (newX !== centroid.position.x || newY !== centroid.position.y || newZ !== centroid.position.z) {
        centroid.position.x = newX;
        centroid.position.y = newY;
        centroid.position.z = newZ;
        changed = true;
      }
    });
    
    iterations++;
    await new Promise(resolve => setTimeout(resolve, 100)); // 为了演示,添加延迟
  }
  
  return centroids;
}
// 创建数据可视化
function createDataVisualization(scene, clusters) {
  // 定义聚类颜色
  const colors = [0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0xff00ff, 0x00ffff];
  
  // 为每个聚类创建点
  clusters.forEach((cluster, index) => {
    const color = new THREE.Color(colors[index % colors.length]);
    
    // 创建点材质
    const material = new THREE.PointsMaterial({
      color: color,
      size: 0.1,
      transparent: true,
      opacity: 0.8
    });
    
    // 创建几何体
    const geometry = new THREE.BufferGeometry();
    const positions = new Float32Array(cluster.points.length * 3);
    
    cluster.points.forEach((point, i) => {
      positions[i * 3] = point.position.x;
      positions[i * 3 + 1] = point.position.y;
      positions[i * 3 + 2] = point.position.z;
    });
    
    geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
    
    // 创建点云
    const points = new THREE.Points(geometry, material);
    scene.add(points);
    
    // 创建中心点
    const centerGeometry = new THREE.SphereGeometry(0.2, 32, 32);
    const centerMaterial = new THREE.MeshStandardMaterial({ color: color });
    const centerSphere = new THREE.Mesh(centerGeometry, centerMaterial);
    centerSphere.position.set(cluster.position.x, cluster.position.y, cluster.position.z);
    scene.add(centerSphere);
  });
}
// 检查是否已加载Three.js轨道控制器
function checkAndLoadOrbitControls() {
  if (!THREE.OrbitControls) {
    const script = document.createElement('script');
    script.src = 'https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/controls/OrbitControls.js';
    script.onload = createAIDataVisualization;
    document.body.appendChild(script);
  } else {
    createAIDataVisualization();
  }
}
// 启动应用
window.addEventListener('load', checkAndLoadOrbitControls);

4. 未来发展趋势

4.1 基于 AI 的实时场景优化

未来,AI 可以用于实时分析和优化 Three.js 场景。例如,根据用户设备性能自动调整场景复杂度,或者根据用户的观看习惯优化渲染效果。

4.2 生成式 AI 与程序化内容创作

生成式 AI 技术的发展将使得 Three.js 场景的创建更加自动化。通过 AI 算法,可以根据简单的文本描述生成复杂的 3D 场景和模型,大大提高开发效率。

4.3 实时深度学习推理与交互

随着 WebAssembly 和 WebGL 的不断发展,未来可能在浏览器中实现更复杂的深度学习模型推理。这将使得 Three.js 应用能够实时分析用户行为和环境数据,并做出智能响应。

4.4 AI 驱动的用户体验个性化

通过分析用户的交互数据,AI 可以为每个用户提供个性化的 Three.js 体验。例如,根据用户的兴趣和行为习惯,自动调整场景内容、动画效果和交互方式。

结论

Three.js 与 AI 的结合为 WebGL 应用开发带来了巨大的潜力。从基础的场景生成到高级的实时 AI 处理,这两者的结合正在推动 Web3D 技术向新的高度发展。随着 AI 技术的不断进步,我们可以期待更多创新的应用场景和交互方式的出现。无论是游戏开发、数据可视化还是虚拟 / 增强现实,Three.js 与 AI 的结合都将为这些领域带来新的突破和可能性。