using System;
using System.Collections.Generic;
using System.Numerics;
using MoonTools.Core.Structs;
namespace MoonTools.Core.Bonk
{
///
/// Used to quickly check if two shapes are potentially overlapping.
///
/// The type that will be used to uniquely identify shape-transform pairs.
public class SpatialHash where T : IEquatable
{
private readonly int cellSize;
private readonly Dictionary>> hashDictionary = new Dictionary>>();
private readonly Dictionary IDLookup = new Dictionary();
public SpatialHash(int cellSize)
{
this.cellSize = cellSize;
}
private (int, int) Hash(Vector2 position)
{
return ((int)Math.Floor(position.X / cellSize), (int)Math.Floor(position.Y / cellSize));
}
///
/// Inserts an element into the SpatialHash.
///
/// A unique ID for the shape-transform pair.
///
///
public void Insert(T id, IShape2D shape, Transform2D transform2D)
{
var box = shape.TransformedAABB(transform2D);
var minHash = Hash(box.Min);
var maxHash = Hash(box.Max);
for (var i = minHash.Item1; i <= maxHash.Item1; i++)
{
for (var j = minHash.Item2; j <= maxHash.Item2; j++)
{
if (!hashDictionary.ContainsKey(i))
{
hashDictionary.Add(i, new Dictionary>());
}
if (!hashDictionary[i].ContainsKey(j))
{
hashDictionary[i].Add(j, new HashSet());
}
hashDictionary[i][j].Add(id);
IDLookup[id] = (shape, transform2D);
}
}
}
///
/// Retrieves all the potential collisions of a shape-transform pair. Excludes any shape-transforms with the given ID.
///
public IEnumerable<(T, IShape2D, Transform2D)> Retrieve(T id, IShape2D shape, Transform2D transform2D)
{
AABB box = shape.TransformedAABB(transform2D);
var minHash = Hash(box.Min);
var maxHash = Hash(box.Max);
for (int i = minHash.Item1; i <= maxHash.Item1; i++)
{
for (int j = minHash.Item2; j <= maxHash.Item2; j++)
{
if (hashDictionary.ContainsKey(i) && hashDictionary[i].ContainsKey(j))
{
foreach (var t in hashDictionary[i][j])
{
var (otherShape, otherTransform) = IDLookup[t];
if (!id.Equals(t)) { yield return (t, otherShape, otherTransform); }
}
}
}
}
}
///
/// Removes everything that has been inserted into the SpatialHash.
///
public void Clear()
{
foreach (var innerDict in hashDictionary.Values)
{
foreach (var set in innerDict.Values)
{
set.Clear();
}
}
IDLookup.Clear();
}
}
}