Skip to content

physics_ammo_terrain

对应 three.js 示例地址

仅需关注 init 函数的内容,其他部分都是示例小程序所使用的描述配置。

js
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import AmmoLib from "three/examples/jsm/libs/ammo.wasm.js";

/** @type {import("@minisheeep/mp-three-examples").OfficialExampleInfo} */
const exampleInfo = {
  name: "physics_ammo_terrain",
  useLoaders: [],
  info: [
    [
      {
        tag: "text",
        content: "Ammo.js physics terrain heightfield demo"
      }
    ]
  ],
  init: ({ window, canvas, GUI, Stats, needToDispose, useFrame }) => {
    const terrainWidthExtents = 100;
    const terrainDepthExtents = 100;
    const terrainWidth = 128;
    const terrainDepth = 128;
    const terrainHalfWidth = terrainWidth / 2;
    const terrainHalfDepth = terrainDepth / 2;
    const terrainMaxHeight = 8;
    const terrainMinHeight = -2;
    let stats;
    let camera, scene, renderer;
    let terrainMesh;
    const clock = new THREE.Clock();
    let collisionConfiguration;
    let dispatcher;
    let broadphase;
    let solver;
    let physicsWorld;
    const dynamicObjects = [];
    let transformAux1;
    let heightData = null;
    let ammoHeightData = null;
    let time = 0;
    const objectTimePeriod = 3;
    let timeNextSpawn = time + objectTimePeriod;
    const maxNumObjects = 30;
    let Ammo;
    AmmoLib.call({}).then(function(lib) {
      Ammo = lib;
      init();
    });
    function init() {
      heightData = generateHeight(terrainWidth, terrainDepth, terrainMinHeight, terrainMaxHeight);
      initGraphics();
      initPhysics();
    }
    function initGraphics() {
      renderer = new THREE.WebGLRenderer({ antialias: true, canvas });
      renderer.setPixelRatio(window.devicePixelRatio);
      renderer.setSize(window.innerWidth, window.innerHeight);
      renderer.setAnimationLoop(animate);
      renderer.shadowMap.enabled = true;
      stats = new Stats(renderer);
      camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.2, 2e3);
      scene = new THREE.Scene();
      scene.background = new THREE.Color(12571109);
      camera.position.y = heightData[terrainHalfWidth + terrainHalfDepth * terrainWidth] * (terrainMaxHeight - terrainMinHeight) + 5;
      camera.position.z = terrainDepthExtents / 2;
      camera.lookAt(0, 0, 0);
      const controls = new OrbitControls(camera, renderer.domElement);
      controls.enableZoom = false;
      const geometry = new THREE.PlaneGeometry(
        terrainWidthExtents,
        terrainDepthExtents,
        terrainWidth - 1,
        terrainDepth - 1
      );
      geometry.rotateX(-Math.PI / 2);
      const vertices = geometry.attributes.position.array;
      for (let i = 0, j = 0, l = vertices.length; i < l; i++, j += 3) {
        vertices[j + 1] = heightData[i];
      }
      geometry.computeVertexNormals();
      const groundMaterial = new THREE.MeshPhongMaterial({ color: 13092807 });
      terrainMesh = new THREE.Mesh(geometry, groundMaterial);
      terrainMesh.receiveShadow = true;
      terrainMesh.castShadow = true;
      scene.add(terrainMesh);
      const textureLoader = new THREE.TextureLoader();
      textureLoader.load("textures/grid.png", function(texture) {
        texture.wrapS = THREE.RepeatWrapping;
        texture.wrapT = THREE.RepeatWrapping;
        texture.repeat.set(terrainWidth - 1, terrainDepth - 1);
        groundMaterial.map = texture;
        groundMaterial.needsUpdate = true;
      });
      const ambientLight = new THREE.AmbientLight(12303291);
      scene.add(ambientLight);
      const light = new THREE.DirectionalLight(16777215, 3);
      light.position.set(100, 100, 50);
      light.castShadow = true;
      const dLight = 200;
      const sLight = dLight * 0.25;
      light.shadow.camera.left = -50;
      light.shadow.camera.right = sLight;
      light.shadow.camera.top = sLight;
      light.shadow.camera.bottom = -50;
      light.shadow.camera.near = dLight / 30;
      light.shadow.camera.far = dLight;
      light.shadow.mapSize.x = 1024 * 2;
      light.shadow.mapSize.y = 1024 * 2;
      scene.add(light);
      window.addEventListener("resize", onWindowResize);
      needToDispose(renderer, scene, controls);
    }
    function onWindowResize() {
      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(window.innerWidth, window.innerHeight);
    }
    function initPhysics() {
      collisionConfiguration = new Ammo.btDefaultCollisionConfiguration();
      dispatcher = new Ammo.btCollisionDispatcher(collisionConfiguration);
      broadphase = new Ammo.btDbvtBroadphase();
      solver = new Ammo.btSequentialImpulseConstraintSolver();
      physicsWorld = new Ammo.btDiscreteDynamicsWorld(
        dispatcher,
        broadphase,
        solver,
        collisionConfiguration
      );
      physicsWorld.setGravity(new Ammo.btVector3(0, -6, 0));
      const groundShape = createTerrainShape();
      const groundTransform = new Ammo.btTransform();
      groundTransform.setIdentity();
      groundTransform.setOrigin(
        new Ammo.btVector3(0, (terrainMaxHeight + terrainMinHeight) / 2, 0)
      );
      const groundMass = 0;
      const groundLocalInertia = new Ammo.btVector3(0, 0, 0);
      const groundMotionState = new Ammo.btDefaultMotionState(groundTransform);
      const groundBody = new Ammo.btRigidBody(
        new Ammo.btRigidBodyConstructionInfo(
          groundMass,
          groundMotionState,
          groundShape,
          groundLocalInertia
        )
      );
      physicsWorld.addRigidBody(groundBody);
      transformAux1 = new Ammo.btTransform();
    }
    function generateHeight(width, depth, minHeight, maxHeight) {
      const size = width * depth;
      const data = new Float32Array(size);
      const hRange = maxHeight - minHeight;
      const w2 = width / 2;
      const d2 = depth / 2;
      const phaseMult = 12;
      let p = 0;
      for (let j = 0; j < depth; j++) {
        for (let i = 0; i < width; i++) {
          const radius = Math.sqrt(Math.pow((i - w2) / w2, 2) + Math.pow((j - d2) / d2, 2));
          const height = (Math.sin(radius * phaseMult) + 1) * 0.5 * hRange + minHeight;
          data[p] = height;
          p++;
        }
      }
      return data;
    }
    function createTerrainShape() {
      const heightScale = 1;
      const upAxis = 1;
      const hdt = "PHY_FLOAT";
      const flipQuadEdges = false;
      ammoHeightData = Ammo._malloc(4 * terrainWidth * terrainDepth);
      let p = 0;
      let p2 = 0;
      for (let j = 0; j < terrainDepth; j++) {
        for (let i = 0; i < terrainWidth; i++) {
          Ammo.HEAPF32[ammoHeightData + p2 >> 2] = heightData[p];
          p++;
          p2 += 4;
        }
      }
      const heightFieldShape = new Ammo.btHeightfieldTerrainShape(
        terrainWidth,
        terrainDepth,
        ammoHeightData,
        heightScale,
        terrainMinHeight,
        terrainMaxHeight,
        upAxis,
        hdt,
        flipQuadEdges
      );
      const scaleX = terrainWidthExtents / (terrainWidth - 1);
      const scaleZ = terrainDepthExtents / (terrainDepth - 1);
      heightFieldShape.setLocalScaling(new Ammo.btVector3(scaleX, 1, scaleZ));
      heightFieldShape.setMargin(0.05);
      return heightFieldShape;
    }
    function generateObject() {
      const numTypes = 4;
      const objectType = Math.ceil(Math.random() * numTypes);
      let threeObject = null;
      let shape = null;
      const objectSize = 3;
      const margin = 0.05;
      let radius, height;
      switch (objectType) {
        case 1:
          radius = 1 + Math.random() * objectSize;
          threeObject = new THREE.Mesh(
            new THREE.SphereGeometry(radius, 20, 20),
            createObjectMaterial()
          );
          shape = new Ammo.btSphereShape(radius);
          shape.setMargin(margin);
          break;
        case 2:
          const sx = 1 + Math.random() * objectSize;
          const sy = 1 + Math.random() * objectSize;
          const sz = 1 + Math.random() * objectSize;
          threeObject = new THREE.Mesh(
            new THREE.BoxGeometry(sx, sy, sz, 1, 1, 1),
            createObjectMaterial()
          );
          shape = new Ammo.btBoxShape(new Ammo.btVector3(sx * 0.5, sy * 0.5, sz * 0.5));
          shape.setMargin(margin);
          break;
        case 3:
          radius = 1 + Math.random() * objectSize;
          height = 1 + Math.random() * objectSize;
          threeObject = new THREE.Mesh(
            new THREE.CylinderGeometry(radius, radius, height, 20, 1),
            createObjectMaterial()
          );
          shape = new Ammo.btCylinderShape(new Ammo.btVector3(radius, height * 0.5, radius));
          shape.setMargin(margin);
          break;
        default:
          radius = 1 + Math.random() * objectSize;
          height = 2 + Math.random() * objectSize;
          threeObject = new THREE.Mesh(
            new THREE.ConeGeometry(radius, height, 20, 2),
            createObjectMaterial()
          );
          shape = new Ammo.btConeShape(radius, height);
          break;
      }
      threeObject.position.set(
        (Math.random() - 0.5) * terrainWidth * 0.6,
        terrainMaxHeight + objectSize + 2,
        (Math.random() - 0.5) * terrainDepth * 0.6
      );
      const mass = objectSize * 5;
      const localInertia = new Ammo.btVector3(0, 0, 0);
      shape.calculateLocalInertia(mass, localInertia);
      const transform = new Ammo.btTransform();
      transform.setIdentity();
      const pos = threeObject.position;
      transform.setOrigin(new Ammo.btVector3(pos.x, pos.y, pos.z));
      const motionState = new Ammo.btDefaultMotionState(transform);
      const rbInfo = new Ammo.btRigidBodyConstructionInfo(mass, motionState, shape, localInertia);
      const body = new Ammo.btRigidBody(rbInfo);
      threeObject.userData.physicsBody = body;
      threeObject.receiveShadow = true;
      threeObject.castShadow = true;
      scene.add(threeObject);
      dynamicObjects.push(threeObject);
      physicsWorld.addRigidBody(body);
    }
    function createObjectMaterial() {
      const c = Math.floor(Math.random() * (1 << 24));
      return new THREE.MeshPhongMaterial({ color: c });
    }
    function animate() {
      render();
      stats.update();
    }
    function render() {
      const deltaTime = clock.getDelta();
      if (dynamicObjects.length < maxNumObjects && time > timeNextSpawn) {
        generateObject();
        timeNextSpawn = time + objectTimePeriod;
      }
      updatePhysics(deltaTime);
      renderer.render(scene, camera);
      time += deltaTime;
    }
    function updatePhysics(deltaTime) {
      physicsWorld.stepSimulation(deltaTime, 10);
      for (let i = 0, il = dynamicObjects.length; i < il; i++) {
        const objThree = dynamicObjects[i];
        const objPhys = objThree.userData.physicsBody;
        const ms = objPhys.getMotionState();
        if (ms) {
          ms.getWorldTransform(transformAux1);
          const p = transformAux1.getOrigin();
          const q = transformAux1.getRotation();
          objThree.position.set(p.x(), p.y(), p.z());
          objThree.quaternion.set(q.x(), q.y(), q.z(), q.w());
        }
      }
    }
  }
};
export {
  exampleInfo as default
};
ts
import { Loader, TypedArray } from 'three';
/**
 * 官网示例的多端使用封装把版本
 * */
export interface OfficialExampleInfo extends MiniProgramMeta {
  /*** 示例名称(保持和官网一致)*/
  name: string;
  /** main */
  init: (context: LoadContext) => void;
}

export interface LoadContext {
  //为了减少官方代码的改动,实际上等同于 canvas
  window: EventTarget & { innerWidth: number; innerHeight: number; devicePixelRatio: number };
  /** HTMLCanvasElement */
  canvas: any;
  /** https://www.npmjs.com/package/lil-gui */
  GUI: any;
  /**
   * https://www.npmjs.com/package/stats.js
   * 也可以使用其他受支持的版本
   * */
  Stats: any;
  /** 收集需要 dispose 的对象(官方示例没有处理这部分)*/
  needToDispose: (...objs: any[]) => void | ((fromFn: () => any[]) => void);

  /**基于 raq 的通用封装 */
  useFrame(animateFunc: (/** ms */ delta: number) => void): { cancel: () => void };

  /** 显示加载模态框 */
  requestLoading(text?: string): Promise<void>;

  /** 隐藏加载模态框*/
  cancelLoading(): void;

  /** 保存文件的通用封装*/
  saveFile(
    fileName: string,
    data: ArrayBuffer | TypedArray | DataView | string
  ): Promise<string | null>;

  /** 示例使用 DracoDecoder 时的资源路径 */
  DecoderPath: {
    GLTF: string;
    STANDARD: string;
  };

  /** 为资源路径拼上 CDN 前缀 */
  withCDNPrefix(path: string): string;

  /**
   * 在小程序中应使用 import { VideoTexture } from '@minisheep/three-platform-adapter/override/jsm/textures/VideoTexture.js';
   * 正常情况(web) 可直接使用 THREE.VideoTexture
   * */
  getVideoTexture(videoOptions: VideoOptions): Promise<[{ isVideoTexture: true }, video: any]>;

  /**
   * 在小程序中应使用 import { CameraTexture } from '@minisheep/three-platform-adapter/override/jsm/textures/CameraTexture.js';
   * 正常情况(web) 可参考示例 webgl_materials_video_webcam
   * */
  getCameraTexture(): { isVideoTexture: true };

  /** 用于动态修改 info 中的占位符*/
  bindInfoText(template: `$${string}$`, initValue?: string): { value: string };

  /** 分屏控件对应的事件回调 */
  onSlideStart(handle: () => void): void;
  /** 分屏控件对应的事件回调 */
  onSlideEnd(handle: () => void): void;
  /** 分屏控件对应的事件回调 */
  onSlideChange(handle: (offset: number, boxSize: number) => void): void;
}

export type VideoOptions = {
  src: string;
  /** 相当于 HTMLVideoElement 的 naturalWidth (小程序中获取不到)*/
  width: number;
  /** 相当于 HTMLVideoElement 的 naturalHeight (小程序中获取不到)*/
  height: number;
  loop?: boolean;
  autoplay?: boolean;
  muted?: boolean;
};

/** 示例小程序中使用的一些配置 */
export interface MiniProgramMeta {
  /** 用于统计加载相关信息 */
  useLoaders: Loader[];
  /** 通用 info */
  info: TagItem[][];
  /** 特殊 info */
  infoPanel?: {
    left?: [string, string][];
    right?: [string, string][];
  };
  /** 分屏控件配置 */
  needSlider?: {
    /** 方向 */
    direction?: 'horizontal' | 'vertical';
    /** 初始偏移 0-100 */
    initPosition?: number;
  };
  /** 操作摇杆控件 */
  needArrowControls?: boolean;
  /** 默认需要的画布类型 */
  canvasType?: '2d' | 'webgl' | 'webgl2';
  /** 为保持效果一致所需要的画布样式 */
  canvasStyle?: {
    bgColor?: string;
    width?: number | string;
    height?: number | string;
  };
  /** 部分示例需要在加载前进行一些提示 */
  initAfterConfirm?: {
    /**
     * 提示类型
     * @default 'default'
     * */
    type?: 'warning' | 'default';
    text: string[];
  };
}

export interface BaseTag<T extends string> {
  tag: T;
  content: string;
}

export interface ATag extends BaseTag<'a'> {
  link: string;
}

export type TextTag = BaseTag<'text'>;

export type TagItem = TextTag | ATag;