AMFImporter_Postprocess.cpp 33 KB

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