本章我们一起来看下怎样将unity中的fbx模型转成stl模型并且保存到本地。
原理:stl模型都是由三角面组成的,只要我们了解stl文件的格式,就能够轻松的将fbx模型转换成stl。
1、先获取到fxb模型在Unity中的模型组件GameObject
2、获取模型mesh,得到总的顶点数和三角面数量
3、循环遍历顶点,并将数据写入到本地文件中
具体代码如下:
//go表示模型组件
//vertices用于保存模型顶点数
Vector3[] vertices = go.transform.GetComponent
//triangles用于保存模型三角面数
int[] triangles = go.transform.GetComponent
int i = 0;
int trianglesCount = triangles.Length;
//计算出stl的大小
int stlSize = 80 + 4 + (trianglesCount + 360) * (4 * 12 + 2);
byte[] stl = new byte[stlSize];
//创建一个文件流用于将数据写入到本地
MemoryStream ms = new MemoryStream(stl);
BinaryWriter writer = new BinaryWriter(ms);
byte[] header = new byte[80];
short _short = 0;
header[0] = 73;
header[1] = 99;
header[2] = 101;
header[3] = 109;
header[4] = 97;
header[5] = 110;
writer.Write(header);
writer.Write(trianglesCount);
//循环遍历顶点,并将数据写入到文件中
for (i = 0; i < trianglesCount; i += 3)
{
writer.Write(0.0f);
writer.Write(0.0f);
writer.Write(0.0f);
writer.Write(vertices[triangles[i]].x);
writer.Write(vertices[triangles[i]].z);
writer.Write(vertices[triangles[i]].y);
writer.Write(vertices[triangles[i + 2]].x);
writer.Write(vertices[triangles[i + 2]].z);
writer.Write(vertices[triangles[i + 2]].y);
writer.Write(vertices[triangles[i + 1]].x);
writer.Write(vertices[triangles[i + 1]].z);
writer.Write(vertices[triangles[i + 1]].y);
writer.Write(_short);
}
writer.Close();
ms.Close();
ms.Dispose();
//将数据保存到本地
File.WriteAllBytes(Application.persistentDataPath + "/" + modelName, stl);