geometry.cpp 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  1. /*************************************************************************/
  2. /* geometry.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "geometry.h"
  31. #include "core/print_string.h"
  32. #include "thirdparty/misc/clipper.hpp"
  33. #include "thirdparty/misc/triangulator.h"
  34. #define SCALE_FACTOR 100000.0 // Based on CMP_EPSILON.
  35. // This implementation is very inefficient, commenting unless bugs happen. See the other one.
  36. /*
  37. bool Geometry::is_point_in_polygon(const Vector2 &p_point, const Vector<Vector2> &p_polygon) {
  38. Vector<int> indices = Geometry::triangulate_polygon(p_polygon);
  39. for (int j = 0; j + 3 <= indices.size(); j += 3) {
  40. int i1 = indices[j], i2 = indices[j + 1], i3 = indices[j + 2];
  41. if (Geometry::is_point_in_triangle(p_point, p_polygon[i1], p_polygon[i2], p_polygon[i3]))
  42. return true;
  43. }
  44. return false;
  45. }
  46. */
  47. void Geometry::MeshData::optimize_vertices() {
  48. Map<int, int> vtx_remap;
  49. for (int i = 0; i < faces.size(); i++) {
  50. for (int j = 0; j < faces[i].indices.size(); j++) {
  51. int idx = faces[i].indices[j];
  52. if (!vtx_remap.has(idx)) {
  53. int ni = vtx_remap.size();
  54. vtx_remap[idx] = ni;
  55. }
  56. faces.write[i].indices.write[j] = vtx_remap[idx];
  57. }
  58. }
  59. for (int i = 0; i < edges.size(); i++) {
  60. int a = edges[i].a;
  61. int b = edges[i].b;
  62. if (!vtx_remap.has(a)) {
  63. int ni = vtx_remap.size();
  64. vtx_remap[a] = ni;
  65. }
  66. if (!vtx_remap.has(b)) {
  67. int ni = vtx_remap.size();
  68. vtx_remap[b] = ni;
  69. }
  70. edges.write[i].a = vtx_remap[a];
  71. edges.write[i].b = vtx_remap[b];
  72. }
  73. Vector<Vector3> new_vertices;
  74. new_vertices.resize(vtx_remap.size());
  75. for (int i = 0; i < vertices.size(); i++) {
  76. if (vtx_remap.has(i))
  77. new_vertices.write[vtx_remap[i]] = vertices[i];
  78. }
  79. vertices = new_vertices;
  80. }
  81. struct _FaceClassify {
  82. struct _Link {
  83. int face;
  84. int edge;
  85. void clear() {
  86. face = -1;
  87. edge = -1;
  88. }
  89. _Link() {
  90. face = -1;
  91. edge = -1;
  92. }
  93. };
  94. bool valid;
  95. int group;
  96. _Link links[3];
  97. Face3 face;
  98. _FaceClassify() {
  99. group = -1;
  100. valid = false;
  101. };
  102. };
  103. static bool _connect_faces(_FaceClassify *p_faces, int len, int p_group) {
  104. // Connect faces, error will occur if an edge is shared between more than 2 faces.
  105. // Clear connections.
  106. bool error = false;
  107. for (int i = 0; i < len; i++) {
  108. for (int j = 0; j < 3; j++) {
  109. p_faces[i].links[j].clear();
  110. }
  111. }
  112. for (int i = 0; i < len; i++) {
  113. if (p_faces[i].group != p_group)
  114. continue;
  115. for (int j = i + 1; j < len; j++) {
  116. if (p_faces[j].group != p_group)
  117. continue;
  118. for (int k = 0; k < 3; k++) {
  119. Vector3 vi1 = p_faces[i].face.vertex[k];
  120. Vector3 vi2 = p_faces[i].face.vertex[(k + 1) % 3];
  121. for (int l = 0; l < 3; l++) {
  122. Vector3 vj2 = p_faces[j].face.vertex[l];
  123. Vector3 vj1 = p_faces[j].face.vertex[(l + 1) % 3];
  124. if (vi1.distance_to(vj1) < 0.00001 &&
  125. vi2.distance_to(vj2) < 0.00001) {
  126. if (p_faces[i].links[k].face != -1) {
  127. ERR_PRINT("already linked\n");
  128. error = true;
  129. break;
  130. }
  131. if (p_faces[j].links[l].face != -1) {
  132. ERR_PRINT("already linked\n");
  133. error = true;
  134. break;
  135. }
  136. p_faces[i].links[k].face = j;
  137. p_faces[i].links[k].edge = l;
  138. p_faces[j].links[l].face = i;
  139. p_faces[j].links[l].edge = k;
  140. }
  141. }
  142. if (error)
  143. break;
  144. }
  145. if (error)
  146. break;
  147. }
  148. if (error)
  149. break;
  150. }
  151. for (int i = 0; i < len; i++) {
  152. p_faces[i].valid = true;
  153. for (int j = 0; j < 3; j++) {
  154. if (p_faces[i].links[j].face == -1)
  155. p_faces[i].valid = false;
  156. }
  157. }
  158. return error;
  159. }
  160. static bool _group_face(_FaceClassify *p_faces, int len, int p_index, int p_group) {
  161. if (p_faces[p_index].group >= 0)
  162. return false;
  163. p_faces[p_index].group = p_group;
  164. for (int i = 0; i < 3; i++) {
  165. ERR_FAIL_INDEX_V(p_faces[p_index].links[i].face, len, true);
  166. _group_face(p_faces, len, p_faces[p_index].links[i].face, p_group);
  167. }
  168. return true;
  169. }
  170. Vector<Vector<Face3>> Geometry::separate_objects(Vector<Face3> p_array) {
  171. Vector<Vector<Face3>> objects;
  172. int len = p_array.size();
  173. const Face3 *arrayptr = p_array.ptr();
  174. Vector<_FaceClassify> fc;
  175. fc.resize(len);
  176. _FaceClassify *_fcptr = fc.ptrw();
  177. for (int i = 0; i < len; i++) {
  178. _fcptr[i].face = arrayptr[i];
  179. }
  180. bool error = _connect_faces(_fcptr, len, -1);
  181. ERR_FAIL_COND_V_MSG(error, Vector<Vector<Face3>>(), "Invalid geometry.");
  182. // Group connected faces in separate objects.
  183. int group = 0;
  184. for (int i = 0; i < len; i++) {
  185. if (!_fcptr[i].valid)
  186. continue;
  187. if (_group_face(_fcptr, len, i, group)) {
  188. group++;
  189. }
  190. }
  191. // Group connected faces in separate objects.
  192. for (int i = 0; i < len; i++) {
  193. _fcptr[i].face = arrayptr[i];
  194. }
  195. if (group >= 0) {
  196. objects.resize(group);
  197. Vector<Face3> *group_faces = objects.ptrw();
  198. for (int i = 0; i < len; i++) {
  199. if (!_fcptr[i].valid)
  200. continue;
  201. if (_fcptr[i].group >= 0 && _fcptr[i].group < group) {
  202. group_faces[_fcptr[i].group].push_back(_fcptr[i].face);
  203. }
  204. }
  205. }
  206. return objects;
  207. }
  208. /*** GEOMETRY WRAPPER ***/
  209. enum _CellFlags {
  210. _CELL_SOLID = 1,
  211. _CELL_EXTERIOR = 2,
  212. _CELL_STEP_MASK = 0x1C,
  213. _CELL_STEP_NONE = 0 << 2,
  214. _CELL_STEP_Y_POS = 1 << 2,
  215. _CELL_STEP_Y_NEG = 2 << 2,
  216. _CELL_STEP_X_POS = 3 << 2,
  217. _CELL_STEP_X_NEG = 4 << 2,
  218. _CELL_STEP_Z_POS = 5 << 2,
  219. _CELL_STEP_Z_NEG = 6 << 2,
  220. _CELL_STEP_DONE = 7 << 2,
  221. _CELL_PREV_MASK = 0xE0,
  222. _CELL_PREV_NONE = 0 << 5,
  223. _CELL_PREV_Y_POS = 1 << 5,
  224. _CELL_PREV_Y_NEG = 2 << 5,
  225. _CELL_PREV_X_POS = 3 << 5,
  226. _CELL_PREV_X_NEG = 4 << 5,
  227. _CELL_PREV_Z_POS = 5 << 5,
  228. _CELL_PREV_Z_NEG = 6 << 5,
  229. _CELL_PREV_FIRST = 7 << 5,
  230. };
  231. 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) {
  232. AABB aabb(Vector3(x, y, z), Vector3(len_x, len_y, len_z));
  233. aabb.position = aabb.position * voxelsize;
  234. aabb.size = aabb.size * voxelsize;
  235. if (!p_face.intersects_aabb(aabb))
  236. return;
  237. if (len_x == 1 && len_y == 1 && len_z == 1) {
  238. p_cell_status[x][y][z] = _CELL_SOLID;
  239. return;
  240. }
  241. int div_x = len_x > 1 ? 2 : 1;
  242. int div_y = len_y > 1 ? 2 : 1;
  243. int div_z = len_z > 1 ? 2 : 1;
  244. #define _SPLIT(m_i, m_div, m_v, m_len_v, m_new_v, m_new_len_v) \
  245. if (m_div == 1) { \
  246. m_new_v = m_v; \
  247. m_new_len_v = 1; \
  248. } else if (m_i == 0) { \
  249. m_new_v = m_v; \
  250. m_new_len_v = m_len_v / 2; \
  251. } else { \
  252. m_new_v = m_v + m_len_v / 2; \
  253. m_new_len_v = m_len_v - m_len_v / 2; \
  254. }
  255. int new_x;
  256. int new_len_x;
  257. int new_y;
  258. int new_len_y;
  259. int new_z;
  260. int new_len_z;
  261. for (int i = 0; i < div_x; i++) {
  262. _SPLIT(i, div_x, x, len_x, new_x, new_len_x);
  263. for (int j = 0; j < div_y; j++) {
  264. _SPLIT(j, div_y, y, len_y, new_y, new_len_y);
  265. for (int k = 0; k < div_z; k++) {
  266. _SPLIT(k, div_z, z, len_z, new_z, new_len_z);
  267. _plot_face(p_cell_status, new_x, new_y, new_z, new_len_x, new_len_y, new_len_z, voxelsize, p_face);
  268. }
  269. }
  270. }
  271. }
  272. 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) {
  273. if (p_cell_status[x][y][z] & 3)
  274. return; // Nothing to do, already used and/or visited.
  275. p_cell_status[x][y][z] = _CELL_PREV_FIRST;
  276. while (true) {
  277. uint8_t &c = p_cell_status[x][y][z];
  278. if ((c & _CELL_STEP_MASK) == _CELL_STEP_NONE) {
  279. // Haven't been in here, mark as outside.
  280. p_cell_status[x][y][z] |= _CELL_EXTERIOR;
  281. }
  282. if ((c & _CELL_STEP_MASK) != _CELL_STEP_DONE) {
  283. // If not done, increase step.
  284. c += 1 << 2;
  285. }
  286. if ((c & _CELL_STEP_MASK) == _CELL_STEP_DONE) {
  287. // Go back.
  288. switch (c & _CELL_PREV_MASK) {
  289. case _CELL_PREV_FIRST: {
  290. return;
  291. } break;
  292. case _CELL_PREV_Y_POS: {
  293. y++;
  294. ERR_FAIL_COND(y >= len_y);
  295. } break;
  296. case _CELL_PREV_Y_NEG: {
  297. y--;
  298. ERR_FAIL_COND(y < 0);
  299. } break;
  300. case _CELL_PREV_X_POS: {
  301. x++;
  302. ERR_FAIL_COND(x >= len_x);
  303. } break;
  304. case _CELL_PREV_X_NEG: {
  305. x--;
  306. ERR_FAIL_COND(x < 0);
  307. } break;
  308. case _CELL_PREV_Z_POS: {
  309. z++;
  310. ERR_FAIL_COND(z >= len_z);
  311. } break;
  312. case _CELL_PREV_Z_NEG: {
  313. z--;
  314. ERR_FAIL_COND(z < 0);
  315. } break;
  316. default: {
  317. ERR_FAIL();
  318. }
  319. }
  320. continue;
  321. }
  322. int next_x = x, next_y = y, next_z = z;
  323. uint8_t prev = 0;
  324. switch (c & _CELL_STEP_MASK) {
  325. case _CELL_STEP_Y_POS: {
  326. next_y++;
  327. prev = _CELL_PREV_Y_NEG;
  328. } break;
  329. case _CELL_STEP_Y_NEG: {
  330. next_y--;
  331. prev = _CELL_PREV_Y_POS;
  332. } break;
  333. case _CELL_STEP_X_POS: {
  334. next_x++;
  335. prev = _CELL_PREV_X_NEG;
  336. } break;
  337. case _CELL_STEP_X_NEG: {
  338. next_x--;
  339. prev = _CELL_PREV_X_POS;
  340. } break;
  341. case _CELL_STEP_Z_POS: {
  342. next_z++;
  343. prev = _CELL_PREV_Z_NEG;
  344. } break;
  345. case _CELL_STEP_Z_NEG: {
  346. next_z--;
  347. prev = _CELL_PREV_Z_POS;
  348. } break;
  349. default:
  350. ERR_FAIL();
  351. }
  352. if (next_x < 0 || next_x >= len_x)
  353. continue;
  354. if (next_y < 0 || next_y >= len_y)
  355. continue;
  356. if (next_z < 0 || next_z >= len_z)
  357. continue;
  358. if (p_cell_status[next_x][next_y][next_z] & 3)
  359. continue;
  360. x = next_x;
  361. y = next_y;
  362. z = next_z;
  363. p_cell_status[x][y][z] |= prev;
  364. }
  365. }
  366. 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) {
  367. ERR_FAIL_INDEX(x, len_x);
  368. ERR_FAIL_INDEX(y, len_y);
  369. ERR_FAIL_INDEX(z, len_z);
  370. if (p_cell_status[x][y][z] & _CELL_EXTERIOR)
  371. return;
  372. #define vert(m_idx) Vector3(((m_idx)&4) >> 2, ((m_idx)&2) >> 1, (m_idx)&1)
  373. static const uint8_t indices[6][4] = {
  374. { 7, 6, 4, 5 },
  375. { 7, 3, 2, 6 },
  376. { 7, 5, 1, 3 },
  377. { 0, 2, 3, 1 },
  378. { 0, 1, 5, 4 },
  379. { 0, 4, 6, 2 },
  380. };
  381. for (int i = 0; i < 6; i++) {
  382. Vector3 face_points[4];
  383. int disp_x = x + ((i % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  384. int disp_y = y + (((i - 1) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  385. int disp_z = z + (((i - 2) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  386. bool plot = false;
  387. if (disp_x < 0 || disp_x >= len_x)
  388. plot = true;
  389. if (disp_y < 0 || disp_y >= len_y)
  390. plot = true;
  391. if (disp_z < 0 || disp_z >= len_z)
  392. plot = true;
  393. if (!plot && (p_cell_status[disp_x][disp_y][disp_z] & _CELL_EXTERIOR))
  394. plot = true;
  395. if (!plot)
  396. continue;
  397. for (int j = 0; j < 4; j++)
  398. face_points[j] = vert(indices[i][j]) + Vector3(x, y, z);
  399. p_faces.push_back(
  400. Face3(
  401. face_points[0],
  402. face_points[1],
  403. face_points[2]));
  404. p_faces.push_back(
  405. Face3(
  406. face_points[2],
  407. face_points[3],
  408. face_points[0]));
  409. }
  410. }
  411. Vector<Face3> Geometry::wrap_geometry(Vector<Face3> p_array, real_t *p_error) {
  412. #define _MIN_SIZE 1.0
  413. #define _MAX_LENGTH 20
  414. int face_count = p_array.size();
  415. const Face3 *faces = p_array.ptr();
  416. AABB global_aabb;
  417. for (int i = 0; i < face_count; i++) {
  418. if (i == 0) {
  419. global_aabb = faces[i].get_aabb();
  420. } else {
  421. global_aabb.merge_with(faces[i].get_aabb());
  422. }
  423. }
  424. global_aabb.grow_by(0.01); // Avoid numerical error.
  425. // Determine amount of cells in grid axis.
  426. int div_x, div_y, div_z;
  427. if (global_aabb.size.x / _MIN_SIZE < _MAX_LENGTH)
  428. div_x = (int)(global_aabb.size.x / _MIN_SIZE) + 1;
  429. else
  430. div_x = _MAX_LENGTH;
  431. if (global_aabb.size.y / _MIN_SIZE < _MAX_LENGTH)
  432. div_y = (int)(global_aabb.size.y / _MIN_SIZE) + 1;
  433. else
  434. div_y = _MAX_LENGTH;
  435. if (global_aabb.size.z / _MIN_SIZE < _MAX_LENGTH)
  436. div_z = (int)(global_aabb.size.z / _MIN_SIZE) + 1;
  437. else
  438. div_z = _MAX_LENGTH;
  439. Vector3 voxelsize = global_aabb.size;
  440. voxelsize.x /= div_x;
  441. voxelsize.y /= div_y;
  442. voxelsize.z /= div_z;
  443. // Create and initialize cells to zero.
  444. uint8_t ***cell_status = memnew_arr(uint8_t **, div_x);
  445. for (int i = 0; i < div_x; i++) {
  446. cell_status[i] = memnew_arr(uint8_t *, div_y);
  447. for (int j = 0; j < div_y; j++) {
  448. cell_status[i][j] = memnew_arr(uint8_t, div_z);
  449. for (int k = 0; k < div_z; k++) {
  450. cell_status[i][j][k] = 0;
  451. }
  452. }
  453. }
  454. // Plot faces into cells.
  455. for (int i = 0; i < face_count; i++) {
  456. Face3 f = faces[i];
  457. for (int j = 0; j < 3; j++) {
  458. f.vertex[j] -= global_aabb.position;
  459. }
  460. _plot_face(cell_status, 0, 0, 0, div_x, div_y, div_z, voxelsize, f);
  461. }
  462. // Determine which cells connect to the outside by traversing the outside and recursively flood-fill marking.
  463. for (int i = 0; i < div_x; i++) {
  464. for (int j = 0; j < div_y; j++) {
  465. _mark_outside(cell_status, i, j, 0, div_x, div_y, div_z);
  466. _mark_outside(cell_status, i, j, div_z - 1, div_x, div_y, div_z);
  467. }
  468. }
  469. for (int i = 0; i < div_z; i++) {
  470. for (int j = 0; j < div_y; j++) {
  471. _mark_outside(cell_status, 0, j, i, div_x, div_y, div_z);
  472. _mark_outside(cell_status, div_x - 1, j, i, div_x, div_y, div_z);
  473. }
  474. }
  475. for (int i = 0; i < div_x; i++) {
  476. for (int j = 0; j < div_z; j++) {
  477. _mark_outside(cell_status, i, 0, j, div_x, div_y, div_z);
  478. _mark_outside(cell_status, i, div_y - 1, j, div_x, div_y, div_z);
  479. }
  480. }
  481. // Build faces for the inside-outside cell divisors.
  482. Vector<Face3> wrapped_faces;
  483. for (int i = 0; i < div_x; i++) {
  484. for (int j = 0; j < div_y; j++) {
  485. for (int k = 0; k < div_z; k++) {
  486. _build_faces(cell_status, i, j, k, div_x, div_y, div_z, wrapped_faces);
  487. }
  488. }
  489. }
  490. // Transform face vertices to global coords.
  491. int wrapped_faces_count = wrapped_faces.size();
  492. Face3 *wrapped_faces_ptr = wrapped_faces.ptrw();
  493. for (int i = 0; i < wrapped_faces_count; i++) {
  494. for (int j = 0; j < 3; j++) {
  495. Vector3 &v = wrapped_faces_ptr[i].vertex[j];
  496. v = v * voxelsize;
  497. v += global_aabb.position;
  498. }
  499. }
  500. // clean up grid
  501. for (int i = 0; i < div_x; i++) {
  502. for (int j = 0; j < div_y; j++) {
  503. memdelete_arr(cell_status[i][j]);
  504. }
  505. memdelete_arr(cell_status[i]);
  506. }
  507. memdelete_arr(cell_status);
  508. if (p_error)
  509. *p_error = voxelsize.length();
  510. return wrapped_faces;
  511. }
  512. Vector<Vector<Vector2>> Geometry::decompose_polygon_in_convex(Vector<Point2> polygon) {
  513. Vector<Vector<Vector2>> decomp;
  514. List<TriangulatorPoly> in_poly, out_poly;
  515. TriangulatorPoly inp;
  516. inp.Init(polygon.size());
  517. for (int i = 0; i < polygon.size(); i++) {
  518. inp.GetPoint(i) = polygon[i];
  519. }
  520. inp.SetOrientation(TRIANGULATOR_CCW);
  521. in_poly.push_back(inp);
  522. TriangulatorPartition tpart;
  523. if (tpart.ConvexPartition_HM(&in_poly, &out_poly) == 0) { // Failed.
  524. ERR_PRINT("Convex decomposing failed!");
  525. return decomp;
  526. }
  527. decomp.resize(out_poly.size());
  528. int idx = 0;
  529. for (List<TriangulatorPoly>::Element *I = out_poly.front(); I; I = I->next()) {
  530. TriangulatorPoly &tp = I->get();
  531. decomp.write[idx].resize(tp.GetNumPoints());
  532. for (int64_t i = 0; i < tp.GetNumPoints(); i++) {
  533. decomp.write[idx].write[i] = tp.GetPoint(i);
  534. }
  535. idx++;
  536. }
  537. return decomp;
  538. }
  539. Geometry::MeshData Geometry::build_convex_mesh(const Vector<Plane> &p_planes) {
  540. MeshData mesh;
  541. #define SUBPLANE_SIZE 1024.0
  542. real_t subplane_size = 1024.0; // Should compute this from the actual plane.
  543. for (int i = 0; i < p_planes.size(); i++) {
  544. Plane p = p_planes[i];
  545. Vector3 ref = Vector3(0.0, 1.0, 0.0);
  546. if (ABS(p.normal.dot(ref)) > 0.95)
  547. ref = Vector3(0.0, 0.0, 1.0); // Change axis.
  548. Vector3 right = p.normal.cross(ref).normalized();
  549. Vector3 up = p.normal.cross(right).normalized();
  550. Vector<Vector3> vertices;
  551. Vector3 center = p.get_any_point();
  552. // make a quad clockwise
  553. vertices.push_back(center - up * subplane_size + right * subplane_size);
  554. vertices.push_back(center - up * subplane_size - right * subplane_size);
  555. vertices.push_back(center + up * subplane_size - right * subplane_size);
  556. vertices.push_back(center + up * subplane_size + right * subplane_size);
  557. for (int j = 0; j < p_planes.size(); j++) {
  558. if (j == i)
  559. continue;
  560. Vector<Vector3> new_vertices;
  561. Plane clip = p_planes[j];
  562. if (clip.normal.dot(p.normal) > 0.95)
  563. continue;
  564. if (vertices.size() < 3)
  565. break;
  566. for (int k = 0; k < vertices.size(); k++) {
  567. int k_n = (k + 1) % vertices.size();
  568. Vector3 edge0_A = vertices[k];
  569. Vector3 edge1_A = vertices[k_n];
  570. real_t dist0 = clip.distance_to(edge0_A);
  571. real_t dist1 = clip.distance_to(edge1_A);
  572. if (dist0 <= 0) { // Behind plane.
  573. new_vertices.push_back(vertices[k]);
  574. }
  575. // Check for different sides and non coplanar.
  576. if ((dist0 * dist1) < 0) {
  577. // Calculate intersection.
  578. Vector3 rel = edge1_A - edge0_A;
  579. real_t den = clip.normal.dot(rel);
  580. if (Math::is_zero_approx(den))
  581. continue; // Point too short.
  582. real_t dist = -(clip.normal.dot(edge0_A) - clip.distance) / den;
  583. Vector3 inters = edge0_A + rel * dist;
  584. new_vertices.push_back(inters);
  585. }
  586. }
  587. vertices = new_vertices;
  588. }
  589. if (vertices.size() < 3)
  590. continue;
  591. // Result is a clockwise face.
  592. MeshData::Face face;
  593. // Add face indices.
  594. for (int j = 0; j < vertices.size(); j++) {
  595. int idx = -1;
  596. for (int k = 0; k < mesh.vertices.size(); k++) {
  597. if (mesh.vertices[k].distance_to(vertices[j]) < 0.001) {
  598. idx = k;
  599. break;
  600. }
  601. }
  602. if (idx == -1) {
  603. idx = mesh.vertices.size();
  604. mesh.vertices.push_back(vertices[j]);
  605. }
  606. face.indices.push_back(idx);
  607. }
  608. face.plane = p;
  609. mesh.faces.push_back(face);
  610. // Add edge.
  611. for (int j = 0; j < face.indices.size(); j++) {
  612. int a = face.indices[j];
  613. int b = face.indices[(j + 1) % face.indices.size()];
  614. bool found = false;
  615. for (int k = 0; k < mesh.edges.size(); k++) {
  616. if (mesh.edges[k].a == a && mesh.edges[k].b == b) {
  617. found = true;
  618. break;
  619. }
  620. if (mesh.edges[k].b == a && mesh.edges[k].a == b) {
  621. found = true;
  622. break;
  623. }
  624. }
  625. if (found)
  626. continue;
  627. MeshData::Edge edge;
  628. edge.a = a;
  629. edge.b = b;
  630. mesh.edges.push_back(edge);
  631. }
  632. }
  633. return mesh;
  634. }
  635. Vector<Plane> Geometry::build_box_planes(const Vector3 &p_extents) {
  636. Vector<Plane> planes;
  637. planes.push_back(Plane(Vector3(1, 0, 0), p_extents.x));
  638. planes.push_back(Plane(Vector3(-1, 0, 0), p_extents.x));
  639. planes.push_back(Plane(Vector3(0, 1, 0), p_extents.y));
  640. planes.push_back(Plane(Vector3(0, -1, 0), p_extents.y));
  641. planes.push_back(Plane(Vector3(0, 0, 1), p_extents.z));
  642. planes.push_back(Plane(Vector3(0, 0, -1), p_extents.z));
  643. return planes;
  644. }
  645. Vector<Plane> Geometry::build_cylinder_planes(real_t p_radius, real_t p_height, int p_sides, Vector3::Axis p_axis) {
  646. Vector<Plane> planes;
  647. for (int i = 0; i < p_sides; i++) {
  648. Vector3 normal;
  649. normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_sides);
  650. normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_sides);
  651. planes.push_back(Plane(normal, p_radius));
  652. }
  653. Vector3 axis;
  654. axis[p_axis] = 1.0;
  655. planes.push_back(Plane(axis, p_height * 0.5));
  656. planes.push_back(Plane(-axis, p_height * 0.5));
  657. return planes;
  658. }
  659. Vector<Plane> Geometry::build_sphere_planes(real_t p_radius, int p_lats, int p_lons, Vector3::Axis p_axis) {
  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. for (int i = 0; i < p_lons; i++) {
  668. Vector3 normal;
  669. normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_lons);
  670. normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_lons);
  671. planes.push_back(Plane(normal, p_radius));
  672. for (int j = 1; j <= p_lats; j++) {
  673. // FIXME: This is stupid.
  674. Vector3 angle = normal.lerp(axis, j / (real_t)p_lats).normalized();
  675. Vector3 pos = angle * p_radius;
  676. planes.push_back(Plane(pos, angle));
  677. planes.push_back(Plane(pos * axis_neg, angle * axis_neg));
  678. }
  679. }
  680. return planes;
  681. }
  682. Vector<Plane> Geometry::build_capsule_planes(real_t p_radius, real_t p_height, int p_sides, int p_lats, Vector3::Axis p_axis) {
  683. Vector<Plane> planes;
  684. Vector3 axis;
  685. axis[p_axis] = 1.0;
  686. Vector3 axis_neg;
  687. axis_neg[(p_axis + 1) % 3] = 1.0;
  688. axis_neg[(p_axis + 2) % 3] = 1.0;
  689. axis_neg[p_axis] = -1.0;
  690. for (int i = 0; i < p_sides; i++) {
  691. Vector3 normal;
  692. normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_sides);
  693. normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_sides);
  694. planes.push_back(Plane(normal, p_radius));
  695. for (int j = 1; j <= p_lats; j++) {
  696. Vector3 angle = normal.lerp(axis, j / (real_t)p_lats).normalized();
  697. Vector3 pos = axis * p_height * 0.5 + angle * p_radius;
  698. planes.push_back(Plane(pos, angle));
  699. planes.push_back(Plane(pos * axis_neg, angle * axis_neg));
  700. }
  701. }
  702. return planes;
  703. }
  704. struct _AtlasWorkRect {
  705. Size2i s;
  706. Point2i p;
  707. int idx;
  708. _FORCE_INLINE_ bool operator<(const _AtlasWorkRect &p_r) const { return s.width > p_r.s.width; };
  709. };
  710. struct _AtlasWorkRectResult {
  711. Vector<_AtlasWorkRect> result;
  712. int max_w;
  713. int max_h;
  714. };
  715. void Geometry::make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size) {
  716. // Super simple, almost brute force scanline stacking fitter.
  717. // It's pretty basic for now, but it tries to make sure that the aspect ratio of the
  718. // resulting atlas is somehow square. This is necessary because video cards have limits.
  719. // On texture size (usually 2048 or 4096), so the more square a texture, the more chances.
  720. // It will work in every hardware.
  721. // For example, it will prioritize a 1024x1024 atlas (works everywhere) instead of a
  722. // 256x8192 atlas (won't work anywhere).
  723. ERR_FAIL_COND(p_rects.size() == 0);
  724. Vector<_AtlasWorkRect> wrects;
  725. wrects.resize(p_rects.size());
  726. for (int i = 0; i < p_rects.size(); i++) {
  727. wrects.write[i].s = p_rects[i];
  728. wrects.write[i].idx = i;
  729. }
  730. wrects.sort();
  731. int widest = wrects[0].s.width;
  732. Vector<_AtlasWorkRectResult> results;
  733. for (int i = 0; i <= 12; i++) {
  734. int w = 1 << i;
  735. int max_h = 0;
  736. int max_w = 0;
  737. if (w < widest)
  738. continue;
  739. Vector<int> hmax;
  740. hmax.resize(w);
  741. for (int j = 0; j < w; j++)
  742. hmax.write[j] = 0;
  743. // Place them.
  744. int ofs = 0;
  745. int limit_h = 0;
  746. for (int j = 0; j < wrects.size(); j++) {
  747. if (ofs + wrects[j].s.width > w) {
  748. ofs = 0;
  749. }
  750. int from_y = 0;
  751. for (int k = 0; k < wrects[j].s.width; k++) {
  752. if (hmax[ofs + k] > from_y)
  753. from_y = hmax[ofs + k];
  754. }
  755. wrects.write[j].p.x = ofs;
  756. wrects.write[j].p.y = from_y;
  757. int end_h = from_y + wrects[j].s.height;
  758. int end_w = ofs + wrects[j].s.width;
  759. if (ofs == 0)
  760. limit_h = end_h;
  761. for (int k = 0; k < wrects[j].s.width; k++) {
  762. hmax.write[ofs + k] = end_h;
  763. }
  764. if (end_h > max_h)
  765. max_h = end_h;
  766. if (end_w > max_w)
  767. max_w = end_w;
  768. if (ofs == 0 || end_h > limit_h) // While h limit not reached, keep stacking.
  769. ofs += wrects[j].s.width;
  770. }
  771. _AtlasWorkRectResult result;
  772. result.result = wrects;
  773. result.max_h = max_h;
  774. result.max_w = max_w;
  775. results.push_back(result);
  776. }
  777. // Find the result with the best aspect ratio.
  778. int best = -1;
  779. real_t best_aspect = 1e20;
  780. for (int i = 0; i < results.size(); i++) {
  781. real_t h = next_power_of_2(results[i].max_h);
  782. real_t w = next_power_of_2(results[i].max_w);
  783. real_t aspect = h > w ? h / w : w / h;
  784. if (aspect < best_aspect) {
  785. best = i;
  786. best_aspect = aspect;
  787. }
  788. }
  789. r_result.resize(p_rects.size());
  790. for (int i = 0; i < p_rects.size(); i++) {
  791. r_result.write[results[best].result[i].idx] = results[best].result[i].p;
  792. }
  793. r_size = Size2(results[best].max_w, results[best].max_h);
  794. }
  795. Vector<Vector<Point2>> Geometry::_polypaths_do_operation(PolyBooleanOperation p_op, const Vector<Point2> &p_polypath_a, const Vector<Point2> &p_polypath_b, bool is_a_open) {
  796. using namespace ClipperLib;
  797. ClipType op = ctUnion;
  798. switch (p_op) {
  799. case OPERATION_UNION:
  800. op = ctUnion;
  801. break;
  802. case OPERATION_DIFFERENCE:
  803. op = ctDifference;
  804. break;
  805. case OPERATION_INTERSECTION:
  806. op = ctIntersection;
  807. break;
  808. case OPERATION_XOR:
  809. op = ctXor;
  810. break;
  811. }
  812. Path path_a, path_b;
  813. // Need to scale points (Clipper's requirement for robust computation).
  814. for (int i = 0; i != p_polypath_a.size(); ++i) {
  815. path_a << IntPoint(p_polypath_a[i].x * SCALE_FACTOR, p_polypath_a[i].y * SCALE_FACTOR);
  816. }
  817. for (int i = 0; i != p_polypath_b.size(); ++i) {
  818. path_b << IntPoint(p_polypath_b[i].x * SCALE_FACTOR, p_polypath_b[i].y * SCALE_FACTOR);
  819. }
  820. Clipper clp;
  821. clp.AddPath(path_a, ptSubject, !is_a_open); // Forward compatible with Clipper 10.0.0.
  822. clp.AddPath(path_b, ptClip, true); // Polylines cannot be set as clip.
  823. Paths paths;
  824. if (is_a_open) {
  825. PolyTree tree; // Needed to populate polylines.
  826. clp.Execute(op, tree);
  827. OpenPathsFromPolyTree(tree, paths);
  828. } else {
  829. clp.Execute(op, paths); // Works on closed polygons only.
  830. }
  831. // Have to scale points down now.
  832. Vector<Vector<Point2>> polypaths;
  833. for (Paths::size_type i = 0; i < paths.size(); ++i) {
  834. Vector<Vector2> polypath;
  835. const Path &scaled_path = paths[i];
  836. for (Paths::size_type j = 0; j < scaled_path.size(); ++j) {
  837. polypath.push_back(Point2(
  838. static_cast<real_t>(scaled_path[j].X) / SCALE_FACTOR,
  839. static_cast<real_t>(scaled_path[j].Y) / SCALE_FACTOR));
  840. }
  841. polypaths.push_back(polypath);
  842. }
  843. return polypaths;
  844. }
  845. Vector<Vector<Point2>> Geometry::_polypath_offset(const Vector<Point2> &p_polypath, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) {
  846. using namespace ClipperLib;
  847. JoinType jt = jtSquare;
  848. switch (p_join_type) {
  849. case JOIN_SQUARE:
  850. jt = jtSquare;
  851. break;
  852. case JOIN_ROUND:
  853. jt = jtRound;
  854. break;
  855. case JOIN_MITER:
  856. jt = jtMiter;
  857. break;
  858. }
  859. EndType et = etClosedPolygon;
  860. switch (p_end_type) {
  861. case END_POLYGON:
  862. et = etClosedPolygon;
  863. break;
  864. case END_JOINED:
  865. et = etClosedLine;
  866. break;
  867. case END_BUTT:
  868. et = etOpenButt;
  869. break;
  870. case END_SQUARE:
  871. et = etOpenSquare;
  872. break;
  873. case END_ROUND:
  874. et = etOpenRound;
  875. break;
  876. }
  877. ClipperOffset co(2.0, 0.25 * SCALE_FACTOR); // Defaults from ClipperOffset.
  878. Path path;
  879. // Need to scale points (Clipper's requirement for robust computation).
  880. for (int i = 0; i != p_polypath.size(); ++i) {
  881. path << IntPoint(p_polypath[i].x * SCALE_FACTOR, p_polypath[i].y * SCALE_FACTOR);
  882. }
  883. co.AddPath(path, jt, et);
  884. Paths paths;
  885. co.Execute(paths, p_delta * SCALE_FACTOR); // Inflate/deflate.
  886. // Have to scale points down now.
  887. Vector<Vector<Point2>> polypaths;
  888. for (Paths::size_type i = 0; i < paths.size(); ++i) {
  889. Vector<Vector2> polypath;
  890. const Path &scaled_path = paths[i];
  891. for (Paths::size_type j = 0; j < scaled_path.size(); ++j) {
  892. polypath.push_back(Point2(
  893. static_cast<real_t>(scaled_path[j].X) / SCALE_FACTOR,
  894. static_cast<real_t>(scaled_path[j].Y) / SCALE_FACTOR));
  895. }
  896. polypaths.push_back(polypath);
  897. }
  898. return polypaths;
  899. }
  900. Vector<Vector3> Geometry::compute_convex_mesh_points(const Plane *p_planes, int p_plane_count) {
  901. Vector<Vector3> points;
  902. // Iterate through every unique combination of any three planes.
  903. for (int i = p_plane_count - 1; i >= 0; i--) {
  904. for (int j = i - 1; j >= 0; j--) {
  905. for (int k = j - 1; k >= 0; k--) {
  906. // Find the point where these planes all cross over (if they
  907. // do at all).
  908. Vector3 convex_shape_point;
  909. if (p_planes[i].intersect_3(p_planes[j], p_planes[k], &convex_shape_point)) {
  910. // See if any *other* plane excludes this point because it's
  911. // on the wrong side.
  912. bool excluded = false;
  913. for (int n = 0; n < p_plane_count; n++) {
  914. if (n != i && n != j && n != k) {
  915. real_t dp = p_planes[n].normal.dot(convex_shape_point);
  916. if (dp - p_planes[n].distance > CMP_EPSILON) {
  917. excluded = true;
  918. break;
  919. }
  920. }
  921. }
  922. // Only add the point if it passed all tests.
  923. if (!excluded) {
  924. points.push_back(convex_shape_point);
  925. }
  926. }
  927. }
  928. }
  929. }
  930. return points;
  931. }