IFCLoader.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2016, assimp 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 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 IFCLoad.cpp
  34. * @brief Implementation of the Industry Foundation Classes loader.
  35. */
  36. #ifndef ASSIMP_BUILD_NO_IFC_IMPORTER
  37. #include <iterator>
  38. #include <limits>
  39. #include <boost/tuple/tuple.hpp>
  40. #ifndef ASSIMP_BUILD_NO_COMPRESSED_IFC
  41. # include "../contrib/unzip/unzip.h"
  42. #endif
  43. #include "IFCLoader.h"
  44. #include "STEPFileReader.h"
  45. #include "IFCUtil.h"
  46. #include "StreamReader.h"
  47. #include "MemoryIOWrapper.h"
  48. #include "../include/assimp/scene.h"
  49. #include "../include/assimp/Importer.hpp"
  50. namespace Assimp {
  51. template<> const std::string LogFunctions<IFCImporter>::log_prefix = "IFC: ";
  52. }
  53. using namespace Assimp;
  54. using namespace Assimp::Formatter;
  55. using namespace Assimp::IFC;
  56. /* DO NOT REMOVE this comment block. The genentitylist.sh script
  57. * just looks for names adhering to the IfcSomething naming scheme
  58. * and includes all matches in the whitelist for code-generation. Thus,
  59. * all entity classes that are only indirectly referenced need to be
  60. * mentioned explicitly.
  61. IfcRepresentationMap
  62. IfcProductRepresentation
  63. IfcUnitAssignment
  64. IfcClosedShell
  65. IfcDoor
  66. */
  67. namespace {
  68. // forward declarations
  69. void SetUnits(ConversionData& conv);
  70. void SetCoordinateSpace(ConversionData& conv);
  71. void ProcessSpatialStructures(ConversionData& conv);
  72. void MakeTreeRelative(ConversionData& conv);
  73. void ConvertUnit(const EXPRESS::DataType& dt,ConversionData& conv);
  74. } // anon
  75. static const aiImporterDesc desc = {
  76. "Industry Foundation Classes (IFC) Importer",
  77. "",
  78. "",
  79. "",
  80. aiImporterFlags_SupportBinaryFlavour,
  81. 0,
  82. 0,
  83. 0,
  84. 0,
  85. "ifc ifczip"
  86. };
  87. // ------------------------------------------------------------------------------------------------
  88. // Constructor to be privately used by Importer
  89. IFCImporter::IFCImporter()
  90. {}
  91. // ------------------------------------------------------------------------------------------------
  92. // Destructor, private as well
  93. IFCImporter::~IFCImporter()
  94. {
  95. }
  96. // ------------------------------------------------------------------------------------------------
  97. // Returns whether the class can handle the format of the given file.
  98. bool IFCImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  99. {
  100. const std::string& extension = GetExtension(pFile);
  101. if (extension == "ifc" || extension == "ifczip") {
  102. return true;
  103. }
  104. else if ((!extension.length() || checkSig) && pIOHandler) {
  105. // note: this is the common identification for STEP-encoded files, so
  106. // it is only unambiguous as long as we don't support any further
  107. // file formats with STEP as their encoding.
  108. const char* tokens[] = {"ISO-10303-21"};
  109. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
  110. }
  111. return false;
  112. }
  113. // ------------------------------------------------------------------------------------------------
  114. // List all extensions handled by this loader
  115. const aiImporterDesc* IFCImporter::GetInfo () const
  116. {
  117. return &desc;
  118. }
  119. // ------------------------------------------------------------------------------------------------
  120. // Setup configuration properties for the loader
  121. void IFCImporter::SetupProperties(const Importer* pImp)
  122. {
  123. settings.skipSpaceRepresentations = pImp->GetPropertyBool(AI_CONFIG_IMPORT_IFC_SKIP_SPACE_REPRESENTATIONS,true);
  124. settings.skipCurveRepresentations = pImp->GetPropertyBool(AI_CONFIG_IMPORT_IFC_SKIP_CURVE_REPRESENTATIONS,true);
  125. settings.useCustomTriangulation = pImp->GetPropertyBool(AI_CONFIG_IMPORT_IFC_CUSTOM_TRIANGULATION,true);
  126. settings.conicSamplingAngle = 10.f;
  127. settings.skipAnnotations = true;
  128. }
  129. // ------------------------------------------------------------------------------------------------
  130. // Imports the given file into the given scene structure.
  131. void IFCImporter::InternReadFile( const std::string& pFile,
  132. aiScene* pScene, IOSystem* pIOHandler)
  133. {
  134. boost::shared_ptr<IOStream> stream(pIOHandler->Open(pFile));
  135. if (!stream) {
  136. ThrowException("Could not open file for reading");
  137. }
  138. // if this is a ifczip file, decompress its contents first
  139. if(GetExtension(pFile) == "ifczip") {
  140. #ifndef ASSIMP_BUILD_NO_COMPRESSED_IFC
  141. unzFile zip = unzOpen( pFile.c_str() );
  142. if(zip == NULL) {
  143. ThrowException("Could not open ifczip file for reading, unzip failed");
  144. }
  145. // chop 'zip' postfix
  146. std::string fileName = pFile.substr(0,pFile.length() - 3);
  147. std::string::size_type s = pFile.find_last_of('\\');
  148. if(s == std::string::npos) {
  149. s = pFile.find_last_of('/');
  150. }
  151. if(s != std::string::npos) {
  152. fileName = fileName.substr(s+1);
  153. }
  154. // search file (same name as the IFCZIP except for the file extension) and place file pointer there
  155. if(UNZ_OK == unzGoToFirstFile(zip)) {
  156. do {
  157. // get file size, etc.
  158. unz_file_info fileInfo;
  159. char filename[256];
  160. unzGetCurrentFileInfo( zip , &fileInfo, filename, sizeof(filename), 0, 0, 0, 0 );
  161. if (GetExtension(filename) != "ifc") {
  162. continue;
  163. }
  164. uint8_t* buff = new uint8_t[fileInfo.uncompressed_size];
  165. LogInfo("Decompressing IFCZIP file");
  166. unzOpenCurrentFile( zip );
  167. const int ret = unzReadCurrentFile( zip, buff, fileInfo.uncompressed_size);
  168. size_t filesize = fileInfo.uncompressed_size;
  169. if ( ret < 0 || size_t(ret) != filesize )
  170. {
  171. delete[] buff;
  172. ThrowException("Failed to decompress IFC ZIP file");
  173. }
  174. unzCloseCurrentFile( zip );
  175. stream.reset(new MemoryIOStream(buff,fileInfo.uncompressed_size,true));
  176. break;
  177. if (unzGoToNextFile(zip) == UNZ_END_OF_LIST_OF_FILE) {
  178. ThrowException("Found no IFC file member in IFCZIP file (1)");
  179. }
  180. } while(true);
  181. }
  182. else {
  183. ThrowException("Found no IFC file member in IFCZIP file (2)");
  184. }
  185. unzClose(zip);
  186. #else
  187. ThrowException("Could not open ifczip file for reading, assimp was built without ifczip support");
  188. #endif
  189. }
  190. boost::scoped_ptr<STEP::DB> db(STEP::ReadFileHeader(stream));
  191. const STEP::HeaderInfo& head = static_cast<const STEP::DB&>(*db).GetHeader();
  192. if(!head.fileSchema.size() || head.fileSchema.substr(0,3) != "IFC") {
  193. ThrowException("Unrecognized file schema: " + head.fileSchema);
  194. }
  195. if (!DefaultLogger::isNullLogger()) {
  196. LogDebug("File schema is \'" + head.fileSchema + '\'');
  197. if (head.timestamp.length()) {
  198. LogDebug("Timestamp \'" + head.timestamp + '\'');
  199. }
  200. if (head.app.length()) {
  201. LogDebug("Application/Exporter identline is \'" + head.app + '\'');
  202. }
  203. }
  204. // obtain a copy of the machine-generated IFC scheme
  205. EXPRESS::ConversionSchema schema;
  206. GetSchema(schema);
  207. // tell the reader which entity types to track with special care
  208. static const char* const types_to_track[] = {
  209. "ifcsite", "ifcbuilding", "ifcproject"
  210. };
  211. // tell the reader for which types we need to simulate STEPs reverse indices
  212. static const char* const inverse_indices_to_track[] = {
  213. "ifcrelcontainedinspatialstructure", "ifcrelaggregates", "ifcrelvoidselement", "ifcreldefinesbyproperties", "ifcpropertyset", "ifcstyleditem"
  214. };
  215. // feed the IFC schema into the reader and pre-parse all lines
  216. STEP::ReadFile(*db, schema, types_to_track, inverse_indices_to_track);
  217. const STEP::LazyObject* proj = db->GetObject("ifcproject");
  218. if (!proj) {
  219. ThrowException("missing IfcProject entity");
  220. }
  221. ConversionData conv(*db,proj->To<IfcProject>(),pScene,settings);
  222. SetUnits(conv);
  223. SetCoordinateSpace(conv);
  224. ProcessSpatialStructures(conv);
  225. MakeTreeRelative(conv);
  226. // NOTE - this is a stress test for the importer, but it works only
  227. // in a build with no entities disabled. See
  228. // scripts/IFCImporter/CPPGenerator.py
  229. // for more information.
  230. #ifdef ASSIMP_IFC_TEST
  231. db->EvaluateAll();
  232. #endif
  233. // do final data copying
  234. if (conv.meshes.size()) {
  235. pScene->mNumMeshes = static_cast<unsigned int>(conv.meshes.size());
  236. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes]();
  237. std::copy(conv.meshes.begin(),conv.meshes.end(),pScene->mMeshes);
  238. // needed to keep the d'tor from burning us
  239. conv.meshes.clear();
  240. }
  241. if (conv.materials.size()) {
  242. pScene->mNumMaterials = static_cast<unsigned int>(conv.materials.size());
  243. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials]();
  244. std::copy(conv.materials.begin(),conv.materials.end(),pScene->mMaterials);
  245. // needed to keep the d'tor from burning us
  246. conv.materials.clear();
  247. }
  248. // apply world coordinate system (which includes the scaling to convert to meters and a -90 degrees rotation around x)
  249. aiMatrix4x4 scale, rot;
  250. aiMatrix4x4::Scaling(static_cast<aiVector3D>(IfcVector3(conv.len_scale)),scale);
  251. aiMatrix4x4::RotationX(-AI_MATH_HALF_PI_F,rot);
  252. pScene->mRootNode->mTransformation = rot * scale * conv.wcs * pScene->mRootNode->mTransformation;
  253. // this must be last because objects are evaluated lazily as we process them
  254. if ( !DefaultLogger::isNullLogger() ){
  255. LogDebug((Formatter::format(),"STEP: evaluated ",db->GetEvaluatedObjectCount()," object records"));
  256. }
  257. }
  258. namespace {
  259. // ------------------------------------------------------------------------------------------------
  260. void ConvertUnit(const IfcNamedUnit& unit,ConversionData& conv)
  261. {
  262. if(const IfcSIUnit* const si = unit.ToPtr<IfcSIUnit>()) {
  263. if(si->UnitType == "LENGTHUNIT") {
  264. conv.len_scale = si->Prefix ? ConvertSIPrefix(si->Prefix) : 1.f;
  265. IFCImporter::LogDebug("got units used for lengths");
  266. }
  267. if(si->UnitType == "PLANEANGLEUNIT") {
  268. if (si->Name != "RADIAN") {
  269. IFCImporter::LogWarn("expected base unit for angles to be radian");
  270. }
  271. }
  272. }
  273. else if(const IfcConversionBasedUnit* const convu = unit.ToPtr<IfcConversionBasedUnit>()) {
  274. if(convu->UnitType == "PLANEANGLEUNIT") {
  275. try {
  276. conv.angle_scale = convu->ConversionFactor->ValueComponent->To<EXPRESS::REAL>();
  277. ConvertUnit(*convu->ConversionFactor->UnitComponent,conv);
  278. IFCImporter::LogDebug("got units used for angles");
  279. }
  280. catch(std::bad_cast&) {
  281. IFCImporter::LogError("skipping unknown IfcConversionBasedUnit.ValueComponent entry - expected REAL");
  282. }
  283. }
  284. }
  285. }
  286. // ------------------------------------------------------------------------------------------------
  287. void ConvertUnit(const EXPRESS::DataType& dt,ConversionData& conv)
  288. {
  289. try {
  290. const EXPRESS::ENTITY& e = dt.To<ENTITY>();
  291. const IfcNamedUnit& unit = e.ResolveSelect<IfcNamedUnit>(conv.db);
  292. if(unit.UnitType != "LENGTHUNIT" && unit.UnitType != "PLANEANGLEUNIT") {
  293. return;
  294. }
  295. ConvertUnit(unit,conv);
  296. }
  297. catch(std::bad_cast&) {
  298. // not entity, somehow
  299. IFCImporter::LogError("skipping unknown IfcUnit entry - expected entity");
  300. }
  301. }
  302. // ------------------------------------------------------------------------------------------------
  303. void SetUnits(ConversionData& conv)
  304. {
  305. // see if we can determine the coordinate space used to express.
  306. for(size_t i = 0; i < conv.proj.UnitsInContext->Units.size(); ++i ) {
  307. ConvertUnit(*conv.proj.UnitsInContext->Units[i],conv);
  308. }
  309. }
  310. // ------------------------------------------------------------------------------------------------
  311. void SetCoordinateSpace(ConversionData& conv)
  312. {
  313. const IfcRepresentationContext* fav = NULL;
  314. BOOST_FOREACH(const IfcRepresentationContext& v, conv.proj.RepresentationContexts) {
  315. fav = &v;
  316. // Model should be the most suitable type of context, hence ignore the others
  317. if (v.ContextType && v.ContextType.Get() == "Model") {
  318. break;
  319. }
  320. }
  321. if (fav) {
  322. if(const IfcGeometricRepresentationContext* const geo = fav->ToPtr<IfcGeometricRepresentationContext>()) {
  323. ConvertAxisPlacement(conv.wcs, *geo->WorldCoordinateSystem, conv);
  324. IFCImporter::LogDebug("got world coordinate system");
  325. }
  326. }
  327. }
  328. // ------------------------------------------------------------------------------------------------
  329. void ResolveObjectPlacement(aiMatrix4x4& m, const IfcObjectPlacement& place, ConversionData& conv)
  330. {
  331. if (const IfcLocalPlacement* const local = place.ToPtr<IfcLocalPlacement>()){
  332. IfcMatrix4 tmp;
  333. ConvertAxisPlacement(tmp, *local->RelativePlacement, conv);
  334. m = static_cast<aiMatrix4x4>(tmp);
  335. if (local->PlacementRelTo) {
  336. aiMatrix4x4 tmp;
  337. ResolveObjectPlacement(tmp,local->PlacementRelTo.Get(),conv);
  338. m = tmp * m;
  339. }
  340. }
  341. else {
  342. IFCImporter::LogWarn("skipping unknown IfcObjectPlacement entity, type is " + place.GetClassName());
  343. }
  344. }
  345. // ------------------------------------------------------------------------------------------------
  346. bool ProcessMappedItem(const IfcMappedItem& mapped, aiNode* nd_src, std::vector< aiNode* >& subnodes_src, unsigned int matid, ConversionData& conv)
  347. {
  348. // insert a custom node here, the cartesian transform operator is simply a conventional transformation matrix
  349. std::auto_ptr<aiNode> nd(new aiNode());
  350. nd->mName.Set("IfcMappedItem");
  351. // handle the Cartesian operator
  352. IfcMatrix4 m;
  353. ConvertTransformOperator(m, *mapped.MappingTarget);
  354. IfcMatrix4 msrc;
  355. ConvertAxisPlacement(msrc,*mapped.MappingSource->MappingOrigin,conv);
  356. msrc = m*msrc;
  357. std::vector<unsigned int> meshes;
  358. const size_t old_openings = conv.collect_openings ? conv.collect_openings->size() : 0;
  359. if (conv.apply_openings) {
  360. IfcMatrix4 minv = msrc;
  361. minv.Inverse();
  362. BOOST_FOREACH(TempOpening& open,*conv.apply_openings){
  363. open.Transform(minv);
  364. }
  365. }
  366. unsigned int localmatid = ProcessMaterials(mapped.GetID(),matid,conv,false);
  367. const IfcRepresentation& repr = mapped.MappingSource->MappedRepresentation;
  368. bool got = false;
  369. BOOST_FOREACH(const IfcRepresentationItem& item, repr.Items) {
  370. if(!ProcessRepresentationItem(item,localmatid,meshes,conv)) {
  371. IFCImporter::LogWarn("skipping mapped entity of type " + item.GetClassName() + ", no representations could be generated");
  372. }
  373. else got = true;
  374. }
  375. if (!got) {
  376. return false;
  377. }
  378. AssignAddedMeshes(meshes,nd.get(),conv);
  379. if (conv.collect_openings) {
  380. // if this pass serves us only to collect opening geometry,
  381. // make sure we transform the TempMesh's which we need to
  382. // preserve as well.
  383. if(const size_t diff = conv.collect_openings->size() - old_openings) {
  384. for(size_t i = 0; i < diff; ++i) {
  385. (*conv.collect_openings)[old_openings+i].Transform(msrc);
  386. }
  387. }
  388. }
  389. nd->mTransformation = nd_src->mTransformation * static_cast<aiMatrix4x4>( msrc );
  390. subnodes_src.push_back(nd.release());
  391. return true;
  392. }
  393. // ------------------------------------------------------------------------------------------------
  394. struct RateRepresentationPredicate {
  395. int Rate(const IfcRepresentation* r) const {
  396. // the smaller, the better
  397. if (! r->RepresentationIdentifier) {
  398. // neutral choice if no extra information is specified
  399. return 0;
  400. }
  401. const std::string& name = r->RepresentationIdentifier.Get();
  402. if (name == "MappedRepresentation") {
  403. if (!r->Items.empty()) {
  404. // take the first item and base our choice on it
  405. const IfcMappedItem* const m = r->Items.front()->ToPtr<IfcMappedItem>();
  406. if (m) {
  407. return Rate(m->MappingSource->MappedRepresentation);
  408. }
  409. }
  410. return 100;
  411. }
  412. return Rate(name);
  413. }
  414. int Rate(const std::string& r) const {
  415. if (r == "SolidModel") {
  416. return -3;
  417. }
  418. // give strong preference to extruded geometry.
  419. if (r == "SweptSolid") {
  420. return -10;
  421. }
  422. if (r == "Clipping") {
  423. return -5;
  424. }
  425. // 'Brep' is difficult to get right due to possible voids in the
  426. // polygon boundaries, so take it only if we are forced to (i.e.
  427. // if the only alternative is (non-clipping) boolean operations,
  428. // which are not supported at all).
  429. if (r == "Brep") {
  430. return -2;
  431. }
  432. // Curves, bounding boxes - those will most likely not be loaded
  433. // as we can't make any use out of this data. So consider them
  434. // last.
  435. if (r == "BoundingBox" || r == "Curve2D") {
  436. return 100;
  437. }
  438. return 0;
  439. }
  440. bool operator() (const IfcRepresentation* a, const IfcRepresentation* b) const {
  441. return Rate(a) < Rate(b);
  442. }
  443. };
  444. // ------------------------------------------------------------------------------------------------
  445. void ProcessProductRepresentation(const IfcProduct& el, aiNode* nd, std::vector< aiNode* >& subnodes, ConversionData& conv)
  446. {
  447. if(!el.Representation) {
  448. return;
  449. }
  450. // extract Color from metadata, if present
  451. unsigned int matid = ProcessMaterials( el.GetID(), std::numeric_limits<uint32_t>::max(), conv, false);
  452. std::vector<unsigned int> meshes;
  453. // we want only one representation type, so bring them in a suitable order (i.e try those
  454. // that look as if we could read them quickly at first). This way of reading
  455. // representation is relatively generic and allows the concrete implementations
  456. // for the different representation types to make some sensible choices what
  457. // to load and what not to load.
  458. const STEP::ListOf< STEP::Lazy< IfcRepresentation >, 1, 0 >& src = el.Representation.Get()->Representations;
  459. std::vector<const IfcRepresentation*> repr_ordered(src.size());
  460. std::copy(src.begin(),src.end(),repr_ordered.begin());
  461. std::sort(repr_ordered.begin(),repr_ordered.end(),RateRepresentationPredicate());
  462. BOOST_FOREACH(const IfcRepresentation* repr, repr_ordered) {
  463. bool res = false;
  464. BOOST_FOREACH(const IfcRepresentationItem& item, repr->Items) {
  465. if(const IfcMappedItem* const geo = item.ToPtr<IfcMappedItem>()) {
  466. res = ProcessMappedItem(*geo,nd,subnodes,matid,conv) || res;
  467. }
  468. else {
  469. res = ProcessRepresentationItem(item,matid,meshes,conv) || res;
  470. }
  471. }
  472. // if we got something meaningful at this point, skip any further representations
  473. if(res) {
  474. break;
  475. }
  476. }
  477. AssignAddedMeshes(meshes,nd,conv);
  478. }
  479. typedef std::map<std::string, std::string> Metadata;
  480. // ------------------------------------------------------------------------------------------------
  481. void ProcessMetadata(const ListOf< Lazy< IfcProperty >, 1, 0 >& set, ConversionData& conv, Metadata& properties,
  482. const std::string& prefix = "",
  483. unsigned int nest = 0)
  484. {
  485. BOOST_FOREACH(const IfcProperty& property, set) {
  486. const std::string& key = prefix.length() > 0 ? (prefix + "." + property.Name) : property.Name;
  487. if (const IfcPropertySingleValue* const singleValue = property.ToPtr<IfcPropertySingleValue>()) {
  488. if (singleValue->NominalValue) {
  489. if (const EXPRESS::STRING* str = singleValue->NominalValue.Get()->ToPtr<EXPRESS::STRING>()) {
  490. std::string value = static_cast<std::string>(*str);
  491. properties[key]=value;
  492. }
  493. else if (const EXPRESS::REAL* val = singleValue->NominalValue.Get()->ToPtr<EXPRESS::REAL>()) {
  494. float value = static_cast<float>(*val);
  495. std::stringstream s;
  496. s << value;
  497. properties[key]=s.str();
  498. }
  499. else if (const EXPRESS::INTEGER* val = singleValue->NominalValue.Get()->ToPtr<EXPRESS::INTEGER>()) {
  500. int64_t value = static_cast<int64_t>(*val);
  501. std::stringstream s;
  502. s << value;
  503. properties[key]=s.str();
  504. }
  505. }
  506. }
  507. else if (const IfcPropertyListValue* const listValue = property.ToPtr<IfcPropertyListValue>()) {
  508. std::stringstream ss;
  509. ss << "[";
  510. unsigned index=0;
  511. BOOST_FOREACH(const IfcValue::Out& v, listValue->ListValues) {
  512. if (!v) continue;
  513. if (const EXPRESS::STRING* str = v->ToPtr<EXPRESS::STRING>()) {
  514. std::string value = static_cast<std::string>(*str);
  515. ss << "'" << value << "'";
  516. }
  517. else if (const EXPRESS::REAL* val = v->ToPtr<EXPRESS::REAL>()) {
  518. float value = static_cast<float>(*val);
  519. ss << value;
  520. }
  521. else if (const EXPRESS::INTEGER* val = v->ToPtr<EXPRESS::INTEGER>()) {
  522. int64_t value = static_cast<int64_t>(*val);
  523. ss << value;
  524. }
  525. if (index+1<listValue->ListValues.size()) {
  526. ss << ",";
  527. }
  528. index++;
  529. }
  530. ss << "]";
  531. properties[key]=ss.str();
  532. }
  533. else if (const IfcComplexProperty* const complexProp = property.ToPtr<IfcComplexProperty>()) {
  534. if(nest > 2) { // mostly arbitrary limit to prevent stack overflow vulnerabilities
  535. IFCImporter::LogError("maximum nesting level for IfcComplexProperty reached, skipping this property.");
  536. }
  537. else {
  538. ProcessMetadata(complexProp->HasProperties, conv, properties, key, nest + 1);
  539. }
  540. }
  541. else {
  542. properties[key]="";
  543. }
  544. }
  545. }
  546. // ------------------------------------------------------------------------------------------------
  547. void ProcessMetadata(uint64_t relDefinesByPropertiesID, ConversionData& conv, Metadata& properties)
  548. {
  549. if (const IfcRelDefinesByProperties* const pset = conv.db.GetObject(relDefinesByPropertiesID)->ToPtr<IfcRelDefinesByProperties>()) {
  550. if (const IfcPropertySet* const set = conv.db.GetObject(pset->RelatingPropertyDefinition->GetID())->ToPtr<IfcPropertySet>()) {
  551. ProcessMetadata(set->HasProperties, conv, properties);
  552. }
  553. }
  554. }
  555. // ------------------------------------------------------------------------------------------------
  556. aiNode* ProcessSpatialStructure(aiNode* parent, const IfcProduct& el, ConversionData& conv, std::vector<TempOpening>* collect_openings = NULL)
  557. {
  558. const STEP::DB::RefMap& refs = conv.db.GetRefs();
  559. // skip over space and annotation nodes - usually, these have no meaning in Assimp's context
  560. bool skipGeometry = false;
  561. if(conv.settings.skipSpaceRepresentations) {
  562. if(el.ToPtr<IfcSpace>()) {
  563. IFCImporter::LogDebug("skipping IfcSpace entity due to importer settings");
  564. skipGeometry = true;
  565. }
  566. }
  567. if(conv.settings.skipAnnotations) {
  568. if(el.ToPtr<IfcAnnotation>()) {
  569. IFCImporter::LogDebug("skipping IfcAnnotation entity due to importer settings");
  570. return NULL;
  571. }
  572. }
  573. // add an output node for this spatial structure
  574. std::auto_ptr<aiNode> nd(new aiNode());
  575. nd->mName.Set(el.GetClassName()+"_"+(el.Name?el.Name.Get():"Unnamed")+"_"+el.GlobalId);
  576. nd->mParent = parent;
  577. conv.already_processed.insert(el.GetID());
  578. // check for node metadata
  579. STEP::DB::RefMapRange children = refs.equal_range(el.GetID());
  580. if (children.first!=refs.end()) {
  581. Metadata properties;
  582. if (children.first==children.second) {
  583. // handles single property set
  584. ProcessMetadata((*children.first).second, conv, properties);
  585. }
  586. else {
  587. // handles multiple property sets (currently all property sets are merged,
  588. // which may not be the best solution in the long run)
  589. for (STEP::DB::RefMap::const_iterator it=children.first; it!=children.second; ++it) {
  590. ProcessMetadata((*it).second, conv, properties);
  591. }
  592. }
  593. if (!properties.empty()) {
  594. aiMetadata* data = new aiMetadata();
  595. data->mNumProperties = properties.size();
  596. data->mKeys = new aiString[data->mNumProperties]();
  597. data->mValues = new aiMetadataEntry[data->mNumProperties]();
  598. unsigned int index = 0;
  599. BOOST_FOREACH(const Metadata::value_type& kv, properties)
  600. data->Set(index++, kv.first, aiString(kv.second));
  601. nd->mMetaData = data;
  602. }
  603. }
  604. if(el.ObjectPlacement) {
  605. ResolveObjectPlacement(nd->mTransformation,el.ObjectPlacement.Get(),conv);
  606. }
  607. std::vector<TempOpening> openings;
  608. IfcMatrix4 myInv;
  609. bool didinv = false;
  610. // convert everything contained directly within this structure,
  611. // this may result in more nodes.
  612. std::vector< aiNode* > subnodes;
  613. try {
  614. // locate aggregates and 'contained-in-here'-elements of this spatial structure and add them in recursively
  615. // on our way, collect openings in *this* element
  616. STEP::DB::RefMapRange range = refs.equal_range(el.GetID());
  617. for(STEP::DB::RefMapRange range2 = range; range2.first != range.second; ++range2.first) {
  618. // skip over meshes that have already been processed before. This is strictly necessary
  619. // because the reverse indices also include references contained in argument lists and
  620. // therefore every element has a back-reference hold by its parent.
  621. if (conv.already_processed.find((*range2.first).second) != conv.already_processed.end()) {
  622. continue;
  623. }
  624. const STEP::LazyObject& obj = conv.db.MustGetObject((*range2.first).second);
  625. // handle regularly-contained elements
  626. if(const IfcRelContainedInSpatialStructure* const cont = obj->ToPtr<IfcRelContainedInSpatialStructure>()) {
  627. if(cont->RelatingStructure->GetID() != el.GetID()) {
  628. continue;
  629. }
  630. BOOST_FOREACH(const IfcProduct& pro, cont->RelatedElements) {
  631. if(pro.ToPtr<IfcOpeningElement>()) {
  632. // IfcOpeningElement is handled below. Sadly we can't use it here as is:
  633. // The docs say that opening elements are USUALLY attached to building storey,
  634. // but we want them for the building elements to which they belong.
  635. continue;
  636. }
  637. aiNode* const ndnew = ProcessSpatialStructure(nd.get(),pro,conv,NULL);
  638. if(ndnew) {
  639. subnodes.push_back( ndnew );
  640. }
  641. }
  642. }
  643. // handle openings, which we collect in a list rather than adding them to the node graph
  644. else if(const IfcRelVoidsElement* const fills = obj->ToPtr<IfcRelVoidsElement>()) {
  645. if(fills->RelatingBuildingElement->GetID() == el.GetID()) {
  646. const IfcFeatureElementSubtraction& open = fills->RelatedOpeningElement;
  647. // move opening elements to a separate node since they are semantically different than elements that are just 'contained'
  648. std::auto_ptr<aiNode> nd_aggr(new aiNode());
  649. nd_aggr->mName.Set("$RelVoidsElement");
  650. nd_aggr->mParent = nd.get();
  651. nd_aggr->mTransformation = nd->mTransformation;
  652. std::vector<TempOpening> openings_local;
  653. aiNode* const ndnew = ProcessSpatialStructure( nd_aggr.get(),open, conv,&openings_local);
  654. if (ndnew) {
  655. nd_aggr->mNumChildren = 1;
  656. nd_aggr->mChildren = new aiNode*[1]();
  657. nd_aggr->mChildren[0] = ndnew;
  658. if(openings_local.size()) {
  659. if (!didinv) {
  660. myInv = aiMatrix4x4(nd->mTransformation ).Inverse();
  661. didinv = true;
  662. }
  663. // we need all openings to be in the local space of *this* node, so transform them
  664. BOOST_FOREACH(TempOpening& op,openings_local) {
  665. op.Transform( myInv*nd_aggr->mChildren[0]->mTransformation);
  666. openings.push_back(op);
  667. }
  668. }
  669. subnodes.push_back( nd_aggr.release() );
  670. }
  671. }
  672. }
  673. }
  674. for(;range.first != range.second; ++range.first) {
  675. // see note in loop above
  676. if (conv.already_processed.find((*range.first).second) != conv.already_processed.end()) {
  677. continue;
  678. }
  679. if(const IfcRelAggregates* const aggr = conv.db.GetObject((*range.first).second)->ToPtr<IfcRelAggregates>()) {
  680. if(aggr->RelatingObject->GetID() != el.GetID()) {
  681. continue;
  682. }
  683. // move aggregate elements to a separate node since they are semantically different than elements that are just 'contained'
  684. std::auto_ptr<aiNode> nd_aggr(new aiNode());
  685. nd_aggr->mName.Set("$RelAggregates");
  686. nd_aggr->mParent = nd.get();
  687. nd_aggr->mTransformation = nd->mTransformation;
  688. nd_aggr->mChildren = new aiNode*[aggr->RelatedObjects.size()]();
  689. BOOST_FOREACH(const IfcObjectDefinition& def, aggr->RelatedObjects) {
  690. if(const IfcProduct* const prod = def.ToPtr<IfcProduct>()) {
  691. aiNode* const ndnew = ProcessSpatialStructure(nd_aggr.get(),*prod,conv,NULL);
  692. if(ndnew) {
  693. nd_aggr->mChildren[nd_aggr->mNumChildren++] = ndnew;
  694. }
  695. }
  696. }
  697. subnodes.push_back( nd_aggr.release() );
  698. }
  699. }
  700. conv.collect_openings = collect_openings;
  701. if(!conv.collect_openings) {
  702. conv.apply_openings = &openings;
  703. }
  704. if (!skipGeometry) {
  705. ProcessProductRepresentation(el,nd.get(),subnodes,conv);
  706. conv.apply_openings = conv.collect_openings = NULL;
  707. }
  708. if (subnodes.size()) {
  709. nd->mChildren = new aiNode*[subnodes.size()]();
  710. BOOST_FOREACH(aiNode* nd2, subnodes) {
  711. nd->mChildren[nd->mNumChildren++] = nd2;
  712. nd2->mParent = nd.get();
  713. }
  714. }
  715. }
  716. catch(...) {
  717. // it hurts, but I don't want to pull boost::ptr_vector into -noboost only for these few spots here
  718. std::for_each(subnodes.begin(),subnodes.end(),delete_fun<aiNode>());
  719. throw;
  720. }
  721. ai_assert(conv.already_processed.find(el.GetID()) != conv.already_processed.end());
  722. conv.already_processed.erase(conv.already_processed.find(el.GetID()));
  723. return nd.release();
  724. }
  725. // ------------------------------------------------------------------------------------------------
  726. void ProcessSpatialStructures(ConversionData& conv)
  727. {
  728. // XXX add support for multiple sites (i.e. IfcSpatialStructureElements with composition == COMPLEX)
  729. // process all products in the file. it is reasonable to assume that a
  730. // file that is relevant for us contains at least a site or a building.
  731. const STEP::DB::ObjectMapByType& map = conv.db.GetObjectsByType();
  732. ai_assert(map.find("ifcsite") != map.end());
  733. const STEP::DB::ObjectSet* range = &map.find("ifcsite")->second;
  734. if (range->empty()) {
  735. ai_assert(map.find("ifcbuilding") != map.end());
  736. range = &map.find("ifcbuilding")->second;
  737. if (range->empty()) {
  738. // no site, no building - fail;
  739. IFCImporter::ThrowException("no root element found (expected IfcBuilding or preferably IfcSite)");
  740. }
  741. }
  742. BOOST_FOREACH(const STEP::LazyObject* lz, *range) {
  743. const IfcSpatialStructureElement* const prod = lz->ToPtr<IfcSpatialStructureElement>();
  744. if(!prod) {
  745. continue;
  746. }
  747. IFCImporter::LogDebug("looking at spatial structure `" + (prod->Name ? prod->Name.Get() : "unnamed") + "`" + (prod->ObjectType? " which is of type " + prod->ObjectType.Get():""));
  748. // the primary site is referenced by an IFCRELAGGREGATES element which assigns it to the IFCPRODUCT
  749. const STEP::DB::RefMap& refs = conv.db.GetRefs();
  750. STEP::DB::RefMapRange range = refs.equal_range(conv.proj.GetID());
  751. for(;range.first != range.second; ++range.first) {
  752. if(const IfcRelAggregates* const aggr = conv.db.GetObject((*range.first).second)->ToPtr<IfcRelAggregates>()) {
  753. BOOST_FOREACH(const IfcObjectDefinition& def, aggr->RelatedObjects) {
  754. // comparing pointer values is not sufficient, we would need to cast them to the same type first
  755. // as there is multiple inheritance in the game.
  756. if (def.GetID() == prod->GetID()) {
  757. IFCImporter::LogDebug("selecting this spatial structure as root structure");
  758. // got it, this is the primary site.
  759. conv.out->mRootNode = ProcessSpatialStructure(NULL,*prod,conv,NULL);
  760. return;
  761. }
  762. }
  763. }
  764. }
  765. }
  766. IFCImporter::LogWarn("failed to determine primary site element, taking the first IfcSite");
  767. BOOST_FOREACH(const STEP::LazyObject* lz, *range) {
  768. const IfcSpatialStructureElement* const prod = lz->ToPtr<IfcSpatialStructureElement>();
  769. if(!prod) {
  770. continue;
  771. }
  772. conv.out->mRootNode = ProcessSpatialStructure(NULL,*prod,conv,NULL);
  773. return;
  774. }
  775. IFCImporter::ThrowException("failed to determine primary site element");
  776. }
  777. // ------------------------------------------------------------------------------------------------
  778. void MakeTreeRelative(aiNode* start, const aiMatrix4x4& combined)
  779. {
  780. // combined is the parent's absolute transformation matrix
  781. const aiMatrix4x4 old = start->mTransformation;
  782. if (!combined.IsIdentity()) {
  783. start->mTransformation = aiMatrix4x4(combined).Inverse() * start->mTransformation;
  784. }
  785. // All nodes store absolute transformations right now, so we need to make them relative
  786. for (unsigned int i = 0; i < start->mNumChildren; ++i) {
  787. MakeTreeRelative(start->mChildren[i],old);
  788. }
  789. }
  790. // ------------------------------------------------------------------------------------------------
  791. void MakeTreeRelative(ConversionData& conv)
  792. {
  793. MakeTreeRelative(conv.out->mRootNode,IfcMatrix4());
  794. }
  795. } // !anon
  796. #endif