AMFImporter_Postprocess.cpp 36 KB

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