geometry_3d.cpp 24 KB

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