Tanoda
pb_Stl_Exporter.cs
Go to the documentation of this file.
1using UnityEngine;
2using System.Linq;
3using System.Collections.Generic;
4
5namespace Parabox.STL
6{
10 public static class pb_Stl_Exporter
11 {
15 public static bool Export(string path, GameObject[] gameObjects, FileType type)
16 {
17 Mesh[] meshes = CreateWorldSpaceMeshesWithTransforms(gameObjects.Select(x => x.transform).ToArray());
18 bool success = false;
19
20 if(meshes != null && meshes.Length > 0)
21 {
22 if(!string.IsNullOrEmpty(path))
23 success = pb_Stl.WriteFile(path, meshes, type);
24 }
25
26 for(int i = 0; meshes != null && i < meshes.Length; i++)
27 Object.DestroyImmediate(meshes[i]);
28
29 return success;
30 }
34 public static string Export(GameObject[] gameObjects, FileType type)
35 {
36 Mesh[] meshes = CreateWorldSpaceMeshesWithTransforms(gameObjects.Select(x => x.transform).ToArray());
37 var retval = "";
38 if(meshes != null && meshes.Length > 0)
39 {
40 retval = pb_Stl.WriteString(meshes);
41 }
42
43 for(int i = 0; meshes != null && i < meshes.Length; i++)
44 Object.DestroyImmediate(meshes[i]);
45
46 return retval;
47 }
48
52 private static Mesh[] CreateWorldSpaceMeshesWithTransforms(IList<Transform> transforms)
53 {
54 if(transforms == null || transforms.Count < 1)
55 return null;
56
57 // move root node to center of selection
58 Vector3 p = Vector3.zero;
59
60 for(int i = 0; i < transforms.Count; i++)
61 p += transforms[i].position;
62 Vector3 mesh_center = p / (float) transforms.Count;
63
64 GameObject root = new GameObject();
65 root.name = "ROOT";
66 root.transform.position = mesh_center;
67
68 // copy all transforms to new root gameobject
69 foreach(Transform t in transforms)
70 {
71 GameObject go = (GameObject) GameObject.Instantiate(t.gameObject);
72 go.transform.SetParent(t.parent, false);
73 go.transform.SetParent(root.transform, true);
74 }
75
76 // move root to 0,0,0 so mesh transformations are relative to origin
77 root.transform.position = Vector3.zero;
78
79 // create new meshes by iterating the root node and transforming vertex & normal
80 // values (ignoring all other mesh attributes since STL doesn't care about them)
81 List<MeshFilter> mfs = root.GetComponentsInChildren<MeshFilter>().Where(x => x.sharedMesh != null).ToList();
82 int meshCount = mfs.Count;
83 Mesh[] meshes = new Mesh[meshCount];
84
85 for(int i = 0; i < meshCount; i++)
86 {
87 Transform t = mfs[i].transform;
88
89 Vector3[] v = mfs[i].sharedMesh.vertices;
90 Vector3[] n = mfs[i].sharedMesh.normals;
91
92 for(int it = 0; it < v.Length; it++)
93 {
94 v[it] = t.TransformPoint(v[it]);
95 n[it] = t.TransformDirection(n[it]);
96 }
97
98 Mesh m = new Mesh();
99
100 m.name = mfs[i].name;
101 m.vertices = v;
102 m.normals = n;
103 m.triangles = mfs[i].sharedMesh.triangles;
104
105 meshes[i] = m;
106 }
107
108 // Cleanup
109 GameObject.DestroyImmediate(root);
110
111 return meshes;
112 }
113 }
114}
UnityEngine.Object Object