Performance Optimization

Improved volumetric flow performance by orders of magnitude
Cleaned up old raymarching support code
Moved asteroid height calculation to vertex shader
Manual culling for asteroid field render update
This commit is contained in:
Reinier Vens 2022-07-19 18:55:17 +01:00
commit be5e7618d6
52 changed files with 1150 additions and 967 deletions

View file

@ -0,0 +1,80 @@
Shader "Aetheria/Asteroid"
{
Properties
{
[NoScaleOffset] _MainTex ("Texture", 2D) = "white" {}
}
CGINCLUDE
#pragma multi_compile_instancing
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc" // for UnityObjectToWorldNormal
#include "Assets/Shaders/Volumetric.cginc"
uniform float _AsteroidVerticalOffset;
struct v2f
{
float2 uv : TEXCOORD0;
half3 ambient : COLOR0;
float4 vertex : SV_POSITION;
};
v2f vert (appdata_base v)
{
v2f o;
UNITY_SETUP_INSTANCE_ID(v);
float3 worldOrigin = mul(unity_ObjectToWorld, float4(0, 0, 0, 1.0)).xyz;
float3 worldPos = mul(unity_ObjectToWorld, float4(v.vertex.xyz, 1.0)).xyz;
const float2 uv = getUV(worldOrigin.xz);
const float surfaceDisp = tex2Dlod(_NebulaSurfaceHeight, half4(uv, 0, 0)).r;
worldPos.y += _AsteroidVerticalOffset - surfaceDisp;
o.vertex = mul(UNITY_MATRIX_VP, float4(worldPos, 1.0));
o.uv = v.texcoord;
// get vertex normal in world space
half3 worldNormal = UnityObjectToWorldNormal(v.normal);
o.ambient = VolumeSampleColorSimple(worldPos, worldNormal).rgb * 10;
return o;
}
sampler2D _MainTex;
fixed4 frag (v2f i) : SV_Target
{
// sample texture
fixed4 col = tex2D(_MainTex, i.uv);
// multiply by lighting
col.rgb *= i.ambient;
return col;
}
float4 frag_shadow(v2f i) : COLOR
{
SHADOW_CASTER_FRAGMENT(i)
}
ENDCG
SubShader
{
Pass
{
Tags {"LightMode"="ForwardBase"}
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
ENDCG
}
Pass
{
Name "ShadowCaster"
Tags { "LightMode" = "ShadowCaster" }
CGPROGRAM
#pragma vertex vert
#pragma fragment frag_shadow
ENDCG
}
}
}

View file

@ -1,10 +1,10 @@
fileFormatVersion: 2
guid: c7e80b274d611c144b9c2cebb238550b
timeCreated: 1521965851
licenseType: Free
guid: 7cbba296f87f57940a560e1645b402f2
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
preprocessorOverride: 0
userData:
assetBundleName:
assetBundleVariant:

View file

@ -1,5 +1,41 @@
#pragma once
#include "./CloudShaderHelper.cginc"
#include "Assets/Shaders/Volumetric.cginc"
float _ExtinctionCoefficient;
struct RaymarchStatus {
float3 intensity;
float depth;
float depthweightsum;
float intTransmittance;
};
void InitRaymarchStatus(inout RaymarchStatus result){
result.intTransmittance = 1.0f;
result.intensity = 0.0f;
result.depthweightsum = 0.00001f;
result.depth = 0.0f;
}
void IntegrateRaymarch(float3 startPos, float3 rayPos, float fade, float stepsize, inout RaymarchStatus result){
float4 c = VolumeSampleColor(rayPos);
float density = c.a;
if (density <= 0.0f)
return;
float extinction = _ExtinctionCoefficient * density / (1-fade);
float clampedExtinction = max(extinction, 1e-7);
float transmittance = exp(-extinction * stepsize);
float3 luminance = c.rgb;
float3 integScatt = (luminance - luminance * transmittance) / clampedExtinction;
float depthWeight = result.intTransmittance * (1-transmittance); //Is it a better idead to use (1-transmittance) * intTransmittance as depth weight?
result.intensity += result.intTransmittance * integScatt;
result.depth += depthWeight * length(rayPos - startPos);
result.depthweightsum += depthWeight;
result.intTransmittance *= transmittance;
}
float GetDensity(float3 startPos, float3 dir, float maxSampleDistance, float raymarchOffset, out float3 intensity,out float depth) {
float raymarchDistance = 0;
@ -14,7 +50,7 @@ float GetDensity(float3 startPos, float3 dir, float maxSampleDistance, float ray
if(raymarchDistance > maxSampleDistance) break;
float step = raymarchDistance - prevRayDist;
float3 rayPos = startPos + dir * raymarchDistance;
float fade = smoothstep(_ProjectionParams.z*.95,_ProjectionParams.z, raymarchDistance);
float fade = smoothstep(_ProjectionParams.z*.9,_ProjectionParams.z, raymarchDistance);
IntegrateRaymarch(startPos, rayPos, fade, step, result);
if (result.intTransmittance < 0.01f) {
result.intTransmittance = 0;

View file

@ -123,7 +123,6 @@ Shader "Aetheria/CloudShader"
#pragma fragment frag
#pragma multi_compile LOW_QUALITY MEDIUM_QUALITY HIGH_QUALITY
#include "./CloudShaderHelper.cginc"
#include "UnityCG.cginc"
#include "Assets/Shaders/PackFloat.cginc"

View file

@ -1,257 +0,0 @@
#include "UnityCG.cginc"
#define EARTH_RADIUS 6371000.0
#define EARTH_CENTER float3(0, -EARTH_RADIUS, 0)
#ifndef SAMPLE_COUNT
#define SAMPLE_COUNT 64
#endif
#define TRANSMITTANCE_SAMPLE_STEP 512.0f
static const float bayerOffsets[3][3] = {
{0, 7, 3},
{6, 5, 2},
{4, 1, 8}
};
//Base shape
float _CloudStartHeight;
float _CloudEndHeight;
sampler3D _BaseTex;
float _BaseTile;
sampler2D _HeightDensity;
//Detal shape
sampler3D _DetailTex;
float _DetailTile;
float _DetailStrength;
//Curl distortion
sampler2D _CurlNoise;
float _CurlTile;
float _CurlStrength;
//Top offset
float _CloudTopOffset;
//Overall cloud size.
float _CloudSize;
//Overall Density
float _CloudOverallDensity;
float _CloudCoverageModifier;
float _CloudTypeModifier;
half4 _WindDirection;
sampler2D _WeatherTex;
float _WeatherTexSize;
//Lighting
float _ScatteringCoefficient;
float _ExtinctionCoefficient;
float _SilverIntensity;
float _SilverSpread;
float SampleDensity(float3 worldPos, int lod, bool cheap, out float wetness);
float Remap(float original_value, float original_min, float original_max, float new_min, float new_max)
{
return new_min + (((original_value - original_min) / (original_max - original_min)) * (new_max - new_min));
}
float RemapClamped(float original_value, float original_min, float original_max, float new_min, float new_max)
{
return new_min + (saturate((original_value - original_min) / (original_max - original_min)) * (new_max - new_min));
}
float HeightPercent(float3 worldPos) {
float sqrMag = worldPos.x * worldPos.x + worldPos.z * worldPos.z;
float heightOffset = EARTH_RADIUS - sqrt(max(0.0, EARTH_RADIUS * EARTH_RADIUS - sqrMag));
return saturate((worldPos.y + heightOffset - _CloudStartHeight) / (_CloudEndHeight-_CloudStartHeight));
}
static float4 cloudGradients[3] = {
float4(0, 0.07, 0.08, 0.15),
float4(0, 0.2, 0.42, 0.6),
float4(0, 0.08, 0.75, 1)
};
float SampleHeight(float heightPercent,float cloudType) {
float4 gradient;
float cloudTypeVal;
if (cloudType < 0.5) {
gradient = lerp(cloudGradients[0], cloudGradients[1], cloudType*2.0);
}
else {
gradient = lerp(cloudGradients[1], cloudGradients[2], (cloudType - 0.5)*2.0);
}
return RemapClamped(heightPercent, gradient.x, gradient.y, 0.0, 1.0)
* RemapClamped(heightPercent, gradient.z, gradient.w, 1.0, 0.0);
}
float3 ApplyWind(float3 worldPos) {
float heightPercent = HeightPercent(worldPos);
// skew in wind direction
worldPos.xz -= (heightPercent) * _WindDirection.xy * _CloudTopOffset;
//animate clouds in wind direction and add a small upward bias to the wind direction
worldPos.xz -= (_WindDirection.xy + float3(0.0, 0.1, 0.0)) * _Time.y * _WindDirection.z;
worldPos.y -= _WindDirection.z * 0.4 * _Time.y;
return worldPos;
}
float HenryGreenstein(float g, float cosTheta) {
float k = 3.0 / (8.0 * 3.1415926f) * (1.0 - g * g) / (2.0 + g * g);
return k * (1.0 + cosTheta * cosTheta) / pow(abs(1.0 + g * g - 2.0 * g * cosTheta), 1.5);
}
float ApplyCoverageToDensity(float sampleResult, float coverage){
sampleResult = RemapClamped(sampleResult, 1.0 - coverage, 1.0, 0.0, 1.0);
sampleResult *= coverage;
return sampleResult;
}
#include "Assets/Shaders/Volumetric.cginc"
float _MultiScatteringA;
float _MultiScatteringB;
float _MultiScatteringC;
//We raymarch to sun using length of pattern 1,2,4,8, corresponding to step value.
//First sample(length 1) should sample at length 0.5, meaning an average inside length 1.
//Second sample should sample at 1.5, meaning an average inside [1, 2],
//Third should sample at 3.0, which is [2, 4]
//Forth at 6.0, meaning [4, 8]
static const float shadowSampleDistance[5] = {
0.5, 1.5, 3.0, 6.0, 12.0
};
static const float shadowSampleContribution[5] = {
1.0f, 1.0f, 2.0f, 4.0f, 8.0f
};
float SampleOpticsDistanceToSun(float3 worldPos) {
int mipmapOffset = 0.5;
float opticsDistance = 0.0f;
[unroll]
for (int i = 0; i < 5; i++) {
half3 direction = _WorldSpaceLightPos0;
float3 samplePoint = worldPos + direction * shadowSampleDistance[i] * TRANSMITTANCE_SAMPLE_STEP;
float wetness;
float sampleResult = SampleDensity(samplePoint, mipmapOffset, true, wetness);
opticsDistance += shadowSampleContribution[i] * TRANSMITTANCE_SAMPLE_STEP * sampleResult;
mipmapOffset += 0.5;
}
return opticsDistance;
}
float SampleEnergy(float3 worldPos, float3 viewDir) {
float opticsDistance = SampleOpticsDistanceToSun(worldPos);
float result = 0.0f;
float cosTheta = dot(viewDir, _WorldSpaceLightPos0);
[unroll]
for (int octaveIndex = 0; octaveIndex < 2; octaveIndex++) { //Multi scattering approximation from Frostbite.
float transmittance = exp(-_ExtinctionCoefficient * pow(_MultiScatteringB, octaveIndex) * opticsDistance);
float ecMult = pow(_MultiScatteringC, octaveIndex);
float phase = lerp(HenryGreenstein(.1f * ecMult, cosTheta), HenryGreenstein((0.99 - _SilverSpread) * ecMult, cosTheta), 0.5f);
result += phase * transmittance * _ScatteringCoefficient * pow(_MultiScatteringA, octaveIndex);
}
return result;
}
//Code from https://area.autodesk.com/blogs/game-dev-blog/volumetric-clouds/.
bool ray_trace_sphere(float3 center, float3 rd, float3 offset, float radius, out float t1, out float t2) {
float3 p = center - offset;
float b = dot(p, rd);
float c = dot(p, p) - (radius * radius);
float f = b * b - c;
if (f >= 0.0) {
float dem = sqrt(f);
t1 = -b - dem;
t2 = -b + dem;
return true;
}
return false;
}
bool resolve_ray_start_end(float3 ws_origin, float3 ws_ray, out float start, out float end) {
//case includes on ground, inside atm, above atm.
float ot1, ot2, it1, it2;
bool outIntersected = ray_trace_sphere(ws_origin, ws_ray, EARTH_CENTER, EARTH_RADIUS + _CloudEndHeight, ot1, ot2);
if (!outIntersected || ot2 < 0.0f)
return false; //you see nothing.
bool inIntersected = ray_trace_sphere(ws_origin, ws_ray, EARTH_CENTER, EARTH_RADIUS + _CloudStartHeight, it1, it2);
if (inIntersected) {
if (it1 * it2 < 0) {
//we're on ground.
start = max(it2, 0);
end = ot2;
}
else {
//we're inside atm, or above atm.
if (ot1 * ot2 < 0) { //Inside atm.
if (it1 > 0.0) {
//Look down.
end = it1;
}
else {
//Look up.
end = ot2;
}
start = 0.0f;
} else { //Outside atm
if (ot1 < 0.0) {
return false;
}
else {
start = ot1;
end = it1;
}
}
}
}
else {
end = ot2;
start = max(ot1, 0);
}
return true;
}
struct RaymarchStatus {
float3 intensity;
float depth;
float depthweightsum;
float intTransmittance;
};
void InitRaymarchStatus(inout RaymarchStatus result){
result.intTransmittance = 1.0f;
result.intensity = 0.0f;
result.depthweightsum = 0.00001f;
result.depth = 0.0f;
}
void IntegrateRaymarch(float3 startPos, float3 rayPos, float fade, float stepsize, inout RaymarchStatus result){
float4 c = VolumeSampleColor(rayPos);
float density = c.a;
if (density <= 0.0f)
return;
float extinction = _ExtinctionCoefficient * density;
float clampedExtinction = max(extinction, 1e-7);
float transmittance = exp(-extinction * stepsize);
float3 luminance = c.rgb * (1-fade);
float3 integScatt = (luminance - luminance * transmittance) / clampedExtinction;
float depthWeight = result.intTransmittance * (1-transmittance); //Is it a better idead to use (1-transmittance) * intTransmittance as depth weight?
result.intensity += result.intTransmittance * integScatt;
result.depth += depthWeight * length(rayPos - startPos);
result.depthweightsum += depthWeight;
result.intTransmittance *= transmittance;
}

View file

@ -142,14 +142,9 @@ void Adjust(uint2 tid : SV_DispatchThreadID)
W_out.GetDimensions(dim.x, dim.y);
float2 uv = (tid + float2(.5,.5)) / dim;
float2 globalPosXZ = (uv - .5) * _FluidTransform.z + _FluidTransform.xy;
float2 gravUV = getUV(globalPosXZ);
float3 globalPos = float3(globalPosXZ.x, -tex2Dlod(_NebulaSurfaceHeight, float4(gravUV, 0, 0)).x, globalPosXZ.y);
float2 f = flow(globalPos).xz * (_FluidTransform.z / dim.x);
float2 prevUV = uv - Delta;
//if(any(prevUV<0)||any(prevUV>1))
W_out[tid] = f;
//else W_out[tid] = lerp(U_in.SampleLevel(samplerU_in, prevUV, 0), f, Damping);
if(any(prevUV<0)||any(prevUV>1))
W_out[tid] = 0;
else W_out[tid] = U_in.SampleLevel(samplerU_in, prevUV, 0);
}

View file

@ -1,41 +1,5 @@
#include "UnityCG.cginc"
//
// Value Noise 3D Deriv
// Return value range of 0.0->1.0, with format float4( value, xderiv, yderiv, zderiv )
//
float4 Value3D_Deriv( float3 P )
{
// https://github.com/BrianSharpe/Wombat/blob/master/Value3D_Deriv.glsl
// establish our grid cell and unit position
float3 Pi = floor(P);
float3 Pf = P - Pi;
float3 Pf_min1 = Pf - 1.0;
// clamp the domain
Pi.xyz = Pi.xyz - floor(Pi.xyz * ( 1.0 / 69.0 )) * 69.0;
float3 Pi_inc1 = step( Pi, float3( (69.0 - 1.5).xxx ) ) * ( Pi + 1.0 );
// calculate the hash
float4 Pt = float4( Pi.xy, Pi_inc1.xy ) + float2( 50.0, 161.0 ).xyxy;
Pt *= Pt;
Pt = Pt.xzxz * Pt.yyww;
float2 hash_mod = float2( 1.0 / ( 635.298681 + float2( Pi.z, Pi_inc1.z ) * 48.500388 ) );
float4 hash_lowz = frac( Pt * hash_mod.xxxx );
float4 hash_highz = frac( Pt * hash_mod.yyyy );
// blend the results and return
float3 blend = Pf * Pf * Pf * (Pf * (Pf * 6.0 - 15.0) + 10.0);
float3 blendDeriv = Pf * Pf * (Pf * (Pf * 30.0 - 60.0) + 30.0);
float4 res0 = lerp( hash_lowz, hash_highz, blend.z );
float4 res1 = lerp( res0.xyxz, res0.zwyw, blend.yyxx );
float4 res3 = lerp( float4( hash_lowz.xy, hash_highz.xy ), float4( hash_lowz.zw, hash_highz.zw ), blend.y );
float2 res4 = lerp( res3.xz, res3.yw, blend.x );
return float4( res1.x, 0.0, 0.0, 0.0 ) + ( float4( res1.yyw, res4.y ) - float4( res1.xxz, res4.x ) ) * float4( blend.x, blendDeriv );
return float4(1,1,1,1);
}
uniform sampler2D _NebulaSurfaceHeight;
float4 _NebulaSurfaceHeight_TexelSize;
uniform sampler2D _NebulaPatch;
@ -73,8 +37,8 @@ uniform half _NebulaFillDensity,
_DynamicIntensity,
_DynamicSkyBoost;
float tri(in float x){return abs(frac(x)-.5);}
float3 tri3(in float3 p){return float3( tri(p.z+tri(p.y*1.)), tri(p.z+tri(p.x*1.)), tri(p.y+tri(p.x*1.)));}
inline float tri(in float x){return abs(frac(x)-.5);}
inline float3 tri3(in float3 p){return float3( tri(p.z+tri(p.y*1.)), tri(p.z+tri(p.x*1.)), tri(p.y+tri(p.x*1.)));}
float triNoise3d(in float3 p)
{
@ -90,12 +54,19 @@ float triNoise3d(in float3 p)
z *= 1.5;
p *= 1.2;
rz+= (tri(p.z+tri(p.x+tri(p.y))))/z;
rz+= tri(p.z+tri(p.x+tri(p.y)))/z;
bp += 0.14;
}
return rz;
}
float3 Tri3D( float3 P )
{
float3 t1 = normalize(tri3(P));
float3 t2 = normalize(tri3(P * 1.61803398875));
return cross(t1,t2);
}
float parabola( float x, float k )
{
return pow( 4.0*x*(1.0-x), k );
@ -120,7 +91,7 @@ float cloudDensity(float3 pos, float surfaceDisp)
const float patchDensity = saturate((-abs(pos.y+patchDisp - _NebulaFloorOffset)+patch)/_NebulaPatchBlend)*_NebulaPatchDensity;
const float floorDist = -dist;
const float floorDensity = floorDist/_NebulaFloorBlend*_NebulaFloorDensity;
const float floorDensity = floorDist/_NebulaFloorBlend;
return patchDensity + max(0,floorDensity);
}
@ -134,18 +105,31 @@ float2 flowTex(float3 pos)
return float3(fluidSample.x,0,fluidSample.y) * (512 / _FluidTransform.z);
}
float2 gravGradient (float2 uv)
{
return float2(
tex2Dlod(_NebulaSurfaceHeight, float4(uv.x + _NebulaSurfaceHeight_TexelSize.x, uv.y, 0, 0)).r - tex2Dlod(_NebulaSurfaceHeight, float4(uv.x - _NebulaSurfaceHeight_TexelSize.x, uv.y, 0, 0)).r,
tex2Dlod(_NebulaSurfaceHeight, float4(uv.x, uv.y + _NebulaSurfaceHeight_TexelSize.y, 0, 0)).r - tex2Dlod(_NebulaSurfaceHeight, float4(uv.x, uv.y - _NebulaSurfaceHeight_TexelSize.y, 0, 0)).r
);
}
float3 flow(float3 pos)
{
const float4 noiseSample1 = Value3D_Deriv( pos / _FlowScale - float3(0,_FlowScroll,0) );
const float4 noiseSample2 = Value3D_Deriv( pos / (_FlowScale * 1.61803398875) - float3(0,_FlowScroll,0) ); // make it golden
return cross(normalize(noiseSample2.yzw), normalize(noiseSample1.yzw)) * _FlowAmplitude;
float3 flowSample = Tri3D( pos / _FlowScale - float3(0,_FlowScroll,0) );
//float2 grad = normalize(gravGradient(getUV(pos.xz)));
flowSample.xyz *= .5;
flowSample.y *= .5;
// flowSample.x += grad.y;
// flowSample.z += -grad.x;
flowSample.xyz *= _FlowAmplitude;
return flowSample;
}
float tri2(in float x){return 1-2*abs(frac(x)-.5);}
float density(float3 pos)
{
float2 uv = getUV(pos.xz);
const float2 uv = getUV(pos.xz);
const float surfaceDisp = tex2Dlod(_NebulaSurfaceHeight, half4(uv, 0, 0)).r;
const float dist = pos.y + surfaceDisp;
float d = pow(abs(dist+_NebulaFillOffset)/_NebulaFillDistance,-_NebulaFillExponent) * _NebulaFillDensity;
@ -156,13 +140,13 @@ float density(float3 pos)
const float3 fl = flow(pos);
const float lerp1 = frac(_Time.y / _FlowPeriod);
const float lerp2 = frac(_Time.y / _FlowPeriod + .5);
const float noise1 = pow(triNoise3d((pos+fl * (lerp1 - .5) * _FlowPeriod) / _NebulaNoiseScale),_NebulaNoiseExponent) * _NebulaNoiseAmplitude * tri2(lerp1);
const float noise2 = pow(triNoise3d((pos+fl * (lerp2 - .5) * _FlowPeriod) / _NebulaNoiseScale),_NebulaNoiseExponent) * _NebulaNoiseAmplitude * tri2(lerp2);
const float noise1 = pow(triNoise3d((pos+fl.xyz * (lerp1 - .5) * _FlowPeriod) / _NebulaNoiseScale),_NebulaNoiseExponent) * _NebulaNoiseAmplitude * tri2(lerp1);
const float noise2 = pow(triNoise3d((pos+fl.xyz * (lerp2 - .5) * _FlowPeriod) / _NebulaNoiseScale),_NebulaNoiseExponent) * _NebulaNoiseAmplitude * tri2(lerp2);
pos.y += (noise1 + noise2) * heightFade;
const float lerp3 = frac(_Time.y / _FlowPeriod * 2 + .25);
const float lerp4 = frac(_Time.y / _FlowPeriod * 2 + .75);
const float noise3 = pow(triNoise3d((pos+fl * (lerp3 - .5) * _FlowPeriod / 2) / _NebulaNoiseScale * 8), _NebulaNoiseExponent) * _NebulaNoiseAmplitude * tri2(lerp3) / 2;
const float noise4 = pow(triNoise3d((pos+fl * (lerp4 - .5) * _FlowPeriod / 2) / _NebulaNoiseScale * 8), _NebulaNoiseExponent) * _NebulaNoiseAmplitude * tri2(lerp4) / 2;
const float noise3 = pow(triNoise3d((pos+fl.xyz * (lerp3 - .5) * _FlowPeriod / 2) / _NebulaNoiseScale * 8), _NebulaNoiseExponent) * _NebulaNoiseAmplitude * tri2(lerp3) / 2;
const float noise4 = pow(triNoise3d((pos+fl.xyz * (lerp4 - .5) * _FlowPeriod / 2) / _NebulaNoiseScale * 8), _NebulaNoiseExponent) * _NebulaNoiseAmplitude * tri2(lerp4) / 2;
pos.y -= (noise3 + noise4) * heightFade;
d += cloudDensity(pos, surfaceDisp);
}