geometry.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438
  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 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. Vector<Vector<Face3>> Geometry::separate_objects(Vector<Face3> p_array) {
  173. Vector<Vector<Face3>> objects;
  174. int len = p_array.size();
  175. const Face3 *arrayptr = p_array.ptr();
  176. Vector<_FaceClassify> fc;
  177. fc.resize(len);
  178. _FaceClassify *_fcptr = fc.ptrw();
  179. for (int i = 0; i < len; i++) {
  180. _fcptr[i].face = arrayptr[i];
  181. }
  182. bool error = _connect_faces(_fcptr, len, -1);
  183. ERR_FAIL_COND_V_MSG(error, Vector<Vector<Face3>>(), "Invalid geometry.");
  184. // Group connected faces in separate objects.
  185. int group = 0;
  186. for (int i = 0; i < len; i++) {
  187. if (!_fcptr[i].valid)
  188. continue;
  189. if (_group_face(_fcptr, len, i, group)) {
  190. group++;
  191. }
  192. }
  193. // Group connected faces in separate objects.
  194. for (int i = 0; i < len; i++) {
  195. _fcptr[i].face = arrayptr[i];
  196. }
  197. if (group >= 0) {
  198. objects.resize(group);
  199. Vector<Face3> *group_faces = objects.ptrw();
  200. for (int i = 0; i < len; i++) {
  201. if (!_fcptr[i].valid)
  202. continue;
  203. if (_fcptr[i].group >= 0 && _fcptr[i].group < group) {
  204. group_faces[_fcptr[i].group].push_back(_fcptr[i].face);
  205. }
  206. }
  207. }
  208. return objects;
  209. }
  210. /*** GEOMETRY WRAPPER ***/
  211. enum _CellFlags {
  212. _CELL_SOLID = 1,
  213. _CELL_EXTERIOR = 2,
  214. _CELL_STEP_MASK = 0x1C,
  215. _CELL_STEP_NONE = 0 << 2,
  216. _CELL_STEP_Y_POS = 1 << 2,
  217. _CELL_STEP_Y_NEG = 2 << 2,
  218. _CELL_STEP_X_POS = 3 << 2,
  219. _CELL_STEP_X_NEG = 4 << 2,
  220. _CELL_STEP_Z_POS = 5 << 2,
  221. _CELL_STEP_Z_NEG = 6 << 2,
  222. _CELL_STEP_DONE = 7 << 2,
  223. _CELL_PREV_MASK = 0xE0,
  224. _CELL_PREV_NONE = 0 << 5,
  225. _CELL_PREV_Y_POS = 1 << 5,
  226. _CELL_PREV_Y_NEG = 2 << 5,
  227. _CELL_PREV_X_POS = 3 << 5,
  228. _CELL_PREV_X_NEG = 4 << 5,
  229. _CELL_PREV_Z_POS = 5 << 5,
  230. _CELL_PREV_Z_NEG = 6 << 5,
  231. _CELL_PREV_FIRST = 7 << 5,
  232. };
  233. 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) {
  234. AABB aabb(Vector3(x, y, z), Vector3(len_x, len_y, len_z));
  235. aabb.position = aabb.position * voxelsize;
  236. aabb.size = aabb.size * voxelsize;
  237. if (!p_face.intersects_aabb(aabb))
  238. return;
  239. if (len_x == 1 && len_y == 1 && len_z == 1) {
  240. p_cell_status[x][y][z] = _CELL_SOLID;
  241. return;
  242. }
  243. int div_x = len_x > 1 ? 2 : 1;
  244. int div_y = len_y > 1 ? 2 : 1;
  245. int div_z = len_z > 1 ? 2 : 1;
  246. #define _SPLIT(m_i, m_div, m_v, m_len_v, m_new_v, m_new_len_v) \
  247. if (m_div == 1) { \
  248. m_new_v = m_v; \
  249. m_new_len_v = 1; \
  250. } else if (m_i == 0) { \
  251. m_new_v = m_v; \
  252. m_new_len_v = m_len_v / 2; \
  253. } else { \
  254. m_new_v = m_v + m_len_v / 2; \
  255. m_new_len_v = m_len_v - m_len_v / 2; \
  256. }
  257. int new_x;
  258. int new_len_x;
  259. int new_y;
  260. int new_len_y;
  261. int new_z;
  262. int new_len_z;
  263. for (int i = 0; i < div_x; i++) {
  264. _SPLIT(i, div_x, x, len_x, new_x, new_len_x);
  265. for (int j = 0; j < div_y; j++) {
  266. _SPLIT(j, div_y, y, len_y, new_y, new_len_y);
  267. for (int k = 0; k < div_z; k++) {
  268. _SPLIT(k, div_z, z, len_z, new_z, new_len_z);
  269. _plot_face(p_cell_status, new_x, new_y, new_z, new_len_x, new_len_y, new_len_z, voxelsize, p_face);
  270. }
  271. }
  272. }
  273. }
  274. 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) {
  275. if (p_cell_status[x][y][z] & 3)
  276. return; // Nothing to do, already used and/or visited.
  277. p_cell_status[x][y][z] = _CELL_PREV_FIRST;
  278. while (true) {
  279. uint8_t &c = p_cell_status[x][y][z];
  280. if ((c & _CELL_STEP_MASK) == _CELL_STEP_NONE) {
  281. // Haven't been in here, mark as outside.
  282. p_cell_status[x][y][z] |= _CELL_EXTERIOR;
  283. }
  284. if ((c & _CELL_STEP_MASK) != _CELL_STEP_DONE) {
  285. // If not done, increase step.
  286. c += 1 << 2;
  287. }
  288. if ((c & _CELL_STEP_MASK) == _CELL_STEP_DONE) {
  289. // Go back.
  290. switch (c & _CELL_PREV_MASK) {
  291. case _CELL_PREV_FIRST: {
  292. return;
  293. } break;
  294. case _CELL_PREV_Y_POS: {
  295. y++;
  296. ERR_FAIL_COND(y >= len_y);
  297. } break;
  298. case _CELL_PREV_Y_NEG: {
  299. y--;
  300. ERR_FAIL_COND(y < 0);
  301. } break;
  302. case _CELL_PREV_X_POS: {
  303. x++;
  304. ERR_FAIL_COND(x >= len_x);
  305. } break;
  306. case _CELL_PREV_X_NEG: {
  307. x--;
  308. ERR_FAIL_COND(x < 0);
  309. } break;
  310. case _CELL_PREV_Z_POS: {
  311. z++;
  312. ERR_FAIL_COND(z >= len_z);
  313. } break;
  314. case _CELL_PREV_Z_NEG: {
  315. z--;
  316. ERR_FAIL_COND(z < 0);
  317. } break;
  318. default: {
  319. ERR_FAIL();
  320. }
  321. }
  322. continue;
  323. }
  324. int next_x = x, next_y = y, next_z = z;
  325. uint8_t prev = 0;
  326. switch (c & _CELL_STEP_MASK) {
  327. case _CELL_STEP_Y_POS: {
  328. next_y++;
  329. prev = _CELL_PREV_Y_NEG;
  330. } break;
  331. case _CELL_STEP_Y_NEG: {
  332. next_y--;
  333. prev = _CELL_PREV_Y_POS;
  334. } break;
  335. case _CELL_STEP_X_POS: {
  336. next_x++;
  337. prev = _CELL_PREV_X_NEG;
  338. } break;
  339. case _CELL_STEP_X_NEG: {
  340. next_x--;
  341. prev = _CELL_PREV_X_POS;
  342. } break;
  343. case _CELL_STEP_Z_POS: {
  344. next_z++;
  345. prev = _CELL_PREV_Z_NEG;
  346. } break;
  347. case _CELL_STEP_Z_NEG: {
  348. next_z--;
  349. prev = _CELL_PREV_Z_POS;
  350. } break;
  351. default:
  352. ERR_FAIL();
  353. }
  354. if (next_x < 0 || next_x >= len_x)
  355. continue;
  356. if (next_y < 0 || next_y >= len_y)
  357. continue;
  358. if (next_z < 0 || next_z >= len_z)
  359. continue;
  360. if (p_cell_status[next_x][next_y][next_z] & 3)
  361. continue;
  362. x = next_x;
  363. y = next_y;
  364. z = next_z;
  365. p_cell_status[x][y][z] |= prev;
  366. }
  367. }
  368. 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) {
  369. ERR_FAIL_INDEX(x, len_x);
  370. ERR_FAIL_INDEX(y, len_y);
  371. ERR_FAIL_INDEX(z, len_z);
  372. if (p_cell_status[x][y][z] & _CELL_EXTERIOR)
  373. return;
  374. #define vert(m_idx) Vector3(((m_idx)&4) >> 2, ((m_idx)&2) >> 1, (m_idx)&1)
  375. static const uint8_t indices[6][4] = {
  376. { 7, 6, 4, 5 },
  377. { 7, 3, 2, 6 },
  378. { 7, 5, 1, 3 },
  379. { 0, 2, 3, 1 },
  380. { 0, 1, 5, 4 },
  381. { 0, 4, 6, 2 },
  382. };
  383. for (int i = 0; i < 6; i++) {
  384. Vector3 face_points[4];
  385. int disp_x = x + ((i % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  386. int disp_y = y + (((i - 1) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  387. int disp_z = z + (((i - 2) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  388. bool plot = false;
  389. if (disp_x < 0 || disp_x >= len_x)
  390. plot = true;
  391. if (disp_y < 0 || disp_y >= len_y)
  392. plot = true;
  393. if (disp_z < 0 || disp_z >= len_z)
  394. plot = true;
  395. if (!plot && (p_cell_status[disp_x][disp_y][disp_z] & _CELL_EXTERIOR))
  396. plot = true;
  397. if (!plot)
  398. continue;
  399. for (int j = 0; j < 4; j++)
  400. face_points[j] = vert(indices[i][j]) + Vector3(x, y, z);
  401. p_faces.push_back(
  402. Face3(
  403. face_points[0],
  404. face_points[1],
  405. face_points[2]));
  406. p_faces.push_back(
  407. Face3(
  408. face_points[2],
  409. face_points[3],
  410. face_points[0]));
  411. }
  412. }
  413. Vector<Face3> Geometry::wrap_geometry(Vector<Face3> p_array, real_t *p_error) {
  414. #define _MIN_SIZE 1.0
  415. #define _MAX_LENGTH 20
  416. int face_count = p_array.size();
  417. const Face3 *faces = p_array.ptr();
  418. AABB global_aabb;
  419. for (int i = 0; i < face_count; i++) {
  420. if (i == 0) {
  421. global_aabb = faces[i].get_aabb();
  422. } else {
  423. global_aabb.merge_with(faces[i].get_aabb());
  424. }
  425. }
  426. global_aabb.grow_by(0.01); // Avoid numerical error.
  427. // Determine amount of cells in grid axis.
  428. int div_x, div_y, div_z;
  429. if (global_aabb.size.x / _MIN_SIZE < _MAX_LENGTH)
  430. div_x = (int)(global_aabb.size.x / _MIN_SIZE) + 1;
  431. else
  432. div_x = _MAX_LENGTH;
  433. if (global_aabb.size.y / _MIN_SIZE < _MAX_LENGTH)
  434. div_y = (int)(global_aabb.size.y / _MIN_SIZE) + 1;
  435. else
  436. div_y = _MAX_LENGTH;
  437. if (global_aabb.size.z / _MIN_SIZE < _MAX_LENGTH)
  438. div_z = (int)(global_aabb.size.z / _MIN_SIZE) + 1;
  439. else
  440. div_z = _MAX_LENGTH;
  441. Vector3 voxelsize = global_aabb.size;
  442. voxelsize.x /= div_x;
  443. voxelsize.y /= div_y;
  444. voxelsize.z /= div_z;
  445. // Create and initialize cells to zero.
  446. uint8_t ***cell_status = memnew_arr(uint8_t **, div_x);
  447. for (int i = 0; i < div_x; i++) {
  448. cell_status[i] = memnew_arr(uint8_t *, div_y);
  449. for (int j = 0; j < div_y; j++) {
  450. cell_status[i][j] = memnew_arr(uint8_t, div_z);
  451. for (int k = 0; k < div_z; k++) {
  452. cell_status[i][j][k] = 0;
  453. }
  454. }
  455. }
  456. // Plot faces into cells.
  457. for (int i = 0; i < face_count; i++) {
  458. Face3 f = faces[i];
  459. for (int j = 0; j < 3; j++) {
  460. f.vertex[j] -= global_aabb.position;
  461. }
  462. _plot_face(cell_status, 0, 0, 0, div_x, div_y, div_z, voxelsize, f);
  463. }
  464. // Determine which cells connect to the outside by traversing the outside and recursively flood-fill marking.
  465. for (int i = 0; i < div_x; i++) {
  466. for (int j = 0; j < div_y; j++) {
  467. _mark_outside(cell_status, i, j, 0, div_x, div_y, div_z);
  468. _mark_outside(cell_status, i, j, div_z - 1, div_x, div_y, div_z);
  469. }
  470. }
  471. for (int i = 0; i < div_z; i++) {
  472. for (int j = 0; j < div_y; j++) {
  473. _mark_outside(cell_status, 0, j, i, div_x, div_y, div_z);
  474. _mark_outside(cell_status, div_x - 1, j, i, div_x, div_y, div_z);
  475. }
  476. }
  477. for (int i = 0; i < div_x; i++) {
  478. for (int j = 0; j < div_z; j++) {
  479. _mark_outside(cell_status, i, 0, j, div_x, div_y, div_z);
  480. _mark_outside(cell_status, i, div_y - 1, j, div_x, div_y, div_z);
  481. }
  482. }
  483. // Build faces for the inside-outside cell divisors.
  484. Vector<Face3> wrapped_faces;
  485. for (int i = 0; i < div_x; i++) {
  486. for (int j = 0; j < div_y; j++) {
  487. for (int k = 0; k < div_z; k++) {
  488. _build_faces(cell_status, i, j, k, div_x, div_y, div_z, wrapped_faces);
  489. }
  490. }
  491. }
  492. // Transform face vertices to global coords.
  493. int wrapped_faces_count = wrapped_faces.size();
  494. Face3 *wrapped_faces_ptr = wrapped_faces.ptrw();
  495. for (int i = 0; i < wrapped_faces_count; i++) {
  496. for (int j = 0; j < 3; j++) {
  497. Vector3 &v = wrapped_faces_ptr[i].vertex[j];
  498. v = v * voxelsize;
  499. v += global_aabb.position;
  500. }
  501. }
  502. // clean up grid
  503. for (int i = 0; i < div_x; i++) {
  504. for (int j = 0; j < div_y; j++) {
  505. memdelete_arr(cell_status[i][j]);
  506. }
  507. memdelete_arr(cell_status[i]);
  508. }
  509. memdelete_arr(cell_status);
  510. if (p_error)
  511. *p_error = voxelsize.length();
  512. return wrapped_faces;
  513. }
  514. Vector<Vector<Vector2>> Geometry::decompose_polygon_in_convex(Vector<Point2> polygon) {
  515. Vector<Vector<Vector2>> decomp;
  516. List<TriangulatorPoly> in_poly, out_poly;
  517. TriangulatorPoly inp;
  518. inp.Init(polygon.size());
  519. for (int i = 0; i < polygon.size(); i++) {
  520. inp.GetPoint(i) = polygon[i];
  521. }
  522. inp.SetOrientation(TRIANGULATOR_CCW);
  523. in_poly.push_back(inp);
  524. TriangulatorPartition tpart;
  525. if (tpart.ConvexPartition_HM(&in_poly, &out_poly) == 0) { // Failed.
  526. ERR_PRINT("Convex decomposing failed!");
  527. return decomp;
  528. }
  529. decomp.resize(out_poly.size());
  530. int idx = 0;
  531. for (List<TriangulatorPoly>::Element *I = out_poly.front(); I; I = I->next()) {
  532. TriangulatorPoly &tp = I->get();
  533. decomp.write[idx].resize(tp.GetNumPoints());
  534. for (int64_t i = 0; i < tp.GetNumPoints(); i++) {
  535. decomp.write[idx].write[i] = tp.GetPoint(i);
  536. }
  537. idx++;
  538. }
  539. return decomp;
  540. }
  541. Geometry::MeshData Geometry::build_convex_mesh(const Vector<Plane> &p_planes) {
  542. MeshData mesh;
  543. #define SUBPLANE_SIZE 1024.0
  544. real_t subplane_size = 1024.0; // Should compute this from the actual plane.
  545. for (int i = 0; i < p_planes.size(); i++) {
  546. Plane p = p_planes[i];
  547. Vector3 ref = Vector3(0.0, 1.0, 0.0);
  548. if (ABS(p.normal.dot(ref)) > 0.95)
  549. ref = Vector3(0.0, 0.0, 1.0); // Change axis.
  550. Vector3 right = p.normal.cross(ref).normalized();
  551. Vector3 up = p.normal.cross(right).normalized();
  552. Vector<Vector3> vertices;
  553. Vector3 center = p.get_any_point();
  554. // make a quad clockwise
  555. vertices.push_back(center - up * subplane_size + right * subplane_size);
  556. vertices.push_back(center - up * subplane_size - right * subplane_size);
  557. vertices.push_back(center + up * subplane_size - right * subplane_size);
  558. vertices.push_back(center + up * subplane_size + right * subplane_size);
  559. for (int j = 0; j < p_planes.size(); j++) {
  560. if (j == i)
  561. continue;
  562. Vector<Vector3> new_vertices;
  563. Plane clip = p_planes[j];
  564. if (clip.normal.dot(p.normal) > 0.95)
  565. continue;
  566. if (vertices.size() < 3)
  567. break;
  568. for (int k = 0; k < vertices.size(); k++) {
  569. int k_n = (k + 1) % vertices.size();
  570. Vector3 edge0_A = vertices[k];
  571. Vector3 edge1_A = vertices[k_n];
  572. real_t dist0 = clip.distance_to(edge0_A);
  573. real_t dist1 = clip.distance_to(edge1_A);
  574. if (dist0 <= 0) { // Behind plane.
  575. new_vertices.push_back(vertices[k]);
  576. }
  577. // Check for different sides and non coplanar.
  578. if ((dist0 * dist1) < 0) {
  579. // Calculate intersection.
  580. Vector3 rel = edge1_A - edge0_A;
  581. real_t den = clip.normal.dot(rel);
  582. if (Math::is_zero_approx(den))
  583. continue; // Point too short.
  584. real_t dist = -(clip.normal.dot(edge0_A) - clip.d) / den;
  585. Vector3 inters = edge0_A + rel * dist;
  586. new_vertices.push_back(inters);
  587. }
  588. }
  589. vertices = new_vertices;
  590. }
  591. if (vertices.size() < 3)
  592. continue;
  593. // Result is a clockwise face.
  594. MeshData::Face face;
  595. // Add face indices.
  596. for (int j = 0; j < vertices.size(); j++) {
  597. int idx = -1;
  598. for (int k = 0; k < mesh.vertices.size(); k++) {
  599. if (mesh.vertices[k].distance_to(vertices[j]) < 0.001) {
  600. idx = k;
  601. break;
  602. }
  603. }
  604. if (idx == -1) {
  605. idx = mesh.vertices.size();
  606. mesh.vertices.push_back(vertices[j]);
  607. }
  608. face.indices.push_back(idx);
  609. }
  610. face.plane = p;
  611. mesh.faces.push_back(face);
  612. // Add edge.
  613. for (int j = 0; j < face.indices.size(); j++) {
  614. int a = face.indices[j];
  615. int b = face.indices[(j + 1) % face.indices.size()];
  616. bool found = false;
  617. for (int k = 0; k < mesh.edges.size(); k++) {
  618. if (mesh.edges[k].a == a && mesh.edges[k].b == b) {
  619. found = true;
  620. break;
  621. }
  622. if (mesh.edges[k].b == a && mesh.edges[k].a == b) {
  623. found = true;
  624. break;
  625. }
  626. }
  627. if (found)
  628. continue;
  629. MeshData::Edge edge;
  630. edge.a = a;
  631. edge.b = b;
  632. mesh.edges.push_back(edge);
  633. }
  634. }
  635. return mesh;
  636. }
  637. Vector<Plane> Geometry::build_box_planes(const Vector3 &p_extents) {
  638. Vector<Plane> planes;
  639. planes.push_back(Plane(Vector3(1, 0, 0), p_extents.x));
  640. planes.push_back(Plane(Vector3(-1, 0, 0), p_extents.x));
  641. planes.push_back(Plane(Vector3(0, 1, 0), p_extents.y));
  642. planes.push_back(Plane(Vector3(0, -1, 0), p_extents.y));
  643. planes.push_back(Plane(Vector3(0, 0, 1), p_extents.z));
  644. planes.push_back(Plane(Vector3(0, 0, -1), p_extents.z));
  645. return planes;
  646. }
  647. Vector<Plane> Geometry::build_cylinder_planes(real_t p_radius, real_t p_height, int p_sides, Vector3::Axis p_axis) {
  648. Vector<Plane> planes;
  649. for (int i = 0; i < p_sides; i++) {
  650. Vector3 normal;
  651. normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_sides);
  652. normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_sides);
  653. planes.push_back(Plane(normal, p_radius));
  654. }
  655. Vector3 axis;
  656. axis[p_axis] = 1.0;
  657. planes.push_back(Plane(axis, p_height * 0.5));
  658. planes.push_back(Plane(-axis, p_height * 0.5));
  659. return planes;
  660. }
  661. Vector<Plane> Geometry::build_sphere_planes(real_t p_radius, int p_lats, int p_lons, Vector3::Axis p_axis) {
  662. Vector<Plane> planes;
  663. Vector3 axis;
  664. axis[p_axis] = 1.0;
  665. Vector3 axis_neg;
  666. axis_neg[(p_axis + 1) % 3] = 1.0;
  667. axis_neg[(p_axis + 2) % 3] = 1.0;
  668. axis_neg[p_axis] = -1.0;
  669. for (int i = 0; i < p_lons; i++) {
  670. Vector3 normal;
  671. normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_lons);
  672. normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_lons);
  673. planes.push_back(Plane(normal, p_radius));
  674. for (int j = 1; j <= p_lats; j++) {
  675. // FIXME: This is stupid.
  676. Vector3 angle = normal.lerp(axis, j / (real_t)p_lats).normalized();
  677. Vector3 pos = angle * p_radius;
  678. planes.push_back(Plane(pos, angle));
  679. planes.push_back(Plane(pos * axis_neg, angle * axis_neg));
  680. }
  681. }
  682. return planes;
  683. }
  684. Vector<Plane> Geometry::build_capsule_planes(real_t p_radius, real_t p_height, int p_sides, int p_lats, Vector3::Axis p_axis) {
  685. Vector<Plane> planes;
  686. Vector3 axis;
  687. axis[p_axis] = 1.0;
  688. Vector3 axis_neg;
  689. axis_neg[(p_axis + 1) % 3] = 1.0;
  690. axis_neg[(p_axis + 2) % 3] = 1.0;
  691. axis_neg[p_axis] = -1.0;
  692. for (int i = 0; i < p_sides; i++) {
  693. Vector3 normal;
  694. normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_sides);
  695. normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_sides);
  696. planes.push_back(Plane(normal, p_radius));
  697. for (int j = 1; j <= p_lats; j++) {
  698. Vector3 angle = normal.lerp(axis, j / (real_t)p_lats).normalized();
  699. Vector3 pos = axis * p_height * 0.5 + angle * p_radius;
  700. planes.push_back(Plane(pos, angle));
  701. planes.push_back(Plane(pos * axis_neg, angle * axis_neg));
  702. }
  703. }
  704. return planes;
  705. }
  706. struct _AtlasWorkRect {
  707. Size2i s;
  708. Point2i p;
  709. int idx;
  710. _FORCE_INLINE_ bool operator<(const _AtlasWorkRect &p_r) const { return s.width > p_r.s.width; };
  711. };
  712. struct _AtlasWorkRectResult {
  713. Vector<_AtlasWorkRect> result;
  714. int max_w;
  715. int max_h;
  716. };
  717. void Geometry::make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size) {
  718. // Super simple, almost brute force scanline stacking fitter.
  719. // It's pretty basic for now, but it tries to make sure that the aspect ratio of the
  720. // resulting atlas is somehow square. This is necessary because video cards have limits.
  721. // On texture size (usually 2048 or 4096), so the more square a texture, the more chances.
  722. // It will work in every hardware.
  723. // For example, it will prioritize a 1024x1024 atlas (works everywhere) instead of a
  724. // 256x8192 atlas (won't work anywhere).
  725. ERR_FAIL_COND(p_rects.size() == 0);
  726. Vector<_AtlasWorkRect> wrects;
  727. wrects.resize(p_rects.size());
  728. for (int i = 0; i < p_rects.size(); i++) {
  729. wrects.write[i].s = p_rects[i];
  730. wrects.write[i].idx = i;
  731. }
  732. wrects.sort();
  733. int widest = wrects[0].s.width;
  734. Vector<_AtlasWorkRectResult> results;
  735. for (int i = 0; i <= 12; i++) {
  736. int w = 1 << i;
  737. int max_h = 0;
  738. int max_w = 0;
  739. if (w < widest)
  740. continue;
  741. Vector<int> hmax;
  742. hmax.resize(w);
  743. for (int j = 0; j < w; j++)
  744. hmax.write[j] = 0;
  745. // Place them.
  746. int ofs = 0;
  747. int limit_h = 0;
  748. for (int j = 0; j < wrects.size(); j++) {
  749. if (ofs + wrects[j].s.width > w) {
  750. ofs = 0;
  751. }
  752. int from_y = 0;
  753. for (int k = 0; k < wrects[j].s.width; k++) {
  754. if (hmax[ofs + k] > from_y)
  755. from_y = hmax[ofs + k];
  756. }
  757. wrects.write[j].p.x = ofs;
  758. wrects.write[j].p.y = from_y;
  759. int end_h = from_y + wrects[j].s.height;
  760. int end_w = ofs + wrects[j].s.width;
  761. if (ofs == 0)
  762. limit_h = end_h;
  763. for (int k = 0; k < wrects[j].s.width; k++) {
  764. hmax.write[ofs + k] = end_h;
  765. }
  766. if (end_h > max_h)
  767. max_h = end_h;
  768. if (end_w > max_w)
  769. max_w = end_w;
  770. if (ofs == 0 || end_h > limit_h) // While h limit not reached, keep stacking.
  771. ofs += wrects[j].s.width;
  772. }
  773. _AtlasWorkRectResult result;
  774. result.result = wrects;
  775. result.max_h = max_h;
  776. result.max_w = max_w;
  777. results.push_back(result);
  778. }
  779. // Find the result with the best aspect ratio.
  780. int best = -1;
  781. real_t best_aspect = 1e20;
  782. for (int i = 0; i < results.size(); i++) {
  783. real_t h = next_power_of_2(results[i].max_h);
  784. real_t w = next_power_of_2(results[i].max_w);
  785. real_t aspect = h > w ? h / w : w / h;
  786. if (aspect < best_aspect) {
  787. best = i;
  788. best_aspect = aspect;
  789. }
  790. }
  791. r_result.resize(p_rects.size());
  792. for (int i = 0; i < p_rects.size(); i++) {
  793. r_result.write[results[best].result[i].idx] = results[best].result[i].p;
  794. }
  795. r_size = Size2(results[best].max_w, results[best].max_h);
  796. }
  797. 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) {
  798. using namespace ClipperLib;
  799. ClipType op = ctUnion;
  800. switch (p_op) {
  801. case OPERATION_UNION:
  802. op = ctUnion;
  803. break;
  804. case OPERATION_DIFFERENCE:
  805. op = ctDifference;
  806. break;
  807. case OPERATION_INTERSECTION:
  808. op = ctIntersection;
  809. break;
  810. case OPERATION_XOR:
  811. op = ctXor;
  812. break;
  813. }
  814. Path path_a, path_b;
  815. // Need to scale points (Clipper's requirement for robust computation).
  816. for (int i = 0; i != p_polypath_a.size(); ++i) {
  817. path_a << IntPoint(p_polypath_a[i].x * SCALE_FACTOR, p_polypath_a[i].y * SCALE_FACTOR);
  818. }
  819. for (int i = 0; i != p_polypath_b.size(); ++i) {
  820. path_b << IntPoint(p_polypath_b[i].x * SCALE_FACTOR, p_polypath_b[i].y * SCALE_FACTOR);
  821. }
  822. Clipper clp;
  823. clp.AddPath(path_a, ptSubject, !is_a_open); // Forward compatible with Clipper 10.0.0.
  824. clp.AddPath(path_b, ptClip, true); // Polylines cannot be set as clip.
  825. Paths paths;
  826. if (is_a_open) {
  827. PolyTree tree; // Needed to populate polylines.
  828. clp.Execute(op, tree);
  829. OpenPathsFromPolyTree(tree, paths);
  830. } else {
  831. clp.Execute(op, paths); // Works on closed polygons only.
  832. }
  833. // Have to scale points down now.
  834. Vector<Vector<Point2>> polypaths;
  835. for (Paths::size_type i = 0; i < paths.size(); ++i) {
  836. Vector<Vector2> polypath;
  837. const Path &scaled_path = paths[i];
  838. for (Paths::size_type j = 0; j < scaled_path.size(); ++j) {
  839. polypath.push_back(Point2(
  840. static_cast<real_t>(scaled_path[j].X) / SCALE_FACTOR,
  841. static_cast<real_t>(scaled_path[j].Y) / SCALE_FACTOR));
  842. }
  843. polypaths.push_back(polypath);
  844. }
  845. return polypaths;
  846. }
  847. Vector<Vector<Point2>> Geometry::_polypath_offset(const Vector<Point2> &p_polypath, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) {
  848. using namespace ClipperLib;
  849. JoinType jt = jtSquare;
  850. switch (p_join_type) {
  851. case JOIN_SQUARE:
  852. jt = jtSquare;
  853. break;
  854. case JOIN_ROUND:
  855. jt = jtRound;
  856. break;
  857. case JOIN_MITER:
  858. jt = jtMiter;
  859. break;
  860. }
  861. EndType et = etClosedPolygon;
  862. switch (p_end_type) {
  863. case END_POLYGON:
  864. et = etClosedPolygon;
  865. break;
  866. case END_JOINED:
  867. et = etClosedLine;
  868. break;
  869. case END_BUTT:
  870. et = etOpenButt;
  871. break;
  872. case END_SQUARE:
  873. et = etOpenSquare;
  874. break;
  875. case END_ROUND:
  876. et = etOpenRound;
  877. break;
  878. }
  879. ClipperOffset co(2.0, 0.25 * SCALE_FACTOR); // Defaults from ClipperOffset.
  880. Path path;
  881. // Need to scale points (Clipper's requirement for robust computation).
  882. for (int i = 0; i != p_polypath.size(); ++i) {
  883. path << IntPoint(p_polypath[i].x * SCALE_FACTOR, p_polypath[i].y * SCALE_FACTOR);
  884. }
  885. co.AddPath(path, jt, et);
  886. Paths paths;
  887. co.Execute(paths, p_delta * SCALE_FACTOR); // Inflate/deflate.
  888. // Have to scale points down now.
  889. Vector<Vector<Point2>> polypaths;
  890. for (Paths::size_type i = 0; i < paths.size(); ++i) {
  891. Vector<Vector2> polypath;
  892. const Path &scaled_path = paths[i];
  893. for (Paths::size_type j = 0; j < scaled_path.size(); ++j) {
  894. polypath.push_back(Point2(
  895. static_cast<real_t>(scaled_path[j].X) / SCALE_FACTOR,
  896. static_cast<real_t>(scaled_path[j].Y) / SCALE_FACTOR));
  897. }
  898. polypaths.push_back(polypath);
  899. }
  900. return polypaths;
  901. }
  902. Vector<Vector3> Geometry::compute_convex_mesh_points(const Plane *p_planes, int p_plane_count) {
  903. Vector<Vector3> points;
  904. // Iterate through every unique combination of any three planes.
  905. for (int i = p_plane_count - 1; i >= 0; i--) {
  906. for (int j = i - 1; j >= 0; j--) {
  907. for (int k = j - 1; k >= 0; k--) {
  908. // Find the point where these planes all cross over (if they
  909. // do at all).
  910. Vector3 convex_shape_point;
  911. if (p_planes[i].intersect_3(p_planes[j], p_planes[k], &convex_shape_point)) {
  912. // See if any *other* plane excludes this point because it's
  913. // on the wrong side.
  914. bool excluded = false;
  915. for (int n = 0; n < p_plane_count; n++) {
  916. if (n != i && n != j && n != k) {
  917. real_t dp = p_planes[n].normal.dot(convex_shape_point);
  918. if (dp - p_planes[n].d > CMP_EPSILON) {
  919. excluded = true;
  920. break;
  921. }
  922. }
  923. }
  924. // Only add the point if it passed all tests.
  925. if (!excluded) {
  926. points.push_back(convex_shape_point);
  927. }
  928. }
  929. }
  930. }
  931. }
  932. return points;
  933. }
  934. Vector<Point2i> Geometry::pack_rects(const Vector<Size2i> &p_sizes, const Size2i &p_atlas_size) {
  935. Vector<stbrp_node> nodes;
  936. nodes.resize(p_atlas_size.width);
  937. stbrp_context context;
  938. stbrp_init_target(&context, p_atlas_size.width, p_atlas_size.height, nodes.ptrw(), p_atlas_size.width);
  939. Vector<stbrp_rect> rects;
  940. rects.resize(p_sizes.size());
  941. for (int i = 0; i < p_sizes.size(); i++) {
  942. rects.write[i].id = 0;
  943. rects.write[i].w = p_sizes[i].width;
  944. rects.write[i].h = p_sizes[i].height;
  945. rects.write[i].x = 0;
  946. rects.write[i].y = 0;
  947. rects.write[i].was_packed = 0;
  948. }
  949. int res = stbrp_pack_rects(&context, rects.ptrw(), rects.size());
  950. if (res == 0) { //pack failed
  951. return Vector<Point2i>();
  952. }
  953. Vector<Point2i> ret;
  954. ret.resize(p_sizes.size());
  955. for (int i = 0; i < p_sizes.size(); i++) {
  956. Point2i r(rects[i].x, rects[i].y);
  957. ret.write[i] = r;
  958. }
  959. return ret;
  960. }
  961. Vector<Vector3i> Geometry::partial_pack_rects(const Vector<Vector2i> &p_sizes, const Size2i &p_atlas_size) {
  962. Vector<stbrp_node> nodes;
  963. nodes.resize(p_atlas_size.width);
  964. zeromem(nodes.ptrw(), sizeof(stbrp_node) * nodes.size());
  965. stbrp_context context;
  966. stbrp_init_target(&context, p_atlas_size.width, p_atlas_size.height, nodes.ptrw(), p_atlas_size.width);
  967. Vector<stbrp_rect> rects;
  968. rects.resize(p_sizes.size());
  969. for (int i = 0; i < p_sizes.size(); i++) {
  970. rects.write[i].id = i;
  971. rects.write[i].w = p_sizes[i].width;
  972. rects.write[i].h = p_sizes[i].height;
  973. rects.write[i].x = 0;
  974. rects.write[i].y = 0;
  975. rects.write[i].was_packed = 0;
  976. }
  977. stbrp_pack_rects(&context, rects.ptrw(), rects.size());
  978. Vector<Vector3i> ret;
  979. ret.resize(p_sizes.size());
  980. for (int i = 0; i < p_sizes.size(); i++) {
  981. ret.write[rects[i].id] = Vector3i(rects[i].x, rects[i].y, rects[i].was_packed != 0 ? 1 : 0);
  982. }
  983. return ret;
  984. }
  985. #define square(m_s) ((m_s) * (m_s))
  986. #define INF 1e20
  987. /* dt of 1d function using squared distance */
  988. static void edt(float *f, int stride, int n) {
  989. float *d = (float *)alloca(sizeof(float) * n + sizeof(int) * n + sizeof(float) * (n + 1));
  990. int *v = (int *)&(d[n]);
  991. float *z = (float *)&v[n];
  992. int k = 0;
  993. v[0] = 0;
  994. z[0] = -INF;
  995. z[1] = +INF;
  996. for (int q = 1; q <= n - 1; q++) {
  997. float s = ((f[q * stride] + square(q)) - (f[v[k] * stride] + square(v[k]))) / (2 * q - 2 * v[k]);
  998. while (s <= z[k]) {
  999. k--;
  1000. s = ((f[q * stride] + square(q)) - (f[v[k] * stride] + square(v[k]))) / (2 * q - 2 * v[k]);
  1001. }
  1002. k++;
  1003. v[k] = q;
  1004. z[k] = s;
  1005. z[k + 1] = +INF;
  1006. }
  1007. k = 0;
  1008. for (int q = 0; q <= n - 1; q++) {
  1009. while (z[k + 1] < q)
  1010. k++;
  1011. d[q] = square(q - v[k]) + f[v[k] * stride];
  1012. }
  1013. for (int i = 0; i < n; i++) {
  1014. f[i * stride] = d[i];
  1015. }
  1016. }
  1017. #undef square
  1018. Vector<uint32_t> Geometry::generate_edf(const Vector<bool> &p_voxels, const Vector3i &p_size, bool p_negative) {
  1019. uint32_t float_count = p_size.x * p_size.y * p_size.z;
  1020. ERR_FAIL_COND_V((uint32_t)p_voxels.size() != float_count, Vector<uint32_t>());
  1021. float *work_memory = memnew_arr(float, float_count);
  1022. for (uint32_t i = 0; i < float_count; i++) {
  1023. work_memory[i] = INF;
  1024. }
  1025. uint32_t y_mult = p_size.x;
  1026. uint32_t z_mult = y_mult * p_size.y;
  1027. //plot solid cells
  1028. {
  1029. const bool *voxr = p_voxels.ptr();
  1030. for (uint32_t i = 0; i < float_count; i++) {
  1031. bool plot = voxr[i];
  1032. if (p_negative) {
  1033. plot = !plot;
  1034. }
  1035. if (plot) {
  1036. work_memory[i] = 0;
  1037. }
  1038. }
  1039. }
  1040. //process in each direction
  1041. //xy->z
  1042. for (int i = 0; i < p_size.x; i++) {
  1043. for (int j = 0; j < p_size.y; j++) {
  1044. edt(&work_memory[i + j * y_mult], z_mult, p_size.z);
  1045. }
  1046. }
  1047. //xz->y
  1048. for (int i = 0; i < p_size.x; i++) {
  1049. for (int j = 0; j < p_size.z; j++) {
  1050. edt(&work_memory[i + j * z_mult], y_mult, p_size.y);
  1051. }
  1052. }
  1053. //yz->x
  1054. for (int i = 0; i < p_size.y; i++) {
  1055. for (int j = 0; j < p_size.z; j++) {
  1056. edt(&work_memory[i * y_mult + j * z_mult], 1, p_size.x);
  1057. }
  1058. }
  1059. Vector<uint32_t> ret;
  1060. ret.resize(float_count);
  1061. {
  1062. uint32_t *w = ret.ptrw();
  1063. for (uint32_t i = 0; i < float_count; i++) {
  1064. w[i] = uint32_t(Math::sqrt(work_memory[i]));
  1065. }
  1066. }
  1067. return ret;
  1068. }
  1069. Vector<int8_t> Geometry::generate_sdf8(const Vector<uint32_t> &p_positive, const Vector<uint32_t> &p_negative) {
  1070. ERR_FAIL_COND_V(p_positive.size() != p_negative.size(), Vector<int8_t>());
  1071. Vector<int8_t> sdf8;
  1072. int s = p_positive.size();
  1073. sdf8.resize(s);
  1074. const uint32_t *rpos = p_positive.ptr();
  1075. const uint32_t *rneg = p_negative.ptr();
  1076. int8_t *wsdf = sdf8.ptrw();
  1077. for (int i = 0; i < s; i++) {
  1078. int32_t diff = int32_t(rpos[i]) - int32_t(rneg[i]);
  1079. wsdf[i] = CLAMP(diff, -128, 127);
  1080. }
  1081. return sdf8;
  1082. }