summaryrefslogtreecommitdiff
path: root/game
diff options
context:
space:
mode:
authorDan Goodliffe <dan@randomdan.homeip.net>2021-01-28 20:27:54 +0000
committerDan Goodliffe <dan@randomdan.homeip.net>2021-01-28 20:27:54 +0000
commit07cdfc19b7ab39db73d3ac097556b23f2e4a90ce (patch)
treed2d2a09612833bcc19c02fdaf2324875d2db5a59 /game
parentSplit common terrain code out (diff)
downloadilt-07cdfc19b7ab39db73d3ac097556b23f2e4a90ce.tar.bz2
ilt-07cdfc19b7ab39db73d3ac097556b23f2e4a90ce.tar.xz
ilt-07cdfc19b7ab39db73d3ac097556b23f2e4a90ce.zip
Basic support for loading a heightmap from an image
Diffstat (limited to 'game')
-rw-r--r--game/terrain.cpp32
-rw-r--r--game/terrain.h2
2 files changed, 34 insertions, 0 deletions
diff --git a/game/terrain.cpp b/game/terrain.cpp
index fc98f08..3e5c187 100644
--- a/game/terrain.cpp
+++ b/game/terrain.cpp
@@ -9,6 +9,8 @@
#include <gfx/models/vertex.hpp>
#include <glm/glm.hpp>
#include <random>
+#include <stb_image.h>
+#include <stdexcept>
Terrain::Terrain() :
m_vertexArrayObject {}, m_vertexArrayBuffers {}, texture {Texture::cachedTexture.get("res/terrain.png")}
@@ -62,6 +64,36 @@ Terrain::Terrain() :
finish(size, size, resolution);
}
+Terrain::Terrain(const std::string & fileName) :
+ m_vertexArrayObject {}, m_vertexArrayBuffers {}, texture {Texture::cachedTexture.get("res/terrain.png")}
+{
+ constexpr auto resolution {100};
+
+ int width, height, numComponents;
+ unsigned char * data = stbi_load((fileName).c_str(), &width, &height, &numComponents, STBI_grey);
+
+ if (!data) {
+ throw std::runtime_error {"Unable to load heightmap: " + fileName};
+ }
+
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+
+ vertices.reserve((width * height) + 4);
+
+ for (auto z = 0; z < height; z += 1) {
+ for (auto x = 0; x < width; x += 1) {
+ vertices.emplace_back(
+ glm::vec3 {resolution * (x - (width / 2)), ((float)data[x + (z * width)] * 0.1F) - 1.5F,
+ resolution * (z - (height / 2))},
+ glm::vec2 {(x % 2) / 2.01, (z % 2) / 2.01}, glm::vec3 {0, 1, 0});
+ }
+ }
+ stbi_image_free(data);
+
+ finish(width, height, resolution);
+}
+
void
Terrain::finish(unsigned int width, unsigned int height, unsigned int resolution)
{
diff --git a/game/terrain.h b/game/terrain.h
index 0edf4bd..64c4f96 100644
--- a/game/terrain.h
+++ b/game/terrain.h
@@ -8,6 +8,7 @@
#include <gfx/renderable.h>
#include <memory>
#include <special_members.hpp>
+#include <string>
#include <vector>
class Shader;
@@ -16,6 +17,7 @@ class Texture;
class Terrain : public WorldObject, public Renderable {
public:
Terrain();
+ explicit Terrain(const std::string &);
~Terrain() override;
NO_COPY(Terrain);
NO_MOVE(Terrain);