So, currently I am trying to change vertex positions in a mesh using a Compute Shader and Compute Buffer. As you can see in my compute shader, I’m just trying to make the vertices move around on the y axis. My goal for this is just to learn how it is done, however regardless of what I do nothing seems to work. I feel like there is a very obvious flaw that I am not seeing.
When I run the code, absolutely nothing happens.
My main C# Script below
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MeshDeformScript : MonoBehaviour
{
public struct MyTestVertexData
{
public uint id;
public Vector4 pos;
public Vector3 nor;
public Vector4 tan;
public Vector4 uv;
}
public GameObject go;
public ComputeShader shader;
//Compute
private int _kernel;
private int dispatchCount = 0;
private ComputeBuffer vertexBuffer;
private MyTestVertexData[] meshVertData;
private Mesh mesh;
// Start is called before the first frame update
void Start()
{
//The Mesh
mesh = go.GetComponent<MeshFilter>().mesh;
mesh.name = "My Mesh";
//MeshVertexData array
meshVertData = new MyTestVertexData[mesh.vertexCount];
for (int j=0; j< mesh.vertexCount; j++)
{
meshVertData[j].id = (uint)j;
meshVertData[j].pos = mesh.vertices[j];
meshVertData[j].nor = mesh.normals[j];
meshVertData[j].uv = mesh.uv[j];
meshVertData[j].tan = mesh.tangents[j];
}
//Compute Buffer
vertexBuffer = new ComputeBuffer(mesh.vertexCount, 16*4);
vertexBuffer.SetData(meshVertData);
//Compute Shader kernel
_kernel = shader.FindKernel ("CSMain");
uint threadX = 0;
uint threadY = 0;
uint threadZ = 0;
shader.GetKernelThreadGroupSizes(_kernel, out threadX, out threadY, out threadZ);
dispatchCount = Mathf.CeilToInt(meshVertData.Length / threadX)+1;
shader.SetBuffer(_kernel, "vertexBuffer", vertexBuffer); // read & write
shader.SetInt("_VertexCount",meshVertData.Length);
}
// Update is called once per frame
void Update()
{
shader.SetFloat("_Time",Time.time);
shader.Dispatch (_kernel, dispatchCount , 1, 1);
}
void OnDestroy()
{
vertexBuffer.Release();
}
}
My Compute Shader
#pragma kernel CSMain
struct MyTestVertexData
{
uint id;
float4 pos;
float3 nor;
float4 tan;
float4 uv;
};
//This is only for vertex kernel
RWStructuredBuffer<MyTestVertexData> vertexBuffer;
float _Time;
uint _VertexCount;
//----------------------VERTEX-----------------------------
[numthreads(1,1,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
//Real id
uint rid = vertexBuffer[id.x].id;
vertexBuffer[rid].pos.y = sin(_Time);
}