IFCGeometry.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371
  1. /*
  2. Open Asset Import Library (ASSIMP)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2010, ASSIMP Development Team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the ASSIMP team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the ASSIMP Development Team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /** @file IFCGeometry.cpp
  34. * @brief Geometry conversion and synthesis for IFC
  35. */
  36. #include "AssimpPCH.h"
  37. #ifndef ASSIMP_BUILD_NO_IFC_IMPORTER
  38. #include "IFCUtil.h"
  39. #include "PolyTools.h"
  40. #include "ProcessHelper.h"
  41. #include <iterator>
  42. namespace Assimp {
  43. namespace IFC {
  44. // ------------------------------------------------------------------------------------------------
  45. bool ProcessPolyloop(const IfcPolyLoop& loop, TempMesh& meshout, ConversionData& /*conv*/)
  46. {
  47. size_t cnt = 0;
  48. BOOST_FOREACH(const IfcCartesianPoint& c, loop.Polygon) {
  49. aiVector3D tmp;
  50. ConvertCartesianPoint(tmp,c);
  51. meshout.verts.push_back(tmp);
  52. ++cnt;
  53. }
  54. meshout.vertcnt.push_back(cnt);
  55. // zero- or one- vertex polyloops simply ignored
  56. if (meshout.vertcnt.back() > 1) {
  57. return true;
  58. }
  59. if (meshout.vertcnt.back()==1) {
  60. meshout.vertcnt.pop_back();
  61. meshout.verts.pop_back();
  62. }
  63. return false;
  64. }
  65. // ------------------------------------------------------------------------------------------------
  66. void ComputePolygonNormals(const TempMesh& meshout, std::vector<aiVector3D>& normals, bool normalize = true, size_t ofs = 0)
  67. {
  68. size_t max_vcount = 0;
  69. std::vector<unsigned int>::const_iterator begin=meshout.vertcnt.begin()+ofs, end=meshout.vertcnt.end(), iit;
  70. for(iit = begin; iit != end; ++iit) {
  71. max_vcount = std::max(max_vcount,static_cast<size_t>(*iit));
  72. }
  73. std::vector<float> temp((max_vcount+2)*4);
  74. normals.reserve( normals.size() + meshout.vertcnt.size()-ofs );
  75. // `NewellNormal()` currently has a relatively strange interface and need to
  76. // re-structure things a bit to meet them.
  77. size_t vidx = std::accumulate(meshout.vertcnt.begin(),begin,0);
  78. for(iit = begin; iit != end; vidx += *iit++) {
  79. if (!*iit) {
  80. normals.push_back(aiVector3D());
  81. continue;
  82. }
  83. for(size_t vofs = 0, cnt = 0; vofs < *iit; ++vofs) {
  84. const aiVector3D& v = meshout.verts[vidx+vofs];
  85. temp[cnt++] = v.x;
  86. temp[cnt++] = v.y;
  87. temp[cnt++] = v.z;
  88. #ifdef _DEBUG
  89. temp[cnt] = std::numeric_limits<float>::quiet_NaN();
  90. #endif
  91. ++cnt;
  92. }
  93. normals.push_back(aiVector3D());
  94. NewellNormal<4,4,4>(normals.back(),*iit,&temp[0],&temp[1],&temp[2]);
  95. }
  96. if(normalize) {
  97. BOOST_FOREACH(aiVector3D& n, normals) {
  98. n.Normalize();
  99. }
  100. }
  101. }
  102. // ------------------------------------------------------------------------------------------------
  103. // Compute the normal of the last polygon in the given mesh
  104. aiVector3D ComputePolygonNormal(const TempMesh& inmesh, bool normalize = true)
  105. {
  106. size_t total = inmesh.vertcnt.back(), vidx = inmesh.verts.size() - total;
  107. std::vector<float> temp((total+2)*3);
  108. for(size_t vofs = 0, cnt = 0; vofs < total; ++vofs) {
  109. const aiVector3D& v = inmesh.verts[vidx+vofs];
  110. temp[cnt++] = v.x;
  111. temp[cnt++] = v.y;
  112. temp[cnt++] = v.z;
  113. }
  114. aiVector3D nor;
  115. NewellNormal<3,3,3>(nor,total,&temp[0],&temp[1],&temp[2]);
  116. return normalize ? nor.Normalize() : nor;
  117. }
  118. // ------------------------------------------------------------------------------------------------
  119. void FixupFaceOrientation(TempMesh& result)
  120. {
  121. const aiVector3D vavg = result.Center();
  122. std::vector<aiVector3D> normals;
  123. ComputePolygonNormals(result,normals);
  124. size_t c = 0, ofs = 0;
  125. BOOST_FOREACH(unsigned int cnt, result.vertcnt) {
  126. if (cnt>2){
  127. const aiVector3D& thisvert = result.verts[c];
  128. if (normals[ofs]*(thisvert-vavg) < 0) {
  129. std::reverse(result.verts.begin()+c,result.verts.begin()+cnt+c);
  130. }
  131. }
  132. c += cnt;
  133. ++ofs;
  134. }
  135. }
  136. // ------------------------------------------------------------------------------------------------
  137. void RecursiveMergeBoundaries(TempMesh& final_result, const TempMesh& in, const TempMesh& boundary, std::vector<aiVector3D>& normals, const aiVector3D& nor_boundary)
  138. {
  139. ai_assert(in.vertcnt.size() >= 1);
  140. ai_assert(boundary.vertcnt.size() == 1);
  141. std::vector<unsigned int>::const_iterator end = in.vertcnt.end(), begin=in.vertcnt.begin(), iit, best_iit;
  142. TempMesh out;
  143. // iterate through all other bounds and find the one for which the shortest connection
  144. // to the outer boundary is actually the shortest possible.
  145. size_t vidx = 0, best_vidx_start = 0;
  146. size_t best_ofs, best_outer = boundary.verts.size();
  147. float best_dist = 1e10;
  148. for(std::vector<unsigned int>::const_iterator iit = begin; iit != end; vidx += *iit++) {
  149. for(size_t vofs = 0; vofs < *iit; ++vofs) {
  150. const aiVector3D& v = in.verts[vidx+vofs];
  151. for(size_t outer = 0; outer < boundary.verts.size(); ++outer) {
  152. const aiVector3D& o = boundary.verts[outer];
  153. const float d = (o-v).SquareLength();
  154. if (d < best_dist) {
  155. best_dist = d;
  156. best_ofs = vofs;
  157. best_outer = outer;
  158. best_iit = iit;
  159. best_vidx_start = vidx;
  160. }
  161. }
  162. }
  163. }
  164. ai_assert(best_outer != boundary.verts.size());
  165. // now that we collected all vertex connections to be added, build the output polygon
  166. const size_t cnt = boundary.verts.size() + *best_iit+2;
  167. out.verts.reserve(cnt);
  168. for(size_t outer = 0; outer < boundary.verts.size(); ++outer) {
  169. const aiVector3D& o = boundary.verts[outer];
  170. out.verts.push_back(o);
  171. if (outer == best_outer) {
  172. for(size_t i = best_ofs; i < *best_iit; ++i) {
  173. out.verts.push_back(in.verts[best_vidx_start + i]);
  174. }
  175. // we need the first vertex of the inner polygon twice as we return to the
  176. // outer loop through the very same connection through which we got there.
  177. for(size_t i = 0; i <= best_ofs; ++i) {
  178. out.verts.push_back(in.verts[best_vidx_start + i]);
  179. }
  180. // reverse face winding if the normal of the sub-polygon points in the
  181. // same direction as the normal of the outer polygonal boundary
  182. if (normals[std::distance(begin,best_iit)] * nor_boundary > 0) {
  183. std::reverse(out.verts.rbegin(),out.verts.rbegin()+*best_iit+1);
  184. }
  185. // also append a copy of the initial insertion point to be able to continue the outer polygon
  186. out.verts.push_back(o);
  187. }
  188. }
  189. out.vertcnt.push_back(cnt);
  190. ai_assert(out.verts.size() == cnt);
  191. if (in.vertcnt.size()-std::count(begin,end,0) > 1) {
  192. // Recursively apply the same algorithm if there are more boundaries to merge. The
  193. // current implementation is relatively inefficient, though.
  194. TempMesh temp;
  195. // drop the boundary that we just processed
  196. const size_t dist = std::distance(begin, best_iit);
  197. TempMesh remaining = in;
  198. remaining.vertcnt.erase(remaining.vertcnt.begin() + dist);
  199. remaining.verts.erase(remaining.verts.begin()+best_vidx_start,remaining.verts.begin()+best_vidx_start+*best_iit);
  200. normals.erase(normals.begin() + dist);
  201. RecursiveMergeBoundaries(temp,remaining,out,normals,nor_boundary);
  202. final_result.Append(temp);
  203. }
  204. else final_result.Append(out);
  205. }
  206. // ------------------------------------------------------------------------------------------------
  207. void MergePolygonBoundaries(TempMesh& result, const TempMesh& inmesh, size_t master_bounds = -1)
  208. {
  209. // standard case - only one boundary, just copy it to the result vector
  210. if (inmesh.vertcnt.size() <= 1) {
  211. result.Append(inmesh);
  212. return;
  213. }
  214. result.vertcnt.reserve(inmesh.vertcnt.size()+result.vertcnt.size());
  215. // XXX get rid of the extra copy if possible
  216. TempMesh meshout = inmesh;
  217. // handle polygons with holes. Our built in triangulation won't handle them as is, but
  218. // the ear cutting algorithm is solid enough to deal with them if we join the inner
  219. // holes with the outer boundaries by dummy connections.
  220. IFCImporter::LogDebug("fixing polygon with holes for triangulation via ear-cutting");
  221. std::vector<unsigned int>::iterator outer_polygon = meshout.vertcnt.end(), begin=meshout.vertcnt.begin(), end=outer_polygon, iit;
  222. // each hole results in two extra vertices
  223. result.verts.reserve(meshout.verts.size()+meshout.vertcnt.size()*2+result.verts.size());
  224. size_t outer_polygon_start = 0;
  225. // do not normalize 'normals', we need the original length for computing the polygon area
  226. std::vector<aiVector3D> normals;
  227. ComputePolygonNormals(meshout,normals,false);
  228. // see if one of the polygons is a IfcFaceOuterBound (in which case `master_bounds` is its index).
  229. // sadly we can't rely on it, the docs say 'At most one of the bounds shall be of the type IfcFaceOuterBound'
  230. float area_outer_polygon = 1e-10f;
  231. if (master_bounds != (size_t)-1) {
  232. outer_polygon = begin + master_bounds;
  233. outer_polygon_start = std::accumulate(begin,outer_polygon,0);
  234. area_outer_polygon = normals[master_bounds].SquareLength();
  235. }
  236. else {
  237. size_t vidx = 0;
  238. for(iit = begin; iit != meshout.vertcnt.end(); vidx += *iit++) {
  239. // find the polygon with the largest area, it must be the outer bound.
  240. aiVector3D& n = normals[std::distance(begin,iit)];
  241. const float area = n.SquareLength();
  242. if (area > area_outer_polygon) {
  243. area_outer_polygon = area;
  244. outer_polygon = iit;
  245. outer_polygon_start = vidx;
  246. }
  247. }
  248. }
  249. ai_assert(outer_polygon != meshout.vertcnt.end());
  250. std::vector<aiVector3D>& in = meshout.verts;
  251. // skip over extremely small boundaries - this is a workaround to fix cases
  252. // in which the number of holes is so extremely large that the
  253. // triangulation code fails.
  254. #define IFC_VERTICAL_HOLE_SIZE_TRESHOLD 0.000001f
  255. size_t vidx = 0, removed = 0, index = 0;
  256. const float treshold = area_outer_polygon * IFC_VERTICAL_HOLE_SIZE_TRESHOLD;
  257. for(iit = begin; iit != end ;++index) {
  258. const float sqlen = normals[index].SquareLength();
  259. if (sqlen < treshold) {
  260. std::vector<aiVector3D>::iterator inbase = in.begin()+vidx;
  261. in.erase(inbase,inbase+*iit);
  262. outer_polygon_start -= outer_polygon_start>vidx ? *iit : 0;
  263. *iit++ = 0;
  264. ++removed;
  265. IFCImporter::LogDebug("skip small hole below treshold");
  266. }
  267. else {
  268. normals[index] /= sqrt(sqlen);
  269. vidx += *iit++;
  270. }
  271. }
  272. // see if one or more of the hole has a face that lies directly on an outer bound.
  273. // this happens for doors, for example.
  274. vidx = 0;
  275. for(iit = begin; ; vidx += *iit++) {
  276. next_loop:
  277. if (iit == end) {
  278. break;
  279. }
  280. if (iit == outer_polygon) {
  281. continue;
  282. }
  283. for(size_t vofs = 0; vofs < *iit; ++vofs) {
  284. if (!*iit) {
  285. continue;
  286. }
  287. const size_t next = (vofs+1)%*iit;
  288. const aiVector3D& v = in[vidx+vofs], &vnext = in[vidx+next],&vd = (vnext-v).Normalize();
  289. for(size_t outer = 0; outer < *outer_polygon; ++outer) {
  290. const aiVector3D& o = in[outer_polygon_start+outer], &onext = in[outer_polygon_start+(outer+1)%*outer_polygon], &od = (onext-o).Normalize();
  291. if (fabs(vd * od) > 1.f-1e-6f && (onext-v).Normalize() * vd > 1.f-1e-6f && (onext-v)*(o-v) < 0) {
  292. IFCImporter::LogDebug("got an inner hole that lies partly on the outer polygonal boundary, merging them to a single contour");
  293. // in between outer and outer+1 insert all vertices of this loop, then drop the original altogether.
  294. std::vector<aiVector3D> tmp(*iit);
  295. const size_t start = (v-o).SquareLength() > (vnext-o).SquareLength() ? vofs : next;
  296. std::vector<aiVector3D>::iterator inbase = in.begin()+vidx, it = std::copy(inbase+start, inbase+*iit,tmp.begin());
  297. std::copy(inbase, inbase+start,it);
  298. std::reverse(tmp.begin(),tmp.end());
  299. in.insert(in.begin()+outer_polygon_start+(outer+1)%*outer_polygon,tmp.begin(),tmp.end());
  300. vidx += outer_polygon_start<vidx ? *iit : 0;
  301. inbase = in.begin()+vidx;
  302. in.erase(inbase,inbase+*iit);
  303. outer_polygon_start -= outer_polygon_start>vidx ? *iit : 0;
  304. *outer_polygon += tmp.size();
  305. *iit++ = 0;
  306. ++removed;
  307. goto next_loop;
  308. }
  309. }
  310. }
  311. }
  312. if ( meshout.vertcnt.size() - removed <= 1) {
  313. result.Append(meshout);
  314. return;
  315. }
  316. // extract the outer boundary and move it to a separate mesh
  317. TempMesh boundary;
  318. boundary.vertcnt.resize(1,*outer_polygon);
  319. boundary.verts.resize(*outer_polygon);
  320. std::vector<aiVector3D>::iterator b = in.begin()+outer_polygon_start;
  321. std::copy(b,b+*outer_polygon,boundary.verts.begin());
  322. in.erase(b,b+*outer_polygon);
  323. std::vector<aiVector3D>::iterator norit = normals.begin()+std::distance(meshout.vertcnt.begin(),outer_polygon);
  324. const aiVector3D nor_boundary = *norit;
  325. normals.erase(norit);
  326. meshout.vertcnt.erase(outer_polygon);
  327. // keep merging the closest inner boundary with the outer boundary until no more boundaries are left
  328. RecursiveMergeBoundaries(result,meshout,boundary,normals,nor_boundary);
  329. }
  330. // ------------------------------------------------------------------------------------------------
  331. void ProcessConnectedFaceSet(const IfcConnectedFaceSet& fset, TempMesh& result, ConversionData& conv)
  332. {
  333. BOOST_FOREACH(const IfcFace& face, fset.CfsFaces) {
  334. // size_t ob = -1, cnt = 0;
  335. TempMesh meshout;
  336. BOOST_FOREACH(const IfcFaceBound& bound, face.Bounds) {
  337. // XXX implement proper merging for polygonal loops
  338. if(const IfcPolyLoop* const polyloop = bound.Bound->ToPtr<IfcPolyLoop>()) {
  339. if(ProcessPolyloop(*polyloop, meshout,conv)) {
  340. //if(bound.ToPtr<IfcFaceOuterBound>()) {
  341. // ob = cnt;
  342. //}
  343. //++cnt;
  344. }
  345. }
  346. else {
  347. IFCImporter::LogWarn("skipping unknown IfcFaceBound entity, type is " + bound.Bound->GetClassName());
  348. continue;
  349. }
  350. /*if(!IsTrue(bound.Orientation)) {
  351. size_t c = 0;
  352. BOOST_FOREACH(unsigned int& c, meshout.vertcnt) {
  353. std::reverse(result.verts.begin() + cnt,result.verts.begin() + cnt + c);
  354. cnt += c;
  355. }
  356. }*/
  357. }
  358. MergePolygonBoundaries(result,meshout);
  359. }
  360. }
  361. // ------------------------------------------------------------------------------------------------
  362. void ProcessRevolvedAreaSolid(const IfcRevolvedAreaSolid& solid, TempMesh& result, ConversionData& conv)
  363. {
  364. TempMesh meshout;
  365. // first read the profile description
  366. if(!ProcessProfile(*solid.SweptArea,meshout,conv) || meshout.verts.size()<=1) {
  367. return;
  368. }
  369. aiVector3D axis, pos;
  370. ConvertAxisPlacement(axis,pos,solid.Axis);
  371. aiMatrix4x4 tb0,tb1;
  372. aiMatrix4x4::Translation(pos,tb0);
  373. aiMatrix4x4::Translation(-pos,tb1);
  374. const std::vector<aiVector3D>& in = meshout.verts;
  375. const size_t size=in.size();
  376. bool has_area = solid.SweptArea->ProfileType == "AREA" && size>2;
  377. const float max_angle = solid.Angle*conv.angle_scale;
  378. if(fabs(max_angle) < 1e-3) {
  379. if(has_area) {
  380. result = meshout;
  381. }
  382. return;
  383. }
  384. const unsigned int cnt_segments = std::max(2u,static_cast<unsigned int>(16 * fabs(max_angle)/AI_MATH_HALF_PI_F));
  385. const float delta = max_angle/cnt_segments;
  386. has_area = has_area && fabs(max_angle) < AI_MATH_TWO_PI_F*0.99;
  387. result.verts.reserve(size*((cnt_segments+1)*4+(has_area?2:0)));
  388. result.vertcnt.reserve(size*cnt_segments+2);
  389. aiMatrix4x4 rot;
  390. rot = tb0 * aiMatrix4x4::Rotation(delta,axis,rot) * tb1;
  391. size_t base = 0;
  392. std::vector<aiVector3D>& out = result.verts;
  393. // dummy data to simplify later processing
  394. for(size_t i = 0; i < size; ++i) {
  395. out.insert(out.end(),4,in[i]);
  396. }
  397. for(unsigned int seg = 0; seg < cnt_segments; ++seg) {
  398. for(size_t i = 0; i < size; ++i) {
  399. const size_t next = (i+1)%size;
  400. result.vertcnt.push_back(4);
  401. const aiVector3D& base_0 = out[base+i*4+3],base_1 = out[base+next*4+3];
  402. out.push_back(base_0);
  403. out.push_back(base_1);
  404. out.push_back(rot*base_1);
  405. out.push_back(rot*base_0);
  406. }
  407. base += size*4;
  408. }
  409. out.erase(out.begin(),out.begin()+size*4);
  410. if(has_area) {
  411. // leave the triangulation of the profile area to the ear cutting
  412. // implementation in aiProcess_Triangulate - for now we just
  413. // feed in two huge polygons.
  414. base -= size*8;
  415. for(size_t i = size; i--; ) {
  416. out.push_back(out[base+i*4+3]);
  417. }
  418. for(size_t i = 0; i < size; ++i ) {
  419. out.push_back(out[i*4]);
  420. }
  421. result.vertcnt.push_back(size);
  422. result.vertcnt.push_back(size);
  423. }
  424. aiMatrix4x4 trafo;
  425. ConvertAxisPlacement(trafo, solid.Position);
  426. result.Transform(trafo);
  427. IFCImporter::LogDebug("generate mesh procedurally by radial extrusion (IfcRevolvedAreaSolid)");
  428. }
  429. // ------------------------------------------------------------------------------------------------
  430. bool TryAddOpenings(const std::vector<TempOpening>& openings,const std::vector<aiVector3D>& nors, TempMesh& curmesh)
  431. {
  432. std::vector<aiVector3D>& out = curmesh.verts;
  433. const size_t s = out.size();
  434. const aiVector3D any_point = out[s-1];
  435. const aiVector3D nor = ComputePolygonNormal(curmesh); ;
  436. bool got_openings = false;
  437. TempMesh res;
  438. size_t c = 0;
  439. BOOST_FOREACH(const TempOpening& t,openings) {
  440. const aiVector3D& outernor = nors[c++];
  441. const float dot = nor * outernor;
  442. if (fabs(dot)<1.f-1e-6f) {
  443. continue;
  444. }
  445. // const aiVector3D diff = t.extrusionDir;
  446. const std::vector<aiVector3D>& va = t.profileMesh->verts;
  447. if(va.size() <= 2) {
  448. continue;
  449. }
  450. // const float dd = t.extrusionDir*nor;
  451. IFCImporter::LogDebug("apply an IfcOpeningElement linked via IfcRelVoidsElement to this polygon");
  452. got_openings = true;
  453. // project va[i] onto the plane formed by the current polygon [given by (any_point,nor)]
  454. for(size_t i = 0; i < va.size(); ++i) {
  455. const aiVector3D& v = va[i];
  456. out.push_back(v-(nor*(v-any_point))*nor);
  457. }
  458. curmesh.vertcnt.push_back(va.size());
  459. res.Clear();
  460. MergePolygonBoundaries(res,curmesh,0);
  461. curmesh = res;
  462. }
  463. return got_openings;
  464. }
  465. // ------------------------------------------------------------------------------------------------
  466. struct DistanceSorter {
  467. DistanceSorter(const aiVector3D& base) : base(base) {}
  468. bool operator () (const TempOpening& a, const TempOpening& b) const {
  469. return (a.profileMesh->Center()-base).SquareLength() < (b.profileMesh->Center()-base).SquareLength();
  470. }
  471. aiVector3D base;
  472. };
  473. // ------------------------------------------------------------------------------------------------
  474. struct XYSorter {
  475. // sort first by X coordinates, then by Y coordinates
  476. bool operator () (const aiVector2D&a, const aiVector2D& b) const {
  477. if (a.x == b.x) {
  478. return a.y < b.y;
  479. }
  480. return a.x < b.x;
  481. }
  482. };
  483. // ------------------------------------------------------------------------------------------------
  484. struct ProjectionInfo {
  485. unsigned int ac, bc;
  486. aiVector3D p,u,v;
  487. };
  488. typedef std::pair< aiVector2D, aiVector2D > BoundingBox;
  489. typedef std::map<aiVector2D,size_t,XYSorter> XYSortedField;
  490. // ------------------------------------------------------------------------------------------------
  491. aiVector2D ProjectPositionVectorOntoPlane(const aiVector3D& x, const ProjectionInfo& proj)
  492. {
  493. const aiVector3D xx = x-proj.p;
  494. return aiVector2D(xx[proj.ac]/proj.u[proj.ac],xx[proj.bc]/proj.v[proj.bc]);
  495. }
  496. // ------------------------------------------------------------------------------------------------
  497. void QuadrifyPart(const aiVector2D& pmin, const aiVector2D& pmax, XYSortedField& field, const std::vector< BoundingBox >& bbs,
  498. std::vector<aiVector2D>& out)
  499. {
  500. if (!(pmin.x-pmax.x) || !(pmin.y-pmax.y)) {
  501. return;
  502. }
  503. float xs = 1e10, xe = 1e10;
  504. bool found = false;
  505. // Search along the x-axis until we find an opening
  506. XYSortedField::iterator start = field.begin();
  507. for(; start != field.end(); ++start) {
  508. const BoundingBox& bb = bbs[(*start).second];
  509. if(bb.first.x >= pmax.x) {
  510. break;
  511. }
  512. if (bb.second.x > pmin.x && bb.second.y > pmin.y && bb.first.y < pmax.y) {
  513. xs = bb.first.x;
  514. xe = bb.second.x;
  515. found = true;
  516. break;
  517. }
  518. }
  519. if (!found) {
  520. // the rectangle [pmin,pend] is opaque, fill it
  521. out.push_back(pmin);
  522. out.push_back(aiVector2D(pmin.x,pmax.y));
  523. out.push_back(pmax);
  524. out.push_back(aiVector2D(pmax.x,pmin.y));
  525. return;
  526. }
  527. xs = std::max(pmin.x,xs);
  528. xe = std::min(pmax.x,xe);
  529. // see if there's an offset to fill at the top of our quad
  530. if (xs - pmin.x) {
  531. out.push_back(pmin);
  532. out.push_back(aiVector2D(pmin.x,pmax.y));
  533. out.push_back(aiVector2D(xs,pmax.y));
  534. out.push_back(aiVector2D(xs,pmin.y));
  535. }
  536. // search along the y-axis for all openings that overlap xs and our quad
  537. float ylast = pmin.y;
  538. found = false;
  539. for(; start != field.end(); ++start) {
  540. const BoundingBox& bb = bbs[(*start).second];
  541. if (bb.first.x > xs || bb.first.y >= pmax.y) {
  542. break;
  543. }
  544. if (bb.second.y > ylast) {
  545. found = true;
  546. const float ys = std::max(bb.first.y,pmin.y), ye = std::min(bb.second.y,pmax.y);
  547. if (ys - ylast) {
  548. QuadrifyPart( aiVector2D(xs,ylast), aiVector2D(xe,ys) ,field,bbs,out);
  549. }
  550. // the following are the window vertices
  551. /*wnd.push_back(aiVector2D(xs,ys));
  552. wnd.push_back(aiVector2D(xs,ye));
  553. wnd.push_back(aiVector2D(xe,ye));
  554. wnd.push_back(aiVector2D(xe,ys));*/
  555. ylast = ye;
  556. }
  557. }
  558. if (!found) {
  559. // the rectangle [pmin,pend] is opaque, fill it
  560. out.push_back(aiVector2D(xs,pmin.y));
  561. out.push_back(aiVector2D(xs,pmax.y));
  562. out.push_back(aiVector2D(xe,pmax.y));
  563. out.push_back(aiVector2D(xe,pmin.y));
  564. return;
  565. }
  566. if (ylast < pmax.y) {
  567. QuadrifyPart( aiVector2D(xs,ylast), aiVector2D(xe,pmax.y) ,field,bbs,out);
  568. }
  569. // now for the whole rest
  570. if (pmax.x-xe) {
  571. QuadrifyPart(aiVector2D(xe,pmin.y), pmax ,field,bbs,out);
  572. }
  573. }
  574. // ------------------------------------------------------------------------------------------------
  575. enum Intersect {
  576. Intersect_No,
  577. Intersect_LiesOnPlane,
  578. Intersect_Yes
  579. };
  580. // ------------------------------------------------------------------------------------------------
  581. Intersect IntersectSegmentPlane(const aiVector3D& p,const aiVector3D& n, const aiVector3D& e0, const aiVector3D& e1, aiVector3D& out)
  582. {
  583. const aiVector3D pdelta = e0 - p, seg = e1-e0;
  584. const float dotOne = n*seg, dotTwo = -(n*pdelta);
  585. if (fabs(dotOne) < 1e-6) {
  586. return fabs(dotTwo) < 1e-6f ? Intersect_LiesOnPlane : Intersect_No;
  587. }
  588. const float t = dotTwo/dotOne;
  589. // t must be in [0..1] if the intersection point is within the given segment
  590. if (t > 1.f || t < 0.f) {
  591. return Intersect_No;
  592. }
  593. out = e0+t*seg;
  594. return Intersect_Yes;
  595. }
  596. // ------------------------------------------------------------------------------------------------
  597. aiVector3D Unproject(const aiVector2D& vproj, const ProjectionInfo& proj)
  598. {
  599. return vproj.x*proj.u + vproj.y*proj.v + proj.p;
  600. }
  601. // ------------------------------------------------------------------------------------------------
  602. void InsertWindowContours(const std::vector< BoundingBox >& bbs,const std::vector< std::vector<aiVector2D> >& contours,const ProjectionInfo& proj, TempMesh& curmesh)
  603. {
  604. ai_assert(contours.size() == bbs.size());
  605. // fix windows - we need to insert the real, polygonal shapes into the quadratic holes that we have now
  606. for(size_t i = 0; i < contours.size();++i) {
  607. const BoundingBox& bb = bbs[i];
  608. const std::vector<aiVector2D>& contour = contours[i];
  609. // check if we need to do it at all - many windows just fit perfectly into their quadratic holes,
  610. // i.e. their contours *are* already their bounding boxes.
  611. if (contour.size() == 4) {
  612. std::set<aiVector2D,XYSorter> verts;
  613. for(size_t n = 0; n < 4; ++n) {
  614. verts.insert(contour[n]);
  615. }
  616. const std::set<aiVector2D,XYSorter>::const_iterator end = verts.end();
  617. if (verts.find(bb.first)!=end && verts.find(bb.second)!=end
  618. && verts.find(aiVector2D(bb.first.x,bb.second.y))!=end
  619. && verts.find(aiVector2D(bb.second.x,bb.first.y))!=end
  620. ) {
  621. continue;
  622. }
  623. }
  624. const float epsilon = (bb.first-bb.second).Length()/1000.f;
  625. // walk through all contour points and find those that lie on the BB corner
  626. size_t last_hit = -1, very_first_hit = -1;
  627. aiVector2D edge;
  628. for(size_t n = 0, e=0, size = contour.size();; n=(n+1)%size, ++e) {
  629. // sanity checking
  630. if (e == size*2) {
  631. IFCImporter::LogError("encountered unexpected topology while generating window contour");
  632. break;
  633. }
  634. const aiVector2D& v = contour[n];
  635. bool hit = false;
  636. if (fabs(v.x-bb.first.x)<epsilon) {
  637. edge.x = bb.first.x;
  638. hit = true;
  639. }
  640. else if (fabs(v.x-bb.second.x)<epsilon) {
  641. edge.x = bb.second.x;
  642. hit = true;
  643. }
  644. if (fabs(v.y-bb.first.y)<epsilon) {
  645. edge.y = bb.first.y;
  646. hit = true;
  647. }
  648. else if (fabs(v.y-bb.second.y)<epsilon) {
  649. edge.y = bb.second.y;
  650. hit = true;
  651. }
  652. if (hit) {
  653. if (last_hit != (size_t)-1) {
  654. const size_t old = curmesh.verts.size();
  655. size_t cnt = last_hit > n ? size-(last_hit-n) : n-last_hit;
  656. for(size_t a = last_hit, e = 0; e <= cnt; a=(a+1)%size, ++e) {
  657. curmesh.verts.push_back(Unproject(contour[a],proj));
  658. }
  659. if (edge != contour[last_hit] && edge != contour[n]) {
  660. curmesh.verts.push_back(Unproject(edge,proj));
  661. }
  662. else if (cnt == 1) {
  663. // avoid degenerate polygons (also known as lines or points)
  664. curmesh.verts.erase(curmesh.verts.begin()+old,curmesh.verts.end());
  665. }
  666. if (const size_t d = curmesh.verts.size()-old) {
  667. curmesh.vertcnt.push_back(d);
  668. std::reverse(curmesh.verts.rbegin(),curmesh.verts.rbegin()+d);
  669. }
  670. if (n == very_first_hit) {
  671. break;
  672. }
  673. }
  674. else {
  675. very_first_hit = n;
  676. }
  677. last_hit = n;
  678. }
  679. }
  680. }
  681. }
  682. // ------------------------------------------------------------------------------------------------
  683. bool TryAddOpenings_Quadrulate(const std::vector<TempOpening>& openings,const std::vector<aiVector3D>& nors, TempMesh& curmesh)
  684. {
  685. std::vector<aiVector3D>& out = curmesh.verts;
  686. // Try to derive a solid base plane within the current surface for use as
  687. // working coordinate system.
  688. aiVector3D vmin,vmax;
  689. ArrayBounds(&out[0],out.size(),vmin,vmax);
  690. const size_t s = out.size();
  691. const aiVector3D any_point = out[s-4];
  692. const aiVector3D nor = ((out[s-3]-any_point)^(out[s-2]-any_point)).Normalize();
  693. const aiVector3D diag = vmax-vmin;
  694. const float ax = fabs(nor.x);
  695. const float ay = fabs(nor.y);
  696. const float az = fabs(nor.z);
  697. unsigned int ac = 0, bc = 1; /* no z coord. -> projection to xy */
  698. if (ax > ay) {
  699. if (ax > az) { /* no x coord. -> projection to yz */
  700. ac = 1; bc = 2;
  701. }
  702. }
  703. else if (ay > az) { /* no y coord. -> projection to zy */
  704. ac = 2; bc = 0;
  705. }
  706. ProjectionInfo proj;
  707. proj.u = proj.v = diag;
  708. proj.u[bc]=0;
  709. proj.v[ac]=0;
  710. proj.ac = ac;
  711. proj.bc = bc;
  712. proj.p = vmin;
  713. // project all points into the coordinate system defined by the p+sv*tu plane
  714. // and compute bounding boxes for them
  715. std::vector< BoundingBox > bbs;
  716. XYSortedField field;
  717. std::vector<aiVector2D> contour_flat;
  718. contour_flat.reserve(out.size());
  719. BOOST_FOREACH(const aiVector3D& x, out) {
  720. contour_flat.push_back(ProjectPositionVectorOntoPlane(x,proj));
  721. }
  722. std::vector< std::vector<aiVector2D> > contours;
  723. size_t c = 0;
  724. BOOST_FOREACH(const TempOpening& t,openings) {
  725. const aiVector3D& outernor = nors[c++];
  726. const float dot = nor * outernor;
  727. if (fabs(dot)<1.f-1e-6f) {
  728. continue;
  729. }
  730. // const aiVector3D diff = t.extrusionDir;
  731. const std::vector<aiVector3D>& va = t.profileMesh->verts;
  732. if(va.size() <= 2) {
  733. continue;
  734. }
  735. aiVector2D vpmin,vpmax;
  736. MinMaxChooser<aiVector2D>()(vpmin,vpmax);
  737. contours.push_back(std::vector<aiVector2D>());
  738. std::vector<aiVector2D>& contour = contours.back();
  739. BOOST_FOREACH(const aiVector3D& x, t.profileMesh->verts) {
  740. const aiVector2D& vproj = ProjectPositionVectorOntoPlane(x,proj);
  741. vpmin = std::min(vpmin,vproj);
  742. vpmax = std::max(vpmax,vproj);
  743. contour.push_back(vproj);
  744. }
  745. if (field.find(vpmin) != field.end()) {
  746. IFCImporter::LogWarn("constraint failure during generation of wall openings, results may be faulty");
  747. }
  748. field[vpmin] = bbs.size();
  749. bbs.push_back(BoundingBox(vpmin,vpmax));
  750. }
  751. if (bbs.empty()) {
  752. return false;
  753. }
  754. std::vector<aiVector2D> outflat;
  755. outflat.reserve(openings.size()*4);
  756. QuadrifyPart(aiVector2D(0.f,0.f),aiVector2D(1.f,1.f),field,bbs,outflat);
  757. ai_assert(!(outflat.size() % 4));
  758. //FixOuterBoundaries(outflat,contour_flat);
  759. // undo the projection, generate output quads
  760. std::vector<aiVector3D> vold;
  761. vold.reserve(outflat.size());
  762. std::swap(vold,curmesh.verts);
  763. std::vector<unsigned int> iold;
  764. iold.resize(outflat.size()/4,4);
  765. std::swap(iold,curmesh.vertcnt);
  766. BOOST_FOREACH(const aiVector2D& vproj, outflat) {
  767. out.push_back(Unproject(vproj,proj));
  768. }
  769. InsertWindowContours(bbs,contours,proj,curmesh);
  770. return true;
  771. }
  772. // ------------------------------------------------------------------------------------------------
  773. void ProcessExtrudedAreaSolid(const IfcExtrudedAreaSolid& solid, TempMesh& result, ConversionData& conv)
  774. {
  775. TempMesh meshout;
  776. // first read the profile description
  777. if(!ProcessProfile(*solid.SweptArea,meshout,conv) || meshout.verts.size()<=1) {
  778. return;
  779. }
  780. aiVector3D dir;
  781. ConvertDirection(dir,solid.ExtrudedDirection);
  782. dir *= solid.Depth;
  783. // assuming that `meshout.verts` is now a list of vertex points forming
  784. // the underlying profile, extrude along the given axis, forming new
  785. // triangles.
  786. std::vector<aiVector3D>& in = meshout.verts;
  787. const size_t size=in.size();
  788. const bool has_area = solid.SweptArea->ProfileType == "AREA" && size>2;
  789. if(solid.Depth < 1e-3) {
  790. if(has_area) {
  791. meshout = result;
  792. }
  793. return;
  794. }
  795. result.verts.reserve(size*(has_area?4:2));
  796. result.vertcnt.reserve(meshout.vertcnt.size()+2);
  797. // transform to target space
  798. aiMatrix4x4 trafo;
  799. ConvertAxisPlacement(trafo, solid.Position);
  800. BOOST_FOREACH(aiVector3D& v,in) {
  801. v *= trafo;
  802. }
  803. aiVector3D min = in[0];
  804. dir *= aiMatrix3x3(trafo);
  805. std::vector<aiVector3D> nors;
  806. // compute the normal vectors for all opening polygons
  807. if (conv.apply_openings) {
  808. if (!conv.settings.useCustomTriangulation) {
  809. // it is essential to apply the openings in the correct spatial order. The direction
  810. // doesn't matter, but we would screw up if we started with e.g. a door in between
  811. // two windows.
  812. std::sort(conv.apply_openings->begin(),conv.apply_openings->end(),DistanceSorter(min));
  813. }
  814. nors.reserve(conv.apply_openings->size());
  815. BOOST_FOREACH(TempOpening& t,*conv.apply_openings) {
  816. TempMesh& bounds = *t.profileMesh.get();
  817. if (bounds.verts.size() <= 2) {
  818. nors.push_back(aiVector3D());
  819. continue;
  820. }
  821. nors.push_back(((bounds.verts[2]-bounds.verts[0])^(bounds.verts[1]-bounds.verts[0]) ).Normalize());
  822. }
  823. }
  824. TempMesh temp;
  825. TempMesh& curmesh = conv.apply_openings ? temp : result;
  826. std::vector<aiVector3D>& out = curmesh.verts;
  827. bool (* const gen_openings)(const std::vector<TempOpening>&,const std::vector<aiVector3D>&, TempMesh&) = conv.settings.useCustomTriangulation
  828. ? &TryAddOpenings_Quadrulate
  829. : &TryAddOpenings;
  830. size_t sides_with_openings = 0;
  831. for(size_t i = 0; i < size; ++i) {
  832. const size_t next = (i+1)%size;
  833. curmesh.vertcnt.push_back(4);
  834. out.push_back(in[i]);
  835. out.push_back(in[i]+dir);
  836. out.push_back(in[next]+dir);
  837. out.push_back(in[next]);
  838. if(conv.apply_openings) {
  839. if(gen_openings(*conv.apply_openings,nors,temp)) {
  840. ++sides_with_openings;
  841. }
  842. result.Append(temp);
  843. temp.Clear();
  844. }
  845. }
  846. size_t sides_with_v_openings = 0;
  847. if(has_area) {
  848. for(size_t n = 0; n < 2; ++n) {
  849. for(size_t i = size; i--; ) {
  850. out.push_back(in[i]+(n?dir:aiVector3D()));
  851. }
  852. curmesh.vertcnt.push_back(size);
  853. if(conv.apply_openings && size > 2) {
  854. // XXX here we are forced to use the un-triangulated version of TryAddOpening, with
  855. // all the problems it causes. The reason is that vertical walls (ehm, floors)
  856. // can have an arbitrary outer shape, so the usual approach of projecting
  857. // the surface and all openings onto a flat quad and triangulating the quad
  858. // fails.
  859. if(TryAddOpenings(*conv.apply_openings,nors,temp)) {
  860. ++sides_with_v_openings;
  861. }
  862. result.Append(temp);
  863. temp.Clear();
  864. }
  865. }
  866. }
  867. // add connection geometry to close the 'holes' for the openings
  868. if(conv.apply_openings) {
  869. //result.infacing.resize(result.verts.size()+);
  870. BOOST_FOREACH(const TempOpening& t,*conv.apply_openings) {
  871. const std::vector<aiVector3D>& in = t.profileMesh->verts;
  872. std::vector<aiVector3D>& out = result.verts;
  873. const aiVector3D dir = t.extrusionDir;
  874. for(size_t i = 0, size = in.size(); i < size; ++i) {
  875. const size_t next = (i+1)%size;
  876. result.vertcnt.push_back(4);
  877. out.push_back(in[i]);
  878. out.push_back(in[i]+dir);
  879. out.push_back(in[next]+dir);
  880. out.push_back(in[next]);
  881. }
  882. }
  883. }
  884. if(conv.apply_openings && ((sides_with_openings != 2 && sides_with_openings) || (sides_with_v_openings != 2 && sides_with_v_openings))) {
  885. IFCImporter::LogWarn("failed to resolve all openings, presumably their topology is not supported by Assimp");
  886. }
  887. IFCImporter::LogDebug("generate mesh procedurally by extrusion (IfcExtrudedAreaSolid)");
  888. }
  889. // ------------------------------------------------------------------------------------------------
  890. void ProcessSweptAreaSolid(const IfcSweptAreaSolid& swept, TempMesh& meshout, ConversionData& conv)
  891. {
  892. if(const IfcExtrudedAreaSolid* const solid = swept.ToPtr<IfcExtrudedAreaSolid>()) {
  893. // Do we just collect openings for a parent element (i.e. a wall)?
  894. // In this case we don't extrude the surface yet, just keep the profile and transform it correctly
  895. if(conv.collect_openings) {
  896. boost::shared_ptr<TempMesh> meshtmp(new TempMesh());
  897. ProcessProfile(swept.SweptArea,*meshtmp,conv);
  898. aiMatrix4x4 m;
  899. ConvertAxisPlacement(m,solid->Position);
  900. meshtmp->Transform(m);
  901. aiVector3D dir;
  902. ConvertDirection(dir,solid->ExtrudedDirection);
  903. conv.collect_openings->push_back(TempOpening(solid, aiMatrix3x3(m) * (dir*solid->Depth),meshtmp));
  904. return;
  905. }
  906. ProcessExtrudedAreaSolid(*solid,meshout,conv);
  907. }
  908. else if(const IfcRevolvedAreaSolid* const rev = swept.ToPtr<IfcRevolvedAreaSolid>()) {
  909. ProcessRevolvedAreaSolid(*rev,meshout,conv);
  910. }
  911. else {
  912. IFCImporter::LogWarn("skipping unknown IfcSweptAreaSolid entity, type is " + swept.GetClassName());
  913. }
  914. }
  915. // ------------------------------------------------------------------------------------------------
  916. void ProcessBoolean(const IfcBooleanResult& boolean, TempMesh& result, ConversionData& conv)
  917. {
  918. if(const IfcBooleanResult* const clip = boolean.ToPtr<IfcBooleanResult>()) {
  919. if(clip->Operator != "DIFFERENCE") {
  920. IFCImporter::LogWarn("encountered unsupported boolean operator: " + (std::string)clip->Operator);
  921. return;
  922. }
  923. TempMesh meshout;
  924. const IfcHalfSpaceSolid* const hs = clip->SecondOperand->ResolveSelectPtr<IfcHalfSpaceSolid>(conv.db);
  925. if(!hs) {
  926. IFCImporter::LogError("expected IfcHalfSpaceSolid as second clipping operand");
  927. return;
  928. }
  929. const IfcPlane* const plane = hs->BaseSurface->ToPtr<IfcPlane>();
  930. if(!plane) {
  931. IFCImporter::LogError("expected IfcPlane as base surface for the IfcHalfSpaceSolid");
  932. return;
  933. }
  934. if(const IfcBooleanResult* const op0 = clip->FirstOperand->ResolveSelectPtr<IfcBooleanResult>(conv.db)) {
  935. ProcessBoolean(*op0,meshout,conv);
  936. }
  937. else if (const IfcSweptAreaSolid* const swept = clip->FirstOperand->ResolveSelectPtr<IfcSweptAreaSolid>(conv.db)) {
  938. ProcessSweptAreaSolid(*swept,meshout,conv);
  939. }
  940. else {
  941. IFCImporter::LogError("expected IfcSweptAreaSolid or IfcBooleanResult as first clipping operand");
  942. return;
  943. }
  944. // extract plane base position vector and normal vector
  945. aiVector3D p,n(0.f,0.f,1.f);
  946. if (plane->Position->Axis) {
  947. ConvertDirection(n,plane->Position->Axis.Get());
  948. }
  949. ConvertCartesianPoint(p,plane->Position->Location);
  950. if(!IsTrue(hs->AgreementFlag)) {
  951. n *= -1.f;
  952. }
  953. // clip the current contents of `meshout` against the plane we obtained from the second operand
  954. const std::vector<aiVector3D>& in = meshout.verts;
  955. std::vector<aiVector3D>& outvert = result.verts;
  956. std::vector<unsigned int>::const_iterator begin=meshout.vertcnt.begin(), end=meshout.vertcnt.end(), iit;
  957. outvert.reserve(in.size());
  958. result.vertcnt.reserve(meshout.vertcnt.size());
  959. unsigned int vidx = 0;
  960. for(iit = begin; iit != end; vidx += *iit++) {
  961. unsigned int newcount = 0;
  962. for(unsigned int i = 0; i < *iit; ++i) {
  963. const aiVector3D& e0 = in[vidx+i], e1 = in[vidx+(i+1)%*iit];
  964. // does the next segment intersect the plane?
  965. aiVector3D isectpos;
  966. const Intersect isect = IntersectSegmentPlane(p,n,e0,e1,isectpos);
  967. if (isect == Intersect_No || isect == Intersect_LiesOnPlane) {
  968. if ( (e0-p).Normalize()*n > 0 ) {
  969. outvert.push_back(e0);
  970. ++newcount;
  971. }
  972. }
  973. else if (isect == Intersect_Yes) {
  974. if ( (e0-p).Normalize()*n > 0 ) {
  975. // e0 is on the right side, so keep it
  976. outvert.push_back(e0);
  977. outvert.push_back(isectpos);
  978. newcount += 2;
  979. }
  980. else {
  981. // e0 is on the wrong side, so drop it and keep e1 instead
  982. outvert.push_back(isectpos);
  983. ++newcount;
  984. }
  985. }
  986. }
  987. if (!newcount) {
  988. continue;
  989. }
  990. aiVector3D vmin,vmax;
  991. ArrayBounds(&*(outvert.end()-newcount),newcount,vmin,vmax);
  992. // filter our double points - those may happen if a point lies
  993. // directly on the intersection line. However, due to float
  994. // precision a bitwise comparison is not feasible to detect
  995. // this case.
  996. const float epsilon = (vmax-vmin).SquareLength() / 1e6f;
  997. FuzzyVectorCompare fz(epsilon);
  998. std::vector<aiVector3D>::iterator e = std::unique( outvert.end()-newcount, outvert.end(), fz );
  999. if (e != outvert.end()) {
  1000. newcount -= static_cast<unsigned int>(std::distance(e,outvert.end()));
  1001. outvert.erase(e,outvert.end());
  1002. }
  1003. if (fz(*( outvert.end()-newcount),outvert.back())) {
  1004. outvert.pop_back();
  1005. --newcount;
  1006. }
  1007. if(newcount > 2) {
  1008. result.vertcnt.push_back(newcount);
  1009. }
  1010. else while(newcount-->0)result.verts.pop_back();
  1011. }
  1012. IFCImporter::LogDebug("generating CSG geometry by plane clipping (IfcBooleanClippingResult)");
  1013. }
  1014. else {
  1015. IFCImporter::LogWarn("skipping unknown IfcBooleanResult entity, type is " + boolean.GetClassName());
  1016. }
  1017. }
  1018. // ------------------------------------------------------------------------------------------------
  1019. bool ProcessGeometricItem(const IfcRepresentationItem& geo, std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  1020. {
  1021. TempMesh meshtmp;
  1022. if(const IfcShellBasedSurfaceModel* shellmod = geo.ToPtr<IfcShellBasedSurfaceModel>()) {
  1023. BOOST_FOREACH(boost::shared_ptr<const IfcShell> shell,shellmod->SbsmBoundary) {
  1024. try {
  1025. const EXPRESS::ENTITY& e = shell->To<ENTITY>();
  1026. const IfcConnectedFaceSet& fs = conv.db.MustGetObject(e).To<IfcConnectedFaceSet>();
  1027. ProcessConnectedFaceSet(fs,meshtmp,conv);
  1028. }
  1029. catch(std::bad_cast&) {
  1030. IFCImporter::LogWarn("unexpected type error, IfcShell ought to inherit from IfcConnectedFaceSet");
  1031. }
  1032. }
  1033. }
  1034. else if(const IfcConnectedFaceSet* fset = geo.ToPtr<IfcConnectedFaceSet>()) {
  1035. ProcessConnectedFaceSet(*fset,meshtmp,conv);
  1036. }
  1037. else if(const IfcSweptAreaSolid* swept = geo.ToPtr<IfcSweptAreaSolid>()) {
  1038. ProcessSweptAreaSolid(*swept,meshtmp,conv);
  1039. }
  1040. else if(const IfcManifoldSolidBrep* brep = geo.ToPtr<IfcManifoldSolidBrep>()) {
  1041. ProcessConnectedFaceSet(brep->Outer,meshtmp,conv);
  1042. }
  1043. else if(const IfcFaceBasedSurfaceModel* surf = geo.ToPtr<IfcFaceBasedSurfaceModel>()) {
  1044. BOOST_FOREACH(const IfcConnectedFaceSet& fc, surf->FbsmFaces) {
  1045. ProcessConnectedFaceSet(fc,meshtmp,conv);
  1046. }
  1047. }
  1048. else if(const IfcBooleanResult* boolean = geo.ToPtr<IfcBooleanResult>()) {
  1049. ProcessBoolean(*boolean,meshtmp,conv);
  1050. }
  1051. else if(geo.ToPtr<IfcBoundingBox>()) {
  1052. // silently skip over bounding boxes
  1053. return false;
  1054. }
  1055. else {
  1056. IFCImporter::LogWarn("skipping unknown IfcGeometricRepresentationItem entity, type is " + geo.GetClassName());
  1057. return false;
  1058. }
  1059. meshtmp.RemoveAdjacentDuplicates();
  1060. FixupFaceOrientation(meshtmp);
  1061. aiMesh* const mesh = meshtmp.ToMesh();
  1062. if(mesh) {
  1063. mesh->mMaterialIndex = ProcessMaterials(geo,conv);
  1064. mesh_indices.push_back(conv.meshes.size());
  1065. conv.meshes.push_back(mesh);
  1066. return true;
  1067. }
  1068. return false;
  1069. }
  1070. // ------------------------------------------------------------------------------------------------
  1071. void AssignAddedMeshes(std::vector<unsigned int>& mesh_indices,aiNode* nd,ConversionData& /*conv*/)
  1072. {
  1073. if (!mesh_indices.empty()) {
  1074. // make unique
  1075. std::sort(mesh_indices.begin(),mesh_indices.end());
  1076. std::vector<unsigned int>::iterator it_end = std::unique(mesh_indices.begin(),mesh_indices.end());
  1077. const size_t size = std::distance(mesh_indices.begin(),it_end);
  1078. nd->mNumMeshes = size;
  1079. nd->mMeshes = new unsigned int[nd->mNumMeshes];
  1080. for(unsigned int i = 0; i < nd->mNumMeshes; ++i) {
  1081. nd->mMeshes[i] = mesh_indices[i];
  1082. }
  1083. }
  1084. }
  1085. // ------------------------------------------------------------------------------------------------
  1086. bool TryQueryMeshCache(const IfcRepresentationItem& item, std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  1087. {
  1088. ConversionData::MeshCache::const_iterator it = conv.cached_meshes.find(&item);
  1089. if (it != conv.cached_meshes.end()) {
  1090. std::copy((*it).second.begin(),(*it).second.end(),std::back_inserter(mesh_indices));
  1091. return true;
  1092. }
  1093. return false;
  1094. }
  1095. // ------------------------------------------------------------------------------------------------
  1096. void PopulateMeshCache(const IfcRepresentationItem& item, const std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  1097. {
  1098. conv.cached_meshes[&item] = mesh_indices;
  1099. }
  1100. // ------------------------------------------------------------------------------------------------
  1101. bool ProcessRepresentationItem(const IfcRepresentationItem& item, std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  1102. {
  1103. if (!TryQueryMeshCache(item,mesh_indices,conv)) {
  1104. if(ProcessGeometricItem(item,mesh_indices,conv)) {
  1105. if(mesh_indices.size()) {
  1106. PopulateMeshCache(item,mesh_indices,conv);
  1107. }
  1108. }
  1109. else return false;
  1110. }
  1111. return true;
  1112. }
  1113. } // ! IFC
  1114. } // ! Assimp
  1115. #endif