GPU Lightning Weapons

This commit is contained in:
Reinier Vens 2021-02-05 03:21:15 +00:00
commit 8d10e33db0
26 changed files with 1163 additions and 876 deletions

View file

@ -0,0 +1,85 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_Name: Lightning 1
m_Shader: {fileID: 4800000, guid: 21dd485e846b4d3a8213cf5551832776, type: 3}
m_ShaderKeywords:
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _BranchIntensity: 10
- _BumpScale: 1
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _GlossMapScale: 1
- _Glossiness: 0.5
- _GlossyReflections: 1
- _Intensity: 100
- _LeaderIntensity: 100
- _LeaderProgress: 2
- _LeaderSize: 0.025
- _Metallic: 0
- _Mode: 0
- _OcclusionStrength: 1
- _Parallax: 0.02
- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _UVSec: 0
- _ZWrite: 1
m_Colors:
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _EndColor: {r: 1, g: 0.049999997, b: 0.049999997, a: 1}
- _StartColor: {r: 1, g: 0.20970267, b: 0.051643193, a: 1}
m_BuildTextureStacks: []

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 476f7453551d79b469dda2d6926b93fd
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 2100000
userData:
assetBundleName:
assetBundleVariant:

View file

@ -78,10 +78,9 @@ void UpdateNodes (uint3 id : SV_DispatchThreadID)
float distance = length(bolt.startPos - samplePos);
node.pos = samplePos +
fbm3(float2(distance, _Time + node.bolt * 10)) +
bolt.startOffset * max(.5 - node.time, 0) * 2 +
bolt.endOffset * max(node.time - .5, 0) * 2;
node.pos = samplePos + fbm3(float2(distance, _Time + node.bolt * 10));
if(node.bolt == 0) node.pos += bolt.startOffset * max(.5 - node.time, 0) * 2 + bolt.endOffset * max(node.time - .5, 0) * 2;
else node.pos += bolt.startOffset;
_NodeBuffer[idx] = node;
}
@ -129,10 +128,10 @@ void CreateWidth (uint3 id : SV_DispatchThreadID)
float uvx = bolt.startTime + node.time * (1-bolt.startTime);
v0.pos = pos - right;
v0.uv = float2(uvx, 0);
v0.uv = float2(uvx, 0 + node.bolt);
v1.pos = pos + right;
v1.uv = float2(uvx, 1);
v1.uv = float2(uvx, 1 + node.bolt);
uint vId = idx * 2;
_VertexBuffer[vId] = v0;

View file

@ -56,6 +56,7 @@ Material:
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _BranchIntensity: 10
- _BumpScale: 1
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
@ -63,6 +64,10 @@ Material:
- _GlossMapScale: 1
- _Glossiness: 0.5
- _GlossyReflections: 1
- _Intensity: 10
- _LeaderIntensity: 100
- _LeaderProgress: 0.81259537
- _LeaderSize: 0.025
- _Metallic: 0
- _Mode: 0
- _OcclusionStrength: 1
@ -75,6 +80,6 @@ Material:
m_Colors:
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _EndColor: {r: 0.40784314, g: 0.9411765, b: 8, a: 0}
- _StartColor: {r: 16, g: 0.8156863, b: 11.043138, a: 1}
- _EndColor: {r: 0.062478006, g: 0.11552096, b: 0.801, a: 0}
- _StartColor: {r: 0.83699995, g: 0.043821972, b: 0.57845026, a: 1}
m_BuildTextureStacks: []

View file

@ -1,7 +1,12 @@
Shader "Aetheria/GPU Lightning" {
Properties {
[HDR]_StartColor("StartColor", Color) = (1,1,1,1)
[HDR]_EndColor("EndColor", Color) = (0,0,0,1)
_StartColor("StartColor", Color) = (1,1,1,1)
_EndColor("EndColor", Color) = (0,0,0,1)
_Intensity("Intensity", Float) = 1
_LeaderIntensity("LeaderIntensity", Float) = 10
_LeaderProgress("Leader Progress", Float) = 1
_LeaderSize("Leader Size", Float) = .01
_BranchIntensity("Branch Intensity", Float) = 1
}
SubShader {
@ -10,7 +15,6 @@ Pass{
CGPROGRAM
#pragma target 5.0
#pragma shader_feature GPUTRAIL_TRAIL_INDEX_ON
#pragma vertex vert
#pragma fragment frag
@ -18,10 +22,14 @@ Pass{
#include "UnityCG.cginc"
#include "LightningVertex.cginc"
#include "Assets/Shaders/Dither Functions.cginc"
float _Intensity;
float _LeaderIntensity;
float _LeaderProgress;
float _LeaderSize;
float _BranchIntensity;
fixed4 _StartColor;
fixed4 _EndColor;
uint _VerticesPerInstance;
StructuredBuffer<uint> _IndexBuffer;
StructuredBuffer<Vertex> _VertexBuffer;
@ -52,9 +60,15 @@ Pass{
fixed4 frag (vs_out In) : COLOR0
{
// Discard fragments that are further than the leader progress
clip(_LeaderProgress-In.uv.x);
// Simple quadratic curve "texture"
float x = 2 * In.uv.y - 1;
float x = 2 * (In.uv.y % 1) - 1;
float a = 1 - x * x;
float i = In.uv.y > 1 ? _BranchIntensity : _Intensity;
a *= lerp(i, _LeaderIntensity, smoothstep(_LeaderProgress - _LeaderSize * 1.5, _LeaderProgress - _LeaderSize, In.uv.x));
// Apply screen space dithering
float2 screenUV = In.screenPos.xy / In.screenPos.w;
@ -65,6 +79,69 @@ Pass{
ENDCG
}
Pass{
Name "ShadowCaster"
Tags { "LightMode" = "ShadowCaster" }
CGPROGRAM
#pragma target 5.0
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
#include "LightningVertex.cginc"
#include "Assets/Shaders/Dither Functions.cginc"
float _LeaderProgress;
float _LeaderSize;
StructuredBuffer<uint> _IndexBuffer;
StructuredBuffer<Vertex> _VertexBuffer;
Vertex GetVertex(uint indexBufferIdx) {
uint idx = _IndexBuffer[indexBufferIdx];
return _VertexBuffer[idx];
}
struct vs_out {
float4 pos : SV_POSITION;
float4 col : COLOR;
float2 uv : TEXCOORD;
float4 screenPos : TEXCOORD1;
};
vs_out vert (uint id : SV_VertexID, uint iId : SV_InstanceID)
{
vs_out Out;
Vertex vtx = GetVertex(id);
Out.pos = UnityObjectToClipPos(float4(vtx.pos, 1.0));
Out.uv = vtx.uv;
Out.col = 1;
Out.screenPos = ComputeScreenPos(float4(vtx.pos, 1.0));
return Out;
}
fixed4 frag (vs_out In) : COLOR0
{
// Discard fragments that are further than the leader progress
clip(_LeaderProgress-In.uv.x);
// Simple quadratic curve "texture"
float x = 2 * (In.uv.y % 1) - 1;
float a = 1 - x * x;
// Apply screen space dithering
float2 screenUV = In.screenPos.xy / In.screenPos.w;
ditherClip(screenUV, a);
SHADOW_CASTER_FRAGMENT(In)
}
ENDCG
}
}

View file

@ -1,3 +1,4 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
@ -5,12 +6,16 @@ using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.Rendering;
using Unity.Mathematics;
using UnityEngine.InputSystem;
using UnityEngine.Serialization;
using static Unity.Mathematics.math;
using static Unity.Mathematics.noise;
using Random = UnityEngine.Random;
public class LightningCompute : MonoBehaviour
{
public Camera Camera;
[Header("Bolt Properties")]
public Vector3 StartPosition;
public Vector3 EndPosition;
@ -22,7 +27,19 @@ public class LightningCompute : MonoBehaviour
public float NoiseFrequency;
public float NoiseGain;
public float NoiseLacunarity;
public Camera Camera;
public bool FixedEndpoint;
public bool Animate;
[Header("Animation Properties")]
public float LeaderWidth;
public float LeaderDuration;
public float LeaderIntensity;
public float PulseDuration;
public float PulseIntensity;
public float PulseWidth;
public AnimationCurve PulseTrunkIntensityCurve;
public AnimationCurve PulseBranchIntensityCurve;
public AnimationCurve PulseWidthCurve;
[Header("Buffer Sizes")]
public int TrunkNodeCount;
@ -36,6 +53,9 @@ public class LightningCompute : MonoBehaviour
public bool DebugDrawNodes;
public bool DebugDrawVertices;
public Action OnLeaderComplete;
public Action OnPulseComplete;
private Transform _cameraTransform;
private ComputeBuffer _nodeBuffer;
@ -48,6 +68,12 @@ public class LightningCompute : MonoBehaviour
private const int GROUP_SIZE = 64;
private int _updateKernel;
private int _createWidthKernel;
private float _animationStartTime;
private float _time;
private bool _leaderComplete;
private bool _pulseComplete;
private bool _initialized;
private Material _materialInstance;
private int NodeBufferSize => TrunkNodeCount + BranchCount * BranchNodeCount;
private int VertexBufferSize => NodeBufferSize * 2;
@ -78,14 +104,21 @@ public class LightningCompute : MonoBehaviour
void Start()
{
Initialize();
_materialInstance = Instantiate(RenderMaterial);
}
void Initialize()
{
if (_initialized) return;
_initialized = true;
if (!Camera)
Camera = Camera.main;
_cameraTransform = Camera.transform;
_updateKernel = ComputeShader.FindKernel("UpdateNodes");
_createWidthKernel = ComputeShader.FindKernel("CreateWidth");
InitBuffers();
}
void InitBuffers()
{
_nodeBuffer = new ComputeBuffer(NodeBufferSize, Marshal.SizeOf(typeof(Node)));
var nodeList = new List<Node>();
for (int i = 0; i < TrunkNodeCount; i++)
@ -113,17 +146,6 @@ public class LightningCompute : MonoBehaviour
endPos = EndPosition,
startTime = 0
};
for (int i = 0; i < BranchCount; i++)
{
_branchEndpoints[i] = Random.insideUnitSphere * BranchLength;
var parent = nodeList[(int)((float) i / BranchCount * TrunkNodeCount)];
_bolts[i+1] = new Bolt
{
startPos = parent.pos,
endPos = parent.pos + _branchEndpoints[i],
startTime = parent.time
};
}
_boltBuffer.SetData(_bolts);
@ -159,6 +181,24 @@ public class LightningCompute : MonoBehaviour
_indexBuffer = new ComputeBuffer(indexData.Length, Marshal.SizeOf(typeof(uint))); // 1 node to 2 triangles(6vertexs)
_indexBuffer.SetData(indexData);
}
public void StartAnimation()
{
Initialize();
_animationStartTime = Time.time;
_time = Random.value * 1000;
_leaderComplete = false;
_pulseComplete = false;
for (int i = 0; i < BranchCount; i++)
{
_branchEndpoints[i] = Random.insideUnitSphere * BranchLength;
_bolts[i+1] = new Bolt
{
startTime = Random.value * .8f
};
}
}
float fbm(float2 p)
{
@ -183,23 +223,51 @@ public class LightningCompute : MonoBehaviour
void Update()
{
var time = Time.time * MorphSpeed;
_time += Time.deltaTime * MorphSpeed;
if(Animate)
{
var leaderLerp = (Time.time - _animationStartTime) / LeaderDuration;
if (leaderLerp > 1 && !_leaderComplete)
{
OnLeaderComplete?.Invoke();
_leaderComplete = true;
}
var pulseLerp = (Time.time - _animationStartTime - LeaderDuration) / PulseDuration;
if (pulseLerp > 1 && !_pulseComplete)
{
OnPulseComplete?.Invoke();
_pulseComplete = true;
}
ComputeShader.SetFloat("_StartWidth", leaderLerp < 1 ? LeaderWidth : StartWidth * PulseWidthCurve.Evaluate(pulseLerp)*PulseWidth);
ComputeShader.SetFloat("_EndWidth", leaderLerp < 1 ? LeaderWidth : EndWidth * PulseWidthCurve.Evaluate(pulseLerp)*PulseWidth);
_materialInstance.SetFloat("_LeaderProgress", leaderLerp);
_materialInstance.SetFloat("_BranchIntensity", leaderLerp < 1 ? LeaderIntensity : PulseBranchIntensityCurve.Evaluate(pulseLerp) * PulseIntensity);
_materialInstance.SetFloat("_Intensity", leaderLerp < 1 ? LeaderIntensity : PulseTrunkIntensityCurve.Evaluate(pulseLerp) * PulseIntensity);
}
else
{
ComputeShader.SetFloat("_StartWidth", StartWidth);
ComputeShader.SetFloat("_EndWidth", EndWidth);
}
var diff = EndPosition - StartPosition;
var dist = diff.magnitude;
_bolts[0].startPos = StartPosition;
_bolts[0].startOffset = -(Vector3) fbm3(float2(0, time));
_bolts[0].startOffset = -(Vector3) fbm3(float2(0, _time));
_bolts[0].endPos = EndPosition;
_bolts[0].endOffset = -(Vector3) fbm3(float2(dist, time));
_bolts[0].endOffset = FixedEndpoint ? -(Vector3) fbm3(float2(dist, _time)) : Vector3.zero;
for (int i = 0; i < BranchCount; i++)
{
var root = Vector3.Lerp(StartPosition, EndPosition, _bolts[i + 1].startTime);
var rootDist = _bolts[i + 1].startTime * dist;
_bolts[i + 1].startPos =
root + (Vector3) fbm3(float2(rootDist, time)) +
root + (Vector3) fbm3(float2(rootDist, _time)) +
_bolts[0].startOffset * (max(.5f - _bolts[i + 1].startTime, 0) * 2) +
_bolts[0].endOffset * (max(_bolts[i + 1].startTime - .5f, 0) * 2);
_bolts[i + 1].startOffset = -(Vector3) fbm3(float2(0, time + (i + 1) * 10));
_bolts[i + 1].startOffset = -(Vector3) fbm3(float2(0, _time + (i + 1) * 10));
_bolts[i + 1].endPos = root + _branchEndpoints[i];
}
@ -208,7 +276,7 @@ public class LightningCompute : MonoBehaviour
ComputeShader.SetBuffer(_updateKernel, "_NodeBuffer", _nodeBuffer);
ComputeShader.SetBuffer(_updateKernel, "_BoltBuffer", _boltBuffer);
ComputeShader.SetFloat("_Time", time);
ComputeShader.SetFloat("_Time", _time);
ComputeShader.SetFloat("_NoiseAmplitude", NoiseAmplitude);
ComputeShader.SetFloat("_NoiseFrequency", NoiseFrequency);
ComputeShader.SetFloat("_NoiseGain", NoiseGain);
@ -219,8 +287,6 @@ public class LightningCompute : MonoBehaviour
ComputeShader.SetInt("_TrunkNodeCount", TrunkNodeCount);
ComputeShader.SetInt("_BranchNodeCount", BranchNodeCount);
ComputeShader.SetVector("_CameraPos", _cameraTransform.position);
ComputeShader.SetFloat("_StartWidth", StartWidth);
ComputeShader.SetFloat("_EndWidth", EndWidth);
ComputeShader.SetBuffer(_createWidthKernel, "_NodeBuffer", _nodeBuffer);
ComputeShader.SetBuffer(_createWidthKernel, "_BoltBuffer", _boltBuffer);
@ -228,10 +294,10 @@ public class LightningCompute : MonoBehaviour
ComputeShader.Dispatch(_createWidthKernel, NodeBufferSize/GROUP_SIZE, 1, 1);
RenderMaterial.SetBuffer("_IndexBuffer", _indexBuffer);
RenderMaterial.SetBuffer("_VertexBuffer", _vertexBuffer);
_materialInstance.SetBuffer("_IndexBuffer", _indexBuffer);
_materialInstance.SetBuffer("_VertexBuffer", _vertexBuffer);
Graphics.DrawProcedural(
RenderMaterial,
_materialInstance,
new Bounds((EndPosition + StartPosition) / 2, (EndPosition - StartPosition).magnitude * Vector3.one),
MeshTopology.Triangles,
IndexBufferSize,
@ -241,6 +307,9 @@ public class LightningCompute : MonoBehaviour
ShadowCastingMode.Off,
false,
0);
//
// if(pulseLerp > 2)
// StartAnimation();
}
#region cleanup

View file

@ -4,7 +4,7 @@ MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
executionOrder: 55
icon: {instanceID: 0}
userData:
assetBundleName: