csg.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488
  1. #include "csg.h"
  2. #include "face3.h"
  3. #include "geometry.h"
  4. #include "os/os.h"
  5. #include "sort.h"
  6. #include "thirdparty/misc/triangulator.h"
  7. void CSGBrush::clear() {
  8. faces.clear();
  9. }
  10. void CSGBrush::build_from_faces(const PoolVector<Vector3> &p_vertices, const PoolVector<Vector2> &p_uvs, const PoolVector<bool> &p_smooth, const PoolVector<Ref<Material> > &p_materials, const PoolVector<bool> &p_invert_faces) {
  11. clear();
  12. int vc = p_vertices.size();
  13. ERR_FAIL_COND((vc % 3) != 0)
  14. PoolVector<Vector3>::Read rv = p_vertices.read();
  15. int uvc = p_uvs.size();
  16. PoolVector<Vector2>::Read ruv = p_uvs.read();
  17. int sc = p_smooth.size();
  18. PoolVector<bool>::Read rs = p_smooth.read();
  19. int mc = p_materials.size();
  20. PoolVector<Ref<Material> >::Read rm = p_materials.read();
  21. int ic = p_invert_faces.size();
  22. PoolVector<bool>::Read ri = p_invert_faces.read();
  23. Map<Ref<Material>, int> material_map;
  24. faces.resize(p_vertices.size() / 3);
  25. for (int i = 0; i < faces.size(); i++) {
  26. Face &f = faces[i];
  27. f.vertices[0] = rv[i * 3 + 0];
  28. f.vertices[1] = rv[i * 3 + 1];
  29. f.vertices[2] = rv[i * 3 + 2];
  30. if (uvc == vc) {
  31. f.uvs[0] = ruv[i * 3 + 0];
  32. f.uvs[1] = ruv[i * 3 + 1];
  33. f.uvs[2] = ruv[i * 3 + 2];
  34. }
  35. if (sc == vc / 3) {
  36. f.smooth = rs[i];
  37. } else {
  38. f.smooth = false;
  39. }
  40. if (ic == vc / 3) {
  41. f.invert = ri[i];
  42. } else {
  43. f.invert = false;
  44. }
  45. if (mc == vc / 3) {
  46. Ref<Material> mat = rm[i];
  47. if (mat.is_valid()) {
  48. const Map<Ref<Material>, int>::Element *E = material_map.find(mat);
  49. if (E) {
  50. f.material = E->get();
  51. } else {
  52. f.material = material_map.size();
  53. material_map[mat] = f.material;
  54. }
  55. } else {
  56. f.material = -1;
  57. }
  58. }
  59. }
  60. materials.resize(material_map.size());
  61. for (Map<Ref<Material>, int>::Element *E = material_map.front(); E; E = E->next()) {
  62. materials[E->get()] = E->key();
  63. }
  64. _regen_face_aabbs();
  65. }
  66. void CSGBrush::_regen_face_aabbs() {
  67. for (int i = 0; i < faces.size(); i++) {
  68. faces[i].aabb.position = faces[i].vertices[0];
  69. faces[i].aabb.expand_to(faces[i].vertices[1]);
  70. faces[i].aabb.expand_to(faces[i].vertices[2]);
  71. faces[i].aabb.grow_by(faces[i].aabb.get_longest_axis_size() * 0.001); //make it a tad bigger to avoid num precision erros
  72. }
  73. }
  74. void CSGBrush::copy_from(const CSGBrush &p_brush, const Transform &p_xform) {
  75. faces = p_brush.faces;
  76. materials = p_brush.materials;
  77. for (int i = 0; i < faces.size(); i++) {
  78. for (int j = 0; j < 3; j++) {
  79. faces[i].vertices[j] = p_xform.xform(p_brush.faces[i].vertices[j]);
  80. }
  81. }
  82. _regen_face_aabbs();
  83. }
  84. ////////////////////////
  85. void CSGBrushOperation::BuildPoly::create(const CSGBrush *p_brush, int p_face, MeshMerge &mesh_merge, bool p_for_B) {
  86. //creates the initial face that will be used for clipping against the other faces
  87. Vector3 va[3] = {
  88. p_brush->faces[p_face].vertices[0],
  89. p_brush->faces[p_face].vertices[1],
  90. p_brush->faces[p_face].vertices[2],
  91. };
  92. plane = Plane(va[0], va[1], va[2]);
  93. to_world.origin = va[0];
  94. to_world.basis.set_axis(2, plane.normal);
  95. to_world.basis.set_axis(0, (va[1] - va[2]).normalized());
  96. to_world.basis.set_axis(1, to_world.basis.get_axis(0).cross(to_world.basis.get_axis(2)).normalized());
  97. to_poly = to_world.affine_inverse();
  98. face_index = p_face;
  99. for (int i = 0; i < 3; i++) {
  100. Point p;
  101. Vector3 localp = to_poly.xform(va[i]);
  102. p.point.x = localp.x;
  103. p.point.y = localp.y;
  104. p.uv = p_brush->faces[p_face].uvs[i];
  105. points.push_back(p);
  106. ///edge
  107. Edge e;
  108. e.points[0] = i;
  109. e.points[1] = (i + 1) % 3;
  110. e.outer = true;
  111. edges.push_back(e);
  112. }
  113. smooth = p_brush->faces[p_face].smooth;
  114. invert = p_brush->faces[p_face].invert;
  115. if (p_brush->faces[p_face].material != -1) {
  116. material = p_brush->materials[p_brush->faces[p_face].material];
  117. }
  118. base_edges = 3;
  119. }
  120. static Vector2 interpolate_uv(const Vector2 &p_vertex_a, const Vector2 &p_vertex_b, const Vector2 &p_vertex_c, const Vector2 &p_uv_a, const Vector2 &p_uv_c) {
  121. float len_a_c = (p_vertex_c - p_vertex_a).length();
  122. if (len_a_c < CMP_EPSILON) {
  123. return p_uv_a;
  124. }
  125. float len_a_b = (p_vertex_b - p_vertex_a).length();
  126. float c = len_a_b / len_a_c;
  127. return p_uv_a.linear_interpolate(p_uv_c, c);
  128. }
  129. static Vector2 interpolate_triangle_uv(const Vector2 &p_pos, const Vector2 *p_vtx, const Vector2 *p_uv) {
  130. if (p_pos.distance_squared_to(p_vtx[0]) < CMP_EPSILON2) {
  131. return p_uv[0];
  132. }
  133. if (p_pos.distance_squared_to(p_vtx[1]) < CMP_EPSILON2) {
  134. return p_uv[1];
  135. }
  136. if (p_pos.distance_squared_to(p_vtx[2]) < CMP_EPSILON2) {
  137. return p_uv[2];
  138. }
  139. Vector2 v0 = p_vtx[1] - p_vtx[0];
  140. Vector2 v1 = p_vtx[2] - p_vtx[0];
  141. Vector2 v2 = p_pos - p_vtx[0];
  142. float d00 = v0.dot(v0);
  143. float d01 = v0.dot(v1);
  144. float d11 = v1.dot(v1);
  145. float d20 = v2.dot(v0);
  146. float d21 = v2.dot(v1);
  147. float denom = (d00 * d11 - d01 * d01);
  148. if (denom == 0) {
  149. return p_uv[0];
  150. }
  151. float v = (d11 * d20 - d01 * d21) / denom;
  152. float w = (d00 * d21 - d01 * d20) / denom;
  153. float u = 1.0f - v - w;
  154. return p_uv[0] * u + p_uv[1] * v + p_uv[2] * w;
  155. }
  156. void CSGBrushOperation::BuildPoly::_clip_segment(const CSGBrush *p_brush, int p_face, const Vector2 *segment, MeshMerge &mesh_merge, bool p_for_B) {
  157. //keep track of what was inserted
  158. Vector<int> inserted_points;
  159. //keep track of point indices for what was inserted, allowing reuse of points.
  160. int segment_idx[2] = { -1, -1 };
  161. //check if edge and poly share a vertex, of so, assign it to segment_idx
  162. for (int i = 0; i < points.size(); i++) {
  163. for (int j = 0; j < 2; j++) {
  164. if (segment[j].distance_to(points[i].point) < CMP_EPSILON) {
  165. segment_idx[j] = i;
  166. inserted_points.push_back(i);
  167. break;
  168. }
  169. }
  170. }
  171. //check if both segment points are shared with other vertices
  172. if (segment_idx[0] != -1 && segment_idx[1] != -1) {
  173. if (segment_idx[0] == segment_idx[1]) {
  174. return; //segment was too tiny, both mapped to same point
  175. }
  176. bool found = false;
  177. //check if the segment already exists
  178. for (int i = 0; i < edges.size(); i++) {
  179. if (
  180. (edges[i].points[0] == segment_idx[0] && edges[i].points[1] == segment_idx[1]) ||
  181. (edges[i].points[0] == segment_idx[1] && edges[i].points[1] == segment_idx[0])) {
  182. found = true;
  183. break;
  184. }
  185. }
  186. if (found) {
  187. //it does already exist, do nothing
  188. return;
  189. }
  190. //directly add the new segment
  191. Edge new_edge;
  192. new_edge.points[0] = segment_idx[0];
  193. new_edge.points[1] = segment_idx[1];
  194. edges.push_back(new_edge);
  195. return;
  196. }
  197. //check edge by edge against the segment points to see if intersects
  198. for (int i = 0; i < base_edges; i++) {
  199. //if a point is shared with one of the edge points, then this edge must not be tested, as it will result in a numerical precision error.
  200. bool edge_valid = true;
  201. for (int j = 0; j < 2; j++) {
  202. if (edges[i].points[0] == segment_idx[0] || edges[i].points[1] == segment_idx[1] || edges[i].points[0] == segment_idx[1] || edges[i].points[1] == segment_idx[0]) {
  203. edge_valid = false; //segment has this point, cant check against this
  204. break;
  205. }
  206. }
  207. if (!edge_valid) //already hit a point in this edge, so dont test it
  208. continue;
  209. //see if either points are within the edge isntead of crossing it
  210. Vector2 res;
  211. bool found = false;
  212. int assign_segment_id = -1;
  213. for (int j = 0; j < 2; j++) {
  214. Vector2 edgeseg[2] = { points[edges[i].points[0]].point, points[edges[i].points[1]].point };
  215. Vector2 closest = Geometry::get_closest_point_to_segment_2d(segment[j], edgeseg);
  216. if (closest.distance_to(segment[j]) < CMP_EPSILON) {
  217. //point rest of this edge
  218. res = closest;
  219. found = true;
  220. assign_segment_id = j;
  221. }
  222. }
  223. //test if the point crosses the edge
  224. if (!found && Geometry::segment_intersects_segment_2d(segment[0], segment[1], points[edges[i].points[0]].point, points[edges[i].points[1]].point, &res)) {
  225. //point does cross the edge
  226. found = true;
  227. }
  228. //check whether an intersection against the segment happened
  229. if (found) {
  230. //It did! so first, must slice the segment
  231. Point new_point;
  232. new_point.point = res;
  233. //make sure to interpolate UV too
  234. new_point.uv = interpolate_uv(points[edges[i].points[0]].point, new_point.point, points[edges[i].points[1]].point, points[edges[i].points[0]].uv, points[edges[i].points[1]].uv);
  235. int point_idx = points.size();
  236. points.push_back(new_point);
  237. //split the edge in 2
  238. Edge new_edge;
  239. new_edge.points[0] = edges[i].points[0];
  240. new_edge.points[1] = point_idx;
  241. new_edge.outer = edges[i].outer;
  242. edges[i].points[0] = point_idx;
  243. edges.insert(i, new_edge);
  244. i++; //skip newly inserted edge
  245. base_edges++; //will need an extra one in the base triangle
  246. if (assign_segment_id >= 0) {
  247. //point did split a segment, so make sure to remember this
  248. segment_idx[assign_segment_id] = point_idx;
  249. }
  250. inserted_points.push_back(point_idx);
  251. }
  252. }
  253. //final step: after cutting the original triangle, try to see if we can still insert
  254. //this segment
  255. //if already inserted two points, just use them for a segment
  256. if (inserted_points.size() >= 2) { //should never be >2 on non-manifold geometry, but cope with error
  257. //two points were inserted, create the new edge
  258. Edge new_edge;
  259. new_edge.points[0] = inserted_points[0];
  260. new_edge.points[1] = inserted_points[1];
  261. edges.push_back(new_edge);
  262. return;
  263. }
  264. // One or no points were inserted (besides splitting), so try to see if extra points can be placed inside the triangle.
  265. // This needs to be done here, after the previous tests were exhausted
  266. for (int i = 0; i < 2; i++) {
  267. if (segment_idx[i] != -1)
  268. continue; //already assigned to something, so skip
  269. //check whether one of the segment endpoints is inside the triangle. If it is, this points needs to be inserted
  270. if (Geometry::is_point_in_triangle(segment[i], points[0].point, points[1].point, points[2].point)) {
  271. Point new_point;
  272. new_point.point = segment[i];
  273. Vector2 point3[3] = { points[0].point, points[1].point, points[2].point };
  274. Vector2 uv3[3] = { points[0].uv, points[1].uv, points[2].uv };
  275. new_point.uv = interpolate_triangle_uv(new_point.point, point3, uv3);
  276. int point_idx = points.size();
  277. points.push_back(new_point);
  278. inserted_points.push_back(point_idx);
  279. }
  280. }
  281. //check again whether two points were inserted, if so then create the new edge
  282. if (inserted_points.size() >= 2) { //should never be >2 on non-manifold geometry, but cope with error
  283. Edge new_edge;
  284. new_edge.points[0] = inserted_points[0];
  285. new_edge.points[1] = inserted_points[1];
  286. edges.push_back(new_edge);
  287. }
  288. }
  289. void CSGBrushOperation::BuildPoly::clip(const CSGBrush *p_brush, int p_face, MeshMerge &mesh_merge, bool p_for_B) {
  290. //Clip function.. find triangle points that will be mapped to the plane and form a segment
  291. Vector2 segment[3]; //2D
  292. int src_points = 0;
  293. for (int i = 0; i < 3; i++) {
  294. Vector3 p = p_brush->faces[p_face].vertices[i];
  295. if (plane.has_point(p)) {
  296. Vector3 pp = plane.project(p);
  297. pp = to_poly.xform(pp);
  298. segment[src_points++] = Vector2(pp.x, pp.y);
  299. } else {
  300. Vector3 q = p_brush->faces[p_face].vertices[(i + 1) % 3];
  301. if (plane.has_point(q))
  302. continue; //next point is in plane, will be added eventually
  303. if (plane.is_point_over(p) == plane.is_point_over(q))
  304. continue; // both on same side of the plane, don't add
  305. Vector3 res;
  306. if (plane.intersects_segment(p, q, &res)) {
  307. res = to_poly.xform(res);
  308. segment[src_points++] = Vector2(res.x, res.y);
  309. }
  310. }
  311. }
  312. //all above or all below, nothing to do. Should not happen though since a precheck was done before.
  313. if (src_points == 0)
  314. return;
  315. //just one point in plane is not worth doing anything
  316. if (src_points == 1)
  317. return;
  318. //transform A points to 2D
  319. if (segment[0].distance_to(segment[1]) < CMP_EPSILON)
  320. return; //too small
  321. _clip_segment(p_brush, p_face, segment, mesh_merge, p_for_B);
  322. }
  323. void CSGBrushOperation::_collision_callback(const CSGBrush *A, int p_face_a, Map<int, BuildPoly> &build_polys_a, const CSGBrush *B, int p_face_b, Map<int, BuildPoly> &build_polys_b, MeshMerge &mesh_merge) {
  324. //construct a frame of reference for both transforms, in order to do intersection test
  325. Vector3 va[3] = {
  326. A->faces[p_face_a].vertices[0],
  327. A->faces[p_face_a].vertices[1],
  328. A->faces[p_face_a].vertices[2],
  329. };
  330. Vector3 vb[3] = {
  331. B->faces[p_face_b].vertices[0],
  332. B->faces[p_face_b].vertices[1],
  333. B->faces[p_face_b].vertices[2],
  334. };
  335. {
  336. //check if either is a degenerate
  337. if (va[0].distance_to(va[1]) < CMP_EPSILON || va[0].distance_to(va[2]) < CMP_EPSILON || va[1].distance_to(va[2]) < CMP_EPSILON)
  338. return;
  339. if (vb[0].distance_to(vb[1]) < CMP_EPSILON || vb[0].distance_to(vb[2]) < CMP_EPSILON || vb[1].distance_to(vb[2]) < CMP_EPSILON)
  340. return;
  341. }
  342. {
  343. //check if points are the same
  344. int equal_count = 0;
  345. for (int i = 0; i < 3; i++) {
  346. for (int j = 0; j < 3; j++) {
  347. if (va[i].distance_to(vb[j]) < mesh_merge.vertex_snap) {
  348. equal_count++;
  349. break;
  350. }
  351. }
  352. }
  353. //if 2 or 3 points are the same, there is no point in doing anything. They can't
  354. //be clipped either, so add both.
  355. if (equal_count == 2 || equal_count == 3) {
  356. return;
  357. }
  358. }
  359. // do a quick pre-check for no-intersection using the SAT theorem
  360. {
  361. //b under or over a plane
  362. int over_count = 0, in_plane_count = 0, under_count = 0;
  363. Plane plane_a(va[0], va[1], va[2]);
  364. if (plane_a.normal == Vector3()) {
  365. return; //degenerate
  366. }
  367. for (int i = 0; i < 3; i++) {
  368. if (plane_a.has_point(vb[i]))
  369. in_plane_count++;
  370. else if (plane_a.is_point_over(vb[i]))
  371. over_count++;
  372. else
  373. under_count++;
  374. }
  375. if (over_count == 0 || under_count == 0)
  376. return; //no intersection, something needs to be under AND over
  377. //a under or over b plane
  378. over_count = 0;
  379. under_count = 0;
  380. in_plane_count = 0;
  381. Plane plane_b(vb[0], vb[1], vb[2]);
  382. if (plane_b.normal == Vector3())
  383. return; //degenerate
  384. for (int i = 0; i < 3; i++) {
  385. if (plane_b.has_point(va[i]))
  386. in_plane_count++;
  387. else if (plane_b.is_point_over(va[i]))
  388. over_count++;
  389. else
  390. under_count++;
  391. }
  392. if (over_count == 0 || under_count == 0)
  393. return; //no intersection, something needs to be under AND over
  394. //edge pairs (cross product combinations), see SAT theorem
  395. for (int i = 0; i < 3; i++) {
  396. Vector3 axis_a = (va[i] - va[(i + 1) % 3]).normalized();
  397. for (int j = 0; j < 3; j++) {
  398. Vector3 axis_b = (vb[j] - vb[(j + 1) % 3]).normalized();
  399. Vector3 sep_axis = axis_a.cross(axis_b);
  400. if (sep_axis == Vector3())
  401. continue; //colineal
  402. sep_axis.normalize();
  403. real_t min_a = 1e20, max_a = -1e20;
  404. real_t min_b = 1e20, max_b = -1e20;
  405. for (int k = 0; k < 3; k++) {
  406. real_t d = sep_axis.dot(va[k]);
  407. min_a = MIN(min_a, d);
  408. max_a = MAX(max_a, d);
  409. d = sep_axis.dot(vb[k]);
  410. min_b = MIN(min_b, d);
  411. max_b = MAX(max_b, d);
  412. }
  413. min_b -= (max_a - min_a) * 0.5;
  414. max_b += (max_a - min_a) * 0.5;
  415. real_t dmin = min_b - (min_a + max_a) * 0.5;
  416. real_t dmax = max_b - (min_a + max_a) * 0.5;
  417. if (dmin > CMP_EPSILON || dmax < -CMP_EPSILON) {
  418. return; //does not contain zero, so they don't overlap
  419. }
  420. }
  421. }
  422. }
  423. //if we are still here, it means they most likely intersect, so create BuildPolys if they dont existy
  424. BuildPoly *poly_a = NULL;
  425. if (!build_polys_a.has(p_face_a)) {
  426. BuildPoly bp;
  427. bp.create(A, p_face_a, mesh_merge, false);
  428. build_polys_a[p_face_a] = bp;
  429. }
  430. poly_a = &build_polys_a[p_face_a];
  431. BuildPoly *poly_b = NULL;
  432. if (!build_polys_b.has(p_face_b)) {
  433. BuildPoly bp;
  434. bp.create(B, p_face_b, mesh_merge, true);
  435. build_polys_b[p_face_b] = bp;
  436. }
  437. poly_b = &build_polys_b[p_face_b];
  438. //clip each other, this could be improved by using vertex unique IDs (more vertices may be shared instead of using snap)
  439. poly_a->clip(B, p_face_b, mesh_merge, false);
  440. poly_b->clip(A, p_face_a, mesh_merge, true);
  441. }
  442. void CSGBrushOperation::_add_poly_points(const BuildPoly &p_poly, int p_edge, int p_from_point, int p_to_point, const Vector<Vector<int> > &vertex_process, Vector<bool> &edge_process, Vector<PolyPoints> &r_poly) {
  443. //this function follows the polygon points counter clockwise and adds them. It creates lists of unique polygons
  444. //every time an unused edge is found, it's pushed to a stack and continues from there.
  445. List<EdgeSort> edge_stack;
  446. {
  447. EdgeSort es;
  448. es.angle = 0; //wont be checked here
  449. es.edge = p_edge;
  450. es.prev_point = p_from_point;
  451. es.edge_point = p_to_point;
  452. edge_stack.push_back(es);
  453. }
  454. //attempt to empty the stack.
  455. while (edge_stack.size()) {
  456. EdgeSort e = edge_stack.front()->get();
  457. edge_stack.pop_front();
  458. if (edge_process[e.edge]) {
  459. //nothing to do here
  460. continue;
  461. }
  462. Vector<int> points;
  463. points.push_back(e.prev_point);
  464. int prev_point = e.prev_point;
  465. int to_point = e.edge_point;
  466. int current_edge = e.edge;
  467. edge_process[e.edge] = true; //mark as processed
  468. int limit = p_poly.points.size() * 4; //avoid infinite recursion
  469. while (to_point != e.prev_point && limit) {
  470. Vector2 segment[2] = { p_poly.points[prev_point].point, p_poly.points[to_point].point };
  471. //construct a basis transform from the segment, which will be used to check the angle
  472. Transform2D t2d;
  473. t2d[0] = (segment[1] - segment[0]).normalized(); //use as Y
  474. t2d[1] = Vector2(-t2d[0].y, t2d[0].x); // use as tangent
  475. t2d[2] = segment[1]; //origin
  476. if (t2d.basis_determinant() == 0)
  477. break; //abort poly
  478. t2d.affine_invert();
  479. //push all edges found here, they will be sorted by minimum angle later.
  480. Vector<EdgeSort> next_edges;
  481. for (int i = 0; i < vertex_process[to_point].size(); i++) {
  482. int edge = vertex_process[to_point][i];
  483. int opposite_point = p_poly.edges[edge].points[0] == to_point ? p_poly.edges[edge].points[1] : p_poly.edges[edge].points[0];
  484. if (opposite_point == prev_point)
  485. continue; //not going back
  486. EdgeSort e;
  487. Vector2 local_vec = t2d.xform(p_poly.points[opposite_point].point);
  488. e.angle = -local_vec.angle(); //negate so we can sort by minimum angle
  489. e.edge = edge;
  490. e.edge_point = opposite_point;
  491. e.prev_point = to_point;
  492. next_edges.push_back(e);
  493. }
  494. //finally, sort by minimum angle
  495. next_edges.sort();
  496. int next_point = -1;
  497. int next_edge = -1;
  498. for (int i = 0; i < next_edges.size(); i++) {
  499. if (i == 0) {
  500. //minimum angle found is the next point
  501. next_point = next_edges[i].edge_point;
  502. next_edge = next_edges[i].edge;
  503. } else {
  504. //the rest are pushed to the stack IF they were not processed yet.
  505. if (!edge_process[next_edges[i].edge]) {
  506. edge_stack.push_back(next_edges[i]);
  507. }
  508. }
  509. }
  510. if (next_edge == -1) {
  511. //did not find anything, may be a dead-end edge (this should normally not happen)
  512. //just flip the direction and go back
  513. next_point = prev_point;
  514. next_edge = current_edge;
  515. }
  516. points.push_back(to_point);
  517. prev_point = to_point;
  518. to_point = next_point;
  519. edge_process[next_edge] = true; //mark this edge as processed
  520. current_edge = next_edge;
  521. limit--;
  522. }
  523. //if more than 2 points were added to the polygon, add it to the list of polygons.
  524. if (points.size() > 2) {
  525. PolyPoints pp;
  526. pp.points = points;
  527. r_poly.push_back(pp);
  528. }
  529. }
  530. }
  531. void CSGBrushOperation::_add_poly_outline(const BuildPoly &p_poly, int p_from_point, int p_to_point, const Vector<Vector<int> > &vertex_process, Vector<int> &r_outline) {
  532. //this is the opposite of the function above. It adds polygon outlines instead.
  533. //this is used for triangulating holes.
  534. //no stack is used here because only the bigger outline is interesting.
  535. r_outline.push_back(p_from_point);
  536. int prev_point = p_from_point;
  537. int to_point = p_to_point;
  538. int limit = p_poly.points.size() * 4; //avoid infinite recursion
  539. while (to_point != p_from_point && limit) {
  540. Vector2 segment[2] = { p_poly.points[prev_point].point, p_poly.points[to_point].point };
  541. //again create a transform to compute the angle.
  542. Transform2D t2d;
  543. t2d[0] = (segment[1] - segment[0]).normalized(); //use as Y
  544. t2d[1] = Vector2(-t2d[0].y, t2d[0].x); // use as tangent
  545. t2d[2] = segment[1]; //origin
  546. if (t2d.basis_determinant() == 0)
  547. break; //abort poly
  548. t2d.affine_invert();
  549. float max_angle;
  550. int next_point_angle = -1;
  551. for (int i = 0; i < vertex_process[to_point].size(); i++) {
  552. int edge = vertex_process[to_point][i];
  553. int opposite_point = p_poly.edges[edge].points[0] == to_point ? p_poly.edges[edge].points[1] : p_poly.edges[edge].points[0];
  554. if (opposite_point == prev_point)
  555. continue; //not going back
  556. float angle = -t2d.xform(p_poly.points[opposite_point].point).angle();
  557. if (next_point_angle == -1 || angle > max_angle) { //same as before but use greater to check.
  558. max_angle = angle;
  559. next_point_angle = opposite_point;
  560. }
  561. }
  562. if (next_point_angle == -1) {
  563. //go back because no route found
  564. next_point_angle = prev_point;
  565. }
  566. r_outline.push_back(to_point);
  567. prev_point = to_point;
  568. to_point = next_point_angle;
  569. limit--;
  570. }
  571. }
  572. void CSGBrushOperation::_merge_poly(MeshMerge &mesh, int p_face_idx, const BuildPoly &p_poly, bool p_from_b) {
  573. //finally, merge the 2D polygon back to 3D
  574. Vector<Vector<int> > vertex_process;
  575. Vector<bool> edge_process;
  576. vertex_process.resize(p_poly.points.size());
  577. edge_process.resize(p_poly.edges.size());
  578. //none processed by default
  579. for (int i = 0; i < edge_process.size(); i++) {
  580. edge_process[i] = false;
  581. }
  582. //put edges in points, so points can go through them
  583. for (int i = 0; i < p_poly.edges.size(); i++) {
  584. vertex_process[p_poly.edges[i].points[0]].push_back(i);
  585. vertex_process[p_poly.edges[i].points[1]].push_back(i);
  586. }
  587. Vector<PolyPoints> polys;
  588. //process points that were not processed
  589. for (int i = 0; i < edge_process.size(); i++) {
  590. if (edge_process[i] == true)
  591. continue; //already processed
  592. int intersect_poly = -1;
  593. if (i > 0) {
  594. //this is disconnected, so it's clearly a hole. lets find where it belongs
  595. Vector2 ref_point = p_poly.points[p_poly.edges[i].points[0]].point;
  596. for (int j = 0; j < polys.size(); j++) {
  597. //find a point outside poly
  598. Vector2 out_point(-1e20, -1e20);
  599. const PolyPoints &pp = polys[j];
  600. for (int k = 0; k < pp.points.size(); k++) {
  601. Vector2 p = p_poly.points[pp.points[k]].point;
  602. out_point.x = MAX(out_point.x, p.x);
  603. out_point.y = MAX(out_point.y, p.y);
  604. }
  605. out_point += Vector2(0.12341234, 0.4123412); // move to a random place to avoid direct edge-point chances
  606. int intersections = 0;
  607. for (int k = 0; k < pp.points.size(); k++) {
  608. Vector2 p1 = p_poly.points[pp.points[k]].point;
  609. Vector2 p2 = p_poly.points[pp.points[(k + 1) % pp.points.size()]].point;
  610. if (Geometry::segment_intersects_segment_2d(ref_point, out_point, p1, p2, NULL)) {
  611. intersections++;
  612. }
  613. }
  614. if (intersections % 2 == 1) {
  615. //hole is inside this poly
  616. intersect_poly = j;
  617. break;
  618. }
  619. }
  620. }
  621. if (intersect_poly != -1) {
  622. //must add this as a hole
  623. Vector<int> outline;
  624. _add_poly_outline(p_poly, p_poly.edges[i].points[0], p_poly.edges[i].points[1], vertex_process, outline);
  625. if (outline.size() > 1) {
  626. polys[intersect_poly].holes.push_back(outline);
  627. }
  628. }
  629. _add_poly_points(p_poly, i, p_poly.edges[i].points[0], p_poly.edges[i].points[1], vertex_process, edge_process, polys);
  630. }
  631. //get rid of holes, not the most optiomal way, but also not a common case at all to be inoptimal
  632. for (int i = 0; i < polys.size(); i++) {
  633. if (!polys[i].holes.size())
  634. continue;
  635. //repeat until no more holes are left to be merged
  636. while (polys[i].holes.size()) {
  637. //try to merge a hole with the outline
  638. bool added_hole = false;
  639. for (int j = 0; j < polys[i].holes.size(); j++) {
  640. //try hole vertices
  641. int with_outline_vertex = -1;
  642. int from_hole_vertex = -1;
  643. bool found = false;
  644. for (int k = 0; k < polys[i].holes[j].size(); k++) {
  645. int from_idx = polys[i].holes[j][k];
  646. Vector2 from = p_poly.points[from_idx].point;
  647. //try a segment from hole vertex to outline vertices
  648. from_hole_vertex = k;
  649. bool valid = true;
  650. for (int l = 0; l < polys[i].points.size(); l++) {
  651. int to_idx = polys[i].points[l];
  652. Vector2 to = p_poly.points[to_idx].point;
  653. with_outline_vertex = l;
  654. //try agaisnt outline (other points) first
  655. valid = true;
  656. for (int m = 0; m < polys[i].points.size(); m++) {
  657. int m_next = (m + 1) % polys[i].points.size();
  658. if (m == with_outline_vertex || m_next == with_outline_vertex) //do not test with edges that share this point
  659. continue;
  660. if (Geometry::segment_intersects_segment_2d(from, to, p_poly.points[polys[i].points[m]].point, p_poly.points[polys[i].points[m_next]].point, NULL)) {
  661. valid = false;
  662. break;
  663. }
  664. }
  665. if (!valid)
  666. continue;
  667. //try agaisnt all holes including self
  668. for (int m = 0; m < polys[i].holes.size(); m++) {
  669. for (int n = 0; n < polys[i].holes[m].size(); n++) {
  670. int n_next = (n + 1) % polys[i].holes[m].size();
  671. if (m == j && (n == from_hole_vertex || n_next == from_hole_vertex)) //contains vertex being tested from current hole, skip
  672. continue;
  673. if (Geometry::segment_intersects_segment_2d(from, to, p_poly.points[polys[i].holes[m][n]].point, p_poly.points[polys[i].holes[m][n_next]].point, NULL)) {
  674. valid = false;
  675. break;
  676. }
  677. }
  678. if (!valid)
  679. break;
  680. }
  681. if (valid) //all passed! exit loop
  682. break;
  683. else
  684. continue; //something went wrong, go on.
  685. }
  686. if (valid) {
  687. found = true; //if in the end this was valid, use it
  688. break;
  689. }
  690. }
  691. if (found) {
  692. //hook this hole with outline, and remove from list of holes
  693. //duplicate point
  694. int insert_at = with_outline_vertex;
  695. polys[i].points.insert(insert_at, polys[i].points[insert_at]);
  696. insert_at++;
  697. //insert all others, outline should be backwards (must check)
  698. int holesize = polys[i].holes[j].size();
  699. for (int k = 0; k <= holesize; k++) {
  700. int idx = (from_hole_vertex + k) % holesize;
  701. polys[i].points.insert(insert_at, polys[i].holes[j][idx]);
  702. insert_at++;
  703. }
  704. added_hole = true;
  705. polys[i].holes.remove(j);
  706. break; //got rid of hole, break and continue
  707. }
  708. }
  709. ERR_BREAK(!added_hole);
  710. }
  711. }
  712. //triangulate polygons
  713. for (int i = 0; i < polys.size(); i++) {
  714. Vector<Vector2> vertices;
  715. vertices.resize(polys[i].points.size());
  716. for (int j = 0; j < vertices.size(); j++) {
  717. vertices[j] = p_poly.points[polys[i].points[j]].point;
  718. }
  719. Vector<int> indices = Geometry::triangulate_polygon(vertices);
  720. for (int j = 0; j < indices.size(); j += 3) {
  721. //obtain the vertex
  722. Vector3 face[3];
  723. Vector2 uv[3];
  724. float cp = Geometry::vec2_cross(p_poly.points[polys[i].points[indices[j + 0]]].point, p_poly.points[polys[i].points[indices[j + 1]]].point, p_poly.points[polys[i].points[indices[j + 2]]].point);
  725. if (Math::abs(cp) < CMP_EPSILON)
  726. continue;
  727. for (int k = 0; k < 3; k++) {
  728. Vector2 p = p_poly.points[polys[i].points[indices[j + k]]].point;
  729. face[k] = p_poly.to_world.xform(Vector3(p.x, p.y, 0));
  730. uv[k] = p_poly.points[polys[i].points[indices[j + k]]].uv;
  731. }
  732. mesh.add_face(face[0], face[1], face[2], uv[0], uv[1], uv[2], p_poly.smooth, p_poly.invert, p_poly.material, p_from_b);
  733. }
  734. }
  735. }
  736. //use a limit to speed up bvh and limit the depth
  737. #define BVH_LIMIT 8
  738. int CSGBrushOperation::MeshMerge::_create_bvh(BVH *p_bvh, BVH **p_bb, int p_from, int p_size, int p_depth, int &max_depth, int &max_alloc) {
  739. if (p_depth > max_depth) {
  740. max_depth = p_depth;
  741. }
  742. if (p_size <= BVH_LIMIT) {
  743. for (int i = 0; i < p_size - 1; i++) {
  744. p_bb[p_from + i]->next = p_bb[p_from + i + 1] - p_bvh;
  745. }
  746. return p_bb[p_from] - p_bvh;
  747. } else if (p_size == 0) {
  748. return -1;
  749. }
  750. AABB aabb;
  751. aabb = p_bb[p_from]->aabb;
  752. for (int i = 1; i < p_size; i++) {
  753. aabb.merge_with(p_bb[p_from + i]->aabb);
  754. }
  755. int li = aabb.get_longest_axis_index();
  756. switch (li) {
  757. case Vector3::AXIS_X: {
  758. SortArray<BVH *, BVHCmpX> sort_x;
  759. sort_x.nth_element(0, p_size, p_size / 2, &p_bb[p_from]);
  760. //sort_x.sort(&p_bb[p_from],p_size);
  761. } break;
  762. case Vector3::AXIS_Y: {
  763. SortArray<BVH *, BVHCmpY> sort_y;
  764. sort_y.nth_element(0, p_size, p_size / 2, &p_bb[p_from]);
  765. //sort_y.sort(&p_bb[p_from],p_size);
  766. } break;
  767. case Vector3::AXIS_Z: {
  768. SortArray<BVH *, BVHCmpZ> sort_z;
  769. sort_z.nth_element(0, p_size, p_size / 2, &p_bb[p_from]);
  770. //sort_z.sort(&p_bb[p_from],p_size);
  771. } break;
  772. }
  773. int left = _create_bvh(p_bvh, p_bb, p_from, p_size / 2, p_depth + 1, max_depth, max_alloc);
  774. int right = _create_bvh(p_bvh, p_bb, p_from + p_size / 2, p_size - p_size / 2, p_depth + 1, max_depth, max_alloc);
  775. int index = max_alloc++;
  776. BVH *_new = &p_bvh[index];
  777. _new->aabb = aabb;
  778. _new->center = aabb.position + aabb.size * 0.5;
  779. _new->face = -1;
  780. _new->left = left;
  781. _new->right = right;
  782. _new->next = -1;
  783. return index;
  784. }
  785. int CSGBrushOperation::MeshMerge::_bvh_count_intersections(BVH *bvhptr, int p_max_depth, int p_bvh_first, const Vector3 &p_begin, const Vector3 &p_end, int p_exclude) const {
  786. uint32_t *stack = (uint32_t *)alloca(sizeof(int) * p_max_depth);
  787. enum {
  788. TEST_AABB_BIT = 0,
  789. VISIT_LEFT_BIT = 1,
  790. VISIT_RIGHT_BIT = 2,
  791. VISIT_DONE_BIT = 3,
  792. VISITED_BIT_SHIFT = 29,
  793. NODE_IDX_MASK = (1 << VISITED_BIT_SHIFT) - 1,
  794. VISITED_BIT_MASK = ~NODE_IDX_MASK,
  795. };
  796. int intersections = 0;
  797. int level = 0;
  798. const Vector3 *vertexptr = points.ptr();
  799. const Face *facesptr = faces.ptr();
  800. AABB segment_aabb;
  801. segment_aabb.position = p_begin;
  802. segment_aabb.expand_to(p_end);
  803. int pos = p_bvh_first;
  804. stack[0] = pos;
  805. while (true) {
  806. uint32_t node = stack[level] & NODE_IDX_MASK;
  807. const BVH &b = bvhptr[node];
  808. bool done = false;
  809. switch (stack[level] >> VISITED_BIT_SHIFT) {
  810. case TEST_AABB_BIT: {
  811. if (b.face >= 0) {
  812. const BVH *bp = &b;
  813. while (bp) {
  814. bool valid = segment_aabb.intersects(bp->aabb) && bp->aabb.intersects_segment(p_begin, p_end);
  815. if (valid && p_exclude != bp->face) {
  816. const Face &s = facesptr[bp->face];
  817. Face3 f3(vertexptr[s.points[0]], vertexptr[s.points[1]], vertexptr[s.points[2]]);
  818. Vector3 res;
  819. if (f3.intersects_segment(p_begin, p_end, &res)) {
  820. intersections++;
  821. }
  822. }
  823. if (bp->next != -1) {
  824. bp = &bvhptr[bp->next];
  825. } else {
  826. bp = NULL;
  827. }
  828. }
  829. stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
  830. } else {
  831. bool valid = segment_aabb.intersects(b.aabb) && b.aabb.intersects_segment(p_begin, p_end);
  832. if (!valid) {
  833. stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
  834. } else {
  835. stack[level] = (VISIT_LEFT_BIT << VISITED_BIT_SHIFT) | node;
  836. }
  837. }
  838. continue;
  839. }
  840. case VISIT_LEFT_BIT: {
  841. stack[level] = (VISIT_RIGHT_BIT << VISITED_BIT_SHIFT) | node;
  842. stack[level + 1] = b.left | TEST_AABB_BIT;
  843. level++;
  844. continue;
  845. }
  846. case VISIT_RIGHT_BIT: {
  847. stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
  848. stack[level + 1] = b.right | TEST_AABB_BIT;
  849. level++;
  850. continue;
  851. }
  852. case VISIT_DONE_BIT: {
  853. if (level == 0) {
  854. done = true;
  855. break;
  856. } else
  857. level--;
  858. continue;
  859. }
  860. }
  861. if (done)
  862. break;
  863. }
  864. return intersections;
  865. }
  866. void CSGBrushOperation::MeshMerge::mark_inside_faces() {
  867. // mark faces that are inside. This helps later do the boolean ops when merging.
  868. // this approach is very brute force (with a bunch of optimizatios, such as BVH and pre AABB intersection test)
  869. AABB aabb;
  870. for (int i = 0; i < points.size(); i++) {
  871. if (i == 0) {
  872. aabb.position = points[i];
  873. } else {
  874. aabb.expand_to(points[i]);
  875. }
  876. }
  877. float max_distance = aabb.size.length() * 1.2;
  878. Vector<BVH> bvhvec;
  879. bvhvec.resize(faces.size() * 3); //will never be larger than this (todo make better)
  880. BVH *bvh = bvhvec.ptrw();
  881. AABB faces_a;
  882. AABB faces_b;
  883. bool first_a = true;
  884. bool first_b = true;
  885. for (int i = 0; i < faces.size(); i++) {
  886. bvh[i].left = -1;
  887. bvh[i].right = -1;
  888. bvh[i].face = i;
  889. bvh[i].aabb.position = points[faces[i].points[0]];
  890. bvh[i].aabb.expand_to(points[faces[i].points[1]]);
  891. bvh[i].aabb.expand_to(points[faces[i].points[2]]);
  892. bvh[i].center = bvh[i].aabb.position + bvh[i].aabb.size * 0.5;
  893. bvh[i].next = -1;
  894. if (faces[i].from_b) {
  895. if (first_b) {
  896. faces_b = bvh[i].aabb;
  897. first_b = false;
  898. } else {
  899. faces_b.merge_with(bvh[i].aabb);
  900. }
  901. } else {
  902. if (first_a) {
  903. faces_a = bvh[i].aabb;
  904. first_a = false;
  905. } else {
  906. faces_a.merge_with(bvh[i].aabb);
  907. }
  908. }
  909. }
  910. AABB intersection_aabb = faces_a.intersection(faces_b);
  911. intersection_aabb.grow_by(intersection_aabb.get_longest_axis_size() * 0.01); //grow a little, avoid numerical error
  912. if (intersection_aabb.size == Vector3()) //AABB do not intersect, so neither do shapes.
  913. return;
  914. Vector<BVH *> bvhtrvec;
  915. bvhtrvec.resize(faces.size());
  916. BVH **bvhptr = bvhtrvec.ptrw();
  917. for (int i = 0; i < faces.size(); i++) {
  918. bvhptr[i] = &bvh[i];
  919. }
  920. int max_depth = 0;
  921. int max_alloc = faces.size();
  922. _create_bvh(bvh, bvhptr, 0, faces.size(), 1, max_depth, max_alloc);
  923. for (int i = 0; i < faces.size(); i++) {
  924. if (!intersection_aabb.intersects(bvh[i].aabb))
  925. continue; //not in AABB intersection, so not in face intersection
  926. Vector3 center = points[faces[i].points[0]];
  927. center += points[faces[i].points[1]];
  928. center += points[faces[i].points[2]];
  929. center /= 3.0;
  930. Plane plane(points[faces[i].points[0]], points[faces[i].points[1]], points[faces[i].points[2]]);
  931. Vector3 target = center + plane.normal * max_distance + Vector3(0.0001234, 0.000512, 0.00013423); //reduce chance of edge hits by doing a small increment
  932. int intersections = _bvh_count_intersections(bvh, max_depth, max_alloc - 1, center, target, i);
  933. if (intersections & 1) {
  934. faces[i].inside = true;
  935. }
  936. }
  937. }
  938. void CSGBrushOperation::MeshMerge::add_face(const Vector3 &p_a, const Vector3 &p_b, const Vector3 &p_c, const Vector2 &p_uv_a, const Vector2 &p_uv_b, const Vector2 &p_uv_c, bool p_smooth, bool p_invert, const Ref<Material> &p_material, bool p_from_b) {
  939. Vector3 src_points[3] = { p_a, p_b, p_c };
  940. Vector2 src_uvs[3] = { p_uv_a, p_uv_b, p_uv_c };
  941. int indices[3];
  942. for (int i = 0; i < 3; i++) {
  943. VertexKey vk;
  944. vk.x = int((double(src_points[i].x) + double(vertex_snap) * 0.31234) / double(vertex_snap));
  945. vk.y = int((double(src_points[i].y) + double(vertex_snap) * 0.31234) / double(vertex_snap));
  946. vk.z = int((double(src_points[i].z) + double(vertex_snap) * 0.31234) / double(vertex_snap));
  947. int res;
  948. if (snap_cache.lookup(vk, &res)) {
  949. indices[i] = res;
  950. } else {
  951. indices[i] = points.size();
  952. points.push_back(src_points[i]);
  953. snap_cache.set(vk, indices[i]);
  954. }
  955. }
  956. if (indices[0] == indices[2] || indices[0] == indices[1] || indices[1] == indices[2])
  957. return; //not adding degenerate
  958. MeshMerge::Face face;
  959. face.from_b = p_from_b;
  960. face.inside = false;
  961. face.smooth = p_smooth;
  962. face.invert = p_invert;
  963. if (p_material.is_valid()) {
  964. if (!materials.has(p_material)) {
  965. face.material_idx = materials.size();
  966. materials[p_material] = face.material_idx;
  967. } else {
  968. face.material_idx = materials[p_material];
  969. }
  970. } else {
  971. face.material_idx = -1;
  972. }
  973. for (int k = 0; k < 3; k++) {
  974. face.points[k] = indices[k];
  975. face.uvs[k] = src_uvs[k];
  976. ;
  977. }
  978. faces.push_back(face);
  979. }
  980. void CSGBrushOperation::merge_brushes(Operation p_operation, const CSGBrush &p_A, const CSGBrush &p_B, CSGBrush &result, float p_snap) {
  981. CallbackData cd;
  982. cd.self = this;
  983. cd.A = &p_A;
  984. cd.B = &p_B;
  985. MeshMerge mesh_merge;
  986. mesh_merge.vertex_snap = p_snap;
  987. //check intersections between faces. Use AABB to speed up precheck
  988. //this generates list of buildpolys and clips them.
  989. //this was originally BVH optimized, but its not really worth it.
  990. for (int i = 0; i < p_A.faces.size(); i++) {
  991. cd.face_a = i;
  992. for (int j = 0; j < p_B.faces.size(); j++) {
  993. if (p_A.faces[i].aabb.intersects(p_B.faces[j].aabb)) {
  994. _collision_callback(&p_A, i, cd.build_polys_A, &p_B, j, cd.build_polys_B, mesh_merge);
  995. }
  996. }
  997. }
  998. //merge the already cliped polys back to 3D
  999. for (Map<int, BuildPoly>::Element *E = cd.build_polys_A.front(); E; E = E->next()) {
  1000. _merge_poly(mesh_merge, E->key(), E->get(), false);
  1001. }
  1002. for (Map<int, BuildPoly>::Element *E = cd.build_polys_B.front(); E; E = E->next()) {
  1003. _merge_poly(mesh_merge, E->key(), E->get(), true);
  1004. }
  1005. //merge the non clipped faces back
  1006. for (int i = 0; i < p_A.faces.size(); i++) {
  1007. if (cd.build_polys_A.has(i))
  1008. continue; //made from buildpoly, skipping
  1009. Vector3 points[3];
  1010. Vector2 uvs[3];
  1011. for (int j = 0; j < 3; j++) {
  1012. points[j] = p_A.faces[i].vertices[j];
  1013. uvs[j] = p_A.faces[i].uvs[j];
  1014. }
  1015. Ref<Material> material;
  1016. if (p_A.faces[i].material != -1) {
  1017. material = p_A.materials[p_A.faces[i].material];
  1018. }
  1019. mesh_merge.add_face(points[0], points[1], points[2], uvs[0], uvs[1], uvs[2], p_A.faces[i].smooth, p_A.faces[i].invert, material, false);
  1020. }
  1021. for (int i = 0; i < p_B.faces.size(); i++) {
  1022. if (cd.build_polys_B.has(i))
  1023. continue; //made from buildpoly, skipping
  1024. Vector3 points[3];
  1025. Vector2 uvs[3];
  1026. for (int j = 0; j < 3; j++) {
  1027. points[j] = p_B.faces[i].vertices[j];
  1028. uvs[j] = p_B.faces[i].uvs[j];
  1029. }
  1030. Ref<Material> material;
  1031. if (p_B.faces[i].material != -1) {
  1032. material = p_B.materials[p_B.faces[i].material];
  1033. }
  1034. mesh_merge.add_face(points[0], points[1], points[2], uvs[0], uvs[1], uvs[2], p_B.faces[i].smooth, p_B.faces[i].invert, material, true);
  1035. }
  1036. //mark faces that ended up inside the intersection
  1037. mesh_merge.mark_inside_faces();
  1038. //regen new brush to start filling it again
  1039. result.clear();
  1040. switch (p_operation) {
  1041. case OPERATION_UNION: {
  1042. int outside_count = 0;
  1043. for (int i = 0; i < mesh_merge.faces.size(); i++) {
  1044. if (mesh_merge.faces[i].inside)
  1045. continue;
  1046. outside_count++;
  1047. }
  1048. result.faces.resize(outside_count);
  1049. outside_count = 0;
  1050. for (int i = 0; i < mesh_merge.faces.size(); i++) {
  1051. if (mesh_merge.faces[i].inside)
  1052. continue;
  1053. for (int j = 0; j < 3; j++) {
  1054. result.faces[outside_count].vertices[j] = mesh_merge.points[mesh_merge.faces[i].points[j]];
  1055. result.faces[outside_count].uvs[j] = mesh_merge.faces[i].uvs[j];
  1056. }
  1057. result.faces[outside_count].smooth = mesh_merge.faces[i].smooth;
  1058. result.faces[outside_count].invert = mesh_merge.faces[i].invert;
  1059. result.faces[outside_count].material = mesh_merge.faces[i].material_idx;
  1060. outside_count++;
  1061. }
  1062. result._regen_face_aabbs();
  1063. } break;
  1064. case OPERATION_INTERSECTION: {
  1065. int inside_count = 0;
  1066. for (int i = 0; i < mesh_merge.faces.size(); i++) {
  1067. if (!mesh_merge.faces[i].inside)
  1068. continue;
  1069. inside_count++;
  1070. }
  1071. result.faces.resize(inside_count);
  1072. inside_count = 0;
  1073. for (int i = 0; i < mesh_merge.faces.size(); i++) {
  1074. if (!mesh_merge.faces[i].inside)
  1075. continue;
  1076. for (int j = 0; j < 3; j++) {
  1077. result.faces[inside_count].vertices[j] = mesh_merge.points[mesh_merge.faces[i].points[j]];
  1078. result.faces[inside_count].uvs[j] = mesh_merge.faces[i].uvs[j];
  1079. }
  1080. result.faces[inside_count].smooth = mesh_merge.faces[i].smooth;
  1081. result.faces[inside_count].invert = mesh_merge.faces[i].invert;
  1082. result.faces[inside_count].material = mesh_merge.faces[i].material_idx;
  1083. inside_count++;
  1084. }
  1085. result._regen_face_aabbs();
  1086. } break;
  1087. case OPERATION_SUBSTRACTION: {
  1088. int face_count = 0;
  1089. for (int i = 0; i < mesh_merge.faces.size(); i++) {
  1090. if (mesh_merge.faces[i].from_b && !mesh_merge.faces[i].inside)
  1091. continue;
  1092. if (!mesh_merge.faces[i].from_b && mesh_merge.faces[i].inside)
  1093. continue;
  1094. face_count++;
  1095. }
  1096. result.faces.resize(face_count);
  1097. face_count = 0;
  1098. for (int i = 0; i < mesh_merge.faces.size(); i++) {
  1099. if (mesh_merge.faces[i].from_b && !mesh_merge.faces[i].inside)
  1100. continue;
  1101. if (!mesh_merge.faces[i].from_b && mesh_merge.faces[i].inside)
  1102. continue;
  1103. for (int j = 0; j < 3; j++) {
  1104. result.faces[face_count].vertices[j] = mesh_merge.points[mesh_merge.faces[i].points[j]];
  1105. result.faces[face_count].uvs[j] = mesh_merge.faces[i].uvs[j];
  1106. }
  1107. if (mesh_merge.faces[i].from_b) {
  1108. //invert facing of insides of B
  1109. SWAP(result.faces[face_count].vertices[1], result.faces[face_count].vertices[2]);
  1110. SWAP(result.faces[face_count].uvs[1], result.faces[face_count].uvs[2]);
  1111. }
  1112. result.faces[face_count].smooth = mesh_merge.faces[i].smooth;
  1113. result.faces[face_count].invert = mesh_merge.faces[i].invert;
  1114. result.faces[face_count].material = mesh_merge.faces[i].material_idx;
  1115. face_count++;
  1116. }
  1117. result._regen_face_aabbs();
  1118. } break;
  1119. }
  1120. //updatelist of materials
  1121. result.materials.resize(mesh_merge.materials.size());
  1122. for (const Map<Ref<Material>, int>::Element *E = mesh_merge.materials.front(); E; E = E->next()) {
  1123. result.materials[E->get()] = E->key();
  1124. }
  1125. }