geometryc.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  1. /*
  2. * Copyright 2011-2015 Branimir Karadzic. All rights reserved.
  3. * License: http://www.opensource.org/licenses/BSD-2-Clause
  4. */
  5. #include <algorithm>
  6. #include <vector>
  7. #include <string>
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include <bgfx.h>
  12. #include "../../src/vertexdecl.h"
  13. #include <tinystl/allocator.h>
  14. #include <tinystl/unordered_map.h>
  15. #include <tinystl/unordered_set.h>
  16. namespace stl = tinystl;
  17. #include <forsyth-too/forsythtriangleorderoptimizer.h>
  18. #include <ib-compress/indexbuffercompression.h>
  19. #if 0
  20. # define BX_TRACE(_format, ...) \
  21. do { \
  22. printf(BX_FILE_LINE_LITERAL "BGFX " _format "\n", ##__VA_ARGS__); \
  23. } while(0)
  24. # define BX_WARN(_condition, _format, ...) \
  25. do { \
  26. if (!(_condition) ) \
  27. { \
  28. BX_TRACE(BX_FILE_LINE_LITERAL "WARN " _format, ##__VA_ARGS__); \
  29. } \
  30. } while(0)
  31. # define BX_CHECK(_condition, _format, ...) \
  32. do { \
  33. if (!(_condition) ) \
  34. { \
  35. BX_TRACE(BX_FILE_LINE_LITERAL "CHECK " _format, ##__VA_ARGS__); \
  36. bx::debugBreak(); \
  37. } \
  38. } while(0)
  39. #endif // 0
  40. #define EXPECT(_condition) \
  41. do { \
  42. if (!(_condition) ) \
  43. { \
  44. printf("Error parsing at:\n" BX_FILE_LINE_LITERAL "\nExpected: " #_condition "\n"); \
  45. exit(EXIT_FAILURE); \
  46. } \
  47. } while(0)
  48. #include <bx/bx.h>
  49. #include <bx/debug.h>
  50. #include <bx/commandline.h>
  51. #include <bx/timer.h>
  52. #include <bx/readerwriter.h>
  53. #include <bx/hash.h>
  54. #include <bx/uint32_t.h>
  55. #include <bx/fpumath.h>
  56. #include <bx/tokenizecmd.h>
  57. #include "bounds.h"
  58. struct Vector3
  59. {
  60. float x;
  61. float y;
  62. float z;
  63. };
  64. typedef std::vector<Vector3> Vector3Array;
  65. struct Index3
  66. {
  67. int32_t m_position;
  68. int32_t m_texcoord;
  69. int32_t m_normal;
  70. int32_t m_vertexIndex;
  71. };
  72. typedef stl::unordered_map<uint64_t, Index3> Index3Map;
  73. struct Triangle
  74. {
  75. uint64_t m_index[3];
  76. };
  77. typedef std::vector<Triangle> TriangleArray;
  78. struct Group
  79. {
  80. uint32_t m_startTriangle;
  81. uint32_t m_numTriangles;
  82. std::string m_name;
  83. std::string m_material;
  84. };
  85. typedef std::vector<Group> GroupArray;
  86. struct Primitive
  87. {
  88. uint32_t m_startVertex;
  89. uint32_t m_startIndex;
  90. uint32_t m_numVertices;
  91. uint32_t m_numIndices;
  92. std::string m_name;
  93. };
  94. typedef std::vector<Primitive> PrimitiveArray;
  95. static uint32_t s_obbSteps = 17;
  96. #define BGFX_CHUNK_MAGIC_VB BX_MAKEFOURCC('V', 'B', ' ', 0x1)
  97. #define BGFX_CHUNK_MAGIC_IB BX_MAKEFOURCC('I', 'B', ' ', 0x0)
  98. #define BGFX_CHUNK_MAGIC_IBC BX_MAKEFOURCC('I', 'B', 'C', 0x0)
  99. #define BGFX_CHUNK_MAGIC_PRI BX_MAKEFOURCC('P', 'R', 'I', 0x0)
  100. long int fsize(FILE* _file)
  101. {
  102. long int pos = ftell(_file);
  103. fseek(_file, 0L, SEEK_END);
  104. long int size = ftell(_file);
  105. fseek(_file, pos, SEEK_SET);
  106. return size;
  107. }
  108. void triangleReorder(uint16_t* _indices, uint32_t _numIndices, uint32_t _numVertices, uint16_t _cacheSize)
  109. {
  110. uint16_t* newIndexList = new uint16_t[_numIndices];
  111. Forsyth::OptimizeFaces(_indices, _numIndices, _numVertices, newIndexList, _cacheSize);
  112. memcpy(_indices, newIndexList, _numIndices*2);
  113. delete [] newIndexList;
  114. }
  115. void triangleCompress(bx::WriterI* _writer, uint16_t* _indices, uint32_t _numIndices, uint8_t* _vertexData, uint32_t _numVertices, uint16_t _stride)
  116. {
  117. uint32_t* vertexRemap = (uint32_t*)malloc(_numVertices*sizeof(uint32_t) );
  118. WriteBitstream writer;
  119. CompressIndexBuffer(_indices, _numIndices/3, vertexRemap, _numVertices, IBCF_AUTO, writer);
  120. writer.Finish();
  121. printf( "uncompressed: %10d, compressed: %10d, ratio: %0.2f%%\n"
  122. , _numIndices*2
  123. , (uint32_t)writer.ByteSize()
  124. , 100.0f - float(writer.ByteSize() ) / float(_numIndices*2)*100.0f
  125. );
  126. BX_UNUSED(_vertexData, _stride);
  127. uint8_t* outVertexData = (uint8_t*)malloc(_numVertices*_stride);
  128. for (uint32_t ii = 0; ii < _numVertices; ++ii)
  129. {
  130. uint32_t remap = vertexRemap[ii];
  131. remap = UINT32_MAX == remap ? ii : remap;
  132. memcpy(&outVertexData[remap*_stride], &_vertexData[ii*_stride], _stride);
  133. }
  134. memcpy(_vertexData, outVertexData, _numVertices*_stride);
  135. free(outVertexData);
  136. free(vertexRemap);
  137. bx::write(_writer, writer.RawData(), (uint32_t)writer.ByteSize() );
  138. }
  139. void calcTangents(void* _vertices, uint16_t _numVertices, bgfx::VertexDecl _decl, const uint16_t* _indices, uint32_t _numIndices)
  140. {
  141. struct PosTexcoord
  142. {
  143. float m_x;
  144. float m_y;
  145. float m_z;
  146. float m_pad0;
  147. float m_u;
  148. float m_v;
  149. float m_pad1;
  150. float m_pad2;
  151. };
  152. float* tangents = new float[6*_numVertices];
  153. memset(tangents, 0, 6*_numVertices*sizeof(float) );
  154. PosTexcoord v0;
  155. PosTexcoord v1;
  156. PosTexcoord v2;
  157. for (uint32_t ii = 0, num = _numIndices/3; ii < num; ++ii)
  158. {
  159. const uint16_t* indices = &_indices[ii*3];
  160. uint32_t i0 = indices[0];
  161. uint32_t i1 = indices[1];
  162. uint32_t i2 = indices[2];
  163. bgfx::vertexUnpack(&v0.m_x, bgfx::Attrib::Position, _decl, _vertices, i0);
  164. bgfx::vertexUnpack(&v0.m_u, bgfx::Attrib::TexCoord0, _decl, _vertices, i0);
  165. bgfx::vertexUnpack(&v1.m_x, bgfx::Attrib::Position, _decl, _vertices, i1);
  166. bgfx::vertexUnpack(&v1.m_u, bgfx::Attrib::TexCoord0, _decl, _vertices, i1);
  167. bgfx::vertexUnpack(&v2.m_x, bgfx::Attrib::Position, _decl, _vertices, i2);
  168. bgfx::vertexUnpack(&v2.m_u, bgfx::Attrib::TexCoord0, _decl, _vertices, i2);
  169. const float bax = v1.m_x - v0.m_x;
  170. const float bay = v1.m_y - v0.m_y;
  171. const float baz = v1.m_z - v0.m_z;
  172. const float bau = v1.m_u - v0.m_u;
  173. const float bav = v1.m_v - v0.m_v;
  174. const float cax = v2.m_x - v0.m_x;
  175. const float cay = v2.m_y - v0.m_y;
  176. const float caz = v2.m_z - v0.m_z;
  177. const float cau = v2.m_u - v0.m_u;
  178. const float cav = v2.m_v - v0.m_v;
  179. const float det = (bau * cav - bav * cau);
  180. const float invDet = 1.0f / det;
  181. const float tx = (bax * cav - cax * bav) * invDet;
  182. const float ty = (bay * cav - cay * bav) * invDet;
  183. const float tz = (baz * cav - caz * bav) * invDet;
  184. const float bx = (cax * bau - bax * cau) * invDet;
  185. const float by = (cay * bau - bay * cau) * invDet;
  186. const float bz = (caz * bau - baz * cau) * invDet;
  187. for (uint32_t jj = 0; jj < 3; ++jj)
  188. {
  189. float* tanu = &tangents[indices[jj]*6];
  190. float* tanv = &tanu[3];
  191. tanu[0] += tx;
  192. tanu[1] += ty;
  193. tanu[2] += tz;
  194. tanv[0] += bx;
  195. tanv[1] += by;
  196. tanv[2] += bz;
  197. }
  198. }
  199. for (uint32_t ii = 0; ii < _numVertices; ++ii)
  200. {
  201. const float* tanu = &tangents[ii*6];
  202. const float* tanv = &tangents[ii*6 + 3];
  203. float normal[4];
  204. bgfx::vertexUnpack(normal, bgfx::Attrib::Normal, _decl, _vertices, ii);
  205. float ndt = bx::vec3Dot(normal, tanu);
  206. float nxt[3];
  207. bx::vec3Cross(nxt, normal, tanu);
  208. float tmp[3];
  209. tmp[0] = tanu[0] - normal[0] * ndt;
  210. tmp[1] = tanu[1] - normal[1] * ndt;
  211. tmp[2] = tanu[2] - normal[2] * ndt;
  212. float tangent[4];
  213. bx::vec3Norm(tangent, tmp);
  214. tangent[3] = bx::vec3Dot(nxt, tanv) < 0.0f ? -1.0f : 1.0f;
  215. bgfx::vertexPack(tangent, true, bgfx::Attrib::Tangent, _decl, _vertices, ii);
  216. }
  217. delete [] tangents;
  218. }
  219. void write(bx::WriterI* _writer, const void* _vertices, uint32_t _numVertices, uint32_t _stride)
  220. {
  221. Sphere maxSphere;
  222. calcMaxBoundingSphere(maxSphere, _vertices, _numVertices, _stride);
  223. Sphere minSphere;
  224. calcMinBoundingSphere(minSphere, _vertices, _numVertices, _stride);
  225. if (minSphere.m_radius > maxSphere.m_radius)
  226. {
  227. bx::write(_writer, maxSphere);
  228. }
  229. else
  230. {
  231. bx::write(_writer, minSphere);
  232. }
  233. Aabb aabb;
  234. calcAabb(aabb, _vertices, _numVertices, _stride);
  235. bx::write(_writer, aabb);
  236. Obb obb;
  237. calcObb(obb, _vertices, _numVertices, _stride, s_obbSteps);
  238. bx::write(_writer, obb);
  239. }
  240. void write(bx::WriterI* _writer
  241. , const uint8_t* _vertices
  242. , uint32_t _numVertices
  243. , const bgfx::VertexDecl& _decl
  244. , const uint16_t* _indices
  245. , uint32_t _numIndices
  246. , const uint8_t* _compressedIndices
  247. , uint32_t _compressedSize
  248. , const std::string& _material
  249. , const PrimitiveArray& _primitives
  250. )
  251. {
  252. using namespace bx;
  253. using namespace bgfx;
  254. uint32_t stride = _decl.getStride();
  255. write(_writer, BGFX_CHUNK_MAGIC_VB);
  256. write(_writer, _vertices, _numVertices, stride);
  257. write(_writer, _decl);
  258. write(_writer, uint16_t(_numVertices) );
  259. write(_writer, _vertices, _numVertices*stride);
  260. if (NULL != _compressedIndices)
  261. {
  262. write(_writer, BGFX_CHUNK_MAGIC_IBC);
  263. write(_writer, _numIndices);
  264. write(_writer, _compressedSize);
  265. write(_writer, _compressedIndices, _compressedSize);
  266. }
  267. else
  268. {
  269. write(_writer, BGFX_CHUNK_MAGIC_IB);
  270. write(_writer, _numIndices);
  271. write(_writer, _indices, _numIndices*2);
  272. }
  273. write(_writer, BGFX_CHUNK_MAGIC_PRI);
  274. uint16_t nameLen = uint16_t(_material.size() );
  275. write(_writer, nameLen);
  276. write(_writer, _material.c_str(), nameLen);
  277. write(_writer, uint16_t(_primitives.size() ) );
  278. for (PrimitiveArray::const_iterator primIt = _primitives.begin(); primIt != _primitives.end(); ++primIt)
  279. {
  280. const Primitive& prim = *primIt;
  281. nameLen = uint16_t(prim.m_name.size() );
  282. write(_writer, nameLen);
  283. write(_writer, prim.m_name.c_str(), nameLen);
  284. write(_writer, prim.m_startIndex);
  285. write(_writer, prim.m_numIndices);
  286. write(_writer, prim.m_startVertex);
  287. write(_writer, prim.m_numVertices);
  288. write(_writer, &_vertices[prim.m_startVertex*stride], prim.m_numVertices, stride);
  289. }
  290. }
  291. void help(const char* _error = NULL)
  292. {
  293. if (NULL != _error)
  294. {
  295. fprintf(stderr, "Error:\n%s\n\n", _error);
  296. }
  297. fprintf(stderr
  298. , "geometryc, bgfx geometry compiler tool\n"
  299. "Copyright 2011-2015 Branimir Karadzic. All rights reserved.\n"
  300. "License: http://www.opensource.org/licenses/BSD-2-Clause\n\n"
  301. );
  302. fprintf(stderr
  303. , "Usage: geometryc -f <in> -o <out>\n"
  304. "\n"
  305. "Supported input file types:\n"
  306. " *.obj Wavefront\n"
  307. "\n"
  308. "Options:\n"
  309. " -f <file path> Input file path.\n"
  310. " -o <file path> Output file path.\n"
  311. " -s, --scale <num> Scale factor.\n"
  312. " --ccw Counter-clockwise winding order.\n"
  313. " --flipv Flip texture coordinate V.\n"
  314. " --obb <num> Number of steps for calculating oriented bounding box.\n"
  315. " Default value is 17. Less steps less precise OBB is.\n"
  316. " More steps slower calculation.\n"
  317. " --packnormal <num> Normal packing.\n"
  318. " 0 - unpacked 12 bytes (default).\n"
  319. " 1 - packed 4 bytes.\n"
  320. " --packuv <num> Texture coordinate packing.\n"
  321. " 0 - unpacked 8 bytes (default).\n"
  322. " 1 - packed 4 bytes.\n"
  323. " --tangent Calculate tangent vectors (packing mode is the same as normal).\n"
  324. " -c, --compress Compress indices.\n"
  325. "\n"
  326. "For additional information, see https://github.com/bkaradzic/bgfx\n"
  327. );
  328. }
  329. inline uint32_t rgbaToAbgr(uint8_t _r, uint8_t _g, uint8_t _b, uint8_t _a)
  330. {
  331. return (uint32_t(_r)<<0)
  332. | (uint32_t(_g)<<8)
  333. | (uint32_t(_b)<<16)
  334. | (uint32_t(_a)<<24)
  335. ;
  336. }
  337. struct GroupSortByMaterial
  338. {
  339. bool operator()(const Group& _lhs, const Group& _rhs)
  340. {
  341. return _lhs.m_material < _rhs.m_material;
  342. }
  343. };
  344. int main(int _argc, const char* _argv[])
  345. {
  346. bx::CommandLine cmdLine(_argc, _argv);
  347. const char* filePath = cmdLine.findOption('f');
  348. if (NULL == filePath)
  349. {
  350. help("Input file name must be specified.");
  351. return EXIT_FAILURE;
  352. }
  353. const char* outFilePath = cmdLine.findOption('o');
  354. if (NULL == outFilePath)
  355. {
  356. help("Output file name must be specified.");
  357. return EXIT_FAILURE;
  358. }
  359. float scale = 1.0f;
  360. const char* scaleArg = cmdLine.findOption('s', "scale");
  361. if (NULL != scaleArg)
  362. {
  363. scale = (float)atof(scaleArg);
  364. }
  365. bool compress = cmdLine.hasArg('c', "compress");
  366. cmdLine.hasArg(s_obbSteps, '\0', "obb");
  367. s_obbSteps = bx::uint32_min(bx::uint32_max(s_obbSteps, 1), 90);
  368. uint32_t packNormal = 0;
  369. cmdLine.hasArg(packNormal, '\0', "packnormal");
  370. uint32_t packUv = 0;
  371. cmdLine.hasArg(packUv, '\0', "packuv");
  372. bool ccw = cmdLine.hasArg("ccw");
  373. bool flipV = cmdLine.hasArg("flipv");
  374. bool hasTangent = cmdLine.hasArg("tangent");
  375. FILE* file = fopen(filePath, "r");
  376. if (NULL == file)
  377. {
  378. printf("Unable to open input file '%s'.", filePath);
  379. exit(EXIT_FAILURE);
  380. }
  381. int64_t parseElapsed = -bx::getHPCounter();
  382. int64_t triReorderElapsed = 0;
  383. uint32_t size = (uint32_t)fsize(file);
  384. char* data = new char[size+1];
  385. size = (uint32_t)fread(data, 1, size, file);
  386. data[size] = '\0';
  387. fclose(file);
  388. // https://en.wikipedia.org/wiki/Wavefront_.obj_file
  389. Vector3Array positions;
  390. Vector3Array normals;
  391. Vector3Array texcoords;
  392. Index3Map indexMap;
  393. TriangleArray triangles;
  394. GroupArray groups;
  395. uint32_t num = 0;
  396. Group group;
  397. group.m_startTriangle = 0;
  398. group.m_numTriangles = 0;
  399. char commandLine[2048];
  400. uint32_t len = sizeof(commandLine);
  401. int argc;
  402. char* argv[64];
  403. const char* next = data;
  404. do
  405. {
  406. next = bx::tokenizeCommandLine(next, commandLine, len, argc, argv, BX_COUNTOF(argv), '\n');
  407. if (0 < argc)
  408. {
  409. if (0 == strcmp(argv[0], "#") )
  410. {
  411. if (2 < argc
  412. && 0 == strcmp(argv[2], "polygons") )
  413. {
  414. }
  415. }
  416. else if (0 == strcmp(argv[0], "f") )
  417. {
  418. Triangle triangle;
  419. memset(&triangle, 0, sizeof(Triangle) );
  420. const int numNormals = (int)normals.size();
  421. const int numTexcoords = (int)texcoords.size();
  422. const int numPositions = (int)positions.size();
  423. for (uint32_t edge = 0, numEdges = argc-1; edge < numEdges; ++edge)
  424. {
  425. Index3 index;
  426. index.m_texcoord = 0;
  427. index.m_normal = 0;
  428. index.m_vertexIndex = -1;
  429. char* vertex = argv[edge+1];
  430. char* texcoord = strchr(vertex, '/');
  431. if (NULL != texcoord)
  432. {
  433. *texcoord++ = '\0';
  434. char* normal = strchr(texcoord, '/');
  435. if (NULL != normal)
  436. {
  437. *normal++ = '\0';
  438. const int nn = atoi(normal);
  439. index.m_normal = (nn < 0) ? nn+numNormals : nn-1;
  440. }
  441. const int tex = atoi(texcoord);
  442. index.m_texcoord = (tex < 0) ? tex+numTexcoords : tex-1;
  443. }
  444. const int pos = atoi(vertex);
  445. index.m_position = (pos < 0) ? pos+numPositions : pos-1;
  446. uint64_t hash0 = index.m_position;
  447. uint64_t hash1 = uint64_t(index.m_texcoord)<<20;
  448. uint64_t hash2 = uint64_t(index.m_normal)<<40;
  449. uint64_t hash = hash0^hash1^hash2;
  450. stl::pair<Index3Map::iterator, bool> result = indexMap.insert(stl::make_pair(hash, index) );
  451. if (!result.second)
  452. {
  453. Index3& oldIndex = result.first->second;
  454. BX_UNUSED(oldIndex);
  455. BX_CHECK(oldIndex.m_position == index.m_position
  456. && oldIndex.m_texcoord == index.m_texcoord
  457. && oldIndex.m_normal == index.m_normal
  458. , "Hash collision!"
  459. );
  460. }
  461. switch (edge)
  462. {
  463. case 0:
  464. case 1:
  465. case 2:
  466. triangle.m_index[edge] = hash;
  467. if (2 == edge)
  468. {
  469. if (ccw)
  470. {
  471. std::swap(triangle.m_index[1], triangle.m_index[2]);
  472. }
  473. triangles.push_back(triangle);
  474. }
  475. break;
  476. default:
  477. if (ccw)
  478. {
  479. triangle.m_index[2] = triangle.m_index[1];
  480. triangle.m_index[1] = hash;
  481. }
  482. else
  483. {
  484. triangle.m_index[1] = triangle.m_index[2];
  485. triangle.m_index[2] = hash;
  486. }
  487. triangles.push_back(triangle);
  488. break;
  489. }
  490. }
  491. }
  492. else if (0 == strcmp(argv[0], "g") )
  493. {
  494. EXPECT(1 < argc);
  495. group.m_name = argv[1];
  496. }
  497. else if (*argv[0] == 'v')
  498. {
  499. group.m_numTriangles = (uint32_t)(triangles.size() ) - group.m_startTriangle;
  500. if (0 < group.m_numTriangles)
  501. {
  502. groups.push_back(group);
  503. group.m_startTriangle = (uint32_t)(triangles.size() );
  504. group.m_numTriangles = 0;
  505. }
  506. if (0 == strcmp(argv[0], "vn") )
  507. {
  508. Vector3 normal;
  509. normal.x = (float)atof(argv[1]);
  510. normal.y = (float)atof(argv[2]);
  511. normal.z = (float)atof(argv[3]);
  512. normals.push_back(normal);
  513. }
  514. else if (0 == strcmp(argv[0], "vp") )
  515. {
  516. static bool once = true;
  517. if (once)
  518. {
  519. once = false;
  520. printf("warning: 'parameter space vertices' are unsupported.\n");
  521. }
  522. }
  523. else if (0 == strcmp(argv[0], "vt") )
  524. {
  525. Vector3 texcoord;
  526. texcoord.x = (float)atof(argv[1]);
  527. texcoord.y = 0.0f;
  528. texcoord.z = 0.0f;
  529. switch (argc)
  530. {
  531. case 4:
  532. texcoord.z = (float)atof(argv[3]);
  533. // fallthrough
  534. case 3:
  535. texcoord.y = (float)atof(argv[2]);
  536. break;
  537. default:
  538. break;
  539. }
  540. texcoords.push_back(texcoord);
  541. }
  542. else
  543. {
  544. float px = (float)atof(argv[1]);
  545. float py = (float)atof(argv[2]);
  546. float pz = (float)atof(argv[3]);
  547. float pw = 1.0f;
  548. if (argc > 4)
  549. {
  550. pw = (float)atof(argv[4]);
  551. }
  552. float invW = scale/pw;
  553. px *= invW;
  554. py *= invW;
  555. pz *= invW;
  556. Vector3 pos;
  557. pos.x = px;
  558. pos.y = py;
  559. pos.z = pz;
  560. positions.push_back(pos);
  561. }
  562. }
  563. else if (0 == strcmp(argv[0], "usemtl") )
  564. {
  565. std::string material(argv[1]);
  566. if (material != group.m_material)
  567. {
  568. group.m_numTriangles = (uint32_t)(triangles.size() ) - group.m_startTriangle;
  569. if (0 < group.m_numTriangles)
  570. {
  571. groups.push_back(group);
  572. group.m_startTriangle = (uint32_t)(triangles.size() );
  573. group.m_numTriangles = 0;
  574. }
  575. }
  576. group.m_material = material;
  577. }
  578. // unsupported tags
  579. // else if (0 == strcmp(argv[0], "mtllib") )
  580. // {
  581. // }
  582. // else if (0 == strcmp(argv[0], "o") )
  583. // {
  584. // }
  585. // else if (0 == strcmp(argv[0], "s") )
  586. // {
  587. // }
  588. }
  589. ++num;
  590. }
  591. while ('\0' != *next);
  592. group.m_numTriangles = (uint32_t)(triangles.size() ) - group.m_startTriangle;
  593. if (0 < group.m_numTriangles)
  594. {
  595. groups.push_back(group);
  596. group.m_startTriangle = (uint32_t)(triangles.size() );
  597. group.m_numTriangles = 0;
  598. }
  599. delete [] data;
  600. int64_t now = bx::getHPCounter();
  601. parseElapsed += now;
  602. int64_t convertElapsed = -now;
  603. std::sort(groups.begin(), groups.end(), GroupSortByMaterial() );
  604. bool hasColor = false;
  605. bool hasNormal;
  606. bool hasTexcoord;
  607. {
  608. Index3Map::const_iterator it = indexMap.begin();
  609. hasNormal = 0 != it->second.m_normal;
  610. hasTexcoord = 0 != it->second.m_texcoord;
  611. if (!hasTexcoord
  612. && texcoords.size() == positions.size() )
  613. {
  614. hasTexcoord = true;
  615. for (Index3Map::iterator it = indexMap.begin(), itEnd = indexMap.end(); it != itEnd; ++it)
  616. {
  617. it->second.m_texcoord = it->second.m_position;
  618. }
  619. }
  620. if (!hasNormal
  621. && normals.size() == positions.size() )
  622. {
  623. hasNormal = true;
  624. for (Index3Map::iterator it = indexMap.begin(), itEnd = indexMap.end(); it != itEnd; ++it)
  625. {
  626. it->second.m_normal = it->second.m_position;
  627. }
  628. }
  629. }
  630. bgfx::VertexDecl decl;
  631. decl.begin();
  632. decl.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float);
  633. if (hasColor)
  634. {
  635. decl.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true);
  636. }
  637. if (hasTexcoord)
  638. {
  639. switch (packUv)
  640. {
  641. default:
  642. case 0:
  643. decl.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float);
  644. break;
  645. case 1:
  646. decl.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Half);
  647. break;
  648. }
  649. }
  650. if (hasNormal)
  651. {
  652. hasTangent &= hasTexcoord;
  653. switch (packNormal)
  654. {
  655. default:
  656. case 0:
  657. decl.add(bgfx::Attrib::Normal, 3, bgfx::AttribType::Float);
  658. if (hasTangent)
  659. {
  660. decl.add(bgfx::Attrib::Tangent, 4, bgfx::AttribType::Float);
  661. }
  662. break;
  663. case 1:
  664. decl.add(bgfx::Attrib::Normal, 4, bgfx::AttribType::Uint8, true, true);
  665. if (hasTangent)
  666. {
  667. decl.add(bgfx::Attrib::Tangent, 4, bgfx::AttribType::Uint8, true, true);
  668. }
  669. break;
  670. }
  671. }
  672. decl.end();
  673. uint32_t stride = decl.getStride();
  674. uint8_t* vertexData = new uint8_t[triangles.size() * 3 * stride];
  675. uint16_t* indexData = new uint16_t[triangles.size() * 3];
  676. int32_t numVertices = 0;
  677. int32_t numIndices = 0;
  678. int32_t numPrimitives = 0;
  679. uint8_t* vertices = vertexData;
  680. uint16_t* indices = indexData;
  681. std::string material = groups.begin()->m_material;
  682. PrimitiveArray primitives;
  683. bx::CrtFileWriter writer;
  684. if (0 != writer.open(outFilePath) )
  685. {
  686. printf("Unable to open output file '%s'.", outFilePath);
  687. exit(EXIT_FAILURE);
  688. }
  689. Primitive prim;
  690. prim.m_startVertex = 0;
  691. prim.m_startIndex = 0;
  692. uint32_t positionOffset = decl.getOffset(bgfx::Attrib::Position);
  693. uint32_t color0Offset = decl.getOffset(bgfx::Attrib::Color0);
  694. bx::CrtAllocator crtAllocator;
  695. bx::MemoryBlock memBlock(&crtAllocator);
  696. uint32_t ii = 0;
  697. for (GroupArray::const_iterator groupIt = groups.begin(); groupIt != groups.end(); ++groupIt, ++ii)
  698. {
  699. for (uint32_t tri = groupIt->m_startTriangle, end = tri + groupIt->m_numTriangles; tri < end; ++tri)
  700. {
  701. if (material != groupIt->m_material
  702. || 65533 < numVertices)
  703. {
  704. prim.m_numVertices = numVertices - prim.m_startVertex;
  705. prim.m_numIndices = numIndices - prim.m_startIndex;
  706. if (0 < prim.m_numVertices)
  707. {
  708. primitives.push_back(prim);
  709. }
  710. if (hasTangent)
  711. {
  712. calcTangents(vertexData, numVertices, decl, indexData, numIndices);
  713. }
  714. bx::MemoryWriter memWriter(&memBlock);
  715. triReorderElapsed -= bx::getHPCounter();
  716. for (PrimitiveArray::const_iterator primIt = primitives.begin(); primIt != primitives.end(); ++primIt)
  717. {
  718. const Primitive& prim = *primIt;
  719. triangleReorder(indexData + prim.m_startIndex, prim.m_numIndices, numVertices, 32);
  720. if (compress)
  721. {
  722. triangleCompress(&memWriter
  723. , indexData + prim.m_startIndex
  724. , prim.m_numIndices
  725. , vertexData + prim.m_startVertex
  726. , numVertices
  727. , stride
  728. );
  729. }
  730. }
  731. triReorderElapsed += bx::getHPCounter();
  732. write(&writer
  733. , vertexData
  734. , numVertices
  735. , decl
  736. , indexData
  737. , numIndices
  738. , (uint8_t*)memBlock.more()
  739. , memBlock.getSize()
  740. , material
  741. , primitives
  742. );
  743. primitives.clear();
  744. for (Index3Map::iterator indexIt = indexMap.begin(); indexIt != indexMap.end(); ++indexIt)
  745. {
  746. indexIt->second.m_vertexIndex = -1;
  747. }
  748. vertices = vertexData;
  749. indices = indexData;
  750. numVertices = 0;
  751. numIndices = 0;
  752. prim.m_startVertex = 0;
  753. prim.m_startIndex = 0;
  754. ++numPrimitives;
  755. material = groupIt->m_material;
  756. }
  757. Triangle& triangle = triangles[tri];
  758. for (uint32_t edge = 0; edge < 3; ++edge)
  759. {
  760. uint64_t hash = triangle.m_index[edge];
  761. Index3& index = indexMap[hash];
  762. if (index.m_vertexIndex == -1)
  763. {
  764. index.m_vertexIndex = numVertices++;
  765. float* position = (float*)(vertices + positionOffset);
  766. memcpy(position, &positions[index.m_position], 3*sizeof(float) );
  767. if (hasColor)
  768. {
  769. uint32_t* color0 = (uint32_t*)(vertices + color0Offset);
  770. *color0 = rgbaToAbgr(numVertices%255, numIndices%255, 0, 0xff);
  771. }
  772. if (hasTexcoord)
  773. {
  774. float uv[2];
  775. memcpy(uv, &texcoords[index.m_texcoord], 2*sizeof(float) );
  776. if (flipV)
  777. {
  778. uv[1] = -uv[1];
  779. }
  780. bgfx::vertexPack(uv, true, bgfx::Attrib::TexCoord0, decl, vertices);
  781. }
  782. if (hasNormal)
  783. {
  784. float normal[4];
  785. bx::vec3Norm(normal, (float*)&normals[index.m_normal]);
  786. bgfx::vertexPack(normal, true, bgfx::Attrib::Normal, decl, vertices);
  787. }
  788. vertices += stride;
  789. }
  790. *indices++ = (uint16_t)index.m_vertexIndex;
  791. ++numIndices;
  792. }
  793. }
  794. if (0 < numVertices)
  795. {
  796. prim.m_numVertices = numVertices - prim.m_startVertex;
  797. prim.m_numIndices = numIndices - prim.m_startIndex;
  798. prim.m_name = groupIt->m_name;
  799. primitives.push_back(prim);
  800. prim.m_startVertex = numVertices;
  801. prim.m_startIndex = numIndices;
  802. }
  803. BX_TRACE("%3d: s %5d, n %5d, %s\n"
  804. , ii
  805. , groupIt->m_startTriangle
  806. , groupIt->m_numTriangles
  807. , groupIt->m_material.c_str()
  808. );
  809. }
  810. if (0 < primitives.size() )
  811. {
  812. if (hasTangent)
  813. {
  814. calcTangents(vertexData, numVertices, decl, indexData, numIndices);
  815. }
  816. bx::MemoryWriter memWriter(&memBlock);
  817. triReorderElapsed -= bx::getHPCounter();
  818. for (PrimitiveArray::const_iterator primIt = primitives.begin(); primIt != primitives.end(); ++primIt)
  819. {
  820. const Primitive& prim = *primIt;
  821. triangleReorder(indexData + prim.m_startIndex, prim.m_numIndices, numVertices, 32);
  822. if (compress)
  823. {
  824. triangleCompress(&memWriter
  825. , indexData + prim.m_startIndex
  826. , prim.m_numIndices
  827. , vertexData + prim.m_startVertex
  828. , numVertices
  829. , stride
  830. );
  831. }
  832. }
  833. triReorderElapsed += bx::getHPCounter();
  834. write(&writer
  835. , vertexData
  836. , numVertices
  837. , decl
  838. , indexData
  839. , numIndices
  840. , (uint8_t*)memBlock.more()
  841. , memBlock.getSize()
  842. , material
  843. , primitives
  844. );
  845. }
  846. printf("size: %d\n", uint32_t(writer.seek() ) );
  847. writer.close();
  848. delete [] indexData;
  849. delete [] vertexData;
  850. now = bx::getHPCounter();
  851. convertElapsed += now;
  852. printf("parse %f [s]\ntri reorder %f [s]\nconvert %f [s]\n# %d, g %d, p %d, v %d, i %d\n"
  853. , double(parseElapsed)/bx::getHPFrequency()
  854. , double(triReorderElapsed)/bx::getHPFrequency()
  855. , double(convertElapsed)/bx::getHPFrequency()
  856. , num
  857. , uint32_t(groups.size() )
  858. , numPrimitives
  859. , numVertices
  860. , numIndices
  861. );
  862. return EXIT_SUCCESS;
  863. }