geometry.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460
  1. /*************************************************************************/
  2. /* geometry.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.h"
  31. #include "core/local_vector.h"
  32. #include "core/print_string.h"
  33. #include "thirdparty/misc/clipper.hpp"
  34. #include "thirdparty/misc/triangulator.h"
  35. #define STB_RECT_PACK_IMPLEMENTATION
  36. #include "thirdparty/stb_rect_pack/stb_rect_pack.h"
  37. #define SCALE_FACTOR 100000.0 // Based on CMP_EPSILON.
  38. // This implementation is very inefficient, commenting unless bugs happen. See the other one.
  39. /*
  40. bool Geometry::is_point_in_polygon(const Vector2 &p_point, const Vector<Vector2> &p_polygon) {
  41. Vector<int> indices = Geometry::triangulate_polygon(p_polygon);
  42. for (int j = 0; j + 3 <= indices.size(); j += 3) {
  43. int i1 = indices[j], i2 = indices[j + 1], i3 = indices[j + 2];
  44. if (Geometry::is_point_in_triangle(p_point, p_polygon[i1], p_polygon[i2], p_polygon[i3]))
  45. return true;
  46. }
  47. return false;
  48. }
  49. */
  50. void Geometry::OccluderMeshData::clear() {
  51. faces.clear();
  52. vertices.clear();
  53. }
  54. void Geometry::MeshData::clear() {
  55. faces.clear();
  56. edges.clear();
  57. vertices.clear();
  58. }
  59. void Geometry::MeshData::optimize_vertices() {
  60. Map<int, int> vtx_remap;
  61. for (int i = 0; i < faces.size(); i++) {
  62. for (int j = 0; j < faces[i].indices.size(); j++) {
  63. int idx = faces[i].indices[j];
  64. if (!vtx_remap.has(idx)) {
  65. int ni = vtx_remap.size();
  66. vtx_remap[idx] = ni;
  67. }
  68. faces.write[i].indices.write[j] = vtx_remap[idx];
  69. }
  70. }
  71. for (int i = 0; i < edges.size(); i++) {
  72. int a = edges[i].a;
  73. int b = edges[i].b;
  74. if (!vtx_remap.has(a)) {
  75. int ni = vtx_remap.size();
  76. vtx_remap[a] = ni;
  77. }
  78. if (!vtx_remap.has(b)) {
  79. int ni = vtx_remap.size();
  80. vtx_remap[b] = ni;
  81. }
  82. edges.write[i].a = vtx_remap[a];
  83. edges.write[i].b = vtx_remap[b];
  84. }
  85. Vector<Vector3> new_vertices;
  86. new_vertices.resize(vtx_remap.size());
  87. for (int i = 0; i < vertices.size(); i++) {
  88. if (vtx_remap.has(i)) {
  89. new_vertices.write[vtx_remap[i]] = vertices[i];
  90. }
  91. }
  92. vertices = new_vertices;
  93. }
  94. struct _FaceClassify {
  95. struct _Link {
  96. int face;
  97. int edge;
  98. void clear() {
  99. face = -1;
  100. edge = -1;
  101. }
  102. _Link() {
  103. face = -1;
  104. edge = -1;
  105. }
  106. };
  107. bool valid;
  108. int group;
  109. _Link links[3];
  110. Face3 face;
  111. _FaceClassify() {
  112. group = -1;
  113. valid = false;
  114. };
  115. };
  116. static bool _connect_faces(_FaceClassify *p_faces, int len, int p_group) {
  117. // Connect faces, error will occur if an edge is shared between more than 2 faces.
  118. // Clear connections.
  119. bool error = false;
  120. for (int i = 0; i < len; i++) {
  121. for (int j = 0; j < 3; j++) {
  122. p_faces[i].links[j].clear();
  123. }
  124. }
  125. for (int i = 0; i < len; i++) {
  126. if (p_faces[i].group != p_group) {
  127. continue;
  128. }
  129. for (int j = i + 1; j < len; j++) {
  130. if (p_faces[j].group != p_group) {
  131. continue;
  132. }
  133. for (int k = 0; k < 3; k++) {
  134. Vector3 vi1 = p_faces[i].face.vertex[k];
  135. Vector3 vi2 = p_faces[i].face.vertex[(k + 1) % 3];
  136. for (int l = 0; l < 3; l++) {
  137. Vector3 vj2 = p_faces[j].face.vertex[l];
  138. Vector3 vj1 = p_faces[j].face.vertex[(l + 1) % 3];
  139. if (vi1.distance_to(vj1) < 0.00001 &&
  140. vi2.distance_to(vj2) < 0.00001) {
  141. if (p_faces[i].links[k].face != -1) {
  142. ERR_PRINT("already linked\n");
  143. error = true;
  144. break;
  145. }
  146. if (p_faces[j].links[l].face != -1) {
  147. ERR_PRINT("already linked\n");
  148. error = true;
  149. break;
  150. }
  151. p_faces[i].links[k].face = j;
  152. p_faces[i].links[k].edge = l;
  153. p_faces[j].links[l].face = i;
  154. p_faces[j].links[l].edge = k;
  155. }
  156. }
  157. if (error) {
  158. break;
  159. }
  160. }
  161. if (error) {
  162. break;
  163. }
  164. }
  165. if (error) {
  166. break;
  167. }
  168. }
  169. for (int i = 0; i < len; i++) {
  170. p_faces[i].valid = true;
  171. for (int j = 0; j < 3; j++) {
  172. if (p_faces[i].links[j].face == -1) {
  173. p_faces[i].valid = false;
  174. }
  175. }
  176. }
  177. return error;
  178. }
  179. static bool _group_face(_FaceClassify *p_faces, int len, int p_index, int p_group) {
  180. if (p_faces[p_index].group >= 0) {
  181. return false;
  182. }
  183. p_faces[p_index].group = p_group;
  184. for (int i = 0; i < 3; i++) {
  185. ERR_FAIL_INDEX_V(p_faces[p_index].links[i].face, len, true);
  186. _group_face(p_faces, len, p_faces[p_index].links[i].face, p_group);
  187. }
  188. return true;
  189. }
  190. PoolVector<PoolVector<Face3>> Geometry::separate_objects(PoolVector<Face3> p_array) {
  191. PoolVector<PoolVector<Face3>> objects;
  192. int len = p_array.size();
  193. PoolVector<Face3>::Read r = p_array.read();
  194. const Face3 *arrayptr = r.ptr();
  195. PoolVector<_FaceClassify> fc;
  196. fc.resize(len);
  197. PoolVector<_FaceClassify>::Write fcw = fc.write();
  198. _FaceClassify *_fcptr = fcw.ptr();
  199. for (int i = 0; i < len; i++) {
  200. _fcptr[i].face = arrayptr[i];
  201. }
  202. bool error = _connect_faces(_fcptr, len, -1);
  203. ERR_FAIL_COND_V_MSG(error, PoolVector<PoolVector<Face3>>(), "Invalid geometry.");
  204. // Group connected faces in separate objects.
  205. int group = 0;
  206. for (int i = 0; i < len; i++) {
  207. if (!_fcptr[i].valid) {
  208. continue;
  209. }
  210. if (_group_face(_fcptr, len, i, group)) {
  211. group++;
  212. }
  213. }
  214. // Group connected faces in separate objects.
  215. for (int i = 0; i < len; i++) {
  216. _fcptr[i].face = arrayptr[i];
  217. }
  218. if (group >= 0) {
  219. objects.resize(group);
  220. PoolVector<PoolVector<Face3>>::Write obw = objects.write();
  221. PoolVector<Face3> *group_faces = obw.ptr();
  222. for (int i = 0; i < len; i++) {
  223. if (!_fcptr[i].valid) {
  224. continue;
  225. }
  226. if (_fcptr[i].group >= 0 && _fcptr[i].group < group) {
  227. group_faces[_fcptr[i].group].push_back(_fcptr[i].face);
  228. }
  229. }
  230. }
  231. return objects;
  232. }
  233. /*** GEOMETRY WRAPPER ***/
  234. enum _CellFlags {
  235. _CELL_SOLID = 1,
  236. _CELL_EXTERIOR = 2,
  237. _CELL_STEP_MASK = 0x1C,
  238. _CELL_STEP_NONE = 0 << 2,
  239. _CELL_STEP_Y_POS = 1 << 2,
  240. _CELL_STEP_Y_NEG = 2 << 2,
  241. _CELL_STEP_X_POS = 3 << 2,
  242. _CELL_STEP_X_NEG = 4 << 2,
  243. _CELL_STEP_Z_POS = 5 << 2,
  244. _CELL_STEP_Z_NEG = 6 << 2,
  245. _CELL_STEP_DONE = 7 << 2,
  246. _CELL_PREV_MASK = 0xE0,
  247. _CELL_PREV_NONE = 0 << 5,
  248. _CELL_PREV_Y_POS = 1 << 5,
  249. _CELL_PREV_Y_NEG = 2 << 5,
  250. _CELL_PREV_X_POS = 3 << 5,
  251. _CELL_PREV_X_NEG = 4 << 5,
  252. _CELL_PREV_Z_POS = 5 << 5,
  253. _CELL_PREV_Z_NEG = 6 << 5,
  254. _CELL_PREV_FIRST = 7 << 5,
  255. };
  256. 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) {
  257. AABB aabb(Vector3(x, y, z), Vector3(len_x, len_y, len_z));
  258. aabb.position = aabb.position * voxelsize;
  259. aabb.size = aabb.size * voxelsize;
  260. if (!p_face.intersects_aabb(aabb)) {
  261. return;
  262. }
  263. if (len_x == 1 && len_y == 1 && len_z == 1) {
  264. p_cell_status[x][y][z] = _CELL_SOLID;
  265. return;
  266. }
  267. int div_x = len_x > 1 ? 2 : 1;
  268. int div_y = len_y > 1 ? 2 : 1;
  269. int div_z = len_z > 1 ? 2 : 1;
  270. #define _SPLIT(m_i, m_div, m_v, m_len_v, m_new_v, m_new_len_v) \
  271. if (m_div == 1) { \
  272. m_new_v = m_v; \
  273. m_new_len_v = 1; \
  274. } else if (m_i == 0) { \
  275. m_new_v = m_v; \
  276. m_new_len_v = m_len_v / 2; \
  277. } else { \
  278. m_new_v = m_v + m_len_v / 2; \
  279. m_new_len_v = m_len_v - m_len_v / 2; \
  280. }
  281. int new_x;
  282. int new_len_x;
  283. int new_y;
  284. int new_len_y;
  285. int new_z;
  286. int new_len_z;
  287. for (int i = 0; i < div_x; i++) {
  288. _SPLIT(i, div_x, x, len_x, new_x, new_len_x);
  289. for (int j = 0; j < div_y; j++) {
  290. _SPLIT(j, div_y, y, len_y, new_y, new_len_y);
  291. for (int k = 0; k < div_z; k++) {
  292. _SPLIT(k, div_z, z, len_z, new_z, new_len_z);
  293. _plot_face(p_cell_status, new_x, new_y, new_z, new_len_x, new_len_y, new_len_z, voxelsize, p_face);
  294. }
  295. }
  296. }
  297. }
  298. 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) {
  299. if (p_cell_status[x][y][z] & 3) {
  300. return; // Nothing to do, already used and/or visited.
  301. }
  302. p_cell_status[x][y][z] = _CELL_PREV_FIRST;
  303. while (true) {
  304. uint8_t &c = p_cell_status[x][y][z];
  305. if ((c & _CELL_STEP_MASK) == _CELL_STEP_NONE) {
  306. // Haven't been in here, mark as outside.
  307. p_cell_status[x][y][z] |= _CELL_EXTERIOR;
  308. }
  309. if ((c & _CELL_STEP_MASK) != _CELL_STEP_DONE) {
  310. // If not done, increase step.
  311. c += 1 << 2;
  312. }
  313. if ((c & _CELL_STEP_MASK) == _CELL_STEP_DONE) {
  314. // Go back.
  315. switch (c & _CELL_PREV_MASK) {
  316. case _CELL_PREV_FIRST: {
  317. return;
  318. } break;
  319. case _CELL_PREV_Y_POS: {
  320. y++;
  321. ERR_FAIL_COND(y >= len_y);
  322. } break;
  323. case _CELL_PREV_Y_NEG: {
  324. y--;
  325. ERR_FAIL_COND(y < 0);
  326. } break;
  327. case _CELL_PREV_X_POS: {
  328. x++;
  329. ERR_FAIL_COND(x >= len_x);
  330. } break;
  331. case _CELL_PREV_X_NEG: {
  332. x--;
  333. ERR_FAIL_COND(x < 0);
  334. } break;
  335. case _CELL_PREV_Z_POS: {
  336. z++;
  337. ERR_FAIL_COND(z >= len_z);
  338. } break;
  339. case _CELL_PREV_Z_NEG: {
  340. z--;
  341. ERR_FAIL_COND(z < 0);
  342. } break;
  343. default: {
  344. ERR_FAIL();
  345. }
  346. }
  347. continue;
  348. }
  349. int next_x = x, next_y = y, next_z = z;
  350. uint8_t prev = 0;
  351. switch (c & _CELL_STEP_MASK) {
  352. case _CELL_STEP_Y_POS: {
  353. next_y++;
  354. prev = _CELL_PREV_Y_NEG;
  355. } break;
  356. case _CELL_STEP_Y_NEG: {
  357. next_y--;
  358. prev = _CELL_PREV_Y_POS;
  359. } break;
  360. case _CELL_STEP_X_POS: {
  361. next_x++;
  362. prev = _CELL_PREV_X_NEG;
  363. } break;
  364. case _CELL_STEP_X_NEG: {
  365. next_x--;
  366. prev = _CELL_PREV_X_POS;
  367. } break;
  368. case _CELL_STEP_Z_POS: {
  369. next_z++;
  370. prev = _CELL_PREV_Z_NEG;
  371. } break;
  372. case _CELL_STEP_Z_NEG: {
  373. next_z--;
  374. prev = _CELL_PREV_Z_POS;
  375. } break;
  376. default:
  377. ERR_FAIL();
  378. }
  379. if (next_x < 0 || next_x >= len_x) {
  380. continue;
  381. }
  382. if (next_y < 0 || next_y >= len_y) {
  383. continue;
  384. }
  385. if (next_z < 0 || next_z >= len_z) {
  386. continue;
  387. }
  388. if (p_cell_status[next_x][next_y][next_z] & 3) {
  389. continue;
  390. }
  391. x = next_x;
  392. y = next_y;
  393. z = next_z;
  394. p_cell_status[x][y][z] |= prev;
  395. }
  396. }
  397. 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, PoolVector<Face3> &p_faces) {
  398. ERR_FAIL_INDEX(x, len_x);
  399. ERR_FAIL_INDEX(y, len_y);
  400. ERR_FAIL_INDEX(z, len_z);
  401. if (p_cell_status[x][y][z] & _CELL_EXTERIOR) {
  402. return;
  403. }
  404. #define vert(m_idx) Vector3(((m_idx)&4) >> 2, ((m_idx)&2) >> 1, (m_idx)&1)
  405. static const uint8_t indices[6][4] = {
  406. { 7, 6, 4, 5 },
  407. { 7, 3, 2, 6 },
  408. { 7, 5, 1, 3 },
  409. { 0, 2, 3, 1 },
  410. { 0, 1, 5, 4 },
  411. { 0, 4, 6, 2 },
  412. };
  413. for (int i = 0; i < 6; i++) {
  414. Vector3 face_points[4];
  415. int disp_x = x + ((i % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  416. int disp_y = y + (((i - 1) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  417. int disp_z = z + (((i - 2) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  418. bool plot = false;
  419. if (disp_x < 0 || disp_x >= len_x) {
  420. plot = true;
  421. }
  422. if (disp_y < 0 || disp_y >= len_y) {
  423. plot = true;
  424. }
  425. if (disp_z < 0 || disp_z >= len_z) {
  426. plot = true;
  427. }
  428. if (!plot && (p_cell_status[disp_x][disp_y][disp_z] & _CELL_EXTERIOR)) {
  429. plot = true;
  430. }
  431. if (!plot) {
  432. continue;
  433. }
  434. for (int j = 0; j < 4; j++) {
  435. face_points[j] = vert(indices[i][j]) + Vector3(x, y, z);
  436. }
  437. p_faces.push_back(
  438. Face3(
  439. face_points[0],
  440. face_points[1],
  441. face_points[2]));
  442. p_faces.push_back(
  443. Face3(
  444. face_points[2],
  445. face_points[3],
  446. face_points[0]));
  447. }
  448. }
  449. PoolVector<Face3> Geometry::wrap_geometry(PoolVector<Face3> p_array, real_t *p_error) {
  450. #define _MIN_SIZE 1.0
  451. #define _MAX_LENGTH 20
  452. int face_count = p_array.size();
  453. PoolVector<Face3>::Read facesr = p_array.read();
  454. const Face3 *faces = facesr.ptr();
  455. AABB global_aabb;
  456. for (int i = 0; i < face_count; i++) {
  457. if (i == 0) {
  458. global_aabb = faces[i].get_aabb();
  459. } else {
  460. global_aabb.merge_with(faces[i].get_aabb());
  461. }
  462. }
  463. global_aabb.grow_by(0.01); // Avoid numerical error.
  464. // Determine amount of cells in grid axis.
  465. int div_x, div_y, div_z;
  466. if (global_aabb.size.x / _MIN_SIZE < _MAX_LENGTH) {
  467. div_x = (int)(global_aabb.size.x / _MIN_SIZE) + 1;
  468. } else {
  469. div_x = _MAX_LENGTH;
  470. }
  471. if (global_aabb.size.y / _MIN_SIZE < _MAX_LENGTH) {
  472. div_y = (int)(global_aabb.size.y / _MIN_SIZE) + 1;
  473. } else {
  474. div_y = _MAX_LENGTH;
  475. }
  476. if (global_aabb.size.z / _MIN_SIZE < _MAX_LENGTH) {
  477. div_z = (int)(global_aabb.size.z / _MIN_SIZE) + 1;
  478. } else {
  479. div_z = _MAX_LENGTH;
  480. }
  481. Vector3 voxelsize = global_aabb.size;
  482. voxelsize.x /= div_x;
  483. voxelsize.y /= div_y;
  484. voxelsize.z /= div_z;
  485. // Create and initialize cells to zero.
  486. uint8_t ***cell_status = memnew_arr(uint8_t **, div_x);
  487. for (int i = 0; i < div_x; i++) {
  488. cell_status[i] = memnew_arr(uint8_t *, div_y);
  489. for (int j = 0; j < div_y; j++) {
  490. cell_status[i][j] = memnew_arr(uint8_t, div_z);
  491. for (int k = 0; k < div_z; k++) {
  492. cell_status[i][j][k] = 0;
  493. }
  494. }
  495. }
  496. // Plot faces into cells.
  497. for (int i = 0; i < face_count; i++) {
  498. Face3 f = faces[i];
  499. for (int j = 0; j < 3; j++) {
  500. f.vertex[j] -= global_aabb.position;
  501. }
  502. _plot_face(cell_status, 0, 0, 0, div_x, div_y, div_z, voxelsize, f);
  503. }
  504. // Determine which cells connect to the outside by traversing the outside and recursively flood-fill marking.
  505. for (int i = 0; i < div_x; i++) {
  506. for (int j = 0; j < div_y; j++) {
  507. _mark_outside(cell_status, i, j, 0, div_x, div_y, div_z);
  508. _mark_outside(cell_status, i, j, div_z - 1, div_x, div_y, div_z);
  509. }
  510. }
  511. for (int i = 0; i < div_z; i++) {
  512. for (int j = 0; j < div_y; j++) {
  513. _mark_outside(cell_status, 0, j, i, div_x, div_y, div_z);
  514. _mark_outside(cell_status, div_x - 1, j, i, div_x, div_y, div_z);
  515. }
  516. }
  517. for (int i = 0; i < div_x; i++) {
  518. for (int j = 0; j < div_z; j++) {
  519. _mark_outside(cell_status, i, 0, j, div_x, div_y, div_z);
  520. _mark_outside(cell_status, i, div_y - 1, j, div_x, div_y, div_z);
  521. }
  522. }
  523. // Build faces for the inside-outside cell divisors.
  524. PoolVector<Face3> wrapped_faces;
  525. for (int i = 0; i < div_x; i++) {
  526. for (int j = 0; j < div_y; j++) {
  527. for (int k = 0; k < div_z; k++) {
  528. _build_faces(cell_status, i, j, k, div_x, div_y, div_z, wrapped_faces);
  529. }
  530. }
  531. }
  532. // Transform face vertices to global coords.
  533. int wrapped_faces_count = wrapped_faces.size();
  534. PoolVector<Face3>::Write wrapped_facesw = wrapped_faces.write();
  535. Face3 *wrapped_faces_ptr = wrapped_facesw.ptr();
  536. for (int i = 0; i < wrapped_faces_count; i++) {
  537. for (int j = 0; j < 3; j++) {
  538. Vector3 &v = wrapped_faces_ptr[i].vertex[j];
  539. v = v * voxelsize;
  540. v += global_aabb.position;
  541. }
  542. }
  543. // clean up grid
  544. for (int i = 0; i < div_x; i++) {
  545. for (int j = 0; j < div_y; j++) {
  546. memdelete_arr(cell_status[i][j]);
  547. }
  548. memdelete_arr(cell_status[i]);
  549. }
  550. memdelete_arr(cell_status);
  551. if (p_error) {
  552. *p_error = voxelsize.length();
  553. }
  554. return wrapped_faces;
  555. }
  556. Vector<Vector<Vector2>> Geometry::decompose_polygon_in_convex(Vector<Point2> polygon) {
  557. Vector<Vector<Vector2>> decomp;
  558. List<TriangulatorPoly> in_poly, out_poly;
  559. TriangulatorPoly inp;
  560. inp.Init(polygon.size());
  561. for (int i = 0; i < polygon.size(); i++) {
  562. inp.GetPoint(i) = polygon[i];
  563. }
  564. inp.SetOrientation(TRIANGULATOR_CCW);
  565. in_poly.push_back(inp);
  566. TriangulatorPartition tpart;
  567. if (tpart.ConvexPartition_HM(&in_poly, &out_poly) == 0) { // Failed.
  568. ERR_PRINT("Convex decomposing failed!");
  569. return decomp;
  570. }
  571. decomp.resize(out_poly.size());
  572. int idx = 0;
  573. for (List<TriangulatorPoly>::Element *I = out_poly.front(); I; I = I->next()) {
  574. TriangulatorPoly &tp = I->get();
  575. decomp.write[idx].resize(tp.GetNumPoints());
  576. for (int64_t i = 0; i < tp.GetNumPoints(); i++) {
  577. decomp.write[idx].write[i] = tp.GetPoint(i);
  578. }
  579. idx++;
  580. }
  581. return decomp;
  582. }
  583. Geometry::MeshData Geometry::build_convex_mesh(const PoolVector<Plane> &p_planes) {
  584. MeshData mesh;
  585. #define SUBPLANE_SIZE 1024.0
  586. real_t subplane_size = 1024.0; // Should compute this from the actual plane.
  587. for (int i = 0; i < p_planes.size(); i++) {
  588. Plane p = p_planes[i];
  589. Vector3 ref = Vector3(0.0, 1.0, 0.0);
  590. if (ABS(p.normal.dot(ref)) > 0.95) {
  591. ref = Vector3(0.0, 0.0, 1.0); // Change axis.
  592. }
  593. Vector3 right = p.normal.cross(ref).normalized();
  594. Vector3 up = p.normal.cross(right).normalized();
  595. Vector<Vector3> vertices;
  596. Vector3 center = p.get_any_point();
  597. // make a quad clockwise
  598. vertices.push_back(center - up * subplane_size + right * subplane_size);
  599. vertices.push_back(center - up * subplane_size - right * subplane_size);
  600. vertices.push_back(center + up * subplane_size - right * subplane_size);
  601. vertices.push_back(center + up * subplane_size + right * subplane_size);
  602. for (int j = 0; j < p_planes.size(); j++) {
  603. if (j == i) {
  604. continue;
  605. }
  606. Vector<Vector3> new_vertices;
  607. Plane clip = p_planes[j];
  608. if (clip.normal.dot(p.normal) > 0.95) {
  609. continue;
  610. }
  611. if (vertices.size() < 3) {
  612. break;
  613. }
  614. for (int k = 0; k < vertices.size(); k++) {
  615. int k_n = (k + 1) % vertices.size();
  616. Vector3 edge0_A = vertices[k];
  617. Vector3 edge1_A = vertices[k_n];
  618. real_t dist0 = clip.distance_to(edge0_A);
  619. real_t dist1 = clip.distance_to(edge1_A);
  620. if (dist0 <= 0) { // Behind plane.
  621. new_vertices.push_back(vertices[k]);
  622. }
  623. // Check for different sides and non coplanar.
  624. if ((dist0 * dist1) < 0) {
  625. // Calculate intersection.
  626. Vector3 rel = edge1_A - edge0_A;
  627. real_t den = clip.normal.dot(rel);
  628. if (Math::is_zero_approx(den)) {
  629. continue; // Point too short.
  630. }
  631. real_t dist = -(clip.normal.dot(edge0_A) - clip.d) / den;
  632. Vector3 inters = edge0_A + rel * dist;
  633. new_vertices.push_back(inters);
  634. }
  635. }
  636. vertices = new_vertices;
  637. }
  638. if (vertices.size() < 3) {
  639. continue;
  640. }
  641. // Result is a clockwise face.
  642. MeshData::Face face;
  643. // Add face indices.
  644. for (int j = 0; j < vertices.size(); j++) {
  645. int idx = -1;
  646. for (int k = 0; k < mesh.vertices.size(); k++) {
  647. if (mesh.vertices[k].distance_to(vertices[j]) < 0.001) {
  648. idx = k;
  649. break;
  650. }
  651. }
  652. if (idx == -1) {
  653. idx = mesh.vertices.size();
  654. mesh.vertices.push_back(vertices[j]);
  655. }
  656. face.indices.push_back(idx);
  657. }
  658. face.plane = p;
  659. mesh.faces.push_back(face);
  660. // Add edge.
  661. for (int j = 0; j < face.indices.size(); j++) {
  662. int a = face.indices[j];
  663. int b = face.indices[(j + 1) % face.indices.size()];
  664. bool found = false;
  665. for (int k = 0; k < mesh.edges.size(); k++) {
  666. if (mesh.edges[k].a == a && mesh.edges[k].b == b) {
  667. found = true;
  668. break;
  669. }
  670. if (mesh.edges[k].b == a && mesh.edges[k].a == b) {
  671. found = true;
  672. break;
  673. }
  674. }
  675. if (found) {
  676. continue;
  677. }
  678. MeshData::Edge edge;
  679. edge.a = a;
  680. edge.b = b;
  681. mesh.edges.push_back(edge);
  682. }
  683. }
  684. return mesh;
  685. }
  686. PoolVector<Plane> Geometry::build_box_planes(const Vector3 &p_extents) {
  687. PoolVector<Plane> planes;
  688. planes.push_back(Plane(Vector3(1, 0, 0), p_extents.x));
  689. planes.push_back(Plane(Vector3(-1, 0, 0), p_extents.x));
  690. planes.push_back(Plane(Vector3(0, 1, 0), p_extents.y));
  691. planes.push_back(Plane(Vector3(0, -1, 0), p_extents.y));
  692. planes.push_back(Plane(Vector3(0, 0, 1), p_extents.z));
  693. planes.push_back(Plane(Vector3(0, 0, -1), p_extents.z));
  694. return planes;
  695. }
  696. PoolVector<Plane> Geometry::build_cylinder_planes(real_t p_radius, real_t p_height, int p_sides, Vector3::Axis p_axis) {
  697. ERR_FAIL_INDEX_V(p_axis, 3, PoolVector<Plane>());
  698. PoolVector<Plane> planes;
  699. for (int i = 0; i < p_sides; i++) {
  700. Vector3 normal;
  701. normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_sides);
  702. normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_sides);
  703. planes.push_back(Plane(normal, p_radius));
  704. }
  705. Vector3 axis;
  706. axis[p_axis] = 1.0;
  707. planes.push_back(Plane(axis, p_height * 0.5));
  708. planes.push_back(Plane(-axis, p_height * 0.5));
  709. return planes;
  710. }
  711. PoolVector<Plane> Geometry::build_sphere_planes(real_t p_radius, int p_lats, int p_lons, Vector3::Axis p_axis) {
  712. ERR_FAIL_INDEX_V(p_axis, 3, PoolVector<Plane>());
  713. PoolVector<Plane> planes;
  714. Vector3 axis;
  715. axis[p_axis] = 1.0;
  716. Vector3 axis_neg;
  717. axis_neg[(p_axis + 1) % 3] = 1.0;
  718. axis_neg[(p_axis + 2) % 3] = 1.0;
  719. axis_neg[p_axis] = -1.0;
  720. for (int i = 0; i < p_lons; i++) {
  721. Vector3 normal;
  722. normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_lons);
  723. normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_lons);
  724. planes.push_back(Plane(normal, p_radius));
  725. for (int j = 1; j <= p_lats; j++) {
  726. // FIXME: This is stupid.
  727. Vector3 angle = normal.linear_interpolate(axis, j / (real_t)p_lats).normalized();
  728. Vector3 pos = angle * p_radius;
  729. planes.push_back(Plane(pos, angle));
  730. planes.push_back(Plane(pos * axis_neg, angle * axis_neg));
  731. }
  732. }
  733. return planes;
  734. }
  735. PoolVector<Plane> Geometry::build_capsule_planes(real_t p_radius, real_t p_height, int p_sides, int p_lats, Vector3::Axis p_axis) {
  736. ERR_FAIL_INDEX_V(p_axis, 3, PoolVector<Plane>());
  737. PoolVector<Plane> planes;
  738. Vector3 axis;
  739. axis[p_axis] = 1.0;
  740. Vector3 axis_neg;
  741. axis_neg[(p_axis + 1) % 3] = 1.0;
  742. axis_neg[(p_axis + 2) % 3] = 1.0;
  743. axis_neg[p_axis] = -1.0;
  744. for (int i = 0; i < p_sides; i++) {
  745. Vector3 normal;
  746. normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_sides);
  747. normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_sides);
  748. planes.push_back(Plane(normal, p_radius));
  749. for (int j = 1; j <= p_lats; j++) {
  750. Vector3 angle = normal.linear_interpolate(axis, j / (real_t)p_lats).normalized();
  751. Vector3 pos = axis * p_height * 0.5 + angle * p_radius;
  752. planes.push_back(Plane(pos, angle));
  753. planes.push_back(Plane(pos * axis_neg, angle * axis_neg));
  754. }
  755. }
  756. return planes;
  757. }
  758. struct _AtlasWorkRect {
  759. Size2i s;
  760. Point2i p;
  761. int idx;
  762. _FORCE_INLINE_ bool operator<(const _AtlasWorkRect &p_r) const { return s.width > p_r.s.width; };
  763. };
  764. struct _AtlasWorkRectResult {
  765. Vector<_AtlasWorkRect> result;
  766. int max_w;
  767. int max_h;
  768. };
  769. void Geometry::make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size) {
  770. // Super simple, almost brute force scanline stacking fitter.
  771. // It's pretty basic for now, but it tries to make sure that the aspect ratio of the
  772. // resulting atlas is somehow square. This is necessary because video cards have limits.
  773. // On texture size (usually 2048 or 4096), so the more square a texture, the more chances.
  774. // It will work in every hardware.
  775. // For example, it will prioritize a 1024x1024 atlas (works everywhere) instead of a
  776. // 256x8192 atlas (won't work anywhere).
  777. ERR_FAIL_COND(p_rects.size() == 0);
  778. for (int i = 0; i < p_rects.size(); i++) {
  779. ERR_FAIL_COND(p_rects[i].width <= 0);
  780. ERR_FAIL_COND(p_rects[i].height <= 0);
  781. }
  782. Vector<_AtlasWorkRect> wrects;
  783. wrects.resize(p_rects.size());
  784. for (int i = 0; i < p_rects.size(); i++) {
  785. wrects.write[i].s = p_rects[i];
  786. wrects.write[i].idx = i;
  787. }
  788. wrects.sort();
  789. int widest = wrects[0].s.width;
  790. Vector<_AtlasWorkRectResult> results;
  791. for (int i = 0; i <= 12; i++) {
  792. int w = 1 << i;
  793. int max_h = 0;
  794. int max_w = 0;
  795. if (w < widest) {
  796. continue;
  797. }
  798. Vector<int> hmax;
  799. hmax.resize(w);
  800. for (int j = 0; j < w; j++) {
  801. hmax.write[j] = 0;
  802. }
  803. // Place them.
  804. int ofs = 0;
  805. int limit_h = 0;
  806. for (int j = 0; j < wrects.size(); j++) {
  807. if (ofs + wrects[j].s.width > w) {
  808. ofs = 0;
  809. }
  810. int from_y = 0;
  811. for (int k = 0; k < wrects[j].s.width; k++) {
  812. if (hmax[ofs + k] > from_y) {
  813. from_y = hmax[ofs + k];
  814. }
  815. }
  816. wrects.write[j].p.x = ofs;
  817. wrects.write[j].p.y = from_y;
  818. int end_h = from_y + wrects[j].s.height;
  819. int end_w = ofs + wrects[j].s.width;
  820. if (ofs == 0) {
  821. limit_h = end_h;
  822. }
  823. for (int k = 0; k < wrects[j].s.width; k++) {
  824. hmax.write[ofs + k] = end_h;
  825. }
  826. if (end_h > max_h) {
  827. max_h = end_h;
  828. }
  829. if (end_w > max_w) {
  830. max_w = end_w;
  831. }
  832. if (ofs == 0 || end_h > limit_h) { // While h limit not reached, keep stacking.
  833. ofs += wrects[j].s.width;
  834. }
  835. }
  836. _AtlasWorkRectResult result;
  837. result.result = wrects;
  838. result.max_h = max_h;
  839. result.max_w = max_w;
  840. results.push_back(result);
  841. }
  842. // Find the result with the best aspect ratio.
  843. int best = -1;
  844. real_t best_aspect = 1e20;
  845. for (int i = 0; i < results.size(); i++) {
  846. real_t h = next_power_of_2(results[i].max_h);
  847. real_t w = next_power_of_2(results[i].max_w);
  848. real_t aspect = h > w ? h / w : w / h;
  849. if (aspect < best_aspect) {
  850. best = i;
  851. best_aspect = aspect;
  852. }
  853. }
  854. r_result.resize(p_rects.size());
  855. for (int i = 0; i < p_rects.size(); i++) {
  856. r_result.write[results[best].result[i].idx] = results[best].result[i].p;
  857. }
  858. r_size = Size2(results[best].max_w, results[best].max_h);
  859. }
  860. 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) {
  861. using namespace ClipperLib;
  862. ClipType op = ctUnion;
  863. switch (p_op) {
  864. case OPERATION_UNION:
  865. op = ctUnion;
  866. break;
  867. case OPERATION_DIFFERENCE:
  868. op = ctDifference;
  869. break;
  870. case OPERATION_INTERSECTION:
  871. op = ctIntersection;
  872. break;
  873. case OPERATION_XOR:
  874. op = ctXor;
  875. break;
  876. }
  877. Path path_a, path_b;
  878. // Need to scale points (Clipper's requirement for robust computation).
  879. for (int i = 0; i != p_polypath_a.size(); ++i) {
  880. path_a << IntPoint(p_polypath_a[i].x * SCALE_FACTOR, p_polypath_a[i].y * SCALE_FACTOR);
  881. }
  882. for (int i = 0; i != p_polypath_b.size(); ++i) {
  883. path_b << IntPoint(p_polypath_b[i].x * SCALE_FACTOR, p_polypath_b[i].y * SCALE_FACTOR);
  884. }
  885. Clipper clp;
  886. clp.AddPath(path_a, ptSubject, !is_a_open); // Forward compatible with Clipper 10.0.0.
  887. clp.AddPath(path_b, ptClip, true); // Polylines cannot be set as clip.
  888. Paths paths;
  889. if (is_a_open) {
  890. PolyTree tree; // Needed to populate polylines.
  891. clp.Execute(op, tree);
  892. OpenPathsFromPolyTree(tree, paths);
  893. } else {
  894. clp.Execute(op, paths); // Works on closed polygons only.
  895. }
  896. // Have to scale points down now.
  897. Vector<Vector<Point2>> polypaths;
  898. for (Paths::size_type i = 0; i < paths.size(); ++i) {
  899. Vector<Vector2> polypath;
  900. const Path &scaled_path = paths[i];
  901. for (Paths::size_type j = 0; j < scaled_path.size(); ++j) {
  902. polypath.push_back(Point2(
  903. static_cast<real_t>(scaled_path[j].X) / SCALE_FACTOR,
  904. static_cast<real_t>(scaled_path[j].Y) / SCALE_FACTOR));
  905. }
  906. polypaths.push_back(polypath);
  907. }
  908. return polypaths;
  909. }
  910. Vector<Vector<Point2>> Geometry::_polypath_offset(const Vector<Point2> &p_polypath, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) {
  911. using namespace ClipperLib;
  912. JoinType jt = jtSquare;
  913. switch (p_join_type) {
  914. case JOIN_SQUARE:
  915. jt = jtSquare;
  916. break;
  917. case JOIN_ROUND:
  918. jt = jtRound;
  919. break;
  920. case JOIN_MITER:
  921. jt = jtMiter;
  922. break;
  923. }
  924. EndType et = etClosedPolygon;
  925. switch (p_end_type) {
  926. case END_POLYGON:
  927. et = etClosedPolygon;
  928. break;
  929. case END_JOINED:
  930. et = etClosedLine;
  931. break;
  932. case END_BUTT:
  933. et = etOpenButt;
  934. break;
  935. case END_SQUARE:
  936. et = etOpenSquare;
  937. break;
  938. case END_ROUND:
  939. et = etOpenRound;
  940. break;
  941. }
  942. ClipperOffset co(2.0, 0.25 * SCALE_FACTOR); // Defaults from ClipperOffset.
  943. Path path;
  944. // Need to scale points (Clipper's requirement for robust computation).
  945. for (int i = 0; i != p_polypath.size(); ++i) {
  946. path << IntPoint(p_polypath[i].x * SCALE_FACTOR, p_polypath[i].y * SCALE_FACTOR);
  947. }
  948. co.AddPath(path, jt, et);
  949. Paths paths;
  950. co.Execute(paths, p_delta * SCALE_FACTOR); // Inflate/deflate.
  951. // Have to scale points down now.
  952. Vector<Vector<Point2>> polypaths;
  953. for (Paths::size_type i = 0; i < paths.size(); ++i) {
  954. Vector<Vector2> polypath;
  955. const Path &scaled_path = paths[i];
  956. for (Paths::size_type j = 0; j < scaled_path.size(); ++j) {
  957. polypath.push_back(Point2(
  958. static_cast<real_t>(scaled_path[j].X) / SCALE_FACTOR,
  959. static_cast<real_t>(scaled_path[j].Y) / SCALE_FACTOR));
  960. }
  961. polypaths.push_back(polypath);
  962. }
  963. return polypaths;
  964. }
  965. real_t Geometry::calculate_convex_hull_volume(const Geometry::MeshData &p_md) {
  966. if (!p_md.vertices.size()) {
  967. return 0.0;
  968. }
  969. // find center
  970. Vector3 center;
  971. for (int n = 0; n < p_md.vertices.size(); n++) {
  972. center += p_md.vertices[n];
  973. }
  974. center /= p_md.vertices.size();
  975. Face3 fa;
  976. real_t volume = 0.0;
  977. // volume of each cone is 1/3 * height * area of face
  978. for (int f = 0; f < p_md.faces.size(); f++) {
  979. const Geometry::MeshData::Face &face = p_md.faces[f];
  980. real_t height = 0.0;
  981. real_t face_area = 0.0;
  982. for (int c = 0; c < face.indices.size() - 2; c++) {
  983. fa.vertex[0] = p_md.vertices[face.indices[0]];
  984. fa.vertex[1] = p_md.vertices[face.indices[c + 1]];
  985. fa.vertex[2] = p_md.vertices[face.indices[c + 2]];
  986. if (!c) {
  987. // calculate height
  988. Plane plane(fa.vertex[0], fa.vertex[1], fa.vertex[2]);
  989. height = -plane.distance_to(center);
  990. }
  991. face_area += Math::sqrt(fa.get_twice_area_squared());
  992. }
  993. volume += face_area * height;
  994. }
  995. volume *= (1.0 / 3.0) * 0.5;
  996. return volume;
  997. }
  998. // note this function is slow, because it builds meshes etc. Not ideal to use in realtime.
  999. // Planes must face OUTWARD from the center of the convex hull, by convention.
  1000. bool Geometry::convex_hull_intersects_convex_hull(const Plane *p_planes_a, int p_plane_count_a, const Plane *p_planes_b, int p_plane_count_b) {
  1001. if (!p_plane_count_a || !p_plane_count_b) {
  1002. return false;
  1003. }
  1004. // OR alternative approach, we can call compute_convex_mesh_points()
  1005. // with both sets of planes, to get an intersection. Not sure which method is
  1006. // faster... this may be faster with more complex hulls.
  1007. // the usual silliness to get from one vector format to another...
  1008. PoolVector<Plane> planes_a;
  1009. PoolVector<Plane> planes_b;
  1010. {
  1011. planes_a.resize(p_plane_count_a);
  1012. PoolVector<Plane>::Write w = planes_a.write();
  1013. memcpy(w.ptr(), p_planes_a, p_plane_count_a * sizeof(Plane));
  1014. }
  1015. {
  1016. planes_b.resize(p_plane_count_b);
  1017. PoolVector<Plane>::Write w = planes_b.write();
  1018. memcpy(w.ptr(), p_planes_b, p_plane_count_b * sizeof(Plane));
  1019. }
  1020. Geometry::MeshData md_A = build_convex_mesh(planes_a);
  1021. Geometry::MeshData md_B = build_convex_mesh(planes_b);
  1022. // hull can't be built
  1023. if (!md_A.vertices.size() || !md_B.vertices.size()) {
  1024. return false;
  1025. }
  1026. // first check the points against the planes
  1027. for (int p = 0; p < p_plane_count_a; p++) {
  1028. const Plane &plane = p_planes_a[p];
  1029. for (int n = 0; n < md_B.vertices.size(); n++) {
  1030. if (!plane.is_point_over(md_B.vertices[n])) {
  1031. return true;
  1032. }
  1033. }
  1034. }
  1035. for (int p = 0; p < p_plane_count_b; p++) {
  1036. const Plane &plane = p_planes_b[p];
  1037. for (int n = 0; n < md_A.vertices.size(); n++) {
  1038. if (!plane.is_point_over(md_A.vertices[n])) {
  1039. return true;
  1040. }
  1041. }
  1042. }
  1043. // now check edges
  1044. for (int n = 0; n < md_A.edges.size(); n++) {
  1045. const Vector3 &pt_a = md_A.vertices[md_A.edges[n].a];
  1046. const Vector3 &pt_b = md_A.vertices[md_A.edges[n].b];
  1047. if (segment_intersects_convex(pt_a, pt_b, p_planes_b, p_plane_count_b, nullptr, nullptr)) {
  1048. return true;
  1049. }
  1050. }
  1051. for (int n = 0; n < md_B.edges.size(); n++) {
  1052. const Vector3 &pt_a = md_B.vertices[md_B.edges[n].a];
  1053. const Vector3 &pt_b = md_B.vertices[md_B.edges[n].b];
  1054. if (segment_intersects_convex(pt_a, pt_b, p_planes_a, p_plane_count_a, nullptr, nullptr)) {
  1055. return true;
  1056. }
  1057. }
  1058. return false;
  1059. }
  1060. Vector<Vector3> Geometry::compute_convex_mesh_points(const Plane *p_planes, int p_plane_count, real_t p_epsilon) {
  1061. Vector<Vector3> points;
  1062. // Iterate through every unique combination of any three planes.
  1063. for (int i = p_plane_count - 1; i >= 0; i--) {
  1064. for (int j = i - 1; j >= 0; j--) {
  1065. for (int k = j - 1; k >= 0; k--) {
  1066. // Find the point where these planes all cross over (if they
  1067. // do at all).
  1068. Vector3 convex_shape_point;
  1069. if (p_planes[i].intersect_3(p_planes[j], p_planes[k], &convex_shape_point)) {
  1070. // See if any *other* plane excludes this point because it's
  1071. // on the wrong side.
  1072. bool excluded = false;
  1073. for (int n = 0; n < p_plane_count; n++) {
  1074. if (n != i && n != j && n != k) {
  1075. real_t dist = p_planes[n].distance_to(convex_shape_point);
  1076. if (dist > p_epsilon) {
  1077. excluded = true;
  1078. break;
  1079. }
  1080. }
  1081. }
  1082. // Only add the point if it passed all tests.
  1083. if (!excluded) {
  1084. points.push_back(convex_shape_point);
  1085. }
  1086. }
  1087. }
  1088. }
  1089. }
  1090. return points;
  1091. }
  1092. Vector<Geometry::PackRectsResult> Geometry::partial_pack_rects(const Vector<Vector2i> &p_sizes, const Size2i &p_atlas_size) {
  1093. Vector<stbrp_node> nodes;
  1094. nodes.resize(p_atlas_size.width);
  1095. memset(nodes.ptrw(), 0, sizeof(stbrp_node) * nodes.size());
  1096. stbrp_context context;
  1097. stbrp_init_target(&context, p_atlas_size.width, p_atlas_size.height, nodes.ptrw(), p_atlas_size.width);
  1098. Vector<stbrp_rect> rects;
  1099. rects.resize(p_sizes.size());
  1100. for (int i = 0; i < p_sizes.size(); i++) {
  1101. rects.write[i].id = i;
  1102. rects.write[i].w = p_sizes[i].width;
  1103. rects.write[i].h = p_sizes[i].height;
  1104. rects.write[i].x = 0;
  1105. rects.write[i].y = 0;
  1106. rects.write[i].was_packed = 0;
  1107. }
  1108. stbrp_pack_rects(&context, rects.ptrw(), rects.size());
  1109. Vector<PackRectsResult> ret;
  1110. ret.resize(p_sizes.size());
  1111. for (int i = 0; i < p_sizes.size(); i++) {
  1112. ret.write[rects[i].id] = { rects[i].x, rects[i].y, static_cast<bool>(rects[i].was_packed) };
  1113. }
  1114. return ret;
  1115. }
  1116. // Expects polygon as a triangle fan
  1117. real_t Geometry::find_polygon_area(const Vector3 *p_verts, int p_num_verts) {
  1118. if (!p_verts || (p_num_verts < 3)) {
  1119. return 0.0;
  1120. }
  1121. Face3 f;
  1122. f.vertex[0] = p_verts[0];
  1123. f.vertex[1] = p_verts[1];
  1124. f.vertex[2] = p_verts[1];
  1125. real_t area = 0.0;
  1126. for (int n = 2; n < p_num_verts; n++) {
  1127. f.vertex[1] = f.vertex[2];
  1128. f.vertex[2] = p_verts[n];
  1129. area += Math::sqrt(f.get_twice_area_squared());
  1130. }
  1131. return area * 0.5;
  1132. }
  1133. // adapted from:
  1134. // https://stackoverflow.com/questions/6989100/sort-points-in-clockwise-order
  1135. void Geometry::sort_polygon_winding(Vector<Vector2> &r_verts, bool p_clockwise) {
  1136. // sort winding order of a (primarily convex) polygon.
  1137. // It can handle some concave polygons, but not
  1138. // where a vertex 'goes back on' a previous vertex ..
  1139. // i.e. it will change the shape in some concave cases.
  1140. struct ElementComparator {
  1141. Vector2 center;
  1142. bool operator()(const Vector2 &a, const Vector2 &b) const {
  1143. if (a.x - center.x >= 0 && b.x - center.x < 0) {
  1144. return true;
  1145. }
  1146. if (a.x - center.x < 0 && b.x - center.x >= 0) {
  1147. return false;
  1148. }
  1149. if (a.x - center.x == 0 && b.x - center.x == 0) {
  1150. if (a.y - center.y >= 0 || b.y - center.y >= 0) {
  1151. return a.y > b.y;
  1152. }
  1153. return b.y > a.y;
  1154. }
  1155. // compute the cross product of vectors (center -> a) x (center -> b)
  1156. real_t det = (a.x - center.x) * (b.y - center.y) - (b.x - center.x) * (a.y - center.y);
  1157. if (det < 0.0) {
  1158. return true;
  1159. }
  1160. if (det > 0.0) {
  1161. return false;
  1162. }
  1163. // points a and b are on the same line from the center
  1164. // check which point is closer to the center
  1165. real_t d1 = (a.x - center.x) * (a.x - center.x) + (a.y - center.y) * (a.y - center.y);
  1166. real_t d2 = (b.x - center.x) * (b.x - center.x) + (b.y - center.y) * (b.y - center.y);
  1167. return d1 > d2;
  1168. }
  1169. };
  1170. int npoints = r_verts.size();
  1171. if (!npoints) {
  1172. return;
  1173. }
  1174. // first calculate center
  1175. Vector2 center;
  1176. for (int n = 0; n < npoints; n++) {
  1177. center += r_verts[n];
  1178. }
  1179. center /= npoints;
  1180. SortArray<Vector2, ElementComparator> sorter;
  1181. sorter.compare.center = center;
  1182. sorter.sort(r_verts.ptrw(), r_verts.size());
  1183. // if not clockwise, reverse order
  1184. if (!p_clockwise) {
  1185. r_verts.invert();
  1186. }
  1187. }