sky.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. /*
  2. * Copyright 2017 Stanislav Pidhorskyi. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
  4. */
  5. /*
  6. * This example demonstrates:
  7. * - Usage of Perez sky model [1] to render a dynamic sky.
  8. * - Rendering a mesh with a lightmap, shading of which is driven by the same parameters as the sky.
  9. *
  10. * Typically, the sky is rendered using cubemaps or other environment maps.
  11. * This approach can provide a high-quality sky, but the downside is that the
  12. * image is static. To achieve daytime changes in sky appearance, there is a need
  13. * in a dynamic model.
  14. *
  15. * Perez "An All-Weather Model for Sky Luminance Distribution" is a simple,
  16. * but good enough model which is, in essence, a function that
  17. * interpolates a sky color. As input, it requires several turbidity
  18. * coefficients, a color at zenith and direction to the sun.
  19. * Turbidity coefficients are taken from [2], which are computed using more
  20. * complex physically based models. Color at zenith depends on daytime and can
  21. * vary depending on many factors.
  22. *
  23. * In the code below, there are two tables that contain sky and sun luminance
  24. * which were computed using code from [3]. Luminance in those tables
  25. * represents actual scale of light energy that comes from sun compared to
  26. * the sky.
  27. *
  28. * The sky is driven by luminance of the sky, while the material of the
  29. * landscape is driven by both, the luminance of the sky and the sun. The
  30. * lightening model is very simple and consists of two parts: directional
  31. * light and hemisphere light. The first is used for the sun while the second
  32. * is used for the sky. Additionally, the second part is modulated by a
  33. * lightmap to achieve ambient occlusion effect.
  34. *
  35. * References
  36. * ==========
  37. *
  38. * [1] R. Perez, R. Seals, and J. Michalsky."An All-Weather Model for Sky Luminance Distribution".
  39. * Solar Energy, Volume 50, Number 3 (March 1993), pp. 235-245.
  40. *
  41. * [2] A. J. Preetham, Peter Shirley, and Brian Smits. "A Practical Analytic Model for Daylight",
  42. * Proceedings of the 26th Annual Conference on Computer Graphics and Interactive Techniques,
  43. * 1999, pp. 91-100.
  44. * https://www.cs.utah.edu/~shirley/papers/sunsky/sunsky.pdf
  45. *
  46. * [3] E. Lengyel, Game Engine Gems, Volume One. Jones & Bartlett Learning, 2010. pp. 219 - 234
  47. *
  48. */
  49. #include "common.h"
  50. #include "bgfx_utils.h"
  51. #include "imgui/imgui.h"
  52. #include "camera.h"
  53. #include <map>
  54. namespace
  55. {
  56. // Represents color. Color-space depends on context.
  57. // In the code below, used to represent color in XYZ, and RGB color-space
  58. typedef bx::Vec3 Color;
  59. // HDTV rec. 709 matrix.
  60. static constexpr float M_XYZ2RGB[] =
  61. {
  62. 3.240479f, -0.969256f, 0.055648f,
  63. -1.53715f, 1.875991f, -0.204043f,
  64. -0.49853f, 0.041556f, 1.057311f,
  65. };
  66. // Converts color representation from CIE XYZ to RGB color-space.
  67. Color xyzToRgb(const Color& xyz)
  68. {
  69. Color rgb(bx::init::None);
  70. rgb.x = M_XYZ2RGB[0] * xyz.x + M_XYZ2RGB[3] * xyz.y + M_XYZ2RGB[6] * xyz.z;
  71. rgb.y = M_XYZ2RGB[1] * xyz.x + M_XYZ2RGB[4] * xyz.y + M_XYZ2RGB[7] * xyz.z;
  72. rgb.z = M_XYZ2RGB[2] * xyz.x + M_XYZ2RGB[5] * xyz.y + M_XYZ2RGB[8] * xyz.z;
  73. return rgb;
  74. };
  75. // Precomputed luminance of sunlight in XYZ colorspace.
  76. // Computed using code from Game Engine Gems, Volume One, chapter 15. Implementation based on Dr. Richard Bird model.
  77. // This table is used for piecewise linear interpolation. Transitions from and to 0.0 at sunset and sunrise are highly inaccurate
  78. static std::map<float, Color> sunLuminanceXYZTable =
  79. {
  80. { 5.0f, { 0.000000f, 0.000000f, 0.000000f } },
  81. { 7.0f, { 12.703322f, 12.989393f, 9.100411f } },
  82. { 8.0f, { 13.202644f, 13.597814f, 11.524929f } },
  83. { 9.0f, { 13.192974f, 13.597458f, 12.264488f } },
  84. { 10.0f, { 13.132943f, 13.535914f, 12.560032f } },
  85. { 11.0f, { 13.088722f, 13.489535f, 12.692996f } },
  86. { 12.0f, { 13.067827f, 13.467483f, 12.745179f } },
  87. { 13.0f, { 13.069653f, 13.469413f, 12.740822f } },
  88. { 14.0f, { 13.094319f, 13.495428f, 12.678066f } },
  89. { 15.0f, { 13.142133f, 13.545483f, 12.526785f } },
  90. { 16.0f, { 13.201734f, 13.606017f, 12.188001f } },
  91. { 17.0f, { 13.182774f, 13.572725f, 11.311157f } },
  92. { 18.0f, { 12.448635f, 12.672520f, 8.267771f } },
  93. { 20.0f, { 0.000000f, 0.000000f, 0.000000f } },
  94. };
  95. // Precomputed luminance of sky in the zenith point in XYZ colorspace.
  96. // Computed using code from Game Engine Gems, Volume One, chapter 15. Implementation based on Dr. Richard Bird model.
  97. // This table is used for piecewise linear interpolation. Day/night transitions are highly inaccurate.
  98. // The scale of luminance change in Day/night transitions is not preserved.
  99. // Luminance at night was increased to eliminate need the of HDR render.
  100. static std::map<float, Color> skyLuminanceXYZTable =
  101. {
  102. { 0.0f, { 0.308f, 0.308f, 0.411f } },
  103. { 1.0f, { 0.308f, 0.308f, 0.410f } },
  104. { 2.0f, { 0.301f, 0.301f, 0.402f } },
  105. { 3.0f, { 0.287f, 0.287f, 0.382f } },
  106. { 4.0f, { 0.258f, 0.258f, 0.344f } },
  107. { 5.0f, { 0.258f, 0.258f, 0.344f } },
  108. { 7.0f, { 0.962851f, 1.000000f, 1.747835f } },
  109. { 8.0f, { 0.967787f, 1.000000f, 1.776762f } },
  110. { 9.0f, { 0.970173f, 1.000000f, 1.788413f } },
  111. { 10.0f, { 0.971431f, 1.000000f, 1.794102f } },
  112. { 11.0f, { 0.972099f, 1.000000f, 1.797096f } },
  113. { 12.0f, { 0.972385f, 1.000000f, 1.798389f } },
  114. { 13.0f, { 0.972361f, 1.000000f, 1.798278f } },
  115. { 14.0f, { 0.972020f, 1.000000f, 1.796740f } },
  116. { 15.0f, { 0.971275f, 1.000000f, 1.793407f } },
  117. { 16.0f, { 0.969885f, 1.000000f, 1.787078f } },
  118. { 17.0f, { 0.967216f, 1.000000f, 1.773758f } },
  119. { 18.0f, { 0.961668f, 1.000000f, 1.739891f } },
  120. { 20.0f, { 0.264f, 0.264f, 0.352f } },
  121. { 21.0f, { 0.264f, 0.264f, 0.352f } },
  122. { 22.0f, { 0.290f, 0.290f, 0.386f } },
  123. { 23.0f, { 0.303f, 0.303f, 0.404f } },
  124. };
  125. // Turbidity tables. Taken from:
  126. // A. J. Preetham, P. Shirley, and B. Smits. A Practical Analytic Model for Daylight. SIGGRAPH '99
  127. // Coefficients correspond to xyY colorspace.
  128. static constexpr Color ABCDE[] =
  129. {
  130. { -0.2592f, -0.2608f, -1.4630f },
  131. { 0.0008f, 0.0092f, 0.4275f },
  132. { 0.2125f, 0.2102f, 5.3251f },
  133. { -0.8989f, -1.6537f, -2.5771f },
  134. { 0.0452f, 0.0529f, 0.3703f },
  135. };
  136. static constexpr Color ABCDE_t[] =
  137. {
  138. { -0.0193f, -0.0167f, 0.1787f },
  139. { -0.0665f, -0.0950f, -0.3554f },
  140. { -0.0004f, -0.0079f, -0.0227f },
  141. { -0.0641f, -0.0441f, 0.1206f },
  142. { -0.0033f, -0.0109f, -0.0670f },
  143. };
  144. // Performs piecewise linear interpolation of a Color parameter.
  145. class DynamicValueController
  146. {
  147. typedef Color ValueType;
  148. typedef std::map<float, ValueType> KeyMap;
  149. public:
  150. DynamicValueController()
  151. {
  152. }
  153. ~DynamicValueController()
  154. {
  155. }
  156. void SetMap(const KeyMap& keymap)
  157. {
  158. m_keyMap = keymap;
  159. }
  160. ValueType GetValue(float time) const
  161. {
  162. typename KeyMap::const_iterator itUpper = m_keyMap.upper_bound(time + 1e-6f);
  163. typename KeyMap::const_iterator itLower = itUpper;
  164. --itLower;
  165. if (itLower == m_keyMap.end())
  166. {
  167. return itUpper->second;
  168. }
  169. if (itUpper == m_keyMap.end())
  170. {
  171. return itLower->second;
  172. }
  173. float lowerTime = itLower->first;
  174. const ValueType& lowerVal = itLower->second;
  175. float upperTime = itUpper->first;
  176. const ValueType& upperVal = itUpper->second;
  177. if (lowerTime == upperTime)
  178. {
  179. return lowerVal;
  180. }
  181. return interpolate(lowerTime, lowerVal, upperTime, upperVal, time);
  182. };
  183. void Clear()
  184. {
  185. m_keyMap.clear();
  186. };
  187. private:
  188. ValueType interpolate(float lowerTime, const ValueType& lowerVal, float upperTime, const ValueType& upperVal, float time) const
  189. {
  190. const float tt = (time - lowerTime) / (upperTime - lowerTime);
  191. const ValueType result = bx::lerp(lowerVal, upperVal, tt);
  192. return result;
  193. };
  194. KeyMap m_keyMap;
  195. };
  196. // Controls sun position according to time, month, and observer's latitude.
  197. // Sun position computation based on Earth's orbital elements: https://nssdc.gsfc.nasa.gov/planetary/factsheet/earthfact.html
  198. class SunController
  199. {
  200. public:
  201. enum Month : int
  202. {
  203. January = 0,
  204. February,
  205. March,
  206. April,
  207. May,
  208. June,
  209. July,
  210. August,
  211. September,
  212. October,
  213. November,
  214. December
  215. };
  216. SunController()
  217. : m_northDir(1.0f, 0.0f, 0.0f)
  218. , m_sunDir(0.0f, -1.0f, 0.0f)
  219. , m_upDir(0.0f, 1.0f, 0.0f)
  220. , m_latitude(50.0f)
  221. , m_month(June)
  222. , m_eclipticObliquity(bx::toRad(23.4f) )
  223. , m_delta(0.0f)
  224. {
  225. }
  226. void Update(float _time)
  227. {
  228. CalculateSunOrbit();
  229. UpdateSunPosition(_time - 12.0f);
  230. }
  231. bx::Vec3 m_northDir;
  232. bx::Vec3 m_sunDir;
  233. bx::Vec3 m_upDir;
  234. float m_latitude;
  235. Month m_month;
  236. private:
  237. void CalculateSunOrbit()
  238. {
  239. const float day = 30.0f * float(m_month) + 15.0f;
  240. float lambda = 280.46f + 0.9856474f * day;
  241. lambda = bx::toRad(lambda);
  242. m_delta = bx::asin(bx::sin(m_eclipticObliquity) * bx::sin(lambda) );
  243. }
  244. void UpdateSunPosition(float _hour)
  245. {
  246. const float latitude = bx::toRad(m_latitude);
  247. const float hh = _hour * bx::kPi / 12.0f;
  248. const float azimuth = bx::atan2(
  249. bx::sin(hh)
  250. , bx::cos(hh) * bx::sin(latitude) - bx::tan(m_delta) * bx::cos(latitude)
  251. );
  252. const float altitude = bx::asin(
  253. bx::sin(latitude) * bx::sin(m_delta) + bx::cos(latitude) * bx::cos(m_delta) * bx::cos(hh)
  254. );
  255. const bx::Quaternion rot0 = bx::fromAxisAngle(m_upDir, -azimuth);
  256. const bx::Vec3 dir = bx::mul(m_northDir, rot0);
  257. const bx::Vec3 uxd = bx::cross(m_upDir, dir);
  258. const bx::Quaternion rot1 = bx::fromAxisAngle(uxd, altitude);
  259. m_sunDir = bx::mul(dir, rot1);
  260. }
  261. float m_eclipticObliquity;
  262. float m_delta;
  263. };
  264. struct ScreenPosVertex
  265. {
  266. float m_x;
  267. float m_y;
  268. static void init()
  269. {
  270. ms_layout
  271. .begin()
  272. .add(bgfx::Attrib::Position, 2, bgfx::AttribType::Float)
  273. .end();
  274. }
  275. static bgfx::VertexLayout ms_layout;
  276. };
  277. bgfx::VertexLayout ScreenPosVertex::ms_layout;
  278. // Renders a screen-space grid of triangles.
  279. // Because of performance reasons, and because sky color is smooth, sky color is computed in vertex shader.
  280. // 32x32 is a reasonable size for the grid to have smooth enough colors.
  281. struct ProceduralSky
  282. {
  283. void init(int verticalCount, int horizontalCount)
  284. {
  285. // Create vertex stream declaration.
  286. ScreenPosVertex::init();
  287. m_skyProgram = loadProgram("vs_sky", "fs_sky");
  288. m_skyProgram_colorBandingFix = loadProgram("vs_sky", "fs_sky_color_banding_fix");
  289. m_preventBanding = true;
  290. bx::AllocatorI* allocator = entry::getAllocator();
  291. ScreenPosVertex* vertices = (ScreenPosVertex*)BX_ALLOC(allocator
  292. , verticalCount * horizontalCount * sizeof(ScreenPosVertex)
  293. );
  294. for (int i = 0; i < verticalCount; i++)
  295. {
  296. for (int j = 0; j < horizontalCount; j++)
  297. {
  298. ScreenPosVertex& v = vertices[i * verticalCount + j];
  299. v.m_x = float(j) / (horizontalCount - 1) * 2.0f - 1.0f;
  300. v.m_y = float(i) / (verticalCount - 1) * 2.0f - 1.0f;
  301. }
  302. }
  303. uint16_t* indices = (uint16_t*)BX_ALLOC(allocator
  304. , (verticalCount - 1) * (horizontalCount - 1) * 6 * sizeof(uint16_t)
  305. );
  306. int k = 0;
  307. for (int i = 0; i < verticalCount - 1; i++)
  308. {
  309. for (int j = 0; j < horizontalCount - 1; j++)
  310. {
  311. indices[k++] = (uint16_t)(j + 0 + horizontalCount * (i + 0));
  312. indices[k++] = (uint16_t)(j + 1 + horizontalCount * (i + 0));
  313. indices[k++] = (uint16_t)(j + 0 + horizontalCount * (i + 1));
  314. indices[k++] = (uint16_t)(j + 1 + horizontalCount * (i + 0));
  315. indices[k++] = (uint16_t)(j + 1 + horizontalCount * (i + 1));
  316. indices[k++] = (uint16_t)(j + 0 + horizontalCount * (i + 1));
  317. }
  318. }
  319. m_vbh = bgfx::createVertexBuffer(bgfx::copy(vertices, sizeof(ScreenPosVertex) * verticalCount * horizontalCount), ScreenPosVertex::ms_layout);
  320. m_ibh = bgfx::createIndexBuffer(bgfx::copy(indices, sizeof(uint16_t) * k));
  321. BX_FREE(allocator, indices);
  322. BX_FREE(allocator, vertices);
  323. }
  324. void shutdown()
  325. {
  326. bgfx::destroy(m_ibh);
  327. bgfx::destroy(m_vbh);
  328. bgfx::destroy(m_skyProgram);
  329. bgfx::destroy(m_skyProgram_colorBandingFix);
  330. }
  331. void draw()
  332. {
  333. bgfx::setState(BGFX_STATE_WRITE_RGB | BGFX_STATE_DEPTH_TEST_EQUAL);
  334. bgfx::setIndexBuffer(m_ibh);
  335. bgfx::setVertexBuffer(0, m_vbh);
  336. bgfx::submit(0, m_preventBanding ? m_skyProgram_colorBandingFix : m_skyProgram);
  337. }
  338. bgfx::VertexBufferHandle m_vbh;
  339. bgfx::IndexBufferHandle m_ibh;
  340. bgfx::ProgramHandle m_skyProgram;
  341. bgfx::ProgramHandle m_skyProgram_colorBandingFix;
  342. bool m_preventBanding;
  343. };
  344. class ExampleProceduralSky : public entry::AppI
  345. {
  346. public:
  347. ExampleProceduralSky(const char* _name, const char* _description, const char* _url)
  348. : entry::AppI(_name, _description, _url)
  349. {
  350. }
  351. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  352. {
  353. Args args(_argc, _argv);
  354. m_width = _width;
  355. m_height = _height;
  356. m_debug = BGFX_DEBUG_NONE;
  357. m_reset = BGFX_RESET_VSYNC;
  358. bgfx::Init init;
  359. init.type = args.m_type;
  360. init.vendorId = args.m_pciId;
  361. init.resolution.width = m_width;
  362. init.resolution.height = m_height;
  363. init.resolution.reset = m_reset;
  364. bgfx::init(init);
  365. // Enable m_debug text.
  366. bgfx::setDebug(m_debug);
  367. // Set view 0 clear state.
  368. bgfx::setViewClear(0
  369. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  370. , 0x000000ff
  371. , 1.0f
  372. , 0
  373. );
  374. m_sunLuminanceXYZ.SetMap(sunLuminanceXYZTable);
  375. m_skyLuminanceXYZ.SetMap(skyLuminanceXYZTable);
  376. m_mesh = meshLoad("meshes/test_scene.bin");
  377. m_lightmapTexture = loadTexture("textures/lightmap.ktx");
  378. // Imgui.
  379. imguiCreate();
  380. m_timeOffset = bx::getHPCounter();
  381. m_time = 0.0f;
  382. m_timeScale = 1.0f;
  383. s_texLightmap = bgfx::createUniform("s_texLightmap", bgfx::UniformType::Sampler);
  384. u_sunLuminance = bgfx::createUniform("u_sunLuminance", bgfx::UniformType::Vec4);
  385. u_skyLuminanceXYZ = bgfx::createUniform("u_skyLuminanceXYZ", bgfx::UniformType::Vec4);
  386. u_skyLuminance = bgfx::createUniform("u_skyLuminance", bgfx::UniformType::Vec4);
  387. u_sunDirection = bgfx::createUniform("u_sunDirection", bgfx::UniformType::Vec4);
  388. u_parameters = bgfx::createUniform("u_parameters", bgfx::UniformType::Vec4);
  389. u_perezCoeff = bgfx::createUniform("u_perezCoeff", bgfx::UniformType::Vec4, 5);
  390. m_landscapeProgram = loadProgram("vs_sky_landscape", "fs_sky_landscape");
  391. m_sky.init(32, 32);
  392. m_sun.Update(0);
  393. cameraCreate();
  394. cameraSetPosition({ 5.0f, 3.0, 0.0f });
  395. cameraSetVerticalAngle(bx::kPi / 8.0f);
  396. cameraSetHorizontalAngle(-bx::kPi / 3.0f);
  397. m_turbidity = 2.15f;
  398. }
  399. virtual int shutdown() override
  400. {
  401. // Cleanup.
  402. cameraDestroy();
  403. imguiDestroy();
  404. meshUnload(m_mesh);
  405. m_sky.shutdown();
  406. bgfx::destroy(s_texLightmap);
  407. bgfx::destroy(u_sunLuminance);
  408. bgfx::destroy(u_skyLuminanceXYZ);
  409. bgfx::destroy(u_skyLuminance);
  410. bgfx::destroy(u_sunDirection);
  411. bgfx::destroy(u_parameters);
  412. bgfx::destroy(u_perezCoeff);
  413. bgfx::destroy(m_lightmapTexture);
  414. bgfx::destroy(m_landscapeProgram);
  415. bgfx::frame();
  416. // Shutdown bgfx.
  417. bgfx::shutdown();
  418. return 0;
  419. }
  420. void imgui(float _width)
  421. {
  422. ImGui::Begin("ProceduralSky");
  423. ImGui::SetWindowSize(ImVec2(_width, 200.0f) );
  424. ImGui::SliderFloat("Time scale", &m_timeScale, 0.0f, 1.0f);
  425. ImGui::SliderFloat("Time", &m_time, 0.0f, 24.0f);
  426. ImGui::SliderFloat("Latitude", &m_sun.m_latitude, -90.0f, 90.0f);
  427. ImGui::SliderFloat("Turbidity", &m_turbidity, 1.9f, 10.0f);
  428. ImGui::Checkbox("Prevent color banding", &m_sky.m_preventBanding);
  429. const char* items[] =
  430. {
  431. "January",
  432. "February",
  433. "March",
  434. "April",
  435. "May",
  436. "June",
  437. "July",
  438. "August",
  439. "September",
  440. "October",
  441. "November",
  442. "December"
  443. };
  444. ImGui::Combo("Month", (int*)&m_sun.m_month, items, 12);
  445. ImGui::End();
  446. }
  447. bool update() override
  448. {
  449. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState))
  450. {
  451. int64_t now = bx::getHPCounter();
  452. static int64_t last = now;
  453. const int64_t frameTime = now - last;
  454. last = now;
  455. const double freq = double(bx::getHPFrequency());
  456. const float deltaTime = float(frameTime / freq);
  457. m_time += m_timeScale * deltaTime;
  458. m_time = bx::mod(m_time, 24.0f);
  459. m_sun.Update(m_time);
  460. imguiBeginFrame(m_mouseState.m_mx
  461. , m_mouseState.m_my
  462. , (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0)
  463. | (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0)
  464. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  465. , m_mouseState.m_mz
  466. , uint16_t(m_width)
  467. , uint16_t(m_height)
  468. );
  469. showExampleDialog(this);
  470. ImGui::SetNextWindowPos(
  471. ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f)
  472. , ImGuiCond_FirstUseEver
  473. );
  474. imgui(m_width / 5.0f - 10.0f);
  475. imguiEndFrame();
  476. // Update camera.
  477. cameraUpdate(deltaTime, m_mouseState, ImGui::MouseOverArea() );
  478. // Set view 0 default viewport.
  479. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height));
  480. float view[16];
  481. cameraGetViewMtx(view);
  482. float proj[16];
  483. bx::mtxProj(proj, 60.0f, float(m_width) / float(m_height), 0.1f, 2000.0f, bgfx::getCaps()->homogeneousDepth);
  484. bgfx::setViewTransform(0, view, proj);
  485. Color sunLuminanceXYZ = m_sunLuminanceXYZ.GetValue(m_time);
  486. Color sunLuminanceRGB = xyzToRgb(sunLuminanceXYZ);
  487. Color skyLuminanceXYZ = m_skyLuminanceXYZ.GetValue(m_time);
  488. Color skyLuminanceRGB = xyzToRgb(skyLuminanceXYZ);
  489. bgfx::setUniform(u_sunLuminance, &sunLuminanceRGB.x);
  490. bgfx::setUniform(u_skyLuminanceXYZ, &skyLuminanceXYZ.x);
  491. bgfx::setUniform(u_skyLuminance, &skyLuminanceRGB.x);
  492. bgfx::setUniform(u_sunDirection, &m_sun.m_sunDir.x);
  493. float exposition[4] = { 0.02f, 3.0f, 0.1f, m_time };
  494. bgfx::setUniform(u_parameters, exposition);
  495. float perezCoeff[4 * 5];
  496. computePerezCoeff(m_turbidity, perezCoeff);
  497. bgfx::setUniform(u_perezCoeff, perezCoeff, 5);
  498. bgfx::setTexture(0, s_texLightmap, m_lightmapTexture);
  499. meshSubmit(m_mesh, 0, m_landscapeProgram, NULL);
  500. m_sky.draw();
  501. bgfx::frame();
  502. return true;
  503. }
  504. return false;
  505. }
  506. void computePerezCoeff(float _turbidity, float* _outPerezCoeff)
  507. {
  508. const bx::Vec3 turbidity = { _turbidity, _turbidity, _turbidity };
  509. for (uint32_t ii = 0; ii < 5; ++ii)
  510. {
  511. const bx::Vec3 tmp = bx::mad(ABCDE_t[ii], turbidity, ABCDE[ii]);
  512. float* out = _outPerezCoeff + 4 * ii;
  513. bx::store(out, tmp);
  514. out[3] = 0.0f;
  515. }
  516. }
  517. bgfx::ProgramHandle m_landscapeProgram;
  518. bgfx::UniformHandle s_texLightmap;
  519. bgfx::TextureHandle m_lightmapTexture;
  520. bgfx::UniformHandle u_sunLuminance;
  521. bgfx::UniformHandle u_skyLuminanceXYZ;
  522. bgfx::UniformHandle u_skyLuminance;
  523. bgfx::UniformHandle u_sunDirection;
  524. bgfx::UniformHandle u_parameters;
  525. bgfx::UniformHandle u_perezCoeff;
  526. ProceduralSky m_sky;
  527. SunController m_sun;
  528. DynamicValueController m_sunLuminanceXYZ;
  529. DynamicValueController m_skyLuminanceXYZ;
  530. uint32_t m_width;
  531. uint32_t m_height;
  532. uint32_t m_debug;
  533. uint32_t m_reset;
  534. Mesh* m_mesh;
  535. entry::MouseState m_mouseState;
  536. float m_time;
  537. float m_timeScale;
  538. int64_t m_timeOffset;
  539. float m_turbidity;
  540. };
  541. } // namespace
  542. ENTRY_IMPLEMENT_MAIN(
  543. ExampleProceduralSky
  544. , "36-sky"
  545. , "Perez dynamic sky model."
  546. , "https://bkaradzic.github.io/bgfx/examples.html#sky"
  547. );