2
0

AMFImporter.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2025, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. #ifndef ASSIMP_BUILD_NO_AMF_IMPORTER
  35. // Header files, Assimp.
  36. #include "AMFImporter.hpp"
  37. #include <assimp/DefaultIOSystem.h>
  38. #include <assimp/fast_atof.h>
  39. #include <assimp/StringUtils.h>
  40. // Header files, stdlib.
  41. #include <memory>
  42. namespace Assimp {
  43. static constexpr aiImporterDesc Description = {
  44. "Additive manufacturing file format(AMF) Importer",
  45. "smalcom",
  46. "",
  47. "See documentation in source code. Chapter: Limitations.",
  48. aiImporterFlags_SupportTextFlavour | aiImporterFlags_LimitedSupport | aiImporterFlags_Experimental,
  49. 0,
  50. 0,
  51. 0,
  52. 0,
  53. "amf"
  54. };
  55. void AMFImporter::Clear() {
  56. mNodeElement_Cur = nullptr;
  57. mUnit.clear();
  58. mMaterial_Converted.clear();
  59. mTexture_Converted.clear();
  60. // Delete all elements
  61. if (!mNodeElement_List.empty()) {
  62. for (AMFNodeElementBase *ne : mNodeElement_List) {
  63. delete ne;
  64. }
  65. mNodeElement_List.clear();
  66. }
  67. }
  68. AMFImporter::AMFImporter() AI_NO_EXCEPT :
  69. mNodeElement_Cur(nullptr),
  70. mXmlParser(nullptr) {
  71. // empty
  72. }
  73. AMFImporter::~AMFImporter() {
  74. delete mXmlParser;
  75. // Clear() is accounting if data already is deleted. So, just check again if all data is deleted.
  76. Clear();
  77. }
  78. /*********************************************************************************************************************************************/
  79. /************************************************************ Functions: find set ************************************************************/
  80. /*********************************************************************************************************************************************/
  81. bool AMFImporter::Find_NodeElement(const std::string &pID, const AMFNodeElementBase::EType pType, AMFNodeElementBase **pNodeElement) const {
  82. for (AMFNodeElementBase *ne : mNodeElement_List) {
  83. if ((ne->ID == pID) && (ne->Type == pType)) {
  84. if (pNodeElement != nullptr) {
  85. *pNodeElement = ne;
  86. }
  87. return true;
  88. }
  89. } // for(CAMFImporter_NodeElement* ne: mNodeElement_List)
  90. return false;
  91. }
  92. bool AMFImporter::Find_ConvertedNode(const std::string &pID, NodeArray &nodeArray, aiNode **pNode) const {
  93. aiString node_name(pID.c_str());
  94. for (aiNode *node : nodeArray) {
  95. if (node->mName == node_name) {
  96. if (pNode != nullptr) {
  97. *pNode = node;
  98. }
  99. return true;
  100. }
  101. } // for(aiNode* node: pNodeList)
  102. return false;
  103. }
  104. bool AMFImporter::Find_ConvertedMaterial(const std::string &pID, const SPP_Material **pConvertedMaterial) const {
  105. for (const SPP_Material &mat : mMaterial_Converted) {
  106. if (mat.ID == pID) {
  107. if (pConvertedMaterial != nullptr) {
  108. *pConvertedMaterial = &mat;
  109. }
  110. return true;
  111. }
  112. } // for(const SPP_Material& mat: mMaterial_Converted)
  113. return false;
  114. }
  115. /*********************************************************************************************************************************************/
  116. /************************************************************ Functions: throw set ***********************************************************/
  117. /*********************************************************************************************************************************************/
  118. void AMFImporter::Throw_CloseNotFound(const std::string &nodeName) {
  119. throw DeadlyImportError("Close tag for node <" + nodeName + "> not found. Seems file is corrupt.");
  120. }
  121. void AMFImporter::Throw_IncorrectAttr(const std::string &nodeName, const std::string &attrName) {
  122. throw DeadlyImportError("Node <" + nodeName + "> has incorrect attribute \"" + attrName + "\".");
  123. }
  124. void AMFImporter::Throw_IncorrectAttrValue(const std::string &nodeName, const std::string &attrName) {
  125. throw DeadlyImportError("Attribute \"" + attrName + "\" in node <" + nodeName + "> has incorrect value.");
  126. }
  127. void AMFImporter::Throw_MoreThanOnceDefined(const std::string &nodeName, const std::string &pNodeType, const std::string &pDescription) {
  128. throw DeadlyImportError("\"" + pNodeType + "\" node can be used only once in " + nodeName + ". Description: " + pDescription);
  129. }
  130. void AMFImporter::Throw_ID_NotFound(const std::string &pID) const {
  131. throw DeadlyImportError("Not found node with name \"", pID, "\".");
  132. }
  133. /*********************************************************************************************************************************************/
  134. /************************************************************* Functions: XML set ************************************************************/
  135. /*********************************************************************************************************************************************/
  136. void AMFImporter::XML_CheckNode_MustHaveChildren(pugi::xml_node &node) {
  137. if (node.children().begin() == node.children().end()) {
  138. throw DeadlyImportError(std::string("Node <") + node.name() + "> must have children.");
  139. }
  140. }
  141. bool AMFImporter::XML_SearchNode(const std::string &nodeName) {
  142. return nullptr != mXmlParser->findNode(nodeName);
  143. }
  144. static bool ParseHelper_Decode_Base64_IsBase64(const char pChar) {
  145. return (isalnum((unsigned char)pChar) || (pChar == '+') || (pChar == '/'));
  146. }
  147. void AMFImporter::ParseHelper_Decode_Base64(const std::string &pInputBase64, std::vector<uint8_t> &pOutputData) const {
  148. // With help from
  149. // René Nyffenegger http://www.adp-gmbh.ch/cpp/common/base64.html
  150. const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  151. uint8_t tidx = 0;
  152. uint8_t arr4[4], arr3[3];
  153. // check input data
  154. if (pInputBase64.size() % 4) {
  155. throw DeadlyImportError("Base64-encoded data must have size multiply of four.");
  156. }
  157. // prepare output place
  158. pOutputData.clear();
  159. pOutputData.reserve(pInputBase64.size() / 4 * 3);
  160. for (size_t in_len = pInputBase64.size(), in_idx = 0; (in_len > 0) && (pInputBase64[in_idx] != '='); in_len--) {
  161. if (ParseHelper_Decode_Base64_IsBase64(pInputBase64[in_idx])) {
  162. arr4[tidx++] = pInputBase64[in_idx++];
  163. if (tidx == 4) {
  164. for (tidx = 0; tidx < 4; tidx++)
  165. arr4[tidx] = (uint8_t)base64_chars.find(arr4[tidx]);
  166. arr3[0] = (arr4[0] << 2) + ((arr4[1] & 0x30) >> 4);
  167. arr3[1] = ((arr4[1] & 0x0F) << 4) + ((arr4[2] & 0x3C) >> 2);
  168. arr3[2] = ((arr4[2] & 0x03) << 6) + arr4[3];
  169. for (tidx = 0; tidx < 3; tidx++)
  170. pOutputData.push_back(arr3[tidx]);
  171. tidx = 0;
  172. } // if(tidx == 4)
  173. } // if(ParseHelper_Decode_Base64_IsBase64(pInputBase64[in_idx]))
  174. else {
  175. in_idx++;
  176. } // if(ParseHelper_Decode_Base64_IsBase64(pInputBase64[in_idx])) else
  177. }
  178. if (tidx) {
  179. for (uint8_t i = tidx; i < 4; i++)
  180. arr4[i] = 0;
  181. for (uint8_t i = 0; i < 4; i++)
  182. arr4[i] = (uint8_t)(base64_chars.find(arr4[i]));
  183. arr3[0] = (arr4[0] << 2) + ((arr4[1] & 0x30) >> 4);
  184. arr3[1] = ((arr4[1] & 0x0F) << 4) + ((arr4[2] & 0x3C) >> 2);
  185. arr3[2] = ((arr4[2] & 0x03) << 6) + arr4[3];
  186. for (uint8_t i = 0; i < (tidx - 1); i++)
  187. pOutputData.push_back(arr3[i]);
  188. }
  189. }
  190. void AMFImporter::ParseFile(const std::string &pFile, IOSystem *pIOHandler) {
  191. std::unique_ptr<IOStream> file(pIOHandler->Open(pFile, "rb"));
  192. // Check whether we can read from the file
  193. if (file == nullptr) {
  194. throw DeadlyImportError("Failed to open AMF file ", pFile, ".");
  195. }
  196. mXmlParser = new XmlParser();
  197. if (!mXmlParser->parse(file.get())) {
  198. delete mXmlParser;
  199. mXmlParser = nullptr;
  200. throw DeadlyImportError("Failed to create XML reader for file ", pFile, ".");
  201. }
  202. // Start reading, search for root tag <amf>
  203. if (!mXmlParser->hasNode("amf")) {
  204. throw DeadlyImportError("Root node \"amf\" not found.");
  205. }
  206. ParseNode_Root();
  207. } // namespace Assimp
  208. void AMFImporter::ParseHelper_Node_Enter(AMFNodeElementBase *node) {
  209. mNodeElement_Cur->Child.push_back(node); // add new element to current element child list.
  210. mNodeElement_Cur = node;
  211. }
  212. void AMFImporter::ParseHelper_Node_Exit() {
  213. if (mNodeElement_Cur != nullptr) mNodeElement_Cur = mNodeElement_Cur->Parent;
  214. }
  215. // <amf
  216. // unit="" - The units to be used. May be "inch", "millimeter", "meter", "feet", or "micron".
  217. // version="" - Version of file format.
  218. // >
  219. // </amf>
  220. // Root XML element.
  221. // Multi elements - No.
  222. void AMFImporter::ParseNode_Root() {
  223. AMFNodeElementBase *ne = nullptr;
  224. XmlNode *root = mXmlParser->findNode("amf");
  225. if (nullptr == root) {
  226. throw DeadlyImportError("Root node \"amf\" not found.");
  227. }
  228. XmlNode node = *root;
  229. mUnit = ai_tolower(std::string(node.attribute("unit").as_string()));
  230. mVersion = node.attribute("version").as_string();
  231. // Read attributes for node <amf>.
  232. // Check attributes
  233. if (!mUnit.empty()) {
  234. if ((mUnit != "inch") && (mUnit != "millimeters") && (mUnit != "millimeter") && (mUnit != "meter") && (mUnit != "feet") && (mUnit != "micron")) {
  235. Throw_IncorrectAttrValue("unit", mUnit);
  236. }
  237. }
  238. // create root node element.
  239. ne = new AMFRoot(nullptr);
  240. mNodeElement_Cur = ne; // set first "current" element
  241. // and assign attribute's values
  242. ((AMFRoot *)ne)->Unit = mUnit;
  243. ((AMFRoot *)ne)->Version = mVersion;
  244. // Check for child nodes
  245. for (XmlNode &currentNode : node.children() ) {
  246. const std::string currentName = currentNode.name();
  247. if (currentName == "object") {
  248. ParseNode_Object(currentNode);
  249. } else if (currentName == "material") {
  250. ParseNode_Material(currentNode);
  251. } else if (currentName == "texture") {
  252. ParseNode_Texture(currentNode);
  253. } else if (currentName == "constellation") {
  254. ParseNode_Constellation(currentNode);
  255. } else if (currentName == "metadata") {
  256. ParseNode_Metadata(currentNode);
  257. }
  258. mNodeElement_Cur = ne;
  259. }
  260. mNodeElement_Cur = ne; // force restore "current" element
  261. mNodeElement_List.push_back(ne); // add to node element list because its a new object in graph.
  262. }
  263. // <constellation
  264. // id="" - The Object ID of the new constellation being defined.
  265. // >
  266. // </constellation>
  267. // A collection of objects or constellations with specific relative locations.
  268. // Multi elements - Yes.
  269. // Parent element - <amf>.
  270. void AMFImporter::ParseNode_Constellation(XmlNode &node) {
  271. std::string id;
  272. id = node.attribute("id").as_string();
  273. // create and if needed - define new grouping object.
  274. AMFNodeElementBase *ne = new AMFConstellation(mNodeElement_Cur);
  275. AMFConstellation &als = *((AMFConstellation *)ne); // alias for convenience
  276. if (!id.empty()) {
  277. als.ID = id;
  278. }
  279. // Check for child nodes
  280. if (!node.empty()) {
  281. ParseHelper_Node_Enter(ne);
  282. for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
  283. std::string name = currentNode.name();
  284. if (name == "instance") {
  285. ParseNode_Instance(currentNode);
  286. } else if (name == "metadata") {
  287. ParseNode_Metadata(currentNode);
  288. }
  289. }
  290. ParseHelper_Node_Exit();
  291. } else {
  292. mNodeElement_Cur->Child.push_back(ne);
  293. }
  294. mNodeElement_List.push_back(ne); // and to node element list because its a new object in graph.
  295. }
  296. // <instance
  297. // objectid="" - The Object ID of the new constellation being defined.
  298. // >
  299. // </instance>
  300. // A collection of objects or constellations with specific relative locations.
  301. // Multi elements - Yes.
  302. // Parent element - <amf>.
  303. void AMFImporter::ParseNode_Instance(XmlNode &node) {
  304. AMFNodeElementBase *ne(nullptr);
  305. // Read attributes for node <constellation>.
  306. std::string objectid = node.attribute("objectid").as_string();
  307. // used object id must be defined, check that.
  308. if (objectid.empty()) {
  309. throw DeadlyImportError("\"objectid\" in <instance> must be defined.");
  310. }
  311. // create and define new grouping object.
  312. ne = new AMFInstance(mNodeElement_Cur);
  313. AMFInstance &als = *((AMFInstance *)ne);
  314. als.ObjectID = objectid;
  315. if (!node.empty()) {
  316. ParseHelper_Node_Enter(ne);
  317. for (auto &currentNode : node.children()) {
  318. const std::string &currentName = currentNode.name();
  319. if (currentName == "deltax") {
  320. XmlParser::getValueAsReal(currentNode, als.Delta.x);
  321. } else if (currentName == "deltay") {
  322. XmlParser::getValueAsReal(currentNode, als.Delta.y);
  323. } else if (currentName == "deltaz") {
  324. XmlParser::getValueAsReal(currentNode, als.Delta.z);
  325. } else if (currentName == "rx") {
  326. XmlParser::getValueAsReal(currentNode, als.Delta.x);
  327. } else if (currentName == "ry") {
  328. XmlParser::getValueAsReal(currentNode, als.Delta.y);
  329. } else if (currentName == "rz") {
  330. XmlParser::getValueAsReal(currentNode, als.Delta.z);
  331. }
  332. }
  333. ParseHelper_Node_Exit();
  334. } else {
  335. mNodeElement_Cur->Child.push_back(ne);
  336. }
  337. mNodeElement_List.push_back(ne); // and to node element list because its a new object in graph.
  338. }
  339. // <object
  340. // id="" - A unique ObjectID for the new object being defined.
  341. // >
  342. // </object>
  343. // An object definition.
  344. // Multi elements - Yes.
  345. // Parent element - <amf>.
  346. void AMFImporter::ParseNode_Object(XmlNode &node) {
  347. AMFNodeElementBase *ne = nullptr;
  348. // Read attributes for node <object>.
  349. std::string id = node.attribute("id").as_string();
  350. // create and if needed - define new geometry object.
  351. ne = new AMFObject(mNodeElement_Cur);
  352. AMFObject &als = *((AMFObject *)ne); // alias for convenience
  353. if (!id.empty()) {
  354. als.ID = id;
  355. }
  356. // Check for child nodes
  357. if (!node.empty()) {
  358. ParseHelper_Node_Enter(ne);
  359. for (auto &currentNode : node.children()) {
  360. const std::string &currentName = currentNode.name();
  361. if (currentName == "color") {
  362. ParseNode_Color(currentNode);
  363. } else if (currentName == "mesh") {
  364. ParseNode_Mesh(currentNode);
  365. } else if (currentName == "metadata") {
  366. ParseNode_Metadata(currentNode);
  367. }
  368. }
  369. ParseHelper_Node_Exit();
  370. } else {
  371. mNodeElement_Cur->Child.push_back(ne); // Add element to child list of current element
  372. }
  373. mNodeElement_List.push_back(ne); // and to node element list because its a new object in graph.
  374. }
  375. // <metadata
  376. // type="" - The type of the attribute.
  377. // >
  378. // </metadata>
  379. // Specify additional information about an entity.
  380. // Multi elements - Yes.
  381. // Parent element - <amf>, <object>, <volume>, <material>, <vertex>.
  382. //
  383. // Reserved types are:
  384. // "Name" - The alphanumeric label of the entity, to be used by the interpreter if interacting with the user.
  385. // "Description" - A description of the content of the entity
  386. // "URL" - A link to an external resource relating to the entity
  387. // "Author" - Specifies the name(s) of the author(s) of the entity
  388. // "Company" - Specifying the company generating the entity
  389. // "CAD" - specifies the name of the originating CAD software and version
  390. // "Revision" - specifies the revision of the entity
  391. // "Tolerance" - specifies the desired manufacturing tolerance of the entity in entity's unit system
  392. // "Volume" - specifies the total volume of the entity, in the entity's unit system, to be used for verification (object and volume only)
  393. void AMFImporter::ParseNode_Metadata(XmlNode &node) {
  394. AMFNodeElementBase *ne = nullptr;
  395. std::string type = node.attribute("type").as_string(), value;
  396. XmlParser::getValueAsString(node, value);
  397. // read attribute
  398. ne = new AMFMetadata(mNodeElement_Cur);
  399. ((AMFMetadata *)ne)->MetaType = type;
  400. ((AMFMetadata *)ne)->Value = value;
  401. mNodeElement_Cur->Child.push_back(ne); // Add element to child list of current element
  402. mNodeElement_List.push_back(ne); // and to node element list because its a new object in graph.
  403. }
  404. bool AMFImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool /*pCheckSig*/) const {
  405. static const char *tokens[] = { "<amf" };
  406. return SearchFileHeaderForToken(pIOHandler, pFile, tokens, AI_COUNT_OF(tokens));
  407. }
  408. const aiImporterDesc *AMFImporter::GetInfo() const {
  409. return &Description;
  410. }
  411. void AMFImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) {
  412. Clear(); // delete old graph.
  413. ParseFile(pFile, pIOHandler);
  414. Postprocess_BuildScene(pScene);
  415. // scene graph is ready, exit.
  416. }
  417. } // namespace Assimp
  418. #endif // !ASSIMP_BUILD_NO_AMF_IMPORTER