geometry_3d.cpp 27 KB

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