AMFImporter_Postprocess.cpp 35 KB

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