scene_importer_mesh.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  1. /*************************************************************************/
  2. /* scene_importer_mesh.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  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 "scene_importer_mesh.h"
  31. #include "core/math/math_defs.h"
  32. #include "scene/resources/surface_tool.h"
  33. void EditorSceneImporterMesh::add_blend_shape(const String &p_name) {
  34. ERR_FAIL_COND(surfaces.size() > 0);
  35. blend_shapes.push_back(p_name);
  36. }
  37. int EditorSceneImporterMesh::get_blend_shape_count() const {
  38. return blend_shapes.size();
  39. }
  40. String EditorSceneImporterMesh::get_blend_shape_name(int p_blend_shape) const {
  41. ERR_FAIL_INDEX_V(p_blend_shape, blend_shapes.size(), String());
  42. return blend_shapes[p_blend_shape];
  43. }
  44. void EditorSceneImporterMesh::set_blend_shape_mode(Mesh::BlendShapeMode p_blend_shape_mode) {
  45. blend_shape_mode = p_blend_shape_mode;
  46. }
  47. Mesh::BlendShapeMode EditorSceneImporterMesh::get_blend_shape_mode() const {
  48. return blend_shape_mode;
  49. }
  50. void EditorSceneImporterMesh::add_surface(Mesh::PrimitiveType p_primitive, const Array &p_arrays, const Array &p_blend_shapes, const Dictionary &p_lods, const Ref<Material> &p_material, const String &p_name) {
  51. ERR_FAIL_COND(p_blend_shapes.size() != blend_shapes.size());
  52. ERR_FAIL_COND(p_arrays.size() != Mesh::ARRAY_MAX);
  53. Surface s;
  54. s.primitive = p_primitive;
  55. s.arrays = p_arrays;
  56. s.name = p_name;
  57. Vector<Vector3> vertex_array = p_arrays[Mesh::ARRAY_VERTEX];
  58. int vertex_count = vertex_array.size();
  59. ERR_FAIL_COND(vertex_count == 0);
  60. for (int i = 0; i < blend_shapes.size(); i++) {
  61. Array bsdata = p_blend_shapes[i];
  62. ERR_FAIL_COND(bsdata.size() != Mesh::ARRAY_MAX);
  63. Vector<Vector3> vertex_data = bsdata[Mesh::ARRAY_VERTEX];
  64. ERR_FAIL_COND(vertex_data.size() != vertex_count);
  65. Surface::BlendShape bs;
  66. bs.arrays = bsdata;
  67. s.blend_shape_data.push_back(bs);
  68. }
  69. List<Variant> lods;
  70. p_lods.get_key_list(&lods);
  71. for (const Variant &E : lods) {
  72. ERR_CONTINUE(!E.is_num());
  73. Surface::LOD lod;
  74. lod.distance = E;
  75. lod.indices = p_lods[E];
  76. ERR_CONTINUE(lod.indices.size() == 0);
  77. s.lods.push_back(lod);
  78. }
  79. s.material = p_material;
  80. surfaces.push_back(s);
  81. mesh.unref();
  82. }
  83. int EditorSceneImporterMesh::get_surface_count() const {
  84. return surfaces.size();
  85. }
  86. Mesh::PrimitiveType EditorSceneImporterMesh::get_surface_primitive_type(int p_surface) {
  87. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Mesh::PRIMITIVE_MAX);
  88. return surfaces[p_surface].primitive;
  89. }
  90. Array EditorSceneImporterMesh::get_surface_arrays(int p_surface) const {
  91. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array());
  92. return surfaces[p_surface].arrays;
  93. }
  94. String EditorSceneImporterMesh::get_surface_name(int p_surface) const {
  95. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), String());
  96. return surfaces[p_surface].name;
  97. }
  98. Array EditorSceneImporterMesh::get_surface_blend_shape_arrays(int p_surface, int p_blend_shape) const {
  99. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array());
  100. ERR_FAIL_INDEX_V(p_blend_shape, surfaces[p_surface].blend_shape_data.size(), Array());
  101. return surfaces[p_surface].blend_shape_data[p_blend_shape].arrays;
  102. }
  103. int EditorSceneImporterMesh::get_surface_lod_count(int p_surface) const {
  104. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), 0);
  105. return surfaces[p_surface].lods.size();
  106. }
  107. Vector<int> EditorSceneImporterMesh::get_surface_lod_indices(int p_surface, int p_lod) const {
  108. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Vector<int>());
  109. ERR_FAIL_INDEX_V(p_lod, surfaces[p_surface].lods.size(), Vector<int>());
  110. return surfaces[p_surface].lods[p_lod].indices;
  111. }
  112. float EditorSceneImporterMesh::get_surface_lod_size(int p_surface, int p_lod) const {
  113. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), 0);
  114. ERR_FAIL_INDEX_V(p_lod, surfaces[p_surface].lods.size(), 0);
  115. return surfaces[p_surface].lods[p_lod].distance;
  116. }
  117. Ref<Material> EditorSceneImporterMesh::get_surface_material(int p_surface) const {
  118. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Ref<Material>());
  119. return surfaces[p_surface].material;
  120. }
  121. void EditorSceneImporterMesh::set_surface_material(int p_surface, const Ref<Material> &p_material) {
  122. ERR_FAIL_INDEX(p_surface, surfaces.size());
  123. surfaces.write[p_surface].material = p_material;
  124. }
  125. Basis EditorSceneImporterMesh::compute_rotation_matrix_from_ortho_6d(Vector3 p_x_raw, Vector3 p_y_raw) {
  126. Vector3 x = p_x_raw.normalized();
  127. Vector3 z = x.cross(p_y_raw);
  128. z = z.normalized();
  129. Vector3 y = z.cross(x);
  130. Basis basis;
  131. basis.set_axis(Vector3::AXIS_X, x);
  132. basis.set_axis(Vector3::AXIS_Y, y);
  133. basis.set_axis(Vector3::AXIS_Z, z);
  134. return basis;
  135. }
  136. void EditorSceneImporterMesh::generate_lods() {
  137. if (!SurfaceTool::simplify_func) {
  138. return;
  139. }
  140. if (!SurfaceTool::simplify_scale_func) {
  141. return;
  142. }
  143. if (!SurfaceTool::simplify_sloppy_func) {
  144. return;
  145. }
  146. if (!SurfaceTool::simplify_with_attrib_func) {
  147. return;
  148. }
  149. for (int i = 0; i < surfaces.size(); i++) {
  150. if (surfaces[i].primitive != Mesh::PRIMITIVE_TRIANGLES) {
  151. continue;
  152. }
  153. surfaces.write[i].lods.clear();
  154. Vector<Vector3> vertices = surfaces[i].arrays[RS::ARRAY_VERTEX];
  155. Vector<int> indices = surfaces[i].arrays[RS::ARRAY_INDEX];
  156. if (indices.size() == 0) {
  157. continue; //no lods if no indices
  158. }
  159. Vector<Vector3> normals = surfaces[i].arrays[RS::ARRAY_NORMAL];
  160. uint32_t vertex_count = vertices.size();
  161. const Vector3 *vertices_ptr = vertices.ptr();
  162. Vector<float> attributes;
  163. Vector<float> normal_weights;
  164. int32_t attribute_count = 6;
  165. if (normals.size()) {
  166. attributes.resize(normals.size() * attribute_count);
  167. for (int32_t normal_i = 0; normal_i < normals.size(); normal_i++) {
  168. Basis basis;
  169. basis.set_euler(normals[normal_i]);
  170. Vector3 basis_x = basis.get_axis(0);
  171. Vector3 basis_y = basis.get_axis(1);
  172. basis = compute_rotation_matrix_from_ortho_6d(basis_x, basis_y);
  173. basis_x = basis.get_axis(0);
  174. basis_y = basis.get_axis(1);
  175. attributes.write[normal_i * attribute_count + 0] = basis_x.x;
  176. attributes.write[normal_i * attribute_count + 1] = basis_x.y;
  177. attributes.write[normal_i * attribute_count + 2] = basis_x.z;
  178. attributes.write[normal_i * attribute_count + 3] = basis_y.x;
  179. attributes.write[normal_i * attribute_count + 4] = basis_y.y;
  180. attributes.write[normal_i * attribute_count + 5] = basis_y.z;
  181. }
  182. normal_weights.resize(vertex_count);
  183. for (int32_t weight_i = 0; weight_i < normal_weights.size(); weight_i++) {
  184. normal_weights.write[weight_i] = 1.0;
  185. }
  186. } else {
  187. attribute_count = 0;
  188. }
  189. const int min_indices = 10;
  190. const float error_tolerance = 1.44224'95703; // Cube root of 3
  191. const float threshold = 1.0 / error_tolerance;
  192. int index_target = indices.size() * threshold;
  193. float max_mesh_error_percentage = 1e0f;
  194. float mesh_error = 0.0f;
  195. float scale = SurfaceTool::simplify_scale_func((const float *)vertices_ptr, vertex_count, sizeof(Vector3));
  196. while (index_target > min_indices) {
  197. Vector<int> new_indices;
  198. new_indices.resize(indices.size());
  199. size_t new_len = SurfaceTool::simplify_with_attrib_func((unsigned int *)new_indices.ptrw(), (const unsigned int *)indices.ptr(), indices.size(), (const float *)vertices_ptr, vertex_count, sizeof(Vector3), index_target, max_mesh_error_percentage, &mesh_error, (float *)attributes.ptrw(), normal_weights.ptrw(), attribute_count);
  200. if ((int)new_len > (index_target * error_tolerance)) {
  201. break;
  202. }
  203. Surface::LOD lod;
  204. lod.distance = mesh_error * scale;
  205. if (Math::is_zero_approx(mesh_error)) {
  206. break;
  207. }
  208. if (new_len <= 0) {
  209. break;
  210. }
  211. new_indices.resize(new_len);
  212. lod.indices = new_indices;
  213. print_line("Lod " + itos(surfaces.write[i].lods.size()) + " begin with " + itos(indices.size() / 3) + " triangles and shoot for " + itos(index_target / 3) + " triangles. Got " + itos(new_len / 3) + " triangles. Lod screen ratio " + rtos(lod.distance));
  214. surfaces.write[i].lods.push_back(lod);
  215. index_target *= threshold;
  216. }
  217. }
  218. }
  219. bool EditorSceneImporterMesh::has_mesh() const {
  220. return mesh.is_valid();
  221. }
  222. Ref<ArrayMesh> EditorSceneImporterMesh::get_mesh(const Ref<Mesh> &p_base) {
  223. ERR_FAIL_COND_V(surfaces.size() == 0, Ref<ArrayMesh>());
  224. if (mesh.is_null()) {
  225. if (p_base.is_valid()) {
  226. mesh = p_base;
  227. }
  228. if (mesh.is_null()) {
  229. mesh.instantiate();
  230. }
  231. mesh->set_name(get_name());
  232. if (has_meta("import_id")) {
  233. mesh->set_meta("import_id", get_meta("import_id"));
  234. }
  235. for (int i = 0; i < blend_shapes.size(); i++) {
  236. mesh->add_blend_shape(blend_shapes[i]);
  237. }
  238. mesh->set_blend_shape_mode(blend_shape_mode);
  239. for (int i = 0; i < surfaces.size(); i++) {
  240. Array bs_data;
  241. if (surfaces[i].blend_shape_data.size()) {
  242. for (int j = 0; j < surfaces[i].blend_shape_data.size(); j++) {
  243. bs_data.push_back(surfaces[i].blend_shape_data[j].arrays);
  244. }
  245. }
  246. Dictionary lods;
  247. if (surfaces[i].lods.size()) {
  248. for (int j = 0; j < surfaces[i].lods.size(); j++) {
  249. lods[surfaces[i].lods[j].distance] = surfaces[i].lods[j].indices;
  250. }
  251. }
  252. mesh->add_surface_from_arrays(surfaces[i].primitive, surfaces[i].arrays, bs_data, lods);
  253. if (surfaces[i].material.is_valid()) {
  254. mesh->surface_set_material(mesh->get_surface_count() - 1, surfaces[i].material);
  255. }
  256. if (surfaces[i].name != String()) {
  257. mesh->surface_set_name(mesh->get_surface_count() - 1, surfaces[i].name);
  258. }
  259. }
  260. mesh->set_lightmap_size_hint(lightmap_size_hint);
  261. if (shadow_mesh.is_valid()) {
  262. Ref<ArrayMesh> shadow = shadow_mesh->get_mesh();
  263. mesh->set_shadow_mesh(shadow);
  264. }
  265. }
  266. return mesh;
  267. }
  268. void EditorSceneImporterMesh::clear() {
  269. surfaces.clear();
  270. blend_shapes.clear();
  271. mesh.unref();
  272. }
  273. void EditorSceneImporterMesh::create_shadow_mesh() {
  274. if (shadow_mesh.is_valid()) {
  275. shadow_mesh.unref();
  276. }
  277. //no shadow mesh for blendshapes
  278. if (blend_shapes.size() > 0) {
  279. return;
  280. }
  281. //no shadow mesh for skeletons
  282. for (int i = 0; i < surfaces.size(); i++) {
  283. if (surfaces[i].arrays[RS::ARRAY_BONES].get_type() != Variant::NIL) {
  284. return;
  285. }
  286. if (surfaces[i].arrays[RS::ARRAY_WEIGHTS].get_type() != Variant::NIL) {
  287. return;
  288. }
  289. }
  290. shadow_mesh.instantiate();
  291. for (int i = 0; i < surfaces.size(); i++) {
  292. LocalVector<int> vertex_remap;
  293. Vector<Vector3> new_vertices;
  294. Vector<Vector3> vertices = surfaces[i].arrays[RS::ARRAY_VERTEX];
  295. int vertex_count = vertices.size();
  296. {
  297. Map<Vector3, int> unique_vertices;
  298. const Vector3 *vptr = vertices.ptr();
  299. for (int j = 0; j < vertex_count; j++) {
  300. Vector3 v = vptr[j];
  301. Map<Vector3, int>::Element *E = unique_vertices.find(v);
  302. if (E) {
  303. vertex_remap.push_back(E->get());
  304. } else {
  305. int vcount = unique_vertices.size();
  306. unique_vertices[v] = vcount;
  307. vertex_remap.push_back(vcount);
  308. new_vertices.push_back(v);
  309. }
  310. }
  311. }
  312. Array new_surface;
  313. new_surface.resize(RS::ARRAY_MAX);
  314. Dictionary lods;
  315. // print_line("original vertex count: " + itos(vertices.size()) + " new vertex count: " + itos(new_vertices.size()));
  316. new_surface[RS::ARRAY_VERTEX] = new_vertices;
  317. Vector<int> indices = surfaces[i].arrays[RS::ARRAY_INDEX];
  318. if (indices.size()) {
  319. int index_count = indices.size();
  320. const int *index_rptr = indices.ptr();
  321. Vector<int> new_indices;
  322. new_indices.resize(indices.size());
  323. int *index_wptr = new_indices.ptrw();
  324. for (int j = 0; j < index_count; j++) {
  325. int index = index_rptr[j];
  326. ERR_FAIL_INDEX(index, vertex_count);
  327. index_wptr[j] = vertex_remap[index];
  328. }
  329. new_surface[RS::ARRAY_INDEX] = new_indices;
  330. // Make sure the same LODs as the full version are used.
  331. // This makes it more coherent between rendered model and its shadows.
  332. for (int j = 0; j < surfaces[i].lods.size(); j++) {
  333. indices = surfaces[i].lods[j].indices;
  334. index_count = indices.size();
  335. index_rptr = indices.ptr();
  336. new_indices.resize(indices.size());
  337. index_wptr = new_indices.ptrw();
  338. for (int k = 0; k < index_count; k++) {
  339. int index = index_rptr[j];
  340. ERR_FAIL_INDEX(index, vertex_count);
  341. index_wptr[j] = vertex_remap[index];
  342. }
  343. lods[surfaces[i].lods[j].distance] = new_indices;
  344. }
  345. }
  346. shadow_mesh->add_surface(surfaces[i].primitive, new_surface, Array(), lods, Ref<Material>(), surfaces[i].name);
  347. }
  348. }
  349. Ref<EditorSceneImporterMesh> EditorSceneImporterMesh::get_shadow_mesh() const {
  350. return shadow_mesh;
  351. }
  352. void EditorSceneImporterMesh::_set_data(const Dictionary &p_data) {
  353. clear();
  354. if (p_data.has("blend_shape_names")) {
  355. blend_shapes = p_data["blend_shape_names"];
  356. }
  357. if (p_data.has("surfaces")) {
  358. Array surface_arr = p_data["surfaces"];
  359. for (int i = 0; i < surface_arr.size(); i++) {
  360. Dictionary s = surface_arr[i];
  361. ERR_CONTINUE(!s.has("primitive"));
  362. ERR_CONTINUE(!s.has("arrays"));
  363. Mesh::PrimitiveType prim = Mesh::PrimitiveType(int(s["primitive"]));
  364. ERR_CONTINUE(prim >= Mesh::PRIMITIVE_MAX);
  365. Array arr = s["arrays"];
  366. Dictionary lods;
  367. String name;
  368. if (s.has("name")) {
  369. name = s["name"];
  370. }
  371. if (s.has("lods")) {
  372. lods = s["lods"];
  373. }
  374. Array blend_shapes;
  375. if (s.has("blend_shapes")) {
  376. blend_shapes = s["blend_shapes"];
  377. }
  378. Ref<Material> material;
  379. if (s.has("material")) {
  380. material = s["material"];
  381. }
  382. add_surface(prim, arr, blend_shapes, lods, material, name);
  383. }
  384. }
  385. }
  386. Dictionary EditorSceneImporterMesh::_get_data() const {
  387. Dictionary data;
  388. if (blend_shapes.size()) {
  389. data["blend_shape_names"] = blend_shapes;
  390. }
  391. Array surface_arr;
  392. for (int i = 0; i < surfaces.size(); i++) {
  393. Dictionary d;
  394. d["primitive"] = surfaces[i].primitive;
  395. d["arrays"] = surfaces[i].arrays;
  396. if (surfaces[i].blend_shape_data.size()) {
  397. Array bs_data;
  398. for (int j = 0; j < surfaces[i].blend_shape_data.size(); j++) {
  399. bs_data.push_back(surfaces[i].blend_shape_data[j].arrays);
  400. }
  401. d["blend_shapes"] = bs_data;
  402. }
  403. if (surfaces[i].lods.size()) {
  404. Dictionary lods;
  405. for (int j = 0; j < surfaces[i].lods.size(); j++) {
  406. lods[surfaces[i].lods[j].distance] = surfaces[i].lods[j].indices;
  407. }
  408. d["lods"] = lods;
  409. }
  410. if (surfaces[i].material.is_valid()) {
  411. d["material"] = surfaces[i].material;
  412. }
  413. if (surfaces[i].name != String()) {
  414. d["name"] = surfaces[i].name;
  415. }
  416. surface_arr.push_back(d);
  417. }
  418. data["surfaces"] = surface_arr;
  419. return data;
  420. }
  421. Vector<Face3> EditorSceneImporterMesh::get_faces() const {
  422. Vector<Face3> faces;
  423. for (int i = 0; i < surfaces.size(); i++) {
  424. if (surfaces[i].primitive == Mesh::PRIMITIVE_TRIANGLES) {
  425. Vector<Vector3> vertices = surfaces[i].arrays[Mesh::ARRAY_VERTEX];
  426. Vector<int> indices = surfaces[i].arrays[Mesh::ARRAY_INDEX];
  427. if (indices.size()) {
  428. for (int j = 0; j < indices.size(); j += 3) {
  429. Face3 f;
  430. f.vertex[0] = vertices[indices[j + 0]];
  431. f.vertex[1] = vertices[indices[j + 1]];
  432. f.vertex[2] = vertices[indices[j + 2]];
  433. faces.push_back(f);
  434. }
  435. } else {
  436. for (int j = 0; j < vertices.size(); j += 3) {
  437. Face3 f;
  438. f.vertex[0] = vertices[j + 0];
  439. f.vertex[1] = vertices[j + 1];
  440. f.vertex[2] = vertices[j + 2];
  441. faces.push_back(f);
  442. }
  443. }
  444. }
  445. }
  446. return faces;
  447. }
  448. Vector<Ref<Shape3D>> EditorSceneImporterMesh::convex_decompose() const {
  449. ERR_FAIL_COND_V(!Mesh::convex_composition_function, Vector<Ref<Shape3D>>());
  450. const Vector<Face3> faces = get_faces();
  451. Vector<Vector<Face3>> decomposed = Mesh::convex_composition_function(faces, -1);
  452. Vector<Ref<Shape3D>> ret;
  453. for (int i = 0; i < decomposed.size(); i++) {
  454. Set<Vector3> points;
  455. for (int j = 0; j < decomposed[i].size(); j++) {
  456. points.insert(decomposed[i][j].vertex[0]);
  457. points.insert(decomposed[i][j].vertex[1]);
  458. points.insert(decomposed[i][j].vertex[2]);
  459. }
  460. Vector<Vector3> convex_points;
  461. convex_points.resize(points.size());
  462. {
  463. Vector3 *w = convex_points.ptrw();
  464. int idx = 0;
  465. for (Set<Vector3>::Element *E = points.front(); E; E = E->next()) {
  466. w[idx++] = E->get();
  467. }
  468. }
  469. Ref<ConvexPolygonShape3D> shape;
  470. shape.instantiate();
  471. shape->set_points(convex_points);
  472. ret.push_back(shape);
  473. }
  474. return ret;
  475. }
  476. Ref<Shape3D> EditorSceneImporterMesh::create_trimesh_shape() const {
  477. Vector<Face3> faces = get_faces();
  478. if (faces.size() == 0) {
  479. return Ref<Shape3D>();
  480. }
  481. Vector<Vector3> face_points;
  482. face_points.resize(faces.size() * 3);
  483. for (int i = 0; i < face_points.size(); i += 3) {
  484. Face3 f = faces.get(i / 3);
  485. face_points.set(i, f.vertex[0]);
  486. face_points.set(i + 1, f.vertex[1]);
  487. face_points.set(i + 2, f.vertex[2]);
  488. }
  489. Ref<ConcavePolygonShape3D> shape = memnew(ConcavePolygonShape3D);
  490. shape->set_faces(face_points);
  491. return shape;
  492. }
  493. Ref<NavigationMesh> EditorSceneImporterMesh::create_navigation_mesh() {
  494. Vector<Face3> faces = get_faces();
  495. if (faces.size() == 0) {
  496. return Ref<NavigationMesh>();
  497. }
  498. Map<Vector3, int> unique_vertices;
  499. LocalVector<int> face_indices;
  500. for (int i = 0; i < faces.size(); i++) {
  501. for (int j = 0; j < 3; j++) {
  502. Vector3 v = faces[i].vertex[j];
  503. int idx;
  504. if (unique_vertices.has(v)) {
  505. idx = unique_vertices[v];
  506. } else {
  507. idx = unique_vertices.size();
  508. unique_vertices[v] = idx;
  509. }
  510. face_indices.push_back(idx);
  511. }
  512. }
  513. Vector<Vector3> vertices;
  514. vertices.resize(unique_vertices.size());
  515. for (Map<Vector3, int>::Element *E = unique_vertices.front(); E; E = E->next()) {
  516. vertices.write[E->get()] = E->key();
  517. }
  518. Ref<NavigationMesh> nm;
  519. nm.instantiate();
  520. nm->set_vertices(vertices);
  521. Vector<int> v3;
  522. v3.resize(3);
  523. for (uint32_t i = 0; i < face_indices.size(); i += 3) {
  524. v3.write[0] = face_indices[i + 0];
  525. v3.write[1] = face_indices[i + 1];
  526. v3.write[2] = face_indices[i + 2];
  527. nm->add_polygon(v3);
  528. }
  529. return nm;
  530. }
  531. 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);
  532. struct EditorSceneImporterMeshLightmapSurface {
  533. Ref<Material> material;
  534. LocalVector<SurfaceTool::Vertex> vertices;
  535. Mesh::PrimitiveType primitive = Mesh::PrimitiveType::PRIMITIVE_MAX;
  536. uint32_t format = 0;
  537. String name;
  538. };
  539. Error EditorSceneImporterMesh::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) {
  540. ERR_FAIL_COND_V(!array_mesh_lightmap_unwrap_callback, ERR_UNCONFIGURED);
  541. ERR_FAIL_COND_V_MSG(blend_shapes.size() != 0, ERR_UNAVAILABLE, "Can't unwrap mesh with blend shapes.");
  542. LocalVector<float> vertices;
  543. LocalVector<float> normals;
  544. LocalVector<int> indices;
  545. LocalVector<float> uv;
  546. LocalVector<Pair<int, int>> uv_indices;
  547. Vector<EditorSceneImporterMeshLightmapSurface> lightmap_surfaces;
  548. // Keep only the scale
  549. Basis basis = p_base_transform.get_basis();
  550. Vector3 scale = Vector3(basis.get_axis(0).length(), basis.get_axis(1).length(), basis.get_axis(2).length());
  551. Transform3D transform;
  552. transform.scale(scale);
  553. Basis normal_basis = transform.basis.inverse().transposed();
  554. for (int i = 0; i < get_surface_count(); i++) {
  555. EditorSceneImporterMeshLightmapSurface s;
  556. s.primitive = get_surface_primitive_type(i);
  557. ERR_FAIL_COND_V_MSG(s.primitive != Mesh::PRIMITIVE_TRIANGLES, ERR_UNAVAILABLE, "Only triangles are supported for lightmap unwrap.");
  558. Array arrays = get_surface_arrays(i);
  559. s.material = get_surface_material(i);
  560. s.name = get_surface_name(i);
  561. SurfaceTool::create_vertex_array_from_triangle_arrays(arrays, s.vertices, &s.format);
  562. PackedVector3Array rvertices = arrays[Mesh::ARRAY_VERTEX];
  563. int vc = rvertices.size();
  564. PackedVector3Array rnormals = arrays[Mesh::ARRAY_NORMAL];
  565. int vertex_ofs = vertices.size() / 3;
  566. vertices.resize((vertex_ofs + vc) * 3);
  567. normals.resize((vertex_ofs + vc) * 3);
  568. uv_indices.resize(vertex_ofs + vc);
  569. for (int j = 0; j < vc; j++) {
  570. Vector3 v = transform.xform(rvertices[j]);
  571. Vector3 n = normal_basis.xform(rnormals[j]).normalized();
  572. vertices[(j + vertex_ofs) * 3 + 0] = v.x;
  573. vertices[(j + vertex_ofs) * 3 + 1] = v.y;
  574. vertices[(j + vertex_ofs) * 3 + 2] = v.z;
  575. normals[(j + vertex_ofs) * 3 + 0] = n.x;
  576. normals[(j + vertex_ofs) * 3 + 1] = n.y;
  577. normals[(j + vertex_ofs) * 3 + 2] = n.z;
  578. uv_indices[j + vertex_ofs] = Pair<int, int>(i, j);
  579. }
  580. PackedInt32Array rindices = arrays[Mesh::ARRAY_INDEX];
  581. int ic = rindices.size();
  582. float eps = 1.19209290e-7F; // Taken from xatlas.h
  583. if (ic == 0) {
  584. for (int j = 0; j < vc / 3; j++) {
  585. Vector3 p0 = transform.xform(rvertices[j * 3 + 0]);
  586. Vector3 p1 = transform.xform(rvertices[j * 3 + 1]);
  587. Vector3 p2 = transform.xform(rvertices[j * 3 + 2]);
  588. if ((p0 - p1).length_squared() < eps || (p1 - p2).length_squared() < eps || (p2 - p0).length_squared() < eps) {
  589. continue;
  590. }
  591. indices.push_back(vertex_ofs + j * 3 + 0);
  592. indices.push_back(vertex_ofs + j * 3 + 1);
  593. indices.push_back(vertex_ofs + j * 3 + 2);
  594. }
  595. } else {
  596. for (int j = 0; j < ic / 3; j++) {
  597. Vector3 p0 = transform.xform(rvertices[rindices[j * 3 + 0]]);
  598. Vector3 p1 = transform.xform(rvertices[rindices[j * 3 + 1]]);
  599. Vector3 p2 = transform.xform(rvertices[rindices[j * 3 + 2]]);
  600. if ((p0 - p1).length_squared() < eps || (p1 - p2).length_squared() < eps || (p2 - p0).length_squared() < eps) {
  601. continue;
  602. }
  603. indices.push_back(vertex_ofs + rindices[j * 3 + 0]);
  604. indices.push_back(vertex_ofs + rindices[j * 3 + 1]);
  605. indices.push_back(vertex_ofs + rindices[j * 3 + 2]);
  606. }
  607. }
  608. lightmap_surfaces.push_back(s);
  609. }
  610. //unwrap
  611. bool use_cache = true; // Used to request cache generation and to know if cache was used
  612. uint8_t *gen_cache;
  613. int gen_cache_size;
  614. float *gen_uvs;
  615. int *gen_vertices;
  616. int *gen_indices;
  617. int gen_vertex_count;
  618. int gen_index_count;
  619. int size_x;
  620. int size_y;
  621. 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);
  622. if (!ok) {
  623. return ERR_CANT_CREATE;
  624. }
  625. //remove surfaces
  626. clear();
  627. //create surfacetools for each surface..
  628. LocalVector<Ref<SurfaceTool>> surfaces_tools;
  629. for (int i = 0; i < lightmap_surfaces.size(); i++) {
  630. Ref<SurfaceTool> st;
  631. st.instantiate();
  632. st->begin(Mesh::PRIMITIVE_TRIANGLES);
  633. st->set_material(lightmap_surfaces[i].material);
  634. st->set_meta("name", lightmap_surfaces[i].name);
  635. surfaces_tools.push_back(st); //stay there
  636. }
  637. print_verbose("Mesh: Gen indices: " + itos(gen_index_count));
  638. //go through all indices
  639. for (int i = 0; i < gen_index_count; i += 3) {
  640. ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 0]], (int)uv_indices.size(), ERR_BUG);
  641. ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 1]], (int)uv_indices.size(), ERR_BUG);
  642. ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 2]], (int)uv_indices.size(), ERR_BUG);
  643. 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);
  644. int surface = uv_indices[gen_vertices[gen_indices[i + 0]]].first;
  645. for (int j = 0; j < 3; j++) {
  646. SurfaceTool::Vertex v = lightmap_surfaces[surface].vertices[uv_indices[gen_vertices[gen_indices[i + j]]].second];
  647. if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_COLOR) {
  648. surfaces_tools[surface]->set_color(v.color);
  649. }
  650. if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_TEX_UV) {
  651. surfaces_tools[surface]->set_uv(v.uv);
  652. }
  653. if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_NORMAL) {
  654. surfaces_tools[surface]->set_normal(v.normal);
  655. }
  656. if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_TANGENT) {
  657. Plane t;
  658. t.normal = v.tangent;
  659. t.d = v.binormal.dot(v.normal.cross(v.tangent)) < 0 ? -1 : 1;
  660. surfaces_tools[surface]->set_tangent(t);
  661. }
  662. if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_BONES) {
  663. surfaces_tools[surface]->set_bones(v.bones);
  664. }
  665. if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_WEIGHTS) {
  666. surfaces_tools[surface]->set_weights(v.weights);
  667. }
  668. Vector2 uv2(gen_uvs[gen_indices[i + j] * 2 + 0], gen_uvs[gen_indices[i + j] * 2 + 1]);
  669. surfaces_tools[surface]->set_uv2(uv2);
  670. surfaces_tools[surface]->add_vertex(v.vertex);
  671. }
  672. }
  673. //generate surfaces
  674. for (unsigned int i = 0; i < surfaces_tools.size(); i++) {
  675. surfaces_tools[i]->index();
  676. Array arrays = surfaces_tools[i]->commit_to_arrays();
  677. add_surface(surfaces_tools[i]->get_primitive(), arrays, Array(), Dictionary(), surfaces_tools[i]->get_material(), surfaces_tools[i]->get_meta("name"));
  678. }
  679. set_lightmap_size_hint(Size2(size_x, size_y));
  680. if (gen_cache_size > 0) {
  681. r_dst_cache.resize(gen_cache_size);
  682. memcpy(r_dst_cache.ptrw(), gen_cache, gen_cache_size);
  683. memfree(gen_cache);
  684. }
  685. if (!use_cache) {
  686. // Cache was not used, free the buffers
  687. memfree(gen_vertices);
  688. memfree(gen_indices);
  689. memfree(gen_uvs);
  690. }
  691. return OK;
  692. }
  693. void EditorSceneImporterMesh::set_lightmap_size_hint(const Size2i &p_size) {
  694. lightmap_size_hint = p_size;
  695. }
  696. Size2i EditorSceneImporterMesh::get_lightmap_size_hint() const {
  697. return lightmap_size_hint;
  698. }
  699. void EditorSceneImporterMesh::_bind_methods() {
  700. ClassDB::bind_method(D_METHOD("add_blend_shape", "name"), &EditorSceneImporterMesh::add_blend_shape);
  701. ClassDB::bind_method(D_METHOD("get_blend_shape_count"), &EditorSceneImporterMesh::get_blend_shape_count);
  702. ClassDB::bind_method(D_METHOD("get_blend_shape_name", "blend_shape_idx"), &EditorSceneImporterMesh::get_blend_shape_name);
  703. ClassDB::bind_method(D_METHOD("set_blend_shape_mode", "mode"), &EditorSceneImporterMesh::set_blend_shape_mode);
  704. ClassDB::bind_method(D_METHOD("get_blend_shape_mode"), &EditorSceneImporterMesh::get_blend_shape_mode);
  705. ClassDB::bind_method(D_METHOD("add_surface", "primitive", "arrays", "blend_shapes", "lods", "material", "name"), &EditorSceneImporterMesh::add_surface, DEFVAL(Array()), DEFVAL(Dictionary()), DEFVAL(Ref<Material>()), DEFVAL(String()));
  706. ClassDB::bind_method(D_METHOD("get_surface_count"), &EditorSceneImporterMesh::get_surface_count);
  707. ClassDB::bind_method(D_METHOD("get_surface_primitive_type", "surface_idx"), &EditorSceneImporterMesh::get_surface_primitive_type);
  708. ClassDB::bind_method(D_METHOD("get_surface_name", "surface_idx"), &EditorSceneImporterMesh::get_surface_name);
  709. ClassDB::bind_method(D_METHOD("get_surface_arrays", "surface_idx"), &EditorSceneImporterMesh::get_surface_arrays);
  710. ClassDB::bind_method(D_METHOD("get_surface_blend_shape_arrays", "surface_idx", "blend_shape_idx"), &EditorSceneImporterMesh::get_surface_blend_shape_arrays);
  711. ClassDB::bind_method(D_METHOD("get_surface_lod_count", "surface_idx"), &EditorSceneImporterMesh::get_surface_lod_count);
  712. ClassDB::bind_method(D_METHOD("get_surface_lod_size", "surface_idx", "lod_idx"), &EditorSceneImporterMesh::get_surface_lod_size);
  713. ClassDB::bind_method(D_METHOD("get_surface_lod_indices", "surface_idx", "lod_idx"), &EditorSceneImporterMesh::get_surface_lod_indices);
  714. ClassDB::bind_method(D_METHOD("get_surface_material", "surface_idx"), &EditorSceneImporterMesh::get_surface_material);
  715. ClassDB::bind_method(D_METHOD("get_mesh"), &EditorSceneImporterMesh::get_mesh);
  716. ClassDB::bind_method(D_METHOD("clear"), &EditorSceneImporterMesh::clear);
  717. ClassDB::bind_method(D_METHOD("_set_data", "data"), &EditorSceneImporterMesh::_set_data);
  718. ClassDB::bind_method(D_METHOD("_get_data"), &EditorSceneImporterMesh::_get_data);
  719. ClassDB::bind_method(D_METHOD("set_lightmap_size_hint", "size"), &EditorSceneImporterMesh::set_lightmap_size_hint);
  720. ClassDB::bind_method(D_METHOD("get_lightmap_size_hint"), &EditorSceneImporterMesh::get_lightmap_size_hint);
  721. ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_data", "_get_data");
  722. }