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/convex_hull.h"
35#include "core/math/random_pcg.h"
36#include "core/math/static_raycaster.h"
37#include "scene/resources/surface_tool.h"
38
39#include <cstdint>
40
41void ImporterMesh::Surface::split_normals(const LocalVector<int> &p_indices, const LocalVector<Vector3> &p_normals) {
42 _split_normals(arrays, p_indices, p_normals);
43
44 for (BlendShape &blend_shape : blend_shape_data) {
45 _split_normals(blend_shape.arrays, p_indices, p_normals);
46 }
47}
48
49void ImporterMesh::Surface::_split_normals(Array &r_arrays, const LocalVector<int> &p_indices, const LocalVector<Vector3> &p_normals) {
50 ERR_FAIL_COND(r_arrays.size() != RS::ARRAY_MAX);
51
52 const PackedVector3Array &vertices = r_arrays[RS::ARRAY_VERTEX];
53 int current_vertex_count = vertices.size();
54 int new_vertex_count = p_indices.size();
55 int final_vertex_count = current_vertex_count + new_vertex_count;
56 const int *indices_ptr = p_indices.ptr();
57
58 for (int i = 0; i < r_arrays.size(); i++) {
59 if (i == RS::ARRAY_INDEX) {
60 continue;
61 }
62
63 if (r_arrays[i].get_type() == Variant::NIL) {
64 continue;
65 }
66
67 switch (r_arrays[i].get_type()) {
68 case Variant::PACKED_VECTOR3_ARRAY: {
69 PackedVector3Array data = r_arrays[i];
70 data.resize(final_vertex_count);
71 Vector3 *data_ptr = data.ptrw();
72 if (i == RS::ARRAY_NORMAL) {
73 const Vector3 *normals_ptr = p_normals.ptr();
74 memcpy(&data_ptr[current_vertex_count], normals_ptr, sizeof(Vector3) * new_vertex_count);
75 } else {
76 for (int j = 0; j < new_vertex_count; j++) {
77 data_ptr[current_vertex_count + j] = data_ptr[indices_ptr[j]];
78 }
79 }
80 r_arrays[i] = data;
81 } break;
82 case Variant::PACKED_VECTOR2_ARRAY: {
83 PackedVector2Array data = r_arrays[i];
84 data.resize(final_vertex_count);
85 Vector2 *data_ptr = data.ptrw();
86 for (int j = 0; j < new_vertex_count; j++) {
87 data_ptr[current_vertex_count + j] = data_ptr[indices_ptr[j]];
88 }
89 r_arrays[i] = data;
90 } break;
91 case Variant::PACKED_FLOAT32_ARRAY: {
92 PackedFloat32Array data = r_arrays[i];
93 int elements = data.size() / current_vertex_count;
94 data.resize(final_vertex_count * elements);
95 float *data_ptr = data.ptrw();
96 for (int j = 0; j < new_vertex_count; j++) {
97 memcpy(&data_ptr[(current_vertex_count + j) * elements], &data_ptr[indices_ptr[j] * elements], sizeof(float) * elements);
98 }
99 r_arrays[i] = data;
100 } break;
101 case Variant::PACKED_INT32_ARRAY: {
102 PackedInt32Array data = r_arrays[i];
103 int elements = data.size() / current_vertex_count;
104 data.resize(final_vertex_count * elements);
105 int32_t *data_ptr = data.ptrw();
106 for (int j = 0; j < new_vertex_count; j++) {
107 memcpy(&data_ptr[(current_vertex_count + j) * elements], &data_ptr[indices_ptr[j] * elements], sizeof(int32_t) * elements);
108 }
109 r_arrays[i] = data;
110 } break;
111 case Variant::PACKED_BYTE_ARRAY: {
112 PackedByteArray data = r_arrays[i];
113 int elements = data.size() / current_vertex_count;
114 data.resize(final_vertex_count * elements);
115 uint8_t *data_ptr = data.ptrw();
116 for (int j = 0; j < new_vertex_count; j++) {
117 memcpy(&data_ptr[(current_vertex_count + j) * elements], &data_ptr[indices_ptr[j] * elements], sizeof(uint8_t) * elements);
118 }
119 r_arrays[i] = data;
120 } break;
121 case Variant::PACKED_COLOR_ARRAY: {
122 PackedColorArray data = r_arrays[i];
123 data.resize(final_vertex_count);
124 Color *data_ptr = data.ptrw();
125 for (int j = 0; j < new_vertex_count; j++) {
126 data_ptr[current_vertex_count + j] = data_ptr[indices_ptr[j]];
127 }
128 r_arrays[i] = data;
129 } break;
130 default: {
131 ERR_FAIL_MSG("Unhandled array type.");
132 } break;
133 }
134 }
135}
136
137void ImporterMesh::add_blend_shape(const String &p_name) {
138 ERR_FAIL_COND(surfaces.size() > 0);
139 blend_shapes.push_back(p_name);
140}
141
142int ImporterMesh::get_blend_shape_count() const {
143 return blend_shapes.size();
144}
145
146String ImporterMesh::get_blend_shape_name(int p_blend_shape) const {
147 ERR_FAIL_INDEX_V(p_blend_shape, blend_shapes.size(), String());
148 return blend_shapes[p_blend_shape];
149}
150
151void ImporterMesh::set_blend_shape_mode(Mesh::BlendShapeMode p_blend_shape_mode) {
152 blend_shape_mode = p_blend_shape_mode;
153}
154
155Mesh::BlendShapeMode ImporterMesh::get_blend_shape_mode() const {
156 return blend_shape_mode;
157}
158
159void 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_name, const uint32_t p_flags) {
160 ERR_FAIL_COND(p_blend_shapes.size() != blend_shapes.size());
161 ERR_FAIL_COND(p_arrays.size() != Mesh::ARRAY_MAX);
162 Surface s;
163 s.primitive = p_primitive;
164 s.arrays = p_arrays;
165 s.name = p_name;
166 s.flags = p_flags;
167
168 Vector<Vector3> vertex_array = p_arrays[Mesh::ARRAY_VERTEX];
169 int vertex_count = vertex_array.size();
170 ERR_FAIL_COND(vertex_count == 0);
171
172 for (int i = 0; i < blend_shapes.size(); i++) {
173 Array bsdata = p_blend_shapes[i];
174 ERR_FAIL_COND(bsdata.size() != Mesh::ARRAY_MAX);
175 Vector<Vector3> vertex_data = bsdata[Mesh::ARRAY_VERTEX];
176 ERR_FAIL_COND(vertex_data.size() != vertex_count);
177 Surface::BlendShape bs;
178 bs.arrays = bsdata;
179 s.blend_shape_data.push_back(bs);
180 }
181
182 List<Variant> lods;
183 p_lods.get_key_list(&lods);
184 for (const Variant &E : lods) {
185 ERR_CONTINUE(!E.is_num());
186 Surface::LOD lod;
187 lod.distance = E;
188 lod.indices = p_lods[E];
189 ERR_CONTINUE(lod.indices.size() == 0);
190 s.lods.push_back(lod);
191 }
192
193 s.material = p_material;
194
195 surfaces.push_back(s);
196 mesh.unref();
197}
198
199int ImporterMesh::get_surface_count() const {
200 return surfaces.size();
201}
202
203Mesh::PrimitiveType ImporterMesh::get_surface_primitive_type(int p_surface) {
204 ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Mesh::PRIMITIVE_MAX);
205 return surfaces[p_surface].primitive;
206}
207Array ImporterMesh::get_surface_arrays(int p_surface) const {
208 ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array());
209 return surfaces[p_surface].arrays;
210}
211String ImporterMesh::get_surface_name(int p_surface) const {
212 ERR_FAIL_INDEX_V(p_surface, surfaces.size(), String());
213 return surfaces[p_surface].name;
214}
215void ImporterMesh::set_surface_name(int p_surface, const String &p_name) {
216 ERR_FAIL_INDEX(p_surface, surfaces.size());
217 surfaces.write[p_surface].name = p_name;
218 mesh.unref();
219}
220
221Array ImporterMesh::get_surface_blend_shape_arrays(int p_surface, int p_blend_shape) const {
222 ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array());
223 ERR_FAIL_INDEX_V(p_blend_shape, surfaces[p_surface].blend_shape_data.size(), Array());
224 return surfaces[p_surface].blend_shape_data[p_blend_shape].arrays;
225}
226int ImporterMesh::get_surface_lod_count(int p_surface) const {
227 ERR_FAIL_INDEX_V(p_surface, surfaces.size(), 0);
228 return surfaces[p_surface].lods.size();
229}
230Vector<int> ImporterMesh::get_surface_lod_indices(int p_surface, int p_lod) const {
231 ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Vector<int>());
232 ERR_FAIL_INDEX_V(p_lod, surfaces[p_surface].lods.size(), Vector<int>());
233
234 return surfaces[p_surface].lods[p_lod].indices;
235}
236
237float ImporterMesh::get_surface_lod_size(int p_surface, int p_lod) const {
238 ERR_FAIL_INDEX_V(p_surface, surfaces.size(), 0);
239 ERR_FAIL_INDEX_V(p_lod, surfaces[p_surface].lods.size(), 0);
240 return surfaces[p_surface].lods[p_lod].distance;
241}
242
243uint32_t ImporterMesh::get_surface_format(int p_surface) const {
244 ERR_FAIL_INDEX_V(p_surface, surfaces.size(), 0);
245 return surfaces[p_surface].flags;
246}
247
248Ref<Material> ImporterMesh::get_surface_material(int p_surface) const {
249 ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Ref<Material>());
250 return surfaces[p_surface].material;
251}
252
253void ImporterMesh::set_surface_material(int p_surface, const Ref<Material> &p_material) {
254 ERR_FAIL_INDEX(p_surface, surfaces.size());
255 surfaces.write[p_surface].material = p_material;
256 mesh.unref();
257}
258
259#define VERTEX_SKIN_FUNC(bone_count, vert_idx, read_array, write_array, transform_array, bone_array, weight_array) \
260 Vector3 transformed_vert; \
261 for (unsigned int weight_idx = 0; weight_idx < bone_count; weight_idx++) { \
262 int bone_idx = bone_array[vert_idx * bone_count + weight_idx]; \
263 float w = weight_array[vert_idx * bone_count + weight_idx]; \
264 if (w < FLT_EPSILON) { \
265 continue; \
266 } \
267 ERR_FAIL_INDEX(bone_idx, static_cast<int>(transform_array.size())); \
268 transformed_vert += transform_array[bone_idx].xform(read_array[vert_idx]) * w; \
269 } \
270 write_array[vert_idx] = transformed_vert;
271
272void ImporterMesh::generate_lods(float p_normal_merge_angle, float p_normal_split_angle, Array p_bone_transform_array) {
273 if (!SurfaceTool::simplify_scale_func) {
274 return;
275 }
276 if (!SurfaceTool::simplify_with_attrib_func) {
277 return;
278 }
279 if (!SurfaceTool::optimize_vertex_cache_func) {
280 return;
281 }
282
283 LocalVector<Transform3D> bone_transform_vector;
284 for (int i = 0; i < p_bone_transform_array.size(); i++) {
285 ERR_FAIL_COND(p_bone_transform_array[i].get_type() != Variant::TRANSFORM3D);
286 bone_transform_vector.push_back(p_bone_transform_array[i]);
287 }
288
289 for (int i = 0; i < surfaces.size(); i++) {
290 if (surfaces[i].primitive != Mesh::PRIMITIVE_TRIANGLES) {
291 continue;
292 }
293
294 surfaces.write[i].lods.clear();
295 Vector<Vector3> vertices = surfaces[i].arrays[RS::ARRAY_VERTEX];
296 PackedInt32Array indices = surfaces[i].arrays[RS::ARRAY_INDEX];
297 Vector<Vector3> normals = surfaces[i].arrays[RS::ARRAY_NORMAL];
298 Vector<Vector2> uvs = surfaces[i].arrays[RS::ARRAY_TEX_UV];
299 Vector<Vector2> uv2s = surfaces[i].arrays[RS::ARRAY_TEX_UV2];
300 Vector<int> bones = surfaces[i].arrays[RS::ARRAY_BONES];
301 Vector<float> weights = surfaces[i].arrays[RS::ARRAY_WEIGHTS];
302
303 unsigned int index_count = indices.size();
304 unsigned int vertex_count = vertices.size();
305
306 if (index_count == 0) {
307 continue; //no lods if no indices
308 }
309
310 const Vector3 *vertices_ptr = vertices.ptr();
311 const int *indices_ptr = indices.ptr();
312
313 if (normals.is_empty()) {
314 normals.resize(index_count);
315 Vector3 *n_ptr = normals.ptrw();
316 for (unsigned int j = 0; j < index_count; j += 3) {
317 const Vector3 &v0 = vertices_ptr[indices_ptr[j + 0]];
318 const Vector3 &v1 = vertices_ptr[indices_ptr[j + 1]];
319 const Vector3 &v2 = vertices_ptr[indices_ptr[j + 2]];
320 Vector3 n = vec3_cross(v0 - v2, v0 - v1).normalized();
321 n_ptr[j + 0] = n;
322 n_ptr[j + 1] = n;
323 n_ptr[j + 2] = n;
324 }
325 }
326
327 if (bones.size() > 0 && weights.size() && bone_transform_vector.size() > 0) {
328 Vector3 *vertices_ptrw = vertices.ptrw();
329
330 // Apply bone transforms to regular surface.
331 unsigned int bone_weight_length = surfaces[i].flags & Mesh::ARRAY_FLAG_USE_8_BONE_WEIGHTS ? 8 : 4;
332
333 const int *bo = bones.ptr();
334 const float *we = weights.ptr();
335
336 for (unsigned int j = 0; j < vertex_count; j++) {
337 VERTEX_SKIN_FUNC(bone_weight_length, j, vertices_ptr, vertices_ptrw, bone_transform_vector, bo, we)
338 }
339
340 vertices_ptr = vertices.ptr();
341 }
342
343 float normal_merge_threshold = Math::cos(Math::deg_to_rad(p_normal_merge_angle));
344 float normal_pre_split_threshold = Math::cos(Math::deg_to_rad(MIN(180.0f, p_normal_split_angle * 2.0f)));
345 float normal_split_threshold = Math::cos(Math::deg_to_rad(p_normal_split_angle));
346 const Vector3 *normals_ptr = normals.ptr();
347
348 HashMap<Vector3, LocalVector<Pair<int, int>>> unique_vertices;
349
350 LocalVector<int> vertex_remap;
351 LocalVector<int> vertex_inverse_remap;
352 LocalVector<Vector3> merged_vertices;
353 LocalVector<Vector3> merged_normals;
354 LocalVector<int> merged_normals_counts;
355 const Vector2 *uvs_ptr = uvs.ptr();
356 const Vector2 *uv2s_ptr = uv2s.ptr();
357
358 for (unsigned int j = 0; j < vertex_count; j++) {
359 const Vector3 &v = vertices_ptr[j];
360 const Vector3 &n = normals_ptr[j];
361
362 HashMap<Vector3, LocalVector<Pair<int, int>>>::Iterator E = unique_vertices.find(v);
363
364 if (E) {
365 const LocalVector<Pair<int, int>> &close_verts = E->value;
366
367 bool found = false;
368 for (const Pair<int, int> &idx : close_verts) {
369 bool is_uvs_close = (!uvs_ptr || uvs_ptr[j].distance_squared_to(uvs_ptr[idx.second]) < CMP_EPSILON2);
370 bool is_uv2s_close = (!uv2s_ptr || uv2s_ptr[j].distance_squared_to(uv2s_ptr[idx.second]) < CMP_EPSILON2);
371 ERR_FAIL_INDEX(idx.second, normals.size());
372 bool is_normals_close = normals[idx.second].dot(n) > normal_merge_threshold;
373 if (is_uvs_close && is_uv2s_close && is_normals_close) {
374 vertex_remap.push_back(idx.first);
375 merged_normals[idx.first] += normals[idx.second];
376 merged_normals_counts[idx.first]++;
377 found = true;
378 break;
379 }
380 }
381
382 if (!found) {
383 int vcount = merged_vertices.size();
384 unique_vertices[v].push_back(Pair<int, int>(vcount, j));
385 vertex_inverse_remap.push_back(j);
386 merged_vertices.push_back(v);
387 vertex_remap.push_back(vcount);
388 merged_normals.push_back(normals_ptr[j]);
389 merged_normals_counts.push_back(1);
390 }
391 } else {
392 int vcount = merged_vertices.size();
393 unique_vertices[v] = LocalVector<Pair<int, int>>();
394 unique_vertices[v].push_back(Pair<int, int>(vcount, j));
395 vertex_inverse_remap.push_back(j);
396 merged_vertices.push_back(v);
397 vertex_remap.push_back(vcount);
398 merged_normals.push_back(normals_ptr[j]);
399 merged_normals_counts.push_back(1);
400 }
401 }
402
403 LocalVector<int> merged_indices;
404 merged_indices.resize(index_count);
405 for (unsigned int j = 0; j < index_count; j++) {
406 merged_indices[j] = vertex_remap[indices[j]];
407 }
408
409 unsigned int merged_vertex_count = merged_vertices.size();
410 const Vector3 *merged_vertices_ptr = merged_vertices.ptr();
411 const int32_t *merged_indices_ptr = merged_indices.ptr();
412
413 {
414 const int *counts_ptr = merged_normals_counts.ptr();
415 Vector3 *merged_normals_ptrw = merged_normals.ptr();
416 for (unsigned int j = 0; j < merged_vertex_count; j++) {
417 merged_normals_ptrw[j] /= counts_ptr[j];
418 }
419 }
420
421 LocalVector<float> normal_weights;
422 normal_weights.resize(merged_vertex_count);
423 for (unsigned int j = 0; j < merged_vertex_count; j++) {
424 normal_weights[j] = 2.0; // Give some weight to normal preservation, may be worth exposing as an import setting
425 }
426
427 Vector<float> merged_vertices_f32 = vector3_to_float32_array(merged_vertices_ptr, merged_vertex_count);
428 float scale = SurfaceTool::simplify_scale_func(merged_vertices_f32.ptr(), merged_vertex_count, sizeof(float) * 3);
429
430 unsigned int index_target = 12; // Start with the smallest target, 4 triangles
431 unsigned int last_index_count = 0;
432
433 int split_vertex_count = vertex_count;
434 LocalVector<Vector3> split_vertex_normals;
435 LocalVector<int> split_vertex_indices;
436 split_vertex_normals.reserve(index_count / 3);
437 split_vertex_indices.reserve(index_count / 3);
438
439 RandomPCG pcg;
440 pcg.seed(123456789); // Keep seed constant across imports
441
442 Ref<StaticRaycaster> raycaster = StaticRaycaster::create();
443 if (raycaster.is_valid()) {
444 raycaster->add_mesh(vertices, indices, 0);
445 raycaster->commit();
446 }
447
448 const float max_mesh_error = FLT_MAX; // We don't want to limit by error, just by index target
449 float mesh_error = 0.0f;
450
451 while (index_target < index_count) {
452 PackedInt32Array new_indices;
453 new_indices.resize(index_count);
454
455 Vector<float> merged_normals_f32 = vector3_to_float32_array(merged_normals.ptr(), merged_normals.size());
456 const int simplify_options = SurfaceTool::SIMPLIFY_LOCK_BORDER;
457
458 size_t new_index_count = SurfaceTool::simplify_with_attrib_func(
459 (unsigned int *)new_indices.ptrw(),
460 (const uint32_t *)merged_indices_ptr, index_count,
461 merged_vertices_f32.ptr(), merged_vertex_count,
462 sizeof(float) * 3, // Vertex stride
463 index_target,
464 max_mesh_error,
465 simplify_options,
466 &mesh_error,
467 merged_normals_f32.ptr(),
468 normal_weights.ptr(), 3);
469
470 if (new_index_count < last_index_count * 1.5f) {
471 index_target = index_target * 1.5f;
472 continue;
473 }
474
475 if (new_index_count == 0 || (new_index_count >= (index_count * 0.75f))) {
476 break;
477 }
478
479 new_indices.resize(new_index_count);
480
481 LocalVector<LocalVector<int>> vertex_corners;
482 vertex_corners.resize(vertex_count);
483 {
484 int *ptrw = new_indices.ptrw();
485 for (unsigned int j = 0; j < new_index_count; j++) {
486 const int &remapped = vertex_inverse_remap[ptrw[j]];
487 vertex_corners[remapped].push_back(j);
488 ptrw[j] = remapped;
489 }
490 }
491
492 if (raycaster.is_valid()) {
493 float error_factor = 1.0f / (scale * MAX(mesh_error, 0.15));
494 const float ray_bias = 0.05;
495 float ray_length = ray_bias + mesh_error * scale * 3.0f;
496
497 Vector<StaticRaycaster::Ray> rays;
498 LocalVector<Vector2> ray_uvs;
499
500 int32_t *new_indices_ptr = new_indices.ptrw();
501
502 int current_ray_count = 0;
503 for (unsigned int j = 0; j < new_index_count; j += 3) {
504 const Vector3 &v0 = vertices_ptr[new_indices_ptr[j + 0]];
505 const Vector3 &v1 = vertices_ptr[new_indices_ptr[j + 1]];
506 const Vector3 &v2 = vertices_ptr[new_indices_ptr[j + 2]];
507 Vector3 face_normal = vec3_cross(v0 - v2, v0 - v1);
508 float face_area = face_normal.length(); // Actually twice the face area, since it's the same error_factor on all faces, we don't care
509
510 Vector3 dir = face_normal / face_area;
511 int ray_count = CLAMP(5.0 * face_area * error_factor, 16, 64);
512
513 rays.resize(current_ray_count + ray_count);
514 StaticRaycaster::Ray *rays_ptr = rays.ptrw();
515
516 ray_uvs.resize(current_ray_count + ray_count);
517 Vector2 *ray_uvs_ptr = ray_uvs.ptr();
518
519 for (int k = 0; k < ray_count; k++) {
520 float u = pcg.randf();
521 float v = pcg.randf();
522
523 if (u + v >= 1.0f) {
524 u = 1.0f - u;
525 v = 1.0f - v;
526 }
527
528 u = 0.9f * u + 0.05f / 3.0f; // Give barycentric coordinates some padding, we don't want to sample right on the edge
529 v = 0.9f * v + 0.05f / 3.0f; // v = (v - one_third) * 0.95f + one_third;
530 float w = 1.0f - u - v;
531
532 Vector3 org = v0 * w + v1 * u + v2 * v;
533 org -= dir * ray_bias;
534 rays_ptr[current_ray_count + k] = StaticRaycaster::Ray(org, dir, 0.0f, ray_length);
535 rays_ptr[current_ray_count + k].id = j / 3;
536 ray_uvs_ptr[current_ray_count + k] = Vector2(u, v);
537 }
538
539 current_ray_count += ray_count;
540 }
541
542 raycaster->intersect(rays);
543
544 LocalVector<Vector3> ray_normals;
545 LocalVector<real_t> ray_normal_weights;
546
547 ray_normals.resize(new_index_count);
548 ray_normal_weights.resize(new_index_count);
549
550 for (unsigned int j = 0; j < new_index_count; j++) {
551 ray_normal_weights[j] = 0.0f;
552 }
553
554 const StaticRaycaster::Ray *rp = rays.ptr();
555 for (int j = 0; j < rays.size(); j++) {
556 if (rp[j].geomID != 0) { // Ray missed
557 continue;
558 }
559
560 if (rp[j].normal.normalized().dot(rp[j].dir) > 0.0f) { // Hit a back face.
561 continue;
562 }
563
564 const float &u = rp[j].u;
565 const float &v = rp[j].v;
566 const float w = 1.0f - u - v;
567
568 const unsigned int &hit_tri_id = rp[j].primID;
569 const unsigned int &orig_tri_id = rp[j].id;
570
571 const Vector3 &n0 = normals_ptr[indices_ptr[hit_tri_id * 3 + 0]];
572 const Vector3 &n1 = normals_ptr[indices_ptr[hit_tri_id * 3 + 1]];
573 const Vector3 &n2 = normals_ptr[indices_ptr[hit_tri_id * 3 + 2]];
574 Vector3 normal = n0 * w + n1 * u + n2 * v;
575
576 Vector2 orig_uv = ray_uvs[j];
577 const real_t orig_bary[3] = { 1.0f - orig_uv.x - orig_uv.y, orig_uv.x, orig_uv.y };
578 for (int k = 0; k < 3; k++) {
579 int idx = orig_tri_id * 3 + k;
580 real_t weight = orig_bary[k];
581 ray_normals[idx] += normal * weight;
582 ray_normal_weights[idx] += weight;
583 }
584 }
585
586 for (unsigned int j = 0; j < new_index_count; j++) {
587 if (ray_normal_weights[j] < 1.0f) { // Not enough data, the new normal would be just a bad guess
588 ray_normals[j] = Vector3();
589 } else {
590 ray_normals[j] /= ray_normal_weights[j];
591 }
592 }
593
594 LocalVector<LocalVector<int>> normal_group_indices;
595 LocalVector<Vector3> normal_group_averages;
596 normal_group_indices.reserve(24);
597 normal_group_averages.reserve(24);
598
599 for (unsigned int j = 0; j < vertex_count; j++) {
600 const LocalVector<int> &corners = vertex_corners[j];
601 const Vector3 &vertex_normal = normals_ptr[j];
602
603 for (const int &corner_idx : corners) {
604 const Vector3 &ray_normal = ray_normals[corner_idx];
605
606 if (ray_normal.length_squared() < CMP_EPSILON2) {
607 continue;
608 }
609
610 bool found = false;
611 for (unsigned int l = 0; l < normal_group_indices.size(); l++) {
612 LocalVector<int> &group_indices = normal_group_indices[l];
613 Vector3 n = normal_group_averages[l] / group_indices.size();
614 if (n.dot(ray_normal) > normal_pre_split_threshold) {
615 found = true;
616 group_indices.push_back(corner_idx);
617 normal_group_averages[l] += ray_normal;
618 break;
619 }
620 }
621
622 if (!found) {
623 normal_group_indices.push_back({ corner_idx });
624 normal_group_averages.push_back(ray_normal);
625 }
626 }
627
628 for (unsigned int k = 0; k < normal_group_indices.size(); k++) {
629 LocalVector<int> &group_indices = normal_group_indices[k];
630 Vector3 n = normal_group_averages[k] / group_indices.size();
631
632 if (vertex_normal.dot(n) < normal_split_threshold) {
633 split_vertex_indices.push_back(j);
634 split_vertex_normals.push_back(n);
635 int new_idx = split_vertex_count++;
636 for (const int &index : group_indices) {
637 new_indices_ptr[index] = new_idx;
638 }
639 }
640 }
641
642 normal_group_indices.clear();
643 normal_group_averages.clear();
644 }
645 }
646
647 Surface::LOD lod;
648 lod.distance = MAX(mesh_error * scale, CMP_EPSILON2);
649 lod.indices = new_indices;
650 surfaces.write[i].lods.push_back(lod);
651 index_target = MAX(new_index_count, index_target) * 2;
652 last_index_count = new_index_count;
653
654 if (mesh_error == 0.0f) {
655 break;
656 }
657 }
658
659 surfaces.write[i].split_normals(split_vertex_indices, split_vertex_normals);
660 surfaces.write[i].lods.sort_custom<Surface::LODComparator>();
661
662 for (int j = 0; j < surfaces.write[i].lods.size(); j++) {
663 Surface::LOD &lod = surfaces.write[i].lods.write[j];
664 unsigned int *lod_indices_ptr = (unsigned int *)lod.indices.ptrw();
665 SurfaceTool::optimize_vertex_cache_func(lod_indices_ptr, lod_indices_ptr, lod.indices.size(), split_vertex_count);
666 }
667 }
668}
669
670bool ImporterMesh::has_mesh() const {
671 return mesh.is_valid();
672}
673
674Ref<ArrayMesh> ImporterMesh::get_mesh(const Ref<ArrayMesh> &p_base) {
675 ERR_FAIL_COND_V(surfaces.size() == 0, Ref<ArrayMesh>());
676
677 if (mesh.is_null()) {
678 if (p_base.is_valid()) {
679 mesh = p_base;
680 }
681 if (mesh.is_null()) {
682 mesh.instantiate();
683 }
684 mesh->set_name(get_name());
685 if (has_meta("import_id")) {
686 mesh->set_meta("import_id", get_meta("import_id"));
687 }
688 for (int i = 0; i < blend_shapes.size(); i++) {
689 mesh->add_blend_shape(blend_shapes[i]);
690 }
691 mesh->set_blend_shape_mode(blend_shape_mode);
692 for (int i = 0; i < surfaces.size(); i++) {
693 Array bs_data;
694 if (surfaces[i].blend_shape_data.size()) {
695 for (int j = 0; j < surfaces[i].blend_shape_data.size(); j++) {
696 bs_data.push_back(surfaces[i].blend_shape_data[j].arrays);
697 }
698 }
699 Dictionary lods;
700 if (surfaces[i].lods.size()) {
701 for (int j = 0; j < surfaces[i].lods.size(); j++) {
702 lods[surfaces[i].lods[j].distance] = surfaces[i].lods[j].indices;
703 }
704 }
705
706 mesh->add_surface_from_arrays(surfaces[i].primitive, surfaces[i].arrays, bs_data, lods, surfaces[i].flags);
707 if (surfaces[i].material.is_valid()) {
708 mesh->surface_set_material(mesh->get_surface_count() - 1, surfaces[i].material);
709 }
710 if (!surfaces[i].name.is_empty()) {
711 mesh->surface_set_name(mesh->get_surface_count() - 1, surfaces[i].name);
712 }
713 }
714
715 mesh->set_lightmap_size_hint(lightmap_size_hint);
716
717 if (shadow_mesh.is_valid()) {
718 Ref<ArrayMesh> shadow = shadow_mesh->get_mesh();
719 mesh->set_shadow_mesh(shadow);
720 }
721 }
722
723 return mesh;
724}
725
726void ImporterMesh::clear() {
727 surfaces.clear();
728 blend_shapes.clear();
729 mesh.unref();
730}
731
732void ImporterMesh::create_shadow_mesh() {
733 if (shadow_mesh.is_valid()) {
734 shadow_mesh.unref();
735 }
736
737 //no shadow mesh for blendshapes
738 if (blend_shapes.size() > 0) {
739 return;
740 }
741 //no shadow mesh for skeletons
742 for (int i = 0; i < surfaces.size(); i++) {
743 if (surfaces[i].arrays[RS::ARRAY_BONES].get_type() != Variant::NIL) {
744 return;
745 }
746 if (surfaces[i].arrays[RS::ARRAY_WEIGHTS].get_type() != Variant::NIL) {
747 return;
748 }
749 }
750
751 shadow_mesh.instantiate();
752
753 for (int i = 0; i < surfaces.size(); i++) {
754 LocalVector<int> vertex_remap;
755 Vector<Vector3> new_vertices;
756 Vector<Vector3> vertices = surfaces[i].arrays[RS::ARRAY_VERTEX];
757 int vertex_count = vertices.size();
758 {
759 HashMap<Vector3, int> unique_vertices;
760 const Vector3 *vptr = vertices.ptr();
761 for (int j = 0; j < vertex_count; j++) {
762 const Vector3 &v = vptr[j];
763
764 HashMap<Vector3, int>::Iterator E = unique_vertices.find(v);
765
766 if (E) {
767 vertex_remap.push_back(E->value);
768 } else {
769 int vcount = unique_vertices.size();
770 unique_vertices[v] = vcount;
771 vertex_remap.push_back(vcount);
772 new_vertices.push_back(v);
773 }
774 }
775 }
776
777 Array new_surface;
778 new_surface.resize(RS::ARRAY_MAX);
779 Dictionary lods;
780
781 // print_line("original vertex count: " + itos(vertices.size()) + " new vertex count: " + itos(new_vertices.size()));
782
783 new_surface[RS::ARRAY_VERTEX] = new_vertices;
784
785 Vector<int> indices = surfaces[i].arrays[RS::ARRAY_INDEX];
786 if (indices.size()) {
787 int index_count = indices.size();
788 const int *index_rptr = indices.ptr();
789 Vector<int> new_indices;
790 new_indices.resize(indices.size());
791 int *index_wptr = new_indices.ptrw();
792
793 for (int j = 0; j < index_count; j++) {
794 int index = index_rptr[j];
795 ERR_FAIL_INDEX(index, vertex_count);
796 index_wptr[j] = vertex_remap[index];
797 }
798
799 new_surface[RS::ARRAY_INDEX] = new_indices;
800
801 // Make sure the same LODs as the full version are used.
802 // This makes it more coherent between rendered model and its shadows.
803 for (int j = 0; j < surfaces[i].lods.size(); j++) {
804 indices = surfaces[i].lods[j].indices;
805
806 index_count = indices.size();
807 index_rptr = indices.ptr();
808 new_indices.resize(indices.size());
809 index_wptr = new_indices.ptrw();
810
811 for (int k = 0; k < index_count; k++) {
812 int index = index_rptr[k];
813 ERR_FAIL_INDEX(index, vertex_count);
814 index_wptr[k] = vertex_remap[index];
815 }
816
817 lods[surfaces[i].lods[j].distance] = new_indices;
818 }
819 }
820
821 shadow_mesh->add_surface(surfaces[i].primitive, new_surface, Array(), lods, Ref<Material>(), surfaces[i].name, surfaces[i].flags);
822 }
823}
824
825Ref<ImporterMesh> ImporterMesh::get_shadow_mesh() const {
826 return shadow_mesh;
827}
828
829void ImporterMesh::_set_data(const Dictionary &p_data) {
830 clear();
831 if (p_data.has("blend_shape_names")) {
832 blend_shapes = p_data["blend_shape_names"];
833 }
834 if (p_data.has("surfaces")) {
835 Array surface_arr = p_data["surfaces"];
836 for (int i = 0; i < surface_arr.size(); i++) {
837 Dictionary s = surface_arr[i];
838 ERR_CONTINUE(!s.has("primitive"));
839 ERR_CONTINUE(!s.has("arrays"));
840 Mesh::PrimitiveType prim = Mesh::PrimitiveType(int(s["primitive"]));
841 ERR_CONTINUE(prim >= Mesh::PRIMITIVE_MAX);
842 Array arr = s["arrays"];
843 Dictionary lods;
844 String surf_name;
845 if (s.has("name")) {
846 surf_name = s["name"];
847 }
848 if (s.has("lods")) {
849 lods = s["lods"];
850 }
851 Array b_shapes;
852 if (s.has("b_shapes")) {
853 b_shapes = s["b_shapes"];
854 }
855 Ref<Material> material;
856 if (s.has("material")) {
857 material = s["material"];
858 }
859 uint32_t flags = 0;
860 if (s.has("flags")) {
861 flags = s["flags"];
862 }
863 add_surface(prim, arr, b_shapes, lods, material, surf_name, flags);
864 }
865 }
866}
867Dictionary ImporterMesh::_get_data() const {
868 Dictionary data;
869 if (blend_shapes.size()) {
870 data["blend_shape_names"] = blend_shapes;
871 }
872 Array surface_arr;
873 for (int i = 0; i < surfaces.size(); i++) {
874 Dictionary d;
875 d["primitive"] = surfaces[i].primitive;
876 d["arrays"] = surfaces[i].arrays;
877 if (surfaces[i].blend_shape_data.size()) {
878 Array bs_data;
879 for (int j = 0; j < surfaces[i].blend_shape_data.size(); j++) {
880 bs_data.push_back(surfaces[i].blend_shape_data[j].arrays);
881 }
882 d["blend_shapes"] = bs_data;
883 }
884 if (surfaces[i].lods.size()) {
885 Dictionary lods;
886 for (int j = 0; j < surfaces[i].lods.size(); j++) {
887 lods[surfaces[i].lods[j].distance] = surfaces[i].lods[j].indices;
888 }
889 d["lods"] = lods;
890 }
891
892 if (surfaces[i].material.is_valid()) {
893 d["material"] = surfaces[i].material;
894 }
895
896 if (!surfaces[i].name.is_empty()) {
897 d["name"] = surfaces[i].name;
898 }
899
900 if (surfaces[i].flags != 0) {
901 d["flags"] = surfaces[i].flags;
902 }
903
904 surface_arr.push_back(d);
905 }
906 data["surfaces"] = surface_arr;
907 return data;
908}
909
910Vector<Face3> ImporterMesh::get_faces() const {
911 Vector<Face3> faces;
912 for (int i = 0; i < surfaces.size(); i++) {
913 if (surfaces[i].primitive == Mesh::PRIMITIVE_TRIANGLES) {
914 Vector<Vector3> vertices = surfaces[i].arrays[Mesh::ARRAY_VERTEX];
915 Vector<int> indices = surfaces[i].arrays[Mesh::ARRAY_INDEX];
916 if (indices.size()) {
917 for (int j = 0; j < indices.size(); j += 3) {
918 Face3 f;
919 f.vertex[0] = vertices[indices[j + 0]];
920 f.vertex[1] = vertices[indices[j + 1]];
921 f.vertex[2] = vertices[indices[j + 2]];
922 faces.push_back(f);
923 }
924 } else {
925 for (int j = 0; j < vertices.size(); j += 3) {
926 Face3 f;
927 f.vertex[0] = vertices[j + 0];
928 f.vertex[1] = vertices[j + 1];
929 f.vertex[2] = vertices[j + 2];
930 faces.push_back(f);
931 }
932 }
933 }
934 }
935
936 return faces;
937}
938
939Vector<Ref<Shape3D>> ImporterMesh::convex_decompose(const Ref<MeshConvexDecompositionSettings> &p_settings) const {
940 ERR_FAIL_NULL_V(Mesh::convex_decomposition_function, Vector<Ref<Shape3D>>());
941
942 const Vector<Face3> faces = get_faces();
943 int face_count = faces.size();
944
945 Vector<Vector3> vertices;
946 uint32_t vertex_count = 0;
947 vertices.resize(face_count * 3);
948 Vector<uint32_t> indices;
949 indices.resize(face_count * 3);
950 {
951 HashMap<Vector3, uint32_t> vertex_map;
952 Vector3 *vertex_w = vertices.ptrw();
953 uint32_t *index_w = indices.ptrw();
954 for (int i = 0; i < face_count; i++) {
955 for (int j = 0; j < 3; j++) {
956 const Vector3 &vertex = faces[i].vertex[j];
957 HashMap<Vector3, uint32_t>::Iterator found_vertex = vertex_map.find(vertex);
958 uint32_t index;
959 if (found_vertex) {
960 index = found_vertex->value;
961 } else {
962 index = ++vertex_count;
963 vertex_map[vertex] = index;
964 vertex_w[index] = vertex;
965 }
966 index_w[i * 3 + j] = index;
967 }
968 }
969 }
970 vertices.resize(vertex_count);
971
972 Vector<Vector<Vector3>> decomposed = Mesh::convex_decomposition_function((real_t *)vertices.ptr(), vertex_count, indices.ptr(), face_count, p_settings, nullptr);
973
974 Vector<Ref<Shape3D>> ret;
975
976 for (int i = 0; i < decomposed.size(); i++) {
977 Ref<ConvexPolygonShape3D> shape;
978 shape.instantiate();
979 shape->set_points(decomposed[i]);
980 ret.push_back(shape);
981 }
982
983 return ret;
984}
985
986Ref<ConvexPolygonShape3D> ImporterMesh::create_convex_shape(bool p_clean, bool p_simplify) const {
987 if (p_simplify) {
988 Ref<MeshConvexDecompositionSettings> settings;
989 settings.instantiate();
990 settings->set_max_convex_hulls(1);
991 Vector<Ref<Shape3D>> decomposed = convex_decompose(settings);
992 if (decomposed.size() == 1) {
993 return decomposed[0];
994 } else {
995 ERR_PRINT("Convex shape simplification failed, falling back to simpler process.");
996 }
997 }
998
999 Vector<Vector3> vertices;
1000 for (int i = 0; i < get_surface_count(); i++) {
1001 Array a = get_surface_arrays(i);
1002 ERR_FAIL_COND_V(a.is_empty(), Ref<ConvexPolygonShape3D>());
1003 Vector<Vector3> v = a[Mesh::ARRAY_VERTEX];
1004 vertices.append_array(v);
1005 }
1006
1007 Ref<ConvexPolygonShape3D> shape = memnew(ConvexPolygonShape3D);
1008
1009 if (p_clean) {
1010 Geometry3D::MeshData md;
1011 Error err = ConvexHullComputer::convex_hull(vertices, md);
1012 if (err == OK) {
1013 shape->set_points(md.vertices);
1014 return shape;
1015 } else {
1016 ERR_PRINT("Convex shape cleaning failed, falling back to simpler process.");
1017 }
1018 }
1019
1020 shape->set_points(vertices);
1021 return shape;
1022}
1023
1024Ref<ConcavePolygonShape3D> ImporterMesh::create_trimesh_shape() const {
1025 Vector<Face3> faces = get_faces();
1026 if (faces.size() == 0) {
1027 return Ref<ConcavePolygonShape3D>();
1028 }
1029
1030 Vector<Vector3> face_points;
1031 face_points.resize(faces.size() * 3);
1032
1033 for (int i = 0; i < face_points.size(); i += 3) {
1034 Face3 f = faces.get(i / 3);
1035 face_points.set(i, f.vertex[0]);
1036 face_points.set(i + 1, f.vertex[1]);
1037 face_points.set(i + 2, f.vertex[2]);
1038 }
1039
1040 Ref<ConcavePolygonShape3D> shape = memnew(ConcavePolygonShape3D);
1041 shape->set_faces(face_points);
1042 return shape;
1043}
1044
1045Ref<NavigationMesh> ImporterMesh::create_navigation_mesh() {
1046 Vector<Face3> faces = get_faces();
1047 if (faces.size() == 0) {
1048 return Ref<NavigationMesh>();
1049 }
1050
1051 HashMap<Vector3, int> unique_vertices;
1052 LocalVector<int> face_indices;
1053
1054 for (int i = 0; i < faces.size(); i++) {
1055 for (int j = 0; j < 3; j++) {
1056 Vector3 v = faces[i].vertex[j];
1057 int idx;
1058 if (unique_vertices.has(v)) {
1059 idx = unique_vertices[v];
1060 } else {
1061 idx = unique_vertices.size();
1062 unique_vertices[v] = idx;
1063 }
1064 face_indices.push_back(idx);
1065 }
1066 }
1067
1068 Vector<Vector3> vertices;
1069 vertices.resize(unique_vertices.size());
1070 for (const KeyValue<Vector3, int> &E : unique_vertices) {
1071 vertices.write[E.value] = E.key;
1072 }
1073
1074 Ref<NavigationMesh> nm;
1075 nm.instantiate();
1076 nm->set_vertices(vertices);
1077
1078 Vector<int> v3;
1079 v3.resize(3);
1080 for (uint32_t i = 0; i < face_indices.size(); i += 3) {
1081 v3.write[0] = face_indices[i + 0];
1082 v3.write[1] = face_indices[i + 1];
1083 v3.write[2] = face_indices[i + 2];
1084 nm->add_polygon(v3);
1085 }
1086
1087 return nm;
1088}
1089
1090extern 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);
1091
1092struct EditorSceneFormatImporterMeshLightmapSurface {
1093 Ref<Material> material;
1094 LocalVector<SurfaceTool::Vertex> vertices;
1095 Mesh::PrimitiveType primitive = Mesh::PrimitiveType::PRIMITIVE_MAX;
1096 uint32_t format = 0;
1097 String name;
1098};
1099
1100static 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 };
1101
1102Error 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) {
1103 ERR_FAIL_NULL_V(array_mesh_lightmap_unwrap_callback, ERR_UNCONFIGURED);
1104 ERR_FAIL_COND_V_MSG(blend_shapes.size() != 0, ERR_UNAVAILABLE, "Can't unwrap mesh with blend shapes.");
1105
1106 LocalVector<float> vertices;
1107 LocalVector<float> normals;
1108 LocalVector<int> indices;
1109 LocalVector<float> uv;
1110 LocalVector<Pair<int, int>> uv_indices;
1111
1112 Vector<EditorSceneFormatImporterMeshLightmapSurface> lightmap_surfaces;
1113
1114 // Keep only the scale
1115 Basis basis = p_base_transform.get_basis();
1116 Vector3 scale = Vector3(basis.get_column(0).length(), basis.get_column(1).length(), basis.get_column(2).length());
1117
1118 Transform3D transform;
1119 transform.scale(scale);
1120
1121 Basis normal_basis = transform.basis.inverse().transposed();
1122
1123 for (int i = 0; i < get_surface_count(); i++) {
1124 EditorSceneFormatImporterMeshLightmapSurface s;
1125 s.primitive = get_surface_primitive_type(i);
1126
1127 ERR_FAIL_COND_V_MSG(s.primitive != Mesh::PRIMITIVE_TRIANGLES, ERR_UNAVAILABLE, "Only triangles are supported for lightmap unwrap.");
1128 Array arrays = get_surface_arrays(i);
1129 s.material = get_surface_material(i);
1130 s.name = get_surface_name(i);
1131
1132 SurfaceTool::create_vertex_array_from_triangle_arrays(arrays, s.vertices, &s.format);
1133
1134 PackedVector3Array rvertices = arrays[Mesh::ARRAY_VERTEX];
1135 int vc = rvertices.size();
1136
1137 PackedVector3Array rnormals = arrays[Mesh::ARRAY_NORMAL];
1138
1139 if (!rnormals.size()) {
1140 continue;
1141 }
1142
1143 int vertex_ofs = vertices.size() / 3;
1144
1145 vertices.resize((vertex_ofs + vc) * 3);
1146 normals.resize((vertex_ofs + vc) * 3);
1147 uv_indices.resize(vertex_ofs + vc);
1148
1149 for (int j = 0; j < vc; j++) {
1150 Vector3 v = transform.xform(rvertices[j]);
1151 Vector3 n = normal_basis.xform(rnormals[j]).normalized();
1152
1153 vertices[(j + vertex_ofs) * 3 + 0] = v.x;
1154 vertices[(j + vertex_ofs) * 3 + 1] = v.y;
1155 vertices[(j + vertex_ofs) * 3 + 2] = v.z;
1156 normals[(j + vertex_ofs) * 3 + 0] = n.x;
1157 normals[(j + vertex_ofs) * 3 + 1] = n.y;
1158 normals[(j + vertex_ofs) * 3 + 2] = n.z;
1159 uv_indices[j + vertex_ofs] = Pair<int, int>(i, j);
1160 }
1161
1162 PackedInt32Array rindices = arrays[Mesh::ARRAY_INDEX];
1163 int ic = rindices.size();
1164
1165 float eps = 1.19209290e-7F; // Taken from xatlas.h
1166 if (ic == 0) {
1167 for (int j = 0; j < vc / 3; j++) {
1168 Vector3 p0 = transform.xform(rvertices[j * 3 + 0]);
1169 Vector3 p1 = transform.xform(rvertices[j * 3 + 1]);
1170 Vector3 p2 = transform.xform(rvertices[j * 3 + 2]);
1171
1172 if ((p0 - p1).length_squared() < eps || (p1 - p2).length_squared() < eps || (p2 - p0).length_squared() < eps) {
1173 continue;
1174 }
1175
1176 indices.push_back(vertex_ofs + j * 3 + 0);
1177 indices.push_back(vertex_ofs + j * 3 + 1);
1178 indices.push_back(vertex_ofs + j * 3 + 2);
1179 }
1180
1181 } else {
1182 for (int j = 0; j < ic / 3; j++) {
1183 ERR_FAIL_INDEX_V(rindices[j * 3 + 0], rvertices.size(), ERR_INVALID_DATA);
1184 ERR_FAIL_INDEX_V(rindices[j * 3 + 1], rvertices.size(), ERR_INVALID_DATA);
1185 ERR_FAIL_INDEX_V(rindices[j * 3 + 2], rvertices.size(), ERR_INVALID_DATA);
1186 Vector3 p0 = transform.xform(rvertices[rindices[j * 3 + 0]]);
1187 Vector3 p1 = transform.xform(rvertices[rindices[j * 3 + 1]]);
1188 Vector3 p2 = transform.xform(rvertices[rindices[j * 3 + 2]]);
1189
1190 if ((p0 - p1).length_squared() < eps || (p1 - p2).length_squared() < eps || (p2 - p0).length_squared() < eps) {
1191 continue;
1192 }
1193
1194 indices.push_back(vertex_ofs + rindices[j * 3 + 0]);
1195 indices.push_back(vertex_ofs + rindices[j * 3 + 1]);
1196 indices.push_back(vertex_ofs + rindices[j * 3 + 2]);
1197 }
1198 }
1199
1200 lightmap_surfaces.push_back(s);
1201 }
1202
1203 //unwrap
1204
1205 bool use_cache = true; // Used to request cache generation and to know if cache was used
1206 uint8_t *gen_cache;
1207 int gen_cache_size;
1208 float *gen_uvs;
1209 int *gen_vertices;
1210 int *gen_indices;
1211 int gen_vertex_count;
1212 int gen_index_count;
1213 int size_x;
1214 int size_y;
1215
1216 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);
1217
1218 if (!ok) {
1219 return ERR_CANT_CREATE;
1220 }
1221
1222 //create surfacetools for each surface..
1223 LocalVector<Ref<SurfaceTool>> surfaces_tools;
1224
1225 for (int i = 0; i < lightmap_surfaces.size(); i++) {
1226 Ref<SurfaceTool> st;
1227 st.instantiate();
1228 st->begin(Mesh::PRIMITIVE_TRIANGLES);
1229 st->set_material(lightmap_surfaces[i].material);
1230 st->set_meta("name", lightmap_surfaces[i].name);
1231
1232 for (int custom_i = 0; custom_i < RS::ARRAY_CUSTOM_COUNT; custom_i++) {
1233 st->set_custom_format(custom_i, (SurfaceTool::CustomFormat)((lightmap_surfaces[i].format >> custom_shift[custom_i]) & RS::ARRAY_FORMAT_CUSTOM_MASK));
1234 }
1235 surfaces_tools.push_back(st); //stay there
1236 }
1237
1238 //remove surfaces
1239 clear();
1240
1241 print_verbose("Mesh: Gen indices: " + itos(gen_index_count));
1242
1243 //go through all indices
1244 for (int i = 0; i < gen_index_count; i += 3) {
1245 ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 0]], (int)uv_indices.size(), ERR_BUG);
1246 ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 1]], (int)uv_indices.size(), ERR_BUG);
1247 ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 2]], (int)uv_indices.size(), ERR_BUG);
1248
1249 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);
1250
1251 int surface = uv_indices[gen_vertices[gen_indices[i + 0]]].first;
1252
1253 for (int j = 0; j < 3; j++) {
1254 SurfaceTool::Vertex v = lightmap_surfaces[surface].vertices[uv_indices[gen_vertices[gen_indices[i + j]]].second];
1255
1256 if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_COLOR) {
1257 surfaces_tools[surface]->set_color(v.color);
1258 }
1259 if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_TEX_UV) {
1260 surfaces_tools[surface]->set_uv(v.uv);
1261 }
1262 if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_NORMAL) {
1263 surfaces_tools[surface]->set_normal(v.normal);
1264 }
1265 if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_TANGENT) {
1266 Plane t;
1267 t.normal = v.tangent;
1268 t.d = v.binormal.dot(v.normal.cross(v.tangent)) < 0 ? -1 : 1;
1269 surfaces_tools[surface]->set_tangent(t);
1270 }
1271 if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_BONES) {
1272 surfaces_tools[surface]->set_bones(v.bones);
1273 }
1274 if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_WEIGHTS) {
1275 surfaces_tools[surface]->set_weights(v.weights);
1276 }
1277 for (int custom_i = 0; custom_i < RS::ARRAY_CUSTOM_COUNT; custom_i++) {
1278 if ((lightmap_surfaces[surface].format >> custom_shift[custom_i]) & RS::ARRAY_FORMAT_CUSTOM_MASK) {
1279 surfaces_tools[surface]->set_custom(custom_i, v.custom[custom_i]);
1280 }
1281 }
1282
1283 Vector2 uv2(gen_uvs[gen_indices[i + j] * 2 + 0], gen_uvs[gen_indices[i + j] * 2 + 1]);
1284 surfaces_tools[surface]->set_uv2(uv2);
1285
1286 surfaces_tools[surface]->add_vertex(v.vertex);
1287 }
1288 }
1289
1290 //generate surfaces
1291 for (int i = 0; i < lightmap_surfaces.size(); i++) {
1292 Ref<SurfaceTool> &tool = surfaces_tools[i];
1293 tool->index();
1294 Array arrays = tool->commit_to_arrays();
1295 add_surface(tool->get_primitive_type(), arrays, Array(), Dictionary(), tool->get_material(), tool->get_meta("name"), lightmap_surfaces[i].format);
1296 }
1297
1298 set_lightmap_size_hint(Size2(size_x, size_y));
1299
1300 if (gen_cache_size > 0) {
1301 r_dst_cache.resize(gen_cache_size);
1302 memcpy(r_dst_cache.ptrw(), gen_cache, gen_cache_size);
1303 memfree(gen_cache);
1304 }
1305
1306 if (!use_cache) {
1307 // Cache was not used, free the buffers
1308 memfree(gen_vertices);
1309 memfree(gen_indices);
1310 memfree(gen_uvs);
1311 }
1312
1313 return OK;
1314}
1315
1316void ImporterMesh::set_lightmap_size_hint(const Size2i &p_size) {
1317 lightmap_size_hint = p_size;
1318}
1319
1320Size2i ImporterMesh::get_lightmap_size_hint() const {
1321 return lightmap_size_hint;
1322}
1323
1324void ImporterMesh::_bind_methods() {
1325 ClassDB::bind_method(D_METHOD("add_blend_shape", "name"), &ImporterMesh::add_blend_shape);
1326 ClassDB::bind_method(D_METHOD("get_blend_shape_count"), &ImporterMesh::get_blend_shape_count);
1327 ClassDB::bind_method(D_METHOD("get_blend_shape_name", "blend_shape_idx"), &ImporterMesh::get_blend_shape_name);
1328
1329 ClassDB::bind_method(D_METHOD("set_blend_shape_mode", "mode"), &ImporterMesh::set_blend_shape_mode);
1330 ClassDB::bind_method(D_METHOD("get_blend_shape_mode"), &ImporterMesh::get_blend_shape_mode);
1331
1332 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));
1333
1334 ClassDB::bind_method(D_METHOD("get_surface_count"), &ImporterMesh::get_surface_count);
1335 ClassDB::bind_method(D_METHOD("get_surface_primitive_type", "surface_idx"), &ImporterMesh::get_surface_primitive_type);
1336 ClassDB::bind_method(D_METHOD("get_surface_name", "surface_idx"), &ImporterMesh::get_surface_name);
1337 ClassDB::bind_method(D_METHOD("get_surface_arrays", "surface_idx"), &ImporterMesh::get_surface_arrays);
1338 ClassDB::bind_method(D_METHOD("get_surface_blend_shape_arrays", "surface_idx", "blend_shape_idx"), &ImporterMesh::get_surface_blend_shape_arrays);
1339 ClassDB::bind_method(D_METHOD("get_surface_lod_count", "surface_idx"), &ImporterMesh::get_surface_lod_count);
1340 ClassDB::bind_method(D_METHOD("get_surface_lod_size", "surface_idx", "lod_idx"), &ImporterMesh::get_surface_lod_size);
1341 ClassDB::bind_method(D_METHOD("get_surface_lod_indices", "surface_idx", "lod_idx"), &ImporterMesh::get_surface_lod_indices);
1342 ClassDB::bind_method(D_METHOD("get_surface_material", "surface_idx"), &ImporterMesh::get_surface_material);
1343 ClassDB::bind_method(D_METHOD("get_surface_format", "surface_idx"), &ImporterMesh::get_surface_format);
1344
1345 ClassDB::bind_method(D_METHOD("set_surface_name", "surface_idx", "name"), &ImporterMesh::set_surface_name);
1346 ClassDB::bind_method(D_METHOD("set_surface_material", "surface_idx", "material"), &ImporterMesh::set_surface_material);
1347
1348 ClassDB::bind_method(D_METHOD("generate_lods", "normal_merge_angle", "normal_split_angle", "bone_transform_array"), &ImporterMesh::generate_lods);
1349 ClassDB::bind_method(D_METHOD("get_mesh", "base_mesh"), &ImporterMesh::get_mesh, DEFVAL(Ref<ArrayMesh>()));
1350 ClassDB::bind_method(D_METHOD("clear"), &ImporterMesh::clear);
1351
1352 ClassDB::bind_method(D_METHOD("_set_data", "data"), &ImporterMesh::_set_data);
1353 ClassDB::bind_method(D_METHOD("_get_data"), &ImporterMesh::_get_data);
1354
1355 ClassDB::bind_method(D_METHOD("set_lightmap_size_hint", "size"), &ImporterMesh::set_lightmap_size_hint);
1356 ClassDB::bind_method(D_METHOD("get_lightmap_size_hint"), &ImporterMesh::get_lightmap_size_hint);
1357
1358 ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "_set_data", "_get_data");
1359}
1360