Implemented quad tree, added test project.

This commit is contained in:
Tiberiu Chibici 2015-05-29 10:48:20 +03:00
parent 4e957167ed
commit 1304499b66
10 changed files with 478 additions and 23 deletions

View File

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TransportGame.Model
{
public interface IPositionable
{
Vector2 Position { get; }
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: cdecfb69b7ca68446910d0a607e934e6
timeCreated: 1432824088
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,23 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TransportGame.Model
{
public class Point
{
public int X { get; set; }
public int Y { get; set; }
public Point()
{
}
public Point(int x, int y)
{
X = x;
Y = y;
}
}
}

View File

@ -0,0 +1,290 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TransportGame.Model;
namespace TransportGame.Utils
{
public class QuadTree<T>: ICollection<T> where T : IPositionable
{
private const int Capacity = 8;
/// <summary>
/// Gets the subtree in northwest position
/// </summary>
public QuadTree<T> NorthWest { get; private set; }
/// <summary>
/// Gets the subtree in northeast position
/// </summary>
public QuadTree<T> NorthEast { get; private set; }
/// <summary>
/// Gets the subtree in southeast position
/// </summary>
public QuadTree<T> SouthEast { get; private set; }
/// <summary>
/// Gets the subtree in southwest position
/// </summary>
public QuadTree<T> SouthWest { get; private set; }
/// <summary>
/// Gets the boundary of this quad tree
/// </summary>
public Rectangle Boundary { get; private set; }
private List<T> points = new List<T>(Capacity);
/// <summary>
/// Initializes a quad tree using specified boundaries
/// </summary>
/// <param name="left">Left</param>
/// <param name="top">Top</param>
/// <param name="right">Right</param>
/// <param name="bottom">Bottom</param>
public QuadTree(float left, float top, float right, float bottom)
{
Boundary = new Rectangle(left, top, right, bottom);
}
/// <summary>
/// Initializes a quad tree using specified boundaries
/// </summary>
/// <param name="boundary">Boundaries</param>
public QuadTree(Rectangle boundary)
{
Boundary = boundary;
}
private void Subdivide()
{
float midx = Boundary.Left + Boundary.Width / 2f;
float midy = Boundary.Top + Boundary.Height / 2f;
NorthWest = new QuadTree<T>(Boundary.Left, Boundary.Top, midx, midy);
NorthEast = new QuadTree<T>(midx, Boundary.Top, Boundary.Right, midy);
SouthEast = new QuadTree<T>(midx, midy, Boundary.Right, Boundary.Bottom);
SouthWest = new QuadTree<T>(Boundary.Left, midy, midx, Boundary.Bottom);
foreach (var point in points)
Add(point);
points.Clear();
}
private void Merge()
{
foreach (var point in NorthWest)
points.Add(point);
foreach (var point in NorthEast)
points.Add(point);
foreach (var point in SouthEast)
points.Add(point);
foreach (var point in SouthWest)
points.Add(point);
NorthWest = null;
NorthEast = null;
SouthEast = null;
SouthWest = null;
}
/// <summary>
/// Adds a point in this quad tree
/// </summary>
/// <param name="item">Point</param>
public void Add(T item)
{
// Precondition - point must be inside boundaries
if (!Boundary.Contains(item.Position))
throw new ArgumentException("Point must be inside boundaries.");
// Reached capacity, subdivide
if (NorthWest == null && points.Count >= Capacity)
Subdivide();
// Not divided in subtrees
if (NorthWest == null)
{
if (!points.Any(p => p.Position.Equals(item.Position)))
points.Add(item);
}
// Add in the right subtree
else
{
if (NorthWest.Boundary.Contains(item.Position))
NorthWest.Add(item);
else if (NorthEast.Boundary.Contains(item.Position))
NorthEast.Add(item);
else if (SouthEast.Boundary.Contains(item.Position))
SouthEast.Add(item);
else SouthWest.Add(item);
}
}
/// <summary>
/// Empties the entire tree
/// </summary>
public void Clear()
{
NorthWest = null;
NorthEast = null;
SouthEast = null;
SouthWest = null;
points.Clear();
}
/// <summary>
/// Tests if specified point is contained in this tree
/// </summary>
/// <param name="item">Point</param>
/// <returns>True if point is contained</returns>
public bool Contains(T item)
{
if (NorthWest == null)
return points.Contains(item);
else
return NorthWest.Contains(item) || NorthEast.Contains(item) || SouthEast.Contains(item) || SouthWest.Contains(item);
}
/// <summary>
/// Copies all points to specified array
/// </summary>
/// <param name="array">Array</param>
/// <param name="arrayIndex">Index where to start copying</param>
public void CopyTo(T[] array, int arrayIndex)
{
foreach (var point in this)
array[arrayIndex++] = point;
}
/// <summary>
/// Gets the number of points in this quad tree
/// </summary>
public int Count
{
get
{
return (NorthWest == null) ? points.Count : NorthWest.Count + NorthEast.Count + SouthEast.Count + SouthWest.Count;
}
}
/// <summary>
/// Returns true if this container is read-only.
/// </summary>
public bool IsReadOnly
{
get
{
return false;
}
}
/// <summary>
/// Removes an item from the tree
/// </summary>
/// <param name="item">Item to remove</param>
/// <returns>True if item was removed</returns>
public bool Remove(T item)
{
if (NorthWest == null)
return points.Remove(item);
else
{
bool result = NorthWest.Remove(item) || NorthEast.Remove(item) || SouthEast.Remove(item) || SouthWest.Remove(item);
// We can merge subdivisions
if (Count < (Capacity - Capacity / 3))
Merge();
return result;
}
}
/// <summary>
/// Gets an enumerator for this collection
/// </summary>
/// <returns></returns>
System.Collections.IEnumerator IEnumerable.GetEnumerator()
{
foreach (var point in this)
yield return point;
}
/// <summary>
/// Gets enumerator for this collection
/// </summary>
/// <returns></returns>
public IEnumerator<T> GetEnumerator()
{
if (NorthWest == null)
{
foreach (var point in points)
yield return point;
}
else
{
foreach (var point in NorthWest)
yield return point;
foreach (var point in NorthEast)
yield return point;
foreach (var point in SouthEast)
yield return point;
foreach (var point in SouthWest)
yield return point;
}
}
/// <summary>
/// Gets all the points in the specified region
/// </summary>
/// <param name="rect">Region</param>
/// <returns>Points</returns>
public IEnumerable<T> Query(Rectangle rect)
{
// No intersection
if (!Rectangle.Intersects(rect, Boundary))
return Enumerable.Empty<T>();
if (NorthWest == null)
{
return points.Where(p => rect.Contains(p.Position));
}
else
{
return NorthWest.Query(rect)
.Concat(NorthEast.Query(rect))
.Concat(SouthEast.Query(rect))
.Concat(SouthWest.Query(rect));
}
}
/// <summary>
/// Gets all the points in the specified region
/// </summary>
/// <param name="left">Left</param>
/// <param name="top">Top</param>
/// <param name="right">Right</param>
/// <param name="bottom">Bottom</param>
/// <returns>Points</returns>
public IEnumerable<T> Query(float left, float top, float right, float bottom)
{
return Query(new Rectangle(left, top, right, bottom));
}
}
}

View File

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: cb5a7be6addc5fe41bfda46c611f4d6b
timeCreated: 1432824088
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

28
Tools/Test/Test.sln Normal file
View File

@ -0,0 +1,28 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.31101.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test", "Test\Test.csproj", "{1A040CAD-758D-4574-A234-E0229D3C9AF9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnityVS.Game.CSharp", "..\..\Game\UnityVS.Game.CSharp.csproj", "{02576F1D-BE9C-CFA7-763D-1EBF63B36977}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1A040CAD-758D-4574-A234-E0229D3C9AF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1A040CAD-758D-4574-A234-E0229D3C9AF9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1A040CAD-758D-4574-A234-E0229D3C9AF9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1A040CAD-758D-4574-A234-E0229D3C9AF9}.Release|Any CPU.Build.0 = Release|Any CPU
{02576F1D-BE9C-CFA7-763D-1EBF63B36977}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{02576F1D-BE9C-CFA7-763D-1EBF63B36977}.Debug|Any CPU.Build.0 = Debug|Any CPU
{02576F1D-BE9C-CFA7-763D-1EBF63B36977}.Release|Any CPU.ActiveCfg = Release|Any CPU
{02576F1D-BE9C-CFA7-763D-1EBF63B36977}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TransportGame.Model;
using TransportGame.Utils;
namespace Test
{
class Program
{
static void Main(string[] args)
{
// TODO: Tests go here
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Test")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("044c2cd3-18db-41ca-ac95-a2df6028b50d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,64 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{1A040CAD-758D-4574-A234-E0229D3C9AF9}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Test</RootNamespace>
<AssemblyName>Test</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\Game\UnityVS.Game.CSharp.csproj">
<Project>{02576f1d-be9c-cfa7-763d-1ebf63b36977}</Project>
<Name>UnityVS.Game.CSharp</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>