Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question Compute Shader Dispatch error

Discussion in 'Editor & General Support' started by ripefruits22, Feb 1, 2022.

  1. ripefruits22

    ripefruits22

    Joined:
    Nov 26, 2021
    Posts:
    17
    I'm fairly new to compute shaders and I'm re-writing an already existing compute shader project and trying to figure out what each line does(https://github.com/SebLague/Slime-Simulation), but I'm having troubles with the compute shaders not running, they both give the error: computeShader.compute: Kernel at index (0) is invalid, the lines that are apparently wrong are the Dispatch() lines, line 98 and 111, but there should be no problems with them, here's the current code for the C# script:
    Code (CSharp):
    1. public class Simulation : MonoBehaviour
    2. {
    3.     public enum SpawnMode { Random, Point, InwardCircle, RandomCircle }
    4.  
    5.     const int Update = 0;
    6.     const int blurMap = 1;
    7.  
    8.     public ComputeShader cS;
    9.     public ComputeShader drawAgents;
    10.  
    11.     public SlimeSettings settings;
    12.  
    13.     public bool showAgentsOnly;
    14.  
    15.     [SerializeField, HideInInspector] protected RenderTexture trailMap;
    16.     [SerializeField, HideInInspector] protected RenderTexture diffusedTrailMap;
    17.  
    18.     ComputeBuffer agentBuffer;
    19.  
    20.     protected virtual void Start()
    21.     {
    22.         Init();
    23.         transform.GetComponentInChildren<MeshRenderer>().material.mainTexture = trailMap;
    24.     }
    25.  
    26.     void Init()
    27.     {
    28.         //create render textures
    29.         trailMap = new RenderTexture(settings.width, settings.height, 0);
    30.         trailMap.enableRandomWrite = true;
    31.         trailMap.Create();
    32.  
    33.         diffusedTrailMap = new RenderTexture(settings.width, settings.height, 0);
    34.         diffusedTrailMap.enableRandomWrite = true;
    35.         diffusedTrailMap.Create();
    36.  
    37.         cS.SetTexture(Update, "trailMap", trailMap);
    38.         cS.SetTexture(blurMap, "TrailMap", trailMap);
    39.         cS.SetTexture(blurMap, "diffusedTrailMap", diffusedTrailMap);
    40.         drawAgents.SetTexture(0, "TargetTexture", trailMap);
    41.  
    42.         Agent[] agents = new Agent[settings.numAgents];
    43.         for (int i = 0; i < agents.Length; i++)
    44.         {
    45.             Vector2 centre = new Vector2(settings.width / 2, settings.height / 2);
    46.             Vector2 startPos = Vector2.zero;
    47.             float randomAngle = Random.value * Mathf.PI * 2;
    48.             float angle = 0;
    49.  
    50.             if (settings.spawnMode == SpawnMode.Point)
    51.             {
    52.                 startPos = centre;
    53.                 angle = randomAngle;
    54.             }
    55.             else if (settings.spawnMode == SpawnMode.Random)
    56.             {
    57.                 startPos = new Vector2(Random.Range(0, settings.width), Random.Range(0, settings.height));
    58.                 angle = randomAngle;
    59.             }
    60.             else if (settings.spawnMode == SpawnMode.InwardCircle)
    61.             {
    62.                 startPos = centre + Random.insideUnitCircle * settings.height * 0.5f;
    63.                 angle = Mathf.Atan2((centre - startPos).normalized.y, (centre - startPos).normalized.x);
    64.             }
    65.             else if (settings.spawnMode == SpawnMode.RandomCircle)
    66.             {
    67.                 startPos = centre + Random.insideUnitCircle * settings.height * 0.15f;
    68.                 angle = randomAngle;
    69.             }
    70.  
    71.             agents[i] = new Agent() { position = startPos, angle = angle};
    72.         }
    73.  
    74.         ComputeHelper.CreateAndSetBuffer<Agent>(ref agentBuffer, agents, cS, "agents", Update);
    75.         cS.SetInt("numAgents", settings.numAgents);
    76.  
    77.         drawAgents.SetBuffer(0, "agents", agentBuffer);
    78.         drawAgents.SetInt("numAgents", settings.numAgents);
    79.  
    80.         cS.SetInt("width", settings.width);
    81.         cS.SetInt("height", settings.height);
    82.  
    83.         cS.SetFloat("trailWeight", settings.trailWeight);
    84.     }
    85.  
    86.     private void FixedUpdate()
    87.     {
    88.         for (int i = 0; i < settings.stepsPerFrame; i++)
    89.         {
    90.             RunSimulation();
    91.         }
    92.     }
    93.  
    94.     private void LateUpdate()
    95.     {
    96.         if (showAgentsOnly)
    97.         {
    98.             drawAgents.Dispatch(0, settings.numAgents, 1, 1); //this line is also showing the same error
    99.         }
    100.     }
    101.  
    102.     private void RunSimulation()
    103.     {
    104.         //Assign settings
    105.         cS.SetFloat("deltaTime", Time.fixedDeltaTime);
    106.         cS.SetFloat("time", Time.fixedTime);
    107.  
    108.         cS.SetFloat("decayRate", settings.decayRate);
    109.         cS.SetFloat("diffuseRate", settings.diffuseRate);
    110.  
    111.         cS.Dispatch(Update, settings.numAgents, 1, 1); //this line is showing the error
    112.     }
    113.  
    114.     private void OnDestroy()
    115.     {
    116.         ComputeHelper.Release(agentBuffer);
    117.     }
    118.  
    119.     public struct Agent
    120.     {
    121.         public Vector2 position;
    122.         public float angle;
    123.     }
    124. }


    code for the first compute shader(cS):
    Code (CSharp):
    1. // Each #kernel tells which function to compile; you can have many kernels
    2. #pragma kernel Update
    3.  
    4. struct Agent
    5. {
    6.     float2 position;
    7.     float angle;
    8. };
    9.  
    10. RWStructuredBuffer<Agent> agents;
    11. uint numAgents;
    12.  
    13. RWTexture2D<float4> trailMap;
    14. int width;
    15. int height;
    16.  
    17. float trailWeight;
    18.  
    19. float deltaTime;
    20. float time;
    21.  
    22. // Hash function www.cs.ubc.ca/~rbridson/docs/schechter-sca08-turbulence.pdf
    23. uint hash(uint state)
    24. {
    25.     state ^= 2747636419u;
    26.     state *= 2654435769u;
    27.     state ^= state >> 16;
    28.     state *= 2654435769u;
    29.     state ^= state >> 16;
    30.     state *= 2654435769u;
    31.     return state;
    32. }
    33.  
    34. float scaleToRange01(uint state)
    35. {
    36.     return state / 4294967295.0;
    37. }
    38.  
    39.  
    40.  
    41. [numthreads(16,1,1)]
    42. void Update (uint3 id : SV_DispatchThreadID)
    43. {
    44.     if (id.x >= numAgents) { return; }
    45.  
    46.     Agent agent = agents[id.x];
    47.     float2 pos = agent.position;
    48.  
    49.     uint random = hash(pos.y * width + pos.x + hash(id.x + time * 100000));
    50.  
    51.     // Update position
    52.     float2 direction = float2(cos(agent.angle), sin(agent.angle));
    53.     float2 newPos = agent.position + direction * deltaTime;// * settings.moveSpeed;
    54.  
    55.     // Clamp agent position to map bounds
    56.     if (newPos.x < 0 || newPos.x >= width || newPos.y < 0 || newPos.y >= height) {
    57.         random = hash(random);
    58.         float randomAngle = scaleToRange01(random) * 2 * 3.1415;
    59.  
    60.         newPos.x = min(width-1, max(0, newPos.x));
    61.         newPos.y = min(height-1, max(0, newPos.y));
    62.         agents[id.x].angle = randomAngle;
    63.     } else {
    64.         int2 coord = int2(newPos);
    65.         float4 oldTrail = trailMap[coord];
    66.         trailMap[coord] = min(1, oldTrail * trailWeight * deltaTime);
    67.     }
    68.  
    69.     agents[id.x].position = newPos;
    70. }
    71.  
    72. #pragma kernel Diffuse
    73.  
    74. float decayRate;
    75. float diffuseRate;
    76. RWTexture2D<float4> diffusedTrailMap;
    77.  
    78. [numthreads(8,8,1)]
    79. void Diffuse(uint3 id : SV_DispatchThreadID)
    80. {
    81.     if (id.x < 0 || id.x >= (uint)width || id.y < 0 || id.y >= (uint)height) {
    82.         return;
    83.     }
    84.  
    85.     float4 sum = 0;
    86.     float4 originalCol = TrailMap[id.xy];
    87.     // 3x3 blur
    88.     for (int offsetX = -1; offsetX <= 1; offsetX ++) {
    89.         for (int offsetY = -1; offsetY <= 1; offsetY ++) {
    90.             int sampleX = min(width-1, max(0, id.x + offsetX));
    91.             int sampleY = min(height-1, max(0, id.y + offsetY));
    92.             sum += TrailMap[int2(sampleX,sampleY)];
    93.         }
    94.     }
    95.  
    96.     float4 blurredCol = sum / 9;
    97.     float diffuseWeight = saturate(diffuseRate * deltaTime);
    98.     blurredCol = originalCol * (1 - diffuseWeight) + blurredCol * (diffuseWeight);
    99.  
    100.     DiffusedTrailMap[id.xy] = max(0, blurredCol - decayRate * deltaTime);
    101. }


    and for the last compute shader:
    Code (CSharp):
    1. #pragma kernel DrawAgentMap
    2.  
    3. struct Agent {
    4.     float2 position;
    5.     float angle;
    6. };
    7.  
    8. RWStructuredBuffer<Agent> agents;
    9. uint numAgents;
    10.  
    11. RWTexture2D<float4> TargetTexture;
    12.  
    13. [numthreads(16,1,1)]
    14. void DrawAgentMap (uint3 id : SV_DispatchThreadID)
    15. {
    16.     if (id.x >= numAgents) {
    17.         return;
    18.     }
    19.  
    20.  
    21.     Agent agent = agents[id.x];
    22.     // Draw to trail map
    23.     int cellX = (int)agent.position.x;
    24.     int cellY = (int)agent.position.y;
    25.     TargetTexture[int2(cellX, cellY)] = 1;
    26. }
    Any help would be appreciated.
     
  2. JeffDUnity3D

    JeffDUnity3D

    Unity Technologies

    Joined:
    May 2, 2017
    Posts:
    14,446
  3. ripefruits22

    ripefruits22

    Joined:
    Nov 26, 2021
    Posts:
    17
    Thanks for responding, I should have checked this sort of stuff before but I'll see if there is a solution there or if updating to a newer version of Unity will fix it.
     
  4. ripefruits22

    ripefruits22

    Joined:
    Nov 26, 2021
    Posts:
    17
    I've managed to fix it, the first compute shader had a type, and the second compute shader had I think and encoding issue? For the second one I used save as then selected save with encoding and selected ASCII, and then cut the code out, deleted everything until there was only one line of nothing, then pasted it back and now it works.
     
    JeffDUnity3D likes this.
  5. JeffDUnity3D

    JeffDUnity3D

    Unity Technologies

    Joined:
    May 2, 2017
    Posts:
    14,446
    Typically you would use "git clone" and not use Save As from the website. And any issues you find should be reported on the Issues page I referred to so the author may respond and hopefully fix if you find a valid problem.
     
  6. ripefruits22

    ripefruits22

    Joined:
    Nov 26, 2021
    Posts:
    17
    When I said save as I meant with Visual Studio saving the actual file, sorry for the confusion.
     
    JeffDUnity3D likes this.