ExporterMesh.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. // Copyright (C) 2009-2020, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include "Exporter.h"
  6. #include <anki/resource/MeshLoader.h>
  7. #include <anki/Collision.h>
  8. #include <anki/Math.h>
  9. #include <cmath>
  10. #include <cfloat>
  11. using namespace anki;
  12. void Exporter::exportMesh(const aiMesh& mesh, const aiMatrix4x4* transform, unsigned vertCountPerFace) const
  13. {
  14. std::string name = mesh.mName.C_Str();
  15. LOGI("Exporting mesh %s", name.c_str());
  16. const bool hasBoneWeights = mesh.mNumBones > 0;
  17. MeshBinaryFile::Header header;
  18. memset(&header, 0, sizeof(header));
  19. // Checks
  20. if(mesh.mNumFaces == 0)
  21. {
  22. ERROR("Incorrect face number");
  23. }
  24. if(mesh.mVertices == 0)
  25. {
  26. ERROR("Incorrect vertex count number");
  27. }
  28. if(!mesh.HasPositions())
  29. {
  30. ERROR("Missing positions");
  31. }
  32. if(!mesh.HasNormals())
  33. {
  34. ERROR("Missing normals");
  35. }
  36. if(!mesh.HasTangentsAndBitangents())
  37. {
  38. ERROR("Missing tangents");
  39. }
  40. if(!mesh.HasTextureCoords(0))
  41. {
  42. ERROR("Missing UVs");
  43. }
  44. //
  45. // Gather the attributes
  46. //
  47. struct WeightVertex
  48. {
  49. uint16_t m_boneIndices[4] = {0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF};
  50. uint8_t m_weights[4] = {0, 0, 0, 0};
  51. };
  52. std::vector<WeightVertex> bweights;
  53. std::vector<float> positions;
  54. struct NTVertex
  55. {
  56. float m_n[3];
  57. float m_t[4];
  58. float m_uv[2];
  59. };
  60. std::vector<NTVertex> ntVerts;
  61. float maxPositionDistance = 0.0; // Distance of positions from zero
  62. float maxUvDistance = -FLT_MAX, minUvDistance = FLT_MAX;
  63. Vec3 aabbMin(MAX_F32), aabbMax(MIN_F32);
  64. {
  65. const aiMatrix3x3 normalMat = (transform) ? aiMatrix3x3(*transform) : aiMatrix3x3();
  66. const unsigned vertCount = mesh.mNumVertices;
  67. positions.resize(vertCount * 3);
  68. ntVerts.resize(vertCount);
  69. for(unsigned i = 0; i < vertCount; i++)
  70. {
  71. aiVector3D pos = mesh.mVertices[i];
  72. aiVector3D n = mesh.mNormals[i];
  73. aiVector3D t = mesh.mTangents[i];
  74. aiVector3D b = mesh.mBitangents[i];
  75. const aiVector3D& uv = mesh.mTextureCoords[0][i];
  76. if(transform)
  77. {
  78. pos = (*transform) * pos;
  79. n = normalMat * n;
  80. t = normalMat * t;
  81. b = normalMat * b;
  82. }
  83. if(m_flipyz)
  84. {
  85. static const aiMatrix4x4 toLefthanded(1, 0, 0, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1);
  86. pos = toLefthanded * pos;
  87. n = toLefthanded * n;
  88. t = toLefthanded * t;
  89. b = toLefthanded * b;
  90. }
  91. positions[i * 3 + 0] = pos.x;
  92. positions[i * 3 + 1] = pos.y;
  93. positions[i * 3 + 2] = pos.z;
  94. for(int d = 0; d < 3; ++d)
  95. {
  96. maxPositionDistance = std::max<float>(maxPositionDistance, fabs(pos[d]));
  97. aabbMin[d] = std::min(aabbMin[d], pos[d]);
  98. aabbMax[d] = std::max(aabbMax[d], pos[d]);
  99. }
  100. ntVerts[i].m_n[0] = n.x;
  101. ntVerts[i].m_n[1] = n.y;
  102. ntVerts[i].m_n[2] = n.z;
  103. ntVerts[i].m_t[0] = t.x;
  104. ntVerts[i].m_t[1] = t.y;
  105. ntVerts[i].m_t[2] = t.z;
  106. ntVerts[i].m_t[3] = ((n ^ t) * b < 0.0) ? 1.0 : -1.0;
  107. ntVerts[i].m_uv[0] = uv.x;
  108. ntVerts[i].m_uv[1] = uv.y;
  109. maxUvDistance = std::max(maxUvDistance, std::max(uv.x, uv.y));
  110. minUvDistance = std::min(minUvDistance, std::min(uv.x, uv.y));
  111. }
  112. if(hasBoneWeights)
  113. {
  114. bweights.resize(vertCount);
  115. for(unsigned i = 0; i < mesh.mNumBones; ++i)
  116. {
  117. const aiBone& bone = *mesh.mBones[i];
  118. for(unsigned j = 0; j < bone.mNumWeights; ++j)
  119. {
  120. const aiVertexWeight& aiWeight = bone.mWeights[j];
  121. assert(aiWeight.mVertexId < bweights.size());
  122. WeightVertex& vert = bweights[aiWeight.mVertexId];
  123. unsigned idx;
  124. if(vert.m_boneIndices[0] == 0xFFFF)
  125. {
  126. idx = 0;
  127. }
  128. else if(vert.m_boneIndices[1] == 0xFFFF)
  129. {
  130. idx = 1;
  131. }
  132. else if(vert.m_boneIndices[2] == 0xFFFF)
  133. {
  134. idx = 2;
  135. }
  136. else if(vert.m_boneIndices[3] == 0xFFFF)
  137. {
  138. idx = 3;
  139. }
  140. else
  141. {
  142. ERROR("Vertex has more than 4 bone weights");
  143. }
  144. vert.m_boneIndices[idx] = uint16_t(i);
  145. vert.m_weights[idx] = uint8_t(aiWeight.mWeight * 0xFF);
  146. }
  147. }
  148. }
  149. // Bump aabbMax a bit
  150. aabbMax += EPSILON * 10.0f;
  151. }
  152. // Chose the formats of the attributes
  153. {
  154. // Positions
  155. auto& posa = header.m_vertexAttributes[VertexAttributeLocation::POSITION];
  156. posa.m_bufferBinding = 0;
  157. posa.m_format = (maxPositionDistance < 2.0) ? Format::R16G16B16A16_SFLOAT : Format::R32G32B32_SFLOAT;
  158. posa.m_relativeOffset = 0;
  159. posa.m_scale = 1.0;
  160. // Normals
  161. auto& na = header.m_vertexAttributes[VertexAttributeLocation::NORMAL];
  162. na.m_bufferBinding = 1;
  163. na.m_format = Format::A2B10G10R10_SNORM_PACK32;
  164. na.m_relativeOffset = 0;
  165. na.m_scale = 1.0;
  166. // Tangents
  167. auto& ta = header.m_vertexAttributes[VertexAttributeLocation::TANGENT];
  168. ta.m_bufferBinding = 1;
  169. ta.m_format = Format::A2B10G10R10_SNORM_PACK32;
  170. ta.m_relativeOffset = sizeof(uint32_t);
  171. ta.m_scale = 1.0;
  172. // UVs
  173. auto& uva = header.m_vertexAttributes[VertexAttributeLocation::UV];
  174. uva.m_bufferBinding = 1;
  175. if(minUvDistance >= 0.0 && maxUvDistance <= 1.0)
  176. {
  177. uva.m_format = Format::R16G16_UNORM;
  178. }
  179. else
  180. {
  181. uva.m_format = Format::R16G16_SFLOAT;
  182. }
  183. uva.m_relativeOffset = sizeof(uint32_t) * 2;
  184. uva.m_scale = 1.0;
  185. // Bone weight
  186. if(hasBoneWeights)
  187. {
  188. auto& bidxa = header.m_vertexAttributes[VertexAttributeLocation::BONE_INDICES];
  189. bidxa.m_bufferBinding = 2;
  190. bidxa.m_format = Format::R16G16B16A16_UINT;
  191. bidxa.m_relativeOffset = 0;
  192. bidxa.m_scale = 1.0;
  193. auto& wa = header.m_vertexAttributes[VertexAttributeLocation::BONE_WEIGHTS];
  194. wa.m_bufferBinding = 2;
  195. wa.m_format = Format::R8G8B8A8_UNORM;
  196. wa.m_relativeOffset = sizeof(uint16_t) * 4;
  197. wa.m_scale = 1.0;
  198. }
  199. }
  200. // Arange the attributes into vert buffers
  201. {
  202. header.m_vertexBufferCount = 2;
  203. // First buff has positions
  204. const auto& posa = header.m_vertexAttributes[VertexAttributeLocation::POSITION];
  205. if(posa.m_format == Format::R32G32B32_SFLOAT)
  206. {
  207. header.m_vertexBuffers[0].m_vertexStride = sizeof(float) * 3;
  208. }
  209. else if(posa.m_format == Format::R16G16B16A16_SFLOAT)
  210. {
  211. header.m_vertexBuffers[0].m_vertexStride = sizeof(uint16_t) * 4;
  212. }
  213. else
  214. {
  215. assert(0);
  216. }
  217. // 2nd buff has normal + tangent + texcoords
  218. header.m_vertexBuffers[1].m_vertexStride = sizeof(uint32_t) * 2 + sizeof(uint16_t) * 2;
  219. // 3rd has bone weights
  220. if(hasBoneWeights)
  221. {
  222. header.m_vertexBuffers[2].m_vertexStride = sizeof(WeightVertex);
  223. ++header.m_vertexBufferCount;
  224. }
  225. }
  226. // Find if it's a convex shape
  227. Bool convex = true;
  228. for(unsigned i = 0; i < mesh.mNumFaces && vertCountPerFace == 3; i++)
  229. {
  230. const aiFace& face = mesh.mFaces[i];
  231. Vec3 triangle[3];
  232. for(unsigned j = 0; j < 3; j++)
  233. {
  234. unsigned idx = face.mIndices[j];
  235. triangle[j].x() = positions[idx * 3 + 0];
  236. triangle[j].y() = positions[idx * 3 + 1];
  237. triangle[j].z() = positions[idx * 3 + 2];
  238. }
  239. // Check that all positions are behind the plane
  240. Plane plane(triangle[0].xyz0(), triangle[1].xyz0(), triangle[2].xyz0());
  241. for(unsigned j = 0; j < positions.size(); j += 3)
  242. {
  243. Vec3 pos;
  244. pos.x() = positions[j + 0];
  245. pos.y() = positions[j + 1];
  246. pos.z() = positions[j + 2];
  247. F32 test = testPlane(plane, pos.xyz0());
  248. if(test > EPSILON)
  249. {
  250. convex = false;
  251. break;
  252. }
  253. }
  254. if(convex == false)
  255. {
  256. break;
  257. }
  258. }
  259. // Write some other header stuff
  260. {
  261. memcpy(&header.m_magic[0], MeshBinaryFile::MAGIC, 8);
  262. header.m_flags = (vertCountPerFace == 4) ? MeshBinaryFile::Flag::QUAD : MeshBinaryFile::Flag::NONE;
  263. if(convex)
  264. {
  265. header.m_flags |= MeshBinaryFile::Flag::CONVEX;
  266. }
  267. header.m_indexType = IndexType::U16;
  268. header.m_totalIndexCount = mesh.mNumFaces * vertCountPerFace;
  269. header.m_totalVertexCount = mesh.mNumVertices;
  270. header.m_subMeshCount = 1;
  271. header.m_aabbMin = aabbMin;
  272. header.m_aabbMax = aabbMax;
  273. }
  274. // Open file
  275. std::fstream file;
  276. file.open(m_outputDirectory + name + ".ankimesh", std::ios::out | std::ios::binary);
  277. // Write header
  278. file.write(reinterpret_cast<char*>(&header), sizeof(header));
  279. // Write sub meshes
  280. {
  281. MeshBinaryFile::SubMesh smesh;
  282. smesh.m_firstIndex = 0;
  283. smesh.m_indexCount = header.m_totalIndexCount;
  284. smesh.m_aabbMin = aabbMin;
  285. smesh.m_aabbMax = aabbMax;
  286. file.write(reinterpret_cast<char*>(&smesh), sizeof(smesh));
  287. }
  288. // Write indices
  289. for(unsigned i = 0; i < mesh.mNumFaces; i++)
  290. {
  291. const aiFace& face = mesh.mFaces[i];
  292. if(face.mNumIndices != vertCountPerFace)
  293. {
  294. ERROR("For some reason assimp returned wrong number of verts for a face (face.mNumIndices=%d). Probably"
  295. "degenerates in input file",
  296. face.mNumIndices);
  297. }
  298. for(unsigned j = 0; j < vertCountPerFace; j++)
  299. {
  300. uint32_t index32 = face.mIndices[j];
  301. if(index32 > 0xFFFF)
  302. {
  303. ERROR("Index too big");
  304. }
  305. uint16_t index = uint16_t(index32);
  306. file.write(reinterpret_cast<char*>(&index), sizeof(index));
  307. }
  308. }
  309. // Write first vert buffer
  310. {
  311. const auto& posa = header.m_vertexAttributes[VertexAttributeLocation::POSITION];
  312. if(posa.m_format == Format::R32G32B32_SFLOAT)
  313. {
  314. file.write(reinterpret_cast<char*>(&positions[0]), positions.size() * sizeof(positions[0]));
  315. }
  316. else if(posa.m_format == Format::R16G16B16A16_SFLOAT)
  317. {
  318. std::vector<uint16_t> pos16;
  319. pos16.resize(mesh.mNumVertices * 4);
  320. const float* p32 = &positions[0];
  321. const float* p32end = p32 + positions.size();
  322. uint16_t* p16 = &pos16[0];
  323. while(p32 != p32end)
  324. {
  325. p16[0] = F16(p32[0]).toU16();
  326. p16[1] = F16(p32[1]).toU16();
  327. p16[2] = F16(p32[2]).toU16();
  328. p16[3] = F16(0.0f).toU16();
  329. p32 += 3;
  330. p16 += 4;
  331. }
  332. file.write(reinterpret_cast<char*>(&pos16[0]), pos16.size() * sizeof(pos16[0]));
  333. }
  334. else
  335. {
  336. assert(0);
  337. }
  338. }
  339. // Write 2nd vert buffer
  340. {
  341. struct Vert
  342. {
  343. uint32_t m_n;
  344. uint32_t m_t;
  345. uint16_t m_uv[2];
  346. };
  347. std::vector<Vert> verts;
  348. verts.resize(mesh.mNumVertices);
  349. for(unsigned i = 0; i < mesh.mNumVertices; ++i)
  350. {
  351. const auto& inVert = ntVerts[i];
  352. verts[i].m_n = packColorToR10G10B10A2SNorm(inVert.m_n[0], inVert.m_n[1], inVert.m_n[2], 0.0);
  353. verts[i].m_t = packColorToR10G10B10A2SNorm(inVert.m_t[0], inVert.m_t[1], inVert.m_t[2], inVert.m_t[3]);
  354. const float uv[2] = {inVert.m_uv[0], inVert.m_uv[1]};
  355. const Format uvfmt = header.m_vertexAttributes[VertexAttributeLocation::UV].m_format;
  356. if(uvfmt == Format::R16G16_UNORM)
  357. {
  358. assert(uv[0] <= 1.0 && uv[0] >= 0.0 && uv[1] <= 1.0 && uv[1] >= 0.0);
  359. verts[i].m_uv[0] = uint16_t(uv[0] * 0xFFFF);
  360. verts[i].m_uv[1] = uint16_t(uv[1] * 0xFFFF);
  361. }
  362. else if(uvfmt == Format::R16G16_SFLOAT)
  363. {
  364. verts[i].m_uv[0] = F16(uv[0]).toU16();
  365. verts[i].m_uv[1] = F16(uv[1]).toU16();
  366. }
  367. else
  368. {
  369. assert(0);
  370. }
  371. }
  372. file.write(reinterpret_cast<char*>(&verts[0]), verts.size() * sizeof(verts[0]));
  373. }
  374. // Write 3rd vert buffer
  375. if(hasBoneWeights)
  376. {
  377. file.write(reinterpret_cast<char*>(&bweights[0]), bweights.size() * sizeof(bweights[0]));
  378. }
  379. }