FBXMeshGeometry.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2012, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /** @file FBXMeshGeometry.cpp
  34. * @brief Assimp::FBX::MeshGeometry implementation
  35. */
  36. #include "AssimpPCH.h"
  37. #ifndef ASSIMP_BUILD_NO_FBX_IMPORTER
  38. #include "FBXParser.h"
  39. #include "FBXDocument.h"
  40. #include "FBXImporter.h"
  41. #include "FBXImportSettings.h"
  42. #include "FBXDocumentUtil.h"
  43. namespace Assimp {
  44. namespace FBX {
  45. using namespace Util;
  46. // ------------------------------------------------------------------------------------------------
  47. MeshGeometry::MeshGeometry(uint64_t id, const Element& element, const std::string& name, const Document& doc)
  48. : Geometry(id, element,name)
  49. {
  50. const Scope* sc = element.Compound();
  51. if (!sc) {
  52. DOMError("failed to read Geometry object (class: Mesh), no data scope found");
  53. }
  54. // must have Mesh elements:
  55. const Element& Vertices = GetRequiredElement(*sc,"Vertices",&element);
  56. const Element& PolygonVertexIndex = GetRequiredElement(*sc,"PolygonVertexIndex",&element);
  57. // optional Mesh elements:
  58. const ElementCollection& Layer = sc->GetCollection("Layer");
  59. const ElementCollection& LayerElementMaterial = sc->GetCollection("LayerElementMaterial");
  60. const ElementCollection& LayerElementUV = sc->GetCollection("LayerElementUV");
  61. const ElementCollection& LayerElementNormal = sc->GetCollection("LayerElementNormal");
  62. std::vector<aiVector3D> tempVerts;
  63. ReadVectorDataArray(tempVerts,Vertices);
  64. if(tempVerts.empty()) {
  65. FBXImporter::LogWarn("encountered mesh with no vertices");
  66. return;
  67. }
  68. std::vector<int> tempFaces;
  69. ReadVectorDataArray(tempFaces,PolygonVertexIndex);
  70. if(tempFaces.empty()) {
  71. FBXImporter::LogWarn("encountered mesh with no faces");
  72. return;
  73. }
  74. vertices.reserve(tempFaces.size());
  75. faces.reserve(tempFaces.size() / 3);
  76. mapping_offsets.resize(tempVerts.size());
  77. mapping_counts.resize(tempVerts.size(),0);
  78. mappings.resize(tempFaces.size());
  79. const size_t vertex_count = tempVerts.size();
  80. // generate output vertices, computing an adjacency table to
  81. // preserve the mapping from fbx indices to *this* indexing.
  82. unsigned int count = 0;
  83. BOOST_FOREACH(int index, tempFaces) {
  84. const int absi = index < 0 ? (-index - 1) : index;
  85. if(static_cast<size_t>(absi) >= vertex_count) {
  86. DOMError("polygon vertex index out of range",&PolygonVertexIndex);
  87. }
  88. vertices.push_back(tempVerts[absi]);
  89. ++count;
  90. ++mapping_counts[absi];
  91. if (index < 0) {
  92. faces.push_back(count);
  93. count = 0;
  94. }
  95. }
  96. unsigned int cursor = 0;
  97. for (size_t i = 0, e = tempVerts.size(); i < e; ++i) {
  98. mapping_offsets[i] = cursor;
  99. cursor += mapping_counts[i];
  100. mapping_counts[i] = 0;
  101. }
  102. cursor = 0;
  103. BOOST_FOREACH(int index, tempFaces) {
  104. const int absi = index < 0 ? (-index - 1) : index;
  105. mappings[mapping_offsets[absi] + mapping_counts[absi]++] = cursor;
  106. }
  107. // if settings.readAllLayers is true:
  108. // * read all layers, try to load as many vertex channels as possible
  109. // if settings.readAllLayers is false:
  110. // * read only the layer with index 0, but warn about any further layers
  111. for (ElementMap::const_iterator it = Layer.first; it != Layer.second; ++it) {
  112. const TokenList& tokens = (*it).second->Tokens();
  113. const char* err;
  114. const int index = ParseTokenAsInt(*tokens[0], err);
  115. if(err) {
  116. DOMError(err,&element);
  117. }
  118. if(doc.Settings().readAllLayers || index == 0) {
  119. const Scope& layer = GetRequiredScope(*(*it).second);
  120. ReadLayer(layer);
  121. }
  122. else {
  123. FBXImporter::LogWarn("ignoring additional geometry layers");
  124. }
  125. }
  126. }
  127. // ------------------------------------------------------------------------------------------------
  128. MeshGeometry::~MeshGeometry()
  129. {
  130. }
  131. // ------------------------------------------------------------------------------------------------
  132. void MeshGeometry::ReadLayer(const Scope& layer)
  133. {
  134. const ElementCollection& LayerElement = layer.GetCollection("LayerElement");
  135. for (ElementMap::const_iterator eit = LayerElement.first; eit != LayerElement.second; ++eit) {
  136. const Scope& elayer = GetRequiredScope(*(*eit).second);
  137. ReadLayerElement(elayer);
  138. }
  139. }
  140. // ------------------------------------------------------------------------------------------------
  141. void MeshGeometry::ReadLayerElement(const Scope& layerElement)
  142. {
  143. const Element& Type = GetRequiredElement(layerElement,"Type");
  144. const Element& TypedIndex = GetRequiredElement(layerElement,"TypedIndex");
  145. const std::string& type = ParseTokenAsString(GetRequiredToken(Type,0));
  146. const int typedIndex = ParseTokenAsInt(GetRequiredToken(TypedIndex,0));
  147. const Scope& top = GetRequiredScope(element);
  148. const ElementCollection candidates = top.GetCollection(type);
  149. for (ElementMap::const_iterator it = candidates.first; it != candidates.second; ++it) {
  150. const int index = ParseTokenAsInt(GetRequiredToken(*(*it).second,0));
  151. if(index == typedIndex) {
  152. ReadVertexData(type,typedIndex,GetRequiredScope(*(*it).second));
  153. return;
  154. }
  155. }
  156. FBXImporter::LogError(Formatter::format("failed to resolve vertex layer element: ")
  157. << type << ", index: " << typedIndex);
  158. }
  159. // ------------------------------------------------------------------------------------------------
  160. void MeshGeometry::ReadVertexData(const std::string& type, int index, const Scope& source)
  161. {
  162. const std::string& MappingInformationType = ParseTokenAsString(GetRequiredToken(
  163. GetRequiredElement(source,"MappingInformationType"),0)
  164. );
  165. const std::string& ReferenceInformationType = ParseTokenAsString(GetRequiredToken(
  166. GetRequiredElement(source,"ReferenceInformationType"),0)
  167. );
  168. if (type == "LayerElementUV") {
  169. if(index >= AI_MAX_NUMBER_OF_TEXTURECOORDS) {
  170. FBXImporter::LogError(Formatter::format("ignoring UV layer, maximum number of UV channels exceeded: ")
  171. << index << " (limit is " << AI_MAX_NUMBER_OF_TEXTURECOORDS << ")" );
  172. return;
  173. }
  174. const Element* Name = source["Name"];
  175. uvNames[index] = "";
  176. if(Name) {
  177. uvNames[index] = ParseTokenAsString(GetRequiredToken(*Name,0));
  178. }
  179. ReadVertexDataUV(uvs[index],source,
  180. MappingInformationType,
  181. ReferenceInformationType
  182. );
  183. }
  184. else if (type == "LayerElementMaterial") {
  185. if (materials.size() > 0) {
  186. FBXImporter::LogError("ignoring additional material layer");
  187. return;
  188. }
  189. ReadVertexDataMaterials(materials,source,
  190. MappingInformationType,
  191. ReferenceInformationType
  192. );
  193. }
  194. else if (type == "LayerElementNormal") {
  195. if (normals.size() > 0) {
  196. FBXImporter::LogError("ignoring additional normal layer");
  197. return;
  198. }
  199. ReadVertexDataNormals(normals,source,
  200. MappingInformationType,
  201. ReferenceInformationType
  202. );
  203. }
  204. else if (type == "LayerElementTangent") {
  205. if (tangents.size() > 0) {
  206. FBXImporter::LogError("ignoring additional tangent layer");
  207. return;
  208. }
  209. ReadVertexDataTangents(tangents,source,
  210. MappingInformationType,
  211. ReferenceInformationType
  212. );
  213. }
  214. else if (type == "LayerElementBinormal") {
  215. if (binormals.size() > 0) {
  216. FBXImporter::LogError("ignoring additional binormal layer");
  217. return;
  218. }
  219. ReadVertexDataBinormals(binormals,source,
  220. MappingInformationType,
  221. ReferenceInformationType
  222. );
  223. }
  224. else if (type == "LayerElementColor") {
  225. if(index >= AI_MAX_NUMBER_OF_COLOR_SETS) {
  226. FBXImporter::LogError(Formatter::format("ignoring vertex color layer, maximum number of color sets exceeded: ")
  227. << index << " (limit is " << AI_MAX_NUMBER_OF_COLOR_SETS << ")" );
  228. return;
  229. }
  230. ReadVertexDataColors(colors[index],source,
  231. MappingInformationType,
  232. ReferenceInformationType
  233. );
  234. }
  235. }
  236. // ------------------------------------------------------------------------------------------------
  237. // Lengthy utility function to read and resolve a FBX vertex data array - that is, the
  238. // output is in polygon vertex order. This logic is used for reading normals, UVs, colors,
  239. // tangents ..
  240. template <typename T>
  241. void ResolveVertexDataArray(std::vector<T>& data_out, const Scope& source,
  242. const std::string& MappingInformationType,
  243. const std::string& ReferenceInformationType,
  244. const char* dataElementName,
  245. const char* indexDataElementName,
  246. size_t vertex_count,
  247. const std::vector<unsigned int>& mapping_counts,
  248. const std::vector<unsigned int>& mapping_offsets,
  249. const std::vector<unsigned int>& mappings)
  250. {
  251. std::vector<T> tempUV;
  252. ReadVectorDataArray(tempUV,GetRequiredElement(source,dataElementName));
  253. // handle permutations of Mapping and Reference type - it would be nice to
  254. // deal with this more elegantly and with less redundancy, but right
  255. // now it seems unavoidable.
  256. if (MappingInformationType == "ByVertice" && ReferenceInformationType == "Direct") {
  257. data_out.resize(vertex_count);
  258. for (size_t i = 0, e = tempUV.size(); i < e; ++i) {
  259. const unsigned int istart = mapping_offsets[i], iend = istart + mapping_counts[i];
  260. for (unsigned int j = istart; j < iend; ++j) {
  261. data_out[mappings[j]] = tempUV[i];
  262. }
  263. }
  264. }
  265. else if (MappingInformationType == "ByVertice" && ReferenceInformationType == "IndexToDirect") {
  266. data_out.resize(vertex_count);
  267. std::vector<int> uvIndices;
  268. ReadVectorDataArray(uvIndices,GetRequiredElement(source,indexDataElementName));
  269. for (size_t i = 0, e = uvIndices.size(); i < e; ++i) {
  270. const unsigned int istart = mapping_offsets[i], iend = istart + mapping_counts[i];
  271. for (unsigned int j = istart; j < iend; ++j) {
  272. if(static_cast<size_t>(uvIndices[i]) >= tempUV.size()) {
  273. DOMError("index out of range",&GetRequiredElement(source,indexDataElementName));
  274. }
  275. data_out[mappings[j]] = tempUV[uvIndices[i]];
  276. }
  277. }
  278. }
  279. else if (MappingInformationType == "ByPolygonVertex" && ReferenceInformationType == "Direct") {
  280. if (tempUV.size() != vertex_count) {
  281. FBXImporter::LogError(Formatter::format("length of input data unexpected for ByPolygon mapping: ")
  282. << tempUV.size() << ", expected " << vertex_count
  283. );
  284. return;
  285. }
  286. data_out.swap(tempUV);
  287. }
  288. else if (MappingInformationType == "ByPolygonVertex" && ReferenceInformationType == "IndexToDirect") {
  289. data_out.resize(vertex_count);
  290. std::vector<int> uvIndices;
  291. ReadVectorDataArray(uvIndices,GetRequiredElement(source,indexDataElementName));
  292. if (uvIndices.size() != vertex_count) {
  293. FBXImporter::LogError("length of input data unexpected for ByPolygonVertex mapping");
  294. return;
  295. }
  296. unsigned int next = 0;
  297. BOOST_FOREACH(int i, uvIndices) {
  298. if(static_cast<size_t>(i) >= tempUV.size()) {
  299. DOMError("index out of range",&GetRequiredElement(source,indexDataElementName));
  300. }
  301. data_out[next++] = tempUV[i];
  302. }
  303. }
  304. else {
  305. FBXImporter::LogError(Formatter::format("ignoring vertex data channel, access type not implemented: ")
  306. << MappingInformationType << "," << ReferenceInformationType);
  307. }
  308. }
  309. // ------------------------------------------------------------------------------------------------
  310. void MeshGeometry::ReadVertexDataNormals(std::vector<aiVector3D>& normals_out, const Scope& source,
  311. const std::string& MappingInformationType,
  312. const std::string& ReferenceInformationType)
  313. {
  314. ResolveVertexDataArray(normals_out,source,MappingInformationType,ReferenceInformationType,
  315. "Normals",
  316. "NormalsIndex",
  317. vertices.size(),
  318. mapping_counts,
  319. mapping_offsets,
  320. mappings);
  321. }
  322. // ------------------------------------------------------------------------------------------------
  323. void MeshGeometry::ReadVertexDataUV(std::vector<aiVector2D>& uv_out, const Scope& source,
  324. const std::string& MappingInformationType,
  325. const std::string& ReferenceInformationType)
  326. {
  327. ResolveVertexDataArray(uv_out,source,MappingInformationType,ReferenceInformationType,
  328. "UV",
  329. "UVIndex",
  330. vertices.size(),
  331. mapping_counts,
  332. mapping_offsets,
  333. mappings);
  334. }
  335. // ------------------------------------------------------------------------------------------------
  336. void MeshGeometry::ReadVertexDataColors(std::vector<aiColor4D>& colors_out, const Scope& source,
  337. const std::string& MappingInformationType,
  338. const std::string& ReferenceInformationType)
  339. {
  340. ResolveVertexDataArray(colors_out,source,MappingInformationType,ReferenceInformationType,
  341. "Colors",
  342. "ColorIndex",
  343. vertices.size(),
  344. mapping_counts,
  345. mapping_offsets,
  346. mappings);
  347. }
  348. // ------------------------------------------------------------------------------------------------
  349. void MeshGeometry::ReadVertexDataTangents(std::vector<aiVector3D>& tangents_out, const Scope& source,
  350. const std::string& MappingInformationType,
  351. const std::string& ReferenceInformationType)
  352. {
  353. ResolveVertexDataArray(tangents_out,source,MappingInformationType,ReferenceInformationType,
  354. "Tangent",
  355. "TangentIndex",
  356. vertices.size(),
  357. mapping_counts,
  358. mapping_offsets,
  359. mappings);
  360. }
  361. // ------------------------------------------------------------------------------------------------
  362. void MeshGeometry::ReadVertexDataBinormals(std::vector<aiVector3D>& binormals_out, const Scope& source,
  363. const std::string& MappingInformationType,
  364. const std::string& ReferenceInformationType)
  365. {
  366. ResolveVertexDataArray(binormals_out,source,MappingInformationType,ReferenceInformationType,
  367. "Binormal",
  368. "BinormalIndex",
  369. vertices.size(),
  370. mapping_counts,
  371. mapping_offsets,
  372. mappings);
  373. }
  374. // ------------------------------------------------------------------------------------------------
  375. void MeshGeometry::ReadVertexDataMaterials(std::vector<unsigned int>& materials_out, const Scope& source,
  376. const std::string& MappingInformationType,
  377. const std::string& ReferenceInformationType)
  378. {
  379. const size_t face_count = faces.size();
  380. ai_assert(face_count);
  381. // materials are handled separately. First of all, they are assigned per-face
  382. // and not per polyvert. Secondly, ReferenceInformationType=IndexToDirect
  383. // has a slightly different meaning for materials.
  384. ReadVectorDataArray(materials_out,GetRequiredElement(source,"Materials"));
  385. if (MappingInformationType == "AllSame") {
  386. // easy - same material for all faces
  387. if (materials_out.empty()) {
  388. FBXImporter::LogError(Formatter::format("expected material index, ignoring"));
  389. return;
  390. }
  391. else if (materials_out.size() > 1) {
  392. FBXImporter::LogWarn(Formatter::format("expected only a single material index, ignoring all except the first one"));
  393. materials_out.clear();
  394. }
  395. materials.assign(vertices.size(),materials_out[0]);
  396. }
  397. else if (MappingInformationType == "ByPolygon" && ReferenceInformationType == "IndexToDirect") {
  398. materials.resize(face_count);
  399. if(materials_out.size() != face_count) {
  400. FBXImporter::LogError(Formatter::format("length of input data unexpected for ByPolygon mapping: ")
  401. << materials_out.size() << ", expected " << face_count
  402. );
  403. return;
  404. }
  405. }
  406. else {
  407. FBXImporter::LogError(Formatter::format("ignoring material assignments, access type not implemented: ")
  408. << MappingInformationType << "," << ReferenceInformationType);
  409. }
  410. }
  411. } // !FBX
  412. } // !Assimp
  413. #endif