importer_mesh.cpp 47 KB

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