如何在 three.js 中使用真实的 3D 地图
TerraPrinter 为 3D 打印制作真实地点的 3D 模型,每个模型也都能下载为 GLB,three.js 可以直接加载:模型正立放置,单位为米,每个地图图层都是一个单独命名的部件,文件中还带有地图的 GPS 范围。
GLB 包含什么
GLB 是二进制的 glTF 2.0,也就是 three.js 用 GLTFLoader 加载的格式。无需任何转换。
- 正立放置,保持打印尺寸。按照 glTF 的约定,Y 轴朝上,单位是米,所以 200 mm 的模型宽 0.2 个单位。模型以原点为中心,底部位于 y = 0,北方指向 −Z。
- 每个图层一个命名部件。Terrain、Buildings、Roads、Water、Parks、Trees 等都是独立的网格,各有自己的颜色。
- 位置信息。地图边缘的经纬度、比例尺、垂直夸张和数据署名都写在文件中。在 three.js 中,它们位于模型的
userData里。 - 任何用途均免费,包括商业游戏和应用。请保留文件中附带的数据署名。
下载 GLB
- 打开 TerraPrinter,找到你的地点:搜索它,或者从某张现成地图开始。
- 画出区域,打开你需要的图层,比如建筑、道路、水体和树木。
- 点击生成 3D 模型。
- 在下载窗口中,点击 STL 和 OBJ 旁边的 GLB。
在预览中隐藏的图层不会写入文件。你添加的边框、名牌或支架会作为单独的部件。
在 three.js 中加载
看看实际效果:在 three.js 中实时运行的巴黎,按照本指南制作。
这是一个完整的网页:一个场景、两盏灯、一台可以用鼠标旋转的相机,以及模型。把它保存在 GLB 旁边,把文件名改成你自己的,然后通过任意本地 Web 服务器打开,因为浏览器不会直接从磁盘加载文件。
<!doctype html>
<html>
<body style="margin: 0">
<script type="importmap">
{ "imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.183.1/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.183.1/examples/jsm/"
} }
</script>
<script type="module">
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(devicePixelRatio);
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color('#1b1f24');
scene.add(new THREE.HemisphereLight(0xffffff, 0x445566, 1.5));
const sun = new THREE.DirectionalLight(0xffffff, 2.5);
sun.position.set(-1, 2, 1);
scene.add(sun);
// The model is at its printed size: a 200 mm print is 0.2 units across.
const camera = new THREE.PerspectiveCamera(40, innerWidth / innerHeight, 0.001, 100);
camera.position.set(0.2, 0.2, 0.25);
const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 0.01, 0);
const gltf = await new GLTFLoader().loadAsync('paris-terraprinter.com.glb');
scene.add(gltf.scene);
renderer.setAnimationLoop(() => {
controls.update();
renderer.render(scene, camera);
});
</script>
</body>
</html>如果使用 Vite 等打包工具,用 npm install three 安装 three,并去掉 import map。import 语句保持不变。
修改或隐藏图层
按名称查找每个图层。three.js 会把名称中的空格替换为下划线,所以 Sports fields 会变成 Sports_fields,而 TerraPrinter 写入的原始名称保留在 userData.name 中。颜色相同的部件共用一个材质,所以修改颜色前,先给该部件分配一个独立的材质。
const model = gltf.scene;
// hide the trees
const trees = model.getObjectByName('Trees');
if (trees) trees.visible = false;
// paint the buildings
const buildings = model.getObjectByName('Buildings');
if (buildings) buildings.material = new THREE.MeshStandardMaterial({ color: '#d9d4c7', roughness: 0.9 });
// every part, by its name in TerraPrinter
model.traverse(o => { if (o.isMesh) console.log(o.userData.name, o.geometry.attributes.position.count); }); 真实尺寸和高度
模型的根节点 gltf.scene.children[0] 在它的 userData 中带有你需要的信息:
bounds和centre:地图边缘和中心点的经纬度。scale(例如 1:10,005)和groundMetresPerUnit:模型的一个单位对应地面上的多少米。verticalExaggeration:为了打印,高度被拉伸了多少倍。1 表示真实高度。mapBoxInModel:地图的西、东、北、南边缘在模型中的位置。printSizeMm、baseThicknessMm、数据署名和许可。
要让一个单位等于地面上的一米,并使用真实高度:
const root = gltf.scene.children[0];
const info = root.userData;
const k = info.groundMetresPerUnit;
root.scale.set(k, k / (info.verticalExaggeration || 1), k);底座是 Terrain 网格的一部分,会随模型一起放大,厚度可达几十米。可以把它藏在你自己的地面之下,或者在下载前在 TerraPrinter 中减小底座厚度。按真实尺寸时,模型和这个地方一样大,所以要把相机拉远,并相应调大远裁剪面。
在模型上标出 GPS 点
经度和纬度在地图的方框内均匀分布,北方朝向 −Z。下面这个函数可以在任意比例下,找到模型上任意经纬度正下方的地面:
const raycaster = new THREE.Raycaster();
function groundAt(lon, lat, root) {
const { bounds: b, mapBoxInModel: m } = root.userData;
const x = m.xWest + (lon - b.west) / (b.east - b.west) * (m.xEast - m.xWest);
const z = m.zNorth + (b.north - lat) / (b.north - b.south) * (m.zSouth - m.zNorth);
// a ray straight down onto the terrain
root.updateWorldMatrix(true, true);
const from = root.localToWorld(new THREE.Vector3(x, 1000, z));
const to = root.localToWorld(new THREE.Vector3(x, 0, z));
raycaster.set(from, to.sub(from).normalize());
const hit = raycaster.intersectObject(root.getObjectByName('Terrain'))[0];
return hit ? hit.point : null;
}
// a red marker on the ground under the Eiffel Tower
const marker = new THREE.Mesh(new THREE.SphereGeometry(0.002), new THREE.MeshStandardMaterial({ color: 'red' }));
marker.position.copy(groundAt(2.2945, 48.8583, gltf.scene.children[0]));
scene.add(marker);如果还想落在屋顶和树冠上,就把射线投向整个 root,而不是 Terrain 部件。如果你把模型缩放到了真实尺寸,也要把标记放大。
文件大小和速度
- 一个约 2 km 宽的市中心,包含所有建筑和树木,文件大小为 60 到 110 MB。树木往往占了大部分,所以如果不需要,就在 TerraPrinter 中关闭它们。
- 用于网站时,可以用 glTF Transform 压缩文件:先用
npm install --global @gltf-transform/cli安装,然后运行gltf-transform meshopt input.glb output.glb。这会压缩几何体,并保留每个部件及其名称。 - 压缩后的文件需要 three.js 自带的解码器:
import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';
const loader = new GLTFLoader();
loader.setMeshoptDecoder(MeshoptDecoder);
const gltf = await loader.loadAsync('output.glb');