Skip to content

Instantly share code, notes, and snippets.

@ogrew
Last active May 14, 2022 06:27
Show Gist options
  • Save ogrew/2f4906bc913ceedbfe0316b338808430 to your computer and use it in GitHub Desktop.
Save ogrew/2f4906bc913ceedbfe0316b338808430 to your computer and use it in GitHub Desktop.
DrawMeshInstancedIndirectを試す(その1)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DrawMeshInstancedIndirect_demo : MonoBehaviour
{
public int count = 10000;
public float radius = 10;
public Mesh copyMesh;
public Material material;
private Bounds bounds;
private ComputeBuffer meshPropertiesBuffer;
private ComputeBuffer argsBuffer;
private uint[] args = new uint[5] { 0, 0, 0, 0, 0 };
private struct MeshProperties
{
public Matrix4x4 mat;
public Vector4 color;
public static int Size()
{
return
sizeof(float) * 4 * 4 + sizeof(float) * 4;
}
}
private void Start()
{
SetUp();
}
private void Update()
{
Graphics.DrawMeshInstancedIndirect(copyMesh, 0, material, bounds, argsBuffer);
}
private void OnDisable()
{
ReleaseBuffers();
}
private void SetUp()
{
bounds = new Bounds(transform.position, Vector3.one * (radius + 1));
InitializeBuffers();
}
private void InitializeBuffers()
{
argsBuffer = new ComputeBuffer(1, args.Length * sizeof(uint), ComputeBufferType.IndirectArguments);
args[0] = copyMesh.GetIndexCount(0);
args[1] = (uint)count;
args[2] = copyMesh.GetIndexStart(0);
args[3] = copyMesh.GetBaseVertex(0);
args[4] = 0;
argsBuffer.SetData(args);
meshPropertiesBuffer = new ComputeBuffer(count, MeshProperties.Size());
MeshProperties[] properties = new MeshProperties[count];
for (int i = 0; i < count; i++)
{
MeshProperties props = new MeshProperties();
var pos = Random.insideUnitSphere * radius;
var rot = Quaternion.Euler(
Random.Range(-180, 180),
Random.Range(-180, 180),
Random.Range(-180, 180)
);
var size = Vector3.one;
props.mat = Matrix4x4.TRS(pos, rot, size);
props.color = Color.Lerp(Color.magenta, Color.cyan, Random.value);
properties[i] = props;
}
meshPropertiesBuffer.SetData(properties);
material.SetBuffer("_Properties", meshPropertiesBuffer);
}
private void ReleaseBuffers()
{
if (meshPropertiesBuffer != null)
{
meshPropertiesBuffer.Release();
}
meshPropertiesBuffer = null;
if (argsBuffer != null)
{
argsBuffer.Release();
}
argsBuffer = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment