85 lines
2.3 KiB
C#
85 lines
2.3 KiB
C#
using System;
|
|
using System.Buffers;
|
|
using System.Collections.Concurrent;
|
|
using Unity.Mathematics;
|
|
using System.Collections.Generic;
|
|
|
|
namespace Net.BITKit.Quadtree
|
|
{
|
|
public struct QuadtreeNode
|
|
{
|
|
public readonly Quadtree Root;
|
|
|
|
public int Depth;
|
|
|
|
public float2 Center; // 节点中心
|
|
public float2 Size; // 节点大小
|
|
|
|
public readonly QuadtreeNode[] Children; // 子节点
|
|
public readonly HashSet<int> Objects; // 存储的对象ID
|
|
|
|
public QuadtreeNode(Quadtree root,float2 center, float2 size)
|
|
{
|
|
Root = root;
|
|
Center = center;
|
|
Size = size;
|
|
|
|
Children = new QuadtreeNode[4];
|
|
|
|
Objects = new HashSet<int>();
|
|
|
|
Depth = 0;
|
|
}
|
|
|
|
public bool Contains(float2 point)
|
|
{
|
|
var min = Center - Size * 0.5f;
|
|
var max = Center + Size * 0.5f;
|
|
|
|
return math.all(point >= min & point <= max);
|
|
}
|
|
|
|
public void Split()
|
|
{
|
|
var childSize = Size / 2;
|
|
var offset = childSize / 2;
|
|
|
|
foreach (var node in Children)
|
|
{
|
|
foreach (var id in Objects)
|
|
{
|
|
var pos = Root.Positions[id];
|
|
if (node.Contains(pos))
|
|
{
|
|
node.Objects.Add(id);
|
|
}
|
|
}
|
|
}
|
|
|
|
Objects.Clear();
|
|
|
|
Children[0] = new QuadtreeNode(Root, Center + new float2(-offset.x, offset.y), childSize)
|
|
{
|
|
Depth = Depth + 1,
|
|
};
|
|
Children[1] = new QuadtreeNode(Root, Center + new float2(offset.x, offset.y), childSize)
|
|
{
|
|
Depth = Depth + 1,
|
|
};
|
|
Children[2] = new QuadtreeNode(Root, Center + new float2(-offset.x, -offset.y), childSize)
|
|
{
|
|
Depth = Depth + 1,
|
|
};
|
|
Children[3] = new QuadtreeNode(Root, Center + new float2(offset.x, -offset.y), childSize)
|
|
{
|
|
Depth = Depth + 1,
|
|
};
|
|
}
|
|
|
|
public bool IsLeaf()
|
|
{
|
|
return Children[0].Size.x == 0; // 如果子节点未初始化,说明是叶子节点
|
|
}
|
|
}
|
|
}
|