PDA

View Full Version : 3D grass decal shader



rks___
11-17-2017, 02:05 AM
Hi, I'm new to GLSL. I'm using libgdx to create a grass patch simulation.

Currently I have 9408 grass decals. Every 3 decals are arranged in a star pattern.

I'm using a DecalBatch (Array of meshes) for the decals with a CameraGroupStrategy with my own shader to render.

Currently I can get the decals top y position to move left and right however it happens very rapidly. The animation looks correct however its way too fast.

The result:
https://media.giphy.com/media/l4Ep7GvDNtI8L4kXm/giphy.gif

I'm unsure if this is because of my terrible vertex shader or if I've done something wrong in the libgdx side of things. Can someone take a look at my logic? :3

Vertex shader:

//attributes
attribute vec4 a_position;
attribute vec4 a_color;
attribute vec2 a_texCoord0;

//input
uniform mat4 u_projectionViewMatrix;
uniform float random;

//output
varying vec4 v_color;
varying vec2 v_texCoords;

void main() {
vec3 movement = vec3(0.2 * ((1.0 - a_texCoord0.y)) * sin(a_position.y + random), 0, 0);
vec4 grass_movement = vec4(a_position.x + movement.x, a_position.y, a_position.z, 1.0);

v_color = a_color;
v_texCoords = a_texCoord0;
gl_Position = u_projectionViewMatrix * grass_movement;
}

This is called by the DecalBatch's render method, it sits in a method part of the CameraGroupStrategy object:

Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
shader.begin();
shader.setUniformMatrix("u_projectionViewMatrix", camera.combined);
shader.setUniformi("u_sampler2D", 0);
shader.setUniformf("random", MathUtils.random(1)); //<-- passed to the vertex shader
shader.end();
Gdx.gl.glDisable(GL20.GL_DEPTH_TEST);

GClements
11-17-2017, 06:49 AM
Currently I can get the decals top y position to move left and right however it happens very rapidly. The animation looks correct however its way too fast.

That's because you're setting the phase to a random value each frame. The phase should increment at a constant rate. Set random to 2*pi*frequency*time, where frequency is the desired oscillation frequency in Hertz (cycles per second) and time is the elapsed time (relative to some fixed point) in seconds.

rks___
11-17-2017, 08:26 PM
Thank you for your help. I got it working!

https://media.giphy.com/media/3ohjV7uTPGJaGvCNbi/giphy.gif

I set random as you said:

...
float phase = 2*pi*frequency*time;
...where I used .2f for the freq and I used libgdx's deltatime for incrementing the time.

rks___
11-19-2017, 01:50 AM
If anyone's interested in the final result:


https://youtu.be/dboU8KWxQ70