geometry_3d.cpp 24 KB

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