D3MFImporter.cpp 16 KB

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