Compare commits

..

1 Commits

Author SHA1 Message Date
Evan Hemsley 4106a76ac9 testing generic transformed shapes 2020-01-04 23:24:36 -08:00
31 changed files with 497 additions and 473 deletions

46
.circleci/config.yml Normal file
View File

@ -0,0 +1,46 @@
version: 2.1
defaults: &defaults
working_directory: ~/repo
docker:
- image: mcr.microsoft.com/dotnet/core/sdk:3.0
environment:
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1
DOTNET_CLI_TELEMETRY_OPTOUT: 1
jobs:
test:
<<: *defaults
steps:
- checkout
- run: dotnet restore
- run: dotnet build -c Release
- run: dotnet test -c Release
- persist_to_workspace:
root: .
paths: ./Bonk/bin
deploy:
<<: *defaults
steps:
- checkout
- attach_workspace:
at: .
- run: dotnet nuget push ./Bonk/bin/Release/MoonTools.Core.Bonk.*.nupkg -k $API_KEY -s https://api.nuget.org/v3/index.json
workflows:
version: 2
test_and_deploy:
jobs:
- test:
filters:
tags:
only: /.*/
- deploy:
requires:
- test
filters:
branches:
ignore: /.*/
tags:
only: /^\d+\.\d+\.\d+(-preview\d*)?$/

View File

@ -1,24 +0,0 @@
kind: pipeline
type: docker
name: default
workspace:
path: /build
steps:
- name: test
image: mcr.microsoft.com/dotnet/core/sdk:3.1
commands:
- dotnet build -c Release
- dotnet test -c Release
- name: deploy
image: mcr.microsoft.com/dotnet/core/sdk:3.1
environment:
API_KEY:
from_secret: API_KEY
commands:
- dotnet nuget push /build/Bonk/bin/Release/MoonTools.Bonk.*.nupkg -s https://api.nuget.org/v3/index.json -k $API_KEY
when:
ref:
- refs/tags/*.*.*

View File

@ -1,9 +1,9 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Numerics; using System.Numerics;
using MoonTools.Structs; using MoonTools.Core.Structs;
namespace MoonTools.Bonk namespace MoonTools.Core.Bonk
{ {
/// <summary> /// <summary>
/// Axis-aligned bounding box. /// Axis-aligned bounding box.
@ -26,13 +26,11 @@ namespace MoonTools.Bonk
public float Right { get { return Max.X; } } public float Right { get { return Max.X; } }
public float Left { get { return Min.X; } } public float Left { get { return Min.X; } }
/// <summary> /// <summary>
/// The top of the AABB. Assumes a downward-aligned Y axis, so this value will be smaller than Bottom. /// The top of the AABB. Assumes a downward-aligned Y axis, so this value will be smaller than Bottom.
/// </summary> /// </summary>
/// <value></value> /// <value></value>
public float Top { get { return Min.Y; } } public float Top { get { return Min.Y; } }
/// <summary> /// <summary>
/// The bottom of the AABB. Assumes a downward-aligned Y axis, so this value will be larger than Top. /// The bottom of the AABB. Assumes a downward-aligned Y axis, so this value will be larger than Top.
/// </summary> /// </summary>

View File

@ -1,29 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<Version>8.0.1</Version> <Version>6.0.0</Version>
<TargetFramework>netstandard2.0</TargetFramework> <TargetFramework>netstandard2.0</TargetFramework>
<Description>.NET Standard High Performance Collision Detection</Description> <Description>.NET Core High Performance Collision Detection</Description>
<PackageId>MoonTools.Bonk</PackageId> <PackageId>MoonTools.Core.Bonk</PackageId>
<RootNamespace>MoonTools.Bonk</RootNamespace> <RootNamespace>MoonTools.Core.Bonk</RootNamespace>
<Company>Moonside Games</Company> <Company>Moonside Games</Company>
<Authors>Evan Hemsley</Authors> <Authors>Evan Hemsley</Authors>
<Copyright>Evan Hemsley 2019</Copyright> <Copyright>Evan Hemsley 2019</Copyright>
<Product>MoonTools.Bonk</Product> <Product>MoonTools.Core.Bonk</Product>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild> <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<AssemblyName>MoonTools.Bonk</AssemblyName> <AssemblyName>MoonTools.Core.Bonk</AssemblyName>
<PackageLicenseExpression>LGPL-3.0-only</PackageLicenseExpression> <PackageLicenseExpression>LGPL-3.0-only</PackageLicenseExpression>
<PackageProjectUrl>https://gitea.moonside.games/MoonsideGames/MoonTools.Bonk</PackageProjectUrl> <PackageProjectUrl>https://github.com/MoonsideGames/MoonTools.Core.Bonk</PackageProjectUrl>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Platforms>x64</Platforms>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.8"> <PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.8">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="System.Collections.Immutable" Version="1.7.1" /> <PackageReference Include="MoonTools.Core.Structs" Version="3.0.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.7.0" />
<PackageReference Include="System.Numerics.Vectors" Version="4.5.0" /> <PackageReference Include="System.Numerics.Vectors" Version="4.5.0" />
<PackageReference Include="Microsoft.Bcl.HashCode" Version="1.1.0" /> <PackageReference Include="Microsoft.Bcl.HashCode" Version="1.1.0" />
<PackageReference Include="MoonTools.Structs" Version="3.0.1" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -1,9 +1,9 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Numerics; using System.Numerics;
using MoonTools.Structs; using MoonTools.Core.Structs;
namespace MoonTools.Bonk namespace MoonTools.Core.Bonk
{ {
/// <summary> /// <summary>
/// Used to quickly check if two shapes are potentially overlapping. /// Used to quickly check if two shapes are potentially overlapping.
@ -14,13 +14,7 @@ namespace MoonTools.Bonk
private readonly int cellSize; private readonly int cellSize;
private readonly Dictionary<long, HashSet<T>> hashDictionary = new Dictionary<long, HashSet<T>>(); private readonly Dictionary<long, HashSet<T>> hashDictionary = new Dictionary<long, HashSet<T>>();
private readonly Dictionary<T, (IHasAABB2D, Transform2D)> IDLookup = new Dictionary<T, (IHasAABB2D, Transform2D)>(); private readonly Dictionary<T, IHasAABB2D> IDLookup = new Dictionary<T, IHasAABB2D>();
public int MinX { get; private set; } = 0;
public int MaxX { get; private set; } = 0;
public int MinY { get; private set; } = 0;
public int MaxY { get; private set; } = 0;
public SpatialHash(int cellSize) public SpatialHash(int cellSize)
{ {
@ -37,10 +31,9 @@ namespace MoonTools.Bonk
/// </summary> /// </summary>
/// <param name="id">A unique ID for the shape-transform pair.</param> /// <param name="id">A unique ID for the shape-transform pair.</param>
/// <param name="shape"></param> /// <param name="shape"></param>
/// <param name="transform2D"></param> public void Insert(T id, IHasAABB2D shape)
public void Insert(T id, IHasAABB2D shape, Transform2D transform2D)
{ {
var box = shape.TransformedAABB(transform2D); var box = shape.AABB;
var minHash = Hash(box.Min); var minHash = Hash(box.Min);
var maxHash = Hash(box.Max); var maxHash = Hash(box.Max);
@ -58,40 +51,30 @@ namespace MoonTools.Bonk
IDLookup[id] = (shape, transform2D); IDLookup[id] = (shape, transform2D);
} }
} }
MinX = Math.Min(MinX, minHash.Item1);
MinY = Math.Min(MinY, minHash.Item2);
MaxX = Math.Max(MaxX, maxHash.Item1);
MaxY = Math.Max(MaxY, maxHash.Item2);
} }
/// <summary> /// <summary>
/// Retrieves all the potential collisions of a shape-transform pair. Excludes any shape-transforms with the given ID. /// Retrieves all the potential collisions of a shape-transform pair. Excludes any shape-transforms with the given ID.
/// </summary> /// </summary>
public IEnumerable<(T, IHasAABB2D, Transform2D)> Retrieve(T id, IHasAABB2D shape, Transform2D transform2D) public IEnumerable<(T, IHasAABB2D)> Retrieve(T id, IHasAABB2D shape)
{ {
var box = shape.TransformedAABB(transform2D); var box = shape.AABB;
var (minX, minY) = Hash(box.Min); var minHash = Hash(box.Min);
var (maxX, maxY) = Hash(box.Max); var maxHash = Hash(box.Max);
if (minX < MinX) { minX = MinX; } for (var i = minHash.Item1; i <= maxHash.Item1; i++)
if (maxX > MaxX) { maxX = MaxX; }
if (minY < MinY) { minY = MinY; }
if (maxY > MaxY) { maxY = MaxY; }
for (var i = minX; i <= maxX; i++)
{ {
for (var j = minY; j <= maxY; j++) for (var j = minHash.Item2; j <= maxHash.Item2; j++)
{ {
var key = MakeLong(i, j); var key = MakeLong(i, j);
if (hashDictionary.ContainsKey(key)) if (hashDictionary.ContainsKey(key))
{ {
foreach (var t in hashDictionary[key]) foreach (var t in hashDictionary[key])
{ {
var (otherShape, otherTransform) = IDLookup[t]; var otherShape = IDLookup[t];
if (!id.Equals(t) && AABB.TestOverlap(box, otherShape.TransformedAABB(otherTransform))) if (!id.Equals(t) && AABB.TestOverlap(shape.AABB, otherShape.AABB))
{ {
yield return (t, otherShape, otherTransform); yield return (t, otherShape);
} }
} }
} }
@ -99,35 +82,29 @@ namespace MoonTools.Bonk
} }
} }
/// <summary> /// <summary>
/// Retrieves objects based on a pre-transformed AABB. /// Retrieves objects based on a pre-transformed AABB.
/// </summary> /// </summary>
/// <param name="aabb">A transformed AABB.</param> /// <param name="aabb">A transformed AABB.</param>
/// <returns></returns> /// <returns></returns>
public IEnumerable<(T, IHasAABB2D, Transform2D)> Retrieve(AABB aabb) public IEnumerable<(T, IHasAABB2D)> Retrieve(AABB aabb)
{ {
var (minX, minY) = Hash(aabb.Min); var minHash = Hash(aabb.Min);
var (maxX, maxY) = Hash(aabb.Max); var maxHash = Hash(aabb.Max);
if (minX < MinX) { minX = MinX; } for (var i = minHash.Item1; i <= maxHash.Item1; i++)
if (maxX > MaxX) { maxX = MaxX; }
if (minY < MinY) { minY = MinY; }
if (maxY > MaxY) { maxY = MaxY; }
for (var i = minX; i <= maxX; i++)
{ {
for (var j = minY; j <= maxY; j++) for (var j = minHash.Item2; j <= maxHash.Item2; j++)
{ {
var key = MakeLong(i, j); var key = MakeLong(i, j);
if (hashDictionary.ContainsKey(key)) if (hashDictionary.ContainsKey(key))
{ {
foreach (var t in hashDictionary[key]) foreach (var t in hashDictionary[key])
{ {
var (otherShape, otherTransform) = IDLookup[t]; var otherShape = IDLookup[t];
if (AABB.TestOverlap(aabb, otherShape.TransformedAABB(otherTransform))) if (AABB.TestOverlap(aabb, otherShape.AABB))
{ {
yield return (t, otherShape, otherTransform); yield return (t, otherShape);
} }
} }
} }

View File

@ -0,0 +1,15 @@
using System.Collections.Generic;
namespace MoonTools.Core.Bonk
{
public interface ICollisionTestable
{
bool TestCollision<T>(ICollisionTestable collisionTestable) where T : struct, IShape2D;
IEnumerable<TransformedShape2D<T>> TransformedShapes<T>() where T : struct, IShape2D;
}
public interface ICollisionTestable<T> : ICollisionTestable where T : struct, IShape2D
{
IEnumerable<TransformedShape2D<T>> TransformedShapes { get; }
}
}

View File

@ -1,16 +1,7 @@
using MoonTools.Structs; namespace MoonTools.Core.Bonk
namespace MoonTools.Bonk
{ {
public interface IHasAABB2D public interface IHasAABB2D
{ {
AABB AABB { get; } AABB AABB { get; }
/// <summary>
/// Returns a bounding box based on the shape.
/// </summary>
/// <param name="transform">A Transform for transforming the shape vertices.</param>
/// <returns>Returns a bounding box based on the shape.</returns>
AABB TransformedAABB(Transform2D transform);
} }
} }

View File

@ -1,8 +1,8 @@
using System; using System;
using System.Numerics; using System.Numerics;
using MoonTools.Structs; using MoonTools.Core.Structs;
namespace MoonTools.Bonk namespace MoonTools.Core.Bonk
{ {
public interface IShape2D : IHasAABB2D, IEquatable<IShape2D> public interface IShape2D : IHasAABB2D, IEquatable<IShape2D>
{ {
@ -13,5 +13,7 @@ namespace MoonTools.Bonk
/// <param name="transform">A Transform for transforming the shape vertices.</param> /// <param name="transform">A Transform for transforming the shape vertices.</param>
/// <returns>The farthest point on the edge of the shape along the given direction.</returns> /// <returns>The farthest point on the edge of the shape along the given direction.</returns>
Vector2 Support(Vector2 direction, Transform2D transform); Vector2 Support(Vector2 direction, Transform2D transform);
AABB TransformedAABB(Transform2D transform);
} }
} }

View File

@ -1,57 +1,50 @@
using System; using System;
using System.Numerics; using System.Numerics;
using MoonTools.Structs;
namespace MoonTools.Bonk namespace MoonTools.Core.Bonk
{ {
/// <summary> /// <summary>
/// A Minkowski difference between two shapes. /// A Minkowski difference between two shapes.
/// </summary> /// </summary>
public struct MinkowskiDifference : IEquatable<MinkowskiDifference> public struct MinkowskiDifference<T, U> : IEquatable<MinkowskiDifference<T, U>> where T : struct, IShape2D where U : struct, IShape2D
{ {
private IShape2D ShapeA { get; } private TransformedShape2D<T> ShapeA { get; }
private Transform2D TransformA { get; } private TransformedShape2D<U> ShapeB { get; }
private IShape2D ShapeB { get; }
private Transform2D TransformB { get; }
public MinkowskiDifference(IShape2D shapeA, Transform2D transformA, IShape2D shapeB, Transform2D transformB) public MinkowskiDifference(TransformedShape2D<T> shapeA, TransformedShape2D<U> shapeB)
{ {
ShapeA = shapeA; ShapeA = shapeA;
TransformA = transformA;
ShapeB = shapeB; ShapeB = shapeB;
TransformB = transformB;
} }
public Vector2 Support(Vector2 direction) public Vector2 Support(Vector2 direction)
{ {
return ShapeA.Support(direction, TransformA) - ShapeB.Support(-direction, TransformB); return ShapeA.Support(direction) - ShapeB.Support(-direction);
} }
public override bool Equals(object other) public override bool Equals(object other)
{ {
return other is MinkowskiDifference minkowskiDifference && Equals(minkowskiDifference); return other is MinkowskiDifference<T, U> minkowskiDifference && Equals(minkowskiDifference);
} }
public bool Equals(MinkowskiDifference other) public bool Equals(MinkowskiDifference<T, U> other)
{ {
return return
ShapeA == other.ShapeA && ShapeA == other.ShapeA &&
TransformA == other.TransformA && ShapeB == other.ShapeB;
ShapeB == other.ShapeB &&
TransformB == other.TransformB;
} }
public override int GetHashCode() public override int GetHashCode()
{ {
return HashCode.Combine(ShapeA, TransformA, ShapeB, TransformB); return HashCode.Combine(ShapeA, ShapeB);
} }
public static bool operator ==(MinkowskiDifference a, MinkowskiDifference b) public static bool operator ==(MinkowskiDifference<T, U> a, MinkowskiDifference<T, U> b)
{ {
return a.Equals(b); return a.Equals(b);
} }
public static bool operator !=(MinkowskiDifference a, MinkowskiDifference b) public static bool operator !=(MinkowskiDifference<T, U> a, MinkowskiDifference<T, U> b)
{ {
return !(a == b); return !(a == b);
} }

View File

@ -1,21 +1,33 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.Immutable; using System.Collections.Immutable;
using System.Numerics; using MoonTools.Core.Structs;
using MoonTools.Structs;
namespace MoonTools.Bonk namespace MoonTools.Core.Bonk
{ {
public struct MultiShape : IHasAABB2D public struct MultiShape<TShape2D> : IHasAABB2D, ICollisionTestable<TShape2D> where TShape2D : struct, IShape2D
{ {
public ImmutableArray<(IShape2D, Transform2D)> ShapeTransformPairs { get; } private static ImmutableArray<TransformedShape2D<TShape2D>>.Builder _builder = ImmutableArray.CreateBuilder<TransformedShape2D<TShape2D>>();
private ImmutableArray<TransformedShape2D<TShape2D>> _transformedShapes;
public IEnumerable<TransformedShape2D<TShape2D>> TransformedShapes { get { return _transformedShapes; } }
public AABB AABB { get; } public AABB AABB { get; }
public MultiShape(ImmutableArray<(IShape2D, Transform2D)> shapeTransformPairs) public MultiShape(ImmutableArray<(TShape2D, Transform2D)> shapeTransformPairs)
{ {
ShapeTransformPairs = shapeTransformPairs; _builder.Clear();
foreach (var (shape, transform) in shapeTransformPairs)
{
_builder.Add(new TransformedShape2D<TShape2D>(shape, transform));
}
AABB = AABBFromShapes(shapeTransformPairs); _transformedShapes = _builder.ToImmutable();
AABB = AABBFromShapes(_transformedShapes);
}
public MultiShape(ImmutableArray<TransformedShape2D<TShape2D>> transformedShapes)
{
_transformedShapes = transformedShapes;
AABB = AABBFromShapes(transformedShapes);
} }
public AABB TransformedAABB(Transform2D transform) public AABB TransformedAABB(Transform2D transform)
@ -23,40 +35,24 @@ namespace MoonTools.Bonk
return AABB.Transformed(AABB, transform); return AABB.Transformed(AABB, transform);
} }
/// <summary> public IEnumerable<TransformedShape2D<TShape2D>> Compose(Transform2D transform)
/// Moves the shapes by pivoting with an offset transform.
/// </summary>
/// <param name="offsetTransform"></param>
/// <returns></returns>
public IEnumerable<(IShape2D, Transform2D)> TransformShapesUsingOffset(Transform2D offsetTransform)
{ {
foreach (var (shape, shapeTransform) in ShapeTransformPairs) foreach (var transformedShape in TransformedShapes)
{ {
var newTransform = new Transform2D(Vector2.Transform(shapeTransform.Position, offsetTransform.TransformMatrix), offsetTransform.Rotation, offsetTransform.Scale); yield return transformedShape.Compose(transform);
yield return (shape, newTransform);
} }
} }
public bool IsSingleShape<T>() where T : struct, IShape2D private static AABB AABBFromShapes(IEnumerable<TransformedShape2D<TShape2D>> transformedShapes)
{
return ShapeTransformPairs.Length == 1 && ShapeTransformPairs[0].Item1 is T;
}
public (T, Transform2D) ShapeTransformPair<T>() where T : struct, IShape2D
{
return ((T, Transform2D))ShapeTransformPairs[0];
}
private static AABB AABBFromShapes(IEnumerable<(IShape2D, Transform2D)> shapeTransforms)
{ {
var minX = float.MaxValue; var minX = float.MaxValue;
var minY = float.MaxValue; var minY = float.MaxValue;
var maxX = float.MinValue; var maxX = float.MinValue;
var maxY = float.MinValue; var maxY = float.MinValue;
foreach (var (shape, transform) in shapeTransforms) foreach (var transformedShape in transformedShapes)
{ {
var aabb = shape.TransformedAABB(transform); var aabb = transformedShape.AABB;
if (aabb.Min.X < minX) if (aabb.Min.X < minX)
{ {

View File

@ -1,6 +1,6 @@
using System.Numerics; using System.Numerics;
namespace MoonTools.Bonk namespace MoonTools.Core.Bonk
{ {
internal struct Edge internal struct Edge
{ {

View File

@ -1,7 +1,9 @@
using MoonTools.Structs; using MoonTools.Core.Structs;
using System;
using System.Collections.Generic;
using System.Numerics; using System.Numerics;
namespace MoonTools.Bonk namespace MoonTools.Core.Bonk
{ {
public static class NarrowPhase public static class NarrowPhase
{ {
@ -11,92 +13,80 @@ namespace MoonTools.Bonk
CounterClockwise CounterClockwise
} }
/// <summary> public static bool TestCollision<T, U>(ICollisionTestable<T> a, ICollisionTestable<U> b) where T : struct, IShape2D where U : struct, IShape2D
/// Tests if two shape-transform pairs are overlapping. Automatically detects fast-path optimizations.
/// </summary>
public static bool TestCollision(IHasAABB2D hasBoundingBoxA, Transform2D transformA, IHasAABB2D hasBoundingBoxB, Transform2D transformB)
{ {
if (hasBoundingBoxA is MultiShape && hasBoundingBoxB is MultiShape) foreach (var shape in a.TransformedShapes)
{ {
return TestCollision((MultiShape)hasBoundingBoxA, transformA, (MultiShape)hasBoundingBoxB, transformB); foreach (var shapeB in b.TransformedShapes)
} {
else if (hasBoundingBoxA is MultiShape && hasBoundingBoxB is IShape2D) return TestCollision(shape, shapeB);
{ }
return TestCollision((MultiShape)hasBoundingBoxA, transformA, (IShape2D)hasBoundingBoxB, transformB);
}
else if (hasBoundingBoxA is IShape2D && hasBoundingBoxB is MultiShape)
{
return TestCollision((IShape2D)hasBoundingBoxA, transformA, (MultiShape)hasBoundingBoxB, transformB);
}
else if (hasBoundingBoxA is IShape2D && hasBoundingBoxB is IShape2D)
{
return TestCollision((IShape2D)hasBoundingBoxA, transformA, (IShape2D)hasBoundingBoxB, transformB);
}
else
{
throw new System.ArgumentException("Collision testing requires MultiShapes or IShape2Ds.");
}
}
public static bool TestCollision(IShape2D shapeA, Transform2D transformA, IShape2D shapeB, Transform2D transformB)
{
if (shapeA is Rectangle rectangleA && shapeB is Rectangle rectangleB && transformA.Rotation == 0 && transformB.Rotation == 0)
{
return TestRectangleOverlap(rectangleA, transformA, rectangleB, transformB);
}
else if (shapeA is Point && shapeB is Rectangle && transformB.Rotation == 0)
{
return TestPointRectangleOverlap((Point)shapeA, transformA, (Rectangle)shapeB, transformB);
}
else if (shapeA is Rectangle && shapeB is Point && transformA.Rotation == 0)
{
return TestPointRectangleOverlap((Point)shapeB, transformB, (Rectangle)shapeA, transformA);
}
else if (shapeA is Circle circleA && shapeB is Circle circleB && transformA.Scale.X == transformA.Scale.Y && transformB.Scale.X == transformB.Scale.Y)
{
return TestCircleOverlap(circleA, transformA, circleB, transformB);
}
return FindCollisionSimplex(shapeA, transformA, shapeB, transformB).Item1;
}
/// <summary>
/// Tests if a multishape-transform and shape-transform pair are overlapping.
/// Note that this must perform pairwise comparison so the worst-case performance of this method will vary inversely with the amount of shapes in the multishape.
/// </summary>
/// <param name="multiShape"></param>
/// <param name="multiShapeTransform"></param>
/// <param name="shape"></param>
/// <param name="shapeTransform"></param>
/// <returns></returns>
public static bool TestCollision(MultiShape multiShape, Transform2D multiShapeTransform, IShape2D shape, Transform2D shapeTransform)
{
foreach (var (otherShape, otherTransform) in multiShape.TransformShapesUsingOffset(multiShapeTransform))
{
if (TestCollision(shape, shapeTransform, otherShape, otherTransform)) { return true; }
} }
return false; return false;
} }
/// <summary> /// <summary>
/// Tests if a multishape-transform and shape-transform pair are overlapping. /// Tests if two shape-transform pairs are overlapping.
/// </summary>
public static bool TestCollision<T, U>(T shape, Transform2D transform, U shapeB, Transform2D transformB) where T : struct, IShape2D where U : struct, IShape2D
{
return TestCollision(new TransformedShape2D<T>(shape, transform), new TransformedShape2D<U>(shapeB, transformB));
}
/// <summary>
/// Tests if two TransformedShapes are overlapping.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="U"></typeparam>
/// <param name="transformedShapeA"></param>
/// <param name="transformedShapeB"></param>
/// <returns></returns>
public static bool TestCollision<T, U>(TransformedShape2D<T> transformedShapeA, TransformedShape2D<U> transformedShapeB) where T : struct, IShape2D where U : struct, IShape2D
{
return FindCollisionSimplex(transformedShapeA, transformedShapeB).Item1;
}
/// <summary>
/// Tests if a multishape-transform and shape-transform pair are overlapping.
/// Note that this must perform pairwise comparison so the worst-case performance of this method will vary inversely with the amount of shapes in the multishape. /// Note that this must perform pairwise comparison so the worst-case performance of this method will vary inversely with the amount of shapes in the multishape.
/// </summary> /// </summary>
/// <param name="multiShape"></param> /// <param name="multiShape"></param>
/// <param name="multiShapeTransform"></param> /// <param name="multiShapeTransform"></param>
/// <param name="shape"></param> /// <param name="shape"></param>
/// <param name="shapeTransform"></param>
/// <returns></returns> /// <returns></returns>
public static bool TestCollision(IShape2D shape, Transform2D shapeTransform, MultiShape multiShape, Transform2D multiShapeTransform) public static bool TestCollision<T, U>(MultiShape<T> multiShape, Transform2D multiShapeTransform, TransformedShape2D<U> shape) where T : struct, IShape2D where U : struct, IShape2D
{ {
foreach (var (otherShape, otherTransform) in multiShape.TransformShapesUsingOffset(multiShapeTransform)) foreach (var transformedShape in multiShape.Compose(multiShapeTransform))
{ {
if (TestCollision(shape, shapeTransform, otherShape, otherTransform)) { return true; } if (TestCollision(shape, transformedShape)) { return true; }
}
return false;
}
public static bool TestCollison<T>(IEnumerable<TransformedShape2D<T>> transformedShapes, Transform2D multiShapeTransform, TransformedShape2D<U> shape) where T : struct, IShape2D where U : struct, IShape2D
{
foreach (var transformedShape in transformedShapes)
{
if (TestCollision(transformedShape.Compose(multiShapeTransform), shape)) { return true; }
} }
return false; return false;
} }
/// <summary> /// <summary>
/// Tests if two multishape-transform pairs are overlapping. /// Tests if a multishape-transform and shape-transform pair are overlapping.
/// Note that this must perform pairwise comparison so the worst-case performance of this method will vary inversely with the amount of shapes in the multishape.
/// </summary>
/// <param name="multiShape"></param>
/// <param name="multiShapeTransform"></param>
/// <param name="shape"></param>
/// <returns></returns>
public static bool TestCollision<T, U>(TransformedShape2D<T> shape, MultiShape<U> multiShape, Transform2D multiShapeTransform) where T : struct, IShape2D where U : struct, IShape2D
{
return TestCollision(multiShape, multiShapeTransform, shape);
}
/// <summary>
/// Tests if two multishape-transform pairs are overlapping.
/// Note that this must perform pairwise comparison so the worst-case performance of this method will vary inversely with the amount of shapes in the multishapes. /// Note that this must perform pairwise comparison so the worst-case performance of this method will vary inversely with the amount of shapes in the multishapes.
/// </summary> /// </summary>
/// <param name="multiShapeA"></param> /// <param name="multiShapeA"></param>
@ -104,13 +94,13 @@ namespace MoonTools.Bonk
/// <param name="multiShapeB"></param> /// <param name="multiShapeB"></param>
/// <param name="transformB"></param> /// <param name="transformB"></param>
/// <returns></returns> /// <returns></returns>
public static bool TestCollision(MultiShape multiShapeA, Transform2D transformA, MultiShape multiShapeB, Transform2D transformB) public static bool TestCollision<T, U>(MultiShape<T> multiShapeA, Transform2D transformA, MultiShape<U> multiShapeB, Transform2D transformB) where T : struct, IShape2D where U : struct, IShape2D
{ {
foreach (var (shapeA, shapeTransformA) in multiShapeA.TransformShapesUsingOffset(transformA)) foreach (var transformedShapeA in multiShapeA.Compose(transformA))
{ {
foreach (var (shapeB, shapeTransformB) in multiShapeB.TransformShapesUsingOffset(transformB)) foreach (var transformedShapeB in multiShapeB.Compose(transformB))
{ {
if (TestCollision(shapeA, shapeTransformA, shapeB, shapeTransformB)) { return true; } if (TestCollision(transformedShapeA, transformedShapeB)) { return true; }
} }
} }
return false; return false;
@ -120,14 +110,12 @@ namespace MoonTools.Bonk
/// Fast path for axis-aligned rectangles. If the transforms have non-zero rotation this will be inaccurate. /// Fast path for axis-aligned rectangles. If the transforms have non-zero rotation this will be inaccurate.
/// </summary> /// </summary>
/// <param name="rectangleA"></param> /// <param name="rectangleA"></param>
/// <param name="transformA"></param>
/// <param name="rectangleB"></param> /// <param name="rectangleB"></param>
/// <param name="transformB"></param>
/// <returns></returns> /// <returns></returns>
public static bool TestRectangleOverlap(Rectangle rectangleA, Transform2D transformA, Rectangle rectangleB, Transform2D transformB) public static bool TestCollision(TransformedShape2D<Rectangle> rectangleA, TransformedShape2D<Rectangle> rectangleB)
{ {
var firstAABB = rectangleA.TransformedAABB(transformA); var firstAABB = rectangleA.AABB;
var secondAABB = rectangleB.TransformedAABB(transformB); var secondAABB = rectangleB.AABB;
return firstAABB.Left <= secondAABB.Right && firstAABB.Right >= secondAABB.Left && firstAABB.Top <= secondAABB.Bottom && firstAABB.Bottom >= secondAABB.Top; return firstAABB.Left <= secondAABB.Right && firstAABB.Right >= secondAABB.Left && firstAABB.Top <= secondAABB.Bottom && firstAABB.Bottom >= secondAABB.Top;
} }
@ -136,33 +124,34 @@ namespace MoonTools.Bonk
/// Fast path for overlapping point and axis-aligned rectangle. The rectangle transform must have non-zero rotation. /// Fast path for overlapping point and axis-aligned rectangle. The rectangle transform must have non-zero rotation.
/// </summary> /// </summary>
/// <param name="point"></param> /// <param name="point"></param>
/// <param name="pointTransform"></param>
/// <param name="rectangle"></param> /// <param name="rectangle"></param>
/// <param name="rectangleTransform"></param>
/// <returns></returns> /// <returns></returns>
public static bool TestPointRectangleOverlap(Point point, Transform2D pointTransform, Rectangle rectangle, Transform2D rectangleTransform) public static bool TestCollision(TransformedShape2D<Point> point, TransformedShape2D<Rectangle> rectangle)
{ {
var transformedPoint = pointTransform.Position; var transformedPoint = point.Transform.Position;
var AABB = rectangle.TransformedAABB(rectangleTransform); var AABB = rectangle.AABB;
return transformedPoint.X >= AABB.Left && transformedPoint.X <= AABB.Right && transformedPoint.Y <= AABB.Bottom && transformedPoint.Y >= AABB.Top; return transformedPoint.X >= AABB.Left && transformedPoint.X <= AABB.Right && transformedPoint.Y <= AABB.Bottom && transformedPoint.Y >= AABB.Top;
} }
public static bool TestCollision(TransformedShape2D<Rectangle> rectangle, TransformedShape2D<Point> point)
{
return TestCollision(point, rectangle);
}
/// <summary> /// <summary>
/// Fast path for overlapping circles. The circles must have uniform scaling. /// Fast path for overlapping circles. The circles must have uniform scaling.
/// </summary> /// </summary>
/// <param name="circleA"></param> /// <param name="circleA"></param>
/// <param name="transformA"></param>
/// <param name="circleB"></param> /// <param name="circleB"></param>
/// <param name="transformB"></param>
/// <returns></returns> /// <returns></returns>
public static bool TestCircleOverlap(Circle circleA, Transform2D transformA, Circle circleB, Transform2D transformB) public static bool TestCollision(TransformedShape2D<Circle> circleA, TransformedShape2D<Circle> circleB)
{ {
var radiusA = circleA.Radius * transformA.Scale.X; var radiusA = circleA.Shape.Radius * circleA.Transform.Scale.X;
var radiusB = circleB.Radius * transformB.Scale.Y; var radiusB = circleB.Shape.Radius * circleB.Transform.Scale.Y;
var centerA = transformA.Position; var centerA = circleA.Transform.Position;
var centerB = transformB.Position; var centerB = circleB.Transform.Position;
var distanceSquared = (centerA - centerB).LengthSquared(); var distanceSquared = (centerA - centerB).LengthSquared();
var radiusSumSquared = (radiusA + radiusB) * (radiusA + radiusB); var radiusSumSquared = (radiusA + radiusB) * (radiusA + radiusB);
@ -173,9 +162,9 @@ namespace MoonTools.Bonk
/// <summary> /// <summary>
/// Tests if the two shape-transform pairs are overlapping, and returns a simplex that can be used by the EPA algorithm to determine a miminum separating vector. /// Tests if the two shape-transform pairs are overlapping, and returns a simplex that can be used by the EPA algorithm to determine a miminum separating vector.
/// </summary> /// </summary>
public static (bool, Simplex2D) FindCollisionSimplex(IShape2D shapeA, Transform2D transformA, IShape2D shapeB, Transform2D transformB) public static (bool, Simplex2D) FindCollisionSimplex<T, U>(TransformedShape2D<T> shapeA, TransformedShape2D<U> shapeB) where T : struct, IShape2D where U : struct, IShape2D
{ {
var minkowskiDifference = new MinkowskiDifference(shapeA, transformA, shapeB, transformB); var minkowskiDifference = new MinkowskiDifference<T, U>(shapeA, shapeB);
var c = minkowskiDifference.Support(Vector2.UnitX); var c = minkowskiDifference.Support(Vector2.UnitX);
var b = minkowskiDifference.Support(-Vector2.UnitX); var b = minkowskiDifference.Support(-Vector2.UnitX);
return Check(minkowskiDifference, c, b); return Check(minkowskiDifference, c, b);
@ -185,7 +174,7 @@ namespace MoonTools.Bonk
/// Returns a minimum separating vector in the direction from A to B. /// Returns a minimum separating vector in the direction from A to B.
/// </summary> /// </summary>
/// <param name="simplex">A simplex returned by the GJK algorithm.</param> /// <param name="simplex">A simplex returned by the GJK algorithm.</param>
public unsafe static Vector2 Intersect(IShape2D shapeA, Transform2D Transform2DA, IShape2D shapeB, Transform2D Transform2DB, Simplex2D simplex) public unsafe static Vector2 Intersect<T, U>(TransformedShape2D<T> shapeA, TransformedShape2D<U> shapeB, Simplex2D simplex) where T : struct, IShape2D where U : struct, IShape2D
{ {
if (shapeA == null) { throw new System.ArgumentNullException(nameof(shapeA)); } if (shapeA == null) { throw new System.ArgumentNullException(nameof(shapeA)); }
if (shapeB == null) { throw new System.ArgumentNullException(nameof(shapeB)); } if (shapeB == null) { throw new System.ArgumentNullException(nameof(shapeB)); }
@ -207,7 +196,7 @@ namespace MoonTools.Bonk
for (var i = 0; i < 32; i++) for (var i = 0; i < 32; i++)
{ {
var edge = FindClosestEdge(winding, simplexVertices); var edge = FindClosestEdge(winding, simplexVertices);
var support = CalculateSupport(shapeA, Transform2DA, shapeB, Transform2DB, edge.normal); var support = CalculateSupport(shapeA, shapeB, edge.normal);
var distance = Vector2.Dot(support, edge.normal); var distance = Vector2.Dot(support, edge.normal);
intersection = edge.normal; intersection = edge.normal;
@ -261,12 +250,12 @@ namespace MoonTools.Bonk
return new Edge(closestDistance, closestNormal, closestIndex); return new Edge(closestDistance, closestNormal, closestIndex);
} }
private static Vector2 CalculateSupport(IShape2D shapeA, Transform2D Transform2DA, IShape2D shapeB, Transform2D Transform2DB, Vector2 direction) private static Vector2 CalculateSupport<T, U>(TransformedShape2D<T> shapeA, TransformedShape2D<U> shapeB, Vector2 direction) where T : struct, IShape2D where U : struct, IShape2D
{ {
return shapeA.Support(direction, Transform2DA) - shapeB.Support(-direction, Transform2DB); return shapeA.Support(direction) - shapeB.Support(-direction);
} }
private static (bool, Simplex2D) Check(MinkowskiDifference minkowskiDifference, Vector2 c, Vector2 b) private static (bool, Simplex2D) Check<T, U>(MinkowskiDifference<T, U> minkowskiDifference, Vector2 c, Vector2 b) where T : struct, IShape2D where U : struct, IShape2D
{ {
var cb = c - b; var cb = c - b;
var c0 = -c; var c0 = -c;
@ -274,7 +263,7 @@ namespace MoonTools.Bonk
return DoSimplex(minkowskiDifference, new Simplex2D(b, c), d); return DoSimplex(minkowskiDifference, new Simplex2D(b, c), d);
} }
private static (bool, Simplex2D) DoSimplex(MinkowskiDifference minkowskiDifference, Simplex2D simplex, Vector2 direction) private static (bool, Simplex2D) DoSimplex<T, U>(MinkowskiDifference<T, U> minkowskiDifference, Simplex2D simplex, Vector2 direction) where T : struct, IShape2D where U : struct, IShape2D
{ {
var a = minkowskiDifference.Support(direction); var a = minkowskiDifference.Support(direction);
var notPastOrigin = Vector2.Dot(a, direction) < 0; var notPastOrigin = Vector2.Dot(a, direction) < 0;

View File

@ -1,8 +1,8 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Numerics; using System.Numerics;
using MoonTools.Structs; using MoonTools.Core.Structs;
namespace MoonTools.Bonk namespace MoonTools.Core.Bonk
{ {
internal unsafe struct SimplexVertexBuffer internal unsafe struct SimplexVertexBuffer
{ {

View File

@ -1,8 +1,8 @@
using System; using System;
using System.Numerics; using System.Numerics;
using MoonTools.Structs; using MoonTools.Core.Structs;
namespace MoonTools.Bonk namespace MoonTools.Core.Bonk
{ {
/// <summary> /// <summary>
/// A Circle is a shape defined by a radius. /// A Circle is a shape defined by a radius.

View File

@ -1,9 +1,9 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Numerics; using System.Numerics;
using MoonTools.Structs; using MoonTools.Core.Structs;
namespace MoonTools.Bonk namespace MoonTools.Core.Bonk
{ {
/// <summary> /// <summary>
/// A line is a shape defined by exactly two points in space. /// A line is a shape defined by exactly two points in space.

View File

@ -1,12 +1,9 @@
using System; using System;
using System.Numerics; using System.Numerics;
using MoonTools.Structs; using MoonTools.Core.Structs;
namespace MoonTools.Bonk namespace MoonTools.Core.Bonk
{ {
/// <summary>
/// A Point is "that which has not part". All points by themselves are identical.
/// </summary>
public struct Point : IShape2D, IEquatable<Point> public struct Point : IShape2D, IEquatable<Point>
{ {
public AABB AABB { get; } public AABB AABB { get; }

View File

@ -2,9 +2,9 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.Immutable; using System.Collections.Immutable;
using System.Numerics; using System.Numerics;
using MoonTools.Structs; using MoonTools.Core.Structs;
namespace MoonTools.Bonk namespace MoonTools.Core.Bonk
{ {
/// <summary> /// <summary>
/// A Shape defined by an arbitrary collection of vertices. /// A Shape defined by an arbitrary collection of vertices.
@ -59,7 +59,7 @@ namespace MoonTools.Bonk
public bool Equals(IShape2D other) public bool Equals(IShape2D other)
{ {
return other is Polygon otherPolygon && Equals(otherPolygon); return (other is Polygon otherPolygon && Equals(otherPolygon));
} }
public bool Equals(Polygon other) public bool Equals(Polygon other)

View File

@ -1,8 +1,8 @@
using System; using System;
using System.Numerics; using System.Numerics;
using MoonTools.Structs; using MoonTools.Core.Structs;
namespace MoonTools.Bonk namespace MoonTools.Core.Bonk
{ {
/// <summary> /// <summary>
/// A rectangle is a shape defined by a width and height. The origin is the center of the rectangle. /// A rectangle is a shape defined by a width and height. The origin is the center of the rectangle.
@ -23,15 +23,15 @@ namespace MoonTools.Bonk
public Vector2 Min { get; } public Vector2 Min { get; }
public Vector2 Max { get; } public Vector2 Max { get; }
public Rectangle(int left, int top, int width, int height) public Rectangle(int width, int height)
{ {
Width = width; Width = width;
Height = height; Height = height;
Left = left; AABB = new AABB(-width / 2f, -height / 2f, width / 2f, height / 2f);
Right = left + width; Right = AABB.Right;
Top = top; Left = AABB.Left;
Bottom = top + height; Top = AABB.Top;
AABB = new AABB(left, top, Right, Bottom); Bottom = AABB.Bottom;
BottomLeft = new Vector2(Left, Bottom); BottomLeft = new Vector2(Left, Bottom);
TopRight = new Vector2(Top, Right); TopRight = new Vector2(Top, Right);
Min = AABB.Min; Min = AABB.Min;

View File

@ -1,9 +1,9 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Numerics; using System.Numerics;
using MoonTools.Structs; using MoonTools.Core.Structs;
using System; using System;
namespace MoonTools.Bonk namespace MoonTools.Core.Bonk
{ {
/// <summary> /// <summary>
/// A simplex is a shape with up to n - 2 vertices in the nth dimension. /// A simplex is a shape with up to n - 2 vertices in the nth dimension.

View File

@ -1,21 +1,26 @@
using System; using System;
using System.Numerics; using System.Numerics;
using MoonTools.Core.Structs;
namespace MoonTools.Bonk namespace MoonTools.Core.Bonk
{ {
public struct SweepResult<T> where T : IEquatable<T> public struct SweepResult<T, U> where T : IEquatable<T> where U : struct, IShape2D
{ {
public readonly static SweepResult<T> False = new SweepResult<T>(); public static SweepResult<T, U> False = new SweepResult<T, U>();
public bool Hit { get; } public bool Hit { get; }
public Vector2 Motion { get; } public Vector2 Motion { get; }
public T ID { get; } public T ID { get; }
public U Shape { get; }
public Transform2D Transform { get; }
public SweepResult(bool hit, Vector2 motion, T id) public SweepResult(bool hit, Vector2 motion, T id, U shape, Transform2D transform)
{ {
Hit = hit; Hit = hit;
Motion = motion; Motion = motion;
ID = id; ID = id;
Shape = shape;
Transform = transform;
} }
} }
} }

View File

@ -1,13 +1,13 @@
using System; using System;
using System.Numerics; using System.Numerics;
using MoonTools.Structs; using MoonTools.Core.Structs;
namespace MoonTools.Bonk namespace MoonTools.Core.Bonk
{ {
public static class SweepTest public static class SweepTest
{ {
/// <summary> /// <summary>
/// Performs a sweep test on and against rectangles. Returns the position 1 pixel before overlap occurs. /// Performs a sweep test on rectangles.
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <param name="spatialHash">A spatial hash.</param> /// <param name="spatialHash">A spatial hash.</param>
@ -15,7 +15,7 @@ namespace MoonTools.Bonk
/// <param name="transform">A transform by which to transform the IHasAABB2D.</param> /// <param name="transform">A transform by which to transform the IHasAABB2D.</param>
/// <param name="ray">Given in world-space.</param> /// <param name="ray">Given in world-space.</param>
/// <returns></returns> /// <returns></returns>
public static SweepResult<T> Test<T>(SpatialHash<T> spatialHash, Rectangle rectangle, Transform2D transform, Vector2 ray) where T : IEquatable<T> public static SweepResult<T, Rectangle> Rectangle<T>(SpatialHash<T> spatialHash, Rectangle rectangle, Transform2D transform, Vector2 ray) where T : IEquatable<T>
{ {
var transformedAABB = rectangle.TransformedAABB(transform); var transformedAABB = rectangle.TransformedAABB(transform);
var sweepBox = SweepBox(transformedAABB, ray); var sweepBox = SweepBox(transformedAABB, ray);
@ -27,100 +27,74 @@ namespace MoonTools.Bonk
foreach (var (id, shape, shapeTransform) in spatialHash.Retrieve(sweepBox)) foreach (var (id, shape, shapeTransform) in spatialHash.Retrieve(sweepBox))
{ {
Rectangle otherRectangle; if (shape is Rectangle otherRectangle)
Transform2D otherTransform;
AABB otherTransformedAABB;
if (shape is Rectangle)
{ {
otherRectangle = (Rectangle)shape; var otherTransformedAABB = otherRectangle.TransformedAABB(shapeTransform);
otherTransformedAABB = shape.TransformedAABB(shapeTransform); float xInvEntry, yInvEntry;
otherTransform = shapeTransform;
}
else if (shape is MultiShape multiShape && multiShape.IsSingleShape<Rectangle>())
{
Transform2D rectangleOffset;
(otherRectangle, rectangleOffset) = multiShape.ShapeTransformPair<Rectangle>();
otherTransform = shapeTransform.Compose(rectangleOffset);
otherTransformedAABB = shape.TransformedAABB(otherTransform);
}
else
{
continue;
}
float xInvEntry, yInvEntry; if (ray.X > 0)
if (ray.X > 0)
{
xInvEntry = otherTransformedAABB.Left - (transformedAABB.Right);
}
else
{
xInvEntry = (otherTransformedAABB.Right) - transformedAABB.Left;
}
if (ray.Y > 0)
{
yInvEntry = otherTransformedAABB.Top - (transformedAABB.Bottom);
}
else
{
yInvEntry = (otherTransformedAABB.Bottom) - transformedAABB.Top;
}
float xEntry, yEntry;
if (ray.X == 0)
{
xEntry = float.MinValue;
}
else
{
xEntry = xInvEntry / ray.X;
}
if (ray.Y == 0)
{
yEntry = float.MinValue;
}
else
{
yEntry = yInvEntry / ray.Y;
}
var entryTime = Math.Max(xEntry, yEntry);
if (entryTime >= 0 && entryTime <= 1)
{
if (entryTime < shortestDistance)
{ {
shortestDistance = entryTime; xInvEntry = shapeTransform.Position.X - (transform.Position.X + transformedAABB.Width);
nearestID = id; }
nearestRectangle = otherRectangle; else
nearestTransform = shapeTransform; {
xInvEntry = (shapeTransform.Position.X + otherTransformedAABB.Width) - transform.Position.X;
}
if (ray.Y > 0)
{
yInvEntry = shapeTransform.Position.Y - (transform.Position.Y + transformedAABB.Height);
}
else
{
yInvEntry = (shapeTransform.Position.Y + otherTransformedAABB.Height) - shapeTransform.Position.Y;
}
float xEntry, yEntry;
if (ray.X == 0)
{
xEntry = float.MinValue;
}
else
{
xEntry = xInvEntry / ray.X;
}
if (ray.Y == 0)
{
yEntry = float.MinValue;
}
else
{
yEntry = yInvEntry / ray.Y;
}
var entryTime = Math.Max(xEntry, yEntry);
if (entryTime > 0 && entryTime < 1)
{
if (entryTime < shortestDistance)
{
shortestDistance = entryTime;
nearestID = id;
nearestRectangle = rectangle;
nearestTransform = shapeTransform;
}
} }
} }
} }
if (nearestRectangle.HasValue) if (nearestRectangle.HasValue)
{ {
var overlapPosition = ray * shortestDistance; return new SweepResult<T, Rectangle>(true, ray * shortestDistance, nearestID, nearestRectangle.Value, nearestTransform.Value);
var correctionX = -Math.Sign(ray.X);
var correctionY = -Math.Sign(ray.Y);
return new SweepResult<T>(true, new Position2D((int)overlapPosition.X + correctionX, (int)overlapPosition.Y + correctionY), nearestID);
} }
else else
{ {
return SweepResult<T>.False; return SweepResult<T, Rectangle>.False;
} }
} }
public static SweepResult<T> Test<T>(SpatialHash<T> spatialHash, Point point, Transform2D transform, Vector2 ray) where T : IEquatable<T>
{
return Test(spatialHash, new Rectangle(0, 0, 0, 0), transform, ray);
}
private static AABB SweepBox(AABB aabb, Vector2 ray) private static AABB SweepBox(AABB aabb, Vector2 ray)
{ {
return new AABB( return new AABB(

View File

@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
using System.Numerics;
using MoonTools.Core.Structs;
namespace MoonTools.Core.Bonk
{
public struct TransformedShape2D<TShape2D> : IEquatable<TransformedShape2D<TShape2D>>, ICollisionTestable<TShape2D>, IHasAABB2D where TShape2D : struct, IShape2D
{
public TShape2D Shape { get; }
public Transform2D Transform { get; }
public AABB AABB { get; }
public IEnumerable<TransformedShape2D<TShape2D>> TransformedShapes { get { yield return this; } }
public TransformedShape2D(TShape2D shape, Transform2D transform)
{
Shape = shape;
Transform = transform;
AABB = shape.TransformedAABB(transform);
}
public TransformedShape2D<TShape2D> Compose(Transform2D transform)
{
return new TransformedShape2D<TShape2D>(Shape, Transform.Compose(transform));
}
public Vector2 Support(Vector2 direction)
{
return Shape.Support(direction, Transform);
}
public void Deconstruct(out TShape2D shape, out Transform2D transform)
{
shape = Shape;
transform = Transform;
}
public bool TestCollision<U>(ICollisionTestable collisionTestable) where U : struct, IShape2D
{
return NarrowPhase.TestCollision(TransformedShapes, collisionTestable.TransformedShapes);
if (collisionTestable is MultiShape<U> multiShape)
{
return NarrowPhase.TestCollision(this, multiShape);
}
else if (collisionTestable is TransformedShape2D<U> shape)
{
return NarrowPhase.TestCollision(this, shape);
}
return false;
}
public override bool Equals(object obj)
{
return obj is TransformedShape2D<TShape2D> d && Equals(d);
}
public bool Equals(TransformedShape2D<TShape2D> other)
{
return Shape.Equals(other.Shape) &&
Transform.Equals(other.Transform);
}
public override int GetHashCode()
{
return HashCode.Combine(Shape, Transform);
}
public static bool operator ==(TransformedShape2D<TShape2D> left, TransformedShape2D<TShape2D> right)
{
return left.Equals(right);
}
public static bool operator !=(TransformedShape2D<TShape2D> left, TransformedShape2D<TShape2D> right)
{
return !(left == right);
}
}
}

View File

@ -1,6 +1,6 @@
using System.Numerics; using System.Numerics;
namespace MoonTools.Bonk.Extensions namespace MoonTools.Core.Bonk.Extensions
{ {
internal static class Vector2Extensions internal static class Vector2Extensions
{ {
@ -15,4 +15,4 @@ namespace MoonTools.Bonk.Extensions
return a.Cross(b) > 0 ? Vector2.Normalize(new Vector2(ab.Y, ab.X)) : Vector2.Normalize(new Vector2(ab.Y, -ab.X)); return a.Cross(b) > 0 ? Vector2.Normalize(new Vector2(ab.Y, ab.X)) : Vector2.Normalize(new Vector2(ab.Y, -ab.X));
} }
} }
} }

View File

@ -1,7 +1,7 @@
# MoonTools.Bonk # MoonTools.Core.Bonk
[![NuGet Badge](https://buildstats.info/nuget/MoonTools.Bonk)](https://www.nuget.org/packages/MoonTools.Bonk/) [![NuGet Badge](https://buildstats.info/nuget/MoonTools.Core.Bonk)](https://www.nuget.org/packages/MoonTools.Core.Bonk/)
[![Build Status](https://gitea.drone.moonside.games/api/badges/MoonsideGames/MoonTools.Bonk/status.svg)](https://gitea.drone.moonside.games/MoonsideGames/MoonTools.Bonk) [![CircleCI](https://circleci.com/gh/MoonsideGames/MoonTools.Core.Bonk.svg?style=svg)](https://circleci.com/gh/MoonsideGames/MoonTools.Core.Bonk)
Bonk is a fast and modular collision detection system for .NET that is part of the MoonTools suite. It can be used with any .NET-based game engine. Bonk is a fast and modular collision detection system for .NET that is part of the MoonTools suite. It can be used with any .NET-based game engine.

View File

@ -1,6 +1,6 @@
using NUnit.Framework; using NUnit.Framework;
using FluentAssertions; using FluentAssertions;
using MoonTools.Bonk; using MoonTools.Core.Bonk;
using System.Numerics; using System.Numerics;
namespace Tests namespace Tests

View File

@ -3,8 +3,8 @@ using FluentAssertions;
using System; using System;
using System.Numerics; using System.Numerics;
using MoonTools.Structs; using MoonTools.Core.Structs;
using MoonTools.Bonk; using MoonTools.Core.Bonk;
namespace Tests namespace Tests
{ {
@ -13,70 +13,61 @@ namespace Tests
[Test] [Test]
public void RectangleOverlap() public void RectangleOverlap()
{ {
var squareA = new Rectangle(-1, -1, 2, 2); var squareA = new TransformedShape2D<Rectangle>(new Rectangle(2, 2), Transform2D.DefaultTransform);
var transformA = Transform2D.DefaultTransform; var squareB = new TransformedShape2D<Rectangle>(new Rectangle(2, 2), new Transform2D(new Vector2(1.5f, 0)));
var squareB = new Rectangle(-1, -1, 2, 2);
var transformB = new Transform2D(new Vector2(1.5f, 0));
var (result, simplex) = NarrowPhase.FindCollisionSimplex(squareA, transformA, squareB, transformB); var (result, simplex) = NarrowPhase.FindCollisionSimplex(squareA, squareB);
result.Should().BeTrue(); result.Should().BeTrue();
var intersection = NarrowPhase.Intersect(squareA, transformA, squareB, transformB, simplex); var intersection = NarrowPhase.Intersect(squareA, squareB, simplex);
intersection.X.Should().Be(1f); intersection.X.Should().Be(1f);
intersection.Y.Should().Be(0); intersection.Y.Should().Be(0);
var movedTransform = new Transform2D(transformA.Position - (intersection * 2)); // move past var movedTransform = new Transform2D(-(intersection * 1.01f)); // move a tiny bit past
NarrowPhase.TestCollision(squareA, movedTransform, squareB, transformB).Should().BeFalse(); NarrowPhase.TestCollision(squareA.Compose(movedTransform), squareB).Should().BeFalse();
} }
[Test] [Test]
public void CircleOverlap() public void CircleOverlap()
{ {
var circleA = new Circle(2); var circleA = new TransformedShape2D<Circle>(new Circle(2), Transform2D.DefaultTransform);
var transformA = Transform2D.DefaultTransform; var circleB = new TransformedShape2D<Circle>(new Circle(1), new Transform2D(new Vector2(1, 1)));
var circleB = new Circle(1);
var transformB = new Transform2D(new Vector2(1, 1));
var (result, simplex) = NarrowPhase.FindCollisionSimplex(circleA, transformA, circleB, transformB); var (result, simplex) = NarrowPhase.FindCollisionSimplex(circleA, circleB);
result.Should().BeTrue(); result.Should().BeTrue();
var intersection = NarrowPhase.Intersect(circleA, transformA, circleB, transformB, simplex); var intersection = NarrowPhase.Intersect(circleA, circleB, simplex);
var ix = (circleA.Radius * (float)Math.Cos(Math.PI / 4)) - ((circleB.Radius * (float)Math.Cos(5 * Math.PI / 4)) + transformB.Position.X); var ix = (2 * (float)Math.Cos(Math.PI / 4)) - ((1 * (float)Math.Cos(5 * Math.PI / 4)) + 1);
var iy = (circleA.Radius * (float)Math.Sin(Math.PI / 4)) - ((circleB.Radius * (float)Math.Sin(5 * Math.PI / 4)) + transformB.Position.Y); var iy = (2 * (float)Math.Sin(Math.PI / 4)) - ((1 * (float)Math.Sin(5 * Math.PI / 4)) + 1);
intersection.X.Should().BeApproximately(ix, 0.01f); intersection.X.Should().BeApproximately(ix, 0.01f);
intersection.Y.Should().BeApproximately(iy, 0.01f); intersection.Y.Should().BeApproximately(iy, 0.01f);
var movedTransform = new Transform2D(transformA.Position - (intersection * 2)); // move past var movedTransform = new Transform2D(-(intersection * 1.01f)); // move a tiny bit past
NarrowPhase.TestCollision(circleA, movedTransform, circleB, transformB).Should().BeFalse(); NarrowPhase.TestCollision(circleA.Compose(movedTransform), circleB).Should().BeFalse();
} }
[Test] [Test]
public void LineRectangleOverlap() public void LineRectangleOverlap()
{ {
var line = new Line(new Position2D(-4, -4), new Position2D(4, 4)); var line = new TransformedShape2D<Line>(new Line(new Position2D(-4, -4), new Position2D(4, 4)), Transform2D.DefaultTransform);
var transformA = Transform2D.DefaultTransform; var square = new TransformedShape2D<Rectangle>(new Rectangle(2, 2), Transform2D.DefaultTransform);
var square = new Rectangle(-1, -1, 2, 2);
var transformB = Transform2D.DefaultTransform;
var (result, simplex) = NarrowPhase.FindCollisionSimplex(line, transformA, square, transformB); var (result, simplex) = NarrowPhase.FindCollisionSimplex(line, square);
result.Should().BeTrue(); result.Should().BeTrue();
var intersection = NarrowPhase.Intersect(line, transformA, square, transformB, simplex); var intersection = NarrowPhase.Intersect(line, square, simplex);
intersection.X.Should().Be(1); var movedTransform = new Transform2D(-(intersection * 1.01f)); // move a tiny bit past
intersection.Y.Should().Be(-1);
var movedTransform = new Transform2D(transformA.Position - (intersection * 2)); // move past NarrowPhase.TestCollision(line.Compose(movedTransform), square).Should().BeFalse();
NarrowPhase.TestCollision(line, movedTransform, square, transformB).Should().BeFalse();
} }
} }
} }

View File

@ -1,8 +1,8 @@
using NUnit.Framework; using NUnit.Framework;
using FluentAssertions; using FluentAssertions;
using MoonTools.Bonk; using MoonTools.Core.Bonk;
using MoonTools.Structs; using MoonTools.Core.Structs;
using System.Numerics; using System.Numerics;
using System.Collections.Immutable; using System.Collections.Immutable;
@ -140,8 +140,8 @@ namespace Tests
[Test] [Test]
public void RectangleEqual() public void RectangleEqual()
{ {
var a = new Rectangle(-1, -1, 3, 3); var a = new Rectangle(3, 3);
var b = new Rectangle(-1, -1, 3, 3); var b = new Rectangle(3, 3);
a.Equals(b).Should().BeTrue(); a.Equals(b).Should().BeTrue();
} }
@ -149,8 +149,8 @@ namespace Tests
[Test] [Test]
public void RectangleEqualOperator() public void RectangleEqualOperator()
{ {
var a = new Rectangle(-1, -1, 3, 3); var a = new Rectangle(3, 3);
var b = new Rectangle(-1, -1, 3, 3); var b = new Rectangle(3, 3);
(a == b).Should().BeTrue(); (a == b).Should().BeTrue();
} }
@ -158,8 +158,8 @@ namespace Tests
[Test] [Test]
public void RectangleNotEqual() public void RectangleNotEqual()
{ {
var a = new Rectangle(-1, -1, 3, 3); var a = new Rectangle(3, 3);
var b = new Rectangle(-3, -3, 6, 6); var b = new Rectangle(6, 6);
a.Equals(b).Should().BeFalse(); a.Equals(b).Should().BeFalse();
} }
@ -167,8 +167,8 @@ namespace Tests
[Test] [Test]
public void RectangleNotEqualOperator() public void RectangleNotEqualOperator()
{ {
var a = new Rectangle(-1, -1, 3, 3); var a = new Rectangle(3, 3);
var b = new Rectangle(-3, -3, 6, 6); var b = new Rectangle(6, 6);
(a != b).Should().BeTrue(); (a != b).Should().BeTrue();
} }

View File

@ -1,6 +1,6 @@
using NUnit.Framework; using NUnit.Framework;
using MoonTools.Bonk; using MoonTools.Core.Bonk;
using MoonTools.Structs; using MoonTools.Core.Structs;
using System.Numerics; using System.Numerics;
using FluentAssertions; using FluentAssertions;
using System.Collections.Immutable; using System.Collections.Immutable;
@ -55,7 +55,7 @@ namespace Tests
public void PointRectangleOverlapping() public void PointRectangleOverlapping()
{ {
var point = new Point(); var point = new Point();
var rectangle = new Rectangle(-2, -2, 4, 4); var rectangle = new Rectangle(4, 4);
NarrowPhase.TestCollision(point, Transform2D.DefaultTransform, rectangle, Transform2D.DefaultTransform).Should().BeTrue(); NarrowPhase.TestCollision(point, Transform2D.DefaultTransform, rectangle, Transform2D.DefaultTransform).Should().BeTrue();
} }
@ -65,7 +65,7 @@ namespace Tests
{ {
var point = new Point(); var point = new Point();
var pointTransform = new Transform2D(new Position2D(5, 5)); var pointTransform = new Transform2D(new Position2D(5, 5));
var rectangle = new Rectangle(-2, -2, 4, 4); var rectangle = new Rectangle(4, 4);
NarrowPhase.TestCollision(point, pointTransform, rectangle, Transform2D.DefaultTransform).Should().BeFalse(); NarrowPhase.TestCollision(point, pointTransform, rectangle, Transform2D.DefaultTransform).Should().BeFalse();
} }
@ -354,10 +354,10 @@ namespace Tests
[Test] [Test]
public void RectanglesNotOverlapping() public void RectanglesNotOverlapping()
{ {
var rectangleA = new Rectangle(-6, -6, 12, 12); var rectangleA = new Rectangle(12, 12);
var transformA = new Transform2D(new Position2D(39, 249)); var transformA = new Transform2D(new Position2D(39, 249));
var rectangleB = new Rectangle(-8, -8, 16, 16); var rectangleB = new Rectangle(16, 16);
var transformB = new Transform2D(new Position2D(16, 240)); var transformB = new Transform2D(new Position2D(16, 240));
NarrowPhase.TestCollision(rectangleA, transformA, rectangleB, transformB).Should().BeFalse(); NarrowPhase.TestCollision(rectangleA, transformA, rectangleB, transformB).Should().BeFalse();
@ -366,10 +366,10 @@ namespace Tests
[Test] [Test]
public void RotatedRectanglesOverlapping() public void RotatedRectanglesOverlapping()
{ {
var rectangleA = new Rectangle(-1, -3, 3, 6); var rectangleA = new Rectangle(3, 6);
var transformA = new Transform2D(new Vector2(4f, 0), (float)System.Math.PI / 2); var transformA = new Transform2D(new Vector2(4f, 0), (float)System.Math.PI / 2);
var rectangleB = new Rectangle(-1, -1, 2, 2); var rectangleB = new Rectangle(2, 2);
var transformB = new Transform2D(new Vector2(0, 0)); var transformB = new Transform2D(new Vector2(0, 0));
NarrowPhase.TestCollision(rectangleA, transformA, rectangleB, transformB).Should().BeTrue(); NarrowPhase.TestCollision(rectangleA, transformA, rectangleB, transformB).Should().BeTrue();
@ -378,10 +378,10 @@ namespace Tests
[Test] [Test]
public void RectanglesTouchingGJK2D() public void RectanglesTouchingGJK2D()
{ {
var rectangleA = new Rectangle(-1, -1, 2, 2); var rectangleA = new Rectangle(2, 2);
var transformA = new Transform2D(new Position2D(-1, 0)); var transformA = new Transform2D(new Position2D(-1, 0));
var rectangleB = new Rectangle(-1, -1, 2, 2); var rectangleB = new Rectangle(2, 2);
var transformB = new Transform2D(new Vector2(1, 0)); var transformB = new Transform2D(new Vector2(1, 0));
NarrowPhase.TestCollision(rectangleA, transformA, rectangleB, transformB).Should().BeTrue(); NarrowPhase.TestCollision(rectangleA, transformA, rectangleB, transformB).Should().BeTrue();
@ -390,10 +390,10 @@ namespace Tests
[Test] [Test]
public void RectanglesOverlappingGJK2D() public void RectanglesOverlappingGJK2D()
{ {
var rectangleA = new Rectangle(-1, -1, 2, 2); var rectangleA = new Rectangle(2, 2);
var transformA = new Transform2D(new Position2D(0, 0)); var transformA = new Transform2D(new Position2D(0, 0));
var rectangleB = new Rectangle(-1, -1, 2, 2); var rectangleB = new Rectangle(2, 2);
var transformB = new Transform2D(new Vector2(1, 0)); var transformB = new Transform2D(new Vector2(1, 0));
NarrowPhase.TestCollision(rectangleA, transformA, rectangleB, transformB).Should().BeTrue(); NarrowPhase.TestCollision(rectangleA, transformA, rectangleB, transformB).Should().BeTrue();
@ -402,44 +402,44 @@ namespace Tests
[Test] [Test]
public void RectanglesTouchingOverlap() public void RectanglesTouchingOverlap()
{ {
var rectangleA = new Rectangle(-1, -1, 2, 2); var rectangleA = new Rectangle(2, 2);
var transformA = new Transform2D(new Position2D(-1, 0)); var transformA = new Transform2D(new Position2D(-1, 0));
var rectangleB = new Rectangle(-1, -1, 2, 2); var rectangleB = new Rectangle(2, 2);
var transformB = new Transform2D(new Vector2(1, 0)); var transformB = new Transform2D(new Vector2(1, 0));
NarrowPhase.TestRectangleOverlap(rectangleA, transformA, rectangleB, transformB).Should().BeTrue(); NarrowPhase.TestCollision(new TransformedShape2D<Rectangle>(rectangleA, transformA), new TransformedShape2D<Rectangle>(rectangleB, transformB)).Should().BeTrue();
} }
[Test] [Test]
public void RectanglesOverlappingOverlap() public void RectanglesOverlappingOverlap()
{ {
var rectangleA = new Rectangle(-1, -1, 2, 2); var rectangleA = new Rectangle(2, 2);
var transformA = new Transform2D(new Position2D(0, 0)); var transformA = new Transform2D(new Position2D(0, 0));
var rectangleB = new Rectangle(-1, -1, 2, 2); var rectangleB = new Rectangle(2, 2);
var transformB = new Transform2D(new Vector2(1, 0), 0, new Vector2(-1, 1)); var transformB = new Transform2D(new Vector2(1, 0));
NarrowPhase.TestRectangleOverlap(rectangleA, transformA, rectangleB, transformB).Should().BeTrue(); NarrowPhase.TestCollision(new TransformedShape2D<Rectangle>(rectangleA, transformA), new TransformedShape2D<Rectangle>(rectangleB, transformB)).Should().BeTrue();
} }
[Test] [Test]
public void MultiRectanglesOverlapping() public void MultiRectanglesOverlapping()
{ {
var multiRectangleA = new MultiShape( var multiRectangleA = new MultiShape<Rectangle>(
ImmutableArray.Create<(IShape2D, Transform2D)>( ImmutableArray.Create(
(new Rectangle(-2, 0, 4, 1), new Transform2D(new Position2D(-5, 0))), (new Rectangle(4, 1), new Transform2D(new Position2D(-5, 0))),
(new Rectangle(-2, 0, 4, 1), new Transform2D(new Position2D(-5, 1))), (new Rectangle(4, 1), new Transform2D(new Position2D(-5, 1))),
(new Rectangle(-2, 0, 4, 1), new Transform2D(new Position2D(-5, 2))) (new Rectangle(4, 1), new Transform2D(new Position2D(-5, 2)))
) )
); );
var transformA = new Transform2D(new Position2D(5, 0)); var transformA = new Transform2D(new Position2D(5, 0));
var multiRectangleB = new MultiShape( var multiRectangleB = new MultiShape<Rectangle>(
ImmutableArray.Create<(IShape2D, Transform2D)>( ImmutableArray.Create(
(new Rectangle(-2, 0, 4, 1), new Transform2D(new Position2D(4, -1))), (new Rectangle(4, 1), new Transform2D(new Position2D(4, -1))),
(new Rectangle(-2, 0, 4, 1), new Transform2D(new Position2D(4, 0))), (new Rectangle(4, 1), new Transform2D(new Position2D(4, 0))),
(new Rectangle(-2, 0, 4, 1), new Transform2D(new Position2D(4, 1))) (new Rectangle(4, 1), new Transform2D(new Position2D(4, 1)))
) )
); );
var transformB = new Transform2D(new Position2D(0, 3)); var transformB = new Transform2D(new Position2D(0, 3));
@ -450,25 +450,30 @@ namespace Tests
[Test] [Test]
public void MultiRectanglesNotOverlapping() public void MultiRectanglesNotOverlapping()
{ {
var multiRectangleA = new MultiShape( var multiRectangleA = new MultiShape<Rectangle>(
ImmutableArray.Create<(IShape2D, Transform2D)>( ImmutableArray.Create(
(new Rectangle(-2, 0, 4, 1), new Transform2D(new Position2D(-5, 0))), (new Rectangle(4, 1), new Transform2D(new Position2D(-5, 0))),
(new Rectangle(-2, 0, 4, 1), new Transform2D(new Position2D(-5, 1))), (new Rectangle(4, 1), new Transform2D(new Position2D(-5, 1))),
(new Rectangle(-2, 0, 4, 1), new Transform2D(new Position2D(-5, 2))) (new Rectangle(4, 1), new Transform2D(new Position2D(-5, 2)))
) )
); );
var transformA = new Transform2D(new Position2D(5, 0)); var transformA = new Transform2D(new Position2D(5, 0));
var multiRectangleB = new MultiShape( var multiRectangleB = new MultiShape<Rectangle>(
ImmutableArray.Create<(IShape2D, Transform2D)>( ImmutableArray.Create(
(new Rectangle(-2, 0, 4, 1), new Transform2D(new Position2D(4, -1))), (new Rectangle(4, 1), new Transform2D(new Position2D(4, -1))),
(new Rectangle(-2, 0, 4, 1), new Transform2D(new Position2D(4, 0))), (new Rectangle(4, 1), new Transform2D(new Position2D(4, 0))),
(new Rectangle(-2, 0, 4, 1), new Transform2D(new Position2D(4, 1))) (new Rectangle(4, 1), new Transform2D(new Position2D(4, 1)))
) )
); );
var transformB = new Transform2D(new Position2D(0, -3)); var transformB = new Transform2D(new Position2D(0, -3));
NarrowPhase.TestCollision(multiRectangleA, transformA, multiRectangleB, transformB).Should().BeFalse(); NarrowPhase.TestCollision(multiRectangleA, transformA, multiRectangleB, transformB).Should().BeFalse();
} }
public class SweepTest
{
}
} }
} }

View File

@ -1,7 +1,7 @@
using FluentAssertions; using FluentAssertions;
using NUnit.Framework; using NUnit.Framework;
using MoonTools.Structs; using MoonTools.Core.Structs;
using MoonTools.Bonk; using MoonTools.Core.Bonk;
using System.Numerics; using System.Numerics;
using System.Collections.Immutable; using System.Collections.Immutable;
@ -14,16 +14,16 @@ namespace Tests
{ {
var spatialHash = new SpatialHash<int>(16); var spatialHash = new SpatialHash<int>(16);
var rectA = new Rectangle(-2, -2, 4, 4); var rectA = new Rectangle(4, 4);
var rectATransform = new Transform2D(new Vector2(-8, -8)); var rectATransform = new Transform2D(new Vector2(-8, -8));
var rectB = new Rectangle(-2, -2, 4, 4); var rectB = new Rectangle(4, 4);
var rectBTransform = new Transform2D(new Vector2(8, 8)); var rectBTransform = new Transform2D(new Vector2(8, 8));
var rectC = new Rectangle(-2, -2, 4, 4); var rectC = new Rectangle(4, 4);
var rectCTransform = new Transform2D(new Vector2(24, -4)); var rectCTransform = new Transform2D(new Vector2(24, -4));
var rectD = new Rectangle(-2, -2, 4, 4); var rectD = new Rectangle(4, 4);
var rectDTransform = new Transform2D(new Vector2(24, 24)); var rectDTransform = new Transform2D(new Vector2(24, 24));
var circleA = new Circle(2); var circleA = new Circle(2);
@ -38,11 +38,11 @@ namespace Tests
var point = new Point(); var point = new Point();
var pointTransform = new Transform2D(new Position2D(8, 8)); var pointTransform = new Transform2D(new Position2D(8, 8));
var multiRectangle = new MultiShape( var multiRectangle = new MultiShape<Rectangle>(
ImmutableArray.Create<(IShape2D, Transform2D)>( ImmutableArray.Create(
(new Rectangle(-2, 0, 4, 1), new Transform2D(new Position2D(-2, -2))), (new Rectangle(4, 1), new Transform2D(new Position2D(-2, -2))),
(new Rectangle(-2, 0, 4, 1), new Transform2D(new Position2D(-2, -1))), (new Rectangle(4, 1), new Transform2D(new Position2D(-2, -1))),
(new Rectangle(-2, 0, 4, 1), new Transform2D(new Position2D(-2, 0))) (new Rectangle(4, 1), new Transform2D(new Position2D(-2, 0)))
) )
); );
var multiRectangleTransform = new Transform2D(new Position2D(8, 8)); var multiRectangleTransform = new Transform2D(new Position2D(8, 8));
@ -78,13 +78,13 @@ namespace Tests
{ {
var spatialHash = new SpatialHash<int>(16); var spatialHash = new SpatialHash<int>(16);
var rectA = new Rectangle(-2, -2, 4, 4); var rectA = new Rectangle(4, 4);
var rectATransform = new Transform2D(new Vector2(-8, -8)); var rectATransform = new Transform2D(new Vector2(-8, -8));
var rectB = new Rectangle(-2, -2, 4, 4); var rectB = new Rectangle(4, 4);
var rectBTransform = new Transform2D(new Vector2(-8, -8)); var rectBTransform = new Transform2D(new Vector2(-8, -8));
var rectC = new Rectangle(-2, -2, 2, 2); var rectC = new Rectangle(2, 2);
var rectCTransform = new Transform2D(new Vector2(-8, -8)); var rectCTransform = new Transform2D(new Vector2(-8, -8));
spatialHash.Insert(0, rectA, rectATransform); spatialHash.Insert(0, rectA, rectATransform);
@ -99,10 +99,10 @@ namespace Tests
{ {
var spatialHash = new SpatialHash<int>(16); var spatialHash = new SpatialHash<int>(16);
var rectA = new Rectangle(-2, -2, 4, 4); var rectA = new Rectangle(4, 4);
var rectATransform = new Transform2D(new Vector2(-8, -8)); var rectATransform = new Transform2D(new Vector2(-8, -8));
var rectB = new Rectangle(-2, -2, 4, 4); var rectB = new Rectangle(4, 4);
var rectBTransform = new Transform2D(new Vector2(8, 8)); var rectBTransform = new Transform2D(new Vector2(8, 8));
spatialHash.Insert(0, rectA, rectATransform); spatialHash.Insert(0, rectA, rectATransform);

View File

@ -1,7 +1,7 @@
using System.Numerics; using System.Numerics;
using FluentAssertions; using FluentAssertions;
using MoonTools.Bonk; using MoonTools.Core.Bonk;
using MoonTools.Structs; using MoonTools.Core.Structs;
using NUnit.Framework; using NUnit.Framework;
namespace Tests namespace Tests
@ -11,32 +11,24 @@ namespace Tests
[Test] [Test]
public void SweepsThrough() public void SweepsThrough()
{ {
var rectangle = new Rectangle(-2, -2, 4, 4); var rectangle = new Rectangle(4, 4);
var transform = new Transform2D(new Position2D(-6, 0)); var transform = new Transform2D(new Position2D(-6, 0));
var otherRectangle = new Rectangle(-2, -2, 4, 4); var otherRectangle = new Rectangle(4, 4);
var otherTransform = new Transform2D(new Position2D(6, 0)); var otherTransform = new Transform2D(new Position2D(6, 0));
var farthestRectangle = new Rectangle(-2, -2, 4, 4); var farthestRectangle = new Rectangle(4, 4);
var farthestTransform = new Transform2D(new Position2D(12, 0)); var farthestTransform = new Transform2D(new Position2D(12, 0));
var downRectangle = new Rectangle(-6, -2, 12, 4);
var downTransform = new Transform2D(new Position2D(-6, 20));
var spatialHash = new SpatialHash<int>(16); var spatialHash = new SpatialHash<int>(16);
spatialHash.Insert(1, otherRectangle, otherTransform); spatialHash.Insert(1, otherRectangle, otherTransform);
spatialHash.Insert(2, farthestRectangle, farthestTransform); spatialHash.Insert(2, farthestRectangle, farthestTransform);
spatialHash.Insert(3, downRectangle, downTransform);
SweepTest.Test(spatialHash, rectangle, transform, new Vector2(12, 0)).Should().Be( SweepTest.Rectangle(spatialHash, rectangle, transform, new Vector2(12, 0)).Should().Be(
new SweepResult<int>(true, new Vector2(7, 0), 1) new SweepResult<int, Rectangle>(true, new Vector2(8, 0), 1, otherRectangle, otherTransform)
); );
SweepTest.Test(spatialHash, rectangle, transform, new Vector2(-12, 0)).Hit.Should().BeFalse(); SweepTest.Rectangle(spatialHash, rectangle, transform, new Vector2(-12, 0)).Hit.Should().BeFalse();
SweepTest.Test(spatialHash, rectangle, transform, new Vector2(0, 20)).Should().Be(
new SweepResult<int>(true, new Vector2(0, 15), 3)
);
} }
} }
} }

View File

@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework> <TargetFramework>netcoreapp3.0</TargetFramework>
<IsPackable>false</IsPackable> <IsPackable>false</IsPackable>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@ -12,4 +12,4 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Bonk\Bonk.csproj" /> <ProjectReference Include="..\Bonk\Bonk.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>