Home > OS >  How to vary the color according to the elevation?
How to vary the color according to the elevation?

Time:02-12

I would like to achieve something like this :

enter image description here

However, I fail to get the Y coordinates (before projection) of a given point inside the Fragment Shader.

Here is my Fragment Shader :

precision mediump float;

vec4 blue = vec4(0.0, 0.0, 1.0, 1.0);
vec4 pink = vec4(1.0, 0.0, 1.0, 1.0);

void main() {
    float y_coordinates = ???
    gl_FragColor = mix(blue , pink , y_coordinates);
}

Should I send them from the Vertex Shader?

CodePudding user response:

Pass the vertex coordinate from the vertex shader to the fragment shader. e.g.:

Vertex shader

attribute vec3 pos;
varying vec3 vertex_pos;

void main() {
    vertex_pos = pos;
    gl_Position = ...;
}

Fragment shader:

precision mediump float;
varying vec3 vertex_pos;

vec4 blue = vec4(0.0, 0.0, 1.0, 1.0);
vec4 pink = vec4(1.0, 0.0, 1.0, 1.0);

void main() {
    gl_FragColor = mix(blue, pink, vertex_pos.y);
}

Note, the y component of the vertex coordinate must be in range [0.0, 1.0]. If your coordinate is in another range, you must map it to the range [0.0, 1.0]. e.g. map from [a, b] to [0.0, 1.0]:

float w = (vertex_pos.y - a) / (b-a);
gl_FragColor = mix(blue, pink, w);
  • Related