]> git.tdb.fi Git - libs/gl.git/blob - demos/forestpond/data/fluidsim_velocity.glsl
Implement water simulation and surface shader for forest pond
[libs/gl.git] / demos / forestpond / data / fluidsim_velocity.glsl
1 import fluidsim;
2
3 #pragma MSP stage(compute)
4 void main()
5 {
6         ivec2 size = imageSize(velocity_out);
7         ivec2 coord = ivec2(gl_GlobalInvocationID.xy)+ivec2(1, 1);
8         if(coord.x>=size.x-1 || coord.y>=size.y-1)
9                 return;
10
11         float surface = texelFetch(surface_in, coord, 0).x;
12         float depth = surface-texelFetch(bottom_in, coord, 0).x;
13         float surface_left = texelFetch(surface_in, coord-ivec2(1, 0), 0).x;
14         float surface_right = texelFetch(surface_in, coord+ivec2(1, 0), 0).x;
15         float depth_right = surface_right-texelFetch(bottom_in, coord+ivec2(1, 0), 0).x;
16         float surface_down = texelFetch(surface_in, coord-ivec2(0, 1), 0).x;
17         float surface_up = texelFetch(surface_in, coord+ivec2(0, 1), 0).x;
18         float depth_up = surface_up-texelFetch(bottom_in, coord+ivec2(0, 1), 0).x;
19         vec2 velocity = texelFetch(velocity_in, coord, 0).xy;
20
21         // Advection step: move velocity vectors 
22         vec2 uv_coord = (vec2(coord)+vec2(0.5))/size;
23         vec2 offset = vec2(0.5, -0.5)/size;
24         vec2 multi = delta_time/size;
25         vec2 v_right = vec2(velocity.x, textureLod(velocity_in, uv_coord+offset, 0).y);
26         vec2 v_up = vec2(textureLod(velocity_in, uv_coord-offset, 0).x, velocity.y);
27         vec2 new_velocity = vec2(textureLod(velocity_in, uv_coord-v_right*multi, 0).x,
28                 textureLod(velocity_in, uv_coord-v_up*multi, 0).y)*velocity_damping;
29
30         // Update step: change velocities based on surface level differences
31         vec2 source_depth = mix(vec2(depth_right, depth_up), vec2(depth), greaterThan(vec2(surface), vec2(surface_right, surface_up)));
32         new_velocity += (vec2(surface)-vec2(surface_right, surface_up))*0.1*gravity*delta_time*min(source_depth/residual_depth, 1.0);
33
34         if(time>=drop_time && time<=drop_time+0.01 && depth>1.0)
35         {
36                 ivec2 d = coord-drop_pos;
37                 if(d.x*d.x+d.y*d.y<4)
38                 {
39                         float v = cos(fract(time-drop_time)*628.3)*100.0;
40                         new_velocity.x += normalize(vec2(d.x+0.5, d.y)).x*v;
41                         new_velocity.y += normalize(vec2(d.x, d.y+0.5)).y*v;
42                 }
43         }
44
45         imageStore(velocity_out, coord, vec4(new_velocity, 0.0, 0.0));
46 }