-
-
Notifications
You must be signed in to change notification settings - Fork 919
Expand file tree
/
Copy pathMeshGroup.cpp
More file actions
576 lines (513 loc) · 18.3 KB
/
MeshGroup.cpp
File metadata and controls
576 lines (513 loc) · 18.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
// Copyright (c) 2023 UltiMaker
// CuraEngine is released under the terms of the AGPLv3 or higher
#include "MeshGroup.h"
#include <filesystem>
#include <fstream>
#include <limits>
#include <png.h>
#include <rapidjson/document.h>
#include <rapidjson/error/en.h>
#include <rapidjson/memorystream.h>
#include <regex>
#include <stdio.h>
#include <string.h>
#include <fmt/format.h>
#include <range/v3/view/enumerate.hpp>
#include <scripta/logger.h>
#include <spdlog/spdlog.h>
#include "settings/types/Ratio.h" //For the shrinkage percentage and scale factor.
#include "utils/Matrix4x3D.h" //To transform the input meshes for shrinkage compensation and to align in command line mode.
#include "utils/MeshUtils.h"
#include "utils/Point2F.h"
#include "utils/Point3F.h" //To accept incoming meshes with floating point vertices.
#include "utils/gettime.h"
#include "utils/section_type.h"
#include "utils/string.h"
namespace cura
{
FILE* binaryMeshBlob = nullptr;
/* Custom fgets function to support Mac line-ends in Ascii STL files. OpenSCAD produces this when used on Mac */
void* fgets_(char* ptr, size_t len, FILE* f)
{
while (len && fread(ptr, 1, 1, f) > 0)
{
if (*ptr == '\n' || *ptr == '\r')
{
*ptr = '\0';
return ptr;
}
ptr++;
len--;
}
return nullptr;
}
Point3LL MeshGroup::min() const
{
if (meshes.size() < 1)
{
return Point3LL(0, 0, 0);
}
Point3LL ret(std::numeric_limits<coord_t>::max(), std::numeric_limits<coord_t>::max(), std::numeric_limits<coord_t>::max());
for (const Mesh& mesh : meshes)
{
if (mesh.settings_.get<bool>("infill_mesh") || mesh.settings_.get<bool>("cutting_mesh")
|| mesh.settings_.get<bool>("anti_overhang_mesh")) // Don't count pieces that are not printed.
{
continue;
}
Point3LL v = mesh.min();
ret.x_ = std::min(ret.x_, v.x_);
ret.y_ = std::min(ret.y_, v.y_);
ret.z_ = std::min(ret.z_, v.z_);
}
return ret;
}
Point3LL MeshGroup::max() const
{
if (meshes.size() < 1)
{
return Point3LL(0, 0, 0);
}
Point3LL ret(std::numeric_limits<int32_t>::min(), std::numeric_limits<int32_t>::min(), std::numeric_limits<int32_t>::min());
for (const Mesh& mesh : meshes)
{
if (mesh.settings_.get<bool>("infill_mesh") || mesh.settings_.get<bool>("cutting_mesh")
|| mesh.settings_.get<bool>("anti_overhang_mesh")) // Don't count pieces that are not printed.
{
continue;
}
Point3LL v = mesh.max();
ret.x_ = std::max(ret.x_, v.x_);
ret.y_ = std::max(ret.y_, v.y_);
ret.z_ = std::max(ret.z_, v.z_);
}
return ret;
}
void MeshGroup::clear()
{
for (Mesh& m : meshes)
{
m.clear();
}
}
void MeshGroup::finalize()
{
// If the machine settings have been supplied, offset the given position vertices to the center of vertices (0,0,0) is at the bed center.
Point3LL meshgroup_offset(0, 0, 0);
if (! settings.get<bool>("machine_center_is_zero"))
{
meshgroup_offset.x_ = settings.get<coord_t>("machine_width") / 2;
meshgroup_offset.y_ = settings.get<coord_t>("machine_depth") / 2;
}
// If a mesh position was given, put the mesh at this position in 3D space.
for (Mesh& mesh : meshes)
{
Point3LL mesh_offset(mesh.settings_.get<coord_t>("mesh_position_x"), mesh.settings_.get<coord_t>("mesh_position_y"), mesh.settings_.get<coord_t>("mesh_position_z"));
if (mesh.settings_.get<bool>("center_object"))
{
Point3LL object_min = mesh.min();
Point3LL object_max = mesh.max();
Point3LL object_size = object_max - object_min;
mesh_offset += Point3LL(-object_min.x_ - object_size.x_ / 2, -object_min.y_ - object_size.y_ / 2, -object_min.z_);
}
mesh.translate(mesh_offset + meshgroup_offset);
}
scaleFromBottom(
settings.get<Ratio>("material_shrinkage_percentage_xy"),
settings.get<Ratio>("material_shrinkage_percentage_z")); // Compensate for the shrinkage of the material.
for (const auto& [idx, mesh] : meshes | ranges::views::enumerate)
{
scripta::log(fmt::format("mesh_{}", idx), mesh, SectionType::NA);
}
}
void MeshGroup::scaleFromBottom(const Ratio factor_xy, const Ratio factor_z)
{
const Point3LL center = (max() + min()) / 2;
const Point3LL origin(center.x_, center.y_, 0);
const Matrix4x3D transformation = Matrix4x3D::scale(factor_xy, factor_xy, factor_z, origin);
for (Mesh& mesh : meshes)
{
mesh.transform(transformation);
}
}
bool loadMeshSTL_ascii(Mesh* mesh, const char* filename, const Matrix4x3D& matrix)
{
FILE* f = fopen(filename, "rt");
char buffer[1024];
Point3F vertex;
int n = 0;
Point3LL v0(0, 0, 0), v1(0, 0, 0), v2(0, 0, 0);
while (fgets_(buffer, sizeof(buffer), f))
{
if (sscanf(buffer, " vertex %f %f %f", &vertex.x_, &vertex.y_, &vertex.z_) == 3)
{
n++;
switch (n)
{
case 1:
v0 = matrix.apply(vertex.toPoint3d());
break;
case 2:
v1 = matrix.apply(vertex.toPoint3d());
break;
case 3:
v2 = matrix.apply(vertex.toPoint3d());
mesh->addFace(v0, v1, v2);
n = 0;
break;
}
}
}
fclose(f);
mesh->finish();
return true;
}
bool loadMeshSTL_binary(Mesh* mesh, const char* filename, const Matrix4x3D& matrix, const std::vector<Point2F>* uv_coordinates = nullptr)
{
FILE* f = fopen(filename, "rb");
fseek(f, 0L, SEEK_END);
long long file_size = ftell(f); // The file size is the position of the cursor after seeking to the end.
rewind(f); // Seek back to start.
size_t face_count = (file_size - 80 - sizeof(uint32_t)) / 50; // Subtract the size of the header. Every face uses exactly 50 bytes.
char buffer[80];
// Skip the header
if (fread(buffer, 80, 1, f) != 1)
{
fclose(f);
return false;
}
uint32_t reported_face_count;
// Read the face count. We'll use it as a sort of redundancy code to check for file corruption.
if (fread(&reported_face_count, sizeof(uint32_t), 1, f) != 1)
{
fclose(f);
return false;
}
if (reported_face_count != face_count)
{
spdlog::warn("Face count reported by file ({}) is not equal to actual face count ({}). File could be corrupt!", reported_face_count, face_count);
}
// For each face read:
// float(x,y,z) = normal, float(X,Y,Z)*3 = vertexes, uint16_t = flags
// Every Face is 50 Bytes: Normal(3*float), Vertices(9*float), 2 Bytes Spacer
mesh->faces_.reserve(face_count);
mesh->vertices_.reserve(face_count);
size_t vertex_index = 0;
for (size_t i = 0; i < face_count; i++)
{
if (fread(buffer, 50, 1, f) != 1)
{
fclose(f);
return false;
}
float* v = reinterpret_cast<float*>(buffer) + 3;
Point3LL v0 = matrix.apply(Point3F(v[0], v[1], v[2]).toPoint3d());
Point3LL v1 = matrix.apply(Point3F(v[3], v[4], v[5]).toPoint3d());
Point3LL v2 = matrix.apply(Point3F(v[6], v[7], v[8]).toPoint3d());
// Handle UV coordinates if provided
if (uv_coordinates && vertex_index + 2 < uv_coordinates->size())
{
std::optional<Point2F> uv0 = (*uv_coordinates)[vertex_index];
std::optional<Point2F> uv1 = (*uv_coordinates)[vertex_index + 1];
std::optional<Point2F> uv2 = (*uv_coordinates)[vertex_index + 2];
vertex_index += 3;
mesh->addFace(v0, v1, v2, uv0, uv1, uv2);
}
else
{
mesh->addFace(v0, v1, v2);
}
}
fclose(f);
mesh->finish();
return true;
}
bool loadMeshSTL(Mesh* mesh, const char* filename, const Matrix4x3D& matrix)
{
FILE* f = fopen(filename, "rb");
if (f == nullptr)
{
return false;
}
// assign filename to mesh_name
mesh->mesh_name_ = filename;
// Skip any whitespace at the beginning of the file.
unsigned long long num_whitespace = 0; // Number of whitespace characters.
unsigned char whitespace;
if (fread(&whitespace, 1, 1, f) != 1)
{
fclose(f);
return false;
}
while (isspace(whitespace))
{
num_whitespace++;
if (fread(&whitespace, 1, 1, f) != 1)
{
fclose(f);
return false;
}
}
fseek(f, num_whitespace, SEEK_SET); // Seek to the place after all whitespace (we may have just read too far).
char buffer[6];
if (fread(buffer, 5, 1, f) != 1)
{
fclose(f);
return false;
}
fclose(f);
buffer[5] = '\0';
if (stringcasecompare(buffer, "solid") == 0)
{
bool load_success = loadMeshSTL_ascii(mesh, filename, matrix);
if (! load_success)
return false;
// This logic is used to handle the case where the file starts with
// "solid" but is a binary file.
if (mesh->faces_.size() < 1)
{
mesh->clear();
return loadMeshSTL_binary(mesh, filename, matrix);
}
return true;
}
return loadMeshSTL_binary(mesh, filename, matrix);
}
bool loadMeshOBJ(Mesh* mesh, const std::string& filename, const Matrix4x3D& matrix)
{
std::ifstream file(filename);
if (! file.is_open())
{
spdlog::error("Could not open OBJ file: {}", filename);
return false;
}
std::vector<Point3LL> vertices;
std::vector<Point2F> uv_coordinates;
std::string line;
std::regex main_regex(R"((v|vt|f)\s+(.*))");
std::regex vertex_regex(R"(([-+]?[0-9]*\.?[0-9]+)\s+([-+]?[0-9]*\.?[0-9]+)\s+([-+]?[0-9]*\.?[0-9]+))");
std::regex uv_regex(R"(([-+]?[0-9]*\.?[0-9]+)\s+([-+]?[0-9]*\.?[0-9]+))");
std::regex face_indices_regex(R"((\d+)(?:\/(\d*))?(?:\/(?:\d*))?)");
auto get_uv_coordinates = [&uv_coordinates](std::optional<size_t> uv_index) -> std::optional<Point2F>
{
if (uv_index.has_value() && uv_index.value() < uv_coordinates.size())
{
return std::make_optional(uv_coordinates[uv_index.value()]);
}
return std::nullopt;
};
while (std::getline(file, line))
{
std::smatch matches;
if (! std::regex_match(line, matches, main_regex))
{
// Unrecognized line, just skip
continue;
}
const std::string line_identifier = matches[1].str();
const std::string payload = matches[2].str();
if (line_identifier == "v" && std::regex_match(payload, matches, vertex_regex))
{
const float x = std::stof(matches[1].str());
const float y = std::stof(matches[2].str());
const float z = std::stof(matches[3].str());
vertices.push_back(matrix.apply(Point3D(x, y, z)));
}
else if (line_identifier == "vt" && std::regex_match(payload, matches, uv_regex))
{
const float u = std::stof(matches[1].str());
const float v = std::stof(matches[2].str());
uv_coordinates.push_back(Point2F(u, v));
}
else if (line_identifier == "f")
{
struct Vertex
{
size_t index;
std::optional<size_t> uv_index;
};
std::vector<Vertex> vertex_indices;
std::sregex_iterator it(payload.begin(), payload.end(), face_indices_regex);
std::sregex_iterator end;
while (it != end)
{
std::smatch vertex_match = *it;
if (vertex_match.size() >= 2)
{
Vertex vertex;
vertex.index = std::stoul(vertex_match[1].str()) - 1;
if (vertex_match[2].matched && vertex_match[2].length() > 0)
{
vertex.uv_index = std::stoul(vertex_match[2].str()) - 1;
}
vertex_indices.push_back(vertex);
}
++it;
}
// Triangulate the face
if (vertex_indices.size() >= 3)
{
for (size_t i = 1; i < vertex_indices.size() - 1; ++i)
{
const Vertex& v0 = vertex_indices[0];
const Vertex& v1 = vertex_indices[i];
const Vertex& v2 = vertex_indices[i + 1];
if (v0.index < vertices.size() && v1.index < vertices.size() && v2.index < vertices.size())
{
mesh->addFace(
vertices[v0.index],
vertices[v1.index],
vertices[v2.index],
get_uv_coordinates(v0.uv_index),
get_uv_coordinates(v1.uv_index),
get_uv_coordinates(v2.uv_index));
}
}
}
}
}
mesh->finish();
return ! mesh->faces_.empty();
}
/*!
* Load UV coordinates from a binary file and store them for later application to mesh faces.
*
* @param uv_filename The path to the binary UV file
* @param uv_coordinates Vector to store the loaded UV coordinates
* @return true if UV coordinates were loaded successfully, false otherwise
*/
bool loadUVCoordinatesFromFile(const std::string& uv_filename, std::vector<Point2F>& uv_coordinates)
{
if (! std::filesystem::exists(uv_filename))
{
return false; // File doesn't exist, not an error
}
std::ifstream file(uv_filename, std::ios::binary);
if (! file.is_open())
{
spdlog::warn("Failed to open UV file: {}", uv_filename);
return false;
}
// Read vertex count (uint32)
uint32_t vertex_count;
if (! file.read(reinterpret_cast<char*>(&vertex_count), sizeof(uint32_t)))
{
spdlog::warn("Failed to read vertex count from UV file: {}", uv_filename);
return false;
}
// Read UV coordinates (2 floats per vertex)
uv_coordinates.resize(vertex_count);
const std::streamsize uv_data_size = vertex_count * 2 * sizeof(float);
if (! file.read(reinterpret_cast<char*>(uv_coordinates.data()), uv_data_size))
{
spdlog::warn("Failed to read UV coordinates from file: {}", uv_filename);
return false;
}
spdlog::info("Loaded {} UV coordinates from: {}", vertex_count, uv_filename);
return true;
}
bool loadMeshSTL_with_uv(Mesh* mesh, const char* filename, const Matrix4x3D& matrix, const std::vector<Point2F>& uv_coordinates)
{
FILE* f = fopen(filename, "rb");
if (f == nullptr)
{
return false;
}
// assign filename to mesh_name
mesh->mesh_name_ = filename;
// Skip any whitespace at the beginning of the file.
unsigned long long num_whitespace = 0; // Number of whitespace characters.
unsigned char whitespace;
if (fread(&whitespace, 1, 1, f) != 1)
{
fclose(f);
return false;
}
while (isspace(whitespace))
{
num_whitespace++;
if (fread(&whitespace, 1, 1, f) != 1)
{
fclose(f);
return false;
}
}
fseek(f, num_whitespace, SEEK_SET); // Seek to the place after all whitespace (we may have just read too far).
char buffer[6];
if (fread(buffer, 5, 1, f) != 1)
{
fclose(f);
return false;
}
fclose(f);
buffer[5] = '\0';
if (stringcasecompare(buffer, "solid") == 0)
{
// ASCII STL with UV coordinates not currently supported
spdlog::warn("ASCII STL with UV coordinates not supported, use binary STL: {}", filename);
return false;
}
return loadMeshSTL_binary(mesh, filename, matrix, &uv_coordinates);
}
bool loadMeshIntoMeshGroup(MeshGroup* meshgroup, const char* filename, const Matrix4x3D& transformation, Settings& object_parent_settings)
{
TimeKeeper load_timer;
const char* ext = strrchr(filename, '.');
if (ext && (strcmp(ext, ".stl") == 0 || strcmp(ext, ".STL") == 0))
{
Mesh mesh(object_parent_settings);
// Check for corresponding UV and PNG files
std::string filename_str(filename);
std::string base_filename = filename_str.substr(0, filename_str.find_last_of('.'));
std::string uv_filename = base_filename + ".uv";
std::string texture_filename = base_filename + ".png";
std::vector<Point2F> uv_coordinates;
bool has_uv = loadUVCoordinatesFromFile(uv_filename, uv_coordinates);
bool load_success = false;
if (has_uv)
{
spdlog::info("Loading STL with UV coordinates from: {}", uv_filename);
load_success = loadMeshSTL_with_uv(&mesh, filename, transformation, uv_coordinates);
}
else
{
load_success = loadMeshSTL(&mesh, filename, transformation);
}
if (load_success) // Load it! If successful...
{
// Try to load the PNG texture if it exists
if (std::filesystem::exists(texture_filename))
{
spdlog::info("Found texture file: {}", texture_filename);
if (MeshUtils::loadTextureFromFile(mesh, texture_filename))
{
spdlog::info("Successfully loaded texture from: {}", texture_filename);
}
else
{
spdlog::warn("Failed to load texture from: {}", texture_filename);
}
}
meshgroup->meshes.push_back(mesh);
spdlog::info("loading '{}' took {:03.3f} seconds", filename, load_timer.restart());
return true;
}
spdlog::warn("loading STL '{}' failed", filename);
return false;
}
if (ext && (strcmp(ext, ".obj") == 0 || strcmp(ext, ".OBJ") == 0))
{
Mesh mesh(object_parent_settings);
if (loadMeshOBJ(&mesh, filename, transformation)) // Load it! If successful...
{
meshgroup->meshes.push_back(mesh);
spdlog::info("loading '{}' took {:03.3f} seconds", filename, load_timer.restart());
return true;
}
spdlog::warn("loading OBJ '{}' failed", filename);
return false;
}
spdlog::warn("Unable to recognize the extension of the file. Currently only .stl and .STL are supported.");
return false;
}
} // namespace cura