diff options
Diffstat (limited to 'libs/assimp/code/AssetLib/AMF')
-rw-r--r-- | libs/assimp/code/AssetLib/AMF/AMFImporter.cpp | 524 | ||||
-rw-r--r-- | libs/assimp/code/AssetLib/AMF/AMFImporter.hpp | 310 | ||||
-rw-r--r-- | libs/assimp/code/AssetLib/AMF/AMFImporter_Geometry.cpp | 284 | ||||
-rw-r--r-- | libs/assimp/code/AssetLib/AMF/AMFImporter_Material.cpp | 327 | ||||
-rw-r--r-- | libs/assimp/code/AssetLib/AMF/AMFImporter_Node.hpp | 305 | ||||
-rw-r--r-- | libs/assimp/code/AssetLib/AMF/AMFImporter_Postprocess.cpp | 894 |
6 files changed, 2644 insertions, 0 deletions
diff --git a/libs/assimp/code/AssetLib/AMF/AMFImporter.cpp b/libs/assimp/code/AssetLib/AMF/AMFImporter.cpp new file mode 100644 index 0000000..4103dcd --- /dev/null +++ b/libs/assimp/code/AssetLib/AMF/AMFImporter.cpp @@ -0,0 +1,524 @@ +/* +--------------------------------------------------------------------------- +Open Asset Import Library (assimp) +--------------------------------------------------------------------------- + +Copyright (c) 2006-2022, assimp team + +All rights reserved. + +Redistribution and use of this software in source and binary forms, +with or without modification, are permitted provided that the following +conditions are met: + +* Redistributions of source code must retain the above +copyright notice, this list of conditions and the +following disclaimer. + +* Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the +following disclaimer in the documentation and/or other +materials provided with the distribution. + +* Neither the name of the assimp team, nor the names of its +contributors may be used to endorse or promote products +derived from this software without specific prior +written permission of the assimp team. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +--------------------------------------------------------------------------- +*/ + +#ifndef ASSIMP_BUILD_NO_AMF_IMPORTER + +// Header files, Assimp. +#include "AMFImporter.hpp" + +#include <assimp/DefaultIOSystem.h> +#include <assimp/fast_atof.h> +#include <assimp/StringUtils.h> + +// Header files, stdlib. +#include <memory> + +namespace Assimp { + +const aiImporterDesc AMFImporter::Description = { + "Additive manufacturing file format(AMF) Importer", + "smalcom", + "", + "See documentation in source code. Chapter: Limitations.", + aiImporterFlags_SupportTextFlavour | aiImporterFlags_LimitedSupport | aiImporterFlags_Experimental, + 0, + 0, + 0, + 0, + "amf" +}; + +void AMFImporter::Clear() { + mNodeElement_Cur = nullptr; + mUnit.clear(); + mMaterial_Converted.clear(); + mTexture_Converted.clear(); + // Delete all elements + if (!mNodeElement_List.empty()) { + for (AMFNodeElementBase *ne : mNodeElement_List) { + delete ne; + } + + mNodeElement_List.clear(); + } +} + +AMFImporter::AMFImporter() AI_NO_EXCEPT : + mNodeElement_Cur(nullptr), + mXmlParser(nullptr), + mUnit(), + mVersion(), + mMaterial_Converted(), + mTexture_Converted() { + // empty +} + +AMFImporter::~AMFImporter() { + delete mXmlParser; + // Clear() is accounting if data already is deleted. So, just check again if all data is deleted. + Clear(); +} + +/*********************************************************************************************************************************************/ +/************************************************************ Functions: find set ************************************************************/ +/*********************************************************************************************************************************************/ + +bool AMFImporter::Find_NodeElement(const std::string &pID, const AMFNodeElementBase::EType pType, AMFNodeElementBase **pNodeElement) const { + for (AMFNodeElementBase *ne : mNodeElement_List) { + if ((ne->ID == pID) && (ne->Type == pType)) { + if (pNodeElement != nullptr) { + *pNodeElement = ne; + } + + return true; + } + } // for(CAMFImporter_NodeElement* ne: mNodeElement_List) + + return false; +} + +bool AMFImporter::Find_ConvertedNode(const std::string &pID, NodeArray &nodeArray, aiNode **pNode) const { + aiString node_name(pID.c_str()); + for (aiNode *node : nodeArray) { + if (node->mName == node_name) { + if (pNode != nullptr) { + *pNode = node; + } + + return true; + } + } // for(aiNode* node: pNodeList) + + return false; +} + +bool AMFImporter::Find_ConvertedMaterial(const std::string &pID, const SPP_Material **pConvertedMaterial) const { + for (const SPP_Material &mat : mMaterial_Converted) { + if (mat.ID == pID) { + if (pConvertedMaterial != nullptr) { + *pConvertedMaterial = &mat; + } + + return true; + } + } // for(const SPP_Material& mat: mMaterial_Converted) + + return false; +} + +/*********************************************************************************************************************************************/ +/************************************************************ Functions: throw set ***********************************************************/ +/*********************************************************************************************************************************************/ + +void AMFImporter::Throw_CloseNotFound(const std::string &nodeName) { + throw DeadlyImportError("Close tag for node <" + nodeName + "> not found. Seems file is corrupt."); +} + +void AMFImporter::Throw_IncorrectAttr(const std::string &nodeName, const std::string &attrName) { + throw DeadlyImportError("Node <" + nodeName + "> has incorrect attribute \"" + attrName + "\"."); +} + +void AMFImporter::Throw_IncorrectAttrValue(const std::string &nodeName, const std::string &attrName) { + throw DeadlyImportError("Attribute \"" + attrName + "\" in node <" + nodeName + "> has incorrect value."); +} + +void AMFImporter::Throw_MoreThanOnceDefined(const std::string &nodeName, const std::string &pNodeType, const std::string &pDescription) { + throw DeadlyImportError("\"" + pNodeType + "\" node can be used only once in " + nodeName + ". Description: " + pDescription); +} + +void AMFImporter::Throw_ID_NotFound(const std::string &pID) const { + throw DeadlyImportError("Not found node with name \"", pID, "\"."); +} + +/*********************************************************************************************************************************************/ +/************************************************************* Functions: XML set ************************************************************/ +/*********************************************************************************************************************************************/ + +void AMFImporter::XML_CheckNode_MustHaveChildren(pugi::xml_node &node) { + if (node.children().begin() == node.children().end()) { + throw DeadlyImportError(std::string("Node <") + node.name() + "> must have children."); + } +} + +bool AMFImporter::XML_SearchNode(const std::string &nodeName) { + return nullptr != mXmlParser->findNode(nodeName); +} + +void AMFImporter::ParseHelper_FixTruncatedFloatString(const char *pInStr, std::string &pOutString) { + size_t instr_len; + + pOutString.clear(); + instr_len = strlen(pInStr); + if (!instr_len) return; + + pOutString.reserve(instr_len * 3 / 2); + // check and correct floats in format ".x". Must be "x.y". + if (pInStr[0] == '.') pOutString.push_back('0'); + + pOutString.push_back(pInStr[0]); + for (size_t ci = 1; ci < instr_len; ci++) { + if ((pInStr[ci] == '.') && ((pInStr[ci - 1] == ' ') || (pInStr[ci - 1] == '-') || (pInStr[ci - 1] == '+') || (pInStr[ci - 1] == '\t'))) { + pOutString.push_back('0'); + pOutString.push_back('.'); + } else { + pOutString.push_back(pInStr[ci]); + } + } +} + +static bool ParseHelper_Decode_Base64_IsBase64(const char pChar) { + return (isalnum((unsigned char)pChar) || (pChar == '+') || (pChar == '/')); +} + +void AMFImporter::ParseHelper_Decode_Base64(const std::string &pInputBase64, std::vector<uint8_t> &pOutputData) const { + // With help from + // René Nyffenegger http://www.adp-gmbh.ch/cpp/common/base64.html + const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + + uint8_t tidx = 0; + uint8_t arr4[4], arr3[3]; + + // check input data + if (pInputBase64.size() % 4) throw DeadlyImportError("Base64-encoded data must have size multiply of four."); + // prepare output place + pOutputData.clear(); + pOutputData.reserve(pInputBase64.size() / 4 * 3); + + for (size_t in_len = pInputBase64.size(), in_idx = 0; (in_len > 0) && (pInputBase64[in_idx] != '='); in_len--) { + if (ParseHelper_Decode_Base64_IsBase64(pInputBase64[in_idx])) { + arr4[tidx++] = pInputBase64[in_idx++]; + if (tidx == 4) { + for (tidx = 0; tidx < 4; tidx++) + arr4[tidx] = (uint8_t)base64_chars.find(arr4[tidx]); + + arr3[0] = (arr4[0] << 2) + ((arr4[1] & 0x30) >> 4); + arr3[1] = ((arr4[1] & 0x0F) << 4) + ((arr4[2] & 0x3C) >> 2); + arr3[2] = ((arr4[2] & 0x03) << 6) + arr4[3]; + for (tidx = 0; tidx < 3; tidx++) + pOutputData.push_back(arr3[tidx]); + + tidx = 0; + } // if(tidx == 4) + } // if(ParseHelper_Decode_Base64_IsBase64(pInputBase64[in_idx])) + else { + in_idx++; + } // if(ParseHelper_Decode_Base64_IsBase64(pInputBase64[in_idx])) else + } + + if (tidx) { + for (uint8_t i = tidx; i < 4; i++) + arr4[i] = 0; + for (uint8_t i = 0; i < 4; i++) + arr4[i] = (uint8_t)(base64_chars.find(arr4[i])); + + arr3[0] = (arr4[0] << 2) + ((arr4[1] & 0x30) >> 4); + arr3[1] = ((arr4[1] & 0x0F) << 4) + ((arr4[2] & 0x3C) >> 2); + arr3[2] = ((arr4[2] & 0x03) << 6) + arr4[3]; + for (uint8_t i = 0; i < (tidx - 1); i++) + pOutputData.push_back(arr3[i]); + } +} + +void AMFImporter::ParseFile(const std::string &pFile, IOSystem *pIOHandler) { + std::unique_ptr<IOStream> file(pIOHandler->Open(pFile, "rb")); + + // Check whether we can read from the file + if (file.get() == nullptr) { + throw DeadlyImportError("Failed to open AMF file ", pFile, "."); + } + + mXmlParser = new XmlParser(); + if (!mXmlParser->parse(file.get())) { + delete mXmlParser; + mXmlParser = nullptr; + throw DeadlyImportError("Failed to create XML reader for file ", pFile, "."); + } + + // Start reading, search for root tag <amf> + if (!mXmlParser->hasNode("amf")) { + throw DeadlyImportError("Root node \"amf\" not found."); + } + ParseNode_Root(); +} // namespace Assimp + +void AMFImporter::ParseHelper_Node_Enter(AMFNodeElementBase *node) { + mNodeElement_Cur->Child.push_back(node); // add new element to current element child list. + mNodeElement_Cur = node; +} + +void AMFImporter::ParseHelper_Node_Exit() { + if (mNodeElement_Cur != nullptr) mNodeElement_Cur = mNodeElement_Cur->Parent; +} + +// <amf +// unit="" - The units to be used. May be "inch", "millimeter", "meter", "feet", or "micron". +// version="" - Version of file format. +// > +// </amf> +// Root XML element. +// Multi elements - No. +void AMFImporter::ParseNode_Root() { + AMFNodeElementBase *ne = nullptr; + XmlNode *root = mXmlParser->findNode("amf"); + if (nullptr == root) { + throw DeadlyImportError("Root node \"amf\" not found."); + } + XmlNode node = *root; + mUnit = ai_tolower(std::string(node.attribute("unit").as_string())); + + mVersion = node.attribute("version").as_string(); + + // Read attributes for node <amf>. + // Check attributes + if (!mUnit.empty()) { + if ((mUnit != "inch") && (mUnit != "millimeters") && (mUnit != "millimeter") && (mUnit != "meter") && (mUnit != "feet") && (mUnit != "micron")) { + Throw_IncorrectAttrValue("unit", mUnit); + } + } + + // create root node element. + ne = new AMFRoot(nullptr); + + mNodeElement_Cur = ne; // set first "current" element + // and assign attribute's values + ((AMFRoot *)ne)->Unit = mUnit; + ((AMFRoot *)ne)->Version = mVersion; + + // Check for child nodes + for (XmlNode ¤tNode : node.children() ) { + const std::string currentName = currentNode.name(); + if (currentName == "object") { + ParseNode_Object(currentNode); + } else if (currentName == "material") { + ParseNode_Material(currentNode); + } else if (currentName == "texture") { + ParseNode_Texture(currentNode); + } else if (currentName == "constellation") { + ParseNode_Constellation(currentNode); + } else if (currentName == "metadata") { + ParseNode_Metadata(currentNode); + } + mNodeElement_Cur = ne; + } + mNodeElement_Cur = ne; // force restore "current" element + mNodeElement_List.push_back(ne); // add to node element list because its a new object in graph. +} + +// <constellation +// id="" - The Object ID of the new constellation being defined. +// > +// </constellation> +// A collection of objects or constellations with specific relative locations. +// Multi elements - Yes. +// Parent element - <amf>. +void AMFImporter::ParseNode_Constellation(XmlNode &node) { + std::string id; + id = node.attribute("id").as_string(); + + // create and if needed - define new grouping object. + AMFNodeElementBase *ne = new AMFConstellation(mNodeElement_Cur); + + AMFConstellation &als = *((AMFConstellation *)ne); // alias for convenience + + if (!id.empty()) { + als.ID = id; + } + + // Check for child nodes + if (!node.empty()) { + ParseHelper_Node_Enter(ne); + for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) { + std::string name = currentNode.name(); + if (name == "instance") { + ParseNode_Instance(currentNode); + } else if (name == "metadata") { + ParseNode_Metadata(currentNode); + } + } + ParseHelper_Node_Exit(); + } else { + mNodeElement_Cur->Child.push_back(ne); + } + mNodeElement_List.push_back(ne); // and to node element list because its a new object in graph. +} + +// <instance +// objectid="" - The Object ID of the new constellation being defined. +// > +// </instance> +// A collection of objects or constellations with specific relative locations. +// Multi elements - Yes. +// Parent element - <amf>. +void AMFImporter::ParseNode_Instance(XmlNode &node) { + AMFNodeElementBase *ne(nullptr); + + // Read attributes for node <constellation>. + std::string objectid = node.attribute("objectid").as_string(); + + // used object id must be defined, check that. + if (objectid.empty()) { + throw DeadlyImportError("\"objectid\" in <instance> must be defined."); + } + // create and define new grouping object. + ne = new AMFInstance(mNodeElement_Cur); + AMFInstance &als = *((AMFInstance *)ne); + als.ObjectID = objectid; + + if (!node.empty()) { + ParseHelper_Node_Enter(ne); + for (auto ¤tNode : node.children()) { + const std::string ¤tName = currentNode.name(); + if (currentName == "deltax") { + XmlParser::getValueAsFloat(currentNode, als.Delta.x); + } else if (currentName == "deltay") { + XmlParser::getValueAsFloat(currentNode, als.Delta.y); + } else if (currentName == "deltaz") { + XmlParser::getValueAsFloat(currentNode, als.Delta.z); + } else if (currentName == "rx") { + XmlParser::getValueAsFloat(currentNode, als.Delta.x); + } else if (currentName == "ry") { + XmlParser::getValueAsFloat(currentNode, als.Delta.y); + } else if (currentName == "rz") { + XmlParser::getValueAsFloat(currentNode, als.Delta.z); + } + } + ParseHelper_Node_Exit(); + } else { + mNodeElement_Cur->Child.push_back(ne); + } + + mNodeElement_List.push_back(ne); // and to node element list because its a new object in graph. +} + +// <object +// id="" - A unique ObjectID for the new object being defined. +// > +// </object> +// An object definition. +// Multi elements - Yes. +// Parent element - <amf>. +void AMFImporter::ParseNode_Object(XmlNode &node) { + AMFNodeElementBase *ne = nullptr; + + // Read attributes for node <object>. + std::string id = node.attribute("id").as_string(); + + // create and if needed - define new geometry object. + ne = new AMFObject(mNodeElement_Cur); + + AMFObject &als = *((AMFObject *)ne); // alias for convenience + + if (!id.empty()) { + als.ID = id; + } + + // Check for child nodes + if (!node.empty()) { + ParseHelper_Node_Enter(ne); + for (auto ¤tNode : node.children()) { + const std::string ¤tName = currentNode.name(); + if (currentName == "color") { + ParseNode_Color(currentNode); + } else if (currentName == "mesh") { + ParseNode_Mesh(currentNode); + } else if (currentName == "metadata") { + ParseNode_Metadata(currentNode); + } + } + ParseHelper_Node_Exit(); + } else { + mNodeElement_Cur->Child.push_back(ne); // Add element to child list of current element + } + + mNodeElement_List.push_back(ne); // and to node element list because its a new object in graph. +} + +// <metadata +// type="" - The type of the attribute. +// > +// </metadata> +// Specify additional information about an entity. +// Multi elements - Yes. +// Parent element - <amf>, <object>, <volume>, <material>, <vertex>. +// +// Reserved types are: +// "Name" - The alphanumeric label of the entity, to be used by the interpreter if interacting with the user. +// "Description" - A description of the content of the entity +// "URL" - A link to an external resource relating to the entity +// "Author" - Specifies the name(s) of the author(s) of the entity +// "Company" - Specifying the company generating the entity +// "CAD" - specifies the name of the originating CAD software and version +// "Revision" - specifies the revision of the entity +// "Tolerance" - specifies the desired manufacturing tolerance of the entity in entity's unit system +// "Volume" - specifies the total volume of the entity, in the entity's unit system, to be used for verification (object and volume only) +void AMFImporter::ParseNode_Metadata(XmlNode &node) { + AMFNodeElementBase *ne = nullptr; + + std::string type = node.attribute("type").as_string(), value; + XmlParser::getValueAsString(node, value); + + // read attribute + ne = new AMFMetadata(mNodeElement_Cur); + ((AMFMetadata *)ne)->Type = type; + ((AMFMetadata *)ne)->Value = value; + mNodeElement_Cur->Child.push_back(ne); // Add element to child list of current element + mNodeElement_List.push_back(ne); // and to node element list because its a new object in graph. +} + +bool AMFImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool /*pCheckSig*/) const { + static const char *tokens[] = { "<amf" }; + return SearchFileHeaderForToken(pIOHandler, pFile, tokens, AI_COUNT_OF(tokens)); +} + +const aiImporterDesc *AMFImporter::GetInfo() const { + return &Description; +} + +void AMFImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) { + Clear(); // delete old graph. + ParseFile(pFile, pIOHandler); + Postprocess_BuildScene(pScene); + // scene graph is ready, exit. +} + +} // namespace Assimp + +#endif // !ASSIMP_BUILD_NO_AMF_IMPORTER diff --git a/libs/assimp/code/AssetLib/AMF/AMFImporter.hpp b/libs/assimp/code/AssetLib/AMF/AMFImporter.hpp new file mode 100644 index 0000000..601eae4 --- /dev/null +++ b/libs/assimp/code/AssetLib/AMF/AMFImporter.hpp @@ -0,0 +1,310 @@ +/* +--------------------------------------------------------------------------- +Open Asset Import Library (assimp) +--------------------------------------------------------------------------- + +Copyright (c) 2006-2022, assimp team + +All rights reserved. + +Redistribution and use of this software in source and binary forms, +with or without modification, are permitted provided that the following +conditions are met: + +* Redistributions of source code must retain the above +copyright notice, this list of conditions and the +following disclaimer. + +* Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the +following disclaimer in the documentation and/or other +materials provided with the distribution. + +* Neither the name of the assimp team, nor the names of its +contributors may be used to endorse or promote products +derived from this software without specific prior +written permission of the assimp team. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +--------------------------------------------------------------------------- +*/ + +/// \file AMFImporter.hpp +/// \brief AMF-format files importer for Assimp. +/// \date 2016 +/// \author smal.root@gmail.com +// Thanks to acorn89 for support. + +#pragma once +#ifndef INCLUDED_AI_AMF_IMPORTER_H +#define INCLUDED_AI_AMF_IMPORTER_H + +#include "AMFImporter_Node.hpp" + +// Header files, Assimp. +#include "assimp/types.h" +#include <assimp/BaseImporter.h> +#include <assimp/XmlParser.h> +#include <assimp/importerdesc.h> +#include <assimp/DefaultLogger.hpp> + +// Header files, stdlib. +#include <set> + +namespace Assimp { + +/// \class AMFImporter +/// Class that holding scene graph which include: geometry, metadata, materials etc. +/// +/// Implementing features. +/// +/// Limitations. +/// +/// 1. When for texture mapping used set of source textures (r, g, b, a) not only one then attribute "tiled" for all set will be true if it true in any of +/// source textures. +/// Example. Triangle use for texture mapping three textures. Two of them has "tiled" set to false and one - set to true. In scene all three textures +/// will be tiled. +/// +/// Unsupported features: +/// 1. Node <composite>, formulas in <composite> and <color>. For implementing this feature can be used expression parser "muParser" like in project +/// "amf_tools". +/// 2. Attribute "profile" in node <color>. +/// 3. Curved geometry: <edge>, <normal> and children nodes of them. +/// 4. Attributes: "unit" and "version" in <amf> read but do nothing. +/// 5. <metadata> stored only for root node <amf>. +/// 6. Color averaging of vertices for which <triangle>'s set different colors. +/// +/// Supported nodes: +/// General: +/// <amf>; <constellation>; <instance> and children <deltax>, <deltay>, <deltaz>, <rx>, <ry>, <rz>; <metadata>; +/// +/// Geometry: +/// <object>; <mesh>; <vertices>; <vertex>; <coordinates> and children <x>, <y>, <z>; <volume>; <triangle> and children <v1>, <v2>, <v3>; +/// +/// Material: +/// <color> and children <r>, <g>, <b>, <a>; <texture>; <material>; +/// two variants of texture coordinates: +/// new - <texmap> and children <utex1>, <utex2>, <utex3>, <vtex1>, <vtex2>, <vtex3> +/// old - <map> and children <u1>, <u2>, <u3>, <v1>, <v2>, <v3> +/// +class AMFImporter : public BaseImporter { +private: + struct SPP_Material; // forward declaration + + /// Data type for post-processing step. More suitable container for part of material's composition. + struct SPP_Composite { + SPP_Material *Material; ///< Pointer to material - part of composition. + std::string Formula; ///< Formula for calculating ratio of \ref Material. + }; + + /// \struct SPP_Material + /// Data type for post-processing step. More suitable container for material. + struct SPP_Material { + std::string ID; ///< Material ID. + std::list<AMFMetadata *> Metadata; ///< Metadata of material. + AMFColor *Color; ///< Color of material. + std::list<SPP_Composite> Composition; ///< List of child materials if current material is composition of few another. + + /// Return color calculated for specified coordinate. + /// \param [in] pX - "x" coordinate. + /// \param [in] pY - "y" coordinate. + /// \param [in] pZ - "z" coordinate. + /// \return calculated color. + aiColor4D GetColor(const float pX, const float pY, const float pZ) const; + }; + + /// Data type for post-processing step. More suitable container for texture. + struct SPP_Texture { + std::string ID; + size_t Width, Height, Depth; + bool Tiled; + char FormatHint[9]; // 8 for string + 1 for terminator. + uint8_t *Data; + }; + + /// Data type for post-processing step. Contain face data. + struct SComplexFace { + aiFace Face; ///< Face vertices. + const AMFColor *Color; ///< Face color. Equal to nullptr if color is not set for the face. + const AMFTexMap *TexMap; ///< Face texture mapping data. Equal to nullptr if texture mapping is not set for the face. + }; + + using AMFMetaDataArray = std::vector<AMFMetadata*>; + using MeshArray = std::vector<aiMesh*>; + using NodeArray = std::vector<aiNode*>; + + /// Clear all temporary data. + void Clear(); + + /// Get data stored in <vertices> and place it to arrays. + /// \param [in] pNodeElement - reference to node element which kept <object> data. + /// \param [in] pVertexCoordinateArray - reference to vertices coordinates kept in <vertices>. + /// \param [in] pVertexColorArray - reference to vertices colors for all <vertex's. If color for vertex is not set then corresponding member of array + /// contain nullptr. + void PostprocessHelper_CreateMeshDataArray(const AMFMesh &pNodeElement, std::vector<aiVector3D> &pVertexCoordinateArray, + std::vector<AMFColor *> &pVertexColorArray) const; + + /// Return converted texture ID which related to specified source textures ID's. If converted texture does not exist then it will be created and ID on new + /// converted texture will be returned. Conversion: set of textures from \ref CAMFImporter_NodeElement_Texture to one \ref SPP_Texture and place it + /// to converted textures list. + /// Any of source ID's can be absent(empty string) or even one ID only specified. But at least one ID must be specified. + /// \param [in] pID_R - ID of source "red" texture. + /// \param [in] pID_G - ID of source "green" texture. + /// \param [in] pID_B - ID of source "blue" texture. + /// \param [in] pID_A - ID of source "alpha" texture. + /// \return index of the texture in array of the converted textures. + size_t PostprocessHelper_GetTextureID_Or_Create(const std::string &pID_R, const std::string &pID_G, const std::string &pID_B, const std::string &pID_A); + + /// Separate input list by texture IDs. This step is needed because aiMesh can contain mesh which is use only one texture (or set: diffuse, bump etc). + /// \param [in] pInputList - input list with faces. Some of them can contain color or texture mapping, or both of them, or nothing. Will be cleared after + /// processing. + /// \param [out] pOutputList_Separated - output list of the faces lists. Separated faces list by used texture IDs. Will be cleared before processing. + void PostprocessHelper_SplitFacesByTextureID(std::list<SComplexFace> &pInputList, std::list<std::list<SComplexFace>> &pOutputList_Separated); + + /// Check if child elements of node element is metadata and add it to scene node. + /// \param [in] pMetadataList - reference to list with collected metadata. + /// \param [out] pSceneNode - scene node in which metadata will be added. + void Postprocess_AddMetadata(const AMFMetaDataArray &pMetadataList, aiNode &pSceneNode) const; + + /// To create aiMesh and aiNode for it from <object>. + /// \param [in] pNodeElement - reference to node element which kept <object> data. + /// \param [out] meshList - reference to a list with all aiMesh of the scene. + /// \param [out] pSceneNode - pointer to place where new aiNode will be created. + void Postprocess_BuildNodeAndObject(const AMFObject &pNodeElement, MeshArray &meshList, aiNode **pSceneNode); + + /// Create mesh for every <volume> in <mesh>. + /// \param [in] pNodeElement - reference to node element which kept <mesh> data. + /// \param [in] pVertexCoordinateArray - reference to vertices coordinates for all <volume>'s. + /// \param [in] pVertexColorArray - reference to vertices colors for all <volume>'s. If color for vertex is not set then corresponding member of array + /// contain nullptr. + /// \param [in] pObjectColor - pointer to colors for <object>. If color is not set then argument contain nullptr. + /// \param [in] pMaterialList - reference to a list with defined materials. + /// \param [out] pMeshList - reference to a list with all aiMesh of the scene. + /// \param [out] pSceneNode - reference to aiNode which will own new aiMesh's. + void Postprocess_BuildMeshSet(const AMFMesh &pNodeElement, const std::vector<aiVector3D> &pVertexCoordinateArray, + const std::vector<AMFColor *> &pVertexColorArray, const AMFColor *pObjectColor, + MeshArray &pMeshList, aiNode &pSceneNode); + + /// Convert material from \ref CAMFImporter_NodeElement_Material to \ref SPP_Material. + /// \param [in] pMaterial - source CAMFImporter_NodeElement_Material. + void Postprocess_BuildMaterial(const AMFMaterial &pMaterial); + + /// Create and add to aiNode's list new part of scene graph defined by <constellation>. + /// \param [in] pConstellation - reference to <constellation> node. + /// \param [out] nodeArray - reference to aiNode's list. + void Postprocess_BuildConstellation(AMFConstellation &pConstellation, NodeArray &nodeArray) const; + + /// Build Assimp scene graph in aiScene from collected data. + /// \param [out] pScene - pointer to aiScene where tree will be built. + void Postprocess_BuildScene(aiScene *pScene); + + /// Decode Base64-encoded data. + /// \param [in] pInputBase64 - reference to input Base64-encoded string. + /// \param [out] pOutputData - reference to output array for decoded data. + void ParseHelper_Decode_Base64(const std::string &pInputBase64, std::vector<uint8_t> &pOutputData) const; + + /// Parse <AMF> node of the file. + void ParseNode_Root(); + + /// Parse <constellation> node of the file. + void ParseNode_Constellation(XmlNode &node); + + /// Parse <instance> node of the file. + void ParseNode_Instance(XmlNode &node); + + /// Parse <material> node of the file. + void ParseNode_Material(XmlNode &node); + + /// Parse <metadata> node. + void ParseNode_Metadata(XmlNode &node); + + /// Parse <object> node of the file. + void ParseNode_Object(XmlNode &node); + + /// Parse <texture> node of the file. + void ParseNode_Texture(XmlNode &node); + + /// Parse <coordinates> node of the file. + void ParseNode_Coordinates(XmlNode &node); + + /// Parse <edge> node of the file. + void ParseNode_Edge(XmlNode &node); + + /// Parse <mesh> node of the file. + void ParseNode_Mesh(XmlNode &node); + + /// Parse <triangle> node of the file. + void ParseNode_Triangle(XmlNode &node); + + /// Parse <vertex> node of the file. + void ParseNode_Vertex(XmlNode &node); + + /// Parse <vertices> node of the file. + void ParseNode_Vertices(XmlNode &node); + + /// Parse <volume> node of the file. + void ParseNode_Volume(XmlNode &node); + + /// Parse <color> node of the file. + void ParseNode_Color(XmlNode &node); + + /// Parse <texmap> of <map> node of the file. + /// \param [in] pUseOldName - if true then use old name of node(and children) - <map>, instead of new name - <texmap>. + void ParseNode_TexMap(XmlNode &node, const bool pUseOldName = false); + +public: + /// Default constructor. + AMFImporter() AI_NO_EXCEPT; + + /// Default destructor. + ~AMFImporter() override; + + /// Parse AMF file and fill scene graph. The function has no return value. Result can be found by analyzing the generated graph. + /// Also exception can be thrown if trouble will found. + /// \param [in] pFile - name of file to be parsed. + /// \param [in] pIOHandler - pointer to IO helper object. + void ParseFile(const std::string &pFile, IOSystem *pIOHandler); + void ParseHelper_Node_Enter(AMFNodeElementBase *child); + void ParseHelper_Node_Exit(); + bool CanRead(const std::string &pFile, IOSystem *pIOHandler, bool pCheckSig) const override; + void InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) override; + const aiImporterDesc *GetInfo() const override; + bool Find_NodeElement(const std::string &pID, const AMFNodeElementBase::EType pType, AMFNodeElementBase **pNodeElement) const; + bool Find_ConvertedNode(const std::string &pID, NodeArray &nodeArray, aiNode **pNode) const; + bool Find_ConvertedMaterial(const std::string &pID, const SPP_Material **pConvertedMaterial) const; + void Throw_CloseNotFound(const std::string &nodeName); + void Throw_IncorrectAttr(const std::string &nodeName, const std::string &pAttrName); + void Throw_IncorrectAttrValue(const std::string &nodeName, const std::string &pAttrName); + void Throw_MoreThanOnceDefined(const std::string &nodeName, const std::string &pNodeType, const std::string &pDescription); + void Throw_ID_NotFound(const std::string &pID) const; + void XML_CheckNode_MustHaveChildren(pugi::xml_node &node); + bool XML_SearchNode(const std::string &nodeName); + void ParseHelper_FixTruncatedFloatString(const char *pInStr, std::string &pOutString); + AMFImporter(const AMFImporter &pScene) = delete; + AMFImporter &operator=(const AMFImporter &pScene) = delete; + +private: + static const aiImporterDesc Description; + + AMFNodeElementBase *mNodeElement_Cur; ///< Current element. + std::list<AMFNodeElementBase *> mNodeElement_List; ///< All elements of scene graph. + XmlParser *mXmlParser; + std::string mUnit; + std::string mVersion; + std::list<SPP_Material> mMaterial_Converted; ///< List of converted materials for postprocessing step. + std::list<SPP_Texture> mTexture_Converted; ///< List of converted textures for postprocessing step. +}; + +} // namespace Assimp + +#endif // INCLUDED_AI_AMF_IMPORTER_H diff --git a/libs/assimp/code/AssetLib/AMF/AMFImporter_Geometry.cpp b/libs/assimp/code/AssetLib/AMF/AMFImporter_Geometry.cpp new file mode 100644 index 0000000..341999f --- /dev/null +++ b/libs/assimp/code/AssetLib/AMF/AMFImporter_Geometry.cpp @@ -0,0 +1,284 @@ +/* +--------------------------------------------------------------------------- +Open Asset Import Library (assimp) +--------------------------------------------------------------------------- + +Copyright (c) 2006-2022, assimp team + +All rights reserved. + +Redistribution and use of this software in source and binary forms, +with or without modification, are permitted provided that the following +conditions are met: + +* Redistributions of source code must retain the above +copyright notice, this list of conditions and the +following disclaimer. + +* Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the +following disclaimer in the documentation and/or other +materials provided with the distribution. + +* Neither the name of the assimp team, nor the names of its +contributors may be used to endorse or promote products +derived from this software without specific prior +written permission of the assimp team. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +--------------------------------------------------------------------------- +*/ + +#ifndef ASSIMP_BUILD_NO_AMF_IMPORTER + +#include "AMFImporter.hpp" +#include <assimp/ParsingUtils.h> + +namespace Assimp { + +// <mesh> +// </mesh> +// A 3D mesh hull. +// Multi elements - Yes. +// Parent element - <object>. +void AMFImporter::ParseNode_Mesh(XmlNode &node) { + AMFNodeElementBase *ne = nullptr; + + // Check for child nodes + if (0 != ASSIMP_stricmp(node.name(), "mesh")) { + return; + } + // create new mesh object. + ne = new AMFMesh(mNodeElement_Cur); + bool found_verts = false, found_volumes = false; + if (!node.empty()) { + ParseHelper_Node_Enter(ne); + pugi::xml_node vertNode = node.child("vertices"); + if (!vertNode.empty()) { + ParseNode_Vertices(vertNode); + found_verts = true; + } + + pugi::xml_node volumeNode = node.child("volume"); + if (!volumeNode.empty()) { + ParseNode_Volume(volumeNode); + found_volumes = true; + } + ParseHelper_Node_Exit(); + } + + if (!found_verts && !found_volumes) { + mNodeElement_Cur->Child.push_back(ne); + } // if(!mReader->isEmptyElement()) else + + // and to node element list because its a new object in graph. + mNodeElement_List.push_back(ne); +} + +// <vertices> +// </vertices> +// The list of vertices to be used in defining triangles. +// Multi elements - No. +// Parent element - <mesh>. +void AMFImporter::ParseNode_Vertices(XmlNode &node) { + AMFNodeElementBase *ne = nullptr; + + // create new mesh object. + ne = new AMFVertices(mNodeElement_Cur); + // Check for child nodes + if (node.empty()) { + mNodeElement_Cur->Child.push_back(ne); // Add element to child list of current element + return; + } + ParseHelper_Node_Enter(ne); + for (XmlNode ¤tNode : node.children()) { + const std::string ¤tName = currentNode.name(); + if (currentName == "vertex") { + ParseNode_Vertex(currentNode); + } + } + ParseHelper_Node_Exit(); + mNodeElement_List.push_back(ne); // and to node element list because its a new object in graph. +} + +// <vertex> +// </vertex> +// A vertex to be referenced in triangles. +// Multi elements - Yes. +// Parent element - <vertices>. +void AMFImporter::ParseNode_Vertex(XmlNode &node) { + AMFNodeElementBase *ne = nullptr; + + // create new mesh object. + ne = new AMFVertex(mNodeElement_Cur); + + // Check for child nodes + pugi::xml_node colorNode = node.child("color"); + bool col_read = false; + bool coord_read = false; + if (!node.empty()) { + ParseHelper_Node_Enter(ne); + if (!colorNode.empty()) { + ParseNode_Color(colorNode); + col_read = true; + } + pugi::xml_node coordNode = node.child("coordinates"); + if (!coordNode.empty()) { + ParseNode_Coordinates(coordNode); + coord_read = true; + } + ParseHelper_Node_Exit(); + } + + if (!coord_read && !col_read) { + mNodeElement_Cur->Child.push_back(ne); // Add element to child list of current element + } + + mNodeElement_List.push_back(ne); // and to node element list because its a new object in graph. +} + +// <coordinates> +// </coordinates> +// Specifies the 3D location of this vertex. +// Multi elements - No. +// Parent element - <vertex>. +// +// Children elements: +// <x>, <y>, <z> +// Multi elements - No. +// X, Y, or Z coordinate, respectively, of a vertex position in space. +void AMFImporter::ParseNode_Coordinates(XmlNode &node) { + AMFNodeElementBase *ne = nullptr; + if (!node.empty()) { + ne = new AMFCoordinates(mNodeElement_Cur); + ParseHelper_Node_Enter(ne); + for (XmlNode ¤tNode : node.children()) { + // create new color object. + AMFCoordinates &als = *((AMFCoordinates *)ne); // alias for convenience + const std::string ¤tName = ai_tolower(currentNode.name()); + if (currentName == "x") { + XmlParser::getValueAsFloat(currentNode, als.Coordinate.x); + } else if (currentName == "y") { + XmlParser::getValueAsFloat(currentNode, als.Coordinate.y); + } else if (currentName == "z") { + XmlParser::getValueAsFloat(currentNode, als.Coordinate.z); + } + } + ParseHelper_Node_Exit(); + + } else { + mNodeElement_Cur->Child.push_back(new AMFCoordinates(mNodeElement_Cur)); + } + + mNodeElement_List.push_back(ne); // and to node element list because its a new object in graph. +} + +// <volume +// materialid="" - Which material to use. +// type="" - What this volume describes can be "region" or "support". If none specified, "object" is assumed. If support, then the geometric +// requirements 1-8 listed in section 5 do not need to be maintained. +// > +// </volume> +// Defines a volume from the established vertex list. +// Multi elements - Yes. +// Parent element - <mesh>. +void AMFImporter::ParseNode_Volume(XmlNode &node) { + std::string materialid; + std::string type; + AMFNodeElementBase *ne = new AMFVolume(mNodeElement_Cur); + + // Read attributes for node <color>. + // and assign read data + + ((AMFVolume *)ne)->MaterialID = node.attribute("materialid").as_string(); + + ((AMFVolume *)ne)->Type = type; + // Check for child nodes + bool col_read = false; + if (!node.empty()) { + ParseHelper_Node_Enter(ne); + for (auto ¤tNode : node.children()) { + const std::string currentName = currentNode.name(); + if (currentName == "color") { + if (col_read) Throw_MoreThanOnceDefined(currentName, "color", "Only one color can be defined for <volume>."); + ParseNode_Color(currentNode); + col_read = true; + } else if (currentName == "triangle") { + ParseNode_Triangle(currentNode); + } else if (currentName == "metadata") { + ParseNode_Metadata(currentNode); + } else if (currentName == "volume") { + ParseNode_Metadata(currentNode); + } + } + ParseHelper_Node_Exit(); + } else { + mNodeElement_Cur->Child.push_back(ne); // Add element to child list of current element + } + + mNodeElement_List.push_back(ne); // and to node element list because its a new object in graph. +} + +// <triangle> +// </triangle> +// Defines a 3D triangle from three vertices, according to the right-hand rule (counter-clockwise when looking from the outside). +// Multi elements - Yes. +// Parent element - <volume>. +// +// Children elements: +// <v1>, <v2>, <v3> +// Multi elements - No. +// Index of the desired vertices in a triangle or edge. +void AMFImporter::ParseNode_Triangle(XmlNode &node) { + AMFNodeElementBase *ne = new AMFTriangle(mNodeElement_Cur); + + // create new triangle object. + + AMFTriangle &als = *((AMFTriangle *)ne); // alias for convenience + + bool col_read = false; + if (!node.empty()) { + ParseHelper_Node_Enter(ne); + std::string v; + for (auto ¤tNode : node.children()) { + const std::string currentName = currentNode.name(); + if (currentName == "color") { + if (col_read) Throw_MoreThanOnceDefined(currentName, "color", "Only one color can be defined for <triangle>."); + ParseNode_Color(currentNode); + col_read = true; + } else if (currentName == "texmap") { + ParseNode_TexMap(currentNode); + } else if (currentName == "map") { + ParseNode_TexMap(currentNode, true); + } else if (currentName == "v1") { + XmlParser::getValueAsString(currentNode, v); + als.V[0] = std::atoi(v.c_str()); + } else if (currentName == "v2") { + XmlParser::getValueAsString(currentNode, v); + als.V[1] = std::atoi(v.c_str()); + } else if (currentName == "v3") { + XmlParser::getValueAsString(currentNode, v); + als.V[2] = std::atoi(v.c_str()); + } + } + ParseHelper_Node_Exit(); + } else { + mNodeElement_Cur->Child.push_back(ne); // Add element to child list of current element + } + + mNodeElement_List.push_back(ne); // and to node element list because its a new object in graph. +} + +} // namespace Assimp + +#endif // !ASSIMP_BUILD_NO_AMF_IMPORTER diff --git a/libs/assimp/code/AssetLib/AMF/AMFImporter_Material.cpp b/libs/assimp/code/AssetLib/AMF/AMFImporter_Material.cpp new file mode 100644 index 0000000..676e748 --- /dev/null +++ b/libs/assimp/code/AssetLib/AMF/AMFImporter_Material.cpp @@ -0,0 +1,327 @@ +/* +--------------------------------------------------------------------------- +Open Asset Import Library (assimp) +--------------------------------------------------------------------------- + +Copyright (c) 2006-2022, assimp team + +All rights reserved. + +Redistribution and use of this software in source and binary forms, +with or without modification, are permitted provided that the following +conditions are met: + +* Redistributions of source code must retain the above +copyright notice, this list of conditions and the +following disclaimer. + +* Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the +following disclaimer in the documentation and/or other +materials provided with the distribution. + +* Neither the name of the assimp team, nor the names of its +contributors may be used to endorse or promote products +derived from this software without specific prior +written permission of the assimp team. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +--------------------------------------------------------------------------- +*/ + +/// \file AMFImporter_Material.cpp +/// \brief Parsing data from material nodes. +/// \date 2016 +/// \author smal.root@gmail.com + +#ifndef ASSIMP_BUILD_NO_AMF_IMPORTER + +#include "AMFImporter.hpp" + +namespace Assimp { + +// <color +// profile="" - The ICC color space used to interpret the three color channels <r>, <g> and <b>. +// > +// </color> +// A color definition. +// Multi elements - No. +// Parent element - <material>, <object>, <volume>, <vertex>, <triangle>. +// +// "profile" can be one of "sRGB", "AdobeRGB", "Wide-Gamut-RGB", "CIERGB", "CIELAB", or "CIEXYZ". +// Children elements: +// <r>, <g>, <b>, <a> +// Multi elements - No. +// Red, Greed, Blue and Alpha (transparency) component of a color in sRGB space, values ranging from 0 to 1. The +// values can be specified as constants, or as a formula depending on the coordinates. +void AMFImporter::ParseNode_Color(XmlNode &node) { + if (node.empty()) { + return; + } + + const std::string &profile = node.attribute("profile").as_string(); + bool read_flag[4] = { false, false, false, false }; + AMFNodeElementBase *ne = new AMFColor(mNodeElement_Cur); + AMFColor &als = *((AMFColor *)ne); // alias for convenience + ParseHelper_Node_Enter(ne); + for (pugi::xml_node &child : node.children()) { + // create new color object. + als.Profile = profile; + + const std::string &name = child.name(); + if ( name == "r") { + read_flag[0] = true; + XmlParser::getValueAsFloat(child, als.Color.r); + } else if (name == "g") { + read_flag[1] = true; + XmlParser::getValueAsFloat(child, als.Color.g); + } else if (name == "b") { + read_flag[2] = true; + XmlParser::getValueAsFloat(child, als.Color.b); + } else if (name == "a") { + read_flag[3] = true; + XmlParser::getValueAsFloat(child, als.Color.a); + } + // check if <a> is absent. Then manually add "a == 1". + if (!read_flag[3]) { + als.Color.a = 1; + } + } + als.Composed = false; + mNodeElement_List.push_back(ne); // and to node element list because its a new object in graph. + ParseHelper_Node_Exit(); + // check that all components was defined + if (!(read_flag[0] && read_flag[1] && read_flag[2])) { + throw DeadlyImportError("Not all color components are defined."); + } +} + +// <material +// id="" - A unique material id. material ID "0" is reserved to denote no material (void) or sacrificial material. +// > +// </material> +// An available material. +// Multi elements - Yes. +// Parent element - <amf>. +void AMFImporter::ParseNode_Material(XmlNode &node) { + // create new object and assign read data + std::string id = node.attribute("id").as_string(); + AMFNodeElementBase *ne = new AMFMaterial(mNodeElement_Cur); + ((AMFMaterial*)ne)->ID = id; + + // Check for child nodes + if (!node.empty()) { + ParseHelper_Node_Enter(ne); + for (pugi::xml_node &child : node.children()) { + const std::string name = child.name(); + if (name == "color") { + ParseNode_Color(child); + } else if (name == "metadata") { + ParseNode_Metadata(child); + } + } + ParseHelper_Node_Exit(); + } else { + mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element + } + + mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph. +} + +// <texture +// id="" - Assigns a unique texture id for the new texture. +// width="" - Width (horizontal size, x) of the texture, in pixels. +// height="" - Height (lateral size, y) of the texture, in pixels. +// depth="" - Depth (vertical size, z) of the texture, in pixels. +// type="" - Encoding of the data in the texture. Currently allowed values are "grayscale" only. In grayscale mode, each pixel is represented by one byte +// in the range of 0-255. When the texture is referenced using the tex function, these values are converted into a single floating point number in the +// range of 0-1 (see Annex 2). A full color graphics will typically require three textures, one for each of the color channels. A graphic involving +// transparency may require a fourth channel. +// tiled="" - If true then texture repeated when UV-coordinates is greater than 1. +// > +// </triangle> +// Specifies an texture data to be used as a map. Lists a sequence of Base64 values specifying values for pixels from left to right then top to bottom, +// then layer by layer. +// Multi elements - Yes. +// Parent element - <amf>. +void AMFImporter::ParseNode_Texture(XmlNode &node) { + const std::string id = node.attribute("id").as_string(); + const uint32_t width = node.attribute("width").as_uint(); + const uint32_t height = node.attribute("height").as_uint(); + uint32_t depth = node.attribute("depth").as_uint(); + const std::string type = node.attribute("type").as_string(); + bool tiled = node.attribute("tiled").as_bool(); + + if (node.empty()) { + return; + } + + // create new texture object. + AMFNodeElementBase *ne = new AMFTexture(mNodeElement_Cur); + + AMFTexture& als = *((AMFTexture*)ne);// alias for convenience + + std::string enc64_data; + XmlParser::getValueAsString(node, enc64_data); + // Check for child nodes + + // check that all components was defined + if (id.empty()) { + throw DeadlyImportError("ID for texture must be defined."); + } + if (width < 1) { + throw DeadlyImportError("Invalid width for texture."); + } + if (height < 1) { + throw DeadlyImportError("Invalid height for texture."); + } + if (type != "grayscale") { + throw DeadlyImportError("Invalid type for texture."); + } + if (enc64_data.empty()) { + throw DeadlyImportError("Texture data not defined."); + } + // copy data + als.ID = id; + als.Width = width; + als.Height = height; + als.Depth = depth; + als.Tiled = tiled; + ParseHelper_Decode_Base64(enc64_data, als.Data); + if (depth == 0) { + depth = (uint32_t)(als.Data.size() / (width * height)); + } + // check data size + if ((width * height * depth) != als.Data.size()) { + throw DeadlyImportError("Texture has incorrect data size."); + } + + mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element + mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph. +} + +// <texmap +// rtexid="" - Texture ID for red color component. +// gtexid="" - Texture ID for green color component. +// btexid="" - Texture ID for blue color component. +// atexid="" - Texture ID for alpha color component. Optional. +// > +// </texmap>, old name: <map> +// Specifies texture coordinates for triangle. +// Multi elements - No. +// Parent element - <triangle>. +// Children elements: +// <utex1>, <utex2>, <utex3>, <vtex1>, <vtex2>, <vtex3>. Old name: <u1>, <u2>, <u3>, <v1>, <v2>, <v3>. +// Multi elements - No. +// Texture coordinates for every vertex of triangle. +void AMFImporter::ParseNode_TexMap(XmlNode &node, const bool pUseOldName) { + // Read attributes for node <color>. + AMFNodeElementBase *ne = new AMFTexMap(mNodeElement_Cur); + AMFTexMap &als = *((AMFTexMap *)ne); // + std::string rtexid, gtexid, btexid, atexid; + if (!node.empty()) { + for (pugi::xml_attribute &attr : node.attributes()) { + const std::string ¤tAttr = attr.name(); + if (currentAttr == "rtexid") { + rtexid = attr.as_string(); + } else if (currentAttr == "gtexid") { + gtexid = attr.as_string(); + } else if (currentAttr == "btexid") { + btexid = attr.as_string(); + } else if (currentAttr == "atexid") { + atexid = attr.as_string(); + } + } + } + + // create new texture coordinates object, alias for convenience + // check data + if (rtexid.empty() && gtexid.empty() && btexid.empty()) { + throw DeadlyImportError("ParseNode_TexMap. At least one texture ID must be defined."); + } + + // Check for children nodes + if (node.children().begin() == node.children().end()) { + throw DeadlyImportError("Invalid children definition."); + } + // read children nodes + bool read_flag[6] = { false, false, false, false, false, false }; + + if (!pUseOldName) { + ParseHelper_Node_Enter(ne); + for ( XmlNode ¤tNode : node.children()) { + const std::string &name = currentNode.name(); + if (name == "utex1") { + read_flag[0] = true; + XmlParser::getValueAsFloat(node, als.TextureCoordinate[0].x); + } else if (name == "utex2") { + read_flag[1] = true; + XmlParser::getValueAsFloat(node, als.TextureCoordinate[1].x); + } else if (name == "utex3") { + read_flag[2] = true; + XmlParser::getValueAsFloat(node, als.TextureCoordinate[2].x); + } else if (name == "vtex1") { + read_flag[3] = true; + XmlParser::getValueAsFloat(node, als.TextureCoordinate[0].y); + } else if (name == "vtex2") { + read_flag[4] = true; + XmlParser::getValueAsFloat(node, als.TextureCoordinate[1].y); + } else if (name == "vtex3") { + read_flag[5] = true; + XmlParser::getValueAsFloat(node, als.TextureCoordinate[2].y); + } + } + ParseHelper_Node_Exit(); + + } else { + for (pugi::xml_attribute &attr : node.attributes()) { + const std::string name = attr.name(); + if (name == "u") { + read_flag[0] = true; + als.TextureCoordinate[0].x = attr.as_float(); + } else if (name == "u2") { + read_flag[1] = true; + als.TextureCoordinate[1].x = attr.as_float(); + } else if (name == "u3") { + read_flag[2] = true; + als.TextureCoordinate[2].x = attr.as_float(); + } else if (name == "v1") { + read_flag[3] = true; + als.TextureCoordinate[0].y = attr.as_float(); + } else if (name == "v2") { + read_flag[4] = true; + als.TextureCoordinate[1].y = attr.as_float(); + } else if (name == "v3") { + read_flag[5] = true; + als.TextureCoordinate[0].y = attr.as_float(); + } + } + } + + // check that all components was defined + if (!(read_flag[0] && read_flag[1] && read_flag[2] && read_flag[3] && read_flag[4] && read_flag[5])) { + throw DeadlyImportError("Not all texture coordinates are defined."); + } + + // copy attributes data + als.TextureID_R = rtexid; + als.TextureID_G = gtexid; + als.TextureID_B = btexid; + als.TextureID_A = atexid; + + mNodeElement_List.push_back(ne); +} + +}// namespace Assimp + +#endif // !ASSIMP_BUILD_NO_AMF_IMPORTER diff --git a/libs/assimp/code/AssetLib/AMF/AMFImporter_Node.hpp b/libs/assimp/code/AssetLib/AMF/AMFImporter_Node.hpp new file mode 100644 index 0000000..c827533 --- /dev/null +++ b/libs/assimp/code/AssetLib/AMF/AMFImporter_Node.hpp @@ -0,0 +1,305 @@ +/* +--------------------------------------------------------------------------- +Open Asset Import Library (assimp) +--------------------------------------------------------------------------- + +Copyright (c) 2006-2022, assimp team + +All rights reserved. + +Redistribution and use of this software in source and binary forms, +with or without modification, are permitted provided that the following +conditions are met: + +* Redistributions of source code must retain the above +copyright notice, this list of conditions and the +following disclaimer. + +* Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the +following disclaimer in the documentation and/or other +materials provided with the distribution. + +* Neither the name of the assimp team, nor the names of its +contributors may be used to endorse or promote products +derived from this software without specific prior +written permission of the assimp team. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +--------------------------------------------------------------------------- +*/ + +/// \file AMFImporter_Node.hpp +/// \brief Elements of scene graph. +/// \date 2016 +/// \author smal.root@gmail.com + +#pragma once +#ifndef INCLUDED_AI_AMF_IMPORTER_NODE_H +#define INCLUDED_AI_AMF_IMPORTER_NODE_H + +// Header files, Assimp. +#include <assimp/scene.h> +#include <assimp/types.h> + +#include <list> +#include <string> +#include <vector> + +/// \class CAMFImporter_NodeElement +/// Base class for elements of nodes. +class AMFNodeElementBase { +public: + /// Define what data type contain node element. + enum EType { + ENET_Color, ///< Color element: <color>. + ENET_Constellation, ///< Grouping element: <constellation>. + ENET_Coordinates, ///< Coordinates element: <coordinates>. + ENET_Edge, ///< Edge element: <edge>. + ENET_Instance, ///< Grouping element: <constellation>. + ENET_Material, ///< Material element: <material>. + ENET_Metadata, ///< Metadata element: <metadata>. + ENET_Mesh, ///< Metadata element: <mesh>. + ENET_Object, ///< Element which hold object: <object>. + ENET_Root, ///< Root element: <amf>. + ENET_Triangle, ///< Triangle element: <triangle>. + ENET_TexMap, ///< Texture coordinates element: <texmap> or <map>. + ENET_Texture, ///< Texture element: <texture>. + ENET_Vertex, ///< Vertex element: <vertex>. + ENET_Vertices, ///< Vertex element: <vertices>. + ENET_Volume, ///< Volume element: <volume>. + + ENET_Invalid ///< Element has invalid type and possible contain invalid data. + }; + + const EType Type; ///< Type of element. + std::string ID; ///< ID of element. + AMFNodeElementBase *Parent; ///< Parent element. If nullptr then this node is root. + std::list<AMFNodeElementBase *> Child; ///< Child elements. + +public: /// Destructor, virtual.. + virtual ~AMFNodeElementBase() { + // empty + } + + /// Disabled copy constructor and co. + AMFNodeElementBase(const AMFNodeElementBase &pNodeElement) = delete; + AMFNodeElementBase(AMFNodeElementBase &&) = delete; + AMFNodeElementBase &operator=(const AMFNodeElementBase &pNodeElement) = delete; + AMFNodeElementBase() = delete; + +protected: + /// In constructor inheritor must set element type. + /// \param [in] pType - element type. + /// \param [in] pParent - parent element. + AMFNodeElementBase(const EType pType, AMFNodeElementBase *pParent) : + Type(pType), ID(), Parent(pParent), Child() { + // empty + } +}; // class IAMFImporter_NodeElement + +/// \struct CAMFImporter_NodeElement_Constellation +/// A collection of objects or constellations with specific relative locations. +struct AMFConstellation : public AMFNodeElementBase { + /// Constructor. + /// \param [in] pParent - pointer to parent node. + AMFConstellation(AMFNodeElementBase *pParent) : + AMFNodeElementBase(ENET_Constellation, pParent) {} + +}; // struct CAMFImporter_NodeElement_Constellation + +/// \struct CAMFImporter_NodeElement_Instance +/// Part of constellation. +struct AMFInstance : public AMFNodeElementBase { + + std::string ObjectID; ///< ID of object for instantiation. + /// \var Delta - The distance of translation in the x, y, or z direction, respectively, in the referenced object's coordinate system, to + /// create an instance of the object in the current constellation. + aiVector3D Delta; + + /// \var Rotation - The rotation, in degrees, to rotate the referenced object about its x, y, and z axes, respectively, to create an + /// instance of the object in the current constellation. Rotations shall be executed in order of x first, then y, then z. + aiVector3D Rotation; + + /// Constructor. + /// \param [in] pParent - pointer to parent node. + AMFInstance(AMFNodeElementBase *pParent) : + AMFNodeElementBase(ENET_Instance, pParent) {} +}; + +/// \struct CAMFImporter_NodeElement_Metadata +/// Structure that define metadata node. +struct AMFMetadata : public AMFNodeElementBase { + + std::string Type; ///< Type of "Value". + std::string Value; ///< Value. + + /// Constructor. + /// \param [in] pParent - pointer to parent node. + AMFMetadata(AMFNodeElementBase *pParent) : + AMFNodeElementBase(ENET_Metadata, pParent) {} +}; + +/// \struct CAMFImporter_NodeElement_Root +/// Structure that define root node. +struct AMFRoot : public AMFNodeElementBase { + + std::string Unit; ///< The units to be used. May be "inch", "millimeter", "meter", "feet", or "micron". + std::string Version; ///< Version of format. + + /// Constructor. + /// \param [in] pParent - pointer to parent node. + AMFRoot(AMFNodeElementBase *pParent) : + AMFNodeElementBase(ENET_Root, pParent) {} +}; + +/// \struct CAMFImporter_NodeElement_Color +/// Structure that define object node. +struct AMFColor : public AMFNodeElementBase { + bool Composed; ///< Type of color stored: if true then look for formula in \ref Color_Composed[4], else - in \ref Color. + std::string Color_Composed[4]; ///< By components formulas of composed color. [0..3] - RGBA. + aiColor4D Color; ///< Constant color. + std::string Profile; ///< The ICC color space used to interpret the three color channels r, g and b.. + + /// @brief Constructor. + /// @param [in] pParent - pointer to parent node. + AMFColor(AMFNodeElementBase *pParent) : + AMFNodeElementBase(ENET_Color, pParent), Composed(false), Color(), Profile() { + // empty + } +}; + +/// \struct CAMFImporter_NodeElement_Material +/// Structure that define material node. +struct AMFMaterial : public AMFNodeElementBase { + + /// Constructor. + /// \param [in] pParent - pointer to parent node. + AMFMaterial(AMFNodeElementBase *pParent) : + AMFNodeElementBase(ENET_Material, pParent) {} +}; + +/// \struct CAMFImporter_NodeElement_Object +/// Structure that define object node. +struct AMFObject : public AMFNodeElementBase { + + /// Constructor. + /// \param [in] pParent - pointer to parent node. + AMFObject(AMFNodeElementBase *pParent) : + AMFNodeElementBase(ENET_Object, pParent) {} +}; + +/// \struct CAMFImporter_NodeElement_Mesh +/// Structure that define mesh node. +struct AMFMesh : public AMFNodeElementBase { + /// Constructor. + /// \param [in] pParent - pointer to parent node. + AMFMesh(AMFNodeElementBase *pParent) : + AMFNodeElementBase(ENET_Mesh, pParent) {} +}; + +/// \struct CAMFImporter_NodeElement_Vertex +/// Structure that define vertex node. +struct AMFVertex : public AMFNodeElementBase { + /// Constructor. + /// \param [in] pParent - pointer to parent node. + AMFVertex(AMFNodeElementBase *pParent) : + AMFNodeElementBase(ENET_Vertex, pParent) {} +}; + +/// \struct CAMFImporter_NodeElement_Edge +/// Structure that define edge node. +struct AMFEdge : public AMFNodeElementBase { + /// Constructor. + /// \param [in] pParent - pointer to parent node. + AMFEdge(AMFNodeElementBase *pParent) : + AMFNodeElementBase(ENET_Edge, pParent) {} +}; + +/// \struct CAMFImporter_NodeElement_Vertices +/// Structure that define vertices node. +struct AMFVertices : public AMFNodeElementBase { + /// Constructor. + /// \param [in] pParent - pointer to parent node. + AMFVertices(AMFNodeElementBase *pParent) : + AMFNodeElementBase(ENET_Vertices, pParent) {} +}; + +/// \struct CAMFImporter_NodeElement_Volume +/// Structure that define volume node. +struct AMFVolume : public AMFNodeElementBase { + std::string MaterialID; ///< Which material to use. + std::string Type; ///< What this volume describes can be "region" or "support". If none specified, "object" is assumed. + + /// Constructor. + /// \param [in] pParent - pointer to parent node. + AMFVolume(AMFNodeElementBase *pParent) : + AMFNodeElementBase(ENET_Volume, pParent) {} +}; + +/// \struct CAMFImporter_NodeElement_Coordinates +/// Structure that define coordinates node. +struct AMFCoordinates : public AMFNodeElementBase { + aiVector3D Coordinate; ///< Coordinate. + + /// Constructor. + /// \param [in] pParent - pointer to parent node. + AMFCoordinates(AMFNodeElementBase *pParent) : + AMFNodeElementBase(ENET_Coordinates, pParent) {} +}; + +/// \struct CAMFImporter_NodeElement_TexMap +/// Structure that define texture coordinates node. +struct AMFTexMap : public AMFNodeElementBase { + aiVector3D TextureCoordinate[3]; ///< Texture coordinates. + std::string TextureID_R; ///< Texture ID for red color component. + std::string TextureID_G; ///< Texture ID for green color component. + std::string TextureID_B; ///< Texture ID for blue color component. + std::string TextureID_A; ///< Texture ID for alpha color component. + + /// Constructor. + /// \param [in] pParent - pointer to parent node. + AMFTexMap(AMFNodeElementBase *pParent) : + AMFNodeElementBase(ENET_TexMap, pParent), TextureCoordinate{}, TextureID_R(), TextureID_G(), TextureID_B(), TextureID_A() { + // empty + } +}; + +/// \struct CAMFImporter_NodeElement_Triangle +/// Structure that define triangle node. +struct AMFTriangle : public AMFNodeElementBase { + size_t V[3]; ///< Triangle vertices. + + /// Constructor. + /// \param [in] pParent - pointer to parent node. + AMFTriangle(AMFNodeElementBase *pParent) : + AMFNodeElementBase(ENET_Triangle, pParent) { + // empty + } +}; + +/// Structure that define texture node. +struct AMFTexture : public AMFNodeElementBase { + size_t Width, Height, Depth; ///< Size of the texture. + std::vector<uint8_t> Data; ///< Data of the texture. + bool Tiled; + + /// Constructor. + /// \param [in] pParent - pointer to parent node. + AMFTexture(AMFNodeElementBase *pParent) : + AMFNodeElementBase(ENET_Texture, pParent), Width(0), Height(0), Depth(0), Data(), Tiled(false) { + // empty + } +}; + +#endif // INCLUDED_AI_AMF_IMPORTER_NODE_H diff --git a/libs/assimp/code/AssetLib/AMF/AMFImporter_Postprocess.cpp b/libs/assimp/code/AssetLib/AMF/AMFImporter_Postprocess.cpp new file mode 100644 index 0000000..a65f926 --- /dev/null +++ b/libs/assimp/code/AssetLib/AMF/AMFImporter_Postprocess.cpp @@ -0,0 +1,894 @@ +/* +--------------------------------------------------------------------------- +Open Asset Import Library (assimp) +--------------------------------------------------------------------------- + +Copyright (c) 2006-2022, assimp team + +All rights reserved. + +Redistribution and use of this software in source and binary forms, +with or without modification, are permitted provided that the following +conditions are met: + +* Redistributions of source code must retain the above +copyright notice, this list of conditions and the +following disclaimer. + +* Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the +following disclaimer in the documentation and/or other +materials provided with the distribution. + +* Neither the name of the assimp team, nor the names of its +contributors may be used to endorse or promote products +derived from this software without specific prior +written permission of the assimp team. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +--------------------------------------------------------------------------- +*/ + +/// \file AMFImporter_Postprocess.cpp +/// \brief Convert built scenegraph and objects to Assimp scenegraph. +/// \date 2016 +/// \author smal.root@gmail.com + +#ifndef ASSIMP_BUILD_NO_AMF_IMPORTER + +#include "AMFImporter.hpp" + +#include <assimp/SceneCombiner.h> +#include <assimp/StandardShapes.h> +#include <assimp/StringUtils.h> + +#include <iterator> + +namespace Assimp { + +aiColor4D AMFImporter::SPP_Material::GetColor(const float /*pX*/, const float /*pY*/, const float /*pZ*/) const { + aiColor4D tcol; + + // Check if stored data are supported. + if (!Composition.empty()) { + throw DeadlyImportError("IME. GetColor for composition"); + } + + if (Color->Composed) { + throw DeadlyImportError("IME. GetColor, composed color"); + } + + tcol = Color->Color; + + // Check if default color must be used + if ((tcol.r == 0) && (tcol.g == 0) && (tcol.b == 0) && (tcol.a == 0)) { + tcol.r = 0.5f; + tcol.g = 0.5f; + tcol.b = 0.5f; + tcol.a = 1; + } + + return tcol; +} + +void AMFImporter::PostprocessHelper_CreateMeshDataArray(const AMFMesh &nodeElement, std::vector<aiVector3D> &vertexCoordinateArray, + std::vector<AMFColor *> &pVertexColorArray) const { + AMFVertices *vn = nullptr; + size_t col_idx; + + // All data stored in "vertices", search for it. + for (AMFNodeElementBase *ne_child : nodeElement.Child) { + if (ne_child->Type == AMFNodeElementBase::ENET_Vertices) { + vn = (AMFVertices*)ne_child; + } + } + + // If "vertices" not found then no work for us. + if (vn == nullptr) { + return; + } + + // all coordinates stored as child and we need to reserve space for future push_back's. + vertexCoordinateArray.reserve(vn->Child.size()); + + // colors count equal vertices count. + pVertexColorArray.resize(vn->Child.size()); + col_idx = 0; + + // Inside vertices collect all data and place to arrays + for (AMFNodeElementBase *vn_child : vn->Child) { + // vertices, colors + if (vn_child->Type == AMFNodeElementBase::ENET_Vertex) { + // by default clear color for current vertex + pVertexColorArray[col_idx] = nullptr; + + for (AMFNodeElementBase *vtx : vn_child->Child) { + if (vtx->Type == AMFNodeElementBase::ENET_Coordinates) { + vertexCoordinateArray.push_back(((AMFCoordinates *)vtx)->Coordinate); + continue; + } + + if (vtx->Type == AMFNodeElementBase::ENET_Color) { + pVertexColorArray[col_idx] = (AMFColor *)vtx; + continue; + } + } + + ++col_idx; + } + } +} + +size_t AMFImporter::PostprocessHelper_GetTextureID_Or_Create(const std::string &r, const std::string &g, const std::string &b, const std::string &a) { + if (r.empty() && g.empty() && b.empty() && a.empty()) { + throw DeadlyImportError("PostprocessHelper_GetTextureID_Or_Create. At least one texture ID must be defined."); + } + + std::string TextureConverted_ID = r + "_" + g + "_" + b + "_" + a; + size_t TextureConverted_Index = 0; + for (const SPP_Texture &tex_convd : mTexture_Converted) { + if (tex_convd.ID == TextureConverted_ID) { + return TextureConverted_Index; + } else { + ++TextureConverted_Index; + } + } + + // Converted texture not found, create it. + AMFTexture *src_texture[4] { + nullptr + }; + std::vector<AMFTexture *> src_texture_4check; + SPP_Texture converted_texture; + + { // find all specified source textures + AMFNodeElementBase *t_tex = nullptr; + + // R + if (!r.empty()) { + if (!Find_NodeElement(r, AMFNodeElementBase::EType::ENET_Texture, &t_tex)) { + Throw_ID_NotFound(r); + } + + src_texture[0] = (AMFTexture *)t_tex; + src_texture_4check.push_back((AMFTexture *)t_tex); + } else { + src_texture[0] = nullptr; + } + + // G + if (!g.empty()) { + if (!Find_NodeElement(g, AMFNodeElementBase::ENET_Texture, &t_tex)) { + Throw_ID_NotFound(g); + } + + src_texture[1] = (AMFTexture *)t_tex; + src_texture_4check.push_back((AMFTexture *)t_tex); + } else { + src_texture[1] = nullptr; + } + + // B + if (!b.empty()) { + if (!Find_NodeElement(b, AMFNodeElementBase::ENET_Texture, &t_tex)) { + Throw_ID_NotFound(b); + } + + src_texture[2] = (AMFTexture *)t_tex; + src_texture_4check.push_back((AMFTexture *)t_tex); + } else { + src_texture[2] = nullptr; + } + + // A + if (!a.empty()) { + if (!Find_NodeElement(a, AMFNodeElementBase::ENET_Texture, &t_tex)) { + Throw_ID_NotFound(a); + } + + src_texture[3] = (AMFTexture *)t_tex; + src_texture_4check.push_back((AMFTexture *)t_tex); + } else { + src_texture[3] = nullptr; + } + } // END: find all specified source textures + + // check that all textures has same size + if (src_texture_4check.size() > 1) { + for (size_t i = 0, i_e = (src_texture_4check.size() - 1); i < i_e; i++) { + if ((src_texture_4check[i]->Width != src_texture_4check[i + 1]->Width) || (src_texture_4check[i]->Height != src_texture_4check[i + 1]->Height) || + (src_texture_4check[i]->Depth != src_texture_4check[i + 1]->Depth)) { + throw DeadlyImportError("PostprocessHelper_GetTextureID_Or_Create. Source texture must has the same size."); + } + } + } // if(src_texture_4check.size() > 1) + + // set texture attributes + converted_texture.Width = src_texture_4check[0]->Width; + converted_texture.Height = src_texture_4check[0]->Height; + converted_texture.Depth = src_texture_4check[0]->Depth; + // if one of source texture is tiled then converted texture is tiled too. + converted_texture.Tiled = false; + for (uint8_t i = 0; i < src_texture_4check.size(); ++i) { + converted_texture.Tiled |= src_texture_4check[i]->Tiled; + } + + // Create format hint. + strcpy(converted_texture.FormatHint, "rgba0000"); // copy initial string. + if (!r.empty()) converted_texture.FormatHint[4] = '8'; + if (!g.empty()) converted_texture.FormatHint[5] = '8'; + if (!b.empty()) converted_texture.FormatHint[6] = '8'; + if (!a.empty()) converted_texture.FormatHint[7] = '8'; + + // Сopy data of textures. + size_t tex_size = 0; + size_t step = 0; + size_t off_g = 0; + size_t off_b = 0; + + // Calculate size of the target array and rule how data will be copied. + if (!r.empty() && nullptr != src_texture[0]) { + tex_size += src_texture[0]->Data.size(); + step++, off_g++, off_b++; + } + if (!g.empty() && nullptr != src_texture[1]) { + tex_size += src_texture[1]->Data.size(); + step++, off_b++; + } + if (!b.empty() && nullptr != src_texture[2]) { + tex_size += src_texture[2]->Data.size(); + step++; + } + if (!a.empty() && nullptr != src_texture[3]) { + tex_size += src_texture[3]->Data.size(); + step++; + } + + // Create target array. + converted_texture.Data = new uint8_t[tex_size]; + // And copy data + auto CopyTextureData = [&](const std::string &pID, const size_t pOffset, const size_t pStep, const uint8_t pSrcTexNum) -> void { + if (!pID.empty()) { + for (size_t idx_target = pOffset, idx_src = 0; idx_target < tex_size; idx_target += pStep, idx_src++) { + AMFTexture *tex = src_texture[pSrcTexNum]; + ai_assert(tex); + converted_texture.Data[idx_target] = tex->Data.at(idx_src); + } + } + }; // auto CopyTextureData = [&](const size_t pOffset, const size_t pStep, const uint8_t pSrcTexNum) -> void + + CopyTextureData(r, 0, step, 0); + CopyTextureData(g, off_g, step, 1); + CopyTextureData(b, off_b, step, 2); + CopyTextureData(a, step - 1, step, 3); + + // Store new converted texture ID + converted_texture.ID = TextureConverted_ID; + // Store new converted texture + mTexture_Converted.push_back(converted_texture); + + return TextureConverted_Index; +} + +void AMFImporter::PostprocessHelper_SplitFacesByTextureID(std::list<SComplexFace> &pInputList, std::list<std::list<SComplexFace>> &pOutputList_Separated) { + auto texmap_is_equal = [](const AMFTexMap *pTexMap1, const AMFTexMap *pTexMap2) -> bool { + if ((pTexMap1 == nullptr) && (pTexMap2 == nullptr)) return true; + if (pTexMap1 == nullptr) return false; + if (pTexMap2 == nullptr) return false; + + if (pTexMap1->TextureID_R != pTexMap2->TextureID_R) return false; + if (pTexMap1->TextureID_G != pTexMap2->TextureID_G) return false; + if (pTexMap1->TextureID_B != pTexMap2->TextureID_B) return false; + if (pTexMap1->TextureID_A != pTexMap2->TextureID_A) return false; + + return true; + }; + + pOutputList_Separated.clear(); + if (pInputList.empty()) return; + + do { + SComplexFace face_start = pInputList.front(); + std::list<SComplexFace> face_list_cur; + + for (std::list<SComplexFace>::iterator it = pInputList.begin(), it_end = pInputList.end(); it != it_end;) { + if (texmap_is_equal(face_start.TexMap, it->TexMap)) { + auto it_old = it; + + ++it; + face_list_cur.push_back(*it_old); + pInputList.erase(it_old); + } else { + ++it; + } + } + + if (!face_list_cur.empty()) pOutputList_Separated.push_back(face_list_cur); + + } while (!pInputList.empty()); +} + +void AMFImporter::Postprocess_AddMetadata(const AMFMetaDataArray &metadataList, aiNode &sceneNode) const { + if (metadataList.empty()) { + return; + } + + if (sceneNode.mMetaData != nullptr) { + throw DeadlyImportError("Postprocess. MetaData member in node are not nullptr. Something went wrong."); + } + + // copy collected metadata to output node. + sceneNode.mMetaData = aiMetadata::Alloc(static_cast<unsigned int>(metadataList.size())); + size_t meta_idx(0); + + for (const AMFMetadata *metadata : metadataList) { + sceneNode.mMetaData->Set(static_cast<unsigned int>(meta_idx++), metadata->Type, aiString(metadata->Value)); + } +} + +void AMFImporter::Postprocess_BuildNodeAndObject(const AMFObject &pNodeElement, MeshArray &meshList, aiNode **pSceneNode) { + AMFColor *object_color = nullptr; + + // create new aiNode and set name as <object> has. + *pSceneNode = new aiNode; + (*pSceneNode)->mName = pNodeElement.ID; + // read mesh and color + for (const AMFNodeElementBase *ne_child : pNodeElement.Child) { + std::vector<aiVector3D> vertex_arr; + std::vector<AMFColor *> color_arr; + + // color for object + if (ne_child->Type == AMFNodeElementBase::ENET_Color) { + object_color = (AMFColor *) ne_child; + } + + if (ne_child->Type == AMFNodeElementBase::ENET_Mesh) { + // Create arrays from children of mesh: vertices. + PostprocessHelper_CreateMeshDataArray(*((AMFMesh *)ne_child), vertex_arr, color_arr); + // Use this arrays as a source when creating every aiMesh + Postprocess_BuildMeshSet(*((AMFMesh *)ne_child), vertex_arr, color_arr, object_color, meshList, **pSceneNode); + } + } // for(const CAMFImporter_NodeElement* ne_child: pNodeElement) +} + +void AMFImporter::Postprocess_BuildMeshSet(const AMFMesh &pNodeElement, const std::vector<aiVector3D> &pVertexCoordinateArray, + const std::vector<AMFColor *> &pVertexColorArray, const AMFColor *pObjectColor, MeshArray &pMeshList, aiNode &pSceneNode) { + std::list<unsigned int> mesh_idx; + + // all data stored in "volume", search for it. + for (const AMFNodeElementBase *ne_child : pNodeElement.Child) { + const AMFColor *ne_volume_color = nullptr; + const SPP_Material *cur_mat = nullptr; + + if (ne_child->Type == AMFNodeElementBase::ENET_Volume) { + /******************* Get faces *******************/ + const AMFVolume *ne_volume = reinterpret_cast<const AMFVolume *>(ne_child); + + std::list<SComplexFace> complex_faces_list; // List of the faces of the volume. + std::list<std::list<SComplexFace>> complex_faces_toplist; // List of the face list for every mesh. + + // check if volume use material + if (!ne_volume->MaterialID.empty()) { + if (!Find_ConvertedMaterial(ne_volume->MaterialID, &cur_mat)) { + Throw_ID_NotFound(ne_volume->MaterialID); + } + } + + // inside "volume" collect all data and place to arrays or create new objects + for (const AMFNodeElementBase *ne_volume_child : ne_volume->Child) { + // color for volume + if (ne_volume_child->Type == AMFNodeElementBase::ENET_Color) { + ne_volume_color = reinterpret_cast<const AMFColor *>(ne_volume_child); + } else if (ne_volume_child->Type == AMFNodeElementBase::ENET_Triangle) // triangles, triangles colors + { + const AMFTriangle &tri_al = *reinterpret_cast<const AMFTriangle *>(ne_volume_child); + + SComplexFace complex_face; + + // initialize pointers + complex_face.Color = nullptr; + complex_face.TexMap = nullptr; + // get data from triangle children: color, texture coordinates. + if (tri_al.Child.size()) { + for (const AMFNodeElementBase *ne_triangle_child : tri_al.Child) { + if (ne_triangle_child->Type == AMFNodeElementBase::ENET_Color) + complex_face.Color = reinterpret_cast<const AMFColor *>(ne_triangle_child); + else if (ne_triangle_child->Type == AMFNodeElementBase::ENET_TexMap) + complex_face.TexMap = reinterpret_cast<const AMFTexMap *>(ne_triangle_child); + } + } // if(tri_al.Child.size()) + + // create new face and store it. + complex_face.Face.mNumIndices = 3; + complex_face.Face.mIndices = new unsigned int[3]; + complex_face.Face.mIndices[0] = static_cast<unsigned int>(tri_al.V[0]); + complex_face.Face.mIndices[1] = static_cast<unsigned int>(tri_al.V[1]); + complex_face.Face.mIndices[2] = static_cast<unsigned int>(tri_al.V[2]); + complex_faces_list.push_back(complex_face); + } + } // for(const CAMFImporter_NodeElement* ne_volume_child: ne_volume->Child) + + /**** Split faces list: one list per mesh ****/ + PostprocessHelper_SplitFacesByTextureID(complex_faces_list, complex_faces_toplist); + + /***** Create mesh for every faces list ******/ + for (std::list<SComplexFace> &face_list_cur : complex_faces_toplist) { + auto VertexIndex_GetMinimal = [](const std::list<SComplexFace> &pFaceList, const size_t *pBiggerThan) -> size_t { + size_t rv = 0; + + if (pBiggerThan != nullptr) { + bool found = false; + const size_t biggerThan = *pBiggerThan; + for (const SComplexFace &face : pFaceList) { + for (size_t idx_vert = 0; idx_vert < face.Face.mNumIndices; idx_vert++) { + if (face.Face.mIndices[idx_vert] > biggerThan) { + rv = face.Face.mIndices[idx_vert]; + found = true; + break; + } + } + + if (found) { + break; + } + } + + if (!found) { + return *pBiggerThan; + } + } else { + rv = pFaceList.front().Face.mIndices[0]; + } // if(pBiggerThan != nullptr) else + + for (const SComplexFace &face : pFaceList) { + for (size_t vi = 0; vi < face.Face.mNumIndices; vi++) { + if (face.Face.mIndices[vi] < rv) { + if (pBiggerThan != nullptr) { + if (face.Face.mIndices[vi] > *pBiggerThan) rv = face.Face.mIndices[vi]; + } else { + rv = face.Face.mIndices[vi]; + } + } + } + } // for(const SComplexFace& face: pFaceList) + + return rv; + }; // auto VertexIndex_GetMinimal = [](const std::list<SComplexFace>& pFaceList, const size_t* pBiggerThan) -> size_t + + auto VertexIndex_Replace = [](std::list<SComplexFace> &pFaceList, const size_t pIdx_From, const size_t pIdx_To) -> void { + for (const SComplexFace &face : pFaceList) { + for (size_t vi = 0; vi < face.Face.mNumIndices; vi++) { + if (face.Face.mIndices[vi] == pIdx_From) face.Face.mIndices[vi] = static_cast<unsigned int>(pIdx_To); + } + } + }; // auto VertexIndex_Replace = [](std::list<SComplexFace>& pFaceList, const size_t pIdx_From, const size_t pIdx_To) -> void + + auto Vertex_CalculateColor = [&](const size_t pIdx) -> aiColor4D { + // Color priorities(In descending order): + // 1. triangle color; + // 2. vertex color; + // 3. volume color; + // 4. object color; + // 5. material; + // 6. default - invisible coat. + // + // Fill vertices colors in color priority list above that's points from 1 to 6. + if ((pIdx < pVertexColorArray.size()) && (pVertexColorArray[pIdx] != nullptr)) // check for vertex color + { + if (pVertexColorArray[pIdx]->Composed) + throw DeadlyImportError("IME: vertex color composed"); + else + return pVertexColorArray[pIdx]->Color; + } else if (ne_volume_color != nullptr) // check for volume color + { + if (ne_volume_color->Composed) + throw DeadlyImportError("IME: volume color composed"); + else + return ne_volume_color->Color; + } else if (pObjectColor != nullptr) // check for object color + { + if (pObjectColor->Composed) + throw DeadlyImportError("IME: object color composed"); + else + return pObjectColor->Color; + } else if (cur_mat != nullptr) // check for material + { + return cur_mat->GetColor(pVertexCoordinateArray.at(pIdx).x, pVertexCoordinateArray.at(pIdx).y, pVertexCoordinateArray.at(pIdx).z); + } else // set default color. + { + return { 0, 0, 0, 0 }; + } // if((vi < pVertexColorArray.size()) && (pVertexColorArray[vi] != nullptr)) else + }; // auto Vertex_CalculateColor = [&](const size_t pIdx) -> aiColor4D + + aiMesh *tmesh = new aiMesh; + + tmesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE; // Only triangles is supported by AMF. + // + // set geometry and colors (vertices) + // + // copy faces/triangles + tmesh->mNumFaces = static_cast<unsigned int>(face_list_cur.size()); + tmesh->mFaces = new aiFace[tmesh->mNumFaces]; + + // Create vertices list and optimize indices. Optimization mean following.In AMF all volumes use one big list of vertices. And one volume + // can use only part of vertices list, for example: vertices list contain few thousands of vertices and volume use vertices 1, 3, 10. + // Do you need all this thousands of garbage? Of course no. So, optimization step transform sparse indices set to continuous. + size_t VertexCount_Max = tmesh->mNumFaces * 3; // 3 - triangles. + std::vector<aiVector3D> vert_arr, texcoord_arr; + std::vector<aiColor4D> col_arr; + + vert_arr.reserve(VertexCount_Max * 2); // "* 2" - see below TODO. + col_arr.reserve(VertexCount_Max * 2); + + { // fill arrays + size_t vert_idx_from, vert_idx_to; + + // first iteration. + vert_idx_to = 0; + vert_idx_from = VertexIndex_GetMinimal(face_list_cur, nullptr); + vert_arr.push_back(pVertexCoordinateArray.at(vert_idx_from)); + col_arr.push_back(Vertex_CalculateColor(vert_idx_from)); + if (vert_idx_from != vert_idx_to) VertexIndex_Replace(face_list_cur, vert_idx_from, vert_idx_to); + + // rest iterations + do { + vert_idx_from = VertexIndex_GetMinimal(face_list_cur, &vert_idx_to); + if (vert_idx_from == vert_idx_to) break; // all indices are transferred, + + vert_arr.push_back(pVertexCoordinateArray.at(vert_idx_from)); + col_arr.push_back(Vertex_CalculateColor(vert_idx_from)); + vert_idx_to++; + if (vert_idx_from != vert_idx_to) VertexIndex_Replace(face_list_cur, vert_idx_from, vert_idx_to); + + } while (true); + } // fill arrays. END. + + // + // check if triangle colors are used and create additional faces if needed. + // + for (const SComplexFace &face_cur : face_list_cur) { + if (face_cur.Color != nullptr) { + aiColor4D face_color; + size_t vert_idx_new = vert_arr.size(); + + if (face_cur.Color->Composed) + throw DeadlyImportError("IME: face color composed"); + else + face_color = face_cur.Color->Color; + + for (size_t idx_ind = 0; idx_ind < face_cur.Face.mNumIndices; idx_ind++) { + vert_arr.push_back(vert_arr.at(face_cur.Face.mIndices[idx_ind])); + col_arr.push_back(face_color); + face_cur.Face.mIndices[idx_ind] = static_cast<unsigned int>(vert_idx_new++); + } + } // if(face_cur.Color != nullptr) + } // for(const SComplexFace& face_cur: face_list_cur) + + // + // if texture is used then copy texture coordinates too. + // + if (face_list_cur.front().TexMap != nullptr) { + size_t idx_vert_new = vert_arr.size(); + ///TODO: clean unused vertices. "* 2": in certain cases - mesh full of triangle colors - vert_arr will contain duplicated vertices for + /// colored triangles and initial vertices (for colored vertices) which in real became unused. This part need more thinking about + /// optimization. + bool *idx_vert_used; + + idx_vert_used = new bool[VertexCount_Max * 2]; + for (size_t i = 0, i_e = VertexCount_Max * 2; i < i_e; i++) + idx_vert_used[i] = false; + + // This ID's will be used when set materials ID in scene. + tmesh->mMaterialIndex = static_cast<unsigned int>(PostprocessHelper_GetTextureID_Or_Create(face_list_cur.front().TexMap->TextureID_R, + face_list_cur.front().TexMap->TextureID_G, + face_list_cur.front().TexMap->TextureID_B, + face_list_cur.front().TexMap->TextureID_A)); + texcoord_arr.resize(VertexCount_Max * 2); + for (const SComplexFace &face_cur : face_list_cur) { + for (size_t idx_ind = 0; idx_ind < face_cur.Face.mNumIndices; idx_ind++) { + const size_t idx_vert = face_cur.Face.mIndices[idx_ind]; + + if (!idx_vert_used[idx_vert]) { + texcoord_arr.at(idx_vert) = face_cur.TexMap->TextureCoordinate[idx_ind]; + idx_vert_used[idx_vert] = true; + } else if (texcoord_arr.at(idx_vert) != face_cur.TexMap->TextureCoordinate[idx_ind]) { + // in that case one vertex is shared with many texture coordinates. We need to duplicate vertex with another texture + // coordinates. + vert_arr.push_back(vert_arr.at(idx_vert)); + col_arr.push_back(col_arr.at(idx_vert)); + texcoord_arr.at(idx_vert_new) = face_cur.TexMap->TextureCoordinate[idx_ind]; + face_cur.Face.mIndices[idx_ind] = static_cast<unsigned int>(idx_vert_new++); + } + } // for(size_t idx_ind = 0; idx_ind < face_cur.Face.mNumIndices; idx_ind++) + } // for(const SComplexFace& face_cur: face_list_cur) + + delete[] idx_vert_used; + // shrink array + texcoord_arr.resize(idx_vert_new); + } // if(face_list_cur.front().TexMap != nullptr) + + // + // copy collected data to mesh + // + tmesh->mNumVertices = static_cast<unsigned int>(vert_arr.size()); + tmesh->mVertices = new aiVector3D[tmesh->mNumVertices]; + tmesh->mColors[0] = new aiColor4D[tmesh->mNumVertices]; + + memcpy(tmesh->mVertices, vert_arr.data(), tmesh->mNumVertices * sizeof(aiVector3D)); + memcpy(tmesh->mColors[0], col_arr.data(), tmesh->mNumVertices * sizeof(aiColor4D)); + if (texcoord_arr.size() > 0) { + tmesh->mTextureCoords[0] = new aiVector3D[tmesh->mNumVertices]; + memcpy(tmesh->mTextureCoords[0], texcoord_arr.data(), tmesh->mNumVertices * sizeof(aiVector3D)); + tmesh->mNumUVComponents[0] = 2; // U and V stored in "x", "y" of aiVector3D. + } + + size_t idx_face = 0; + for (const SComplexFace &face_cur : face_list_cur) + tmesh->mFaces[idx_face++] = face_cur.Face; + + // store new aiMesh + mesh_idx.push_back(static_cast<unsigned int>(pMeshList.size())); + pMeshList.push_back(tmesh); + } // for(const std::list<SComplexFace>& face_list_cur: complex_faces_toplist) + } // if(ne_child->Type == CAMFImporter_NodeElement::ENET_Volume) + } // for(const CAMFImporter_NodeElement* ne_child: pNodeElement.Child) + + // if meshes was created then assign new indices with current aiNode + if (!mesh_idx.empty()) { + std::list<unsigned int>::const_iterator mit = mesh_idx.begin(); + + pSceneNode.mNumMeshes = static_cast<unsigned int>(mesh_idx.size()); + pSceneNode.mMeshes = new unsigned int[pSceneNode.mNumMeshes]; + for (size_t i = 0; i < pSceneNode.mNumMeshes; i++) + pSceneNode.mMeshes[i] = *mit++; + } // if(mesh_idx.size() > 0) +} + +void AMFImporter::Postprocess_BuildMaterial(const AMFMaterial &pMaterial) { + SPP_Material new_mat; + + new_mat.ID = pMaterial.ID; + for (const AMFNodeElementBase *mat_child : pMaterial.Child) { + if (mat_child->Type == AMFNodeElementBase::ENET_Color) { + new_mat.Color = (AMFColor*)mat_child; + } else if (mat_child->Type == AMFNodeElementBase::ENET_Metadata) { + new_mat.Metadata.push_back((AMFMetadata *)mat_child); + } + } // for(const CAMFImporter_NodeElement* mat_child; pMaterial.Child) + + // place converted material to special list + mMaterial_Converted.push_back(new_mat); +} + +void AMFImporter::Postprocess_BuildConstellation(AMFConstellation &pConstellation, NodeArray &nodeArray) const { + aiNode *con_node; + std::list<aiNode *> ch_node; + + // We will build next hierarchy: + // aiNode as parent (<constellation>) for set of nodes as a children + // |- aiNode for transformation (<instance> -> <delta...>, <r...>) - aiNode for pointing to object ("objectid") + // ... + // \_ aiNode for transformation (<instance> -> <delta...>, <r...>) - aiNode for pointing to object ("objectid") + con_node = new aiNode; + con_node->mName = pConstellation.ID; + // Walk through children and search for instances of another objects, constellations. + for (const AMFNodeElementBase *ne : pConstellation.Child) { + aiMatrix4x4 tmat; + aiNode *t_node; + aiNode *found_node; + + if (ne->Type == AMFNodeElementBase::ENET_Metadata) continue; + if (ne->Type != AMFNodeElementBase::ENET_Instance) throw DeadlyImportError("Only <instance> nodes can be in <constellation>."); + + // create alias for convenience + AMFInstance &als = *((AMFInstance *)ne); + // find referenced object + if (!Find_ConvertedNode(als.ObjectID, nodeArray, &found_node)) Throw_ID_NotFound(als.ObjectID); + + // create node for applying transformation + t_node = new aiNode; + t_node->mParent = con_node; + // apply transformation + aiMatrix4x4::Translation(als.Delta, tmat), t_node->mTransformation *= tmat; + aiMatrix4x4::RotationX(als.Rotation.x, tmat), t_node->mTransformation *= tmat; + aiMatrix4x4::RotationY(als.Rotation.y, tmat), t_node->mTransformation *= tmat; + aiMatrix4x4::RotationZ(als.Rotation.z, tmat), t_node->mTransformation *= tmat; + // create array for one child node + t_node->mNumChildren = 1; + t_node->mChildren = new aiNode *[t_node->mNumChildren]; + SceneCombiner::Copy(&t_node->mChildren[0], found_node); + t_node->mChildren[0]->mParent = t_node; + ch_node.push_back(t_node); + } // for(const CAMFImporter_NodeElement* ne: pConstellation.Child) + + // copy found aiNode's as children + if (ch_node.empty()) throw DeadlyImportError("<constellation> must have at least one <instance>."); + + size_t ch_idx = 0; + + con_node->mNumChildren = static_cast<unsigned int>(ch_node.size()); + con_node->mChildren = new aiNode *[con_node->mNumChildren]; + for (aiNode *node : ch_node) + con_node->mChildren[ch_idx++] = node; + + // and place "root" of <constellation> node to node list + nodeArray.push_back(con_node); +} + +void AMFImporter::Postprocess_BuildScene(aiScene *pScene) { + NodeArray nodeArray; + MeshArray mesh_list; + AMFMetaDataArray meta_list; + + // + // Because for AMF "material" is just complex colors mixing so aiMaterial will not be used. + // For building aiScene we are must to do few steps: + // at first creating root node for aiScene. + pScene->mRootNode = new aiNode; + pScene->mRootNode->mParent = nullptr; + pScene->mFlags |= AI_SCENE_FLAGS_ALLOW_SHARED; + // search for root(<amf>) element + AMFNodeElementBase *root_el = nullptr; + + for (AMFNodeElementBase *ne : mNodeElement_List) { + if (ne->Type != AMFNodeElementBase::ENET_Root) { + continue; + } + + root_el = ne; + break; + } // for(const CAMFImporter_NodeElement* ne: mNodeElement_List) + + // Check if root element are found. + if (root_el == nullptr) { + throw DeadlyImportError("Root(<amf>) element not found."); + } + + // after that walk through children of root and collect data. Five types of nodes can be placed at top level - in <amf>: <object>, <material>, <texture>, + // <constellation> and <metadata>. But at first we must read <material> and <texture> because they will be used in <object>. <metadata> can be read + // at any moment. + // + // 1. <material> + // 2. <texture> will be converted later when processing triangles list. \sa Postprocess_BuildMeshSet + for (const AMFNodeElementBase *root_child : root_el->Child) { + if (root_child->Type == AMFNodeElementBase::ENET_Material) { + Postprocess_BuildMaterial(*((AMFMaterial *)root_child)); + } + } + + // After "appearance" nodes we must read <object> because it will be used in <constellation> -> <instance>. + // + // 3. <object> + for (const AMFNodeElementBase *root_child : root_el->Child) { + if (root_child->Type == AMFNodeElementBase::ENET_Object) { + aiNode *tnode = nullptr; + + // for <object> mesh and node must be built: object ID assigned to aiNode name and will be used in future for <instance> + Postprocess_BuildNodeAndObject(*((AMFObject *)root_child), mesh_list, &tnode); + if (tnode != nullptr) { + nodeArray.push_back(tnode); + } + } + } // for(const CAMFImporter_NodeElement* root_child: root_el->Child) + + // And finally read rest of nodes. + // + for (const AMFNodeElementBase *root_child : root_el->Child) { + // 4. <constellation> + if (root_child->Type == AMFNodeElementBase::ENET_Constellation) { + // <object> and <constellation> at top of self abstraction use aiNode. So we can use only aiNode list for creating new aiNode's. + Postprocess_BuildConstellation(*((AMFConstellation *)root_child), nodeArray); + } + + // 5, <metadata> + if (root_child->Type == AMFNodeElementBase::ENET_Metadata) meta_list.push_back((AMFMetadata *)root_child); + } // for(const CAMFImporter_NodeElement* root_child: root_el->Child) + + // at now we can add collected metadata to root node + Postprocess_AddMetadata(meta_list, *pScene->mRootNode); + // + // Check constellation children + // + // As said in specification: + // "When multiple objects and constellations are defined in a single file, only the top level objects and constellations are available for printing." + // What that means? For example: if some object is used in constellation then you must show only constellation but not original object. + // And at this step we are checking that relations. +nl_clean_loop: + + if (nodeArray.size() > 1) { + // walk through all nodes + for (NodeArray::iterator nl_it = nodeArray.begin(); nl_it != nodeArray.end(); ++nl_it) { + // and try to find them in another top nodes. + NodeArray::const_iterator next_it = nl_it; + + ++next_it; + for (; next_it != nodeArray.end(); ++next_it) { + if ((*next_it)->FindNode((*nl_it)->mName) != nullptr) { + // if current top node(nl_it) found in another top node then erase it from node_list and restart search loop. + nodeArray.erase(nl_it); + + goto nl_clean_loop; + } + } // for(; next_it != node_list.end(); next_it++) + } // for(std::list<aiNode*>::const_iterator nl_it = node_list.begin(); nl_it != node_list.end(); nl_it++) + } + + // + // move created objects to aiScene + // + // + // Nodes + if (!nodeArray.empty()) { + NodeArray::const_iterator nl_it = nodeArray.begin(); + + pScene->mRootNode->mNumChildren = static_cast<unsigned int>(nodeArray.size()); + pScene->mRootNode->mChildren = new aiNode *[pScene->mRootNode->mNumChildren]; + for (size_t i = 0; i < pScene->mRootNode->mNumChildren; i++) { + // Objects and constellation that must be showed placed at top of hierarchy in <amf> node. So all aiNode's in node_list must have + // mRootNode only as parent. + (*nl_it)->mParent = pScene->mRootNode; + pScene->mRootNode->mChildren[i] = *nl_it++; + } + } // if(node_list.size() > 0) + + // + // Meshes + if (!mesh_list.empty()) { + MeshArray::const_iterator ml_it = mesh_list.begin(); + + pScene->mNumMeshes = static_cast<unsigned int>(mesh_list.size()); + pScene->mMeshes = new aiMesh *[pScene->mNumMeshes]; + for (size_t i = 0; i < pScene->mNumMeshes; i++) + pScene->mMeshes[i] = *ml_it++; + } // if(mesh_list.size() > 0) + + // + // Textures + pScene->mNumTextures = static_cast<unsigned int>(mTexture_Converted.size()); + if (pScene->mNumTextures > 0) { + size_t idx; + + idx = 0; + pScene->mTextures = new aiTexture *[pScene->mNumTextures]; + for (const SPP_Texture &tex_convd : mTexture_Converted) { + pScene->mTextures[idx] = new aiTexture; + pScene->mTextures[idx]->mWidth = static_cast<unsigned int>(tex_convd.Width); + pScene->mTextures[idx]->mHeight = static_cast<unsigned int>(tex_convd.Height); + pScene->mTextures[idx]->pcData = (aiTexel *)tex_convd.Data; + // texture format description. + strcpy(pScene->mTextures[idx]->achFormatHint, tex_convd.FormatHint); + idx++; + } // for(const SPP_Texture& tex_convd: mTexture_Converted) + + // Create materials for embedded textures. + idx = 0; + pScene->mNumMaterials = static_cast<unsigned int>(mTexture_Converted.size()); + pScene->mMaterials = new aiMaterial *[pScene->mNumMaterials]; + for (const SPP_Texture &tex_convd : mTexture_Converted) { + const aiString texture_id(AI_EMBEDDED_TEXNAME_PREFIX + ai_to_string(idx)); + const int mode = aiTextureOp_Multiply; + const int repeat = tex_convd.Tiled ? 1 : 0; + + pScene->mMaterials[idx] = new aiMaterial; + pScene->mMaterials[idx]->AddProperty(&texture_id, AI_MATKEY_TEXTURE_DIFFUSE(0)); + pScene->mMaterials[idx]->AddProperty(&mode, 1, AI_MATKEY_TEXOP_DIFFUSE(0)); + pScene->mMaterials[idx]->AddProperty(&repeat, 1, AI_MATKEY_MAPPINGMODE_U_DIFFUSE(0)); + pScene->mMaterials[idx]->AddProperty(&repeat, 1, AI_MATKEY_MAPPINGMODE_V_DIFFUSE(0)); + idx++; + } + } // if(pScene->mNumTextures > 0) +} // END: after that walk through children of root and collect data + +} // namespace Assimp + +#endif // !ASSIMP_BUILD_NO_AMF_IMPORTER |