importer_mesh.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  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. #include "importer_mesh.h"
  31. #include "core/io/marshalls.h"
  32. #include "core/math/convex_hull.h"
  33. #include "core/math/random_pcg.h"
  34. #include "scene/resources/surface_tool.h"
  35. String ImporterMesh::validate_blend_shape_name(const String &p_name) {
  36. String name = p_name;
  37. const char *characters = ":";
  38. for (const char *p = characters; *p; p++) {
  39. name = name.replace(String::chr(*p), "_");
  40. }
  41. return name;
  42. }
  43. void ImporterMesh::add_blend_shape(const String &p_name) {
  44. ERR_FAIL_COND(surfaces.size() > 0);
  45. blend_shapes.push_back(validate_blend_shape_name(p_name));
  46. }
  47. int ImporterMesh::get_blend_shape_count() const {
  48. return blend_shapes.size();
  49. }
  50. String ImporterMesh::get_blend_shape_name(int p_blend_shape) const {
  51. ERR_FAIL_INDEX_V(p_blend_shape, blend_shapes.size(), String());
  52. return blend_shapes[p_blend_shape];
  53. }
  54. void ImporterMesh::set_blend_shape_mode(Mesh::BlendShapeMode p_blend_shape_mode) {
  55. blend_shape_mode = p_blend_shape_mode;
  56. }
  57. Mesh::BlendShapeMode ImporterMesh::get_blend_shape_mode() const {
  58. return blend_shape_mode;
  59. }
  60. 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) {
  61. ERR_FAIL_COND(p_blend_shapes.size() != blend_shapes.size());
  62. ERR_FAIL_COND(p_arrays.size() != Mesh::ARRAY_MAX);
  63. Surface s;
  64. s.primitive = p_primitive;
  65. s.arrays = p_arrays;
  66. s.name = p_name;
  67. s.flags = p_flags;
  68. Vector<Vector3> vertex_array = p_arrays[Mesh::ARRAY_VERTEX];
  69. int vertex_count = vertex_array.size();
  70. ERR_FAIL_COND(vertex_count == 0);
  71. for (int i = 0; i < blend_shapes.size(); i++) {
  72. Array bsdata = p_blend_shapes[i];
  73. ERR_FAIL_COND(bsdata.size() != Mesh::ARRAY_MAX);
  74. Vector<Vector3> vertex_data = bsdata[Mesh::ARRAY_VERTEX];
  75. ERR_FAIL_COND(vertex_data.size() != vertex_count);
  76. Surface::BlendShape bs;
  77. bs.arrays = bsdata;
  78. s.blend_shape_data.push_back(bs);
  79. }
  80. for (const KeyValue<Variant, Variant> &kv : p_lods) {
  81. ERR_CONTINUE(!kv.key.is_num());
  82. Surface::LOD lod;
  83. lod.distance = kv.key;
  84. lod.indices = kv.value;
  85. ERR_CONTINUE(lod.indices.is_empty());
  86. s.lods.push_back(lod);
  87. }
  88. s.material = p_material;
  89. surfaces.push_back(s);
  90. mesh.unref();
  91. }
  92. int ImporterMesh::get_surface_count() const {
  93. return surfaces.size();
  94. }
  95. Mesh::PrimitiveType ImporterMesh::get_surface_primitive_type(int p_surface) {
  96. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Mesh::PRIMITIVE_MAX);
  97. return surfaces[p_surface].primitive;
  98. }
  99. Array ImporterMesh::get_surface_arrays(int p_surface) const {
  100. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array());
  101. return surfaces[p_surface].arrays;
  102. }
  103. String ImporterMesh::get_surface_name(int p_surface) const {
  104. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), String());
  105. return surfaces[p_surface].name;
  106. }
  107. void ImporterMesh::set_surface_name(int p_surface, const String &p_name) {
  108. ERR_FAIL_INDEX(p_surface, surfaces.size());
  109. surfaces.write[p_surface].name = p_name;
  110. mesh.unref();
  111. }
  112. Array ImporterMesh::get_surface_blend_shape_arrays(int p_surface, int p_blend_shape) const {
  113. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array());
  114. ERR_FAIL_INDEX_V(p_blend_shape, surfaces[p_surface].blend_shape_data.size(), Array());
  115. return surfaces[p_surface].blend_shape_data[p_blend_shape].arrays;
  116. }
  117. int ImporterMesh::get_surface_lod_count(int p_surface) const {
  118. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), 0);
  119. return surfaces[p_surface].lods.size();
  120. }
  121. Vector<int> ImporterMesh::get_surface_lod_indices(int p_surface, int p_lod) const {
  122. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Vector<int>());
  123. ERR_FAIL_INDEX_V(p_lod, surfaces[p_surface].lods.size(), Vector<int>());
  124. return surfaces[p_surface].lods[p_lod].indices;
  125. }
  126. float ImporterMesh::get_surface_lod_size(int p_surface, int p_lod) const {
  127. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), 0);
  128. ERR_FAIL_INDEX_V(p_lod, surfaces[p_surface].lods.size(), 0);
  129. return surfaces[p_surface].lods[p_lod].distance;
  130. }
  131. uint64_t ImporterMesh::get_surface_format(int p_surface) const {
  132. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), 0);
  133. return surfaces[p_surface].flags;
  134. }
  135. Ref<Material> ImporterMesh::get_surface_material(int p_surface) const {
  136. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Ref<Material>());
  137. return surfaces[p_surface].material;
  138. }
  139. void ImporterMesh::set_surface_material(int p_surface, const Ref<Material> &p_material) {
  140. ERR_FAIL_INDEX(p_surface, surfaces.size());
  141. surfaces.write[p_surface].material = p_material;
  142. mesh.unref();
  143. }
  144. template <typename T>
  145. static Vector<T> _remap_array(Vector<T> p_array, const Vector<uint32_t> &p_remap, uint32_t p_vertex_count) {
  146. ERR_FAIL_COND_V(p_array.size() % p_remap.size() != 0, p_array);
  147. int num_elements = p_array.size() / p_remap.size();
  148. T *data = p_array.ptrw();
  149. SurfaceTool::remap_vertex_func(data, data, p_remap.size(), sizeof(T) * num_elements, p_remap.ptr());
  150. p_array.resize(p_vertex_count * num_elements);
  151. return p_array;
  152. }
  153. static void _remap_arrays(Array &r_arrays, const Vector<uint32_t> &p_remap, uint32_t p_vertex_count) {
  154. for (int i = 0; i < r_arrays.size(); i++) {
  155. if (i == RS::ARRAY_INDEX) {
  156. continue;
  157. }
  158. switch (r_arrays[i].get_type()) {
  159. case Variant::NIL:
  160. break;
  161. case Variant::PACKED_VECTOR3_ARRAY:
  162. r_arrays[i] = _remap_array<Vector3>(r_arrays[i], p_remap, p_vertex_count);
  163. break;
  164. case Variant::PACKED_VECTOR2_ARRAY:
  165. r_arrays[i] = _remap_array<Vector2>(r_arrays[i], p_remap, p_vertex_count);
  166. break;
  167. case Variant::PACKED_FLOAT32_ARRAY:
  168. r_arrays[i] = _remap_array<float>(r_arrays[i], p_remap, p_vertex_count);
  169. break;
  170. case Variant::PACKED_INT32_ARRAY:
  171. r_arrays[i] = _remap_array<int32_t>(r_arrays[i], p_remap, p_vertex_count);
  172. break;
  173. case Variant::PACKED_BYTE_ARRAY:
  174. r_arrays[i] = _remap_array<uint8_t>(r_arrays[i], p_remap, p_vertex_count);
  175. break;
  176. case Variant::PACKED_COLOR_ARRAY:
  177. r_arrays[i] = _remap_array<Color>(r_arrays[i], p_remap, p_vertex_count);
  178. break;
  179. default:
  180. ERR_FAIL_MSG("Unhandled array type.");
  181. }
  182. }
  183. }
  184. void ImporterMesh::optimize_indices() {
  185. if (!SurfaceTool::optimize_vertex_cache_func) {
  186. return;
  187. }
  188. if (!SurfaceTool::optimize_vertex_fetch_remap_func || !SurfaceTool::remap_vertex_func || !SurfaceTool::remap_index_func) {
  189. return;
  190. }
  191. for (int i = 0; i < surfaces.size(); i++) {
  192. if (surfaces[i].primitive != Mesh::PRIMITIVE_TRIANGLES) {
  193. continue;
  194. }
  195. Vector<Vector3> vertices = surfaces[i].arrays[RS::ARRAY_VERTEX];
  196. PackedInt32Array indices = surfaces[i].arrays[RS::ARRAY_INDEX];
  197. unsigned int index_count = indices.size();
  198. unsigned int vertex_count = vertices.size();
  199. if (index_count == 0) {
  200. continue;
  201. }
  202. // Optimize indices for vertex cache to establish final triangle order.
  203. int *indices_ptr = indices.ptrw();
  204. SurfaceTool::optimize_vertex_cache_func((unsigned int *)indices_ptr, (const unsigned int *)indices_ptr, index_count, vertex_count);
  205. surfaces.write[i].arrays[RS::ARRAY_INDEX] = indices;
  206. for (int j = 0; j < surfaces[i].lods.size(); ++j) {
  207. Surface::LOD &lod = surfaces.write[i].lods.write[j];
  208. int *lod_indices_ptr = lod.indices.ptrw();
  209. SurfaceTool::optimize_vertex_cache_func((unsigned int *)lod_indices_ptr, (const unsigned int *)lod_indices_ptr, lod.indices.size(), vertex_count);
  210. }
  211. // Concatenate indices for all LODs in the order of coarse->fine; this establishes the effective order of vertices,
  212. // and is important to optimize for vertex fetch (all GPUs) and shading (Mali GPUs)
  213. PackedInt32Array merged_indices;
  214. for (int j = surfaces[i].lods.size() - 1; j >= 0; --j) {
  215. merged_indices.append_array(surfaces[i].lods[j].indices);
  216. }
  217. merged_indices.append_array(indices);
  218. // Generate remap array that establishes optimal vertex order according to the order of indices above.
  219. Vector<uint32_t> remap;
  220. remap.resize(vertex_count);
  221. unsigned int new_vertex_count = SurfaceTool::optimize_vertex_fetch_remap_func(remap.ptrw(), (const unsigned int *)merged_indices.ptr(), merged_indices.size(), vertex_count);
  222. // We need to remap all vertex and index arrays in lockstep according to the remap.
  223. SurfaceTool::remap_index_func((unsigned int *)indices_ptr, (const unsigned int *)indices_ptr, index_count, remap.ptr());
  224. surfaces.write[i].arrays[RS::ARRAY_INDEX] = indices;
  225. for (int j = 0; j < surfaces[i].lods.size(); ++j) {
  226. Surface::LOD &lod = surfaces.write[i].lods.write[j];
  227. int *lod_indices_ptr = lod.indices.ptrw();
  228. SurfaceTool::remap_index_func((unsigned int *)lod_indices_ptr, (const unsigned int *)lod_indices_ptr, lod.indices.size(), remap.ptr());
  229. }
  230. _remap_arrays(surfaces.write[i].arrays, remap, new_vertex_count);
  231. for (int j = 0; j < surfaces[i].blend_shape_data.size(); j++) {
  232. _remap_arrays(surfaces.write[i].blend_shape_data.write[j].arrays, remap, new_vertex_count);
  233. }
  234. }
  235. if (shadow_mesh.is_valid()) {
  236. shadow_mesh->optimize_indices();
  237. }
  238. }
  239. #define VERTEX_SKIN_FUNC(bone_count, vert_idx, read_array, write_array, transform_array, bone_array, weight_array) \
  240. Vector3 transformed_vert; \
  241. for (unsigned int weight_idx = 0; weight_idx < bone_count; weight_idx++) { \
  242. int bone_idx = bone_array[vert_idx * bone_count + weight_idx]; \
  243. float w = weight_array[vert_idx * bone_count + weight_idx]; \
  244. if (w < FLT_EPSILON) { \
  245. continue; \
  246. } \
  247. ERR_FAIL_INDEX(bone_idx, static_cast<int>(transform_array.size())); \
  248. transformed_vert += transform_array[bone_idx].xform(read_array[vert_idx]) * w; \
  249. } \
  250. write_array[vert_idx] = transformed_vert;
  251. void ImporterMesh::generate_lods(float p_normal_merge_angle, Array p_bone_transform_array) {
  252. if (!SurfaceTool::simplify_scale_func) {
  253. return;
  254. }
  255. if (!SurfaceTool::simplify_with_attrib_func) {
  256. return;
  257. }
  258. LocalVector<Transform3D> bone_transform_vector;
  259. for (int i = 0; i < p_bone_transform_array.size(); i++) {
  260. ERR_FAIL_COND(p_bone_transform_array[i].get_type() != Variant::TRANSFORM3D);
  261. bone_transform_vector.push_back(p_bone_transform_array[i]);
  262. }
  263. for (int i = 0; i < surfaces.size(); i++) {
  264. if (surfaces[i].primitive != Mesh::PRIMITIVE_TRIANGLES) {
  265. continue;
  266. }
  267. surfaces.write[i].lods.clear();
  268. Vector<Vector3> vertices = surfaces[i].arrays[RS::ARRAY_VERTEX];
  269. PackedInt32Array indices = surfaces[i].arrays[RS::ARRAY_INDEX];
  270. Vector<Vector3> normals = surfaces[i].arrays[RS::ARRAY_NORMAL];
  271. Vector<float> tangents = surfaces[i].arrays[RS::ARRAY_TANGENT];
  272. Vector<Vector2> uvs = surfaces[i].arrays[RS::ARRAY_TEX_UV];
  273. Vector<Vector2> uv2s = surfaces[i].arrays[RS::ARRAY_TEX_UV2];
  274. Vector<int> bones = surfaces[i].arrays[RS::ARRAY_BONES];
  275. Vector<float> weights = surfaces[i].arrays[RS::ARRAY_WEIGHTS];
  276. unsigned int index_count = indices.size();
  277. unsigned int vertex_count = vertices.size();
  278. if (index_count == 0) {
  279. continue; //no lods if no indices
  280. }
  281. const Vector3 *vertices_ptr = vertices.ptr();
  282. const int *indices_ptr = indices.ptr();
  283. if (normals.is_empty()) {
  284. normals.resize(index_count);
  285. Vector3 *n_ptr = normals.ptrw();
  286. for (unsigned int j = 0; j < index_count; j += 3) {
  287. const Vector3 &v0 = vertices_ptr[indices_ptr[j + 0]];
  288. const Vector3 &v1 = vertices_ptr[indices_ptr[j + 1]];
  289. const Vector3 &v2 = vertices_ptr[indices_ptr[j + 2]];
  290. Vector3 n = vec3_cross(v0 - v2, v0 - v1).normalized();
  291. n_ptr[j + 0] = n;
  292. n_ptr[j + 1] = n;
  293. n_ptr[j + 2] = n;
  294. }
  295. }
  296. if (bones.size() > 0 && weights.size() && bone_transform_vector.size() > 0) {
  297. Vector3 *vertices_ptrw = vertices.ptrw();
  298. // Apply bone transforms to regular surface.
  299. unsigned int bone_weight_length = surfaces[i].flags & Mesh::ARRAY_FLAG_USE_8_BONE_WEIGHTS ? 8 : 4;
  300. const int *bo = bones.ptr();
  301. const float *we = weights.ptr();
  302. for (unsigned int j = 0; j < vertex_count; j++) {
  303. VERTEX_SKIN_FUNC(bone_weight_length, j, vertices_ptr, vertices_ptrw, bone_transform_vector, bo, we)
  304. }
  305. vertices_ptr = vertices.ptr();
  306. }
  307. float normal_merge_threshold = Math::cos(Math::deg_to_rad(p_normal_merge_angle));
  308. const Vector3 *normals_ptr = normals.ptr();
  309. HashMap<Vector3, LocalVector<Pair<int, int>>> unique_vertices;
  310. LocalVector<int> vertex_remap;
  311. LocalVector<int> vertex_inverse_remap;
  312. LocalVector<Vector3> merged_vertices;
  313. LocalVector<Vector3> merged_normals;
  314. LocalVector<int> merged_normals_counts;
  315. const Vector2 *uvs_ptr = uvs.ptr();
  316. const Vector2 *uv2s_ptr = uv2s.ptr();
  317. const float *tangents_ptr = tangents.ptr();
  318. for (unsigned int j = 0; j < vertex_count; j++) {
  319. const Vector3 &v = vertices_ptr[j];
  320. const Vector3 &n = normals_ptr[j];
  321. HashMap<Vector3, LocalVector<Pair<int, int>>>::Iterator E = unique_vertices.find(v);
  322. if (E) {
  323. const LocalVector<Pair<int, int>> &close_verts = E->value;
  324. bool found = false;
  325. for (const Pair<int, int> &idx : close_verts) {
  326. bool is_uvs_close = (!uvs_ptr || uvs_ptr[j].distance_squared_to(uvs_ptr[idx.second]) < CMP_EPSILON2);
  327. bool is_uv2s_close = (!uv2s_ptr || uv2s_ptr[j].distance_squared_to(uv2s_ptr[idx.second]) < CMP_EPSILON2);
  328. bool is_tang_aligned = !tangents_ptr || (tangents_ptr[j * 4 + 3] < 0) == (tangents_ptr[idx.second * 4 + 3] < 0);
  329. ERR_FAIL_INDEX(idx.second, normals.size());
  330. bool is_normals_close = normals[idx.second].dot(n) > normal_merge_threshold;
  331. if (is_uvs_close && is_uv2s_close && is_normals_close && is_tang_aligned) {
  332. vertex_remap.push_back(idx.first);
  333. merged_normals[idx.first] += normals[idx.second];
  334. merged_normals_counts[idx.first]++;
  335. found = true;
  336. break;
  337. }
  338. }
  339. if (!found) {
  340. int vcount = merged_vertices.size();
  341. unique_vertices[v].push_back(Pair<int, int>(vcount, j));
  342. vertex_inverse_remap.push_back(j);
  343. merged_vertices.push_back(v);
  344. vertex_remap.push_back(vcount);
  345. merged_normals.push_back(normals_ptr[j]);
  346. merged_normals_counts.push_back(1);
  347. }
  348. } else {
  349. int vcount = merged_vertices.size();
  350. unique_vertices[v] = LocalVector<Pair<int, int>>();
  351. unique_vertices[v].push_back(Pair<int, int>(vcount, j));
  352. vertex_inverse_remap.push_back(j);
  353. merged_vertices.push_back(v);
  354. vertex_remap.push_back(vcount);
  355. merged_normals.push_back(normals_ptr[j]);
  356. merged_normals_counts.push_back(1);
  357. }
  358. }
  359. LocalVector<int> merged_indices;
  360. merged_indices.resize(index_count);
  361. for (unsigned int j = 0; j < index_count; j++) {
  362. merged_indices[j] = vertex_remap[indices[j]];
  363. }
  364. unsigned int merged_vertex_count = merged_vertices.size();
  365. const Vector3 *merged_vertices_ptr = merged_vertices.ptr();
  366. const int32_t *merged_indices_ptr = merged_indices.ptr();
  367. {
  368. const int *counts_ptr = merged_normals_counts.ptr();
  369. Vector3 *merged_normals_ptrw = merged_normals.ptr();
  370. for (unsigned int j = 0; j < merged_vertex_count; j++) {
  371. merged_normals_ptrw[j] /= counts_ptr[j];
  372. }
  373. }
  374. const float normal_weights[3] = {
  375. // Give some weight to normal preservation, may be worth exposing as an import setting
  376. 2.0f, 2.0f, 2.0f
  377. };
  378. Vector<float> merged_vertices_f32 = vector3_to_float32_array(merged_vertices_ptr, merged_vertex_count);
  379. float scale = SurfaceTool::simplify_scale_func(merged_vertices_f32.ptr(), merged_vertex_count, sizeof(float) * 3);
  380. unsigned int index_target = 12; // Start with the smallest target, 4 triangles
  381. unsigned int last_index_count = 0;
  382. const float max_mesh_error = FLT_MAX; // We don't want to limit by error, just by index target
  383. float mesh_error = 0.0f;
  384. while (index_target < index_count) {
  385. PackedInt32Array new_indices;
  386. new_indices.resize(index_count);
  387. Vector<float> merged_normals_f32 = vector3_to_float32_array(merged_normals.ptr(), merged_normals.size());
  388. const int simplify_options = SurfaceTool::SIMPLIFY_LOCK_BORDER;
  389. size_t new_index_count = SurfaceTool::simplify_with_attrib_func(
  390. (unsigned int *)new_indices.ptrw(),
  391. (const uint32_t *)merged_indices_ptr, index_count,
  392. merged_vertices_f32.ptr(), merged_vertex_count,
  393. sizeof(float) * 3, // Vertex stride
  394. merged_normals_f32.ptr(),
  395. sizeof(float) * 3, // Attribute stride
  396. normal_weights, 3,
  397. nullptr, // Vertex lock
  398. index_target,
  399. max_mesh_error,
  400. simplify_options,
  401. &mesh_error);
  402. if (new_index_count < last_index_count * 1.5f) {
  403. index_target = index_target * 1.5f;
  404. continue;
  405. }
  406. if (new_index_count == 0 || (new_index_count >= (index_count * 0.75f))) {
  407. break;
  408. }
  409. if (new_index_count > 5000000) {
  410. // This limit theoretically shouldn't be needed, but it's here
  411. // as an ad-hoc fix to prevent a crash with complex meshes.
  412. // The crash still happens with limit of 6000000, but 5000000 works.
  413. // In the future, identify what's causing that crash and fix it.
  414. WARN_PRINT("Mesh LOD generation failed for mesh " + get_name() + " surface " + itos(i) + ", mesh is too complex. Some automatic LODs were not generated.");
  415. break;
  416. }
  417. new_indices.resize(new_index_count);
  418. {
  419. int *ptrw = new_indices.ptrw();
  420. for (unsigned int j = 0; j < new_index_count; j++) {
  421. ptrw[j] = vertex_inverse_remap[ptrw[j]];
  422. }
  423. }
  424. Surface::LOD lod;
  425. lod.distance = MAX(mesh_error * scale, CMP_EPSILON2);
  426. lod.indices = new_indices;
  427. surfaces.write[i].lods.push_back(lod);
  428. index_target = MAX(new_index_count, index_target) * 2;
  429. last_index_count = new_index_count;
  430. if (mesh_error == 0.0f) {
  431. break;
  432. }
  433. }
  434. surfaces.write[i].lods.sort_custom<Surface::LODComparator>();
  435. }
  436. }
  437. void ImporterMesh::_generate_lods_bind(float p_normal_merge_angle, float p_normal_split_angle, Array p_skin_pose_transform_array) {
  438. // p_normal_split_angle is unused, but kept for compatibility
  439. generate_lods(p_normal_merge_angle, p_skin_pose_transform_array);
  440. }
  441. bool ImporterMesh::has_mesh() const {
  442. return mesh.is_valid();
  443. }
  444. Ref<ArrayMesh> ImporterMesh::get_mesh(const Ref<ArrayMesh> &p_base) {
  445. ERR_FAIL_COND_V(surfaces.is_empty(), Ref<ArrayMesh>());
  446. if (mesh.is_null()) {
  447. if (p_base.is_valid()) {
  448. mesh = p_base;
  449. }
  450. if (mesh.is_null()) {
  451. mesh.instantiate();
  452. }
  453. mesh->set_name(get_name());
  454. if (has_meta("import_id")) {
  455. mesh->set_meta("import_id", get_meta("import_id"));
  456. }
  457. for (int i = 0; i < blend_shapes.size(); i++) {
  458. mesh->add_blend_shape(blend_shapes[i]);
  459. }
  460. mesh->set_blend_shape_mode(blend_shape_mode);
  461. for (int i = 0; i < surfaces.size(); i++) {
  462. Array bs_data;
  463. if (surfaces[i].blend_shape_data.size()) {
  464. for (int j = 0; j < surfaces[i].blend_shape_data.size(); j++) {
  465. bs_data.push_back(surfaces[i].blend_shape_data[j].arrays);
  466. }
  467. }
  468. Dictionary lods;
  469. if (surfaces[i].lods.size()) {
  470. for (int j = 0; j < surfaces[i].lods.size(); j++) {
  471. lods[surfaces[i].lods[j].distance] = surfaces[i].lods[j].indices;
  472. }
  473. }
  474. mesh->add_surface_from_arrays(surfaces[i].primitive, surfaces[i].arrays, bs_data, lods, surfaces[i].flags);
  475. if (surfaces[i].material.is_valid()) {
  476. mesh->surface_set_material(mesh->get_surface_count() - 1, surfaces[i].material);
  477. }
  478. if (!surfaces[i].name.is_empty()) {
  479. mesh->surface_set_name(mesh->get_surface_count() - 1, surfaces[i].name);
  480. }
  481. }
  482. mesh->set_lightmap_size_hint(lightmap_size_hint);
  483. if (shadow_mesh.is_valid()) {
  484. Ref<ArrayMesh> shadow = shadow_mesh->get_mesh();
  485. mesh->set_shadow_mesh(shadow);
  486. }
  487. }
  488. return mesh;
  489. }
  490. void ImporterMesh::clear() {
  491. surfaces.clear();
  492. blend_shapes.clear();
  493. mesh.unref();
  494. }
  495. void ImporterMesh::create_shadow_mesh() {
  496. if (shadow_mesh.is_valid()) {
  497. shadow_mesh.unref();
  498. }
  499. //no shadow mesh for blendshapes
  500. if (blend_shapes.size() > 0) {
  501. return;
  502. }
  503. //no shadow mesh for skeletons
  504. for (int i = 0; i < surfaces.size(); i++) {
  505. if (surfaces[i].arrays[RS::ARRAY_BONES].get_type() != Variant::NIL) {
  506. return;
  507. }
  508. if (surfaces[i].arrays[RS::ARRAY_WEIGHTS].get_type() != Variant::NIL) {
  509. return;
  510. }
  511. }
  512. shadow_mesh.instantiate();
  513. for (int i = 0; i < surfaces.size(); i++) {
  514. LocalVector<int> vertex_remap;
  515. Vector<Vector3> new_vertices;
  516. Vector<Vector3> vertices = surfaces[i].arrays[RS::ARRAY_VERTEX];
  517. int vertex_count = vertices.size();
  518. {
  519. HashMap<Vector3, int> unique_vertices;
  520. const Vector3 *vptr = vertices.ptr();
  521. for (int j = 0; j < vertex_count; j++) {
  522. const Vector3 &v = vptr[j];
  523. HashMap<Vector3, int>::Iterator E = unique_vertices.find(v);
  524. if (E) {
  525. vertex_remap.push_back(E->value);
  526. } else {
  527. int vcount = unique_vertices.size();
  528. unique_vertices[v] = vcount;
  529. vertex_remap.push_back(vcount);
  530. new_vertices.push_back(v);
  531. }
  532. }
  533. }
  534. Array new_surface;
  535. new_surface.resize(RS::ARRAY_MAX);
  536. Dictionary lods;
  537. // print_line("original vertex count: " + itos(vertices.size()) + " new vertex count: " + itos(new_vertices.size()));
  538. new_surface[RS::ARRAY_VERTEX] = new_vertices;
  539. Vector<int> indices = surfaces[i].arrays[RS::ARRAY_INDEX];
  540. if (indices.size()) {
  541. int index_count = indices.size();
  542. const int *index_rptr = indices.ptr();
  543. Vector<int> new_indices;
  544. new_indices.resize(indices.size());
  545. int *index_wptr = new_indices.ptrw();
  546. for (int j = 0; j < index_count; j++) {
  547. int index = index_rptr[j];
  548. ERR_FAIL_INDEX(index, vertex_count);
  549. index_wptr[j] = vertex_remap[index];
  550. }
  551. new_surface[RS::ARRAY_INDEX] = new_indices;
  552. // Make sure the same LODs as the full version are used.
  553. // This makes it more coherent between rendered model and its shadows.
  554. for (int j = 0; j < surfaces[i].lods.size(); j++) {
  555. indices = surfaces[i].lods[j].indices;
  556. index_count = indices.size();
  557. index_rptr = indices.ptr();
  558. new_indices.resize(indices.size());
  559. index_wptr = new_indices.ptrw();
  560. for (int k = 0; k < index_count; k++) {
  561. int index = index_rptr[k];
  562. ERR_FAIL_INDEX(index, vertex_count);
  563. index_wptr[k] = vertex_remap[index];
  564. }
  565. lods[surfaces[i].lods[j].distance] = new_indices;
  566. }
  567. }
  568. shadow_mesh->add_surface(surfaces[i].primitive, new_surface, Array(), lods, Ref<Material>(), surfaces[i].name, surfaces[i].flags);
  569. }
  570. }
  571. Ref<ImporterMesh> ImporterMesh::get_shadow_mesh() const {
  572. return shadow_mesh;
  573. }
  574. void ImporterMesh::_set_data(const Dictionary &p_data) {
  575. clear();
  576. if (p_data.has("blend_shape_names")) {
  577. blend_shapes = p_data["blend_shape_names"];
  578. }
  579. if (p_data.has("surfaces")) {
  580. Array surface_arr = p_data["surfaces"];
  581. for (int i = 0; i < surface_arr.size(); i++) {
  582. Dictionary s = surface_arr[i];
  583. ERR_CONTINUE(!s.has("primitive"));
  584. ERR_CONTINUE(!s.has("arrays"));
  585. Mesh::PrimitiveType prim = Mesh::PrimitiveType(int(s["primitive"]));
  586. ERR_CONTINUE(prim >= Mesh::PRIMITIVE_MAX);
  587. Array arr = s["arrays"];
  588. Dictionary lods;
  589. String surf_name;
  590. if (s.has("name")) {
  591. surf_name = s["name"];
  592. }
  593. if (s.has("lods")) {
  594. lods = s["lods"];
  595. }
  596. Array b_shapes;
  597. if (s.has("b_shapes")) {
  598. b_shapes = s["b_shapes"];
  599. }
  600. Ref<Material> material;
  601. if (s.has("material")) {
  602. material = s["material"];
  603. }
  604. uint64_t flags = 0;
  605. if (s.has("flags")) {
  606. flags = s["flags"];
  607. }
  608. add_surface(prim, arr, b_shapes, lods, material, surf_name, flags);
  609. }
  610. }
  611. }
  612. Dictionary ImporterMesh::_get_data() const {
  613. Dictionary data;
  614. if (blend_shapes.size()) {
  615. data["blend_shape_names"] = blend_shapes;
  616. }
  617. Array surface_arr;
  618. for (int i = 0; i < surfaces.size(); i++) {
  619. Dictionary d;
  620. d["primitive"] = surfaces[i].primitive;
  621. d["arrays"] = surfaces[i].arrays;
  622. if (surfaces[i].blend_shape_data.size()) {
  623. Array bs_data;
  624. for (int j = 0; j < surfaces[i].blend_shape_data.size(); j++) {
  625. bs_data.push_back(surfaces[i].blend_shape_data[j].arrays);
  626. }
  627. d["blend_shapes"] = bs_data;
  628. }
  629. if (surfaces[i].lods.size()) {
  630. Dictionary lods;
  631. for (int j = 0; j < surfaces[i].lods.size(); j++) {
  632. lods[surfaces[i].lods[j].distance] = surfaces[i].lods[j].indices;
  633. }
  634. d["lods"] = lods;
  635. }
  636. if (surfaces[i].material.is_valid()) {
  637. d["material"] = surfaces[i].material;
  638. }
  639. if (!surfaces[i].name.is_empty()) {
  640. d["name"] = surfaces[i].name;
  641. }
  642. d["flags"] = surfaces[i].flags;
  643. surface_arr.push_back(d);
  644. }
  645. data["surfaces"] = surface_arr;
  646. return data;
  647. }
  648. Vector<Face3> ImporterMesh::get_faces() const {
  649. Vector<Face3> faces;
  650. for (int i = 0; i < surfaces.size(); i++) {
  651. if (surfaces[i].primitive == Mesh::PRIMITIVE_TRIANGLES) {
  652. Vector<Vector3> vertices = surfaces[i].arrays[Mesh::ARRAY_VERTEX];
  653. Vector<int> indices = surfaces[i].arrays[Mesh::ARRAY_INDEX];
  654. if (indices.size()) {
  655. for (int j = 0; j < indices.size(); j += 3) {
  656. Face3 f;
  657. f.vertex[0] = vertices[indices[j + 0]];
  658. f.vertex[1] = vertices[indices[j + 1]];
  659. f.vertex[2] = vertices[indices[j + 2]];
  660. faces.push_back(f);
  661. }
  662. } else {
  663. for (int j = 0; j < vertices.size(); j += 3) {
  664. Face3 f;
  665. f.vertex[0] = vertices[j + 0];
  666. f.vertex[1] = vertices[j + 1];
  667. f.vertex[2] = vertices[j + 2];
  668. faces.push_back(f);
  669. }
  670. }
  671. }
  672. }
  673. return faces;
  674. }
  675. Vector<Ref<Shape3D>> ImporterMesh::convex_decompose(const Ref<MeshConvexDecompositionSettings> &p_settings) const {
  676. ERR_FAIL_NULL_V(Mesh::convex_decomposition_function, Vector<Ref<Shape3D>>());
  677. const Vector<Face3> faces = get_faces();
  678. int face_count = faces.size();
  679. Vector<Vector3> vertices;
  680. uint32_t vertex_count = 0;
  681. vertices.resize(face_count * 3);
  682. Vector<uint32_t> indices;
  683. indices.resize(face_count * 3);
  684. {
  685. HashMap<Vector3, uint32_t> vertex_map;
  686. Vector3 *vertex_w = vertices.ptrw();
  687. uint32_t *index_w = indices.ptrw();
  688. for (int i = 0; i < face_count; i++) {
  689. for (int j = 0; j < 3; j++) {
  690. const Vector3 &vertex = faces[i].vertex[j];
  691. HashMap<Vector3, uint32_t>::Iterator found_vertex = vertex_map.find(vertex);
  692. uint32_t index;
  693. if (found_vertex) {
  694. index = found_vertex->value;
  695. } else {
  696. index = vertex_count++;
  697. vertex_map[vertex] = index;
  698. vertex_w[index] = vertex;
  699. }
  700. index_w[i * 3 + j] = index;
  701. }
  702. }
  703. }
  704. vertices.resize(vertex_count);
  705. Vector<Vector<Vector3>> decomposed = Mesh::convex_decomposition_function((real_t *)vertices.ptr(), vertex_count, indices.ptr(), face_count, p_settings, nullptr);
  706. Vector<Ref<Shape3D>> ret;
  707. for (int i = 0; i < decomposed.size(); i++) {
  708. Ref<ConvexPolygonShape3D> shape;
  709. shape.instantiate();
  710. shape->set_points(decomposed[i]);
  711. ret.push_back(shape);
  712. }
  713. return ret;
  714. }
  715. Ref<ConvexPolygonShape3D> ImporterMesh::create_convex_shape(bool p_clean, bool p_simplify) const {
  716. if (p_simplify) {
  717. Ref<MeshConvexDecompositionSettings> settings;
  718. settings.instantiate();
  719. settings->set_max_convex_hulls(1);
  720. Vector<Ref<Shape3D>> decomposed = convex_decompose(settings);
  721. if (decomposed.size() == 1) {
  722. return decomposed[0];
  723. } else {
  724. ERR_PRINT("Convex shape simplification failed, falling back to simpler process.");
  725. }
  726. }
  727. Vector<Vector3> vertices;
  728. for (int i = 0; i < get_surface_count(); i++) {
  729. Array a = get_surface_arrays(i);
  730. ERR_FAIL_COND_V(a.is_empty(), Ref<ConvexPolygonShape3D>());
  731. Vector<Vector3> v = a[Mesh::ARRAY_VERTEX];
  732. vertices.append_array(v);
  733. }
  734. Ref<ConvexPolygonShape3D> shape = memnew(ConvexPolygonShape3D);
  735. if (p_clean) {
  736. Geometry3D::MeshData md;
  737. Error err = ConvexHullComputer::convex_hull(vertices, md);
  738. if (err == OK) {
  739. shape->set_points(md.vertices);
  740. return shape;
  741. } else {
  742. ERR_PRINT("Convex shape cleaning failed, falling back to simpler process.");
  743. }
  744. }
  745. shape->set_points(vertices);
  746. return shape;
  747. }
  748. Ref<ConcavePolygonShape3D> ImporterMesh::create_trimesh_shape() const {
  749. Vector<Face3> faces = get_faces();
  750. if (faces.size() == 0) {
  751. return Ref<ConcavePolygonShape3D>();
  752. }
  753. Vector<Vector3> face_points;
  754. face_points.resize(faces.size() * 3);
  755. for (int i = 0; i < face_points.size(); i += 3) {
  756. Face3 f = faces.get(i / 3);
  757. face_points.set(i, f.vertex[0]);
  758. face_points.set(i + 1, f.vertex[1]);
  759. face_points.set(i + 2, f.vertex[2]);
  760. }
  761. Ref<ConcavePolygonShape3D> shape = memnew(ConcavePolygonShape3D);
  762. shape->set_faces(face_points);
  763. return shape;
  764. }
  765. Ref<NavigationMesh> ImporterMesh::create_navigation_mesh() {
  766. Vector<Face3> faces = get_faces();
  767. if (faces.size() == 0) {
  768. return Ref<NavigationMesh>();
  769. }
  770. HashMap<Vector3, int> unique_vertices;
  771. Vector<Vector<int>> face_polygons;
  772. face_polygons.resize(faces.size());
  773. for (int i = 0; i < faces.size(); i++) {
  774. Vector<int> face_indices;
  775. face_indices.resize(3);
  776. for (int j = 0; j < 3; j++) {
  777. Vector3 v = faces[i].vertex[j];
  778. int idx;
  779. if (unique_vertices.has(v)) {
  780. idx = unique_vertices[v];
  781. } else {
  782. idx = unique_vertices.size();
  783. unique_vertices[v] = idx;
  784. }
  785. face_indices.write[j] = idx;
  786. }
  787. face_polygons.write[i] = face_indices;
  788. }
  789. Vector<Vector3> vertices;
  790. vertices.resize(unique_vertices.size());
  791. for (const KeyValue<Vector3, int> &E : unique_vertices) {
  792. vertices.write[E.value] = E.key;
  793. }
  794. Ref<NavigationMesh> nm;
  795. nm.instantiate();
  796. nm->set_data(vertices, face_polygons);
  797. return nm;
  798. }
  799. 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);
  800. struct EditorSceneFormatImporterMeshLightmapSurface {
  801. Ref<Material> material;
  802. LocalVector<SurfaceTool::Vertex> vertices;
  803. Mesh::PrimitiveType primitive = Mesh::PrimitiveType::PRIMITIVE_MAX;
  804. uint64_t format = 0;
  805. String name;
  806. };
  807. 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 };
  808. 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) {
  809. ERR_FAIL_NULL_V(array_mesh_lightmap_unwrap_callback, ERR_UNCONFIGURED);
  810. ERR_FAIL_COND_V_MSG(blend_shapes.size() != 0, ERR_UNAVAILABLE, "Can't unwrap mesh with blend shapes.");
  811. LocalVector<float> vertices;
  812. LocalVector<float> normals;
  813. LocalVector<int> indices;
  814. LocalVector<float> uv;
  815. LocalVector<Pair<int, int>> uv_indices;
  816. Vector<EditorSceneFormatImporterMeshLightmapSurface> lightmap_surfaces;
  817. // Keep only the scale
  818. Basis basis = p_base_transform.get_basis();
  819. Vector3 scale = Vector3(basis.get_column(0).length(), basis.get_column(1).length(), basis.get_column(2).length());
  820. Transform3D transform;
  821. transform.scale(scale);
  822. Basis normal_basis = transform.basis.inverse().transposed();
  823. for (int i = 0; i < get_surface_count(); i++) {
  824. EditorSceneFormatImporterMeshLightmapSurface s;
  825. s.primitive = get_surface_primitive_type(i);
  826. ERR_FAIL_COND_V_MSG(s.primitive != Mesh::PRIMITIVE_TRIANGLES, ERR_UNAVAILABLE, "Only triangles are supported for lightmap unwrap.");
  827. Array arrays = get_surface_arrays(i);
  828. s.material = get_surface_material(i);
  829. s.name = get_surface_name(i);
  830. SurfaceTool::create_vertex_array_from_arrays(arrays, s.vertices, &s.format);
  831. PackedVector3Array rvertices = arrays[Mesh::ARRAY_VERTEX];
  832. int vc = rvertices.size();
  833. PackedVector3Array rnormals = arrays[Mesh::ARRAY_NORMAL];
  834. if (!rnormals.size()) {
  835. continue;
  836. }
  837. int vertex_ofs = vertices.size() / 3;
  838. vertices.resize((vertex_ofs + vc) * 3);
  839. normals.resize((vertex_ofs + vc) * 3);
  840. uv_indices.resize(vertex_ofs + vc);
  841. for (int j = 0; j < vc; j++) {
  842. Vector3 v = transform.xform(rvertices[j]);
  843. Vector3 n = normal_basis.xform(rnormals[j]).normalized();
  844. vertices[(j + vertex_ofs) * 3 + 0] = v.x;
  845. vertices[(j + vertex_ofs) * 3 + 1] = v.y;
  846. vertices[(j + vertex_ofs) * 3 + 2] = v.z;
  847. normals[(j + vertex_ofs) * 3 + 0] = n.x;
  848. normals[(j + vertex_ofs) * 3 + 1] = n.y;
  849. normals[(j + vertex_ofs) * 3 + 2] = n.z;
  850. uv_indices[j + vertex_ofs] = Pair<int, int>(i, j);
  851. }
  852. PackedInt32Array rindices = arrays[Mesh::ARRAY_INDEX];
  853. int ic = rindices.size();
  854. float eps = 1.19209290e-7F; // Taken from xatlas.h
  855. if (ic == 0) {
  856. for (int j = 0; j < vc / 3; j++) {
  857. Vector3 p0 = transform.xform(rvertices[j * 3 + 0]);
  858. Vector3 p1 = transform.xform(rvertices[j * 3 + 1]);
  859. Vector3 p2 = transform.xform(rvertices[j * 3 + 2]);
  860. if ((p0 - p1).length_squared() < eps || (p1 - p2).length_squared() < eps || (p2 - p0).length_squared() < eps) {
  861. continue;
  862. }
  863. indices.push_back(vertex_ofs + j * 3 + 0);
  864. indices.push_back(vertex_ofs + j * 3 + 1);
  865. indices.push_back(vertex_ofs + j * 3 + 2);
  866. }
  867. } else {
  868. for (int j = 0; j < ic / 3; j++) {
  869. ERR_FAIL_INDEX_V(rindices[j * 3 + 0], rvertices.size(), ERR_INVALID_DATA);
  870. ERR_FAIL_INDEX_V(rindices[j * 3 + 1], rvertices.size(), ERR_INVALID_DATA);
  871. ERR_FAIL_INDEX_V(rindices[j * 3 + 2], rvertices.size(), ERR_INVALID_DATA);
  872. Vector3 p0 = transform.xform(rvertices[rindices[j * 3 + 0]]);
  873. Vector3 p1 = transform.xform(rvertices[rindices[j * 3 + 1]]);
  874. Vector3 p2 = transform.xform(rvertices[rindices[j * 3 + 2]]);
  875. if ((p0 - p1).length_squared() < eps || (p1 - p2).length_squared() < eps || (p2 - p0).length_squared() < eps) {
  876. continue;
  877. }
  878. indices.push_back(vertex_ofs + rindices[j * 3 + 0]);
  879. indices.push_back(vertex_ofs + rindices[j * 3 + 1]);
  880. indices.push_back(vertex_ofs + rindices[j * 3 + 2]);
  881. }
  882. }
  883. lightmap_surfaces.push_back(s);
  884. }
  885. //unwrap
  886. bool use_cache = true; // Used to request cache generation and to know if cache was used
  887. uint8_t *gen_cache;
  888. int gen_cache_size;
  889. float *gen_uvs;
  890. int *gen_vertices;
  891. int *gen_indices;
  892. int gen_vertex_count;
  893. int gen_index_count;
  894. int size_x;
  895. int size_y;
  896. 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);
  897. if (!ok) {
  898. return ERR_CANT_CREATE;
  899. }
  900. //create surfacetools for each surface..
  901. LocalVector<Ref<SurfaceTool>> surfaces_tools;
  902. for (int i = 0; i < lightmap_surfaces.size(); i++) {
  903. Ref<SurfaceTool> st;
  904. st.instantiate();
  905. st->set_skin_weight_count((lightmap_surfaces[i].format & Mesh::ARRAY_FLAG_USE_8_BONE_WEIGHTS) ? SurfaceTool::SKIN_8_WEIGHTS : SurfaceTool::SKIN_4_WEIGHTS);
  906. st->begin(Mesh::PRIMITIVE_TRIANGLES);
  907. st->set_material(lightmap_surfaces[i].material);
  908. st->set_meta("name", lightmap_surfaces[i].name);
  909. for (int custom_i = 0; custom_i < RS::ARRAY_CUSTOM_COUNT; custom_i++) {
  910. st->set_custom_format(custom_i, (SurfaceTool::CustomFormat)((lightmap_surfaces[i].format >> custom_shift[custom_i]) & RS::ARRAY_FORMAT_CUSTOM_MASK));
  911. }
  912. surfaces_tools.push_back(st); //stay there
  913. }
  914. //remove surfaces
  915. clear();
  916. print_verbose("Mesh: Gen indices: " + itos(gen_index_count));
  917. //go through all indices
  918. for (int i = 0; i < gen_index_count; i += 3) {
  919. ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 0]], (int)uv_indices.size(), ERR_BUG);
  920. ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 1]], (int)uv_indices.size(), ERR_BUG);
  921. ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 2]], (int)uv_indices.size(), ERR_BUG);
  922. 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);
  923. int surface = uv_indices[gen_vertices[gen_indices[i + 0]]].first;
  924. for (int j = 0; j < 3; j++) {
  925. SurfaceTool::Vertex v = lightmap_surfaces[surface].vertices[uv_indices[gen_vertices[gen_indices[i + j]]].second];
  926. if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_COLOR) {
  927. surfaces_tools[surface]->set_color(v.color);
  928. }
  929. if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_TEX_UV) {
  930. surfaces_tools[surface]->set_uv(v.uv);
  931. }
  932. if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_NORMAL) {
  933. surfaces_tools[surface]->set_normal(v.normal);
  934. }
  935. if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_TANGENT) {
  936. Plane t;
  937. t.normal = v.tangent;
  938. t.d = v.binormal.dot(v.normal.cross(v.tangent)) < 0 ? -1 : 1;
  939. surfaces_tools[surface]->set_tangent(t);
  940. }
  941. if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_BONES) {
  942. surfaces_tools[surface]->set_bones(v.bones);
  943. }
  944. if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_WEIGHTS) {
  945. surfaces_tools[surface]->set_weights(v.weights);
  946. }
  947. for (int custom_i = 0; custom_i < RS::ARRAY_CUSTOM_COUNT; custom_i++) {
  948. if ((lightmap_surfaces[surface].format >> custom_shift[custom_i]) & RS::ARRAY_FORMAT_CUSTOM_MASK) {
  949. surfaces_tools[surface]->set_custom(custom_i, v.custom[custom_i]);
  950. }
  951. }
  952. Vector2 uv2(gen_uvs[gen_indices[i + j] * 2 + 0], gen_uvs[gen_indices[i + j] * 2 + 1]);
  953. surfaces_tools[surface]->set_uv2(uv2);
  954. surfaces_tools[surface]->add_vertex(v.vertex);
  955. }
  956. }
  957. //generate surfaces
  958. for (int i = 0; i < lightmap_surfaces.size(); i++) {
  959. Ref<SurfaceTool> &tool = surfaces_tools[i];
  960. tool->index();
  961. Array arrays = tool->commit_to_arrays();
  962. uint64_t format = lightmap_surfaces[i].format;
  963. if (tool->get_skin_weight_count() == SurfaceTool::SKIN_8_WEIGHTS) {
  964. format |= RS::ARRAY_FLAG_USE_8_BONE_WEIGHTS;
  965. } else {
  966. format &= ~RS::ARRAY_FLAG_USE_8_BONE_WEIGHTS;
  967. }
  968. add_surface(tool->get_primitive_type(), arrays, Array(), Dictionary(), tool->get_material(), tool->get_meta("name"), format);
  969. }
  970. set_lightmap_size_hint(Size2(size_x, size_y));
  971. if (gen_cache_size > 0) {
  972. r_dst_cache.resize(gen_cache_size);
  973. memcpy(r_dst_cache.ptrw(), gen_cache, gen_cache_size);
  974. memfree(gen_cache);
  975. }
  976. if (!use_cache) {
  977. // Cache was not used, free the buffers
  978. memfree(gen_vertices);
  979. memfree(gen_indices);
  980. memfree(gen_uvs);
  981. }
  982. return OK;
  983. }
  984. void ImporterMesh::set_lightmap_size_hint(const Size2i &p_size) {
  985. lightmap_size_hint = p_size;
  986. }
  987. Size2i ImporterMesh::get_lightmap_size_hint() const {
  988. return lightmap_size_hint;
  989. }
  990. void ImporterMesh::_bind_methods() {
  991. ClassDB::bind_method(D_METHOD("add_blend_shape", "name"), &ImporterMesh::add_blend_shape);
  992. ClassDB::bind_method(D_METHOD("get_blend_shape_count"), &ImporterMesh::get_blend_shape_count);
  993. ClassDB::bind_method(D_METHOD("get_blend_shape_name", "blend_shape_idx"), &ImporterMesh::get_blend_shape_name);
  994. ClassDB::bind_method(D_METHOD("set_blend_shape_mode", "mode"), &ImporterMesh::set_blend_shape_mode);
  995. ClassDB::bind_method(D_METHOD("get_blend_shape_mode"), &ImporterMesh::get_blend_shape_mode);
  996. 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));
  997. ClassDB::bind_method(D_METHOD("get_surface_count"), &ImporterMesh::get_surface_count);
  998. ClassDB::bind_method(D_METHOD("get_surface_primitive_type", "surface_idx"), &ImporterMesh::get_surface_primitive_type);
  999. ClassDB::bind_method(D_METHOD("get_surface_name", "surface_idx"), &ImporterMesh::get_surface_name);
  1000. ClassDB::bind_method(D_METHOD("get_surface_arrays", "surface_idx"), &ImporterMesh::get_surface_arrays);
  1001. ClassDB::bind_method(D_METHOD("get_surface_blend_shape_arrays", "surface_idx", "blend_shape_idx"), &ImporterMesh::get_surface_blend_shape_arrays);
  1002. ClassDB::bind_method(D_METHOD("get_surface_lod_count", "surface_idx"), &ImporterMesh::get_surface_lod_count);
  1003. ClassDB::bind_method(D_METHOD("get_surface_lod_size", "surface_idx", "lod_idx"), &ImporterMesh::get_surface_lod_size);
  1004. ClassDB::bind_method(D_METHOD("get_surface_lod_indices", "surface_idx", "lod_idx"), &ImporterMesh::get_surface_lod_indices);
  1005. ClassDB::bind_method(D_METHOD("get_surface_material", "surface_idx"), &ImporterMesh::get_surface_material);
  1006. ClassDB::bind_method(D_METHOD("get_surface_format", "surface_idx"), &ImporterMesh::get_surface_format);
  1007. ClassDB::bind_method(D_METHOD("set_surface_name", "surface_idx", "name"), &ImporterMesh::set_surface_name);
  1008. ClassDB::bind_method(D_METHOD("set_surface_material", "surface_idx", "material"), &ImporterMesh::set_surface_material);
  1009. ClassDB::bind_method(D_METHOD("generate_lods", "normal_merge_angle", "normal_split_angle", "bone_transform_array"), &ImporterMesh::_generate_lods_bind);
  1010. ClassDB::bind_method(D_METHOD("get_mesh", "base_mesh"), &ImporterMesh::get_mesh, DEFVAL(Ref<ArrayMesh>()));
  1011. ClassDB::bind_method(D_METHOD("clear"), &ImporterMesh::clear);
  1012. ClassDB::bind_method(D_METHOD("_set_data", "data"), &ImporterMesh::_set_data);
  1013. ClassDB::bind_method(D_METHOD("_get_data"), &ImporterMesh::_get_data);
  1014. ClassDB::bind_method(D_METHOD("set_lightmap_size_hint", "size"), &ImporterMesh::set_lightmap_size_hint);
  1015. ClassDB::bind_method(D_METHOD("get_lightmap_size_hint"), &ImporterMesh::get_lightmap_size_hint);
  1016. ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_data", "_get_data");
  1017. }