geometryc.cpp 26 KB

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