Skip to content

webgl_geometry_extrude_splines

对应 three.js 示例地址

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

js
import * as THREE from "three";
import * as Curves from "three/examples/jsm/curves/CurveExtras.js";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";

/** @type {import("@minisheeep/mp-three-examples").OfficialExampleInfo} */
const exampleInfo = {
  name: "webgl_geometry_extrude_splines",
  useLoaders: [],
  info: [
    [
      {
        tag: "a",
        link: "https://threejs.org",
        content: "three.js"
      },
      {
        tag: "text",
        content: "- spline extrusion examples"
      }
    ]
  ],
  init: ({ window, canvas, GUI, Stats, needToDispose, useFrame }) => {
    let stats;
    let camera, scene, renderer, splineCamera, cameraHelper, cameraEye;
    const direction = new THREE.Vector3();
    const binormal = new THREE.Vector3();
    const normal = new THREE.Vector3();
    const position = new THREE.Vector3();
    const lookAt = new THREE.Vector3();
    const pipeSpline = new THREE.CatmullRomCurve3([
      new THREE.Vector3(0, 10, -10),
      new THREE.Vector3(10, 0, -10),
      new THREE.Vector3(20, 0, 0),
      new THREE.Vector3(30, 0, 10),
      new THREE.Vector3(30, 0, 20),
      new THREE.Vector3(20, 0, 30),
      new THREE.Vector3(10, 0, 30),
      new THREE.Vector3(0, 0, 30),
      new THREE.Vector3(-10, 10, 30),
      new THREE.Vector3(-10, 20, 30),
      new THREE.Vector3(0, 30, 30),
      new THREE.Vector3(10, 30, 30),
      new THREE.Vector3(20, 30, 15),
      new THREE.Vector3(10, 30, 10),
      new THREE.Vector3(0, 30, 10),
      new THREE.Vector3(-10, 20, 10),
      new THREE.Vector3(-10, 10, 10),
      new THREE.Vector3(0, 0, 10),
      new THREE.Vector3(10, -10, 10),
      new THREE.Vector3(20, -15, 10),
      new THREE.Vector3(30, -15, 10),
      new THREE.Vector3(40, -15, 10),
      new THREE.Vector3(50, -15, 10),
      new THREE.Vector3(60, 0, 10),
      new THREE.Vector3(70, 0, 0),
      new THREE.Vector3(80, 0, 0),
      new THREE.Vector3(90, 0, 0),
      new THREE.Vector3(100, 0, 0)
    ]);
    const sampleClosedSpline = new THREE.CatmullRomCurve3([
      new THREE.Vector3(0, -40, -40),
      new THREE.Vector3(0, 40, -40),
      new THREE.Vector3(0, 140, -40),
      new THREE.Vector3(0, 40, 40),
      new THREE.Vector3(0, -40, 40)
    ]);
    sampleClosedSpline.curveType = "catmullrom";
    sampleClosedSpline.closed = true;
    const splines = {
      GrannyKnot: new Curves.GrannyKnot(),
      HeartCurve: new Curves.HeartCurve(3.5),
      VivianiCurve: new Curves.VivianiCurve(70),
      KnotCurve: new Curves.KnotCurve(),
      HelixCurve: new Curves.HelixCurve(),
      TrefoilKnot: new Curves.TrefoilKnot(),
      TorusKnot: new Curves.TorusKnot(20),
      CinquefoilKnot: new Curves.CinquefoilKnot(20),
      TrefoilPolynomialKnot: new Curves.TrefoilPolynomialKnot(14),
      FigureEightPolynomialKnot: new Curves.FigureEightPolynomialKnot(),
      DecoratedTorusKnot4a: new Curves.DecoratedTorusKnot4a(),
      DecoratedTorusKnot4b: new Curves.DecoratedTorusKnot4b(),
      DecoratedTorusKnot5a: new Curves.DecoratedTorusKnot5a(),
      DecoratedTorusKnot5c: new Curves.DecoratedTorusKnot5c(),
      PipeSpline: pipeSpline,
      SampleClosedSpline: sampleClosedSpline
    };
    let parent, tubeGeometry, mesh;
    const params = {
      spline: "GrannyKnot",
      scale: 4,
      extrusionSegments: 100,
      radiusSegments: 3,
      closed: true,
      animationView: false,
      lookAhead: false,
      cameraHelper: false
    };
    const material = new THREE.MeshLambertMaterial({ color: 16711935 });
    const wireframeMaterial = new THREE.MeshBasicMaterial({
      color: 0,
      opacity: 0.3,
      wireframe: true,
      transparent: true
    });
    function addTube() {
      if (mesh !== void 0) {
        parent.remove(mesh);
        mesh.geometry.dispose();
      }
      const extrudePath = splines[params.spline];
      tubeGeometry = new THREE.TubeGeometry(
        extrudePath,
        params.extrusionSegments,
        2,
        params.radiusSegments,
        params.closed
      );
      addGeometry(tubeGeometry);
      setScale();
    }
    function setScale() {
      mesh.scale.set(params.scale, params.scale, params.scale);
    }
    function addGeometry(geometry) {
      mesh = new THREE.Mesh(geometry, material);
      const wireframe = new THREE.Mesh(geometry, wireframeMaterial);
      mesh.add(wireframe);
      parent.add(mesh);
    }
    function animateCamera() {
      cameraHelper.visible = params.cameraHelper;
      cameraEye.visible = params.cameraHelper;
    }
    init();
    function init() {
      camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.01, 1e4);
      camera.position.set(0, 50, 500);
      scene = new THREE.Scene();
      scene.background = new THREE.Color(15790320);
      scene.add(new THREE.AmbientLight(16777215));
      const light = new THREE.DirectionalLight(16777215, 1.5);
      light.position.set(0, 0, 1);
      scene.add(light);
      parent = new THREE.Object3D();
      scene.add(parent);
      splineCamera = new THREE.PerspectiveCamera(
        84,
        window.innerWidth / window.innerHeight,
        0.01,
        1e3
      );
      parent.add(splineCamera);
      cameraHelper = new THREE.CameraHelper(splineCamera);
      scene.add(cameraHelper);
      addTube();
      cameraEye = new THREE.Mesh(
        new THREE.SphereGeometry(5),
        new THREE.MeshBasicMaterial({ color: 14540253 })
      );
      parent.add(cameraEye);
      cameraHelper.visible = params.cameraHelper;
      cameraEye.visible = params.cameraHelper;
      renderer = new THREE.WebGLRenderer({ antialias: true, canvas });
      renderer.setPixelRatio(window.devicePixelRatio);
      renderer.setSize(window.innerWidth, window.innerHeight);
      renderer.setAnimationLoop(animate);
      stats = new Stats(renderer);
      const gui = new GUI({ width: 285 });
      const folderGeometry = gui.addFolder("Geometry");
      folderGeometry.add(params, "spline", Object.keys(splines)).onChange(function() {
        addTube();
      });
      folderGeometry.add(params, "scale", 2, 10).step(2).onChange(function() {
        setScale();
      });
      folderGeometry.add(params, "extrusionSegments", 50, 500).step(50).onChange(function() {
        addTube();
      });
      folderGeometry.add(params, "radiusSegments", 2, 12).step(1).onChange(function() {
        addTube();
      });
      folderGeometry.add(params, "closed").onChange(function() {
        addTube();
      });
      folderGeometry.open();
      const folderCamera = gui.addFolder("Camera");
      folderCamera.add(params, "animationView").onChange(function() {
        animateCamera();
      });
      folderCamera.add(params, "lookAhead").onChange(function() {
        animateCamera();
      });
      folderCamera.add(params, "cameraHelper").onChange(function() {
        animateCamera();
      });
      folderCamera.open();
      const controls = new OrbitControls(camera, renderer.domElement);
      controls.minDistance = 100;
      controls.maxDistance = 2e3;
      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 animate() {
      render();
      stats.update();
    }
    function render() {
      const time = Date.now();
      const looptime = 20 * 1e3;
      const t = time % looptime / looptime;
      tubeGeometry.parameters.path.getPointAt(t, position);
      position.multiplyScalar(params.scale);
      const segments = tubeGeometry.tangents.length;
      const pickt = t * segments;
      const pick = Math.floor(pickt);
      const pickNext = (pick + 1) % segments;
      binormal.subVectors(tubeGeometry.binormals[pickNext], tubeGeometry.binormals[pick]);
      binormal.multiplyScalar(pickt - pick).add(tubeGeometry.binormals[pick]);
      tubeGeometry.parameters.path.getTangentAt(t, direction);
      const offset = 15;
      normal.copy(binormal).cross(direction);
      position.add(normal.clone().multiplyScalar(offset));
      splineCamera.position.copy(position);
      cameraEye.position.copy(position);
      tubeGeometry.parameters.path.getPointAt(
        (t + 30 / tubeGeometry.parameters.path.getLength()) % 1,
        lookAt
      );
      lookAt.multiplyScalar(params.scale);
      if (!params.lookAhead) lookAt.copy(position).add(direction);
      splineCamera.matrix.lookAt(splineCamera.position, lookAt, normal);
      splineCamera.quaternion.setFromRotationMatrix(splineCamera.matrix);
      cameraHelper.update();
      renderer.render(scene, params.animationView === true ? splineCamera : camera);
    }
  }
};
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 {
  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: Record<string, 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;