geometry_3d.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  1. /*************************************************************************/
  2. /* geometry_3d.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 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_3d.h"
  31. #include "thirdparty/misc/clipper.hpp"
  32. #include "thirdparty/misc/polypartition.h"
  33. void Geometry3D::get_closest_points_between_segments(const Vector3 &p_p0, const Vector3 &p_p1, const Vector3 &p_q0, const Vector3 &p_q1, Vector3 &r_ps, Vector3 &r_qt) {
  34. // Based on David Eberly's Computation of Distance Between Line Segments algorithm.
  35. Vector3 p = p_p1 - p_p0;
  36. Vector3 q = p_q1 - p_q0;
  37. Vector3 r = p_p0 - p_q0;
  38. real_t a = p.dot(p);
  39. real_t b = p.dot(q);
  40. real_t c = q.dot(q);
  41. real_t d = p.dot(r);
  42. real_t e = q.dot(r);
  43. real_t s = 0.0f;
  44. real_t t = 0.0f;
  45. real_t det = a * c - b * b;
  46. if (det > CMP_EPSILON) {
  47. // Non-parallel segments
  48. real_t bte = b * e;
  49. real_t ctd = c * d;
  50. if (bte <= ctd) {
  51. // s <= 0.0f
  52. if (e <= 0.0f) {
  53. // t <= 0.0f
  54. s = (-d >= a ? 1 : (-d > 0.0f ? -d / a : 0.0f));
  55. t = 0.0f;
  56. } else if (e < c) {
  57. // 0.0f < t < 1
  58. s = 0.0f;
  59. t = e / c;
  60. } else {
  61. // t >= 1
  62. s = (b - d >= a ? 1 : (b - d > 0.0f ? (b - d) / a : 0.0f));
  63. t = 1;
  64. }
  65. } else {
  66. // s > 0.0f
  67. s = bte - ctd;
  68. if (s >= det) {
  69. // s >= 1
  70. if (b + e <= 0.0f) {
  71. // t <= 0.0f
  72. s = (-d <= 0.0f ? 0.0f : (-d < a ? -d / a : 1));
  73. t = 0.0f;
  74. } else if (b + e < c) {
  75. // 0.0f < t < 1
  76. s = 1;
  77. t = (b + e) / c;
  78. } else {
  79. // t >= 1
  80. s = (b - d <= 0.0f ? 0.0f : (b - d < a ? (b - d) / a : 1));
  81. t = 1;
  82. }
  83. } else {
  84. // 0.0f < s < 1
  85. real_t ate = a * e;
  86. real_t btd = b * d;
  87. if (ate <= btd) {
  88. // t <= 0.0f
  89. s = (-d <= 0.0f ? 0.0f : (-d >= a ? 1 : -d / a));
  90. t = 0.0f;
  91. } else {
  92. // t > 0.0f
  93. t = ate - btd;
  94. if (t >= det) {
  95. // t >= 1
  96. s = (b - d <= 0.0f ? 0.0f : (b - d >= a ? 1 : (b - d) / a));
  97. t = 1;
  98. } else {
  99. // 0.0f < t < 1
  100. s /= det;
  101. t /= det;
  102. }
  103. }
  104. }
  105. }
  106. } else {
  107. // Parallel segments
  108. if (e <= 0.0f) {
  109. s = (-d <= 0.0f ? 0.0f : (-d >= a ? 1 : -d / a));
  110. t = 0.0f;
  111. } else if (e >= c) {
  112. s = (b - d <= 0.0f ? 0.0f : (b - d >= a ? 1 : (b - d) / a));
  113. t = 1;
  114. } else {
  115. s = 0.0f;
  116. t = e / c;
  117. }
  118. }
  119. r_ps = (1 - s) * p_p0 + s * p_p1;
  120. r_qt = (1 - t) * p_q0 + t * p_q1;
  121. }
  122. real_t Geometry3D::get_closest_distance_between_segments(const Vector3 &p_p0, const Vector3 &p_p1, const Vector3 &p_q0, const Vector3 &p_q1) {
  123. Vector3 ps;
  124. Vector3 qt;
  125. get_closest_points_between_segments(p_p0, p_p1, p_q0, p_q1, ps, qt);
  126. Vector3 st = qt - ps;
  127. return st.length();
  128. }
  129. void Geometry3D::MeshData::optimize_vertices() {
  130. HashMap<int, int> vtx_remap;
  131. for (uint32_t i = 0; i < faces.size(); i++) {
  132. for (uint32_t j = 0; j < faces[i].indices.size(); j++) {
  133. int idx = faces[i].indices[j];
  134. if (!vtx_remap.has(idx)) {
  135. int ni = vtx_remap.size();
  136. vtx_remap[idx] = ni;
  137. }
  138. faces[i].indices[j] = vtx_remap[idx];
  139. }
  140. }
  141. for (uint32_t i = 0; i < edges.size(); i++) {
  142. int a = edges[i].vertex_a;
  143. int b = edges[i].vertex_b;
  144. if (!vtx_remap.has(a)) {
  145. int ni = vtx_remap.size();
  146. vtx_remap[a] = ni;
  147. }
  148. if (!vtx_remap.has(b)) {
  149. int ni = vtx_remap.size();
  150. vtx_remap[b] = ni;
  151. }
  152. edges[i].vertex_a = vtx_remap[a];
  153. edges[i].vertex_b = vtx_remap[b];
  154. }
  155. LocalVector<Vector3> new_vertices;
  156. new_vertices.resize(vtx_remap.size());
  157. for (uint32_t i = 0; i < vertices.size(); i++) {
  158. if (vtx_remap.has(i)) {
  159. new_vertices[vtx_remap[i]] = vertices[i];
  160. }
  161. }
  162. vertices = new_vertices;
  163. }
  164. struct _FaceClassify {
  165. struct _Link {
  166. int face = -1;
  167. int edge = -1;
  168. void clear() {
  169. face = -1;
  170. edge = -1;
  171. }
  172. _Link() {}
  173. };
  174. bool valid = false;
  175. int group = -1;
  176. _Link links[3];
  177. Face3 face;
  178. _FaceClassify() {}
  179. };
  180. static bool _connect_faces(_FaceClassify *p_faces, int len, int p_group) {
  181. // Connect faces, error will occur if an edge is shared between more than 2 faces.
  182. // Clear connections.
  183. bool error = false;
  184. for (int i = 0; i < len; i++) {
  185. for (int j = 0; j < 3; j++) {
  186. p_faces[i].links[j].clear();
  187. }
  188. }
  189. for (int i = 0; i < len; i++) {
  190. if (p_faces[i].group != p_group) {
  191. continue;
  192. }
  193. for (int j = i + 1; j < len; j++) {
  194. if (p_faces[j].group != p_group) {
  195. continue;
  196. }
  197. for (int k = 0; k < 3; k++) {
  198. Vector3 vi1 = p_faces[i].face.vertex[k];
  199. Vector3 vi2 = p_faces[i].face.vertex[(k + 1) % 3];
  200. for (int l = 0; l < 3; l++) {
  201. Vector3 vj2 = p_faces[j].face.vertex[l];
  202. Vector3 vj1 = p_faces[j].face.vertex[(l + 1) % 3];
  203. if (vi1.distance_to(vj1) < 0.00001f &&
  204. vi2.distance_to(vj2) < 0.00001f) {
  205. if (p_faces[i].links[k].face != -1) {
  206. ERR_PRINT("already linked\n");
  207. error = true;
  208. break;
  209. }
  210. if (p_faces[j].links[l].face != -1) {
  211. ERR_PRINT("already linked\n");
  212. error = true;
  213. break;
  214. }
  215. p_faces[i].links[k].face = j;
  216. p_faces[i].links[k].edge = l;
  217. p_faces[j].links[l].face = i;
  218. p_faces[j].links[l].edge = k;
  219. }
  220. }
  221. if (error) {
  222. break;
  223. }
  224. }
  225. if (error) {
  226. break;
  227. }
  228. }
  229. if (error) {
  230. break;
  231. }
  232. }
  233. for (int i = 0; i < len; i++) {
  234. p_faces[i].valid = true;
  235. for (int j = 0; j < 3; j++) {
  236. if (p_faces[i].links[j].face == -1) {
  237. p_faces[i].valid = false;
  238. }
  239. }
  240. }
  241. return error;
  242. }
  243. static bool _group_face(_FaceClassify *p_faces, int len, int p_index, int p_group) {
  244. if (p_faces[p_index].group >= 0) {
  245. return false;
  246. }
  247. p_faces[p_index].group = p_group;
  248. for (int i = 0; i < 3; i++) {
  249. ERR_FAIL_INDEX_V(p_faces[p_index].links[i].face, len, true);
  250. _group_face(p_faces, len, p_faces[p_index].links[i].face, p_group);
  251. }
  252. return true;
  253. }
  254. Vector<Vector<Face3>> Geometry3D::separate_objects(Vector<Face3> p_array) {
  255. Vector<Vector<Face3>> objects;
  256. int len = p_array.size();
  257. const Face3 *arrayptr = p_array.ptr();
  258. Vector<_FaceClassify> fc;
  259. fc.resize(len);
  260. _FaceClassify *_fcptr = fc.ptrw();
  261. for (int i = 0; i < len; i++) {
  262. _fcptr[i].face = arrayptr[i];
  263. }
  264. bool error = _connect_faces(_fcptr, len, -1);
  265. ERR_FAIL_COND_V_MSG(error, Vector<Vector<Face3>>(), "Invalid geometry.");
  266. // Group connected faces in separate objects.
  267. int group = 0;
  268. for (int i = 0; i < len; i++) {
  269. if (!_fcptr[i].valid) {
  270. continue;
  271. }
  272. if (_group_face(_fcptr, len, i, group)) {
  273. group++;
  274. }
  275. }
  276. // Group connected faces in separate objects.
  277. for (int i = 0; i < len; i++) {
  278. _fcptr[i].face = arrayptr[i];
  279. }
  280. if (group >= 0) {
  281. objects.resize(group);
  282. Vector<Face3> *group_faces = objects.ptrw();
  283. for (int i = 0; i < len; i++) {
  284. if (!_fcptr[i].valid) {
  285. continue;
  286. }
  287. if (_fcptr[i].group >= 0 && _fcptr[i].group < group) {
  288. group_faces[_fcptr[i].group].push_back(_fcptr[i].face);
  289. }
  290. }
  291. }
  292. return objects;
  293. }
  294. /*** GEOMETRY WRAPPER ***/
  295. enum _CellFlags {
  296. _CELL_SOLID = 1,
  297. _CELL_EXTERIOR = 2,
  298. _CELL_STEP_MASK = 0x1C,
  299. _CELL_STEP_NONE = 0 << 2,
  300. _CELL_STEP_Y_POS = 1 << 2,
  301. _CELL_STEP_Y_NEG = 2 << 2,
  302. _CELL_STEP_X_POS = 3 << 2,
  303. _CELL_STEP_X_NEG = 4 << 2,
  304. _CELL_STEP_Z_POS = 5 << 2,
  305. _CELL_STEP_Z_NEG = 6 << 2,
  306. _CELL_STEP_DONE = 7 << 2,
  307. _CELL_PREV_MASK = 0xE0,
  308. _CELL_PREV_NONE = 0 << 5,
  309. _CELL_PREV_Y_POS = 1 << 5,
  310. _CELL_PREV_Y_NEG = 2 << 5,
  311. _CELL_PREV_X_POS = 3 << 5,
  312. _CELL_PREV_X_NEG = 4 << 5,
  313. _CELL_PREV_Z_POS = 5 << 5,
  314. _CELL_PREV_Z_NEG = 6 << 5,
  315. _CELL_PREV_FIRST = 7 << 5,
  316. };
  317. 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) {
  318. AABB aabb(Vector3(x, y, z), Vector3(len_x, len_y, len_z));
  319. aabb.position = aabb.position * voxelsize;
  320. aabb.size = aabb.size * voxelsize;
  321. if (!p_face.intersects_aabb(aabb)) {
  322. return;
  323. }
  324. if (len_x == 1 && len_y == 1 && len_z == 1) {
  325. p_cell_status[x][y][z] = _CELL_SOLID;
  326. return;
  327. }
  328. int div_x = len_x > 1 ? 2 : 1;
  329. int div_y = len_y > 1 ? 2 : 1;
  330. int div_z = len_z > 1 ? 2 : 1;
  331. #define SPLIT_DIV(m_i, m_div, m_v, m_len_v, m_new_v, m_new_len_v) \
  332. if (m_div == 1) { \
  333. m_new_v = m_v; \
  334. m_new_len_v = 1; \
  335. } else if (m_i == 0) { \
  336. m_new_v = m_v; \
  337. m_new_len_v = m_len_v / 2; \
  338. } else { \
  339. m_new_v = m_v + m_len_v / 2; \
  340. m_new_len_v = m_len_v - m_len_v / 2; \
  341. }
  342. int new_x;
  343. int new_len_x;
  344. int new_y;
  345. int new_len_y;
  346. int new_z;
  347. int new_len_z;
  348. for (int i = 0; i < div_x; i++) {
  349. SPLIT_DIV(i, div_x, x, len_x, new_x, new_len_x);
  350. for (int j = 0; j < div_y; j++) {
  351. SPLIT_DIV(j, div_y, y, len_y, new_y, new_len_y);
  352. for (int k = 0; k < div_z; k++) {
  353. SPLIT_DIV(k, div_z, z, len_z, new_z, new_len_z);
  354. _plot_face(p_cell_status, new_x, new_y, new_z, new_len_x, new_len_y, new_len_z, voxelsize, p_face);
  355. }
  356. }
  357. }
  358. #undef SPLIT_DIV
  359. }
  360. 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) {
  361. if (p_cell_status[x][y][z] & 3) {
  362. return; // Nothing to do, already used and/or visited.
  363. }
  364. p_cell_status[x][y][z] = _CELL_PREV_FIRST;
  365. while (true) {
  366. uint8_t &c = p_cell_status[x][y][z];
  367. if ((c & _CELL_STEP_MASK) == _CELL_STEP_NONE) {
  368. // Haven't been in here, mark as outside.
  369. p_cell_status[x][y][z] |= _CELL_EXTERIOR;
  370. }
  371. if ((c & _CELL_STEP_MASK) != _CELL_STEP_DONE) {
  372. // If not done, increase step.
  373. c += 1 << 2;
  374. }
  375. if ((c & _CELL_STEP_MASK) == _CELL_STEP_DONE) {
  376. // Go back.
  377. switch (c & _CELL_PREV_MASK) {
  378. case _CELL_PREV_FIRST: {
  379. return;
  380. } break;
  381. case _CELL_PREV_Y_POS: {
  382. y++;
  383. ERR_FAIL_COND(y >= len_y);
  384. } break;
  385. case _CELL_PREV_Y_NEG: {
  386. y--;
  387. ERR_FAIL_COND(y < 0);
  388. } break;
  389. case _CELL_PREV_X_POS: {
  390. x++;
  391. ERR_FAIL_COND(x >= len_x);
  392. } break;
  393. case _CELL_PREV_X_NEG: {
  394. x--;
  395. ERR_FAIL_COND(x < 0);
  396. } break;
  397. case _CELL_PREV_Z_POS: {
  398. z++;
  399. ERR_FAIL_COND(z >= len_z);
  400. } break;
  401. case _CELL_PREV_Z_NEG: {
  402. z--;
  403. ERR_FAIL_COND(z < 0);
  404. } break;
  405. default: {
  406. ERR_FAIL();
  407. }
  408. }
  409. continue;
  410. }
  411. int next_x = x, next_y = y, next_z = z;
  412. uint8_t prev = 0;
  413. switch (c & _CELL_STEP_MASK) {
  414. case _CELL_STEP_Y_POS: {
  415. next_y++;
  416. prev = _CELL_PREV_Y_NEG;
  417. } break;
  418. case _CELL_STEP_Y_NEG: {
  419. next_y--;
  420. prev = _CELL_PREV_Y_POS;
  421. } break;
  422. case _CELL_STEP_X_POS: {
  423. next_x++;
  424. prev = _CELL_PREV_X_NEG;
  425. } break;
  426. case _CELL_STEP_X_NEG: {
  427. next_x--;
  428. prev = _CELL_PREV_X_POS;
  429. } break;
  430. case _CELL_STEP_Z_POS: {
  431. next_z++;
  432. prev = _CELL_PREV_Z_NEG;
  433. } break;
  434. case _CELL_STEP_Z_NEG: {
  435. next_z--;
  436. prev = _CELL_PREV_Z_POS;
  437. } break;
  438. default:
  439. ERR_FAIL();
  440. }
  441. if (next_x < 0 || next_x >= len_x) {
  442. continue;
  443. }
  444. if (next_y < 0 || next_y >= len_y) {
  445. continue;
  446. }
  447. if (next_z < 0 || next_z >= len_z) {
  448. continue;
  449. }
  450. if (p_cell_status[next_x][next_y][next_z] & 3) {
  451. continue;
  452. }
  453. x = next_x;
  454. y = next_y;
  455. z = next_z;
  456. p_cell_status[x][y][z] |= prev;
  457. }
  458. }
  459. 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) {
  460. ERR_FAIL_INDEX(x, len_x);
  461. ERR_FAIL_INDEX(y, len_y);
  462. ERR_FAIL_INDEX(z, len_z);
  463. if (p_cell_status[x][y][z] & _CELL_EXTERIOR) {
  464. return;
  465. }
  466. #define vert(m_idx) Vector3(((m_idx)&4) >> 2, ((m_idx)&2) >> 1, (m_idx)&1)
  467. static const uint8_t indices[6][4] = {
  468. { 7, 6, 4, 5 },
  469. { 7, 3, 2, 6 },
  470. { 7, 5, 1, 3 },
  471. { 0, 2, 3, 1 },
  472. { 0, 1, 5, 4 },
  473. { 0, 4, 6, 2 },
  474. };
  475. for (int i = 0; i < 6; i++) {
  476. Vector3 face_points[4];
  477. int disp_x = x + ((i % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  478. int disp_y = y + (((i - 1) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  479. int disp_z = z + (((i - 2) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  480. bool plot = false;
  481. if (disp_x < 0 || disp_x >= len_x) {
  482. plot = true;
  483. }
  484. if (disp_y < 0 || disp_y >= len_y) {
  485. plot = true;
  486. }
  487. if (disp_z < 0 || disp_z >= len_z) {
  488. plot = true;
  489. }
  490. if (!plot && (p_cell_status[disp_x][disp_y][disp_z] & _CELL_EXTERIOR)) {
  491. plot = true;
  492. }
  493. if (!plot) {
  494. continue;
  495. }
  496. for (int j = 0; j < 4; j++) {
  497. face_points[j] = vert(indices[i][j]) + Vector3(x, y, z);
  498. }
  499. p_faces.push_back(
  500. Face3(
  501. face_points[0],
  502. face_points[1],
  503. face_points[2]));
  504. p_faces.push_back(
  505. Face3(
  506. face_points[2],
  507. face_points[3],
  508. face_points[0]));
  509. }
  510. }
  511. Vector<Face3> Geometry3D::wrap_geometry(Vector<Face3> p_array, real_t *p_error) {
  512. int face_count = p_array.size();
  513. const Face3 *faces = p_array.ptr();
  514. constexpr double min_size = 1.0;
  515. constexpr int max_length = 20;
  516. AABB global_aabb;
  517. for (int i = 0; i < face_count; i++) {
  518. if (i == 0) {
  519. global_aabb = faces[i].get_aabb();
  520. } else {
  521. global_aabb.merge_with(faces[i].get_aabb());
  522. }
  523. }
  524. global_aabb.grow_by(0.01f); // Avoid numerical error.
  525. // Determine amount of cells in grid axis.
  526. int div_x, div_y, div_z;
  527. if (global_aabb.size.x / min_size < max_length) {
  528. div_x = (int)(global_aabb.size.x / min_size) + 1;
  529. } else {
  530. div_x = max_length;
  531. }
  532. if (global_aabb.size.y / min_size < max_length) {
  533. div_y = (int)(global_aabb.size.y / min_size) + 1;
  534. } else {
  535. div_y = max_length;
  536. }
  537. if (global_aabb.size.z / min_size < max_length) {
  538. div_z = (int)(global_aabb.size.z / min_size) + 1;
  539. } else {
  540. div_z = max_length;
  541. }
  542. Vector3 voxelsize = global_aabb.size;
  543. voxelsize.x /= div_x;
  544. voxelsize.y /= div_y;
  545. voxelsize.z /= div_z;
  546. // Create and initialize cells to zero.
  547. uint8_t ***cell_status = memnew_arr(uint8_t **, div_x);
  548. for (int i = 0; i < div_x; i++) {
  549. cell_status[i] = memnew_arr(uint8_t *, div_y);
  550. for (int j = 0; j < div_y; j++) {
  551. cell_status[i][j] = memnew_arr(uint8_t, div_z);
  552. for (int k = 0; k < div_z; k++) {
  553. cell_status[i][j][k] = 0;
  554. }
  555. }
  556. }
  557. // Plot faces into cells.
  558. for (int i = 0; i < face_count; i++) {
  559. Face3 f = faces[i];
  560. for (int j = 0; j < 3; j++) {
  561. f.vertex[j] -= global_aabb.position;
  562. }
  563. _plot_face(cell_status, 0, 0, 0, div_x, div_y, div_z, voxelsize, f);
  564. }
  565. // Determine which cells connect to the outside by traversing the outside and recursively flood-fill marking.
  566. for (int i = 0; i < div_x; i++) {
  567. for (int j = 0; j < div_y; j++) {
  568. _mark_outside(cell_status, i, j, 0, div_x, div_y, div_z);
  569. _mark_outside(cell_status, i, j, div_z - 1, div_x, div_y, div_z);
  570. }
  571. }
  572. for (int i = 0; i < div_z; i++) {
  573. for (int j = 0; j < div_y; j++) {
  574. _mark_outside(cell_status, 0, j, i, div_x, div_y, div_z);
  575. _mark_outside(cell_status, div_x - 1, j, i, div_x, div_y, div_z);
  576. }
  577. }
  578. for (int i = 0; i < div_x; i++) {
  579. for (int j = 0; j < div_z; j++) {
  580. _mark_outside(cell_status, i, 0, j, div_x, div_y, div_z);
  581. _mark_outside(cell_status, i, div_y - 1, j, div_x, div_y, div_z);
  582. }
  583. }
  584. // Build faces for the inside-outside cell divisors.
  585. Vector<Face3> wrapped_faces;
  586. for (int i = 0; i < div_x; i++) {
  587. for (int j = 0; j < div_y; j++) {
  588. for (int k = 0; k < div_z; k++) {
  589. _build_faces(cell_status, i, j, k, div_x, div_y, div_z, wrapped_faces);
  590. }
  591. }
  592. }
  593. // Transform face vertices to global coords.
  594. int wrapped_faces_count = wrapped_faces.size();
  595. Face3 *wrapped_faces_ptr = wrapped_faces.ptrw();
  596. for (int i = 0; i < wrapped_faces_count; i++) {
  597. for (int j = 0; j < 3; j++) {
  598. Vector3 &v = wrapped_faces_ptr[i].vertex[j];
  599. v = v * voxelsize;
  600. v += global_aabb.position;
  601. }
  602. }
  603. // clean up grid
  604. for (int i = 0; i < div_x; i++) {
  605. for (int j = 0; j < div_y; j++) {
  606. memdelete_arr(cell_status[i][j]);
  607. }
  608. memdelete_arr(cell_status[i]);
  609. }
  610. memdelete_arr(cell_status);
  611. if (p_error) {
  612. *p_error = voxelsize.length();
  613. }
  614. return wrapped_faces;
  615. }
  616. Geometry3D::MeshData Geometry3D::build_convex_mesh(const Vector<Plane> &p_planes) {
  617. MeshData mesh;
  618. #define SUBPLANE_SIZE 1024.0
  619. real_t subplane_size = 1024.0; // Should compute this from the actual plane.
  620. for (int i = 0; i < p_planes.size(); i++) {
  621. Plane p = p_planes[i];
  622. Vector3 ref = Vector3(0.0, 1.0, 0.0);
  623. if (ABS(p.normal.dot(ref)) > 0.95f) {
  624. ref = Vector3(0.0, 0.0, 1.0); // Change axis.
  625. }
  626. Vector3 right = p.normal.cross(ref).normalized();
  627. Vector3 up = p.normal.cross(right).normalized();
  628. Vector3 center = p.center();
  629. // make a quad clockwise
  630. LocalVector<Vector3> vertices = {
  631. center - up * subplane_size + right * subplane_size,
  632. center - up * subplane_size - right * subplane_size,
  633. center + up * subplane_size - right * subplane_size,
  634. center + up * subplane_size + right * subplane_size
  635. };
  636. for (int j = 0; j < p_planes.size(); j++) {
  637. if (j == i) {
  638. continue;
  639. }
  640. LocalVector<Vector3> new_vertices;
  641. Plane clip = p_planes[j];
  642. if (clip.normal.dot(p.normal) > 0.95f) {
  643. continue;
  644. }
  645. if (vertices.size() < 3) {
  646. break;
  647. }
  648. for (uint32_t k = 0; k < vertices.size(); k++) {
  649. int k_n = (k + 1) % vertices.size();
  650. Vector3 edge0_A = vertices[k];
  651. Vector3 edge1_A = vertices[k_n];
  652. real_t dist0 = clip.distance_to(edge0_A);
  653. real_t dist1 = clip.distance_to(edge1_A);
  654. if (dist0 <= 0) { // Behind plane.
  655. new_vertices.push_back(vertices[k]);
  656. }
  657. // Check for different sides and non coplanar.
  658. if ((dist0 * dist1) < 0) {
  659. // Calculate intersection.
  660. Vector3 rel = edge1_A - edge0_A;
  661. real_t den = clip.normal.dot(rel);
  662. if (Math::is_zero_approx(den)) {
  663. continue; // Point too short.
  664. }
  665. real_t dist = -(clip.normal.dot(edge0_A) - clip.d) / den;
  666. Vector3 inters = edge0_A + rel * dist;
  667. new_vertices.push_back(inters);
  668. }
  669. }
  670. vertices = new_vertices;
  671. }
  672. if (vertices.size() < 3) {
  673. continue;
  674. }
  675. // Result is a clockwise face.
  676. MeshData::Face face;
  677. // Add face indices.
  678. for (uint32_t j = 0; j < vertices.size(); j++) {
  679. int idx = -1;
  680. for (uint32_t k = 0; k < mesh.vertices.size(); k++) {
  681. if (mesh.vertices[k].distance_to(vertices[j]) < 0.001f) {
  682. idx = k;
  683. break;
  684. }
  685. }
  686. if (idx == -1) {
  687. idx = mesh.vertices.size();
  688. mesh.vertices.push_back(vertices[j]);
  689. }
  690. face.indices.push_back(idx);
  691. }
  692. face.plane = p;
  693. mesh.faces.push_back(face);
  694. // Add edge.
  695. for (uint32_t j = 0; j < face.indices.size(); j++) {
  696. int a = face.indices[j];
  697. int b = face.indices[(j + 1) % face.indices.size()];
  698. bool found = false;
  699. int found_idx = -1;
  700. for (uint32_t k = 0; k < mesh.edges.size(); k++) {
  701. if (mesh.edges[k].vertex_a == a && mesh.edges[k].vertex_b == b) {
  702. found = true;
  703. found_idx = k;
  704. break;
  705. }
  706. if (mesh.edges[k].vertex_b == a && mesh.edges[k].vertex_a == b) {
  707. found = true;
  708. found_idx = k;
  709. break;
  710. }
  711. }
  712. if (found) {
  713. mesh.edges[found_idx].face_b = j;
  714. continue;
  715. }
  716. MeshData::Edge edge;
  717. edge.vertex_a = a;
  718. edge.vertex_b = b;
  719. edge.face_a = j;
  720. edge.face_b = -1;
  721. mesh.edges.push_back(edge);
  722. }
  723. }
  724. return mesh;
  725. }
  726. Vector<Plane> Geometry3D::build_box_planes(const Vector3 &p_extents) {
  727. Vector<Plane> planes = {
  728. Plane(Vector3(1, 0, 0), p_extents.x),
  729. Plane(Vector3(-1, 0, 0), p_extents.x),
  730. Plane(Vector3(0, 1, 0), p_extents.y),
  731. Plane(Vector3(0, -1, 0), p_extents.y),
  732. Plane(Vector3(0, 0, 1), p_extents.z),
  733. Plane(Vector3(0, 0, -1), p_extents.z)
  734. };
  735. return planes;
  736. }
  737. Vector<Plane> Geometry3D::build_cylinder_planes(real_t p_radius, real_t p_height, int p_sides, Vector3::Axis p_axis) {
  738. ERR_FAIL_INDEX_V(p_axis, 3, Vector<Plane>());
  739. Vector<Plane> planes;
  740. const double sides_step = Math_TAU / p_sides;
  741. for (int i = 0; i < p_sides; i++) {
  742. Vector3 normal;
  743. normal[(p_axis + 1) % 3] = Math::cos(i * sides_step);
  744. normal[(p_axis + 2) % 3] = Math::sin(i * sides_step);
  745. planes.push_back(Plane(normal, p_radius));
  746. }
  747. Vector3 axis;
  748. axis[p_axis] = 1.0;
  749. planes.push_back(Plane(axis, p_height * 0.5f));
  750. planes.push_back(Plane(-axis, p_height * 0.5f));
  751. return planes;
  752. }
  753. Vector<Plane> Geometry3D::build_sphere_planes(real_t p_radius, int p_lats, int p_lons, Vector3::Axis p_axis) {
  754. ERR_FAIL_INDEX_V(p_axis, 3, Vector<Plane>());
  755. Vector<Plane> planes;
  756. Vector3 axis;
  757. axis[p_axis] = 1.0;
  758. Vector3 axis_neg;
  759. axis_neg[(p_axis + 1) % 3] = 1.0;
  760. axis_neg[(p_axis + 2) % 3] = 1.0;
  761. axis_neg[p_axis] = -1.0;
  762. const double lon_step = Math_TAU / p_lons;
  763. for (int i = 0; i < p_lons; i++) {
  764. Vector3 normal;
  765. normal[(p_axis + 1) % 3] = Math::cos(i * lon_step);
  766. normal[(p_axis + 2) % 3] = Math::sin(i * lon_step);
  767. planes.push_back(Plane(normal, p_radius));
  768. for (int j = 1; j <= p_lats; j++) {
  769. Vector3 plane_normal = normal.lerp(axis, j / (real_t)p_lats).normalized();
  770. planes.push_back(Plane(plane_normal, p_radius));
  771. planes.push_back(Plane(plane_normal * axis_neg, p_radius));
  772. }
  773. }
  774. return planes;
  775. }
  776. Vector<Plane> Geometry3D::build_capsule_planes(real_t p_radius, real_t p_height, int p_sides, int p_lats, Vector3::Axis p_axis) {
  777. ERR_FAIL_INDEX_V(p_axis, 3, Vector<Plane>());
  778. Vector<Plane> planes;
  779. Vector3 axis;
  780. axis[p_axis] = 1.0;
  781. Vector3 axis_neg;
  782. axis_neg[(p_axis + 1) % 3] = 1.0;
  783. axis_neg[(p_axis + 2) % 3] = 1.0;
  784. axis_neg[p_axis] = -1.0;
  785. const double sides_step = Math_TAU / p_sides;
  786. for (int i = 0; i < p_sides; i++) {
  787. Vector3 normal;
  788. normal[(p_axis + 1) % 3] = Math::cos(i * sides_step);
  789. normal[(p_axis + 2) % 3] = Math::sin(i * sides_step);
  790. planes.push_back(Plane(normal, p_radius));
  791. for (int j = 1; j <= p_lats; j++) {
  792. Vector3 plane_normal = normal.lerp(axis, j / (real_t)p_lats).normalized();
  793. Vector3 position = axis * p_height * 0.5f + plane_normal * p_radius;
  794. planes.push_back(Plane(plane_normal, position));
  795. planes.push_back(Plane(plane_normal * axis_neg, position * axis_neg));
  796. }
  797. }
  798. return planes;
  799. }
  800. Vector<Vector3> Geometry3D::compute_convex_mesh_points(const Plane *p_planes, int p_plane_count) {
  801. Vector<Vector3> points;
  802. // Iterate through every unique combination of any three planes.
  803. for (int i = p_plane_count - 1; i >= 0; i--) {
  804. for (int j = i - 1; j >= 0; j--) {
  805. for (int k = j - 1; k >= 0; k--) {
  806. // Find the point where these planes all cross over (if they
  807. // do at all).
  808. Vector3 convex_shape_point;
  809. if (p_planes[i].intersect_3(p_planes[j], p_planes[k], &convex_shape_point)) {
  810. // See if any *other* plane excludes this point because it's
  811. // on the wrong side.
  812. bool excluded = false;
  813. for (int n = 0; n < p_plane_count; n++) {
  814. if (n != i && n != j && n != k) {
  815. real_t dp = p_planes[n].normal.dot(convex_shape_point);
  816. if (dp - p_planes[n].d > (real_t)CMP_EPSILON) {
  817. excluded = true;
  818. break;
  819. }
  820. }
  821. }
  822. // Only add the point if it passed all tests.
  823. if (!excluded) {
  824. points.push_back(convex_shape_point);
  825. }
  826. }
  827. }
  828. }
  829. }
  830. return points;
  831. }
  832. #define square(m_s) ((m_s) * (m_s))
  833. #define INF 1e20
  834. /* dt of 1d function using squared distance */
  835. static void edt(float *f, int stride, int n) {
  836. float *d = (float *)alloca(sizeof(float) * n + sizeof(int) * n + sizeof(float) * (n + 1));
  837. int *v = reinterpret_cast<int *>(&(d[n]));
  838. float *z = reinterpret_cast<float *>(&v[n]);
  839. int k = 0;
  840. v[0] = 0;
  841. z[0] = -INF;
  842. z[1] = +INF;
  843. for (int q = 1; q <= n - 1; q++) {
  844. float s = ((f[q * stride] + square(q)) - (f[v[k] * stride] + square(v[k]))) / (2 * q - 2 * v[k]);
  845. while (s <= z[k]) {
  846. k--;
  847. s = ((f[q * stride] + square(q)) - (f[v[k] * stride] + square(v[k]))) / (2 * q - 2 * v[k]);
  848. }
  849. k++;
  850. v[k] = q;
  851. z[k] = s;
  852. z[k + 1] = +INF;
  853. }
  854. k = 0;
  855. for (int q = 0; q <= n - 1; q++) {
  856. while (z[k + 1] < q) {
  857. k++;
  858. }
  859. d[q] = square(q - v[k]) + f[v[k] * stride];
  860. }
  861. for (int i = 0; i < n; i++) {
  862. f[i * stride] = d[i];
  863. }
  864. }
  865. #undef square
  866. Vector<uint32_t> Geometry3D::generate_edf(const Vector<bool> &p_voxels, const Vector3i &p_size, bool p_negative) {
  867. uint32_t float_count = p_size.x * p_size.y * p_size.z;
  868. ERR_FAIL_COND_V((uint32_t)p_voxels.size() != float_count, Vector<uint32_t>());
  869. float *work_memory = memnew_arr(float, float_count);
  870. for (uint32_t i = 0; i < float_count; i++) {
  871. work_memory[i] = INF;
  872. }
  873. uint32_t y_mult = p_size.x;
  874. uint32_t z_mult = y_mult * p_size.y;
  875. //plot solid cells
  876. {
  877. const bool *voxr = p_voxels.ptr();
  878. for (uint32_t i = 0; i < float_count; i++) {
  879. bool plot = voxr[i];
  880. if (p_negative) {
  881. plot = !plot;
  882. }
  883. if (plot) {
  884. work_memory[i] = 0;
  885. }
  886. }
  887. }
  888. //process in each direction
  889. //xy->z
  890. for (int i = 0; i < p_size.x; i++) {
  891. for (int j = 0; j < p_size.y; j++) {
  892. edt(&work_memory[i + j * y_mult], z_mult, p_size.z);
  893. }
  894. }
  895. //xz->y
  896. for (int i = 0; i < p_size.x; i++) {
  897. for (int j = 0; j < p_size.z; j++) {
  898. edt(&work_memory[i + j * z_mult], y_mult, p_size.y);
  899. }
  900. }
  901. //yz->x
  902. for (int i = 0; i < p_size.y; i++) {
  903. for (int j = 0; j < p_size.z; j++) {
  904. edt(&work_memory[i * y_mult + j * z_mult], 1, p_size.x);
  905. }
  906. }
  907. Vector<uint32_t> ret;
  908. ret.resize(float_count);
  909. {
  910. uint32_t *w = ret.ptrw();
  911. for (uint32_t i = 0; i < float_count; i++) {
  912. w[i] = uint32_t(Math::sqrt(work_memory[i]));
  913. }
  914. }
  915. memdelete_arr(work_memory);
  916. return ret;
  917. }
  918. Vector<int8_t> Geometry3D::generate_sdf8(const Vector<uint32_t> &p_positive, const Vector<uint32_t> &p_negative) {
  919. ERR_FAIL_COND_V(p_positive.size() != p_negative.size(), Vector<int8_t>());
  920. Vector<int8_t> sdf8;
  921. int s = p_positive.size();
  922. sdf8.resize(s);
  923. const uint32_t *rpos = p_positive.ptr();
  924. const uint32_t *rneg = p_negative.ptr();
  925. int8_t *wsdf = sdf8.ptrw();
  926. for (int i = 0; i < s; i++) {
  927. int32_t diff = int32_t(rpos[i]) - int32_t(rneg[i]);
  928. wsdf[i] = CLAMP(diff, -128, 127);
  929. }
  930. return sdf8;
  931. }