callback.cpp 12 KB

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