PDA

View Full Version : How do I move individual vertices from the vertex shader?



hashbrown
05-08-2017, 11:56 AM
I'm a little confused when using the vertex shader. I'm trying to displace each vertex point of my mesh from the vertex shader program using cos(rad), but when I do, all vertices are moved at the same time. I'm guessing this is because the GPU processes all vertex points in parallel?

How am I able to move individual vertex points so I can create something like a 2D or 3D Sinewave? Eventually I'm aiming to make something like this, but I just can't figure out how to move individual vertices from the shader:

https://s14.postimg.org/w3n8p470t/sombrero.png (https://postimg.org/image/w3n8p470t/)

Thanks very much in advance and sorry for such a newbie question. I'll also share my vertex shader code so you know what I've tried:

By the way, I know the following code won't generate that sombrero looking pattern, I was just testing :)



attribute vec4 a_position;
uniform mat4 u_mvp;
uniform float u_timer;


void main() {
vec4 newPos = vec4(a_position.x, u_timer/1000.0, a_position.z, a_position.w);
gl_Position = u_mvp* newPos;
}

john_connor
05-08-2017, 12:55 PM
How am I able to move individual vertex points so I can create something like a 2D or 3D Sinewave?

gl_VertexID is unique for each vertex within a drawcommand
https://www.khronos.org/opengl/wiki/Vertex_Shader#Other_inputs

glDrawArrays(GL_POINTS, 0, 100 * 100); will invoke the program 100 x 100 times
int x = gl_VertexID % 100;
int y = gl_VertexID / 100;
so you can define the 2D position at the ground

hashbrown
05-08-2017, 01:45 PM
gl_VertexID is unique for each vertex within a drawcommand
https://www.khronos.org/opengl/wiki/Vertex_Shader#Other_inputs

glDrawArrays(GL_POINTS, 0, 100 * 100); will invoke the program 100 x 100 times
int x = gl_VertexID % 100;
int y = gl_VertexID / 100;
so you can define the 2D position at the ground

John, I'm pretty sure this is what I'm looking for, is this feature available in WebGL/GLSL1.0? I tried the modulo % operator but unfortunately it doesn't work in glsl 1.0 only GLSL 3.0 and >. So I might have to use the mod function according to some articles on Stack Overflow when using WebGL.

Update:

Nevermind, I found gl_VertexID :) You can't use it with WebGL 1.0, but it's definitely in WebGL 2.0. I found it on the 2.0 spec reference card. Sadly though, WebGL 2.0 is still not in every browser, only 28.71% global reach, compared to WebGL 1.0's 92.07%. I'll try coming up with a WebGL 1.0 alternative.

hashbrown
05-09-2017, 09:15 PM
I figured it out :) Just in case somebody is interested, I was able to displace the vertices in the following manner:



void main() {
vec4 pos = a_position;

float amt = scale * 0.5 * sin(a_position.y * frequency * u_timer) + 1.0;
vec4 dis = vec4(a_normals, 1.0);
pos = a_position + amt * dis;
gl_Position = u_mvp * pos;
}