# 2. A Procedural Grid with the Simple API Part of [[Runtime Mesh Generation]]. Previous: [[1. Mesh Anatomy and the Simple API]]. Next: [[3. The MeshData API and Vertex Layouts]]. > [!warning] Code not compiled in Unity > Type-checked against 6000.5.8f1. `GridTopology` passed the tests in [[6. Mesh Generation Tests Performance and Pitfalls]] on .NET 10. `SimpleGridMesh` was not run in a scene. A grid of quads is the mesh you'll generate most often: terrain patches, water, cloth, floors, heat maps, wave visualizers. Getting its math right once, in a class that doesn't touch `UnityEngine`, pays off in every later part. ## 2.1 The math For `cellsX × cellsZ` cells: - vertices: `(cellsX + 1) × (cellsZ + 1)`. There's one more vertex than cells on each axis. - indices: `cellsX × cellsZ × 6`. That's two triangles per cell, three indices each. - vertex `(x, z)` lives at `z × (cellsX + 1) + x` (row-major, x fastest). So a 255 × 255 cell grid has 256 × 256 = **65,536** vertices, which is one more than a 16-bit index buffer can address. That off-by-one is the most common "why is half my terrain garbage" bug. ```csharp // Assets/Scripts/Meshes/GridTopology.cs using System; /// <summary> /// Pure math for a (cellsX x cellsZ) grid of quads: vertex count, index count, /// and the two clockwise triangles per cell that Unity treats as front-facing. /// No UnityEngine types, so it can be unit-tested outside the Editor. /// </summary> public static class GridTopology { /// <summary>16-bit index buffers address at most 65,535 vertices.</summary> public const int MaxVerticesFor16BitIndices = 65535; public static int VertexCount(int cellsX, int cellsZ) { Validate(cellsX, cellsZ); return (cellsX + 1) * (cellsZ + 1); } public static int IndexCount(int cellsX, int cellsZ) { Validate(cellsX, cellsZ); return cellsX * cellsZ * 6; } public static bool Needs32BitIndices(int cellsX, int cellsZ) => VertexCount(cellsX, cellsZ) > MaxVerticesFor16BitIndices; /// <summary>Row-major vertex index: x runs fastest.</summary> public static int VertexIndex(int x, int z, int cellsX) => z * (cellsX + 1) + x; /// <summary> /// Writes the six indices for cell (x, z) starting at indices[offset]. /// Winding is clockwise when viewed from +Y, which Unity renders as the front face. /// </summary> public static void WriteCell(int x, int z, int cellsX, int[] indices, int offset) { var bl = VertexIndex(x, z, cellsX); var br = bl + 1; var tl = bl + cellsX + 1; var tr = tl + 1; indices[offset + 0] = bl; indices[offset + 1] = tl; indices[offset + 2] = tr; indices[offset + 3] = bl; indices[offset + 4] = tr; indices[offset + 5] = br; } public static int[] BuildIndices(int cellsX, int cellsZ) { var indices = new int[IndexCount(cellsX, cellsZ)]; var o = 0; for (var z = 0; z < cellsZ; z++) for (var x = 0; x < cellsX; x++) { WriteCell(x, z, cellsX, indices, o); o += 6; } return indices; } static void Validate(int cellsX, int cellsZ) { if (cellsX < 1 || cellsZ < 1) throw new ArgumentOutOfRangeException(nameof(cellsX), "A grid needs at least one cell on each axis."); } } ``` Seen from above (+Y), `bl → tl → tr` goes *up then right*, which is clockwise, so the grid faces up. The test in part 6 checks this with a cross product instead of trusting the drawing. ## 2.2 SimpleGridMesh: an animated wave ```csharp // Assets/Scripts/Meshes/SimpleGridMesh.cs using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering; /// <summary> /// Builds a wavy grid with the simple Mesh API (SetVertices / SetUVs / SetTriangles). /// Good for editor tools and meshes that change rarely. Rebuild() reuses lists and the Mesh. /// </summary> [RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))] public sealed class SimpleGridMesh : MonoBehaviour { [SerializeField, Min(1)] int cellsX = 64; [SerializeField, Min(1)] int cellsZ = 64; [SerializeField, Min(0.01f)] float cellSize = 0.25f; [SerializeField] float waveHeight = 0.5f; [SerializeField] float waveFrequency = 0.6f; [SerializeField] bool animate; Mesh _mesh; readonly List<Vector3> _positions = new List<Vector3>(); readonly List<Vector2> _uvs = new List<Vector2>(); int[] _indices; int _builtX = -1, _builtZ = -1; void OnEnable() { _mesh = new Mesh { name = "SimpleGridMesh (runtime)" }; _mesh.MarkDynamic(); GetComponent<MeshFilter>().sharedMesh = _mesh; Rebuild(0f); } void OnDisable() { if (_mesh != null) Destroy(_mesh); _mesh = null; _builtX = _builtZ = -1; } void Update() { if (animate) Rebuild(Time.time); } public void Rebuild(float time) { var topologyChanged = cellsX != _builtX || cellsZ != _builtZ; _positions.Clear(); _uvs.Clear(); for (var z = 0; z <= cellsZ; z++) for (var x = 0; x <= cellsX; x++) { var px = x * cellSize; var pz = z * cellSize; var py = Mathf.Sin(px * waveFrequency + time) * Mathf.Cos(pz * waveFrequency + time) * waveHeight; _positions.Add(new Vector3(px, py, pz)); _uvs.Add(new Vector2((float)x / cellsX, (float)z / cellsZ)); } if (topologyChanged) { _mesh.Clear(); _mesh.indexFormat = GridTopology.Needs32BitIndices(cellsX, cellsZ) ? IndexFormat.UInt32 : IndexFormat.UInt16; _indices = GridTopology.BuildIndices(cellsX, cellsZ); } _mesh.SetVertices(_positions); _mesh.SetUVs(0, _uvs); if (topologyChanged) { _mesh.SetTriangles(_indices, 0, false); _builtX = cellsX; _builtZ = cellsZ; } _mesh.RecalculateNormals(); _mesh.RecalculateBounds(); } } ``` ### Step by step 1. Create a GameObject called `WaveGrid`. Add **SimpleGridMesh**; it adds MeshFilter and MeshRenderer. Give the renderer a Lit material. 2. Leave `cellsX`/`cellsZ` at 64 and `cellSize` at 0.25. That makes a 16 m square. Tick **animate**. 3. Press Play. The grid ripples. 4. Open the **Profiler** (CPU, Hierarchy) and find `SimpleGridMesh.Update`. Look at the time under `Mesh.SetVertices` and `Mesh.RecalculateNormals`. Raise the cells to 200 × 200 (40k vertices) and watch them grow. That cost is what parts 3 and 4 remove. ### Design choices to notice - **Topology is cached.** Indices depend only on the cell counts, so they're rebuilt (and `SetTriangles` called) only when the size changes. Each frame re-uploads positions and UVs only. This is a *Dirty Flag* ([[Game Programming Patterns (Review)]]): remember what you built, and redo only what changed. - **`MarkDynamic()`** hints to the graphics driver that this buffer is rewritten often. Use it on meshes you update every frame. Don't use it on meshes you build once. - **`SetTriangles(_indices, 0, false)`** skips the bounds calculation because `RecalculateBounds()` runs right after, once the new positions are in. - **`indexFormat` is set right after `Clear()` and before `SetTriangles`.** If you set it after the triangles, the triangles that don't fit in 16 bits are already lost. ## 2.3 Make it useful - **Water surface:** feed `Time.time` from a shared clock so every tile matches at the seams. Pair it with [[Water and Stylized Surfaces]] for the shader. For a big ocean, move the wave into a vertex shader instead. The CPU should only generate what gameplay needs to *query* (buoyancy). - **Music visualizer:** replace the sine with FFT bins. [[Music Visualization]] already has the spectrum code. - **Gray-box floor:** for a level whose layout is data, generate floor tiles from the same grid that [[Procedural Generation]] lays out. Then the art matches the logic exactly.