./
Coverage:
low: ≥ 0%
medium: ≥ 75.0%
high: ≥ 90.0%
Lines:
216 / 222
97.3%
Branches:
132 / 153
86.3%
Functions:
14 / 14
100.0%

src/mesh/io/gltf.cpp
Line Branch Exec Source
1 // SPDX-License-Identifier: BSD-3-Clause
2
3 #include "mesh/io/formats.h"
4
5 #define CGLTF_IMPLEMENTATION
6 #define CGLTF_WRITE_IMPLEMENTATION
7 #pragma GCC diagnostic push
8 #pragma GCC diagnostic ignored "-Wformat-truncation"
9 #include <cgltf_write.h>
10 #pragma GCC diagnostic pop
11
12 #include <algorithm>
13 #include <cstring>
14 #include <deque>
15 #include <limits>
16 #include <memory>
17 #include <stdexcept>
18 #include <string>
19
20 namespace terraingen::detail {
21
22 178 std::array<double, 4> RotationQuaternion(const std::array<double, 9>& r) {
23 178 const double trace = r[0] + r[4] + r[8];
24
2/2
✓ Branch 0 taken 134 times.
✓ Branch 1 taken 44 times.
178 if (trace > 0.0) {
25 134 const double s = 2.0 * std::sqrt(1.0 + trace);
26 134 return {(r[7] - r[5]) / s, (r[2] - r[6]) / s, (r[3] - r[1]) / s, 0.25 * s};
27 }
28
3/4
✓ Branch 0 taken 1 time.
✓ Branch 1 taken 43 times.
✓ Branch 2 taken 1 time.
✗ Branch 3 not taken.
44 if (r[0] > r[4] && r[0] > r[8]) {
29 1 const double s = 2.0 * std::sqrt(1.0 + r[0] - r[4] - r[8]);
30 1 return {0.25 * s, (r[1] + r[3]) / s, (r[2] + r[6]) / s, (r[7] - r[5]) / s};
31 }
32
2/2
✓ Branch 0 taken 42 times.
✓ Branch 1 taken 1 time.
43 if (r[4] > r[8]) {
33 42 const double s = 2.0 * std::sqrt(1.0 + r[4] - r[0] - r[8]);
34 42 return {(r[1] + r[3]) / s, 0.25 * s, (r[5] + r[7]) / s, (r[2] - r[6]) / s};
35 }
36 1 const double s = 2.0 * std::sqrt(1.0 + r[8] - r[0] - r[4]);
37 1 return {(r[2] + r[6]) / s, (r[5] + r[7]) / s, 0.25 * s, (r[3] - r[1]) / s};
38 }
39
40 namespace {
41
42 /// The cgltf document of a scene: every array sized before any pointer into it is taken, and the
43 /// binary buffer every accessor reads.
44 class GltfDocument {
45 public:
46 26 GltfDocument(const std::vector<SceneMesh>& meshes, const std::vector<SceneNode>& nodes)
47
2/2
✓ Branch 1 taken 26 times.
✓ Branch 4 taken 26 times.
26 : m_views(ViewCount(meshes)), m_accessors(m_views.size()), m_attributes(2 * meshes.size()),
48
3/3
✓ Branch 1 taken 26 times.
✓ Branch 4 taken 26 times.
✓ Branch 7 taken 26 times.
26 m_materials(meshes.size()), m_primitives(meshes.size()), m_meshes(meshes.size()),
49
3/3
✓ Branch 1 taken 26 times.
✓ Branch 4 taken 26 times.
✓ Branch 7 taken 26 times.
52 m_nodes(nodes.size()), m_roots(nodes.size()) {
50 26 std::size_t view = 0;
51
2/2
✓ Branch 0 taken 150 times.
✓ Branch 1 taken 26 times.
176 for (std::size_t m = 0; m < meshes.size(); ++m) {
52
1/1
✓ Branch 1 taken 150 times.
150 AddMesh(m, meshes[m], view);
53 }
54
2/2
✓ Branch 0 taken 173 times.
✓ Branch 1 taken 26 times.
199 for (std::size_t n = 0; n < nodes.size(); ++n) {
55 173 AddNode(n, nodes[n]);
56 }
57 26 }
58
59 /// Writes the document as .glb (`binary`), or as .gltf with its buffer in a .bin beside it.
60 26 void Write(const std::filesystem::path& path, bool binary) {
61 26 cgltf_buffer buffer{};
62
2/2
✓ Branch 0 taken 3 times.
✓ Branch 1 taken 23 times.
26 buffer.size = m_binary.size();
63
2/2
✓ Branch 0 taken 3 times.
✓ Branch 1 taken 23 times.
26 std::string bin;
64
2/2
✓ Branch 0 taken 3 times.
✓ Branch 1 taken 23 times.
26 if (!binary) {
65
1/1
✓ Branch 1 taken 3 times.
3 std::filesystem::path binPath = path;
66
2/2
✓ Branch 1 taken 3 times.
✓ Branch 4 taken 3 times.
3 binPath.replace_extension(".bin");
67
1/1
✓ Branch 1 taken 3 times.
3 WriteFile(binPath, m_binary);
68
1/1
✓ Branch 1 taken 3 times.
6 bin = binPath.filename().string();
69 3 buffer.uri = bin.data();
70 3 }
71
2/2
✓ Branch 0 taken 437 times.
✓ Branch 1 taken 26 times.
463 for (cgltf_buffer_view& view : m_views) {
72 437 view.buffer = &buffer;
73 }
74 26 cgltf_scene scene{};
75
1/1
✓ Branch 1 taken 26 times.
26 scene.nodes = m_roots.data();
76
1/1
✓ Branch 1 taken 26 times.
26 scene.nodes_count = m_roots.size();
77 26 cgltf_data data{};
78
1/1
✓ Branch 1 taken 26 times.
27 std::string version = "2.0";
79
1/1
✓ Branch 1 taken 26 times.
27 std::string generator = "TerrainGen";
80
2/2
✓ Branch 0 taken 23 times.
✓ Branch 1 taken 3 times.
26 data.asset.version = version.data();
81 26 data.asset.generator = generator.data();
82 26 data.buffers = &buffer;
83 26 data.buffers_count = 1;
84
2/2
✓ Branch 0 taken 23 times.
✓ Branch 1 taken 3 times.
26 data.buffer_views = m_views.data();
85
2/2
✓ Branch 0 taken 23 times.
✓ Branch 1 taken 3 times.
26 data.buffer_views_count = m_views.size();
86 26 data.accessors = m_accessors.data();
87 26 data.accessors_count = m_accessors.size();
88 26 data.materials = m_materials.data();
89 26 data.materials_count = m_materials.size();
90 26 data.meshes = m_meshes.data();
91 26 data.meshes_count = m_meshes.size();
92 26 data.nodes = m_nodes.data();
93 26 data.nodes_count = m_nodes.size();
94 26 data.scenes = &scene;
95 26 data.scenes_count = 1;
96 26 data.scene = &scene;
97
2/2
✓ Branch 0 taken 23 times.
✓ Branch 1 taken 3 times.
26 if (binary) {
98 23 data.bin = m_binary.data();
99 23 data.bin_size = m_binary.size();
100 }
101 26 cgltf_options options{};
102
2/2
✓ Branch 0 taken 3 times.
✓ Branch 1 taken 23 times.
26 options.type = binary ? cgltf_file_type_glb : cgltf_file_type_gltf;
103
4/4
✓ Branch 1 taken 26 times.
✓ Branch 4 taken 26 times.
✓ Branch 7 taken 1 time.
✓ Branch 8 taken 25 times.
27 if (cgltf_write_file(&options, path.string().c_str(), &data) != cgltf_result_success) {
104
2/2
✓ Branch 2 taken 1 time.
✓ Branch 5 taken 1 time.
3 throw std::runtime_error("Cannot write " + path.string());
105 }
106 27 }
107
108 private:
109 26 static std::size_t ViewCount(const std::vector<SceneMesh>& meshes) {
110 26 std::size_t count = 0;
111
2/2
✓ Branch 0 taken 150 times.
✓ Branch 1 taken 26 times.
176 for (const SceneMesh& scene : meshes) {
112
2/2
✓ Branch 0 taken 137 times.
✓ Branch 1 taken 13 times.
287 count += scene.normals.empty() ? 2u : 3u;
113 }
114
1/1
✓ Branch 1 taken 26 times.
26 return count;
115 }
116
117 437 char* Name(const std::string& name) {
118
4/4
✓ Branch 1 taken 150 times.
✓ Branch 4 taken 150 times.
✓ Branch 7 taken 137 times.
✓ Branch 10 taken 137 times.
437 return m_names.emplace_back(name).data();
119 }
120
121 /// Ends a view and its accessor at `view` over the bytes added since `start`.
122 437 cgltf_accessor* AddAccessor(std::size_t& view, std::size_t start, cgltf_buffer_view_type type,
123 cgltf_component_type component, cgltf_type kind,
124 std::size_t count) {
125 437 cgltf_buffer_view& v = m_views[view];
126 437 v.offset = start;
127 437 v.size = m_binary.size() - start;
128 437 v.type = type;
129 437 cgltf_accessor& a = m_accessors[view];
130 437 a.component_type = component;
131 437 a.type = kind;
132 437 a.count = count;
133 437 a.buffer_view = &v;
134 437 ++view;
135 437 return &a;
136 }
137
138 287 cgltf_accessor* AddVectors(std::size_t& view, const std::vector<Vec3d>& vectors, bool bounds) {
139 287 const std::size_t start = m_binary.size();
140 287 constexpr float kInf = std::numeric_limits<float>::infinity();
141 287 std::array<float, 3> low{kInf, kInf, kInf};
142 287 std::array<float, 3> high{-kInf, -kInf, -kInf};
143
2/2
✓ Branch 0 taken 650422 times.
✓ Branch 1 taken 287 times.
650709 for (const Vec3d& vector : vectors) {
144 650422 const Vec3d p = YUp(vector);
145 650422 const std::array<float, 3> stored{static_cast<float>(p.x), static_cast<float>(p.y),
146 650422 static_cast<float>(p.z)};
147
2/2
✓ Branch 0 taken 1951266 times.
✓ Branch 1 taken 650422 times.
2601688 for (std::size_t c = 0; c < 3; ++c) {
148 1951266 Put(m_binary, stored[c]);
149
4/4
✓ Branch 0 taken 12027 times.
✓ Branch 1 taken 1939239 times.
✓ Branch 2 taken 21484 times.
✓ Branch 3 taken 1929782 times.
1963293 low[c] = std::min(low[c], stored[c]);
150
2/2
✓ Branch 0 taken 21484 times.
✓ Branch 1 taken 1929782 times.
1972750 high[c] = std::max(high[c], stored[c]);
151 }
152 }
153 287 cgltf_accessor* accessor =
154 287 AddAccessor(view, start, cgltf_buffer_view_type_vertices, cgltf_component_type_r_32f,
155 cgltf_type_vec3, vectors.size());
156
2/2
✓ Branch 0 taken 150 times.
✓ Branch 1 taken 137 times.
287 if (bounds) {
157 150 accessor->has_min = accessor->has_max = 1;
158 150 std::copy(low.begin(), low.end(), accessor->min);
159 150 std::copy(high.begin(), high.end(), accessor->max);
160 }
161 287 return accessor;
162 }
163
164 150 void AddMesh(std::size_t m, const SceneMesh& scene, std::size_t& view) {
165 150 cgltf_attribute* attributes = &m_attributes[2 * m];
166
2/2
✓ Branch 2 taken 137 times.
✓ Branch 3 taken 13 times.
300 attributes[0] = {Name("POSITION"), cgltf_attribute_type_position, 0,
167
1/1
✓ Branch 1 taken 150 times.
150 AddVectors(view, scene.mesh.positions, true)};
168 150 std::size_t count = 1;
169
2/2
✓ Branch 0 taken 137 times.
✓ Branch 1 taken 13 times.
150 if (!scene.normals.empty()) {
170 274 attributes[1] = {Name("NORMAL"), cgltf_attribute_type_normal, 0,
171
1/1
✓ Branch 1 taken 137 times.
137 AddVectors(view, scene.normals, false)};
172 137 count = 2;
173 }
174 150 const std::size_t start = m_binary.size();
175
2/2
✓ Branch 0 taken 835324 times.
✓ Branch 1 taken 150 times.
835474 for (const auto& t : scene.mesh.triangles) {
176
2/2
✓ Branch 0 taken 2505972 times.
✓ Branch 1 taken 835324 times.
3341296 for (const std::uint32_t v : t) {
177 2505972 Put(m_binary, v);
178 }
179 }
180 150 cgltf_material& material = m_materials[m];
181 150 material.name = Name(scene.material.name);
182 150 material.has_pbr_metallic_roughness = 1;
183 150 auto& pbr = material.pbr_metallic_roughness;
184
2/2
✓ Branch 0 taken 450 times.
✓ Branch 1 taken 150 times.
600 for (std::size_t c = 0; c < 3; ++c) {
185 450 pbr.base_color_factor[c] = static_cast<float>(scene.material.color[c]);
186 }
187 150 pbr.base_color_factor[3] = 1.0f;
188 150 pbr.metallic_factor = 0.0f;
189 150 pbr.roughness_factor = 1.0f;
190 150 cgltf_primitive& primitive = m_primitives[m];
191 150 primitive.type = cgltf_primitive_type_triangles;
192 300 primitive.indices =
193 150 AddAccessor(view, start, cgltf_buffer_view_type_indices, cgltf_component_type_r_32u,
194 150 cgltf_type_scalar, 3 * scene.mesh.triangles.size());
195 150 primitive.material = &material;
196 150 primitive.attributes = attributes;
197 150 primitive.attributes_count = count;
198 150 m_meshes[m].primitives = &primitive;
199 150 m_meshes[m].primitives_count = 1;
200 150 }
201
202 173 void AddNode(std::size_t n, const SceneNode& node) {
203 173 cgltf_node& out = m_nodes[n];
204 173 out.mesh = &m_meshes[node.mesh];
205 173 const auto q = RotationQuaternion(YUp(node.pose.rotation));
206 173 const Vec3d t = YUp(node.pose.translation);
207 173 out.has_translation = out.has_rotation = out.has_scale = 1;
208 173 const std::array<double, 3> translation{t.x, t.y, t.z};
209 173 const std::array<double, 3> scale{node.scale.x, node.scale.z, node.scale.y};
210
2/2
✓ Branch 0 taken 519 times.
✓ Branch 1 taken 173 times.
692 for (std::size_t c = 0; c < 3; ++c) {
211 519 out.translation[c] = static_cast<float>(translation[c]);
212 519 out.scale[c] = static_cast<float>(scale[c]);
213 }
214
2/2
✓ Branch 0 taken 692 times.
✓ Branch 1 taken 173 times.
865 for (std::size_t c = 0; c < 4; ++c) {
215 692 out.rotation[c] = static_cast<float>(q[c]);
216 }
217 173 m_roots[n] = &out;
218 173 }
219
220 std::string m_binary;
221 std::deque<std::string> m_names;
222 std::vector<cgltf_buffer_view> m_views;
223 std::vector<cgltf_accessor> m_accessors;
224 std::vector<cgltf_attribute> m_attributes;
225 std::vector<cgltf_material> m_materials;
226 std::vector<cgltf_primitive> m_primitives;
227 std::vector<cgltf_mesh> m_meshes;
228 std::vector<cgltf_node> m_nodes;
229 std::vector<cgltf_node*> m_roots;
230 };
231
232 /// The position accessor of `primitive`, or null.
233 74 const cgltf_accessor* PositionAccessor(const cgltf_primitive& primitive) {
234 74 const cgltf_accessor* positions = nullptr;
235
2/2
✓ Branch 0 taken 141 times.
✓ Branch 1 taken 74 times.
215 for (std::size_t a = 0; a < primitive.attributes_count; ++a) {
236
2/2
✓ Branch 0 taken 74 times.
✓ Branch 1 taken 67 times.
141 if (primitive.attributes[a].type == cgltf_attribute_type_position) {
237 74 positions = primitive.attributes[a].data;
238 }
239 }
240 74 return positions;
241 }
242
243 /// Adds the vertices of `positions`, placed by the column-major `world` transform, and the
244 /// triangles of `primitive` to `read`.
245 74 void AppendPrimitive(const cgltf_primitive& primitive, const cgltf_accessor& positions,
246 const cgltf_float (&world)[16], SceneMesh& read) {
247 74 const auto offset = static_cast<std::uint32_t>(read.mesh.positions.size());
248
2/2
✓ Branch 0 taken 14636 times.
✓ Branch 1 taken 74 times.
14710 for (std::size_t v = 0; v < positions.count; ++v) {
249 14636 cgltf_float q[3] = {};
250 14636 cgltf_accessor_read_float(&positions, v, q, 3);
251 58544 const auto axis = [&](std::size_t c) {
252 43908 return static_cast<double>(world[c] * q[0] + world[4 + c] * q[1] + world[8 + c] * q[2] +
253 43908 world[12 + c]);
254 14636 };
255 14636 read.mesh.positions.push_back(ZUp({axis(0), axis(1), axis(2)}));
256 }
257
1/2
✓ Branch 0 taken 74 times.
✗ Branch 1 not taken.
74 const std::size_t count = primitive.indices ? primitive.indices->count : positions.count;
258
2/2
✓ Branch 0 taken 24732 times.
✓ Branch 1 taken 74 times.
24806 for (std::size_t i = 0; i + 2 < count; i += 3) {
259 24732 std::array<std::uint32_t, 3> triangle{};
260
2/2
✓ Branch 0 taken 74196 times.
✓ Branch 1 taken 24732 times.
98928 for (std::size_t c = 0; c < 3; ++c) {
261 74196 const std::size_t index =
262
1/2
✓ Branch 0 taken 74196 times.
✗ Branch 1 not taken.
74196 primitive.indices ? cgltf_accessor_read_index(primitive.indices, i + c) : i + c;
263 74196 triangle[c] = offset + static_cast<std::uint32_t>(index);
264 }
265 24732 read.mesh.triangles.push_back(triangle);
266 }
267 74 }
268
269 /// The name and base color of a glTF material.
270 14 MeshMaterial ReadMaterial(const cgltf_material& material) {
271 14 MeshMaterial read;
272
2/3
✓ Branch 0 taken 14 times.
✗ Branch 1 not taken.
✓ Branch 3 taken 14 times.
28 read.name = material.name ? material.name : "default";
273
2/2
✓ Branch 0 taken 42 times.
✓ Branch 1 taken 14 times.
56 for (std::size_t c = 0; c < 3; ++c) {
274 42 read.color[c] = static_cast<double>(material.pbr_metallic_roughness.base_color_factor[c]);
275 }
276 14 return read;
277 }
278
279 /// Adds the triangles of `node` and its children, placed by their world transforms, to `read`.
280 74 void AppendNodeTriangles(const cgltf_node& node, SceneMesh& read) {
281
1/2
✓ Branch 0 taken 74 times.
✗ Branch 1 not taken.
74 if (node.mesh != nullptr) {
282 74 cgltf_float world[16];
283 74 cgltf_node_transform_world(&node, world);
284
2/2
✓ Branch 1 taken 74 times.
✓ Branch 2 taken 74 times.
148 for (std::size_t p = 0; p < node.mesh->primitives_count; ++p) {
285 74 const cgltf_primitive& primitive = node.mesh->primitives[p];
286 74 const cgltf_accessor* positions = PositionAccessor(primitive);
287
2/4
✓ Branch 0 taken 74 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 74 times.
74 if (primitive.type != cgltf_primitive_type_triangles || positions == nullptr) {
288 ✗ continue;
289 }
290 74 AppendPrimitive(primitive, *positions, world, read);
291
4/6
✓ Branch 0 taken 74 times.
✗ Branch 1 not taken.
✓ Branch 3 taken 74 times.
✗ Branch 4 not taken.
✓ Branch 5 taken 14 times.
✓ Branch 6 taken 60 times.
148 if (primitive.material != nullptr && read.material == MeshMaterial{}) {
292 14 read.material = ReadMaterial(*primitive.material);
293 }
294 }
295 }
296
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 74 times.
74 for (std::size_t c = 0; c < node.children_count; ++c) {
297 ✗ AppendNodeTriangles(*node.children[c], read);
298 }
299 74 }
300
301 } // namespace
302
303 26 void WriteGltf(const std::filesystem::path& path, bool binary, const std::vector<SceneMesh>& meshes,
304 const std::vector<SceneNode>& nodes) {
305
1/1
✓ Branch 2 taken 25 times.
26 GltfDocument(meshes, nodes).Write(path, binary);
306 25 }
307
308 11 SceneMesh ReadGltf(const std::filesystem::path& path) {
309 11 const std::string file = path.string();
310 11 cgltf_options options{};
311 11 cgltf_data* parsed = nullptr;
312
3/3
✓ Branch 1 taken 11 times.
✓ Branch 3 taken 1 time.
✓ Branch 4 taken 10 times.
11 if (cgltf_parse_file(&options, file.c_str(), &parsed) != cgltf_result_success) {
313
2/2
✓ Branch 2 taken 1 time.
✓ Branch 5 taken 1 time.
2 throw std::runtime_error("Cannot read glTF " + file);
314 }
315
1/1
✓ Branch 1 taken 10 times.
10 const std::unique_ptr<cgltf_data, decltype(&cgltf_free)> data(parsed, cgltf_free);
316
3/5
✓ Branch 1 taken 10 times.
✓ Branch 3 taken 10 times.
✗ Branch 4 not taken.
✗ Branch 5 not taken.
✓ Branch 6 taken 10 times.
20 if (cgltf_load_buffers(&options, data.get(), file.c_str()) != cgltf_result_success ||
317 10 cgltf_validate(data.get()) != cgltf_result_success) {
318
0/2
✗ Branch 2 not taken.
✗ Branch 5 not taken.
✗ throw std::runtime_error("Cannot load the buffers of glTF " + file);
319 }
320
1/1
✓ Branch 1 taken 10 times.
10 SceneMesh read;
321
1/2
✓ Branch 0 taken 10 times.
✗ Branch 1 not taken.
10 if (data->scene != nullptr) {
322
2/2
✓ Branch 0 taken 74 times.
✓ Branch 1 taken 10 times.
84 for (std::size_t n = 0; n < data->scene->nodes_count; ++n) {
323
1/1
✓ Branch 1 taken 74 times.
74 AppendNodeTriangles(*data->scene->nodes[n], read);
324 }
325 } else {
326
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ for (std::size_t n = 0; n < data->nodes_count; ++n) {
327
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ if (data->nodes[n].parent == nullptr) {
328
0/1
✗ Branch 1 not taken.
✗ AppendNodeTriangles(data->nodes[n], read);
329 }
330 }
331 }
332
1/2
✓ Branch 0 taken 10 times.
✗ Branch 1 not taken.
10 return read;
333 10 }
334
335 } // namespace terraingen::detail
336