2using System.Collections.Generic;
21 public static class pb_Stl
26 public static bool WriteFile(
string path, Mesh mesh,
FileType type =
FileType.Ascii,
bool convertToRightHandedCoordinates =
true)
28 return WriteFile(path,
new Mesh[] { mesh }, type, convertToRightHandedCoordinates);
41 public static bool WriteFile(
string path, IList<Mesh> meshes,
FileType type =
FileType.Ascii,
bool convertToRightHandedCoordinates =
true)
51 using (BinaryWriter writer =
new BinaryWriter(
File.Open(path,
FileMode.Create),
new ASCIIEncoding()))
54 writer.Write(
new byte[80]);
56 uint totalTriangleCount = (uint) (meshes.Sum(x => x.triangles.Length) / 3);
59 writer.Write( totalTriangleCount );
61 foreach(Mesh mesh
in meshes)
63 Vector3[] v = convertToRightHandedCoordinates ? Left2Right(mesh.vertices) : mesh.vertices;
64 Vector3[] n = convertToRightHandedCoordinates ? Left2Right(mesh.normals) : mesh.normals;
65 int[] t = mesh.triangles;
66 int triangleCount = t.Length;
67 if(convertToRightHandedCoordinates)
68 System.Array.Reverse(t);
70 for(
int i = 0; i < triangleCount; i += 3)
72 int a = t[i], b = t[i+1], c = t[i+2];
74 Vector3 avg = AvgNrm(n[a], n[b], n[c]);
93 writer.Write( (ushort)0 );
101 string model = WriteString(meshes);
102 File.WriteAllText(path, model);
106 catch(System.Exception e)
118 public static string WriteString(Mesh mesh,
bool convertToRightHandedCoordinates =
true)
120 return WriteString(
new Mesh[] { mesh }, convertToRightHandedCoordinates);
126 public static string WriteString(IList<Mesh> meshes,
bool convertToRightHandedCoordinates =
true)
128 StringBuilder sb =
new StringBuilder();
130 string name = meshes.Count == 1 ? meshes[0].name :
"Composite Mesh";
132 sb.AppendLine(
string.Format(
"solid {0}", name));
134 foreach(Mesh mesh
in meshes)
136 Vector3[] v = convertToRightHandedCoordinates ? Left2Right(mesh.vertices) : mesh.vertices;
137 Vector3[] n = convertToRightHandedCoordinates ? Left2Right(mesh.normals) : mesh.normals;
138 int[] t = mesh.triangles;
139 if(convertToRightHandedCoordinates) System.Array.Reverse(t);
140 int triLen = t.Length;
142 for(
int i = 0; i < triLen; i+=3)
148 Vector3 nrm = AvgNrm(n[a], n[b], n[c]);
150 sb.AppendLine(
string.Format(
"facet normal {0} {1} {2}", nrm.x, nrm.y, nrm.z));
152 sb.AppendLine(
"outer loop");
154 sb.AppendLine(
string.Format(
"\tvertex {0} {1} {2}", v[a].x, v[a].y, v[a].z));
155 sb.AppendLine(
string.Format(
"\tvertex {0} {1} {2}", v[b].x, v[b].y, v[b].z));
156 sb.AppendLine(
string.Format(
"\tvertex {0} {1} {2}", v[c].x, v[c].y, v[c].z));
158 sb.AppendLine(
"endloop");
160 sb.AppendLine(
"endfacet");
164 sb.AppendLine(
string.Format(
"endsolid {0}", name));
166 return sb.ToString();
169 private static Vector3[] Left2Right(Vector3[] v)
174 for(
int i = 0; i < v.Length; i++)
175 r[i] = l2r.MultiplyPoint3x4(v[i]);
183 private static Vector3 AvgNrm(Vector3 a, Vector3 b, Vector3 c)
186 (a.x + b.x + c.x) / 3f,
187 (a.y + b.y + c.y) / 3f,
188 (a.z + b.z + c.z) / 3f );
System.IO.FileMode FileMode