Mshb Csg.cpp 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468
  1. /******************************************************************************/
  2. #include "stdafx.h"
  3. namespace EE{
  4. /******************************************************************************/
  5. // if it won't work then probably 'edgeToTri' should be converted to Dbl version
  6. /******************************************************************************/
  7. // CSG
  8. /******************************************************************************/
  9. #if DEBUG
  10. Int F=-1,
  11. P=-1,
  12. E=-1,
  13. O=-1;
  14. Bool DrawEdges,
  15. DrawPolys,
  16. DrawTris,
  17. DrawVtxs,
  18. DrawInside;
  19. #endif
  20. /******************************************************************************/
  21. enum // SOLID_FLAG
  22. {
  23. SOLID_CUT=1<<31,
  24. };
  25. /******************************************************************************/
  26. UInt SolidSwap(UInt flag)
  27. {
  28. UInt out=(flag&~SOLID_ALL);
  29. if(flag&SOLID_AL )out|=SOLID_AR;
  30. if(flag&SOLID_AR )out|=SOLID_AL;
  31. if(flag&SOLID_BL )out|=SOLID_BR;
  32. if(flag&SOLID_BR )out|=SOLID_BL;
  33. if(flag&SOLID_NAL)out|=SOLID_NAR;
  34. if(flag&SOLID_NAR)out|=SOLID_NAL;
  35. if(flag&SOLID_NBL)out|=SOLID_NBR;
  36. if(flag&SOLID_NBR)out|=SOLID_NBL;
  37. return out;
  38. }
  39. /******************************************************************************/
  40. struct CSG // Constructive Solid Geometry
  41. {
  42. STRUCT(Vtx , VtxFull) // vertex with enhanced position precision
  43. //{
  44. VecD posd; // position (double precision)
  45. void from(C MeshBase &mshb, Int i)
  46. {
  47. super::from(mshb, i);
  48. posd=pos;
  49. }
  50. void to(MeshBase &mshb, Int i)C
  51. {
  52. super::to(mshb, i);
  53. if(InRange(i, mshb.vtx) && mshb.vtx.pos())mshb.vtx.pos(i)=posd;
  54. }
  55. };
  56. struct Face
  57. {
  58. VecI ind ; // triangle vertex indexes
  59. Int id ;
  60. UInt flag; // SOLID_FLAG
  61. BoxI boxi;
  62. Int last_tested_with;
  63. void set(C VecI &ind, Int id, UInt flag) {T.ind=ind; T.id=id; T.flag=flag;}
  64. Face()
  65. {
  66. last_tested_with=-1;
  67. }
  68. };
  69. struct FaceEdge
  70. {
  71. UInt flag ;
  72. EdgeD2_I edge_2d;
  73. EdgeD edge ;
  74. FaceEdge& set(C EdgeD &edge, C MatrixD &face_matrix)
  75. {
  76. T.edge=edge;
  77. T.edge_2d.set(face_matrix.convert(edge, true));
  78. return T;
  79. }
  80. FaceEdge(){flag=0;}
  81. };
  82. struct FacePos
  83. {
  84. VecD2 pos_2d;
  85. VecD pos ;
  86. };
  87. struct FaceEdgeI
  88. {
  89. VecI2 index; // 'face_pos' index
  90. UInt flag ; // ETQ_FLAG
  91. void set(Int index0, Int index1, UInt flag) {T.index.set(index0, index1); T.flag=flag;}
  92. };
  93. Memb<Vtx > vtx ; // list of vertexes
  94. Memb<Face> face , // list of faces
  95. face_over, // list of possibly overlapped faces
  96. face_done; // list of processed faces
  97. Box box_ab ; // Box(a) & Box(b), operation box
  98. Boxes boxes_ab ;
  99. Memc<Int> *box_face ;
  100. CutsCache cuts_cache_a,
  101. cuts_cache_b;
  102. // per face
  103. Memc<FaceEdge > face_edge ;
  104. Memc<FacePos > face_pos ;
  105. Memc<FaceEdgeI> face_edgei;
  106. void addTri(C VecI &ind, Int id, UInt flag)
  107. {
  108. Box box =vtx[ind.x].pos;
  109. box|=vtx[ind.y].pos;
  110. box|=vtx[ind.z].pos;
  111. if(CutsEps(box, box_ab))face .New().set(ind, id, flag); // add for processing
  112. else face_done.New().set(ind, id, flag); // add as processed
  113. }
  114. void addMesh(C MeshBase &mshb, UInt flag)
  115. {
  116. Int vtxs=vtx.elms();
  117. FREPA(mshb.vtx )T.vtx.New().from(mshb, i);
  118. FREPA(mshb.tri )addTri(mshb.tri.ind(i)+vtxs, mshb.tri.id() ? mshb.tri.id(i) : -1, flag);
  119. FREPA(mshb.quad)
  120. {
  121. addTri(mshb.quad.ind(i).tri0()+vtxs, mshb.quad.id() ? mshb.quad.id(i) : -1, flag);
  122. addTri(mshb.quad.ind(i).tri1()+vtxs, mshb.quad.id() ? mshb.quad.id(i) : -1, flag);
  123. }
  124. }
  125. void setFaceBox(Face &face)
  126. {
  127. VecI &ind =face.ind;
  128. Box box =vtx [ind.x].pos;
  129. box|=vtx [ind.y].pos;
  130. box|=vtx [ind.z].pos;
  131. face.boxi=boxes_ab.coords(box.extend(EPS));
  132. }
  133. void assignFacesToBoxes()
  134. {
  135. REPA(face)
  136. {
  137. setFaceBox(face[i]);
  138. BoxI &boxi=face[i].boxi;
  139. for(Int z=boxi.min.z; z<=boxi.max.z; z++)
  140. for(Int y=boxi.min.y; y<=boxi.max.y; y++)
  141. for(Int x=boxi.min.x; x<=boxi.max.x; x++)box_face[boxes_ab.index(VecI(x, y, z))].New()=i;
  142. }
  143. }
  144. Int getPos(C VecD &pos, C MatrixD &face_matrix)
  145. {
  146. // find existing
  147. REPA(face_pos)if(Equal(face_pos[i].pos, pos))return i;
  148. // add new
  149. Int i =face_pos.elms();
  150. FacePos &fp=face_pos.New ();
  151. fp.pos =pos;
  152. fp.pos_2d=face_matrix.convert(pos, true);
  153. return i;
  154. }
  155. void triFromEdges(Face &face, TriD &face_tri, MatrixD &face_matrix, Memb<Face> &faces)
  156. {
  157. // add base edges
  158. face_edge.New().set(face_tri.edge0(), face_matrix).flag=ETQ_R;
  159. face_edge.New().set(face_tri.edge1(), face_matrix).flag=ETQ_R;
  160. face_edge.New().set(face_tri.edge2(), face_matrix).flag=ETQ_R;
  161. // cut edges
  162. Memc<Dbl> steps;
  163. REPAD(i, face_edge)
  164. {
  165. FaceEdge &face_edge_i=face_edge[i];
  166. REPAD(j, face_edge)if(i!=j)
  167. {
  168. EdgeD2 cuts;
  169. REPD(c, CutsEdgeEdge(face_edge_i.edge_2d, face_edge[j].edge_2d, &cuts))
  170. {
  171. Dbl step=DistPointPlane(cuts.p[c], face_edge_i.edge_2d.p[0], face_edge_i.edge_2d.dir);
  172. if( step>EPSD && step<face_edge_i.edge_2d.length-EPSD)steps.New()=step/face_edge_i.edge_2d.length;
  173. }
  174. }
  175. Sort(steps.data(), steps.elms());
  176. Int p0=getPos(face_edge_i.edge.p[0], face_matrix), p1;
  177. FREPA(steps)
  178. {
  179. p1=getPos(face_edge_i.edge.lerp(steps[i]), face_matrix);
  180. if(p1!=p0)
  181. {
  182. face_edgei.New().set(p0, p1, face_edge_i.flag);
  183. p0=p1;
  184. }
  185. }
  186. p1=getPos(face_edge_i.edge.p[1], face_matrix); if(p1!=p0)face_edgei.New().set(p0, p1, face_edge_i.flag);
  187. // finish
  188. steps.clear();
  189. }
  190. // join edges
  191. FREPAD(i, face_edgei)
  192. {
  193. FaceEdgeI &face_edgei_i=face_edgei[i]; Int pi0=face_edgei_i.index.x, pi1=face_edgei_i.index.y;
  194. for(Int j=i+1; j<face_edgei.elms(); )
  195. {
  196. FaceEdgeI &face_edgei_j=face_edgei[j]; Int pj0=face_edgei_j.index.x, pj1=face_edgei_j.index.y;
  197. if((pi0==pj0 && pi1==pj1) // equal in the same order
  198. || (pi1==pj0 && pi0==pj1)) // equal in reversed order
  199. {
  200. face_edgei_i.flag|=((pi0==pj0) ? face_edgei_j.flag : EtqFlagSwap(face_edgei_j.flag)); // if equal in reversed order then swap the solid flag
  201. face_edgei.remove(j);
  202. }else j++;
  203. }
  204. // adjust flags
  205. if(!face_edgei_i.flag )face_edgei_i.flag|= ETQ_LR;else // if there's no side , then add both of them
  206. if( face_edgei_i.flag&ETQ_L && face_edgei_i.flag&ETQ_R)face_edgei_i.flag&=~ETQ_LR; // if it has both sides, then remove them
  207. }
  208. // create triangles
  209. {
  210. // codes assume that 'mshb' will not change the order of vertexes, but only triangles will be created from edges (edge->tri)
  211. MeshBase mshb(face_pos.elms(), face_edgei.elms(), 0, 0, EDGE_FLAG);
  212. REPA(mshb.vtx)
  213. {
  214. mshb.vtx.pos(i).set(face_pos[i].pos_2d, 0);
  215. }
  216. REPA(mshb.edge)
  217. {
  218. FaceEdgeI &src=face_edgei[i];
  219. mshb.edge.ind (i)=src.index;
  220. mshb.edge.flag(i)=src.flag ;
  221. }
  222. #if DEBUG
  223. // draw edges
  224. if(DrawEdges)REPA(face_edgei)if(E<0 || E==i)
  225. {
  226. EdgeD edge(face_pos[face_edgei[i].index.x].pos, face_pos[face_edgei[i].index.y].pos);
  227. edge.draw(RED);
  228. if(E>=0)
  229. {
  230. edge.p[0].draw(RED);
  231. edge.p[1].draw(RED);
  232. }
  233. }
  234. // draw polys
  235. if(DrawPolys)
  236. {
  237. SetMatrix((Matrix)face_matrix);
  238. Meml<Poly> polys; mshb.edgeToPoly(polys);
  239. REPA(polys)if(P<0 || P==i)polys[i].draw3D(GREEN);
  240. if(InRange(P, polys))
  241. {
  242. REPA(polys[P].vtx)
  243. {
  244. Vec pos=mshb.vtx.pos(polys[P].vtx[i].index);
  245. Vec2 screen; if(PosToScreenM(pos, screen))D.text(screen, S+i);
  246. }
  247. }
  248. SetMatrix();
  249. }
  250. #endif
  251. mshb.edgeToTri(false);
  252. // convert mshb vtxs/triangles to csg vtxs/faces
  253. Int vtxs=vtx.elms();
  254. FREPA(mshb.vtx)
  255. {
  256. Vtx &v=vtx.New();
  257. v.posd=face_pos[i].pos;
  258. v.lerp(vtx[face.ind.x], vtx[face.ind.y], vtx[face.ind.z], (Vec)TriBlend(v.posd, face_tri, true));
  259. }
  260. FREPA(mshb.tri)
  261. {
  262. faces.New().set(mshb.tri.ind(i)+vtxs, face.id, face.flag|SOLID_CUT);
  263. }
  264. #if DEBUG
  265. // draw tris
  266. if(DrawTris)REPA(mshb.tri)
  267. {
  268. VecI &ind=faces[faces.elms()-1-i].ind;
  269. TriD(vtx[ind.x].posd, vtx[ind.y].posd, vtx[ind.z].posd).draw(ColorI(i), true);
  270. }
  271. // draw vtxs
  272. if(DrawVtxs)if(F>=0)REPA(face_pos)
  273. {
  274. Vec p=face_pos[i].pos;
  275. Vec2 s; if(PosToScreen(p, s))D.text(s, S+i);
  276. }
  277. #endif
  278. }
  279. // finish
  280. face_edgei.clear();
  281. face_pos .clear();
  282. }
  283. void cutFaces(Bool detect_self_intersections)
  284. {
  285. REPA(face) // for each face
  286. {
  287. Face &face=T.face[i];
  288. BoxI &boxi= face.boxi;
  289. TriD face_tri (vtx[face.ind.x].posd, vtx[face.ind.y].posd, vtx[face.ind.z].posd);
  290. PlaneD face_plane(face_tri.p[0], face_tri.n);
  291. MatrixD face_matrix; face_matrix.setPosDir(face_tri.p[0], -face_tri.n);
  292. PlaneD face_tri_planes[3]=
  293. {
  294. PlaneD(face_tri.p[0], CrossN(face_tri.n, face_tri.p[0]-face_tri.p[1])),
  295. PlaneD(face_tri.p[1], CrossN(face_tri.n, face_tri.p[1]-face_tri.p[2])),
  296. PlaneD(face_tri.p[2], CrossN(face_tri.n, face_tri.p[2]-face_tri.p[0])),
  297. };
  298. /*TriD2 face_tri_2d( face_matrix.convert(face_tri.p[0], true), face_matrix.convert(face_tri.p[1], true), face_matrix.convert(face_tri.p[2], true));
  299. PlaneD2 face_tri_planes[3]=
  300. {
  301. PlaneD2(face_tri_2d.p[0], PerpN(face_tri_2d.p[0]-face_tri_2d.p[1])),
  302. PlaneD2(face_tri_2d.p[1], PerpN(face_tri_2d.p[1]-face_tri_2d.p[2])),
  303. PlaneD2(face_tri_2d.p[2], PerpN(face_tri_2d.p[2]-face_tri_2d.p[0])),
  304. };*/
  305. Bool overlapped=false;
  306. for(Int z=boxi.min.z; z<=boxi.max.z; z++) // for every box where face lies
  307. for(Int y=boxi.min.y; y<=boxi.max.y; y++)
  308. for(Int x=boxi.min.x; x<=boxi.max.x; x++)
  309. {
  310. Memc<Int> &box_face=T.box_face[boxes_ab.index(VecI(x, y, z))];
  311. REPAD(t, box_face) // for each face in that box
  312. {
  313. Int testi=box_face[t]; if(testi!=i) // if the face isn't current
  314. {
  315. Face &test=T.face[testi];
  316. UInt flag=(face.flag|test.flag); if(detect_self_intersections ? true : (flag&SOLID_A && flag&SOLID_B))
  317. if(test.last_tested_with!=i) // if we haven't yet tested the pair
  318. {
  319. test.last_tested_with=i;
  320. TriD test_tri(vtx[test.ind.x].posd, vtx[test.ind.y].posd, vtx[test.ind.z].posd);
  321. // TODO: optimize
  322. /*#if 0
  323. Bool p0_equal=(face_tri.p[0]==test_tri.p[0] || face_tri.p[0]==test_tri.p[1] || face_tri.p[0]==test_tri.p[2]),
  324. p1_equal=(face_tri.p[1]==test_tri.p[0] || face_tri.p[1]==test_tri.p[1] || face_tri.p[1]==test_tri.p[2]),
  325. p2_equal=(face_tri.p[2]==test_tri.p[0] || face_tri.p[2]==test_tri.p[1] || face_tri.p[2]==test_tri.p[2]);
  326. #else
  327. Bool p0_equal=(Equal(face_tri.p[0], test_tri.p[0]) || Equal(face_tri.p[0], test_tri.p[1]) || Equal(face_tri.p[0], test_tri.p[2])),
  328. p1_equal=(Equal(face_tri.p[1], test_tri.p[0]) || Equal(face_tri.p[1], test_tri.p[1]) || Equal(face_tri.p[1], test_tri.p[2])),
  329. p2_equal=(Equal(face_tri.p[2], test_tri.p[0]) || Equal(face_tri.p[2], test_tri.p[1]) || Equal(face_tri.p[2], test_tri.p[2]));
  330. #endif
  331. //if(p0_equal+p1_equal+p2_equal<=1) // we can easily skip thise triangles which share 2,3 vertexes, no we can't because they can overlap*/
  332. {
  333. EdgeD edge;
  334. Int c=CutsTriPlaneEps(test_tri, face_plane, edge);
  335. if(c==-1) // coplanar
  336. {
  337. overlapped=true;
  338. REP(3) // all triangle edges
  339. {
  340. edge.set(test_tri.p[i], test_tri.p[(i+1)%3]);
  341. if(ClipEps(edge, face_tri_planes[0])) // Eps necessary
  342. if(ClipEps(edge, face_tri_planes[1]))
  343. if(ClipEps(edge, face_tri_planes[2]))
  344. {
  345. face_edge.New().set(edge, face_matrix);
  346. }
  347. }
  348. }else
  349. if(c==2)
  350. {
  351. if(ClipEps(edge, face_tri_planes[0])) // Eps necessary
  352. if(ClipEps(edge, face_tri_planes[1]))
  353. if(ClipEps(edge, face_tri_planes[2]))
  354. {
  355. face_edge.New().set(edge, face_matrix);
  356. }
  357. }
  358. }
  359. }
  360. }
  361. }
  362. }
  363. #if DEBUG
  364. if(F<0 || i==F)
  365. #endif
  366. {
  367. #if DEBUG
  368. if(DrawEdges && !face_edge.elms())face_tri.draw(RED);
  369. #endif
  370. Memb<Face> &faces=(overlapped ? face_over : face_done);
  371. if(face_edge.elms())triFromEdges(face, face_tri, face_matrix, faces); // intersection
  372. else faces.New()=face ; // no intersection
  373. }
  374. face_edge.clear();
  375. }
  376. }
  377. Bool overlap(TriD &tri_a, TriD &tri_b)
  378. {
  379. /* we need to use more comples cases, because triangles are created from polygons
  380. simple algorithm is not enough:
  381. return
  382. (Equal(tri_a.p[0], tri_b.p[0]) || Equal(tri_a.p[0], tri_b.p[1]) || Equal(tri_a.p[0], tri_b.p[2]))
  383. && (Equal(tri_a.p[1], tri_b.p[0]) || Equal(tri_a.p[1], tri_b.p[1]) || Equal(tri_a.p[1], tri_b.p[2]))
  384. && (Equal(tri_a.p[2], tri_b.p[0]) || Equal(tri_a.p[2], tri_b.p[1]) || Equal(tri_a.p[2], tri_b.p[2]));
  385. */
  386. #if DEBUG
  387. if(Kb.b(KB_O))return false;
  388. #endif
  389. Bool max =(tri_a.area()>tri_b.area());
  390. TriD &tri0=(max ? tri_a : tri_b), // bigger
  391. &tri1=(max ? tri_b : tri_a); // smaller
  392. if(tri1.coplanar(tri0))
  393. {
  394. VecD tri_n[3]=
  395. {
  396. CrossN(tri0.n, tri0.p[0]-tri0.p[1]),
  397. CrossN(tri0.n, tri0.p[1]-tri0.p[2]),
  398. CrossN(tri0.n, tri0.p[2]-tri0.p[0]),
  399. };
  400. EdgeD_I ei0[3]=
  401. {
  402. EdgeD_I(tri0.p[0], tri0.p[1]),
  403. EdgeD_I(tri0.p[1], tri0.p[2]),
  404. EdgeD_I(tri0.p[2], tri0.p[0]),
  405. };
  406. REPD(e1, 3)
  407. {
  408. EdgeD_I ei1(tri1.p[e1], tri1.p[(e1+1)%3]);
  409. EdgeD cuts;
  410. Bool touch=false;
  411. REPD(e0, 3)if(Int c=CutsEdgeEdge(ei1, ei0[e0], &cuts))
  412. {
  413. if(c==2)return DistPointPlane(tri1.p[(e1+2)%3], tri0.p[e0], tri_n[e0])<0;
  414. Int dup0;
  415. if(Equal(cuts.p[0], ei0[e0].p[0]))dup0=0;else
  416. if(Equal(cuts.p[0], ei0[e0].p[1]))dup0=1;else dup0=-1;
  417. Int dup1;
  418. if(Equal(cuts.p[0], ei1.p[0]))dup1=0;else
  419. if(Equal(cuts.p[0], ei1.p[1]))dup1=1;else dup1=-1;
  420. if(dup0<0)
  421. {
  422. if(dup1<0)return true;
  423. if(DistPointPlane(ei1.p[!dup1], tri0.p[e0], tri_n[e0])<0)return true;
  424. }else
  425. {
  426. if(dup1!=0)if(DistPointPlane(ei1.p[0], tri0.p[(e0+dup0 )%3], tri_n[(e0+dup0 )%3])<-EPSD
  427. && DistPointPlane(ei1.p[0], tri0.p[(e0+dup0+2)%3], tri_n[(e0+dup0+2)%3])<-EPSD)return true;
  428. if(dup1!=1)if(DistPointPlane(ei1.p[1], tri0.p[(e0+dup0 )%3], tri_n[(e0+dup0 )%3])<-EPSD
  429. && DistPointPlane(ei1.p[1], tri0.p[(e0+dup0+2)%3], tri_n[(e0+dup0+2)%3])<-EPSD)return true;
  430. }
  431. touch=true;
  432. }
  433. if(!touch && DistPointPlane(ei1.p[0], tri0.p[0], tri_n[0])<0
  434. && DistPointPlane(ei1.p[0], tri0.p[1], tri_n[1])<0
  435. && DistPointPlane(ei1.p[0], tri0.p[2], tri_n[2])<0)return true;
  436. }
  437. }
  438. return false;
  439. }
  440. // TODO: analyze if 'removeOverlapped' works ok (order, enabling B<->A, removing)
  441. void removeOverlapped()
  442. {
  443. // set boxes
  444. REPA(face_over)setFaceBox(face_over[i]);
  445. // detect overlaps
  446. REPAD(i, face_over)
  447. {
  448. Face &face_i=face_over[i]; TriD tri_i(vtx[face_i.ind.x].posd, vtx[face_i.ind.y].posd, vtx[face_i.ind.z].posd);
  449. Bool face_i_has_a=((face_i.flag&SOLID_A)!=0);
  450. REPD(j, i)
  451. {
  452. Face &face_j=face_over[j];
  453. Bool face_j_has_a=((face_j.flag&SOLID_A)!=0);
  454. if(face_i_has_a!=face_j_has_a && Cuts(face_i.boxi, face_j.boxi))
  455. {
  456. TriD tri_j(vtx[face_j.ind.x].posd, vtx[face_j.ind.y].posd, vtx[face_j.ind.z].posd);
  457. if(overlap(tri_i, tri_j))
  458. {
  459. /*#if DEBUG
  460. tri_i.draw(RED , true);
  461. tri_j.draw(GREEN, true);
  462. #endif*/
  463. face_j.flag|=((Dot(tri_i.n, tri_j.n)>0) ? face_i.flag : SolidSwap(face_i.flag)); // if equal in reversed order the swap the solid flag
  464. face_j.boxi|=face_i.boxi;
  465. goto overlapped;
  466. }
  467. }
  468. }
  469. face_done.New()=face_i;
  470. overlapped:;
  471. }
  472. }
  473. void setCutFacesSolid(C MeshBase &a, C MeshBase &b)
  474. {
  475. // set solid for 'cut' faces
  476. REPA(face_done)
  477. {
  478. Face &face=face_done[i];
  479. UInt &flag=face.flag;
  480. if(flag&SOLID_CUT)
  481. {
  482. flag^=SOLID_CUT;
  483. if(!(flag&SOLID_A) || !(flag&SOLID_B))
  484. {
  485. VecI &ind=face.ind;
  486. Vec p =Avg(vtx[ind.x].pos, vtx[ind.y].pos, vtx[ind.z].pos);
  487. if(!(flag&SOLID_A)) // if there's no info about SOLID_A
  488. {
  489. if(CutsPointMesh(p, a, null, &cuts_cache_a))flag|=SOLID_AR |SOLID_AL ;
  490. else flag|=SOLID_NAR|SOLID_NAL;
  491. #if DEBUG
  492. if(DrawInside)TriD(vtx[ind.x].posd, vtx[ind.y].posd, vtx[ind.z].posd).draw((flag&SOLID_AR) ? ORANGE : PURPLE, true);
  493. #endif
  494. }
  495. if(!(flag&SOLID_B)) // if there's no info about SOLID_B
  496. {
  497. if(CutsPointMesh(p, b, null, &cuts_cache_b))flag|=SOLID_BR |SOLID_BL ;
  498. else flag|=SOLID_NBR|SOLID_NBL;
  499. #if DEBUG
  500. if(DrawInside)TriD(vtx[ind.x].posd, vtx[ind.y].posd, vtx[ind.z].posd).draw((flag&SOLID_BR) ? ORANGE : PURPLE, true);
  501. #endif
  502. }
  503. }
  504. }
  505. }
  506. }
  507. void build(MeshBase &mshb, UInt flag)
  508. {
  509. mshb.create(face_done.elms()*3, 0, face_done.elms(), 0, flag);
  510. FREPA(face_done)
  511. {
  512. Face &face=face_done[i];
  513. Int p0 =i*3+0,
  514. p1 =i*3+1,
  515. p2 =i*3+2;
  516. vtx[face.ind.x].to(mshb, p0);
  517. vtx[face.ind.y].to(mshb, p1);
  518. vtx[face.ind.z].to(mshb, p2);
  519. mshb.tri.ind (i).set(p0,p1,p2);
  520. mshb.tri.flag(i)=face.flag;
  521. if(mshb.tri.id())mshb.tri.id (i)=face.id ;
  522. }
  523. }
  524. void distributeSolid(MeshBase &mshb, Int tri, UInt flag, UInt solid) // distribute the solid info for neighbor faces, 'solid' here is equal to SOLID_A or SOLID_B
  525. {
  526. Memb<Int> tris; tris.New()=tri; // list of triangles for checking
  527. for(; tris.elms(); )
  528. {
  529. Int tri=tris.pop(); // get the triangle and remove it from the list
  530. if(!(mshb.tri.flag(tri)&solid)) // if there's no info about solid
  531. {
  532. mshb.tri.flag (tri)|=flag; // add info
  533. VecI adj_face=mshb.tri.adjFace(tri) ; // list of neighbors
  534. #if DEBUG
  535. if(!Kb.b(KB_D))
  536. #endif
  537. REPA(adj_face) // for each neighbor
  538. {
  539. Int adj =adj_face.c[i];
  540. if( adj!=-1)tris.New()=adj; // if it exists then add it to the list, compare to -1 and not >=0 because it can have SIGN_BIT
  541. }
  542. }
  543. }
  544. }
  545. void setSolid(MeshBase &mshb, C MeshBase &a, C MeshBase &b)
  546. {
  547. mshb.setVtxDup().setAdjacencies(true, false);
  548. // distribute info about solid which we already have
  549. #if DEBUG
  550. if(!Kb.b(KB_D))
  551. #endif
  552. REPD(s, 2) // distribute 2 solids
  553. {
  554. UInt solid=(s ? SOLID_B : SOLID_A); // SOLID_A and SOLID_B
  555. REPA(mshb.tri) // for each triangle
  556. {
  557. if(UInt f=(mshb.tri.flag(i)&solid)) // if it has info about solid
  558. {
  559. VecI af=mshb.tri.adjFace(i); // list of neighbors
  560. REPA(af) // for each neighbor
  561. {
  562. Int adj =af.c[i];
  563. if( adj!=-1 && !(mshb.tri.flag(adj)&solid))distributeSolid(mshb, adj, f, solid); // if the neighbor exists and it doesn't have the info about solid which we can provide, compare to -1 and not >=0 because it can have SIGN_BIT
  564. }
  565. }
  566. }
  567. }
  568. // test missing solid's
  569. REPD(s, 2)
  570. {
  571. UInt solid=(s ? SOLID_B : SOLID_A); // SOLID_A and SOLID_B
  572. REPA(mshb.tri) // for each triangle
  573. {
  574. if(!(mshb.tri.flag(i)&solid)) // if doesn't have info about solid
  575. {
  576. Int *p = mshb.tri.ind(i).c;
  577. Vec pos =Avg(mshb.vtx.pos(p[0]), mshb.vtx.pos(p[1]), mshb.vtx.pos(p[2]));
  578. Bool inside=CutsPointMesh(pos, s ? b : a, null, s ? &cuts_cache_b : &cuts_cache_a); // test solid info
  579. UInt flag =(inside ? (s?(SOLID_BL|SOLID_BR):(SOLID_AL|SOLID_AR)) : (s?(SOLID_NBL|SOLID_NBR):(SOLID_NAL|SOLID_NAR)));
  580. distributeSolid(mshb, i, flag, solid); // distribute solid info
  581. }
  582. }
  583. }
  584. }
  585. Bool faceIs(UInt sel, UInt f, Bool &reverse)
  586. {
  587. reverse=false;
  588. switch(sel)
  589. {
  590. case SEL_A: // a sub b
  591. {
  592. if(f&SOLID_NBL && f&SOLID_NBR) // outside B
  593. {
  594. if(f&SOLID_AR && f&SOLID_NAL)return true;
  595. if(f&SOLID_AL && f&SOLID_NAR)return reverse=true;
  596. }else
  597. if(f&SOLID_AR && f&SOLID_AL) // inside A
  598. {
  599. if(f&SOLID_BR && f&SOLID_NBL)return reverse=true;
  600. if(f&SOLID_BL && f&SOLID_NBR)return true;
  601. }
  602. }break;
  603. case SEL_B: // b sub a
  604. {
  605. if(f&SOLID_NAL && f&SOLID_NAR) // outside A
  606. {
  607. if(f&SOLID_BR && f&SOLID_NBL)return true;
  608. if(f&SOLID_BL && f&SOLID_NBR)return reverse=true;
  609. }else
  610. if(f&SOLID_BR && f&SOLID_BL) // inside B
  611. {
  612. if(f&SOLID_AR && f&SOLID_NAL)return reverse=true;
  613. if(f&SOLID_AL && f&SOLID_NAR)return true;
  614. }
  615. }break;
  616. case SEL_A|SEL_B : // xor
  617. case SEL_A|SEL_B|SEL_AB: // add,or
  618. {
  619. if(f&SOLID_NBL && f&SOLID_NBR) // outside B
  620. {
  621. if(f&SOLID_AR && f&SOLID_NAL)return true;
  622. if(f&SOLID_AL && f&SOLID_NAR)return reverse=true;
  623. }else
  624. if(f&SOLID_NAL && f&SOLID_NAR) // outside A
  625. {
  626. if(f&SOLID_BR && f&SOLID_NBL)return true;
  627. if(f&SOLID_BL && f&SOLID_NBR)return reverse=true;
  628. }else // covers
  629. {
  630. if(f&SOLID_AR && f&SOLID_NAL && f&SOLID_BR && f&SOLID_NBL)return true;
  631. if(f&SOLID_AL && f&SOLID_NAR && f&SOLID_BL && f&SOLID_NBR)return reverse=true;
  632. }
  633. }break;
  634. case SEL_AB: // and,mul
  635. {
  636. if(f&SOLID_BL && f&SOLID_BR) // inside B
  637. {
  638. if(f&SOLID_AR && f&SOLID_NAL)return true;
  639. if(f&SOLID_AL && f&SOLID_NAR)return reverse=true;
  640. }else
  641. if(f&SOLID_AL && f&SOLID_AR) // inside A
  642. {
  643. if(f&SOLID_BR && f&SOLID_NBL)return true;
  644. if(f&SOLID_BL && f&SOLID_NBR)return reverse=true;
  645. }else // covers
  646. {
  647. if(f&SOLID_AR && f&SOLID_NAL && f&SOLID_BR && f&SOLID_NBL)return true;
  648. if(f&SOLID_AL && f&SOLID_NAR && f&SOLID_BL && f&SOLID_NBR)return reverse=true;
  649. }
  650. }break;
  651. }
  652. return false;
  653. }
  654. void removeAndFlipFaces(MeshBase &mshb, UInt sel)
  655. {
  656. Memt<Bool> is; is.setNum(mshb.tris());
  657. REPA(mshb.tri)
  658. {
  659. Bool reverse;
  660. if(is[i]=faceIs(sel, mshb.tri.flag(i), reverse))if(reverse)
  661. {
  662. VecI ind=mshb.tri.ind(i).reverse();
  663. if(mshb.vtx.nrm())
  664. {
  665. mshb.vtx.nrm(ind.x).chs();
  666. mshb.vtx.nrm(ind.y).chs();
  667. mshb.vtx.nrm(ind.z).chs();
  668. }
  669. if(mshb.vtx.tan() && !mshb.vtx.bin())
  670. {
  671. mshb.vtx.tan(ind.x).chs();
  672. mshb.vtx.tan(ind.y).chs();
  673. mshb.vtx.tan(ind.z).chs();
  674. if(mshb.vtx.tex0())
  675. {
  676. CHS(mshb.vtx.tex0(ind.x).x);
  677. CHS(mshb.vtx.tex0(ind.y).x);
  678. CHS(mshb.vtx.tex0(ind.z).x);
  679. }
  680. if(mshb.vtx.tex1())
  681. {
  682. CHS(mshb.vtx.tex1(ind.x).x);
  683. CHS(mshb.vtx.tex1(ind.y).x);
  684. CHS(mshb.vtx.tex1(ind.z).x);
  685. }
  686. if(mshb.vtx.tex2())
  687. {
  688. CHS(mshb.vtx.tex2(ind.x).x);
  689. CHS(mshb.vtx.tex2(ind.y).x);
  690. CHS(mshb.vtx.tex2(ind.z).x);
  691. }
  692. }
  693. }
  694. }
  695. mshb.keepTris(is);
  696. }
  697. void optimize(MeshBase &mshb, Flt weld_pos_eps)
  698. {
  699. mshb.removeUnusedVtxs(); mshb.weldVtxValues(VTX_POS, weld_pos_eps, EPS_COL_COS, -1).weldVtx(VTX_ALL, 0);
  700. }
  701. CSG(C MeshBase &a, C MeshBase &b, UInt sel, MeshBase &dest, Bool detect_self_intersections, Flt weld_pos_eps) : cuts_cache_a(a), cuts_cache_b(b)
  702. {
  703. #if DEBUG
  704. DrawEdges ^=Kb.bp(KB_E);
  705. DrawPolys ^=Kb.bp(KB_P);
  706. DrawTris ^=Kb.bp(KB_T);
  707. DrawVtxs ^=Kb.bp(KB_V);
  708. DrawInside^=Kb.bp(KB_I);
  709. #endif
  710. // load data
  711. box_ab=(cuts_cache_a.box&cuts_cache_b.box);
  712. addMesh(a, SOLID_AR|SOLID_NAL);
  713. addMesh(b, SOLID_BR|SOLID_NBL);
  714. boxes_ab.set(box_ab, face.elms());
  715. New(box_face, boxes_ab.num());
  716. // process data
  717. assignFacesToBoxes();
  718. cutFaces (detect_self_intersections);
  719. removeOverlapped ();
  720. setCutFacesSolid (a, b);
  721. // build data
  722. Bool id=(((a.flag()|b.flag())&FACE_ID)!=0);
  723. MeshBase temp;
  724. build (temp, ((a.flag()|b.flag())&VTX_ALL) | TRI_FLAG | (id ? FACE_ID : 0));
  725. setSolid (temp, a, b);
  726. #if DEBUG
  727. if(!Kb.b(KB_R))
  728. #endif
  729. removeAndFlipFaces(temp, sel);
  730. optimize (temp, weld_pos_eps);
  731. Swap (dest, temp);
  732. }
  733. ~CSG()
  734. {
  735. DeleteN(box_face);
  736. }
  737. };
  738. /******************************************************************************/
  739. struct Material4
  740. {
  741. MaterialPtr m[4];
  742. Material4( ) {}
  743. Material4(C MeshPart &part)
  744. {
  745. m[0]=part.multiMaterial(0);
  746. m[1]=part.multiMaterial(1);
  747. m[2]=part.multiMaterial(2);
  748. m[3]=part.multiMaterial(3);
  749. }
  750. };
  751. void Csg(MeshBase &a, C MeshBase &b, UInt sel, MeshBase *dest, Bool detect_self_intersections, Flt weld_pos_eps)
  752. {
  753. CSG csg(a, b, sel, dest ? *dest : a, detect_self_intersections, weld_pos_eps);
  754. }
  755. void Csg(MeshLod &a, C MeshLod &b, UInt sel, MeshLod *dest, Bool detect_self_intersections, Flt weld_pos_eps)
  756. {
  757. Memc<Material4> materials;
  758. FREPA(a)materials.add(a.parts[i]);
  759. FREPA(b)materials.add(b.parts[i]);
  760. MeshBase a_base; a_base.create(a, ~0, true);
  761. MeshBase b_base; b_base.create(b, ~0, true);
  762. REPA(b_base.edge)b_base.edge.id(i)+=a.parts.elms();
  763. REPA(b_base.tri )b_base.tri .id(i)+=a.parts.elms();
  764. REPA(b_base.quad)b_base.quad.id(i)+=a.parts.elms();
  765. Csg(a_base, b_base, sel, null, detect_self_intersections, weld_pos_eps);
  766. if(!dest)dest=&a;
  767. a_base.copyId(*dest);
  768. FREPA(*dest)dest->parts[i].multiMaterial(materials[i].m[0], materials[i].m[1], materials[i].m[2], materials[i].m[3]);
  769. }
  770. /******************************************************************************/
  771. // CLIP MESH
  772. /******************************************************************************/
  773. static void ClipMeshSimple(C MeshBase &src, C Matrix *matrix, MeshBase &dest, C Plane *clip_plane, Int clip_planes, Flt weld_pos_eps) // processes only vertex positions and face (triangle and quad) indexes
  774. {
  775. MeshBase temp;
  776. // box test
  777. Vec corner[8]; OBox(Box(src), matrix ? *matrix : MatrixIdentity).toCorners(corner);
  778. Bool all_inside=true;
  779. REPD(p, clip_planes)
  780. {
  781. Bool inside=false,
  782. outside=false;
  783. REPAD(c, corner)
  784. {
  785. if(Dist(corner[c], clip_plane[p])<=0)inside=true;else outside=true;
  786. }
  787. if(!inside)goto finished; // if no vertexes are inside the plane then cancel
  788. if(outside)all_inside=false;
  789. }
  790. // create dest
  791. if(all_inside)
  792. {
  793. temp.create(src, VTX_POS|FACE_ALL);
  794. if(matrix)temp.transform(*matrix);
  795. }else
  796. {
  797. Bool set_flags=(src.tri.flag() || src.quad.flag());
  798. Memc< Byte > poly_flags;
  799. Memc< Memc<Vec> > polys;
  800. Memc<Vec> poly[2];
  801. Bool poly_cur=0;
  802. // triangles
  803. REPA(src.tri)
  804. {
  805. VecI ind=src.tri.ind(i);
  806. poly[poly_cur].add(src.vtx.pos(ind.x));
  807. poly[poly_cur].add(src.vtx.pos(ind.y));
  808. poly[poly_cur].add(src.vtx.pos(ind.z));
  809. if(matrix)REPAO(poly[poly_cur])*=*matrix;
  810. REP(clip_planes)
  811. {
  812. ClipPoly(poly[poly_cur], clip_plane[i], poly[poly_cur^1]);
  813. poly_cur^=1; if(!poly[poly_cur].elms())goto no_tri;
  814. }
  815. Swap(polys.New(), poly[poly_cur]); if(set_flags)poly_flags.add(src.tri.flag() ? src.tri.flag(i) : 0);
  816. no_tri:;
  817. poly[poly_cur^1].clear();
  818. }
  819. // quads
  820. REPA(src.quad)
  821. {
  822. VecI4 ind=src.quad.ind(i);
  823. poly[poly_cur].add(src.vtx.pos(ind.x));
  824. poly[poly_cur].add(src.vtx.pos(ind.y));
  825. poly[poly_cur].add(src.vtx.pos(ind.z));
  826. poly[poly_cur].add(src.vtx.pos(ind.w));
  827. if(matrix)REPAO(poly[poly_cur])*=*matrix;
  828. REP(clip_planes)
  829. {
  830. ClipPoly(poly[poly_cur], clip_plane[i], poly[poly_cur^1]);
  831. poly_cur^=1; if(!poly[poly_cur].elms())goto no_quad;
  832. }
  833. Swap(polys.New(), poly[poly_cur]); if(set_flags)poly_flags.add(src.quad.flag() ? src.quad.flag(i) : 0);
  834. no_quad:;
  835. poly[poly_cur^1].clear();
  836. }
  837. // polys to dest
  838. Triangulate(polys, temp, weld_pos_eps, true, poly_flags.data());
  839. }
  840. finished:
  841. Swap(dest, temp);
  842. }
  843. /******************************************************************************/
  844. void ClipMesh(C MeshBase &src, C Matrix *matrix, MeshBase &dest, C Plane *clip_plane, Int clip_planes, UInt flag_and, Flt weld_pos_eps)
  845. {
  846. flag_and&=src.flag();
  847. if(!(flag_and&VTX_ALL&~(VTX_POS|VTX_FLAG|VTX_DUP))) // if simple is enough
  848. {
  849. ClipMeshSimple(src, matrix, dest, clip_plane, clip_planes, weld_pos_eps);
  850. }else
  851. {
  852. MeshBase temp;
  853. // box test
  854. Vec corner[8]; OBox(Box(src), matrix ? *matrix : MatrixIdentity).toCorners(corner);
  855. Bool all_inside=true;
  856. REPD(p, clip_planes)
  857. {
  858. Bool inside=false,
  859. outside=false;
  860. REPAD(c, corner)
  861. {
  862. if(Dist(corner[c], clip_plane[p])<=0)inside=true;else outside=true;
  863. }
  864. if(!inside)goto finished; // if no vertexes are inside the plane then cancel
  865. if(outside)all_inside=false;
  866. }
  867. // create dest
  868. if(all_inside)
  869. {
  870. temp.create(src, flag_and);
  871. if(matrix)temp.transform(*matrix);
  872. }else
  873. {
  874. Matrix3 matrix3; if(matrix){matrix3=*matrix; matrix3.normalize();}
  875. Bool set_flags=FlagTest(flag_and, FACE_FLAG);
  876. Memc< Byte > poly_flags;
  877. Memc< Memc<VtxFull> > polys;
  878. Memc<VtxFull> poly[2];
  879. Bool poly_cur=0;
  880. // triangles
  881. REPA(src.tri)
  882. {
  883. VecI ind=src.tri.ind(i);
  884. poly[poly_cur].New().from(src, ind.x);
  885. poly[poly_cur].New().from(src, ind.y);
  886. poly[poly_cur].New().from(src, ind.z);
  887. if(matrix)REPAO(poly[poly_cur]).mul(*matrix, matrix3);
  888. REP(clip_planes)
  889. {
  890. ClipPoly(poly[poly_cur], clip_plane[i], poly[poly_cur^1]);
  891. poly_cur^=1; if(!poly[poly_cur].elms())goto no_tri;
  892. }
  893. Swap(polys.New(), poly[poly_cur]); if(set_flags)poly_flags.add(src.tri.flag() ? src.tri.flag(i) : 0);
  894. no_tri:;
  895. poly[poly_cur^1].clear();
  896. }
  897. // quads
  898. REPA(src.quad)
  899. {
  900. VecI4 ind=src.quad.ind(i);
  901. poly[poly_cur].New().from(src, ind.x);
  902. poly[poly_cur].New().from(src, ind.y);
  903. poly[poly_cur].New().from(src, ind.z);
  904. poly[poly_cur].New().from(src, ind.w);
  905. if(matrix)REPAO(poly[poly_cur]).mul(*matrix, matrix3);
  906. REP(clip_planes)
  907. {
  908. ClipPoly(poly[poly_cur], clip_plane[i], poly[poly_cur^1]);
  909. poly_cur^=1; if(!poly[poly_cur].elms())goto no_quad;
  910. }
  911. Swap(polys.New(), poly[poly_cur]); if(set_flags)poly_flags.add(src.quad.flag() ? src.quad.flag(i) : 0);
  912. no_quad:;
  913. poly[poly_cur^1].clear();
  914. }
  915. // polys to dest
  916. Triangulate(polys, temp, flag_and, weld_pos_eps, true, poly_flags.data());
  917. }
  918. finished:
  919. Swap(dest, temp);
  920. }
  921. }
  922. /******************************************************************************/
  923. void ClipMesh(C Mesh &src, C Matrix *matrix, Mesh &dest, C Plane *clip_plane, Int clip_planes, UInt flag_and, Flt weld_pos_eps)
  924. {
  925. Mesh temp;
  926. // box test
  927. Vec corner[8]; src.ext.toCorners(corner); if(matrix)Transform(corner, *matrix, Elms(corner));
  928. Bool all_inside=true;
  929. REPD(p, clip_planes)
  930. {
  931. Bool inside=false,
  932. outside=false;
  933. REPAD(c, corner)
  934. {
  935. if(Dist(corner[c], clip_plane[p])<=0)inside=true;else outside=true;
  936. }
  937. if(!inside)goto finished; // if no vertexes are inside the plane then cancel
  938. if(outside)all_inside=false;
  939. }
  940. // create dest
  941. if(all_inside)
  942. {
  943. temp.create(src, flag_and);
  944. if(matrix)
  945. {
  946. temp.transform(*matrix).setBox();
  947. temp.lod_center=src.lod_center*(*matrix); // set manual lod center after setting box
  948. }
  949. }else
  950. {
  951. Flt scale=(matrix ? matrix->maxScale() : 1);
  952. Matrix3 matrix3; if(matrix){matrix3=*matrix; matrix3.normalize();}
  953. Memc< Byte > poly_flags;
  954. Memc< Memc<VtxFull> > polys;
  955. Memc<VtxFull> poly[2];
  956. Bool poly_cur=0;
  957. temp.setLods(src.lods()); temp.copyParams(src);
  958. REPD(l, src.lods()) // order is important
  959. {
  960. C MeshLod & src_lod=src .lod(l);
  961. MeshLod &dest_lod=temp.lod(l);
  962. FREPA(src_lod)
  963. {
  964. C MeshPart &src_part = src_lod .parts[i]; MeshBase temp; if(!src_part.base.is() && src_part.render.is())temp.create(src_part.render);
  965. C MeshBase &src =(src_part.base.is() ? src_part.base : temp);
  966. Bool set_flags=FlagTest(src.flag()&flag_and, FACE_FLAG);
  967. // triangles
  968. REPA(src.tri)
  969. {
  970. VecI ind=src.tri.ind(i);
  971. poly[poly_cur].New().from(src, ind.x);
  972. poly[poly_cur].New().from(src, ind.y);
  973. poly[poly_cur].New().from(src, ind.z);
  974. if(matrix)REPAO(poly[poly_cur]).mul(*matrix, matrix3);
  975. REP(clip_planes)
  976. {
  977. ClipPoly(poly[poly_cur], clip_plane[i], poly[poly_cur^1]);
  978. poly_cur^=1; if(!poly[poly_cur].elms())goto no_tri;
  979. }
  980. Swap(polys.New(), poly[poly_cur]); if(set_flags)poly_flags.add(src.tri.flag() ? src.tri.flag(i) : 0);
  981. no_tri:;
  982. poly[poly_cur^1].clear();
  983. }
  984. // quads
  985. REPA(src.quad)
  986. {
  987. VecI4 ind=src.quad.ind(i);
  988. poly[poly_cur].New().from(src, ind.x);
  989. poly[poly_cur].New().from(src, ind.y);
  990. poly[poly_cur].New().from(src, ind.z);
  991. poly[poly_cur].New().from(src, ind.w);
  992. if(matrix)REPAO(poly[poly_cur]).mul(*matrix, matrix3);
  993. REP(clip_planes)
  994. {
  995. ClipPoly(poly[poly_cur], clip_plane[i], poly[poly_cur^1]);
  996. poly_cur^=1; if(!poly[poly_cur].elms())goto no_quad;
  997. }
  998. Swap(polys.New(), poly[poly_cur]); if(set_flags)poly_flags.add(src.quad.flag() ? src.quad.flag(i) : 0);
  999. no_quad:;
  1000. poly[poly_cur^1].clear();
  1001. }
  1002. // polys to dest
  1003. if(polys.elms())
  1004. {
  1005. MeshPart &dest_part=dest_lod.parts.New(); dest_part.copyParams(src_part); dest_part.scaleParams(scale);
  1006. Triangulate(polys, dest_part.base, src.flag()&flag_and, weld_pos_eps, true, poly_flags.data());
  1007. polys.clear(); poly_flags.clear();
  1008. }
  1009. }
  1010. if(!dest_lod.parts.elms())temp.removeLod(l);else
  1011. {
  1012. dest_lod. copyParams(src_lod);
  1013. dest_lod.scaleParams(scale);
  1014. }
  1015. }
  1016. temp.setBox();
  1017. temp.lod_center=src.lod_center; if(matrix)temp.lod_center*=*matrix; // set manual lod center after setting box
  1018. }
  1019. finished:
  1020. Swap(dest, temp);
  1021. }
  1022. /******************************************************************************/
  1023. void SplitMesh(C Mesh &src, C Matrix *matrix, Mesh &dest_positive, Mesh &dest_negative, C Plane &clip_plane, UInt flag_and, Flt weld_pos_eps)
  1024. {
  1025. Bool same=(&dest_positive==&dest_negative);
  1026. Mesh temp_positive, temp_negative2, &temp_negative=(same ? temp_positive : temp_negative2); // if we're splitting to the same mesh, then just store everything in 'temp_positive'
  1027. // box test
  1028. Vec corner[8]; src.ext.toCorners(corner); if(matrix)Transform(corner, *matrix, Elms(corner));
  1029. Bool inside=false,
  1030. outside=false;
  1031. REPAD(c, corner)
  1032. {
  1033. if(Dist(corner[c], clip_plane)<=0)inside=true;else outside=true;
  1034. }
  1035. if(!inside) // if no vertexes are inside the plane
  1036. {
  1037. temp_positive.create(src, flag_and);
  1038. if(matrix)
  1039. {
  1040. temp_positive.transform(*matrix).setBox();
  1041. temp_positive.lod_center=src.lod_center*(*matrix); // set manual lod center after setting box
  1042. }
  1043. }else
  1044. if(!outside) // if no vertexes are outside the plane
  1045. {
  1046. temp_negative.create(src, flag_and);
  1047. if(matrix)
  1048. {
  1049. temp_negative.transform(*matrix).setBox();
  1050. temp_negative.lod_center=src.lod_center*(*matrix); // set manual lod center after setting box
  1051. }
  1052. }
  1053. else // vertexes are from both sides so we need to cut
  1054. {
  1055. Flt scale=(matrix ? matrix->maxScale() : 1);
  1056. Matrix3 matrix3; if(matrix){matrix3=*matrix; matrix3.normalize();}
  1057. Memc< Memc<VtxFull> > polys_pos, polys_neg;
  1058. Memc<VtxFull> poly_src, poly_pos, poly_neg;
  1059. temp_positive.setLods(src.lods()); temp_positive.copyParams(src);
  1060. if(!same){temp_negative.setLods(src.lods()); temp_negative.copyParams(src);}
  1061. REPD(l, src.lods()) // order is important
  1062. {
  1063. C MeshLod & src_lod =src .lod(l);
  1064. MeshLod &dest_lod_p=temp_positive.lod(l),
  1065. &dest_lod_n=temp_negative.lod(l);
  1066. FREPA(src_lod)
  1067. {
  1068. C MeshPart &src_part= src_lod .parts[i]; MeshBase temp; if(!src_part.base.is() && src_part.render.is())temp.create(src_part.render);
  1069. C MeshBase &src =(src_part.base.is() ? src_part.base : temp);
  1070. // triangles
  1071. REPA(src.tri)
  1072. {
  1073. VecI ind=src.tri.ind(i);
  1074. poly_src.New().from(src, ind.x);
  1075. poly_src.New().from(src, ind.y);
  1076. poly_src.New().from(src, ind.z);
  1077. if(matrix)REPAO(poly_src).mul(*matrix, matrix3);
  1078. SplitPoly(poly_src, clip_plane, poly_pos, poly_neg);
  1079. if(poly_pos.elms())Swap(polys_pos.New(), poly_pos);
  1080. if(poly_neg.elms())Swap(polys_neg.New(), poly_neg);
  1081. poly_src.clear();
  1082. }
  1083. // quads
  1084. REPA(src.quad)
  1085. {
  1086. VecI4 ind=src.quad.ind(i);
  1087. poly_src.New().from(src, ind.x);
  1088. poly_src.New().from(src, ind.y);
  1089. poly_src.New().from(src, ind.z);
  1090. poly_src.New().from(src, ind.w);
  1091. if(matrix)REPAO(poly_src).mul(*matrix, matrix3);
  1092. SplitPoly(poly_src, clip_plane, poly_pos, poly_neg);
  1093. if(poly_pos.elms())Swap(polys_pos.New(), poly_pos);
  1094. if(poly_neg.elms())Swap(polys_neg.New(), poly_neg);
  1095. poly_src.clear();
  1096. }
  1097. // polys to dest
  1098. if(polys_pos.elms())
  1099. {
  1100. MeshPart &dest_part=dest_lod_p.parts.New(); dest_part.copyParams(src_part); dest_part.scaleParams(scale);
  1101. Triangulate(polys_pos, dest_part.base, src.flag()&flag_and, weld_pos_eps, true);
  1102. polys_pos.clear();
  1103. }
  1104. if(polys_neg.elms())
  1105. {
  1106. MeshPart &dest_part=dest_lod_n.parts.New(); dest_part.copyParams(src_part); dest_part.scaleParams(scale);
  1107. Triangulate(polys_neg, dest_part.base, src.flag()&flag_and, weld_pos_eps, true);
  1108. polys_neg.clear();
  1109. }
  1110. }
  1111. // copy lod settings (or remove them if no parts exist)
  1112. if(!dest_lod_p.parts.elms())temp_positive.removeLod(l);else
  1113. {
  1114. dest_lod_p. copyParams(src_lod);
  1115. dest_lod_p.scaleParams(scale);
  1116. }
  1117. if(!same && !dest_lod_n.parts.elms())temp_negative.removeLod(l);else
  1118. {
  1119. dest_lod_n. copyParams(src_lod);
  1120. dest_lod_n.scaleParams(scale);
  1121. }
  1122. }
  1123. temp_positive.setBox();
  1124. if(!same)temp_negative.setBox();
  1125. // set manual lod center after setting box
  1126. temp_positive.lod_center=
  1127. temp_negative.lod_center=src.lod_center;
  1128. if(matrix)
  1129. {
  1130. temp_positive.lod_center*=*matrix;
  1131. temp_negative.lod_center*=*matrix;
  1132. }
  1133. }
  1134. Swap(dest_positive, temp_positive);
  1135. if(!same)Swap(dest_negative, temp_negative);
  1136. }
  1137. /******************************************************************************/
  1138. struct MiddlePoint
  1139. {
  1140. Flt prev_dist, next_dist;
  1141. Vec pos;
  1142. void set(Flt prev_dist, Flt next_dist, C Vec &pos) {T.prev_dist=prev_dist; T.next_dist=next_dist; T.pos=pos;}
  1143. };
  1144. static void SplitPoly(C Memc<VtxFull> &poly, C Plane &plane, Memc<VtxFull> &output_positive, Memc<VtxFull> &output_negative, Memc<Edge> &edges)
  1145. {
  1146. output_positive.clear();
  1147. output_negative.clear();
  1148. switch(poly.elms())
  1149. {
  1150. case 0: break;
  1151. case 1:
  1152. if(Dist(poly[0].pos, plane)<0)output_negative.add(poly[0]);
  1153. else output_positive.add(poly[0]);
  1154. break;
  1155. default: // >=2
  1156. {
  1157. Memc<MiddlePoint> middles;
  1158. C VtxFull *prev =&poly.last();
  1159. Flt prev_dist=Dist(prev->pos, plane);
  1160. FREPA(poly) // preserve order
  1161. {
  1162. Bool have_mid =false;
  1163. C VtxFull &next =poly[i]; VtxFull mid;
  1164. Flt next_dist=Dist(next.pos, plane);
  1165. // negative
  1166. if(prev_dist<0)
  1167. {
  1168. output_negative.add(*prev);
  1169. if(next_dist>=0) // change of side
  1170. {
  1171. if(!have_mid){have_mid=true; mid.lerp(*prev, next, prev_dist/(prev_dist-next_dist));} // -prev_dist/(next_dist-prev_dist)
  1172. output_negative.add(mid);
  1173. }
  1174. }
  1175. else // prev_dist>=0
  1176. {
  1177. if(next_dist<0) // change of side
  1178. {
  1179. if(!have_mid){have_mid=true; mid.lerp(*prev, next, prev_dist/(prev_dist-next_dist));}
  1180. output_negative.add(mid);
  1181. }
  1182. }
  1183. // positive
  1184. if(prev_dist>0)
  1185. {
  1186. output_positive.add(*prev);
  1187. if(next_dist<=0) // change of side
  1188. {
  1189. if(!have_mid){have_mid=true; mid.lerp(*prev, next, prev_dist/(prev_dist-next_dist));} // -prev_dist/(next_dist-prev_dist)
  1190. output_positive.add(mid);
  1191. }
  1192. }
  1193. else // prev_dist<=0
  1194. {
  1195. if(next_dist>0) // change of side
  1196. {
  1197. if(!have_mid){have_mid=true; mid.lerp(*prev, next, prev_dist/(prev_dist-next_dist));}
  1198. output_positive.add(mid);
  1199. }
  1200. }
  1201. if(have_mid)middles.New().set(prev_dist, next_dist, mid.pos);
  1202. prev =&next;
  1203. prev_dist= next_dist;
  1204. }
  1205. // rotate the middle vertexes until they're sorted
  1206. Vec nrm =0; REPA(poly)nrm+=GetNormalEdge(poly[i].pos, poly[(i+1)%poly.elms()].pos); // get average face normal
  1207. Vec cross=Cross(plane.normal, nrm);
  1208. for(; middles.elms()>=2; )// && Dot(middles.last().pos, cross)>Dot(middles.first().pos, cross); )
  1209. {
  1210. Flt a=Dot(middles.first().pos, cross),
  1211. b=Dot(middles.last ().pos, cross); if(a>=b)break; // must be stored in Flt variables insted of comparing values directly due to imprecisions of FPU
  1212. middles.rotateOrder(1);
  1213. }
  1214. // create clip edges
  1215. FREPA(middles)if(InRange(i+1, middles))
  1216. {
  1217. MiddlePoint &m =middles[i ],
  1218. &m1=middles[i+1];
  1219. if(m .prev_dist<=0 && m .next_dist>=0
  1220. && m1.prev_dist>=0 && m1.next_dist<=0)edges.New().set(m.pos, m1.pos);
  1221. }
  1222. }break;
  1223. }
  1224. }
  1225. /******************************************************************************/
  1226. void SplitMeshSolid(C Mesh &src, C Matrix *matrix, Mesh &dest_positive, Mesh &dest_negative, C Plane &clip_plane, C MaterialPtr &material, Flt tex_scale, UInt flag_and, Flt weld_pos_eps)
  1227. {
  1228. Mesh temp_positive, temp_negative;
  1229. // box test
  1230. Vec corner[8]; src.ext.toCorners(corner); if(matrix)Transform(corner, *matrix, Elms(corner));
  1231. Bool inside=false,
  1232. outside=false;
  1233. REPAD(c, corner)
  1234. {
  1235. if(Dist(corner[c], clip_plane)<=0)inside=true;else outside=true;
  1236. }
  1237. if(!inside) // if no vertexes are inside the plane
  1238. {
  1239. temp_positive.create(src, flag_and);
  1240. if(matrix)
  1241. {
  1242. temp_positive.transform(*matrix).setBox();
  1243. temp_positive.lod_center=src.lod_center*(*matrix); // set manual lod center after setting box
  1244. }
  1245. }else
  1246. if(!outside) // if no vertexes are outside the plane
  1247. {
  1248. temp_negative.create(src, flag_and);
  1249. if(matrix)
  1250. {
  1251. temp_negative.transform(*matrix).setBox();
  1252. temp_negative.lod_center=src.lod_center*(*matrix); // set manual lod center after setting box
  1253. }
  1254. }else // vertexes are from both sides so we need to cut
  1255. {
  1256. Flt scale=(matrix ? matrix->maxScale() : 1);
  1257. Matrix3 matrix3; if(matrix){matrix3=*matrix; matrix3.normalize();}
  1258. Memc< Memc<VtxFull> > polys_pos, polys_neg;
  1259. Memc<VtxFull> poly_src, poly_pos, poly_neg;
  1260. temp_positive.setLods(src.lods()); temp_positive.copyParams(src);
  1261. temp_negative.setLods(src.lods()); temp_negative.copyParams(src);
  1262. REPD(l, src.lods()) // order is important
  1263. {
  1264. Memc<Edge> edges;
  1265. C MeshLod & src_lod =src .lod(l);
  1266. MeshLod &dest_lod_p=temp_positive.lod(l),
  1267. &dest_lod_n=temp_negative.lod(l);
  1268. FREPA(src_lod)
  1269. {
  1270. C MeshPart &src_part= src_lod .parts[i]; MeshBase temp; if(!src_part.base.is() && src_part.render.is())temp.create(src_part.render);
  1271. C MeshBase &src =(src_part.base.is() ? src_part.base : temp);
  1272. // triangles
  1273. REPA(src.tri)
  1274. {
  1275. VecI ind=src.tri.ind(i);
  1276. poly_src.New().from(src, ind.x);
  1277. poly_src.New().from(src, ind.y);
  1278. poly_src.New().from(src, ind.z);
  1279. if(matrix)REPAO(poly_src).mul(*matrix, matrix3);
  1280. SplitPoly(poly_src, clip_plane, poly_pos, poly_neg, edges);
  1281. if(poly_pos.elms())Swap(polys_pos.New(), poly_pos);
  1282. if(poly_neg.elms())Swap(polys_neg.New(), poly_neg);
  1283. poly_src.clear();
  1284. }
  1285. // quads
  1286. REPA(src.quad)
  1287. {
  1288. VecI4 ind=src.quad.ind(i);
  1289. poly_src.New().from(src, ind.x);
  1290. poly_src.New().from(src, ind.y);
  1291. poly_src.New().from(src, ind.z);
  1292. poly_src.New().from(src, ind.w);
  1293. if(matrix)REPAO(poly_src).mul(*matrix, matrix3);
  1294. SplitPoly(poly_src, clip_plane, poly_pos, poly_neg, edges);
  1295. if(poly_pos.elms())Swap(polys_pos.New(), poly_pos);
  1296. if(poly_neg.elms())Swap(polys_neg.New(), poly_neg);
  1297. poly_src.clear();
  1298. }
  1299. // polys to dest
  1300. if(polys_pos.elms())
  1301. {
  1302. MeshPart &dest_part=dest_lod_p.parts.New(); dest_part.copyParams(src_part); dest_part.scaleParams(scale);
  1303. Triangulate(polys_pos, dest_part.base, src.flag()&flag_and, weld_pos_eps, true);
  1304. polys_pos.clear();
  1305. }
  1306. if(polys_neg.elms())
  1307. {
  1308. MeshPart &dest_part=dest_lod_n.parts.New(); dest_part.copyParams(src_part); dest_part.scaleParams(scale);
  1309. Triangulate(polys_neg, dest_part.base, src.flag()&flag_and, weld_pos_eps, true);
  1310. polys_neg.clear();
  1311. }
  1312. }
  1313. // create insides
  1314. if(edges.elms())
  1315. {
  1316. MeshBase temp(edges.elms()*2, edges.elms(), 0, 0, EDGE_FLAG);
  1317. REPA(edges)
  1318. {
  1319. temp.vtx .pos (i*2+0)=edges[i].p[0];
  1320. temp.vtx .pos (i*2+1)=edges[i].p[1];
  1321. temp.edge.ind (i ).set(i*2+0, i*2+1);
  1322. temp.edge.flag(i )=ETQ_R;
  1323. }
  1324. temp.weldVtx().removeDoubleEdges();
  1325. MeshBase temp2D(temp); temp2D.transform(~Matrix3().setDir(clip_plane.normal)).edgeToTri(); Swap(temp2D.tri, temp.tri);
  1326. if(temp.faces())
  1327. {
  1328. temp.texMap(clip_plane).texScale(Vec2(tex_scale)).include(VTX_NRM); REPA(temp.vtx)temp.vtx.nrm(i)=-clip_plane.normal;
  1329. MeshPart &solid_p=dest_lod_p.parts.New(); solid_p.base=temp ; solid_p.material(material, l);
  1330. MeshPart &solid_n=dest_lod_n.parts.New(); solid_n.base=temp.reverse(); solid_n.material(material, l);
  1331. }
  1332. }
  1333. // copy lod settings (or remove them if no parts exist)
  1334. if(!dest_lod_p.parts.elms())temp_positive.removeLod(l);else
  1335. {
  1336. dest_lod_p. copyParams(src_lod);
  1337. dest_lod_p.scaleParams(scale);
  1338. }
  1339. if(!dest_lod_n.parts.elms())temp_negative.removeLod(l);else
  1340. {
  1341. dest_lod_n. copyParams(src_lod);
  1342. dest_lod_n.scaleParams(scale);
  1343. }
  1344. //dest_lod_p.weldVtxValues(VTX_POS, EPS);
  1345. //dest_lod_n.weldVtxValues(VTX_POS, EPS);
  1346. }
  1347. temp_positive.setBox();
  1348. temp_negative.setBox();
  1349. // set manual lod center after setting box
  1350. temp_positive.lod_center=
  1351. temp_negative.lod_center=src.lod_center;
  1352. if(matrix)
  1353. {
  1354. temp_positive.lod_center*=*matrix;
  1355. temp_negative.lod_center*=*matrix;
  1356. }
  1357. }
  1358. Swap(dest_positive, temp_positive);
  1359. Swap(dest_negative, temp_negative);
  1360. }
  1361. /******************************************************************************/
  1362. }
  1363. /******************************************************************************/