geometry.cpp 30 KB

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