Created
July 6, 2017 22:46
-
-
Save runewake2/adb8211d1d7133e62ea36b022edb31d2 to your computer and use it in GitHub Desktop.
Grass Physics.CS class from Simulating Grass Physics and Trampling in Compute Shaders video: https://youtu.be/gF1LZNOUb9w
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class GrassPhysics : MonoBehaviour | |
{ | |
[HideInInspector] public ComputeShader calculationEngine; | |
public Texture2D initialInput; | |
public Texture2D springynessMap; | |
public float maxSpringyness; | |
public float recoverySpeed = 1; | |
public bool reinitialize = false; | |
public RenderTexture texture; //TODO: Make private after tests | |
public Texture getSimulatedTexture | |
{ | |
get { return texture; } | |
} | |
private int physicsSimulationId; | |
public Material simulatedMaterial; //TODO: Temporary, move to another class | |
void Start() | |
{ | |
physicsSimulationId = calculationEngine.FindKernel("PhysicsUpdate"); | |
int overwrite = calculationEngine.FindKernel("FlashInput"); | |
texture = new RenderTexture(initialInput.width, initialInput.height, 24); | |
texture.wrapMode = TextureWrapMode.Repeat; | |
texture.enableRandomWrite = true; | |
texture.Create(); | |
// Assign width and height | |
calculationEngine.SetFloat("Width", texture.width); | |
calculationEngine.SetFloat("Height", texture.height); | |
// Assign textures for overwrite | |
calculationEngine.SetTexture(overwrite, "Input", initialInput); | |
calculationEngine.SetTexture(overwrite, "Result", texture); | |
calculationEngine.Dispatch(overwrite, texture.width / 8, texture.height / 8, 1); | |
// Input and output of simulation are the same texture! | |
calculationEngine.SetTexture(physicsSimulationId, "Result", texture); | |
calculationEngine.SetTexture(physicsSimulationId, "SpringynessMap", springynessMap); | |
calculationEngine.SetFloat("MaxSpringyness", maxSpringyness); | |
calculationEngine.SetFloat("RecoverySpeed", 1.0f / recoverySpeed); | |
simulatedMaterial.SetTexture("_DeformationMap", texture); | |
} | |
void FixedUpdate() | |
{ | |
if (reinitialize) // Use this to refresh the current texture if needed. | |
{ | |
Start(); | |
reinitialize = false; | |
} | |
calculationEngine.SetFloat("ElapsedTime", Time.fixedDeltaTime); | |
calculationEngine.Dispatch(physicsSimulationId, texture.width / 8, texture.height / 8, 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment