简介

Aspose.3D FOSS for TypeScript(@aspose/3d)是一个开源、MIT 许可证的 3D 文件格式库,主要面向 Node.js 设计。构建 3D 模型查看器、格式转换器、几何处理工具或服务端 3D 流水线的开发者可以通过一条命令进行安装(参见安装指南),并立即开始加载、构建和导出 3D 内容。该库使用 Node.js 的 require('fs') 和 Buffer;在浏览器中使用需提供相应的 shim 来兼容这些 API,官方并不支持。

该库支持主要的互换格式——OBJ、glTF 2.0 / GLB、STL、3MF 和 COLLADA,均可用于导入和导出。虽然已有 FBX 导入/导出类,但尚未接入格式自动检测。场景图 API 复制了 3D 创作工具中熟悉的模型:一个 Scene 包含一个 rootNode,每个 Node 可以携带子节点和实体对象(Mesh、Camera、Light),并且变换层级可完整读取和写入。

关键特性

  • 多格式 I/O: 导入和导出 OBJ(包括 .mtl 材料),glTF 2.0 / GLB,STL(二进制和 ASCII),3MF,和 COLLADA,支持从文件路径和内存中 Buffer 对象。FBX 支持尚未接入自动检测。
  • 场景图 API: Scene, Node, Mesh, Camera, Light 层级结构具备完整的父/子管理;可通过递归遍历节点 node.childNodes
  • PBR 材料系统: 通过可访问的 Lambert、Phong 和 PBR(金属/粗糙度)材料 node.material
  • 网格操作: 通过以下方式访问原始顶点数据 mesh.controlPoints (数组的 Vector4),多边形索引通过 mesh.polygonCount,以及顶点元素通道通过 mesh.getElement()
  • 数学工具: Vector2, Vector3, Vector4, Matrix4, Quaternion,以及用于空间计算的包围盒类型
  • 动画系统: 关键帧动画与 AnimationClip, AnimationChannel,以及插值曲线(线性、贝塞尔、TCB样条)
  • 特定格式选项: 每种格式 LoadOptions / SaveOptions 类控制坐标翻转、缩放、材质加载等

入门

从源码构建软件包。需要 Node.js 18 或更高版本;建议使用 TypeScript 5.0+。

git clone https://github.com/aspose-3d-foss/Aspose.3D-FOSS-for-TypeScript.git
cd Aspose.3D-FOSS-for-TypeScript
npm install
npm run build

加载 OBJ 文件并检查场景:

import { Scene } from '@aspose/3d';
import { ObjLoadOptions } from '@aspose/3d/formats/obj';

const scene = new Scene();
const options = new ObjLoadOptions();
options.enableMaterials = true;
scene.open('model.obj', options);

for (const node of scene.rootNode.childNodes) {
    if (node.entity && 'controlPoints' in node.entity) {
        const mesh = node.entity as any;
        console.log(`Mesh "${node.name}": ${mesh.controlPoints.length} vertices`);
    }
}

场景图 API

每个场景都是以 scene.rootNode 为根的 Node 对象树。使用 addChildNode() 构建层级结构,通过其 entity 属性将 Camera 或 Light 等实体附加到节点,并通过 transform 和 globalTransform 读取每个节点的局部或世界空间变换。

import { Scene, Node, Camera, Light } from '@aspose/3d';

const scene = new Scene();

const cameraNode = new Node('MainCamera');
cameraNode.entity = new Camera('MainCamera');
scene.rootNode.addChildNode(cameraNode);

const lightNode = new Node('KeyLight');
lightNode.entity = new Light('KeyLight');
scene.rootNode.addChildNode(lightNode);

for (const child of scene.rootNode.childNodes) {
    console.log(`${child.name}: ${child.entity?.constructor.name}`);
}

数学工具

Vector3、Vector4、Matrix4 和 Quaternion 支持库中所有几何运算。Vector3 和 Vector4 暴露 x/y/z(/w) 组件以及 length、dot()、cross();Matrix4 是一个通过 m00–m33 访问的 4×4 网格,配合 transpose() 和 concatenate() 使用;Quaternion 为旋转数学提供 normalize()、conjugate()、inverse() 和 dot()。

import { Vector3, Quaternion, Matrix4 } from '@aspose/3d/utilities';

const position = new Vector3(1.0, 2.0, 3.0);
const rotation = new Quaternion(1.0, 0.0, 0.0, 0.0);
const transform = new Matrix4();

console.log(`length=${position.length} determinant=${transform.determinant}`);
console.log(`rotation w=${rotation.w} x=${rotation.x} y=${rotation.y} z=${rotation.z}`);

另请参阅

相关资源