D3MFImporter.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2019, 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. #ifndef ASSIMP_BUILD_NO_3MF_IMPORTER
  34. #include "D3MFImporter.h"
  35. #include <assimp/scene.h>
  36. #include <assimp/IOSystem.hpp>
  37. #include <assimp/DefaultLogger.hpp>
  38. #include <assimp/importerdesc.h>
  39. #include <assimp/StringComparison.h>
  40. #include <assimp/StringUtils.h>
  41. #include <string>
  42. #include <vector>
  43. #include <map>
  44. #include <cassert>
  45. #include <memory>
  46. #include "D3MFOpcPackage.h"
  47. #include <unzip.h>
  48. #include <assimp/irrXMLWrapper.h>
  49. #include "3MFXmlTags.h"
  50. #include <assimp/fast_atof.h>
  51. #include <iomanip>
  52. namespace Assimp {
  53. namespace D3MF {
  54. class XmlSerializer {
  55. public:
  56. using MatArray = std::vector<aiMaterial*>;
  57. using MatId2MatArray = std::map<unsigned int, std::vector<unsigned int>>;
  58. XmlSerializer(XmlReader* xmlReader)
  59. : mMeshes()
  60. , mMatArray()
  61. , mActiveMatGroup( 99999999 )
  62. , mMatId2MatArray()
  63. , xmlReader(xmlReader){
  64. // empty
  65. }
  66. ~XmlSerializer() {
  67. // empty
  68. }
  69. void ImportXml(aiScene* scene) {
  70. if ( nullptr == scene ) {
  71. return;
  72. }
  73. scene->mRootNode = new aiNode();
  74. std::vector<aiNode*> children;
  75. std::string nodeName;
  76. while(ReadToEndElement(D3MF::XmlTag::model)) {
  77. nodeName = xmlReader->getNodeName();
  78. if( nodeName == D3MF::XmlTag::object) {
  79. children.push_back(ReadObject(scene));
  80. } else if( nodeName == D3MF::XmlTag::build) {
  81. //
  82. } else if ( nodeName == D3MF::XmlTag::basematerials ) {
  83. ReadBaseMaterials();
  84. } else if ( nodeName == D3MF::XmlTag::meta ) {
  85. ReadMetadata();
  86. }
  87. }
  88. if ( scene->mRootNode->mName.length == 0 ) {
  89. scene->mRootNode->mName.Set( "3MF" );
  90. }
  91. // import the metadata
  92. if ( !mMetaData.empty() ) {
  93. const size_t numMeta( mMetaData.size() );
  94. scene->mMetaData = aiMetadata::Alloc(static_cast<unsigned int>( numMeta ) );
  95. for ( size_t i = 0; i < numMeta; ++i ) {
  96. aiString val( mMetaData[ i ].value );
  97. scene->mMetaData->Set(static_cast<unsigned int>( i ), mMetaData[ i ].name, val );
  98. }
  99. }
  100. // import the meshes
  101. scene->mNumMeshes = static_cast<unsigned int>( mMeshes.size());
  102. scene->mMeshes = new aiMesh*[scene->mNumMeshes]();
  103. std::copy( mMeshes.begin(), mMeshes.end(), scene->mMeshes);
  104. // import the materials
  105. scene->mNumMaterials = static_cast<unsigned int>( mMatArray.size() );
  106. if ( 0 != scene->mNumMaterials ) {
  107. scene->mMaterials = new aiMaterial*[ scene->mNumMaterials ];
  108. std::copy( mMatArray.begin(), mMatArray.end(), scene->mMaterials );
  109. }
  110. // create the scenegraph
  111. scene->mRootNode->mNumChildren = static_cast<unsigned int>(children.size());
  112. scene->mRootNode->mChildren = new aiNode*[scene->mRootNode->mNumChildren]();
  113. std::copy(children.begin(), children.end(), scene->mRootNode->mChildren);
  114. }
  115. private:
  116. aiNode* ReadObject(aiScene* scene) {
  117. std::unique_ptr<aiNode> node(new aiNode());
  118. std::vector<unsigned long> meshIds;
  119. const char *attrib( nullptr );
  120. std::string name, type;
  121. attrib = xmlReader->getAttributeValue( D3MF::XmlTag::id.c_str() );
  122. if ( nullptr != attrib ) {
  123. name = attrib;
  124. }
  125. attrib = xmlReader->getAttributeValue( D3MF::XmlTag::type.c_str() );
  126. if ( nullptr != attrib ) {
  127. type = attrib;
  128. }
  129. node->mParent = scene->mRootNode;
  130. node->mName.Set(name);
  131. size_t meshIdx = mMeshes.size();
  132. while(ReadToEndElement(D3MF::XmlTag::object)) {
  133. if(xmlReader->getNodeName() == D3MF::XmlTag::mesh) {
  134. auto mesh = ReadMesh();
  135. mesh->mName.Set(name);
  136. mMeshes.push_back(mesh);
  137. meshIds.push_back(static_cast<unsigned long>(meshIdx));
  138. ++meshIdx;
  139. }
  140. }
  141. node->mNumMeshes = static_cast<unsigned int>(meshIds.size());
  142. node->mMeshes = new unsigned int[node->mNumMeshes];
  143. std::copy(meshIds.begin(), meshIds.end(), node->mMeshes);
  144. return node.release();
  145. }
  146. aiMesh *ReadMesh() {
  147. aiMesh* mesh = new aiMesh();
  148. while(ReadToEndElement(D3MF::XmlTag::mesh)) {
  149. if(xmlReader->getNodeName() == D3MF::XmlTag::vertices) {
  150. ImportVertices(mesh);
  151. } else if(xmlReader->getNodeName() == D3MF::XmlTag::triangles) {
  152. ImportTriangles(mesh);
  153. }
  154. }
  155. return mesh;
  156. }
  157. void ReadMetadata() {
  158. const std::string name = xmlReader->getAttributeValue( D3MF::XmlTag::meta_name.c_str() );
  159. xmlReader->read();
  160. const std::string value = xmlReader->getNodeData();
  161. if ( name.empty() ) {
  162. return;
  163. }
  164. MetaEntry entry;
  165. entry.name = name;
  166. entry.value = value;
  167. mMetaData.push_back( entry );
  168. }
  169. void ImportVertices(aiMesh* mesh) {
  170. std::vector<aiVector3D> vertices;
  171. while(ReadToEndElement(D3MF::XmlTag::vertices)) {
  172. if(xmlReader->getNodeName() == D3MF::XmlTag::vertex) {
  173. vertices.push_back(ReadVertex());
  174. }
  175. }
  176. mesh->mNumVertices = static_cast<unsigned int>(vertices.size());
  177. mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  178. std::copy(vertices.begin(), vertices.end(), mesh->mVertices);
  179. }
  180. aiVector3D ReadVertex() {
  181. aiVector3D vertex;
  182. vertex.x = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::x.c_str()), nullptr);
  183. vertex.y = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::y.c_str()), nullptr);
  184. vertex.z = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::z.c_str()), nullptr);
  185. return vertex;
  186. }
  187. void ImportTriangles(aiMesh* mesh) {
  188. std::vector<aiFace> faces;
  189. while(ReadToEndElement(D3MF::XmlTag::triangles)) {
  190. const std::string nodeName( xmlReader->getNodeName() );
  191. if(xmlReader->getNodeName() == D3MF::XmlTag::triangle) {
  192. faces.push_back(ReadTriangle());
  193. const char *pidToken( xmlReader->getAttributeValue( D3MF::XmlTag::p1.c_str() ) );
  194. if ( nullptr != pidToken ) {
  195. int matIdx( std::atoi( pidToken ) );
  196. mesh->mMaterialIndex = matIdx;
  197. }
  198. }
  199. }
  200. mesh->mNumFaces = static_cast<unsigned int>(faces.size());
  201. mesh->mFaces = new aiFace[mesh->mNumFaces];
  202. mesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  203. std::copy(faces.begin(), faces.end(), mesh->mFaces);
  204. }
  205. aiFace ReadTriangle() {
  206. aiFace face;
  207. face.mNumIndices = 3;
  208. face.mIndices = new unsigned int[face.mNumIndices];
  209. face.mIndices[0] = static_cast<unsigned int>(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v1.c_str())));
  210. face.mIndices[1] = static_cast<unsigned int>(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v2.c_str())));
  211. face.mIndices[2] = static_cast<unsigned int>(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v3.c_str())));
  212. return face;
  213. }
  214. void ReadBaseMaterials() {
  215. std::vector<unsigned int> MatIdArray;
  216. const char *baseMaterialId( xmlReader->getAttributeValue( D3MF::XmlTag::basematerials_id.c_str() ) );
  217. if ( nullptr != baseMaterialId ) {
  218. unsigned int id = std::atoi( baseMaterialId );
  219. const size_t newMatIdx( mMatArray.size() );
  220. if ( id != mActiveMatGroup ) {
  221. mActiveMatGroup = id;
  222. MatId2MatArray::const_iterator it( mMatId2MatArray.find( id ) );
  223. if ( mMatId2MatArray.end() == it ) {
  224. MatIdArray.clear();
  225. mMatId2MatArray[ id ] = MatIdArray;
  226. } else {
  227. MatIdArray = it->second;
  228. }
  229. }
  230. MatIdArray.push_back( static_cast<unsigned int>( newMatIdx ) );
  231. mMatId2MatArray[ mActiveMatGroup ] = MatIdArray;
  232. }
  233. while ( ReadToEndElement( D3MF::XmlTag::basematerials ) ) {
  234. mMatArray.push_back( readMaterialDef() );
  235. }
  236. }
  237. bool parseColor( const char *color, aiColor4D &diffuse ) {
  238. if ( nullptr == color ) {
  239. return false;
  240. }
  241. //format of the color string: #RRGGBBAA or #RRGGBB (3MF Core chapter 5.1.1)
  242. const size_t len( strlen( color ) );
  243. if ( 9 != len && 7 != len) {
  244. return false;
  245. }
  246. const char *buf( color );
  247. if ( '#' != *buf ) {
  248. return false;
  249. }
  250. ++buf;
  251. char comp[ 3 ] = { 0,0,'\0' };
  252. comp[ 0 ] = *buf;
  253. ++buf;
  254. comp[ 1 ] = *buf;
  255. ++buf;
  256. diffuse.r = static_cast<ai_real>( strtol( comp, NULL, 16 ) ) / ai_real(255.0);
  257. comp[ 0 ] = *buf;
  258. ++buf;
  259. comp[ 1 ] = *buf;
  260. ++buf;
  261. diffuse.g = static_cast< ai_real >( strtol( comp, NULL, 16 ) ) / ai_real(255.0);
  262. comp[ 0 ] = *buf;
  263. ++buf;
  264. comp[ 1 ] = *buf;
  265. ++buf;
  266. diffuse.b = static_cast< ai_real >( strtol( comp, NULL, 16 ) ) / ai_real(255.0);
  267. if(7 == len)
  268. return true;
  269. comp[ 0 ] = *buf;
  270. ++buf;
  271. comp[ 1 ] = *buf;
  272. ++buf;
  273. diffuse.a = static_cast< ai_real >( strtol( comp, NULL, 16 ) ) / ai_real(255.0);
  274. return true;
  275. }
  276. void assignDiffuseColor( aiMaterial *mat ) {
  277. const char *color = xmlReader->getAttributeValue( D3MF::XmlTag::basematerials_displaycolor.c_str() );
  278. aiColor4D diffuse;
  279. if ( parseColor( color, diffuse ) ) {
  280. mat->AddProperty<aiColor4D>( &diffuse, 1, AI_MATKEY_COLOR_DIFFUSE );
  281. }
  282. }
  283. aiMaterial *readMaterialDef() {
  284. aiMaterial *mat( nullptr );
  285. const char *name( nullptr );
  286. const std::string nodeName( xmlReader->getNodeName() );
  287. if ( nodeName == D3MF::XmlTag::basematerials_base ) {
  288. name = xmlReader->getAttributeValue( D3MF::XmlTag::basematerials_name.c_str() );
  289. std::string stdMatName;
  290. aiString matName;
  291. std::string strId( to_string( mActiveMatGroup ) );
  292. stdMatName += "id";
  293. stdMatName += strId;
  294. stdMatName += "_";
  295. if ( nullptr != name ) {
  296. stdMatName += std::string( name );
  297. } else {
  298. stdMatName += "basemat";
  299. }
  300. matName.Set( stdMatName );
  301. mat = new aiMaterial;
  302. mat->AddProperty( &matName, AI_MATKEY_NAME );
  303. assignDiffuseColor( mat );
  304. }
  305. return mat;
  306. }
  307. private:
  308. bool ReadToStartElement(const std::string& startTag) {
  309. while(xmlReader->read()) {
  310. const std::string &nodeName( xmlReader->getNodeName() );
  311. if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT && nodeName == startTag) {
  312. return true;
  313. } else if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT_END && nodeName == startTag) {
  314. return false;
  315. }
  316. }
  317. return false;
  318. }
  319. bool ReadToEndElement(const std::string& closeTag) {
  320. while(xmlReader->read()) {
  321. const std::string &nodeName( xmlReader->getNodeName() );
  322. if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT) {
  323. return true;
  324. } else if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT_END && nodeName == closeTag) {
  325. return false;
  326. }
  327. }
  328. ASSIMP_LOG_ERROR("unexpected EOF, expected closing <" + closeTag + "> tag");
  329. return false;
  330. }
  331. private:
  332. struct MetaEntry {
  333. std::string name;
  334. std::string value;
  335. };
  336. std::vector<MetaEntry> mMetaData;
  337. std::vector<aiMesh*> mMeshes;
  338. MatArray mMatArray;
  339. unsigned int mActiveMatGroup;
  340. MatId2MatArray mMatId2MatArray;
  341. XmlReader* xmlReader;
  342. };
  343. } //namespace D3MF
  344. static const aiImporterDesc desc = {
  345. "3mf Importer",
  346. "",
  347. "",
  348. "http://3mf.io/",
  349. aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_SupportCompressedFlavour,
  350. 0,
  351. 0,
  352. 0,
  353. 0,
  354. "3mf"
  355. };
  356. D3MFImporter::D3MFImporter()
  357. : BaseImporter() {
  358. // empty
  359. }
  360. D3MFImporter::~D3MFImporter() {
  361. // empty
  362. }
  363. bool D3MFImporter::CanRead(const std::string &filename, IOSystem *pIOHandler, bool checkSig) const {
  364. const std::string extension( GetExtension( filename ) );
  365. if(extension == desc.mFileExtensions ) {
  366. return true;
  367. } else if ( !extension.length() || checkSig ) {
  368. if ( nullptr == pIOHandler ) {
  369. return false;
  370. }
  371. if ( !D3MF::D3MFOpcPackage::isZipArchive( pIOHandler, filename ) ) {
  372. return false;
  373. }
  374. D3MF::D3MFOpcPackage opcPackage( pIOHandler, filename );
  375. return opcPackage.validate();
  376. }
  377. return false;
  378. }
  379. void D3MFImporter::SetupProperties(const Importer * /*pImp*/) {
  380. // empty
  381. }
  382. const aiImporterDesc *D3MFImporter::GetInfo() const {
  383. return &desc;
  384. }
  385. void D3MFImporter::InternReadFile( const std::string &filename, aiScene *pScene, IOSystem *pIOHandler ) {
  386. D3MF::D3MFOpcPackage opcPackage(pIOHandler, filename);
  387. std::unique_ptr<CIrrXML_IOStreamReader> xmlStream(new CIrrXML_IOStreamReader(opcPackage.RootStream()));
  388. std::unique_ptr<D3MF::XmlReader> xmlReader(irr::io::createIrrXMLReader(xmlStream.get()));
  389. D3MF::XmlSerializer xmlSerializer(xmlReader.get());
  390. xmlSerializer.ImportXml(pScene);
  391. }
  392. } // Namespace Assimp
  393. #endif // ASSIMP_BUILD_NO_3MF_IMPORTER