I’m trying to get Graphics.RenderPrimitivesIndexedIndirect to work in a Web build using the WebGPU graphics api. I have managed to get Graphics.RenderMesh to work, but none of the render primitives methods seem to work. By this I mean, the objects display when running in the editor, but not in the web build.
I have used the chrome extension WebGPU Inspector and from a capture can see that there are zero draw calls coming from the Graphics.RenderPrimitivesIndexedIndirect call. In fact, if I remove all meshes from the scene I can clearly see there are no opaque draws at all.
So my first question is, do the render primitive methods work at all for WebGPU?
My follow up question being, if they do work, what am I doing wrong?
Here’s the full script which sets up the compute shader and the draw call. Sorry, it’s very messy, I’ve just been messing around today.
using System.Collections.Generic;
using Unity.Collections;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.Rendering;
public class PolygonManager : MonoBehaviour
{
/*
The purpose of this MonoBehaviour is to read the positions associated with an
array of line renderers and pass them to a compute buffer which
computes an extrusion of each 2d shape lying along the xz plane defined by
each line renderer.
*/
private struct SourceShape
{
public int pointsBufferOffset;
public int pointsBufferSize;
public override string ToString()
{
return string.Format("{0} <= x < {1}", pointsBufferOffset, pointsBufferOffset + pointsBufferSize);
}
}
private struct SourcePoint
{
public float3 position;
}
private struct DebugInfo
{
public int success;
public int errorCode;
public override string ToString()
{
string[] errors = new string[]
{
"None",
"Dequeue failure",
"Enqueue failure",
"Ear clipping failed to resolve",
"Ear clipping terminated incorrectly",
"Not enough points",
"Queue overflow"
};
return string.Format("Result {0} - {1}",
success.ToString() + "/" + (success == 1 ? "Failure" : success == 2 ? "Success" : "Unknown"),
errorCode.ToString() + "/" + (errorCode < 0 ? "UNDEFINED [< 0]" : errorCode >= errors.Length ? "UNDEFINED [OUT OF ARRAY BOUNDS]" : errors[errorCode])
);
}
}
[SerializeField]
private LineRenderer[] lineRenderers;
[SerializeField]
private ComputeShader triangulationComputeShader = default;
[SerializeField]
private Material material = default;
// Buffers
private ComputeBuffer sourcePointsBuffer;
private ComputeBuffer sourceShapesBuffer;
private ComputeBuffer drawVertexBuffer;
private GraphicsBuffer drawIndexBuffer;
private GraphicsBuffer computeIndexBuffer;
private GraphicsBuffer argsBuffer;
private ComputeBuffer debugInfoBuffer;
private ComputeBuffer wallFaceNormalBuffer;
private ComputeBuffer heightsBuffer;
// Misc
private int idTriangulationKernel;
private int dispatchSize;
private Bounds combinedBounds;
// Buffer strides
private const int SOURCE_SHAPE_STRIDE = sizeof(int) * 2;
private const int SOURCE_POINT_STRIDE = sizeof(float) * 3;
private const int DRAW_VERTEX_STRIDE = sizeof(float) * 3 * 2;
private const int DEBUG_INFO_STRIDE = sizeof(int) * 2;
private const int WALL_FACE_STRIDE = sizeof(float) * 3;
// Start is called once before the first execution of Update after the MonoBehaviour is created
private void OnEnable()
{
SourceShape[] sourceShapes = new SourceShape[lineRenderers.Length];
List<SourcePoint> sourcePointsList = new List<SourcePoint>();
GraphicsBuffer.IndirectDrawIndexedArgs[] args = new GraphicsBuffer.IndirectDrawIndexedArgs[lineRenderers.Length];
int pointOffset;
combinedBounds = lineRenderers[0].bounds;
DebugInfo[] debugDetails = new DebugInfo[lineRenderers.Length];
// Loop over the line renderers
for (int j = 0; j < lineRenderers.Length; j++)
{
LineRenderer lineRenderer = lineRenderers[j];
// Prepopulate debug details to verify they are changed by the compute shader
debugDetails[j] = new DebugInfo
{
success = 99,
errorCode = 99
};
// Update point offset
pointOffset = sourcePointsList.Count;
// Grow bounds
combinedBounds.Encapsulate(lineRenderer.bounds);
// Copy line renderer positions to native array
NativeArray<Vector3> positions = new NativeArray<Vector3>(lineRenderer.positionCount, Allocator.Temp);
lineRenderer.GetPositions(positions);
// Loop over positions
for (int i = 0; i < positions.Length; i++)
{
sourcePointsList.Add(new SourcePoint { position = (float3)positions[i] });
}
// Construct shape struct to hold offset and length info for buffer
sourceShapes[j] = new SourceShape
{
pointsBufferOffset = pointOffset,
pointsBufferSize = positions.Length
};
// Construct draw args for shapes draw command
args[j] = new GraphicsBuffer.IndirectDrawIndexedArgs
{
indexCountPerInstance = (uint)(sourceShapes[j].pointsBufferSize * 2 - 2) * 6,
instanceCount = 1,
startIndex = (uint)(sourceShapes[j].pointsBufferOffset * 2 - 2 * j) * 6,
baseVertexIndex = 0,
startInstance = 0
};
}
sourceShapesBuffer = new ComputeBuffer(lineRenderers.Length, SOURCE_SHAPE_STRIDE, ComputeBufferType.Structured, ComputeBufferMode.Immutable);
sourceShapesBuffer.SetData(sourceShapes);
debugInfoBuffer = new ComputeBuffer(lineRenderers.Length, DEBUG_INFO_STRIDE, ComputeBufferType.Structured, ComputeBufferMode.Immutable);
debugInfoBuffer.SetData(debugDetails);
sourcePointsBuffer = new ComputeBuffer(sourcePointsList.Count, SOURCE_POINT_STRIDE, ComputeBufferType.Structured, ComputeBufferMode.Immutable);
sourcePointsBuffer.SetData(sourcePointsList);
drawVertexBuffer = new ComputeBuffer(sourcePointsList.Count, DRAW_VERTEX_STRIDE, ComputeBufferType.Structured, ComputeBufferMode.Immutable);
// The next buffer creation is likely redundant
// It has been added along with a buffer copy
// just in case the WebGPU build was failing due
// to incompatibility with an index buffer marked
// structured. I think this is just a DX11 issue
// though
// Compute shader writes to this (Structured only)
computeIndexBuffer = new GraphicsBuffer(
GraphicsBuffer.Target.Structured | GraphicsBuffer.Target.CopySource,
(sourcePointsList.Count * 2 - sourceShapes.Length * 2) * 6,
sizeof(uint)
);
// Rendering reads from this (Index only)
drawIndexBuffer = new GraphicsBuffer(
GraphicsBuffer.Target.Index | GraphicsBuffer.Target.CopyDestination,
(sourcePointsList.Count * 2 - sourceShapes.Length * 2) * 6,
sizeof(uint)
);
wallFaceNormalBuffer = new ComputeBuffer(sourcePointsList.Count * 2, WALL_FACE_STRIDE, ComputeBufferType.Structured, ComputeBufferMode.Immutable);
heightsBuffer = new ComputeBuffer(sourceShapes.Length, sizeof(float), ComputeBufferType.Structured, ComputeBufferMode.Dynamic);
heightsBuffer.SetData(new float[] { 5, 10 });
argsBuffer = new GraphicsBuffer(GraphicsBuffer.Target.IndirectArguments, sourceShapes.Length, GraphicsBuffer.IndirectDrawIndexedArgs.size);
argsBuffer.SetData(args);
idTriangulationKernel = triangulationComputeShader.FindKernel("Main");
// Set buffers for compute shader
triangulationComputeShader.SetBuffer(idTriangulationKernel, "_SourcePoints", sourcePointsBuffer);
triangulationComputeShader.SetBuffer(idTriangulationKernel, "_SourceShapes", sourceShapesBuffer);
triangulationComputeShader.SetBuffer(idTriangulationKernel, "_DrawVertexes", drawVertexBuffer);
triangulationComputeShader.SetBuffer(idTriangulationKernel, "_DrawIndexes", computeIndexBuffer);
triangulationComputeShader.SetBuffer(idTriangulationKernel, "_DebugDetails", debugInfoBuffer);
triangulationComputeShader.SetBuffer(idTriangulationKernel, "_WallFaceNormals", wallFaceNormalBuffer);
triangulationComputeShader.SetInt("_NumShapes", lineRenderers.Length);
// Determine dispatch size
triangulationComputeShader.GetKernelThreadGroupSizes(idTriangulationKernel, out uint threadGroupSize, out _, out _);
dispatchSize = Mathf.CeilToInt((float)lineRenderers.Length / threadGroupSize);
}
private void OnDisable()
{
sourcePointsBuffer.Release();
sourceShapesBuffer.Release();
drawVertexBuffer.Release();
drawIndexBuffer.Release();
argsBuffer.Release();
}
// Update is called once per frame
private void LateUpdate()
{
Debug.Log($"Dispatching {dispatchSize} thread groups for {lineRenderers.Length} shapes");
triangulationComputeShader.Dispatch(idTriangulationKernel, dispatchSize, 1, 1);
Graphics.CopyBuffer(computeIndexBuffer, drawIndexBuffer);
// Probably not needed, added just to see if it would fix WebGPU issue
#if UNITY_WEBGL
CommandBuffer cmd = new CommandBuffer();
cmd.name = "Compute-Graphics Barrier";
Graphics.ExecuteCommandBuffer(cmd);
cmd.Release();
#endif
// Commented out calls to various debug functions which print results of compute shader
// AsyncGPUReadback.Request(debugInfoBuffer, DebugInfoCallback);
// AsyncGPUReadback.Request(drawIndexBuffer, DrawIndexCallback);
// AsyncGPUReadback.Request(drawVertexBuffer, DrawVertexCallback);
// AsyncGPUReadback.Request(wallFaceNormalBuffer, WallFaceNormalCallback);
// Modulate height of extrusions for interest
float[] heights = new float[lineRenderers.Length];
for (int i = 0; i < lineRenderers.Length; i++)
{
heights[i] = Mathf.Sin(Time.realtimeSinceStartup * (i + 13) / 10f) * 7f;
}
heightsBuffer.SetData(heights);
// Render each shape as its own instance
RenderParams rp = new RenderParams(material);
rp.shadowCastingMode = ShadowCastingMode.Off;
rp.worldBounds = new Bounds(new Vector3(), new Vector3(100000, 100000, 100000));
rp.matProps = new MaterialPropertyBlock();
// Assign buffers
rp.matProps.SetBuffer("_DrawVertexes", drawVertexBuffer);
rp.matProps.SetBuffer("_SourceShapes", sourceShapesBuffer);
rp.matProps.SetBuffer("_WallFaceNormals", wallFaceNormalBuffer);
rp.matProps.SetBuffer("_Heights", heightsBuffer);
// Draw all shapes with multi-draw indirect
Graphics.RenderPrimitivesIndexedIndirect(
rp,
MeshTopology.Triangles,
drawIndexBuffer,
argsBuffer,
lineRenderers.Length
);
}
private void DebugInfoCallback(AsyncGPUReadbackRequest req)
{
Debug.Log("Callback on GPU read");
NativeArray<DebugInfo> result = req.GetData<DebugInfo>();
for (int i = 0; i < result.Length; i++)
{
Debug.LogFormat("Got result: {0}", result[i]);
}
}
private void DrawIndexCallback(AsyncGPUReadbackRequest req)
{
Debug.Log("Callback on GPU read");
NativeArray<int> result = req.GetData<int>();
string indexes = "";
for (int i = 0; i < result.Length; i++)
{
indexes += result[i].ToString() + ",";
}
Debug.LogFormat("Indexes: {0}", indexes);
}
private void DrawVertexCallback(AsyncGPUReadbackRequest req)
{
Debug.Log("Callback on GPU read");
NativeArray<float3> result = req.GetData<float3>();
string indexes = "";
for (int i = 0; i < result.Length; i++)
{
indexes += result[i].ToString() + ",";
}
Debug.LogFormat("Vertexes: {0}", indexes);
}
private void WallFaceNormalCallback(AsyncGPUReadbackRequest req)
{
Debug.Log("Callback on GPU read");
NativeArray<float3> result = req.GetData<float3>();
string indexes = "";
for (int i = 0; i < result.Length; i++)
{
indexes += result[i].ToString() + ",";
}
Debug.LogFormat("Wall face normals: {0}", indexes);
}
}