2
0

geometry.cpp 34 KB

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