512 lines
19 KiB
C#
512 lines
19 KiB
C#
using System.Linq;
|
||
using OpenTK.Mathematics;
|
||
using VoxelEngine.Core;
|
||
using VoxelEngine.World;
|
||
using VoxelEngine.World.Blocks;
|
||
using VoxelEngine.World.Chunk;
|
||
using VoxelEngine.World.Persistence;
|
||
using VoxelEngine.World.Streaming;
|
||
using VoxelEngine.World.WorldGen;
|
||
using Xunit;
|
||
using VoxelChunk = VoxelEngine.World.Chunk.Chunk;
|
||
|
||
namespace VoxelEngine.Tests.Streaming;
|
||
|
||
// Synchronous executor: runs the submitted action on the calling thread.
|
||
internal sealed class SynchronousJobExecutor : IJobExecutor
|
||
{
|
||
public void Submit(Action work) => work();
|
||
}
|
||
|
||
// Fake renderer: never touches GL. Just records lifecycle.
|
||
internal sealed class FakeRenderer : IChunkRenderer
|
||
{
|
||
public bool Disposed { get; private set; }
|
||
public int DrawCount { get; private set; }
|
||
public float[] Mesh { get; }
|
||
|
||
public FakeRenderer(float[] mesh) { this.Mesh = mesh; }
|
||
public void Draw() => this.DrawCount++;
|
||
public void Dispose() => this.Disposed = true;
|
||
}
|
||
|
||
// Minimal mesher returning a fixed-length non-empty mesh.
|
||
internal sealed class FakeMesher : IChunkMesher
|
||
{
|
||
public float[] Build(VoxelChunk chunk, BlockRegistry registry, Func<int, int, int, bool>? neighborOpaqueOutside = null)
|
||
=> new float[6]; // one vertex worth
|
||
}
|
||
|
||
// Mesher that returns an empty mesh, simulating a pure-air chunk.
|
||
internal sealed class EmptyMesher : IChunkMesher
|
||
{
|
||
public float[] Build(VoxelChunk chunk, BlockRegistry registry, Func<int, int, int, bool>? neighborOpaqueOutside = null)
|
||
=> Array.Empty<float>();
|
||
}
|
||
|
||
public class ChunkStreamerTests
|
||
{
|
||
private static (ChunkStreamer streamer, World.World world, List<FakeRenderer> created) CreateStreamer(
|
||
Configuration cfg, Func<int, int, int>? surfaceHeightAt = null)
|
||
{
|
||
var registry = new BlockRegistry();
|
||
var store = new InMemoryChunkModificationStore();
|
||
var world = new World.World(registry, store);
|
||
var mesher = new FakeMesher();
|
||
var executor = new SynchronousJobExecutor();
|
||
var created = new List<FakeRenderer>();
|
||
Func<float[], IChunkRenderer> factory = m =>
|
||
{
|
||
var r = new FakeRenderer(m);
|
||
created.Add(r);
|
||
return r;
|
||
};
|
||
Func<Vector3i, VoxelChunk> generate = _ => new VoxelChunk();
|
||
Func<int, int, int> height = surfaceHeightAt ?? ((_, _) => 8);
|
||
var streamer = new ChunkStreamer(cfg, world, generate, height, mesher, registry, executor, factory);
|
||
return (streamer, world, created);
|
||
}
|
||
|
||
[Fact]
|
||
public void Tick_FirstCall_LoadsAllChunksInLoadBox()
|
||
{
|
||
var cfg = new Configuration
|
||
{
|
||
RenderDistanceHorizontal = 1,
|
||
MaxGenerateJobsInFlight = 100,
|
||
MaxMeshUploadsPerFrame = 100,
|
||
};
|
||
var (streamer, world, created) = CreateStreamer(cfg);
|
||
|
||
streamer.Tick(new Vector3i(0, 0, 0));
|
||
|
||
// Load box H=1, V=0 → 3 × 1 × 3 = 9 chunks
|
||
Assert.Equal(9, created.Count);
|
||
for (int x = -1; x <= 1; x++)
|
||
for (int z = -1; z <= 1; z++)
|
||
{
|
||
var pos = new Vector3i(x, 0, z);
|
||
Assert.NotNull(world.GetChunk(pos));
|
||
Assert.True(streamer.IsReady(pos));
|
||
}
|
||
}
|
||
|
||
[Fact]
|
||
public void Tick_PlayerMoves_LoadsNewChunks()
|
||
{
|
||
var cfg = new Configuration
|
||
{
|
||
RenderDistanceHorizontal = 1,
|
||
MaxGenerateJobsInFlight = 100,
|
||
MaxMeshUploadsPerFrame = 100,
|
||
};
|
||
var (streamer, world, created) = CreateStreamer(cfg);
|
||
|
||
streamer.Tick(new Vector3i(0, 0, 0)); // loads 9
|
||
|
||
// After the second tick the 3 new x=2 chunks must be ready.
|
||
// Cardinal-neighbor dirty-marking may also produce remesh renderers, so
|
||
// we assert on world state rather than an exact renderer count.
|
||
streamer.Tick(new Vector3i(1, 0, 0));
|
||
|
||
for (int z = -1; z <= 1; z++)
|
||
{
|
||
var newPos = new Vector3i(2, 0, z);
|
||
Assert.NotNull(world.GetChunk(newPos));
|
||
Assert.True(streamer.IsReady(newPos));
|
||
}
|
||
// x=-1 column must be unloaded
|
||
for (int z = -1; z <= 1; z++)
|
||
{
|
||
Assert.Null(world.GetChunk(new Vector3i(-1, 0, z)));
|
||
Assert.False(streamer.IsReady(new Vector3i(-1, 0, z)));
|
||
}
|
||
}
|
||
|
||
[Fact]
|
||
public void Tick_RespectsMaxMeshUploadsPerFrame()
|
||
{
|
||
var cfg = new Configuration
|
||
{
|
||
RenderDistanceHorizontal = 1,
|
||
MaxGenerateJobsInFlight = 100,
|
||
MaxMeshUploadsPerFrame = 2, // cap drains per tick
|
||
};
|
||
var (streamer, _, created) = CreateStreamer(cfg);
|
||
|
||
// With sync executor every submitted job completes immediately and
|
||
// posts into _completed. The cap throttles how many drain per Tick().
|
||
streamer.Tick(new Vector3i(0, 0, 0)); // dispatch fills the queue; drain ≤ 2
|
||
Assert.Equal(2, created.Count);
|
||
|
||
streamer.Tick(new Vector3i(0, 0, 0)); // same player chunk, drains 2 more
|
||
Assert.Equal(4, created.Count);
|
||
}
|
||
|
||
[Fact]
|
||
public void Tick_ClampsYToWorldBounds()
|
||
{
|
||
var cfg = new Configuration
|
||
{
|
||
RenderDistanceHorizontal = 0,
|
||
MaxGenerateJobsInFlight = 100,
|
||
MaxMeshUploadsPerFrame = 100,
|
||
};
|
||
// Surface far above the world ceiling -> top chunk clamps to
|
||
// WorldHeightChunks-1 (31). Full column loads cy 0..31 and nothing above.
|
||
var (streamer, world, _) = CreateStreamer(cfg, surfaceHeightAt: (_, _) => 100_000);
|
||
|
||
streamer.Tick(new Vector3i(0, 0, 0));
|
||
|
||
for (int cy = 0; cy < WorldConstants.WorldHeightChunks; cy++)
|
||
{
|
||
var pos = new Vector3i(0, cy, 0);
|
||
Assert.NotNull(world.GetChunk(pos));
|
||
Assert.True(streamer.IsReady(pos));
|
||
}
|
||
}
|
||
|
||
[Fact]
|
||
public void Tick_AppliesModificationDiffOnLoad()
|
||
{
|
||
var cfg = new Configuration
|
||
{
|
||
RenderDistanceHorizontal = 0,
|
||
MaxGenerateJobsInFlight = 100,
|
||
MaxMeshUploadsPerFrame = 100,
|
||
};
|
||
var registry = new BlockRegistry();
|
||
var store = new InMemoryChunkModificationStore();
|
||
var world = new World.World(registry, store);
|
||
var mesher = new FakeMesher();
|
||
var executor = new SynchronousJobExecutor();
|
||
Func<float[], IChunkRenderer> factory = m => new FakeRenderer(m);
|
||
Func<Vector3i, VoxelChunk> generate = _ => new VoxelChunk(); // all air
|
||
|
||
// Pre-record an edit before the chunk loads.
|
||
var pos = new Vector3i(0, 0, 0);
|
||
int localIndex = (5 * VoxelChunk.Size + 6) * VoxelChunk.Size + 7;
|
||
store.RecordEdit(pos, localIndex, registry.Stone.Id);
|
||
|
||
var streamer = new ChunkStreamer(cfg, world, generate, (_, _) => 8, mesher, registry, executor, factory);
|
||
streamer.Tick(pos);
|
||
|
||
Assert.Equal(registry.Stone.Id, world.GetBlock(5, 6, 7).Id);
|
||
}
|
||
|
||
[Fact]
|
||
public void Tick_PlayerMovesAway_UnloadsOldChunksAndDisposesRenderer()
|
||
{
|
||
var cfg = new Configuration
|
||
{
|
||
RenderDistanceHorizontal = 0,
|
||
MaxGenerateJobsInFlight = 100,
|
||
MaxMeshUploadsPerFrame = 100,
|
||
};
|
||
var (streamer, world, created) = CreateStreamer(cfg);
|
||
|
||
streamer.Tick(new Vector3i(0, 0, 0)); // loads (0,0,0)
|
||
Assert.Single(created);
|
||
Assert.NotNull(world.GetChunk(new Vector3i(0, 0, 0)));
|
||
|
||
streamer.Tick(new Vector3i(5, 0, 0)); // (0,0,0) now out of range; (5,0,0) loaded
|
||
|
||
Assert.True(created[0].Disposed);
|
||
Assert.Null(world.GetChunk(new Vector3i(0, 0, 0)));
|
||
Assert.False(streamer.IsReady(new Vector3i(0, 0, 0)));
|
||
}
|
||
|
||
[Fact]
|
||
public void Tick_UnloadKeepsModificationStoreDiff()
|
||
{
|
||
var cfg = new Configuration
|
||
{
|
||
RenderDistanceHorizontal = 0,
|
||
MaxGenerateJobsInFlight = 100,
|
||
MaxMeshUploadsPerFrame = 100,
|
||
};
|
||
var registry = new BlockRegistry();
|
||
var store = new InMemoryChunkModificationStore();
|
||
var world = new World.World(registry, store);
|
||
var mesher = new FakeMesher();
|
||
var executor = new SynchronousJobExecutor();
|
||
Func<float[], IChunkRenderer> factory = m => new FakeRenderer(m);
|
||
Func<Vector3i, VoxelChunk> generate = _ => new VoxelChunk();
|
||
var streamer = new ChunkStreamer(cfg, world, generate, (_, _) => 8, mesher, registry, executor, factory);
|
||
|
||
var pos = new Vector3i(0, 0, 0);
|
||
streamer.Tick(pos);
|
||
store.RecordEdit(pos, 0, registry.Stone.Id);
|
||
|
||
streamer.Tick(new Vector3i(99, 0, 0)); // unloads (0,0,0)
|
||
Assert.True(store.HasDiff(pos)); // diff survives unload
|
||
}
|
||
|
||
[Fact]
|
||
public void SpawnReady_FlipsTrueOnceSpawnAreaLoaded()
|
||
{
|
||
var cfg = new Configuration
|
||
{
|
||
RenderDistanceHorizontal = 1,
|
||
SpawnReadyRadiusHorizontal = 1,
|
||
MaxGenerateJobsInFlight = 100,
|
||
MaxMeshUploadsPerFrame = 1, // throttle to expose progression
|
||
};
|
||
var (streamer, _, _) = CreateStreamer(cfg);
|
||
|
||
Assert.False(streamer.SpawnReady);
|
||
// Tick once per chunk needed (3×3×1 = 9 chunks at this Y). Spawn area
|
||
// restricted by Y bounds (only Y=0 valid here) → 9 ticks.
|
||
for (int i = 0; i < 9; i++) streamer.Tick(new Vector3i(0, 0, 0));
|
||
Assert.True(streamer.SpawnReady);
|
||
}
|
||
|
||
[Fact]
|
||
public void MarkDirty_RemeshesChunkOnNextTick()
|
||
{
|
||
var cfg = new Configuration
|
||
{
|
||
RenderDistanceHorizontal = 0,
|
||
MaxGenerateJobsInFlight = 100,
|
||
MaxMeshUploadsPerFrame = 100,
|
||
};
|
||
var (streamer, _, created) = CreateStreamer(cfg);
|
||
|
||
streamer.Tick(new Vector3i(0, 0, 0));
|
||
Assert.Single(created);
|
||
var initialRenderer = created[0];
|
||
|
||
streamer.MarkDirty(new Vector3i(0, 0, 0));
|
||
streamer.Tick(new Vector3i(0, 0, 0)); // same chunk, but a remesh is queued
|
||
|
||
// Two renderers exist over the lifetime — old disposed, new live.
|
||
Assert.Equal(2, created.Count);
|
||
Assert.True(initialRenderer.Disposed);
|
||
Assert.False(created[1].Disposed);
|
||
}
|
||
|
||
[Fact]
|
||
public void Tick_LoadingChunk_MarksReadyCardinalNeighborsDirty()
|
||
{
|
||
var cfg = new Configuration
|
||
{
|
||
RenderDistanceHorizontal = 1,
|
||
MaxGenerateJobsInFlight = 100,
|
||
MaxMeshUploadsPerFrame = 100,
|
||
};
|
||
var (streamer, _, created) = CreateStreamer(cfg);
|
||
|
||
streamer.Tick(new Vector3i(0, 0, 0)); // load initial 3×3
|
||
int firstWave = created.Count; // 9 chunks
|
||
|
||
// Move so we load a new x=2 column. The new chunks become ready and
|
||
// mark their cardinal neighbors (x=1 column) dirty during Drain.
|
||
streamer.Tick(new Vector3i(1, 0, 0)); // dispatch + drain new loads → dirty marks set
|
||
streamer.Tick(new Vector3i(1, 0, 0)); // dispatch the queued remeshes → drain them
|
||
|
||
// Should have: 3 new loads + at least 3 remeshes of the x=1 column.
|
||
Assert.True(created.Count > firstWave + 3,
|
||
$"Expected remeshes beyond the 3 new loads; got {created.Count - firstWave}");
|
||
}
|
||
|
||
[Fact]
|
||
public void MarkDirty_OnUntrackedChunk_IsNoOp()
|
||
{
|
||
var cfg = new Configuration { RenderDistanceHorizontal = 0 };
|
||
var (streamer, _, created) = CreateStreamer(cfg);
|
||
|
||
streamer.MarkDirty(new Vector3i(99, 0, 99));
|
||
streamer.Tick(new Vector3i(0, 0, 0));
|
||
|
||
// Only the chunk in the load box was created; no spurious remesh.
|
||
Assert.Single(created);
|
||
}
|
||
|
||
[Fact]
|
||
public void Tick_GeneratorThrows_LogsAndDoesNotRetry()
|
||
{
|
||
var cfg = new Configuration
|
||
{
|
||
RenderDistanceHorizontal = 0,
|
||
MaxGenerateJobsInFlight = 100,
|
||
MaxMeshUploadsPerFrame = 100,
|
||
};
|
||
var registry = new BlockRegistry();
|
||
var store = new InMemoryChunkModificationStore();
|
||
var world = new World.World(registry, store);
|
||
var mesher = new FakeMesher();
|
||
var executor = new SynchronousJobExecutor();
|
||
int generateCalls = 0;
|
||
Func<Vector3i, VoxelChunk> generate = _ =>
|
||
{
|
||
generateCalls++;
|
||
throw new InvalidOperationException("boom");
|
||
};
|
||
Func<float[], IChunkRenderer> factory = m => new FakeRenderer(m);
|
||
|
||
var streamer = new ChunkStreamer(cfg, world, generate, (_, _) => 8, mesher, registry, executor, factory);
|
||
|
||
streamer.Tick(new Vector3i(0, 0, 0));
|
||
Assert.Equal(1, generateCalls);
|
||
Assert.False(streamer.IsReady(new Vector3i(0, 0, 0)));
|
||
|
||
// Tick again — same chunk, same position. Should NOT call generate again.
|
||
streamer.Tick(new Vector3i(0, 0, 0));
|
||
Assert.Equal(1, generateCalls);
|
||
}
|
||
|
||
[Fact]
|
||
public void InstallResult_EmptyMesh_SkipsRendererCreationButMarksReady()
|
||
{
|
||
var cfg = new Configuration
|
||
{
|
||
RenderDistanceHorizontal = 0,
|
||
MaxGenerateJobsInFlight = 100,
|
||
MaxMeshUploadsPerFrame = 100,
|
||
};
|
||
var registry = new BlockRegistry();
|
||
var store = new InMemoryChunkModificationStore();
|
||
var world = new World.World(registry, store);
|
||
var mesher = new EmptyMesher();
|
||
var executor = new SynchronousJobExecutor();
|
||
int rendererFactoryCalls = 0;
|
||
Func<float[], IChunkRenderer> factory = m =>
|
||
{
|
||
rendererFactoryCalls++;
|
||
return new FakeRenderer(m);
|
||
};
|
||
Func<Vector3i, VoxelChunk> generate = _ => new VoxelChunk();
|
||
|
||
var streamer = new ChunkStreamer(cfg, world, generate, (_, _) => 8, mesher, registry, executor, factory);
|
||
var pos = new Vector3i(0, 0, 0);
|
||
streamer.Tick(pos);
|
||
|
||
Assert.True(streamer.IsReady(pos));
|
||
Assert.Equal(0, rendererFactoryCalls);
|
||
Assert.Equal(0, streamer.RendererCount);
|
||
}
|
||
|
||
[Fact]
|
||
public void Tick_VerticalPriorityWeight_PrefersHorizontalAtSameDistance()
|
||
{
|
||
var cfg = new Configuration
|
||
{
|
||
RenderDistanceHorizontal = 1,
|
||
MaxGenerateJobsInFlight = 100,
|
||
MaxMeshUploadsPerFrame = 5, // player's chunk + 4 horizontal cardinals
|
||
VerticalPriorityWeight = 4,
|
||
};
|
||
// Surface at worldY 48 -> top chunk 3, so a full column is cy 0..3 and
|
||
// the player at Y=2 has in-column vertical neighbours at Y=1 and Y=3.
|
||
var (streamer, world, _) = CreateStreamer(cfg, surfaceHeightAt: (_, _) => 48);
|
||
|
||
var playerPos = new Vector3i(0, 2, 0);
|
||
streamer.Tick(playerPos);
|
||
|
||
// Drain budget = 5 = priority 0 (player) + 4 priority-1 (horizontal
|
||
// cardinals). With VerticalPriorityWeight=4, vertical cardinals
|
||
// (Y=1, Y=3) have priority 4 -- they must NOT be among the first 5.
|
||
Assert.NotNull(world.GetChunk(playerPos));
|
||
Assert.NotNull(world.GetChunk(new Vector3i( 1, 2, 0)));
|
||
Assert.NotNull(world.GetChunk(new Vector3i(-1, 2, 0)));
|
||
Assert.NotNull(world.GetChunk(new Vector3i( 0, 2, 1)));
|
||
Assert.NotNull(world.GetChunk(new Vector3i( 0, 2, -1)));
|
||
Assert.Null(world.GetChunk(new Vector3i(0, 3, 0)));
|
||
Assert.Null(world.GetChunk(new Vector3i(0, 1, 0)));
|
||
}
|
||
|
||
[Fact]
|
||
public void Tick_LoadsFullColumn_FromBedrockToSurface()
|
||
{
|
||
var cfg = new Configuration
|
||
{
|
||
RenderDistanceHorizontal = 0, // single column at the player
|
||
MaxGenerateJobsInFlight = 100,
|
||
MaxMeshUploadsPerFrame = 100,
|
||
};
|
||
// Surface at worldY 40 -> top chunk floor(40/16) = 2. Full column loads
|
||
// cy 0,1,2; chunk Y 3+ is air above the surface and must NOT load.
|
||
var (streamer, world, _) = CreateStreamer(cfg, surfaceHeightAt: (_, _) => 40);
|
||
|
||
streamer.Tick(new Vector3i(0, 0, 0));
|
||
|
||
Assert.NotNull(world.GetChunk(new Vector3i(0, 0, 0))); // bedrock
|
||
Assert.NotNull(world.GetChunk(new Vector3i(0, 1, 0))); // mid
|
||
Assert.NotNull(world.GetChunk(new Vector3i(0, 2, 0))); // surface
|
||
Assert.Null(world.GetChunk(new Vector3i(0, 3, 0))); // air above surface
|
||
Assert.Null(world.GetChunk(new Vector3i(0, 5, 0))); // air above surface
|
||
}
|
||
|
||
[Fact]
|
||
public void Tick_LoadsEditedSectionAboveSurface()
|
||
{
|
||
var cfg = new Configuration
|
||
{
|
||
RenderDistanceHorizontal = 0,
|
||
MaxGenerateJobsInFlight = 100,
|
||
MaxMeshUploadsPerFrame = 100,
|
||
};
|
||
var registry = new BlockRegistry();
|
||
var store = new InMemoryChunkModificationStore();
|
||
var world = new World.World(registry, store);
|
||
var mesher = new FakeMesher();
|
||
var executor = new SynchronousJobExecutor();
|
||
Func<float[], IChunkRenderer> factory = m => new FakeRenderer(m);
|
||
Func<Vector3i, VoxelChunk> generate = _ => new VoxelChunk();
|
||
|
||
// Surface at worldY 8 -> top chunk 0. A player edit sits in chunk Y 5,
|
||
// far above the surface; that edited section must still load.
|
||
var edited = new Vector3i(0, 5, 0);
|
||
store.RecordEdit(edited, 0, registry.Stone.Id);
|
||
|
||
var streamer = new ChunkStreamer(cfg, world, generate, (_, _) => 8, mesher, registry, executor, factory);
|
||
streamer.Tick(new Vector3i(0, 0, 0));
|
||
|
||
Assert.NotNull(world.GetChunk(new Vector3i(0, 0, 0))); // surface column
|
||
Assert.NotNull(world.GetChunk(edited)); // edited air section above surface
|
||
Assert.Null(world.GetChunk(new Vector3i(0, 3, 0))); // unedited air -- not loaded
|
||
}
|
||
|
||
[Fact]
|
||
public void RecomputeTargetSet_CachesSurfaceHeights_OnlySamplesNewColumns()
|
||
{
|
||
var cfg = new Configuration
|
||
{
|
||
RenderDistanceHorizontal = 1,
|
||
SpawnReadyRadiusHorizontal = 1,
|
||
MaxGenerateJobsInFlight = 100,
|
||
MaxMeshUploadsPerFrame = 100,
|
||
};
|
||
int calls = 0;
|
||
var (streamer, _, _) = CreateStreamer(cfg, surfaceHeightAt: (_, _) => { calls++; return 8; });
|
||
|
||
streamer.Tick(new Vector3i(0, 0, 0));
|
||
int afterFirst = calls; // 9 columns × 5 samples = 45 (spawn-check reuses cache)
|
||
streamer.Tick(new Vector3i(1, 0, 0)); // overlaps 6 columns; only the cx=2 strip is new
|
||
int newCalls = calls - afterFirst;
|
||
|
||
Assert.Equal(45, afterFirst);
|
||
Assert.Equal(15, newCalls); // 3 new columns × 5 — cached columns are not re-sampled
|
||
}
|
||
|
||
[Fact]
|
||
public void DrawVisible_DrawsOnlyChunksPassingPredicate_AndReturnsCount()
|
||
{
|
||
var cfg = new Configuration
|
||
{
|
||
RenderDistanceHorizontal = 1,
|
||
MaxGenerateJobsInFlight = 100,
|
||
MaxMeshUploadsPerFrame = 100,
|
||
};
|
||
var (streamer, _, created) = CreateStreamer(cfg);
|
||
streamer.Tick(new Vector3i(0, 0, 0)); // 9 columns, all chunk Y 0, non-empty meshes
|
||
|
||
int drawn = streamer.DrawVisible(
|
||
pos => pos == new Vector3i(0, 0, 0), // only the centre chunk "visible"
|
||
(_, r) => r.Draw());
|
||
|
||
Assert.Equal(1, drawn);
|
||
Assert.Equal(1, created.Sum(r => r.DrawCount));
|
||
}
|
||
}
|