IFCLoader.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605
  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 "IFCLoader.h"
  39. #include "STEPFileReader.h"
  40. #include "IFCReaderGen.h"
  41. #include "StreamReader.h"
  42. #include "MemoryIOWrapper.h"
  43. #include "ProcessHelper.h"
  44. #include <boost/tuple/tuple.hpp>
  45. using namespace Assimp;
  46. using namespace Assimp::Formatter;
  47. namespace EXPRESS = STEP::EXPRESS;
  48. template<> const std::string LogFunctions<IFCImporter>::log_prefix = "IFC: ";
  49. /* DO NOT REMOVE this comment block. The genentitylist.sh script
  50. * just looks for names adhering to the IFC :: IfcSomething naming scheme
  51. * and includes all matches in the whitelist for code-generation. Thus,
  52. * all entity classes that are only indirectly referenced need to be
  53. * mentioned explicitly.
  54. IFC::IfcRepresentationMap
  55. IFC::IfcProductRepresentation
  56. IFC::IfcUnitAssignment
  57. IFC::IfcClosedShell
  58. IFC::IfcDoor
  59. */
  60. namespace {
  61. // helper for std::for_each to delete all heap-allocated items in a container
  62. template<typename T>
  63. struct delete_fun
  64. {
  65. void operator()(T* del) {
  66. delete del;
  67. }
  68. };
  69. // intermediate data dump during conversion
  70. struct ConversionData
  71. {
  72. ConversionData(const STEP::DB& db, const IFC::IfcProject& proj, aiScene* out,const IFCImporter::Settings& settings)
  73. : len_scale(1.0)
  74. , angle_scale(1.0)
  75. , db(db)
  76. , proj(proj)
  77. , out(out)
  78. , settings(settings)
  79. {}
  80. ~ConversionData() {
  81. std::for_each(meshes.begin(),meshes.end(),delete_fun<aiMesh>());
  82. std::for_each(materials.begin(),materials.end(),delete_fun<aiMaterial>());
  83. }
  84. float len_scale, angle_scale;
  85. bool plane_angle_in_radians;
  86. const STEP::DB& db;
  87. const IFC::IfcProject& proj;
  88. aiScene* out;
  89. aiMatrix4x4 wcs;
  90. std::vector<aiMesh*> meshes;
  91. std::vector<aiMaterial*> materials;
  92. typedef std::map<const IFC::IfcRepresentationItem*, std::vector<unsigned int> > MeshCache;
  93. MeshCache cached_meshes;
  94. const IFCImporter::Settings& settings;
  95. };
  96. // helper used during mesh construction
  97. struct TempMesh
  98. {
  99. std::vector<aiVector3D> verts;
  100. std::vector<unsigned int> vertcnt;
  101. std::vector<unsigned int> mat_idx;
  102. aiMesh* ToMesh() {
  103. ai_assert(verts.size() == std::accumulate(vertcnt.begin(),vertcnt.end(),0));
  104. if (verts.empty()) {
  105. return NULL;
  106. }
  107. std::auto_ptr<aiMesh> mesh(new aiMesh());
  108. // copy vertices
  109. mesh->mNumVertices = static_cast<unsigned int>(verts.size());
  110. mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  111. std::copy(verts.begin(),verts.end(),mesh->mVertices);
  112. // and build up faces
  113. mesh->mNumFaces = static_cast<unsigned int>(vertcnt.size());
  114. mesh->mFaces = new aiFace[mesh->mNumFaces];
  115. for(unsigned int i = 0, acc = 0; i < mesh->mNumFaces; ++i) {
  116. aiFace& f = mesh->mFaces[i];
  117. f.mNumIndices = vertcnt[i];
  118. f.mIndices = new unsigned int[f.mNumIndices];
  119. for(unsigned int a = 0; a < f.mNumIndices; ++a) {
  120. f.mIndices[a] = acc++;
  121. }
  122. }
  123. // XXX materials
  124. mesh->mMaterialIndex = UINT_MAX;
  125. return mesh.release();
  126. }
  127. };
  128. // forward declarations
  129. float ConvertSIPrefix(const std::string& prefix);
  130. void SetUnits(ConversionData& conv);
  131. void ConvertAxisPlacement(aiMatrix4x4& out, const IFC::IfcAxis2Placement& in, ConversionData& conv);
  132. void SetCoordinateSpace(ConversionData& conv);
  133. void ProcessSpatialStructures(ConversionData& conv);
  134. aiNode* ProcessSpatialStructure(aiNode* parent, const IFC::IfcProduct& el ,ConversionData& conv);
  135. void ProcessProductRepresentation(const IFC::IfcProduct& el, aiNode* nd, ConversionData& conv);
  136. void MakeTreeRelative(ConversionData& conv);
  137. void ConvertUnit(const EXPRESS::DataType* dt,ConversionData& conv);
  138. } // anon
  139. // ------------------------------------------------------------------------------------------------
  140. // Constructor to be privately used by Importer
  141. IFCImporter::IFCImporter()
  142. {}
  143. // ------------------------------------------------------------------------------------------------
  144. // Destructor, private as well
  145. IFCImporter::~IFCImporter()
  146. {
  147. }
  148. // ------------------------------------------------------------------------------------------------
  149. // Returns whether the class can handle the format of the given file.
  150. bool IFCImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  151. {
  152. const std::string& extension = GetExtension(pFile);
  153. if (extension == "ifc") {
  154. return true;
  155. }
  156. else if ((!extension.length() || checkSig) && pIOHandler) {
  157. // note: this is the common identification for STEP-encoded files, so
  158. // it is only unambiguous as long as we don't support any further
  159. // file formats with STEP as their encoding.
  160. const char* tokens[] = {"ISO-10303-21"};
  161. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
  162. }
  163. return false;
  164. }
  165. // ------------------------------------------------------------------------------------------------
  166. // List all extensions handled by this loader
  167. void IFCImporter::GetExtensionList(std::set<std::string>& app)
  168. {
  169. app.insert("ifc");
  170. }
  171. // ------------------------------------------------------------------------------------------------
  172. // Setup configuration properties for the loader
  173. void IFCImporter::SetupProperties(const Importer* pImp)
  174. {
  175. settings.skipSpaceRepresentations = pImp->GetPropertyBool(AI_CONFIG_IMPORT_IFC_SKIP_SPACE_REPRESENTATIONS,true);
  176. settings.skipCurveRepresentations = pImp->GetPropertyBool(AI_CONFIG_IMPORT_IFC_SKIP_CURVE_REPRESENTATIONS,true);
  177. }
  178. // ------------------------------------------------------------------------------------------------
  179. // Imports the given file into the given scene structure.
  180. void IFCImporter::InternReadFile( const std::string& pFile,
  181. aiScene* pScene, IOSystem* pIOHandler)
  182. {
  183. boost::shared_ptr<IOStream> stream(pIOHandler->Open(pFile));
  184. if (!stream) {
  185. ThrowException("Could not open file for reading");
  186. }
  187. boost::scoped_ptr<STEP::DB> db(STEP::ReadFileHeader(stream));
  188. const STEP::HeaderInfo& head = const_cast<const STEP::DB&>(*db).GetHeader();
  189. if(!head.fileSchema.size() || head.fileSchema.substr(0,3) != "IFC") {
  190. ThrowException("Unrecognized file schema: " + head.fileSchema);
  191. }
  192. if (!DefaultLogger::isNullLogger()) {
  193. LogDebug("File schema is \'" + head.fileSchema + '\'');
  194. if (head.timestamp.length()) {
  195. LogDebug("Timestamp \'" + head.timestamp + '\'');
  196. }
  197. if (head.app.length()) {
  198. LogDebug("Application/Exporter identline is \'" + head.app + '\'');
  199. }
  200. }
  201. // obtain a copy of the machine-generated IFC scheme
  202. EXPRESS::ConversionSchema schema;
  203. IFC::GetSchema(schema);
  204. // feed the IFC schema into the reader and pre-parse all lines
  205. STEP::ReadFile(*db, schema);
  206. const STEP::LazyObject* proj = db->GetObject("ifcproject");
  207. if (!proj) {
  208. ThrowException("missing IfcProject entity");
  209. }
  210. ConversionData conv(*db,proj->To<IFC::IfcProject>(),pScene,settings);
  211. SetUnits(conv);
  212. SetCoordinateSpace(conv);
  213. ProcessSpatialStructures(conv);
  214. MakeTreeRelative(conv);
  215. #ifdef ASSIMP_IFC_TEST
  216. db->EvaluateAll();
  217. #endif
  218. // do final data copying
  219. if (conv.meshes.size()) {
  220. pScene->mNumMeshes = static_cast<unsigned int>(conv.meshes.size());
  221. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes]();
  222. std::copy(conv.meshes.begin(),conv.meshes.end(),pScene->mMeshes);
  223. // needed to keep the d'tor from burning us
  224. conv.meshes.clear();
  225. }
  226. if (conv.materials.size()) {
  227. pScene->mNumMaterials = static_cast<unsigned int>(conv.materials.size());
  228. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials]();
  229. std::copy(conv.materials.begin(),conv.materials.end(),pScene->mMaterials);
  230. // needed to keep the d'tor from burning us
  231. conv.materials.clear();
  232. }
  233. // apply world coordinate system (which includes the scaling to convert to meters and a -90 degrees rotation around x)
  234. aiMatrix4x4 scale, rot;
  235. aiMatrix4x4::Scaling(aiVector3D(conv.len_scale,conv.len_scale,conv.len_scale),scale);
  236. aiMatrix4x4::RotationX(-AI_MATH_HALF_PI_F,rot);
  237. pScene->mRootNode->mTransformation = rot * scale * conv.wcs * pScene->mRootNode->mTransformation;
  238. // this must be last because objects are evaluated lazily as we process them
  239. if ( !DefaultLogger::isNullLogger() ){
  240. LogDebug((Formatter::format(),"STEP: evaluated ",db->GetEvaluatedObjectCount()," object records"));
  241. }
  242. }
  243. namespace {
  244. // ------------------------------------------------------------------------------------------------
  245. bool IsTrue(const EXPRESS::BOOLEAN& in)
  246. {
  247. return (std::string)in == "TRUE" || (std::string)in == "T";
  248. }
  249. // ------------------------------------------------------------------------------------------------
  250. float ConvertSIPrefix(const std::string& prefix)
  251. {
  252. if (prefix == "EXA") {
  253. return 1e18f;
  254. }
  255. else if (prefix == "PETA") {
  256. return 1e15f;
  257. }
  258. else if (prefix == "TERA") {
  259. return 1e12f;
  260. }
  261. else if (prefix == "GIGA") {
  262. return 1e9f;
  263. }
  264. else if (prefix == "MEGA") {
  265. return 1e6f;
  266. }
  267. else if (prefix == "KILO") {
  268. return 1e3f;
  269. }
  270. else if (prefix == "HECTO") {
  271. return 1e2f;
  272. }
  273. else if (prefix == "DECA") {
  274. return 1e-0f;
  275. }
  276. else if (prefix == "DECI") {
  277. return 1e-1f;
  278. }
  279. else if (prefix == "CENTI") {
  280. return 1e-2f;
  281. }
  282. else if (prefix == "MILLI") {
  283. return 1e-3f;
  284. }
  285. else if (prefix == "MICRO") {
  286. return 1e-6f;
  287. }
  288. else if (prefix == "NANO") {
  289. return 1e-9f;
  290. }
  291. else if (prefix == "PICO") {
  292. return 1e-12f;
  293. }
  294. else if (prefix == "FEMTO") {
  295. return 1e-15f;
  296. }
  297. else if (prefix == "ATTO") {
  298. return 1e-18f;
  299. }
  300. else {
  301. IFCImporter::LogError("Unrecognized SI prefix: " + prefix);
  302. return 1;
  303. }
  304. }
  305. // ------------------------------------------------------------------------------------------------
  306. void ConvertUnit(const IFC::IfcNamedUnit& unit,ConversionData& conv)
  307. {
  308. if(const IFC::IfcSIUnit* const si = unit.ToPtr<IFC::IfcSIUnit>()) {
  309. if(si->UnitType == "LENGTHUNIT") {
  310. conv.len_scale = si->Prefix ? ConvertSIPrefix(si->Prefix) : 1.f;
  311. IFCImporter::LogDebug("got units used for lengths");
  312. }
  313. if(si->UnitType == "PLANEANGLEUNIT") {
  314. if (si->Name != "RADIAN") {
  315. IFCImporter::LogWarn("expected base unit for angles to be radian");
  316. }
  317. }
  318. }
  319. else if(const IFC::IfcConversionBasedUnit* const convu = unit.ToPtr<IFC::IfcConversionBasedUnit>()) {
  320. if(convu->UnitType == "PLANEANGLEUNIT") {
  321. try {
  322. conv.angle_scale = convu->ConversionFactor->ValueComponent->To<EXPRESS::REAL>();
  323. ConvertUnit(convu->ConversionFactor->UnitComponent,conv);
  324. IFCImporter::LogDebug("got units used for angles");
  325. }
  326. catch(std::bad_cast&) {
  327. IFCImporter::LogError("skipping unknown IfcConversionBasedUnit.ValueComponent entry - expected REAL");
  328. }
  329. }
  330. }
  331. }
  332. // ------------------------------------------------------------------------------------------------
  333. void ConvertUnit(const EXPRESS::DataType* dt,ConversionData& conv)
  334. {
  335. try {
  336. const EXPRESS::ENTITY& e = dt->To<IFC::ENTITY>();
  337. const IFC::IfcNamedUnit& unit = e.ResolveSelect<IFC::IfcNamedUnit>(conv.db);
  338. if(unit.UnitType != "LENGTHUNIT" && unit.UnitType != "PLANEANGLEUNIT") {
  339. return;
  340. }
  341. ConvertUnit(unit,conv);
  342. }
  343. catch(std::bad_cast&) {
  344. // not entity, somehow
  345. IFCImporter::LogError("skipping unknown IfcUnit entry - expected entity");
  346. }
  347. }
  348. // ------------------------------------------------------------------------------------------------
  349. void SetUnits(ConversionData& conv)
  350. {
  351. // see if we can determine the coordinate space used to express.
  352. for(size_t i = 0; i < conv.proj.UnitsInContext->Units.size(); ++i ) {
  353. ConvertUnit(conv.proj.UnitsInContext->Units[i],conv);
  354. }
  355. }
  356. // ------------------------------------------------------------------------------------------------
  357. void ConvertColor(aiColor4D& out, const IFC::IfcColourRgb& in)
  358. {
  359. out.r = in.Red;
  360. out.g = in.Green;
  361. out.b = in.Blue;
  362. out.a = 1.f;
  363. }
  364. // ------------------------------------------------------------------------------------------------
  365. void ConvertColor(aiColor4D& out, const IFC::IfcColourOrFactor* in,ConversionData& conv,const aiColor4D* base)
  366. {
  367. if (const EXPRESS::REAL* const r = in->ToPtr<EXPRESS::REAL>()) {
  368. out.r = out.g = out.b = *r;
  369. if(base) {
  370. out.r *= base->r;
  371. out.g *= base->g;
  372. out.b *= base->b;
  373. out.a = base->a;
  374. }
  375. else out.a = 1.0;
  376. }
  377. else if (const IFC::IfcColourRgb* const rgb = in->ResolveSelectPtr<IFC::IfcColourRgb>(conv.db)) {
  378. ConvertColor(out,*rgb);
  379. }
  380. else {
  381. IFCImporter::LogWarn("skipping unknown IfcColourOrFactor entity");
  382. }
  383. }
  384. // ------------------------------------------------------------------------------------------------
  385. void ConvertCartesianPoint(aiVector3D& out, const IFC::IfcCartesianPoint& in)
  386. {
  387. out = aiVector3D();
  388. for(size_t i = 0; i < in.Coordinates.size(); ++i) {
  389. out[i] = in.Coordinates[i];
  390. }
  391. }
  392. // ------------------------------------------------------------------------------------------------
  393. void ConvertDirection(aiVector3D& out, const IFC::IfcDirection& in)
  394. {
  395. out = aiVector3D();
  396. for(size_t i = 0; i < in.DirectionRatios.size(); ++i) {
  397. out[i] = in.DirectionRatios[i];
  398. }
  399. const float len = out.Length();
  400. if (len<1e-6) {
  401. IFCImporter::LogWarn("direction vector too small, normalizing would result in a division by zero");
  402. return;
  403. }
  404. out /= len;
  405. }
  406. // ------------------------------------------------------------------------------------------------
  407. void AssignMatrixAxes(aiMatrix4x4& out, const aiVector3D& x, const aiVector3D& y, const aiVector3D& z)
  408. {
  409. out.a1 = x.x;
  410. out.b1 = x.y;
  411. out.c1 = x.z;
  412. out.a2 = y.x;
  413. out.b2 = y.y;
  414. out.c2 = y.z;
  415. out.a3 = z.x;
  416. out.b3 = z.y;
  417. out.c3 = z.z;
  418. }
  419. // ------------------------------------------------------------------------------------------------
  420. void ConvertAxisPlacement(aiMatrix4x4& out, const IFC::IfcAxis2Placement3D& in, ConversionData& conv)
  421. {
  422. aiVector3D loc;
  423. ConvertCartesianPoint(loc,in.Location);
  424. aiVector3D z(0.f,0.f,1.f),r(0.f,1.f,0.f),x;
  425. if (in.Axis) {
  426. ConvertDirection(z,*in.Axis.Get());
  427. }
  428. if (in.RefDirection) {
  429. ConvertDirection(r,*in.RefDirection.Get());
  430. }
  431. aiVector3D v = r.Normalize();
  432. aiVector3D tmpx = z * (v*z);
  433. x = (v-tmpx).Normalize();
  434. aiVector3D y = (z^x);
  435. aiMatrix4x4::Translation(loc,out);
  436. AssignMatrixAxes(out,x,y,z);
  437. }
  438. // ------------------------------------------------------------------------------------------------
  439. void ConvertAxisPlacement(aiMatrix4x4& out, const IFC::IfcAxis2Placement2D& in, ConversionData& conv)
  440. {
  441. aiVector3D loc;
  442. ConvertCartesianPoint(loc,in.Location);
  443. aiVector3D x(1.f,0.f,1.f);
  444. if (in.RefDirection) {
  445. ConvertDirection(x,*in.RefDirection.Get());
  446. }
  447. const aiVector3D y = aiVector3D(x.y,-x.x,0.f);
  448. aiMatrix4x4::Translation(loc,out);
  449. AssignMatrixAxes(out,x,y,aiVector3D(0.f,0.f,1.f));
  450. }
  451. // ------------------------------------------------------------------------------------------------
  452. void ConvertAxisPlacement(aiVector3D& axis, aiVector3D& pos, const IFC::IfcAxis1Placement& in, ConversionData& conv)
  453. {
  454. ConvertCartesianPoint(pos,in.Location);
  455. if (in.Axis) {
  456. ConvertDirection(axis,in.Axis.Get());
  457. }
  458. else {
  459. axis = aiVector3D(0.f,0.f,1.f);
  460. }
  461. }
  462. // ------------------------------------------------------------------------------------------------
  463. void ConvertAxisPlacement(aiMatrix4x4& out, const IFC::IfcAxis2Placement& in, ConversionData& conv)
  464. {
  465. if(const IFC::IfcAxis2Placement3D* pl3 = in.ResolveSelectPtr<IFC::IfcAxis2Placement3D>(conv.db)) {
  466. ConvertAxisPlacement(out,*pl3,conv);
  467. }
  468. else if(const IFC::IfcAxis2Placement2D* pl2 = in.ResolveSelectPtr<IFC::IfcAxis2Placement2D>(conv.db)) {
  469. ConvertAxisPlacement(out,*pl2,conv);
  470. }
  471. else {
  472. IFCImporter::LogWarn("skipping unknown IfcAxis2Placement entity");
  473. }
  474. }
  475. // ------------------------------------------------------------------------------------------------
  476. void SetCoordinateSpace(ConversionData& conv)
  477. {
  478. const IFC::IfcRepresentationContext* fav = NULL;
  479. BOOST_FOREACH(const IFC::IfcRepresentationContext& v, conv.proj.RepresentationContexts) {
  480. fav = &v;
  481. // Model should be the most suitable type of context, hence ignore the others
  482. if (v.ContextType && v.ContextType.Get() == "Model") {
  483. break;
  484. }
  485. }
  486. if (fav) {
  487. if(const IFC::IfcGeometricRepresentationContext* const geo = fav->ToPtr<IFC::IfcGeometricRepresentationContext>()) {
  488. ConvertAxisPlacement(conv.wcs, *geo->WorldCoordinateSystem, conv);
  489. IFCImporter::LogDebug("got world coordinate system");
  490. }
  491. }
  492. }
  493. // ------------------------------------------------------------------------------------------------
  494. void ConvertTransformOperator(aiMatrix4x4& out, const IFC::IfcCartesianTransformationOperator& op)
  495. {
  496. aiVector3D loc;
  497. ConvertCartesianPoint(loc,op.LocalOrigin);
  498. aiVector3D x(1.f,0.f,0.f),y(0.f,1.f,0.f),z(0.f,0.f,1.f);
  499. if (op.Axis1) {
  500. ConvertDirection(x,*op.Axis1.Get());
  501. }
  502. if (op.Axis2) {
  503. ConvertDirection(y,*op.Axis2.Get());
  504. }
  505. if (const IFC::IfcCartesianTransformationOperator3D* op2 = op.ToPtr<IFC::IfcCartesianTransformationOperator3D>()) {
  506. if(op2->Axis3) {
  507. ConvertDirection(z,*op2->Axis3.Get());
  508. }
  509. }
  510. aiMatrix4x4 locm;
  511. aiMatrix4x4::Translation(loc,locm);
  512. AssignMatrixAxes(out,x,y,z);
  513. const float sc = op.Scale?op.Scale.Get():1.f;
  514. aiMatrix4x4 s;
  515. aiMatrix4x4::Scaling(aiVector3D(sc,sc,sc),s);
  516. out = locm * out * s;
  517. }
  518. // ------------------------------------------------------------------------------------------------
  519. bool ProcessPolyloop(const IFC::IfcPolyLoop& loop, TempMesh& meshout, ConversionData& conv)
  520. {
  521. size_t cnt = 0;
  522. BOOST_FOREACH(const IFC::IfcCartesianPoint& c, loop.Polygon) {
  523. aiVector3D tmp;
  524. ConvertCartesianPoint(tmp,c);
  525. meshout.verts.push_back(tmp);
  526. ++cnt;
  527. }
  528. // zero- or one- vertex polyloops simply ignored
  529. if (cnt >= 1) {
  530. meshout.vertcnt.push_back(cnt);
  531. return true;
  532. }
  533. if (cnt==1) {
  534. meshout.vertcnt.pop_back();
  535. }
  536. return false;
  537. }
  538. // ------------------------------------------------------------------------------------------------
  539. void ProcessConnectedFaceSet(const IFC::IfcConnectedFaceSet& fset, TempMesh& result, ConversionData& conv)
  540. {
  541. BOOST_FOREACH(const IFC::IfcFace& face, fset.CfsFaces) {
  542. TempMesh meshout;
  543. size_t ob = face.Bounds.size(), cnt = 0;
  544. BOOST_FOREACH(const IFC::IfcFaceBound& bound, face.Bounds) {
  545. if(const IFC::IfcPolyLoop* const polyloop = bound.Bound->ToPtr<IFC::IfcPolyLoop>()) {
  546. if(ProcessPolyloop(*polyloop, meshout, conv)) {
  547. if(bound.ToPtr<IFC::IfcFaceOuterBound>()) {
  548. ob = cnt;
  549. }
  550. ++cnt;
  551. }
  552. }
  553. else {
  554. IFCImporter::LogWarn("skipping unknown IfcFaceBound entity, type is " + bound.Bound->GetClassName());
  555. continue;
  556. }
  557. if(!IsTrue(bound.Orientation)) {
  558. size_t c = 0;
  559. BOOST_FOREACH(unsigned int& i, meshout.vertcnt) {
  560. std::reverse(meshout.verts.begin() + cnt,meshout.verts.begin() + cnt + c);
  561. cnt += c;
  562. }
  563. }
  564. }
  565. result.vertcnt.reserve(meshout.vertcnt.size()+result.vertcnt.size());
  566. if (meshout.vertcnt.size() <= 1) {
  567. result.verts.reserve(meshout.verts.size()+result.verts.size());
  568. std::copy(meshout.verts.begin(),meshout.verts.end(),std::back_inserter(result.verts));
  569. std::copy(meshout.vertcnt.begin(),meshout.vertcnt.end(),std::back_inserter(result.vertcnt));
  570. continue;
  571. }
  572. IFCImporter::LogDebug("fixing polygon with holes for triangulation via ear-cutting");
  573. // each hole results in two extra vertices
  574. result.verts.reserve(meshout.verts.size()+cnt*2+result.verts.size());
  575. // handle polygons with holes. our built in triangulation won't handle them as is, but
  576. // the ear cutting algorithm is solid enough to deal with them if we join the inner
  577. // holes with the outer boundaries by dummy connections.
  578. size_t outer_polygon_start = 0;
  579. // see if one of the polygons is a IfcFaceOuterBound - treats this as the outer boundary.
  580. // sadly we can't rely on it, the docs say 'At most one of the bounds shall be of the type IfcFaceOuterBound'
  581. std::vector<unsigned int>::iterator outer_polygon = meshout.vertcnt.end(), begin=meshout.vertcnt.begin(), iit;
  582. if (ob < face.Bounds.size()) {
  583. outer_polygon = begin + ob;
  584. outer_polygon_start = std::accumulate(begin,outer_polygon,0);
  585. }
  586. else {
  587. float area_outer_polygon = 1e-10f;
  588. // find the polygon with the largest area, it must be the outer bound.
  589. size_t max_vcount = 0;
  590. for(iit = begin; iit != meshout.vertcnt.end(); ++iit) {
  591. ai_assert(*iit);
  592. max_vcount = std::max(max_vcount,static_cast<size_t>(*iit));
  593. }
  594. std::vector<float> temp((max_vcount+2)*4);
  595. size_t vidx = 0;
  596. for(iit = begin; iit != meshout.vertcnt.end(); vidx += *iit++) {
  597. for(size_t vofs = 0, cnt = 0; vofs < *iit; ++vofs) {
  598. const aiVector3D& v = meshout.verts[vidx+vofs];
  599. temp[cnt++] = v.x;
  600. temp[cnt++] = v.y;
  601. temp[cnt++] = v.z;
  602. #ifdef _DEBUG
  603. temp[cnt] = std::numeric_limits<float>::quiet_NaN();
  604. #endif
  605. ++cnt;
  606. }
  607. aiVector3D nor;
  608. NewellNormal<4,4,4>(nor,*iit,&temp[0],&temp[1],&temp[2]);
  609. const float area = nor.SquareLength();
  610. if (area > area_outer_polygon) {
  611. area_outer_polygon = area;
  612. outer_polygon = iit;
  613. outer_polygon_start = vidx;
  614. }
  615. }
  616. }
  617. ai_assert(outer_polygon != meshout.vertcnt.end());
  618. typedef boost::tuple<unsigned int, unsigned int, unsigned int> InsertionPoint;
  619. std::vector< InsertionPoint > insertions(*outer_polygon,boost::make_tuple(0u,0u,0u));
  620. // iterate through all other polyloops and find points in the outer polyloop that are close
  621. size_t vidx = 0;
  622. for(iit = begin; iit != meshout.vertcnt.end(); vidx += *iit++) {
  623. if (iit == outer_polygon) {
  624. continue;
  625. }
  626. size_t best_ofs,best_outer;
  627. float best_dist = 1e10;
  628. for(size_t vofs = 0; vofs < *iit; ++vofs) {
  629. const aiVector3D& v = meshout.verts[vidx+vofs];
  630. for(size_t outer = 0; outer < *outer_polygon; ++outer) {
  631. if (insertions[outer].get<0>()) {
  632. continue;
  633. }
  634. const aiVector3D& o = meshout.verts[outer_polygon_start+outer];
  635. const float d = (o-v).SquareLength();
  636. if (d < best_dist) {
  637. best_dist = d;
  638. best_ofs = vofs;
  639. best_outer = outer;
  640. }
  641. }
  642. }
  643. // we will later insert a hidden connection line right after the closest point in the outer polygon
  644. insertions[best_outer] = boost::make_tuple(*iit,vidx,best_ofs);
  645. }
  646. // now that we collected all vertex connections to be added, build the output polygon
  647. cnt = *outer_polygon;
  648. for(size_t outer = 0; outer < *outer_polygon; ++outer) {
  649. const aiVector3D& o = meshout.verts[outer_polygon_start+outer];
  650. result.verts.push_back(o);
  651. const InsertionPoint& ins = insertions[outer];
  652. if (!ins.get<0>()) {
  653. continue;
  654. }
  655. for(size_t i = ins.get<2>(); i < ins.get<0>(); ++i) {
  656. result.verts.push_back(meshout.verts[ins.get<1>() + i]);
  657. }
  658. for(size_t i = 0; i < ins.get<2>(); ++i) {
  659. result.verts.push_back(meshout.verts[ins.get<1>() + i]);
  660. }
  661. // we need the first vertex of the inner polygon twice as we return to the
  662. // outer loop through the very same connection through which we got there.
  663. result.verts.push_back(meshout.verts[ins.get<1>() + ins.get<2>()]);
  664. // also append a copy of the initial insertion point to be able to continue the outer polygon
  665. result.verts.push_back(o);
  666. cnt += ins.get<0>()+2;
  667. }
  668. result.vertcnt.push_back(cnt);
  669. }
  670. }
  671. // ------------------------------------------------------------------------------------------------
  672. void ProcessPolyLine(const IFC::IfcPolyline& def, TempMesh& meshout, ConversionData& conv)
  673. {
  674. // this won't produce a valid mesh, it just spits out a list of vertices
  675. aiVector3D t;
  676. BOOST_FOREACH(const IFC::IfcCartesianPoint& cp, def.Points) {
  677. ConvertCartesianPoint(t,cp);
  678. meshout.verts.push_back(t);
  679. }
  680. }
  681. // ------------------------------------------------------------------------------------------------
  682. void ProcessClosedProfile(const IFC::IfcArbitraryClosedProfileDef& def, TempMesh& meshout, ConversionData& conv)
  683. {
  684. if(const IFC::IfcPolyline* poly = def.OuterCurve->ToPtr<IFC::IfcPolyline>()) {
  685. ProcessPolyLine(*poly,meshout,conv);
  686. if(meshout.verts.size()>2 && meshout.verts.front() == meshout.verts.back()) {
  687. meshout.verts.pop_back(); // duplicate element, first==last
  688. }
  689. }
  690. else {
  691. IFCImporter::LogWarn("skipping unknown IfcCurve entity, type is " + def.OuterCurve->GetClassName());
  692. return;
  693. }
  694. }
  695. // ------------------------------------------------------------------------------------------------
  696. void ProcessOpenProfile(const IFC::IfcArbitraryOpenProfileDef& def, TempMesh& meshout, ConversionData& conv)
  697. {
  698. if(const IFC::IfcPolyline* poly = def.Curve->ToPtr<IFC::IfcPolyline>()) {
  699. ProcessPolyLine(*poly,meshout,conv);
  700. }
  701. else {
  702. IFCImporter::LogWarn("skipping unknown IfcBoundedCurve entity, type is " + def.Curve->GetClassName());
  703. return;
  704. }
  705. }
  706. // ------------------------------------------------------------------------------------------------
  707. void ProcessParametrizedProfile(const IFC::IfcParameterizedProfileDef& def, TempMesh& meshout, ConversionData& conv)
  708. {
  709. if(const IFC::IfcRectangleProfileDef* const cprofile = def.ToPtr<IFC::IfcRectangleProfileDef>()) {
  710. const float x = cprofile->XDim*0.5f, y = cprofile->YDim*0.5f;
  711. meshout.verts.reserve(meshout.verts.size()+4);
  712. meshout.verts.push_back( aiVector3D( x, y, 0.f ));
  713. meshout.verts.push_back( aiVector3D(-x, y, 0.f ));
  714. meshout.verts.push_back( aiVector3D(-x,-y, 0.f ));
  715. meshout.verts.push_back( aiVector3D( x,-y, 0.f ));
  716. meshout.vertcnt.push_back(4);
  717. }
  718. else if( const IFC::IfcCircleProfileDef* const circle = def.ToPtr<IFC::IfcCircleProfileDef>()) {
  719. if( const IFC::IfcCircleHollowProfileDef* const hollow = def.ToPtr<IFC::IfcCircleHollowProfileDef>()) {
  720. // TODO
  721. }
  722. const size_t segments = 32;
  723. const float delta = AI_MATH_TWO_PI_F/segments, radius = circle->Radius;
  724. meshout.verts.reserve(segments);
  725. float angle = 0.f;
  726. for(size_t i = 0; i < segments; ++i, angle += delta) {
  727. meshout.verts.push_back( aiVector3D( cos(angle)*radius, sin(angle)*radius, 0.f ));
  728. }
  729. meshout.vertcnt.push_back(segments);
  730. }
  731. else {
  732. IFCImporter::LogWarn("skipping unknown IfcParameterizedProfileDef entity, type is " + def.GetClassName());
  733. return;
  734. }
  735. aiMatrix4x4 trafo;
  736. ConvertAxisPlacement(trafo, *def.Position,conv);
  737. BOOST_FOREACH(aiVector3D& v, meshout.verts) {
  738. v *= trafo;
  739. }
  740. }
  741. // ------------------------------------------------------------------------------------------------
  742. bool ProcessProfile(const IFC::IfcProfileDef& prof, TempMesh& meshout, ConversionData& conv)
  743. {
  744. if(const IFC::IfcArbitraryClosedProfileDef* const cprofile = prof.ToPtr<IFC::IfcArbitraryClosedProfileDef>()) {
  745. ProcessClosedProfile(*cprofile,meshout,conv);
  746. }
  747. else if(const IFC::IfcArbitraryOpenProfileDef* const copen = prof.ToPtr<IFC::IfcArbitraryOpenProfileDef>()) {
  748. ProcessOpenProfile(*copen,meshout,conv);
  749. }
  750. else if(const IFC::IfcParameterizedProfileDef* const cparam = prof.ToPtr<IFC::IfcParameterizedProfileDef>()) {
  751. ProcessParametrizedProfile(*cparam,meshout,conv);
  752. }
  753. else {
  754. IFCImporter::LogWarn("skipping unknown IfcProfileDef entity, type is " + prof.GetClassName());
  755. return false;
  756. }
  757. return true;
  758. }
  759. // ------------------------------------------------------------------------------------------------
  760. void FixupFaceOrientation(TempMesh& result)
  761. {
  762. aiVector3D vavg;
  763. BOOST_FOREACH(aiVector3D& v, result.verts) {
  764. vavg += v;
  765. }
  766. // fixup face orientation.
  767. vavg /= static_cast<float>( result.verts.size() );
  768. size_t c = 0;
  769. BOOST_FOREACH(unsigned int cnt, result.vertcnt) {
  770. if (cnt>2){
  771. const aiVector3D& thisvert = result.verts[c];
  772. const aiVector3D normal((thisvert-result.verts[c+1])^(thisvert-result.verts[c+2]));
  773. if (normal*(thisvert-vavg) < 0) {
  774. std::reverse(result.verts.begin()+c,result.verts.begin()+cnt+c);
  775. }
  776. }
  777. c += cnt;
  778. }
  779. }
  780. // ------------------------------------------------------------------------------------------------
  781. void ProcessRevolvedAreaSolid(const IFC::IfcRevolvedAreaSolid& solid, TempMesh& result, ConversionData& conv)
  782. {
  783. TempMesh meshout;
  784. // first read the profile description
  785. if(!ProcessProfile(*solid.SweptArea,meshout,conv) || meshout.verts.size()<=1) {
  786. return;
  787. }
  788. aiVector3D axis, pos;
  789. ConvertAxisPlacement(axis,pos,solid.Axis,conv);
  790. aiMatrix4x4 tb0,tb1;
  791. aiMatrix4x4::Translation(pos,tb0);
  792. aiMatrix4x4::Translation(-pos,tb1);
  793. const std::vector<aiVector3D>& in = meshout.verts;
  794. const size_t size=in.size();
  795. bool has_area = solid.SweptArea->ProfileType == "AREA" && size>2;
  796. const float max_angle = solid.Angle*conv.angle_scale;
  797. if(fabs(max_angle) < 1e-3) {
  798. if(has_area) {
  799. result = meshout;
  800. }
  801. return;
  802. }
  803. const unsigned int cnt_segments = std::max(2u,static_cast<unsigned int>(16 * fabs(max_angle)/AI_MATH_HALF_PI_F));
  804. const float delta = max_angle/cnt_segments;
  805. has_area = has_area && fabs(max_angle) < AI_MATH_TWO_PI_F*0.99;
  806. result.verts.reserve(size*((cnt_segments+1)*4+(has_area?2:0)));
  807. result.vertcnt.reserve(size*cnt_segments+2);
  808. aiMatrix4x4 rot;
  809. rot = tb0 * aiMatrix4x4::Rotation(delta,axis,rot) * tb1;
  810. size_t base = 0;
  811. std::vector<aiVector3D>& out = result.verts;
  812. // dummy data to simplify later processing
  813. for(size_t i = 0; i < size; ++i) {
  814. out.insert(out.end(),4,in[i]);
  815. }
  816. for(unsigned int seg = 0; seg < cnt_segments; ++seg) {
  817. for(size_t i = 0; i < size; ++i) {
  818. const size_t next = (i+1)%size;
  819. result.vertcnt.push_back(4);
  820. const aiVector3D& base_0 = out[base+i*4+3],base_1 = out[base+next*4+3];
  821. out.push_back(base_0);
  822. out.push_back(base_1);
  823. out.push_back(rot*base_1);
  824. out.push_back(rot*base_0);
  825. }
  826. base += size*4;
  827. }
  828. out.erase(out.begin(),out.begin()+size*4);
  829. if(has_area) {
  830. // leave the triangulation of the profile area to the ear cutting
  831. // implementation in aiProcess_Triangulate - for now we just
  832. // feed in two huge polygons.
  833. base -= size*8;
  834. for(size_t i = size; i--; ) {
  835. out.push_back(out[base+i*4+3]);
  836. }
  837. for(size_t i = 0; i < size; ++i ) {
  838. out.push_back(out[i*4]);
  839. }
  840. result.vertcnt.push_back(size);
  841. result.vertcnt.push_back(size);
  842. }
  843. aiMatrix4x4 trafo;
  844. ConvertAxisPlacement(trafo, solid.Position,conv);
  845. BOOST_FOREACH(aiVector3D& v, out) {
  846. v *= trafo;
  847. }
  848. FixupFaceOrientation(result);
  849. IFCImporter::LogDebug("generate mesh procedurally by radial extrusion (IfcRevolvedAreaSolid)");
  850. }
  851. // ------------------------------------------------------------------------------------------------
  852. void ProcessExtrudedAreaSolid(const IFC::IfcExtrudedAreaSolid& solid, TempMesh& result, ConversionData& conv)
  853. {
  854. TempMesh meshout;
  855. // first read the profile description
  856. if(!ProcessProfile(*solid.SweptArea,meshout,conv) || meshout.verts.size()<=1) {
  857. return;
  858. }
  859. aiVector3D dir;
  860. ConvertDirection(dir,solid.ExtrudedDirection);
  861. dir *= solid.Depth;
  862. // assuming that `meshout.verts` is now a list of vertex points forming
  863. // the underlying profile, extrude along the given axis, forming new
  864. // triangles.
  865. const std::vector<aiVector3D>& in = meshout.verts;
  866. const size_t size=in.size();
  867. const bool has_area = solid.SweptArea->ProfileType == "AREA" && size>2;
  868. if(solid.Depth < 1e-3) {
  869. if(has_area) {
  870. meshout = result;
  871. }
  872. return;
  873. }
  874. result.verts.reserve(size*(has_area?4:2));
  875. result.vertcnt.reserve(meshout.vertcnt.size()+2);
  876. for(size_t i = 0; i < size; ++i) {
  877. const size_t next = (i+1)%size;
  878. result.vertcnt.push_back(4);
  879. result.verts.push_back(in[i]);
  880. result.verts.push_back(in[next]);
  881. result.verts.push_back(in[next]+dir);
  882. result.verts.push_back(in[i]+dir);
  883. }
  884. if(has_area) {
  885. // leave the triangulation of the profile area to the ear cutting
  886. // implementation in aiProcess_Triangulate - for now we just
  887. // feed in two huge polygons.
  888. for(size_t i = size; i--; ) {
  889. result.verts.push_back(in[i]+dir);
  890. }
  891. for(size_t i = 0; i < size; ++i ) {
  892. result.verts.push_back(in[i]);
  893. }
  894. result.vertcnt.push_back(size);
  895. result.vertcnt.push_back(size);
  896. }
  897. aiMatrix4x4 trafo;
  898. ConvertAxisPlacement(trafo, solid.Position,conv);
  899. BOOST_FOREACH(aiVector3D& v, result.verts) {
  900. v *= trafo;
  901. }
  902. FixupFaceOrientation(result);
  903. IFCImporter::LogDebug("generate mesh procedurally by extrusion (IfcExtrudedAreaSolid)");
  904. }
  905. // ------------------------------------------------------------------------------------------------
  906. void ProcessSweptAreaSolid(const IFC::IfcSweptAreaSolid& swept, TempMesh& meshout, ConversionData& conv)
  907. {
  908. if(const IFC::IfcExtrudedAreaSolid* const solid = swept.ToPtr<IFC::IfcExtrudedAreaSolid>()) {
  909. ProcessExtrudedAreaSolid(*solid,meshout,conv);
  910. }
  911. else if(const IFC::IfcRevolvedAreaSolid* const rev = swept.ToPtr<IFC::IfcRevolvedAreaSolid>()) {
  912. ProcessRevolvedAreaSolid(*rev,meshout,conv);
  913. }
  914. else {
  915. IFCImporter::LogWarn("skipping unknown IfcSweptAreaSolid entity, type is " + swept.GetClassName());
  916. }
  917. }
  918. // ------------------------------------------------------------------------------------------------
  919. void ProcessBoolean(const IFC::IfcBooleanResult& boolean, TempMesh& meshout, ConversionData& conv)
  920. {
  921. if(const IFC::IfcBooleanClippingResult* const clip = boolean.ToPtr<IFC::IfcBooleanClippingResult>()) {
  922. if(const IFC::IfcBooleanResult* const op0 = clip->FirstOperand->ResolveSelectPtr<IFC::IfcBooleanResult>(conv.db)) {
  923. ProcessBoolean(*op0,meshout,conv);
  924. }
  925. else if (const IFC::IfcSweptAreaSolid* const swept = clip->FirstOperand->ResolveSelectPtr<IFC::IfcSweptAreaSolid>(conv.db)) {
  926. ProcessSweptAreaSolid(*swept,meshout,conv);
  927. // XXX
  928. }
  929. }
  930. else {
  931. IFCImporter::LogWarn("skipping unknown IfcBooleanResult entity, type is " + boolean.GetClassName());
  932. }
  933. }
  934. // ------------------------------------------------------------------------------------------------
  935. int ConvertShadingMode(const std::string& name)
  936. {
  937. if (name == "BLINN") {
  938. return aiShadingMode_Blinn;
  939. }
  940. else if (name == "FLAT" || name == "NOTDEFINED") {
  941. return aiShadingMode_NoShading;
  942. }
  943. else if (name == "PHONG") {
  944. return aiShadingMode_Phong;
  945. }
  946. IFCImporter::LogWarn("shading mode "+name+" not recognized by Assimp, using Phong instead");
  947. return aiShadingMode_Phong;
  948. }
  949. // ------------------------------------------------------------------------------------------------
  950. unsigned int ProcessMaterials(const IFC::IfcRepresentationItem& item, ConversionData& conv)
  951. {
  952. aiString name;
  953. aiColor4D col;
  954. if (conv.materials.empty()) {
  955. std::auto_ptr<MaterialHelper> mat(new MaterialHelper());
  956. name.Set("<IFCDefault>");
  957. mat->AddProperty(&name,AI_MATKEY_NAME);
  958. col = aiColor4D(0.6f,0.6f,0.6f,1.0f);
  959. mat->AddProperty(&col,1, AI_MATKEY_COLOR_DIFFUSE);
  960. conv.materials.push_back(mat.release());
  961. }
  962. STEP::DB::RefMapRange range = conv.db.GetRefs().equal_range(item.GetID());
  963. for(;range.first != range.second; ++range.first) {
  964. if(const IFC::IfcStyledItem* const styled = conv.db.GetObject((*range.first).second)->ToPtr<IFC::IfcStyledItem>()) {
  965. BOOST_FOREACH(const IFC::IfcPresentationStyleAssignment& as, styled->Styles) {
  966. BOOST_FOREACH(const IFC::IfcPresentationStyleSelect* sel, as.Styles) {
  967. if (const IFC::IfcSurfaceStyle* surf = sel->ResolveSelectPtr<IFC::IfcSurfaceStyle>(conv.db)) {
  968. const std::string side = static_cast<std::string>(surf->Side);
  969. if (side != "BOTH") {
  970. IFCImporter::LogWarn("ignoring surface side marker on IFC::IfcSurfaceStyle: " + side);
  971. }
  972. std::auto_ptr<MaterialHelper> mat(new MaterialHelper());
  973. name.Set((surf->Name? surf->Name.Get() : "IfcSurfaceStyle_Unnamed"));
  974. mat->AddProperty(&name,AI_MATKEY_NAME);
  975. // now see which kinds of surface information are present
  976. BOOST_FOREACH(const IFC::IfcSurfaceStyleElementSelect* sel2, surf->Styles) {
  977. if (const IFC::IfcSurfaceStyleShading* shade = sel2->ResolveSelectPtr<IFC::IfcSurfaceStyleShading>(conv.db)) {
  978. aiColor4D col_base;
  979. ConvertColor(col_base, shade->SurfaceColour);
  980. mat->AddProperty(&col,1, AI_MATKEY_COLOR_DIFFUSE);
  981. if (const IFC::IfcSurfaceStyleRendering* ren = shade->ToPtr<IFC::IfcSurfaceStyleRendering>()) {
  982. if (ren->DiffuseColour) {
  983. ConvertColor(col, ren->DiffuseColour.Get(),conv,&col_base);
  984. mat->AddProperty(&col,1, AI_MATKEY_COLOR_DIFFUSE);
  985. }
  986. if (ren->SpecularColour) {
  987. ConvertColor(col, ren->SpecularColour.Get(),conv,&col_base);
  988. mat->AddProperty(&col,1, AI_MATKEY_COLOR_SPECULAR);
  989. }
  990. if (ren->TransmissionColour) {
  991. ConvertColor(col, ren->TransmissionColour.Get(),conv,&col_base);
  992. mat->AddProperty(&col,1, AI_MATKEY_COLOR_TRANSPARENT);
  993. }
  994. if (ren->ReflectionColour) {
  995. ConvertColor(col, ren->ReflectionColour.Get(),conv,&col_base);
  996. mat->AddProperty(&col,1, AI_MATKEY_COLOR_REFLECTIVE);
  997. }
  998. const int shading = (ren->SpecularHighlight && ren->SpecularColour)?ConvertShadingMode(ren->ReflectanceMethod):aiShadingMode_Gouraud;
  999. mat->AddProperty(&shading,1, AI_MATKEY_SHADING_MODEL);
  1000. if (ren->SpecularHighlight) {
  1001. if(const EXPRESS::REAL* rt = ren->SpecularHighlight.Get()->ToPtr<EXPRESS::REAL>()) {
  1002. // at this point we don't distinguish between the two distinct ways of
  1003. // specifying highlight intensities. leave this to the user.
  1004. const float e = *rt;
  1005. mat->AddProperty(&e,1,AI_MATKEY_SHININESS);
  1006. }
  1007. else {
  1008. IFCImporter::LogWarn("unexpected type error, SpecularHighlight should be a REAL");
  1009. }
  1010. }
  1011. }
  1012. }
  1013. else if (const IFC::IfcSurfaceStyleWithTextures* tex = sel2->ResolveSelectPtr<IFC::IfcSurfaceStyleWithTextures>(conv.db)) {
  1014. // XXX
  1015. }
  1016. }
  1017. conv.materials.push_back(mat.release());
  1018. return conv.materials.size()-1;
  1019. }
  1020. }
  1021. }
  1022. }
  1023. }
  1024. return 0;
  1025. }
  1026. // ------------------------------------------------------------------------------------------------
  1027. bool ProcessTopologicalItem(const IFC::IfcTopologicalRepresentationItem& topo, std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  1028. {
  1029. TempMesh meshtmp;
  1030. if(const IFC::IfcConnectedFaceSet* fset = topo.ToPtr<IFC::IfcConnectedFaceSet>()) {
  1031. ProcessConnectedFaceSet(*fset,meshtmp,conv);
  1032. }
  1033. else {
  1034. IFCImporter::LogWarn("skipping unknown IfcTopologicalRepresentationItem entity, type is " + topo.GetClassName());
  1035. return false;
  1036. }
  1037. aiMesh* const mesh = meshtmp.ToMesh();
  1038. if(mesh) {
  1039. mesh->mMaterialIndex = ProcessMaterials(topo,conv);
  1040. mesh_indices.push_back(conv.meshes.size());
  1041. conv.meshes.push_back(mesh);
  1042. return true;
  1043. }
  1044. return false;
  1045. }
  1046. // ------------------------------------------------------------------------------------------------
  1047. bool ProcessGeometricItem(const IFC::IfcGeometricRepresentationItem& geo, std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  1048. {
  1049. TempMesh meshtmp;
  1050. if(const IFC::IfcShellBasedSurfaceModel* shellmod = geo.ToPtr<IFC::IfcShellBasedSurfaceModel>()) {
  1051. BOOST_FOREACH(const IFC::IfcShell* shell,shellmod->SbsmBoundary) {
  1052. try {
  1053. const EXPRESS::ENTITY& e = shell->To<IFC::ENTITY>();
  1054. const IFC::IfcConnectedFaceSet& fs = conv.db.MustGetObject(e).To<IFC::IfcConnectedFaceSet>();
  1055. ProcessConnectedFaceSet(fs,meshtmp,conv);
  1056. }
  1057. catch(std::bad_cast&) {
  1058. IFCImporter::LogWarn("unexpected type error, IfcShell ought to inherit from IfcConnectedFaceSet");
  1059. }
  1060. }
  1061. }
  1062. else if(const IFC::IfcSweptAreaSolid* swept = geo.ToPtr<IFC::IfcSweptAreaSolid>()) {
  1063. ProcessSweptAreaSolid(*swept,meshtmp,conv);
  1064. }
  1065. else if(const IFC::IfcManifoldSolidBrep* brep = geo.ToPtr<IFC::IfcManifoldSolidBrep>()) {
  1066. ProcessConnectedFaceSet(brep->Outer,meshtmp,conv);
  1067. }
  1068. else if(const IFC::IfcFaceBasedSurfaceModel* surf = geo.ToPtr<IFC::IfcFaceBasedSurfaceModel>()) {
  1069. BOOST_FOREACH(const IFC::IfcConnectedFaceSet& fc, surf->FbsmFaces) {
  1070. ProcessConnectedFaceSet(fc,meshtmp,conv);
  1071. }
  1072. }
  1073. else if(const IFC::IfcBooleanResult* boolean = geo.ToPtr<IFC::IfcBooleanResult>()) {
  1074. ProcessBoolean(*boolean,meshtmp,conv);
  1075. }
  1076. else if(const IFC::IfcBoundingBox* bb = geo.ToPtr<IFC::IfcBoundingBox>()) {
  1077. // silently skip over bounding boxes
  1078. return false;
  1079. }
  1080. else {
  1081. IFCImporter::LogWarn("skipping unknown IfcGeometricRepresentationItem entity, type is " + geo.GetClassName());
  1082. return false;
  1083. }
  1084. aiMesh* const mesh = meshtmp.ToMesh();
  1085. if(mesh) {
  1086. mesh->mMaterialIndex = ProcessMaterials(geo,conv);
  1087. mesh_indices.push_back(conv.meshes.size());
  1088. conv.meshes.push_back(mesh);
  1089. return true;
  1090. }
  1091. return false;
  1092. }
  1093. // ------------------------------------------------------------------------------------------------
  1094. void AssignAddedMeshes(std::vector<unsigned int>& mesh_indices,aiNode* nd,ConversionData& conv)
  1095. {
  1096. if (!mesh_indices.empty()) {
  1097. // make unique
  1098. std::sort(mesh_indices.begin(),mesh_indices.end());
  1099. std::vector<unsigned int>::iterator it_end = std::unique(mesh_indices.begin(),mesh_indices.end());
  1100. const size_t size = std::distance(mesh_indices.begin(),it_end);
  1101. nd->mNumMeshes = size;
  1102. nd->mMeshes = new unsigned int[nd->mNumMeshes];
  1103. for(unsigned int i = 0; i < nd->mNumMeshes; ++i) {
  1104. nd->mMeshes[i] = mesh_indices[i];
  1105. }
  1106. }
  1107. }
  1108. // ------------------------------------------------------------------------------------------------
  1109. bool TryQueryMeshCache(const IFC::IfcRepresentationItem& item, std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  1110. {
  1111. ConversionData::MeshCache::const_iterator it = conv.cached_meshes.find(&item);
  1112. if (it != conv.cached_meshes.end()) {
  1113. std::copy((*it).second.begin(),(*it).second.end(),std::back_inserter(mesh_indices));
  1114. return true;
  1115. }
  1116. return false;
  1117. }
  1118. // ------------------------------------------------------------------------------------------------
  1119. void PopulateMeshCache(const IFC::IfcRepresentationItem& item, const std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  1120. {
  1121. conv.cached_meshes[&item] = mesh_indices;
  1122. }
  1123. // ------------------------------------------------------------------------------------------------
  1124. bool ProcessRepresentationItem(const IFC::IfcRepresentationItem& item, std::vector<unsigned int>& mesh_indices, ConversionData& conv)
  1125. {
  1126. if(const IFC::IfcTopologicalRepresentationItem* const topo = item.ToPtr<IFC::IfcTopologicalRepresentationItem>()) {
  1127. if (!TryQueryMeshCache(item,mesh_indices,conv)) {
  1128. if(ProcessTopologicalItem(*topo,mesh_indices,conv)) {
  1129. PopulateMeshCache(item,mesh_indices,conv);
  1130. }
  1131. else return false;
  1132. }
  1133. return true;
  1134. }
  1135. else if(const IFC::IfcGeometricRepresentationItem* const geo = item.ToPtr<IFC::IfcGeometricRepresentationItem>()) {
  1136. if (!TryQueryMeshCache(item,mesh_indices,conv)) {
  1137. if(ProcessGeometricItem(*geo,mesh_indices,conv)) {
  1138. PopulateMeshCache(item,mesh_indices,conv);
  1139. }
  1140. else return false;
  1141. }
  1142. return true;
  1143. }
  1144. return false;
  1145. }
  1146. // ------------------------------------------------------------------------------------------------
  1147. void ResolveObjectPlacement(aiMatrix4x4& m, const IFC::IfcObjectPlacement& place, ConversionData& conv)
  1148. {
  1149. if (const IFC::IfcLocalPlacement* const local = place.ToPtr<IFC::IfcLocalPlacement>()){
  1150. ConvertAxisPlacement(m, *local->RelativePlacement, conv);
  1151. if (local->PlacementRelTo) {
  1152. aiMatrix4x4 tmp;
  1153. ResolveObjectPlacement(tmp,local->PlacementRelTo.Get(),conv);
  1154. m = tmp * m;
  1155. }
  1156. }
  1157. else {
  1158. IFCImporter::LogWarn("skipping unknown IfcObjectPlacement entity, type is " + place.GetClassName());
  1159. }
  1160. }
  1161. // ------------------------------------------------------------------------------------------------
  1162. void GetAbsTransform(aiMatrix4x4& out, const aiNode* nd, ConversionData& conv)
  1163. {
  1164. aiMatrix4x4 t;
  1165. if (nd->mParent) {
  1166. GetAbsTransform(t,nd->mParent,conv);
  1167. }
  1168. out = t*nd->mTransformation;
  1169. }
  1170. // ------------------------------------------------------------------------------------------------
  1171. void ProcessMappedItem(const IFC::IfcMappedItem& mapped, aiNode* nd_src, std::vector< aiNode* >& subnodes_src, ConversionData& conv)
  1172. {
  1173. // insert a custom node here, the cartesian transform operator is simply a conventional transformation matrix
  1174. std::auto_ptr<aiNode> nd(new aiNode());
  1175. nd->mName.Set("MappedItem");
  1176. std::vector<unsigned int> meshes;
  1177. const IFC::IfcRepresentation& repr = mapped.MappingSource->MappedRepresentation;
  1178. BOOST_FOREACH(const IFC::IfcRepresentationItem& item, repr.Items) {
  1179. if(!ProcessRepresentationItem(item,meshes,conv)) {
  1180. IFCImporter::LogWarn("skipping unknown mapped entity, type is " + item.GetClassName());
  1181. }
  1182. }
  1183. AssignAddedMeshes(meshes,nd.get(),conv);
  1184. // handle the cartesian operator
  1185. aiMatrix4x4 m;
  1186. ConvertTransformOperator(m, *mapped.MappingTarget);
  1187. aiMatrix4x4 msrc;
  1188. ConvertAxisPlacement(msrc,*mapped.MappingSource->MappingOrigin,conv);
  1189. aiMatrix4x4 minv = msrc;
  1190. minv.Inverse();
  1191. //aiMatrix4x4 correct;
  1192. //GetAbsTransform(correct,nd_src,conv);
  1193. nd->mTransformation = nd_src->mTransformation * minv * m * msrc;
  1194. subnodes_src.push_back(nd.release());
  1195. }
  1196. // ------------------------------------------------------------------------------------------------
  1197. void ProcessProductRepresentation(const IFC::IfcProduct& el, aiNode* nd, std::vector< aiNode* >& subnodes, ConversionData& conv)
  1198. {
  1199. if(!el.Representation) {
  1200. return;
  1201. }
  1202. if(conv.settings.skipSpaceRepresentations) {
  1203. if(const IFC::IfcSpace* const space = el.ToPtr<IFC::IfcSpace>()) {
  1204. IFCImporter::LogWarn("skipping IfcSpace entity due to importer settings");
  1205. return;
  1206. }
  1207. }
  1208. std::vector<unsigned int> meshes;
  1209. BOOST_FOREACH(const IFC::IfcRepresentation& repr, el.Representation.Get()->Representations) {
  1210. if (conv.settings.skipCurveRepresentations && repr.RepresentationType && repr.RepresentationType.Get() == "Curve2D") {
  1211. IFCImporter::LogWarn("skipping Curve2D representation item due to importer settings");
  1212. continue;
  1213. }
  1214. BOOST_FOREACH(const IFC::IfcRepresentationItem& item, repr.Items) {
  1215. if(const IFC::IfcMappedItem* const geo = item.ToPtr<IFC::IfcMappedItem>()) {
  1216. ProcessMappedItem(*geo,nd,subnodes,conv);
  1217. }
  1218. else {
  1219. ProcessRepresentationItem(item,meshes,conv);
  1220. }
  1221. }
  1222. }
  1223. AssignAddedMeshes(meshes,nd,conv);
  1224. }
  1225. // ------------------------------------------------------------------------------------------------
  1226. aiNode* ProcessSpatialStructure(aiNode* parent, const IFC::IfcProduct& el, ConversionData& conv)
  1227. {
  1228. const STEP::DB::RefMap& refs = conv.db.GetRefs();
  1229. // add an output node for this spatial structure
  1230. std::auto_ptr<aiNode> nd(new aiNode());
  1231. nd->mName.Set(el.GetClassName()+"_"+(el.Name?el.Name:el.GlobalId));
  1232. nd->mParent = parent;
  1233. if(el.ObjectPlacement) {
  1234. ResolveObjectPlacement(nd->mTransformation,el.ObjectPlacement.Get(),conv);
  1235. }
  1236. // convert everything contained directly within this structure,
  1237. // this may result in more nodes.
  1238. std::vector< aiNode* > subnodes;
  1239. try {
  1240. ProcessProductRepresentation(el,nd.get(),subnodes,conv);
  1241. // locate aggregates and 'contained-in-here'-elements of this spatial structure and add them in recursively
  1242. STEP::DB::RefMapRange range = refs.equal_range(el.GetID());
  1243. for(STEP::DB::RefMapRange range2=range;range2.first != range.second; ++range2.first) {
  1244. if(const IFC::IfcRelContainedInSpatialStructure* const cont = conv.db.GetObject((*range2.first).second)->
  1245. ToPtr<IFC::IfcRelContainedInSpatialStructure>()) {
  1246. BOOST_FOREACH(const IFC::IfcProduct& pro, cont->RelatedElements) {
  1247. subnodes.push_back( ProcessSpatialStructure(nd.get(),pro,conv) );
  1248. }
  1249. break;
  1250. }
  1251. }
  1252. for(;range.first != range.second; ++range.first) {
  1253. if(const IFC::IfcRelAggregates* const aggr = conv.db.GetObject((*range.first).second)->ToPtr<IFC::IfcRelAggregates>()) {
  1254. // move aggregate elements to a separate node since they are semantically different than elements that are merely 'contained'
  1255. std::auto_ptr<aiNode> nd_aggr(new aiNode());
  1256. nd_aggr->mName.Set("$Aggregates");
  1257. nd_aggr->mParent = nd.get();
  1258. nd_aggr->mChildren = new aiNode*[aggr->RelatedObjects.size()]();
  1259. BOOST_FOREACH(const IFC::IfcObjectDefinition& def, aggr->RelatedObjects) {
  1260. if(const IFC::IfcProduct* const prod = def.ToPtr<IFC::IfcProduct>()) {
  1261. nd_aggr->mChildren[nd_aggr->mNumChildren++] = ProcessSpatialStructure(nd_aggr.get(),*prod,conv);
  1262. }
  1263. }
  1264. subnodes.push_back( nd_aggr.release() );
  1265. break;
  1266. }
  1267. }
  1268. if (subnodes.size()) {
  1269. nd->mChildren = new aiNode*[subnodes.size()]();
  1270. BOOST_FOREACH(aiNode* nd2, subnodes) {
  1271. nd->mChildren[nd->mNumChildren++] = nd2;
  1272. nd2->mParent = nd.get();
  1273. }
  1274. }
  1275. }
  1276. catch(...) {
  1277. // it hurts, but I don't want to pull boost::ptr_vector into -noboost only for these few spots here
  1278. std::for_each(subnodes.begin(),subnodes.end(),delete_fun<aiNode>());
  1279. throw;
  1280. }
  1281. return nd.release();
  1282. }
  1283. // ------------------------------------------------------------------------------------------------
  1284. void ProcessSpatialStructures(ConversionData& conv)
  1285. {
  1286. // process all products in the file. it is reasonable to assume that a
  1287. // file that is relevant for us contains at least a site or a building.
  1288. const STEP::DB::ObjectMapByType& map = conv.db.GetObjectsByType();
  1289. STEP::DB::ObjectMapRange range = map.equal_range("ifcsite");
  1290. if (range.first == map.end()) {
  1291. range = map.equal_range("ifcbuilding");
  1292. if (range.first == map.end()) {
  1293. // no site, no building - try all ids. this will take ages, but it should rarely happen.
  1294. range = STEP::DB::ObjectMapRange(map.begin(),map.end());
  1295. }
  1296. }
  1297. for(;range.first != range.second; ++range.first) {
  1298. const IFC::IfcSpatialStructureElement* const prod = (*range.first).second->ToPtr<IFC::IfcSpatialStructureElement>();
  1299. if(!prod) {
  1300. continue;
  1301. }
  1302. IFCImporter::LogDebug("looking at spatial structure `" + (prod->Name ? prod->Name.Get() : "unnamed") + "`" + (prod->ObjectType? " which is of type " + prod->ObjectType.Get():""));
  1303. // the primary site is referenced by an IFCRELAGGREGATES element which assigns it to the IFCPRODUCT
  1304. const STEP::DB::RefMap& refs = conv.db.GetRefs();
  1305. STEP::DB::RefMapRange range = refs.equal_range(conv.proj.GetID());
  1306. for(;range.first != range.second; ++range.first) {
  1307. if(const IFC::IfcRelAggregates* const aggr = conv.db.GetObject((*range.first).second)->ToPtr<IFC::IfcRelAggregates>()) {
  1308. BOOST_FOREACH(const IFC::IfcObjectDefinition& def, aggr->RelatedObjects) {
  1309. // comparing pointer values is not sufficient, we would need to cast them to the same type first
  1310. // as there is multiple inheritance in the game.
  1311. if (def.GlobalId == prod->GlobalId) {
  1312. IFCImporter::LogDebug("selecting this spatial structure as root structure");
  1313. // got it, this is the primary site.
  1314. conv.out->mRootNode = ProcessSpatialStructure(NULL,*prod,conv);
  1315. return;
  1316. }
  1317. }
  1318. }
  1319. }
  1320. }
  1321. IFCImporter::ThrowException("Failed to determine primary site element");
  1322. }
  1323. // ------------------------------------------------------------------------------------------------
  1324. void MakeTreeRelative(aiNode* start, const aiMatrix4x4& combined)
  1325. {
  1326. // combined is the parent's absolute transformation matrix
  1327. aiMatrix4x4 old = start->mTransformation;
  1328. if (!combined.IsIdentity()) {
  1329. start->mTransformation = aiMatrix4x4(combined).Inverse() * start->mTransformation;
  1330. }
  1331. // All nodes store absolute transformations right now, so we need to make them relative
  1332. for (unsigned int i = 0; i < start->mNumChildren; ++i) {
  1333. MakeTreeRelative(start->mChildren[i],old);
  1334. }
  1335. }
  1336. // ------------------------------------------------------------------------------------------------
  1337. void MakeTreeRelative(ConversionData& conv)
  1338. {
  1339. MakeTreeRelative(conv.out->mRootNode,aiMatrix4x4());
  1340. }
  1341. } // !anon
  1342. #endif