geometry.cpp 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  1. /*************************************************************************/
  2. /* geometry.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 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. bool Geometry::is_point_in_polygon(const Vector2 &p_point, const Vector<Vector2> &p_polygon) {
  33. Vector<int> indices = Geometry::triangulate_polygon(p_polygon);
  34. for (int j = 0; j + 3 <= indices.size(); j += 3) {
  35. int i1 = indices[j], i2 = indices[j + 1], i3 = indices[j + 2];
  36. if (Geometry::is_point_in_triangle(p_point, p_polygon[i1], p_polygon[i2], p_polygon[i3]))
  37. return true;
  38. }
  39. return false;
  40. }
  41. void Geometry::MeshData::optimize_vertices() {
  42. Map<int, int> vtx_remap;
  43. for (int i = 0; i < faces.size(); i++) {
  44. for (int j = 0; j < faces[i].indices.size(); j++) {
  45. int idx = faces[i].indices[j];
  46. if (!vtx_remap.has(idx)) {
  47. int ni = vtx_remap.size();
  48. vtx_remap[idx] = ni;
  49. }
  50. faces.write[i].indices.write[j] = vtx_remap[idx];
  51. }
  52. }
  53. for (int i = 0; i < edges.size(); i++) {
  54. int a = edges[i].a;
  55. int b = edges[i].b;
  56. if (!vtx_remap.has(a)) {
  57. int ni = vtx_remap.size();
  58. vtx_remap[a] = ni;
  59. }
  60. if (!vtx_remap.has(b)) {
  61. int ni = vtx_remap.size();
  62. vtx_remap[b] = ni;
  63. }
  64. edges.write[i].a = vtx_remap[a];
  65. edges.write[i].b = vtx_remap[b];
  66. }
  67. Vector<Vector3> new_vertices;
  68. new_vertices.resize(vtx_remap.size());
  69. for (int i = 0; i < vertices.size(); i++) {
  70. if (vtx_remap.has(i))
  71. new_vertices.write[vtx_remap[i]] = vertices[i];
  72. }
  73. vertices = new_vertices;
  74. }
  75. Vector<Vector<Vector2> > (*Geometry::_decompose_func)(const Vector<Vector2> &p_polygon) = NULL;
  76. struct _FaceClassify {
  77. struct _Link {
  78. int face;
  79. int edge;
  80. void clear() {
  81. face = -1;
  82. edge = -1;
  83. }
  84. _Link() {
  85. face = -1;
  86. edge = -1;
  87. }
  88. };
  89. bool valid;
  90. int group;
  91. _Link links[3];
  92. Face3 face;
  93. _FaceClassify() {
  94. group = -1;
  95. valid = false;
  96. };
  97. };
  98. static bool _connect_faces(_FaceClassify *p_faces, int len, int p_group) {
  99. /* connect faces, error will occur if an edge is shared between more than 2 faces */
  100. /* clear connections */
  101. bool error = false;
  102. for (int i = 0; i < len; i++) {
  103. for (int j = 0; j < 3; j++) {
  104. p_faces[i].links[j].clear();
  105. }
  106. }
  107. for (int i = 0; i < len; i++) {
  108. if (p_faces[i].group != p_group)
  109. continue;
  110. for (int j = i + 1; j < len; j++) {
  111. if (p_faces[j].group != p_group)
  112. continue;
  113. for (int k = 0; k < 3; k++) {
  114. Vector3 vi1 = p_faces[i].face.vertex[k];
  115. Vector3 vi2 = p_faces[i].face.vertex[(k + 1) % 3];
  116. for (int l = 0; l < 3; l++) {
  117. Vector3 vj2 = p_faces[j].face.vertex[l];
  118. Vector3 vj1 = p_faces[j].face.vertex[(l + 1) % 3];
  119. if (vi1.distance_to(vj1) < 0.00001 &&
  120. vi2.distance_to(vj2) < 0.00001) {
  121. if (p_faces[i].links[k].face != -1) {
  122. ERR_PRINT("already linked\n");
  123. error = true;
  124. break;
  125. }
  126. if (p_faces[j].links[l].face != -1) {
  127. ERR_PRINT("already linked\n");
  128. error = true;
  129. break;
  130. }
  131. p_faces[i].links[k].face = j;
  132. p_faces[i].links[k].edge = l;
  133. p_faces[j].links[l].face = i;
  134. p_faces[j].links[l].edge = k;
  135. }
  136. }
  137. if (error)
  138. break;
  139. }
  140. if (error)
  141. break;
  142. }
  143. if (error)
  144. break;
  145. }
  146. for (int i = 0; i < len; i++) {
  147. p_faces[i].valid = true;
  148. for (int j = 0; j < 3; j++) {
  149. if (p_faces[i].links[j].face == -1)
  150. p_faces[i].valid = false;
  151. }
  152. /*printf("face %i is valid: %i, group %i. connected to %i:%i,%i:%i,%i:%i\n",i,p_faces[i].valid,p_faces[i].group,
  153. p_faces[i].links[0].face,
  154. p_faces[i].links[0].edge,
  155. p_faces[i].links[1].face,
  156. p_faces[i].links[1].edge,
  157. p_faces[i].links[2].face,
  158. p_faces[i].links[2].edge);*/
  159. }
  160. return error;
  161. }
  162. static bool _group_face(_FaceClassify *p_faces, int len, int p_index, int p_group) {
  163. if (p_faces[p_index].group >= 0)
  164. return false;
  165. p_faces[p_index].group = p_group;
  166. for (int i = 0; i < 3; i++) {
  167. ERR_FAIL_INDEX_V(p_faces[p_index].links[i].face, len, true);
  168. _group_face(p_faces, len, p_faces[p_index].links[i].face, p_group);
  169. }
  170. return true;
  171. }
  172. PoolVector<PoolVector<Face3> > Geometry::separate_objects(PoolVector<Face3> p_array) {
  173. PoolVector<PoolVector<Face3> > objects;
  174. int len = p_array.size();
  175. PoolVector<Face3>::Read r = p_array.read();
  176. const Face3 *arrayptr = r.ptr();
  177. PoolVector<_FaceClassify> fc;
  178. fc.resize(len);
  179. PoolVector<_FaceClassify>::Write fcw = fc.write();
  180. _FaceClassify *_fcptr = fcw.ptr();
  181. for (int i = 0; i < len; i++) {
  182. _fcptr[i].face = arrayptr[i];
  183. }
  184. bool error = _connect_faces(_fcptr, len, -1);
  185. if (error) {
  186. ERR_FAIL_COND_V(error, PoolVector<PoolVector<Face3> >()); // invalid geometry
  187. }
  188. /* group connected faces in separate objects */
  189. int group = 0;
  190. for (int i = 0; i < len; i++) {
  191. if (!_fcptr[i].valid)
  192. continue;
  193. if (_group_face(_fcptr, len, i, group)) {
  194. group++;
  195. }
  196. }
  197. /* group connected faces in separate objects */
  198. for (int i = 0; i < len; i++) {
  199. _fcptr[i].face = arrayptr[i];
  200. }
  201. if (group >= 0) {
  202. objects.resize(group);
  203. PoolVector<PoolVector<Face3> >::Write obw = objects.write();
  204. PoolVector<Face3> *group_faces = obw.ptr();
  205. for (int i = 0; i < len; i++) {
  206. if (!_fcptr[i].valid)
  207. continue;
  208. if (_fcptr[i].group >= 0 && _fcptr[i].group < group) {
  209. group_faces[_fcptr[i].group].push_back(_fcptr[i].face);
  210. }
  211. }
  212. }
  213. return objects;
  214. }
  215. /*** GEOMETRY WRAPPER ***/
  216. enum _CellFlags {
  217. _CELL_SOLID = 1,
  218. _CELL_EXTERIOR = 2,
  219. _CELL_STEP_MASK = 0x1C,
  220. _CELL_STEP_NONE = 0 << 2,
  221. _CELL_STEP_Y_POS = 1 << 2,
  222. _CELL_STEP_Y_NEG = 2 << 2,
  223. _CELL_STEP_X_POS = 3 << 2,
  224. _CELL_STEP_X_NEG = 4 << 2,
  225. _CELL_STEP_Z_POS = 5 << 2,
  226. _CELL_STEP_Z_NEG = 6 << 2,
  227. _CELL_STEP_DONE = 7 << 2,
  228. _CELL_PREV_MASK = 0xE0,
  229. _CELL_PREV_NONE = 0 << 5,
  230. _CELL_PREV_Y_POS = 1 << 5,
  231. _CELL_PREV_Y_NEG = 2 << 5,
  232. _CELL_PREV_X_POS = 3 << 5,
  233. _CELL_PREV_X_NEG = 4 << 5,
  234. _CELL_PREV_Z_POS = 5 << 5,
  235. _CELL_PREV_Z_NEG = 6 << 5,
  236. _CELL_PREV_FIRST = 7 << 5,
  237. };
  238. 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) {
  239. AABB aabb(Vector3(x, y, z), Vector3(len_x, len_y, len_z));
  240. aabb.position = aabb.position * voxelsize;
  241. aabb.size = aabb.size * voxelsize;
  242. if (!p_face.intersects_aabb(aabb))
  243. return;
  244. if (len_x == 1 && len_y == 1 && len_z == 1) {
  245. p_cell_status[x][y][z] = _CELL_SOLID;
  246. return;
  247. }
  248. int div_x = len_x > 1 ? 2 : 1;
  249. int div_y = len_y > 1 ? 2 : 1;
  250. int div_z = len_z > 1 ? 2 : 1;
  251. #define _SPLIT(m_i, m_div, m_v, m_len_v, m_new_v, m_new_len_v) \
  252. if (m_div == 1) { \
  253. m_new_v = m_v; \
  254. m_new_len_v = 1; \
  255. } else if (m_i == 0) { \
  256. m_new_v = m_v; \
  257. m_new_len_v = m_len_v / 2; \
  258. } else { \
  259. m_new_v = m_v + m_len_v / 2; \
  260. m_new_len_v = m_len_v - m_len_v / 2; \
  261. }
  262. int new_x;
  263. int new_len_x;
  264. int new_y;
  265. int new_len_y;
  266. int new_z;
  267. int new_len_z;
  268. for (int i = 0; i < div_x; i++) {
  269. _SPLIT(i, div_x, x, len_x, new_x, new_len_x);
  270. for (int j = 0; j < div_y; j++) {
  271. _SPLIT(j, div_y, y, len_y, new_y, new_len_y);
  272. for (int k = 0; k < div_z; k++) {
  273. _SPLIT(k, div_z, z, len_z, new_z, new_len_z);
  274. _plot_face(p_cell_status, new_x, new_y, new_z, new_len_x, new_len_y, new_len_z, voxelsize, p_face);
  275. }
  276. }
  277. }
  278. }
  279. 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) {
  280. if (p_cell_status[x][y][z] & 3)
  281. return; // nothing to do, already used and/or visited
  282. p_cell_status[x][y][z] = _CELL_PREV_FIRST;
  283. while (true) {
  284. uint8_t &c = p_cell_status[x][y][z];
  285. //printf("at %i,%i,%i\n",x,y,z);
  286. if ((c & _CELL_STEP_MASK) == _CELL_STEP_NONE) {
  287. /* Haven't been in here, mark as outside */
  288. p_cell_status[x][y][z] |= _CELL_EXTERIOR;
  289. //printf("not marked as anything, marking exterior\n");
  290. }
  291. //printf("cell step is %i\n",(c&_CELL_STEP_MASK));
  292. if ((c & _CELL_STEP_MASK) != _CELL_STEP_DONE) {
  293. /* if not done, increase step */
  294. c += 1 << 2;
  295. //printf("incrementing cell step\n");
  296. }
  297. if ((c & _CELL_STEP_MASK) == _CELL_STEP_DONE) {
  298. /* Go back */
  299. //printf("done, going back a cell\n");
  300. switch (c & _CELL_PREV_MASK) {
  301. case _CELL_PREV_FIRST: {
  302. //printf("at end, finished marking\n");
  303. return;
  304. } break;
  305. case _CELL_PREV_Y_POS: {
  306. y++;
  307. ERR_FAIL_COND(y >= len_y);
  308. } break;
  309. case _CELL_PREV_Y_NEG: {
  310. y--;
  311. ERR_FAIL_COND(y < 0);
  312. } break;
  313. case _CELL_PREV_X_POS: {
  314. x++;
  315. ERR_FAIL_COND(x >= len_x);
  316. } break;
  317. case _CELL_PREV_X_NEG: {
  318. x--;
  319. ERR_FAIL_COND(x < 0);
  320. } break;
  321. case _CELL_PREV_Z_POS: {
  322. z++;
  323. ERR_FAIL_COND(z >= len_z);
  324. } break;
  325. case _CELL_PREV_Z_NEG: {
  326. z--;
  327. ERR_FAIL_COND(z < 0);
  328. } break;
  329. default: {
  330. ERR_FAIL();
  331. }
  332. }
  333. continue;
  334. }
  335. //printf("attempting new cell!\n");
  336. int next_x = x, next_y = y, next_z = z;
  337. uint8_t prev = 0;
  338. switch (c & _CELL_STEP_MASK) {
  339. case _CELL_STEP_Y_POS: {
  340. next_y++;
  341. prev = _CELL_PREV_Y_NEG;
  342. } break;
  343. case _CELL_STEP_Y_NEG: {
  344. next_y--;
  345. prev = _CELL_PREV_Y_POS;
  346. } break;
  347. case _CELL_STEP_X_POS: {
  348. next_x++;
  349. prev = _CELL_PREV_X_NEG;
  350. } break;
  351. case _CELL_STEP_X_NEG: {
  352. next_x--;
  353. prev = _CELL_PREV_X_POS;
  354. } break;
  355. case _CELL_STEP_Z_POS: {
  356. next_z++;
  357. prev = _CELL_PREV_Z_NEG;
  358. } break;
  359. case _CELL_STEP_Z_NEG: {
  360. next_z--;
  361. prev = _CELL_PREV_Z_POS;
  362. } break;
  363. default: ERR_FAIL();
  364. }
  365. //printf("testing if new cell will be ok...!\n");
  366. if (next_x < 0 || next_x >= len_x)
  367. continue;
  368. if (next_y < 0 || next_y >= len_y)
  369. continue;
  370. if (next_z < 0 || next_z >= len_z)
  371. continue;
  372. //printf("testing if new cell is traversable\n");
  373. if (p_cell_status[next_x][next_y][next_z] & 3)
  374. continue;
  375. //printf("move to it\n");
  376. x = next_x;
  377. y = next_y;
  378. z = next_z;
  379. p_cell_status[x][y][z] |= prev;
  380. }
  381. }
  382. 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) {
  383. ERR_FAIL_INDEX(x, len_x);
  384. ERR_FAIL_INDEX(y, len_y);
  385. ERR_FAIL_INDEX(z, len_z);
  386. if (p_cell_status[x][y][z] & _CELL_EXTERIOR)
  387. return;
  388. /* static const Vector3 vertices[8]={
  389. Vector3(0,0,0),
  390. Vector3(0,0,1),
  391. Vector3(0,1,0),
  392. Vector3(0,1,1),
  393. Vector3(1,0,0),
  394. Vector3(1,0,1),
  395. Vector3(1,1,0),
  396. Vector3(1,1,1),
  397. };
  398. */
  399. #define vert(m_idx) Vector3((m_idx & 4) >> 2, (m_idx & 2) >> 1, m_idx & 1)
  400. static const uint8_t indices[6][4] = {
  401. { 7, 6, 4, 5 },
  402. { 7, 3, 2, 6 },
  403. { 7, 5, 1, 3 },
  404. { 0, 2, 3, 1 },
  405. { 0, 1, 5, 4 },
  406. { 0, 4, 6, 2 },
  407. };
  408. /*
  409. {0,1,2,3},
  410. {0,1,4,5},
  411. {0,2,4,6},
  412. {4,5,6,7},
  413. {2,3,7,6},
  414. {1,3,5,7},
  415. {0,2,3,1},
  416. {0,1,5,4},
  417. {0,4,6,2},
  418. {7,6,4,5},
  419. {7,3,2,6},
  420. {7,5,1,3},
  421. */
  422. for (int i = 0; i < 6; i++) {
  423. Vector3 face_points[4];
  424. int disp_x = x + ((i % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  425. int disp_y = y + (((i - 1) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  426. int disp_z = z + (((i - 2) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  427. bool plot = false;
  428. if (disp_x < 0 || disp_x >= len_x)
  429. plot = true;
  430. if (disp_y < 0 || disp_y >= len_y)
  431. plot = true;
  432. if (disp_z < 0 || disp_z >= len_z)
  433. plot = true;
  434. if (!plot && (p_cell_status[disp_x][disp_y][disp_z] & _CELL_EXTERIOR))
  435. plot = true;
  436. if (!plot)
  437. continue;
  438. for (int j = 0; j < 4; j++)
  439. face_points[j] = vert(indices[i][j]) + Vector3(x, y, z);
  440. p_faces.push_back(
  441. Face3(
  442. face_points[0],
  443. face_points[1],
  444. face_points[2]));
  445. p_faces.push_back(
  446. Face3(
  447. face_points[2],
  448. face_points[3],
  449. face_points[0]));
  450. }
  451. }
  452. PoolVector<Face3> Geometry::wrap_geometry(PoolVector<Face3> p_array, real_t *p_error) {
  453. #define _MIN_SIZE 1.0
  454. #define _MAX_LENGTH 20
  455. int face_count = p_array.size();
  456. PoolVector<Face3>::Read facesr = p_array.read();
  457. const Face3 *faces = facesr.ptr();
  458. AABB global_aabb;
  459. for (int i = 0; i < face_count; i++) {
  460. if (i == 0) {
  461. global_aabb = faces[i].get_aabb();
  462. } else {
  463. global_aabb.merge_with(faces[i].get_aabb());
  464. }
  465. }
  466. global_aabb.grow_by(0.01); // avoid numerical error
  467. // determine amount of cells in grid axis
  468. int div_x, div_y, div_z;
  469. if (global_aabb.size.x / _MIN_SIZE < _MAX_LENGTH)
  470. div_x = (int)(global_aabb.size.x / _MIN_SIZE) + 1;
  471. else
  472. div_x = _MAX_LENGTH;
  473. if (global_aabb.size.y / _MIN_SIZE < _MAX_LENGTH)
  474. div_y = (int)(global_aabb.size.y / _MIN_SIZE) + 1;
  475. else
  476. div_y = _MAX_LENGTH;
  477. if (global_aabb.size.z / _MIN_SIZE < _MAX_LENGTH)
  478. div_z = (int)(global_aabb.size.z / _MIN_SIZE) + 1;
  479. else
  480. div_z = _MAX_LENGTH;
  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. return wrapped_faces;
  554. }
  555. Geometry::MeshData Geometry::build_convex_mesh(const PoolVector<Plane> &p_planes) {
  556. MeshData mesh;
  557. #define SUBPLANE_SIZE 1024.0
  558. real_t subplane_size = 1024.0; // should compute this from the actual plane
  559. for (int i = 0; i < p_planes.size(); i++) {
  560. Plane p = p_planes[i];
  561. Vector3 ref = Vector3(0.0, 1.0, 0.0);
  562. if (ABS(p.normal.dot(ref)) > 0.95)
  563. ref = Vector3(0.0, 0.0, 1.0); // change axis
  564. Vector3 right = p.normal.cross(ref).normalized();
  565. Vector3 up = p.normal.cross(right).normalized();
  566. Vector<Vector3> vertices;
  567. Vector3 center = p.get_any_point();
  568. // make a quad clockwise
  569. vertices.push_back(center - up * subplane_size + right * subplane_size);
  570. vertices.push_back(center - up * subplane_size - right * subplane_size);
  571. vertices.push_back(center + up * subplane_size - right * subplane_size);
  572. vertices.push_back(center + up * subplane_size + right * subplane_size);
  573. for (int j = 0; j < p_planes.size(); j++) {
  574. if (j == i)
  575. continue;
  576. Vector<Vector3> new_vertices;
  577. Plane clip = p_planes[j];
  578. if (clip.normal.dot(p.normal) > 0.95)
  579. continue;
  580. if (vertices.size() < 3)
  581. break;
  582. for (int k = 0; k < vertices.size(); k++) {
  583. int k_n = (k + 1) % vertices.size();
  584. Vector3 edge0_A = vertices[k];
  585. Vector3 edge1_A = vertices[k_n];
  586. real_t dist0 = clip.distance_to(edge0_A);
  587. real_t dist1 = clip.distance_to(edge1_A);
  588. if (dist0 <= 0) { // behind plane
  589. new_vertices.push_back(vertices[k]);
  590. }
  591. // check for different sides and non coplanar
  592. if ((dist0 * dist1) < 0) {
  593. // calculate intersection
  594. Vector3 rel = edge1_A - edge0_A;
  595. real_t den = clip.normal.dot(rel);
  596. if (Math::abs(den) < CMP_EPSILON)
  597. continue; // point too short
  598. real_t dist = -(clip.normal.dot(edge0_A) - clip.d) / den;
  599. Vector3 inters = edge0_A + rel * dist;
  600. new_vertices.push_back(inters);
  601. }
  602. }
  603. vertices = new_vertices;
  604. }
  605. if (vertices.size() < 3)
  606. continue;
  607. //result is a clockwise face
  608. MeshData::Face face;
  609. // add face indices
  610. for (int j = 0; j < vertices.size(); j++) {
  611. int idx = -1;
  612. for (int k = 0; k < mesh.vertices.size(); k++) {
  613. if (mesh.vertices[k].distance_to(vertices[j]) < 0.001) {
  614. idx = k;
  615. break;
  616. }
  617. }
  618. if (idx == -1) {
  619. idx = mesh.vertices.size();
  620. mesh.vertices.push_back(vertices[j]);
  621. }
  622. face.indices.push_back(idx);
  623. }
  624. face.plane = p;
  625. mesh.faces.push_back(face);
  626. //add edge
  627. for (int j = 0; j < face.indices.size(); j++) {
  628. int a = face.indices[j];
  629. int b = face.indices[(j + 1) % face.indices.size()];
  630. bool found = false;
  631. for (int k = 0; k < mesh.edges.size(); k++) {
  632. if (mesh.edges[k].a == a && mesh.edges[k].b == b) {
  633. found = true;
  634. break;
  635. }
  636. if (mesh.edges[k].b == a && mesh.edges[k].a == b) {
  637. found = true;
  638. break;
  639. }
  640. }
  641. if (found)
  642. continue;
  643. MeshData::Edge edge;
  644. edge.a = a;
  645. edge.b = b;
  646. mesh.edges.push_back(edge);
  647. }
  648. }
  649. return mesh;
  650. }
  651. PoolVector<Plane> Geometry::build_box_planes(const Vector3 &p_extents) {
  652. PoolVector<Plane> planes;
  653. planes.push_back(Plane(Vector3(1, 0, 0), p_extents.x));
  654. planes.push_back(Plane(Vector3(-1, 0, 0), p_extents.x));
  655. planes.push_back(Plane(Vector3(0, 1, 0), p_extents.y));
  656. planes.push_back(Plane(Vector3(0, -1, 0), p_extents.y));
  657. planes.push_back(Plane(Vector3(0, 0, 1), p_extents.z));
  658. planes.push_back(Plane(Vector3(0, 0, -1), p_extents.z));
  659. return planes;
  660. }
  661. PoolVector<Plane> Geometry::build_cylinder_planes(real_t p_radius, real_t p_height, int p_sides, Vector3::Axis p_axis) {
  662. PoolVector<Plane> planes;
  663. for (int i = 0; i < p_sides; i++) {
  664. Vector3 normal;
  665. normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_sides);
  666. normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_sides);
  667. planes.push_back(Plane(normal, p_radius));
  668. }
  669. Vector3 axis;
  670. axis[p_axis] = 1.0;
  671. planes.push_back(Plane(axis, p_height * 0.5));
  672. planes.push_back(Plane(-axis, p_height * 0.5));
  673. return planes;
  674. }
  675. PoolVector<Plane> Geometry::build_sphere_planes(real_t p_radius, int p_lats, int p_lons, Vector3::Axis p_axis) {
  676. PoolVector<Plane> planes;
  677. Vector3 axis;
  678. axis[p_axis] = 1.0;
  679. Vector3 axis_neg;
  680. axis_neg[(p_axis + 1) % 3] = 1.0;
  681. axis_neg[(p_axis + 2) % 3] = 1.0;
  682. axis_neg[p_axis] = -1.0;
  683. for (int i = 0; i < p_lons; i++) {
  684. Vector3 normal;
  685. normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_lons);
  686. normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_lons);
  687. planes.push_back(Plane(normal, p_radius));
  688. for (int j = 1; j <= p_lats; j++) {
  689. //todo this is stupid, fix
  690. Vector3 angle = normal.linear_interpolate(axis, j / (real_t)p_lats).normalized();
  691. Vector3 pos = angle * p_radius;
  692. planes.push_back(Plane(pos, angle));
  693. planes.push_back(Plane(pos * axis_neg, angle * axis_neg));
  694. }
  695. }
  696. return planes;
  697. }
  698. PoolVector<Plane> Geometry::build_capsule_planes(real_t p_radius, real_t p_height, int p_sides, int p_lats, Vector3::Axis p_axis) {
  699. PoolVector<Plane> planes;
  700. Vector3 axis;
  701. axis[p_axis] = 1.0;
  702. Vector3 axis_neg;
  703. axis_neg[(p_axis + 1) % 3] = 1.0;
  704. axis_neg[(p_axis + 2) % 3] = 1.0;
  705. axis_neg[p_axis] = -1.0;
  706. for (int i = 0; i < p_sides; i++) {
  707. Vector3 normal;
  708. normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_sides);
  709. normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_sides);
  710. planes.push_back(Plane(normal, p_radius));
  711. for (int j = 1; j <= p_lats; j++) {
  712. Vector3 angle = normal.linear_interpolate(axis, j / (real_t)p_lats).normalized();
  713. Vector3 pos = axis * p_height * 0.5 + angle * p_radius;
  714. planes.push_back(Plane(pos, angle));
  715. planes.push_back(Plane(pos * axis_neg, angle * axis_neg));
  716. }
  717. }
  718. return planes;
  719. }
  720. struct _AtlasWorkRect {
  721. Size2i s;
  722. Point2i p;
  723. int idx;
  724. _FORCE_INLINE_ bool operator<(const _AtlasWorkRect &p_r) const { return s.width > p_r.s.width; };
  725. };
  726. struct _AtlasWorkRectResult {
  727. Vector<_AtlasWorkRect> result;
  728. int max_w;
  729. int max_h;
  730. };
  731. void Geometry::make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size) {
  732. //super simple, almost brute force scanline stacking fitter
  733. //it's pretty basic for now, but it tries to make sure that the aspect ratio of the
  734. //resulting atlas is somehow square. This is necessary because video cards have limits
  735. //on texture size (usually 2048 or 4096), so the more square a texture, the more chances
  736. //it will work in every hardware.
  737. // for example, it will prioritize a 1024x1024 atlas (works everywhere) instead of a
  738. // 256x8192 atlas (won't work anywhere).
  739. ERR_FAIL_COND(p_rects.size() == 0);
  740. Vector<_AtlasWorkRect> wrects;
  741. wrects.resize(p_rects.size());
  742. for (int i = 0; i < p_rects.size(); i++) {
  743. wrects.write[i].s = p_rects[i];
  744. wrects.write[i].idx = i;
  745. }
  746. wrects.sort();
  747. int widest = wrects[0].s.width;
  748. Vector<_AtlasWorkRectResult> results;
  749. for (int i = 0; i <= 12; i++) {
  750. int w = 1 << i;
  751. int max_h = 0;
  752. int max_w = 0;
  753. if (w < widest)
  754. continue;
  755. Vector<int> hmax;
  756. hmax.resize(w);
  757. for (int j = 0; j < w; j++)
  758. hmax.write[j] = 0;
  759. //place them
  760. int ofs = 0;
  761. int limit_h = 0;
  762. for (int j = 0; j < wrects.size(); j++) {
  763. if (ofs + wrects[j].s.width > w) {
  764. ofs = 0;
  765. }
  766. int from_y = 0;
  767. for (int k = 0; k < wrects[j].s.width; k++) {
  768. if (hmax[ofs + k] > from_y)
  769. from_y = hmax[ofs + k];
  770. }
  771. wrects.write[j].p.x = ofs;
  772. wrects.write[j].p.y = from_y;
  773. int end_h = from_y + wrects[j].s.height;
  774. int end_w = ofs + wrects[j].s.width;
  775. if (ofs == 0)
  776. limit_h = end_h;
  777. for (int k = 0; k < wrects[j].s.width; k++) {
  778. hmax.write[ofs + k] = end_h;
  779. }
  780. if (end_h > max_h)
  781. max_h = end_h;
  782. if (end_w > max_w)
  783. max_w = end_w;
  784. if (ofs == 0 || end_h > limit_h) //while h limit not reached, keep stacking
  785. ofs += wrects[j].s.width;
  786. }
  787. _AtlasWorkRectResult result;
  788. result.result = wrects;
  789. result.max_h = max_h;
  790. result.max_w = max_w;
  791. results.push_back(result);
  792. }
  793. //find the result with the best aspect ratio
  794. int best = -1;
  795. real_t best_aspect = 1e20;
  796. for (int i = 0; i < results.size(); i++) {
  797. real_t h = next_power_of_2(results[i].max_h);
  798. real_t w = next_power_of_2(results[i].max_w);
  799. real_t aspect = h > w ? h / w : w / h;
  800. if (aspect < best_aspect) {
  801. best = i;
  802. best_aspect = aspect;
  803. }
  804. }
  805. r_result.resize(p_rects.size());
  806. for (int i = 0; i < p_rects.size(); i++) {
  807. r_result.write[results[best].result[i].idx] = results[best].result[i].p;
  808. }
  809. r_size = Size2(results[best].max_w, results[best].max_h);
  810. }