Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to vary the color according to the elevation?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading