geometry.cpp 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  1. /*************************************************************************/
  2. /* geometry.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 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 "geometry.h"
  31. #include "core/print_string.h"
  32. #include "thirdparty/misc/clipper.hpp"
  33. #include "thirdparty/misc/triangulator.h"
  34. #define SCALE_FACTOR 100000.0 // Based on CMP_EPSILON.
  35. // This implementation is very inefficient, commenting unless bugs happen. See the other one.
  36. /*
  37. bool Geometry::is_point_in_polygon(const Vector2 &p_point, const Vector<Vector2> &p_polygon) {
  38. Vector<int> indices = Geometry::triangulate_polygon(p_polygon);
  39. for (int j = 0; j + 3 <= indices.size(); j += 3) {
  40. int i1 = indices[j], i2 = indices[j + 1], i3 = indices[j + 2];
  41. if (Geometry::is_point_in_triangle(p_point, p_polygon[i1], p_polygon[i2], p_polygon[i3]))
  42. return true;
  43. }
  44. return false;
  45. }
  46. */
  47. void Geometry::MeshData::optimize_vertices() {
  48. Map<int, int> vtx_remap;
  49. for (int i = 0; i < faces.size(); i++) {
  50. for (int j = 0; j < faces[i].indices.size(); j++) {
  51. int idx = faces[i].indices[j];
  52. if (!vtx_remap.has(idx)) {
  53. int ni = vtx_remap.size();
  54. vtx_remap[idx] = ni;
  55. }
  56. faces.write[i].indices.write[j] = vtx_remap[idx];
  57. }
  58. }
  59. for (int i = 0; i < edges.size(); i++) {
  60. int a = edges[i].a;
  61. int b = edges[i].b;
  62. if (!vtx_remap.has(a)) {
  63. int ni = vtx_remap.size();
  64. vtx_remap[a] = ni;
  65. }
  66. if (!vtx_remap.has(b)) {
  67. int ni = vtx_remap.size();
  68. vtx_remap[b] = ni;
  69. }
  70. edges.write[i].a = vtx_remap[a];
  71. edges.write[i].b = vtx_remap[b];
  72. }
  73. Vector<Vector3> new_vertices;
  74. new_vertices.resize(vtx_remap.size());
  75. for (int i = 0; i < vertices.size(); i++) {
  76. if (vtx_remap.has(i))
  77. new_vertices.write[vtx_remap[i]] = vertices[i];
  78. }
  79. vertices = new_vertices;
  80. }
  81. struct _FaceClassify {
  82. struct _Link {
  83. int face;
  84. int edge;
  85. void clear() {
  86. face = -1;
  87. edge = -1;
  88. }
  89. _Link() {
  90. face = -1;
  91. edge = -1;
  92. }
  93. };
  94. bool valid;
  95. int group;
  96. _Link links[3];
  97. Face3 face;
  98. _FaceClassify() {
  99. group = -1;
  100. valid = false;
  101. };
  102. };
  103. static bool _connect_faces(_FaceClassify *p_faces, int len, int p_group) {
  104. // Connect faces, error will occur if an edge is shared between more than 2 faces.
  105. // Clear connections.
  106. bool error = false;
  107. for (int i = 0; i < len; i++) {
  108. for (int j = 0; j < 3; j++) {
  109. p_faces[i].links[j].clear();
  110. }
  111. }
  112. for (int i = 0; i < len; i++) {
  113. if (p_faces[i].group != p_group)
  114. continue;
  115. for (int j = i + 1; j < len; j++) {
  116. if (p_faces[j].group != p_group)
  117. continue;
  118. for (int k = 0; k < 3; k++) {
  119. Vector3 vi1 = p_faces[i].face.vertex[k];
  120. Vector3 vi2 = p_faces[i].face.vertex[(k + 1) % 3];
  121. for (int l = 0; l < 3; l++) {
  122. Vector3 vj2 = p_faces[j].face.vertex[l];
  123. Vector3 vj1 = p_faces[j].face.vertex[(l + 1) % 3];
  124. if (vi1.distance_to(vj1) < 0.00001 &&
  125. vi2.distance_to(vj2) < 0.00001) {
  126. if (p_faces[i].links[k].face != -1) {
  127. ERR_PRINT("already linked\n");
  128. error = true;
  129. break;
  130. }
  131. if (p_faces[j].links[l].face != -1) {
  132. ERR_PRINT("already linked\n");
  133. error = true;
  134. break;
  135. }
  136. p_faces[i].links[k].face = j;
  137. p_faces[i].links[k].edge = l;
  138. p_faces[j].links[l].face = i;
  139. p_faces[j].links[l].edge = k;
  140. }
  141. }
  142. if (error)
  143. break;
  144. }
  145. if (error)
  146. break;
  147. }
  148. if (error)
  149. break;
  150. }
  151. for (int i = 0; i < len; i++) {
  152. p_faces[i].valid = true;
  153. for (int j = 0; j < 3; j++) {
  154. if (p_faces[i].links[j].face == -1)
  155. p_faces[i].valid = false;
  156. }
  157. }
  158. return error;
  159. }
  160. static bool _group_face(_FaceClassify *p_faces, int len, int p_index, int p_group) {
  161. if (p_faces[p_index].group >= 0)
  162. return false;
  163. p_faces[p_index].group = p_group;
  164. for (int i = 0; i < 3; i++) {
  165. ERR_FAIL_INDEX_V(p_faces[p_index].links[i].face, len, true);
  166. _group_face(p_faces, len, p_faces[p_index].links[i].face, p_group);
  167. }
  168. return true;
  169. }
  170. Vector<Vector<Face3>> Geometry::separate_objects(Vector<Face3> p_array) {
  171. Vector<Vector<Face3>> objects;
  172. int len = p_array.size();
  173. const Face3 *arrayptr = p_array.ptr();
  174. Vector<_FaceClassify> fc;
  175. fc.resize(len);
  176. _FaceClassify *_fcptr = fc.ptrw();
  177. for (int i = 0; i < len; i++) {
  178. _fcptr[i].face = arrayptr[i];
  179. }
  180. bool error = _connect_faces(_fcptr, len, -1);
  181. ERR_FAIL_COND_V_MSG(error, Vector<Vector<Face3>>(), "Invalid geometry.");
  182. // Group connected faces in separate objects.
  183. int group = 0;
  184. for (int i = 0; i < len; i++) {
  185. if (!_fcptr[i].valid)
  186. continue;
  187. if (_group_face(_fcptr, len, i, group)) {
  188. group++;
  189. }
  190. }
  191. // Group connected faces in separate objects.
  192. for (int i = 0; i < len; i++) {
  193. _fcptr[i].face = arrayptr[i];
  194. }
  195. if (group >= 0) {
  196. objects.resize(group);
  197. Vector<Face3> *group_faces = objects.ptrw();
  198. for (int i = 0; i < len; i++) {
  199. if (!_fcptr[i].valid)
  200. continue;
  201. if (_fcptr[i].group >= 0 && _fcptr[i].group < group) {
  202. group_faces[_fcptr[i].group].push_back(_fcptr[i].face);
  203. }
  204. }
  205. }
  206. return objects;
  207. }
  208. /*** GEOMETRY WRAPPER ***/
  209. enum _CellFlags {
  210. _CELL_SOLID = 1,
  211. _CELL_EXTERIOR = 2,
  212. _CELL_STEP_MASK = 0x1C,
  213. _CELL_STEP_NONE = 0 << 2,
  214. _CELL_STEP_Y_POS = 1 << 2,
  215. _CELL_STEP_Y_NEG = 2 << 2,
  216. _CELL_STEP_X_POS = 3 << 2,
  217. _CELL_STEP_X_NEG = 4 << 2,
  218. _CELL_STEP_Z_POS = 5 << 2,
  219. _CELL_STEP_Z_NEG = 6 << 2,
  220. _CELL_STEP_DONE = 7 << 2,
  221. _CELL_PREV_MASK = 0xE0,
  222. _CELL_PREV_NONE = 0 << 5,
  223. _CELL_PREV_Y_POS = 1 << 5,
  224. _CELL_PREV_Y_NEG = 2 << 5,
  225. _CELL_PREV_X_POS = 3 << 5,
  226. _CELL_PREV_X_NEG = 4 << 5,
  227. _CELL_PREV_Z_POS = 5 << 5,
  228. _CELL_PREV_Z_NEG = 6 << 5,
  229. _CELL_PREV_FIRST = 7 << 5,
  230. };
  231. static inline void _plot_face(uint8_t ***p_cell_status, int x, int y, int z, int len_x, int len_y, int len_z, const Vector3 &voxelsize, const Face3 &p_face) {
  232. AABB aabb(Vector3(x, y, z), Vector3(len_x, len_y, len_z));
  233. aabb.position = aabb.position * voxelsize;
  234. aabb.size = aabb.size * voxelsize;
  235. if (!p_face.intersects_aabb(aabb))
  236. return;
  237. if (len_x == 1 && len_y == 1 && len_z == 1) {
  238. p_cell_status[x][y][z] = _CELL_SOLID;
  239. return;
  240. }
  241. int div_x = len_x > 1 ? 2 : 1;
  242. int div_y = len_y > 1 ? 2 : 1;
  243. int div_z = len_z > 1 ? 2 : 1;
  244. #define _SPLIT(m_i, m_div, m_v, m_len_v, m_new_v, m_new_len_v) \
  245. if (m_div == 1) { \
  246. m_new_v = m_v; \
  247. m_new_len_v = 1; \
  248. } else if (m_i == 0) { \
  249. m_new_v = m_v; \
  250. m_new_len_v = m_len_v / 2; \
  251. } else { \
  252. m_new_v = m_v + m_len_v / 2; \
  253. m_new_len_v = m_len_v - m_len_v / 2; \
  254. }
  255. int new_x;
  256. int new_len_x;
  257. int new_y;
  258. int new_len_y;
  259. int new_z;
  260. int new_len_z;
  261. for (int i = 0; i < div_x; i++) {
  262. _SPLIT(i, div_x, x, len_x, new_x, new_len_x);
  263. for (int j = 0; j < div_y; j++) {
  264. _SPLIT(j, div_y, y, len_y, new_y, new_len_y);
  265. for (int k = 0; k < div_z; k++) {
  266. _SPLIT(k, div_z, z, len_z, new_z, new_len_z);
  267. _plot_face(p_cell_status, new_x, new_y, new_z, new_len_x, new_len_y, new_len_z, voxelsize, p_face);
  268. }
  269. }
  270. }
  271. }
  272. static inline void _mark_outside(uint8_t ***p_cell_status, int x, int y, int z, int len_x, int len_y, int len_z) {
  273. if (p_cell_status[x][y][z] & 3)
  274. return; // Nothing to do, already used and/or visited.
  275. p_cell_status[x][y][z] = _CELL_PREV_FIRST;
  276. while (true) {
  277. uint8_t &c = p_cell_status[x][y][z];
  278. if ((c & _CELL_STEP_MASK) == _CELL_STEP_NONE) {
  279. // Haven't been in here, mark as outside.
  280. p_cell_status[x][y][z] |= _CELL_EXTERIOR;
  281. }
  282. if ((c & _CELL_STEP_MASK) != _CELL_STEP_DONE) {
  283. // If not done, increase step.
  284. c += 1 << 2;
  285. }
  286. if ((c & _CELL_STEP_MASK) == _CELL_STEP_DONE) {
  287. // Go back.
  288. switch (c & _CELL_PREV_MASK) {
  289. case _CELL_PREV_FIRST: {
  290. return;
  291. } break;
  292. case _CELL_PREV_Y_POS: {
  293. y++;
  294. ERR_FAIL_COND(y >= len_y);
  295. } break;
  296. case _CELL_PREV_Y_NEG: {
  297. y--;
  298. ERR_FAIL_COND(y < 0);
  299. } break;
  300. case _CELL_PREV_X_POS: {
  301. x++;
  302. ERR_FAIL_COND(x >= len_x);
  303. } break;
  304. case _CELL_PREV_X_NEG: {
  305. x--;
  306. ERR_FAIL_COND(x < 0);
  307. } break;
  308. case _CELL_PREV_Z_POS: {
  309. z++;
  310. ERR_FAIL_COND(z >= len_z);
  311. } break;
  312. case _CELL_PREV_Z_NEG: {
  313. z--;
  314. ERR_FAIL_COND(z < 0);
  315. } break;
  316. default: {
  317. ERR_FAIL();
  318. }
  319. }
  320. continue;
  321. }
  322. int next_x = x, next_y = y, next_z = z;
  323. uint8_t prev = 0;
  324. switch (c & _CELL_STEP_MASK) {
  325. case _CELL_STEP_Y_POS: {
  326. next_y++;
  327. prev = _CELL_PREV_Y_NEG;
  328. } break;
  329. case _CELL_STEP_Y_NEG: {
  330. next_y--;
  331. prev = _CELL_PREV_Y_POS;
  332. } break;
  333. case _CELL_STEP_X_POS: {
  334. next_x++;
  335. prev = _CELL_PREV_X_NEG;
  336. } break;
  337. case _CELL_STEP_X_NEG: {
  338. next_x--;
  339. prev = _CELL_PREV_X_POS;
  340. } break;
  341. case _CELL_STEP_Z_POS: {
  342. next_z++;
  343. prev = _CELL_PREV_Z_NEG;
  344. } break;
  345. case _CELL_STEP_Z_NEG: {
  346. next_z--;
  347. prev = _CELL_PREV_Z_POS;
  348. } break;
  349. default: ERR_FAIL();
  350. }
  351. if (next_x < 0 || next_x >= len_x)
  352. continue;
  353. if (next_y < 0 || next_y >= len_y)
  354. continue;
  355. if (next_z < 0 || next_z >= len_z)
  356. continue;
  357. if (p_cell_status[next_x][next_y][next_z] & 3)
  358. continue;
  359. x = next_x;
  360. y = next_y;
  361. z = next_z;
  362. p_cell_status[x][y][z] |= prev;
  363. }
  364. }
  365. static inline void _build_faces(uint8_t ***p_cell_status, int x, int y, int z, int len_x, int len_y, int len_z, Vector<Face3> &p_faces) {
  366. ERR_FAIL_INDEX(x, len_x);
  367. ERR_FAIL_INDEX(y, len_y);
  368. ERR_FAIL_INDEX(z, len_z);
  369. if (p_cell_status[x][y][z] & _CELL_EXTERIOR)
  370. return;
  371. #define vert(m_idx) Vector3(((m_idx)&4) >> 2, ((m_idx)&2) >> 1, (m_idx)&1)
  372. static const uint8_t indices[6][4] = {
  373. { 7, 6, 4, 5 },
  374. { 7, 3, 2, 6 },
  375. { 7, 5, 1, 3 },
  376. { 0, 2, 3, 1 },
  377. { 0, 1, 5, 4 },
  378. { 0, 4, 6, 2 },
  379. };
  380. for (int i = 0; i < 6; i++) {
  381. Vector3 face_points[4];
  382. int disp_x = x + ((i % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  383. int disp_y = y + (((i - 1) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  384. int disp_z = z + (((i - 2) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  385. bool plot = false;
  386. if (disp_x < 0 || disp_x >= len_x)
  387. plot = true;
  388. if (disp_y < 0 || disp_y >= len_y)
  389. plot = true;
  390. if (disp_z < 0 || disp_z >= len_z)
  391. plot = true;
  392. if (!plot && (p_cell_status[disp_x][disp_y][disp_z] & _CELL_EXTERIOR))
  393. plot = true;
  394. if (!plot)
  395. continue;
  396. for (int j = 0; j < 4; j++)
  397. face_points[j] = vert(indices[i][j]) + Vector3(x, y, z);
  398. p_faces.push_back(
  399. Face3(
  400. face_points[0],
  401. face_points[1],
  402. face_points[2]));
  403. p_faces.push_back(
  404. Face3(
  405. face_points[2],
  406. face_points[3],
  407. face_points[0]));
  408. }
  409. }
  410. Vector<Face3> Geometry::wrap_geometry(Vector<Face3> p_array, real_t *p_error) {
  411. #define _MIN_SIZE 1.0
  412. #define _MAX_LENGTH 20
  413. int face_count = p_array.size();
  414. const Face3 *faces = p_array.ptr();
  415. AABB global_aabb;
  416. for (int i = 0; i < face_count; i++) {
  417. if (i == 0) {
  418. global_aabb = faces[i].get_aabb();
  419. } else {
  420. global_aabb.merge_with(faces[i].get_aabb());
  421. }
  422. }
  423. global_aabb.grow_by(0.01); // Avoid numerical error.
  424. // Determine amount of cells in grid axis.
  425. int div_x, div_y, div_z;
  426. if (global_aabb.size.x / _MIN_SIZE < _MAX_LENGTH)
  427. div_x = (int)(global_aabb.size.x / _MIN_SIZE) + 1;
  428. else
  429. div_x = _MAX_LENGTH;
  430. if (global_aabb.size.y / _MIN_SIZE < _MAX_LENGTH)
  431. div_y = (int)(global_aabb.size.y / _MIN_SIZE) + 1;
  432. else
  433. div_y = _MAX_LENGTH;
  434. if (global_aabb.size.z / _MIN_SIZE < _MAX_LENGTH)
  435. div_z = (int)(global_aabb.size.z / _MIN_SIZE) + 1;
  436. else
  437. div_z = _MAX_LENGTH;
  438. Vector3 voxelsize = global_aabb.size;
  439. voxelsize.x /= div_x;
  440. voxelsize.y /= div_y;
  441. voxelsize.z /= div_z;
  442. // Create and initialize cells to zero.
  443. uint8_t ***cell_status = memnew_arr(uint8_t **, div_x);
  444. for (int i = 0; i < div_x; i++) {
  445. cell_status[i] = memnew_arr(uint8_t *, div_y);
  446. for (int j = 0; j < div_y; j++) {
  447. cell_status[i][j] = memnew_arr(uint8_t, div_z);
  448. for (int k = 0; k < div_z; k++) {
  449. cell_status[i][j][k] = 0;
  450. }
  451. }
  452. }
  453. // Plot faces into cells.
  454. for (int i = 0; i < face_count; i++) {
  455. Face3 f = faces[i];
  456. for (int j = 0; j < 3; j++) {
  457. f.vertex[j] -= global_aabb.position;
  458. }
  459. _plot_face(cell_status, 0, 0, 0, div_x, div_y, div_z, voxelsize, f);
  460. }
  461. // Determine which cells connect to the outside by traversing the outside and recursively flood-fill marking.
  462. for (int i = 0; i < div_x; i++) {
  463. for (int j = 0; j < div_y; j++) {
  464. _mark_outside(cell_status, i, j, 0, div_x, div_y, div_z);
  465. _mark_outside(cell_status, i, j, div_z - 1, div_x, div_y, div_z);
  466. }
  467. }
  468. for (int i = 0; i < div_z; i++) {
  469. for (int j = 0; j < div_y; j++) {
  470. _mark_outside(cell_status, 0, j, i, div_x, div_y, div_z);
  471. _mark_outside(cell_status, div_x - 1, j, i, div_x, div_y, div_z);
  472. }
  473. }
  474. for (int i = 0; i < div_x; i++) {
  475. for (int j = 0; j < div_z; j++) {
  476. _mark_outside(cell_status, i, 0, j, div_x, div_y, div_z);
  477. _mark_outside(cell_status, i, div_y - 1, j, div_x, div_y, div_z);
  478. }
  479. }
  480. // Build faces for the inside-outside cell divisors.
  481. Vector<Face3> wrapped_faces;
  482. for (int i = 0; i < div_x; i++) {
  483. for (int j = 0; j < div_y; j++) {
  484. for (int k = 0; k < div_z; k++) {
  485. _build_faces(cell_status, i, j, k, div_x, div_y, div_z, wrapped_faces);
  486. }
  487. }
  488. }
  489. // Transform face vertices to global coords.
  490. int wrapped_faces_count = wrapped_faces.size();
  491. Face3 *wrapped_faces_ptr = wrapped_faces.ptrw();
  492. for (int i = 0; i < wrapped_faces_count; i++) {
  493. for (int j = 0; j < 3; j++) {
  494. Vector3 &v = wrapped_faces_ptr[i].vertex[j];
  495. v = v * voxelsize;
  496. v += global_aabb.position;
  497. }
  498. }
  499. // clean up grid
  500. for (int i = 0; i < div_x; i++) {
  501. for (int j = 0; j < div_y; j++) {
  502. memdelete_arr(cell_status[i][j]);
  503. }
  504. memdelete_arr(cell_status[i]);
  505. }
  506. memdelete_arr(cell_status);
  507. if (p_error)
  508. *p_error = voxelsize.length();
  509. return wrapped_faces;
  510. }
  511. Vector<Vector<Vector2>> Geometry::decompose_polygon_in_convex(Vector<Point2> polygon) {
  512. Vector<Vector<Vector2>> decomp;
  513. List<TriangulatorPoly> in_poly, out_poly;
  514. TriangulatorPoly inp;
  515. inp.Init(polygon.size());
  516. for (int i = 0; i < polygon.size(); i++) {
  517. inp.GetPoint(i) = polygon[i];
  518. }
  519. inp.SetOrientation(TRIANGULATOR_CCW);
  520. in_poly.push_back(inp);
  521. TriangulatorPartition tpart;
  522. if (tpart.ConvexPartition_HM(&in_poly, &out_poly) == 0) { // Failed.
  523. ERR_PRINT("Convex decomposing failed!");
  524. return decomp;
  525. }
  526. decomp.resize(out_poly.size());
  527. int idx = 0;
  528. for (List<TriangulatorPoly>::Element *I = out_poly.front(); I; I = I->next()) {
  529. TriangulatorPoly &tp = I->get();
  530. decomp.write[idx].resize(tp.GetNumPoints());
  531. for (int64_t i = 0; i < tp.GetNumPoints(); i++) {
  532. decomp.write[idx].write[i] = tp.GetPoint(i);
  533. }
  534. idx++;
  535. }
  536. return decomp;
  537. }
  538. Geometry::MeshData Geometry::build_convex_mesh(const Vector<Plane> &p_planes) {
  539. MeshData mesh;
  540. #define SUBPLANE_SIZE 1024.0
  541. real_t subplane_size = 1024.0; // Should compute this from the actual plane.
  542. for (int i = 0; i < p_planes.size(); i++) {
  543. Plane p = p_planes[i];
  544. Vector3 ref = Vector3(0.0, 1.0, 0.0);
  545. if (ABS(p.normal.dot(ref)) > 0.95)
  546. ref = Vector3(0.0, 0.0, 1.0); // Change axis.
  547. Vector3 right = p.normal.cross(ref).normalized();
  548. Vector3 up = p.normal.cross(right).normalized();
  549. Vector<Vector3> vertices;
  550. Vector3 center = p.get_any_point();
  551. // make a quad clockwise
  552. vertices.push_back(center - up * subplane_size + right * subplane_size);
  553. vertices.push_back(center - up * subplane_size - right * subplane_size);
  554. vertices.push_back(center + up * subplane_size - right * subplane_size);
  555. vertices.push_back(center + up * subplane_size + right * subplane_size);
  556. for (int j = 0; j < p_planes.size(); j++) {
  557. if (j == i)
  558. continue;
  559. Vector<Vector3> new_vertices;
  560. Plane clip = p_planes[j];
  561. if (clip.normal.dot(p.normal) > 0.95)
  562. continue;
  563. if (vertices.size() < 3)
  564. break;
  565. for (int k = 0; k < vertices.size(); k++) {
  566. int k_n = (k + 1) % vertices.size();
  567. Vector3 edge0_A = vertices[k];
  568. Vector3 edge1_A = vertices[k_n];
  569. real_t dist0 = clip.distance_to(edge0_A);
  570. real_t dist1 = clip.distance_to(edge1_A);
  571. if (dist0 <= 0) { // Behind plane.
  572. new_vertices.push_back(vertices[k]);
  573. }
  574. // Check for different sides and non coplanar.
  575. if ((dist0 * dist1) < 0) {
  576. // Calculate intersection.
  577. Vector3 rel = edge1_A - edge0_A;
  578. real_t den = clip.normal.dot(rel);
  579. if (Math::is_zero_approx(den))
  580. continue; // Point too short.
  581. real_t dist = -(clip.normal.dot(edge0_A) - clip.distance) / den;
  582. Vector3 inters = edge0_A + rel * dist;
  583. new_vertices.push_back(inters);
  584. }
  585. }
  586. vertices = new_vertices;
  587. }
  588. if (vertices.size() < 3)
  589. continue;
  590. // Result is a clockwise face.
  591. MeshData::Face face;
  592. // Add face indices.
  593. for (int j = 0; j < vertices.size(); j++) {
  594. int idx = -1;
  595. for (int k = 0; k < mesh.vertices.size(); k++) {
  596. if (mesh.vertices[k].distance_to(vertices[j]) < 0.001) {
  597. idx = k;
  598. break;
  599. }
  600. }
  601. if (idx == -1) {
  602. idx = mesh.vertices.size();
  603. mesh.vertices.push_back(vertices[j]);
  604. }
  605. face.indices.push_back(idx);
  606. }
  607. face.plane = p;
  608. mesh.faces.push_back(face);
  609. // Add edge.
  610. for (int j = 0; j < face.indices.size(); j++) {
  611. int a = face.indices[j];
  612. int b = face.indices[(j + 1) % face.indices.size()];
  613. bool found = false;
  614. for (int k = 0; k < mesh.edges.size(); k++) {
  615. if (mesh.edges[k].a == a && mesh.edges[k].b == b) {
  616. found = true;
  617. break;
  618. }
  619. if (mesh.edges[k].b == a && mesh.edges[k].a == b) {
  620. found = true;
  621. break;
  622. }
  623. }
  624. if (found)
  625. continue;
  626. MeshData::Edge edge;
  627. edge.a = a;
  628. edge.b = b;
  629. mesh.edges.push_back(edge);
  630. }
  631. }
  632. return mesh;
  633. }
  634. Vector<Plane> Geometry::build_box_planes(const Vector3 &p_extents) {
  635. Vector<Plane> planes;
  636. planes.push_back(Plane(Vector3(1, 0, 0), p_extents.x));
  637. planes.push_back(Plane(Vector3(-1, 0, 0), p_extents.x));
  638. planes.push_back(Plane(Vector3(0, 1, 0), p_extents.y));
  639. planes.push_back(Plane(Vector3(0, -1, 0), p_extents.y));
  640. planes.push_back(Plane(Vector3(0, 0, 1), p_extents.z));
  641. planes.push_back(Plane(Vector3(0, 0, -1), p_extents.z));
  642. return planes;
  643. }
  644. Vector<Plane> Geometry::build_cylinder_planes(real_t p_radius, real_t p_height, int p_sides, Vector3::Axis p_axis) {
  645. Vector<Plane> planes;
  646. for (int i = 0; i < p_sides; i++) {
  647. Vector3 normal;
  648. normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_sides);
  649. normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_sides);
  650. planes.push_back(Plane(normal, p_radius));
  651. }
  652. Vector3 axis;
  653. axis[p_axis] = 1.0;
  654. planes.push_back(Plane(axis, p_height * 0.5));
  655. planes.push_back(Plane(-axis, p_height * 0.5));
  656. return planes;
  657. }
  658. Vector<Plane> Geometry::build_sphere_planes(real_t p_radius, int p_lats, int p_lons, Vector3::Axis p_axis) {
  659. Vector<Plane> planes;
  660. Vector3 axis;
  661. axis[p_axis] = 1.0;
  662. Vector3 axis_neg;
  663. axis_neg[(p_axis + 1) % 3] = 1.0;
  664. axis_neg[(p_axis + 2) % 3] = 1.0;
  665. axis_neg[p_axis] = -1.0;
  666. for (int i = 0; i < p_lons; i++) {
  667. Vector3 normal;
  668. normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_lons);
  669. normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_lons);
  670. planes.push_back(Plane(normal, p_radius));
  671. for (int j = 1; j <= p_lats; j++) {
  672. // FIXME: This is stupid.
  673. Vector3 angle = normal.lerp(axis, j / (real_t)p_lats).normalized();
  674. Vector3 pos = angle * p_radius;
  675. planes.push_back(Plane(pos, angle));
  676. planes.push_back(Plane(pos * axis_neg, angle * axis_neg));
  677. }
  678. }
  679. return planes;
  680. }
  681. Vector<Plane> Geometry::build_capsule_planes(real_t p_radius, real_t p_height, int p_sides, int p_lats, Vector3::Axis p_axis) {
  682. Vector<Plane> planes;
  683. Vector3 axis;
  684. axis[p_axis] = 1.0;
  685. Vector3 axis_neg;
  686. axis_neg[(p_axis + 1) % 3] = 1.0;
  687. axis_neg[(p_axis + 2) % 3] = 1.0;
  688. axis_neg[p_axis] = -1.0;
  689. for (int i = 0; i < p_sides; i++) {
  690. Vector3 normal;
  691. normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_sides);
  692. normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_sides);
  693. planes.push_back(Plane(normal, p_radius));
  694. for (int j = 1; j <= p_lats; j++) {
  695. Vector3 angle = normal.lerp(axis, j / (real_t)p_lats).normalized();
  696. Vector3 pos = axis * p_height * 0.5 + angle * p_radius;
  697. planes.push_back(Plane(pos, angle));
  698. planes.push_back(Plane(pos * axis_neg, angle * axis_neg));
  699. }
  700. }
  701. return planes;
  702. }
  703. struct _AtlasWorkRect {
  704. Size2i s;
  705. Point2i p;
  706. int idx;
  707. _FORCE_INLINE_ bool operator<(const _AtlasWorkRect &p_r) const { return s.width > p_r.s.width; };
  708. };
  709. struct _AtlasWorkRectResult {
  710. Vector<_AtlasWorkRect> result;
  711. int max_w;
  712. int max_h;
  713. };
  714. void Geometry::make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size) {
  715. // Super simple, almost brute force scanline stacking fitter.
  716. // It's pretty basic for now, but it tries to make sure that the aspect ratio of the
  717. // resulting atlas is somehow square. This is necessary because video cards have limits.
  718. // On texture size (usually 2048 or 4096), so the more square a texture, the more chances.
  719. // It will work in every hardware.
  720. // For example, it will prioritize a 1024x1024 atlas (works everywhere) instead of a
  721. // 256x8192 atlas (won't work anywhere).
  722. ERR_FAIL_COND(p_rects.size() == 0);
  723. Vector<_AtlasWorkRect> wrects;
  724. wrects.resize(p_rects.size());
  725. for (int i = 0; i < p_rects.size(); i++) {
  726. wrects.write[i].s = p_rects[i];
  727. wrects.write[i].idx = i;
  728. }
  729. wrects.sort();
  730. int widest = wrects[0].s.width;
  731. Vector<_AtlasWorkRectResult> results;
  732. for (int i = 0; i <= 12; i++) {
  733. int w = 1 << i;
  734. int max_h = 0;
  735. int max_w = 0;
  736. if (w < widest)
  737. continue;
  738. Vector<int> hmax;
  739. hmax.resize(w);
  740. for (int j = 0; j < w; j++)
  741. hmax.write[j] = 0;
  742. // Place them.
  743. int ofs = 0;
  744. int limit_h = 0;
  745. for (int j = 0; j < wrects.size(); j++) {
  746. if (ofs + wrects[j].s.width > w) {
  747. ofs = 0;
  748. }
  749. int from_y = 0;
  750. for (int k = 0; k < wrects[j].s.width; k++) {
  751. if (hmax[ofs + k] > from_y)
  752. from_y = hmax[ofs + k];
  753. }
  754. wrects.write[j].p.x = ofs;
  755. wrects.write[j].p.y = from_y;
  756. int end_h = from_y + wrects[j].s.height;
  757. int end_w = ofs + wrects[j].s.width;
  758. if (ofs == 0)
  759. limit_h = end_h;
  760. for (int k = 0; k < wrects[j].s.width; k++) {
  761. hmax.write[ofs + k] = end_h;
  762. }
  763. if (end_h > max_h)
  764. max_h = end_h;
  765. if (end_w > max_w)
  766. max_w = end_w;
  767. if (ofs == 0 || end_h > limit_h) // While h limit not reached, keep stacking.
  768. ofs += wrects[j].s.width;
  769. }
  770. _AtlasWorkRectResult result;
  771. result.result = wrects;
  772. result.max_h = max_h;
  773. result.max_w = max_w;
  774. results.push_back(result);
  775. }
  776. // Find the result with the best aspect ratio.
  777. int best = -1;
  778. real_t best_aspect = 1e20;
  779. for (int i = 0; i < results.size(); i++) {
  780. real_t h = next_power_of_2(results[i].max_h);
  781. real_t w = next_power_of_2(results[i].max_w);
  782. real_t aspect = h > w ? h / w : w / h;
  783. if (aspect < best_aspect) {
  784. best = i;
  785. best_aspect = aspect;
  786. }
  787. }
  788. r_result.resize(p_rects.size());
  789. for (int i = 0; i < p_rects.size(); i++) {
  790. r_result.write[results[best].result[i].idx] = results[best].result[i].p;
  791. }
  792. r_size = Size2(results[best].max_w, results[best].max_h);
  793. }
  794. Vector<Vector<Point2>> Geometry::_polypaths_do_operation(PolyBooleanOperation p_op, const Vector<Point2> &p_polypath_a, const Vector<Point2> &p_polypath_b, bool is_a_open) {
  795. using namespace ClipperLib;
  796. ClipType op = ctUnion;
  797. switch (p_op) {
  798. case OPERATION_UNION: op = ctUnion; break;
  799. case OPERATION_DIFFERENCE: op = ctDifference; break;
  800. case OPERATION_INTERSECTION: op = ctIntersection; break;
  801. case OPERATION_XOR: op = ctXor; break;
  802. }
  803. Path path_a, path_b;
  804. // Need to scale points (Clipper's requirement for robust computation).
  805. for (int i = 0; i != p_polypath_a.size(); ++i) {
  806. path_a << IntPoint(p_polypath_a[i].x * SCALE_FACTOR, p_polypath_a[i].y * SCALE_FACTOR);
  807. }
  808. for (int i = 0; i != p_polypath_b.size(); ++i) {
  809. path_b << IntPoint(p_polypath_b[i].x * SCALE_FACTOR, p_polypath_b[i].y * SCALE_FACTOR);
  810. }
  811. Clipper clp;
  812. clp.AddPath(path_a, ptSubject, !is_a_open); // Forward compatible with Clipper 10.0.0.
  813. clp.AddPath(path_b, ptClip, true); // Polylines cannot be set as clip.
  814. Paths paths;
  815. if (is_a_open) {
  816. PolyTree tree; // Needed to populate polylines.
  817. clp.Execute(op, tree);
  818. OpenPathsFromPolyTree(tree, paths);
  819. } else {
  820. clp.Execute(op, paths); // Works on closed polygons only.
  821. }
  822. // Have to scale points down now.
  823. Vector<Vector<Point2>> polypaths;
  824. for (Paths::size_type i = 0; i < paths.size(); ++i) {
  825. Vector<Vector2> polypath;
  826. const Path &scaled_path = paths[i];
  827. for (Paths::size_type j = 0; j < scaled_path.size(); ++j) {
  828. polypath.push_back(Point2(
  829. static_cast<real_t>(scaled_path[j].X) / SCALE_FACTOR,
  830. static_cast<real_t>(scaled_path[j].Y) / SCALE_FACTOR));
  831. }
  832. polypaths.push_back(polypath);
  833. }
  834. return polypaths;
  835. }
  836. Vector<Vector<Point2>> Geometry::_polypath_offset(const Vector<Point2> &p_polypath, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) {
  837. using namespace ClipperLib;
  838. JoinType jt = jtSquare;
  839. switch (p_join_type) {
  840. case JOIN_SQUARE: jt = jtSquare; break;
  841. case JOIN_ROUND: jt = jtRound; break;
  842. case JOIN_MITER: jt = jtMiter; break;
  843. }
  844. EndType et = etClosedPolygon;
  845. switch (p_end_type) {
  846. case END_POLYGON: et = etClosedPolygon; break;
  847. case END_JOINED: et = etClosedLine; break;
  848. case END_BUTT: et = etOpenButt; break;
  849. case END_SQUARE: et = etOpenSquare; break;
  850. case END_ROUND: et = etOpenRound; break;
  851. }
  852. ClipperOffset co(2.0, 0.25 * SCALE_FACTOR); // Defaults from ClipperOffset.
  853. Path path;
  854. // Need to scale points (Clipper's requirement for robust computation).
  855. for (int i = 0; i != p_polypath.size(); ++i) {
  856. path << IntPoint(p_polypath[i].x * SCALE_FACTOR, p_polypath[i].y * SCALE_FACTOR);
  857. }
  858. co.AddPath(path, jt, et);
  859. Paths paths;
  860. co.Execute(paths, p_delta * SCALE_FACTOR); // Inflate/deflate.
  861. // Have to scale points down now.
  862. Vector<Vector<Point2>> polypaths;
  863. for (Paths::size_type i = 0; i < paths.size(); ++i) {
  864. Vector<Vector2> polypath;
  865. const Path &scaled_path = paths[i];
  866. for (Paths::size_type j = 0; j < scaled_path.size(); ++j) {
  867. polypath.push_back(Point2(
  868. static_cast<real_t>(scaled_path[j].X) / SCALE_FACTOR,
  869. static_cast<real_t>(scaled_path[j].Y) / SCALE_FACTOR));
  870. }
  871. polypaths.push_back(polypath);
  872. }
  873. return polypaths;
  874. }
  875. Vector<Vector3> Geometry::compute_convex_mesh_points(const Plane *p_planes, int p_plane_count) {
  876. Vector<Vector3> points;
  877. // Iterate through every unique combination of any three planes.
  878. for (int i = p_plane_count - 1; i >= 0; i--) {
  879. for (int j = i - 1; j >= 0; j--) {
  880. for (int k = j - 1; k >= 0; k--) {
  881. // Find the point where these planes all cross over (if they
  882. // do at all).
  883. Vector3 convex_shape_point;
  884. if (p_planes[i].intersect_3(p_planes[j], p_planes[k], &convex_shape_point)) {
  885. // See if any *other* plane excludes this point because it's
  886. // on the wrong side.
  887. bool excluded = false;
  888. for (int n = 0; n < p_plane_count; n++) {
  889. if (n != i && n != j && n != k) {
  890. real_t dp = p_planes[n].normal.dot(convex_shape_point);
  891. if (dp - p_planes[n].distance > CMP_EPSILON) {
  892. excluded = true;
  893. break;
  894. }
  895. }
  896. }
  897. // Only add the point if it passed all tests.
  898. if (!excluded) {
  899. points.push_back(convex_shape_point);
  900. }
  901. }
  902. }
  903. }
  904. }
  905. return points;
  906. }