Debian Codegraph @

scene/resources/3d/importer_mesh.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* importer_mesh.cpp */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 #include "importer_mesh.h"
32
33 #include "core/io/marshalls.h"
34 #include "core/math/random_pcg.h"
35 #include "scene/resources/surface_tool.h"
36
37 #ifndef PHYSICS_3D_DISABLED
38 #include "core/math/convex_hull.h"
39 #endif // PHYSICS_3D_DISABLED
40
41 String ImporterMesh::validate_blend_shape_name(const String &p_name) {
42 return p_name.replace_char(':', '_');
43 }
44
45 void ImporterMesh::add_blend_shape(const String &p_name) {
46 ERR_FAIL_COND(surfaces.size() > 0);
47 blend_shapes.push_back(validate_blend_shape_name(p_name));
48 }
49
50 int ImporterMesh::get_blend_shape_count() const {
51 return blend_shapes.size();
52 }
53
54 String ImporterMesh::get_blend_shape_name(int p_blend_shape) const {
55 ERR_FAIL_INDEX_V(p_blend_shape, blend_shapes.size(), String());
56 return blend_shapes[p_blend_shape];
57 }
58
59 void ImporterMesh::set_blend_shape_mode(Mesh::BlendShapeMode p_blend_shape_mode) {
60 blend_shape_mode = p_blend_shape_mode;
61 }
62
63 Mesh::BlendShapeMode ImporterMesh::get_blend_shape_mode() const {
64 return blend_shape_mode;
65 }
66
67 void ImporterMesh::add_surface(Mesh::PrimitiveType p_primitive, const Array &p_arrays, const TypedArray<Array> &p_blend_shapes, const Dictionary &p_lods, const Ref<Material> &p_material, const String &p_surface_name, const uint64_t p_flags) {
68 ERR_FAIL_COND(p_blend_shapes.size() != blend_shapes.size());
69 ERR_FAIL_COND(p_arrays.size() != Mesh::ARRAY_MAX);
70 Surface s;
71 s.primitive = p_primitive;
72 s.arrays = p_arrays;
73 s.name = p_surface_name;
74 s.flags = p_flags;
75
76 Vector<Vector3> vertex_array = p_arrays[Mesh::ARRAY_VERTEX];
77 int vertex_count = vertex_array.size();
78 ERR_FAIL_COND(vertex_count == 0);
79
80 for (int i = 0; i < blend_shapes.size(); i++) {
81 Array bsdata = p_blend_shapes[i];
82 ERR_FAIL_COND(bsdata.size() != Mesh::ARRAY_MAX);
83 Vector<Vector3> vertex_data = bsdata[Mesh::ARRAY_VERTEX];
84 ERR_FAIL_COND(vertex_data.size() != vertex_count);
85 Surface::BlendShape bs;
86 bs.arrays = bsdata;
87 s.blend_shape_data.push_back(bs);
88 }
89
90 for (const KeyValue<Variant, Variant> &kv : p_lods) {
91 ERR_CONTINUE(!kv.key.is_num());
92 Surface::LOD lod;
93 lod.distance = kv.key;
94 lod.indices = kv.value;
95 ERR_CONTINUE(lod.indices.is_empty());
96 s.lods.push_back(lod);
97 }
98
99 s.material = p_material;
100
101 surfaces.push_back(s);
102 mesh.unref();
103 }
104
105 int ImporterMesh::get_surface_count() const {
106 return surfaces.size();
107 }
108
109 Mesh::PrimitiveType ImporterMesh::get_surface_primitive_type(int p_surface) {
110 ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Mesh::PRIMITIVE_MAX);
111 return surfaces[p_surface].primitive;
112 }
113 Array ImporterMesh::get_surface_arrays(int p_surface) const {
114 ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array());
115 return surfaces[p_surface].arrays;
116 }
117 String ImporterMesh::get_surface_name(int p_surface) const {
118 ERR_FAIL_INDEX_V(p_surface, surfaces.size(), String());
119 return surfaces[p_surface].name;
120 }
121 void ImporterMesh::set_surface_name(int p_surface, const String &p_name) {
122 ERR_FAIL_INDEX(p_surface, surfaces.size());
123 surfaces.write[p_surface].name = p_name;
124 mesh.unref();
125 }
126
127 Array ImporterMesh::get_surface_blend_shape_arrays(int p_surface, int p_blend_shape) const {
128 ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array());
129 ERR_FAIL_INDEX_V(p_blend_shape, surfaces[p_surface].blend_shape_data.size(), Array());
130 return surfaces[p_surface].blend_shape_data[p_blend_shape].arrays;
131 }
132 int ImporterMesh::get_surface_lod_count(int p_surface) const {
133 ERR_FAIL_INDEX_V(p_surface, surfaces.size(), 0);
134 return surfaces[p_surface].lods.size();
135 }
136 Vector<int> ImporterMesh::get_surface_lod_indices(int p_surface, int p_lod) const {
137 ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Vector<int>());
138 ERR_FAIL_INDEX_V(p_lod, surfaces[p_surface].lods.size(), Vector<int>());
139
140 return surfaces[p_surface].lods[p_lod].indices;
141 }
142
143 float ImporterMesh::get_surface_lod_size(int p_surface, int p_lod) const {
144 ERR_FAIL_INDEX_V(p_surface, surfaces.size(), 0);
145 ERR_FAIL_INDEX_V(p_lod, surfaces[p_surface].lods.size(), 0);
146 return surfaces[p_surface].lods[p_lod].distance;
147 }
148
149 uint64_t ImporterMesh::get_surface_format(int p_surface) const {
150 ERR_FAIL_INDEX_V(p_surface, surfaces.size(), 0);
151 return surfaces[p_surface].flags;
152 }
153
154 Ref<Material> ImporterMesh::get_surface_material(int p_surface) const {
155 ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Ref<Material>());
156 return surfaces[p_surface].material;
157 }
158
159 void ImporterMesh::set_surface_material(int p_surface, const Ref<Material> &p_material) {
160 ERR_FAIL_INDEX(p_surface, surfaces.size());
161 surfaces.write[p_surface].material = p_material;
162 mesh.unref();
163 }
164
165 template <typename T>
166 static Vector<T> _remap_array(Vector<T> p_array, const Vector<uint32_t> &p_remap, uint32_t p_vertex_count) {
167 ERR_FAIL_COND_V(p_array.size() % p_remap.size() != 0, p_array);
168 int num_elements = p_array.size() / p_remap.size();
169 T *data = p_array.ptrw();
170 SurfaceTool::remap_vertex_func(data, data, p_remap.size(), sizeof(T) * num_elements, p_remap.ptr());
171 p_array.resize(p_vertex_count * num_elements);
172 return p_array;
173 }
174
175 static void _remap_arrays(Array &r_arrays, const Vector<uint32_t> &p_remap, uint32_t p_vertex_count) {
176 for (int i = 0; i < r_arrays.size(); i++) {
177 if (i == RS::ARRAY_INDEX) {
178 continue;
179 }
180
181 switch (r_arrays[i].get_type()) {
182 case Variant::NIL:
183 break;
184 case Variant::PACKED_VECTOR3_ARRAY:
185 r_arrays[i] = _remap_array<Vector3>(r_arrays[i], p_remap, p_vertex_count);
186 break;
187 case Variant::PACKED_VECTOR2_ARRAY:
188 r_arrays[i] = _remap_array<Vector2>(r_arrays[i], p_remap, p_vertex_count);
189 break;
190 case Variant::PACKED_FLOAT32_ARRAY:
191 r_arrays[i] = _remap_array<float>(r_arrays[i], p_remap, p_vertex_count);
192 break;
193 case Variant::PACKED_INT32_ARRAY:
194 r_arrays[i] = _remap_array<int32_t>(r_arrays[i], p_remap, p_vertex_count);
195 break;
196 case Variant::PACKED_BYTE_ARRAY:
197 r_arrays[i] = _remap_array<uint8_t>(r_arrays[i], p_remap, p_vertex_count);
198 break;
199 case Variant::PACKED_COLOR_ARRAY:
200 r_arrays[i] = _remap_array<Color>(r_arrays[i], p_remap, p_vertex_count);
201 break;
202 default:
203 ERR_FAIL_MSG("Unhandled array type.");
204 }
205 }
206 }
207
208 void ImporterMesh::optimize_indices() {
209 if (!SurfaceTool::optimize_vertex_cache_func) {
210 return;
211 }
212 if (!SurfaceTool::optimize_vertex_fetch_remap_func || !SurfaceTool::remap_vertex_func || !SurfaceTool::remap_index_func) {
213 return;
214 }
215
216 for (int i = 0; i < surfaces.size(); i++) {
217 if (surfaces[i].primitive != Mesh::PRIMITIVE_TRIANGLES) {
218 continue;
219 }
220
221 Vector<Vector3> vertices = surfaces[i].arrays[RS::ARRAY_VERTEX];
222 PackedInt32Array indices = surfaces[i].arrays[RS::ARRAY_INDEX];
223
224 unsigned int index_count = indices.size();
225 unsigned int vertex_count = vertices.size();
226
227 if (index_count == 0) {
228 continue;
229 }
230
231 // Optimize indices for vertex cache to establish final triangle order.
232 int *indices_ptr = indices.ptrw();
233 SurfaceTool::optimize_vertex_cache_func((unsigned int *)indices_ptr, (const unsigned int *)indices_ptr, index_count, vertex_count);
234 surfaces.write[i].arrays[RS::ARRAY_INDEX] = indices;
235
236 for (int j = 0; j < surfaces[i].lods.size(); ++j) {
237 Surface::LOD &lod = surfaces.write[i].lods.write[j];
238 int *lod_indices_ptr = lod.indices.ptrw();
239 SurfaceTool::optimize_vertex_cache_func((unsigned int *)lod_indices_ptr, (const unsigned int *)lod_indices_ptr, lod.indices.size(), vertex_count);
240 }
241
242 // Concatenate indices for all LODs in the order of coarse->fine; this establishes the effective order of vertices,
243 // and is important to optimize for vertex fetch (all GPUs) and shading (Mali GPUs)
244 PackedInt32Array merged_indices;
245 for (int j = surfaces[i].lods.size() - 1; j >= 0; --j) {
246 merged_indices.append_array(surfaces[i].lods[j].indices);
247 }
248 merged_indices.append_array(indices);
249
250 // Generate remap array that establishes optimal vertex order according to the order of indices above.
251 Vector<uint32_t> remap;
252 remap.resize(vertex_count);
253 unsigned int new_vertex_count = SurfaceTool::optimize_vertex_fetch_remap_func(remap.ptrw(), (const unsigned int *)merged_indices.ptr(), merged_indices.size(), vertex_count);
254
255 // We need to remap all vertex and index arrays in lockstep according to the remap.
256 SurfaceTool::remap_index_func((unsigned int *)indices_ptr, (const unsigned int *)indices_ptr, index_count, remap.ptr());
257 surfaces.write[i].arrays[RS::ARRAY_INDEX] = indices;
258
259 for (int j = 0; j < surfaces[i].lods.size(); ++j) {
260 Surface::LOD &lod = surfaces.write[i].lods.write[j];
261 int *lod_indices_ptr = lod.indices.ptrw();
262 SurfaceTool::remap_index_func((unsigned int *)lod_indices_ptr, (const unsigned int *)lod_indices_ptr, lod.indices.size(), remap.ptr());
263 }
264
265 _remap_arrays(surfaces.write[i].arrays, remap, new_vertex_count);
266 for (int j = 0; j < surfaces[i].blend_shape_data.size(); j++) {
267 _remap_arrays(surfaces.write[i].blend_shape_data.write[j].arrays, remap, new_vertex_count);
268 }
269 }
270
271 if (shadow_mesh.is_valid()) {
272 shadow_mesh->optimize_indices();
273 }
274 }
275
276 #define VERTEX_SKIN_FUNC(bone_count, vert_idx, read_array, write_array, transform_array, bone_array, weight_array) \
277 Vector3 transformed_vert; \
278 for (unsigned int weight_idx = 0; weight_idx < bone_count; weight_idx++) { \
279 int bone_idx = bone_array[vert_idx * bone_count + weight_idx]; \
280 float w = weight_array[vert_idx * bone_count + weight_idx]; \
281 if (w < FLT_EPSILON) { \
282 continue; \
283 } \
284 ERR_FAIL_INDEX(bone_idx, static_cast<int>(transform_array.size())); \
285 transformed_vert += transform_array[bone_idx].xform(read_array[vert_idx]) * w; \
286 } \
287 write_array[vert_idx] = transformed_vert;
288
289 void ImporterMesh::generate_lods(float p_normal_merge_angle, Array p_bone_transform_array) {
290 if (!SurfaceTool::simplify_scale_func) {
291 return;
292 }
293 if (!SurfaceTool::simplify_with_attrib_func) {
294 return;
295 }
296
297 LocalVector<Transform3D> bone_transform_vector;
298 for (int i = 0; i < p_bone_transform_array.size(); i++) {
299 ERR_FAIL_COND(p_bone_transform_array[i].get_type() != Variant::TRANSFORM3D);
300 bone_transform_vector.push_back(p_bone_transform_array[i]);
301 }
302
303 for (int i = 0; i < surfaces.size(); i++) {
304 if (surfaces[i].primitive != Mesh::PRIMITIVE_TRIANGLES) {
305 continue;
306 }
307
308 surfaces.write[i].lods.clear();
309 Vector<Vector3> vertices = surfaces[i].arrays[RS::ARRAY_VERTEX];
310 PackedInt32Array indices = surfaces[i].arrays[RS::ARRAY_INDEX];
311 Vector<Vector3> normals = surfaces[i].arrays[RS::ARRAY_NORMAL];
312 Vector<float> tangents = surfaces[i].arrays[RS::ARRAY_TANGENT];
313 Vector<Vector2> uvs = surfaces[i].arrays[RS::ARRAY_TEX_UV];
314 Vector<Vector2> uv2s = surfaces[i].arrays[RS::ARRAY_TEX_UV2];
315 Vector<int> bones = surfaces[i].arrays[RS::ARRAY_BONES];
316 Vector<float> weights = surfaces[i].arrays[RS::ARRAY_WEIGHTS];
317 Vector<Color> colors = surfaces[i].arrays[RS::ARRAY_COLOR];
318
319 unsigned int index_count = indices.size();
320 unsigned int vertex_count = vertices.size();
321
322 if (index_count == 0) {
323 continue; //no lods if no indices
324 }
325 ERR_FAIL_COND_MSG(index_count % 3 != 0, "ImporterMesh::generate_lods: Indexed triangle meshes MUST have an index array with a size that is a multiple of 3, but got " + itos(index_count) + " indices. Cannot generate LODs for this invalid mesh.");
326
327 const Vector3 *vertices_ptr = vertices.ptr();
328 const int *indices_ptr = indices.ptr();
329
330 if (normals.is_empty()) {
331 normals.resize(index_count);
332 Vector3 *n_ptr = normals.ptrw();
333 for (unsigned int j = 0; j < index_count; j += 3) {
334 const Vector3 &v0 = vertices_ptr[indices_ptr[j + 0]];
335 const Vector3 &v1 = vertices_ptr[indices_ptr[j + 1]];
336 const Vector3 &v2 = vertices_ptr[indices_ptr[j + 2]];
337 Vector3 n = vec3_cross(v0 - v2, v0 - v1).normalized();
338 n_ptr[j + 0] = n;
339 n_ptr[j + 1] = n;
340 n_ptr[j + 2] = n;
341 }
342 }
343
344 bool deformable = bones.size() > 0 || blend_shapes.size() > 0;
345
346 if (bones.size() > 0 && weights.size() && bone_transform_vector.size() > 0) {
347 Vector3 *vertices_ptrw = vertices.ptrw();
348
349 // Apply bone transforms to regular surface.
350 unsigned int bone_weight_length = surfaces[i].flags & Mesh::ARRAY_FLAG_USE_8_BONE_WEIGHTS ? 8 : 4;
351
352 const int *bo = bones.ptr();
353 const float *we = weights.ptr();
354
355 for (unsigned int j = 0; j < vertex_count; j++) {
356 VERTEX_SKIN_FUNC(bone_weight_length, j, vertices_ptr, vertices_ptrw, bone_transform_vector, bo, we)
357 }
358
359 vertices_ptr = vertices.ptr();
360 }
361
362 float normal_merge_threshold = Math::cos(Math::deg_to_rad(p_normal_merge_angle));
363 const Vector3 *normals_ptr = normals.ptr();
364
365 HashMap<Vector3, LocalVector<Pair<int, int>>> unique_vertices;
366
367 LocalVector<int> vertex_remap;
368 LocalVector<int> vertex_inverse_remap;
369 LocalVector<Vector3> merged_vertices;
370 LocalVector<Vector3> merged_normals;
371 LocalVector<int> merged_normals_counts;
372 const Vector2 *uvs_ptr = uvs.ptr();
373 const Vector2 *uv2s_ptr = uv2s.ptr();
374 const float *tangents_ptr = tangents.ptr();
375 const Color *colors_ptr = colors.ptr();
376
377 for (unsigned int j = 0; j < vertex_count; j++) {
378 const Vector3 &v = vertices_ptr[j];
379 const Vector3 &n = normals_ptr[j];
380
381 HashMap<Vector3, LocalVector<Pair<int, int>>>::Iterator E = unique_vertices.find(v);
382
383 if (E) {
384 const LocalVector<Pair<int, int>> &close_verts = E->value;
385
386 bool found = false;
387 for (const Pair<int, int> &idx : close_verts) {
388 bool is_uvs_close = (!uvs_ptr || uvs_ptr[j].distance_squared_to(uvs_ptr[idx.second]) < CMP_EPSILON2);
389 bool is_uv2s_close = (!uv2s_ptr || uv2s_ptr[j].distance_squared_to(uv2s_ptr[idx.second]) < CMP_EPSILON2);
390 bool is_tang_aligned = !tangents_ptr || (tangents_ptr[j * 4 + 3] < 0) == (tangents_ptr[idx.second * 4 + 3] < 0);
391 ERR_FAIL_INDEX(idx.second, normals.size());
392 bool is_normals_close = normals[idx.second].dot(n) > normal_merge_threshold;
393 bool is_col_close = (!colors_ptr || colors_ptr[j].is_equal_approx(colors_ptr[idx.second]));
394 if (is_uvs_close && is_uv2s_close && is_normals_close && is_tang_aligned && is_col_close) {
395 vertex_remap.push_back(idx.first);
396 merged_normals[idx.first] += normals[idx.second];
397 merged_normals_counts[idx.first]++;
398 found = true;
399 break;
400 }
401 }
402
403 if (!found) {
404 int vcount = merged_vertices.size();
405 unique_vertices[v].push_back(Pair<int, int>(vcount, j));
406 vertex_inverse_remap.push_back(j);
407 merged_vertices.push_back(v);
408 vertex_remap.push_back(vcount);
409 merged_normals.push_back(normals_ptr[j]);
410 merged_normals_counts.push_back(1);
411 }
412 } else {
413 int vcount = merged_vertices.size();
414 unique_vertices[v] = LocalVector<Pair<int, int>>();
415 unique_vertices[v].push_back(Pair<int, int>(vcount, j));
416 vertex_inverse_remap.push_back(j);
417 merged_vertices.push_back(v);
418 vertex_remap.push_back(vcount);
419 merged_normals.push_back(normals_ptr[j]);
420 merged_normals_counts.push_back(1);
421 }
422 }
423
424 LocalVector<int> merged_indices;
425 merged_indices.resize(index_count);
426 for (unsigned int j = 0; j < index_count; j++) {
427 merged_indices[j] = vertex_remap[indices[j]];
428 }
429
430 unsigned int merged_vertex_count = merged_vertices.size();
431 const Vector3 *merged_vertices_ptr = merged_vertices.ptr();
432 Vector3 *merged_normals_ptr = merged_normals.ptr();
433
434 {
435 const int *counts_ptr = merged_normals_counts.ptr();
436 for (unsigned int j = 0; j < merged_vertex_count; j++) {
437 merged_normals_ptr[j] /= counts_ptr[j];
438 }
439 }
440
441 Vector<float> merged_vertices_f32 = vector3_to_float32_array(merged_vertices_ptr, merged_vertex_count);
442 float scale = SurfaceTool::simplify_scale_func(merged_vertices_f32.ptr(), merged_vertex_count, sizeof(float) * 3);
443
444 const size_t attrib_count = 6; // 3 for normal + 3 for color (if present)
445
446 float attrib_weights[attrib_count] = {};
447
448 // Give some weight to normal preservation
449 attrib_weights[0] = attrib_weights[1] = attrib_weights[2] = 1.0f;
450
451 // Give some weight to colors but only if present to avoid redundant computations during simplification
452 if (colors_ptr) {
453 attrib_weights[3] = attrib_weights[4] = attrib_weights[5] = 1.0f;
454 }
455
456 LocalVector<float> merged_attribs;
457 merged_attribs.resize(merged_vertex_count * attrib_count);
458 float *merged_attribs_ptr = merged_attribs.ptr();
459
460 memset(merged_attribs_ptr, 0, merged_attribs.size() * sizeof(float));
461
462 for (unsigned int j = 0; j < merged_vertex_count; ++j) {
463 merged_attribs_ptr[j * attrib_count + 0] = merged_normals_ptr[j].x;
464 merged_attribs_ptr[j * attrib_count + 1] = merged_normals_ptr[j].y;
465 merged_attribs_ptr[j * attrib_count + 2] = merged_normals_ptr[j].z;
466
467 if (colors_ptr) {
468 unsigned int rj = vertex_inverse_remap[j];
469
470 merged_attribs_ptr[j * attrib_count + 3] = colors_ptr[rj].r;
471 merged_attribs_ptr[j * attrib_count + 4] = colors_ptr[rj].g;
472 merged_attribs_ptr[j * attrib_count + 5] = colors_ptr[rj].b;
473 }
474 }
475
476 print_verbose("LOD Generation: Triangles " + itos(index_count / 3) + ", vertices " + itos(vertex_count) + " (merged " + itos(merged_vertex_count) + ")" + (deformable ? ", deformable" : ""));
477
478 const float max_mesh_error = 1.0f; // We only need LODs that can be selected by error threshold.
479 const unsigned min_target_indices = 12;
480
481 LocalVector<int> current_indices = merged_indices;
482 float current_error = 0.0f;
483 bool allow_prune = true;
484
485 while (current_indices.size() > min_target_indices * 2) {
486 unsigned int current_index_count = current_indices.size();
487 unsigned int target_index_count = MAX(((current_index_count / 3) / 2) * 3, min_target_indices);
488
489 PackedInt32Array new_indices;
490 new_indices.resize(current_index_count);
491
492 int simplify_options = SurfaceTool::SIMPLIFY_SPARSE; // Does not change appearance, but speeds up subsequent iterations.
493
494 // Lock geometric boundary in case the mesh is composed of multiple material subsets.
495 simplify_options |= SurfaceTool::SIMPLIFY_LOCK_BORDER;
496
497 if (allow_prune) {
498 // Remove small disconnected components.
499 simplify_options |= SurfaceTool::SIMPLIFY_PRUNE;
500 }
501
502 if (deformable) {
503 // Improves appearance of deformable objects after deformation by using more regular tessellation.
504 simplify_options |= SurfaceTool::SIMPLIFY_REGULARIZE;
505 }
506
507 float step_error = 0.0f;
508 size_t new_index_count = SurfaceTool::simplify_with_attrib_func(
509 (unsigned int *)new_indices.ptrw(),
510 (const uint32_t *)current_indices.ptr(), current_index_count,
511 merged_vertices_f32.ptr(), merged_vertex_count,
512 sizeof(float) * 3, // Vertex stride
513 merged_attribs_ptr,
514 sizeof(float) * attrib_count, // Attribute stride
515 attrib_weights, attrib_count,
516 nullptr, // Vertex lock
517 target_index_count,
518 max_mesh_error,
519 simplify_options,
520 &step_error);
521
522 if (new_index_count == 0 && allow_prune) {
523 // If the best result the simplifier could arrive at with pruning enabled is 0 triangles, there might still be an opportunity
524 // to reduce the number of triangles further *without* completely decimating the mesh. It will be impossible to reach the target
525 // this way - if the target was reachable without going down to 0, the simplifier would have done it! - but we might still be able
526 // to get one more slightly lower level if we retry without pruning.
527 allow_prune = false;
528 continue;
529 }
530
531 // Accumulate error over iterations. Usually, it's correct to use step_error as is; however, on coarse LODs, we may start
532 // getting *smaller* relative error compared to the previous LOD. To make sure the error is monotonic and strictly increasing,
533 // and to limit the switching (pop) distance, we ensure the error grows by an arbitrary factor each iteration.
534 current_error = MAX(current_error * 1.5f, step_error);
535
536 new_indices.resize(new_index_count);
537 current_indices = new_indices;
538
539 if (new_index_count == 0 || (new_index_count >= current_index_count * 0.75f)) {
540 print_verbose(" LOD stop: got " + itos(new_index_count / 3) + " triangles when asking for " + itos(target_index_count / 3));
541 break;
542 }
543
544 if (current_error > max_mesh_error) {
545 print_verbose(" LOD stop: reached " + rtos(current_error) + " cumulative error (step error " + rtos(step_error) + ")");
546 break;
547 }
548
549 // We need to remap the LOD indices back to the original vertex array; note that we already copied new_indices into current_indices for subsequent iteration.
550 {
551 int *ptrw = new_indices.ptrw();
552 for (unsigned int j = 0; j < new_index_count; j++) {
553 ptrw[j] = vertex_inverse_remap[ptrw[j]];
554 }
555 }
556
557 Surface::LOD lod;
558 lod.distance = MAX(current_error * scale, CMP_EPSILON2);
559 lod.indices = new_indices;
560 surfaces.write[i].lods.push_back(lod);
561
562 print_verbose(" LOD " + itos(surfaces.write[i].lods.size()) + ": " + itos(new_index_count / 3) + " triangles, error " + rtos(current_error) + " (step error " + rtos(step_error) + ")");
563 }
564
565 surfaces.write[i].lods.sort_custom<Surface::LODComparator>();
566 }
567 }
568
569 void ImporterMesh::_generate_lods_bind(float p_normal_merge_angle, float p_normal_split_angle, Array p_skin_pose_transform_array) {
570 // p_normal_split_angle is unused, but kept for compatibility
571 generate_lods(p_normal_merge_angle, p_skin_pose_transform_array);
572 }
573
574 bool ImporterMesh::has_mesh() const {
575 return mesh.is_valid();
576 }
577
578 Ref<ArrayMesh> ImporterMesh::get_mesh(const Ref<ArrayMesh> &p_base) {
579 ERR_FAIL_COND_V(surfaces.is_empty(), Ref<ArrayMesh>());
580
581 if (mesh.is_null()) {
582 if (p_base.is_valid()) {
583 mesh = p_base;
584 }
585 if (mesh.is_null()) {
586 mesh.instantiate();
587 }
588 mesh->set_name(get_name());
589 if (has_meta("import_id")) {
590 mesh->set_meta("import_id", get_meta("import_id"));
591 }
592 for (int i = 0; i < blend_shapes.size(); i++) {
593 mesh->add_blend_shape(blend_shapes[i]);
594 }
595 mesh->set_blend_shape_mode(blend_shape_mode);
596 for (int i = 0; i < surfaces.size(); i++) {
597 Array bs_data;
598 if (surfaces[i].blend_shape_data.size()) {
599 for (int j = 0; j < surfaces[i].blend_shape_data.size(); j++) {
600 bs_data.push_back(surfaces[i].blend_shape_data[j].arrays);
601 }
602 }
603 Dictionary lods;
604 if (surfaces[i].lods.size()) {
605 for (int j = 0; j < surfaces[i].lods.size(); j++) {
606 lods[surfaces[i].lods[j].distance] = surfaces[i].lods[j].indices;
607 }
608 }
609
610 mesh->add_surface_from_arrays(surfaces[i].primitive, surfaces[i].arrays, bs_data, lods, surfaces[i].flags);
611 if (surfaces[i].material.is_valid()) {
612 mesh->surface_set_material(mesh->get_surface_count() - 1, surfaces[i].material);
613 }
614 if (!surfaces[i].name.is_empty()) {
615 mesh->surface_set_name(mesh->get_surface_count() - 1, surfaces[i].name);
616 }
617 }
618
619 mesh->set_lightmap_size_hint(lightmap_size_hint);
620
621 if (shadow_mesh.is_valid()) {
622 Ref<ArrayMesh> shadow = shadow_mesh->get_mesh();
623 mesh->set_shadow_mesh(shadow);
624 }
625 }
626
627 return mesh;
628 }
629
630 Ref<ImporterMesh> ImporterMesh::from_mesh(const Ref<Mesh> &p_mesh) {
631 Ref<ImporterMesh> importer_mesh;
632 importer_mesh.instantiate();
633 if (p_mesh.is_null()) {
634 return importer_mesh;
635 }
636 Ref<ArrayMesh> array_mesh = p_mesh;
637 // Convert blend shape mode and names if any.
638 if (p_mesh->get_blend_shape_count() > 0) {
639 ArrayMesh::BlendShapeMode shape_mode = ArrayMesh::BLEND_SHAPE_MODE_NORMALIZED;
640 if (array_mesh.is_valid()) {
641 shape_mode = array_mesh->get_blend_shape_mode();
642 }
643 importer_mesh->set_blend_shape_mode(shape_mode);
644 for (int morph_i = 0; morph_i < p_mesh->get_blend_shape_count(); morph_i++) {
645 importer_mesh->add_blend_shape(p_mesh->get_blend_shape_name(morph_i));
646 }
647 }
648 // Add surfaces one by one.
649 for (int32_t surface_i = 0; surface_i < p_mesh->get_surface_count(); surface_i++) {
650 Ref<Material> mat = p_mesh->surface_get_material(surface_i);
651 String surface_name;
652 if (array_mesh.is_valid()) {
653 surface_name = array_mesh->surface_get_name(surface_i);
654 }
655 if (surface_name.is_empty() && mat.is_valid()) {
656 surface_name = mat->get_name();
657 }
658 importer_mesh->add_surface(p_mesh->surface_get_primitive_type(surface_i), p_mesh->surface_get_arrays(surface_i),
659 p_mesh->surface_get_blend_shape_arrays(surface_i), p_mesh->surface_get_lods(surface_i),
660 mat, surface_name, p_mesh->surface_get_format(surface_i));
661 }
662 // Merge metadata.
663 importer_mesh->merge_meta_from(*p_mesh);
664 importer_mesh->set_name(p_mesh->get_name());
665 return importer_mesh;
666 }
667
668 void ImporterMesh::clear() {
669 surfaces.clear();
670 blend_shapes.clear();
671 mesh.unref();
672 }
673
674 void ImporterMesh::create_shadow_mesh() {
675 if (shadow_mesh.is_valid()) {
676 shadow_mesh.unref();
677 }
678
679 //no shadow mesh for blendshapes
680 if (blend_shapes.size() > 0) {
681 return;
682 }
683 //no shadow mesh for skeletons
684 for (int i = 0; i < surfaces.size(); i++) {
685 if (surfaces[i].arrays[RS::ARRAY_BONES].get_type() != Variant::NIL) {
686 return;
687 }
688 if (surfaces[i].arrays[RS::ARRAY_WEIGHTS].get_type() != Variant::NIL) {
689 return;
690 }
691 }
692
693 shadow_mesh.instantiate();
694
695 for (int i = 0; i < surfaces.size(); i++) {
696 LocalVector<int> vertex_remap;
697 Vector<Vector3> new_vertices;
698 Vector<Vector3> vertices = surfaces[i].arrays[RS::ARRAY_VERTEX];
699 int vertex_count = vertices.size();
700 {
701 HashMap<Vector3, int> unique_vertices;
702 const Vector3 *vptr = vertices.ptr();
703 for (int j = 0; j < vertex_count; j++) {
704 const Vector3 &v = vptr[j];
705
706 HashMap<Vector3, int>::Iterator E = unique_vertices.find(v);
707
708 if (E) {
709 vertex_remap.push_back(E->value);
710 } else {
711 int vcount = unique_vertices.size();
712 unique_vertices[v] = vcount;
713 vertex_remap.push_back(vcount);
714 new_vertices.push_back(v);
715 }
716 }
717 }
718
719 Array new_surface;
720 new_surface.resize(RS::ARRAY_MAX);
721 Dictionary lods;
722
723 // print_line("original vertex count: " + itos(vertices.size()) + " new vertex count: " + itos(new_vertices.size()));
724
725 new_surface[RS::ARRAY_VERTEX] = new_vertices;
726
727 Vector<int> indices = surfaces[i].arrays[RS::ARRAY_INDEX];
728 if (indices.size()) {
729 int index_count = indices.size();
730 const int *index_rptr = indices.ptr();
731 Vector<int> new_indices;
732 new_indices.resize(indices.size());
733 int *index_wptr = new_indices.ptrw();
734
735 for (int j = 0; j < index_count; j++) {
736 int index = index_rptr[j];
737 ERR_FAIL_INDEX(index, vertex_count);
738 index_wptr[j] = vertex_remap[index];
739 }
740
741 new_surface[RS::ARRAY_INDEX] = new_indices;
742
743 // Make sure the same LODs as the full version are used.
744 // This makes it more coherent between rendered model and its shadows.
745 for (int j = 0; j < surfaces[i].lods.size(); j++) {
746 indices = surfaces[i].lods[j].indices;
747
748 index_count = indices.size();
749 index_rptr = indices.ptr();
750 new_indices.resize(indices.size());
751 index_wptr = new_indices.ptrw();
752
753 for (int k = 0; k < index_count; k++) {
754 int index = index_rptr[k];
755 ERR_FAIL_INDEX(index, vertex_count);
756 index_wptr[k] = vertex_remap[index];
757 }
758
759 lods[surfaces[i].lods[j].distance] = new_indices;
760 }
761 }
762
763 shadow_mesh->add_surface(surfaces[i].primitive, new_surface, Array(), lods, Ref<Material>(), surfaces[i].name, surfaces[i].flags);
764 }
765 }
766
767 Ref<ImporterMesh> ImporterMesh::get_shadow_mesh() const {
768 return shadow_mesh;
769 }
770
771 void ImporterMesh::_set_data(const Dictionary &p_data) {
772 clear();
773 if (p_data.has("blend_shape_names")) {
774 blend_shapes = p_data["blend_shape_names"];
775 }
776 if (p_data.has("surfaces")) {
777 Array surface_arr = p_data["surfaces"];
778 for (int i = 0; i < surface_arr.size(); i++) {
779 Dictionary s = surface_arr[i];
780 ERR_CONTINUE(!s.has("primitive"));
781 ERR_CONTINUE(!s.has("arrays"));
782 Mesh::PrimitiveType prim = Mesh::PrimitiveType(int(s["primitive"]));
783 ERR_CONTINUE(prim >= Mesh::PRIMITIVE_MAX);
784 Array arr = s["arrays"];
785 Dictionary lods;
786 String surf_name;
787 if (s.has("name")) {
788 surf_name = s["name"];
789 }
790 if (s.has("lods")) {
791 lods = s["lods"];
792 }
793 Array b_shapes;
794 if (s.has("b_shapes")) {
795 b_shapes = s["b_shapes"];
796 }
797 Ref<Material> material;
798 if (s.has("material")) {
799 material = s["material"];
800 }
801 uint64_t flags = 0;
802 if (s.has("flags")) {
803 flags = s["flags"];
804 }
805 add_surface(prim, arr, b_shapes, lods, material, surf_name, flags);
806 }
807 }
808 }
809 Dictionary ImporterMesh::_get_data() const {
810 Dictionary data;
811 if (blend_shapes.size()) {
812 data["blend_shape_names"] = blend_shapes;
813 }
814 Array surface_arr;
815 for (int i = 0; i < surfaces.size(); i++) {
816 Dictionary d;
817 d["primitive"] = surfaces[i].primitive;
818 d["arrays"] = surfaces[i].arrays;
819 if (surfaces[i].blend_shape_data.size()) {
820 Array bs_data;
821 for (int j = 0; j < surfaces[i].blend_shape_data.size(); j++) {
822 bs_data.push_back(surfaces[i].blend_shape_data[j].arrays);
823 }
824 d["blend_shapes"] = bs_data;
825 }
826 if (surfaces[i].lods.size()) {
827 Dictionary lods;
828 for (int j = 0; j < surfaces[i].lods.size(); j++) {
829 lods[surfaces[i].lods[j].distance] = surfaces[i].lods[j].indices;
830 }
831 d["lods"] = lods;
832 }
833
834 if (surfaces[i].material.is_valid()) {
835 d["material"] = surfaces[i].material;
836 }
837
838 if (!surfaces[i].name.is_empty()) {
839 d["name"] = surfaces[i].name;
840 }
841
842 d["flags"] = surfaces[i].flags;
843
844 surface_arr.push_back(d);
845 }
846 data["surfaces"] = surface_arr;
847 return data;
848 }
849
850 Vector<Face3> ImporterMesh::get_faces() const {
851 Vector<Face3> faces;
852 for (int i = 0; i < surfaces.size(); i++) {
853 if (surfaces[i].primitive == Mesh::PRIMITIVE_TRIANGLES) {
854 Vector<Vector3> vertices = surfaces[i].arrays[Mesh::ARRAY_VERTEX];
855 Vector<int> indices = surfaces[i].arrays[Mesh::ARRAY_INDEX];
856 if (indices.size()) {
857 for (int j = 0; j < indices.size(); j += 3) {
858 Face3 f;
859 f.vertex[0] = vertices[indices[j + 0]];
860 f.vertex[1] = vertices[indices[j + 1]];
861 f.vertex[2] = vertices[indices[j + 2]];
862 faces.push_back(f);
863 }
864 } else {
865 for (int j = 0; j < vertices.size(); j += 3) {
866 Face3 f;
867 f.vertex[0] = vertices[j + 0];
868 f.vertex[1] = vertices[j + 1];
869 f.vertex[2] = vertices[j + 2];
870 faces.push_back(f);
871 }
872 }
873 }
874 }
875
876 return faces;
877 }
878
879 #ifndef PHYSICS_3D_DISABLED
880 Vector<Ref<Shape3D>> ImporterMesh::convex_decompose(const Ref<MeshConvexDecompositionSettings> &p_settings) const {
881 ERR_FAIL_NULL_V(Mesh::convex_decomposition_function, Vector<Ref<Shape3D>>());
882
883 const Vector<Face3> faces = get_faces();
884 int face_count = faces.size();
885
886 Vector<Vector3> vertices;
887 uint32_t vertex_count = 0;
888 vertices.resize(face_count * 3);
889 Vector<uint32_t> indices;
890 indices.resize(face_count * 3);
891 {
892 HashMap<Vector3, uint32_t> vertex_map;
893 Vector3 *vertex_w = vertices.ptrw();
894 uint32_t *index_w = indices.ptrw();
895 for (int i = 0; i < face_count; i++) {
896 for (int j = 0; j < 3; j++) {
897 const Vector3 &vertex = faces[i].vertex[j];
898 HashMap<Vector3, uint32_t>::Iterator found_vertex = vertex_map.find(vertex);
899 uint32_t index;
900 if (found_vertex) {
901 index = found_vertex->value;
902 } else {
903 index = vertex_count++;
904 vertex_map[vertex] = index;
905 vertex_w[index] = vertex;
906 }
907 index_w[i * 3 + j] = index;
908 }
909 }
910 }
911 vertices.resize(vertex_count);
912
913 Vector<Vector<Vector3>> decomposed = Mesh::convex_decomposition_function((real_t *)vertices.ptr(), vertex_count, indices.ptr(), face_count, p_settings, nullptr);
914
915 Vector<Ref<Shape3D>> ret;
916
917 for (int i = 0; i < decomposed.size(); i++) {
918 Ref<ConvexPolygonShape3D> shape;
919 shape.instantiate();
920 shape->set_points(decomposed[i]);
921 ret.push_back(shape);
922 }
923
924 return ret;
925 }
926
927 Ref<ConvexPolygonShape3D> ImporterMesh::create_convex_shape(bool p_clean, bool p_simplify) const {
928 if (p_simplify) {
929 Ref<MeshConvexDecompositionSettings> settings;
930 settings.instantiate();
931 settings->set_max_convex_hulls(1);
932 Vector<Ref<Shape3D>> decomposed = convex_decompose(settings);
933 if (decomposed.size() == 1) {
934 return decomposed[0];
935 } else {
936 ERR_PRINT("Convex shape simplification failed, falling back to simpler process.");
937 }
938 }
939
940 Vector<Vector3> vertices;
941 for (int i = 0; i < get_surface_count(); i++) {
942 Array a = get_surface_arrays(i);
943 ERR_FAIL_COND_V(a.is_empty(), Ref<ConvexPolygonShape3D>());
944 Vector<Vector3> v = a[Mesh::ARRAY_VERTEX];
945 vertices.append_array(v);
946 }
947
948 Ref<ConvexPolygonShape3D> shape = memnew(ConvexPolygonShape3D);
949
950 if (p_clean) {
951 Geometry3D::MeshData md;
952 Error err = ConvexHullComputer::convex_hull(vertices, md);
953 if (err == OK) {
954 shape->set_points(Vector<Vector3>(md.vertices));
955 return shape;
956 } else {
957 ERR_PRINT("Convex shape cleaning failed, falling back to simpler process.");
958 }
959 }
960
961 shape->set_points(vertices);
962 return shape;
963 }
964
965 Ref<ConcavePolygonShape3D> ImporterMesh::create_trimesh_shape() const {
966 Vector<Face3> faces = get_faces();
967 if (faces.is_empty()) {
968 return Ref<ConcavePolygonShape3D>();
969 }
970
971 Vector<Vector3> face_points;
972 face_points.resize(faces.size() * 3);
973
974 for (int i = 0; i < face_points.size(); i += 3) {
975 Face3 f = faces.get(i / 3);
976 face_points.set(i, f.vertex[0]);
977 face_points.set(i + 1, f.vertex[1]);
978 face_points.set(i + 2, f.vertex[2]);
979 }
980
981 Ref<ConcavePolygonShape3D> shape = memnew(ConcavePolygonShape3D);
982 shape->set_faces(face_points);
983 return shape;
984 }
985 #endif // PHYSICS_3D_DISABLED
986
987 Ref<NavigationMesh> ImporterMesh::create_navigation_mesh() {
988 Vector<Face3> faces = get_faces();
989 if (faces.is_empty()) {
990 return Ref<NavigationMesh>();
991 }
992
993 HashMap<Vector3, int> unique_vertices;
994 Vector<Vector<int>> face_polygons;
995 face_polygons.resize(faces.size());
996
997 for (int i = 0; i < faces.size(); i++) {
998 Vector<int> face_indices;
999 face_indices.resize(3);
1000 for (int j = 0; j < 3; j++) {
1001 Vector3 v = faces[i].vertex[j];
1002 int idx;
1003 if (unique_vertices.has(v)) {
1004 idx = unique_vertices[v];
1005 } else {
1006 idx = unique_vertices.size();
1007 unique_vertices[v] = idx;
1008 }
1009 face_indices.write[j] = idx;
1010 }
1011 face_polygons.write[i] = face_indices;
1012 }
1013
1014 Vector<Vector3> vertices;
1015 vertices.resize(unique_vertices.size());
1016 for (const KeyValue<Vector3, int> &E : unique_vertices) {
1017 vertices.write[E.value] = E.key;
1018 }
1019
1020 Ref<NavigationMesh> nm;
1021 nm.instantiate();
1022 nm->set_data(vertices, face_polygons);
1023
1024 return nm;
1025 }
1026
1027 extern bool (*array_mesh_lightmap_unwrap_callback)(float p_texel_size, const float *p_vertices, const float *p_normals, int p_vertex_count, const int *p_indices, int p_index_count, const uint8_t *p_cache_data, bool *r_use_cache, uint8_t **r_mesh_cache, int *r_mesh_cache_size, float **r_uv, int **r_vertex, int *r_vertex_count, int **r_index, int *r_index_count, int *r_size_hint_x, int *r_size_hint_y);
1028
1029 struct EditorSceneFormatImporterMeshLightmapSurface {
1030 Ref<Material> material;
1031 LocalVector<SurfaceTool::Vertex> vertices;
1032 Mesh::PrimitiveType primitive = Mesh::PrimitiveType::PRIMITIVE_MAX;
1033 uint64_t format = 0;
1034 String name;
1035 };
1036
1037 static const uint32_t custom_shift[RS::ARRAY_CUSTOM_COUNT] = { Mesh::ARRAY_FORMAT_CUSTOM0_SHIFT, Mesh::ARRAY_FORMAT_CUSTOM1_SHIFT, Mesh::ARRAY_FORMAT_CUSTOM2_SHIFT, Mesh::ARRAY_FORMAT_CUSTOM3_SHIFT };
1038
1039 Error ImporterMesh::lightmap_unwrap_cached(const Transform3D &p_base_transform, float p_texel_size, const Vector<uint8_t> &p_src_cache, Vector<uint8_t> &r_dst_cache) {
1040 ERR_FAIL_NULL_V(array_mesh_lightmap_unwrap_callback, ERR_UNCONFIGURED);
1041 ERR_FAIL_COND_V_MSG(blend_shapes.size() != 0, ERR_UNAVAILABLE, "Can't unwrap mesh with blend shapes.");
1042
1043 LocalVector<float> vertices;
1044 LocalVector<float> normals;
1045 LocalVector<int> indices;
1046 LocalVector<float> uv;
1047 LocalVector<Pair<int, int>> uv_indices;
1048
1049 Vector<EditorSceneFormatImporterMeshLightmapSurface> lightmap_surfaces;
1050
1051 // Keep only the scale
1052 Basis basis = p_base_transform.get_basis();
1053 Vector3 scale = Vector3(basis.get_column(0).length(), basis.get_column(1).length(), basis.get_column(2).length());
1054
1055 Transform3D transform;
1056 transform.scale(scale);
1057
1058 Basis normal_basis = transform.basis.inverse().transposed();
1059
1060 for (int i = 0; i < get_surface_count(); i++) {
1061 EditorSceneFormatImporterMeshLightmapSurface s;
1062 s.primitive = get_surface_primitive_type(i);
1063
1064 ERR_FAIL_COND_V_MSG(s.primitive != Mesh::PRIMITIVE_TRIANGLES, ERR_UNAVAILABLE, "Only triangles are supported for lightmap unwrap.");
1065 Array arrays = get_surface_arrays(i);
1066 s.material = get_surface_material(i);
1067 s.name = get_surface_name(i);
1068
1069 SurfaceTool::create_vertex_array_from_arrays(arrays, s.vertices, &s.format);
1070
1071 PackedVector3Array rvertices = arrays[Mesh::ARRAY_VERTEX];
1072 int vc = rvertices.size();
1073
1074 PackedVector3Array rnormals = arrays[Mesh::ARRAY_NORMAL];
1075
1076 if (!rnormals.size()) {
1077 continue;
1078 }
1079
1080 int vertex_ofs = vertices.size() / 3;
1081
1082 vertices.resize((vertex_ofs + vc) * 3);
1083 normals.resize((vertex_ofs + vc) * 3);
1084 uv_indices.resize(vertex_ofs + vc);
1085
1086 for (int j = 0; j < vc; j++) {
1087 Vector3 v = transform.xform(rvertices[j]);
1088 Vector3 n = normal_basis.xform(rnormals[j]).normalized();
1089
1090 vertices[(j + vertex_ofs) * 3 + 0] = v.x;
1091 vertices[(j + vertex_ofs) * 3 + 1] = v.y;
1092 vertices[(j + vertex_ofs) * 3 + 2] = v.z;
1093 normals[(j + vertex_ofs) * 3 + 0] = n.x;
1094 normals[(j + vertex_ofs) * 3 + 1] = n.y;
1095 normals[(j + vertex_ofs) * 3 + 2] = n.z;
1096 uv_indices[j + vertex_ofs] = Pair<int, int>(i, j);
1097 }
1098
1099 PackedInt32Array rindices = arrays[Mesh::ARRAY_INDEX];
1100 int ic = rindices.size();
1101
1102 float eps = 1.19209290e-7F; // Taken from xatlas.h
1103 if (ic == 0) {
1104 for (int j = 0; j < vc / 3; j++) {
1105 Vector3 p0 = transform.xform(rvertices[j * 3 + 0]);
1106 Vector3 p1 = transform.xform(rvertices[j * 3 + 1]);
1107 Vector3 p2 = transform.xform(rvertices[j * 3 + 2]);
1108
1109 if ((p0 - p1).length_squared() < eps || (p1 - p2).length_squared() < eps || (p2 - p0).length_squared() < eps) {
1110 continue;
1111 }
1112
1113 indices.push_back(vertex_ofs + j * 3 + 0);
1114 indices.push_back(vertex_ofs + j * 3 + 1);
1115 indices.push_back(vertex_ofs + j * 3 + 2);
1116 }
1117
1118 } else {
1119 for (int j = 0; j < ic / 3; j++) {
1120 ERR_FAIL_INDEX_V(rindices[j * 3 + 0], rvertices.size(), ERR_INVALID_DATA);
1121 ERR_FAIL_INDEX_V(rindices[j * 3 + 1], rvertices.size(), ERR_INVALID_DATA);
1122 ERR_FAIL_INDEX_V(rindices[j * 3 + 2], rvertices.size(), ERR_INVALID_DATA);
1123 Vector3 p0 = transform.xform(rvertices[rindices[j * 3 + 0]]);
1124 Vector3 p1 = transform.xform(rvertices[rindices[j * 3 + 1]]);
1125 Vector3 p2 = transform.xform(rvertices[rindices[j * 3 + 2]]);
1126
1127 if ((p0 - p1).length_squared() < eps || (p1 - p2).length_squared() < eps || (p2 - p0).length_squared() < eps) {
1128 continue;
1129 }
1130
1131 indices.push_back(vertex_ofs + rindices[j * 3 + 0]);
1132 indices.push_back(vertex_ofs + rindices[j * 3 + 1]);
1133 indices.push_back(vertex_ofs + rindices[j * 3 + 2]);
1134 }
1135 }
1136
1137 lightmap_surfaces.push_back(s);
1138 }
1139
1140 //unwrap
1141
1142 bool use_cache = true; // Used to request cache generation and to know if cache was used
1143 uint8_t *gen_cache;
1144 int gen_cache_size;
1145 float *gen_uvs;
1146 int *gen_vertices;
1147 int *gen_indices;
1148 int gen_vertex_count;
1149 int gen_index_count;
1150 int size_x;
1151 int size_y;
1152
1153 bool ok = array_mesh_lightmap_unwrap_callback(p_texel_size, vertices.ptr(), normals.ptr(), vertices.size() / 3, indices.ptr(), indices.size(), p_src_cache.ptr(), &use_cache, &gen_cache, &gen_cache_size, &gen_uvs, &gen_vertices, &gen_vertex_count, &gen_indices, &gen_index_count, &size_x, &size_y);
1154
1155 if (!ok) {
1156 return ERR_CANT_CREATE;
1157 }
1158
1159 //create surfacetools for each surface..
1160 LocalVector<Ref<SurfaceTool>> surfaces_tools;
1161
1162 for (int i = 0; i < lightmap_surfaces.size(); i++) {
1163 Ref<SurfaceTool> st;
1164 st.instantiate();
1165 st->set_skin_weight_count((lightmap_surfaces[i].format & Mesh::ARRAY_FLAG_USE_8_BONE_WEIGHTS) ? SurfaceTool::SKIN_8_WEIGHTS : SurfaceTool::SKIN_4_WEIGHTS);
1166 st->begin(Mesh::PRIMITIVE_TRIANGLES);
1167 st->set_material(lightmap_surfaces[i].material);
1168 st->set_meta("name", lightmap_surfaces[i].name);
1169
1170 for (int custom_i = 0; custom_i < RS::ARRAY_CUSTOM_COUNT; custom_i++) {
1171 st->set_custom_format(custom_i, (SurfaceTool::CustomFormat)((lightmap_surfaces[i].format >> custom_shift[custom_i]) & RS::ARRAY_FORMAT_CUSTOM_MASK));
1172 }
1173 surfaces_tools.push_back(st); //stay there
1174 }
1175
1176 //remove surfaces
1177 clear();
1178
1179 print_verbose("Mesh: Gen indices: " + itos(gen_index_count));
1180
1181 //go through all indices
1182 for (int i = 0; i < gen_index_count; i += 3) {
1183 ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 0]], (int)uv_indices.size(), ERR_BUG);
1184 ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 1]], (int)uv_indices.size(), ERR_BUG);
1185 ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 2]], (int)uv_indices.size(), ERR_BUG);
1186
1187 ERR_FAIL_COND_V(uv_indices[gen_vertices[gen_indices[i + 0]]].first != uv_indices[gen_vertices[gen_indices[i + 1]]].first || uv_indices[gen_vertices[gen_indices[i + 0]]].first != uv_indices[gen_vertices[gen_indices[i + 2]]].first, ERR_BUG);
1188
1189 int surface = uv_indices[gen_vertices[gen_indices[i + 0]]].first;
1190
1191 for (int j = 0; j < 3; j++) {
1192 SurfaceTool::Vertex v = lightmap_surfaces[surface].vertices[uv_indices[gen_vertices[gen_indices[i + j]]].second];
1193
1194 if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_COLOR) {
1195 surfaces_tools[surface]->set_color(v.color);
1196 }
1197 if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_TEX_UV) {
1198 surfaces_tools[surface]->set_uv(v.uv);
1199 }
1200 if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_NORMAL) {
1201 surfaces_tools[surface]->set_normal(v.normal);
1202 }
1203 if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_TANGENT) {
1204 Plane t;
1205 t.normal = v.tangent;
1206 t.d = v.binormal.dot(v.normal.cross(v.tangent)) < 0 ? -1 : 1;
1207 surfaces_tools[surface]->set_tangent(t);
1208 }
1209 if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_BONES) {
1210 surfaces_tools[surface]->set_bones(v.bones);
1211 }
1212 if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_WEIGHTS) {
1213 surfaces_tools[surface]->set_weights(v.weights);
1214 }
1215 for (int custom_i = 0; custom_i < RS::ARRAY_CUSTOM_COUNT; custom_i++) {
1216 if ((lightmap_surfaces[surface].format >> custom_shift[custom_i]) & RS::ARRAY_FORMAT_CUSTOM_MASK) {
1217 surfaces_tools[surface]->set_custom(custom_i, v.custom[custom_i]);
1218 }
1219 }
1220
1221 Vector2 uv2(gen_uvs[gen_indices[i + j] * 2 + 0], gen_uvs[gen_indices[i + j] * 2 + 1]);
1222 surfaces_tools[surface]->set_uv2(uv2);
1223
1224 surfaces_tools[surface]->add_vertex(v.vertex);
1225 }
1226 }
1227
1228 //generate surfaces
1229 for (int i = 0; i < lightmap_surfaces.size(); i++) {
1230 Ref<SurfaceTool> &tool = surfaces_tools[i];
1231 tool->index();
1232 Array arrays = tool->commit_to_arrays();
1233
1234 uint64_t format = lightmap_surfaces[i].format;
1235 if (tool->get_skin_weight_count() == SurfaceTool::SKIN_8_WEIGHTS) {
1236 format |= RS::ARRAY_FLAG_USE_8_BONE_WEIGHTS;
1237 } else {
1238 format &= ~RS::ARRAY_FLAG_USE_8_BONE_WEIGHTS;
1239 }
1240
1241 add_surface(tool->get_primitive_type(), arrays, Array(), Dictionary(), tool->get_material(), tool->get_meta("name"), format);
1242 }
1243
1244 set_lightmap_size_hint(Size2(size_x, size_y));
1245
1246 if (gen_cache_size > 0) {
1247 r_dst_cache.resize(gen_cache_size);
1248 memcpy(r_dst_cache.ptrw(), gen_cache, gen_cache_size);
1249 memfree(gen_cache);
1250 }
1251
1252 if (!use_cache) {
1253 // Cache was not used, free the buffers
1254 memfree(gen_vertices);
1255 memfree(gen_indices);
1256 memfree(gen_uvs);
1257 }
1258
1259 return OK;
1260 }
1261
1262 void ImporterMesh::set_lightmap_size_hint(const Size2i &p_size) {
1263 lightmap_size_hint = p_size;
1264 }
1265
1266 Size2i ImporterMesh::get_lightmap_size_hint() const {
1267 return lightmap_size_hint;
1268 }
1269
1270 void ImporterMesh::_bind_methods() {
1271 ClassDB::bind_method(D_METHOD("add_blend_shape", "name"), &ImporterMesh::add_blend_shape);
1272 ClassDB::bind_method(D_METHOD("get_blend_shape_count"), &ImporterMesh::get_blend_shape_count);
1273 ClassDB::bind_method(D_METHOD("get_blend_shape_name", "blend_shape_idx"), &ImporterMesh::get_blend_shape_name);
1274
1275 ClassDB::bind_method(D_METHOD("set_blend_shape_mode", "mode"), &ImporterMesh::set_blend_shape_mode);
1276 ClassDB::bind_method(D_METHOD("get_blend_shape_mode"), &ImporterMesh::get_blend_shape_mode);
1277
1278 ClassDB::bind_method(D_METHOD("add_surface", "primitive", "arrays", "blend_shapes", "lods", "material", "name", "flags"), &ImporterMesh::add_surface, DEFVAL(TypedArray<Array>()), DEFVAL(Dictionary()), DEFVAL(Ref<Material>()), DEFVAL(String()), DEFVAL(0));
1279
1280 ClassDB::bind_method(D_METHOD("get_surface_count"), &ImporterMesh::get_surface_count);
1281 ClassDB::bind_method(D_METHOD("get_surface_primitive_type", "surface_idx"), &ImporterMesh::get_surface_primitive_type);
1282 ClassDB::bind_method(D_METHOD("get_surface_name", "surface_idx"), &ImporterMesh::get_surface_name);
1283 ClassDB::bind_method(D_METHOD("get_surface_arrays", "surface_idx"), &ImporterMesh::get_surface_arrays);
1284 ClassDB::bind_method(D_METHOD("get_surface_blend_shape_arrays", "surface_idx", "blend_shape_idx"), &ImporterMesh::get_surface_blend_shape_arrays);
1285 ClassDB::bind_method(D_METHOD("get_surface_lod_count", "surface_idx"), &ImporterMesh::get_surface_lod_count);
1286 ClassDB::bind_method(D_METHOD("get_surface_lod_size", "surface_idx", "lod_idx"), &ImporterMesh::get_surface_lod_size);
1287 ClassDB::bind_method(D_METHOD("get_surface_lod_indices", "surface_idx", "lod_idx"), &ImporterMesh::get_surface_lod_indices);
1288 ClassDB::bind_method(D_METHOD("get_surface_material", "surface_idx"), &ImporterMesh::get_surface_material);
1289 ClassDB::bind_method(D_METHOD("get_surface_format", "surface_idx"), &ImporterMesh::get_surface_format);
1290
1291 ClassDB::bind_method(D_METHOD("set_surface_name", "surface_idx", "name"), &ImporterMesh::set_surface_name);
1292 ClassDB::bind_method(D_METHOD("set_surface_material", "surface_idx", "material"), &ImporterMesh::set_surface_material);
1293
1294 ClassDB::bind_method(D_METHOD("generate_lods", "normal_merge_angle", "normal_split_angle", "bone_transform_array"), &ImporterMesh::_generate_lods_bind);
1295 ClassDB::bind_method(D_METHOD("get_mesh", "base_mesh"), &ImporterMesh::get_mesh, DEFVAL(Ref<ArrayMesh>()));
1296 ClassDB::bind_static_method("ImporterMesh", D_METHOD("from_mesh", "mesh"), &ImporterMesh::from_mesh);
1297 ClassDB::bind_method(D_METHOD("clear"), &ImporterMesh::clear);
1298
1299 ClassDB::bind_method(D_METHOD("_set_data", "data"), &ImporterMesh::_set_data);
1300 ClassDB::bind_method(D_METHOD("_get_data"), &ImporterMesh::_get_data);
1301
1302 ClassDB::bind_method(D_METHOD("set_lightmap_size_hint", "size"), &ImporterMesh::set_lightmap_size_hint);
1303 ClassDB::bind_method(D_METHOD("get_lightmap_size_hint"), &ImporterMesh::get_lightmap_size_hint);
1304
1305 ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_data", "_get_data");
1306 }