geometryc.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419
  1. /*
  2. * Copyright 2011-2021 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include <algorithm>
  6. #include <bx/string.h>
  7. #include <bgfx/bgfx.h>
  8. #include "../../src/vertexlayout.h"
  9. #include <tinystl/allocator.h>
  10. #include <tinystl/string.h>
  11. #include <tinystl/vector.h>
  12. namespace stl = tinystl;
  13. #include <meshoptimizer/src/meshoptimizer.h>
  14. #define CGLTF_IMPLEMENTATION
  15. #include <cgltf/cgltf.h>
  16. #define BGFX_GEOMETRYC_VERSION_MAJOR 1
  17. #define BGFX_GEOMETRYC_VERSION_MINOR 0
  18. #if 0
  19. # define BX_TRACE(_format, ...) \
  20. do { \
  21. bx::printf(BX_FILE_LINE_LITERAL "BGFX " _format "\n", ##__VA_ARGS__); \
  22. } while(0)
  23. # define BX_WARN(_condition, _format, ...) \
  24. do { \
  25. if (!(_condition) ) \
  26. { \
  27. BX_TRACE(BX_FILE_LINE_LITERAL "WARN " _format, ##__VA_ARGS__); \
  28. } \
  29. } while(0)
  30. # define BX_ASSERT(_condition, _format, ...) \
  31. do { \
  32. if (!(_condition) ) \
  33. { \
  34. BX_TRACE(BX_FILE_LINE_LITERAL "CHECK " _format, ##__VA_ARGS__); \
  35. bx::debugBreak(); \
  36. } \
  37. } while(0)
  38. #endif // 0
  39. #include <bx/bx.h>
  40. #include <bx/debug.h>
  41. #include <bx/commandline.h>
  42. #include <bx/timer.h>
  43. #include <bx/hash.h>
  44. #include <bx/uint32_t.h>
  45. #include <bx/math.h>
  46. #include <bx/file.h>
  47. #include "bounds.h"
  48. typedef stl::vector<bx::Vec3> Vec3Array;
  49. struct Index3
  50. {
  51. int32_t m_position;
  52. int32_t m_texcoord;
  53. int32_t m_normal;
  54. int32_t m_vbc; // Barycentric ID. Holds either 0, 1 or 2.
  55. };
  56. struct TriIndices
  57. {
  58. Index3 m_index[3];
  59. };
  60. typedef stl::vector<TriIndices> TriangleArray;
  61. struct Group
  62. {
  63. uint32_t m_startTriangle;
  64. uint32_t m_numTriangles;
  65. stl::string m_name;
  66. stl::string m_material;
  67. };
  68. typedef stl::vector<Group> GroupArray;
  69. struct Primitive
  70. {
  71. uint32_t m_startVertex;
  72. uint32_t m_startIndex;
  73. uint32_t m_numVertices;
  74. uint32_t m_numIndices;
  75. stl::string m_name;
  76. };
  77. typedef stl::vector<Primitive> PrimitiveArray;
  78. struct Axis
  79. {
  80. enum Enum
  81. {
  82. NegativeX,
  83. PositiveX,
  84. NegativeY,
  85. PositiveY,
  86. NegativeZ,
  87. PositiveZ,
  88. };
  89. };
  90. static bx::Vec3 s_axisVectors[6] =
  91. {
  92. bx::Vec3(-1.0f, 0.0f, 0.0f),
  93. bx::Vec3( 1.0f, 0.0f, 0.0f),
  94. bx::Vec3( 0.0f,-1.0f, 0.0f),
  95. bx::Vec3( 0.0f, 1.0f, 0.0f),
  96. bx::Vec3( 0.0f, 0.0f,-1.0f),
  97. bx::Vec3( 0.0f, 0.0f, 1.0f),
  98. };
  99. struct CoordinateSystem
  100. {
  101. bx::Handness::Enum m_handness;
  102. Axis::Enum m_up;
  103. Axis::Enum m_forward;
  104. };
  105. struct CoordinateSystemMapping
  106. {
  107. const char* m_param;
  108. CoordinateSystem m_coordinateSystem;
  109. };
  110. static const CoordinateSystemMapping s_coordinateSystemMappings[] =
  111. {
  112. { "lh-up+y", { bx::Handness::Left, Axis::PositiveY, Axis::PositiveZ } },
  113. { "lh-up+z", { bx::Handness::Left, Axis::PositiveZ, Axis::PositiveY } },
  114. { "rh-up+y", { bx::Handness::Right, Axis::PositiveY, Axis::PositiveZ } },
  115. { "rh-up+z", { bx::Handness::Right, Axis::PositiveZ, Axis::PositiveY } },
  116. };
  117. struct Mesh
  118. {
  119. Vec3Array m_positions;
  120. Vec3Array m_normals;
  121. Vec3Array m_texcoords;
  122. TriangleArray m_triangles;
  123. GroupArray m_groups;
  124. CoordinateSystem m_coordinateSystem;
  125. };
  126. static uint32_t s_obbSteps = 17;
  127. constexpr uint32_t kChunkVertexBuffer = BX_MAKEFOURCC('V', 'B', ' ', 0x1);
  128. constexpr uint32_t kChunkVertexBufferCompressed = BX_MAKEFOURCC('V', 'B', 'C', 0x0);
  129. constexpr uint32_t kChunkIndexBuffer = BX_MAKEFOURCC('I', 'B', ' ', 0x0);
  130. constexpr uint32_t kChunkIndexBufferCompressed = BX_MAKEFOURCC('I', 'B', 'C', 0x1);
  131. constexpr uint32_t kChunkPrimitive = BX_MAKEFOURCC('P', 'R', 'I', 0x0);
  132. void optimizeVertexCache(uint16_t* _indices, uint32_t _numIndices, uint32_t _numVertices)
  133. {
  134. uint16_t* newIndexList = new uint16_t[_numIndices];
  135. meshopt_optimizeVertexCache(newIndexList, _indices, _numIndices, _numVertices);
  136. bx::memCopy(_indices, newIndexList, _numIndices * 2);
  137. delete[] newIndexList;
  138. }
  139. uint32_t optimizeVertexFetch(uint16_t* _indices, uint32_t _numIndices, uint8_t* _vertexData, uint32_t _numVertices, uint16_t _stride)
  140. {
  141. unsigned char* newVertices = (unsigned char*)malloc(_numVertices * _stride );
  142. size_t vertexCount = meshopt_optimizeVertexFetch(newVertices, _indices, _numIndices, _vertexData, _numVertices, _stride);
  143. bx::memCopy(_vertexData, newVertices, _numVertices * _stride);
  144. free(newVertices);
  145. return uint32_t(vertexCount);
  146. }
  147. void writeCompressedIndices(bx::WriterI* _writer, const uint16_t* _indices, uint32_t _numIndices, uint32_t _numVertices)
  148. {
  149. size_t maxSize = meshopt_encodeIndexBufferBound(_numIndices, _numVertices);
  150. unsigned char* compressedIndices = (unsigned char*)malloc(maxSize);
  151. size_t compressedSize = meshopt_encodeIndexBuffer(compressedIndices, maxSize, _indices, _numIndices);
  152. bx::printf("Indices uncompressed: %10d, compressed: %10d, ratio: %0.2f%%\n"
  153. , _numIndices*2
  154. , (uint32_t)compressedSize
  155. , 100.0f - float(compressedSize ) / float(_numIndices*2)*100.0f
  156. );
  157. bx::write(_writer, (uint32_t)compressedSize);
  158. bx::write(_writer, compressedIndices, (uint32_t)compressedSize );
  159. free(compressedIndices);
  160. }
  161. void writeCompressedVertices(bx::WriterI* _writer, const uint8_t* _vertices, uint32_t _numVertices, uint16_t _stride)
  162. {
  163. size_t maxSize = meshopt_encodeVertexBufferBound(_numVertices, _stride);
  164. unsigned char* compressedVertices = (unsigned char*)malloc(maxSize);
  165. size_t compressedSize = meshopt_encodeVertexBuffer(compressedVertices, maxSize, _vertices, _numVertices, _stride);
  166. bx::printf("Vertices uncompressed: %10d, compressed: %10d, ratio: %0.2f%%\n"
  167. , _numVertices * _stride
  168. , (uint32_t)compressedSize
  169. , 100.0f - float(compressedSize) / float(_numVertices * _stride)*100.0f
  170. );
  171. bx::write(_writer, (uint32_t)compressedSize);
  172. bx::write(_writer, compressedVertices, (uint32_t)compressedSize );
  173. free(compressedVertices);
  174. }
  175. void calcTangents(void* _vertices, uint16_t _numVertices, bgfx::VertexLayout _layout, const uint16_t* _indices, uint32_t _numIndices)
  176. {
  177. struct PosTexcoord
  178. {
  179. float m_x;
  180. float m_y;
  181. float m_z;
  182. float m_pad0;
  183. float m_u;
  184. float m_v;
  185. float m_pad1;
  186. float m_pad2;
  187. };
  188. float* tangents = new float[6*_numVertices];
  189. bx::memSet(tangents, 0, 6*_numVertices*sizeof(float) );
  190. PosTexcoord v0;
  191. PosTexcoord v1;
  192. PosTexcoord v2;
  193. for (uint32_t ii = 0, num = _numIndices/3; ii < num; ++ii)
  194. {
  195. const uint16_t* indices = &_indices[ii*3];
  196. uint32_t i0 = indices[0];
  197. uint32_t i1 = indices[1];
  198. uint32_t i2 = indices[2];
  199. bgfx::vertexUnpack(&v0.m_x, bgfx::Attrib::Position, _layout, _vertices, i0);
  200. bgfx::vertexUnpack(&v0.m_u, bgfx::Attrib::TexCoord0, _layout, _vertices, i0);
  201. bgfx::vertexUnpack(&v1.m_x, bgfx::Attrib::Position, _layout, _vertices, i1);
  202. bgfx::vertexUnpack(&v1.m_u, bgfx::Attrib::TexCoord0, _layout, _vertices, i1);
  203. bgfx::vertexUnpack(&v2.m_x, bgfx::Attrib::Position, _layout, _vertices, i2);
  204. bgfx::vertexUnpack(&v2.m_u, bgfx::Attrib::TexCoord0, _layout, _vertices, i2);
  205. const float bax = v1.m_x - v0.m_x;
  206. const float bay = v1.m_y - v0.m_y;
  207. const float baz = v1.m_z - v0.m_z;
  208. const float bau = v1.m_u - v0.m_u;
  209. const float bav = v1.m_v - v0.m_v;
  210. const float cax = v2.m_x - v0.m_x;
  211. const float cay = v2.m_y - v0.m_y;
  212. const float caz = v2.m_z - v0.m_z;
  213. const float cau = v2.m_u - v0.m_u;
  214. const float cav = v2.m_v - v0.m_v;
  215. const float det = (bau * cav - bav * cau);
  216. const float invDet = 1.0f / det;
  217. const float tx = (bax * cav - cax * bav) * invDet;
  218. const float ty = (bay * cav - cay * bav) * invDet;
  219. const float tz = (baz * cav - caz * bav) * invDet;
  220. const float bx = (cax * bau - bax * cau) * invDet;
  221. const float by = (cay * bau - bay * cau) * invDet;
  222. const float bz = (caz * bau - baz * cau) * invDet;
  223. for (uint32_t jj = 0; jj < 3; ++jj)
  224. {
  225. float* tanu = &tangents[indices[jj]*6];
  226. float* tanv = &tanu[3];
  227. tanu[0] += tx;
  228. tanu[1] += ty;
  229. tanu[2] += tz;
  230. tanv[0] += bx;
  231. tanv[1] += by;
  232. tanv[2] += bz;
  233. }
  234. }
  235. for (uint32_t ii = 0; ii < _numVertices; ++ii)
  236. {
  237. const bx::Vec3 tanu = bx::load<bx::Vec3>(&tangents[ii*6]);
  238. const bx::Vec3 tanv = bx::load<bx::Vec3>(&tangents[ii*6 + 3]);
  239. float nxyzw[4];
  240. bgfx::vertexUnpack(nxyzw, bgfx::Attrib::Normal, _layout, _vertices, ii);
  241. const bx::Vec3 normal = bx::load<bx::Vec3>(nxyzw);
  242. const float ndt = bx::dot(normal, tanu);
  243. const bx::Vec3 nxt = bx::cross(normal, tanu);
  244. const bx::Vec3 tmp = bx::sub(tanu, bx::mul(normal, ndt) );
  245. float tangent[4];
  246. bx::store(tangent, bx::normalize(tmp) );
  247. tangent[3] = bx::dot(nxt, tanv) < 0.0f ? -1.0f : 1.0f;
  248. bgfx::vertexPack(tangent, true, bgfx::Attrib::Tangent, _layout, _vertices, ii);
  249. }
  250. delete [] tangents;
  251. }
  252. void write(bx::WriterI* _writer, const void* _vertices, uint32_t _numVertices, uint32_t _stride)
  253. {
  254. Sphere maxSphere;
  255. calcMaxBoundingSphere(maxSphere, _vertices, _numVertices, _stride);
  256. Sphere minSphere;
  257. calcMinBoundingSphere(minSphere, _vertices, _numVertices, _stride);
  258. if (minSphere.radius > maxSphere.radius)
  259. {
  260. bx::write(_writer, maxSphere);
  261. }
  262. else
  263. {
  264. bx::write(_writer, minSphere);
  265. }
  266. Aabb aabb;
  267. toAabb(aabb, _vertices, _numVertices, _stride);
  268. bx::write(_writer, aabb);
  269. Obb obb;
  270. calcObb(obb, _vertices, _numVertices, _stride, s_obbSteps);
  271. bx::write(_writer, obb);
  272. }
  273. void write(
  274. bx::WriterI* _writer
  275. , const uint8_t* _vertices
  276. , uint32_t _numVertices
  277. , const bgfx::VertexLayout& _layout
  278. , const uint16_t* _indices
  279. , uint32_t _numIndices
  280. , bool _compress
  281. , const stl::string& _material
  282. , const PrimitiveArray& _primitives
  283. )
  284. {
  285. using namespace bx;
  286. using namespace bgfx;
  287. uint32_t stride = _layout.getStride();
  288. if (_compress)
  289. {
  290. write(_writer, kChunkVertexBufferCompressed);
  291. write(_writer, _vertices, _numVertices, stride);
  292. write(_writer, _layout);
  293. write(_writer, uint16_t(_numVertices) );
  294. writeCompressedVertices(_writer, _vertices, _numVertices, uint16_t(stride) );
  295. }
  296. else
  297. {
  298. write(_writer, kChunkVertexBuffer);
  299. write(_writer, _vertices, _numVertices, stride);
  300. write(_writer, _layout);
  301. write(_writer, uint16_t(_numVertices) );
  302. write(_writer, _vertices, _numVertices*stride);
  303. }
  304. if (_compress)
  305. {
  306. write(_writer, kChunkIndexBufferCompressed);
  307. write(_writer, _numIndices);
  308. writeCompressedIndices(_writer, _indices, _numIndices, _numVertices);
  309. }
  310. else
  311. {
  312. write(_writer, kChunkIndexBuffer);
  313. write(_writer, _numIndices);
  314. write(_writer, _indices, _numIndices*2);
  315. }
  316. write(_writer, kChunkPrimitive);
  317. uint16_t nameLen = uint16_t(_material.size() );
  318. write(_writer, nameLen);
  319. write(_writer, _material.c_str(), nameLen);
  320. write(_writer, uint16_t(_primitives.size() ) );
  321. for (PrimitiveArray::const_iterator primIt = _primitives.begin(); primIt != _primitives.end(); ++primIt)
  322. {
  323. const Primitive& prim = *primIt;
  324. nameLen = uint16_t(prim.m_name.size() );
  325. write(_writer, nameLen);
  326. write(_writer, prim.m_name.c_str(), nameLen);
  327. write(_writer, prim.m_startIndex);
  328. write(_writer, prim.m_numIndices);
  329. write(_writer, prim.m_startVertex);
  330. write(_writer, prim.m_numVertices);
  331. write(_writer, &_vertices[prim.m_startVertex*stride], prim.m_numVertices, stride);
  332. }
  333. }
  334. inline uint32_t rgbaToAbgr(uint8_t _r, uint8_t _g, uint8_t _b, uint8_t _a)
  335. {
  336. return (uint32_t(_r)<<0)
  337. | (uint32_t(_g)<<8)
  338. | (uint32_t(_b)<<16)
  339. | (uint32_t(_a)<<24)
  340. ;
  341. }
  342. struct GroupSortByMaterial
  343. {
  344. bool operator()(const Group& _lhs, const Group& _rhs)
  345. {
  346. return 0 < bx::strCmp(_lhs.m_material.c_str(), _rhs.m_material.c_str() );
  347. }
  348. };
  349. void mtxCoordinateTransform(float* _result, const CoordinateSystem& _cs)
  350. {
  351. bx::Vec3 up = s_axisVectors[_cs.m_up];
  352. bx::Vec3 forward = s_axisVectors[_cs.m_forward];
  353. bx::Vec3 right = cross(forward,up);
  354. if (_cs.m_handness == bx::Handness::Left)
  355. {
  356. right = bx::mul(right, -1.0f);
  357. }
  358. bx::mtxIdentity(_result);
  359. bx::store(&_result[0], right);
  360. bx::store(&_result[4], forward);
  361. bx::store(&_result[8], up);
  362. }
  363. float mtxDeterminant(const float* _a)
  364. {
  365. const float xx = _a[ 0];
  366. const float xy = _a[ 1];
  367. const float xz = _a[ 2];
  368. const float xw = _a[ 3];
  369. const float yx = _a[ 4];
  370. const float yy = _a[ 5];
  371. const float yz = _a[ 6];
  372. const float yw = _a[ 7];
  373. const float zx = _a[ 8];
  374. const float zy = _a[ 9];
  375. const float zz = _a[10];
  376. const float zw = _a[11];
  377. const float wx = _a[12];
  378. const float wy = _a[13];
  379. const float wz = _a[14];
  380. const float ww = _a[15];
  381. float det = 0.0f;
  382. det += xx * (yy*(zz*ww - zw*wz) - yz*(zy*ww - zw*wy) + yw*(zy*wz - zz*wy) );
  383. det -= xy * (yx*(zz*ww - zw*wz) - yz*(zx*ww - zw*wx) + yw*(zx*wz - zz*wx) );
  384. det += xz * (yx*(zy*ww - zw*wy) - yy*(zx*ww - zw*wx) + yw*(zx*wy - zy*wx) );
  385. det -= xw * (yx*(zy*wz - zz*wy) - yy*(zx*wz - zz*wx) + yz*(zx*wy - zy*wx) );
  386. return det;
  387. }
  388. void parseObj(char* _data, uint32_t _size, Mesh* _mesh, bool _hasBc)
  389. {
  390. // Reference(s):
  391. // - Wavefront .obj file
  392. // https://en.wikipedia.org/wiki/Wavefront_.obj_file
  393. // Coordinate system is right-handed, but up/forward is not defined, but +Y Up, +Z Forward seems to be a common default
  394. _mesh->m_coordinateSystem.m_handness = bx::Handness::Right;
  395. _mesh->m_coordinateSystem.m_up = Axis::PositiveY;
  396. _mesh->m_coordinateSystem.m_forward = Axis::PositiveZ;
  397. uint32_t num = 0;
  398. Group group;
  399. group.m_startTriangle = 0;
  400. group.m_numTriangles = 0;
  401. char commandLine[2048];
  402. uint32_t len = sizeof(commandLine);
  403. int argc;
  404. char* argv[64];
  405. for (bx::StringView next(_data, _size); !next.isEmpty(); )
  406. {
  407. next = bx::tokenizeCommandLine(next, commandLine, len, argc, argv, BX_COUNTOF(argv), '\n');
  408. if (0 < argc)
  409. {
  410. if (0 == bx::strCmp(argv[0], "#") )
  411. {
  412. if (2 < argc
  413. && 0 == bx::strCmp(argv[2], "polygons") )
  414. {
  415. }
  416. }
  417. else if (0 == bx::strCmp(argv[0], "f") )
  418. {
  419. TriIndices triangle;
  420. bx::memSet(&triangle, 0, sizeof(TriIndices) );
  421. const int numNormals = (int)_mesh->m_normals.size();
  422. const int numTexcoords = (int)_mesh->m_texcoords.size();
  423. const int numPositions = (int)_mesh->m_positions.size();
  424. for (uint32_t edge = 0, numEdges = argc-1; edge < numEdges; ++edge)
  425. {
  426. Index3 index;
  427. index.m_texcoord = -1;
  428. index.m_normal = -1;
  429. if (_hasBc)
  430. {
  431. index.m_vbc = edge < 3 ? edge : (1+(edge+1) )&1;
  432. }
  433. else
  434. {
  435. index.m_vbc = 0;
  436. }
  437. {
  438. bx::StringView triplet(argv[edge + 1]);
  439. bx::StringView vertex(triplet);
  440. bx::StringView texcoord = bx::strFind(triplet, '/');
  441. if (!texcoord.isEmpty() )
  442. {
  443. vertex.set(vertex.getPtr(), texcoord.getPtr() );
  444. const bx::StringView normal = bx::strFind(bx::StringView(texcoord.getPtr() + 1, triplet.getTerm() ), '/');
  445. if (!normal.isEmpty() )
  446. {
  447. int32_t nn;
  448. bx::fromString(&nn, bx::StringView(normal.getPtr() + 1, triplet.getTerm() ) );
  449. index.m_normal = (nn < 0) ? nn + numNormals : nn - 1;
  450. }
  451. texcoord.set(texcoord.getPtr() + 1, normal.getPtr() );
  452. // Reference(s):
  453. // - Wavefront .obj file / Vertex normal indices without texture coordinate indices
  454. // https://en.wikipedia.org/wiki/Wavefront_.obj_file#Vertex_Normal_Indices_Without_Texture_Coordinate_Indices
  455. if (!texcoord.isEmpty() )
  456. {
  457. int32_t tex;
  458. bx::fromString(&tex, texcoord);
  459. index.m_texcoord = (tex < 0) ? tex + numTexcoords : tex - 1;
  460. }
  461. }
  462. int32_t pos;
  463. bx::fromString(&pos, vertex);
  464. index.m_position = (pos < 0) ? pos + numPositions : pos - 1;
  465. }
  466. switch (edge)
  467. {
  468. case 0: case 1: case 2:
  469. triangle.m_index[edge] = index;
  470. if (2 == edge)
  471. {
  472. _mesh->m_triangles.push_back(triangle);
  473. }
  474. break;
  475. default:
  476. triangle.m_index[1] = triangle.m_index[2];
  477. triangle.m_index[2] = index;
  478. _mesh->m_triangles.push_back(triangle);
  479. break;
  480. }
  481. }
  482. }
  483. else if (0 == bx::strCmp(argv[0], "g") )
  484. {
  485. group.m_name = argv[1];
  486. }
  487. else if (*argv[0] == 'v')
  488. {
  489. group.m_numTriangles = (uint32_t)(_mesh->m_triangles.size() ) - group.m_startTriangle;
  490. if (0 < group.m_numTriangles)
  491. {
  492. _mesh->m_groups.push_back(group);
  493. group.m_startTriangle = (uint32_t)(_mesh->m_triangles.size() );
  494. group.m_numTriangles = 0;
  495. }
  496. if (0 == bx::strCmp(argv[0], "vn") )
  497. {
  498. bx::Vec3 normal(bx::init::None);
  499. bx::fromString(&normal.x, argv[1]);
  500. bx::fromString(&normal.y, argv[2]);
  501. bx::fromString(&normal.z, argv[3]);
  502. _mesh->m_normals.push_back(normal);
  503. }
  504. else if (0 == bx::strCmp(argv[0], "vp") )
  505. {
  506. static bool once = true;
  507. if (once)
  508. {
  509. once = false;
  510. bx::printf("warning: 'parameter space vertices' are unsupported.\n");
  511. }
  512. }
  513. else if (0 == bx::strCmp(argv[0], "vt") )
  514. {
  515. bx::Vec3 texcoord(bx::init::None);
  516. texcoord.y = 0.0f;
  517. texcoord.z = 0.0f;
  518. bx::fromString(&texcoord.x, argv[1]);
  519. switch (argc)
  520. {
  521. case 4:
  522. bx::fromString(&texcoord.z, argv[3]);
  523. BX_FALLTHROUGH;
  524. case 3:
  525. bx::fromString(&texcoord.y, argv[2]);
  526. break;
  527. default:
  528. break;
  529. }
  530. _mesh->m_texcoords.push_back(texcoord);
  531. }
  532. else
  533. {
  534. float px, py, pz, pw;
  535. bx::fromString(&px, argv[1]);
  536. bx::fromString(&py, argv[2]);
  537. bx::fromString(&pz, argv[3]);
  538. if (argc == 5 || argc == 8)
  539. {
  540. bx::fromString(&pw, argv[4]);
  541. }
  542. else
  543. {
  544. pw = 1.0f;
  545. }
  546. bx::Vec3 pos(px, py, pz);
  547. const float invW = bx::rcp(pw);
  548. pos = bx::mul(pos, invW);
  549. _mesh->m_positions.push_back(pos);
  550. }
  551. }
  552. else if (0 == bx::strCmp(argv[0], "usemtl") )
  553. {
  554. stl::string material(argv[1]);
  555. if (0 != bx::strCmp(material.c_str(), group.m_material.c_str() ) )
  556. {
  557. group.m_numTriangles = (uint32_t)(_mesh->m_triangles.size() ) - group.m_startTriangle;
  558. if (0 < group.m_numTriangles)
  559. {
  560. _mesh->m_groups.push_back(group);
  561. group.m_startTriangle = (uint32_t)(_mesh->m_triangles.size() );
  562. group.m_numTriangles = 0;
  563. }
  564. }
  565. group.m_material = material;
  566. }
  567. // unsupported tags
  568. // else if (0 == bx::strCmp(argv[0], "mtllib") )
  569. // {
  570. // }
  571. // else if (0 == bx::strCmp(argv[0], "o") )
  572. // {
  573. // }
  574. // else if (0 == bx::strCmp(argv[0], "s") )
  575. // {
  576. // }
  577. }
  578. ++num;
  579. }
  580. group.m_numTriangles = (uint32_t)(_mesh->m_triangles.size() ) - group.m_startTriangle;
  581. if (0 < group.m_numTriangles)
  582. {
  583. _mesh->m_groups.push_back(group);
  584. group.m_startTriangle = (uint32_t)(_mesh->m_triangles.size() );
  585. group.m_numTriangles = 0;
  586. }
  587. bx::printf("obj parser # %d\n", num);
  588. }
  589. void gltfReadFloat(const float* _accessorData, cgltf_size _accessorNumComponents, cgltf_size _index, cgltf_float* _out, cgltf_size _outElementSize)
  590. {
  591. const float* input = &_accessorData[_accessorNumComponents * _index];
  592. for (cgltf_size ii = 0; ii < _outElementSize; ++ii)
  593. {
  594. _out[ii] = (ii < _accessorNumComponents) ? input[ii] : 0.0f;
  595. }
  596. }
  597. void processGltfNode(cgltf_node* _node, Mesh* _mesh, Group* _group, bool _hasBc)
  598. {
  599. cgltf_mesh* mesh = _node->mesh;
  600. if (NULL != mesh)
  601. {
  602. float nodeToWorld[16];
  603. cgltf_node_transform_world(_node, nodeToWorld);
  604. float nodeToWorldNormal[16];
  605. bx::mtxCofactor(nodeToWorldNormal, nodeToWorld);
  606. for (cgltf_size primitiveIndex = 0; primitiveIndex < mesh->primitives_count; ++primitiveIndex)
  607. {
  608. cgltf_primitive* primitive = &mesh->primitives[primitiveIndex];
  609. cgltf_size numVertex = primitive->attributes[0].data->count;
  610. int32_t basePositionIndex = (int32_t)_mesh->m_positions.size();
  611. int32_t baseNormalIndex = (int32_t)_mesh->m_normals.size();
  612. int32_t baseTexcoordIndex = (int32_t)_mesh->m_texcoords.size();
  613. bool hasNormal = false;
  614. bool hasTexcoord = false;
  615. for (cgltf_size attributeIndex = 0; attributeIndex < primitive->attributes_count; ++attributeIndex)
  616. {
  617. cgltf_attribute* attribute = &primitive->attributes[attributeIndex];
  618. cgltf_accessor* accessor = attribute->data;
  619. cgltf_size accessorCount = accessor->count;
  620. BX_ASSERT(numVertex == accessorCount, "Invalid attribute count");
  621. cgltf_size floatCount = cgltf_accessor_unpack_floats(accessor, NULL, 0);
  622. float* accessorData = (float*)malloc(floatCount * sizeof(float) );
  623. cgltf_accessor_unpack_floats(accessor, accessorData, floatCount);
  624. cgltf_size numComponents = cgltf_num_components(accessor->type);
  625. if (attribute->type == cgltf_attribute_type_position && attribute->index == 0)
  626. {
  627. _mesh->m_positions.reserve(_mesh->m_positions.size() + accessorCount);
  628. bx::Vec3 pos(bx::init::None);
  629. for (cgltf_size v = 0; v < accessorCount; ++v)
  630. {
  631. gltfReadFloat(accessorData, numComponents, v, &pos.x, 3);
  632. pos = mul(pos, nodeToWorld);
  633. _mesh->m_positions.push_back(pos);
  634. }
  635. }
  636. else if (attribute->type == cgltf_attribute_type_normal && attribute->index == 0)
  637. {
  638. _mesh->m_normals.reserve(_mesh->m_normals.size() + accessorCount);
  639. hasNormal = true;
  640. bx::Vec3 normal(bx::init::None);
  641. for (cgltf_size v = 0; v < accessorCount; ++v)
  642. {
  643. gltfReadFloat(accessorData, numComponents, v, &normal.x, 3);
  644. normal = mul(normal, nodeToWorldNormal);
  645. _mesh->m_normals.push_back(normal);
  646. }
  647. }
  648. else if (attribute->type == cgltf_attribute_type_texcoord && attribute->index == 0)
  649. {
  650. _mesh->m_texcoords.reserve(_mesh->m_texcoords.size() + accessorCount);
  651. hasTexcoord = true;
  652. bx::Vec3 texcoord(bx::init::None);
  653. for (cgltf_size v = 0; v < accessorCount; ++v)
  654. {
  655. gltfReadFloat(accessorData, numComponents, v, &texcoord.x, 3);
  656. _mesh->m_texcoords.push_back(texcoord);
  657. }
  658. }
  659. free(accessorData);
  660. }
  661. if (primitive->indices != NULL)
  662. {
  663. cgltf_accessor* accessor = primitive->indices;
  664. for (cgltf_size v = 0; v < accessor->count; v += 3)
  665. {
  666. TriIndices triangle;
  667. for (int i = 0; i < 3; ++i)
  668. {
  669. Index3 index;
  670. int32_t vertexIndex = int32_t(cgltf_accessor_read_index(accessor, v+i) );
  671. index.m_position = basePositionIndex + vertexIndex;
  672. index.m_normal = hasNormal ? baseNormalIndex + vertexIndex : -1;
  673. index.m_texcoord = hasTexcoord ? baseTexcoordIndex + vertexIndex : -1;
  674. index.m_vbc = _hasBc ? i : 0;
  675. triangle.m_index[i] = index;
  676. }
  677. _mesh->m_triangles.push_back(triangle);
  678. }
  679. }
  680. else
  681. {
  682. for (cgltf_size v = 0; v < numVertex; v += 3)
  683. {
  684. TriIndices triangle;
  685. for (int i = 0; i < 3; ++i)
  686. {
  687. Index3 index;
  688. int32_t vertexIndex = int32_t(v * 3 + i);
  689. index.m_position = basePositionIndex + vertexIndex;
  690. index.m_normal = hasNormal ? baseNormalIndex + vertexIndex : -1;
  691. index.m_texcoord = hasTexcoord ? baseTexcoordIndex + vertexIndex : -1;
  692. index.m_vbc = _hasBc ? i : 0;
  693. triangle.m_index[i] = index;
  694. }
  695. _mesh->m_triangles.push_back(triangle);
  696. }
  697. }
  698. _group->m_numTriangles = (uint32_t)(_mesh->m_triangles.size() ) - _group->m_startTriangle;
  699. if (0 < _group->m_numTriangles)
  700. {
  701. _mesh->m_groups.push_back(*_group);
  702. _group->m_startTriangle = (uint32_t)(_mesh->m_triangles.size() );
  703. _group->m_numTriangles = 0;
  704. }
  705. }
  706. }
  707. for (cgltf_size childIndex = 0; childIndex < _node->children_count; ++childIndex)
  708. processGltfNode(_node->children[childIndex], _mesh, _group, _hasBc);
  709. }
  710. void parseGltf(char* _data, uint32_t _size, Mesh* _mesh, bool _hasBc, const bx::StringView& _path)
  711. {
  712. // Reference(s):
  713. // - Gltf 2.0 specification
  714. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0
  715. _mesh->m_coordinateSystem.m_handness = bx::Handness::Right;
  716. _mesh->m_coordinateSystem.m_forward = Axis::PositiveZ;
  717. _mesh->m_coordinateSystem.m_up = Axis::PositiveY;
  718. Group group;
  719. group.m_startTriangle = 0;
  720. group.m_numTriangles = 0;
  721. cgltf_options options = { };
  722. cgltf_data* data = NULL;
  723. cgltf_result result = cgltf_parse(&options, _data, _size, &data);
  724. if (result == cgltf_result_success)
  725. {
  726. char* path = (char*)malloc(_path.getLength()+1);
  727. bx::memCopy(path, _path.getPtr(), _path.getLength() );
  728. path[_path.getLength()] = 0;
  729. result = cgltf_load_buffers(&options, data, path);
  730. free(path);
  731. if (result == cgltf_result_success)
  732. {
  733. for (cgltf_size sceneIndex = 0; sceneIndex < data->scenes_count; ++sceneIndex)
  734. {
  735. cgltf_scene* scene = &data->scenes[sceneIndex];
  736. for (cgltf_size nodeIndex = 0; nodeIndex < scene->nodes_count; ++nodeIndex)
  737. {
  738. cgltf_node* node = scene->nodes[nodeIndex];
  739. processGltfNode(node, _mesh, &group, _hasBc);
  740. }
  741. }
  742. }
  743. cgltf_free(data);
  744. }
  745. }
  746. void help(const char* _error = NULL)
  747. {
  748. if (NULL != _error)
  749. {
  750. bx::printf("Error:\n%s\n\n", _error);
  751. }
  752. bx::printf(
  753. "geometryc, bgfx geometry compiler tool, version %d.%d.%d.\n"
  754. "Copyright 2011-2021 Branimir Karadzic. All rights reserved.\n"
  755. "License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause\n\n"
  756. , BGFX_GEOMETRYC_VERSION_MAJOR
  757. , BGFX_GEOMETRYC_VERSION_MINOR
  758. , BGFX_API_VERSION
  759. );
  760. bx::printf(
  761. "Usage: geometryc -f <in> -o <out>\n"
  762. "\n"
  763. "Supported input file types:\n"
  764. " *.obj Wavefront\n"
  765. " *.gltf,*.glb glTF 2.0\n"
  766. "\n"
  767. "Options:\n"
  768. " -h, --help Help.\n"
  769. " -v, --version Version information only.\n"
  770. " -f <file path> Input file path.\n"
  771. " -o <file path> Output file path.\n"
  772. " -s, --scale <num> Scale factor.\n"
  773. " --ccw Front face is counter-clockwise winding order.\n"
  774. " --flipv Flip texture coordinate V.\n"
  775. " --obb <num> Number of steps for calculating oriented bounding box.\n"
  776. " Default value is 17. Less steps less precise OBB is.\n"
  777. " More steps slower calculation.\n"
  778. " --packnormal <num> Normal packing.\n"
  779. " 0 - unpacked 12 bytes (default).\n"
  780. " 1 - packed 4 bytes.\n"
  781. " --packuv <num> Texture coordinate packing.\n"
  782. " 0 - unpacked 8 bytes (default).\n"
  783. " 1 - packed 4 bytes.\n"
  784. " --tangent Calculate tangent vectors (packing mode is the same as normal).\n"
  785. " --barycentric Adds barycentric vertex attribute (packed in bgfx::Attrib::Color1).\n"
  786. " -c, --compress Compress indices.\n"
  787. " --[l/r]h-up+[y/z] Coordinate system. Default is '--lh-up+y' Left-Handed +Y is up.\n"
  788. "\n"
  789. "For additional information, see https://github.com/bkaradzic/bgfx\n"
  790. );
  791. }
  792. int main(int _argc, const char* _argv[])
  793. {
  794. bx::CommandLine cmdLine(_argc, _argv);
  795. if (cmdLine.hasArg('v', "version") )
  796. {
  797. bx::printf(
  798. "geometryc, bgfx geometry compiler tool, version %d.%d.%d.\n"
  799. , BGFX_GEOMETRYC_VERSION_MAJOR
  800. , BGFX_GEOMETRYC_VERSION_MINOR
  801. , BGFX_API_VERSION
  802. );
  803. return bx::kExitSuccess;
  804. }
  805. if (cmdLine.hasArg('h', "help") )
  806. {
  807. help();
  808. return bx::kExitFailure;
  809. }
  810. const char* filePath = cmdLine.findOption('f');
  811. if (NULL == filePath)
  812. {
  813. help("Input file name must be specified.");
  814. return bx::kExitFailure;
  815. }
  816. const char* outFilePath = cmdLine.findOption('o');
  817. if (NULL == outFilePath)
  818. {
  819. help("Output file name must be specified.");
  820. return bx::kExitFailure;
  821. }
  822. float scale = 1.0f;
  823. const char* scaleArg = cmdLine.findOption('s', "scale");
  824. if (NULL != scaleArg)
  825. {
  826. if (!bx::fromString(&scale, scaleArg) )
  827. {
  828. scale = 1.0f;
  829. }
  830. }
  831. bool compress = cmdLine.hasArg('c', "compress");
  832. cmdLine.hasArg(s_obbSteps, '\0', "obb");
  833. s_obbSteps = bx::uint32_min(bx::uint32_max(s_obbSteps, 1), 90);
  834. uint32_t packNormal = 0;
  835. cmdLine.hasArg(packNormal, '\0', "packnormal");
  836. uint32_t packUv = 0;
  837. cmdLine.hasArg(packUv, '\0', "packuv");
  838. bool ccw = cmdLine.hasArg("ccw");
  839. bool flipV = cmdLine.hasArg("flipv");
  840. bool hasTangent = cmdLine.hasArg("tangent");
  841. bool hasBc = cmdLine.hasArg("barycentric");
  842. CoordinateSystem outputCoordinateSystem;
  843. outputCoordinateSystem.m_handness = bx::Handness::Left;
  844. outputCoordinateSystem.m_forward = Axis::PositiveZ;
  845. outputCoordinateSystem.m_up = Axis::PositiveY;
  846. for (uint32_t ii = 0; ii < BX_COUNTOF(s_coordinateSystemMappings); ++ii)
  847. {
  848. if (cmdLine.hasArg(s_coordinateSystemMappings[ii].m_param) )
  849. {
  850. outputCoordinateSystem = s_coordinateSystemMappings[ii].m_coordinateSystem;
  851. }
  852. }
  853. bx::FileReader fr;
  854. if (!bx::open(&fr, filePath) )
  855. {
  856. bx::printf("Unable to open input file '%s'.", filePath);
  857. return bx::kExitFailure;
  858. }
  859. int64_t parseElapsed = -bx::getHPCounter();
  860. int64_t triReorderElapsed = 0;
  861. uint32_t size = (uint32_t)bx::getSize(&fr);
  862. char* data = new char[size+1];
  863. size = bx::read(&fr, data, size);
  864. data[size] = '\0';
  865. bx::close(&fr);
  866. Mesh mesh;
  867. bx::StringView ext = bx::FilePath(filePath).getExt();
  868. if (0 == bx::strCmpI(ext, ".obj") )
  869. {
  870. parseObj(data, size, &mesh, hasBc);
  871. }
  872. else if (0 == bx::strCmpI(ext, ".gltf") || 0 == bx::strCmpI(ext, ".glb") )
  873. {
  874. parseGltf(data, size, &mesh, hasBc, bx::FilePath(filePath).getPath() );
  875. }
  876. else
  877. {
  878. bx::printf("Unsupported input file format '%s'.", filePath);
  879. exit(bx::kExitFailure);
  880. }
  881. delete [] data;
  882. int64_t now = bx::getHPCounter();
  883. parseElapsed += now;
  884. int64_t convertElapsed = -now;
  885. std::sort(mesh.m_groups.begin(), mesh.m_groups.end(), GroupSortByMaterial() );
  886. bool changeWinding = ccw;
  887. if (scale != 1.0f)
  888. {
  889. for (Vec3Array::iterator it = mesh.m_positions.begin(), itEnd = mesh.m_positions.end(); it != itEnd; ++it)
  890. {
  891. it->x *= scale;
  892. it->y *= scale;
  893. it->z *= scale;
  894. }
  895. }
  896. {
  897. float meshTransform[16];
  898. mtxCoordinateTransform(meshTransform, mesh.m_coordinateSystem);
  899. float meshInvTranform[16];
  900. bx::mtxTranspose(meshInvTranform, meshTransform);
  901. float outTransform[16];
  902. mtxCoordinateTransform(outTransform, outputCoordinateSystem);
  903. float transform[16];
  904. bx::mtxMul(transform, meshInvTranform, outTransform);
  905. if ( mtxDeterminant(transform) < 0.0f )
  906. {
  907. changeWinding = !changeWinding;
  908. }
  909. float identity[16];
  910. bx::mtxIdentity(identity);
  911. if ( 0 != bx::memCmp(identity, transform, sizeof(transform) ) )
  912. {
  913. for (Vec3Array::iterator it = mesh.m_positions.begin(), itEnd = mesh.m_positions.end(); it != itEnd; ++it)
  914. {
  915. *it = bx::mul(*it, transform);
  916. }
  917. for (Vec3Array::iterator it = mesh.m_normals.begin(), itEnd = mesh.m_normals.end(); it != itEnd; ++it)
  918. {
  919. *it = bx::mul(*it, transform);
  920. }
  921. }
  922. }
  923. bool hasColor = false;
  924. bool hasNormal = false;
  925. bool hasTexcoord = false;
  926. {
  927. for (TriangleArray::iterator jt = mesh.m_triangles.begin(), jtEnd = mesh.m_triangles.end(); jt != jtEnd && !hasTexcoord; ++jt)
  928. {
  929. for (uint32_t i = 0; i < 3; ++i)
  930. {
  931. hasTexcoord |= -1 != jt->m_index[i].m_texcoord;
  932. }
  933. }
  934. for (TriangleArray::iterator jt = mesh.m_triangles.begin(), jtEnd = mesh.m_triangles.end(); jt != jtEnd && !hasNormal; ++jt)
  935. {
  936. for (uint32_t i = 0; i < 3; ++i)
  937. {
  938. hasNormal |= -1 != jt->m_index[i].m_normal;
  939. }
  940. }
  941. if (changeWinding)
  942. {
  943. for (TriangleArray::iterator jt = mesh.m_triangles.begin(), jtEnd = mesh.m_triangles.end(); jt != jtEnd; ++jt)
  944. {
  945. bx::swap(jt->m_index[1], jt->m_index[2]);
  946. }
  947. }
  948. }
  949. bgfx::VertexLayout layout;
  950. layout.begin();
  951. layout.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float);
  952. if (hasColor)
  953. {
  954. layout.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true);
  955. }
  956. if (hasBc)
  957. {
  958. layout.add(bgfx::Attrib::Color1, 4, bgfx::AttribType::Uint8, true);
  959. }
  960. if (hasTexcoord)
  961. {
  962. switch (packUv)
  963. {
  964. default:
  965. case 0:
  966. layout.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float);
  967. break;
  968. case 1:
  969. layout.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Half);
  970. break;
  971. }
  972. }
  973. if (hasNormal)
  974. {
  975. hasTangent &= hasTexcoord;
  976. switch (packNormal)
  977. {
  978. default:
  979. case 0:
  980. layout.add(bgfx::Attrib::Normal, 3, bgfx::AttribType::Float);
  981. if (hasTangent)
  982. {
  983. layout.add(bgfx::Attrib::Tangent, 4, bgfx::AttribType::Float);
  984. }
  985. break;
  986. case 1:
  987. layout.add(bgfx::Attrib::Normal, 4, bgfx::AttribType::Uint8, true, true);
  988. if (hasTangent)
  989. {
  990. layout.add(bgfx::Attrib::Tangent, 4, bgfx::AttribType::Uint8, true, true);
  991. }
  992. break;
  993. }
  994. }
  995. layout.end();
  996. uint32_t stride = layout.getStride();
  997. uint8_t* vertexData = new uint8_t[mesh.m_triangles.size() * 3 * stride];
  998. uint16_t* indexData = new uint16_t[mesh.m_triangles.size() * 3];
  999. int32_t numVertices = 0;
  1000. int32_t numIndices = 0;
  1001. int32_t writtenPrimitives = 0;
  1002. int32_t writtenVertices = 0;
  1003. int32_t writtenIndices = 0;
  1004. uint8_t* vertices = vertexData;
  1005. uint16_t* indices = indexData;
  1006. const uint32_t tableSize = 65536 * 2;
  1007. const uint32_t hashmod = tableSize - 1;
  1008. uint32_t* table = new uint32_t[tableSize];
  1009. bx::memSet(table, 0xff, tableSize * sizeof(uint32_t) );
  1010. stl::string material = mesh.m_groups.empty() ? "" : mesh.m_groups.begin()->m_material;
  1011. PrimitiveArray primitives;
  1012. bx::FileWriter writer;
  1013. if (!bx::open(&writer, outFilePath) )
  1014. {
  1015. bx::printf("Unable to open output file '%s'.", outFilePath);
  1016. exit(bx::kExitFailure);
  1017. }
  1018. Primitive prim;
  1019. prim.m_startVertex = 0;
  1020. prim.m_startIndex = 0;
  1021. uint32_t positionOffset = layout.getOffset(bgfx::Attrib::Position);
  1022. uint32_t color0Offset = layout.getOffset(bgfx::Attrib::Color0);
  1023. Group sentinelGroup;
  1024. sentinelGroup.m_startTriangle = 0;
  1025. sentinelGroup.m_numTriangles = UINT32_MAX;
  1026. mesh.m_groups.push_back(sentinelGroup);
  1027. uint32_t ii = 0;
  1028. for (GroupArray::const_iterator groupIt = mesh.m_groups.begin(); groupIt != mesh.m_groups.end(); ++groupIt, ++ii)
  1029. {
  1030. bool sentinel = groupIt->m_startTriangle == 0 && groupIt->m_numTriangles == UINT32_MAX;
  1031. for (uint32_t tri = groupIt->m_startTriangle, end = tri + groupIt->m_numTriangles; tri < end; ++tri)
  1032. {
  1033. if (0 != bx::strCmp(material.c_str(), groupIt->m_material.c_str() )
  1034. || sentinel
  1035. || 65533 <= numVertices)
  1036. {
  1037. prim.m_numVertices = numVertices - prim.m_startVertex;
  1038. prim.m_numIndices = numIndices - prim.m_startIndex;
  1039. if (0 < prim.m_numVertices)
  1040. {
  1041. primitives.push_back(prim);
  1042. }
  1043. if (hasTangent)
  1044. {
  1045. calcTangents(vertexData, uint16_t(numVertices), layout, indexData, numIndices);
  1046. }
  1047. triReorderElapsed -= bx::getHPCounter();
  1048. for (PrimitiveArray::const_iterator primIt = primitives.begin(); primIt != primitives.end(); ++primIt)
  1049. {
  1050. const Primitive& prim1 = *primIt;
  1051. optimizeVertexCache(indexData + prim1.m_startIndex, prim1.m_numIndices, numVertices);
  1052. }
  1053. numVertices = optimizeVertexFetch(indexData, numIndices, vertexData, numVertices, uint16_t(stride) );
  1054. triReorderElapsed += bx::getHPCounter();
  1055. if ( numVertices > 0 && numIndices > 0 )
  1056. {
  1057. write(&writer
  1058. , vertexData
  1059. , numVertices
  1060. , layout
  1061. , indexData
  1062. , numIndices
  1063. , compress
  1064. , material
  1065. , primitives
  1066. );
  1067. }
  1068. primitives.clear();
  1069. bx::memSet(table, 0xff, tableSize * sizeof(uint32_t) );
  1070. ++writtenPrimitives;
  1071. writtenVertices += numVertices;
  1072. writtenIndices += numIndices;
  1073. vertices = vertexData;
  1074. indices = indexData;
  1075. numVertices = 0;
  1076. numIndices = 0;
  1077. prim.m_startVertex = 0;
  1078. prim.m_startIndex = 0;
  1079. material = groupIt->m_material;
  1080. if (sentinel)
  1081. break;
  1082. }
  1083. TriIndices& triangle = mesh.m_triangles[tri];
  1084. for (uint32_t edge = 0; edge < 3; ++edge)
  1085. {
  1086. Index3& index = triangle.m_index[edge];
  1087. float* position = (float*)(vertices + positionOffset);
  1088. bx::memCopy(position, &mesh.m_positions[index.m_position], 3*sizeof(float) );
  1089. if (hasColor)
  1090. {
  1091. uint32_t* color0 = (uint32_t*)(vertices + color0Offset);
  1092. *color0 = rgbaToAbgr(numVertices%255, numIndices%255, 0, 0xff);
  1093. }
  1094. if (hasBc)
  1095. {
  1096. const float bc[4] =
  1097. {
  1098. (index.m_vbc == 0) ? 1.0f : 0.0f,
  1099. (index.m_vbc == 1) ? 1.0f : 0.0f,
  1100. (index.m_vbc == 2) ? 1.0f : 0.0f,
  1101. 0.0f
  1102. };
  1103. bgfx::vertexPack(bc, true, bgfx::Attrib::Color1, layout, vertices);
  1104. }
  1105. if (hasTexcoord)
  1106. {
  1107. float uv[2];
  1108. bx::memCopy(uv, &mesh.m_texcoords[index.m_texcoord == -1 ? 0 : index.m_texcoord], 2*sizeof(float) );
  1109. if (flipV)
  1110. {
  1111. uv[1] = -uv[1];
  1112. }
  1113. bgfx::vertexPack(uv, true, bgfx::Attrib::TexCoord0, layout, vertices);
  1114. }
  1115. if (hasNormal)
  1116. {
  1117. float normal[4];
  1118. bx::store(normal, bx::normalize(bx::load<bx::Vec3>(&mesh.m_normals[index.m_normal == -1 ? 0 : index.m_normal]) ) );
  1119. normal[3] = 0.0f;
  1120. bgfx::vertexPack(normal, true, bgfx::Attrib::Normal, layout, vertices);
  1121. }
  1122. uint32_t hash = bx::hash<bx::HashMurmur2A>(vertices, stride);
  1123. size_t bucket = hash & hashmod;
  1124. uint32_t vertexIndex = UINT32_MAX;
  1125. for (size_t probe = 0; probe <= hashmod; ++probe)
  1126. {
  1127. uint32_t& item = table[bucket];
  1128. if (item == ~0u)
  1129. {
  1130. vertices += stride;
  1131. item = numVertices++;
  1132. vertexIndex = item;
  1133. break;
  1134. }
  1135. if (0 == bx::memCmp(vertexData + item * stride, vertices, stride) )
  1136. {
  1137. vertexIndex = item;
  1138. break;
  1139. }
  1140. bucket = (bucket + probe + 1) & hashmod;
  1141. }
  1142. if ( vertexIndex == UINT32_MAX )
  1143. {
  1144. bx::printf("hash table insert failed");
  1145. exit(bx::kExitFailure);
  1146. }
  1147. *indices++ = (uint16_t)vertexIndex;
  1148. ++numIndices;
  1149. }
  1150. }
  1151. prim.m_numVertices = numVertices - prim.m_startVertex;
  1152. if (0 < prim.m_numVertices)
  1153. {
  1154. prim.m_numIndices = numIndices - prim.m_startIndex;
  1155. prim.m_name = groupIt->m_name;
  1156. primitives.push_back(prim);
  1157. prim.m_startVertex = numVertices;
  1158. prim.m_startIndex = numIndices;
  1159. }
  1160. BX_TRACE("%3d: s %5d, n %5d, %s\n"
  1161. , ii
  1162. , groupIt->m_startTriangle
  1163. , groupIt->m_numTriangles
  1164. , groupIt->m_material.c_str()
  1165. );
  1166. }
  1167. BX_ASSERT(0 == primitives.size(), "Not all primitives are written");
  1168. bx::printf("size: %d\n", uint32_t(bx::seek(&writer) ) );
  1169. bx::close(&writer);
  1170. delete [] table;
  1171. delete [] indexData;
  1172. delete [] vertexData;
  1173. now = bx::getHPCounter();
  1174. convertElapsed += now;
  1175. bx::printf("parse %f [s]\ntri reorder %f [s]\nconvert %f [s]\ng %d, p %d, v %d, i %d\n"
  1176. , double(parseElapsed)/bx::getHPFrequency()
  1177. , double(triReorderElapsed)/bx::getHPFrequency()
  1178. , double(convertElapsed)/bx::getHPFrequency()
  1179. , uint32_t(mesh.m_groups.size()-1)
  1180. , writtenPrimitives
  1181. , writtenVertices
  1182. , writtenIndices
  1183. );
  1184. return bx::kExitSuccess;
  1185. }