STL (Stereolithography) 文件是一种广泛用于3D打印和计算机辅助设计 (CAD) 领域的文件格式。它描述了一个三维模型的表面而不包含颜色、材质或其他非几何信息。STL文件通常用于3D打印过程中,因为它们仅包含构建物体所需的位置信息。
由于STL文件只包含表面信息,因此在导出过程中可能会丢失一些细节,特别是当模型具有非常小的特征或内部几何结构时。因此,在导出之前,最好确保你的模型是“水密的”(即没有内部孔或洞),并且所有的细节都在可接受的打印分辨率内。
为了将一个3D模型保存为STL文件,你通常需要使用一个3D建模软件或CAD软件,如SolidWorks、Fusion 360、Blender、Tinkercad等。
下面基于OCCT实现将3D模型保存为STL文件:
void SaveFile(const QString filename)
{
std::fstream fs;
fs.open(filename.toStdString(), std::ios::out);
bool flag = fs.is_open();
fs << "solid OCC STL\n";
TopoDS_Shape aBottle = MakeBottle(50, 70, 30);
IMeshTools_Parameters aMeshParams; //离散化的参数
BRepMesh_IncrementalMesh::SetParallelDefault(true);
for (TopExp_Explorer Ex(aBottle, TopAbs_FACE); Ex.More(); Ex.Next())
{
TopoDS_Face aFace = TopoDS::Face(Ex.Current());
//划分网格
BRepMesh_IncrementalMesh aMesher(aFace, aMeshParams);
const Standard_Integer aStatus = aMesher.GetStatusFlags();
//读取网格
TopLoc_Location loc = aFace.Location();
const Poly_ListOfTriangulation triangulars = BRep_Tool::Triangulations(aFace, loc); //容器
int num = triangulars.Size();
Poly_ListOfTriangulation::iterator iter = triangulars.begin();
for (iter; iter != triangulars.end(); iter++) {
Handle(Poly_Triangulation) poy = *iter;
Standard_Integer nodNum = poy->NbTriangles();
bool f = poy->HasNormals();
for (int i = 1; i <= nodNum; i++) {
Poly_Triangle tri = poy->Triangle(i);
Standard_Integer n1, n2, n3;
tri.Get(n1, n2, n3); //得到三角形三个顶点编号
//计算三角形面片的法线
double x1 = poy->Node(n1).X();
double y1 = poy->Node(n1).Y();
double z1 = poy->Node(n1).Z();
double x2 = poy->Node(n2).X();
double y2 = poy->Node(n2).Y();
double z2 = poy->Node(n2).Z();
double x3 = poy->Node(n3).X();
double y3 = poy->Node(n3).Y();
double z3 = poy->Node(n3).Z();
double detX1 = x2 - x1;
double detY1 = y2 - y1;
double detZ1 = z2 - z1;
double detX2 = x3 - x2;
double detY2 = y3 - y2;
double detZ2 = z3 - z2;
double X = detY1 * detZ2 - detZ1 * detY2;
double Y = detZ1 * detX2 - detX1 * detZ2;
double Z = detX1 * detY2 - detY1 * detX2;
double module = std::pow(X * X + Y * Y + Z * Z, 0.5);
X /= module;
Y /= module;
Z /= module;
//gp_Dir normal = poy->Normal(i);
fs << " facet normal " << X << " " << Y << " " << Z << "\n";
fs << " outer loop" << "\n";
fs << " vertex " << poy->Node(n1).X() << " " << poy->Node(n1).Y() << " " << poy->Node(n1).Z() << "\n";
//std::cout<< " vertex " << poy->Node(n1).X() << " " << poy->Node(n1).Y() << " " << poy->Node(n1).Z() << "\n";
fs << " vertex " << poy->Node(n2).X() << " " << poy->Node(n2).Y() << " " << poy->Node(n2).Z() << "\n";
fs << " vertex " << poy->Node(n3).X() << " " << poy->Node(n3).Y() << " " << poy->Node(n3).Z() << "\n";
fs << " endloop" << "\n";
fs << " endfacet" << "\n";
}
}
}
fs << "endsolid OCC STL\n";
fs.close();
}
文件有点大,接近30M,打开特别慢