Files
grass-cutters/Assets/Scripts/World/GrassField.cs
NiemandKG 57d0f4d31a Frame time on a big farm: batched grass, sleeping bundles, no light probes
Measured in a real 2560x1440 window on the player's Mommy save (RTX 4090):
the GPU took ~5 ms, the main thread the rest.

- Grass: a fully mown sector draws only its floor (one draw, not up to six);
  untouched and fully mown sectors share a mow map look, so the fur pile
  draws them all in one instanced call per pile (GC_SECTOR_BUFFER, sector
  frames from a structured buffer). Grass draws 1112 -> 337 at the base,
  876 -> 439 in the meadow.
- Bundles: loose ones sleep when they come to rest (our gravity kept ~600
  bodies awake), ones on belts skip the ground checks, and all of them are
  stepped from one CargoTick instead of two Unity messages each.
- Belts leave a jammed line alone and only look every few steps whether it
  can move; splitters test distance before transforming every bundle.
- Light probes off on everything (the planet has none) and the GPU Resident
  Drawer off: both cost CPU per moving renderer for nothing.
- -demogpu N -onscreen measures frame time with one feature off at a time.

Base view 17-19 ms -> 14-15 ms, meadow 14-16 ms -> 11.5-12 ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 20:01:02 +06:00

527 lines
27 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
namespace GrassCutter
{
/// <summary>
/// Draws Herbaria-7's grass and hemp around the camera straight from the GPU, one draw per sector in view so every
/// strand keeps its place on the ball and reads that sector's mow map: up close the meadow is a pile of real strands,
/// long round "sausages" over a dark floor (GrassStrand.shader: one ribbon per cell of the sector's flat frame, placed
/// from the instance id, a fine ring and a coarser one); out to the horizon, where strands would be under a pixel, it
/// turns into shells (GrassFur.shader). Hemp plants poke out of it (Grass.shader). Further out still, only the floor of
/// the sectors the crew has worked on is drawn, so a mown region stays visible from a long way off.
/// </summary>
[DefaultExecutionOrder(-60)]
public class GrassField : MonoBehaviour
{
public static GrassField Instance { get; private set; }
public Material furMat, strandMat, hempMat, flowerMat;
public Mesh hempMesh, flowerMesh;
/// <summary>By <see cref="Crop"/>: the plant up close and the same plant further off.</summary>
public CropLook[] crops;
[System.Serializable]
public class CropLook { public Material mat; public Mesh near, far; }
// hemp: cell size, fade start / end, inner skip radius, density
static readonly Ring Hemp = new Ring { cell = 2.4f, fadeA = 62f, fadeB = 88f, inner = 0f, density = 0.34f };
struct Ring { public float cell, fadeA, fadeB, inner, density; }
static readonly Ring Flowers = new Ring { cell = 1.05f, fadeA = 54f, fadeB = 76f, inner = 0f, density = 0.7f };
// a stand of plants: thick to 30 m, then cheap ones to the edge of the strands. By crop.
static readonly Ring[] CropNear =
{
default,
new Ring { cell = 0.46f, fadeA = 25f, fadeB = 35f, inner = 0f, density = 0.92f },
new Ring { cell = 0.46f, fadeA = 25f, fadeB = 35f, inner = 0f, density = 0.92f },
new Ring { cell = 0.82f, fadeA = 25f, fadeB = 35f, inner = 0f, density = 0.95f },
new Ring { cell = 0.85f, fadeA = 25f, fadeB = 35f, inner = 0f, density = 0.95f },
};
static readonly Ring[] CropFar =
{
default,
new Ring { cell = 0.72f, fadeA = 64f, fadeB = 88f, inner = 30f, density = 0.92f },
new Ring { cell = 0.72f, fadeA = 64f, fadeB = 88f, inner = 30f, density = 0.92f },
new Ring { cell = 0.95f, fadeA = 72f, fadeB = 100f, inner = 30f, density = 0.95f },
new Ring { cell = 0.95f, fadeA = 72f, fadeB = 100f, inner = 30f, density = 0.95f },
};
// fur: shells, drawn between inner..outer metres (handing over through a dithered band), sinks into the ground
// fadeA..fadeB. Both share one grid laid over the sector.
static readonly Pile FurFloor = new Pile { shells = 1, inner = 0f, outer = StrandEnd, fadeA = 900f, fadeB = 1000f };
static readonly Pile FurFarBase = new Pile { shells = 8, inner = StrandEnd, outer = 158f, fadeA = 118f, fadeB = 158f };
/// <summary>How far the pile reaches, as a multiple of its usual 158 m: the opening film pushes it out so the shots from the air stay furry.</summary>
public static float FurReach = 1f;
/// <summary>The share of blades drawn (graphics settings: grass).</summary>
public static float Detail = 1f;
static Pile FurFar => FurReach == 1f ? FurFarBase : new Pile { shells = FurFarBase.shells, inner = FurFarBase.inner, outer = FurFarBase.outer * FurReach, fadeA = FurFarBase.fadeA * FurReach, fadeB = FurFarBase.fadeB * FurReach };
float _gatheredReach = 1f;
struct Pile { public float inner, outer, fadeA, fadeB; public int shells; }
const int GridSide = 13;
/// <summary>The floor under the strands is seen up close: a finer grid, so no bump of the ground between its corners shows through.</summary>
const int FloorSide = 37;
const float SeamBand = 5f;
/// <summary>Mown ground stays visible this far, on this many of the nearest sectors.</summary>
const float OverlayReach = 1500f;
const int OverlayMax = 400;
// strands: cell (one strand each), ribbon rows, drawn between inner..outer metres, width in metres
const float StrandEnd = 46f;
static readonly Tuft StrandNear = new Tuft { cell = 0.055f, rows = new[] { 0f, 0.3f, 0.6f, 0.8f, 0.92f, 1f }, inner = 0f, outer = 12f, width = 0.05f };
static readonly Tuft StrandMid = new Tuft { cell = 0.13f, rows = new[] { 0f, 0.6f, 1f }, inner = 12f, outer = StrandEnd, width = 0.115f };
struct Tuft { public float cell, inner, outer, width; public float[] rows; }
/// <summary>The strand texture tiles every this many metres (256 px, a strand every ~3 px: ~1200 strands per m²).</summary>
const float FurTile = 2.5f;
/// <summary>The pile never grows taller than this (just under the crew's eyes).</summary>
public const float FurMax = 1.02f;
static readonly int HeightId = Shader.PropertyToID("_GcHeight"), CamId = Shader.PropertyToID("_GcCam");
static readonly int GridId = Shader.PropertyToID("_GcGrid"), FadeId = Shader.PropertyToID("_GcFade");
static readonly int PushersId = Shader.PropertyToID("_GcPushers"), PusherCountId = Shader.PropertyToID("_GcPusherCount");
static readonly int ShellsId = Shader.PropertyToID("_GcShells"), FurTexId = Shader.PropertyToID("_GcFurTex"), FurScaleId = Shader.PropertyToID("_GcFurScale");
static readonly int FurMaxId = Shader.PropertyToID("_GcFurMax"), CamUpId = Shader.PropertyToID("_GcCamUp");
static readonly int SectorCId = Shader.PropertyToID("_GcC"), SectorE1Id = Shader.PropertyToID("_GcE1"), SectorE2Id = Shader.PropertyToID("_GcE2");
static readonly int SaltId = Shader.PropertyToID("_GcSalt"), BordersId = Shader.PropertyToID("_GcBorders"), MaskTexId = Shader.PropertyToID("_GcMaskTex");
static readonly int FurNId = Shader.PropertyToID("_GcFurN"), FurUId = Shader.PropertyToID("_GcFurU"), FurVId = Shader.PropertyToID("_GcFurV");
static readonly int StrandId = Shader.PropertyToID("_GcStrand"), CamFwdId = Shader.PropertyToID("_GcCamFwd");
const int MaxPushers = 8;
readonly Vector4[] _pushers = new Vector4[MaxPushers];
Mesh _grid, _floorGrid, _strandNear, _strandMid;
Texture2D _furTex;
readonly List<MaterialPropertyBlock> _mpbs = new List<MaterialPropertyBlock>();
readonly List<HexGrid.Sector> _near = new List<HexGrid.Sector>();
readonly List<HexGrid.Sector> _worked = new List<HexGrid.Sector>();
readonly Plane[] _frustum = new Plane[6];
int _mpbUsed, _here = -1;
/// <summary>Grass draws issued last frame (for -demogpu).</summary>
public int Draws { get; private set; }
int _deckHash;
/// <summary>The grass's blocks were cleared (the ball changed size): the deck goes back in next frame.</summary>
public void Redeck() => _deckHash = int.MinValue;
void Awake()
{
Instance = this;
_grid = BuildGrid(GridSide);
_floorGrid = BuildGrid(FloorSide);
_strandNear = BuildRibbon(StrandNear.rows);
_strandMid = BuildRibbon(StrandMid.rows);
_furTex = BuildStrands(256, 3, 7);
Shader.SetGlobalTexture(FurTexId, _furTex);
Shader.SetGlobalFloat(FurScaleId, 1f / FurTile);
Shader.SetGlobalFloat(FurMaxId, FurMax);
Shader.SetGlobalVectorArray(PushersId, _pushers);
}
void OnDestroy()
{
if (_furTex) Destroy(_furTex);
foreach (var b in _batches) b.buffer?.Release();
if (_furBatchMat) Destroy(_furBatchMat);
}
// ───────────────────────── batches ─────────────────────────
/// <summary>One sector's frame as the fur shader reads it from <c>_GcSectorBuf</c> (GC_SECTOR_BUFFER).</summary>
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
struct SectorData { public Vector4 c, e1, e2, salt, grid, b0, b1, b2, b3, b4, b5; }
/// <summary>The sectors of one pile and one shared mow map look, drawn together at the end of the frame.</summary>
sealed class Batch
{
public Pile pile;
public bool onlyWorked;
public Texture2D mask;
public readonly List<SectorData> items = new List<SectorData>();
public Bounds bounds;
public GraphicsBuffer buffer;
public readonly MaterialPropertyBlock mpb = new MaterialPropertyBlock();
}
static readonly int SectorBufId = Shader.PropertyToID("_GcSectorBuf");
readonly List<Batch> _batches = new List<Batch>();
Material _furBatchMat;
bool Batched(Pile p, HexGrid.Sector s, Texture2D mask, bool onlyWorked)
{
if (mask != MowMap.Blank && mask != MowMap.Full) return false;
if (!_furBatchMat && furMat)
{
_furBatchMat = new Material(furMat) { name = furMat.name + " (batched)" };
_furBatchMat.EnableKeyword("GC_SECTOR_BUFFER");
}
if (!_furBatchMat) return false;
Batch b = null;
foreach (var x in _batches)
if (x.mask == mask && x.onlyWorked == onlyWorked && x.pile.shells == p.shells && x.pile.inner == p.inner && x.pile.outer == p.outer && x.pile.fadeA == p.fadeA && x.pile.fadeB == p.fadeB) { b = x; break; }
if (b == null) { b = new Batch { pile = p, onlyWorked = onlyWorked, mask = mask }; _batches.Add(b); }
if (b.items.Count == 0) b.bounds = s.bounds; else b.bounds.Encapsulate(s.bounds);
bool floor = p.shells == 1;
var bs = s.borders;
b.items.Add(new SectorData
{
c = s.c, e1 = s.e1, e2 = s.e2, salt = s.salt,
grid = new Vector4(s.half, s.half * 2f / ((floor ? FloorSide : GridSide) - 1), 0f, 0f),
b0 = bs[0], b1 = bs[1], b2 = bs[2], b3 = bs[3], b4 = bs[4], b5 = bs[5],
});
return true;
}
void DrawBatches()
{
foreach (var b in _batches)
{
int n = b.items.Count;
if (n == 0) continue;
if (b.buffer == null || b.buffer.count < n)
{
b.buffer?.Release();
b.buffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, Mathf.NextPowerOfTwo(Mathf.Max(64, n)), System.Runtime.InteropServices.Marshal.SizeOf<SectorData>());
}
b.buffer.SetData(b.items);
var p = b.pile;
b.mpb.SetBuffer(SectorBufId, b.buffer);
b.mpb.SetTexture(MaskTexId, b.mask);
b.mpb.SetVector(ShellsId, new Vector4(p.shells, b.onlyWorked ? 0f : p.inner, b.onlyWorked ? 1e6f : p.outer, SeamBand));
b.mpb.SetVector(FadeId, new Vector4(p.fadeA, b.onlyWorked ? 1e6f : p.fadeB, b.onlyWorked ? 1f : 0f, 0f));
var rp = new RenderParams(_furBatchMat)
{
worldBounds = b.bounds,
matProps = b.mpb,
shadowCastingMode = ShadowCastingMode.Off,
receiveShadows = true,
layer = 0,
};
Graphics.RenderMeshPrimitives(rp, p.shells == 1 ? _floorGrid : _grid, 0, p.shells * n);
_drawn++;
b.items.Clear();
}
}
/// <summary>Meadow height in metres.</summary>
public static float CurrentHeight => GameDefs.GrassHeight;
// ───────────────────────── update ─────────────────────────
void LateUpdate()
{
Shader.SetGlobalFloat(HeightId, GameDefs.GrassHeight);
WatchDeck();
UpdatePushers();
Draw();
}
void WatchDeck()
{
var dm = DeckManager.Instance;
if (!dm) return;
int hash = 17;
foreach (var t in dm.TileKeys) hash = hash * 31 + t;
if (hash != _deckHash) { _deckHash = hash; MowMap.SetDeck(dm.TileKeys); }
}
void UpdatePushers()
{
int n = 0;
foreach (var p in PlayerAgent.All)
{
if (!p || n >= MaxPushers) continue;
var pos = p.transform.position;
_pushers[n++] = new Vector4(pos.x, pos.y, pos.z, p.Driving.Value ? 0f : 1.15f);
}
foreach (var v in Vehicle.All)
{
if (!v || n >= MaxPushers) continue;
var pos = v.transform.position;
_pushers[n++] = new Vector4(pos.x, pos.y, pos.z, v.length * 0.55f);
}
for (int i = n; i < MaxPushers; i++) _pushers[i] = Vector4.zero;
Shader.SetGlobalVectorArray(PushersId, _pushers);
Shader.SetGlobalFloat(PusherCountId, n);
}
void Draw()
{
var cam = CameraFx.Cam ? CameraFx.Cam : Camera.main;
if (!cam) return;
var cp = cam.transform.position;
Shader.SetGlobalVector(CamId, new Vector4(cp.x, cp.y, cp.z, 0f));
Shader.SetGlobalVector(CamFwdId, cam.transform.forward);
Shader.SetGlobalVector(CamUpId, Planet.LocalUp);
var dir = Planet.LocalUp;
int here = HexGrid.SectorAt(dir);
if (here != _here || _gatheredReach != FurReach) { _here = here; _gatheredReach = FurReach; GatherNear(here); }
_mpbUsed = 0;
_drawn = 0;
PublishFurAxes(dir);
GeometryUtility.CalculateFrustumPlanes(cam, _frustum);
float alt = Planet.Altitude(cp);
foreach (var s in _near)
{
if (!GeometryUtility.TestPlanesAABB(_frustum, s.bounds)) continue;
float arc = (s.c - dir).magnitude * Planet.Radius;
float reachable = Mathf.Max(arc - s.radius, alt);
var mask = MowMap.TextureFor(s);
// mown to the last blade: only the floor shows (the pile's shells and every plant are cut away in the
// shader anyway), one draw instead of up to six. Near the base that is most of what is in view.
if (mask == MowMap.Full && mask)
{
if (furMat) DrawPile(FurFloor, s, mask, true);
continue;
}
if (furMat)
{
var far = FurFar;
if (reachable < FurFloor.outer + SeamBand) DrawPile(FurFloor, s, mask, false);
if (reachable < far.outer && arc + s.radius > far.inner - SeamBand) DrawPile(far, s, mask, false);
else if (reachable >= far.outer && mask != MowMap.Blank) DrawPile(FurFloor, s, mask, true);
}
if (alt > FurFarBase.outer) continue;
Flat(s, dir, out float u, out float v);
if (strandMat)
{
if (arc < StrandNear.outer + s.radius) DrawTuft(_strandNear, StrandNear, s, mask, u, v);
if (arc < StrandMid.outer + s.radius) DrawTuft(_strandMid, StrandMid, s, mask, u, v);
}
var crop = (int)Crops.At(s);
if (crop > 0 && crops != null && crop < crops.Length && crops[crop].mat)
{
if (arc < CropNear[crop].fadeB + s.radius) DrawRing(crops[crop].mat, crops[crop].near, CropNear[crop], s, mask, u, v);
if (arc < CropFar[crop].fadeB + s.radius) DrawRing(crops[crop].mat, crops[crop].far, CropFar[crop], s, mask, u, v);
continue;
}
if (hempMat && hempMesh && arc < Hemp.fadeB + s.radius) DrawRing(hempMat, hempMesh, Hemp, s, mask, u, v);
if (flowerMat && flowerMesh && arc < Flowers.fadeB + s.radius) DrawRing(flowerMat, flowerMesh, Flowers, s, mask, u, v);
}
if (furMat)
foreach (var s in _worked)
if (GeometryUtility.TestPlanesAABB(_frustum, s.bounds)) DrawPile(FurFloor, s, MowMap.TextureFor(s), true);
DrawBatches();
Draws = _mpbUsed + _drawn;
}
int _drawn;
/// <summary>Every sector the rings can reach from here, the one underfoot first, and the worked ones further out.</summary>
void GatherNear(int here)
{
_near.Clear();
var from = HexGrid.Get(here);
_near.Add(from);
var seen = new HashSet<int> { here };
float reach = Mathf.Max(Hemp.fadeB, FurFar.outer) + 40f;
for (int i = 0; i < _near.Count; i++)
foreach (int n in _near[i].neighbours)
{
if (!seen.Add(n)) continue;
var s = HexGrid.Get(n);
if ((s.c - from.c).magnitude * Planet.Radius < reach) _near.Add(s);
}
MowMap.Trim(from.c);
_worked.Clear();
foreach (var m in MowMap.All)
if (m.keep && !seen.Contains(m.s.id) && (m.s.c - from.c).magnitude * Planet.Radius < OverlayReach) _worked.Add(m.s);
if (_worked.Count > OverlayMax)
{
_worked.Sort((a, b) => (a.c - from.c).sqrMagnitude.CompareTo((b.c - from.c).sqrMagnitude));
_worked.RemoveRange(OverlayMax, _worked.Count - OverlayMax);
}
}
static void Flat(HexGrid.Sector s, Vector3 dir, out float u, out float v) => MowMap.Flat(s, dir, out u, out v);
static void SetSector(MaterialPropertyBlock mpb, HexGrid.Sector s, Texture2D mask)
{
mpb.SetVector(SectorCId, s.c);
mpb.SetVector(SectorE1Id, s.e1);
mpb.SetVector(SectorE2Id, s.e2);
mpb.SetVector(SaltId, s.salt);
mpb.SetVectorArray(BordersId, s.borders);
mpb.SetTexture(MaskTexId, mask);
}
MaterialPropertyBlock NextMpb()
{
if (_mpbUsed == _mpbs.Count) _mpbs.Add(new MaterialPropertyBlock());
return _mpbs[_mpbUsed++];
}
/// <summary>The strand texture lies on the cube face under the camera: no seam for as far as the pile reaches.</summary>
static void PublishFurAxes(Vector3 d)
{
float x = Mathf.Abs(d.x), y = Mathf.Abs(d.y), z = Mathf.Abs(d.z);
Vector3 n, u, v;
if (x >= y && x >= z) { n = new Vector3(Mathf.Sign(d.x), 0f, 0f); u = Vector3.forward; v = Vector3.up; }
else if (y >= z) { n = new Vector3(0f, Mathf.Sign(d.y), 0f); u = Vector3.right; v = Vector3.forward; }
else { n = new Vector3(0f, 0f, Mathf.Sign(d.z)); u = Vector3.right; v = Vector3.up; }
Shader.SetGlobalVector(FurNId, n);
Shader.SetGlobalVector(FurUId, u);
Shader.SetGlobalVector(FurVId, v);
}
/// <summary>The pile over a whole sector. onlyWorked: past the grass, just the floor where something was cut.</summary>
void DrawPile(Pile p, HexGrid.Sector s, Texture2D mask, bool onlyWorked)
{
if (Batched(p, s, mask, onlyWorked)) return;
var mpb = NextMpb();
SetSector(mpb, s, mask);
bool floor = p.shells == 1;
mpb.SetVector(GridId, new Vector4(s.half, s.half * 2f / ((floor ? FloorSide : GridSide) - 1), 0f, 0f));
mpb.SetVector(ShellsId, new Vector4(p.shells, onlyWorked ? 0f : p.inner, onlyWorked ? 1e6f : p.outer, SeamBand));
mpb.SetVector(FadeId, new Vector4(p.fadeA, onlyWorked ? 1e6f : p.fadeB, onlyWorked ? 1f : 0f, 0f));
var rp = new RenderParams(furMat)
{
worldBounds = s.bounds,
matProps = mpb,
shadowCastingMode = ShadowCastingMode.Off,
receiveShadows = true,
layer = 0,
};
Graphics.RenderMeshPrimitives(rp, floor ? _floorGrid : _grid, 0, p.shells);
}
/// <summary>The window of a sector's cells that the camera's ring can touch. False when there is none.</summary>
static bool Window(HexGrid.Sector s, float u, float v, float reach, float cell, out int x0, out int z0, out int w, out int h)
{
x0 = Mathf.FloorToInt(Mathf.Max(u - reach, -s.halfU) / cell);
z0 = Mathf.FloorToInt(Mathf.Max(v - reach, -s.halfV) / cell);
w = Mathf.CeilToInt(Mathf.Min(u + reach, s.halfU) / cell) - x0 + 1;
h = Mathf.CeilToInt(Mathf.Min(v + reach, s.halfV) / cell) - z0 + 1;
return w > 0 && h > 0;
}
void DrawTuft(Mesh mesh, Tuft t, HexGrid.Sector s, Texture2D mask, float u, float v)
{
if (!Window(s, u, v, t.outer + SeamBand, t.cell, out int x0, out int z0, out int w, out int h)) return;
var mpb = NextMpb();
SetSector(mpb, s, mask);
mpb.SetVector(GridId, new Vector4(x0, z0, t.cell, w));
mpb.SetVector(StrandId, new Vector4(t.inner, t.outer, SeamBand, t.width));
var rp = new RenderParams(strandMat)
{
worldBounds = s.bounds,
matProps = mpb,
shadowCastingMode = ShadowCastingMode.Off,
receiveShadows = true,
layer = 0,
};
Graphics.RenderMeshPrimitives(rp, mesh, 0, w * h);
}
void DrawRing(Material mat, Mesh mesh, Ring r, HexGrid.Sector s, Texture2D mask, float u, float v)
{
if (!Window(s, u, v, r.fadeB, r.cell, out int x0, out int z0, out int w, out int h)) return;
var mpb = NextMpb();
SetSector(mpb, s, mask);
mpb.SetVector(GridId, new Vector4(x0, z0, r.cell, w));
mpb.SetVector(FadeId, new Vector4(r.fadeA, r.fadeB, r.inner, r.density * Detail));
var rp = new RenderParams(mat)
{
worldBounds = s.bounds,
matProps = mpb,
shadowCastingMode = ShadowCastingMode.Off,
receiveShadows = true,
layer = 0,
};
Graphics.RenderMeshPrimitives(rp, mesh, 0, w * h);
}
// ───────────────────────── meshes ─────────────────────────
/// <summary>A flat grid of n×n vertices over -1..1 in local x/z (the sector scales it, the shells are the shader's job).</summary>
static Mesh BuildGrid(int n)
{
var v = new Vector3[n * n];
for (int z = 0; z < n; z++)
for (int x = 0; x < n; x++)
v[z * n + x] = new Vector3(x * 2f / (n - 1) - 1f, 0f, z * 2f / (n - 1) - 1f);
var t = new int[(n - 1) * (n - 1) * 6];
int k = 0;
for (int z = 0; z < n - 1; z++)
for (int x = 0; x < n - 1; x++)
{
int i = z * n + x;
t[k++] = i; t[k++] = i + n; t[k++] = i + 1;
t[k++] = i + 1; t[k++] = i + n; t[k++] = i + n + 1;
}
var m = new Mesh { name = "FurGrid" };
m.SetVertices(v);
m.SetTriangles(t, 0);
return m;
}
/// <summary>One strand: a ribbon with a row of two vertices per entry; x = side (-1..1), y = along the strand.</summary>
static Mesh BuildRibbon(float[] rows)
{
var v = new Vector3[rows.Length * 2];
for (int i = 0; i < rows.Length; i++)
{
v[i * 2] = new Vector3(-1f, rows[i], 0f);
v[i * 2 + 1] = new Vector3(1f, rows[i], 0f);
}
var t = new int[(rows.Length - 1) * 6];
for (int i = 0, k = 0; i < rows.Length - 1; i++)
{
int a = i * 2;
t[k++] = a; t[k++] = a + 2; t[k++] = a + 1;
t[k++] = a + 1; t[k++] = a + 2; t[k++] = a + 3;
}
var m = new Mesh { name = "Strand" };
m.SetVertices(v);
m.SetTriangles(t, 0);
m.bounds = new Bounds(Vector3.up * 0.5f, new Vector3(2f, 2f, 2f));
return m;
}
/// <summary>
/// The strand texture: one strand per jittered spacing×spacing cell, r = its height tapering to 0 at the rim (so a
/// shell cuts it as a cone), g = its tint. Tiles seamlessly; the mips average the strands for distant shells.
/// </summary>
static Texture2D BuildStrands(int res, int spacing, int seed)
{
var rng = new System.Random(seed);
float Rnd() => (float)rng.NextDouble();
var px = new Color32[res * res];
int cells = res / spacing;
float span = cells * spacing;
for (int cz = 0; cz < cells; cz++)
for (int cx = 0; cx < cells; cx++)
{
// full-cell jitter: a regular strand grid beats against the shell spacing into rings (moiré)
float sx = (cx + Rnd()) * spacing * res / span, sz = (cz + Rnd()) * spacing * res / span;
float h = Mathf.Lerp(0.55f, 1f, Mathf.Sqrt(Rnd()));
float rad = spacing * Mathf.Lerp(0.6f, 0.85f, Rnd());
byte tint = (byte)(Rnd() * 255f);
int r = Mathf.CeilToInt(rad);
for (int dz = -r; dz <= r; dz++)
for (int dx = -r; dx <= r; dx++)
{
int x = Mathf.FloorToInt(sx) + dx, z = Mathf.FloorToInt(sz) + dz;
float d = new Vector2(x + 0.5f - sx, z + 0.5f - sz).magnitude / rad;
if (d >= 1f) continue;
x = (x % res + res) % res;
z = (z % res + res) % res;
byte val = (byte)(h * (1f - d * d) * 255f);
int i = z * res + x;
if (val > px[i].r) px[i] = new Color32(val, tint, 0, 255);
}
}
var tex = new Texture2D(res, res, TextureFormat.RGBA32, true, true)
{
name = "FurStrands", wrapMode = TextureWrapMode.Repeat, filterMode = FilterMode.Trilinear, anisoLevel = 8,
};
tex.SetPixels32(px);
tex.Apply(true, true);
return tex;
}
}
}