Repository navigation
Expand file tree
/
Copy pathTerrain.cpp
More file actions
395 lines (320 loc) · 12.1 KB
/
Copy pathTerrain.cpp
File metadata and controls
395 lines (320 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
#include "Terrain.h"
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include "common/texture.h"
#include <iostream>
using namespace glm;
Terrain::Terrain(int width, int height, float amplitude)
: width(width), height(height), amplitude(amplitude),
vao(0), vbo(0), ebo(0), textureID_(0)
{
textureID_ = loadSOIL("models/hexagons_medieval.png");
if (textureID_ == 0) {
std::cout << "WARNING: Terrain texture failed to load! Using fallback." << std::endl;
}
generate();
}
Terrain::~Terrain()
{
if (vao) glDeleteVertexArrays(1, &vao);
if (vbo) glDeleteBuffers(1, &vbo);
if (ebo) glDeleteBuffers(1, &ebo);
}
void Terrain::generate()
{
generateHeightmap();
computeNormals();
applyDiagonalSymmetry();
buildMesh();
}
float Terrain::hash(int xi, int zi) const
{
int seed = xi * 45678 + zi * 345678 + 12345;
seed = (seed << 13) ^ seed;
return (1.0f - ((seed * (seed * seed * 12345 + 789123) + 1234567890) & 0x7fffffff) / 2147483647.0f); //returns value between 0 and 1
}
float Terrain::noise(float x, float z) const
{
//divide into cells (fx,fz) of size 1*1
int xi = static_cast<int>(floor(x));
int zi = static_cast<int>(floor(z));
float fx = x - xi;
float fz = z - zi;
//hermite curve
float ux = fx * fx * (3.0f - 2.0f * fx);
float uz = fz * fz * (3.0f - 2.0f * fz);
//assign noise values to corners of the cell
float n00 = hash(xi, zi);
float n01 = hash(xi, zi + 1);
float n10 = hash(xi + 1, zi);
float n11 = hash(xi + 1, zi + 1);
//billinear interpolation
float nz0 = mix(n00, n01, uz);
float nz1 = mix(n10, n11, uz);
return mix(nz0, nz1, ux);
}
void Terrain::generateHeightmap()
{
heightmap.resize(width * height);
float freq = 0.1f;
for (int z = 0; z < height; ++z)
{
for (int x = 0; x < width; ++x)
{
float h =
noise(x * freq, z * freq) * amplitude +
noise(x * freq * 2.5f, z * freq * 2.5f) * (amplitude * 0.25f) +
noise(x * freq * 6.0f, z * freq * 6.0f) * (amplitude * 0.1f);
heightmap[z * width + x] = h; //use z*width + x to store 2D data in 1D array
}
}
}
void Terrain::applyDiagonalSymmetry()
{
int N = std::min(width, height);
for (int z = 0; z < N; ++z)
{
for (int x = 0; x < z; ++x)
{
std::swap(heightmap[z * width + x], heightmap[x * width + z]);
}
}
}
void Terrain::computeNormals()
{
vertices.resize(width * height);
// Set Positions and UVs
for (int z = 0; z < height; ++z)
{
for (int x = 0; x < width; ++x)
{
float h = heightmap[z * width + x];
vertices[z * width + x].pos = vec3(x, h, z);
vertices[z * width + x].normal = vec3(0.0f);
// CALCULATE TEXTURE COORDINATES (UVs)
// This maps the image across the terrain.
// "0.1f" scales the texture so it repeats every 10 units (prevents it looking stretched)
vertices[z * width + x].texCoords = vec2(x * 0.1f, z * 0.1f);
}
}
// Calculate Normals (Standard Logic)
for (int z = 0; z < height - 1; ++z)
{
for (int x = 0; x < width - 1; ++x)
{
vec3 p0 = vertices[z * width + x].pos;
vec3 p1 = vertices[z * width + x + 1].pos;
vec3 p2 = vertices[(z + 1) * width + x].pos;
vec3 p3 = vertices[(z + 1) * width + x + 1].pos;
vec3 n1 = cross(p2 - p0, p1 - p0);
vec3 n2 = cross(p2 - p1, p3 - p1);
vertices[z * width + x].normal += n1;
vertices[z * width + x + 1].normal += n1 + n2;
vertices[(z + 1) * width + x].normal += n1 + n2;
vertices[(z + 1) * width + x + 1].normal += n2;
}
}
// 3. Normalize
for (auto& v : vertices)
{
if (length(v.normal) > 0.0001f)
v.normal = normalize(v.normal);
else
v.normal = vec3(0, 1, 0);
}
}
void Terrain::buildMesh()
{
indices.clear();
for (int z = 0; z < height - 1; ++z)
{
for (int x = 0; x < width - 1; ++x)
{
unsigned int i0 = z * width + x;
unsigned int i1 = z * width + x + 1;
unsigned int i2 = (z + 1) * width + x;
unsigned int i3 = (z + 1) * width + x + 1;
indices.push_back(i0);
indices.push_back(i2);
indices.push_back(i1);
indices.push_back(i1);
indices.push_back(i2);
indices.push_back(i3);
}
}
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
glGenBuffers(1, &ebo);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(TerrainVertex), vertices.data(), GL_DYNAMIC_DRAW); //Changed to DYNAMIC_DRAW so the ground updates without freezing
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), indices.data(), GL_STATIC_DRAW);
// position attribute
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(TerrainVertex), (void*)offsetof(TerrainVertex, pos));
// normal attribute
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(TerrainVertex), (void*)offsetof(TerrainVertex, normal));
// TEXTURE COORDINATES (Attribute 2)
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(TerrainVertex), (void*)offsetof(TerrainVertex, texCoords));
glBindVertexArray(0);
}
void Terrain::draw(const glm::mat4& model)
{
GLuint currentProgram;
glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)¤tProgram);
GLuint modelLoc = glGetUniformLocation(currentProgram, "M");
if (modelLoc != GL_INVALID_INDEX)
glUniformMatrix4fv(modelLoc, 1, GL_FALSE, &model[0][0]);
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(indices.size()), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
}
void Terrain::draw(const glm::mat4& model, GLuint shaderProgram)
{
glUseProgram(shaderProgram);
GLuint modelLoc = glGetUniformLocation(shaderProgram, "model");
if (modelLoc != GL_INVALID_INDEX)
glUniformMatrix4fv(modelLoc, 1, GL_FALSE, &model[0][0]);
//BIND TEXTURE
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureID_);
glUniform1i(glGetUniformLocation(shaderProgram, "diffuseColorSampler"), 0);
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(indices.size()), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
}
glm::vec3 Terrain::getHeightAt(float x, float z) const
{
int xi = static_cast<int>(x);
int zi = static_cast<int>(z);
if (xi < 0 || zi < 0 || xi >= width - 1 || zi >= height - 1)
return vec3(x, 0.0f, z);
float h = heightmap[zi * width + xi];
return vec3(x, h, z);
}
// Flatten terrain area for building placement
void Terrain::flattenArea(const glm::vec3& center, float radius)
{
// Convert world position to grid coordinates
int centerX = static_cast<int>(center.x);
int centerZ = static_cast<int>(center.z);
// Get the height at the center point
float targetHeight = heightmap[centerZ * width + centerX];
// Flatten in a circle around the center
int radiusInt = static_cast<int>(radius) + 1;
for (int z = centerZ - radiusInt; z <= centerZ + radiusInt; ++z)
{
for (int x = centerX - radiusInt; x <= centerX + radiusInt; ++x)
{
// Check bounds
if (x < 0 || x >= width || z < 0 || z >= height) continue;
// Check if within circular radius
float dx = x - center.x;
float dz = z - center.z;
float distance = sqrt(dx * dx + dz * dz);
if (distance <= radius)
{
// Smooth falloff at edges (quadratic)
float falloff = 1.0f - (distance / (radius*radius));
falloff = falloff * falloff; // Square for smoother transition
// Blend between current height and target height
int index = z * width + x;
float currentHeight = heightmap[index];
heightmap[index] = glm::mix(currentHeight, targetHeight, falloff);
// Update vertex position
vertices[index].pos.y = heightmap[index];
}
}
}
// Recalculate normals for affected area
recalculateNormalsInArea(centerX, centerZ, radiusInt);
// Update GPU buffer with new vertex data
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferSubData(GL_ARRAY_BUFFER, 0, vertices.size() * sizeof(TerrainVertex), vertices.data());
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void Terrain::createHole(glm::vec3 position, float radius, float depth) {
// Convert world position to grid coordinates (assuming 1:1 scale)
int centerX = static_cast<int>(position.x);
int centerZ = static_cast<int>(position.z);
int radiusInt = static_cast<int>(radius) + 1;
// Modify Heightmap and Vertex Data
for (int z = centerZ - radiusInt; z <= centerZ + radiusInt; ++z) {
for (int x = centerX - radiusInt; x <= centerX + radiusInt; ++x) {
// Check bounds
if (x < 0 || x >= width || z < 0 || z >= height) continue;
// Calculate distance for the crater shape
float dx = x - position.x;
float dz = z - position.z;
float distance = sqrt(dx * dx + dz * dz);
if (distance <= radius) {
// Bell curve falloff: 1.0 at center, 0.0 at radius edge
float falloff = 1.0f - (distance / (radius*radius));
// Squaring the falloff makes the hole look more like a rounded bowl
falloff = falloff * falloff;
int index = z * width + x;
// Subtract the depth based on the falloff
heightmap[index] -= depth * falloff;
// Update the vertex position for rendering
vertices[index].pos.y = heightmap[index];
}
}
}
// Recalculate Normals (Ensures lighting looks correct inside the hole)
recalculateNormalsInArea(centerX, centerZ, radiusInt);
// Upload to GPU (Using your existing vbo and vertices.data())
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferSubData(GL_ARRAY_BUFFER, 0, vertices.size() * sizeof(TerrainVertex), vertices.data());
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
//Recalculate normals for a specific area
void Terrain::recalculateNormalsInArea(int centerX, int centerZ, int radius)
{
// Expand radius slightly to ensure smooth transitions
int expandedRadius = radius + 2;
int minX = std::max(0, centerX - expandedRadius);
int maxX = std::min(width - 1, centerX + expandedRadius);
int minZ = std::max(0, centerZ - expandedRadius);
int maxZ = std::min(height - 1, centerZ + expandedRadius);
// Reset normals in affected area
for (int z = minZ; z <= maxZ; ++z)
{
for (int x = minX; x <= maxX; ++x)
{
vertices[z * width + x].normal = vec3(0.0f);
}
}
// Recalculate normals from surrounding triangles
for (int z = minZ; z < maxZ; ++z)
{
for (int x = minX; x < maxX; ++x)
{
vec3 p0 = vertices[z * width + x].pos;
vec3 p1 = vertices[z * width + x + 1].pos;
vec3 p2 = vertices[(z + 1) * width + x].pos;
vec3 p3 = vertices[(z + 1) * width + x + 1].pos;
vec3 n1 = cross(p2 - p0, p1 - p0);
vec3 n2 = cross(p2 - p1, p3 - p1);
vertices[z * width + x].normal += n1;
vertices[z * width + x + 1].normal += n1 + n2;
vertices[(z + 1) * width + x].normal += n1 + n2;
vertices[(z + 1) * width + x + 1].normal += n2;
}
}
// Normalize all normals in affected area
for (int z = minZ; z <= maxZ; ++z)
{
for (int x = minX; x <= maxX; ++x)
{
vec3& n = vertices[z * width + x].normal;
if (length(n) > 0.0001f)
n = normalize(n);
else
n = vec3(0, 1, 0);
}
}
}