IFCLoader.cpp 37 KB

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