Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/scene/resources/3d/importer_mesh.cpp
9903 views
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_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_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
if (bones.size() > 0 && weights.size() && bone_transform_vector.size() > 0) {
345
Vector3 *vertices_ptrw = vertices.ptrw();
346
347
// Apply bone transforms to regular surface.
348
unsigned int bone_weight_length = surfaces[i].flags & Mesh::ARRAY_FLAG_USE_8_BONE_WEIGHTS ? 8 : 4;
349
350
const int *bo = bones.ptr();
351
const float *we = weights.ptr();
352
353
for (unsigned int j = 0; j < vertex_count; j++) {
354
VERTEX_SKIN_FUNC(bone_weight_length, j, vertices_ptr, vertices_ptrw, bone_transform_vector, bo, we)
355
}
356
357
vertices_ptr = vertices.ptr();
358
}
359
360
float normal_merge_threshold = Math::cos(Math::deg_to_rad(p_normal_merge_angle));
361
const Vector3 *normals_ptr = normals.ptr();
362
363
HashMap<Vector3, LocalVector<Pair<int, int>>> unique_vertices;
364
365
LocalVector<int> vertex_remap;
366
LocalVector<int> vertex_inverse_remap;
367
LocalVector<Vector3> merged_vertices;
368
LocalVector<Vector3> merged_normals;
369
LocalVector<int> merged_normals_counts;
370
const Vector2 *uvs_ptr = uvs.ptr();
371
const Vector2 *uv2s_ptr = uv2s.ptr();
372
const float *tangents_ptr = tangents.ptr();
373
const Color *colors_ptr = colors.ptr();
374
375
for (unsigned int j = 0; j < vertex_count; j++) {
376
const Vector3 &v = vertices_ptr[j];
377
const Vector3 &n = normals_ptr[j];
378
379
HashMap<Vector3, LocalVector<Pair<int, int>>>::Iterator E = unique_vertices.find(v);
380
381
if (E) {
382
const LocalVector<Pair<int, int>> &close_verts = E->value;
383
384
bool found = false;
385
for (const Pair<int, int> &idx : close_verts) {
386
bool is_uvs_close = (!uvs_ptr || uvs_ptr[j].distance_squared_to(uvs_ptr[idx.second]) < CMP_EPSILON2);
387
bool is_uv2s_close = (!uv2s_ptr || uv2s_ptr[j].distance_squared_to(uv2s_ptr[idx.second]) < CMP_EPSILON2);
388
bool is_tang_aligned = !tangents_ptr || (tangents_ptr[j * 4 + 3] < 0) == (tangents_ptr[idx.second * 4 + 3] < 0);
389
ERR_FAIL_INDEX(idx.second, normals.size());
390
bool is_normals_close = normals[idx.second].dot(n) > normal_merge_threshold;
391
bool is_col_close = (!colors_ptr || colors_ptr[j].is_equal_approx(colors_ptr[idx.second]));
392
if (is_uvs_close && is_uv2s_close && is_normals_close && is_tang_aligned && is_col_close) {
393
vertex_remap.push_back(idx.first);
394
merged_normals[idx.first] += normals[idx.second];
395
merged_normals_counts[idx.first]++;
396
found = true;
397
break;
398
}
399
}
400
401
if (!found) {
402
int vcount = merged_vertices.size();
403
unique_vertices[v].push_back(Pair<int, int>(vcount, j));
404
vertex_inverse_remap.push_back(j);
405
merged_vertices.push_back(v);
406
vertex_remap.push_back(vcount);
407
merged_normals.push_back(normals_ptr[j]);
408
merged_normals_counts.push_back(1);
409
}
410
} else {
411
int vcount = merged_vertices.size();
412
unique_vertices[v] = LocalVector<Pair<int, int>>();
413
unique_vertices[v].push_back(Pair<int, int>(vcount, j));
414
vertex_inverse_remap.push_back(j);
415
merged_vertices.push_back(v);
416
vertex_remap.push_back(vcount);
417
merged_normals.push_back(normals_ptr[j]);
418
merged_normals_counts.push_back(1);
419
}
420
}
421
422
LocalVector<int> merged_indices;
423
merged_indices.resize(index_count);
424
for (unsigned int j = 0; j < index_count; j++) {
425
merged_indices[j] = vertex_remap[indices[j]];
426
}
427
428
unsigned int merged_vertex_count = merged_vertices.size();
429
const Vector3 *merged_vertices_ptr = merged_vertices.ptr();
430
const int32_t *merged_indices_ptr = merged_indices.ptr();
431
Vector3 *merged_normals_ptr = merged_normals.ptr();
432
433
{
434
const int *counts_ptr = merged_normals_counts.ptr();
435
for (unsigned int j = 0; j < merged_vertex_count; j++) {
436
merged_normals_ptr[j] /= counts_ptr[j];
437
}
438
}
439
440
Vector<float> merged_vertices_f32 = vector3_to_float32_array(merged_vertices_ptr, merged_vertex_count);
441
float scale = SurfaceTool::simplify_scale_func(merged_vertices_f32.ptr(), merged_vertex_count, sizeof(float) * 3);
442
443
const size_t attrib_count = 6; // 3 for normal + 3 for color (if present)
444
445
float attrib_weights[attrib_count] = {};
446
447
// Give some weight to normal preservation
448
attrib_weights[0] = attrib_weights[1] = attrib_weights[2] = 1.0f;
449
450
// Give some weight to colors but only if present to avoid redundant computations during simplification
451
if (colors_ptr) {
452
attrib_weights[3] = attrib_weights[4] = attrib_weights[5] = 1.0f;
453
}
454
455
LocalVector<float> merged_attribs;
456
merged_attribs.resize(merged_vertex_count * attrib_count);
457
float *merged_attribs_ptr = merged_attribs.ptr();
458
459
memset(merged_attribs_ptr, 0, merged_attribs.size() * sizeof(float));
460
461
for (unsigned int j = 0; j < merged_vertex_count; ++j) {
462
merged_attribs_ptr[j * attrib_count + 0] = merged_normals_ptr[j].x;
463
merged_attribs_ptr[j * attrib_count + 1] = merged_normals_ptr[j].y;
464
merged_attribs_ptr[j * attrib_count + 2] = merged_normals_ptr[j].z;
465
466
if (colors_ptr) {
467
unsigned int rj = vertex_inverse_remap[j];
468
469
merged_attribs_ptr[j * attrib_count + 3] = colors_ptr[rj].r;
470
merged_attribs_ptr[j * attrib_count + 4] = colors_ptr[rj].g;
471
merged_attribs_ptr[j * attrib_count + 5] = colors_ptr[rj].b;
472
}
473
}
474
475
unsigned int index_target = 12; // Start with the smallest target, 4 triangles
476
unsigned int last_index_count = 0;
477
478
const float max_mesh_error = 1.0f; // we only need LODs that can be selected by error threshold
479
float mesh_error = 0.0f;
480
481
while (index_target < index_count) {
482
PackedInt32Array new_indices;
483
new_indices.resize(index_count);
484
485
const int simplify_options = SurfaceTool::SIMPLIFY_LOCK_BORDER;
486
487
size_t new_index_count = SurfaceTool::simplify_with_attrib_func(
488
(unsigned int *)new_indices.ptrw(),
489
(const uint32_t *)merged_indices_ptr, index_count,
490
merged_vertices_f32.ptr(), merged_vertex_count,
491
sizeof(float) * 3, // Vertex stride
492
merged_attribs_ptr,
493
sizeof(float) * attrib_count, // Attribute stride
494
attrib_weights, attrib_count,
495
nullptr, // Vertex lock
496
index_target,
497
max_mesh_error,
498
simplify_options,
499
&mesh_error);
500
501
if (new_index_count < last_index_count * 1.5f) {
502
index_target = index_target * 1.5f;
503
continue;
504
}
505
506
if (new_index_count == 0 || (new_index_count >= (index_count * 0.75f))) {
507
break;
508
}
509
if (new_index_count > 5000000) {
510
// This limit theoretically shouldn't be needed, but it's here
511
// as an ad-hoc fix to prevent a crash with complex meshes.
512
// The crash still happens with limit of 6000000, but 5000000 works.
513
// In the future, identify what's causing that crash and fix it.
514
WARN_PRINT("Mesh LOD generation failed for mesh " + get_name() + " surface " + itos(i) + ", mesh is too complex. Some automatic LODs were not generated.");
515
break;
516
}
517
518
new_indices.resize(new_index_count);
519
{
520
int *ptrw = new_indices.ptrw();
521
for (unsigned int j = 0; j < new_index_count; j++) {
522
ptrw[j] = vertex_inverse_remap[ptrw[j]];
523
}
524
}
525
526
Surface::LOD lod;
527
lod.distance = MAX(mesh_error * scale, CMP_EPSILON2);
528
lod.indices = new_indices;
529
surfaces.write[i].lods.push_back(lod);
530
index_target = MAX(new_index_count, index_target) * 2;
531
last_index_count = new_index_count;
532
533
if (mesh_error == 0.0f) {
534
break;
535
}
536
}
537
538
surfaces.write[i].lods.sort_custom<Surface::LODComparator>();
539
}
540
}
541
542
void ImporterMesh::_generate_lods_bind(float p_normal_merge_angle, float p_normal_split_angle, Array p_skin_pose_transform_array) {
543
// p_normal_split_angle is unused, but kept for compatibility
544
generate_lods(p_normal_merge_angle, p_skin_pose_transform_array);
545
}
546
547
bool ImporterMesh::has_mesh() const {
548
return mesh.is_valid();
549
}
550
551
Ref<ArrayMesh> ImporterMesh::get_mesh(const Ref<ArrayMesh> &p_base) {
552
ERR_FAIL_COND_V(surfaces.is_empty(), Ref<ArrayMesh>());
553
554
if (mesh.is_null()) {
555
if (p_base.is_valid()) {
556
mesh = p_base;
557
}
558
if (mesh.is_null()) {
559
mesh.instantiate();
560
}
561
mesh->set_name(get_name());
562
if (has_meta("import_id")) {
563
mesh->set_meta("import_id", get_meta("import_id"));
564
}
565
for (int i = 0; i < blend_shapes.size(); i++) {
566
mesh->add_blend_shape(blend_shapes[i]);
567
}
568
mesh->set_blend_shape_mode(blend_shape_mode);
569
for (int i = 0; i < surfaces.size(); i++) {
570
Array bs_data;
571
if (surfaces[i].blend_shape_data.size()) {
572
for (int j = 0; j < surfaces[i].blend_shape_data.size(); j++) {
573
bs_data.push_back(surfaces[i].blend_shape_data[j].arrays);
574
}
575
}
576
Dictionary lods;
577
if (surfaces[i].lods.size()) {
578
for (int j = 0; j < surfaces[i].lods.size(); j++) {
579
lods[surfaces[i].lods[j].distance] = surfaces[i].lods[j].indices;
580
}
581
}
582
583
mesh->add_surface_from_arrays(surfaces[i].primitive, surfaces[i].arrays, bs_data, lods, surfaces[i].flags);
584
if (surfaces[i].material.is_valid()) {
585
mesh->surface_set_material(mesh->get_surface_count() - 1, surfaces[i].material);
586
}
587
if (!surfaces[i].name.is_empty()) {
588
mesh->surface_set_name(mesh->get_surface_count() - 1, surfaces[i].name);
589
}
590
}
591
592
mesh->set_lightmap_size_hint(lightmap_size_hint);
593
594
if (shadow_mesh.is_valid()) {
595
Ref<ArrayMesh> shadow = shadow_mesh->get_mesh();
596
mesh->set_shadow_mesh(shadow);
597
}
598
}
599
600
return mesh;
601
}
602
603
void ImporterMesh::clear() {
604
surfaces.clear();
605
blend_shapes.clear();
606
mesh.unref();
607
}
608
609
void ImporterMesh::create_shadow_mesh() {
610
if (shadow_mesh.is_valid()) {
611
shadow_mesh.unref();
612
}
613
614
//no shadow mesh for blendshapes
615
if (blend_shapes.size() > 0) {
616
return;
617
}
618
//no shadow mesh for skeletons
619
for (int i = 0; i < surfaces.size(); i++) {
620
if (surfaces[i].arrays[RS::ARRAY_BONES].get_type() != Variant::NIL) {
621
return;
622
}
623
if (surfaces[i].arrays[RS::ARRAY_WEIGHTS].get_type() != Variant::NIL) {
624
return;
625
}
626
}
627
628
shadow_mesh.instantiate();
629
630
for (int i = 0; i < surfaces.size(); i++) {
631
LocalVector<int> vertex_remap;
632
Vector<Vector3> new_vertices;
633
Vector<Vector3> vertices = surfaces[i].arrays[RS::ARRAY_VERTEX];
634
int vertex_count = vertices.size();
635
{
636
HashMap<Vector3, int> unique_vertices;
637
const Vector3 *vptr = vertices.ptr();
638
for (int j = 0; j < vertex_count; j++) {
639
const Vector3 &v = vptr[j];
640
641
HashMap<Vector3, int>::Iterator E = unique_vertices.find(v);
642
643
if (E) {
644
vertex_remap.push_back(E->value);
645
} else {
646
int vcount = unique_vertices.size();
647
unique_vertices[v] = vcount;
648
vertex_remap.push_back(vcount);
649
new_vertices.push_back(v);
650
}
651
}
652
}
653
654
Array new_surface;
655
new_surface.resize(RS::ARRAY_MAX);
656
Dictionary lods;
657
658
// print_line("original vertex count: " + itos(vertices.size()) + " new vertex count: " + itos(new_vertices.size()));
659
660
new_surface[RS::ARRAY_VERTEX] = new_vertices;
661
662
Vector<int> indices = surfaces[i].arrays[RS::ARRAY_INDEX];
663
if (indices.size()) {
664
int index_count = indices.size();
665
const int *index_rptr = indices.ptr();
666
Vector<int> new_indices;
667
new_indices.resize(indices.size());
668
int *index_wptr = new_indices.ptrw();
669
670
for (int j = 0; j < index_count; j++) {
671
int index = index_rptr[j];
672
ERR_FAIL_INDEX(index, vertex_count);
673
index_wptr[j] = vertex_remap[index];
674
}
675
676
new_surface[RS::ARRAY_INDEX] = new_indices;
677
678
// Make sure the same LODs as the full version are used.
679
// This makes it more coherent between rendered model and its shadows.
680
for (int j = 0; j < surfaces[i].lods.size(); j++) {
681
indices = surfaces[i].lods[j].indices;
682
683
index_count = indices.size();
684
index_rptr = indices.ptr();
685
new_indices.resize(indices.size());
686
index_wptr = new_indices.ptrw();
687
688
for (int k = 0; k < index_count; k++) {
689
int index = index_rptr[k];
690
ERR_FAIL_INDEX(index, vertex_count);
691
index_wptr[k] = vertex_remap[index];
692
}
693
694
lods[surfaces[i].lods[j].distance] = new_indices;
695
}
696
}
697
698
shadow_mesh->add_surface(surfaces[i].primitive, new_surface, Array(), lods, Ref<Material>(), surfaces[i].name, surfaces[i].flags);
699
}
700
}
701
702
Ref<ImporterMesh> ImporterMesh::get_shadow_mesh() const {
703
return shadow_mesh;
704
}
705
706
void ImporterMesh::_set_data(const Dictionary &p_data) {
707
clear();
708
if (p_data.has("blend_shape_names")) {
709
blend_shapes = p_data["blend_shape_names"];
710
}
711
if (p_data.has("surfaces")) {
712
Array surface_arr = p_data["surfaces"];
713
for (int i = 0; i < surface_arr.size(); i++) {
714
Dictionary s = surface_arr[i];
715
ERR_CONTINUE(!s.has("primitive"));
716
ERR_CONTINUE(!s.has("arrays"));
717
Mesh::PrimitiveType prim = Mesh::PrimitiveType(int(s["primitive"]));
718
ERR_CONTINUE(prim >= Mesh::PRIMITIVE_MAX);
719
Array arr = s["arrays"];
720
Dictionary lods;
721
String surf_name;
722
if (s.has("name")) {
723
surf_name = s["name"];
724
}
725
if (s.has("lods")) {
726
lods = s["lods"];
727
}
728
Array b_shapes;
729
if (s.has("b_shapes")) {
730
b_shapes = s["b_shapes"];
731
}
732
Ref<Material> material;
733
if (s.has("material")) {
734
material = s["material"];
735
}
736
uint64_t flags = 0;
737
if (s.has("flags")) {
738
flags = s["flags"];
739
}
740
add_surface(prim, arr, b_shapes, lods, material, surf_name, flags);
741
}
742
}
743
}
744
Dictionary ImporterMesh::_get_data() const {
745
Dictionary data;
746
if (blend_shapes.size()) {
747
data["blend_shape_names"] = blend_shapes;
748
}
749
Array surface_arr;
750
for (int i = 0; i < surfaces.size(); i++) {
751
Dictionary d;
752
d["primitive"] = surfaces[i].primitive;
753
d["arrays"] = surfaces[i].arrays;
754
if (surfaces[i].blend_shape_data.size()) {
755
Array bs_data;
756
for (int j = 0; j < surfaces[i].blend_shape_data.size(); j++) {
757
bs_data.push_back(surfaces[i].blend_shape_data[j].arrays);
758
}
759
d["blend_shapes"] = bs_data;
760
}
761
if (surfaces[i].lods.size()) {
762
Dictionary lods;
763
for (int j = 0; j < surfaces[i].lods.size(); j++) {
764
lods[surfaces[i].lods[j].distance] = surfaces[i].lods[j].indices;
765
}
766
d["lods"] = lods;
767
}
768
769
if (surfaces[i].material.is_valid()) {
770
d["material"] = surfaces[i].material;
771
}
772
773
if (!surfaces[i].name.is_empty()) {
774
d["name"] = surfaces[i].name;
775
}
776
777
d["flags"] = surfaces[i].flags;
778
779
surface_arr.push_back(d);
780
}
781
data["surfaces"] = surface_arr;
782
return data;
783
}
784
785
Vector<Face3> ImporterMesh::get_faces() const {
786
Vector<Face3> faces;
787
for (int i = 0; i < surfaces.size(); i++) {
788
if (surfaces[i].primitive == Mesh::PRIMITIVE_TRIANGLES) {
789
Vector<Vector3> vertices = surfaces[i].arrays[Mesh::ARRAY_VERTEX];
790
Vector<int> indices = surfaces[i].arrays[Mesh::ARRAY_INDEX];
791
if (indices.size()) {
792
for (int j = 0; j < indices.size(); j += 3) {
793
Face3 f;
794
f.vertex[0] = vertices[indices[j + 0]];
795
f.vertex[1] = vertices[indices[j + 1]];
796
f.vertex[2] = vertices[indices[j + 2]];
797
faces.push_back(f);
798
}
799
} else {
800
for (int j = 0; j < vertices.size(); j += 3) {
801
Face3 f;
802
f.vertex[0] = vertices[j + 0];
803
f.vertex[1] = vertices[j + 1];
804
f.vertex[2] = vertices[j + 2];
805
faces.push_back(f);
806
}
807
}
808
}
809
}
810
811
return faces;
812
}
813
814
#ifndef PHYSICS_3D_DISABLED
815
Vector<Ref<Shape3D>> ImporterMesh::convex_decompose(const Ref<MeshConvexDecompositionSettings> &p_settings) const {
816
ERR_FAIL_NULL_V(Mesh::convex_decomposition_function, Vector<Ref<Shape3D>>());
817
818
const Vector<Face3> faces = get_faces();
819
int face_count = faces.size();
820
821
Vector<Vector3> vertices;
822
uint32_t vertex_count = 0;
823
vertices.resize(face_count * 3);
824
Vector<uint32_t> indices;
825
indices.resize(face_count * 3);
826
{
827
HashMap<Vector3, uint32_t> vertex_map;
828
Vector3 *vertex_w = vertices.ptrw();
829
uint32_t *index_w = indices.ptrw();
830
for (int i = 0; i < face_count; i++) {
831
for (int j = 0; j < 3; j++) {
832
const Vector3 &vertex = faces[i].vertex[j];
833
HashMap<Vector3, uint32_t>::Iterator found_vertex = vertex_map.find(vertex);
834
uint32_t index;
835
if (found_vertex) {
836
index = found_vertex->value;
837
} else {
838
index = vertex_count++;
839
vertex_map[vertex] = index;
840
vertex_w[index] = vertex;
841
}
842
index_w[i * 3 + j] = index;
843
}
844
}
845
}
846
vertices.resize(vertex_count);
847
848
Vector<Vector<Vector3>> decomposed = Mesh::convex_decomposition_function((real_t *)vertices.ptr(), vertex_count, indices.ptr(), face_count, p_settings, nullptr);
849
850
Vector<Ref<Shape3D>> ret;
851
852
for (int i = 0; i < decomposed.size(); i++) {
853
Ref<ConvexPolygonShape3D> shape;
854
shape.instantiate();
855
shape->set_points(decomposed[i]);
856
ret.push_back(shape);
857
}
858
859
return ret;
860
}
861
862
Ref<ConvexPolygonShape3D> ImporterMesh::create_convex_shape(bool p_clean, bool p_simplify) const {
863
if (p_simplify) {
864
Ref<MeshConvexDecompositionSettings> settings;
865
settings.instantiate();
866
settings->set_max_convex_hulls(1);
867
Vector<Ref<Shape3D>> decomposed = convex_decompose(settings);
868
if (decomposed.size() == 1) {
869
return decomposed[0];
870
} else {
871
ERR_PRINT("Convex shape simplification failed, falling back to simpler process.");
872
}
873
}
874
875
Vector<Vector3> vertices;
876
for (int i = 0; i < get_surface_count(); i++) {
877
Array a = get_surface_arrays(i);
878
ERR_FAIL_COND_V(a.is_empty(), Ref<ConvexPolygonShape3D>());
879
Vector<Vector3> v = a[Mesh::ARRAY_VERTEX];
880
vertices.append_array(v);
881
}
882
883
Ref<ConvexPolygonShape3D> shape = memnew(ConvexPolygonShape3D);
884
885
if (p_clean) {
886
Geometry3D::MeshData md;
887
Error err = ConvexHullComputer::convex_hull(vertices, md);
888
if (err == OK) {
889
shape->set_points(md.vertices);
890
return shape;
891
} else {
892
ERR_PRINT("Convex shape cleaning failed, falling back to simpler process.");
893
}
894
}
895
896
shape->set_points(vertices);
897
return shape;
898
}
899
900
Ref<ConcavePolygonShape3D> ImporterMesh::create_trimesh_shape() const {
901
Vector<Face3> faces = get_faces();
902
if (faces.is_empty()) {
903
return Ref<ConcavePolygonShape3D>();
904
}
905
906
Vector<Vector3> face_points;
907
face_points.resize(faces.size() * 3);
908
909
for (int i = 0; i < face_points.size(); i += 3) {
910
Face3 f = faces.get(i / 3);
911
face_points.set(i, f.vertex[0]);
912
face_points.set(i + 1, f.vertex[1]);
913
face_points.set(i + 2, f.vertex[2]);
914
}
915
916
Ref<ConcavePolygonShape3D> shape = memnew(ConcavePolygonShape3D);
917
shape->set_faces(face_points);
918
return shape;
919
}
920
#endif // PHYSICS_3D_DISABLED
921
922
Ref<NavigationMesh> ImporterMesh::create_navigation_mesh() {
923
Vector<Face3> faces = get_faces();
924
if (faces.is_empty()) {
925
return Ref<NavigationMesh>();
926
}
927
928
HashMap<Vector3, int> unique_vertices;
929
Vector<Vector<int>> face_polygons;
930
face_polygons.resize(faces.size());
931
932
for (int i = 0; i < faces.size(); i++) {
933
Vector<int> face_indices;
934
face_indices.resize(3);
935
for (int j = 0; j < 3; j++) {
936
Vector3 v = faces[i].vertex[j];
937
int idx;
938
if (unique_vertices.has(v)) {
939
idx = unique_vertices[v];
940
} else {
941
idx = unique_vertices.size();
942
unique_vertices[v] = idx;
943
}
944
face_indices.write[j] = idx;
945
}
946
face_polygons.write[i] = face_indices;
947
}
948
949
Vector<Vector3> vertices;
950
vertices.resize(unique_vertices.size());
951
for (const KeyValue<Vector3, int> &E : unique_vertices) {
952
vertices.write[E.value] = E.key;
953
}
954
955
Ref<NavigationMesh> nm;
956
nm.instantiate();
957
nm->set_data(vertices, face_polygons);
958
959
return nm;
960
}
961
962
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);
963
964
struct EditorSceneFormatImporterMeshLightmapSurface {
965
Ref<Material> material;
966
LocalVector<SurfaceTool::Vertex> vertices;
967
Mesh::PrimitiveType primitive = Mesh::PrimitiveType::PRIMITIVE_MAX;
968
uint64_t format = 0;
969
String name;
970
};
971
972
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 };
973
974
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) {
975
ERR_FAIL_NULL_V(array_mesh_lightmap_unwrap_callback, ERR_UNCONFIGURED);
976
ERR_FAIL_COND_V_MSG(blend_shapes.size() != 0, ERR_UNAVAILABLE, "Can't unwrap mesh with blend shapes.");
977
978
LocalVector<float> vertices;
979
LocalVector<float> normals;
980
LocalVector<int> indices;
981
LocalVector<float> uv;
982
LocalVector<Pair<int, int>> uv_indices;
983
984
Vector<EditorSceneFormatImporterMeshLightmapSurface> lightmap_surfaces;
985
986
// Keep only the scale
987
Basis basis = p_base_transform.get_basis();
988
Vector3 scale = Vector3(basis.get_column(0).length(), basis.get_column(1).length(), basis.get_column(2).length());
989
990
Transform3D transform;
991
transform.scale(scale);
992
993
Basis normal_basis = transform.basis.inverse().transposed();
994
995
for (int i = 0; i < get_surface_count(); i++) {
996
EditorSceneFormatImporterMeshLightmapSurface s;
997
s.primitive = get_surface_primitive_type(i);
998
999
ERR_FAIL_COND_V_MSG(s.primitive != Mesh::PRIMITIVE_TRIANGLES, ERR_UNAVAILABLE, "Only triangles are supported for lightmap unwrap.");
1000
Array arrays = get_surface_arrays(i);
1001
s.material = get_surface_material(i);
1002
s.name = get_surface_name(i);
1003
1004
SurfaceTool::create_vertex_array_from_arrays(arrays, s.vertices, &s.format);
1005
1006
PackedVector3Array rvertices = arrays[Mesh::ARRAY_VERTEX];
1007
int vc = rvertices.size();
1008
1009
PackedVector3Array rnormals = arrays[Mesh::ARRAY_NORMAL];
1010
1011
if (!rnormals.size()) {
1012
continue;
1013
}
1014
1015
int vertex_ofs = vertices.size() / 3;
1016
1017
vertices.resize((vertex_ofs + vc) * 3);
1018
normals.resize((vertex_ofs + vc) * 3);
1019
uv_indices.resize(vertex_ofs + vc);
1020
1021
for (int j = 0; j < vc; j++) {
1022
Vector3 v = transform.xform(rvertices[j]);
1023
Vector3 n = normal_basis.xform(rnormals[j]).normalized();
1024
1025
vertices[(j + vertex_ofs) * 3 + 0] = v.x;
1026
vertices[(j + vertex_ofs) * 3 + 1] = v.y;
1027
vertices[(j + vertex_ofs) * 3 + 2] = v.z;
1028
normals[(j + vertex_ofs) * 3 + 0] = n.x;
1029
normals[(j + vertex_ofs) * 3 + 1] = n.y;
1030
normals[(j + vertex_ofs) * 3 + 2] = n.z;
1031
uv_indices[j + vertex_ofs] = Pair<int, int>(i, j);
1032
}
1033
1034
PackedInt32Array rindices = arrays[Mesh::ARRAY_INDEX];
1035
int ic = rindices.size();
1036
1037
float eps = 1.19209290e-7F; // Taken from xatlas.h
1038
if (ic == 0) {
1039
for (int j = 0; j < vc / 3; j++) {
1040
Vector3 p0 = transform.xform(rvertices[j * 3 + 0]);
1041
Vector3 p1 = transform.xform(rvertices[j * 3 + 1]);
1042
Vector3 p2 = transform.xform(rvertices[j * 3 + 2]);
1043
1044
if ((p0 - p1).length_squared() < eps || (p1 - p2).length_squared() < eps || (p2 - p0).length_squared() < eps) {
1045
continue;
1046
}
1047
1048
indices.push_back(vertex_ofs + j * 3 + 0);
1049
indices.push_back(vertex_ofs + j * 3 + 1);
1050
indices.push_back(vertex_ofs + j * 3 + 2);
1051
}
1052
1053
} else {
1054
for (int j = 0; j < ic / 3; j++) {
1055
ERR_FAIL_INDEX_V(rindices[j * 3 + 0], rvertices.size(), ERR_INVALID_DATA);
1056
ERR_FAIL_INDEX_V(rindices[j * 3 + 1], rvertices.size(), ERR_INVALID_DATA);
1057
ERR_FAIL_INDEX_V(rindices[j * 3 + 2], rvertices.size(), ERR_INVALID_DATA);
1058
Vector3 p0 = transform.xform(rvertices[rindices[j * 3 + 0]]);
1059
Vector3 p1 = transform.xform(rvertices[rindices[j * 3 + 1]]);
1060
Vector3 p2 = transform.xform(rvertices[rindices[j * 3 + 2]]);
1061
1062
if ((p0 - p1).length_squared() < eps || (p1 - p2).length_squared() < eps || (p2 - p0).length_squared() < eps) {
1063
continue;
1064
}
1065
1066
indices.push_back(vertex_ofs + rindices[j * 3 + 0]);
1067
indices.push_back(vertex_ofs + rindices[j * 3 + 1]);
1068
indices.push_back(vertex_ofs + rindices[j * 3 + 2]);
1069
}
1070
}
1071
1072
lightmap_surfaces.push_back(s);
1073
}
1074
1075
//unwrap
1076
1077
bool use_cache = true; // Used to request cache generation and to know if cache was used
1078
uint8_t *gen_cache;
1079
int gen_cache_size;
1080
float *gen_uvs;
1081
int *gen_vertices;
1082
int *gen_indices;
1083
int gen_vertex_count;
1084
int gen_index_count;
1085
int size_x;
1086
int size_y;
1087
1088
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);
1089
1090
if (!ok) {
1091
return ERR_CANT_CREATE;
1092
}
1093
1094
//create surfacetools for each surface..
1095
LocalVector<Ref<SurfaceTool>> surfaces_tools;
1096
1097
for (int i = 0; i < lightmap_surfaces.size(); i++) {
1098
Ref<SurfaceTool> st;
1099
st.instantiate();
1100
st->set_skin_weight_count((lightmap_surfaces[i].format & Mesh::ARRAY_FLAG_USE_8_BONE_WEIGHTS) ? SurfaceTool::SKIN_8_WEIGHTS : SurfaceTool::SKIN_4_WEIGHTS);
1101
st->begin(Mesh::PRIMITIVE_TRIANGLES);
1102
st->set_material(lightmap_surfaces[i].material);
1103
st->set_meta("name", lightmap_surfaces[i].name);
1104
1105
for (int custom_i = 0; custom_i < RS::ARRAY_CUSTOM_COUNT; custom_i++) {
1106
st->set_custom_format(custom_i, (SurfaceTool::CustomFormat)((lightmap_surfaces[i].format >> custom_shift[custom_i]) & RS::ARRAY_FORMAT_CUSTOM_MASK));
1107
}
1108
surfaces_tools.push_back(st); //stay there
1109
}
1110
1111
//remove surfaces
1112
clear();
1113
1114
print_verbose("Mesh: Gen indices: " + itos(gen_index_count));
1115
1116
//go through all indices
1117
for (int i = 0; i < gen_index_count; i += 3) {
1118
ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 0]], (int)uv_indices.size(), ERR_BUG);
1119
ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 1]], (int)uv_indices.size(), ERR_BUG);
1120
ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 2]], (int)uv_indices.size(), ERR_BUG);
1121
1122
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);
1123
1124
int surface = uv_indices[gen_vertices[gen_indices[i + 0]]].first;
1125
1126
for (int j = 0; j < 3; j++) {
1127
SurfaceTool::Vertex v = lightmap_surfaces[surface].vertices[uv_indices[gen_vertices[gen_indices[i + j]]].second];
1128
1129
if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_COLOR) {
1130
surfaces_tools[surface]->set_color(v.color);
1131
}
1132
if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_TEX_UV) {
1133
surfaces_tools[surface]->set_uv(v.uv);
1134
}
1135
if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_NORMAL) {
1136
surfaces_tools[surface]->set_normal(v.normal);
1137
}
1138
if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_TANGENT) {
1139
Plane t;
1140
t.normal = v.tangent;
1141
t.d = v.binormal.dot(v.normal.cross(v.tangent)) < 0 ? -1 : 1;
1142
surfaces_tools[surface]->set_tangent(t);
1143
}
1144
if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_BONES) {
1145
surfaces_tools[surface]->set_bones(v.bones);
1146
}
1147
if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_WEIGHTS) {
1148
surfaces_tools[surface]->set_weights(v.weights);
1149
}
1150
for (int custom_i = 0; custom_i < RS::ARRAY_CUSTOM_COUNT; custom_i++) {
1151
if ((lightmap_surfaces[surface].format >> custom_shift[custom_i]) & RS::ARRAY_FORMAT_CUSTOM_MASK) {
1152
surfaces_tools[surface]->set_custom(custom_i, v.custom[custom_i]);
1153
}
1154
}
1155
1156
Vector2 uv2(gen_uvs[gen_indices[i + j] * 2 + 0], gen_uvs[gen_indices[i + j] * 2 + 1]);
1157
surfaces_tools[surface]->set_uv2(uv2);
1158
1159
surfaces_tools[surface]->add_vertex(v.vertex);
1160
}
1161
}
1162
1163
//generate surfaces
1164
for (int i = 0; i < lightmap_surfaces.size(); i++) {
1165
Ref<SurfaceTool> &tool = surfaces_tools[i];
1166
tool->index();
1167
Array arrays = tool->commit_to_arrays();
1168
1169
uint64_t format = lightmap_surfaces[i].format;
1170
if (tool->get_skin_weight_count() == SurfaceTool::SKIN_8_WEIGHTS) {
1171
format |= RS::ARRAY_FLAG_USE_8_BONE_WEIGHTS;
1172
} else {
1173
format &= ~RS::ARRAY_FLAG_USE_8_BONE_WEIGHTS;
1174
}
1175
1176
add_surface(tool->get_primitive_type(), arrays, Array(), Dictionary(), tool->get_material(), tool->get_meta("name"), format);
1177
}
1178
1179
set_lightmap_size_hint(Size2(size_x, size_y));
1180
1181
if (gen_cache_size > 0) {
1182
r_dst_cache.resize(gen_cache_size);
1183
memcpy(r_dst_cache.ptrw(), gen_cache, gen_cache_size);
1184
memfree(gen_cache);
1185
}
1186
1187
if (!use_cache) {
1188
// Cache was not used, free the buffers
1189
memfree(gen_vertices);
1190
memfree(gen_indices);
1191
memfree(gen_uvs);
1192
}
1193
1194
return OK;
1195
}
1196
1197
void ImporterMesh::set_lightmap_size_hint(const Size2i &p_size) {
1198
lightmap_size_hint = p_size;
1199
}
1200
1201
Size2i ImporterMesh::get_lightmap_size_hint() const {
1202
return lightmap_size_hint;
1203
}
1204
1205
void ImporterMesh::_bind_methods() {
1206
ClassDB::bind_method(D_METHOD("add_blend_shape", "name"), &ImporterMesh::add_blend_shape);
1207
ClassDB::bind_method(D_METHOD("get_blend_shape_count"), &ImporterMesh::get_blend_shape_count);
1208
ClassDB::bind_method(D_METHOD("get_blend_shape_name", "blend_shape_idx"), &ImporterMesh::get_blend_shape_name);
1209
1210
ClassDB::bind_method(D_METHOD("set_blend_shape_mode", "mode"), &ImporterMesh::set_blend_shape_mode);
1211
ClassDB::bind_method(D_METHOD("get_blend_shape_mode"), &ImporterMesh::get_blend_shape_mode);
1212
1213
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));
1214
1215
ClassDB::bind_method(D_METHOD("get_surface_count"), &ImporterMesh::get_surface_count);
1216
ClassDB::bind_method(D_METHOD("get_surface_primitive_type", "surface_idx"), &ImporterMesh::get_surface_primitive_type);
1217
ClassDB::bind_method(D_METHOD("get_surface_name", "surface_idx"), &ImporterMesh::get_surface_name);
1218
ClassDB::bind_method(D_METHOD("get_surface_arrays", "surface_idx"), &ImporterMesh::get_surface_arrays);
1219
ClassDB::bind_method(D_METHOD("get_surface_blend_shape_arrays", "surface_idx", "blend_shape_idx"), &ImporterMesh::get_surface_blend_shape_arrays);
1220
ClassDB::bind_method(D_METHOD("get_surface_lod_count", "surface_idx"), &ImporterMesh::get_surface_lod_count);
1221
ClassDB::bind_method(D_METHOD("get_surface_lod_size", "surface_idx", "lod_idx"), &ImporterMesh::get_surface_lod_size);
1222
ClassDB::bind_method(D_METHOD("get_surface_lod_indices", "surface_idx", "lod_idx"), &ImporterMesh::get_surface_lod_indices);
1223
ClassDB::bind_method(D_METHOD("get_surface_material", "surface_idx"), &ImporterMesh::get_surface_material);
1224
ClassDB::bind_method(D_METHOD("get_surface_format", "surface_idx"), &ImporterMesh::get_surface_format);
1225
1226
ClassDB::bind_method(D_METHOD("set_surface_name", "surface_idx", "name"), &ImporterMesh::set_surface_name);
1227
ClassDB::bind_method(D_METHOD("set_surface_material", "surface_idx", "material"), &ImporterMesh::set_surface_material);
1228
1229
ClassDB::bind_method(D_METHOD("generate_lods", "normal_merge_angle", "normal_split_angle", "bone_transform_array"), &ImporterMesh::_generate_lods_bind);
1230
ClassDB::bind_method(D_METHOD("get_mesh", "base_mesh"), &ImporterMesh::get_mesh, DEFVAL(Ref<ArrayMesh>()));
1231
ClassDB::bind_method(D_METHOD("clear"), &ImporterMesh::clear);
1232
1233
ClassDB::bind_method(D_METHOD("_set_data", "data"), &ImporterMesh::_set_data);
1234
ClassDB::bind_method(D_METHOD("_get_data"), &ImporterMesh::_get_data);
1235
1236
ClassDB::bind_method(D_METHOD("set_lightmap_size_hint", "size"), &ImporterMesh::set_lightmap_size_hint);
1237
ClassDB::bind_method(D_METHOD("get_lightmap_size_hint"), &ImporterMesh::get_lightmap_size_hint);
1238
1239
ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_data", "_get_data");
1240
}
1241
1242