callback.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. /*
  2. * Copyright 2011-2014 Branimir Karadzic. All rights reserved.
  3. * License: http://www.opensource.org/licenses/BSD-2-Clause
  4. */
  5. #include "common.h"
  6. #include <bgfx.h>
  7. #include <bx/timer.h>
  8. #include <bx/readerwriter.h>
  9. #include <bx/allocator.h>
  10. #include <bx/string.h>
  11. #include "fpumath.h"
  12. #include "aviwriter.h"
  13. #include <inttypes.h>
  14. #include <stdio.h>
  15. #include <string.h>
  16. struct PosColorVertex
  17. {
  18. float m_x;
  19. float m_y;
  20. float m_z;
  21. uint32_t m_abgr;
  22. };
  23. static bgfx::VertexDecl s_PosColorDecl;
  24. static PosColorVertex s_cubeVertices[8] =
  25. {
  26. {-1.0f, 1.0f, 1.0f, 0xff000000 },
  27. { 1.0f, 1.0f, 1.0f, 0xff0000ff },
  28. {-1.0f, -1.0f, 1.0f, 0xff00ff00 },
  29. { 1.0f, -1.0f, 1.0f, 0xff00ffff },
  30. {-1.0f, 1.0f, -1.0f, 0xffff0000 },
  31. { 1.0f, 1.0f, -1.0f, 0xffff00ff },
  32. {-1.0f, -1.0f, -1.0f, 0xffffff00 },
  33. { 1.0f, -1.0f, -1.0f, 0xffffffff },
  34. };
  35. static const uint16_t s_cubeIndices[36] =
  36. {
  37. 0, 1, 2, // 0
  38. 1, 3, 2,
  39. 4, 6, 5, // 2
  40. 5, 6, 7,
  41. 0, 2, 4, // 4
  42. 4, 2, 6,
  43. 1, 5, 3, // 6
  44. 5, 7, 3,
  45. 0, 4, 1, // 8
  46. 4, 5, 1,
  47. 2, 3, 6, // 10
  48. 6, 3, 7,
  49. };
  50. static const char* s_shaderPath = NULL;
  51. static void shaderFilePath(char* _out, const char* _name)
  52. {
  53. strcpy(_out, s_shaderPath);
  54. strcat(_out, _name);
  55. strcat(_out, ".bin");
  56. }
  57. long int fsize(FILE* _file)
  58. {
  59. long int pos = ftell(_file);
  60. fseek(_file, 0L, SEEK_END);
  61. long int size = ftell(_file);
  62. fseek(_file, pos, SEEK_SET);
  63. return size;
  64. }
  65. static const bgfx::Memory* load(const char* _filePath)
  66. {
  67. FILE* file = fopen(_filePath, "rb");
  68. if (NULL != file)
  69. {
  70. uint32_t size = (uint32_t)fsize(file);
  71. const bgfx::Memory* mem = bgfx::alloc(size+1);
  72. size_t ignore = fread(mem->data, 1, size, file);
  73. BX_UNUSED(ignore);
  74. fclose(file);
  75. mem->data[mem->size-1] = '\0';
  76. return mem;
  77. }
  78. return NULL;
  79. }
  80. static const bgfx::Memory* loadShader(const char* _name)
  81. {
  82. char filePath[512];
  83. shaderFilePath(filePath, _name);
  84. return load(filePath);
  85. }
  86. void saveTga(const char* _filePath, uint32_t _width, uint32_t _height, uint32_t _srcPitch, const void* _src, bool _grayscale, bool _yflip)
  87. {
  88. FILE* file = fopen(_filePath, "wb");
  89. if ( NULL != file )
  90. {
  91. uint8_t type = _grayscale ? 3 : 2;
  92. uint8_t bpp = _grayscale ? 8 : 32;
  93. putc(0, file);
  94. putc(0, file);
  95. putc(type, file);
  96. putc(0, file);
  97. putc(0, file);
  98. putc(0, file);
  99. putc(0, file);
  100. putc(0, file);
  101. putc(0, file);
  102. putc(0, file);
  103. putc(0, file);
  104. putc(0, file);
  105. putc(_width&0xff, file);
  106. putc( (_width>>8)&0xff, file);
  107. putc(_height&0xff, file);
  108. putc( (_height>>8)&0xff, file);
  109. putc(bpp, file);
  110. putc(32, file);
  111. uint32_t dstPitch = _width*bpp/8;
  112. if (_yflip)
  113. {
  114. uint8_t* data = (uint8_t*)_src + _srcPitch*_height - _srcPitch;
  115. for (uint32_t yy = 0; yy < _height; ++yy)
  116. {
  117. fwrite(data, dstPitch, 1, file);
  118. data -= _srcPitch;
  119. }
  120. }
  121. else
  122. {
  123. uint8_t* data = (uint8_t*)_src;
  124. for (uint32_t yy = 0; yy < _height; ++yy)
  125. {
  126. fwrite(data, dstPitch, 1, file);
  127. data += _srcPitch;
  128. }
  129. }
  130. fclose(file);
  131. }
  132. }
  133. struct BgfxCallback : public bgfx::CallbackI
  134. {
  135. virtual ~BgfxCallback()
  136. {
  137. }
  138. virtual void fatal(bgfx::Fatal::Enum _code, const char* _str) BX_OVERRIDE
  139. {
  140. // Something unexpected happened, inform user and bail out.
  141. dbgPrintf("Fatal error: 0x%08x: %s", _code, _str);
  142. // Must terminate, continuing will cause crash anyway.
  143. abort();
  144. }
  145. virtual uint32_t cacheReadSize(uint64_t _id) BX_OVERRIDE
  146. {
  147. char filePath[256];
  148. bx::snprintf(filePath, sizeof(filePath), "%016" PRIx64, _id);
  149. // Use cache id as filename.
  150. FILE* file = fopen(filePath, "rb");
  151. if (NULL != file)
  152. {
  153. uint32_t size = fsize(file);
  154. fclose(file);
  155. // Return size of shader file.
  156. return size;
  157. }
  158. // Return 0 if shader is not found.
  159. return 0;
  160. }
  161. virtual bool cacheRead(uint64_t _id, void* _data, uint32_t _size) BX_OVERRIDE
  162. {
  163. char filePath[256];
  164. bx::snprintf(filePath, sizeof(filePath), "temp/%016" PRIx64, _id);
  165. // Use cache id as filename.
  166. FILE* file = fopen(filePath, "rb");
  167. if (NULL != file)
  168. {
  169. // Read shader.
  170. size_t result = fread(_data, 1, _size, file);
  171. fclose(file);
  172. // Make sure that read size matches requested size.
  173. return result == _size;
  174. }
  175. // Shader is not found in cache, needs to be rebuilt.
  176. return false;
  177. }
  178. virtual void cacheWrite(uint64_t _id, const void* _data, uint32_t _size) BX_OVERRIDE
  179. {
  180. char filePath[256];
  181. bx::snprintf(filePath, sizeof(filePath), "temp/%016" PRIx64, _id);
  182. // Use cache id as filename.
  183. FILE* file = fopen(filePath, "wb");
  184. if (NULL != file)
  185. {
  186. // Write shader to cache location.
  187. fwrite(_data, 1, _size, file);
  188. fclose(file);
  189. }
  190. }
  191. virtual void screenShot(const char* _filePath, uint32_t _width, uint32_t _height, uint32_t _pitch, const void* _data, uint32_t /*_size*/, bool _yflip) BX_OVERRIDE
  192. {
  193. char temp[1024];
  194. // Save screen shot as TGA.
  195. bx::snprintf(temp, BX_COUNTOF(temp), "%s.mip0.tga", _filePath);
  196. saveTga(temp, _width, _height, _pitch, _data, false, _yflip);
  197. uint32_t width = _width;
  198. uint32_t height = _height;
  199. uint32_t pitch = _pitch;
  200. uint8_t* data = (uint8_t*)_data;
  201. // Generate mip maps.
  202. uint32_t mip = 1;
  203. for (; 2 <= width && 2 <= height; ++mip)
  204. {
  205. bx::snprintf(temp, BX_COUNTOF(temp), "%s.mip%d.tga", _filePath, mip);
  206. bgfx::imageRgba8Downsample2x2(width, height, pitch, data, data);
  207. width >>= 1;
  208. height >>= 1;
  209. pitch = width*4;
  210. saveTga(temp, width, height, pitch, _data, false, _yflip);
  211. }
  212. if (width > height)
  213. {
  214. for (; 2 <= width; ++mip)
  215. {
  216. memcpy(&data[width*4], data, width*4);
  217. bx::snprintf(temp, BX_COUNTOF(temp), "%s.mip%d.tga", _filePath, mip);
  218. bgfx::imageRgba8Downsample2x2(width, 2, pitch, data, data);
  219. width >>= 1;
  220. pitch = width*4;
  221. saveTga(temp, width, 2, pitch, _data, false, _yflip);
  222. }
  223. }
  224. else
  225. {
  226. for (; 2 <= height; ++mip)
  227. {
  228. uint32_t* src = (uint32_t*)data;
  229. for (uint32_t ii = 0; ii < height; ++ii, src += 2)
  230. {
  231. src[1] = src[0];
  232. }
  233. bx::snprintf(temp, BX_COUNTOF(temp), "%s.mip%d.tga", _filePath, mip);
  234. bgfx::imageRgba8Downsample2x2(2, height, 8, data, data);
  235. height >>= 1;
  236. saveTga(temp, 2, height, 8, _data, false, _yflip);
  237. }
  238. }
  239. }
  240. virtual void captureBegin(uint32_t _width, uint32_t _height, uint32_t /*_pitch*/, bgfx::TextureFormat::Enum /*_format*/, bool _yflip) BX_OVERRIDE
  241. {
  242. m_writer = new AviWriter;
  243. if (!m_writer->open("temp/capture.avi", _width, _height, 60, _yflip) )
  244. {
  245. delete m_writer;
  246. m_writer = NULL;
  247. }
  248. }
  249. virtual void captureEnd() BX_OVERRIDE
  250. {
  251. if (NULL != m_writer)
  252. {
  253. m_writer->close();
  254. delete m_writer;
  255. m_writer = NULL;
  256. }
  257. }
  258. virtual void captureFrame(const void* _data, uint32_t /*_size*/) BX_OVERRIDE
  259. {
  260. if (NULL != m_writer)
  261. {
  262. m_writer->frame(_data);
  263. }
  264. }
  265. AviWriter* m_writer;
  266. };
  267. class BgfxAllocator : public bx::ReallocatorI
  268. {
  269. public:
  270. BgfxAllocator()
  271. : m_numBlocks(0)
  272. , m_maxBlocks(0)
  273. {
  274. }
  275. virtual ~BgfxAllocator()
  276. {
  277. }
  278. virtual void* alloc(size_t _size, const char* _file, uint32_t _line) BX_OVERRIDE
  279. {
  280. BX_UNUSED(_file, _line);
  281. void* ptr = ::malloc(_size);
  282. dbgPrintf("%s(%d): ALLOC %p of %d byte(s)\n", _file, _line, ptr, _size);
  283. ++m_numBlocks;
  284. m_maxBlocks = bx::uint32_max(m_maxBlocks, m_numBlocks);
  285. return ptr;
  286. }
  287. virtual void free(void* _ptr, const char* _file, uint32_t _line) BX_OVERRIDE
  288. {
  289. if (NULL != _ptr)
  290. {
  291. dbgPrintf("%s(%d): FREE %p\n", _file, _line, _ptr);
  292. BX_UNUSED(_file, _line);
  293. ::free(_ptr);
  294. --m_numBlocks;
  295. }
  296. }
  297. virtual void* realloc(void* _ptr, size_t _size, const char* _file, uint32_t _line) BX_OVERRIDE
  298. {
  299. BX_UNUSED(_file, _line);
  300. void* ptr = ::realloc(_ptr, _size);
  301. dbgPrintf("%s(%d): REALLOC %p (old %p) of %d byte(s)\n", _file, _line, ptr, _ptr, _size);
  302. if (NULL == _ptr)
  303. {
  304. ++m_numBlocks;
  305. m_maxBlocks = bx::uint32_max(m_maxBlocks, m_numBlocks);
  306. }
  307. return ptr;
  308. }
  309. void dumpStats() const
  310. {
  311. dbgPrintf("Allocator stats: num blocks %d (peak: %d)\n", m_numBlocks, m_maxBlocks);
  312. }
  313. private:
  314. uint32_t m_numBlocks;
  315. uint32_t m_maxBlocks;
  316. };
  317. int _main_(int /*_argc*/, char** /*_argv*/)
  318. {
  319. BgfxCallback callback;
  320. BgfxAllocator allocator;
  321. uint32_t width = 1280;
  322. uint32_t height = 720;
  323. bgfx::init(&callback, &allocator);
  324. bgfx::reset(width, height, BGFX_RESET_CAPTURE);
  325. // Enable debug text.
  326. bgfx::setDebug(BGFX_DEBUG_TEXT);
  327. // Set view 0 default viewport.
  328. bgfx::setViewRect(0, 0, 0, 1280, 720);
  329. // Set view 0 clear state.
  330. bgfx::setViewClear(0
  331. , BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT
  332. , 0x303030ff
  333. , 1.0f
  334. , 0
  335. );
  336. // Setup root path for binary shaders. Shader binaries are different
  337. // for each renderer.
  338. switch (bgfx::getRendererType() )
  339. {
  340. default:
  341. case bgfx::RendererType::Direct3D9:
  342. s_shaderPath = "shaders/dx9/";
  343. break;
  344. case bgfx::RendererType::Direct3D11:
  345. s_shaderPath = "shaders/dx11/";
  346. break;
  347. case bgfx::RendererType::OpenGL:
  348. s_shaderPath = "shaders/glsl/";
  349. break;
  350. case bgfx::RendererType::OpenGLES2:
  351. case bgfx::RendererType::OpenGLES3:
  352. s_shaderPath = "shaders/gles/";
  353. break;
  354. }
  355. // Create vertex stream declaration.
  356. s_PosColorDecl.begin();
  357. s_PosColorDecl.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float);
  358. s_PosColorDecl.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true);
  359. s_PosColorDecl.end();
  360. const bgfx::Memory* mem;
  361. // Create static vertex buffer.
  362. mem = bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) );
  363. bgfx::VertexBufferHandle vbh = bgfx::createVertexBuffer(mem, s_PosColorDecl);
  364. // Create static index buffer.
  365. mem = bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) );
  366. bgfx::IndexBufferHandle ibh = bgfx::createIndexBuffer(mem);
  367. // Load vertex shader.
  368. mem = loadShader("vs_callback");
  369. bgfx::VertexShaderHandle vsh = bgfx::createVertexShader(mem);
  370. // Load fragment shader.
  371. mem = loadShader("fs_callback");
  372. bgfx::FragmentShaderHandle fsh = bgfx::createFragmentShader(mem);
  373. // Create program from shaders.
  374. bgfx::ProgramHandle program = bgfx::createProgram(vsh, fsh);
  375. // We can destroy vertex and fragment shader here since
  376. // their reference is kept inside bgfx after calling createProgram.
  377. // Vertex and fragment shader will be destroyed once program is
  378. // destroyed.
  379. bgfx::destroyVertexShader(vsh);
  380. bgfx::destroyFragmentShader(fsh);
  381. float time = 0.0f;
  382. // 5 second 60Hz video
  383. for (uint32_t frame = 0; frame < 300; ++frame)
  384. {
  385. // This dummy draw call is here to make sure that view 0 is cleared
  386. // if no other draw calls are submitted to view 0.
  387. bgfx::submit(0);
  388. int64_t now = bx::getHPCounter();
  389. static int64_t last = now;
  390. const int64_t frameTime = now - last;
  391. last = now;
  392. const double freq = double(bx::getHPFrequency() );
  393. const double toMs = 1000.0/freq;
  394. // Use debug font to print information about this example.
  395. bgfx::dbgTextClear();
  396. bgfx::dbgTextPrintf( 0, 1, 0x4f, "bgfx/examples/07-callback");
  397. bgfx::dbgTextPrintf( 0, 2, 0x6f, "Description: Implementing application specific callbacks for taking screen shots,");
  398. bgfx::dbgTextPrintf(13, 3, 0x6f, "caching OpenGL binary shaders, and video capture.");
  399. bgfx::dbgTextPrintf( 0, 4, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs);
  400. float at[3] = { 0.0f, 0.0f, 0.0f };
  401. float eye[3] = { 0.0f, 0.0f, -35.0f };
  402. float view[16];
  403. float proj[16];
  404. mtxLookAt(view, eye, at);
  405. mtxProj(proj, 60.0f, float(width)/float(height), 0.1f, 100.0f);
  406. // Set view and projection matrix for view 0.
  407. bgfx::setViewTransform(0, view, proj);
  408. time += 1.0f/60.0f;
  409. // Submit 11x11 cubes.
  410. for (uint32_t yy = 0; yy < 11; ++yy)
  411. {
  412. for (uint32_t xx = 0; xx < 11-yy; ++xx)
  413. {
  414. float mtx[16];
  415. mtxRotateXY(mtx, time + xx*0.21f, time + yy*0.37f);
  416. mtx[12] = -15.0f + float(xx)*3.0f;
  417. mtx[13] = -15.0f + float(yy)*3.0f;
  418. mtx[14] = 0.0f;
  419. // Set model matrix for rendering.
  420. bgfx::setTransform(mtx);
  421. // Set vertex and fragment shaders.
  422. bgfx::setProgram(program);
  423. // Set vertex and index buffer.
  424. bgfx::setVertexBuffer(vbh);
  425. bgfx::setIndexBuffer(ibh);
  426. // Set render states.
  427. bgfx::setState(BGFX_STATE_DEFAULT);
  428. // Submit primitive for rendering to view 0.
  429. bgfx::submit(0);
  430. }
  431. }
  432. // Take screen shot at frame 150.
  433. if (150 == frame)
  434. {
  435. bgfx::saveScreenShot("temp/frame150");
  436. }
  437. // Advance to next frame. Rendering thread will be kicked to
  438. // process submitted rendering primitives.
  439. bgfx::frame();
  440. }
  441. // Cleanup.
  442. bgfx::destroyIndexBuffer(ibh);
  443. bgfx::destroyVertexBuffer(vbh);
  444. bgfx::destroyProgram(program);
  445. // Shutdown bgfx.
  446. bgfx::shutdown();
  447. allocator.dumpStats();
  448. return 0;
  449. }