In GLSL is it possible to offset vertices based on height map colour?
Posted
by
Rob
on Game Development
See other posts from Game Development
or by Rob
Published on 2013-11-03T23:33:43Z
Indexed on
2013/11/04
16:13 UTC
Read the original article
Hit count: 499
I am attempting to generate some terrain based upon a heightmap. I have generated a 32 x 32 grid and a corresponding height map ->
In my vertex shader I am trying to offset the position of the Y axis based upon the colour of the heightmap, white vertices being higher than black ones.
//Vertex Shader Code
#version 330
uniform mat4 modelMatrix;
uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;
uniform sampler2D heightmap;
layout (location=0) in vec4 vertexPos;
layout (location=1) in vec4 vertexColour;
layout (location=3) in vec2 vertexTextureCoord;
layout (location=4) in float offset;
out vec4 fragCol;
out vec4 fragPos;
out vec2 fragTex;
void main()
{
// Retreive the current pixel's colour
vec4 hmColour = texture(heightmap,vertexTextureCoord);
// Offset the y position by the value of current texel's colour value ?
vec4 offset = vec4(vertexPos.x , vertexPos.y + hmColour.r, vertexPos.z , 1.0);
// Final Position
gl_Position = projectionMatrix * viewMatrix * modelMatrix * offset;
// Data sent to Fragment Shader.
fragCol = vertexColour;
fragPos = vertexPos;
fragTex = vertexTextureCoord;
}
However the code I have produced only creates a grid with none of the y vertices higher than any others.
This is the C++ code that generates the grid and texture co-orientates which I believe to be correct as the texture is mapped to the grid, hence the white blob in the middle.
The grid-lines are generated in the fragment shader, sorry for any confusion.
I have tried multiplying the r value of hmColour by 1000 unfortunately that had no effect.
The only other problem it could be is that the texture coordinate data is incorrect ?
for (int z = 0; z < MAP_Z ; z++)
{
for(int x = 0; x < MAP_X ; x++)
{
//Generate Vertex Buffer
vertexData[iVertex++] = float (x) * MAP_X;
vertexData[iVertex++] = 0;
vertexData[iVertex++] = -(float) (z) * MAP_Z;
//Colour Buffer NOT NEEDED
colourData[iColour++] = 255.0f; // R
colourData[iColour++] = 1.0f; // G
colourData[iColour++] = 0.0f; // B
//Texture Buffer
textureData[iTexture++] = (float ) x * (1.0f / MAP_X);
textureData[iTexture++] = (float ) z * (1.0f / MAP_Z);
}
}
The heightmap texture I am trying to use appears like so (without grid-lines).
This is the corresponding fragment shader
// Fragment Shader Code
#version 330
uniform sampler2D hmTexture;
layout (location=0) out vec4 fragColour;
in vec2 fragTex;
in vec4 pos;
void main(void) {
vec2 line = fragTex * 32;
// Without Gridlines
fragColour = texture(hmTexture,fragTex);
// With grid lines
// + mix(vec4(0.0, 0.0, 1.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0),
// smoothstep(0.05,fract(line.y), 0.99) * smoothstep(0.05,fract(line.x),0.99));
}
© Game Development or respective owner