bgfx_utils.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. /*
  2. * Copyright 2011-2015 Branimir Karadzic. All rights reserved.
  3. * License: http://www.opensource.org/licenses/BSD-2-Clause
  4. */
  5. #include <string.h> // strlen
  6. #include "common.h"
  7. #include <tinystl/allocator.h>
  8. #include <tinystl/vector.h>
  9. #include <tinystl/string.h>
  10. namespace stl = tinystl;
  11. #include <bgfx.h>
  12. #include <bx/readerwriter.h>
  13. #include <bx/fpumath.h>
  14. #include "entry/entry.h"
  15. #include <ib-compress/indexbufferdecompression.h>
  16. #include "bgfx_utils.h"
  17. void* load(bx::FileReaderI* _reader, const char* _filePath, uint32_t* _size)
  18. {
  19. if (0 == bx::open(_reader, _filePath) )
  20. {
  21. uint32_t size = (uint32_t)bx::getSize(_reader);
  22. void* data = malloc(size);
  23. bx::read(_reader, data, size);
  24. bx::close(_reader);
  25. if (NULL != _size)
  26. {
  27. *_size = size;
  28. }
  29. return data;
  30. }
  31. if (NULL != _size)
  32. {
  33. *_size = 0;
  34. }
  35. return NULL;
  36. }
  37. void* load(const char* _filePath, uint32_t* _size)
  38. {
  39. return load(entry::getFileReader(), _filePath, _size);
  40. }
  41. static const bgfx::Memory* loadMem(bx::FileReaderI* _reader, const char* _filePath)
  42. {
  43. if (0 == bx::open(_reader, _filePath) )
  44. {
  45. uint32_t size = (uint32_t)bx::getSize(_reader);
  46. const bgfx::Memory* mem = bgfx::alloc(size+1);
  47. bx::read(_reader, mem->data, size);
  48. bx::close(_reader);
  49. mem->data[mem->size-1] = '\0';
  50. return mem;
  51. }
  52. return NULL;
  53. }
  54. static bgfx::ShaderHandle loadShader(bx::FileReaderI* _reader, const char* _name)
  55. {
  56. char filePath[512];
  57. const char* shaderPath = "shaders/dx9/";
  58. switch (bgfx::getRendererType() )
  59. {
  60. case bgfx::RendererType::Direct3D11:
  61. shaderPath = "shaders/dx11/";
  62. break;
  63. case bgfx::RendererType::OpenGL:
  64. shaderPath = "shaders/glsl/";
  65. break;
  66. case bgfx::RendererType::OpenGLES:
  67. shaderPath = "shaders/gles/";
  68. break;
  69. default:
  70. break;
  71. }
  72. strcpy(filePath, shaderPath);
  73. strcat(filePath, _name);
  74. strcat(filePath, ".bin");
  75. return bgfx::createShader(loadMem(_reader, filePath) );
  76. }
  77. bgfx::ShaderHandle loadShader(const char* _name)
  78. {
  79. return loadShader(entry::getFileReader(), _name);
  80. }
  81. bgfx::ProgramHandle loadProgram(bx::FileReaderI* _reader, const char* _vsName, const char* _fsName)
  82. {
  83. bgfx::ShaderHandle vsh = loadShader(_reader, _vsName);
  84. bgfx::ShaderHandle fsh = loadShader(_reader, _fsName);
  85. return bgfx::createProgram(vsh, fsh, true /* destroy shaders when program is destroyed */);
  86. }
  87. bgfx::ProgramHandle loadProgram(const char* _vsName, const char* _fsName)
  88. {
  89. return loadProgram(entry::getFileReader(), _vsName, _fsName);
  90. }
  91. bgfx::TextureHandle loadTexture(bx::FileReaderI* _reader, const char* _name, uint32_t _flags, uint8_t _skip, bgfx::TextureInfo* _info)
  92. {
  93. char filePath[512];
  94. strcpy(filePath, "textures/");
  95. strcat(filePath, _name);
  96. const bgfx::Memory* mem = loadMem(_reader, filePath);
  97. return bgfx::createTexture(mem, _flags, _skip, _info);
  98. }
  99. bgfx::TextureHandle loadTexture(const char* _name, uint32_t _flags, uint8_t _skip, bgfx::TextureInfo* _info)
  100. {
  101. return loadTexture(entry::getFileReader(), _name, _flags, _skip, _info);
  102. }
  103. void calcTangents(void* _vertices, uint16_t _numVertices, bgfx::VertexDecl _decl, const uint16_t* _indices, uint32_t _numIndices)
  104. {
  105. struct PosTexcoord
  106. {
  107. float m_x;
  108. float m_y;
  109. float m_z;
  110. float m_pad0;
  111. float m_u;
  112. float m_v;
  113. float m_pad1;
  114. float m_pad2;
  115. };
  116. float* tangents = new float[6*_numVertices];
  117. memset(tangents, 0, 6*_numVertices*sizeof(float) );
  118. PosTexcoord v0;
  119. PosTexcoord v1;
  120. PosTexcoord v2;
  121. for (uint32_t ii = 0, num = _numIndices/3; ii < num; ++ii)
  122. {
  123. const uint16_t* indices = &_indices[ii*3];
  124. uint32_t i0 = indices[0];
  125. uint32_t i1 = indices[1];
  126. uint32_t i2 = indices[2];
  127. bgfx::vertexUnpack(&v0.m_x, bgfx::Attrib::Position, _decl, _vertices, i0);
  128. bgfx::vertexUnpack(&v0.m_u, bgfx::Attrib::TexCoord0, _decl, _vertices, i0);
  129. bgfx::vertexUnpack(&v1.m_x, bgfx::Attrib::Position, _decl, _vertices, i1);
  130. bgfx::vertexUnpack(&v1.m_u, bgfx::Attrib::TexCoord0, _decl, _vertices, i1);
  131. bgfx::vertexUnpack(&v2.m_x, bgfx::Attrib::Position, _decl, _vertices, i2);
  132. bgfx::vertexUnpack(&v2.m_u, bgfx::Attrib::TexCoord0, _decl, _vertices, i2);
  133. const float bax = v1.m_x - v0.m_x;
  134. const float bay = v1.m_y - v0.m_y;
  135. const float baz = v1.m_z - v0.m_z;
  136. const float bau = v1.m_u - v0.m_u;
  137. const float bav = v1.m_v - v0.m_v;
  138. const float cax = v2.m_x - v0.m_x;
  139. const float cay = v2.m_y - v0.m_y;
  140. const float caz = v2.m_z - v0.m_z;
  141. const float cau = v2.m_u - v0.m_u;
  142. const float cav = v2.m_v - v0.m_v;
  143. const float det = (bau * cav - bav * cau);
  144. const float invDet = 1.0f / det;
  145. const float tx = (bax * cav - cax * bav) * invDet;
  146. const float ty = (bay * cav - cay * bav) * invDet;
  147. const float tz = (baz * cav - caz * bav) * invDet;
  148. const float bx = (cax * bau - bax * cau) * invDet;
  149. const float by = (cay * bau - bay * cau) * invDet;
  150. const float bz = (caz * bau - baz * cau) * invDet;
  151. for (uint32_t jj = 0; jj < 3; ++jj)
  152. {
  153. float* tanu = &tangents[indices[jj]*6];
  154. float* tanv = &tanu[3];
  155. tanu[0] += tx;
  156. tanu[1] += ty;
  157. tanu[2] += tz;
  158. tanv[0] += bx;
  159. tanv[1] += by;
  160. tanv[2] += bz;
  161. }
  162. }
  163. for (uint32_t ii = 0; ii < _numVertices; ++ii)
  164. {
  165. const float* tanu = &tangents[ii*6];
  166. const float* tanv = &tangents[ii*6 + 3];
  167. float normal[4];
  168. bgfx::vertexUnpack(normal, bgfx::Attrib::Normal, _decl, _vertices, ii);
  169. float ndt = bx::vec3Dot(normal, tanu);
  170. float nxt[3];
  171. bx::vec3Cross(nxt, normal, tanu);
  172. float tmp[3];
  173. tmp[0] = tanu[0] - normal[0] * ndt;
  174. tmp[1] = tanu[1] - normal[1] * ndt;
  175. tmp[2] = tanu[2] - normal[2] * ndt;
  176. float tangent[4];
  177. bx::vec3Norm(tangent, tmp);
  178. tangent[3] = bx::vec3Dot(nxt, tanv) < 0.0f ? -1.0f : 1.0f;
  179. bgfx::vertexPack(tangent, true, bgfx::Attrib::Tangent, _decl, _vertices, ii);
  180. }
  181. delete [] tangents;
  182. }
  183. struct Aabb
  184. {
  185. float m_min[3];
  186. float m_max[3];
  187. };
  188. struct Obb
  189. {
  190. float m_mtx[16];
  191. };
  192. struct Sphere
  193. {
  194. float m_center[3];
  195. float m_radius;
  196. };
  197. struct Primitive
  198. {
  199. uint32_t m_startIndex;
  200. uint32_t m_numIndices;
  201. uint32_t m_startVertex;
  202. uint32_t m_numVertices;
  203. Sphere m_sphere;
  204. Aabb m_aabb;
  205. Obb m_obb;
  206. };
  207. typedef stl::vector<Primitive> PrimitiveArray;
  208. struct Group
  209. {
  210. Group()
  211. {
  212. reset();
  213. }
  214. void reset()
  215. {
  216. m_vbh.idx = bgfx::invalidHandle;
  217. m_ibh.idx = bgfx::invalidHandle;
  218. m_prims.clear();
  219. }
  220. bgfx::VertexBufferHandle m_vbh;
  221. bgfx::IndexBufferHandle m_ibh;
  222. Sphere m_sphere;
  223. Aabb m_aabb;
  224. Obb m_obb;
  225. PrimitiveArray m_prims;
  226. };
  227. namespace bgfx
  228. {
  229. int32_t read(bx::ReaderI* _reader, bgfx::VertexDecl& _decl);
  230. }
  231. struct Mesh
  232. {
  233. void load(bx::ReaderSeekerI* _reader)
  234. {
  235. #define BGFX_CHUNK_MAGIC_VB BX_MAKEFOURCC('V', 'B', ' ', 0x1)
  236. #define BGFX_CHUNK_MAGIC_IB BX_MAKEFOURCC('I', 'B', ' ', 0x0)
  237. #define BGFX_CHUNK_MAGIC_IBC BX_MAKEFOURCC('I', 'B', 'C', 0x0)
  238. #define BGFX_CHUNK_MAGIC_PRI BX_MAKEFOURCC('P', 'R', 'I', 0x0)
  239. using namespace bx;
  240. using namespace bgfx;
  241. Group group;
  242. bx::ReallocatorI* allocator = entry::getAllocator();
  243. uint32_t chunk;
  244. while (4 == bx::read(_reader, chunk) )
  245. {
  246. switch (chunk)
  247. {
  248. case BGFX_CHUNK_MAGIC_VB:
  249. {
  250. read(_reader, group.m_sphere);
  251. read(_reader, group.m_aabb);
  252. read(_reader, group.m_obb);
  253. read(_reader, m_decl);
  254. uint16_t stride = m_decl.getStride();
  255. uint16_t numVertices;
  256. read(_reader, numVertices);
  257. const bgfx::Memory* mem = bgfx::alloc(numVertices*stride);
  258. read(_reader, mem->data, mem->size);
  259. group.m_vbh = bgfx::createVertexBuffer(mem, m_decl);
  260. }
  261. break;
  262. case BGFX_CHUNK_MAGIC_IB:
  263. {
  264. uint32_t numIndices;
  265. read(_reader, numIndices);
  266. const bgfx::Memory* mem = bgfx::alloc(numIndices*2);
  267. read(_reader, mem->data, mem->size);
  268. group.m_ibh = bgfx::createIndexBuffer(mem);
  269. }
  270. break;
  271. case BGFX_CHUNK_MAGIC_IBC:
  272. {
  273. uint32_t numIndices;
  274. bx::read(_reader, numIndices);
  275. const bgfx::Memory* mem = bgfx::alloc(numIndices*2);
  276. uint32_t compressedSize;
  277. bx::read(_reader, compressedSize);
  278. void* compressedIndices = BX_ALLOC(allocator, compressedSize);
  279. bx::read(_reader, compressedIndices, compressedSize);
  280. ReadBitstream rbs( (const uint8_t*)compressedIndices, compressedSize);
  281. DecompressIndexBuffer( (uint16_t*)mem->data, numIndices / 3, rbs);
  282. BX_FREE(allocator, compressedIndices);
  283. group.m_ibh = bgfx::createIndexBuffer(mem);
  284. }
  285. break;
  286. case BGFX_CHUNK_MAGIC_PRI:
  287. {
  288. uint16_t len;
  289. read(_reader, len);
  290. stl::string material;
  291. material.resize(len);
  292. read(_reader, const_cast<char*>(material.c_str() ), len);
  293. uint16_t num;
  294. read(_reader, num);
  295. for (uint32_t ii = 0; ii < num; ++ii)
  296. {
  297. read(_reader, len);
  298. stl::string name;
  299. name.resize(len);
  300. read(_reader, const_cast<char*>(name.c_str() ), len);
  301. Primitive prim;
  302. read(_reader, prim.m_startIndex);
  303. read(_reader, prim.m_numIndices);
  304. read(_reader, prim.m_startVertex);
  305. read(_reader, prim.m_numVertices);
  306. read(_reader, prim.m_sphere);
  307. read(_reader, prim.m_aabb);
  308. read(_reader, prim.m_obb);
  309. group.m_prims.push_back(prim);
  310. }
  311. m_groups.push_back(group);
  312. group.reset();
  313. }
  314. break;
  315. default:
  316. DBG("%08x at %d", chunk, bx::skip(_reader, 0) );
  317. break;
  318. }
  319. }
  320. }
  321. void unload()
  322. {
  323. for (GroupArray::const_iterator it = m_groups.begin(), itEnd = m_groups.end(); it != itEnd; ++it)
  324. {
  325. const Group& group = *it;
  326. bgfx::destroyVertexBuffer(group.m_vbh);
  327. if (bgfx::isValid(group.m_ibh) )
  328. {
  329. bgfx::destroyIndexBuffer(group.m_ibh);
  330. }
  331. }
  332. m_groups.clear();
  333. }
  334. void submit(uint8_t _id, bgfx::ProgramHandle _program, const float* _mtx, uint64_t _state) const
  335. {
  336. if (BGFX_STATE_MASK == _state)
  337. {
  338. _state = 0
  339. | BGFX_STATE_RGB_WRITE
  340. | BGFX_STATE_ALPHA_WRITE
  341. | BGFX_STATE_DEPTH_WRITE
  342. | BGFX_STATE_DEPTH_TEST_LESS
  343. | BGFX_STATE_CULL_CCW
  344. | BGFX_STATE_MSAA
  345. ;
  346. }
  347. uint32_t cached = bgfx::setTransform(_mtx);
  348. for (GroupArray::const_iterator it = m_groups.begin(), itEnd = m_groups.end(); it != itEnd; ++it)
  349. {
  350. const Group& group = *it;
  351. bgfx::setTransform(cached);
  352. bgfx::setProgram(_program);
  353. bgfx::setIndexBuffer(group.m_ibh);
  354. bgfx::setVertexBuffer(group.m_vbh);
  355. bgfx::setState(_state);
  356. bgfx::submit(_id);
  357. }
  358. }
  359. void submit(const MeshState*const* _state, uint8_t _numPasses, const float* _mtx, uint16_t _numMatrices) const
  360. {
  361. uint32_t cached = bgfx::setTransform(_mtx, _numMatrices);
  362. for (uint32_t pass = 0; pass < _numPasses; ++pass)
  363. {
  364. const MeshState& state = *_state[pass];
  365. for (GroupArray::const_iterator it = m_groups.begin(), itEnd = m_groups.end(); it != itEnd; ++it)
  366. {
  367. const Group& group = *it;
  368. bgfx::setTransform(cached, _numMatrices);
  369. for (uint8_t tex = 0; tex < state.m_numTextures; ++tex)
  370. {
  371. const MeshState::Texture& texture = state.m_textures[tex];
  372. bgfx::setTexture(texture.m_stage
  373. , texture.m_sampler
  374. , texture.m_texture
  375. , texture.m_flags
  376. );
  377. }
  378. bgfx::setProgram(state.m_program);
  379. bgfx::setIndexBuffer(group.m_ibh);
  380. bgfx::setVertexBuffer(group.m_vbh);
  381. bgfx::setState(state.m_state);
  382. bgfx::submit(state.m_viewId);
  383. }
  384. }
  385. }
  386. bgfx::VertexDecl m_decl;
  387. typedef stl::vector<Group> GroupArray;
  388. GroupArray m_groups;
  389. };
  390. Mesh* meshLoad(bx::ReaderSeekerI* _reader)
  391. {
  392. Mesh* mesh = new Mesh;
  393. mesh->load(_reader);
  394. return mesh;
  395. }
  396. Mesh* meshLoad(const char* _filePath)
  397. {
  398. bx::FileReaderI* reader = entry::getFileReader();
  399. bx::open(reader, _filePath);
  400. Mesh* mesh = meshLoad(reader);
  401. bx::close(reader);
  402. return mesh;
  403. }
  404. void meshUnload(Mesh* _mesh)
  405. {
  406. _mesh->unload();
  407. delete _mesh;
  408. }
  409. MeshState* meshStateCreate()
  410. {
  411. MeshState* state = (MeshState*)BX_ALLOC(entry::getAllocator(), sizeof(MeshState) );
  412. return state;
  413. }
  414. void meshStateDestroy(MeshState* _meshState)
  415. {
  416. BX_FREE(entry::getAllocator(), _meshState);
  417. }
  418. void meshSubmit(const Mesh* _mesh, uint8_t _id, bgfx::ProgramHandle _program, const float* _mtx, uint64_t _state)
  419. {
  420. _mesh->submit(_id, _program, _mtx, _state);
  421. }
  422. void meshSubmit(const Mesh* _mesh, const MeshState*const* _state, uint8_t _numPasses, const float* _mtx, uint16_t _numMatrices)
  423. {
  424. _mesh->submit(_state, _numPasses, _mtx, _numMatrices);
  425. }