terrain_renderer.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. #include "terrain_renderer.h"
  2. #include "../../game/map/visibility_service.h"
  3. #include "../gl/buffer.h"
  4. #include "../gl/mesh.h"
  5. #include "../gl/resources.h"
  6. #include "../scene_renderer.h"
  7. #include <QDebug>
  8. #include <QElapsedTimer>
  9. #include <QQuaternion>
  10. #include <QVector2D>
  11. #include <QtGlobal>
  12. #include <algorithm>
  13. #include <cmath>
  14. #include <unordered_map>
  15. namespace {
  16. using std::uint32_t;
  17. const QMatrix4x4 kIdentityMatrix;
  18. inline uint32_t hashCoords(int x, int z, uint32_t salt = 0u) {
  19. uint32_t ux = static_cast<uint32_t>(x * 73856093);
  20. uint32_t uz = static_cast<uint32_t>(z * 19349663);
  21. return ux ^ uz ^ (salt * 83492791u);
  22. }
  23. inline float rand01(uint32_t &state) {
  24. state = state * 1664525u + 1013904223u;
  25. return static_cast<float>((state >> 8) & 0xFFFFFF) /
  26. static_cast<float>(0xFFFFFF);
  27. }
  28. inline float remap(float value, float minOut, float maxOut) {
  29. return minOut + (maxOut - minOut) * value;
  30. }
  31. inline QVector3D applyTint(const QVector3D &color, float tint) {
  32. QVector3D c = color * tint;
  33. return QVector3D(std::clamp(c.x(), 0.0f, 1.0f), std::clamp(c.y(), 0.0f, 1.0f),
  34. std::clamp(c.z(), 0.0f, 1.0f));
  35. }
  36. inline QVector3D clamp01(const QVector3D &c) {
  37. return QVector3D(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 float hashTo01(uint32_t h) {
  41. h ^= h >> 17;
  42. h *= 0xed5ad4bbu;
  43. h ^= h >> 11;
  44. h *= 0xac4c1b51u;
  45. h ^= h >> 15;
  46. h *= 0x31848babu;
  47. h ^= h >> 14;
  48. return (h & 0x00FFFFFFu) / float(0x01000000);
  49. }
  50. inline float linstep(float a, float b, float x) {
  51. return std::clamp((x - a) / std::max(1e-6f, (b - a)), 0.0f, 1.0f);
  52. }
  53. inline float smooth(float a, float b, float x) {
  54. float t = linstep(a, b, x);
  55. return t * t * (3.0f - 2.0f * t);
  56. }
  57. inline float valueNoise(float x, float z, uint32_t salt = 0u) {
  58. int x0 = int(std::floor(x)), z0 = int(std::floor(z));
  59. int x1 = x0 + 1, z1 = z0 + 1;
  60. float tx = x - float(x0), tz = z - float(z0);
  61. float n00 = hashTo01(hashCoords(x0, z0, salt));
  62. float n10 = hashTo01(hashCoords(x1, z0, salt));
  63. float n01 = hashTo01(hashCoords(x0, z1, salt));
  64. float n11 = hashTo01(hashCoords(x1, z1, salt));
  65. float nx0 = n00 * (1 - tx) + n10 * tx;
  66. float nx1 = n01 * (1 - tx) + n11 * tx;
  67. return nx0 * (1 - tz) + nx1 * tz;
  68. }
  69. } // namespace
  70. namespace Render::GL {
  71. TerrainRenderer::TerrainRenderer() = default;
  72. TerrainRenderer::~TerrainRenderer() = default;
  73. void TerrainRenderer::configure(const Game::Map::TerrainHeightMap &heightMap,
  74. const Game::Map::BiomeSettings &biomeSettings) {
  75. m_width = heightMap.getWidth();
  76. m_height = heightMap.getHeight();
  77. m_tileSize = heightMap.getTileSize();
  78. m_heightData = heightMap.getHeightData();
  79. m_terrainTypes = heightMap.getTerrainTypes();
  80. m_biomeSettings = biomeSettings;
  81. m_noiseSeed = biomeSettings.seed;
  82. buildMeshes();
  83. }
  84. void TerrainRenderer::submit(Renderer &renderer, ResourceManager *resources) {
  85. if (m_chunks.empty()) {
  86. return;
  87. }
  88. Q_UNUSED(resources);
  89. auto &visibility = Game::Map::VisibilityService::instance();
  90. const bool useVisibility = visibility.isInitialized();
  91. for (const auto &chunk : m_chunks) {
  92. if (!chunk.mesh)
  93. continue;
  94. if (useVisibility) {
  95. bool anyVisible = false;
  96. for (int gz = chunk.minZ; gz <= chunk.maxZ && !anyVisible; ++gz) {
  97. for (int gx = chunk.minX; gx <= chunk.maxX; ++gx) {
  98. if (visibility.stateAt(gx, gz) ==
  99. Game::Map::VisibilityState::Visible) {
  100. anyVisible = true;
  101. break;
  102. }
  103. }
  104. }
  105. if (!anyVisible)
  106. continue;
  107. }
  108. renderer.terrainChunk(chunk.mesh.get(), kIdentityMatrix, chunk.params,
  109. 0x0080u, true, 0.0f);
  110. }
  111. }
  112. int TerrainRenderer::sectionFor(Game::Map::TerrainType type) const {
  113. switch (type) {
  114. case Game::Map::TerrainType::Mountain:
  115. return 2;
  116. case Game::Map::TerrainType::Hill:
  117. return 1;
  118. case Game::Map::TerrainType::Flat:
  119. default:
  120. return 0;
  121. }
  122. }
  123. void TerrainRenderer::buildMeshes() {
  124. QElapsedTimer timer;
  125. timer.start();
  126. m_chunks.clear();
  127. if (m_width < 2 || m_height < 2 || m_heightData.empty()) {
  128. return;
  129. }
  130. float minH = std::numeric_limits<float>::infinity();
  131. float maxH = -std::numeric_limits<float>::infinity();
  132. for (float h : m_heightData) {
  133. minH = std::min(minH, h);
  134. maxH = std::max(maxH, h);
  135. }
  136. const float heightRange = std::max(1e-4f, maxH - minH);
  137. const float halfWidth = m_width * 0.5f - 0.5f;
  138. const float halfHeight = m_height * 0.5f - 0.5f;
  139. const int vertexCount = m_width * m_height;
  140. std::vector<QVector3D> positions(vertexCount);
  141. std::vector<QVector3D> normals(vertexCount, QVector3D(0.0f, 0.0f, 0.0f));
  142. std::vector<QVector3D> faceAccum(vertexCount, QVector3D(0, 0, 0));
  143. for (int z = 0; z < m_height; ++z) {
  144. for (int x = 0; x < m_width; ++x) {
  145. int idx = z * m_width + x;
  146. float worldX = (x - halfWidth) * m_tileSize;
  147. float worldZ = (z - halfHeight) * m_tileSize;
  148. positions[idx] = QVector3D(worldX, m_heightData[idx], worldZ);
  149. }
  150. }
  151. auto accumulateNormal = [&](int i0, int i1, int i2) {
  152. const QVector3D &v0 = positions[i0];
  153. const QVector3D &v1 = positions[i1];
  154. const QVector3D &v2 = positions[i2];
  155. QVector3D normal = QVector3D::crossProduct(v1 - v0, v2 - v0);
  156. normals[i0] += normal;
  157. normals[i1] += normal;
  158. normals[i2] += normal;
  159. };
  160. auto sampleHeightAt = [&](float gx, float gz) {
  161. gx = std::clamp(gx, 0.0f, float(m_width - 1));
  162. gz = std::clamp(gz, 0.0f, float(m_height - 1));
  163. int x0 = int(std::floor(gx));
  164. int z0 = int(std::floor(gz));
  165. int x1 = std::min(x0 + 1, m_width - 1);
  166. int z1 = std::min(z0 + 1, m_height - 1);
  167. float tx = gx - float(x0);
  168. float tz = gz - float(z0);
  169. float h00 = m_heightData[z0 * m_width + x0];
  170. float h10 = m_heightData[z0 * m_width + x1];
  171. float h01 = m_heightData[z1 * m_width + x0];
  172. float h11 = m_heightData[z1 * m_width + x1];
  173. float h0 = h00 * (1.0f - tx) + h10 * tx;
  174. float h1 = h01 * (1.0f - tx) + h11 * tx;
  175. return h0 * (1.0f - tz) + h1 * tz;
  176. };
  177. auto normalFromHeightsAt = [&](float gx, float gz) {
  178. float gx0 = std::clamp(gx - 1.0f, 0.0f, float(m_width - 1));
  179. float gx1 = std::clamp(gx + 1.0f, 0.0f, float(m_width - 1));
  180. float gz0 = std::clamp(gz - 1.0f, 0.0f, float(m_height - 1));
  181. float gz1 = std::clamp(gz + 1.0f, 0.0f, float(m_height - 1));
  182. float hL = sampleHeightAt(gx0, gz);
  183. float hR = sampleHeightAt(gx1, gz);
  184. float hD = sampleHeightAt(gx, gz0);
  185. float hU = sampleHeightAt(gx, gz1);
  186. QVector3D dx(2.0f * m_tileSize, hR - hL, 0.0f);
  187. QVector3D dz(0.0f, hU - hD, 2.0f * m_tileSize);
  188. QVector3D n = QVector3D::crossProduct(dz, dx);
  189. if (n.lengthSquared() > 0.0f)
  190. n.normalize();
  191. return n.isNull() ? QVector3D(0, 1, 0) : n;
  192. };
  193. for (int z = 0; z < m_height - 1; ++z) {
  194. for (int x = 0; x < m_width - 1; ++x) {
  195. int idx0 = z * m_width + x;
  196. int idx1 = idx0 + 1;
  197. int idx2 = (z + 1) * m_width + x;
  198. int idx3 = idx2 + 1;
  199. accumulateNormal(idx0, idx1, idx2);
  200. accumulateNormal(idx2, idx1, idx3);
  201. }
  202. }
  203. for (int i = 0; i < vertexCount; ++i) {
  204. normals[i].normalize();
  205. if (normals[i].isNull())
  206. normals[i] = QVector3D(0.0f, 1.0f, 0.0f);
  207. faceAccum[i] = normals[i];
  208. }
  209. {
  210. std::vector<QVector3D> filtered = normals;
  211. auto getN = [&](int x, int z) -> QVector3D & {
  212. return normals[z * m_width + x];
  213. };
  214. for (int z = 1; z < m_height - 1; ++z) {
  215. for (int x = 1; x < m_width - 1; ++x) {
  216. const int idx = z * m_width + x;
  217. const float h0 = m_heightData[idx];
  218. const float nh = (h0 - minH) / heightRange;
  219. const float hL = m_heightData[z * m_width + (x - 1)];
  220. const float hR = m_heightData[z * m_width + (x + 1)];
  221. const float hD = m_heightData[(z - 1) * m_width + x];
  222. const float hU = m_heightData[(z + 1) * m_width + x];
  223. const float avgNbr = 0.25f * (hL + hR + hD + hU);
  224. const float convexity = h0 - avgNbr;
  225. const QVector3D n0 = normals[idx];
  226. const float slope = 1.0f - std::clamp(n0.y(), 0.0f, 1.0f);
  227. const float ridgeS = smooth(0.35f, 0.70f, slope);
  228. const float ridgeC = smooth(0.00f, 0.20f, convexity);
  229. const float ridgeFactor =
  230. std::clamp(0.5f * ridgeS + 0.5f * ridgeC, 0.0f, 1.0f);
  231. const float baseBoost = 0.6f * (1.0f - nh);
  232. QVector3D acc(0, 0, 0);
  233. float wsum = 0.0f;
  234. for (int dz = -1; dz <= 1; ++dz) {
  235. for (int dx = -1; dx <= 1; ++dx) {
  236. const int nx = x + dx;
  237. const int nz = z + dz;
  238. const int nIdx = nz * m_width + nx;
  239. const float dh = std::abs(m_heightData[nIdx] - h0);
  240. const QVector3D nn = getN(nx, nz);
  241. const float ndot = std::max(0.0f, QVector3D::dotProduct(n0, nn));
  242. const float w_h = 1.0f / (1.0f + 2.0f * dh);
  243. const float w_n = std::pow(ndot, 8.0f);
  244. const float w_b = 1.0f + baseBoost;
  245. const float w_r = 1.0f - ridgeFactor * 0.85f;
  246. const float w = w_h * w_n * w_b * w_r;
  247. acc += nn * w;
  248. wsum += w;
  249. }
  250. }
  251. QVector3D nFiltered = (wsum > 0.0f) ? (acc / wsum) : n0;
  252. nFiltered.normalize();
  253. const QVector3D nOrig = faceAccum[idx];
  254. const QVector3D nFinal =
  255. (ridgeFactor > 0.0f)
  256. ? (nFiltered * (1.0f - ridgeFactor) + nOrig * ridgeFactor)
  257. : nFiltered;
  258. filtered[idx] = nFinal.normalized();
  259. }
  260. }
  261. normals.swap(filtered);
  262. }
  263. auto quadSection = [&](Game::Map::TerrainType a, Game::Map::TerrainType b,
  264. Game::Map::TerrainType c, Game::Map::TerrainType d) {
  265. int priorityA = sectionFor(a);
  266. int priorityB = sectionFor(b);
  267. int priorityC = sectionFor(c);
  268. int priorityD = sectionFor(d);
  269. int result = priorityA;
  270. result = std::max(result, priorityB);
  271. result = std::max(result, priorityC);
  272. result = std::max(result, priorityD);
  273. return result;
  274. };
  275. const int chunkSize = 16;
  276. std::size_t totalTriangles = 0;
  277. for (int chunkZ = 0; chunkZ < m_height - 1; chunkZ += chunkSize) {
  278. int chunkMaxZ = std::min(chunkZ + chunkSize, m_height - 1);
  279. for (int chunkX = 0; chunkX < m_width - 1; chunkX += chunkSize) {
  280. int chunkMaxX = std::min(chunkX + chunkSize, m_width - 1);
  281. struct SectionData {
  282. std::vector<Vertex> vertices;
  283. std::vector<unsigned int> indices;
  284. std::unordered_map<int, unsigned int> remap;
  285. float heightSum = 0.0f;
  286. int heightCount = 0;
  287. float rotationDeg = 0.0f;
  288. bool flipU = false;
  289. float tint = 1.0f;
  290. QVector3D normalSum = QVector3D(0, 0, 0);
  291. float slopeSum = 0.0f;
  292. float heightVarSum = 0.0f;
  293. int statCount = 0;
  294. float aoSum = 0.0f;
  295. int aoCount = 0;
  296. };
  297. SectionData sections[3];
  298. uint32_t chunkSeed = hashCoords(chunkX, chunkZ, m_noiseSeed);
  299. uint32_t variantSeed = chunkSeed ^ 0x9e3779b9u;
  300. float rotationStep = static_cast<float>((variantSeed >> 5) & 3) * 90.0f;
  301. bool flip = ((variantSeed >> 7) & 1u) != 0u;
  302. static const float tintVariants[7] = {0.9f, 0.94f, 0.97f, 1.0f,
  303. 1.03f, 1.06f, 1.1f};
  304. float tint = tintVariants[(variantSeed >> 12) % 7];
  305. for (auto &section : sections) {
  306. section.rotationDeg = rotationStep;
  307. section.flipU = flip;
  308. section.tint = tint;
  309. }
  310. auto ensureVertex = [&](SectionData &section,
  311. int globalIndex) -> unsigned int {
  312. auto it = section.remap.find(globalIndex);
  313. if (it != section.remap.end()) {
  314. return it->second;
  315. }
  316. Vertex v{};
  317. const QVector3D &pos = positions[globalIndex];
  318. const QVector3D &normal = normals[globalIndex];
  319. v.position[0] = pos.x();
  320. v.position[1] = pos.y();
  321. v.position[2] = pos.z();
  322. v.normal[0] = normal.x();
  323. v.normal[1] = normal.y();
  324. v.normal[2] = normal.z();
  325. float texScale = 0.2f / std::max(1.0f, m_tileSize);
  326. float uu = pos.x() * texScale;
  327. float vv = pos.z() * texScale;
  328. if (section.flipU)
  329. uu = -uu;
  330. float ru = uu, rv = vv;
  331. switch (static_cast<int>(section.rotationDeg)) {
  332. case 90: {
  333. float t = ru;
  334. ru = -rv;
  335. rv = t;
  336. } break;
  337. case 180:
  338. ru = -ru;
  339. rv = -rv;
  340. break;
  341. case 270: {
  342. float t = ru;
  343. ru = rv;
  344. rv = -t;
  345. } break;
  346. default:
  347. break;
  348. }
  349. v.texCoord[0] = ru;
  350. v.texCoord[1] = rv;
  351. section.vertices.push_back(v);
  352. unsigned int localIndex =
  353. static_cast<unsigned int>(section.vertices.size() - 1);
  354. section.remap.emplace(globalIndex, localIndex);
  355. section.normalSum += normal;
  356. return localIndex;
  357. };
  358. for (int z = chunkZ; z < chunkMaxZ; ++z) {
  359. for (int x = chunkX; x < chunkMaxX; ++x) {
  360. int idx0 = z * m_width + x;
  361. int idx1 = idx0 + 1;
  362. int idx2 = (z + 1) * m_width + x;
  363. int idx3 = idx2 + 1;
  364. int sectionIndex =
  365. quadSection(m_terrainTypes[idx0], m_terrainTypes[idx1],
  366. m_terrainTypes[idx2], m_terrainTypes[idx3]);
  367. if (sectionIndex > 0) {
  368. SectionData &section = sections[sectionIndex];
  369. unsigned int v0 = ensureVertex(section, idx0);
  370. unsigned int v1 = ensureVertex(section, idx1);
  371. unsigned int v2 = ensureVertex(section, idx2);
  372. unsigned int v3 = ensureVertex(section, idx3);
  373. section.indices.push_back(v0);
  374. section.indices.push_back(v1);
  375. section.indices.push_back(v2);
  376. section.indices.push_back(v2);
  377. section.indices.push_back(v1);
  378. section.indices.push_back(v3);
  379. float quadHeight = (m_heightData[idx0] + m_heightData[idx1] +
  380. m_heightData[idx2] + m_heightData[idx3]) *
  381. 0.25f;
  382. section.heightSum += quadHeight;
  383. section.heightCount += 1;
  384. float nY = (normals[idx0].y() + normals[idx1].y() +
  385. normals[idx2].y() + normals[idx3].y()) *
  386. 0.25f;
  387. float slope = 1.0f - std::clamp(nY, 0.0f, 1.0f);
  388. section.slopeSum += slope;
  389. float hmin =
  390. std::min(std::min(m_heightData[idx0], m_heightData[idx1]),
  391. std::min(m_heightData[idx2], m_heightData[idx3]));
  392. float hmax =
  393. std::max(std::max(m_heightData[idx0], m_heightData[idx1]),
  394. std::max(m_heightData[idx2], m_heightData[idx3]));
  395. section.heightVarSum += (hmax - hmin);
  396. section.statCount += 1;
  397. auto H = [&](int gx, int gz) {
  398. gx = std::clamp(gx, 0, m_width - 1);
  399. gz = std::clamp(gz, 0, m_height - 1);
  400. return m_heightData[gz * m_width + gx];
  401. };
  402. int cx = x, cz = z;
  403. float hC = quadHeight;
  404. float ao = 0.0f;
  405. ao += std::max(0.0f, H(cx - 1, cz) - hC);
  406. ao += std::max(0.0f, H(cx + 1, cz) - hC);
  407. ao += std::max(0.0f, H(cx, cz - 1) - hC);
  408. ao += std::max(0.0f, H(cx, cz + 1) - hC);
  409. ao = std::clamp(ao * 0.15f, 0.0f, 1.0f);
  410. section.aoSum += ao;
  411. section.aoCount += 1;
  412. }
  413. }
  414. }
  415. for (int i = 0; i < 3; ++i) {
  416. SectionData &section = sections[i];
  417. if (section.indices.empty())
  418. continue;
  419. auto mesh = std::make_unique<Mesh>(section.vertices, section.indices);
  420. if (!mesh)
  421. continue;
  422. ChunkMesh chunk;
  423. chunk.mesh = std::move(mesh);
  424. chunk.minX = chunkX;
  425. chunk.maxX = chunkMaxX - 1;
  426. chunk.minZ = chunkZ;
  427. chunk.maxZ = chunkMaxZ - 1;
  428. chunk.type = (i == 0) ? Game::Map::TerrainType::Flat
  429. : (i == 1) ? Game::Map::TerrainType::Hill
  430. : Game::Map::TerrainType::Mountain;
  431. chunk.averageHeight =
  432. (section.heightCount > 0)
  433. ? section.heightSum / float(section.heightCount)
  434. : 0.0f;
  435. const float nhChunk = (chunk.averageHeight - minH) / heightRange;
  436. const float avgSlope =
  437. (section.statCount > 0)
  438. ? (section.slopeSum / float(section.statCount))
  439. : 0.0f;
  440. const float roughness =
  441. (section.statCount > 0)
  442. ? (section.heightVarSum / float(section.statCount))
  443. : 0.0f;
  444. const float centerGX = 0.5f * (chunk.minX + chunk.maxX);
  445. const float centerGZ = 0.5f * (chunk.minZ + chunk.maxZ);
  446. auto Hgrid = [&](int gx, int gz) {
  447. gx = std::clamp(gx, 0, m_width - 1);
  448. gz = std::clamp(gz, 0, m_height - 1);
  449. return m_heightData[gz * m_width + gx];
  450. };
  451. const int cxi = int(centerGX);
  452. const int czi = int(centerGZ);
  453. const float hC = Hgrid(cxi, czi);
  454. const float hL = Hgrid(cxi - 1, czi);
  455. const float hR = Hgrid(cxi + 1, czi);
  456. const float hD = Hgrid(cxi, czi - 1);
  457. const float hU = Hgrid(cxi, czi + 1);
  458. const float convexity = hC - 0.25f * (hL + hR + hD + hU);
  459. const float edgeFactor = smooth(0.25f, 0.55f, avgSlope);
  460. const float entranceFactor =
  461. (1.0f - edgeFactor) * smooth(0.00f, 0.15f, -convexity);
  462. const float plateauFlat = 1.0f - smooth(0.10f, 0.25f, avgSlope);
  463. const float plateauHeight = smooth(0.60f, 0.80f, nhChunk);
  464. const float plateauFactor = plateauFlat * plateauHeight;
  465. QVector3D baseColor = getTerrainColor(chunk.type, chunk.averageHeight);
  466. QVector3D rockTint = m_biomeSettings.rockLow;
  467. float slopeMix = std::clamp(
  468. avgSlope * ((chunk.type == Game::Map::TerrainType::Flat) ? 0.30f
  469. : (chunk.type == Game::Map::TerrainType::Hill) ? 0.60f
  470. : 0.90f),
  471. 0.0f, 1.0f);
  472. slopeMix += 0.15f * edgeFactor;
  473. slopeMix -= 0.10f * entranceFactor;
  474. slopeMix -= 0.08f * plateauFactor;
  475. slopeMix = std::clamp(slopeMix, 0.0f, 1.0f);
  476. float centerWX = (centerGX - halfWidth) * m_tileSize;
  477. float centerWZ = (centerGZ - halfHeight) * m_tileSize;
  478. float macro = valueNoise(centerWX * 0.02f, centerWZ * 0.02f,
  479. m_noiseSeed ^ 0x51C3u);
  480. float macroShade = 0.9f + 0.2f * macro;
  481. float aoAvg = (section.aoCount > 0)
  482. ? (section.aoSum / float(section.aoCount))
  483. : 0.0f;
  484. float aoShade = 1.0f - 0.35f * aoAvg;
  485. QVector3D avgN = section.normalSum;
  486. if (avgN.lengthSquared() > 0.0f)
  487. avgN.normalize();
  488. QVector3D north(0, 0, 1);
  489. float northness = std::clamp(
  490. QVector3D::dotProduct(avgN, north) * 0.5f + 0.5f, 0.0f, 1.0f);
  491. QVector3D coolTint(0.96f, 1.02f, 1.04f);
  492. QVector3D warmTint(1.03f, 1.0f, 0.97f);
  493. QVector3D aspectTint =
  494. coolTint * northness + warmTint * (1.0f - northness);
  495. float featureBright =
  496. 1.0f + 0.08f * plateauFactor - 0.05f * entranceFactor;
  497. QVector3D featureTint =
  498. QVector3D(1.0f + 0.03f * plateauFactor - 0.03f * entranceFactor,
  499. 1.0f + 0.01f * plateauFactor - 0.01f * entranceFactor,
  500. 1.0f - 0.02f * plateauFactor + 0.03f * entranceFactor);
  501. chunk.tint = section.tint;
  502. QVector3D color = baseColor * (1.0f - slopeMix) + rockTint * slopeMix;
  503. color = applyTint(color, chunk.tint);
  504. color *= macroShade;
  505. color.setX(color.x() * aspectTint.x() * featureTint.x());
  506. color.setY(color.y() * aspectTint.y() * featureTint.y());
  507. color.setZ(color.z() * aspectTint.z() * featureTint.z());
  508. color *= aoShade * featureBright;
  509. color = color * 0.96f + QVector3D(0.04f, 0.04f, 0.04f);
  510. chunk.color = clamp01(color);
  511. TerrainChunkParams params;
  512. auto tintColor = [&](const QVector3D &base) {
  513. return clamp01(applyTint(base, chunk.tint));
  514. };
  515. params.grassPrimary = tintColor(m_biomeSettings.grassPrimary);
  516. params.grassSecondary = tintColor(m_biomeSettings.grassSecondary);
  517. params.grassDry = tintColor(m_biomeSettings.grassDry);
  518. params.soilColor = tintColor(m_biomeSettings.soilColor);
  519. params.rockLow = tintColor(m_biomeSettings.rockLow);
  520. params.rockHigh = tintColor(m_biomeSettings.rockHigh);
  521. params.tileSize = std::max(0.001f, m_tileSize);
  522. params.macroNoiseScale = m_biomeSettings.terrainMacroNoiseScale;
  523. params.detailNoiseScale = m_biomeSettings.terrainDetailNoiseScale;
  524. float slopeThreshold = m_biomeSettings.terrainRockThreshold;
  525. float sharpnessMul = 1.0f;
  526. if (chunk.type == Game::Map::TerrainType::Hill) {
  527. slopeThreshold -= 0.08f;
  528. sharpnessMul = 1.25f;
  529. } else if (chunk.type == Game::Map::TerrainType::Mountain) {
  530. slopeThreshold -= 0.16f;
  531. sharpnessMul = 1.60f;
  532. }
  533. slopeThreshold -= 0.05f * edgeFactor;
  534. slopeThreshold += 0.04f * entranceFactor;
  535. slopeThreshold = std::clamp(
  536. slopeThreshold - std::clamp(avgSlope * 0.20f, 0.0f, 0.12f), 0.05f,
  537. 0.9f);
  538. params.slopeRockThreshold = slopeThreshold;
  539. params.slopeRockSharpness =
  540. std::max(1.0f, m_biomeSettings.terrainRockSharpness * sharpnessMul);
  541. float soilHeight = m_biomeSettings.terrainSoilHeight;
  542. if (chunk.type == Game::Map::TerrainType::Hill)
  543. soilHeight -= 0.06f;
  544. else if (chunk.type == Game::Map::TerrainType::Mountain)
  545. soilHeight -= 0.12f;
  546. soilHeight += 0.05f * entranceFactor - 0.03f * plateauFactor;
  547. params.soilBlendHeight = soilHeight;
  548. params.soilBlendSharpness =
  549. std::max(0.75f, m_biomeSettings.terrainSoilSharpness *
  550. (chunk.type == Game::Map::TerrainType::Mountain
  551. ? 0.80f
  552. : 0.95f));
  553. const uint32_t noiseKeyA =
  554. hashCoords(chunk.minX, chunk.minZ, m_noiseSeed ^ 0xB5297A4Du);
  555. const uint32_t noiseKeyB =
  556. hashCoords(chunk.minX, chunk.minZ, m_noiseSeed ^ 0x68E31DA4u);
  557. params.noiseOffset = QVector2D(hashTo01(noiseKeyA) * 256.0f,
  558. hashTo01(noiseKeyB) * 256.0f);
  559. float baseAmp =
  560. m_biomeSettings.heightNoiseAmplitude *
  561. (0.7f + 0.3f * std::clamp(roughness * 0.6f, 0.0f, 1.0f));
  562. if (chunk.type == Game::Map::TerrainType::Mountain)
  563. baseAmp *= 1.25f;
  564. baseAmp *= (1.0f + 0.10f * edgeFactor - 0.08f * plateauFactor -
  565. 0.06f * entranceFactor);
  566. params.heightNoiseStrength = baseAmp;
  567. params.heightNoiseFrequency = m_biomeSettings.heightNoiseFrequency;
  568. params.ambientBoost =
  569. m_biomeSettings.terrainAmbientBoost *
  570. ((chunk.type == Game::Map::TerrainType::Mountain) ? 0.90f : 0.95f);
  571. params.rockDetailStrength =
  572. m_biomeSettings.terrainRockDetailStrength *
  573. (0.75f + 0.35f * std::clamp(avgSlope * 1.2f, 0.0f, 1.0f) +
  574. 0.15f * edgeFactor - 0.10f * plateauFactor -
  575. 0.08f * entranceFactor);
  576. params.tint = clamp01(QVector3D(chunk.tint, chunk.tint, chunk.tint));
  577. params.lightDirection = QVector3D(0.35f, 0.8f, 0.45f);
  578. chunk.params = params;
  579. totalTriangles += chunk.mesh->getIndices().size() / 3;
  580. m_chunks.push_back(std::move(chunk));
  581. }
  582. }
  583. }
  584. }
  585. QVector3D TerrainRenderer::getTerrainColor(Game::Map::TerrainType type,
  586. float height) const {
  587. switch (type) {
  588. case Game::Map::TerrainType::Mountain:
  589. if (height > 4.0f) {
  590. return m_biomeSettings.rockHigh;
  591. }
  592. return m_biomeSettings.rockLow;
  593. case Game::Map::TerrainType::Hill: {
  594. float t = std::clamp(height / 3.0f, 0.0f, 1.0f);
  595. QVector3D grass = m_biomeSettings.grassSecondary * (1.0f - t) +
  596. m_biomeSettings.grassDry * t;
  597. QVector3D rock =
  598. m_biomeSettings.rockLow * (1.0f - t) + m_biomeSettings.rockHigh * t;
  599. float rockBlend = std::clamp(0.25f + 0.5f * t, 0.0f, 0.75f);
  600. return grass * (1.0f - rockBlend) + rock * rockBlend;
  601. }
  602. case Game::Map::TerrainType::Flat:
  603. default: {
  604. float moisture = std::clamp((height - 0.5f) * 0.2f, 0.0f, 0.4f);
  605. QVector3D base = m_biomeSettings.grassPrimary * (1.0f - moisture) +
  606. m_biomeSettings.grassSecondary * moisture;
  607. float dryBlend = std::clamp((height - 2.0f) * 0.12f, 0.0f, 0.3f);
  608. return base * (1.0f - dryBlend) + m_biomeSettings.grassDry * dryBlend;
  609. }
  610. }
  611. }
  612. } // namespace Render::GL