bgfx_utils.cpp 14 KB

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