I’m rendering the output of a 2D cellular simulation as solid colored squares. Cell colors change every frame. Vertex positions are static. My first attempt uses a Mesh and a flat color vertex shader. It works. But I’m new to Unity and graphics coding, so… Are there obvious optimizations I’m missing?
Can/should I use a ParticleSystem? A stretched 2DTexture redered with SetPixels()? Something else?
This is for Android/iOS, so newer GPU features may not be available.
Also, the simulation relies on cell update order, so (I think) not parallelizable enough for a clever simulate-on-the-shader solution as suggested here.
my naive mesh handler
public class PixelGrid : MonoBehaviour {
Mesh mesh;
// called once for setup
public void setGridSpace (int columnCount, int rowCount) {
Vector3[] verticies = new Vector3[4 * columnCount * rowCount];
int[] triangles = new int[6 * columnCount * rowCount];
for (int j=0; j<rowCount; j++) {
for (int i=0; i<columnCount; i++) {
int n = i + j * columnCount;
verticies [4 * n] = new Vector3 (i, j);
verticies [4 * n + 1] = new Vector3 (i, j + 1);
verticies [4 * n + 2] = new Vector3 (i + 1, j);
verticies [4 * n + 3] = new Vector3 (i + 1, j + 1);
triangles [6 * n] = 4 * n;
triangles [6 * n + 1] = 4 * n + 1;
triangles [6 * n + 2] = 4 * n + 2;
triangles [6 * n + 3] = 4 * n + 2;
triangles [6 * n + 4] = 4 * n + 1;
triangles [6 * n + 5] = 4 * n + 3;
}
}
mesh = gameObject.GetComponent<MeshFilter> ().mesh;
mesh.Clear ();
mesh.vertices = verticies;
mesh.triangles = triangles;
mesh.Optimize ();
}
// called every frame
public void setCellColors32 (Color32[] cellColors32) {
Color32[] vertexColors32 = new Color32[4 * cellColors32.Length];
for (int i = 0; i < cellColors32.Length; i++) {
vertexColors32 [4 * i] = cellColors32 *;*
_ vertexColors32 [4 * i + 1] = cellColors32 ;_
_ vertexColors32 [4 * i + 2] = cellColors32 ;
vertexColors32 [4 * i + 3] = cellColors32 ;
* }
mesh.colors32 = vertexColors32;
}
}
----------
my naive flat color vertex shader
Shader “Flat Vertex Color” {
Subshader {
Cull Off
ZWrite Off
Fog { Mode Off }
AlphaTest Off
Blend Off
Pass {
CGPROGRAM*
* #pragma vertex vert*
* #pragma fragment frag*
* struct vertexInput {
float4 vertex : POSITION;
float4 color : COLOR;
};
struct vertexOutput {_
float4 pos : SV_POSITION;
_ float4 color: COLOR;
};
vertexOutput vert(vertexInput v) {
vertexOutput o;_
o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
_ o.color = v.color;
return o;
}
fixed4 frag(vertexOutput i) : COLOR {
return i.color;
}
ENDCG*
* }
}
}*_