diff --git a/Assets/Scripts/Editor/RockMeshRadius.cs b/Assets/Scripts/Editor/RockMeshRadius.cs index cefb3b1b1..971284924 100644 --- a/Assets/Scripts/Editor/RockMeshRadius.cs +++ b/Assets/Scripts/Editor/RockMeshRadius.cs @@ -56,8 +56,8 @@ namespace Aetheria.EditorTools var (_, meshes, measured) = Load(scene); var failures = meshes.Select((m, i) => (m, i)).Where(p => !(measured[p.i] > 0f) || Mathf.Abs(p.m.Radius - measured[p.i]) > Tolerance).ToArray(); if (failures.Length > 0) - throw new InvalidOperationException("InstancedMesh.Radius differs from the measured one (run RockMeshRadius.Fill): " + string.Join(", ", - failures.Select(f => $"{f.m.Mesh.name} stored {f.m.Radius} measured {measured[f.i]}"))); + throw new InvalidOperationException("InstancedMesh.Radius differs from the measured one, or is unset, on mesh (run RockMeshRadius.Fill): " + string.Join(", ", + failures.Select(f => f.m.Mesh.name))); return Summary("ok", measured); } finally diff --git a/Assets/Scripts/ServerShared/DrawAhead.cs b/Assets/Scripts/ServerShared/DrawAhead.cs index 5ec84c804..7115ccf30 100644 --- a/Assets/Scripts/ServerShared/DrawAhead.cs +++ b/Assets/Scripts/ServerShared/DrawAhead.cs @@ -45,35 +45,53 @@ public static class DrawAhead public static float RockScale(float gameplayRadius, float meshRadius) => meshRadius > 0f ? gameplayRadius / meshRadius : throw new System.ArgumentException("InstancedMesh.Radius is not set (zero, negative or not a number): run RockMeshRadius.Fill."); - // Which mesh each rock of a belt takes, and at what scale (ruling rock-meshes-by-size). meshRadii are the kept meshes' measured radii in - // the renderer's own order; the meshes are ranked by radius here, not by the caller. Rocks ranked by unworn size split into one run per mesh, - // smallest rocks on the smallest mesh and the last run taking the remainder; equal sizes and equal radii rank by index, so the answer is stable. - // Unworn, so a mined rock keeps its mesh and only shrinks. The renderer builds its instance matrices from Mesh and Scale and decides neither. - public sealed class RockMeshing + // One rock's entry in a belt's draw list: the rock (its index in the belt) and the scale that draws it at its gameplay radius on the mesh it is listed under. + public readonly struct RockDraw { - private readonly float[] _meshRadii; - - // Per rock: the index into meshRadii (as given) of the mesh it takes. - public int[] Mesh { get; } - - public RockMeshing(IReadOnlyList unwornSizes, IReadOnlyList meshRadii) - { - _meshRadii = meshRadii.ToArray(); - for (var m = 0; m < _meshRadii.Length; m++) - if (!(_meshRadii[m] > 0f)) throw new System.ArgumentException($"InstancedMesh.Radius of mesh #{m} is not set (zero, negative or not a number): run RockMeshRadius.Fill."); - var meshByRank = Enumerable.Range(0, _meshRadii.Length).OrderBy(m => _meshRadii[m]).ThenBy(m => m).ToArray(); - var rockByRank = Enumerable.Range(0, unwornSizes.Count).OrderBy(i => unwornSizes[i]).ThenBy(i => i).ToArray(); - var run = System.Math.Max(1, unwornSizes.Count / _meshRadii.Length); - Mesh = new int[unwornSizes.Count]; - for (var rank = 0; rank < rockByRank.Length; rank++) Mesh[rockByRank[rank]] = meshByRank[System.Math.Min(rank / run, meshByRank.Length - 1)]; - } - - // The scale that draws the rock at its current gameplay radius on the mesh it was given. - public float Scale(int rock, float gameplayRadius) => RockScale(gameplayRadius, _meshRadii[Mesh[rock]]); + public readonly int Rock; + public readonly float Scale; + public RockDraw(int rock, float scale) { Rock = rock; Scale = scale; } } - public static RockMeshing AssignRockMeshes(AsteroidBelt belt, PlanetSettings settings, IReadOnlyList meshRadii) => - new(Enumerable.Range(0, belt.Data.Asteroids.Length).Select(i => belt.UndamagedSize(i, settings)).ToArray(), meshRadii); + // The whole per-rock draw list of a belt (ruling rock-meshes-by-size); the renderer decides nothing and indexes nothing. Meshes are the kept + // candidates ranked ascending by radius, and ByMesh[m] lists the rocks drawn on Meshes[m], so a renderer batching by mesh iterates the two together. + // Rocks ranked by unworn size split into one run per mesh, smallest rocks on the smallest mesh and the last run taking the remainder; equal sizes and + // equal radii rank by index, and a mesh lists its rocks by index. Unworn, so a mined rock keeps its mesh and only shrinks. + // A list starts with every Scale NaN; Draw fills each entry's Scale from the poses (pose.w is the rock's gameplay radius) and returns the same arrays every call. + public sealed class BeltDraw + { + private readonly float[] _radii; + private readonly int[][] _rocks; + + public T[] Meshes { get; } + public RockDraw[][] ByMesh { get; } + + public BeltDraw(IReadOnlyList unwornSizes, IReadOnlyList candidates, System.Func radius) + { + var radii = candidates.Select(radius).ToArray(); + for (var m = 0; m < radii.Length; m++) + if (!(radii[m] > 0f)) throw new System.ArgumentException($"InstancedMesh.Radius of mesh #{m} is not set (zero, negative or not a number): run RockMeshRadius.Fill."); + var meshByRank = Enumerable.Range(0, radii.Length).OrderBy(m => radii[m]).ThenBy(m => m).ToArray(); + _radii = meshByRank.Select(m => radii[m]).ToArray(); + Meshes = meshByRank.Select(m => candidates[m]).ToArray(); + var rockByRank = Enumerable.Range(0, unwornSizes.Count).OrderBy(i => unwornSizes[i]).ThenBy(i => i).ToArray(); + var run = System.Math.Max(1, unwornSizes.Count / radii.Length); + _rocks = Enumerable.Range(0, radii.Length).Select(m => rockByRank + .Where((_, rank) => System.Math.Min(rank / run, radii.Length - 1) == m).OrderBy(i => i).ToArray()).ToArray(); + ByMesh = _rocks.Select(r => r.Select(rock => new RockDraw(rock, float.NaN)).ToArray()).ToArray(); + } + + public RockDraw[][] Draw(IReadOnlyList poses) + { + for (var m = 0; m < _rocks.Length; m++) + for (var k = 0; k < _rocks[m].Length; k++) + ByMesh[m][k] = new RockDraw(_rocks[m][k], RockScale(poses[_rocks[m][k]].w, _radii[m])); + return ByMesh; + } + } + + public static BeltDraw DrawListOf(AsteroidBelt belt, PlanetSettings settings, IReadOnlyList meshes, System.Func radius) => + new(Enumerable.Range(0, belt.Data.Asteroids.Length).Select(i => belt.UndamagedSize(i, settings)).ToArray(), meshes, radius); // A ship in a wormhole animation has its pose scripted by the step, not integrated from Velocity and TurnRate, // so it is drawn where the step put it: extrapolating a scripted pose draws a streak that resets every step. diff --git a/Assets/Scripts/Zone Display/ZoneRenderer.cs b/Assets/Scripts/Zone Display/ZoneRenderer.cs index c3a10ffa4..741f36218 100644 --- a/Assets/Scripts/Zone Display/ZoneRenderer.cs +++ b/Assets/Scripts/Zone Display/ZoneRenderer.cs @@ -73,11 +73,9 @@ public class ZoneRenderer : MonoBehaviour [HideInInspector] public Dictionary EntityInstances = new Dictionary(); [HideInInspector] public Dictionary Planets = new Dictionary(); - private Dictionary _beltMeshes = new Dictionary(); + // Ruling rock-meshes-by-size: DrawAhead owns the whole draw list (kept meshes ranked, each rock's mesh and scale); the renderer only draws it. + private Dictionary> _beltDraw = new Dictionary>(); private Dictionary _beltMatrices = new Dictionary(); - // Per rock: the mesh it takes and its slot in that mesh's matrix batch (ruling rock-meshes-by-size). - private Dictionary _beltMeshing = new Dictionary(); - private Dictionary _beltSlotOf = new Dictionary(); // Cut 1 (docs/mining-cut.md): the renderer's own buffer, filled from Zone.EvaluateBelt each frame. No pose // is stored on AsteroidBelt any more. private Dictionary _beltTransforms = new Dictionary(); @@ -384,10 +382,8 @@ public class ZoneRenderer : MonoBehaviour Planets.Clear(); Map.Clear(); - _beltMeshes.Clear(); + _beltDraw.Clear(); _beltMatrices.Clear(); - _beltMeshing.Clear(); - _beltSlotOf.Clear(); _beltTransforms.Clear(); _tourPlanets.Clear(); } @@ -452,17 +448,10 @@ public class ZoneRenderer : MonoBehaviour var meshes = AsteroidMeshes.ToList(); while (meshes.Count > Settings.AsteroidMeshCount) meshes.RemoveAt(Random.Range(0, meshes.Count)); - _beltMeshes[key] = meshes.ToArray(); _beltTransforms[key] = new float4[beltData.Asteroids.Length]; - // Ruling rock-meshes-by-size: DrawAhead ranks the meshes by radius and the rocks by size, and refuses a mesh with no radius. - var meshing = DrawAhead.AssignRockMeshes(Zone.AsteroidBelts[key], Zone.Settings, meshes.Select(m => m.Radius).ToArray()); - _beltMeshing[key] = meshing; - var meshOf = meshing.Mesh; - var slotOf = new int[meshOf.Length]; - var perMesh = new int[meshes.Count]; - for (int i = 0; i < meshOf.Length; i++) slotOf[i] = perMesh[meshOf[i]]++; - _beltSlotOf[key] = slotOf; - _beltMatrices[key] = perMesh.Select(n => new Matrix4x4[n]).ToArray(); + var draw = DrawAhead.DrawListOf(Zone.AsteroidBelts[key], Zone.Settings, meshes, m => m.Radius); + _beltDraw[key] = draw; + _beltMatrices[key] = draw.ByMesh.Select(rocks => new Matrix4x4[rocks.Length]).ToArray(); Map.RegisterBelt(key, _beltTransforms[key]); } @@ -556,25 +545,21 @@ public class ZoneRenderer : MonoBehaviour new Vector3(orbitPosition.x,height,orbitPosition.y), new Vector3(belt.Radius * 2,100,belt.Radius * 2)))) { - var meshes = _beltMeshes[key]; + var draw = _beltDraw[key]; var matrices = _beltMatrices[key]; - var meshing = _beltMeshing[key]; - var meshOf = meshing.Mesh; - var slotOf = _beltSlotOf[key]; - for (int tx = 0; tx < transforms.Length; tx++) + var byMesh = draw.Draw(transforms); + for (int m = 0; m < byMesh.Length; m++) { - var transform = transforms[tx]; - var i = meshOf[tx]; - matrices[i][slotOf[tx]] = Matrix4x4.TRS(DrawAhead.ChunkAt(Zone, ItemManager.GameplaySettings, transform, lead).ToUnity(), - Quaternion.Euler( - cos(transform.z + (float)i / meshes.Length) * 100, - sin(transform.z + (float)i / meshes.Length) * 100, - (float)tx / transforms.Length * 360), - Vector3.one * meshing.Scale(tx, transform.w)); + for (int k = 0; k < byMesh[m].Length; k++) + { + var rock = byMesh[m][k]; + var transform = transforms[rock.Rock]; + matrices[m][k] = Matrix4x4.TRS(DrawAhead.ChunkAt(Zone, ItemManager.GameplaySettings, transform, lead).ToUnity(), + Quaternion.Euler(cos(transform.z) * 100, sin(transform.z) * 100, (float)rock.Rock / transforms.Length * 360), + Vector3.one * rock.Scale); + } + Graphics.DrawMeshInstanced(draw.Meshes[m].Mesh, 0, draw.Meshes[m].Material, matrices[m]); } - - for (int i = 0; i < meshes.Length; i++) - Graphics.DrawMeshInstanced(meshes[i].Mesh, 0, meshes[i].Material, matrices[i]); } } diff --git a/tests/Aetheria.Shared.Tests/DrawnPoseTests.cs b/tests/Aetheria.Shared.Tests/DrawnPoseTests.cs index f5de7dc14..e4c2537dd 100644 --- a/tests/Aetheria.Shared.Tests/DrawnPoseTests.cs +++ b/tests/Aetheria.Shared.Tests/DrawnPoseTests.cs @@ -402,6 +402,22 @@ public sealed class DrawnPoseTests : IDisposable } } + // A mesh candidate as the renderer holds it: a name and a measured radius, in the renderer's own order. + private record Candidate(string Name, float Radius); + + private static DrawAhead.BeltDraw List(float[] sizes, params Candidate[] candidates) => + new(sizes, candidates, c => c.Radius); + + private static float4[] Poses(params float[] radii) => radii.Select(r => float4(0, 0, 0, r)).ToArray(); + + private static int[] MeshOf(DrawAhead.BeltDraw list, int rocks) + { + var meshOf = new int[rocks]; + for (var m = 0; m < list.ByMesh.Length; m++) + foreach (var d in list.ByMesh[m]) meshOf[d.Rock] = m; + return meshOf; + } + // Biggest rock, biggest mesh; smallest, smallest; sizes from the belt's own authored asteroids. [Fact] public void RocksRankedBySizeTakeMeshesRankedByRadius() @@ -409,21 +425,50 @@ public sealed class DrawnPoseTests : IDisposable var w = Build(); var belt = w.Zone.AsteroidBelts[w.Belt]; var sizes = Enumerable.Range(0, w.Asteroids.Length).Select(i => belt.UndamagedSize(i, w.Zone.Settings)).ToArray(); - var meshOf = DrawAhead.AssignRockMeshes(belt, w.Zone.Settings, new[] { 1f, 2f, 3f }).Mesh; - var biggest = Array.IndexOf(sizes, sizes.Max()); - var smallest = Array.IndexOf(sizes, sizes.Min()); - Assert.Equal(2, meshOf[biggest]); - Assert.Equal(0, meshOf[smallest]); + var list = DrawAhead.DrawListOf(belt, w.Zone.Settings, new[] { new Candidate("b", 3f), new Candidate("s", 1f), new Candidate("m", 2f) }, c => c.Radius); + var meshOf = MeshOf(list, sizes.Length); + Assert.Equal(sizes.Length, list.ByMesh.Sum(r => r.Length)); + Assert.Equal(new[] { "s", "m", "b" }, list.Meshes.Select(c => c.Name).ToArray()); + Assert.Equal(2, meshOf[Array.IndexOf(sizes, sizes.Max())]); + Assert.Equal(0, meshOf[Array.IndexOf(sizes, sizes.Min())]); for (var a = 0; a < sizes.Length; a++) for (var b = 0; b < sizes.Length; b++) if (sizes[a] < sizes[b]) Assert.True(meshOf[a] <= meshOf[b], $"rock {a} (size {sizes[a]}) is smaller than rock {b} ({sizes[b]}) and takes a bigger mesh"); - Assert.Equal(new[] { 0, 1, 2 }, meshOf.Distinct().OrderBy(m => m).ToArray()); + } + + // The renderer's draw list: more rocks than meshes, unequal radii, unsorted candidates and unsorted sizes, so a scale taken by rock index, a + // kept list left unsorted, a reversed kept order and a slot or mesh assigned by rock index all fail. Sizes by rank: 1 (rock 1), 2 (3), 4 (2), 5 (5), 7 (4), 9 (0). + [Fact] + public void TheDrawListGivesEachRockItsMeshAndItsScale() + { + var list = List(new[] { 9f, 1f, 4f, 2f, 7f, 5f }, new Candidate("big", 2.4f), new Candidate("small", 1.0f), new Candidate("mid", 1.5f)); + var byMesh = list.Draw(Poses(10f, 11f, 12f, 13f, 14f, 15f)); + Assert.Equal(new[] { "small", "mid", "big" }, list.Meshes.Select(c => c.Name).ToArray()); + Assert.Equal(new[] { 1, 3 }, byMesh[0].Select(d => d.Rock).ToArray()); + Assert.Equal(new[] { 2, 5 }, byMesh[1].Select(d => d.Rock).ToArray()); + Assert.Equal(new[] { 0, 4 }, byMesh[2].Select(d => d.Rock).ToArray()); + Assert.Equal(new[] { 11f / 1.0f, 13f / 1.0f }, byMesh[0].Select(d => d.Scale).ToArray()); + Assert.Equal(new[] { 12f / 1.5f, 15f / 1.5f }, byMesh[1].Select(d => d.Scale).ToArray()); + Assert.Equal(new[] { 10f / 2.4f, 14f / 2.4f }, byMesh[2].Select(d => d.Scale).ToArray()); + } + + // Worn rocks are drawn at their current radius on the mesh the unworn size gave them; the list reads the poses each call. + [Fact] + public void TheDrawListScalesByTheCurrentRadiusOnTheSameMesh() + { + var list = List(new[] { 3f, 1f, 2f }, new Candidate("a", 2f), new Candidate("b", 4f)); + var first = list.Draw(Poses(8f, 8f, 8f)).Select(r => r.Select(d => d.Rock).ToArray()).ToArray(); + var worn = list.Draw(Poses(2f, 8f, 8f)); + Assert.Equal(first, worn.Select(r => r.Select(d => d.Rock).ToArray()).ToArray()); + var rock0 = worn.SelectMany((r, m) => r.Select(d => (d.Rock, m, d.Scale))).Single(d => d.Rock == 0); + Assert.Equal((1, 2f / 4f), (rock0.m, rock0.Scale)); } [Fact] public void EqualRocksTakeMeshesByIndex() { - int[] Meshes(float[] sizes, params float[] radii) => new DrawAhead.RockMeshing(sizes, radii).Mesh; + int[] Meshes(float[] sizes, params float[] radii) => + MeshOf(List(sizes, radii.Select((r, i) => new Candidate("c" + i, r)).ToArray()), sizes.Length); Assert.Equal(new[] { 0, 0, 1, 1, 2, 2, 2 }, Meshes(new[] { 5f, 5f, 5f, 5f, 5f, 5f, 5f }, 1f, 2f, 3f)); Assert.Equal(new[] { 2, 0, 2, 1, 2 }, Meshes(new[] { 9f, 1f, 4f, 2f, 7f }, 1f, 2f, 3f)); Assert.Equal(new[] { 0, 1, 1 }, Meshes(new[] { 1f, 2f, 3f }, 1f, 2f)); @@ -432,20 +477,6 @@ public sealed class DrawnPoseTests : IDisposable Assert.Equal(new[] { 0, 0, 1, 1, 2, 2, 2 }, Meshes(new[] { 5f, 5f, 5f, 5f, 5f, 5f, 5f }, 4f, 4f, 4f)); } - // The renderer hands the kept meshes in the order it holds them: the ranking is DrawAhead's. The smallest rock takes the smallest radius wherever - // it stands in the list, and the scale it is drawn at is its gameplay radius over that mesh's radius (mutants: no ranking, descending, radius 1, - // the first mesh's radius, the wrong mesh count). - [Fact] - public void MeshesAreRankedByRadiusWhateverOrderTheyAreGiven() - { - var radii = new[] { 2.4f, 1.0f, 1.5f }; - var meshing = new DrawAhead.RockMeshing(new[] { 9f, 1f, 4f, 2f, 7f, 5f }, radii); - Assert.Equal(new[] { 0, 1, 2, 1, 0, 2 }, meshing.Mesh); - Assert.Equal(3f / 2.4f, meshing.Scale(0, 3f), 5); - Assert.Equal(3f / 1.0f, meshing.Scale(1, 3f), 5); - Assert.Equal(1.2f / 1.5f, meshing.Scale(2, 1.2f), 5); - } - // A mesh with no measured radius is refused at load, naming the field and the mesh, never an infinite scale. [Theory] [InlineData(0f)] @@ -453,7 +484,7 @@ public sealed class DrawnPoseTests : IDisposable [InlineData(float.NaN)] public void AMeshWithoutARadiusIsRefusedByName(float radius) { - var refused = Assert.Throws(() => new DrawAhead.RockMeshing(new[] { 1f, 2f }, new[] { 1.5f, radius })); + var refused = Assert.Throws(() => List(new[] { 1f, 2f }, new Candidate("ok", 1.5f), new Candidate("bad", radius))); Assert.Contains("InstancedMesh.Radius", refused.Message); Assert.Contains("#1", refused.Message); Assert.Contains("InstancedMesh.Radius", Assert.Throws(() => DrawAhead.RockScale(1f, radius)).Message); @@ -465,13 +496,15 @@ public sealed class DrawnPoseTests : IDisposable { var w = Build(); var belt = w.Zone.AsteroidBelts[w.Belt]; - var before = DrawAhead.AssignRockMeshes(belt, w.Zone.Settings, new[] { 1f, 2f, 3f }).Mesh; + var candidates = new[] { new Candidate("a", 1f), new Candidate("b", 2f), new Candidate("c", 3f) }; + int[] Meshes() => MeshOf(DrawAhead.DrawListOf(belt, w.Zone.Settings, candidates, c => c.Radius), w.Asteroids.Length); + var before = Meshes(); var chunk = new ChunkId(w.Belt, 5); var hitpoints = w.Zone.Settings.AsteroidHitpoints.Evaluate(w.Asteroids[5].Size); var unworn = w.Zone.ChunkRadius(chunk); Assert.False(w.Zone.Wear(chunk, hitpoints * .9f)); Assert.True(w.Zone.ChunkRadius(chunk) < unworn * .5f, "the rock has shrunk to less than half its size"); - Assert.Equal(before, DrawAhead.AssignRockMeshes(belt, w.Zone.Settings, new[] { 1f, 2f, 3f }).Mesh); + Assert.Equal(before, Meshes()); } // Where the renderer decides a rock's height and scale it calls DrawAhead, and the reticle calls the same function: no inline copy of the rock @@ -485,11 +518,15 @@ public sealed class DrawnPoseTests : IDisposable var manager = Source("Assets/Scripts/Gameplay/ActionGameManager.cs"); var drawAhead = Source("Assets/Scripts/ServerShared/DrawAhead.cs"); Assert.Contains("DrawAhead.ChunkAt(", renderer); - // What the renderer still does itself: hand DrawAhead the kept meshes' own radii and draw each rock on the mesh and scale it returns. - Assert.Contains("DrawAhead.AssignRockMeshes(Zone.AsteroidBelts[key], Zone.Settings, meshes.Select(m => m.Radius).ToArray())", renderer); - Assert.Contains("meshing.Scale(tx, transform.w)", renderer); + // The renderer holds no mesh choice, sort or index arithmetic: it iterates DrawAhead's list. + Assert.Contains("DrawAhead.DrawListOf(", renderer); + Assert.Contains("draw.Draw(transforms)", renderer); Assert.DoesNotContain("RockScale(", renderer); Assert.DoesNotContain(".Sort(", renderer); + Assert.DoesNotContain("OrderBy", renderer); + Assert.DoesNotContain("meshOf", renderer); + Assert.DoesNotContain("slotOf", renderer); + Assert.DoesNotContain("perMesh", renderer); Assert.DoesNotContain("FloaterHeight(", renderer); Assert.DoesNotContain("Vector3.one * transform.w", renderer); Assert.Contains("DrawAhead.Chunk(", manager);