Skip to content

Instantly share code, notes, and snippets.

@bzgeb
Last active April 6, 2019 18:50
Show Gist options
  • Save bzgeb/6922387 to your computer and use it in GitHub Desktop.
Save bzgeb/6922387 to your computer and use it in GitHub Desktop.
This is how trees and grass bend
fixed4 TerrainWaveGrass (inout float4 vertex, float waveAmount, fixed4 color)
{
float4 _waveXSize = float4(0.012, 0.02, 0.06, 0.024) * _WaveAndDistance.y;
float4 _waveZSize = float4 (0.006, .02, 0.02, 0.05) * _WaveAndDistance.y;
float4 waveSpeed = float4 (0.3, .5, .4, 1.2) * 4;
float4 _waveXmove = float4(0.012, 0.02, -0.06, 0.048) * 2;
float4 _waveZmove = float4 (0.006, .02, -0.02, 0.1);
float4 waves;
waves = vertex.x * _waveXSize;
waves += vertex.z * _waveZSize;
// Add in time to model them over time
waves += _WaveAndDistance.x * waveSpeed;
float4 s, c;
waves = frac (waves);
FastSinCos (waves, s,c);
s = s * s;
s = s * s;
float lighting = dot (s, normalize (float4 (1,1,.4,.2))) * .7;
s = s * waveAmount;
float3 waveMove = float3 (0,0,0);
waveMove.x = dot (s, _waveXmove);
waveMove.z = dot (s, _waveZmove);
vertex.xz -= waveMove.xz * _WaveAndDistance.z;
// apply color animation
fixed3 waveColor = lerp (fixed3(0.5,0.5,0.5), _WavingTint.rgb, lighting);
// Fade the grass out before detail distance.
// Saturate because Radeon HD drivers on OS X 10.4.10 don't saturate vertex colors properly.
float3 offset = vertex.xyz - _CameraPosition.xyz;
color.a = saturate (2 * (_WaveAndDistance.w - dot (offset, offset)) * _CameraPosition.w);
return fixed4(2 * waveColor * color.rgb, color.a);
}
// Detail bending
inline float4 AnimateVertex(float4 pos, float3 normal, float4 animParams)
{
// animParams stored in color
// animParams.x = branch phase
// animParams.y = edge flutter factor
// animParams.z = primary factor
// animParams.w = secondary factor
float fDetailAmp = 0.1f;
float fBranchAmp = 0.3f;
// Phases (object, vertex, branch)
float fObjPhase = dot(_Object2World[3].xyz, 1);
float fBranchPhase = fObjPhase + animParams.x;
float fVtxPhase = dot(pos.xyz, animParams.y + fBranchPhase);
// x is used for edges; y is used for branches
float2 vWavesIn = _Time.yy + float2(fVtxPhase, fBranchPhase );
// 1.975, 0.793, 0.375, 0.193 are good frequencies
float4 vWaves = (frac( vWavesIn.xxyy * float4(1.975, 0.793, 0.375, 0.193) ) * 2.0 - 1.0);
vWaves = SmoothTriangleWave( vWaves );
float2 vWavesSum = vWaves.xz + vWaves.yw;
// Edge (xz) and branch bending (y)
float3 bend = animParams.y * fDetailAmp * normal.xyz;
bend.y = animParams.w * fBranchAmp;
pos.xyz += ((vWavesSum.xyx * bend) + (_Wind.xyz * vWavesSum.y * animParams.w)) * _Wind.w;
// Primary bending
// Displace position
pos.xyz += animParams.z * _Wind.xyz;
return pos;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment