10 ////////////////////////////////////////////////////////////////////////////////
12 Mesh::Mesh(std::vector<GLfloat> v, std::vector<GLuint> i)
13 : vertices(v), indices(i)
18 float Mesh::min(size_t start) const
20 float v = vertices[start];
21 for (size_t i=start; i < vertices.size(); i += 3)
23 v = fmin(v, vertices[i]);
28 float Mesh::max(size_t start) const
30 float v = vertices[start];
31 for (size_t i=start; i < vertices.size(); i += 3)
33 v = fmax(v, vertices[i]);
37 ////////////////////////////////////////////////////////////////////////////////
42 bool operator!=(const Vec3& rhs) const
44 return x != rhs.x || y != rhs.y || z != rhs.z;
46 bool operator<(const Vec3& rhs) const
48 if (x != rhs.x) return x < rhs.x;
49 else if (y != rhs.y) return y < rhs.y;
50 else if (z != rhs.z) return z < rhs.z;
55 typedef std::pair<Vec3, GLuint> Vec3i;
57 ////////////////////////////////////////////////////////////////////////////////
59 Mesh* Mesh::load_stl(const QString& filename)
62 file.open(QIODevice::ReadOnly);
64 QDataStream data(&file);
65 data.setByteOrder(QDataStream::LittleEndian);
66 data.setFloatingPointPrecision(QDataStream::SinglePrecision);
68 // Skip .stl file header
71 // Load the triangle count from the .stl file
75 // Extract vertices into an array of xyz, unsigned pairs
76 QVector<Vec3i> verts(tri_count*3);
78 // Dummy array, because readRawData is faster than skipRawData
79 char buffer[sizeof(float)*3];
81 // Store vertices in the array, processing one triangle at a time.
82 for (auto v=verts.begin(); v != verts.end(); v += 3)
84 // Skip face's normal vector
85 data.readRawData(buffer, 3*sizeof(float));
87 // Load vertex data from .stl file into vertices
88 data >> v[0].first.x >> v[0].first.y >> v[0].first.z;
89 data >> v[1].first.x >> v[1].first.y >> v[1].first.z;
90 data >> v[2].first.x >> v[2].first.y >> v[2].first.z;
92 // Skip face attribute
93 data.readRawData(buffer, sizeof(uint16_t));
96 // Save indicies as the second element in the array
97 // (so that we can reconstruct triangle order after sorting)
98 for (size_t i=0; i < tri_count*3; ++i)
103 // Sort the set of vertices (to deduplicate)
104 std::sort(verts.begin(), verts.end());
106 // This vector will store triangles as sets of 3 indices
107 std::vector<GLuint> indices(tri_count*3);
109 // Go through the sorted vertex list, deduplicating and creating
110 // an indexed geometry representation for the triangles.
111 // Unique vertices are moved so that they occupy the first vertex_count
112 // positions in the verts array.
113 size_t vertex_count = 0;
116 if (!vertex_count || v.first != verts[vertex_count-1].first)
118 verts[vertex_count++] = v;
120 indices[v.second] = vertex_count - 1;
122 verts.resize(vertex_count);
124 std::vector<GLfloat> flat_verts;
125 flat_verts.reserve(vertex_count*3);
128 flat_verts.push_back(v.first.x);
129 flat_verts.push_back(v.first.y);
130 flat_verts.push_back(v.first.z);
133 return new Mesh(flat_verts, indices);