Files
systemrevivalserver/World/SpatialIndex.cs
T
2025-11-10 07:42:03 -05:00

38 lines
1.3 KiB
C#

using StackExchange.Redis;
namespace Server.World;
public static class SpatialIndex
{
public const int CellSize = 50; // units
public static (int cx, int cy, int cz) Cell(double x, double y, double z) =>
((int)Math.Floor(x / CellSize), (int)Math.Floor(y / CellSize), (int)Math.Floor(z / CellSize));
public static async Task UpdateAsync(IDatabase db, ulong zoneId, ulong charId,
(int cx, int cy, int cz) oldCell, (int cx, int cy, int cz) newCell, TimeSpan ttl)
{
var oldKey = $"z:{{{zoneId}}}:c:{oldCell.cx}:{oldCell.cy}:{oldCell.cz}";
var newKey = $"z:{{{zoneId}}}:c:{newCell.cx}:{newCell.cy}:{newCell.cz}";
var batch = db.CreateBatch();
var tasks = new List<Task>();
if (oldCell != newCell)
tasks.Add(batch.SetRemoveAsync(oldKey, charId));
tasks.Add(batch.SetAddAsync(newKey, charId));
tasks.Add(batch.KeyExpireAsync(newKey, ttl));
batch.Execute();
await Task.WhenAll(tasks);
}
public static IEnumerable<string> NeighborCellKeys(ulong zoneId, (int cx, int cy, int cz) c, int r = 1)
{
for (int dx = -r; dx <= r; dx++)
for (int dy = -r; dy <= r; dy++)
yield return $"z:{{{zoneId}}}:c:{c.cx + dx}:{c.cy + dy}:{c.cz}";
}
}