AMFImporter_Postprocess.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2020, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /// \file AMFImporter_Postprocess.cpp
  35. /// \brief Convert built scenegraph and objects to Assimp scenegraph.
  36. /// \date 2016
  37. /// \author [email protected]
  38. #ifndef ASSIMP_BUILD_NO_AMF_IMPORTER
  39. #include "AMFImporter.hpp"
  40. // Header files, Assimp.
  41. #include <assimp/SceneCombiner.h>
  42. #include <assimp/StandardShapes.h>
  43. #include <assimp/StringUtils.h>
  44. // Header files, stdlib.
  45. #include <iterator>
  46. namespace Assimp {
  47. aiColor4D AMFImporter::SPP_Material::GetColor(const float /*pX*/, const float /*pY*/, const float /*pZ*/) const {
  48. aiColor4D tcol;
  49. // Check if stored data are supported.
  50. if (!Composition.empty()) {
  51. throw DeadlyImportError("IME. GetColor for composition");
  52. } else if (Color->Composed) {
  53. throw DeadlyImportError("IME. GetColor, composed color");
  54. } else {
  55. tcol = Color->Color;
  56. }
  57. // Check if default color must be used
  58. if ((tcol.r == 0) && (tcol.g == 0) && (tcol.b == 0) && (tcol.a == 0)) {
  59. tcol.r = 0.5f;
  60. tcol.g = 0.5f;
  61. tcol.b = 0.5f;
  62. tcol.a = 1;
  63. }
  64. return tcol;
  65. }
  66. void AMFImporter::PostprocessHelper_CreateMeshDataArray(const CAMFImporter_NodeElement_Mesh &pNodeElement, std::vector<aiVector3D> &pVertexCoordinateArray,
  67. std::vector<CAMFImporter_NodeElement_Color *> &pVertexColorArray) const {
  68. CAMFImporter_NodeElement_Vertices *vn = nullptr;
  69. size_t col_idx;
  70. // All data stored in "vertices", search for it.
  71. for (CAMFImporter_NodeElement *ne_child : pNodeElement.Child) {
  72. if (ne_child->Type == CAMFImporter_NodeElement::ENET_Vertices) vn = (CAMFImporter_NodeElement_Vertices *)ne_child;
  73. }
  74. // If "vertices" not found then no work for us.
  75. if (vn == nullptr) return;
  76. pVertexCoordinateArray.reserve(vn->Child.size()); // all coordinates stored as child and we need to reserve space for future push_back's.
  77. pVertexColorArray.resize(vn->Child.size()); // colors count equal vertices count.
  78. col_idx = 0;
  79. // Inside vertices collect all data and place to arrays
  80. for (CAMFImporter_NodeElement *vn_child : vn->Child) {
  81. // vertices, colors
  82. if (vn_child->Type == CAMFImporter_NodeElement::ENET_Vertex) {
  83. // by default clear color for current vertex
  84. pVertexColorArray[col_idx] = nullptr;
  85. for (CAMFImporter_NodeElement *vtx : vn_child->Child) {
  86. if (vtx->Type == CAMFImporter_NodeElement::ENET_Coordinates) {
  87. pVertexCoordinateArray.push_back(((CAMFImporter_NodeElement_Coordinates *)vtx)->Coordinate);
  88. continue;
  89. }
  90. if (vtx->Type == CAMFImporter_NodeElement::ENET_Color) {
  91. pVertexColorArray[col_idx] = (CAMFImporter_NodeElement_Color *)vtx;
  92. continue;
  93. }
  94. } // for(CAMFImporter_NodeElement* vtx: vn_child->Child)
  95. col_idx++;
  96. } // if(vn_child->Type == CAMFImporter_NodeElement::ENET_Vertex)
  97. } // for(CAMFImporter_NodeElement* vn_child: vn->Child)
  98. }
  99. size_t AMFImporter::PostprocessHelper_GetTextureID_Or_Create(const std::string &pID_R, const std::string &pID_G, const std::string &pID_B,
  100. const std::string &pID_A) {
  101. size_t TextureConverted_Index;
  102. std::string TextureConverted_ID;
  103. // check input data
  104. if (pID_R.empty() && pID_G.empty() && pID_B.empty() && pID_A.empty())
  105. throw DeadlyImportError("PostprocessHelper_GetTextureID_Or_Create. At least one texture ID must be defined.");
  106. // Create ID
  107. TextureConverted_ID = pID_R + "_" + pID_G + "_" + pID_B + "_" + pID_A;
  108. // Check if texture specified by set of IDs is converted already.
  109. TextureConverted_Index = 0;
  110. for (const SPP_Texture &tex_convd : mTexture_Converted) {
  111. if (tex_convd.ID == TextureConverted_ID) {
  112. return TextureConverted_Index;
  113. } else {
  114. ++TextureConverted_Index;
  115. }
  116. }
  117. //
  118. // Converted texture not found, create it.
  119. //
  120. CAMFImporter_NodeElement_Texture *src_texture[4]{ nullptr };
  121. std::vector<CAMFImporter_NodeElement_Texture *> src_texture_4check;
  122. SPP_Texture converted_texture;
  123. { // find all specified source textures
  124. CAMFImporter_NodeElement *t_tex;
  125. // R
  126. if (!pID_R.empty()) {
  127. if (!Find_NodeElement(pID_R, CAMFImporter_NodeElement::ENET_Texture, &t_tex)) Throw_ID_NotFound(pID_R);
  128. src_texture[0] = (CAMFImporter_NodeElement_Texture *)t_tex;
  129. src_texture_4check.push_back((CAMFImporter_NodeElement_Texture *)t_tex);
  130. } else {
  131. src_texture[0] = nullptr;
  132. }
  133. // G
  134. if (!pID_G.empty()) {
  135. if (!Find_NodeElement(pID_G, CAMFImporter_NodeElement::ENET_Texture, &t_tex)) Throw_ID_NotFound(pID_G);
  136. src_texture[1] = (CAMFImporter_NodeElement_Texture *)t_tex;
  137. src_texture_4check.push_back((CAMFImporter_NodeElement_Texture *)t_tex);
  138. } else {
  139. src_texture[1] = nullptr;
  140. }
  141. // B
  142. if (!pID_B.empty()) {
  143. if (!Find_NodeElement(pID_B, CAMFImporter_NodeElement::ENET_Texture, &t_tex)) Throw_ID_NotFound(pID_B);
  144. src_texture[2] = (CAMFImporter_NodeElement_Texture *)t_tex;
  145. src_texture_4check.push_back((CAMFImporter_NodeElement_Texture *)t_tex);
  146. } else {
  147. src_texture[2] = nullptr;
  148. }
  149. // A
  150. if (!pID_A.empty()) {
  151. if (!Find_NodeElement(pID_A, CAMFImporter_NodeElement::ENET_Texture, &t_tex)) Throw_ID_NotFound(pID_A);
  152. src_texture[3] = (CAMFImporter_NodeElement_Texture *)t_tex;
  153. src_texture_4check.push_back((CAMFImporter_NodeElement_Texture *)t_tex);
  154. } else {
  155. src_texture[3] = nullptr;
  156. }
  157. } // END: find all specified source textures
  158. // check that all textures has same size
  159. if (src_texture_4check.size() > 1) {
  160. for (size_t i = 0, i_e = (src_texture_4check.size() - 1); i < i_e; i++) {
  161. if ((src_texture_4check[i]->Width != src_texture_4check[i + 1]->Width) || (src_texture_4check[i]->Height != src_texture_4check[i + 1]->Height) ||
  162. (src_texture_4check[i]->Depth != src_texture_4check[i + 1]->Depth)) {
  163. throw DeadlyImportError("PostprocessHelper_GetTextureID_Or_Create. Source texture must has the same size.");
  164. }
  165. }
  166. } // if(src_texture_4check.size() > 1)
  167. // set texture attributes
  168. converted_texture.Width = src_texture_4check[0]->Width;
  169. converted_texture.Height = src_texture_4check[0]->Height;
  170. converted_texture.Depth = src_texture_4check[0]->Depth;
  171. // if one of source texture is tiled then converted texture is tiled too.
  172. converted_texture.Tiled = false;
  173. for (uint8_t i = 0; i < src_texture_4check.size(); i++)
  174. converted_texture.Tiled |= src_texture_4check[i]->Tiled;
  175. // Create format hint.
  176. strcpy(converted_texture.FormatHint, "rgba0000"); // copy initial string.
  177. if (!pID_R.empty()) converted_texture.FormatHint[4] = '8';
  178. if (!pID_G.empty()) converted_texture.FormatHint[5] = '8';
  179. if (!pID_B.empty()) converted_texture.FormatHint[6] = '8';
  180. if (!pID_A.empty()) converted_texture.FormatHint[7] = '8';
  181. //
  182. // Сopy data of textures.
  183. //
  184. size_t tex_size = 0;
  185. size_t step = 0;
  186. size_t off_g = 0;
  187. size_t off_b = 0;
  188. // Calculate size of the target array and rule how data will be copied.
  189. if (!pID_R.empty() && nullptr != src_texture[0]) {
  190. tex_size += src_texture[0]->Data.size();
  191. step++, off_g++, off_b++;
  192. }
  193. if (!pID_G.empty() && nullptr != src_texture[1]) {
  194. tex_size += src_texture[1]->Data.size();
  195. step++, off_b++;
  196. }
  197. if (!pID_B.empty() && nullptr != src_texture[2]) {
  198. tex_size += src_texture[2]->Data.size();
  199. step++;
  200. }
  201. if (!pID_A.empty() && nullptr != src_texture[3]) {
  202. tex_size += src_texture[3]->Data.size();
  203. step++;
  204. }
  205. // Create target array.
  206. converted_texture.Data = new uint8_t[tex_size];
  207. // And copy data
  208. auto CopyTextureData = [&](const std::string &pID, const size_t pOffset, const size_t pStep, const uint8_t pSrcTexNum) -> void {
  209. if (!pID.empty()) {
  210. for (size_t idx_target = pOffset, idx_src = 0; idx_target < tex_size; idx_target += pStep, idx_src++) {
  211. CAMFImporter_NodeElement_Texture *tex = src_texture[pSrcTexNum];
  212. ai_assert(tex);
  213. converted_texture.Data[idx_target] = tex->Data.at(idx_src);
  214. }
  215. }
  216. }; // auto CopyTextureData = [&](const size_t pOffset, const size_t pStep, const uint8_t pSrcTexNum) -> void
  217. CopyTextureData(pID_R, 0, step, 0);
  218. CopyTextureData(pID_G, off_g, step, 1);
  219. CopyTextureData(pID_B, off_b, step, 2);
  220. CopyTextureData(pID_A, step - 1, step, 3);
  221. // Store new converted texture ID
  222. converted_texture.ID = TextureConverted_ID;
  223. // Store new converted texture
  224. mTexture_Converted.push_back(converted_texture);
  225. return TextureConverted_Index;
  226. }
  227. void AMFImporter::PostprocessHelper_SplitFacesByTextureID(std::list<SComplexFace> &pInputList, std::list<std::list<SComplexFace>> &pOutputList_Separated) {
  228. auto texmap_is_equal = [](const CAMFImporter_NodeElement_TexMap *pTexMap1, const CAMFImporter_NodeElement_TexMap *pTexMap2) -> bool {
  229. if ((pTexMap1 == nullptr) && (pTexMap2 == nullptr)) return true;
  230. if (pTexMap1 == nullptr) return false;
  231. if (pTexMap2 == nullptr) return false;
  232. if (pTexMap1->TextureID_R != pTexMap2->TextureID_R) return false;
  233. if (pTexMap1->TextureID_G != pTexMap2->TextureID_G) return false;
  234. if (pTexMap1->TextureID_B != pTexMap2->TextureID_B) return false;
  235. if (pTexMap1->TextureID_A != pTexMap2->TextureID_A) return false;
  236. return true;
  237. };
  238. pOutputList_Separated.clear();
  239. if (pInputList.empty()) return;
  240. do {
  241. SComplexFace face_start = pInputList.front();
  242. std::list<SComplexFace> face_list_cur;
  243. for (std::list<SComplexFace>::iterator it = pInputList.begin(), it_end = pInputList.end(); it != it_end;) {
  244. if (texmap_is_equal(face_start.TexMap, it->TexMap)) {
  245. auto it_old = it;
  246. ++it;
  247. face_list_cur.push_back(*it_old);
  248. pInputList.erase(it_old);
  249. } else {
  250. ++it;
  251. }
  252. }
  253. if (!face_list_cur.empty()) pOutputList_Separated.push_back(face_list_cur);
  254. } while (!pInputList.empty());
  255. }
  256. void AMFImporter::Postprocess_AddMetadata(const std::list<CAMFImporter_NodeElement_Metadata *> &metadataList, aiNode &sceneNode) const {
  257. if (!metadataList.empty()) {
  258. if (sceneNode.mMetaData != nullptr) throw DeadlyImportError("Postprocess. MetaData member in node are not nullptr. Something went wrong.");
  259. // copy collected metadata to output node.
  260. sceneNode.mMetaData = aiMetadata::Alloc(static_cast<unsigned int>(metadataList.size()));
  261. size_t meta_idx(0);
  262. for (const CAMFImporter_NodeElement_Metadata &metadata : metadataList) {
  263. sceneNode.mMetaData->Set(static_cast<unsigned int>(meta_idx++), metadata.Type, aiString(metadata.Value));
  264. }
  265. } // if(!metadataList.empty())
  266. }
  267. void AMFImporter::Postprocess_BuildNodeAndObject(const CAMFImporter_NodeElement_Object &pNodeElement, std::list<aiMesh *> &pMeshList, aiNode **pSceneNode) {
  268. CAMFImporter_NodeElement_Color *object_color = nullptr;
  269. // create new aiNode and set name as <object> has.
  270. *pSceneNode = new aiNode;
  271. (*pSceneNode)->mName = pNodeElement.ID;
  272. // read mesh and color
  273. for (const CAMFImporter_NodeElement *ne_child : pNodeElement.Child) {
  274. std::vector<aiVector3D> vertex_arr;
  275. std::vector<CAMFImporter_NodeElement_Color *> color_arr;
  276. // color for object
  277. if (ne_child->Type == CAMFImporter_NodeElement::ENET_Color) object_color = (CAMFImporter_NodeElement_Color *)ne_child;
  278. if (ne_child->Type == CAMFImporter_NodeElement::ENET_Mesh) {
  279. // Create arrays from children of mesh: vertices.
  280. PostprocessHelper_CreateMeshDataArray(*((CAMFImporter_NodeElement_Mesh *)ne_child), vertex_arr, color_arr);
  281. // Use this arrays as a source when creating every aiMesh
  282. Postprocess_BuildMeshSet(*((CAMFImporter_NodeElement_Mesh *)ne_child), vertex_arr, color_arr, object_color, pMeshList, **pSceneNode);
  283. }
  284. } // for(const CAMFImporter_NodeElement* ne_child: pNodeElement)
  285. }
  286. void AMFImporter::Postprocess_BuildMeshSet(const CAMFImporter_NodeElement_Mesh &pNodeElement, const std::vector<aiVector3D> &pVertexCoordinateArray,
  287. const std::vector<CAMFImporter_NodeElement_Color *> &pVertexColorArray,
  288. const CAMFImporter_NodeElement_Color *pObjectColor, std::list<aiMesh *> &pMeshList, aiNode &pSceneNode) {
  289. std::list<unsigned int> mesh_idx;
  290. // all data stored in "volume", search for it.
  291. for (const CAMFImporter_NodeElement *ne_child : pNodeElement.Child) {
  292. const CAMFImporter_NodeElement_Color *ne_volume_color = nullptr;
  293. const SPP_Material *cur_mat = nullptr;
  294. if (ne_child->Type == CAMFImporter_NodeElement::ENET_Volume) {
  295. /******************* Get faces *******************/
  296. const CAMFImporter_NodeElement_Volume *ne_volume = reinterpret_cast<const CAMFImporter_NodeElement_Volume *>(ne_child);
  297. std::list<SComplexFace> complex_faces_list; // List of the faces of the volume.
  298. std::list<std::list<SComplexFace>> complex_faces_toplist; // List of the face list for every mesh.
  299. // check if volume use material
  300. if (!ne_volume->MaterialID.empty()) {
  301. if (!Find_ConvertedMaterial(ne_volume->MaterialID, &cur_mat)) Throw_ID_NotFound(ne_volume->MaterialID);
  302. }
  303. // inside "volume" collect all data and place to arrays or create new objects
  304. for (const CAMFImporter_NodeElement *ne_volume_child : ne_volume->Child) {
  305. // color for volume
  306. if (ne_volume_child->Type == CAMFImporter_NodeElement::ENET_Color) {
  307. ne_volume_color = reinterpret_cast<const CAMFImporter_NodeElement_Color *>(ne_volume_child);
  308. } else if (ne_volume_child->Type == CAMFImporter_NodeElement::ENET_Triangle) // triangles, triangles colors
  309. {
  310. const CAMFImporter_NodeElement_Triangle &tri_al = *reinterpret_cast<const CAMFImporter_NodeElement_Triangle *>(ne_volume_child);
  311. SComplexFace complex_face;
  312. // initialize pointers
  313. complex_face.Color = nullptr;
  314. complex_face.TexMap = nullptr;
  315. // get data from triangle children: color, texture coordinates.
  316. if (tri_al.Child.size()) {
  317. for (const CAMFImporter_NodeElement *ne_triangle_child : tri_al.Child) {
  318. if (ne_triangle_child->Type == CAMFImporter_NodeElement::ENET_Color)
  319. complex_face.Color = reinterpret_cast<const CAMFImporter_NodeElement_Color *>(ne_triangle_child);
  320. else if (ne_triangle_child->Type == CAMFImporter_NodeElement::ENET_TexMap)
  321. complex_face.TexMap = reinterpret_cast<const CAMFImporter_NodeElement_TexMap *>(ne_triangle_child);
  322. }
  323. } // if(tri_al.Child.size())
  324. // create new face and store it.
  325. complex_face.Face.mNumIndices = 3;
  326. complex_face.Face.mIndices = new unsigned int[3];
  327. complex_face.Face.mIndices[0] = static_cast<unsigned int>(tri_al.V[0]);
  328. complex_face.Face.mIndices[1] = static_cast<unsigned int>(tri_al.V[1]);
  329. complex_face.Face.mIndices[2] = static_cast<unsigned int>(tri_al.V[2]);
  330. complex_faces_list.push_back(complex_face);
  331. }
  332. } // for(const CAMFImporter_NodeElement* ne_volume_child: ne_volume->Child)
  333. /**** Split faces list: one list per mesh ****/
  334. PostprocessHelper_SplitFacesByTextureID(complex_faces_list, complex_faces_toplist);
  335. /***** Create mesh for every faces list ******/
  336. for (std::list<SComplexFace> &face_list_cur : complex_faces_toplist) {
  337. auto VertexIndex_GetMinimal = [](const std::list<SComplexFace> &pFaceList, const size_t *pBiggerThan) -> size_t {
  338. size_t rv = 0;
  339. if (pBiggerThan != nullptr) {
  340. bool found = false;
  341. for (const SComplexFace &face : pFaceList) {
  342. for (size_t idx_vert = 0; idx_vert < face.Face.mNumIndices; idx_vert++) {
  343. if (face.Face.mIndices[idx_vert] > *pBiggerThan) {
  344. rv = face.Face.mIndices[idx_vert];
  345. found = true;
  346. break;
  347. }
  348. }
  349. if (found) break;
  350. }
  351. if (!found) return *pBiggerThan;
  352. } else {
  353. rv = pFaceList.front().Face.mIndices[0];
  354. } // if(pBiggerThan != nullptr) else
  355. for (const SComplexFace &face : pFaceList) {
  356. for (size_t vi = 0; vi < face.Face.mNumIndices; vi++) {
  357. if (face.Face.mIndices[vi] < rv) {
  358. if (pBiggerThan != nullptr) {
  359. if (face.Face.mIndices[vi] > *pBiggerThan) rv = face.Face.mIndices[vi];
  360. } else {
  361. rv = face.Face.mIndices[vi];
  362. }
  363. }
  364. }
  365. } // for(const SComplexFace& face: pFaceList)
  366. return rv;
  367. }; // auto VertexIndex_GetMinimal = [](const std::list<SComplexFace>& pFaceList, const size_t* pBiggerThan) -> size_t
  368. auto VertexIndex_Replace = [](std::list<SComplexFace> &pFaceList, const size_t pIdx_From, const size_t pIdx_To) -> void {
  369. for (const SComplexFace &face : pFaceList) {
  370. for (size_t vi = 0; vi < face.Face.mNumIndices; vi++) {
  371. if (face.Face.mIndices[vi] == pIdx_From) face.Face.mIndices[vi] = static_cast<unsigned int>(pIdx_To);
  372. }
  373. }
  374. }; // auto VertexIndex_Replace = [](std::list<SComplexFace>& pFaceList, const size_t pIdx_From, const size_t pIdx_To) -> void
  375. auto Vertex_CalculateColor = [&](const size_t pIdx) -> aiColor4D {
  376. // Color priorities(In descending order):
  377. // 1. triangle color;
  378. // 2. vertex color;
  379. // 3. volume color;
  380. // 4. object color;
  381. // 5. material;
  382. // 6. default - invisible coat.
  383. //
  384. // Fill vertices colors in color priority list above that's points from 1 to 6.
  385. if ((pIdx < pVertexColorArray.size()) && (pVertexColorArray[pIdx] != nullptr)) // check for vertex color
  386. {
  387. if (pVertexColorArray[pIdx]->Composed)
  388. throw DeadlyImportError("IME: vertex color composed");
  389. else
  390. return pVertexColorArray[pIdx]->Color;
  391. } else if (ne_volume_color != nullptr) // check for volume color
  392. {
  393. if (ne_volume_color->Composed)
  394. throw DeadlyImportError("IME: volume color composed");
  395. else
  396. return ne_volume_color->Color;
  397. } else if (pObjectColor != nullptr) // check for object color
  398. {
  399. if (pObjectColor->Composed)
  400. throw DeadlyImportError("IME: object color composed");
  401. else
  402. return pObjectColor->Color;
  403. } else if (cur_mat != nullptr) // check for material
  404. {
  405. return cur_mat->GetColor(pVertexCoordinateArray.at(pIdx).x, pVertexCoordinateArray.at(pIdx).y, pVertexCoordinateArray.at(pIdx).z);
  406. } else // set default color.
  407. {
  408. return { 0, 0, 0, 0 };
  409. } // if((vi < pVertexColorArray.size()) && (pVertexColorArray[vi] != nullptr)) else
  410. }; // auto Vertex_CalculateColor = [&](const size_t pIdx) -> aiColor4D
  411. aiMesh *tmesh = new aiMesh;
  412. tmesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE; // Only triangles is supported by AMF.
  413. //
  414. // set geometry and colors (vertices)
  415. //
  416. // copy faces/triangles
  417. tmesh->mNumFaces = static_cast<unsigned int>(face_list_cur.size());
  418. tmesh->mFaces = new aiFace[tmesh->mNumFaces];
  419. // Create vertices list and optimize indices. Optimisation mean following.In AMF all volumes use one big list of vertices. And one volume
  420. // can use only part of vertices list, for example: vertices list contain few thousands of vertices and volume use vertices 1, 3, 10.
  421. // Do you need all this thousands of garbage? Of course no. So, optimisation step transformate sparse indices set to continuous.
  422. size_t VertexCount_Max = tmesh->mNumFaces * 3; // 3 - triangles.
  423. std::vector<aiVector3D> vert_arr, texcoord_arr;
  424. std::vector<aiColor4D> col_arr;
  425. vert_arr.reserve(VertexCount_Max * 2); // "* 2" - see below TODO.
  426. col_arr.reserve(VertexCount_Max * 2);
  427. { // fill arrays
  428. size_t vert_idx_from, vert_idx_to;
  429. // first iteration.
  430. vert_idx_to = 0;
  431. vert_idx_from = VertexIndex_GetMinimal(face_list_cur, nullptr);
  432. vert_arr.push_back(pVertexCoordinateArray.at(vert_idx_from));
  433. col_arr.push_back(Vertex_CalculateColor(vert_idx_from));
  434. if (vert_idx_from != vert_idx_to) VertexIndex_Replace(face_list_cur, vert_idx_from, vert_idx_to);
  435. // rest iterations
  436. do {
  437. vert_idx_from = VertexIndex_GetMinimal(face_list_cur, &vert_idx_to);
  438. if (vert_idx_from == vert_idx_to) break; // all indices are transferred,
  439. vert_arr.push_back(pVertexCoordinateArray.at(vert_idx_from));
  440. col_arr.push_back(Vertex_CalculateColor(vert_idx_from));
  441. vert_idx_to++;
  442. if (vert_idx_from != vert_idx_to) VertexIndex_Replace(face_list_cur, vert_idx_from, vert_idx_to);
  443. } while (true);
  444. } // fill arrays. END.
  445. //
  446. // check if triangle colors are used and create additional faces if needed.
  447. //
  448. for (const SComplexFace &face_cur : face_list_cur) {
  449. if (face_cur.Color != nullptr) {
  450. aiColor4D face_color;
  451. size_t vert_idx_new = vert_arr.size();
  452. if (face_cur.Color->Composed)
  453. throw DeadlyImportError("IME: face color composed");
  454. else
  455. face_color = face_cur.Color->Color;
  456. for (size_t idx_ind = 0; idx_ind < face_cur.Face.mNumIndices; idx_ind++) {
  457. vert_arr.push_back(vert_arr.at(face_cur.Face.mIndices[idx_ind]));
  458. col_arr.push_back(face_color);
  459. face_cur.Face.mIndices[idx_ind] = static_cast<unsigned int>(vert_idx_new++);
  460. }
  461. } // if(face_cur.Color != nullptr)
  462. } // for(const SComplexFace& face_cur: face_list_cur)
  463. //
  464. // if texture is used then copy texture coordinates too.
  465. //
  466. if (face_list_cur.front().TexMap != nullptr) {
  467. size_t idx_vert_new = vert_arr.size();
  468. ///TODO: clean unused vertices. "* 2": in certain cases - mesh full of triangle colors - vert_arr will contain duplicated vertices for
  469. /// colored triangles and initial vertices (for colored vertices) which in real became unused. This part need more thinking about
  470. /// optimisation.
  471. bool *idx_vert_used;
  472. idx_vert_used = new bool[VertexCount_Max * 2];
  473. for (size_t i = 0, i_e = VertexCount_Max * 2; i < i_e; i++)
  474. idx_vert_used[i] = false;
  475. // This ID's will be used when set materials ID in scene.
  476. tmesh->mMaterialIndex = static_cast<unsigned int>(PostprocessHelper_GetTextureID_Or_Create(face_list_cur.front().TexMap->TextureID_R,
  477. face_list_cur.front().TexMap->TextureID_G,
  478. face_list_cur.front().TexMap->TextureID_B,
  479. face_list_cur.front().TexMap->TextureID_A));
  480. texcoord_arr.resize(VertexCount_Max * 2);
  481. for (const SComplexFace &face_cur : face_list_cur) {
  482. for (size_t idx_ind = 0; idx_ind < face_cur.Face.mNumIndices; idx_ind++) {
  483. const size_t idx_vert = face_cur.Face.mIndices[idx_ind];
  484. if (!idx_vert_used[idx_vert]) {
  485. texcoord_arr.at(idx_vert) = face_cur.TexMap->TextureCoordinate[idx_ind];
  486. idx_vert_used[idx_vert] = true;
  487. } else if (texcoord_arr.at(idx_vert) != face_cur.TexMap->TextureCoordinate[idx_ind]) {
  488. // in that case one vertex is shared with many texture coordinates. We need to duplicate vertex with another texture
  489. // coordinates.
  490. vert_arr.push_back(vert_arr.at(idx_vert));
  491. col_arr.push_back(col_arr.at(idx_vert));
  492. texcoord_arr.at(idx_vert_new) = face_cur.TexMap->TextureCoordinate[idx_ind];
  493. face_cur.Face.mIndices[idx_ind] = static_cast<unsigned int>(idx_vert_new++);
  494. }
  495. } // for(size_t idx_ind = 0; idx_ind < face_cur.Face.mNumIndices; idx_ind++)
  496. } // for(const SComplexFace& face_cur: face_list_cur)
  497. delete[] idx_vert_used;
  498. // shrink array
  499. texcoord_arr.resize(idx_vert_new);
  500. } // if(face_list_cur.front().TexMap != nullptr)
  501. //
  502. // copy collected data to mesh
  503. //
  504. tmesh->mNumVertices = static_cast<unsigned int>(vert_arr.size());
  505. tmesh->mVertices = new aiVector3D[tmesh->mNumVertices];
  506. tmesh->mColors[0] = new aiColor4D[tmesh->mNumVertices];
  507. memcpy(tmesh->mVertices, vert_arr.data(), tmesh->mNumVertices * sizeof(aiVector3D));
  508. memcpy(tmesh->mColors[0], col_arr.data(), tmesh->mNumVertices * sizeof(aiColor4D));
  509. if (texcoord_arr.size() > 0) {
  510. tmesh->mTextureCoords[0] = new aiVector3D[tmesh->mNumVertices];
  511. memcpy(tmesh->mTextureCoords[0], texcoord_arr.data(), tmesh->mNumVertices * sizeof(aiVector3D));
  512. tmesh->mNumUVComponents[0] = 2; // U and V stored in "x", "y" of aiVector3D.
  513. }
  514. size_t idx_face = 0;
  515. for (const SComplexFace &face_cur : face_list_cur)
  516. tmesh->mFaces[idx_face++] = face_cur.Face;
  517. // store new aiMesh
  518. mesh_idx.push_back(static_cast<unsigned int>(pMeshList.size()));
  519. pMeshList.push_back(tmesh);
  520. } // for(const std::list<SComplexFace>& face_list_cur: complex_faces_toplist)
  521. } // if(ne_child->Type == CAMFImporter_NodeElement::ENET_Volume)
  522. } // for(const CAMFImporter_NodeElement* ne_child: pNodeElement.Child)
  523. // if meshes was created then assign new indices with current aiNode
  524. if (!mesh_idx.empty()) {
  525. std::list<unsigned int>::const_iterator mit = mesh_idx.begin();
  526. pSceneNode.mNumMeshes = static_cast<unsigned int>(mesh_idx.size());
  527. pSceneNode.mMeshes = new unsigned int[pSceneNode.mNumMeshes];
  528. for (size_t i = 0; i < pSceneNode.mNumMeshes; i++)
  529. pSceneNode.mMeshes[i] = *mit++;
  530. } // if(mesh_idx.size() > 0)
  531. }
  532. void AMFImporter::Postprocess_BuildMaterial(const CAMFImporter_NodeElement_Material &pMaterial) {
  533. SPP_Material new_mat;
  534. new_mat.ID = pMaterial.ID;
  535. for (const CAMFImporter_NodeElement *mat_child : pMaterial.Child) {
  536. if (mat_child->Type == CAMFImporter_NodeElement::ENET_Color) {
  537. new_mat.Color = (CAMFImporter_NodeElement_Color *)mat_child;
  538. } else if (mat_child->Type == CAMFImporter_NodeElement::ENET_Metadata) {
  539. new_mat.Metadata.push_back((CAMFImporter_NodeElement_Metadata *)mat_child);
  540. }
  541. } // for(const CAMFImporter_NodeElement* mat_child; pMaterial.Child)
  542. // place converted material to special list
  543. mMaterial_Converted.push_back(new_mat);
  544. }
  545. void AMFImporter::Postprocess_BuildConstellation(CAMFImporter_NodeElement_Constellation &pConstellation, std::list<aiNode *> &pNodeList) const {
  546. aiNode *con_node;
  547. std::list<aiNode *> ch_node;
  548. // We will build next hierarchy:
  549. // aiNode as parent (<constellation>) for set of nodes as a children
  550. // |- aiNode for transformation (<instance> -> <delta...>, <r...>) - aiNode for pointing to object ("objectid")
  551. // ...
  552. // \_ aiNode for transformation (<instance> -> <delta...>, <r...>) - aiNode for pointing to object ("objectid")
  553. con_node = new aiNode;
  554. con_node->mName = pConstellation.ID;
  555. // Walk through children and search for instances of another objects, constellations.
  556. for (const CAMFImporter_NodeElement *ne : pConstellation.Child) {
  557. aiMatrix4x4 tmat;
  558. aiNode *t_node;
  559. aiNode *found_node;
  560. if (ne->Type == CAMFImporter_NodeElement::ENET_Metadata) continue;
  561. if (ne->Type != CAMFImporter_NodeElement::ENET_Instance) throw DeadlyImportError("Only <instance> nodes can be in <constellation>.");
  562. // create alias for conveniance
  563. CAMFImporter_NodeElement_Instance &als = *((CAMFImporter_NodeElement_Instance *)ne);
  564. // find referenced object
  565. if (!Find_ConvertedNode(als.ObjectID, pNodeList, &found_node)) Throw_ID_NotFound(als.ObjectID);
  566. // create node for applying transformation
  567. t_node = new aiNode;
  568. t_node->mParent = con_node;
  569. // apply transformation
  570. aiMatrix4x4::Translation(als.Delta, tmat), t_node->mTransformation *= tmat;
  571. aiMatrix4x4::RotationX(als.Rotation.x, tmat), t_node->mTransformation *= tmat;
  572. aiMatrix4x4::RotationY(als.Rotation.y, tmat), t_node->mTransformation *= tmat;
  573. aiMatrix4x4::RotationZ(als.Rotation.z, tmat), t_node->mTransformation *= tmat;
  574. // create array for one child node
  575. t_node->mNumChildren = 1;
  576. t_node->mChildren = new aiNode *[t_node->mNumChildren];
  577. SceneCombiner::Copy(&t_node->mChildren[0], found_node);
  578. t_node->mChildren[0]->mParent = t_node;
  579. ch_node.push_back(t_node);
  580. } // for(const CAMFImporter_NodeElement* ne: pConstellation.Child)
  581. // copy found aiNode's as children
  582. if (ch_node.empty()) throw DeadlyImportError("<constellation> must have at least one <instance>.");
  583. size_t ch_idx = 0;
  584. con_node->mNumChildren = static_cast<unsigned int>(ch_node.size());
  585. con_node->mChildren = new aiNode *[con_node->mNumChildren];
  586. for (aiNode *node : ch_node)
  587. con_node->mChildren[ch_idx++] = node;
  588. // and place "root" of <constellation> node to node list
  589. pNodeList.push_back(con_node);
  590. }
  591. void AMFImporter::Postprocess_BuildScene(aiScene *pScene) {
  592. std::list<aiNode *> node_list;
  593. std::list<aiMesh *> mesh_list;
  594. std::list<CAMFImporter_NodeElement_Metadata *> meta_list;
  595. //
  596. // Because for AMF "material" is just complex colors mixing so aiMaterial will not be used.
  597. // For building aiScene we are must to do few steps:
  598. // at first creating root node for aiScene.
  599. pScene->mRootNode = new aiNode;
  600. pScene->mRootNode->mParent = nullptr;
  601. pScene->mFlags |= AI_SCENE_FLAGS_ALLOW_SHARED;
  602. // search for root(<amf>) element
  603. CAMFImporter_NodeElement *root_el = nullptr;
  604. for (CAMFImporter_NodeElement *ne : mNodeElement_List) {
  605. if (ne->Type != CAMFImporter_NodeElement::ENET_Root) continue;
  606. root_el = ne;
  607. break;
  608. } // for(const CAMFImporter_NodeElement* ne: mNodeElement_List)
  609. // Check if root element are found.
  610. if (root_el == nullptr) throw DeadlyImportError("Root(<amf>) element not found.");
  611. // 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>,
  612. // <constellation> and <metadata>. But at first we must read <material> and <texture> because they will be used in <object>. <metadata> can be read
  613. // at any moment.
  614. //
  615. // 1. <material>
  616. // 2. <texture> will be converted later when processing triangles list. \sa Postprocess_BuildMeshSet
  617. for (const CAMFImporter_NodeElement *root_child : root_el->Child) {
  618. if (root_child->Type == CAMFImporter_NodeElement::ENET_Material) Postprocess_BuildMaterial(*((CAMFImporter_NodeElement_Material *)root_child));
  619. }
  620. // After "appearance" nodes we must read <object> because it will be used in <constellation> -> <instance>.
  621. //
  622. // 3. <object>
  623. for (const CAMFImporter_NodeElement *root_child : root_el->Child) {
  624. if (root_child->Type == CAMFImporter_NodeElement::ENET_Object) {
  625. aiNode *tnode = nullptr;
  626. // for <object> mesh and node must be built: object ID assigned to aiNode name and will be used in future for <instance>
  627. Postprocess_BuildNodeAndObject(*((CAMFImporter_NodeElement_Object *)root_child), mesh_list, &tnode);
  628. if (tnode != nullptr) node_list.push_back(tnode);
  629. }
  630. } // for(const CAMFImporter_NodeElement* root_child: root_el->Child)
  631. // And finally read rest of nodes.
  632. //
  633. for (const CAMFImporter_NodeElement *root_child : root_el->Child) {
  634. // 4. <constellation>
  635. if (root_child->Type == CAMFImporter_NodeElement::ENET_Constellation) {
  636. // <object> and <constellation> at top of self abstraction use aiNode. So we can use only aiNode list for creating new aiNode's.
  637. Postprocess_BuildConstellation(*((CAMFImporter_NodeElement_Constellation *)root_child), node_list);
  638. }
  639. // 5, <metadata>
  640. if (root_child->Type == CAMFImporter_NodeElement::ENET_Metadata) meta_list.push_back((CAMFImporter_NodeElement_Metadata *)root_child);
  641. } // for(const CAMFImporter_NodeElement* root_child: root_el->Child)
  642. // at now we can add collected metadata to root node
  643. Postprocess_AddMetadata(meta_list, *pScene->mRootNode);
  644. //
  645. // Check constellation children
  646. //
  647. // As said in specification:
  648. // "When multiple objects and constellations are defined in a single file, only the top level objects and constellations are available for printing."
  649. // What that means? For example: if some object is used in constellation then you must show only constellation but not original object.
  650. // And at this step we are checking that relations.
  651. nl_clean_loop:
  652. if (node_list.size() > 1) {
  653. // walk through all nodes
  654. for (std::list<aiNode *>::iterator nl_it = node_list.begin(); nl_it != node_list.end(); ++nl_it) {
  655. // and try to find them in another top nodes.
  656. std::list<aiNode *>::const_iterator next_it = nl_it;
  657. ++next_it;
  658. for (; next_it != node_list.end(); ++next_it) {
  659. if ((*next_it)->FindNode((*nl_it)->mName) != nullptr) {
  660. // if current top node(nl_it) found in another top node then erase it from node_list and restart search loop.
  661. node_list.erase(nl_it);
  662. goto nl_clean_loop;
  663. }
  664. } // for(; next_it != node_list.end(); next_it++)
  665. } // for(std::list<aiNode*>::const_iterator nl_it = node_list.begin(); nl_it != node_list.end(); nl_it++)
  666. }
  667. //
  668. // move created objects to aiScene
  669. //
  670. //
  671. // Nodes
  672. if (!node_list.empty()) {
  673. std::list<aiNode *>::const_iterator nl_it = node_list.begin();
  674. pScene->mRootNode->mNumChildren = static_cast<unsigned int>(node_list.size());
  675. pScene->mRootNode->mChildren = new aiNode *[pScene->mRootNode->mNumChildren];
  676. for (size_t i = 0; i < pScene->mRootNode->mNumChildren; i++) {
  677. // Objects and constellation that must be showed placed at top of hierarchy in <amf> node. So all aiNode's in node_list must have
  678. // mRootNode only as parent.
  679. (*nl_it)->mParent = pScene->mRootNode;
  680. pScene->mRootNode->mChildren[i] = *nl_it++;
  681. }
  682. } // if(node_list.size() > 0)
  683. //
  684. // Meshes
  685. if (!mesh_list.empty()) {
  686. std::list<aiMesh *>::const_iterator ml_it = mesh_list.begin();
  687. pScene->mNumMeshes = static_cast<unsigned int>(mesh_list.size());
  688. pScene->mMeshes = new aiMesh *[pScene->mNumMeshes];
  689. for (size_t i = 0; i < pScene->mNumMeshes; i++)
  690. pScene->mMeshes[i] = *ml_it++;
  691. } // if(mesh_list.size() > 0)
  692. //
  693. // Textures
  694. pScene->mNumTextures = static_cast<unsigned int>(mTexture_Converted.size());
  695. if (pScene->mNumTextures > 0) {
  696. size_t idx;
  697. idx = 0;
  698. pScene->mTextures = new aiTexture *[pScene->mNumTextures];
  699. for (const SPP_Texture &tex_convd : mTexture_Converted) {
  700. pScene->mTextures[idx] = new aiTexture;
  701. pScene->mTextures[idx]->mWidth = static_cast<unsigned int>(tex_convd.Width);
  702. pScene->mTextures[idx]->mHeight = static_cast<unsigned int>(tex_convd.Height);
  703. pScene->mTextures[idx]->pcData = (aiTexel *)tex_convd.Data;
  704. // texture format description.
  705. strcpy(pScene->mTextures[idx]->achFormatHint, tex_convd.FormatHint);
  706. idx++;
  707. } // for(const SPP_Texture& tex_convd: mTexture_Converted)
  708. // Create materials for embedded textures.
  709. idx = 0;
  710. pScene->mNumMaterials = static_cast<unsigned int>(mTexture_Converted.size());
  711. pScene->mMaterials = new aiMaterial *[pScene->mNumMaterials];
  712. for (const SPP_Texture &tex_convd : mTexture_Converted) {
  713. const aiString texture_id(AI_EMBEDDED_TEXNAME_PREFIX + to_string(idx));
  714. const int mode = aiTextureOp_Multiply;
  715. const int repeat = tex_convd.Tiled ? 1 : 0;
  716. pScene->mMaterials[idx] = new aiMaterial;
  717. pScene->mMaterials[idx]->AddProperty(&texture_id, AI_MATKEY_TEXTURE_DIFFUSE(0));
  718. pScene->mMaterials[idx]->AddProperty(&mode, 1, AI_MATKEY_TEXOP_DIFFUSE(0));
  719. pScene->mMaterials[idx]->AddProperty(&repeat, 1, AI_MATKEY_MAPPINGMODE_U_DIFFUSE(0));
  720. pScene->mMaterials[idx]->AddProperty(&repeat, 1, AI_MATKEY_MAPPINGMODE_V_DIFFUSE(0));
  721. idx++;
  722. }
  723. } // if(pScene->mNumTextures > 0)
  724. } // END: after that walk through children of root and collect data
  725. } // namespace Assimp
  726. #endif // !ASSIMP_BUILD_NO_AMF_IMPORTER