geometryc.cpp 24 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  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/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 = -1;
  427. index.m_normal = -1;
  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. // https://en.wikipedia.org/wiki/Wavefront_.obj_file#Vertex_Normal_Indices_Without_Texture_Coordinate_Indices
  442. if(*texcoord != '\0')
  443. {
  444. const int tex = atoi(texcoord);
  445. index.m_texcoord = (tex < 0) ? tex+numTexcoords : tex-1;
  446. }
  447. }
  448. const int pos = atoi(vertex);
  449. index.m_position = (pos < 0) ? pos+numPositions : pos-1;
  450. uint64_t hash0 = index.m_position;
  451. uint64_t hash1 = uint64_t(index.m_texcoord)<<20;
  452. uint64_t hash2 = uint64_t(index.m_normal)<<40;
  453. uint64_t hash = hash0^hash1^hash2;
  454. stl::pair<Index3Map::iterator, bool> result = indexMap.insert(stl::make_pair(hash, index) );
  455. if (!result.second)
  456. {
  457. Index3& oldIndex = result.first->second;
  458. BX_UNUSED(oldIndex);
  459. BX_CHECK(oldIndex.m_position == index.m_position
  460. && oldIndex.m_texcoord == index.m_texcoord
  461. && oldIndex.m_normal == index.m_normal
  462. , "Hash collision!"
  463. );
  464. }
  465. switch (edge)
  466. {
  467. case 0:
  468. case 1:
  469. case 2:
  470. triangle.m_index[edge] = hash;
  471. if (2 == edge)
  472. {
  473. if (ccw)
  474. {
  475. std::swap(triangle.m_index[1], triangle.m_index[2]);
  476. }
  477. triangles.push_back(triangle);
  478. }
  479. break;
  480. default:
  481. if (ccw)
  482. {
  483. triangle.m_index[2] = triangle.m_index[1];
  484. triangle.m_index[1] = hash;
  485. }
  486. else
  487. {
  488. triangle.m_index[1] = triangle.m_index[2];
  489. triangle.m_index[2] = hash;
  490. }
  491. triangles.push_back(triangle);
  492. break;
  493. }
  494. }
  495. }
  496. else if (0 == strcmp(argv[0], "g") )
  497. {
  498. EXPECT(1 < argc);
  499. group.m_name = argv[1];
  500. }
  501. else if (*argv[0] == 'v')
  502. {
  503. group.m_numTriangles = (uint32_t)(triangles.size() ) - group.m_startTriangle;
  504. if (0 < group.m_numTriangles)
  505. {
  506. groups.push_back(group);
  507. group.m_startTriangle = (uint32_t)(triangles.size() );
  508. group.m_numTriangles = 0;
  509. }
  510. if (0 == strcmp(argv[0], "vn") )
  511. {
  512. Vector3 normal;
  513. normal.x = (float)atof(argv[1]);
  514. normal.y = (float)atof(argv[2]);
  515. normal.z = (float)atof(argv[3]);
  516. normals.push_back(normal);
  517. }
  518. else if (0 == strcmp(argv[0], "vp") )
  519. {
  520. static bool once = true;
  521. if (once)
  522. {
  523. once = false;
  524. printf("warning: 'parameter space vertices' are unsupported.\n");
  525. }
  526. }
  527. else if (0 == strcmp(argv[0], "vt") )
  528. {
  529. Vector3 texcoord;
  530. texcoord.x = (float)atof(argv[1]);
  531. texcoord.y = 0.0f;
  532. texcoord.z = 0.0f;
  533. switch (argc)
  534. {
  535. case 4:
  536. texcoord.z = (float)atof(argv[3]);
  537. // fallthrough
  538. case 3:
  539. texcoord.y = (float)atof(argv[2]);
  540. break;
  541. default:
  542. break;
  543. }
  544. texcoords.push_back(texcoord);
  545. }
  546. else
  547. {
  548. float px = (float)atof(argv[1]);
  549. float py = (float)atof(argv[2]);
  550. float pz = (float)atof(argv[3]);
  551. float pw = 1.0f;
  552. if (argc > 4)
  553. {
  554. pw = (float)atof(argv[4]);
  555. }
  556. float invW = scale/pw;
  557. px *= invW;
  558. py *= invW;
  559. pz *= invW;
  560. Vector3 pos;
  561. pos.x = px;
  562. pos.y = py;
  563. pos.z = pz;
  564. positions.push_back(pos);
  565. }
  566. }
  567. else if (0 == strcmp(argv[0], "usemtl") )
  568. {
  569. std::string material(argv[1]);
  570. if (material != group.m_material)
  571. {
  572. group.m_numTriangles = (uint32_t)(triangles.size() ) - group.m_startTriangle;
  573. if (0 < group.m_numTriangles)
  574. {
  575. groups.push_back(group);
  576. group.m_startTriangle = (uint32_t)(triangles.size() );
  577. group.m_numTriangles = 0;
  578. }
  579. }
  580. group.m_material = material;
  581. }
  582. // unsupported tags
  583. // else if (0 == strcmp(argv[0], "mtllib") )
  584. // {
  585. // }
  586. // else if (0 == strcmp(argv[0], "o") )
  587. // {
  588. // }
  589. // else if (0 == strcmp(argv[0], "s") )
  590. // {
  591. // }
  592. }
  593. ++num;
  594. }
  595. while ('\0' != *next);
  596. group.m_numTriangles = (uint32_t)(triangles.size() ) - group.m_startTriangle;
  597. if (0 < group.m_numTriangles)
  598. {
  599. groups.push_back(group);
  600. group.m_startTriangle = (uint32_t)(triangles.size() );
  601. group.m_numTriangles = 0;
  602. }
  603. delete [] data;
  604. int64_t now = bx::getHPCounter();
  605. parseElapsed += now;
  606. int64_t convertElapsed = -now;
  607. std::sort(groups.begin(), groups.end(), GroupSortByMaterial() );
  608. bool hasColor = false;
  609. bool hasNormal;
  610. bool hasTexcoord;
  611. {
  612. Index3Map::const_iterator it = indexMap.begin();
  613. hasNormal = -1 != it->second.m_normal;
  614. hasTexcoord = -1 != it->second.m_texcoord;
  615. if (!hasTexcoord
  616. && texcoords.size() == positions.size() )
  617. {
  618. hasTexcoord = true;
  619. for (Index3Map::iterator jt = indexMap.begin(), jtEnd = indexMap.end(); jt != jtEnd; ++jt)
  620. {
  621. jt->second.m_texcoord = jt->second.m_position;
  622. }
  623. }
  624. if (!hasNormal
  625. && normals.size() == positions.size() )
  626. {
  627. hasNormal = true;
  628. for (Index3Map::iterator jt = indexMap.begin(), jtEnd = indexMap.end(); jt != jtEnd; ++jt)
  629. {
  630. jt->second.m_normal = jt->second.m_position;
  631. }
  632. }
  633. }
  634. bgfx::VertexDecl decl;
  635. decl.begin();
  636. decl.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float);
  637. if (hasColor)
  638. {
  639. decl.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true);
  640. }
  641. if (hasTexcoord)
  642. {
  643. switch (packUv)
  644. {
  645. default:
  646. case 0:
  647. decl.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float);
  648. break;
  649. case 1:
  650. decl.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Half);
  651. break;
  652. }
  653. }
  654. if (hasNormal)
  655. {
  656. hasTangent &= hasTexcoord;
  657. switch (packNormal)
  658. {
  659. default:
  660. case 0:
  661. decl.add(bgfx::Attrib::Normal, 3, bgfx::AttribType::Float);
  662. if (hasTangent)
  663. {
  664. decl.add(bgfx::Attrib::Tangent, 4, bgfx::AttribType::Float);
  665. }
  666. break;
  667. case 1:
  668. decl.add(bgfx::Attrib::Normal, 4, bgfx::AttribType::Uint8, true, true);
  669. if (hasTangent)
  670. {
  671. decl.add(bgfx::Attrib::Tangent, 4, bgfx::AttribType::Uint8, true, true);
  672. }
  673. break;
  674. }
  675. }
  676. decl.end();
  677. uint32_t stride = decl.getStride();
  678. uint8_t* vertexData = new uint8_t[triangles.size() * 3 * stride];
  679. uint16_t* indexData = new uint16_t[triangles.size() * 3];
  680. int32_t numVertices = 0;
  681. int32_t numIndices = 0;
  682. int32_t numPrimitives = 0;
  683. uint8_t* vertices = vertexData;
  684. uint16_t* indices = indexData;
  685. std::string material = groups.begin()->m_material;
  686. PrimitiveArray primitives;
  687. bx::CrtFileWriter writer;
  688. if (0 != writer.open(outFilePath) )
  689. {
  690. printf("Unable to open output file '%s'.", outFilePath);
  691. exit(EXIT_FAILURE);
  692. }
  693. Primitive prim;
  694. prim.m_startVertex = 0;
  695. prim.m_startIndex = 0;
  696. uint32_t positionOffset = decl.getOffset(bgfx::Attrib::Position);
  697. uint32_t color0Offset = decl.getOffset(bgfx::Attrib::Color0);
  698. bx::CrtAllocator crtAllocator;
  699. bx::MemoryBlock memBlock(&crtAllocator);
  700. uint32_t ii = 0;
  701. for (GroupArray::const_iterator groupIt = groups.begin(); groupIt != groups.end(); ++groupIt, ++ii)
  702. {
  703. for (uint32_t tri = groupIt->m_startTriangle, end = tri + groupIt->m_numTriangles; tri < end; ++tri)
  704. {
  705. if (material != groupIt->m_material
  706. || 65533 < numVertices)
  707. {
  708. prim.m_numVertices = numVertices - prim.m_startVertex;
  709. prim.m_numIndices = numIndices - prim.m_startIndex;
  710. if (0 < prim.m_numVertices)
  711. {
  712. primitives.push_back(prim);
  713. }
  714. if (hasTangent)
  715. {
  716. calcTangents(vertexData, numVertices, decl, indexData, numIndices);
  717. }
  718. bx::MemoryWriter memWriter(&memBlock);
  719. triReorderElapsed -= bx::getHPCounter();
  720. for (PrimitiveArray::const_iterator primIt = primitives.begin(); primIt != primitives.end(); ++primIt)
  721. {
  722. const Primitive& prim1 = *primIt;
  723. triangleReorder(indexData + prim1.m_startIndex, prim1.m_numIndices, numVertices, 32);
  724. if (compress)
  725. {
  726. triangleCompress(&memWriter
  727. , indexData + prim1.m_startIndex
  728. , prim1.m_numIndices
  729. , vertexData + prim1.m_startVertex
  730. , numVertices
  731. , stride
  732. );
  733. }
  734. }
  735. triReorderElapsed += bx::getHPCounter();
  736. write(&writer
  737. , vertexData
  738. , numVertices
  739. , decl
  740. , indexData
  741. , numIndices
  742. , (uint8_t*)memBlock.more()
  743. , memBlock.getSize()
  744. , material
  745. , primitives
  746. );
  747. primitives.clear();
  748. for (Index3Map::iterator indexIt = indexMap.begin(); indexIt != indexMap.end(); ++indexIt)
  749. {
  750. indexIt->second.m_vertexIndex = -1;
  751. }
  752. vertices = vertexData;
  753. indices = indexData;
  754. numVertices = 0;
  755. numIndices = 0;
  756. prim.m_startVertex = 0;
  757. prim.m_startIndex = 0;
  758. ++numPrimitives;
  759. material = groupIt->m_material;
  760. }
  761. Triangle& triangle = triangles[tri];
  762. for (uint32_t edge = 0; edge < 3; ++edge)
  763. {
  764. uint64_t hash = triangle.m_index[edge];
  765. Index3& index = indexMap[hash];
  766. if (index.m_vertexIndex == -1)
  767. {
  768. index.m_vertexIndex = numVertices++;
  769. float* position = (float*)(vertices + positionOffset);
  770. memcpy(position, &positions[index.m_position], 3*sizeof(float) );
  771. if (hasColor)
  772. {
  773. uint32_t* color0 = (uint32_t*)(vertices + color0Offset);
  774. *color0 = rgbaToAbgr(numVertices%255, numIndices%255, 0, 0xff);
  775. }
  776. if (hasTexcoord)
  777. {
  778. float uv[2];
  779. memcpy(uv, &texcoords[index.m_texcoord], 2*sizeof(float) );
  780. if (flipV)
  781. {
  782. uv[1] = -uv[1];
  783. }
  784. bgfx::vertexPack(uv, true, bgfx::Attrib::TexCoord0, decl, vertices);
  785. }
  786. if (hasNormal)
  787. {
  788. float normal[4];
  789. bx::vec3Norm(normal, (float*)&normals[index.m_normal]);
  790. bgfx::vertexPack(normal, true, bgfx::Attrib::Normal, decl, vertices);
  791. }
  792. vertices += stride;
  793. }
  794. *indices++ = (uint16_t)index.m_vertexIndex;
  795. ++numIndices;
  796. }
  797. }
  798. if (0 < numVertices)
  799. {
  800. prim.m_numVertices = numVertices - prim.m_startVertex;
  801. prim.m_numIndices = numIndices - prim.m_startIndex;
  802. prim.m_name = groupIt->m_name;
  803. primitives.push_back(prim);
  804. prim.m_startVertex = numVertices;
  805. prim.m_startIndex = numIndices;
  806. }
  807. BX_TRACE("%3d: s %5d, n %5d, %s\n"
  808. , ii
  809. , groupIt->m_startTriangle
  810. , groupIt->m_numTriangles
  811. , groupIt->m_material.c_str()
  812. );
  813. }
  814. if (0 < primitives.size() )
  815. {
  816. if (hasTangent)
  817. {
  818. calcTangents(vertexData, numVertices, decl, indexData, numIndices);
  819. }
  820. bx::MemoryWriter memWriter(&memBlock);
  821. triReorderElapsed -= bx::getHPCounter();
  822. for (PrimitiveArray::const_iterator primIt = primitives.begin(); primIt != primitives.end(); ++primIt)
  823. {
  824. const Primitive& prim1 = *primIt;
  825. triangleReorder(indexData + prim1.m_startIndex, prim1.m_numIndices, numVertices, 32);
  826. if (compress)
  827. {
  828. triangleCompress(&memWriter
  829. , indexData + prim1.m_startIndex
  830. , prim1.m_numIndices
  831. , vertexData + prim1.m_startVertex
  832. , numVertices
  833. , stride
  834. );
  835. }
  836. }
  837. triReorderElapsed += bx::getHPCounter();
  838. write(&writer
  839. , vertexData
  840. , numVertices
  841. , decl
  842. , indexData
  843. , numIndices
  844. , (uint8_t*)memBlock.more()
  845. , memBlock.getSize()
  846. , material
  847. , primitives
  848. );
  849. }
  850. printf("size: %d\n", uint32_t(writer.seek() ) );
  851. writer.close();
  852. delete [] indexData;
  853. delete [] vertexData;
  854. now = bx::getHPCounter();
  855. convertElapsed += now;
  856. printf("parse %f [s]\ntri reorder %f [s]\nconvert %f [s]\n# %d, g %d, p %d, v %d, i %d\n"
  857. , double(parseElapsed)/bx::getHPFrequency()
  858. , double(triReorderElapsed)/bx::getHPFrequency()
  859. , double(convertElapsed)/bx::getHPFrequency()
  860. , num
  861. , uint32_t(groups.size() )
  862. , numPrimitives
  863. , numVertices
  864. , numIndices
  865. );
  866. return EXIT_SUCCESS;
  867. }