terrain.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. /*
  2. * Copyright 2015 Andrew Mac. 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 "camera.h"
  9. #include "bounds.h"
  10. #include <bx/allocator.h>
  11. #include <bx/debug.h>
  12. #include <bx/math.h>
  13. namespace
  14. {
  15. static const uint16_t s_terrainSize = 256;
  16. struct PosTexCoord0Vertex
  17. {
  18. float m_x;
  19. float m_y;
  20. float m_z;
  21. float m_u;
  22. float m_v;
  23. static void init()
  24. {
  25. ms_layout
  26. .begin()
  27. .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
  28. .add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
  29. .end();
  30. }
  31. static bgfx::VertexLayout ms_layout;
  32. };
  33. bgfx::VertexLayout PosTexCoord0Vertex::ms_layout;
  34. struct TerrainData
  35. {
  36. int32_t m_mode;
  37. bool m_dirty;
  38. float m_transform[16];
  39. uint8_t* m_heightMap;
  40. PosTexCoord0Vertex* m_vertices;
  41. uint32_t m_vertexCount;
  42. uint16_t* m_indices;
  43. uint32_t m_indexCount;
  44. };
  45. struct BrushData
  46. {
  47. bool m_raise;
  48. int32_t m_size;
  49. float m_power;
  50. };
  51. class ExampleTerrain : public entry::AppI
  52. {
  53. public:
  54. ExampleTerrain(const char* _name, const char* _description, const char* _url)
  55. : entry::AppI(_name, _description, _url)
  56. {
  57. }
  58. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  59. {
  60. Args args(_argc, _argv);
  61. m_width = _width;
  62. m_height = _height;
  63. m_debug = BGFX_DEBUG_NONE;
  64. m_reset = BGFX_RESET_VSYNC;
  65. bgfx::Init init;
  66. init.type = args.m_type;
  67. init.vendorId = args.m_pciId;
  68. init.resolution.width = m_width;
  69. init.resolution.height = m_height;
  70. init.resolution.reset = m_reset;
  71. bgfx::init(init);
  72. // Enable m_debug text.
  73. bgfx::setDebug(m_debug);
  74. // Set view 0 clear state.
  75. bgfx::setViewClear(0
  76. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  77. , 0x303030ff
  78. , 1.0f
  79. , 0
  80. );
  81. // Create vertex stream declaration.
  82. PosTexCoord0Vertex::init();
  83. // Create program from shaders.
  84. m_terrainProgram = loadProgram("vs_terrain", "fs_terrain");
  85. m_terrainHeightTextureProgram = loadProgram("vs_terrain_height_texture", "fs_terrain");
  86. // Imgui.
  87. imguiCreate();
  88. m_timeOffset = bx::getHPCounter();
  89. m_vbh.idx = bgfx::kInvalidHandle;
  90. m_ibh.idx = bgfx::kInvalidHandle;
  91. m_dvbh.idx = bgfx::kInvalidHandle;
  92. m_dibh.idx = bgfx::kInvalidHandle;
  93. m_heightTexture.idx = bgfx::kInvalidHandle;
  94. s_heightTexture = bgfx::createUniform("s_heightTexture", bgfx::UniformType::Sampler);
  95. m_oldWidth = 0;
  96. m_oldHeight = 0;
  97. m_oldReset = m_reset;
  98. m_brush.m_power = 0.5f;
  99. m_brush.m_size = 10;
  100. m_brush.m_raise = true;
  101. uint32_t num = s_terrainSize * s_terrainSize;
  102. m_terrain.m_mode = 0;
  103. m_terrain.m_dirty = true;
  104. m_terrain.m_vertices = (PosTexCoord0Vertex*)BX_ALLOC(entry::getAllocator(), num * sizeof(PosTexCoord0Vertex) );
  105. m_terrain.m_indices = (uint16_t*)BX_ALLOC(entry::getAllocator(), num * sizeof(uint16_t) * 6);
  106. m_terrain.m_heightMap = (uint8_t*)BX_ALLOC(entry::getAllocator(), num);
  107. bx::mtxSRT(m_terrain.m_transform, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f);
  108. bx::memSet(m_terrain.m_heightMap, 0, sizeof(uint8_t) * s_terrainSize * s_terrainSize);
  109. cameraCreate();
  110. cameraSetPosition({ s_terrainSize/2.0f, 100.0f, 0.0f });
  111. cameraSetVerticalAngle(-bx::kPiQuarter);
  112. }
  113. virtual int shutdown() override
  114. {
  115. // Cleanup.
  116. cameraDestroy();
  117. imguiDestroy();
  118. if (bgfx::isValid(m_ibh) )
  119. {
  120. bgfx::destroy(m_ibh);
  121. }
  122. if (bgfx::isValid(m_vbh) )
  123. {
  124. bgfx::destroy(m_vbh);
  125. }
  126. if (bgfx::isValid(m_dibh) )
  127. {
  128. bgfx::destroy(m_dibh);
  129. }
  130. if (bgfx::isValid(m_dvbh) )
  131. {
  132. bgfx::destroy(m_dvbh);
  133. }
  134. bgfx::destroy(s_heightTexture);
  135. if (bgfx::isValid(m_heightTexture) )
  136. {
  137. bgfx::destroy(m_heightTexture);
  138. }
  139. bgfx::destroy(m_terrainProgram);
  140. bgfx::destroy(m_terrainHeightTextureProgram);
  141. /// When data is passed to bgfx via makeRef we need to make
  142. /// sure library is done with it before freeing memory blocks.
  143. bgfx::frame();
  144. bx::AllocatorI* allocator = entry::getAllocator();
  145. BX_FREE(allocator, m_terrain.m_vertices);
  146. BX_FREE(allocator, m_terrain.m_indices);
  147. BX_FREE(allocator, m_terrain.m_heightMap);
  148. // Shutdown bgfx.
  149. bgfx::shutdown();
  150. return 0;
  151. }
  152. void updateTerrainMesh()
  153. {
  154. m_terrain.m_vertexCount = 0;
  155. for (uint32_t y = 0; y < s_terrainSize; y++)
  156. {
  157. for (uint32_t x = 0; x < s_terrainSize; x++)
  158. {
  159. PosTexCoord0Vertex* vert = &m_terrain.m_vertices[m_terrain.m_vertexCount];
  160. vert->m_x = (float)x;
  161. vert->m_y = m_terrain.m_heightMap[(y * s_terrainSize) + x];
  162. vert->m_z = (float)y;
  163. vert->m_u = (x + 0.5f) / s_terrainSize;
  164. vert->m_v = (y + 0.5f) / s_terrainSize;
  165. m_terrain.m_vertexCount++;
  166. }
  167. }
  168. m_terrain.m_indexCount = 0;
  169. for (uint16_t y = 0; y < (s_terrainSize - 1); y++)
  170. {
  171. uint16_t y_offset = (y * s_terrainSize);
  172. for (uint16_t x = 0; x < (s_terrainSize - 1); x++)
  173. {
  174. m_terrain.m_indices[m_terrain.m_indexCount + 0] = y_offset + x + 1;
  175. m_terrain.m_indices[m_terrain.m_indexCount + 1] = y_offset + x + s_terrainSize;
  176. m_terrain.m_indices[m_terrain.m_indexCount + 2] = y_offset + x;
  177. m_terrain.m_indices[m_terrain.m_indexCount + 3] = y_offset + x + s_terrainSize + 1;
  178. m_terrain.m_indices[m_terrain.m_indexCount + 4] = y_offset + x + s_terrainSize;
  179. m_terrain.m_indices[m_terrain.m_indexCount + 5] = y_offset + x + 1;
  180. m_terrain.m_indexCount += 6;
  181. }
  182. }
  183. }
  184. void updateTerrain()
  185. {
  186. const bgfx::Memory* mem;
  187. switch (m_terrain.m_mode)
  188. {
  189. default: // Vertex Buffer : Destroy and recreate a regular vertex buffer to update terrain.
  190. updateTerrainMesh();
  191. if (bgfx::isValid(m_vbh) )
  192. {
  193. bgfx::destroy(m_vbh);
  194. }
  195. mem = bgfx::makeRef(&m_terrain.m_vertices[0], sizeof(PosTexCoord0Vertex) * m_terrain.m_vertexCount);
  196. m_vbh = bgfx::createVertexBuffer(mem, PosTexCoord0Vertex::ms_layout);
  197. if (bgfx::isValid(m_ibh) )
  198. {
  199. bgfx::destroy(m_ibh);
  200. }
  201. mem = bgfx::makeRef(&m_terrain.m_indices[0], sizeof(uint16_t) * m_terrain.m_indexCount);
  202. m_ibh = bgfx::createIndexBuffer(mem);
  203. break;
  204. case 1: // Dynamic Vertex Buffer : Utilize dynamic vertex buffer to update terrain.
  205. updateTerrainMesh();
  206. if (!bgfx::isValid(m_dvbh) )
  207. {
  208. m_dvbh = bgfx::createDynamicVertexBuffer(m_terrain.m_vertexCount, PosTexCoord0Vertex::ms_layout);
  209. }
  210. mem = bgfx::makeRef(&m_terrain.m_vertices[0], sizeof(PosTexCoord0Vertex) * m_terrain.m_vertexCount);
  211. bgfx::update(m_dvbh, 0, mem);
  212. if (!bgfx::isValid(m_dibh) )
  213. {
  214. m_dibh = bgfx::createDynamicIndexBuffer(m_terrain.m_indexCount);
  215. }
  216. mem = bgfx::makeRef(&m_terrain.m_indices[0], sizeof(uint16_t) * m_terrain.m_indexCount);
  217. bgfx::update(m_dibh, 0, mem);
  218. break;
  219. case 2: // Height Texture: Update a height texture that is sampled in the terrain vertex shader.
  220. if (!bgfx::isValid(m_vbh) || !bgfx::isValid(m_ibh) )
  221. {
  222. updateTerrainMesh();
  223. mem = bgfx::makeRef(&m_terrain.m_vertices[0], sizeof(PosTexCoord0Vertex) * m_terrain.m_vertexCount);
  224. m_vbh = bgfx::createVertexBuffer(mem, PosTexCoord0Vertex::ms_layout);
  225. mem = bgfx::makeRef(&m_terrain.m_indices[0], sizeof(uint16_t) * m_terrain.m_indexCount);
  226. m_ibh = bgfx::createIndexBuffer(mem);
  227. }
  228. if (!bgfx::isValid(m_heightTexture) )
  229. {
  230. m_heightTexture = bgfx::createTexture2D(s_terrainSize, s_terrainSize, false, 1, bgfx::TextureFormat::R8);
  231. }
  232. mem = bgfx::makeRef(&m_terrain.m_heightMap[0], sizeof(uint8_t) * s_terrainSize * s_terrainSize);
  233. bgfx::updateTexture2D(m_heightTexture, 0, 0, 0, 0, s_terrainSize, s_terrainSize, mem);
  234. break;
  235. }
  236. }
  237. void paintTerrainHeight(uint32_t _x, uint32_t _y)
  238. {
  239. for (int32_t area_y = -m_brush.m_size; area_y < m_brush.m_size; ++area_y)
  240. {
  241. for (int32_t area_x = -m_brush.m_size; area_x < m_brush.m_size; ++area_x)
  242. {
  243. int32_t brush_x = _x + area_x;
  244. if (brush_x < 0
  245. || brush_x >= (int32_t)s_terrainSize)
  246. {
  247. continue;
  248. }
  249. int32_t brush_y = _y + area_y;
  250. if (brush_y < 0
  251. || brush_y >= (int32_t)s_terrainSize)
  252. {
  253. continue;
  254. }
  255. uint32_t heightMapPos = (brush_y * s_terrainSize) + brush_x;
  256. float height = (float)m_terrain.m_heightMap[heightMapPos];
  257. // Brush attenuation
  258. float a2 = (float)(area_x * area_x);
  259. float b2 = (float)(area_y * area_y);
  260. float brushAttn = m_brush.m_size - bx::sqrt(a2 + b2);
  261. // Raise/Lower and scale by brush power.
  262. height += 0.0f < bx::clamp(brushAttn*m_brush.m_power, 0.0f, m_brush.m_power) && m_brush.m_raise
  263. ? 1.0f
  264. : -1.0f
  265. ;
  266. m_terrain.m_heightMap[heightMapPos] = (uint8_t)bx::clamp(height, 0.0f, 255.0f);
  267. m_terrain.m_dirty = true;
  268. }
  269. }
  270. }
  271. void mousePickTerrain()
  272. {
  273. float ray_clip[4];
  274. ray_clip[0] = ( (2.0f * m_mouseState.m_mx) / m_width - 1.0f) * -1.0f;
  275. ray_clip[1] = ( (1.0f - (2.0f * m_mouseState.m_my) / m_height) ) * -1.0f;
  276. ray_clip[2] = -1.0f;
  277. ray_clip[3] = 1.0f;
  278. float invProjMtx[16];
  279. bx::mtxInverse(invProjMtx, m_projMtx);
  280. float ray_eye[4];
  281. bx::vec4MulMtx(ray_eye, ray_clip, invProjMtx);
  282. ray_eye[2] = -1.0f;
  283. ray_eye[3] = 0.0f;
  284. float invViewMtx[16];
  285. bx::mtxInverse(invViewMtx, m_viewMtx);
  286. float ray_world[4];
  287. bx::vec4MulMtx(ray_world, ray_eye, invViewMtx);
  288. const bx::Vec3 rayDir = bx::mul(bx::normalize(bx::load<bx::Vec3>(ray_world) ), -1.0f);
  289. bx::Vec3 pos = cameraGetPosition();
  290. for (int i = 0; i < 1000; ++i)
  291. {
  292. pos = bx::add(pos, rayDir);
  293. if (pos.x < 0
  294. || pos.x >= s_terrainSize
  295. || pos.z < 0
  296. || pos.z >= s_terrainSize)
  297. {
  298. continue;
  299. }
  300. uint32_t heightMapPos = ( (uint32_t)pos.z * s_terrainSize) + (uint32_t)pos.x;
  301. if (pos.y < m_terrain.m_heightMap[heightMapPos])
  302. {
  303. paintTerrainHeight( (uint32_t)pos.x, (uint32_t)pos.z);
  304. return;
  305. }
  306. }
  307. }
  308. bool update() override
  309. {
  310. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) )
  311. {
  312. int64_t now = bx::getHPCounter();
  313. static int64_t last = now;
  314. const int64_t frameTime = now - last;
  315. last = now;
  316. const double freq = double(bx::getHPFrequency() );
  317. const float deltaTime = float(frameTime/freq);
  318. imguiBeginFrame(m_mouseState.m_mx
  319. , m_mouseState.m_my
  320. , (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)
  321. | (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
  322. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  323. , m_mouseState.m_mz
  324. , uint16_t(m_width)
  325. , uint16_t(m_height)
  326. );
  327. showExampleDialog(this);
  328. ImGui::SetNextWindowPos(
  329. ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f)
  330. , ImGuiCond_FirstUseEver
  331. );
  332. ImGui::SetNextWindowSize(
  333. ImVec2(m_width / 5.0f, m_height / 3.0f)
  334. , ImGuiCond_FirstUseEver
  335. );
  336. ImGui::Begin("Settings"
  337. , NULL
  338. , 0
  339. );
  340. ImGui::Separator();
  341. m_terrain.m_dirty |= ImGui::RadioButton("Vertex Buffer", &m_terrain.m_mode, 0);
  342. m_terrain.m_dirty |= ImGui::RadioButton("Dynamic Vertex Buffer", &m_terrain.m_mode, 1);
  343. m_terrain.m_dirty |= ImGui::RadioButton("Height Texture", &m_terrain.m_mode, 2);
  344. ImGui::Separator();
  345. ImGui::Checkbox("Raise Terrain", &m_brush.m_raise);
  346. ImGui::SliderInt("Brush Size", &m_brush.m_size, 1, 50);
  347. ImGui::SliderFloat("Brush Power", &m_brush.m_power, 0.0f, 1.0f);
  348. ImGui::End();
  349. imguiEndFrame();
  350. if (!ImGui::MouseOverArea() )
  351. {
  352. // Update camera.
  353. cameraUpdate(deltaTime, m_mouseState);
  354. if (!!m_mouseState.m_buttons[entry::MouseButton::Left])
  355. {
  356. mousePickTerrain();
  357. }
  358. }
  359. // Update terrain.
  360. if (m_terrain.m_dirty)
  361. {
  362. updateTerrain();
  363. m_terrain.m_dirty = false;
  364. }
  365. // Set view 0 default viewport.
  366. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  367. cameraGetViewMtx(m_viewMtx);
  368. bx::mtxProj(m_projMtx, 60.0f, float(m_width) / float(m_height), 0.1f, 2000.0f, bgfx::getCaps()->homogeneousDepth);
  369. bgfx::setViewTransform(0, m_viewMtx, m_projMtx);
  370. bgfx::setTransform(m_terrain.m_transform);
  371. switch (m_terrain.m_mode)
  372. {
  373. default:
  374. bgfx::setVertexBuffer(0, m_vbh);
  375. bgfx::setIndexBuffer(m_ibh);
  376. bgfx::submit(0, m_terrainProgram);
  377. break;
  378. case 1:
  379. bgfx::setVertexBuffer(0, m_dvbh);
  380. bgfx::setIndexBuffer(m_dibh);
  381. bgfx::submit(0, m_terrainProgram);
  382. break;
  383. case 2:
  384. bgfx::setVertexBuffer(0, m_vbh);
  385. bgfx::setIndexBuffer(m_ibh);
  386. bgfx::setTexture(0, s_heightTexture, m_heightTexture);
  387. bgfx::submit(0, m_terrainHeightTextureProgram);
  388. break;
  389. }
  390. // Advance to next frame. Rendering thread will be kicked to
  391. // process submitted rendering primitives.
  392. bgfx::frame();
  393. return true;
  394. }
  395. return false;
  396. }
  397. bgfx::VertexBufferHandle m_vbh;
  398. bgfx::IndexBufferHandle m_ibh;
  399. bgfx::DynamicVertexBufferHandle m_dvbh;
  400. bgfx::DynamicIndexBufferHandle m_dibh;
  401. bgfx::ProgramHandle m_terrainProgram;
  402. bgfx::ProgramHandle m_terrainHeightTextureProgram;
  403. bgfx::UniformHandle s_heightTexture;
  404. bgfx::TextureHandle m_heightTexture;
  405. float m_viewMtx[16];
  406. float m_projMtx[16];
  407. uint32_t m_width;
  408. uint32_t m_height;
  409. uint32_t m_debug;
  410. uint32_t m_reset;
  411. uint32_t m_oldWidth;
  412. uint32_t m_oldHeight;
  413. uint32_t m_oldReset;
  414. TerrainData m_terrain;
  415. BrushData m_brush;
  416. entry::MouseState m_mouseState;
  417. int64_t m_timeOffset;
  418. };
  419. } // namespace
  420. ENTRY_IMPLEMENT_MAIN(
  421. ExampleTerrain
  422. , "27-terrain"
  423. , "Terrain painting example."
  424. , "https://bkaradzic.github.io/bgfx/examples.html#terrain"
  425. );