geometryv.cpp 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331
  1. /*
  2. * Copyright 2019-2019 Attila Kocsis. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
  4. */
  5. #include "common.h"
  6. #include <bgfx/bgfx.h>
  7. #include <bx/commandline.h>
  8. #include <bx/easing.h>
  9. #include <bx/file.h>
  10. #include <bx/math.h>
  11. #include <bx/os.h>
  12. #include <bx/settings.h>
  13. #include <entry/entry.h>
  14. #include <entry/input.h>
  15. #include <entry/cmd.h>
  16. #include <entry/dialog.h>
  17. #include <imgui/imgui.h>
  18. #include <debugdraw/debugdraw.h>
  19. #include <bgfx_utils.h>
  20. #include <tinystl/allocator.h>
  21. #include <tinystl/vector.h>
  22. namespace stl = tinystl;
  23. #include <string>
  24. #include <algorithm>
  25. #include <bgfx/embedded_shader.h>
  26. #include "vs_mesh.bin.h"
  27. #include "fs_mesh.bin.h"
  28. #define SCENE_VIEW_ID 0
  29. #define BGFX_GEOMETRYV_VERSION_MAJOR 1
  30. #define BGFX_GEOMETRYV_VERSION_MINOR 0
  31. static const bgfx::EmbeddedShader s_embeddedShaders[] =
  32. {
  33. BGFX_EMBEDDED_SHADER(vs_mesh),
  34. BGFX_EMBEDDED_SHADER(fs_mesh),
  35. BGFX_EMBEDDED_SHADER_END()
  36. };
  37. static const char* s_attribShortNames[] =
  38. {
  39. "P", // Position
  40. "N", // Normal
  41. "T", // Tangent
  42. "B", // Bitangent
  43. "C0", // Color0
  44. "C1", // Color1
  45. "C2", // Color2
  46. "C3", // Color3
  47. "I", // Indices
  48. "W", // Weight
  49. "TC0", // TexCoord0
  50. "TC1", // TexCoord1
  51. "TC2", // TexCoord2
  52. "TC3", // TexCoord3
  53. "TC4", // TexCoord4
  54. "TC5", // TexCoord5
  55. "TC6", // TexCoord6
  56. "TC7", // TexCoord7
  57. };
  58. BX_STATIC_ASSERT(BX_COUNTOF(s_attribShortNames) == bgfx::Attrib::Count);
  59. static const char* s_supportedExt[] =
  60. {
  61. "bin",
  62. };
  63. struct Binding
  64. {
  65. enum Enum
  66. {
  67. App,
  68. View,
  69. Help,
  70. About,
  71. Count
  72. };
  73. };
  74. static const InputBinding s_bindingApp[] =
  75. {
  76. { entry::Key::KeyQ, entry::Modifier::None, 1, NULL, "exit" },
  77. { entry::Key::KeyF, entry::Modifier::None, 1, NULL, "graphics fullscreen" },
  78. INPUT_BINDING_END
  79. };
  80. const char* s_resetCmd =
  81. "view dolly\n"
  82. "view orbit\n"
  83. ;
  84. static const InputBinding s_bindingView[] =
  85. {
  86. { entry::Key::Esc, entry::Modifier::None, 1, NULL, "exit" },
  87. { entry::Key::Key1, entry::Modifier::None, 1, NULL, "view dolly" },
  88. { entry::Key::Key0, entry::Modifier::None, 1, NULL, s_resetCmd },
  89. { entry::Key::Plus, entry::Modifier::None, 1, NULL, "view dolly +0.1" },
  90. { entry::Key::Minus, entry::Modifier::None, 1, NULL, "view dolly -0.1" },
  91. { entry::Key::KeyW, entry::Modifier::None, 1, NULL, "view orbit y -0.1" },
  92. { entry::Key::KeyS, entry::Modifier::None, 1, NULL, "view orbit y +0.1" },
  93. { entry::Key::KeyA, entry::Modifier::None, 1, NULL, "view orbit x +0.1" },
  94. { entry::Key::KeyD, entry::Modifier::None, 1, NULL, "view orbit x -0.1" },
  95. { entry::Key::Up, entry::Modifier::None, 1, NULL, "view file-up" },
  96. { entry::Key::Down, entry::Modifier::None, 1, NULL, "view file-down" },
  97. { entry::Key::KeyI, entry::Modifier::None, 1, NULL, "view info" },
  98. { entry::Key::KeyH, entry::Modifier::None, 1, NULL, "view help" },
  99. { entry::Key::Return, entry::Modifier::None, 1, NULL, "view files" },
  100. { entry::Key::Space, entry::Modifier::None, 1, NULL, "view geo\n" },
  101. INPUT_BINDING_END
  102. };
  103. static const InputBinding s_bindingHelp[] =
  104. {
  105. { entry::Key::Esc, entry::Modifier::None, 1, NULL, "view help" },
  106. { entry::Key::KeyH, entry::Modifier::None, 1, NULL, "view help" },
  107. INPUT_BINDING_END
  108. };
  109. static const InputBinding s_bindingAbout[] =
  110. {
  111. { entry::Key::Esc, entry::Modifier::None, 1, NULL, "view about" },
  112. INPUT_BINDING_END
  113. };
  114. static const char* s_bindingName[] =
  115. {
  116. "App",
  117. "View",
  118. "Help",
  119. "About",
  120. };
  121. BX_STATIC_ASSERT(Binding::Count == BX_COUNTOF(s_bindingName) );
  122. static const InputBinding* s_binding[] =
  123. {
  124. s_bindingApp,
  125. s_bindingView,
  126. s_bindingHelp,
  127. s_bindingAbout,
  128. };
  129. BX_STATIC_ASSERT(Binding::Count == BX_COUNTOF(s_binding) );
  130. static const char* s_filter = ""
  131. "Bgfx geometry (bin) | *.bin\n"
  132. ;
  133. struct Camera
  134. {
  135. Camera()
  136. {
  137. init(bx::init::Zero, 2.0f, 0.01f, 100.0f);
  138. }
  139. void init(const bx::Vec3& _center, float _distance, float _near, float _far)
  140. {
  141. m_target.curr = _center;
  142. m_target.dest = _center;
  143. m_pos.curr = _center;
  144. m_pos.curr.z += _distance;
  145. m_pos.dest = _center;
  146. m_pos.dest.z += _distance;
  147. m_orbit[0] = 0.0f;
  148. m_orbit[1] = 0.0f;
  149. m_near = _near;
  150. m_far = _far;
  151. }
  152. void mtxLookAt(float* _outViewMtx)
  153. {
  154. bx::mtxLookAt(_outViewMtx, m_pos.curr, m_target.curr);
  155. }
  156. void orbit(float _dx, float _dy)
  157. {
  158. m_orbit[0] += _dx;
  159. m_orbit[1] += _dy;
  160. }
  161. void distance(float _z)
  162. {
  163. _z = bx::clamp(_z, m_near, m_far);
  164. bx::Vec3 toTarget = bx::sub(m_target.dest, m_pos.dest);
  165. bx::Vec3 toTargetNorm = bx::normalize(toTarget);
  166. m_pos.dest = bx::mad(toTargetNorm, -_z, m_target.dest);
  167. }
  168. void dolly(float _dz)
  169. {
  170. const bx::Vec3 toTarget = bx::sub(m_target.dest, m_pos.dest);
  171. const float toTargetLen = bx::length(toTarget);
  172. const float invToTargetLen = 1.0f / (toTargetLen + bx::kFloatMin);
  173. const bx::Vec3 toTargetNorm = bx::mul(toTarget, invToTargetLen);
  174. float delta = toTargetLen * _dz;
  175. float newLen = toTargetLen - delta;
  176. if ( (m_near < newLen || _dz < 0.0f)
  177. && (newLen < m_far || _dz > 0.0f) )
  178. {
  179. m_pos.dest = bx::mad(toTargetNorm, delta, m_pos.dest);
  180. }
  181. }
  182. void consumeOrbit(float _amount)
  183. {
  184. float consume[2];
  185. consume[0] = m_orbit[0] * _amount;
  186. consume[1] = m_orbit[1] * _amount;
  187. m_orbit[0] -= consume[0];
  188. m_orbit[1] -= consume[1];
  189. const bx::Vec3 toPos = bx::sub(m_pos.curr, m_target.curr);
  190. const float toPosLen = bx::length(toPos);
  191. const float invToPosLen = 1.0f / (toPosLen + bx::kFloatMin);
  192. const bx::Vec3 toPosNorm = bx::mul(toPos, invToPosLen);
  193. float ll[2];
  194. bx::toLatLong(&ll[0], &ll[1], toPosNorm);
  195. ll[0] += consume[0];
  196. ll[1] -= consume[1];
  197. ll[1] = bx::clamp(ll[1], 0.02f, 0.98f);
  198. const bx::Vec3 tmp = bx::fromLatLong(ll[0], ll[1]);
  199. const bx::Vec3 diff = bx::mul(bx::sub(tmp, toPosNorm), toPosLen);
  200. m_pos.curr = bx::add(m_pos.curr, diff);
  201. m_pos.dest = bx::add(m_pos.dest, diff);
  202. }
  203. void update(float _dt)
  204. {
  205. const float amount = bx::min(_dt / 0.12f, 1.0f);
  206. consumeOrbit(amount);
  207. m_target.curr = bx::lerp(m_target.curr, m_target.dest, amount);
  208. m_pos.curr = bx::lerp(m_pos.curr, m_pos.dest, amount);
  209. }
  210. struct Interp3f
  211. {
  212. bx::Vec3 curr = bx::init::None;
  213. bx::Vec3 dest = bx::init::None;
  214. };
  215. Interp3f m_target;
  216. Interp3f m_pos;
  217. float m_orbit[2];
  218. float m_near, m_far;
  219. };
  220. struct Mouse
  221. {
  222. Mouse()
  223. {
  224. m_dx = 0.0f;
  225. m_dy = 0.0f;
  226. m_prevMx = 0.0f;
  227. m_prevMx = 0.0f;
  228. m_scroll = 0;
  229. m_scrollPrev = 0;
  230. }
  231. void update(float _mx, float _my, int32_t _mz, uint32_t _width, uint32_t _height)
  232. {
  233. const float widthf = float(int32_t(_width));
  234. const float heightf = float(int32_t(_height));
  235. // Delta movement.
  236. m_dx = float(_mx - m_prevMx)/widthf;
  237. m_dy = float(_my - m_prevMy)/heightf;
  238. m_prevMx = _mx;
  239. m_prevMy = _my;
  240. // Scroll.
  241. m_scroll = _mz - m_scrollPrev;
  242. m_scrollPrev = _mz;
  243. }
  244. float m_dx; // Screen space.
  245. float m_dy;
  246. float m_prevMx;
  247. float m_prevMy;
  248. int32_t m_scroll;
  249. int32_t m_scrollPrev;
  250. };
  251. struct View
  252. {
  253. View()
  254. : m_fileIndex(0)
  255. , m_width(1280)
  256. , m_height(720)
  257. , m_help(false)
  258. , m_about(false)
  259. , m_info(false)
  260. , m_files(false)
  261. , m_axes(false)
  262. , m_meshCenter(0.0f,0.0f,0.0f)
  263. , m_meshRadius(1.0f)
  264. , m_idleTimer(0.0f)
  265. {
  266. load();
  267. }
  268. ~View()
  269. {
  270. }
  271. int32_t cmd(int32_t _argc, char const* const* _argv)
  272. {
  273. if (_argc >= 2)
  274. {
  275. if (0 == bx::strCmp(_argv[1], "file-up") )
  276. {
  277. m_fileIndex = bx::uint32_satsub(m_fileIndex, 1);
  278. }
  279. else if (0 == bx::strCmp(_argv[1], "file-down") )
  280. {
  281. uint32_t numFiles = bx::uint32_satsub(uint32_t(m_fileList.size() ), 1);
  282. ++m_fileIndex;
  283. m_fileIndex = bx::uint32_min(m_fileIndex, numFiles);
  284. }
  285. else if (0 == bx::strCmp(_argv[1], "help") )
  286. {
  287. m_help ^= true;
  288. }
  289. else if (0 == bx::strCmp(_argv[1], "about") )
  290. {
  291. m_about ^= true;
  292. }
  293. else if (0 == bx::strCmp(_argv[1], "save") )
  294. {
  295. save();
  296. }
  297. else if (0 == bx::strCmp(_argv[1], "info") )
  298. {
  299. m_info ^= true;
  300. }
  301. else if (0 == bx::strCmp(_argv[1], "files") )
  302. {
  303. m_files ^= true;
  304. }
  305. else if (0 == bx::strCmp(_argv[1], "dolly") )
  306. {
  307. if (_argc >= 3)
  308. {
  309. float dolly;
  310. bx::fromString(&dolly, _argv[2]);
  311. if (_argv[2][0] == '+'
  312. || _argv[2][0] == '-')
  313. {
  314. m_camera.dolly(dolly);
  315. m_idleTimer = 0.0f;
  316. }
  317. }
  318. else
  319. {
  320. m_camera.distance(m_meshRadius * 2.0f);
  321. }
  322. }
  323. else if (0 == bx::strCmp(_argv[1], "orbit") )
  324. {
  325. if (_argc >= 4)
  326. {
  327. int axis = (_argv[2][0] == 'x' ? 0 : 1);
  328. float orbit[2] = { 0.0f, 0.0f};
  329. bx::fromString(&orbit[axis], _argv[3]);
  330. m_camera.orbit(orbit[0], orbit[1]);
  331. m_idleTimer = 0.0f;
  332. }
  333. else
  334. {
  335. m_camera.m_target.dest = m_meshCenter;
  336. m_camera.m_pos.dest = m_meshCenter;
  337. m_camera.m_pos.dest.z -= m_meshRadius * 2.0f;
  338. m_camera.m_orbit[0] = 0.0f;
  339. m_camera.m_orbit[1] = 0.0f;
  340. }
  341. }
  342. else if (0 == bx::strCmp(_argv[1], "axes") )
  343. {
  344. m_axes ^= true;
  345. }
  346. }
  347. return 0;
  348. }
  349. static bool sortNameAscending(const std::string& _lhs, const std::string& _rhs)
  350. {
  351. return 0 > bx::strCmpV(_lhs.c_str(), _rhs.c_str() );
  352. }
  353. void updateFileList(const bx::FilePath& _filePath)
  354. {
  355. bx::DirectoryReader dr;
  356. if (bx::open(&dr, _filePath) )
  357. {
  358. m_path = _filePath;
  359. }
  360. else if (bx::open(&dr, _filePath.getPath()) )
  361. {
  362. m_path = _filePath.getPath();
  363. }
  364. else
  365. {
  366. DBG("File path `%s` not found.", _filePath.getCPtr() );
  367. return;
  368. }
  369. bx::Error err;
  370. m_fileList.clear();
  371. while (err.isOk() )
  372. {
  373. bx::FileInfo fi;
  374. bx::read(&dr, fi, &err);
  375. if (err.isOk()
  376. && bx::FileType::File == fi.type)
  377. {
  378. bx::StringView ext = fi.filePath.getExt();
  379. if (!ext.isEmpty() )
  380. {
  381. ext.set(ext.getPtr()+1, ext.getTerm() );
  382. bool supported = false;
  383. for (uint32_t ii = 0; ii < BX_COUNTOF(s_supportedExt); ++ii)
  384. {
  385. const bx::StringView supportedExt(s_supportedExt[ii]);
  386. if (0 == bx::strCmpI(bx::max(ext.getPtr(), ext.getTerm() - supportedExt.getLength() ), supportedExt) )
  387. {
  388. supported = true;
  389. break;
  390. }
  391. }
  392. if (supported)
  393. {
  394. const bx::StringView fileName = fi.filePath.getFileName();
  395. m_fileList.push_back(std::string(fileName.getPtr(), fileName.getTerm() ) );
  396. }
  397. }
  398. }
  399. }
  400. bx::close(&dr);
  401. std::sort(m_fileList.begin(), m_fileList.end(), sortNameAscending);
  402. m_fileIndex = 0;
  403. uint32_t idx = 0;
  404. const bx::StringView fileName = _filePath.getFileName();
  405. for (FileList::const_iterator it = m_fileList.begin(); it != m_fileList.end(); ++it, ++idx)
  406. {
  407. if (0 == bx::strCmpI(it->c_str(), fileName) )
  408. {
  409. // If it is case-insensitive match then might be correct one, but keep
  410. // searching.
  411. m_fileIndex = idx;
  412. if (0 == bx::strCmp(it->c_str(), fileName) )
  413. {
  414. // If it is exact match we're done.
  415. break;
  416. }
  417. }
  418. }
  419. }
  420. void load()
  421. {
  422. bx::FilePath filePath(bx::Dir::Home);
  423. filePath.join(".config/bgfx/geometryv.ini");
  424. bx::Settings settings(entry::getAllocator() );
  425. bx::FileReader reader;
  426. if (bx::open(&reader, filePath) )
  427. {
  428. bx::read(&reader, settings, bx::ErrorAssert{});
  429. bx::close(&reader);
  430. if (!bx::fromString(&m_width, settings.get("view/width") ) )
  431. {
  432. m_width = 1280;
  433. }
  434. if (!bx::fromString(&m_height, settings.get("view/height") ) )
  435. {
  436. m_height = 720;
  437. }
  438. }
  439. }
  440. void save()
  441. {
  442. bx::FilePath filePath(bx::Dir::Home);
  443. filePath.join(".config/bgfx/geometryv.ini");
  444. if (bx::makeAll(filePath.getPath() ) )
  445. {
  446. bx::Settings settings(entry::getAllocator() );
  447. char tmp[256];
  448. bx::toString(tmp, sizeof(tmp), m_width);
  449. settings.set("view/width", tmp);
  450. bx::toString(tmp, sizeof(tmp), m_height);
  451. settings.set("view/height", tmp);
  452. bx::FileWriter writer;
  453. if (bx::open(&writer, filePath) )
  454. {
  455. bx::write(&writer, settings, bx::ErrorAssert{});
  456. bx::close(&writer);
  457. }
  458. }
  459. }
  460. bx::FilePath m_path;
  461. typedef stl::vector<std::string> FileList;
  462. FileList m_fileList;
  463. uint32_t m_fileIndex;
  464. uint32_t m_width;
  465. uint32_t m_height;
  466. bool m_help;
  467. bool m_about;
  468. bool m_info;
  469. bool m_files;
  470. bool m_axes;
  471. Camera m_camera;
  472. Mouse m_mouse;
  473. bx::Vec3 m_meshCenter;
  474. float m_meshRadius;
  475. float m_idleTimer;
  476. };
  477. int cmdView(CmdContext* /*_context*/, void* _userData, int _argc, char const* const* _argv)
  478. {
  479. View* view = static_cast<View*>(_userData);
  480. return view->cmd(_argc, _argv);
  481. }
  482. template<bx::LerpFn lerpT, bx::EaseFn easeT>
  483. struct InterpolatorT
  484. {
  485. float from;
  486. float to;
  487. float duration;
  488. int64_t offset;
  489. InterpolatorT(float _value)
  490. {
  491. reset(_value);
  492. }
  493. void reset(float _value)
  494. {
  495. from = _value;
  496. to = _value;
  497. duration = 0.0;
  498. offset = bx::getHPCounter();
  499. }
  500. void set(float _value, float _duration)
  501. {
  502. if (_value != to)
  503. {
  504. from = getValue();
  505. to = _value;
  506. duration = _duration;
  507. offset = bx::getHPCounter();
  508. }
  509. }
  510. float getValue()
  511. {
  512. if (isActive() )
  513. {
  514. const double freq = double(bx::getHPFrequency() );
  515. int64_t now = bx::getHPCounter();
  516. float time = (float)(double(now - offset) / freq);
  517. float lerp = bx::clamp(time, 0.0f, duration) / duration;
  518. return lerpT(from, to, easeT(lerp) );
  519. }
  520. return to;
  521. }
  522. bool isActive() const
  523. {
  524. const double freq = double(bx::getHPFrequency() );
  525. int64_t now = bx::getHPCounter();
  526. float time = (float)(double(now - offset) / freq);
  527. float lerp = bx::clamp(time, 0.0f, duration) / duration;
  528. return lerp < 1.0f;
  529. }
  530. };
  531. typedef InterpolatorT<bx::lerp, bx::easeInOutQuad> Interpolator;
  532. void keyBindingHelp(const char* _bindings, const char* _description)
  533. {
  534. ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "%s", _bindings);
  535. ImGui::SameLine(140);
  536. ImGui::Text("%s", _description);
  537. }
  538. void help(const char* _error = NULL)
  539. {
  540. if (NULL != _error)
  541. {
  542. bx::printf("Error:\n%s\n\n", _error);
  543. }
  544. bx::printf(
  545. "geometryv, bgfx geometry viewer tool, version %d.%d.%d.\n"
  546. "Copyright 2019-2019 Attila Kocsis. All rights reserved.\n"
  547. "License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE\n\n"
  548. , BGFX_GEOMETRYV_VERSION_MAJOR
  549. , BGFX_GEOMETRYV_VERSION_MINOR
  550. , BGFX_API_VERSION
  551. );
  552. bx::printf(
  553. "Usage: geometryv <file path>\n"
  554. "\n"
  555. "Supported input file types:\n"
  556. );
  557. for (uint32_t ii = 0; ii < BX_COUNTOF(s_supportedExt); ++ii)
  558. {
  559. bx::printf(" *.%s\n", s_supportedExt[ii]);
  560. }
  561. bx::printf(
  562. "\n"
  563. "Options:\n"
  564. " -h, --help Help.\n"
  565. " -v, --version Version information only.\n"
  566. "\n"
  567. "For additional information, see https://github.com/bkaradzic/bgfx\n"
  568. );
  569. }
  570. int _main_(int _argc, char** _argv)
  571. {
  572. bx::CommandLine cmdLine(_argc, _argv);
  573. if (cmdLine.hasArg('v', "version") )
  574. {
  575. bx::printf(
  576. "geometryv, bgfx geometry viewer tool, version %d.%d.%d.\n"
  577. , BGFX_GEOMETRYV_VERSION_MAJOR
  578. , BGFX_GEOMETRYV_VERSION_MINOR
  579. , BGFX_API_VERSION
  580. );
  581. return bx::kExitSuccess;
  582. }
  583. if (cmdLine.hasArg('h', "help") )
  584. {
  585. help();
  586. return bx::kExitFailure;
  587. }
  588. uint32_t debug = BGFX_DEBUG_TEXT;
  589. inputAddBindings(s_bindingName[Binding::App], s_binding[Binding::App]);
  590. inputAddBindings(s_bindingName[Binding::View], s_binding[Binding::View]);
  591. View view;
  592. cmdAdd("view", cmdView, &view);
  593. entry::setWindowFlags(entry::WindowHandle{0}, ENTRY_WINDOW_FLAG_ASPECT_RATIO, false);
  594. entry::setWindowSize(entry::WindowHandle{0}, view.m_width, view.m_height);
  595. bgfx::Init init;
  596. init.resolution.width = view.m_width;
  597. init.resolution.width = view.m_height;
  598. init.resolution.reset = 0
  599. | BGFX_RESET_VSYNC
  600. | BGFX_RESET_MSAA_X16
  601. ;
  602. bgfx::init(init);
  603. // Set view 0 clear state.
  604. bgfx::setViewClear(SCENE_VIEW_ID
  605. , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
  606. , 0x000000ff
  607. , 1.0f
  608. , 0
  609. );
  610. imguiCreate();
  611. ddInit();
  612. const bgfx::Caps* caps = bgfx::getCaps();
  613. bgfx::RendererType::Enum type = caps->rendererType;
  614. bgfx::ShaderHandle vsMesh = bgfx::createEmbeddedShader(s_embeddedShaders, type, "vs_mesh");
  615. bgfx::ShaderHandle fsMesh = bgfx::createEmbeddedShader(s_embeddedShaders, type, "fs_mesh");
  616. bgfx::ProgramHandle meshProgram = bgfx::createProgram(
  617. vsMesh
  618. , fsMesh
  619. , true
  620. );
  621. float speed = 0.37f;
  622. float time = 0.0f;
  623. Interpolator menuFade(5.0f);
  624. auto anyActive = [&]() -> bool
  625. {
  626. return false
  627. || ImGui::MouseOverArea()
  628. || menuFade.isActive()
  629. ;
  630. };
  631. const char* filePath = _argc < 2 ? "" : _argv[1];
  632. std::string path = filePath;
  633. {
  634. bx::FilePath fp(filePath);
  635. view.updateFileList(fp);
  636. }
  637. int exitcode = bx::kExitSuccess;
  638. Mesh* mesh = NULL;
  639. {
  640. uint32_t fileIndex = 0;
  641. entry::WindowState windowState;
  642. while (!entry::processWindowEvents(windowState, debug, init.resolution.reset) )
  643. {
  644. const entry::MouseState& mouseState = windowState.m_mouse;
  645. view.m_width = windowState.m_width;
  646. view.m_height = windowState.m_height;
  647. if (!windowState.m_dropFile.isEmpty() )
  648. {
  649. view.updateFileList(windowState.m_dropFile);
  650. windowState.m_dropFile.clear();
  651. }
  652. imguiBeginFrame(mouseState.m_mx
  653. , mouseState.m_my
  654. , (mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)
  655. | (mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
  656. | (mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  657. , mouseState.m_mz
  658. , uint16_t(view.m_width)
  659. , uint16_t(view.m_height)
  660. );
  661. bool modalWindow = view.m_help || view.m_about;
  662. bool overArea = false
  663. || ImGui::GetMousePos().y <= ImGui::GetTextLineHeightWithSpacing()
  664. || ImGui::MouseOverArea()
  665. ;
  666. overArea &= !modalWindow;
  667. if (overArea)
  668. {
  669. menuFade.set(5.0f, 0.25f);
  670. }
  671. else if (modalWindow)
  672. {
  673. menuFade.reset(0.0f);
  674. }
  675. else
  676. {
  677. menuFade.set(0.0f, 2.0f);
  678. }
  679. ImGui::PushStyleVar(ImGuiStyleVar_Alpha, bx::clamp(menuFade.getValue(), 0.0f, 1.0f) );
  680. ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0.0f);
  681. if (ImGui::BeginMainMenuBar() )
  682. {
  683. if (ImGui::BeginMenu("File"))
  684. {
  685. if (ImGui::MenuItem("Open File") )
  686. {
  687. bx::FilePath tmp = view.m_path;
  688. if (openFileSelectionDialog(
  689. tmp
  690. , FileSelectionDialogType::Open
  691. , "geometryv: Open File"
  692. , s_filter
  693. ) )
  694. {
  695. view.updateFileList(tmp);
  696. }
  697. }
  698. if (ImGui::MenuItem("Show File List", NULL, view.m_files) )
  699. {
  700. cmdExec("view files");
  701. }
  702. ImGui::Separator();
  703. if (ImGui::MenuItem("Exit") )
  704. {
  705. cmdExec("exit");
  706. }
  707. ImGui::EndMenu();
  708. }
  709. if (ImGui::BeginMenu("View") )
  710. {
  711. if (ImGui::MenuItem("Info", NULL, view.m_info) )
  712. {
  713. cmdExec("view info");
  714. }
  715. if (ImGui::MenuItem("Reset") )
  716. {
  717. cmdExec(s_resetCmd);
  718. }
  719. ImGui::Separator();
  720. bool axes = view.m_axes;
  721. if (ImGui::MenuItem("XYZ Axes", NULL, &axes) )
  722. {
  723. cmdExec("view axes");
  724. }
  725. ImGui::Separator();
  726. if (ImGui::MenuItem("Save Options") )
  727. {
  728. cmdExec("view save");
  729. }
  730. ImGui::EndMenu();
  731. }
  732. if (ImGui::BeginMenu("Help") )
  733. {
  734. if (ImGui::MenuItem("View Help") )
  735. {
  736. cmdExec("view help");
  737. }
  738. ImGui::Separator();
  739. if (ImGui::MenuItem("About") )
  740. {
  741. cmdExec("view about");
  742. }
  743. ImGui::EndMenu();
  744. }
  745. if (0 != view.m_fileList.size() )
  746. {
  747. ImGui::Separator();
  748. ImGui::TextColored(
  749. ImVec4(0.0f, 1.0f, 1.0f, 1.0f)
  750. , "%s"
  751. , view.m_fileList[view.m_fileIndex].c_str()
  752. );
  753. }
  754. ImGui::EndMainMenuBar();
  755. }
  756. ImGui::PopStyleVar(2);
  757. static bool help = false;
  758. static bool about = false;
  759. view.m_mouse.update(float(mouseState.m_mx), float(mouseState.m_my), mouseState.m_mz, view.m_width, view.m_height);
  760. if (!overArea)
  761. {
  762. if (mouseState.m_buttons[entry::MouseButton::Left])
  763. {
  764. view.m_idleTimer = 0.0f;
  765. view.m_camera.orbit(view.m_mouse.m_dx, view.m_mouse.m_dy);
  766. }
  767. else if (mouseState.m_buttons[entry::MouseButton::Right])
  768. {
  769. view.m_idleTimer = 0.0f;
  770. view.m_camera.dolly(view.m_mouse.m_dx + view.m_mouse.m_dy);
  771. }
  772. else if (0 != view.m_mouse.m_scroll)
  773. {
  774. view.m_idleTimer = 0.0f;
  775. view.m_camera.dolly(float(view.m_mouse.m_scroll)*0.1f);
  776. }
  777. }
  778. if (help != view.m_help)
  779. {
  780. if (!help)
  781. {
  782. ImGui::OpenPopup("Help");
  783. inputRemoveBindings(s_bindingName[Binding::View]);
  784. inputAddBindings(s_bindingName[Binding::Help], s_binding[Binding::Help]);
  785. }
  786. else
  787. {
  788. inputRemoveBindings(s_bindingName[Binding::Help]);
  789. inputAddBindings(s_bindingName[Binding::View], s_binding[Binding::View]);
  790. }
  791. help = view.m_help;
  792. }
  793. if (about != view.m_about)
  794. {
  795. if (!about)
  796. {
  797. ImGui::OpenPopup("About");
  798. inputRemoveBindings(s_bindingName[Binding::View]);
  799. inputAddBindings(s_bindingName[Binding::About], s_binding[Binding::About]);
  800. }
  801. else
  802. {
  803. inputRemoveBindings(s_bindingName[Binding::About]);
  804. inputAddBindings(s_bindingName[Binding::View], s_binding[Binding::View]);
  805. }
  806. about = view.m_about;
  807. }
  808. if (view.m_info)
  809. {
  810. ImGui::SetNextWindowSize(
  811. ImVec2(450.0f, 320.0f)
  812. , ImGuiCond_FirstUseEver
  813. );
  814. if (ImGui::Begin("Info", &view.m_info) )
  815. {
  816. if (ImGui::BeginChild("##info", ImVec2(0.0f, 0.0f) ) )
  817. {
  818. if (NULL == mesh)
  819. {
  820. ImGui::Text("Geometry is not loaded.");
  821. }
  822. else
  823. {
  824. char layout[128] = {0};
  825. for(int32_t attrib = bgfx::Attrib::Position; attrib < bgfx::Attrib::Count; attrib++)
  826. {
  827. if ( mesh->m_layout.has(bgfx::Attrib::Enum(attrib)) )
  828. bx::strCat(layout, sizeof(layout), s_attribShortNames[attrib]);
  829. }
  830. ImGui::Text("Name: %s %s", view.m_fileList[view.m_fileIndex].c_str(), layout);
  831. ImGui::Indent();
  832. for (GroupArray::const_iterator itGroup = mesh->m_groups.begin(), itGroupEnd = mesh->m_groups.end()
  833. ; itGroup != itGroupEnd
  834. ; ++itGroup
  835. )
  836. {
  837. ImGui::Text("Group v %d i %d c %.2f %.2f %.2f r %.2f"
  838. , itGroup->m_numVertices
  839. , itGroup->m_numIndices
  840. , itGroup->m_sphere.center.x
  841. , itGroup->m_sphere.center.y
  842. , itGroup->m_sphere.center.z
  843. , itGroup->m_sphere.radius
  844. );
  845. ImGui::Indent();
  846. for (PrimitiveArray::const_iterator itPrim = itGroup->m_prims.begin(), itPrimEnd = itGroup->m_prims.end()
  847. ; itPrim != itPrimEnd
  848. ; ++itPrim
  849. )
  850. {
  851. ImGui::Text("Primitive v %d i %d c %.2f %.2f %.2f r %.2f"
  852. , itPrim->m_numVertices
  853. , itPrim->m_numIndices
  854. , itPrim->m_sphere.center.x
  855. , itPrim->m_sphere.center.y
  856. , itPrim->m_sphere.center.z
  857. , itPrim->m_sphere.radius
  858. );
  859. }
  860. ImGui::Unindent();
  861. }
  862. ImGui::Unindent();
  863. ImGui::Separator();
  864. }
  865. ImGui::EndChild();
  866. }
  867. }
  868. ImGui::End();
  869. }
  870. if (view.m_files)
  871. {
  872. char temp[bx::kMaxFilePath];
  873. bx::snprintf(temp, BX_COUNTOF(temp), "%s##File", view.m_path.getCPtr() );
  874. ImGui::SetNextWindowSize(
  875. ImVec2(400.0f, 400.0f)
  876. , ImGuiCond_FirstUseEver
  877. );
  878. if (ImGui::Begin(temp, &view.m_files) )
  879. {
  880. if (ImGui::BeginChild("##file_list", ImVec2(0.0f, 0.0f) ) )
  881. {
  882. ImGui::PushFont(ImGui::Font::Mono);
  883. const float itemHeight = ImGui::GetTextLineHeightWithSpacing();
  884. const float listHeight =
  885. bx::max(1.0f, bx::floor(ImGui::GetWindowHeight()/itemHeight) )
  886. * itemHeight
  887. ;
  888. ImGui::PushItemWidth(-1);
  889. if (ImGui::BeginListBox("##empty", ImVec2(0.0f, listHeight) ) )
  890. {
  891. const int32_t itemCount = int32_t(view.m_fileList.size() );
  892. ImGuiListClipper clipper;
  893. clipper.Begin(itemCount, itemHeight);
  894. int32_t start = clipper.DisplayStart;
  895. int32_t end = clipper.DisplayEnd;
  896. const int32_t index = int32_t(view.m_fileIndex);
  897. if (index <= start)
  898. {
  899. ImGui::SetScrollY(ImGui::GetScrollY() - (start-index+1)*itemHeight);
  900. }
  901. else if (index >= end)
  902. {
  903. ImGui::SetScrollY(ImGui::GetScrollY() + (index-end+1)*itemHeight);
  904. }
  905. while (clipper.Step() )
  906. {
  907. for (int32_t pos = clipper.DisplayStart; pos < clipper.DisplayEnd; ++pos)
  908. {
  909. ImGui::PushID(pos);
  910. bool isSelected = uint32_t(pos) == view.m_fileIndex;
  911. if (ImGui::Selectable(view.m_fileList[pos].c_str(), &isSelected) )
  912. {
  913. view.m_fileIndex = pos;
  914. }
  915. ImGui::PopID();
  916. }
  917. }
  918. clipper.End();
  919. ImGui::EndListBox();
  920. }
  921. ImGui::PopFont();
  922. ImGui::EndChild();
  923. }
  924. }
  925. ImGui::End();
  926. }
  927. if (ImGui::BeginPopupModal("About", &view.m_about, ImGuiWindowFlags_AlwaysAutoResize) )
  928. {
  929. ImGui::SetWindowFontScale(1.0f);
  930. ImGui::Text(
  931. "geometryv, bgfx geometry viewer tool " ICON_KI_WRENCH ", version %d.%d.%d.\n"
  932. "Copyright 2019-2019 Attila Kocsis. All rights reserved.\n"
  933. "License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE\n"
  934. , BGFX_GEOMETRYV_VERSION_MAJOR
  935. , BGFX_GEOMETRYV_VERSION_MINOR
  936. , BGFX_API_VERSION
  937. );
  938. ImGui::Dummy(ImVec2(0.0f, 0.0f) );
  939. ImGui::SameLine(ImGui::GetWindowWidth() - 136.0f);
  940. if (ImGui::Button("Close", ImVec2(128.0f, 0.0f) )
  941. || !view.m_about)
  942. {
  943. view.m_about = false;
  944. ImGui::CloseCurrentPopup();
  945. }
  946. ImGui::EndPopup();
  947. }
  948. if (ImGui::BeginPopupModal("Help", &view.m_help, ImGuiWindowFlags_AlwaysAutoResize) )
  949. {
  950. ImGui::SetWindowFontScale(1.0f);
  951. ImGui::Text("Key bindings:\n\n");
  952. ImGui::PushFont(ImGui::Font::Mono);
  953. keyBindingHelp("ESC", "Exit.");
  954. keyBindingHelp("h", "Toggle help screen.");
  955. keyBindingHelp("i", "Toggle info screen.");
  956. keyBindingHelp("f", "Toggle full-screen.");
  957. ImGui::NextLine();
  958. keyBindingHelp("LMB+drag", "Orbit.");
  959. keyBindingHelp("W/A/S/D", "Orbit.");
  960. keyBindingHelp("RMB+drag or MW", "Dolly.");
  961. keyBindingHelp("=/-", "Dolly.");
  962. keyBindingHelp("0", "Reset.");
  963. keyBindingHelp("1", "Fit to window.");
  964. ImGui::NextLine();
  965. keyBindingHelp("up", "Previous geometry.");
  966. keyBindingHelp("down", "Next geometry.");
  967. ImGui::NextLine();
  968. ImGui::NextLine();
  969. ImGui::PopFont();
  970. ImGui::Dummy(ImVec2(0.0f, 0.0f) );
  971. ImGui::SameLine(ImGui::GetWindowWidth() - 136.0f);
  972. if (ImGui::Button("Close", ImVec2(128.0f, 0.0f) )
  973. || !view.m_help)
  974. {
  975. view.m_help = false;
  976. ImGui::CloseCurrentPopup();
  977. }
  978. ImGui::EndPopup();
  979. }
  980. imguiEndFrame();
  981. if ( (NULL == mesh || view.m_fileIndex != fileIndex)
  982. && 0 != view.m_fileList.size() )
  983. {
  984. if (NULL != mesh )
  985. {
  986. meshUnload(mesh);
  987. }
  988. fileIndex = view.m_fileIndex;
  989. bx::FilePath fp = view.m_path;
  990. fp.join(view.m_fileList[view.m_fileIndex].c_str() );
  991. mesh = meshLoad(fp.getCPtr());
  992. std::string title;
  993. if (NULL != mesh )
  994. {
  995. uint32_t numPrimitives = 0;
  996. uint32_t numVertices = 0;
  997. uint32_t numIndices = 0;
  998. bx::Aabb boundingBox = {};
  999. for (GroupArray::const_iterator it = mesh->m_groups.begin(), itEnd = mesh->m_groups.end(); it != itEnd; ++it)
  1000. {
  1001. if ( it == mesh->m_groups.begin())
  1002. {
  1003. boundingBox = it->m_aabb;
  1004. }
  1005. else
  1006. {
  1007. aabbExpand(boundingBox, it->m_aabb.min);
  1008. aabbExpand(boundingBox, it->m_aabb.max);
  1009. }
  1010. numPrimitives += (uint32_t)it->m_prims.size();
  1011. numVertices += (uint32_t)it->m_numVertices;
  1012. numIndices += (uint32_t)it->m_numIndices;
  1013. }
  1014. bx::stringPrintf(
  1015. title
  1016. , "%s (g %d, p %d, v %d, i %d)"
  1017. , fp.getCPtr()
  1018. , mesh->m_groups.size()
  1019. , numPrimitives
  1020. , numVertices
  1021. , numIndices
  1022. );
  1023. view.m_meshCenter = bx::getCenter(boundingBox);
  1024. view.m_meshRadius = bx::length(bx::getExtents(boundingBox) );
  1025. view.m_camera.init( view.m_meshCenter, view.m_meshRadius * 2.0f, 0.01f, view.m_meshRadius * 10.0f);
  1026. }
  1027. else
  1028. {
  1029. bx::stringPrintf(title, "Failed to load %s!", filePath);
  1030. }
  1031. entry::WindowHandle handle = { 0 };
  1032. entry::setWindowTitle(handle, title.c_str() );
  1033. }
  1034. int64_t now = bx::getHPCounter();
  1035. static int64_t last = now;
  1036. const int64_t frameTime = now - last;
  1037. last = now;
  1038. const double freq = double(bx::getHPFrequency() );
  1039. const float deltaTime = float(frameTime/freq);
  1040. time += (float)(frameTime*speed/freq);
  1041. // Update camera.
  1042. float viewMatrix[16];
  1043. view.m_camera.update(deltaTime);
  1044. view.m_camera.mtxLookAt(viewMatrix);
  1045. float projMatrix[16];
  1046. const float aspect = float(view.m_width)/float(view.m_height);
  1047. bx::mtxProj(projMatrix, 60.0f, aspect, 0.01f, 1000.0f, caps->homogeneousDepth);
  1048. bgfx::setViewTransform(SCENE_VIEW_ID, viewMatrix, projMatrix);
  1049. bgfx::setViewRect(SCENE_VIEW_ID, 0, 0, uint16_t(view.m_width), uint16_t(view.m_height) );
  1050. bgfx::touch(SCENE_VIEW_ID);
  1051. if ( view.m_axes )
  1052. {
  1053. DebugDrawEncoder dde;
  1054. dde.begin(SCENE_VIEW_ID);
  1055. dde.drawAxis(0.0f, 0.0f, 0.0f);
  1056. dde.drawGrid(Axis::Y, {0.0f, 0.0f, 0.0f});
  1057. dde.end();
  1058. }
  1059. bgfx::dbgTextClear();
  1060. float orientation[16];
  1061. bx::mtxIdentity(orientation);
  1062. bgfx::setTransform(orientation);
  1063. float mtx[16];
  1064. bx::mtxIdentity(mtx);
  1065. if (NULL != mesh)
  1066. {
  1067. meshSubmit(mesh
  1068. , SCENE_VIEW_ID
  1069. , meshProgram
  1070. , mtx);
  1071. }
  1072. bgfx::frame();
  1073. // Slow down when nothing is animating...
  1074. if (view.m_idleTimer > 2.0f
  1075. && !anyActive() )
  1076. {
  1077. bx::sleep(100);
  1078. }
  1079. view.m_idleTimer += deltaTime;
  1080. }
  1081. }
  1082. if (NULL != mesh )
  1083. {
  1084. meshUnload(mesh);
  1085. }
  1086. bgfx::destroy(meshProgram);
  1087. ddShutdown();
  1088. imguiDestroy();
  1089. bgfx::shutdown();
  1090. return exitcode;
  1091. }