callback.cpp 11 KB

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