callback.cpp 11 KB

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