terrain_renderer.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. #include "terrain_renderer.h"
  2. #include "../../game/map/visibility_service.h"
  3. #include "../gl/mesh.h"
  4. #include "../gl/render_constants.h"
  5. #include "../gl/resources.h"
  6. #include "../scene_renderer.h"
  7. #include "ground/terrain_gpu.h"
  8. #include "ground_utils.h"
  9. #include "map/terrain.h"
  10. #include <QDebug>
  11. #include <QElapsedTimer>
  12. #include <QQuaternion>
  13. #include <QVector2D>
  14. #include <QtGlobal>
  15. #include <algorithm>
  16. #include <cmath>
  17. #include <cstddef>
  18. #include <cstdint>
  19. #include <limits>
  20. #include <memory>
  21. #include <qelapsedtimer.h>
  22. #include <qglobal.h>
  23. #include <qmatrix4x4.h>
  24. #include <qvectornd.h>
  25. #include <unordered_map>
  26. #include <utility>
  27. #include <vector>
  28. namespace {
  29. using std::uint32_t;
  30. using namespace Render::GL::BitShift;
  31. using namespace Render::GL::Geometry;
  32. using namespace Render::GL::HashXorShift;
  33. using namespace Render::Ground;
  34. const QMatrix4x4 k_identity_matrix;
  35. inline auto applyTint(const QVector3D &color, float tint) -> QVector3D {
  36. QVector3D const c = color * tint;
  37. return {std::clamp(c.x(), 0.0F, 1.0F), std::clamp(c.y(), 0.0F, 1.0F),
  38. std::clamp(c.z(), 0.0F, 1.0F)};
  39. }
  40. inline auto clamp01(const QVector3D &c) -> QVector3D {
  41. return {std::clamp(c.x(), 0.0F, 1.0F), std::clamp(c.y(), 0.0F, 1.0F),
  42. std::clamp(c.z(), 0.0F, 1.0F)};
  43. }
  44. inline auto linstep(float a, float b, float x) -> float {
  45. return std::clamp((x - a) / std::max(1e-6F, (b - a)), 0.0F, 1.0F);
  46. }
  47. inline auto smooth(float a, float b, float x) -> float {
  48. float const t = linstep(a, b, x);
  49. return t * t * (3.0F - 2.0F * t);
  50. }
  51. inline auto value_noise(float x, float z, uint32_t salt = 0U) -> float {
  52. int const x0 = int(std::floor(x));
  53. int const z0 = int(std::floor(z));
  54. int const x1 = x0 + 1;
  55. int const z1 = z0 + 1;
  56. float const tx = x - float(x0);
  57. float const tz = z - float(z0);
  58. float const n00 = hash_to_01(hash_coords(x0, z0, salt));
  59. float const n10 = hash_to_01(hash_coords(x1, z0, salt));
  60. float const n01 = hash_to_01(hash_coords(x0, z1, salt));
  61. float const n11 = hash_to_01(hash_coords(x1, z1, salt));
  62. float const nx0 = n00 * (1 - tx) + n10 * tx;
  63. float const nx1 = n01 * (1 - tx) + n11 * tx;
  64. return nx0 * (1 - tz) + nx1 * tz;
  65. }
  66. } // namespace
  67. namespace Render::GL {
  68. TerrainRenderer::TerrainRenderer() = default;
  69. TerrainRenderer::~TerrainRenderer() = default;
  70. void TerrainRenderer::configure(
  71. const Game::Map::TerrainHeightMap &height_map,
  72. const Game::Map::BiomeSettings &biome_settings) {
  73. m_width = height_map.getWidth();
  74. m_height = height_map.getHeight();
  75. m_tile_size = height_map.getTileSize();
  76. m_heightData = height_map.getHeightData();
  77. m_terrain_types = height_map.getTerrainTypes();
  78. m_hillEntrances = height_map.getHillEntrances();
  79. m_biome_settings = biome_settings;
  80. m_noiseSeed = biome_settings.seed;
  81. build_meshes();
  82. }
  83. void TerrainRenderer::submit(Renderer &renderer, ResourceManager *resources) {
  84. if (m_chunks.empty()) {
  85. return;
  86. }
  87. Q_UNUSED(resources);
  88. auto &visibility = Game::Map::VisibilityService::instance();
  89. const bool use_visibility = visibility.is_initialized();
  90. for (const auto &chunk : m_chunks) {
  91. if (!chunk.mesh) {
  92. continue;
  93. }
  94. if (use_visibility) {
  95. bool any_visible = false;
  96. for (int gz = chunk.minZ; gz <= chunk.maxZ && !any_visible; ++gz) {
  97. for (int gx = chunk.minX; gx <= chunk.maxX; ++gx) {
  98. if (visibility.stateAt(gx, gz) ==
  99. Game::Map::VisibilityState::Visible) {
  100. any_visible = true;
  101. break;
  102. }
  103. }
  104. }
  105. if (!any_visible) {
  106. continue;
  107. }
  108. }
  109. renderer.terrain_chunk(chunk.mesh.get(), k_identity_matrix, chunk.params,
  110. 0x0080U, true, 0.0F);
  111. }
  112. }
  113. auto TerrainRenderer::section_for(Game::Map::TerrainType type) -> int {
  114. switch (type) {
  115. case Game::Map::TerrainType::Mountain:
  116. return 2;
  117. case Game::Map::TerrainType::Hill:
  118. return 1;
  119. case Game::Map::TerrainType::Forest:
  120. case Game::Map::TerrainType::Flat:
  121. default:
  122. return 0;
  123. }
  124. }
  125. void TerrainRenderer::build_meshes() {
  126. QElapsedTimer timer;
  127. timer.start();
  128. m_chunks.clear();
  129. if (m_width < 2 || m_height < 2 || m_heightData.empty()) {
  130. return;
  131. }
  132. std::vector<float> height_data = m_heightData;
  133. std::vector<float> entry_weight;
  134. if (!m_hillEntrances.empty() &&
  135. m_hillEntrances.size() == height_data.size()) {
  136. constexpr int k_entry_radius = 4;
  137. entry_weight.assign(height_data.size(), 0.0F);
  138. for (int z = 0; z < m_height; ++z) {
  139. for (int x = 0; x < m_width; ++x) {
  140. int const idx = z * m_width + x;
  141. if (m_terrain_types[idx] != Game::Map::TerrainType::Hill) {
  142. continue;
  143. }
  144. float min_dist = float(k_entry_radius + 1);
  145. for (int dz = -k_entry_radius; dz <= k_entry_radius; ++dz) {
  146. int const nz = z + dz;
  147. if (nz < 0 || nz >= m_height) {
  148. continue;
  149. }
  150. for (int dx = -k_entry_radius; dx <= k_entry_radius; ++dx) {
  151. int const nx = x + dx;
  152. if (nx < 0 || nx >= m_width) {
  153. continue;
  154. }
  155. int const n_idx = nz * m_width + nx;
  156. if (!m_hillEntrances[n_idx]) {
  157. continue;
  158. }
  159. float const dist = std::sqrt(float(dx * dx + dz * dz));
  160. min_dist = std::min(min_dist, dist);
  161. }
  162. }
  163. if (min_dist <= k_entry_radius) {
  164. float const t = 1.0F - (min_dist / float(k_entry_radius));
  165. entry_weight[idx] = t * t;
  166. }
  167. }
  168. }
  169. }
  170. float min_h = std::numeric_limits<float>::infinity();
  171. float max_h = -std::numeric_limits<float>::infinity();
  172. for (float const h : height_data) {
  173. min_h = std::min(min_h, h);
  174. max_h = std::max(max_h, h);
  175. }
  176. const float height_range = std::max(1e-4F, max_h - min_h);
  177. const float half_width = m_width * 0.5F - 0.5F;
  178. const float half_height = m_height * 0.5F - 0.5F;
  179. const int vertex_count = m_width * m_height;
  180. std::vector<QVector3D> positions(vertex_count);
  181. std::vector<QVector3D> normals(vertex_count, QVector3D(0.0F, 0.0F, 0.0F));
  182. std::vector<QVector3D> face_accum(vertex_count, QVector3D(0, 0, 0));
  183. for (int z = 0; z < m_height; ++z) {
  184. for (int x = 0; x < m_width; ++x) {
  185. int const idx = z * m_width + x;
  186. float const world_x = (x - half_width) * m_tile_size;
  187. float const world_z = (z - half_height) * m_tile_size;
  188. positions[idx] = QVector3D(world_x, height_data[idx], world_z);
  189. }
  190. }
  191. auto sample_height_at = [&](float gx, float gz) {
  192. gx = std::clamp(gx, 0.0F, float(m_width - 1));
  193. gz = std::clamp(gz, 0.0F, float(m_height - 1));
  194. int const x0 = int(std::floor(gx));
  195. int const z0 = int(std::floor(gz));
  196. int const x1 = std::min(x0 + 1, m_width - 1);
  197. int const z1 = std::min(z0 + 1, m_height - 1);
  198. float const tx = gx - float(x0);
  199. float const tz = gz - float(z0);
  200. float const h00 = height_data[z0 * m_width + x0];
  201. float const h10 = height_data[z0 * m_width + x1];
  202. float const h01 = height_data[z1 * m_width + x0];
  203. float const h11 = height_data[z1 * m_width + x1];
  204. float const h0 = h00 * (1.0F - tx) + h10 * tx;
  205. float const h1 = h01 * (1.0F - tx) + h11 * tx;
  206. return h0 * (1.0F - tz) + h1 * tz;
  207. };
  208. auto sample_entry_at = [&](float gx, float gz) {
  209. if (entry_weight.empty()) {
  210. return 0.0F;
  211. }
  212. gx = std::clamp(gx, 0.0F, float(m_width - 1));
  213. gz = std::clamp(gz, 0.0F, float(m_height - 1));
  214. int const x0 = int(std::floor(gx));
  215. int const z0 = int(std::floor(gz));
  216. int const x1 = std::min(x0 + 1, m_width - 1);
  217. int const z1 = std::min(z0 + 1, m_height - 1);
  218. float const tx = gx - float(x0);
  219. float const tz = gz - float(z0);
  220. float const e00 = entry_weight[z0 * m_width + x0];
  221. float const e10 = entry_weight[z0 * m_width + x1];
  222. float const e01 = entry_weight[z1 * m_width + x0];
  223. float const e11 = entry_weight[z1 * m_width + x1];
  224. float const e0 = e00 * (1.0F - tx) + e10 * tx;
  225. float const e1 = e01 * (1.0F - tx) + e11 * tx;
  226. return e0 * (1.0F - tz) + e1 * tz;
  227. };
  228. auto normal_from_heights_at = [&](float gx, float gz) {
  229. float const gx0 = std::clamp(gx - 1.0F, 0.0F, float(m_width - 1));
  230. float const gx1 = std::clamp(gx + 1.0F, 0.0F, float(m_width - 1));
  231. float const gz0 = std::clamp(gz - 1.0F, 0.0F, float(m_height - 1));
  232. float const gz1 = std::clamp(gz + 1.0F, 0.0F, float(m_height - 1));
  233. float const h_l = sample_height_at(gx0, gz);
  234. float const h_r = sample_height_at(gx1, gz);
  235. float const h_d = sample_height_at(gx, gz0);
  236. float const h_u = sample_height_at(gx, gz1);
  237. QVector3D const dx(2.0F * m_tile_size, h_r - h_l, 0.0F);
  238. QVector3D const dz(0.0F, h_u - h_d, 2.0F * m_tile_size);
  239. QVector3D n = QVector3D::crossProduct(dz, dx);
  240. if (n.lengthSquared() > 0.0F) {
  241. n.normalize();
  242. }
  243. return n.isNull() ? QVector3D(0, 1, 0) : n;
  244. };
  245. for (int i = 0; i < vertex_count; ++i) {
  246. int const x = i % m_width;
  247. int const z = i / m_width;
  248. normals[i] = normal_from_heights_at(float(x), float(z));
  249. face_accum[i] = normals[i];
  250. }
  251. {
  252. std::vector<QVector3D> filtered = normals;
  253. auto get_n = [&](int x, int z) -> QVector3D & {
  254. return normals[z * m_width + x];
  255. };
  256. for (int z = 1; z < m_height - 1; ++z) {
  257. for (int x = 1; x < m_width - 1; ++x) {
  258. const int idx = z * m_width + x;
  259. const float h0 = height_data[idx];
  260. const float nh = (h0 - min_h) / height_range;
  261. const float h_l = height_data[z * m_width + (x - 1)];
  262. const float h_r = height_data[z * m_width + (x + 1)];
  263. const float h_d = height_data[(z - 1) * m_width + x];
  264. const float h_u = height_data[(z + 1) * m_width + x];
  265. const float avg_nbr = 0.25F * (h_l + h_r + h_d + h_u);
  266. const float convexity = h0 - avg_nbr;
  267. const QVector3D n0 = normals[idx];
  268. const float slope = 1.0F - std::clamp(n0.y(), 0.0F, 1.0F);
  269. const float ridge_s = smooth(0.35F, 0.70F, slope);
  270. const float ridge_c = smooth(-0.02F, 0.18F, convexity);
  271. const float ridge_factor =
  272. std::clamp(0.5F * ridge_s + 0.5F * ridge_c, 0.0F, 1.0F);
  273. const float base_boost = 0.6F * (1.0F - nh);
  274. QVector3D acc(0, 0, 0);
  275. float wsum = 0.0F;
  276. for (int dz = -1; dz <= 1; ++dz) {
  277. for (int dx = -1; dx <= 1; ++dx) {
  278. const int nx = x + dx;
  279. const int nz = z + dz;
  280. const int n_idx = nz * m_width + nx;
  281. const float dh = std::abs(height_data[n_idx] - h0);
  282. const QVector3D nn = get_n(nx, nz);
  283. const float ndot = std::max(0.0F, QVector3D::dotProduct(n0, nn));
  284. const float w_h = 1.0F / (1.0F + 2.0F * dh);
  285. const float w_n = std::pow(ndot, 8.0F);
  286. const float w_b = 1.0F + base_boost;
  287. const float w_r = 1.0F - ridge_factor * 0.85F;
  288. const float w = w_h * w_n * w_b * w_r;
  289. acc += nn * w;
  290. wsum += w;
  291. }
  292. }
  293. QVector3D n_filtered = (wsum > 0.0F) ? (acc / wsum) : n0;
  294. n_filtered.normalize();
  295. const QVector3D n_orig = face_accum[idx];
  296. const QVector3D n_final =
  297. (ridge_factor > 0.0F)
  298. ? (n_filtered * (1.0F - ridge_factor) + n_orig * ridge_factor)
  299. : n_filtered;
  300. filtered[idx] = n_final.normalized();
  301. }
  302. }
  303. normals.swap(filtered);
  304. }
  305. auto quad_section = [&](Game::Map::TerrainType a, Game::Map::TerrainType b,
  306. Game::Map::TerrainType c, Game::Map::TerrainType d) {
  307. int const priority_a = section_for(a);
  308. int const priority_b = section_for(b);
  309. int const priority_c = section_for(c);
  310. int const priority_d = section_for(d);
  311. int result = priority_a;
  312. result = std::max(result, priority_b);
  313. result = std::max(result, priority_c);
  314. result = std::max(result, priority_d);
  315. return result;
  316. };
  317. const int chunk_size = DefaultChunkSize;
  318. std::size_t total_triangles = 0;
  319. for (int chunk_z = 0; chunk_z < m_height - 1; chunk_z += chunk_size) {
  320. int const chunk_max_z = std::min(chunk_z + chunk_size, m_height - 1);
  321. for (int chunk_x = 0; chunk_x < m_width - 1; chunk_x += chunk_size) {
  322. int const chunk_max_x = std::min(chunk_x + chunk_size, m_width - 1);
  323. struct SectionData {
  324. std::vector<Vertex> vertices;
  325. std::vector<unsigned int> indices;
  326. std::unordered_map<int, unsigned int> remap;
  327. float heightSum = 0.0F;
  328. int heightCount = 0;
  329. float rotationDeg = 0.0F;
  330. bool flipU = false;
  331. float tint = 1.0F;
  332. QVector3D normalSum = QVector3D(0, 0, 0);
  333. float slopeSum = 0.0F;
  334. float heightVarSum = 0.0F;
  335. int statCount = 0;
  336. float aoSum = 0.0F;
  337. int aoCount = 0;
  338. };
  339. SectionData sections[3];
  340. uint32_t const chunk_seed = hash_coords(chunk_x, chunk_z, m_noiseSeed);
  341. uint32_t const variant_seed = chunk_seed ^ k_golden_ratio;
  342. constexpr int k_rotation_shift = 5;
  343. constexpr int k_rotation_mask = 3;
  344. constexpr float k_rotation_step_degrees = 90.0F;
  345. constexpr int k_flip_shift = 7;
  346. constexpr int k_tint_shift = 12;
  347. constexpr int k_tint_variant_count = 7;
  348. float const rotation_step =
  349. static_cast<float>((variant_seed >> k_rotation_shift) &
  350. k_rotation_mask) *
  351. k_rotation_step_degrees;
  352. bool const flip = ((variant_seed >> k_flip_shift) & 1U) != 0U;
  353. static const float tint_variants[k_tint_variant_count] = {
  354. 0.9F, 0.94F, 0.97F, 1.0F, 1.03F, 1.06F, 1.1F};
  355. float const tint =
  356. tint_variants[(variant_seed >> k_tint_shift) % k_tint_variant_count];
  357. for (auto &section : sections) {
  358. section.rotationDeg = rotation_step;
  359. section.flipU = flip;
  360. section.tint = tint;
  361. }
  362. auto ensure_vertex = [&](SectionData &section,
  363. int globalIndex) -> unsigned int {
  364. auto it = section.remap.find(globalIndex);
  365. if (it != section.remap.end()) {
  366. return it->second;
  367. }
  368. Vertex v{};
  369. const QVector3D &pos = positions[globalIndex];
  370. const QVector3D &normal = normals[globalIndex];
  371. v.position[0] = pos.x();
  372. v.position[1] = pos.y();
  373. v.position[2] = pos.z();
  374. v.normal[0] = normal.x();
  375. v.normal[1] = normal.y();
  376. v.normal[2] = normal.z();
  377. float const tex_scale = 0.2F / std::max(1.0F, m_tile_size);
  378. float uu = pos.x() * tex_scale;
  379. float const vv = pos.z() * tex_scale;
  380. if (section.flipU) {
  381. uu = -uu;
  382. }
  383. float ru = uu;
  384. float rv = vv;
  385. switch (static_cast<int>(section.rotationDeg)) {
  386. case 90: {
  387. float const t = ru;
  388. ru = -rv;
  389. rv = t;
  390. } break;
  391. case 180:
  392. ru = -ru;
  393. rv = -rv;
  394. break;
  395. case 270: {
  396. float const t = ru;
  397. ru = rv;
  398. rv = -t;
  399. } break;
  400. default:
  401. break;
  402. }
  403. v.tex_coord[0] = ru;
  404. v.tex_coord[1] =
  405. entry_weight.empty() ? 0.0F : entry_weight[globalIndex];
  406. section.vertices.push_back(v);
  407. auto const local_index =
  408. static_cast<unsigned int>(section.vertices.size() - 1);
  409. section.remap.emplace(globalIndex, local_index);
  410. section.normalSum += normal;
  411. return local_index;
  412. };
  413. auto add_vertex = [&](SectionData &section, const QVector3D &pos,
  414. const QVector3D &normal,
  415. float entry_mask) -> unsigned int {
  416. Vertex v{};
  417. v.position[0] = pos.x();
  418. v.position[1] = pos.y();
  419. v.position[2] = pos.z();
  420. v.normal[0] = normal.x();
  421. v.normal[1] = normal.y();
  422. v.normal[2] = normal.z();
  423. float const tex_scale = 0.2F / std::max(1.0F, m_tile_size);
  424. float uu = pos.x() * tex_scale;
  425. float const vv = pos.z() * tex_scale;
  426. if (section.flipU) {
  427. uu = -uu;
  428. }
  429. float ru = uu;
  430. float rv = vv;
  431. switch (static_cast<int>(section.rotationDeg)) {
  432. case 90: {
  433. float const t = ru;
  434. ru = -rv;
  435. rv = t;
  436. } break;
  437. case 180:
  438. ru = -ru;
  439. rv = -rv;
  440. break;
  441. case 270: {
  442. float const t = ru;
  443. ru = rv;
  444. rv = -t;
  445. } break;
  446. default:
  447. break;
  448. }
  449. v.tex_coord[0] = ru;
  450. v.tex_coord[1] = entry_weight.empty() ? 0.0F : entry_mask;
  451. section.vertices.push_back(v);
  452. auto const local_index =
  453. static_cast<unsigned int>(section.vertices.size() - 1);
  454. section.normalSum += normal;
  455. return local_index;
  456. };
  457. auto add_vertex_at_grid = [&](SectionData &section, float gx, float gz,
  458. float entry_mask) -> unsigned int {
  459. float const world_x = (gx - half_width) * m_tile_size;
  460. float const world_z = (gz - half_height) * m_tile_size;
  461. float const h = sample_height_at(gx, gz);
  462. QVector3D const pos(world_x, h, world_z);
  463. QVector3D const normal = normal_from_heights_at(gx, gz);
  464. return add_vertex(section, pos, normal, entry_mask);
  465. };
  466. for (int z = chunk_z; z < chunk_max_z; ++z) {
  467. for (int x = chunk_x; x < chunk_max_x; ++x) {
  468. int const idx0 = z * m_width + x;
  469. int const idx1 = idx0 + 1;
  470. int const idx2 = (z + 1) * m_width + x;
  471. int const idx3 = idx2 + 1;
  472. int const section_index =
  473. quad_section(m_terrain_types[idx0], m_terrain_types[idx1],
  474. m_terrain_types[idx2], m_terrain_types[idx3]);
  475. if (section_index > 0) {
  476. SectionData &section = sections[section_index];
  477. unsigned int const v0 = ensure_vertex(section, idx0);
  478. unsigned int const v1 = ensure_vertex(section, idx1);
  479. unsigned int const v2 = ensure_vertex(section, idx2);
  480. unsigned int const v3 = ensure_vertex(section, idx3);
  481. float entry_factor = 0.0F;
  482. if (!entry_weight.empty()) {
  483. entry_factor = 0.25F * (entry_weight[idx0] + entry_weight[idx1] +
  484. entry_weight[idx2] + entry_weight[idx3]);
  485. }
  486. bool const subdivide = entry_factor > 0.25F;
  487. if (subdivide) {
  488. float const gx = float(x);
  489. float const gz = float(z);
  490. unsigned int const v00 = v0;
  491. unsigned int const v20 = v1;
  492. unsigned int const v02 = v2;
  493. unsigned int const v22 = v3;
  494. unsigned int const v10 = add_vertex_at_grid(
  495. section, gx + 0.5F, gz, sample_entry_at(gx + 0.5F, gz));
  496. unsigned int const v01 = add_vertex_at_grid(
  497. section, gx, gz + 0.5F, sample_entry_at(gx, gz + 0.5F));
  498. unsigned int const v21 =
  499. add_vertex_at_grid(section, gx + 1.0F, gz + 0.5F,
  500. sample_entry_at(gx + 1.0F, gz + 0.5F));
  501. unsigned int const v12 =
  502. add_vertex_at_grid(section, gx + 0.5F, gz + 1.0F,
  503. sample_entry_at(gx + 0.5F, gz + 1.0F));
  504. unsigned int const v11 =
  505. add_vertex_at_grid(section, gx + 0.5F, gz + 0.5F,
  506. sample_entry_at(gx + 0.5F, gz + 0.5F));
  507. section.indices.push_back(v00);
  508. section.indices.push_back(v10);
  509. section.indices.push_back(v01);
  510. section.indices.push_back(v10);
  511. section.indices.push_back(v11);
  512. section.indices.push_back(v01);
  513. section.indices.push_back(v10);
  514. section.indices.push_back(v20);
  515. section.indices.push_back(v11);
  516. section.indices.push_back(v20);
  517. section.indices.push_back(v21);
  518. section.indices.push_back(v11);
  519. section.indices.push_back(v01);
  520. section.indices.push_back(v11);
  521. section.indices.push_back(v02);
  522. section.indices.push_back(v11);
  523. section.indices.push_back(v12);
  524. section.indices.push_back(v02);
  525. section.indices.push_back(v11);
  526. section.indices.push_back(v21);
  527. section.indices.push_back(v12);
  528. section.indices.push_back(v21);
  529. section.indices.push_back(v22);
  530. section.indices.push_back(v12);
  531. } else {
  532. section.indices.push_back(v0);
  533. section.indices.push_back(v1);
  534. section.indices.push_back(v2);
  535. section.indices.push_back(v2);
  536. section.indices.push_back(v1);
  537. section.indices.push_back(v3);
  538. }
  539. float const quad_height = (height_data[idx0] + height_data[idx1] +
  540. height_data[idx2] + height_data[idx3]) *
  541. 0.25F;
  542. section.heightSum += quad_height;
  543. section.heightCount += 1;
  544. float const n_y = (normals[idx0].y() + normals[idx1].y() +
  545. normals[idx2].y() + normals[idx3].y()) *
  546. 0.25F;
  547. float const slope = 1.0F - std::clamp(n_y, 0.0F, 1.0F);
  548. section.slopeSum += slope;
  549. float const hmin =
  550. std::min(std::min(height_data[idx0], height_data[idx1]),
  551. std::min(height_data[idx2], height_data[idx3]));
  552. float const hmax =
  553. std::max(std::max(height_data[idx0], height_data[idx1]),
  554. std::max(height_data[idx2], height_data[idx3]));
  555. section.heightVarSum += (hmax - hmin);
  556. section.statCount += 1;
  557. auto h = [&](int gx, int gz) {
  558. gx = std::clamp(gx, 0, m_width - 1);
  559. gz = std::clamp(gz, 0, m_height - 1);
  560. return height_data[gz * m_width + gx];
  561. };
  562. int const cx = x;
  563. int const cz = z;
  564. float const h_c = quad_height;
  565. float ao = 0.0F;
  566. ao += std::max(0.0F, h(cx - 1, cz) - h_c);
  567. ao += std::max(0.0F, h(cx + 1, cz) - h_c);
  568. ao += std::max(0.0F, h(cx, cz - 1) - h_c);
  569. ao += std::max(0.0F, h(cx, cz + 1) - h_c);
  570. ao = std::clamp(ao * 0.15F, 0.0F, 1.0F);
  571. section.aoSum += ao;
  572. section.aoCount += 1;
  573. }
  574. }
  575. }
  576. for (int i = 0; i < 3; ++i) {
  577. SectionData const &section = sections[i];
  578. if (section.indices.empty()) {
  579. continue;
  580. }
  581. auto mesh = std::make_unique<Mesh>(section.vertices, section.indices);
  582. if (!mesh) {
  583. continue;
  584. }
  585. ChunkMesh chunk;
  586. chunk.mesh = std::move(mesh);
  587. chunk.minX = chunk_x;
  588. chunk.maxX = chunk_max_x - 1;
  589. chunk.minZ = chunk_z;
  590. chunk.maxZ = chunk_max_z - 1;
  591. chunk.type = (i == 0) ? Game::Map::TerrainType::Flat
  592. : (i == 1) ? Game::Map::TerrainType::Hill
  593. : Game::Map::TerrainType::Mountain;
  594. chunk.averageHeight =
  595. (section.heightCount > 0)
  596. ? section.heightSum / float(section.heightCount)
  597. : 0.0F;
  598. const float nh_chunk = (chunk.averageHeight - min_h) / height_range;
  599. const float avg_slope =
  600. (section.statCount > 0)
  601. ? (section.slopeSum / float(section.statCount))
  602. : 0.0F;
  603. const float roughness =
  604. (section.statCount > 0)
  605. ? (section.heightVarSum / float(section.statCount))
  606. : 0.0F;
  607. const float center_gx = 0.5F * (chunk.minX + chunk.maxX);
  608. const float center_gz = 0.5F * (chunk.minZ + chunk.maxZ);
  609. auto hgrid = [&](int gx, int gz) {
  610. gx = std::clamp(gx, 0, m_width - 1);
  611. gz = std::clamp(gz, 0, m_height - 1);
  612. return height_data[gz * m_width + gx];
  613. };
  614. const int cxi = int(center_gx);
  615. const int czi = int(center_gz);
  616. const float h_c = hgrid(cxi, czi);
  617. const float h_l = hgrid(cxi - 1, czi);
  618. const float h_r = hgrid(cxi + 1, czi);
  619. const float h_d = hgrid(cxi, czi - 1);
  620. const float h_u = hgrid(cxi, czi + 1);
  621. const float convexity = h_c - 0.25F * (h_l + h_r + h_d + h_u);
  622. const float edge_factor = smooth(0.25F, 0.55F, avg_slope);
  623. const float entrance_factor =
  624. (1.0F - edge_factor) * smooth(0.00F, 0.15F, -convexity);
  625. const float plateau_flat = 1.0F - smooth(0.10F, 0.25F, avg_slope);
  626. const float plateau_height = smooth(0.60F, 0.80F, nh_chunk);
  627. const float plateau_factor = plateau_flat * plateau_height;
  628. QVector3D const base_color =
  629. getTerrainColor(chunk.type, chunk.averageHeight);
  630. QVector3D const rock_tint = m_biome_settings.rock_low;
  631. float slope_mix = std::clamp(
  632. avg_slope * ((chunk.type == Game::Map::TerrainType::Flat) ? 0.30F
  633. : (chunk.type == Game::Map::TerrainType::Hill)
  634. ? 0.55F
  635. : 0.90F),
  636. 0.0F, 1.0F);
  637. slope_mix += 0.15F * edge_factor;
  638. slope_mix -= 0.10F * entrance_factor;
  639. slope_mix -= 0.08F * plateau_factor;
  640. slope_mix = std::clamp(slope_mix, 0.0F, 1.0F);
  641. float const center_wx = (center_gx - half_width) * m_tile_size;
  642. float const center_wz = (center_gz - half_height) * m_tile_size;
  643. float const macro = value_noise(center_wx * 0.02F, center_wz * 0.02F,
  644. m_noiseSeed ^ 0x51C3U);
  645. float const macro_shade = 0.9F + 0.2F * macro;
  646. float const ao_avg = (section.aoCount > 0)
  647. ? (section.aoSum / float(section.aoCount))
  648. : 0.0F;
  649. float const ao_shade = 1.0F - 0.35F * ao_avg;
  650. QVector3D avg_n = section.normalSum;
  651. if (avg_n.lengthSquared() > 0.0F) {
  652. avg_n.normalize();
  653. }
  654. QVector3D const north(0, 0, 1);
  655. float const northness = std::clamp(
  656. QVector3D::dotProduct(avg_n, north) * 0.5F + 0.5F, 0.0F, 1.0F);
  657. QVector3D const cool_tint(0.96F, 1.02F, 1.04F);
  658. QVector3D const warm_tint(1.03F, 1.0F, 0.97F);
  659. QVector3D const aspect_tint =
  660. cool_tint * northness + warm_tint * (1.0F - northness);
  661. float const feature_bright =
  662. 1.0F + 0.08F * plateau_factor - 0.05F * entrance_factor;
  663. QVector3D const feature_tint =
  664. QVector3D(1.0F + 0.03F * plateau_factor - 0.03F * entrance_factor,
  665. 1.0F + 0.01F * plateau_factor - 0.01F * entrance_factor,
  666. 1.0F - 0.02F * plateau_factor + 0.03F * entrance_factor);
  667. chunk.tint = section.tint;
  668. QVector3D color =
  669. base_color * (1.0F - slope_mix) + rock_tint * slope_mix;
  670. color = applyTint(color, chunk.tint);
  671. color *= macro_shade;
  672. color.setX(color.x() * aspect_tint.x() * feature_tint.x());
  673. color.setY(color.y() * aspect_tint.y() * feature_tint.y());
  674. color.setZ(color.z() * aspect_tint.z() * feature_tint.z());
  675. color *= ao_shade * feature_bright;
  676. color = color * 0.96F + QVector3D(0.04F, 0.04F, 0.04F);
  677. chunk.color = clamp01(color);
  678. TerrainChunkParams params;
  679. auto tint_color = [&](const QVector3D &base) {
  680. return clamp01(applyTint(base, chunk.tint));
  681. };
  682. params.grass_primary = tint_color(m_biome_settings.grass_primary);
  683. params.grass_secondary = tint_color(m_biome_settings.grass_secondary);
  684. params.grass_dry = tint_color(m_biome_settings.grass_dry);
  685. params.soil_color = tint_color(m_biome_settings.soil_color);
  686. params.rock_low = tint_color(m_biome_settings.rock_low);
  687. params.rock_high = tint_color(m_biome_settings.rock_high);
  688. params.tile_size = std::max(0.001F, m_tile_size);
  689. params.macro_noise_scale = m_biome_settings.terrain_macro_noise_scale;
  690. params.detail_noise_scale = m_biome_settings.terrain_detail_noise_scale;
  691. float slope_threshold = m_biome_settings.terrain_rock_threshold;
  692. float sharpness_mul = 1.0F;
  693. if (chunk.type == Game::Map::TerrainType::Hill) {
  694. slope_threshold -= 0.06F;
  695. sharpness_mul = 1.15F;
  696. } else if (chunk.type == Game::Map::TerrainType::Mountain) {
  697. slope_threshold -= 0.16F;
  698. sharpness_mul = 1.60F;
  699. }
  700. slope_threshold -= 0.05F * edge_factor;
  701. slope_threshold += 0.04F * entrance_factor;
  702. slope_threshold = std::clamp(
  703. slope_threshold - std::clamp(avg_slope * 0.20F, 0.0F, 0.12F), 0.05F,
  704. 0.9F);
  705. params.slope_rock_threshold = slope_threshold;
  706. params.slope_rock_sharpness = std::max(
  707. 1.0F, m_biome_settings.terrain_rock_sharpness * sharpness_mul);
  708. float soil_height = m_biome_settings.terrain_soil_height;
  709. if (chunk.type == Game::Map::TerrainType::Hill) {
  710. soil_height -= 0.04F;
  711. } else if (chunk.type == Game::Map::TerrainType::Mountain) {
  712. soil_height -= 0.12F;
  713. }
  714. soil_height += 0.05F * entrance_factor - 0.03F * plateau_factor;
  715. params.soil_blend_height = soil_height;
  716. params.soil_blend_sharpness =
  717. std::max(0.75F, m_biome_settings.terrain_soil_sharpness *
  718. (chunk.type == Game::Map::TerrainType::Mountain
  719. ? 0.80F
  720. : 0.95F));
  721. const uint32_t noise_key_a =
  722. hash_coords(chunk.minX, chunk.minZ, m_noiseSeed ^ 0xB5297A4DU);
  723. const uint32_t noise_key_b =
  724. hash_coords(chunk.minX, chunk.minZ, m_noiseSeed ^ 0x68E31DA4U);
  725. constexpr float k_noise_offset_scale = 256.0F;
  726. params.noise_offset =
  727. QVector2D(hash_to_01(noise_key_a) * k_noise_offset_scale,
  728. hash_to_01(noise_key_b) * k_noise_offset_scale);
  729. float base_amp =
  730. m_biome_settings.height_noise_amplitude *
  731. (0.7F + 0.3F * std::clamp(roughness * 0.6F, 0.0F, 1.0F));
  732. if (chunk.type == Game::Map::TerrainType::Hill) {
  733. base_amp *= 1.12F;
  734. } else if (chunk.type == Game::Map::TerrainType::Mountain) {
  735. base_amp *= 1.25F;
  736. }
  737. base_amp *= (1.0F + 0.10F * edge_factor - 0.08F * plateau_factor -
  738. 0.06F * entrance_factor);
  739. params.height_noise_strength = base_amp;
  740. params.height_noise_frequency = m_biome_settings.height_noise_frequency;
  741. params.ambient_boost =
  742. m_biome_settings.terrain_ambient_boost *
  743. ((chunk.type == Game::Map::TerrainType::Hill) ? 0.97F
  744. : (chunk.type == Game::Map::TerrainType::Mountain) ? 0.90F
  745. : 0.95F);
  746. params.rock_detail_strength =
  747. m_biome_settings.terrain_rock_detail_strength *
  748. (0.75F + 0.35F * std::clamp(avg_slope * 1.2F, 0.0F, 1.0F) +
  749. 0.15F * edge_factor - 0.10F * plateau_factor -
  750. 0.08F * entrance_factor);
  751. params.tint = clamp01(QVector3D(chunk.tint, chunk.tint, chunk.tint));
  752. params.light_direction = QVector3D(0.35F, 0.8F, 0.45F);
  753. chunk.params = params;
  754. total_triangles += chunk.mesh->get_indices().size() / 3;
  755. m_chunks.push_back(std::move(chunk));
  756. }
  757. }
  758. }
  759. }
  760. auto TerrainRenderer::getTerrainColor(Game::Map::TerrainType type,
  761. float height) const -> QVector3D {
  762. switch (type) {
  763. case Game::Map::TerrainType::Mountain:
  764. if (height > 4.0F) {
  765. return m_biome_settings.rock_high;
  766. }
  767. return m_biome_settings.rock_low;
  768. case Game::Map::TerrainType::Hill: {
  769. float const t = std::clamp(height / 3.0F, 0.0F, 1.0F);
  770. float const t_smooth = t * t * (3.0F - 2.0F * t);
  771. QVector3D const grass_low = m_biome_settings.grass_primary * 0.3F +
  772. m_biome_settings.grass_secondary * 0.7F;
  773. QVector3D const grass_high = m_biome_settings.grass_secondary * 0.6F +
  774. m_biome_settings.grass_dry * 0.4F;
  775. QVector3D const grass =
  776. grass_low * (1.0F - t_smooth) + grass_high * t_smooth;
  777. QVector3D const rock = m_biome_settings.rock_low * (1.0F - t_smooth) +
  778. m_biome_settings.rock_high * t_smooth;
  779. float const rock_blend_base = 0.15F + 0.45F * t_smooth;
  780. float const height_factor = std::clamp((height - 0.5F) * 0.3F, 0.0F, 0.25F);
  781. float const rock_blend =
  782. std::clamp(rock_blend_base + height_factor, 0.0F, 0.70F);
  783. return grass * (1.0F - rock_blend) + rock * rock_blend;
  784. }
  785. case Game::Map::TerrainType::Forest: {
  786. float const moisture = std::clamp((height - 0.5F) * 0.2F, 0.0F, 0.4F);
  787. QVector3D const base = m_biome_settings.grass_primary * (1.0F - moisture) +
  788. m_biome_settings.grass_secondary * moisture;
  789. float const dry_blend = std::clamp((height - 2.0F) * 0.12F, 0.0F, 0.3F);
  790. QVector3D const with_dry =
  791. base * (1.0F - dry_blend) + m_biome_settings.grass_dry * dry_blend;
  792. return QVector3D(with_dry.x() * 0.7F, with_dry.y() * 0.9F,
  793. with_dry.z() * 0.6F);
  794. }
  795. case Game::Map::TerrainType::Flat:
  796. default: {
  797. float const moisture = std::clamp((height - 0.5F) * 0.2F, 0.0F, 0.4F);
  798. QVector3D const base = m_biome_settings.grass_primary * (1.0F - moisture) +
  799. m_biome_settings.grass_secondary * moisture;
  800. float const dry_blend = std::clamp((height - 2.0F) * 0.12F, 0.0F, 0.3F);
  801. return base * (1.0F - dry_blend) + m_biome_settings.grass_dry * dry_blend;
  802. }
  803. }
  804. }
  805. } // namespace Render::GL