using System.Collections.Generic;
using UnityEngine;
///
/// Represents the cull area used for network culling.
///
public class CullArea : MonoBehaviour
{
private const int MAX_NUMBER_OF_ALLOWED_CELLS = 250;
public const int MAX_NUMBER_OF_SUBDIVISIONS = 3;
///
/// This represents the first ID which is assigned to the first created cell.
/// If you already have some interest groups blocking this first ID, fell free to change it.
/// However increasing the first group ID decreases the maximum amount of allowed cells.
/// Allowed values are in range from 1 to 250.
///
public readonly int FIRST_GROUP_ID = 1;
///
/// This represents the order in which updates are sent.
/// The number represents the subdivision of the cell hierarchy:
/// - 0: message is sent to all players
/// - 1: message is sent to players who are interested in the matching cell of the first subdivision
/// If there is only one subdivision we are sending one update to all players
/// before sending three consequent updates only to players who are in the same cell
/// or interested in updates of the current cell.
///
public readonly int[] SUBDIVISION_FIRST_LEVEL_ORDER = new int[4] { 0, 1, 1, 1 };
///
/// This represents the order in which updates are sent.
/// The number represents the subdivision of the cell hierarchy:
/// - 0: message is sent to all players
/// - 1: message is sent to players who are interested in the matching cell of the first subdivision
/// - 2: message is sent to players who are interested in the matching cell of the second subdivision
/// If there are two subdivisions we are sending every second update only to players
/// who are in the same cell or interested in updates of the current cell.
///
public readonly int[] SUBDIVISION_SECOND_LEVEL_ORDER = new int[8] { 0, 2, 1, 2, 0, 2, 1, 2 };
///
/// This represents the order in which updates are sent.
/// The number represents the subdivision of the cell hierarchy:
/// - 0: message is sent to all players
/// - 1: message is sent to players who are interested in the matching cell of the first subdivision
/// - 2: message is sent to players who are interested in the matching cell of the second subdivision
/// - 3: message is sent to players who are interested in the matching cell of the third subdivision
/// If there are two subdivisions we are sending every second update only to players
/// who are in the same cell or interested in updates of the current cell.
///
public readonly int[] SUBDIVISION_THIRD_LEVEL_ORDER = new int[12] { 0, 3, 2, 3, 1, 3, 2, 3, 1, 3, 2, 3 };
public Vector2 Center;
public Vector2 Size = new Vector2(25.0f, 25.0f);
public Vector2[] Subdivisions = new Vector2[MAX_NUMBER_OF_SUBDIVISIONS];
public int NumberOfSubdivisions;
public int CellCount { get; private set; }
public CellTree CellTree { get; private set; }
public Dictionary Map { get; private set; }
public bool YIsUpAxis = true;
public bool RecreateCellHierarchy = false;
private int idCounter;
///
/// Creates the cell hierarchy at runtime.
///
private void Awake()
{
idCounter = FIRST_GROUP_ID;
CreateCellHierarchy();
}
///
/// Creates the cell hierarchy in editor and draws the cell view.
///
public void OnDrawGizmos()
{
idCounter = FIRST_GROUP_ID;
if (RecreateCellHierarchy)
{
CreateCellHierarchy();
}
DrawCells();
}
///
/// Creates the cell hierarchy.
///
private void CreateCellHierarchy()
{
if (!IsCellCountAllowed())
{
if (Debug.isDebugBuild)
{
Debug.LogError("There are too many cells created by your subdivision options. Maximum allowed number of cells is " + (MAX_NUMBER_OF_ALLOWED_CELLS - FIRST_GROUP_ID) + ". Current number of cells is " + CellCount + ".");
return;
}
else
{
Application.Quit();
}
}
CellTreeNode rootNode = new CellTreeNode(idCounter++, CellTreeNode.ENodeType.Root, null);
if (YIsUpAxis)
{
Center = new Vector2(transform.position.x, transform.position.y);
Size = new Vector2(transform.localScale.x, transform.localScale.y);
rootNode.Center = new Vector3(Center.x, Center.y, 0.0f);
rootNode.Size = new Vector3(Size.x, Size.y, 0.0f);
rootNode.TopLeft = new Vector3((Center.x - (Size.x / 2.0f)), (Center.y - (Size.y / 2.0f)), 0.0f);
rootNode.BottomRight = new Vector3((Center.x + (Size.x / 2.0f)), (Center.y + (Size.y / 2.0f)), 0.0f);
}
else
{
Center = new Vector2(transform.position.x, transform.position.z);
Size = new Vector2(transform.localScale.x, transform.localScale.z);
rootNode.Center = new Vector3(Center.x, 0.0f, Center.y);
rootNode.Size = new Vector3(Size.x, 0.0f, Size.y);
rootNode.TopLeft = new Vector3((Center.x - (Size.x / 2.0f)), 0.0f, (Center.y - (Size.y / 2.0f)));
rootNode.BottomRight = new Vector3((Center.x + (Size.x / 2.0f)), 0.0f, (Center.y + (Size.y / 2.0f)));
}
CreateChildCells(rootNode, 1);
CellTree = new CellTree(rootNode);
RecreateCellHierarchy = false;
}
///
/// Creates all child cells.
///
/// The current parent node.
/// The cell level within the current hierarchy.
private void CreateChildCells(CellTreeNode parent, int cellLevelInHierarchy)
{
if (cellLevelInHierarchy > NumberOfSubdivisions)
{
return;
}
int rowCount = (int) Subdivisions[(cellLevelInHierarchy - 1)].x;
int columnCount = (int) Subdivisions[(cellLevelInHierarchy - 1)].y;
float startX = parent.Center.x - (parent.Size.x / 2.0f);
float width = parent.Size.x / rowCount;
for (int row = 0; row < rowCount; ++row)
{
for (int column = 0; column < columnCount; ++column)
{
float xPos = startX + (row * width) + (width / 2.0f);
CellTreeNode node = new CellTreeNode(idCounter++, (NumberOfSubdivisions == cellLevelInHierarchy) ? CellTreeNode.ENodeType.Leaf : CellTreeNode.ENodeType.Node, parent);
if (YIsUpAxis)
{
float startY = parent.Center.y - (parent.Size.y / 2.0f);
float height = parent.Size.y / columnCount;
float yPos = startY + (column * height) + (height / 2.0f);
node.Center = new Vector3(xPos, yPos, 0.0f);
node.Size = new Vector3(width, height, 0.0f);
node.TopLeft = new Vector3(xPos - (width / 2.0f), yPos - (height / 2.0f), 0.0f);
node.BottomRight = new Vector3(xPos + (width / 2.0f), yPos + (height / 2.0f), 0.0f);
}
else
{
float startZ = parent.Center.z - (parent.Size.z / 2.0f);
float depth = parent.Size.z / columnCount;
float zPos = startZ + (column * depth) + (depth / 2.0f);
node.Center = new Vector3(xPos, 0.0f, zPos);
node.Size = new Vector3(width, 0.0f, depth);
node.TopLeft = new Vector3(xPos - (width / 2.0f), 0.0f, zPos - (depth / 2.0f));
node.BottomRight = new Vector3(xPos + (width / 2.0f), 0.0f, zPos + (depth / 2.0f));
}
parent.AddChild(node);
CreateChildCells(node, (cellLevelInHierarchy + 1));
}
}
}
///
/// Draws the cells.
///
private void DrawCells()
{
if ((CellTree != null) && (CellTree.RootNode != null))
{
CellTree.RootNode.Draw();
}
else
{
RecreateCellHierarchy = true;
}
}
///
/// Checks if the cell count is allowed.
///
/// True if the cell count is allowed, false if the cell count is too large.
private bool IsCellCountAllowed()
{
int horizontalCells = 1;
int verticalCells = 1;
foreach (Vector2 v in Subdivisions)
{
horizontalCells *= (int) v.x;
verticalCells *= (int) v.y;
}
CellCount = horizontalCells * verticalCells;
return (CellCount <= (MAX_NUMBER_OF_ALLOWED_CELLS - FIRST_GROUP_ID));
}
///
/// Gets a list of all cell IDs the player is currently inside or nearby.
///
/// The current position of the player.
/// A list containing all cell IDs the player is currently inside or nearby.
public List GetActiveCells(Vector3 position)
{
List insideCells = new List(0);
CellTree.RootNode.GetInsideCells(insideCells, YIsUpAxis, position);
List nearbyCells = new List(0);
CellTree.RootNode.GetNearbyCells(nearbyCells, YIsUpAxis, position);
foreach (int id in nearbyCells)
{
if (!insideCells.Contains(id))
{
insideCells.Add(id);
}
}
return insideCells;
}
}
///
/// Represents the tree accessible from its root node.
///
public class CellTree
{
///
/// Represents the root node of the cell tree.
///
public CellTreeNode RootNode { get; private set; }
///
/// Default constructor.
///
public CellTree()
{
}
///
/// Constructor to define the root node.
///
/// The root node of the tree.
public CellTree(CellTreeNode root)
{
RootNode = root;
}
}
///
/// Represents a single node of the tree.
///
public class CellTreeNode
{
public enum ENodeType
{
Root,
Node,
Leaf
}
///
/// Represents the unique ID of the cell.
///
public int Id;
///
/// Represents the center, top-left or bottom-right position of the cell
/// or the size of the cell.
///
public Vector3 Center, Size, TopLeft, BottomRight;
///
/// Describes the current node type of the cell tree node.
///
public ENodeType NodeType;
///
/// Reference tot he parent node.
///
public CellTreeNode Parent;
///
/// A list containing all child nodes.
///
public List Childs;
///
/// The max distance the player can have to the center of the cell for being 'nearby'.
/// This is calculated once at runtime.
///
private float maxDistance;
///
/// Default constructor.
///
public CellTreeNode()
{
}
///
/// Constructor to define the ID and the node type as well as setting a parent node.
///
/// The ID of the cell is used as the interest group.
/// The node type of the cell tree node.
/// The parent node of the cell tree node.
public CellTreeNode(int id, ENodeType nodeType, CellTreeNode parent)
{
Id = id;
NodeType = nodeType;
Parent = parent;
}
///
/// Adds the given child to the node.
///
/// The child which is added to the node.
public void AddChild(CellTreeNode child)
{
if (Childs == null)
{
Childs = new List(1);
}
Childs.Add(child);
}
///
/// Draws the cell in the editor.
///
public void Draw()
{
#if UNITY_EDITOR
if (Childs != null)
{
foreach (CellTreeNode node in Childs)
{
node.Draw();
}
}
Gizmos.color = new Color((NodeType == ENodeType.Root) ? 1 : 0, (NodeType == ENodeType.Node) ? 1 : 0, (NodeType == ENodeType.Leaf) ? 1 : 0);
Gizmos.DrawWireCube(Center, Size);
UnityEditor.Handles.Label(Center, Id.ToString(), new GUIStyle() { fontStyle = FontStyle.Bold });
#endif
}
///
/// Gathers all leaf nodes and adds them to a given list.
///
/// The list containing all gathered leaf nodes.
public void GetAllLeafNodes(List leafNodes)
{
if (Childs != null)
{
foreach (CellTreeNode node in Childs)
{
node.GetAllLeafNodes(leafNodes);
}
}
else
{
leafNodes.Add(this);
}
}
///
/// Gathers all cell IDs the player is currently inside.
///
/// The list to add all cell IDs to the player is currently inside.
/// Describes if the y-axis is used as up-axis.
/// The current position of the player
public void GetInsideCells(List insideCells, bool yIsUpAxis, Vector3 position)
{
if (IsPointInsideCell(yIsUpAxis, position))
{
insideCells.Add(Id);
if (Childs != null)
{
foreach (CellTreeNode node in Childs)
{
node.GetInsideCells(insideCells, yIsUpAxis, position);
}
}
}
}
///
/// Gathers all cell IDs the palyer is currently nearby.
///
/// The list to add all cell IDs to the player is currently nearby.
/// Describes if the y-axis is used as up-axis.
/// The current position of the player
public void GetNearbyCells(List nearbyCells, bool yIsUpAxis, Vector3 position)
{
if (IsPointNearCell(yIsUpAxis, position))
{
if (NodeType != ENodeType.Leaf)
{
foreach (CellTreeNode node in Childs)
{
node.GetNearbyCells(nearbyCells, yIsUpAxis, position);
}
}
else
{
nearbyCells.Add(Id);
}
}
}
///
/// Checks if the given point is inside the cell.
///
/// Describes if the y-axis is used as up-axis.
/// The point to check.
/// True if the point is inside the cell, false if the point is not inside the cell.
public bool IsPointInsideCell(bool yIsUpAxis, Vector3 point)
{
if ((point.x < TopLeft.x) || (point.x > BottomRight.x))
{
return false;
}
if (yIsUpAxis)
{
if ((point.y >= TopLeft.y) && (point.y <= BottomRight.y))
{
return true;
}
}
else
{
if ((point.z >= TopLeft.z) && (point.z <= BottomRight.z))
{
return true;
}
}
return false;
}
///
/// Checks if the given point is near the cell.
///
/// Describes if the y-axis is used as up-axis.
/// The point to check.
/// True if the point is near the cell, false if the point is too far away.
public bool IsPointNearCell(bool yIsUpAxis, Vector3 point)
{
if (maxDistance == 0.0f)
{
maxDistance = (Size.x + Size.y + Size.z) / 2.0f;
}
return ((point - Center).sqrMagnitude <= (maxDistance * maxDistance));
}
}