]> git.sur5r.net Git - fstl/blob - src/loader.cpp
New upstream version 0.10.0
[fstl] / src / loader.cpp
1 #include <future>
2
3 #include "loader.h"
4 #include "vertex.h"
5
6 Loader::Loader(QObject* parent, const QString& filename, bool is_reload)
7     : QThread(parent), filename(filename), is_reload(is_reload)
8 {
9     // Nothing to do here
10 }
11
12 void Loader::run()
13 {
14     Mesh* mesh = load_stl();
15     if (mesh)
16     {
17         if (mesh->empty())
18         {
19             emit error_empty_mesh();
20             delete mesh;
21         }
22         else
23         {
24             emit got_mesh(mesh, is_reload);
25             emit loaded_file(filename);
26         }
27     }
28 }
29
30 ////////////////////////////////////////////////////////////////////////////////
31
32 void parallel_sort(Vertex* begin, Vertex* end, int threads)
33 {
34     if (threads < 2 || end - begin < 2)
35     {
36         std::sort(begin, end);
37     }
38     else
39     {
40         const auto mid = begin + (end - begin) / 2;
41         if (threads == 2)
42         {
43             auto future = std::async(parallel_sort, begin, mid, threads / 2);
44             std::sort(mid, end);
45             future.wait();
46         }
47         else
48         {
49             auto a = std::async(std::launch::async, parallel_sort, begin, mid, threads / 2);
50             auto b = std::async(std::launch::async, parallel_sort, mid, end, threads / 2);
51             a.wait();
52             b.wait();
53         }
54         std::inplace_merge(begin, mid, end);
55     }
56 }
57
58 Mesh* mesh_from_verts(uint32_t tri_count, QVector<Vertex>& verts)
59 {
60     // Save indicies as the second element in the array
61     // (so that we can reconstruct triangle order after sorting)
62     for (size_t i=0; i < tri_count*3; ++i)
63     {
64         verts[i].i = i;
65     }
66
67     // Check how many threads the hardware can safely support. This may return
68     // 0 if the property can't be read so we shoud check for that too.
69     auto threads = std::thread::hardware_concurrency();
70     if (threads == 0)
71     {
72         threads = 8;
73     }
74
75     // Sort the set of vertices (to deduplicate)
76     parallel_sort(verts.begin(), verts.end(), threads);
77
78     // This vector will store triangles as sets of 3 indices
79     std::vector<GLuint> indices(tri_count*3);
80
81     // Go through the sorted vertex list, deduplicating and creating
82     // an indexed geometry representation for the triangles.
83     // Unique vertices are moved so that they occupy the first vertex_count
84     // positions in the verts array.
85     size_t vertex_count = 0;
86     for (auto v : verts)
87     {
88         if (!vertex_count || v != verts[vertex_count-1])
89         {
90             verts[vertex_count++] = v;
91         }
92         indices[v.i] = vertex_count - 1;
93     }
94     verts.resize(vertex_count);
95
96     std::vector<GLfloat> flat_verts;
97     flat_verts.reserve(vertex_count*3);
98     for (auto v : verts)
99     {
100         flat_verts.push_back(v.x);
101         flat_verts.push_back(v.y);
102         flat_verts.push_back(v.z);
103     }
104
105     return new Mesh(std::move(flat_verts), std::move(indices));
106 }
107
108 ////////////////////////////////////////////////////////////////////////////////
109
110 Mesh* Loader::load_stl()
111 {
112     QFile file(filename);
113     if (!file.open(QIODevice::ReadOnly))
114     {
115         emit error_missing_file();
116         return NULL;
117     }
118
119     // First, try to read the stl as an ASCII file
120     if (file.read(5) == "solid")
121     {
122         file.readLine(); // skip solid name
123         const auto line = file.readLine().trimmed();
124         if (line.startsWith("facet") ||
125             line.startsWith("endsolid"))
126         {
127             file.seek(0);
128             return read_stl_ascii(file);
129         }
130         // Otherwise, this STL is a binary stl but contains 'solid' as
131         // the first five characters.  This is a bad life choice, but
132         // we can gracefully handle it by falling through to the binary
133         // STL reader below.
134     }
135
136     file.seek(0);
137     return read_stl_binary(file);
138 }
139
140 Mesh* Loader::read_stl_binary(QFile& file)
141 {
142     QDataStream data(&file);
143     data.setByteOrder(QDataStream::LittleEndian);
144     data.setFloatingPointPrecision(QDataStream::SinglePrecision);
145
146     // Load the triangle count from the .stl file
147     file.seek(80);
148     uint32_t tri_count;
149     data >> tri_count;
150
151     // Verify that the file is the right size
152     if (file.size() != 84 + tri_count*50)
153     {
154         emit error_bad_stl();
155         return NULL;
156     }
157
158     // Extract vertices into an array of xyz, unsigned pairs
159     QVector<Vertex> verts(tri_count*3);
160
161     // Dummy array, because readRawData is faster than skipRawData
162     std::unique_ptr<uint8_t[]> buffer(new uint8_t[tri_count * 50]);
163     data.readRawData((char*)buffer.get(), tri_count * 50);
164
165     // Store vertices in the array, processing one triangle at a time.
166     auto b = buffer.get() + 3 * sizeof(float);
167     for (auto v=verts.begin(); v != verts.end(); v += 3)
168     {
169         // Load vertex data from .stl file into vertices
170         for (unsigned i=0; i < 3; ++i)
171         {
172             qFromLittleEndian<float>(b, 3, &v[i]);
173             b += 3 * sizeof(float);
174         }
175
176         // Skip face attribute and next face's normal vector
177         b += 3 * sizeof(float) + sizeof(uint16_t);
178     }
179
180     return mesh_from_verts(tri_count, verts);
181 }
182
183 Mesh* Loader::read_stl_ascii(QFile& file)
184 {
185     file.readLine();
186     uint32_t tri_count = 0;
187     QVector<Vertex> verts(tri_count*3);
188
189     bool okay = true;
190     while (!file.atEnd() && okay)
191     {
192         const auto line = file.readLine().simplified();
193         if (line.startsWith("endsolid"))
194         {
195             break;
196         }
197         else if (!line.startsWith("facet normal") ||
198                  !file.readLine().simplified().startsWith("outer loop"))
199         {
200             okay = false;
201             break;
202         }
203
204         for (int i=0; i < 3; ++i)
205         {
206             auto line = file.readLine().simplified().split(' ');
207             if (line[0] != "vertex")
208             {
209                 okay = false;
210                 break;
211             }
212             const float x = line[1].toFloat(&okay);
213             const float y = line[2].toFloat(&okay);
214             const float z = line[3].toFloat(&okay);
215             verts.push_back(Vertex(x, y, z));
216         }
217         if (!file.readLine().trimmed().startsWith("endloop") ||
218             !file.readLine().trimmed().startsWith("endfacet"))
219         {
220             okay = false;
221             break;
222         }
223         tri_count++;
224     }
225
226     if (okay)
227     {
228         return mesh_from_verts(tri_count, verts);
229     }
230     else
231     {
232         emit error_bad_stl();
233         return NULL;
234     }
235 }
236