2
0

IFCLoader.cpp 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681
  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 IFC.cpp
  34. * @brief Implementation of the Industry Foundation Classes loader.
  35. */
  36. #include "AssimpPCH.h"
  37. #ifndef ASSIMP_BUILD_NO_IFC_IMPORTER
  38. #include <iterator>
  39. #include <boost/tuple/tuple.hpp>
  40. #include "IFCLoader.h"
  41. #include "STEPFileReader.h"
  42. #include "IFCReaderGen.h"
  43. #include "StreamReader.h"
  44. #include "MemoryIOWrapper.h"
  45. #include "ProcessHelper.h"
  46. #include "PolyTools.h"
  47. using namespace Assimp;
  48. using namespace Assimp::Formatter;
  49. namespace EXPRESS = STEP::EXPRESS;
  50. template<> const std::string LogFunctions<IFCImporter>::log_prefix = "IFC: ";
  51. /* DO NOT REMOVE this comment block. The genentitylist.sh script
  52. * just looks for names adhering to the IFC :: IfcSomething naming scheme
  53. * and includes all matches in the whitelist for code-generation. Thus,
  54. * all entity classes that are only indirectly referenced need to be
  55. * mentioned explicitly.
  56. IFC::IfcRepresentationMap
  57. IFC::IfcProductRepresentation
  58. IFC::IfcUnitAssignment
  59. IFC::IfcClosedShell
  60. IFC::IfcDoor
  61. */
  62. namespace {
  63. // helper for std::for_each to delete all heap-allocated items in a container
  64. template<typename T>
  65. struct delete_fun
  66. {
  67. void operator()(T* del) {
  68. delete del;
  69. }
  70. };
  71. // ------------------------------------------------------------------------------------------------
  72. // Temporary representation of an opening in a wall or a floor
  73. // ------------------------------------------------------------------------------------------------
  74. struct TempMesh;
  75. struct TempOpening
  76. {
  77. const IFC::IfcExtrudedAreaSolid* solid;
  78. aiVector3D extrusionDir;
  79. boost::shared_ptr<TempMesh> profileMesh;
  80. // ------------------------------------------------------------------------------
  81. TempOpening(const IFC::IfcExtrudedAreaSolid* solid,aiVector3D extrusionDir,boost::shared_ptr<TempMesh> profileMesh)
  82. : solid(solid)
  83. , extrusionDir(extrusionDir)
  84. , profileMesh(profileMesh)
  85. {
  86. }
  87. // ------------------------------------------------------------------------------
  88. void Transform(const aiMatrix4x4& mat); // defined later since TempMesh is not complete yet
  89. };
  90. // ------------------------------------------------------------------------------------------------
  91. // Intermediate data storage during conversion. Keeps everything and a bit more.
  92. // ------------------------------------------------------------------------------------------------
  93. struct ConversionData
  94. {
  95. ConversionData(const STEP::DB& db, const IFC::IfcProject& proj, aiScene* out,const IFCImporter::Settings& settings)
  96. : len_scale(1.0)
  97. , angle_scale(1.0)
  98. , db(db)
  99. , proj(proj)
  100. , out(out)
  101. , settings(settings)
  102. , apply_openings()
  103. , collect_openings()
  104. {}
  105. ~ConversionData() {
  106. std::for_each(meshes.begin(),meshes.end(),delete_fun<aiMesh>());
  107. std::for_each(materials.begin(),materials.end(),delete_fun<aiMaterial>());
  108. }
  109. float len_scale, angle_scale;
  110. bool plane_angle_in_radians;
  111. const STEP::DB& db;
  112. const IFC::IfcProject& proj;
  113. aiScene* out;
  114. aiMatrix4x4 wcs;
  115. std::vector<aiMesh*> meshes;
  116. std::vector<aiMaterial*> materials;
  117. typedef std::map<const IFC::IfcRepresentationItem*, std::vector<unsigned int> > MeshCache;
  118. MeshCache cached_meshes;
  119. const IFCImporter::Settings& settings;
  120. // Intermediate arrays used to resolve openings in walls: only one of them
  121. // can be given at a time. apply_openings if present if the current element
  122. // is a wall and needs its openings to be poured into its geometry while
  123. // collect_openings is present only if the current element is an
  124. // IfcOpeningElement, for which all the geometry needs to be preserved
  125. // for later processing by a parent, which is a wall.
  126. std::vector<TempOpening>* apply_openings;
  127. std::vector<TempOpening>* collect_openings;
  128. };
  129. // ------------------------------------------------------------------------------------------------
  130. struct FuzzyVectorCompare {
  131. FuzzyVectorCompare(float epsilon) : epsilon(epsilon) {}
  132. bool operator()(const aiVector3D& a, const aiVector3D& b) {
  133. return fabs((a-b).SquareLength()) < epsilon;
  134. }
  135. const float epsilon;
  136. };
  137. // ------------------------------------------------------------------------------------------------
  138. // Helper used during mesh construction. Aids at creating aiMesh'es out of relatively few polygons.
  139. // ------------------------------------------------------------------------------------------------
  140. struct TempMesh
  141. {
  142. std::vector<aiVector3D> verts;
  143. std::vector<unsigned int> vertcnt;
  144. // ------------------------------------------------------------------------------
  145. aiMesh* ToMesh() {
  146. ai_assert(verts.size() == std::accumulate(vertcnt.begin(),vertcnt.end(),0));
  147. if (verts.empty()) {
  148. return NULL;
  149. }
  150. std::auto_ptr<aiMesh> mesh(new aiMesh());
  151. // copy vertices
  152. mesh->mNumVertices = static_cast<unsigned int>(verts.size());
  153. mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  154. std::copy(verts.begin(),verts.end(),mesh->mVertices);
  155. // and build up faces
  156. mesh->mNumFaces = static_cast<unsigned int>(vertcnt.size());
  157. mesh->mFaces = new aiFace[mesh->mNumFaces];
  158. for(unsigned int i = 0,n=0, acc = 0; i < mesh->mNumFaces; ++n) {
  159. aiFace& f = mesh->mFaces[i];
  160. if (!vertcnt[n]) {
  161. --mesh->mNumFaces;
  162. continue;
  163. }
  164. f.mNumIndices = vertcnt[n];
  165. f.mIndices = new unsigned int[f.mNumIndices];
  166. for(unsigned int a = 0; a < f.mNumIndices; ++a) {
  167. f.mIndices[a] = acc++;
  168. }
  169. ++i;
  170. }
  171. return mesh.release();
  172. }
  173. // ------------------------------------------------------------------------------
  174. void Clear() {
  175. verts.clear();
  176. vertcnt.clear();
  177. }
  178. // ------------------------------------------------------------------------------
  179. void Transform(const aiMatrix4x4& mat) {
  180. BOOST_FOREACH(aiVector3D& v, verts) {
  181. v *= mat;
  182. }
  183. }
  184. // ------------------------------------------------------------------------------
  185. aiVector3D Center() {
  186. return std::accumulate(verts.begin(),verts.end(),aiVector3D(0.f,0.f,0.f)) / static_cast<float>(verts.size());
  187. }
  188. // ------------------------------------------------------------------------------
  189. void Append(const TempMesh& other) {
  190. verts.insert(verts.end(),other.verts.begin(),other.verts.end());
  191. vertcnt.insert(vertcnt.end(),other.vertcnt.begin(),other.vertcnt.end());
  192. }
  193. // ------------------------------------------------------------------------------
  194. void RemoveAdjacentDuplicates() {
  195. bool drop = false;
  196. std::vector<aiVector3D>::iterator base = verts.begin();
  197. BOOST_FOREACH(unsigned int& cnt, vertcnt) {
  198. if (cnt < 2){
  199. base += cnt;
  200. continue;
  201. }
  202. aiVector3D vmin,vmax;
  203. ArrayBounds(&*base, cnt ,vmin,vmax);
  204. const float epsilon = (vmax-vmin).SquareLength() / 1e9f, dotepsilon = 1e-7;
  205. //// look for vertices that lie directly on the line between their predecessor and their
  206. //// successor and replace them with either of them.
  207. //for(size_t i = 0; i < cnt; ++i) {
  208. // aiVector3D& v1 = *(base+i), &v0 = *(base+(i?i-1:cnt-1)), &v2 = *(base+(i+1)%cnt);
  209. // const aiVector3D& d0 = (v1-v0), &d1 = (v2-v1);
  210. // const float l0 = d0.SquareLength(), l1 = d1.SquareLength();
  211. // if (!l0 || !l1) {
  212. // continue;
  213. // }
  214. // const float d = (d0/sqrt(l0))*(d1/sqrt(l1));
  215. // if ( d >= 1.f-dotepsilon ) {
  216. // v1 = v0;
  217. // }
  218. // else if ( d0*d1 < -1.f+dotepsilon ) {
  219. // v2 = v1;
  220. // continue;
  221. // }
  222. //}
  223. // drop any identical, adjacent vertices. this pass will collect the dropouts
  224. // of the previous pass as a side-effect.
  225. FuzzyVectorCompare fz(epsilon);
  226. std::vector<aiVector3D>::iterator end = base+cnt, e = std::unique( base, end, fz );
  227. if (e != end) {
  228. cnt -= static_cast<unsigned int>(std::distance(e, end));
  229. verts.erase(e,end);
  230. drop = true;
  231. }
  232. // check front and back vertices for this polygon
  233. if (cnt > 1 && fz(*base,*(base+cnt-1))) {
  234. verts.erase(base+ --cnt);
  235. drop = true;
  236. }
  237. // removing adjacent duplicates shouldn't erase everything :-)
  238. ai_assert(cnt>0);
  239. base += cnt;
  240. }
  241. if(drop) {
  242. IFCImporter::LogDebug("removed duplicate vertices");
  243. }
  244. }
  245. };
  246. // ------------------------------------------------------------------------------
  247. void TempOpening::Transform(const aiMatrix4x4& mat)
  248. {
  249. if(profileMesh) {
  250. profileMesh->Transform(mat);
  251. }
  252. extrusionDir *= aiMatrix3x3(mat);
  253. }
  254. // forward declarations
  255. float ConvertSIPrefix(const std::string& prefix);
  256. void SetUnits(ConversionData& conv);
  257. void ConvertAxisPlacement(aiMatrix4x4& out, const IFC::IfcAxis2Placement& in, ConversionData& conv);
  258. void SetCoordinateSpace(ConversionData& conv);
  259. void ProcessSpatialStructures(ConversionData& conv);
  260. aiNode* ProcessSpatialStructure(aiNode* parent, const IFC::IfcProduct& el ,ConversionData& conv);
  261. void ProcessProductRepresentation(const IFC::IfcProduct& el, aiNode* nd, ConversionData& conv);
  262. void MakeTreeRelative(ConversionData& conv);
  263. void ConvertUnit(const EXPRESS::DataType& dt,ConversionData& conv);
  264. void ProcessSweptAreaSolid(const IFC::IfcSweptAreaSolid& swept, TempMesh& meshout, ConversionData& conv);
  265. } // anon
  266. // ------------------------------------------------------------------------------------------------
  267. // Constructor to be privately used by Importer
  268. IFCImporter::IFCImporter()
  269. {}
  270. // ------------------------------------------------------------------------------------------------
  271. // Destructor, private as well
  272. IFCImporter::~IFCImporter()
  273. {
  274. }
  275. // ------------------------------------------------------------------------------------------------
  276. // Returns whether the class can handle the format of the given file.
  277. bool IFCImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  278. {
  279. const std::string& extension = GetExtension(pFile);
  280. if (extension == "ifc") {
  281. return true;
  282. }
  283. else if ((!extension.length() || checkSig) && pIOHandler) {
  284. // note: this is the common identification for STEP-encoded files, so
  285. // it is only unambiguous as long as we don't support any further
  286. // file formats with STEP as their encoding.
  287. const char* tokens[] = {"ISO-10303-21"};
  288. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
  289. }
  290. return false;
  291. }
  292. // ------------------------------------------------------------------------------------------------
  293. // List all extensions handled by this loader
  294. void IFCImporter::GetExtensionList(std::set<std::string>& app)
  295. {
  296. app.insert("ifc");
  297. }
  298. // ------------------------------------------------------------------------------------------------
  299. // Setup configuration properties for the loader
  300. void IFCImporter::SetupProperties(const Importer* pImp)
  301. {
  302. settings.skipSpaceRepresentations = pImp->GetPropertyBool(AI_CONFIG_IMPORT_IFC_SKIP_SPACE_REPRESENTATIONS,true);
  303. settings.skipCurveRepresentations = pImp->GetPropertyBool(AI_CONFIG_IMPORT_IFC_SKIP_CURVE_REPRESENTATIONS,true);
  304. settings.useCustomTriangulation = pImp->GetPropertyBool(AI_CONFIG_IMPORT_IFC_CUSTOM_TRIANGULATION,true);
  305. }
  306. // ------------------------------------------------------------------------------------------------
  307. // Imports the given file into the given scene structure.
  308. void IFCImporter::InternReadFile( const std::string& pFile,
  309. aiScene* pScene, IOSystem* pIOHandler)
  310. {
  311. boost::shared_ptr<IOStream> stream(pIOHandler->Open(pFile));
  312. if (!stream) {
  313. ThrowException("Could not open file for reading");
  314. }
  315. boost::scoped_ptr<STEP::DB> db(STEP::ReadFileHeader(stream));
  316. const STEP::HeaderInfo& head = const_cast<const STEP::DB&>(*db).GetHeader();
  317. if(!head.fileSchema.size() || head.fileSchema.substr(0,3) != "IFC") {
  318. ThrowException("Unrecognized file schema: " + head.fileSchema);
  319. }
  320. if (!DefaultLogger::isNullLogger()) {
  321. LogDebug("File schema is \'" + head.fileSchema + '\'');
  322. if (head.timestamp.length()) {
  323. LogDebug("Timestamp \'" + head.timestamp + '\'');
  324. }
  325. if (head.app.length()) {
  326. LogDebug("Application/Exporter identline is \'" + head.app + '\'');
  327. }
  328. }
  329. // obtain a copy of the machine-generated IFC scheme
  330. EXPRESS::ConversionSchema schema;
  331. IFC::GetSchema(schema);
  332. // tell the reader which entity types to track with special care
  333. static const char* const types_to_track[] = {
  334. "ifcsite", "ifcbuilding", "ifcproject"
  335. };
  336. // tell the reader for which types we need to simulate STEPs reverse indices
  337. static const char* const inverse_indices_to_track[] = {
  338. "ifcrelcontainedinspatialstructure", "ifcrelaggregates", "ifcrelvoidselement", "ifcstyleditem"
  339. };
  340. // feed the IFC schema into the reader and pre-parse all lines
  341. STEP::ReadFile(*db, schema, types_to_track, inverse_indices_to_track);
  342. const STEP::LazyObject* proj = db->GetObject("ifcproject");
  343. if (!proj) {
  344. ThrowException("missing IfcProject entity");
  345. }
  346. ConversionData conv(*db,proj->To<IFC::IfcProject>(),pScene,settings);
  347. SetUnits(conv);
  348. SetCoordinateSpace(conv);
  349. ProcessSpatialStructures(conv);
  350. MakeTreeRelative(conv);
  351. // NOTE - this is a stress test for the importer, but it works only
  352. // in a build with no entities disabled. See
  353. // scripts/IFCImporter/CPPGenerator.py
  354. // for more information.
  355. #ifdef ASSIMP_IFC_TEST
  356. db->EvaluateAll();
  357. #endif
  358. // do final data copying
  359. if (conv.meshes.size()) {
  360. pScene->mNumMeshes = static_cast<unsigned int>(conv.meshes.size());
  361. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes]();
  362. std::copy(conv.meshes.begin(),conv.meshes.end(),pScene->mMeshes);
  363. // needed to keep the d'tor from burning us
  364. conv.meshes.clear();
  365. }
  366. if (conv.materials.size()) {
  367. pScene->mNumMaterials = static_cast<unsigned int>(conv.materials.size());
  368. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials]();
  369. std::copy(conv.materials.begin(),conv.materials.end(),pScene->mMaterials);
  370. // needed to keep the d'tor from burning us
  371. conv.materials.clear();
  372. }
  373. // apply world coordinate system (which includes the scaling to convert to meters and a -90 degrees rotation around x)
  374. aiMatrix4x4 scale, rot;
  375. aiMatrix4x4::Scaling(aiVector3D(conv.len_scale,conv.len_scale,conv.len_scale),scale);
  376. aiMatrix4x4::RotationX(-AI_MATH_HALF_PI_F,rot);
  377. pScene->mRootNode->mTransformation = rot * scale * conv.wcs * pScene->mRootNode->mTransformation;
  378. // this must be last because objects are evaluated lazily as we process them
  379. if ( !DefaultLogger::isNullLogger() ){
  380. LogDebug((Formatter::format(),"STEP: evaluated ",db->GetEvaluatedObjectCount()," object records"));
  381. }
  382. }
  383. namespace {
  384. // ------------------------------------------------------------------------------------------------
  385. bool IsTrue(const EXPRESS::BOOLEAN& in)
  386. {
  387. return (std::string)in == "TRUE" || (std::string)in == "T";
  388. }
  389. // ------------------------------------------------------------------------------------------------
  390. float ConvertSIPrefix(const std::string& prefix)
  391. {
  392. if (prefix == "EXA") {
  393. return 1e18f;
  394. }
  395. else if (prefix == "PETA") {
  396. return 1e15f;
  397. }
  398. else if (prefix == "TERA") {
  399. return 1e12f;
  400. }
  401. else if (prefix == "GIGA") {
  402. return 1e9f;
  403. }
  404. else if (prefix == "MEGA") {
  405. return 1e6f;
  406. }
  407. else if (prefix == "KILO") {
  408. return 1e3f;
  409. }
  410. else if (prefix == "HECTO") {
  411. return 1e2f;
  412. }
  413. else if (prefix == "DECA") {
  414. return 1e-0f;
  415. }
  416. else if (prefix == "DECI") {
  417. return 1e-1f;
  418. }
  419. else if (prefix == "CENTI") {
  420. return 1e-2f;
  421. }
  422. else if (prefix == "MILLI") {
  423. return 1e-3f;
  424. }
  425. else if (prefix == "MICRO") {
  426. return 1e-6f;
  427. }
  428. else if (prefix == "NANO") {
  429. return 1e-9f;
  430. }
  431. else if (prefix == "PICO") {
  432. return 1e-12f;
  433. }
  434. else if (prefix == "FEMTO") {
  435. return 1e-15f;
  436. }
  437. else if (prefix == "ATTO") {
  438. return 1e-18f;
  439. }
  440. else {
  441. IFCImporter::LogError("Unrecognized SI prefix: " + prefix);
  442. return 1;
  443. }
  444. }
  445. // ------------------------------------------------------------------------------------------------
  446. void ConvertUnit(const IFC::IfcNamedUnit& unit,ConversionData& conv)
  447. {
  448. if(const IFC::IfcSIUnit* const si = unit.ToPtr<IFC::IfcSIUnit>()) {
  449. if(si->UnitType == "LENGTHUNIT") {
  450. conv.len_scale = si->Prefix ? ConvertSIPrefix(si->Prefix) : 1.f;
  451. IFCImporter::LogDebug("got units used for lengths");
  452. }
  453. if(si->UnitType == "PLANEANGLEUNIT") {
  454. if (si->Name != "RADIAN") {
  455. IFCImporter::LogWarn("expected base unit for angles to be radian");
  456. }
  457. }
  458. }
  459. else if(const IFC::IfcConversionBasedUnit* const convu = unit.ToPtr<IFC::IfcConversionBasedUnit>()) {
  460. if(convu->UnitType == "PLANEANGLEUNIT") {
  461. try {
  462. conv.angle_scale = convu->ConversionFactor->ValueComponent->To<EXPRESS::REAL>();
  463. ConvertUnit(*convu->ConversionFactor->UnitComponent,conv);
  464. IFCImporter::LogDebug("got units used for angles");
  465. }
  466. catch(std::bad_cast&) {
  467. IFCImporter::LogError("skipping unknown IfcConversionBasedUnit.ValueComponent entry - expected REAL");
  468. }
  469. }
  470. }
  471. }
  472. // ------------------------------------------------------------------------------------------------
  473. void ConvertUnit(const EXPRESS::DataType& dt,ConversionData& conv)
  474. {
  475. try {
  476. const EXPRESS::ENTITY& e = dt.To<IFC::ENTITY>();
  477. const IFC::IfcNamedUnit& unit = e.ResolveSelect<IFC::IfcNamedUnit>(conv.db);
  478. if(unit.UnitType != "LENGTHUNIT" && unit.UnitType != "PLANEANGLEUNIT") {
  479. return;
  480. }
  481. ConvertUnit(unit,conv);
  482. }
  483. catch(std::bad_cast&) {
  484. // not entity, somehow
  485. IFCImporter::LogError("skipping unknown IfcUnit entry - expected entity");
  486. }
  487. }
  488. // ------------------------------------------------------------------------------------------------
  489. void SetUnits(ConversionData& conv)
  490. {
  491. // see if we can determine the coordinate space used to express.
  492. for(size_t i = 0; i < conv.proj.UnitsInContext->Units.size(); ++i ) {
  493. ConvertUnit(*conv.proj.UnitsInContext->Units[i],conv);
  494. }
  495. }
  496. // ------------------------------------------------------------------------------------------------
  497. void ConvertColor(aiColor4D& out, const IFC::IfcColourRgb& in)
  498. {
  499. out.r = in.Red;
  500. out.g = in.Green;
  501. out.b = in.Blue;
  502. out.a = 1.f;
  503. }
  504. // ------------------------------------------------------------------------------------------------
  505. void ConvertColor(aiColor4D& out, const IFC::IfcColourOrFactor& in,ConversionData& conv,const aiColor4D* base)
  506. {
  507. if (const EXPRESS::REAL* const r = in.ToPtr<EXPRESS::REAL>()) {
  508. out.r = out.g = out.b = *r;
  509. if(base) {
  510. out.r *= base->r;
  511. out.g *= base->g;
  512. out.b *= base->b;
  513. out.a = base->a;
  514. }
  515. else out.a = 1.0;
  516. }
  517. else if (const IFC::IfcColourRgb* const rgb = in.ResolveSelectPtr<IFC::IfcColourRgb>(conv.db)) {
  518. ConvertColor(out,*rgb);
  519. }
  520. else {
  521. IFCImporter::LogWarn("skipping unknown IfcColourOrFactor entity");
  522. }
  523. }
  524. // ------------------------------------------------------------------------------------------------
  525. void ConvertCartesianPoint(aiVector3D& out, const IFC::IfcCartesianPoint& in)
  526. {
  527. out = aiVector3D();
  528. for(size_t i = 0; i < in.Coordinates.size(); ++i) {
  529. out[i] = in.Coordinates[i];
  530. }
  531. }
  532. // ------------------------------------------------------------------------------------------------
  533. void ConvertDirection(aiVector3D& out, const IFC::IfcDirection& in)
  534. {
  535. out = aiVector3D();
  536. for(size_t i = 0; i < in.DirectionRatios.size(); ++i) {
  537. out[i] = in.DirectionRatios[i];
  538. }
  539. const float len = out.Length();
  540. if (len<1e-6) {
  541. IFCImporter::LogWarn("direction vector too small, normalizing would result in a division by zero");
  542. return;
  543. }
  544. out /= len;
  545. }
  546. // ------------------------------------------------------------------------------------------------
  547. void AssignMatrixAxes(aiMatrix4x4& out, const aiVector3D& x, const aiVector3D& y, const aiVector3D& z)
  548. {
  549. out.a1 = x.x;
  550. out.b1 = x.y;
  551. out.c1 = x.z;
  552. out.a2 = y.x;
  553. out.b2 = y.y;
  554. out.c2 = y.z;
  555. out.a3 = z.x;
  556. out.b3 = z.y;
  557. out.c3 = z.z;
  558. }
  559. // ------------------------------------------------------------------------------------------------
  560. void ConvertAxisPlacement(aiMatrix4x4& out, const IFC::IfcAxis2Placement3D& in, ConversionData& conv)
  561. {
  562. aiVector3D loc;
  563. ConvertCartesianPoint(loc,in.Location);
  564. aiVector3D z(0.f,0.f,1.f),r(1.f,0.f,0.f),x;
  565. if (in.Axis) {
  566. ConvertDirection(z,*in.Axis.Get());
  567. }
  568. if (in.RefDirection) {
  569. ConvertDirection(r,*in.RefDirection.Get());
  570. }
  571. aiVector3D v = r.Normalize();
  572. aiVector3D tmpx = z * (v*z);
  573. x = (v-tmpx).Normalize();
  574. aiVector3D y = (z^x);
  575. aiMatrix4x4::Translation(loc,out);
  576. AssignMatrixAxes(out,x,y,z);
  577. }
  578. // ------------------------------------------------------------------------------------------------
  579. void ConvertAxisPlacement(aiMatrix4x4& out, const IFC::IfcAxis2Placement2D& in, ConversionData& conv)
  580. {
  581. aiVector3D loc;
  582. ConvertCartesianPoint(loc,in.Location);
  583. aiVector3D x(1.f,0.f,0.f);
  584. if (in.RefDirection) {
  585. ConvertDirection(x,*in.RefDirection.Get());
  586. }
  587. const aiVector3D y = aiVector3D(x.y,-x.x,0.f);
  588. aiMatrix4x4::Translation(loc,out);
  589. AssignMatrixAxes(out,x,y,aiVector3D(0.f,0.f,1.f));
  590. }
  591. // ------------------------------------------------------------------------------------------------
  592. void ConvertAxisPlacement(aiVector3D& axis, aiVector3D& pos, const IFC::IfcAxis1Placement& in, ConversionData& conv)
  593. {
  594. ConvertCartesianPoint(pos,in.Location);
  595. if (in.Axis) {
  596. ConvertDirection(axis,in.Axis.Get());
  597. }
  598. else {
  599. axis = aiVector3D(0.f,0.f,1.f);
  600. }
  601. }
  602. // ------------------------------------------------------------------------------------------------
  603. void ConvertAxisPlacement(aiMatrix4x4& out, const IFC::IfcAxis2Placement& in, ConversionData& conv)
  604. {
  605. if(const IFC::IfcAxis2Placement3D* pl3 = in.ResolveSelectPtr<IFC::IfcAxis2Placement3D>(conv.db)) {
  606. ConvertAxisPlacement(out,*pl3,conv);
  607. }
  608. else if(const IFC::IfcAxis2Placement2D* pl2 = in.ResolveSelectPtr<IFC::IfcAxis2Placement2D>(conv.db)) {
  609. ConvertAxisPlacement(out,*pl2,conv);
  610. }
  611. else {
  612. IFCImporter::LogWarn("skipping unknown IfcAxis2Placement entity");
  613. }
  614. }
  615. // ------------------------------------------------------------------------------------------------
  616. void SetCoordinateSpace(ConversionData& conv)
  617. {
  618. const IFC::IfcRepresentationContext* fav = NULL;
  619. BOOST_FOREACH(const IFC::IfcRepresentationContext& v, conv.proj.RepresentationContexts) {
  620. fav = &v;
  621. // Model should be the most suitable type of context, hence ignore the others
  622. if (v.ContextType && v.ContextType.Get() == "Model") {
  623. break;
  624. }
  625. }
  626. if (fav) {
  627. if(const IFC::IfcGeometricRepresentationContext* const geo = fav->ToPtr<IFC::IfcGeometricRepresentationContext>()) {
  628. ConvertAxisPlacement(conv.wcs, *geo->WorldCoordinateSystem, conv);
  629. IFCImporter::LogDebug("got world coordinate system");
  630. }
  631. }
  632. }
  633. // ------------------------------------------------------------------------------------------------
  634. void ConvertTransformOperator(aiMatrix4x4& out, const IFC::IfcCartesianTransformationOperator& op)
  635. {
  636. aiVector3D loc;
  637. ConvertCartesianPoint(loc,op.LocalOrigin);
  638. aiVector3D x(1.f,0.f,0.f),y(0.f,1.f,0.f),z(0.f,0.f,1.f);
  639. if (op.Axis1) {
  640. ConvertDirection(x,*op.Axis1.Get());
  641. }
  642. if (op.Axis2) {
  643. ConvertDirection(y,*op.Axis2.Get());
  644. }
  645. if (const IFC::IfcCartesianTransformationOperator3D* op2 = op.ToPtr<IFC::IfcCartesianTransformationOperator3D>()) {
  646. if(op2->Axis3) {
  647. ConvertDirection(z,*op2->Axis3.Get());
  648. }
  649. }
  650. aiMatrix4x4 locm;
  651. aiMatrix4x4::Translation(loc,locm);
  652. AssignMatrixAxes(out,x,y,z);
  653. aiVector3D vscale;
  654. if (const IFC::IfcCartesianTransformationOperator3DnonUniform* nuni = op.ToPtr<IFC::IfcCartesianTransformationOperator3DnonUniform>()) {
  655. vscale.x = nuni->Scale?op.Scale.Get():1.f;
  656. vscale.y = nuni->Scale2?nuni->Scale2.Get():1.f;
  657. vscale.z = nuni->Scale3?nuni->Scale3.Get():1.f;
  658. }
  659. else {
  660. const float sc = op.Scale?op.Scale.Get():1.f;
  661. vscale = aiVector3D(sc,sc,sc);
  662. }
  663. aiMatrix4x4 s;
  664. aiMatrix4x4::Scaling(vscale,s);
  665. out = locm * out * s;
  666. }
  667. // ------------------------------------------------------------------------------------------------
  668. bool ProcessPolyloop(const IFC::IfcPolyLoop& loop, TempMesh& meshout, ConversionData& conv)
  669. {
  670. size_t cnt = 0;
  671. BOOST_FOREACH(const IFC::IfcCartesianPoint& c, loop.Polygon) {
  672. aiVector3D tmp;
  673. ConvertCartesianPoint(tmp,c);
  674. meshout.verts.push_back(tmp);
  675. ++cnt;
  676. }
  677. meshout.vertcnt.push_back(cnt);
  678. // zero- or one- vertex polyloops simply ignored
  679. if (meshout.vertcnt.back() > 1) {
  680. return true;
  681. }
  682. if (meshout.vertcnt.back()==1) {
  683. meshout.vertcnt.pop_back();
  684. meshout.verts.pop_back();
  685. }
  686. return false;
  687. }
  688. // ------------------------------------------------------------------------------------------------
  689. void ComputePolygonNormals(const TempMesh& meshout, std::vector<aiVector3D>& normals, bool normalize = true, size_t ofs = 0)
  690. {
  691. size_t max_vcount = 0;
  692. std::vector<unsigned int>::const_iterator begin=meshout.vertcnt.begin()+ofs, end=meshout.vertcnt.end(), iit;
  693. for(iit = begin; iit != end; ++iit) {
  694. max_vcount = std::max(max_vcount,static_cast<size_t>(*iit));
  695. }
  696. std::vector<float> temp((max_vcount+2)*4);
  697. normals.reserve( normals.size() + meshout.vertcnt.size()-ofs );
  698. // `NewellNormal()` currently has a relatively strange interface and need to
  699. // re-structure things a bit to meet them.
  700. size_t vidx = std::accumulate(meshout.vertcnt.begin(),begin,0);
  701. for(iit = begin; iit != end; vidx += *iit++) {
  702. if (!*iit) {
  703. normals.push_back(aiVector3D());
  704. continue;
  705. }
  706. for(size_t vofs = 0, cnt = 0; vofs < *iit; ++vofs) {
  707. const aiVector3D& v = meshout.verts[vidx+vofs];
  708. temp[cnt++] = v.x;
  709. temp[cnt++] = v.y;
  710. temp[cnt++] = v.z;
  711. #ifdef _DEBUG
  712. temp[cnt] = std::numeric_limits<float>::quiet_NaN();
  713. #endif
  714. ++cnt;
  715. }
  716. normals.push_back(aiVector3D());
  717. NewellNormal<4,4,4>(normals.back(),*iit,&temp[0],&temp[1],&temp[2]);
  718. }
  719. if(normalize) {
  720. BOOST_FOREACH(aiVector3D& n, normals) {
  721. n.Normalize();
  722. }
  723. }
  724. }
  725. // ------------------------------------------------------------------------------------------------
  726. // Compute the normal of the last polygon in the given mesh
  727. aiVector3D ComputePolygonNormal(const TempMesh& inmesh, bool normalize = true)
  728. {
  729. size_t total = inmesh.vertcnt.back(), vidx = inmesh.verts.size() - total;
  730. std::vector<float> temp((total+2)*3);
  731. for(size_t vofs = 0, cnt = 0; vofs < total; ++vofs) {
  732. const aiVector3D& v = inmesh.verts[vidx+vofs];
  733. temp[cnt++] = v.x;
  734. temp[cnt++] = v.y;
  735. temp[cnt++] = v.z;
  736. }
  737. aiVector3D nor;
  738. NewellNormal<3,3,3>(nor,total,&temp[0],&temp[1],&temp[2]);
  739. return normalize ? nor.Normalize() : nor;
  740. }
  741. // ------------------------------------------------------------------------------------------------
  742. void FixupFaceOrientation(TempMesh& result)
  743. {
  744. const aiVector3D vavg = result.Center();
  745. std::vector<aiVector3D> normals;
  746. ComputePolygonNormals(result,normals);
  747. size_t c = 0, ofs = 0;
  748. BOOST_FOREACH(unsigned int cnt, result.vertcnt) {
  749. if (cnt>2){
  750. const aiVector3D& thisvert = result.verts[c];
  751. if (normals[ofs]*(thisvert-vavg) < 0) {
  752. std::reverse(result.verts.begin()+c,result.verts.begin()+cnt+c);
  753. }
  754. }
  755. c += cnt;
  756. ++ofs;
  757. }
  758. }
  759. // ------------------------------------------------------------------------------------------------
  760. void RecursiveMergeBoundaries(TempMesh& final_result, const TempMesh& in, const TempMesh& boundary, std::vector<aiVector3D>& normals, const aiVector3D& nor_boundary)
  761. {
  762. ai_assert(in.vertcnt.size() >= 1);
  763. ai_assert(boundary.vertcnt.size() == 1);
  764. std::vector<unsigned int>::const_iterator end = in.vertcnt.end(), begin=in.vertcnt.begin(), iit, best_iit;
  765. TempMesh out;
  766. // iterate through all other bounds and find the one for which the shortest connection
  767. // to the outer boundary is actually the shortest possible.
  768. size_t vidx = 0, best_vidx_start = 0;
  769. size_t best_ofs, best_outer = boundary.verts.size();
  770. float best_dist = 1e10;
  771. for(std::vector<unsigned int>::const_iterator iit = begin; iit != end; vidx += *iit++) {
  772. for(size_t vofs = 0; vofs < *iit; ++vofs) {
  773. const aiVector3D& v = in.verts[vidx+vofs];
  774. for(size_t outer = 0; outer < boundary.verts.size(); ++outer) {
  775. const aiVector3D& o = boundary.verts[outer];
  776. const float d = (o-v).SquareLength();
  777. if (d < best_dist) {
  778. best_dist = d;
  779. best_ofs = vofs;
  780. best_outer = outer;
  781. best_iit = iit;
  782. best_vidx_start = vidx;
  783. }
  784. }
  785. }
  786. }
  787. ai_assert(best_outer != boundary.verts.size());
  788. // now that we collected all vertex connections to be added, build the output polygon
  789. const size_t cnt = boundary.verts.size() + *best_iit+2;
  790. out.verts.reserve(cnt);
  791. for(size_t outer = 0; outer < boundary.verts.size(); ++outer) {
  792. const aiVector3D& o = boundary.verts[outer];
  793. out.verts.push_back(o);
  794. if (outer == best_outer) {
  795. for(size_t i = best_ofs; i < *best_iit; ++i) {
  796. out.verts.push_back(in.verts[best_vidx_start + i]);
  797. }
  798. // we need the first vertex of the inner polygon twice as we return to the
  799. // outer loop through the very same connection through which we got there.
  800. for(size_t i = 0; i <= best_ofs; ++i) {
  801. out.verts.push_back(in.verts[best_vidx_start + i]);
  802. }
  803. // reverse face winding if the normal of the sub-polygon points in the
  804. // same direction as the normal of the outer polygonal boundary
  805. if (normals[std::distance(begin,best_iit)] * nor_boundary > 0) {
  806. std::reverse(out.verts.rbegin(),out.verts.rbegin()+*best_iit+1);
  807. }
  808. // also append a copy of the initial insertion point to be able to continue the outer polygon
  809. out.verts.push_back(o);
  810. }
  811. }
  812. out.vertcnt.push_back(cnt);
  813. ai_assert(out.verts.size() == cnt);
  814. if (in.vertcnt.size()-std::count(begin,end,0) > 1) {
  815. // Recursively apply the same algorithm if there are more boundaries to merge. The
  816. // current implementation is relatively inefficient, though.
  817. TempMesh temp;
  818. // drop the boundary that we just processed
  819. const size_t dist = std::distance(begin, best_iit);
  820. TempMesh remaining = in;
  821. remaining.vertcnt.erase(remaining.vertcnt.begin() + dist);
  822. remaining.verts.erase(remaining.verts.begin()+best_vidx_start,remaining.verts.begin()+best_vidx_start+*best_iit);
  823. normals.erase(normals.begin() + dist);
  824. RecursiveMergeBoundaries(temp,remaining,out,normals,nor_boundary);
  825. final_result.Append(temp);
  826. }
  827. else final_result.Append(out);
  828. }
  829. // ------------------------------------------------------------------------------------------------
  830. void MergePolygonBoundaries(TempMesh& result, const TempMesh& inmesh, size_t master_bounds = -1)
  831. {
  832. // standard case - only one boundary, just copy it to the result vector
  833. if (inmesh.vertcnt.size() <= 1) {
  834. result.Append(inmesh);
  835. return;
  836. }
  837. result.vertcnt.reserve(inmesh.vertcnt.size()+result.vertcnt.size());
  838. // XXX get rid of the extra copy if possible
  839. TempMesh meshout = inmesh;
  840. // handle polygons with holes. Our built in triangulation won't handle them as is, but
  841. // the ear cutting algorithm is solid enough to deal with them if we join the inner
  842. // holes with the outer boundaries by dummy connections.
  843. IFCImporter::LogDebug("fixing polygon with holes for triangulation via ear-cutting");
  844. std::vector<unsigned int>::iterator outer_polygon = meshout.vertcnt.end(), begin=meshout.vertcnt.begin(), end=outer_polygon, iit;
  845. // each hole results in two extra vertices
  846. result.verts.reserve(meshout.verts.size()+meshout.vertcnt.size()*2+result.verts.size());
  847. size_t outer_polygon_start = 0;
  848. // do not normalize 'normals', we need the original length for computing the polygon area
  849. std::vector<aiVector3D> normals;
  850. ComputePolygonNormals(meshout,normals,false);
  851. // see if one of the polygons is a IfcFaceOuterBound (in which case `master_bounds` is its index).
  852. // sadly we can't rely on it, the docs say 'At most one of the bounds shall be of the type IfcFaceOuterBound'
  853. float area_outer_polygon = 1e-10f;
  854. if (master_bounds != -1) {
  855. outer_polygon = begin + master_bounds;
  856. outer_polygon_start = std::accumulate(begin,outer_polygon,0);
  857. area_outer_polygon = normals[master_bounds].SquareLength();
  858. }
  859. else {
  860. size_t vidx = 0;
  861. for(iit = begin; iit != meshout.vertcnt.end(); vidx += *iit++) {
  862. // find the polygon with the largest area, it must be the outer bound.
  863. aiVector3D& n = normals[std::distance(begin,iit)];
  864. const float area = n.SquareLength();
  865. if (area > area_outer_polygon) {
  866. area_outer_polygon = area;
  867. outer_polygon = iit;
  868. outer_polygon_start = vidx;
  869. }
  870. }
  871. }
  872. ai_assert(outer_polygon != meshout.vertcnt.end());
  873. std::vector<aiVector3D>& in = meshout.verts;
  874. // skip over extremely small boundaries - this is a workaround to fix cases
  875. // in which the number of holes is so extremely large that the
  876. // triangulation code fails.
  877. #define IFC_VERTICAL_HOLE_SIZE_TRESHOLD 0.000001f
  878. size_t vidx = 0, removed = 0, index = 0;
  879. const float treshold = area_outer_polygon * IFC_VERTICAL_HOLE_SIZE_TRESHOLD;
  880. for(iit = begin; iit != end ;++index) {
  881. const float sqlen = normals[index].SquareLength();
  882. if (sqlen < treshold) {
  883. std::vector<aiVector3D>::iterator inbase = in.begin()+vidx;
  884. in.erase(inbase,inbase+*iit);
  885. outer_polygon_start -= outer_polygon_start>vidx ? *iit : 0;
  886. *iit++ = 0;
  887. ++removed;
  888. IFCImporter::LogDebug("skip small hole below treshold");
  889. }
  890. else {
  891. normals[index] /= sqrt(sqlen);
  892. vidx += *iit++;
  893. }
  894. }
  895. // see if one or more of the hole has a face that lies directly on an outer bound.
  896. // this happens for doors, for example.
  897. vidx = 0;
  898. for(iit = begin; ; vidx += *iit++) {
  899. next_loop:
  900. if (iit == end) {
  901. break;
  902. }
  903. if (iit == outer_polygon) {
  904. continue;
  905. }
  906. for(size_t vofs = 0; vofs < *iit; ++vofs) {
  907. if (!*iit) {
  908. continue;
  909. }
  910. const size_t next = (vofs+1)%*iit;
  911. const aiVector3D& v = in[vidx+vofs], &vnext = in[vidx+next],&vd = (vnext-v).Normalize();
  912. for(size_t outer = 0; outer < *outer_polygon; ++outer) {
  913. const aiVector3D& o = in[outer_polygon_start+outer], &onext = in[outer_polygon_start+(outer+1)%*outer_polygon], &od = (onext-o).Normalize();
  914. if (fabs(vd * od) > 1.f-1e-6f && (onext-v).Normalize() * vd > 1.f-1e-6f && (onext-v)*(o-v) < 0) {
  915. IFCImporter::LogDebug("got an inner hole that lies partly on the outer polygonal boundary, merging them to a single contour");
  916. // in between outer and outer+1 insert all vertices of this loop, then drop the original altogether.
  917. std::vector<aiVector3D> tmp(*iit);
  918. const size_t start = (v-o).SquareLength() > (vnext-o).SquareLength() ? vofs : next;
  919. std::vector<aiVector3D>::iterator inbase = in.begin()+vidx, it = std::copy(inbase+start, inbase+*iit,tmp.begin());
  920. std::copy(inbase, inbase+start,it);
  921. std::reverse(tmp.begin(),tmp.end());
  922. in.insert(in.begin()+outer_polygon_start+(outer+1)%*outer_polygon,tmp.begin(),tmp.end());
  923. vidx += outer_polygon_start<vidx ? *iit : 0;
  924. inbase = in.begin()+vidx;
  925. in.erase(inbase,inbase+*iit);
  926. outer_polygon_start -= outer_polygon_start>vidx ? *iit : 0;
  927. *outer_polygon += tmp.size();
  928. *iit++ = 0;
  929. ++removed;
  930. goto next_loop;
  931. }
  932. }
  933. }
  934. }
  935. if ( meshout.vertcnt.size() - removed <= 1) {
  936. result.Append(meshout);
  937. return;
  938. }
  939. // extract the outer boundary and move it to a separate mesh
  940. TempMesh boundary;
  941. boundary.vertcnt.resize(1,*outer_polygon);
  942. boundary.verts.resize(*outer_polygon);
  943. std::vector<aiVector3D>::iterator b = in.begin()+outer_polygon_start;
  944. std::copy(b,b+*outer_polygon,boundary.verts.begin());
  945. in.erase(b,b+*outer_polygon);
  946. std::vector<aiVector3D>::iterator norit = normals.begin()+std::distance(meshout.vertcnt.begin(),outer_polygon);
  947. const aiVector3D nor_boundary = *norit;
  948. normals.erase(norit);
  949. meshout.vertcnt.erase(outer_polygon);
  950. // keep merging the closest inner boundary with the outer boundary until no more boundaries are left
  951. RecursiveMergeBoundaries(result,meshout,boundary,normals,nor_boundary);
  952. }
  953. // ------------------------------------------------------------------------------------------------
  954. void ProcessConnectedFaceSet(const IFC::IfcConnectedFaceSet& fset, TempMesh& result, ConversionData& conv)
  955. {
  956. BOOST_FOREACH(const IFC::IfcFace& face, fset.CfsFaces) {
  957. size_t ob = -1, cnt = 0;
  958. TempMesh meshout;
  959. BOOST_FOREACH(const IFC::IfcFaceBound& bound, face.Bounds) {
  960. // XXX implement proper merging for polygonal loops
  961. if(const IFC::IfcPolyLoop* const polyloop = bound.Bound->ToPtr<IFC::IfcPolyLoop>()) {
  962. if(ProcessPolyloop(*polyloop, meshout,conv)) {
  963. if(bound.ToPtr<IFC::IfcFaceOuterBound>()) {
  964. ob = cnt;
  965. }
  966. ++cnt;
  967. }
  968. }
  969. else {
  970. IFCImporter::LogWarn("skipping unknown IfcFaceBound entity, type is " + bound.Bound->GetClassName());
  971. continue;
  972. }
  973. /*if(!IsTrue(bound.Orientation)) {
  974. size_t c = 0;
  975. BOOST_FOREACH(unsigned int& c, meshout.vertcnt) {
  976. std::reverse(result.verts.begin() + cnt,result.verts.begin() + cnt + c);
  977. cnt += c;
  978. }
  979. }*/
  980. }
  981. MergePolygonBoundaries(result,meshout);
  982. }
  983. }
  984. // ------------------------------------------------------------------------------------------------
  985. void ProcessPolyLine(const IFC::IfcPolyline& def, TempMesh& meshout, ConversionData& conv)
  986. {
  987. // this won't produce a valid mesh, it just spits out a list of vertices
  988. aiVector3D t;
  989. BOOST_FOREACH(const IFC::IfcCartesianPoint& cp, def.Points) {
  990. ConvertCartesianPoint(t,cp);
  991. meshout.verts.push_back(t);
  992. }
  993. meshout.vertcnt.push_back(meshout.verts.size());
  994. }
  995. // ------------------------------------------------------------------------------------------------
  996. bool ProcessCurve(const IFC::IfcCurve& curve, TempMesh& meshout, ConversionData& conv)
  997. {
  998. if(const IFC::IfcPolyline* poly = curve.ToPtr<IFC::IfcPolyline>()) {
  999. ProcessPolyLine(*poly,meshout,conv);
  1000. }
  1001. else {
  1002. IFCImporter::LogWarn("skipping unknown IfcCurve entity, type is " + curve.GetClassName());
  1003. return false;
  1004. }
  1005. return true;
  1006. }
  1007. // ------------------------------------------------------------------------------------------------
  1008. void ProcessClosedProfile(const IFC::IfcArbitraryClosedProfileDef& def, TempMesh& meshout, ConversionData& conv)
  1009. {
  1010. ProcessCurve(def.OuterCurve,meshout,conv);
  1011. }
  1012. // ------------------------------------------------------------------------------------------------
  1013. void ProcessOpenProfile(const IFC::IfcArbitraryOpenProfileDef& def, TempMesh& meshout, ConversionData& conv)
  1014. {
  1015. ProcessCurve(def.Curve,meshout,conv);
  1016. }
  1017. // ------------------------------------------------------------------------------------------------
  1018. void ProcessParametrizedProfile(const IFC::IfcParameterizedProfileDef& def, TempMesh& meshout, ConversionData& conv)
  1019. {
  1020. if(const IFC::IfcRectangleProfileDef* const cprofile = def.ToPtr<IFC::IfcRectangleProfileDef>()) {
  1021. const float x = cprofile->XDim*0.5f, y = cprofile->YDim*0.5f;
  1022. meshout.verts.reserve(meshout.verts.size()+4);
  1023. meshout.verts.push_back( aiVector3D( x, y, 0.f ));
  1024. meshout.verts.push_back( aiVector3D(-x, y, 0.f ));
  1025. meshout.verts.push_back( aiVector3D(-x,-y, 0.f ));
  1026. meshout.verts.push_back( aiVector3D( x,-y, 0.f ));
  1027. meshout.vertcnt.push_back(4);
  1028. }
  1029. else if( const IFC::IfcCircleProfileDef* const circle = def.ToPtr<IFC::IfcCircleProfileDef>()) {
  1030. if( const IFC::IfcCircleHollowProfileDef* const hollow = def.ToPtr<IFC::IfcCircleHollowProfileDef>()) {
  1031. // TODO
  1032. }
  1033. const size_t segments = 32;
  1034. const float delta = AI_MATH_TWO_PI_F/segments, radius = circle->Radius;
  1035. meshout.verts.reserve(segments);
  1036. float angle = 0.f;
  1037. for(size_t i = 0; i < segments; ++i, angle += delta) {
  1038. meshout.verts.push_back( aiVector3D( cos(angle)*radius, sin(angle)*radius, 0.f ));
  1039. }
  1040. meshout.vertcnt.push_back(segments);
  1041. }
  1042. else {
  1043. IFCImporter::LogWarn("skipping unknown IfcParameterizedProfileDef entity, type is " + def.GetClassName());
  1044. return;
  1045. }
  1046. aiMatrix4x4 trafo;
  1047. ConvertAxisPlacement(trafo, *def.Position,conv);
  1048. meshout.Transform(trafo);
  1049. }
  1050. // ------------------------------------------------------------------------------------------------
  1051. bool ProcessProfile(const IFC::IfcProfileDef& prof, TempMesh& meshout, ConversionData& conv)
  1052. {
  1053. if(const IFC::IfcArbitraryClosedProfileDef* const cprofile = prof.ToPtr<IFC::IfcArbitraryClosedProfileDef>()) {
  1054. ProcessClosedProfile(*cprofile,meshout,conv);
  1055. }
  1056. else if(const IFC::IfcArbitraryOpenProfileDef* const copen = prof.ToPtr<IFC::IfcArbitraryOpenProfileDef>()) {
  1057. ProcessOpenProfile(*copen,meshout,conv);
  1058. }
  1059. else if(const IFC::IfcParameterizedProfileDef* const cparam = prof.ToPtr<IFC::IfcParameterizedProfileDef>()) {
  1060. ProcessParametrizedProfile(*cparam,meshout,conv);
  1061. }
  1062. else {
  1063. IFCImporter::LogWarn("skipping unknown IfcProfileDef entity, type is " + prof.GetClassName());
  1064. return false;
  1065. }
  1066. meshout.RemoveAdjacentDuplicates();
  1067. if (!meshout.vertcnt.size() || meshout.vertcnt.front() <= 1) {
  1068. return false;
  1069. }
  1070. return true;
  1071. }
  1072. // ------------------------------------------------------------------------------------------------
  1073. void ProcessRevolvedAreaSolid(const IFC::IfcRevolvedAreaSolid& solid, TempMesh& result, ConversionData& conv)
  1074. {
  1075. TempMesh meshout;
  1076. // first read the profile description
  1077. if(!ProcessProfile(*solid.SweptArea,meshout,conv) || meshout.verts.size()<=1) {
  1078. return;
  1079. }
  1080. aiVector3D axis, pos;
  1081. ConvertAxisPlacement(axis,pos,solid.Axis,conv);
  1082. aiMatrix4x4 tb0,tb1;
  1083. aiMatrix4x4::Translation(pos,tb0);
  1084. aiMatrix4x4::Translation(-pos,tb1);
  1085. const std::vector<aiVector3D>& in = meshout.verts;
  1086. const size_t size=in.size();
  1087. bool has_area = solid.SweptArea->ProfileType == "AREA" && size>2;
  1088. const float max_angle = solid.Angle*conv.angle_scale;
  1089. if(fabs(max_angle) < 1e-3) {
  1090. if(has_area) {
  1091. result = meshout;
  1092. }
  1093. return;
  1094. }
  1095. const unsigned int cnt_segments = std::max(2u,static_cast<unsigned int>(16 * fabs(max_angle)/AI_MATH_HALF_PI_F));
  1096. const float delta = max_angle/cnt_segments;
  1097. has_area = has_area && fabs(max_angle) < AI_MATH_TWO_PI_F*0.99;
  1098. result.verts.reserve(size*((cnt_segments+1)*4+(has_area?2:0)));
  1099. result.vertcnt.reserve(size*cnt_segments+2);
  1100. aiMatrix4x4 rot;
  1101. rot = tb0 * aiMatrix4x4::Rotation(delta,axis,rot) * tb1;
  1102. size_t base = 0;
  1103. std::vector<aiVector3D>& out = result.verts;
  1104. // dummy data to simplify later processing
  1105. for(size_t i = 0; i < size; ++i) {
  1106. out.insert(out.end(),4,in[i]);
  1107. }
  1108. for(unsigned int seg = 0; seg < cnt_segments; ++seg) {
  1109. for(size_t i = 0; i < size; ++i) {
  1110. const size_t next = (i+1)%size;
  1111. result.vertcnt.push_back(4);
  1112. const aiVector3D& base_0 = out[base+i*4+3],base_1 = out[base+next*4+3];
  1113. out.push_back(base_0);
  1114. out.push_back(base_1);
  1115. out.push_back(rot*base_1);
  1116. out.push_back(rot*base_0);
  1117. }
  1118. base += size*4;
  1119. }
  1120. out.erase(out.begin(),out.begin()+size*4);
  1121. if(has_area) {
  1122. // leave the triangulation of the profile area to the ear cutting
  1123. // implementation in aiProcess_Triangulate - for now we just
  1124. // feed in two huge polygons.
  1125. base -= size*8;
  1126. for(size_t i = size; i--; ) {
  1127. out.push_back(out[base+i*4+3]);
  1128. }
  1129. for(size_t i = 0; i < size; ++i ) {
  1130. out.push_back(out[i*4]);
  1131. }
  1132. result.vertcnt.push_back(size);
  1133. result.vertcnt.push_back(size);
  1134. }
  1135. aiMatrix4x4 trafo;
  1136. ConvertAxisPlacement(trafo, solid.Position,conv);
  1137. result.Transform(trafo);
  1138. IFCImporter::LogDebug("generate mesh procedurally by radial extrusion (IfcRevolvedAreaSolid)");
  1139. }
  1140. // ------------------------------------------------------------------------------------------------
  1141. bool TryAddOpenings(const std::vector<TempOpening>& openings,const std::vector<aiVector3D>& nors, TempMesh& curmesh)
  1142. {
  1143. std::vector<aiVector3D>& out = curmesh.verts;
  1144. const size_t s = out.size();
  1145. const aiVector3D any_point = out[s-1];
  1146. const aiVector3D nor = ComputePolygonNormal(curmesh); ;
  1147. bool got_openings = false;
  1148. TempMesh res;
  1149. size_t c = 0;
  1150. BOOST_FOREACH(const TempOpening& t,openings) {
  1151. const aiVector3D& outernor = nors[c++];
  1152. const float dot = nor * outernor;
  1153. if (fabs(dot)<1.f-1e-6f) {
  1154. continue;
  1155. }
  1156. const aiVector3D diff = t.extrusionDir;
  1157. const std::vector<aiVector3D>& va = t.profileMesh->verts;
  1158. if(va.size() <= 2) {
  1159. continue;
  1160. }
  1161. const float dd = t.extrusionDir*nor;
  1162. IFCImporter::LogDebug("apply an IfcOpeningElement linked via IfcRelVoidsElement to this polygon");
  1163. got_openings = true;
  1164. // project va[i] onto the plane formed by the current polygon [given by (any_point,nor)]
  1165. for(size_t i = 0; i < va.size(); ++i) {
  1166. const aiVector3D& v = va[i];
  1167. out.push_back(v-(nor*(v-any_point))*nor);
  1168. }
  1169. curmesh.vertcnt.push_back(va.size());
  1170. res.Clear();
  1171. MergePolygonBoundaries(res,curmesh,0);
  1172. curmesh = res;
  1173. }
  1174. return got_openings;
  1175. }
  1176. // ------------------------------------------------------------------------------------------------
  1177. struct DistanceSorter {
  1178. DistanceSorter(const aiVector3D& base) : base(base) {}
  1179. bool operator () (const TempOpening& a, const TempOpening& b) const {
  1180. return (a.profileMesh->Center()-base).SquareLength() < (b.profileMesh->Center()-base).SquareLength();
  1181. }
  1182. aiVector3D base;
  1183. };
  1184. // ------------------------------------------------------------------------------------------------
  1185. struct XYSorter {
  1186. // sort first by X coordinates, then by Y coordinates
  1187. bool operator () (const aiVector2D&a, const aiVector2D& b) const {
  1188. if (a.x == b.x) {
  1189. return a.y < b.y;
  1190. }
  1191. return a.x < b.x;
  1192. }
  1193. };
  1194. // ------------------------------------------------------------------------------------------------
  1195. struct ProjectionInfo {
  1196. unsigned int ac, bc;
  1197. aiVector3D p,u,v;
  1198. };
  1199. typedef std::pair< aiVector2D, aiVector2D > BoundingBox;
  1200. typedef std::map<aiVector2D,size_t,XYSorter> XYSortedField;
  1201. // ------------------------------------------------------------------------------------------------
  1202. aiVector2D ProjectPositionVectorOntoPlane(const aiVector3D& x, const ProjectionInfo& proj)
  1203. {
  1204. const aiVector3D xx = x-proj.p;
  1205. return aiVector2D(xx[proj.ac]/proj.u[proj.ac],xx[proj.bc]/proj.v[proj.bc]);
  1206. }
  1207. // ------------------------------------------------------------------------------------------------
  1208. void QuadrifyPart(const aiVector2D& pmin, const aiVector2D& pmax, XYSortedField& field, const std::vector< BoundingBox >& bbs,
  1209. std::vector<aiVector2D>& out)
  1210. {
  1211. if (!(pmin.x-pmax.x) || !(pmin.y-pmax.y)) {
  1212. return;
  1213. }
  1214. float xs = 1e10, xe = 1e10;
  1215. bool found = false;
  1216. // Search along the x-axis until we find an opening
  1217. XYSortedField::iterator start = field.begin();
  1218. for(; start != field.end(); ++start) {
  1219. const BoundingBox& bb = bbs[(*start).second];
  1220. if (bb.second.x > pmin.x && bb.first.x < pmax.x && bb.second.y > pmin.y && bb.first.y < pmax.y) {
  1221. xs = bb.first.x;
  1222. xe = bb.second.x;
  1223. found = true;
  1224. break;
  1225. }
  1226. }
  1227. xs = std::max(pmin.x,xs);
  1228. xe = std::min(pmax.x,xe);
  1229. if (!found) {
  1230. // the rectangle [pmin,pend] is opaque, fill it
  1231. out.push_back(pmin);
  1232. out.push_back(aiVector2D(pmin.x,pmax.y));
  1233. out.push_back(pmax);
  1234. out.push_back(aiVector2D(pmax.x,pmin.y));
  1235. return;
  1236. }
  1237. if (xs - pmin.x) {
  1238. out.push_back(pmin);
  1239. out.push_back(aiVector2D(pmin.x,pmax.y));
  1240. out.push_back(aiVector2D(xs,pmax.y));
  1241. out.push_back(aiVector2D(xs,pmin.y));
  1242. }
  1243. // search along the y-axis for all openings that overlap xs and our element
  1244. float ylast = pmin.y;
  1245. found = false;
  1246. for(; start != field.end(); ++start) {
  1247. const BoundingBox& bb = bbs[(*start).second];
  1248. if (bb.second.y > ylast && bb.first.y < pmax.y) {
  1249. found = true;
  1250. const float ys = std::max(bb.first.y,pmin.y), ye = std::min(bb.second.y,pmax.y);
  1251. if (ys - ylast) {
  1252. // Divide et impera!
  1253. QuadrifyPart( aiVector2D(xs,ylast), aiVector2D(xe,ys) ,field,bbs,out);
  1254. }
  1255. // the following are the window vertices
  1256. /*wnd.push_back(aiVector2D(xs,ys));
  1257. wnd.push_back(aiVector2D(xs,ye));
  1258. wnd.push_back(aiVector2D(xe,ye));
  1259. wnd.push_back(aiVector2D(xe,ys));*/
  1260. ylast = ye;
  1261. }
  1262. if (bb.first.x > xs) {
  1263. break;
  1264. }
  1265. }
  1266. if (!found) {
  1267. // the rectangle [pmin,pend] is opaque, fill it
  1268. out.push_back(aiVector2D(xs,pmin.y));
  1269. out.push_back(aiVector2D(xs,pmax.y));
  1270. out.push_back(aiVector2D(xe,pmax.y));
  1271. out.push_back(aiVector2D(xe,pmin.y));
  1272. return;
  1273. }
  1274. if (ylast < pmax.y) {
  1275. // Divide et impera!
  1276. QuadrifyPart( aiVector2D(xs,ylast), aiVector2D(xe,pmax.y) ,field,bbs,out);
  1277. }
  1278. // Divide et impera! - now for the whole rest
  1279. if (pmax.x-xe) {
  1280. QuadrifyPart(aiVector2D(xe,pmin.y), pmax ,field,bbs,out);
  1281. }
  1282. }
  1283. // ------------------------------------------------------------------------------------------------
  1284. enum Intersect {
  1285. Intersect_No,
  1286. Intersect_LiesOnPlane,
  1287. Intersect_Yes
  1288. };
  1289. // ------------------------------------------------------------------------------------------------
  1290. Intersect IntersectSegmentPlane(const aiVector3D& p,const aiVector3D& n, const aiVector3D& e0, const aiVector3D& e1, aiVector3D& out)
  1291. {
  1292. const aiVector3D pdelta = e0 - p, seg = e1-e0;
  1293. const float dotOne = n*seg, dotTwo = -(n*pdelta);
  1294. if (fabs(dotOne) < 1e-6) {
  1295. return fabs(dotTwo) < 1e-6f ? Intersect_LiesOnPlane : Intersect_No;
  1296. }
  1297. const float t = dotTwo/dotOne;
  1298. // t must be in [0..1] if the intersection point is within the given segment
  1299. if (t > 1.f || t < 0.f) {
  1300. return Intersect_No;
  1301. }
  1302. out = e0+t*seg;
  1303. return Intersect_Yes;
  1304. }
  1305. // ------------------------------------------------------------------------------------------------
  1306. aiVector3D Unproject(const aiVector2D& vproj, const ProjectionInfo& proj)
  1307. {
  1308. return vproj.x*proj.u + vproj.y*proj.v + proj.p;
  1309. }
  1310. // ------------------------------------------------------------------------------------------------
  1311. void InsertWindowContours(const std::vector< BoundingBox >& bbs,const std::vector< std::vector<aiVector2D> >& contours,const ProjectionInfo& proj, TempMesh& curmesh)
  1312. {
  1313. ai_assert(contours.size() == bbs.size());
  1314. // fix windows - we need to insert the real, polygonal shapes into the quadratic holes that we have now
  1315. for(size_t i = 0; i < contours.size();++i) {
  1316. const BoundingBox& bb = bbs[i];
  1317. const std::vector<aiVector2D>& contour = contours[i];
  1318. // check if we need to do it at all - many windows just fit perfectly into their quadratic holes,
  1319. // i.e. their contours *are* already their bounding boxes.
  1320. if (contour.size() == 4) {
  1321. std::set<aiVector2D,XYSorter> verts;
  1322. for(size_t n = 0; n < 4; ++n) {
  1323. verts.insert(contour[n]);
  1324. }
  1325. const std::set<aiVector2D,XYSorter>::const_iterator end = verts.end();
  1326. if (verts.find(bb.first)!=end && verts.find(bb.second)!=end
  1327. && verts.find(aiVector2D(bb.first.x,bb.second.y))!=end
  1328. && verts.find(aiVector2D(bb.second.x,bb.first.y))!=end
  1329. ) {
  1330. continue;
  1331. }
  1332. }
  1333. const float epsilon = (bb.first-bb.second).Length()/1000.f;
  1334. // walk through all contour points and find those that lie on the BB corner
  1335. size_t last_hit = -1, very_first_hit = -1;
  1336. aiVector2D edge;
  1337. for(size_t n = 0, e=0, size = contour.size();; n=(n+1)%size, ++e) {
  1338. // sanity checking
  1339. if (e == size*2) {
  1340. IFCImporter::LogError("encountered unexpected topology while generating window contour");
  1341. break;
  1342. }
  1343. const aiVector2D& v = contour[n];
  1344. bool hit = false;
  1345. if (fabs(v.x-bb.first.x)<epsilon) {
  1346. edge.x = bb.first.x;
  1347. hit = true;
  1348. }
  1349. else if (fabs(v.x-bb.second.x)<epsilon) {
  1350. edge.x = bb.second.x;
  1351. hit = true;
  1352. }
  1353. if (fabs(v.y-bb.first.y)<epsilon) {
  1354. edge.y = bb.first.y;
  1355. hit = true;
  1356. }
  1357. else if (fabs(v.y-bb.second.y)<epsilon) {
  1358. edge.y = bb.second.y;
  1359. hit = true;
  1360. }
  1361. if (hit) {
  1362. if (last_hit != -1) {
  1363. const size_t old = curmesh.verts.size();
  1364. size_t cnt = last_hit > n ? size-(last_hit-n) : n-last_hit;
  1365. for(size_t a = last_hit, e = 0; e <= cnt; a=(a+1)%size, ++e) {
  1366. curmesh.verts.push_back(Unproject(contour[a],proj));
  1367. }
  1368. if (edge != contour[last_hit] && edge != contour[n]) {
  1369. curmesh.verts.push_back(Unproject(edge,proj));
  1370. }
  1371. else if (cnt == 1) {
  1372. // avoid degenerate polygons (also known as lines or points)
  1373. curmesh.verts.erase(curmesh.verts.begin()+old,curmesh.verts.end());
  1374. }
  1375. if (const size_t d = curmesh.verts.size()-old) {
  1376. curmesh.vertcnt.push_back(d);
  1377. std::reverse(curmesh.verts.rbegin(),curmesh.verts.rbegin()+d);
  1378. }
  1379. if (n == very_first_hit) {
  1380. break;
  1381. }
  1382. }
  1383. else {
  1384. very_first_hit = n;
  1385. }
  1386. last_hit = n;
  1387. }
  1388. }
  1389. }
  1390. }
  1391. // ------------------------------------------------------------------------------------------------
  1392. bool TryAddOpenings_Quadrulate(const std::vector<TempOpening>& openings,const std::vector<aiVector3D>& nors, TempMesh& curmesh)
  1393. {
  1394. std::vector<aiVector3D>& out = curmesh.verts;
  1395. // Try to derive a solid base plane within the current surface for use as
  1396. // working coordinate system.
  1397. aiVector3D vmin,vmax;
  1398. ArrayBounds(&out[0],out.size(),vmin,vmax);
  1399. const size_t s = out.size();
  1400. const aiVector3D any_point = out[s-4];
  1401. const aiVector3D nor = ((out[s-3]-any_point)^(out[s-2]-any_point)).Normalize();
  1402. const aiVector3D diag = vmax-vmin, diagn = aiVector3D(diag).Normalize();
  1403. const float ax = fabs(nor.x);
  1404. const float ay = fabs(nor.y);
  1405. const float az = fabs(nor.z);
  1406. unsigned int ac = 0, bc = 1; /* no z coord. -> projection to xy */
  1407. if (ax > ay) {
  1408. if (ax > az) { /* no x coord. -> projection to yz */
  1409. ac = 1; bc = 2;
  1410. }
  1411. }
  1412. else if (ay > az) { /* no y coord. -> projection to zy */
  1413. ac = 2; bc = 0;
  1414. }
  1415. ProjectionInfo proj;
  1416. proj.u = proj.v = diag;
  1417. proj.u[bc]=0;
  1418. proj.v[ac]=0;
  1419. proj.ac = ac;
  1420. proj.bc = bc;
  1421. proj.p = vmin;
  1422. // project all points into the coordinate system defined by the p+sv*tu plane
  1423. // and compute bounding boxes for them
  1424. std::vector< BoundingBox > bbs;
  1425. XYSortedField field;
  1426. std::vector<aiVector2D> contour_flat;
  1427. contour_flat.reserve(out.size());
  1428. BOOST_FOREACH(const aiVector3D& x, out) {
  1429. contour_flat.push_back(ProjectPositionVectorOntoPlane(x,proj));
  1430. }
  1431. std::vector< std::vector<aiVector2D> > contours;
  1432. size_t c = 0;
  1433. BOOST_FOREACH(const TempOpening& t,openings) {
  1434. const aiVector3D& outernor = nors[c++];
  1435. const float dot = nor * outernor;
  1436. if (fabs(dot)<1.f-1e-6f) {
  1437. continue;
  1438. }
  1439. const aiVector3D diff = t.extrusionDir;
  1440. const std::vector<aiVector3D>& va = t.profileMesh->verts;
  1441. if(va.size() <= 2) {
  1442. continue;
  1443. }
  1444. aiVector2D vpmin,vpmax;
  1445. MinMaxChooser<aiVector2D>()(vpmin,vpmax);
  1446. contours.push_back(std::vector<aiVector2D>());
  1447. std::vector<aiVector2D>& contour = contours.back();
  1448. BOOST_FOREACH(const aiVector3D& x, t.profileMesh->verts) {
  1449. const aiVector2D& vproj = ProjectPositionVectorOntoPlane(x,proj);
  1450. vpmin = std::min(vpmin,vproj);
  1451. vpmax = std::max(vpmax,vproj);
  1452. contour.push_back(vproj);
  1453. }
  1454. if (field.find(vpmin) != field.end()) {
  1455. IFCImporter::LogWarn("constraint failure during generation of wall openings, results may be faulty");
  1456. }
  1457. field[vpmin] = bbs.size();
  1458. bbs.push_back(BoundingBox(vpmin,vpmax));
  1459. }
  1460. if (bbs.empty()) {
  1461. return false;
  1462. }
  1463. std::vector<aiVector2D> outflat;
  1464. outflat.reserve(openings.size()*4);
  1465. QuadrifyPart(aiVector2D(0.f,0.f),aiVector2D(1.f,1.f),field,bbs,outflat);
  1466. ai_assert(!(outflat.size() % 4));
  1467. //FixOuterBoundaries(outflat,contour_flat);
  1468. // undo the projection, generate output quads
  1469. std::vector<aiVector3D> vold;
  1470. vold.reserve(outflat.size());
  1471. std::swap(vold,curmesh.verts);
  1472. std::vector<unsigned int> iold;
  1473. iold.resize(outflat.size()/4,4);
  1474. std::swap(iold,curmesh.vertcnt);
  1475. BOOST_FOREACH(const aiVector2D& vproj, outflat) {
  1476. out.push_back(Unproject(vproj,proj));
  1477. }
  1478. InsertWindowContours(bbs,contours,proj,curmesh);
  1479. return true;
  1480. }
  1481. // ------------------------------------------------------------------------------------------------
  1482. void ProcessExtrudedAreaSolid(const IFC::IfcExtrudedAreaSolid& solid, TempMesh& result, ConversionData& conv)
  1483. {
  1484. TempMesh meshout;
  1485. // first read the profile description
  1486. if(!ProcessProfile(*solid.SweptArea,meshout,conv) || meshout.verts.size()<=1) {
  1487. return;
  1488. }
  1489. aiVector3D dir;
  1490. ConvertDirection(dir,solid.ExtrudedDirection);
  1491. dir *= solid.Depth;
  1492. // assuming that `meshout.verts` is now a list of vertex points forming
  1493. // the underlying profile, extrude along the given axis, forming new
  1494. // triangles.
  1495. std::vector<aiVector3D>& in = meshout.verts;
  1496. const size_t size=in.size();
  1497. const bool has_area = solid.SweptArea->ProfileType == "AREA" && size>2;
  1498. if(solid.Depth < 1e-3) {
  1499. if(has_area) {
  1500. meshout = result;
  1501. }
  1502. return;
  1503. }
  1504. result.verts.reserve(size*(has_area?4:2));
  1505. result.vertcnt.reserve(meshout.vertcnt.size()+2);
  1506. // transform to target space
  1507. aiMatrix4x4 trafo;
  1508. ConvertAxisPlacement(trafo, solid.Position,conv);
  1509. BOOST_FOREACH(aiVector3D& v,in) {
  1510. v *= trafo;
  1511. }
  1512. aiVector3D min = in[0];
  1513. dir *= aiMatrix3x3(trafo);
  1514. std::vector<aiVector3D> nors;
  1515. // compute the normal vectors for all opening polygons
  1516. if (conv.apply_openings) {
  1517. if (!conv.settings.useCustomTriangulation) {
  1518. // it is essential to apply the openings in the correct spatial order. The direction
  1519. // doesn't matter, but we would screw up if we started with e.g. a door in between
  1520. // two windows.
  1521. std::sort(conv.apply_openings->begin(),conv.apply_openings->end(),DistanceSorter(min));
  1522. }
  1523. nors.reserve(conv.apply_openings->size());
  1524. BOOST_FOREACH(TempOpening& t,*conv.apply_openings) {
  1525. TempMesh& bounds = *t.profileMesh.get();
  1526. if (bounds.verts.size() <= 2) {
  1527. nors.push_back(aiVector3D());
  1528. continue;
  1529. }
  1530. nors.push_back(((bounds.verts[2]-bounds.verts[0])^(bounds.verts[1]-bounds.verts[0]) ).Normalize());
  1531. }
  1532. }
  1533. TempMesh temp;
  1534. TempMesh& curmesh = conv.apply_openings ? temp : result;
  1535. std::vector<aiVector3D>& out = curmesh.verts;
  1536. bool (* const gen_openings)(const std::vector<TempOpening>&,const std::vector<aiVector3D>&, TempMesh&) = conv.settings.useCustomTriangulation
  1537. ? &TryAddOpenings_Quadrulate
  1538. : &TryAddOpenings;
  1539. size_t sides_with_openings = 0;
  1540. for(size_t i = 0; i < size; ++i) {
  1541. const size_t next = (i+1)%size;
  1542. curmesh.vertcnt.push_back(4);
  1543. out.push_back(in[i]);
  1544. out.push_back(in[i]+dir);
  1545. out.push_back(in[next]+dir);
  1546. out.push_back(in[next]);
  1547. if(conv.apply_openings) {
  1548. if(gen_openings(*conv.apply_openings,nors,temp)) {
  1549. ++sides_with_openings;
  1550. }
  1551. result.Append(temp);
  1552. temp.Clear();
  1553. }
  1554. }
  1555. size_t sides_with_v_openings = 0;
  1556. if(has_area) {
  1557. for(size_t n = 0; n < 2; ++n) {
  1558. for(size_t i = size; i--; ) {
  1559. out.push_back(in[i]+(n?dir:aiVector3D()));
  1560. }
  1561. curmesh.vertcnt.push_back(size);
  1562. if(conv.apply_openings && size > 2) {
  1563. // XXX here we are forced to use the un-triangulated version of TryAddOpening, with
  1564. // all the problems it causes. The reason is that vertical walls (ehm, floors)
  1565. // can have an arbitrary outer shape, so the usual approach of projecting
  1566. // the surface and all openings onto a flat quad and triangulating the quad
  1567. // fails.
  1568. if(TryAddOpenings(*conv.apply_openings,nors,temp)) {
  1569. ++sides_with_v_openings;
  1570. }
  1571. result.Append(temp);
  1572. temp.Clear();
  1573. }
  1574. }
  1575. }
  1576. // add connection geometry to close the 'holes' for the openings
  1577. if(conv.apply_openings) {
  1578. //result.infacing.resize(result.verts.size()+);
  1579. BOOST_FOREACH(const TempOpening& t,*conv.apply_openings) {
  1580. const std::vector<aiVector3D>& in = t.profileMesh->verts;
  1581. std::vector<aiVector3D>& out = result.verts;
  1582. const aiVector3D dir = t.extrusionDir;
  1583. for(size_t i = 0, size = in.size(); i < size; ++i) {
  1584. const size_t next = (i+1)%size;
  1585. result.vertcnt.push_back(4);
  1586. out.push_back(in[i]);
  1587. out.push_back(in[i]+dir);
  1588. out.push_back(in[next]+dir);
  1589. out.push_back(in[next]);
  1590. }
  1591. }
  1592. }
  1593. if(conv.apply_openings && (sides_with_openings != 2 && sides_with_openings || sides_with_v_openings != 2 && sides_with_v_openings)) {
  1594. IFCImporter::LogWarn("failed to resolve all openings, presumably their topology is not supported by Assimp");
  1595. }
  1596. IFCImporter::LogDebug("generate mesh procedurally by extrusion (IfcExtrudedAreaSolid)");
  1597. }
  1598. // ------------------------------------------------------------------------------------------------
  1599. void ProcessSweptAreaSolid(const IFC::IfcSweptAreaSolid& swept, TempMesh& meshout, ConversionData& conv)
  1600. {
  1601. if(const IFC::IfcExtrudedAreaSolid* const solid = swept.ToPtr<IFC::IfcExtrudedAreaSolid>()) {
  1602. // Do we just collect openings for a parent element (i.e. a wall)?
  1603. // In this case we don't extrude the surface yet, just keep the profile and transform it correctly
  1604. if(conv.collect_openings) {
  1605. boost::shared_ptr<TempMesh> meshtmp(new TempMesh());
  1606. ProcessProfile(swept.SweptArea,*meshtmp,conv);
  1607. aiMatrix4x4 m;
  1608. ConvertAxisPlacement(m,solid->Position,conv);
  1609. meshtmp->Transform(m);
  1610. aiVector3D dir;
  1611. ConvertDirection(dir,solid->ExtrudedDirection);
  1612. conv.collect_openings->push_back(TempOpening(solid, aiMatrix3x3(m) * (dir*solid->Depth),meshtmp));
  1613. return;
  1614. }
  1615. ProcessExtrudedAreaSolid(*solid,meshout,conv);
  1616. }
  1617. else if(const IFC::IfcRevolvedAreaSolid* const rev = swept.ToPtr<IFC::IfcRevolvedAreaSolid>()) {
  1618. ProcessRevolvedAreaSolid(*rev,meshout,conv);
  1619. }
  1620. else {
  1621. IFCImporter::LogWarn("skipping unknown IfcSweptAreaSolid entity, type is " + swept.GetClassName());
  1622. }
  1623. }
  1624. // ------------------------------------------------------------------------------------------------
  1625. void ProcessBoolean(const IFC::IfcBooleanResult& boolean, TempMesh& result, ConversionData& conv)
  1626. {
  1627. if(const IFC::IfcBooleanClippingResult* const clip = boolean.ToPtr<IFC::IfcBooleanClippingResult>()) {
  1628. if(clip->Operator != "DIFFERENCE") {
  1629. IFCImporter::LogWarn("encountered unsupported boolean operator: " + (std::string)clip->Operator);
  1630. return;
  1631. }
  1632. TempMesh meshout;
  1633. const IFC::IfcHalfSpaceSolid* const hs = clip->SecondOperand->ResolveSelectPtr<IFC::IfcHalfSpaceSolid>(conv.db);
  1634. if(!hs) {
  1635. IFCImporter::LogError("expected IfcHalfSpaceSolid as second clipping operand");
  1636. return;
  1637. }
  1638. const IFC::IfcPlane* const plane = hs->BaseSurface->ToPtr<IFC::IfcPlane>();
  1639. if(!plane) {
  1640. IFCImporter::LogError("expected IfcPlane as base surface for the IfcHalfSpaceSolid");
  1641. return;
  1642. }
  1643. if(const IFC::IfcBooleanResult* const op0 = clip->FirstOperand->ResolveSelectPtr<IFC::IfcBooleanResult>(conv.db)) {
  1644. ProcessBoolean(*op0,meshout,conv);
  1645. }
  1646. else if (const IFC::IfcSweptAreaSolid* const swept = clip->FirstOperand->ResolveSelectPtr<IFC::IfcSweptAreaSolid>(conv.db)) {
  1647. ProcessSweptAreaSolid(*swept,meshout,conv);
  1648. }
  1649. else {
  1650. IFCImporter::LogError("expected IfcSweptAreaSolid or IfcBooleanResult as first clipping operand");
  1651. return;
  1652. }
  1653. // extract plane base position vector and normal vector
  1654. aiVector3D p,n(0.f,0.f,1.f);
  1655. if (plane->Position->Axis) {
  1656. ConvertDirection(n,plane->Position->Axis.Get());
  1657. }
  1658. ConvertCartesianPoint(p,plane->Position->Location);
  1659. if(!IsTrue(hs->AgreementFlag)) {
  1660. n *= -1.f;
  1661. }
  1662. // clip the current contents of `meshout` against the plane we obtained from the second operand
  1663. const std::vector<aiVector3D>& in = meshout.verts;
  1664. std::vector<aiVector3D>& outvert = result.verts;
  1665. std::vector<unsigned int>::const_iterator begin=meshout.vertcnt.begin(), end=meshout.vertcnt.end(), iit;
  1666. outvert.reserve(in.size());
  1667. result.vertcnt.reserve(meshout.vertcnt.size());
  1668. unsigned int vidx = 0;
  1669. for(iit = begin; iit != end; vidx += *iit++) {
  1670. unsigned int newcount = 0;
  1671. for(unsigned int i = 0; i < *iit; ++i) {
  1672. const aiVector3D& e0 = in[vidx+i], e1 = in[vidx+(i+1)%*iit];
  1673. // does the next segment intersect the plane?
  1674. aiVector3D isectpos;
  1675. const Intersect isect = IntersectSegmentPlane(p,n,e0,e1,isectpos);
  1676. if (isect == Intersect_No || isect == Intersect_LiesOnPlane) {
  1677. if ( (e0-p).Normalize()*n > 0 ) {
  1678. outvert.push_back(e0);
  1679. ++newcount;
  1680. }
  1681. }
  1682. else if (isect == Intersect_Yes) {
  1683. if ( (e0-p).Normalize()*n > 0 ) {
  1684. // e0 is on the right side, so keep it
  1685. outvert.push_back(e0);
  1686. outvert.push_back(isectpos);
  1687. newcount += 2;
  1688. }
  1689. else {
  1690. // e0 is on the wrong side, so drop it and keep e1 instead
  1691. outvert.push_back(isectpos);
  1692. ++newcount;
  1693. }
  1694. }
  1695. }
  1696. if (!newcount) {
  1697. continue;
  1698. }
  1699. aiVector3D vmin,vmax;
  1700. ArrayBounds(&*(outvert.end()-newcount),newcount,vmin,vmax);
  1701. // filter our double points - those may happen if a point lies
  1702. // directly on the intersection line. However, due to float
  1703. // precision a bitwise comparison is not feasible to detect
  1704. // this case.
  1705. const float epsilon = (vmax-vmin).SquareLength() / 1e6f;
  1706. FuzzyVectorCompare fz(epsilon);
  1707. std::vector<aiVector3D>::iterator e = std::unique( outvert.end()-newcount, outvert.end(), fz );
  1708. if (e != outvert.end()) {
  1709. newcount -= static_cast<unsigned int>(std::distance(e,outvert.end()));
  1710. outvert.erase(e,outvert.end());
  1711. }
  1712. if (fz(*( outvert.end()-newcount),outvert.back())) {
  1713. outvert.pop_back();
  1714. --newcount;
  1715. }
  1716. if(newcount > 2) {
  1717. result.vertcnt.push_back(newcount);
  1718. }
  1719. else while(newcount-->0)result.verts.pop_back();
  1720. }
  1721. IFCImporter::LogDebug("generating CSG geometry by plane clipping (IfcBooleanClippingResult)");
  1722. }
  1723. else {
  1724. IFCImporter::LogWarn("skipping unknown IfcBooleanResult entity, type is " + boolean.GetClassName());
  1725. }
  1726. }
  1727. // ------------------------------------------------------------------------------------------------
  1728. int ConvertShadingMode(const std::string& name)
  1729. {
  1730. if (name == "BLINN") {
  1731. return aiShadingMode_Blinn;
  1732. }
  1733. else if (name == "FLAT" || name == "NOTDEFINED") {
  1734. return aiShadingMode_NoShading;
  1735. }
  1736. else if (name == "PHONG") {
  1737. return aiShadingMode_Phong;
  1738. }
  1739. IFCImporter::LogWarn("shading mode "+name+" not recognized by Assimp, using Phong instead");
  1740. return aiShadingMode_Phong;
  1741. }
  1742. // ------------------------------------------------------------------------------------------------
  1743. void FillMaterial(MaterialHelper* mat,const IFC::IfcSurfaceStyle* surf,ConversionData& conv)
  1744. {
  1745. aiString name;
  1746. name.Set((surf->Name? surf->Name.Get() : "IfcSurfaceStyle_Unnamed"));
  1747. mat->AddProperty(&name,AI_MATKEY_NAME);
  1748. // now see which kinds of surface information are present
  1749. BOOST_FOREACH(boost::shared_ptr< const IFC::IfcSurfaceStyleElementSelect > sel2, surf->Styles) {
  1750. if (const IFC::IfcSurfaceStyleShading* shade = sel2->ResolveSelectPtr<IFC::IfcSurfaceStyleShading>(conv.db)) {
  1751. aiColor4D col_base,col;
  1752. ConvertColor(col_base, shade->SurfaceColour);
  1753. mat->AddProperty(&col_base,1, AI_MATKEY_COLOR_DIFFUSE);
  1754. if (const IFC::IfcSurfaceStyleRendering* ren = shade->ToPtr<IFC::IfcSurfaceStyleRendering>()) {
  1755. if (ren->Transparency) {
  1756. const float t = 1.f-ren->Transparency.Get();
  1757. mat->AddProperty(&t,1, AI_MATKEY_OPACITY);
  1758. }
  1759. if (ren->DiffuseColour) {
  1760. ConvertColor(col, *ren->DiffuseColour.Get(),conv,&col_base);
  1761. mat->AddProperty(&col,1, AI_MATKEY_COLOR_DIFFUSE);
  1762. }
  1763. if (ren->SpecularColour) {
  1764. ConvertColor(col, *ren->SpecularColour.Get(),conv,&col_base);
  1765. mat->AddProperty(&col,1, AI_MATKEY_COLOR_SPECULAR);
  1766. }
  1767. if (ren->TransmissionColour) {
  1768. ConvertColor(col, *ren->TransmissionColour.Get(),conv,&col_base);
  1769. mat->AddProperty(&col,1, AI_MATKEY_COLOR_TRANSPARENT);
  1770. }
  1771. if (ren->ReflectionColour) {
  1772. ConvertColor(col, *ren->ReflectionColour.Get(),conv,&col_base);
  1773. mat->AddProperty(&col,1, AI_MATKEY_COLOR_REFLECTIVE);
  1774. }
  1775. const int shading = (ren->SpecularHighlight && ren->SpecularColour)?ConvertShadingMode(ren->ReflectanceMethod):aiShadingMode_Gouraud;
  1776. mat->AddProperty(&shading,1, AI_MATKEY_SHADING_MODEL);
  1777. if (ren->SpecularHighlight) {
  1778. if(const EXPRESS::REAL* rt = ren->SpecularHighlight.Get()->ToPtr<EXPRESS::REAL>()) {
  1779. // at this point we don't distinguish between the two distinct ways of
  1780. // specifying highlight intensities. leave this to the user.
  1781. const float e = *rt;
  1782. mat->AddProperty(&e,1,AI_MATKEY_SHININESS);
  1783. }
  1784. else {
  1785. IFCImporter::LogWarn("unexpected type error, SpecularHighlight should be a REAL");
  1786. }
  1787. }
  1788. }
  1789. }
  1790. else if (const IFC::IfcSurfaceStyleWithTextures* tex = sel2->ResolveSelectPtr<IFC::IfcSurfaceStyleWithTextures>(conv.db)) {
  1791. // XXX
  1792. }
  1793. }
  1794. }
  1795. // ------------------------------------------------------------------------------------------------
  1796. unsigned int ProcessMaterials(const IFC::IfcRepresentationItem& item, ConversionData& conv)
  1797. {
  1798. if (conv.materials.empty()) {
  1799. aiString name;
  1800. std::auto_ptr<MaterialHelper> mat(new MaterialHelper());
  1801. name.Set("<IFCDefault>");
  1802. mat->AddProperty(&name,AI_MATKEY_NAME);
  1803. aiColor4D col = aiColor4D(0.6f,0.6f,0.6f,1.0f);
  1804. mat->AddProperty(&col,1, AI_MATKEY_COLOR_DIFFUSE);
  1805. conv.materials.push_back(mat.release());
  1806. }
  1807. STEP::DB::RefMapRange range = conv.db.GetRefs().equal_range(item.GetID());
  1808. for(;range.first != range.second; ++range.first) {
  1809. if(const IFC::IfcStyledItem* const styled = conv.db.GetObject((*range.first).second)->ToPtr<IFC::IfcStyledItem>()) {
  1810. BOOST_FOREACH(const IFC::IfcPresentationStyleAssignment& as, styled->Styles) {
  1811. BOOST_FOREACH(boost::shared_ptr<const IFC::IfcPresentationStyleSelect> sel, as.Styles) {
  1812. if (const IFC::IfcSurfaceStyle* const surf = sel->ResolveSelectPtr<IFC::IfcSurfaceStyle>(conv.db)) {
  1813. const std::string side = static_cast<std::string>(surf->Side);
  1814. if (side != "BOTH") {
  1815. IFCImporter::LogWarn("ignoring surface side marker on IFC::IfcSurfaceStyle: " + side);
  1816. }
  1817. std::auto_ptr<MaterialHelper> mat(new MaterialHelper());
  1818. FillMaterial(mat.get(),surf,conv);
  1819. conv.materials.push_back(mat.release());
  1820. return conv.materials.size()-1;
  1821. }
  1822. }
  1823. }
  1824. }
  1825. }
  1826. return 0;
  1827. }
  1828. // ------------------------------------------------------------------------------------------------
  1829. bool ProcessTopologicalItem(const IFC::IfcTopologicalRepresentationItem& topo, std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  1830. {
  1831. TempMesh meshtmp;
  1832. if(const IFC::IfcConnectedFaceSet* fset = topo.ToPtr<IFC::IfcConnectedFaceSet>()) {
  1833. ProcessConnectedFaceSet(*fset,meshtmp,conv);
  1834. }
  1835. else {
  1836. IFCImporter::LogWarn("skipping unknown IfcTopologicalRepresentationItem entity, type is " + topo.GetClassName());
  1837. return false;
  1838. }
  1839. meshtmp.RemoveAdjacentDuplicates();
  1840. FixupFaceOrientation(meshtmp);
  1841. aiMesh* const mesh = meshtmp.ToMesh();
  1842. if(mesh) {
  1843. mesh->mMaterialIndex = ProcessMaterials(topo,conv);
  1844. mesh_indices.push_back(conv.meshes.size());
  1845. conv.meshes.push_back(mesh);
  1846. return true;
  1847. }
  1848. return false;
  1849. }
  1850. // ------------------------------------------------------------------------------------------------
  1851. bool ProcessGeometricItem(const IFC::IfcGeometricRepresentationItem& geo, std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  1852. {
  1853. TempMesh meshtmp;
  1854. if(const IFC::IfcShellBasedSurfaceModel* shellmod = geo.ToPtr<IFC::IfcShellBasedSurfaceModel>()) {
  1855. BOOST_FOREACH(boost::shared_ptr<const IFC::IfcShell> shell,shellmod->SbsmBoundary) {
  1856. try {
  1857. const EXPRESS::ENTITY& e = shell->To<IFC::ENTITY>();
  1858. const IFC::IfcConnectedFaceSet& fs = conv.db.MustGetObject(e).To<IFC::IfcConnectedFaceSet>();
  1859. ProcessConnectedFaceSet(fs,meshtmp,conv);
  1860. }
  1861. catch(std::bad_cast&) {
  1862. IFCImporter::LogWarn("unexpected type error, IfcShell ought to inherit from IfcConnectedFaceSet");
  1863. }
  1864. }
  1865. }
  1866. else if(const IFC::IfcSweptAreaSolid* swept = geo.ToPtr<IFC::IfcSweptAreaSolid>()) {
  1867. ProcessSweptAreaSolid(*swept,meshtmp,conv);
  1868. }
  1869. else if(const IFC::IfcManifoldSolidBrep* brep = geo.ToPtr<IFC::IfcManifoldSolidBrep>()) {
  1870. ProcessConnectedFaceSet(brep->Outer,meshtmp,conv);
  1871. }
  1872. else if(const IFC::IfcFaceBasedSurfaceModel* surf = geo.ToPtr<IFC::IfcFaceBasedSurfaceModel>()) {
  1873. BOOST_FOREACH(const IFC::IfcConnectedFaceSet& fc, surf->FbsmFaces) {
  1874. ProcessConnectedFaceSet(fc,meshtmp,conv);
  1875. }
  1876. }
  1877. else if(const IFC::IfcBooleanResult* boolean = geo.ToPtr<IFC::IfcBooleanResult>()) {
  1878. ProcessBoolean(*boolean,meshtmp,conv);
  1879. }
  1880. else if(const IFC::IfcBoundingBox* bb = geo.ToPtr<IFC::IfcBoundingBox>()) {
  1881. // silently skip over bounding boxes
  1882. return false;
  1883. }
  1884. else {
  1885. IFCImporter::LogWarn("skipping unknown IfcGeometricRepresentationItem entity, type is " + geo.GetClassName());
  1886. return false;
  1887. }
  1888. meshtmp.RemoveAdjacentDuplicates();
  1889. FixupFaceOrientation(meshtmp);
  1890. aiMesh* const mesh = meshtmp.ToMesh();
  1891. if(mesh) {
  1892. mesh->mMaterialIndex = ProcessMaterials(geo,conv);
  1893. mesh_indices.push_back(conv.meshes.size());
  1894. conv.meshes.push_back(mesh);
  1895. return true;
  1896. }
  1897. return false;
  1898. }
  1899. // ------------------------------------------------------------------------------------------------
  1900. void AssignAddedMeshes(std::vector<unsigned int>& mesh_indices,aiNode* nd,ConversionData& conv)
  1901. {
  1902. if (!mesh_indices.empty()) {
  1903. // make unique
  1904. std::sort(mesh_indices.begin(),mesh_indices.end());
  1905. std::vector<unsigned int>::iterator it_end = std::unique(mesh_indices.begin(),mesh_indices.end());
  1906. const size_t size = std::distance(mesh_indices.begin(),it_end);
  1907. nd->mNumMeshes = size;
  1908. nd->mMeshes = new unsigned int[nd->mNumMeshes];
  1909. for(unsigned int i = 0; i < nd->mNumMeshes; ++i) {
  1910. nd->mMeshes[i] = mesh_indices[i];
  1911. }
  1912. }
  1913. }
  1914. // ------------------------------------------------------------------------------------------------
  1915. bool TryQueryMeshCache(const IFC::IfcRepresentationItem& item, std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  1916. {
  1917. ConversionData::MeshCache::const_iterator it = conv.cached_meshes.find(&item);
  1918. if (it != conv.cached_meshes.end()) {
  1919. std::copy((*it).second.begin(),(*it).second.end(),std::back_inserter(mesh_indices));
  1920. return true;
  1921. }
  1922. return false;
  1923. }
  1924. // ------------------------------------------------------------------------------------------------
  1925. void PopulateMeshCache(const IFC::IfcRepresentationItem& item, const std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  1926. {
  1927. conv.cached_meshes[&item] = mesh_indices;
  1928. }
  1929. // ------------------------------------------------------------------------------------------------
  1930. bool ProcessRepresentationItem(const IFC::IfcRepresentationItem& item, std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  1931. {
  1932. if(const IFC::IfcTopologicalRepresentationItem* const topo = item.ToPtr<IFC::IfcTopologicalRepresentationItem>()) {
  1933. if (!TryQueryMeshCache(item,mesh_indices,conv)) {
  1934. if(ProcessTopologicalItem(*topo,mesh_indices,conv)) {
  1935. if(mesh_indices.size()) {
  1936. PopulateMeshCache(item,mesh_indices,conv);
  1937. }
  1938. }
  1939. else return false;
  1940. }
  1941. return true;
  1942. }
  1943. else if(const IFC::IfcGeometricRepresentationItem* const geo = item.ToPtr<IFC::IfcGeometricRepresentationItem>()) {
  1944. if (!TryQueryMeshCache(item,mesh_indices,conv)) {
  1945. if(ProcessGeometricItem(*geo,mesh_indices,conv)) {
  1946. if(mesh_indices.size()) {
  1947. PopulateMeshCache(item,mesh_indices,conv);
  1948. }
  1949. }
  1950. else return false;
  1951. }
  1952. return true;
  1953. }
  1954. return false;
  1955. }
  1956. // ------------------------------------------------------------------------------------------------
  1957. void ResolveObjectPlacement(aiMatrix4x4& m, const IFC::IfcObjectPlacement& place, ConversionData& conv)
  1958. {
  1959. if (const IFC::IfcLocalPlacement* const local = place.ToPtr<IFC::IfcLocalPlacement>()){
  1960. ConvertAxisPlacement(m, *local->RelativePlacement, conv);
  1961. if (local->PlacementRelTo) {
  1962. aiMatrix4x4 tmp;
  1963. ResolveObjectPlacement(tmp,local->PlacementRelTo.Get(),conv);
  1964. m = tmp * m;
  1965. }
  1966. }
  1967. else {
  1968. IFCImporter::LogWarn("skipping unknown IfcObjectPlacement entity, type is " + place.GetClassName());
  1969. }
  1970. }
  1971. // ------------------------------------------------------------------------------------------------
  1972. void GetAbsTransform(aiMatrix4x4& out, const aiNode* nd, ConversionData& conv)
  1973. {
  1974. aiMatrix4x4 t;
  1975. if (nd->mParent) {
  1976. GetAbsTransform(t,nd->mParent,conv);
  1977. }
  1978. out = t*nd->mTransformation;
  1979. }
  1980. // ------------------------------------------------------------------------------------------------
  1981. void ProcessMappedItem(const IFC::IfcMappedItem& mapped, aiNode* nd_src, std::vector< aiNode* >& subnodes_src, ConversionData& conv)
  1982. {
  1983. // insert a custom node here, the cartesian transform operator is simply a conventional transformation matrix
  1984. std::auto_ptr<aiNode> nd(new aiNode());
  1985. nd->mName.Set("IfcMappedItem");
  1986. // handle the cartesian operator
  1987. aiMatrix4x4 m;
  1988. ConvertTransformOperator(m, *mapped.MappingTarget);
  1989. aiMatrix4x4 msrc;
  1990. ConvertAxisPlacement(msrc,*mapped.MappingSource->MappingOrigin,conv);
  1991. msrc = m*msrc;
  1992. std::vector<unsigned int> meshes;
  1993. const size_t old_openings = conv.collect_openings ? conv.collect_openings->size() : 0;
  1994. if (conv.apply_openings) {
  1995. aiMatrix4x4 minv = msrc;
  1996. minv.Inverse();
  1997. BOOST_FOREACH(TempOpening& open,*conv.apply_openings){
  1998. open.Transform(minv);
  1999. }
  2000. }
  2001. const IFC::IfcRepresentation& repr = mapped.MappingSource->MappedRepresentation;
  2002. BOOST_FOREACH(const IFC::IfcRepresentationItem& item, repr.Items) {
  2003. if(!ProcessRepresentationItem(item,meshes,conv)) {
  2004. IFCImporter::LogWarn("skipping unknown mapped entity, type is " + item.GetClassName());
  2005. }
  2006. }
  2007. AssignAddedMeshes(meshes,nd.get(),conv);
  2008. if (conv.collect_openings) {
  2009. // if this pass serves us only to collect opening geometry,
  2010. // make sure we transform the TempMesh's which we need to
  2011. // preserve as well.
  2012. if(const size_t diff = conv.collect_openings->size() - old_openings) {
  2013. for(size_t i = 0; i < diff; ++i) {
  2014. (*conv.collect_openings)[old_openings+i].Transform(msrc);
  2015. }
  2016. }
  2017. }
  2018. nd->mTransformation = nd_src->mTransformation * msrc;
  2019. subnodes_src.push_back(nd.release());
  2020. }
  2021. // ------------------------------------------------------------------------------------------------
  2022. void ProcessProductRepresentation(const IFC::IfcProduct& el, aiNode* nd, std::vector< aiNode* >& subnodes, ConversionData& conv)
  2023. {
  2024. if(!el.Representation) {
  2025. return;
  2026. }
  2027. if(conv.settings.skipSpaceRepresentations) {
  2028. if(const IFC::IfcSpace* const space = el.ToPtr<IFC::IfcSpace>()) {
  2029. IFCImporter::LogWarn("skipping IfcSpace entity due to importer settings");
  2030. return;
  2031. }
  2032. }
  2033. std::vector<unsigned int> meshes;
  2034. BOOST_FOREACH(const IFC::IfcRepresentation& repr, el.Representation.Get()->Representations) {
  2035. if (conv.settings.skipCurveRepresentations && repr.RepresentationType && repr.RepresentationType.Get() == "Curve2D") {
  2036. IFCImporter::LogWarn("skipping Curve2D representation item due to importer settings");
  2037. continue;
  2038. }
  2039. BOOST_FOREACH(const IFC::IfcRepresentationItem& item, repr.Items) {
  2040. if(const IFC::IfcMappedItem* const geo = item.ToPtr<IFC::IfcMappedItem>()) {
  2041. ProcessMappedItem(*geo,nd,subnodes,conv);
  2042. }
  2043. else {
  2044. ProcessRepresentationItem(item,meshes,conv);
  2045. }
  2046. }
  2047. }
  2048. AssignAddedMeshes(meshes,nd,conv);
  2049. }
  2050. // ------------------------------------------------------------------------------------------------
  2051. aiNode* ProcessSpatialStructure(aiNode* parent, const IFC::IfcProduct& el, ConversionData& conv, std::vector<TempOpening>* collect_openings = NULL)
  2052. {
  2053. const STEP::DB::RefMap& refs = conv.db.GetRefs();
  2054. // add an output node for this spatial structure
  2055. std::auto_ptr<aiNode> nd(new aiNode());
  2056. nd->mName.Set(el.GetClassName()+"_"+(el.Name?el.Name:el.GlobalId));
  2057. nd->mParent = parent;
  2058. if(el.ObjectPlacement) {
  2059. ResolveObjectPlacement(nd->mTransformation,el.ObjectPlacement.Get(),conv);
  2060. }
  2061. std::vector<TempOpening> openings;
  2062. aiMatrix4x4 myInv;
  2063. bool didinv = false;
  2064. // convert everything contained directly within this structure,
  2065. // this may result in more nodes.
  2066. std::vector< aiNode* > subnodes;
  2067. try {
  2068. // locate aggregates and 'contained-in-here'-elements of this spatial structure and add them in recursively
  2069. // on our way, collect openings in *this* element
  2070. STEP::DB::RefMapRange range = refs.equal_range(el.GetID());
  2071. for(STEP::DB::RefMapRange range2 = range; range2.first != range.second; ++range2.first) {
  2072. const STEP::LazyObject& obj = conv.db.MustGetObject((*range2.first).second);
  2073. // handle regularly-contained elements
  2074. if(const IFC::IfcRelContainedInSpatialStructure* const cont = obj->ToPtr<IFC::IfcRelContainedInSpatialStructure>()) {
  2075. BOOST_FOREACH(const IFC::IfcProduct& pro, cont->RelatedElements) {
  2076. if(const IFC::IfcOpeningElement* const open = pro.ToPtr<IFC::IfcOpeningElement>()) {
  2077. // IfcOpeningElement is handled below. Sadly we can't use it here as is:
  2078. // The docs say that opening elements are USUALLY attached to building storeys
  2079. // but we want them for the building elements to which they belong to.
  2080. continue;
  2081. }
  2082. subnodes.push_back( ProcessSpatialStructure(nd.get(),pro,conv,NULL) );
  2083. }
  2084. }
  2085. // handle openings, which we collect in a list rather than adding them to the node graph
  2086. else if(const IFC::IfcRelVoidsElement* const fills = obj->ToPtr<IFC::IfcRelVoidsElement>()) {
  2087. if(fills->RelatingBuildingElement->GetID() == el.GetID()) {
  2088. const IFC::IfcFeatureElementSubtraction& open = fills->RelatedOpeningElement;
  2089. // move opening elements to a separate node since they are semantically different than elements that are just 'contained'
  2090. std::auto_ptr<aiNode> nd_aggr(new aiNode());
  2091. nd_aggr->mName.Set("$RelVoidsElement");
  2092. nd_aggr->mParent = nd.get();
  2093. nd_aggr->mTransformation = nd->mTransformation;
  2094. nd_aggr->mNumChildren = 1;
  2095. nd_aggr->mChildren = new aiNode*[1]();
  2096. std::vector<TempOpening> openings_local;
  2097. nd_aggr->mChildren[0] = ProcessSpatialStructure( nd_aggr.get(),open, conv,&openings_local);
  2098. if(openings_local.size()) {
  2099. if (!didinv) {
  2100. myInv = aiMatrix4x4(nd->mTransformation ).Inverse();
  2101. didinv = true;
  2102. }
  2103. // we need all openings to be in the local space of *this* node, so transform them
  2104. BOOST_FOREACH(TempOpening& op,openings_local) {
  2105. op.Transform( myInv*nd_aggr->mChildren[0]->mTransformation);
  2106. openings.push_back(op);
  2107. }
  2108. }
  2109. subnodes.push_back( nd_aggr.release() );
  2110. }
  2111. }
  2112. }
  2113. for(;range.first != range.second; ++range.first) {
  2114. if(const IFC::IfcRelAggregates* const aggr = conv.db.GetObject((*range.first).second)->ToPtr<IFC::IfcRelAggregates>()) {
  2115. // move aggregate elements to a separate node since they are semantically different than elements that are just 'contained'
  2116. std::auto_ptr<aiNode> nd_aggr(new aiNode());
  2117. nd_aggr->mName.Set("$RelAggregates");
  2118. nd_aggr->mParent = nd.get();
  2119. nd_aggr->mTransformation = nd->mTransformation;
  2120. nd_aggr->mChildren = new aiNode*[aggr->RelatedObjects.size()]();
  2121. BOOST_FOREACH(const IFC::IfcObjectDefinition& def, aggr->RelatedObjects) {
  2122. if(const IFC::IfcProduct* const prod = def.ToPtr<IFC::IfcProduct>()) {
  2123. nd_aggr->mChildren[nd_aggr->mNumChildren++] = ProcessSpatialStructure(nd_aggr.get(),*prod,conv,NULL);
  2124. }
  2125. }
  2126. subnodes.push_back( nd_aggr.release() );
  2127. }
  2128. }
  2129. conv.collect_openings = collect_openings;
  2130. if(!conv.collect_openings) {
  2131. conv.apply_openings = &openings;
  2132. }
  2133. ProcessProductRepresentation(el,nd.get(),subnodes,conv);
  2134. conv.apply_openings = conv.collect_openings = NULL;
  2135. if (subnodes.size()) {
  2136. nd->mChildren = new aiNode*[subnodes.size()]();
  2137. BOOST_FOREACH(aiNode* nd2, subnodes) {
  2138. nd->mChildren[nd->mNumChildren++] = nd2;
  2139. nd2->mParent = nd.get();
  2140. }
  2141. }
  2142. }
  2143. catch(...) {
  2144. // it hurts, but I don't want to pull boost::ptr_vector into -noboost only for these few spots here
  2145. std::for_each(subnodes.begin(),subnodes.end(),delete_fun<aiNode>());
  2146. throw;
  2147. }
  2148. return nd.release();
  2149. }
  2150. // ------------------------------------------------------------------------------------------------
  2151. void ProcessSpatialStructures(ConversionData& conv)
  2152. {
  2153. // XXX add support for multiple sites (i.e. IfcSpatialStructureElements with composition == COMPLEX)
  2154. // process all products in the file. it is reasonable to assume that a
  2155. // file that is relevant for us contains at least a site or a building.
  2156. const STEP::DB::ObjectMapByType& map = conv.db.GetObjectsByType();
  2157. ai_assert(map.find("ifcsite") != map.end());
  2158. const STEP::DB::ObjectSet* range = &map.find("ifcsite")->second;
  2159. if (range->empty()) {
  2160. ai_assert(map.find("ifcbuilding") != map.end());
  2161. range = &map.find("ifcbuilding")->second;
  2162. if (range->empty()) {
  2163. // no site, no building - fail;
  2164. IFCImporter::ThrowException("no root element found (expected IfcBuilding or preferably IfcSite)");
  2165. }
  2166. }
  2167. BOOST_FOREACH(const STEP::LazyObject* lz, *range) {
  2168. const IFC::IfcSpatialStructureElement* const prod = lz->ToPtr<IFC::IfcSpatialStructureElement>();
  2169. if(!prod) {
  2170. continue;
  2171. }
  2172. IFCImporter::LogDebug("looking at spatial structure `" + (prod->Name ? prod->Name.Get() : "unnamed") + "`" + (prod->ObjectType? " which is of type " + prod->ObjectType.Get():""));
  2173. // the primary site is referenced by an IFCRELAGGREGATES element which assigns it to the IFCPRODUCT
  2174. const STEP::DB::RefMap& refs = conv.db.GetRefs();
  2175. STEP::DB::RefMapRange range = refs.equal_range(conv.proj.GetID());
  2176. for(;range.first != range.second; ++range.first) {
  2177. if(const IFC::IfcRelAggregates* const aggr = conv.db.GetObject((*range.first).second)->ToPtr<IFC::IfcRelAggregates>()) {
  2178. BOOST_FOREACH(const IFC::IfcObjectDefinition& def, aggr->RelatedObjects) {
  2179. // comparing pointer values is not sufficient, we would need to cast them to the same type first
  2180. // as there is multiple inheritance in the game.
  2181. if (def.GetID() == prod->GetID()) {
  2182. IFCImporter::LogDebug("selecting this spatial structure as root structure");
  2183. // got it, this is the primary site.
  2184. conv.out->mRootNode = ProcessSpatialStructure(NULL,*prod,conv,NULL);
  2185. return;
  2186. }
  2187. }
  2188. }
  2189. }
  2190. }
  2191. IFCImporter::LogWarn("failed to determine primary site element, taking the first IfcSite");
  2192. BOOST_FOREACH(const STEP::LazyObject* lz, *range) {
  2193. const IFC::IfcSpatialStructureElement* const prod = lz->ToPtr<IFC::IfcSpatialStructureElement>();
  2194. if(!prod) {
  2195. continue;
  2196. }
  2197. conv.out->mRootNode = ProcessSpatialStructure(NULL,*prod,conv,NULL);
  2198. return;
  2199. }
  2200. IFCImporter::ThrowException("failed to determine primary site element");
  2201. }
  2202. // ------------------------------------------------------------------------------------------------
  2203. void MakeTreeRelative(aiNode* start, const aiMatrix4x4& combined)
  2204. {
  2205. // combined is the parent's absolute transformation matrix
  2206. aiMatrix4x4 old = start->mTransformation;
  2207. if (!combined.IsIdentity()) {
  2208. start->mTransformation = aiMatrix4x4(combined).Inverse() * start->mTransformation;
  2209. }
  2210. // All nodes store absolute transformations right now, so we need to make them relative
  2211. for (unsigned int i = 0; i < start->mNumChildren; ++i) {
  2212. MakeTreeRelative(start->mChildren[i],old);
  2213. }
  2214. }
  2215. // ------------------------------------------------------------------------------------------------
  2216. void MakeTreeRelative(ConversionData& conv)
  2217. {
  2218. MakeTreeRelative(conv.out->mRootNode,aiMatrix4x4());
  2219. }
  2220. } // !anon
  2221. #endif