gltf 模型通常会比较大,导致 3D 场景加载较慢。
那有没有啥优化加载性能的方式呢?
有,就是 Draco。
https://github.com/google/draco

它是谷歌推出的,用于压缩和解压缩 3D 网格模型的一个库。
gltf-pipeline 支持了 draco 的压缩和解压缩。
我们来试一下:
npx create-vite gltf-draco-test

创建 vite 项目。
进入项目,安装依赖:
npm install
npm install --save three
npm install --save-dev @types/three
改下 src/index.js
import './style.css';
import * as THREE from 'three';
import {
OrbitControls
} from 'three/addons/controls/OrbitControls.js';
import mesh from './mesh.js';
const scene = new THREE.Scene();
scene.add(mesh);
const light = new THREE.DirectionalLight(0xffffff);
light.position.set(100, 100, 100);
scene.add(light);
const light2 = new THREE.AmbientLight();
scene.add(light2);
const axesHelper = new THREE.AxesHelper(1000);
scene.add(axesHelper);
const width = window.innerWidth;
const height = window.innerHeight;
const camera = new THREE.PerspectiveCamera(60, width / height, 1, 10000);
camera.position.set(10, 10, 10);
camera.lookAt(0, 0, 0);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(width, height)
function render() {
renderer.render(scene, camera);
requestAnimationFrame(render);
}
render();
document.body.append(renderer.domElement);
const controls = new OrbitControls(camera, renderer.domElement);
创建 Scene、Light、Camera、Renderer
改下 style.css
body {
margin: 0;
}
然后创建 mesh.js
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
const loader = new GLTFLoader();
const mesh = new THREE.Group();
loader.load("./Michelle.glb", function (gltf) {
console.log(gltf);
gltf.scene.scale.setScalar(5);
mesh.add(gltf.scene);
})
export default mesh;
这里还是用的上节的模型,把它拿过来:
https://github.com/QuarkGluonPlasma/threejs-course-code/blob/main/dancing-mirror/public/Michelle.glb

放到 public 目录下:

先跑起来看下:
npm run dev


模型加载正常。
其实这个模型有 3.3M 的大小:

因为在本地,所以加载比较快。
我们用 draco 来压缩下:
npx gltf-pipeline -i ./public/Michelle.glb -o ./public/Michelle2.glb -d


压缩后的 glb 模型只有 2.5M 了,越大的模型压缩效果越明显。
我们加载试一下:

直接加载压缩过的模型会报错:

因为需要用 DRACOLoader 来解压缩。
我们改下代码:

const mesh = new THREE.Group();
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath( 'https://www.gstatic.com/draco/versioned/decoders/1.5.6/' );
loader.setDRACOLoader(dracoLoader);
创建 DRACOLoader,然后指定 decoder 的路径,它会从这里下载解码器。
之后把它设置到 GLTFLoader 的 dracoLoader
看下效果:

现在,模型就解码出来了。
我们看下网络传输:

现在就只需要加载 2.5M 的压缩模型了。
现在我们的 draco decoder 是从 cdn 下载的,其实 three.js 也内置了:

但 node_modules 下的代码网页访问不到,我们要把这个 /examples/jsm/libs/draco/gltf 目录复制出来,放到 public 下:


这样也可以:

案例代码上传了小册仓库。
总结
这节我们学了用 draco 来压缩模型,提高 gltf 模型加载性能。
这个是 google 推出的一个工具,我们可以用 gltf-pipeline 来压缩模型,它集成了 draco,只要在转换模型的时候加一个 -d
之后压缩过的模型在 threejs 里加载的时候,需要给 GLTFLoader 设置下 DRACOLoader 的实例,这个 dracoLoader 要指定从哪里下载 decoder
decoder 可以直接用 cdn 的,也可以把 three 的 libs 下的 decoder 复制出来,设置好对应的 decoderPath 加载路径就行。
这样,我们就可以下载压缩过的模型来提升 gltf 模型的加载速度了。