123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266 |
- #if !ASTAR_NO_GRID_GRAPH
- using UnityEngine;
- using System.Collections.Generic;
- using Pathfinding.Serialization;
- namespace Pathfinding {
-
-
-
-
-
-
-
-
-
-
-
-
- [Pathfinding.Util.Preserve]
- public class LayerGridGraph : GridGraph, IUpdatableGraph {
-
- protected override void OnDestroy () {
- base.OnDestroy();
-
- RemoveGridGraphFromStatic();
- }
- void RemoveGridGraphFromStatic () {
- LevelGridNode.SetGridGraph(active.data.GetGraphIndex(this), null);
- }
-
-
-
-
- [JsonMember]
- internal int layerCount;
-
- [JsonMember]
- public float mergeSpanRange = 0.5F;
-
- [JsonMember]
- public float characterHeight = 0.4F;
- internal int lastScannedWidth;
- internal int lastScannedDepth;
- public override bool uniformWidthDepthGrid {
- get {
- return false;
- }
- }
- public override int LayerCount {
- get {
- return layerCount;
- }
- }
- public override int CountNodes () {
- if (nodes == null) return 0;
- int counter = 0;
- for (int i = 0; i < nodes.Length; i++) {
- if (nodes[i] != null) counter++;
- }
- return counter;
- }
- public override void GetNodes (System.Action<GraphNode> action) {
- if (nodes == null) return;
- for (int i = 0; i < nodes.Length; i++) {
- if (nodes[i] != null) action(nodes[i]);
- }
- }
- protected override List<GraphNode> GetNodesInRegion (Bounds b, GraphUpdateShape shape) {
- var rect = GetRectFromBounds(b);
- if (nodes == null || !rect.IsValid() || nodes.Length != width*depth*layerCount) {
- return Pathfinding.Util.ListPool<GraphNode>.Claim();
- }
-
- var inArea = Pathfinding.Util.ListPool<GraphNode>.Claim(rect.Width*rect.Height*layerCount);
-
- for (int l = 0; l < layerCount; l++) {
- var lwd = l * width * depth;
- for (int x = rect.xmin; x <= rect.xmax; x++) {
- for (int z = rect.ymin; z <= rect.ymax; z++) {
- int index = lwd + z*width + x;
- GraphNode node = nodes[index];
-
-
- if (node != null && b.Contains((Vector3)node.position) && (shape == null || shape.Contains((Vector3)node.position))) {
- inArea.Add(node);
- }
- }
- }
- }
- return inArea;
- }
- public override List<GraphNode> GetNodesInRegion (IntRect rect) {
-
- var inArea = Pathfinding.Util.ListPool<GraphNode>.Claim();
-
- var gridRect = new IntRect(0, 0, width-1, depth-1);
-
- rect = IntRect.Intersection(rect, gridRect);
- if (nodes == null || !rect.IsValid() || nodes.Length != width*depth*layerCount) return inArea;
- for (int l = 0; l < layerCount; l++) {
- var lwd = l * Width * Depth;
- for (int z = rect.ymin; z <= rect.ymax; z++) {
- var offset = lwd + z*Width;
- for (int x = rect.xmin; x <= rect.xmax; x++) {
- var node = nodes[offset + x];
- if (node != null) {
- inArea.Add(node);
- }
- }
- }
- }
- return inArea;
- }
-
-
-
-
-
-
- public override int GetNodesInRegion (IntRect rect, GridNodeBase[] buffer) {
-
-
- var gridRect = new IntRect(0, 0, width-1, depth-1);
- rect = IntRect.Intersection(rect, gridRect);
- if (nodes == null || !rect.IsValid() || nodes.Length != width*depth*layerCount) return 0;
- int counter = 0;
- try {
- for (int l = 0; l < layerCount; l++) {
- var lwd = l * Width * Depth;
- for (int z = rect.ymin; z <= rect.ymax; z++) {
- var offset = lwd + z*Width;
- for (int x = rect.xmin; x <= rect.xmax; x++) {
- var node = nodes[offset + x];
- if (node != null) {
- buffer[counter] = node;
- counter++;
- }
- }
- }
- }
- } catch (System.IndexOutOfRangeException) {
-
- throw new System.ArgumentException("Buffer is too small");
- }
- return counter;
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public override GridNodeBase GetNode (int x, int z) {
- if (x < 0 || z < 0 || x >= width || z >= depth) return null;
- return nodes[x + z*width];
- }
-
-
-
-
-
-
-
-
- public GridNodeBase GetNode (int x, int z, int layer) {
- if (x < 0 || z < 0 || x >= width || z >= depth || layer < 0 || layer >= layerCount) return null;
- return nodes[x + z*width + layer*width*depth];
- }
- void IUpdatableGraph.UpdateArea (GraphUpdateObject o) {
- if (nodes == null || nodes.Length != width*depth*layerCount) {
- Debug.LogWarning("The Grid Graph is not scanned, cannot update area ");
-
- return;
- }
- IntRect originalRect, affectRect, physicsRect;
- bool willChangeWalkability;
- int erosion;
- CalculateAffectedRegions(o, out originalRect, out affectRect, out physicsRect, out willChangeWalkability, out erosion);
- bool willChangeNodeInstances = (o is LayerGridGraphUpdate && ((LayerGridGraphUpdate)o).recalculateNodes);
- bool preserveExistingNodes = (o is LayerGridGraphUpdate ? ((LayerGridGraphUpdate)o).preserveExistingNodes : !o.resetPenaltyOnPhysics);
- if (o.trackChangedNodes && willChangeNodeInstances) {
- Debug.LogError("Cannot track changed nodes when creating or deleting nodes.\nWill not update LayerGridGraph");
- return;
- }
-
- var gridRect = new IntRect(0, 0, width-1, depth-1);
- IntRect clampedRect = IntRect.Intersection(affectRect, gridRect);
-
- if (!willChangeNodeInstances) {
- for (int x = clampedRect.xmin; x <= clampedRect.xmax; x++) {
- for (int z = clampedRect.ymin; z <= clampedRect.ymax; z++) {
- for (int y = 0; y < layerCount; y++) {
- o.WillUpdateNode(nodes[y*width*depth + z*width+x]);
- }
- }
- }
- }
-
- if (o.updatePhysics && !o.modifyWalkability) {
- collision.Initialize(transform, nodeSize);
- clampedRect = IntRect.Intersection(physicsRect, gridRect);
- for (int x = clampedRect.xmin; x <= clampedRect.xmax; x++) {
- for (int z = clampedRect.ymin; z <= clampedRect.ymax; z++) {
- RecalculateCell(x, z, !preserveExistingNodes, false);
- }
- }
- for (int x = clampedRect.xmin; x <= clampedRect.xmax; x++) {
- for (int z = clampedRect.ymin; z <= clampedRect.ymax; z++) {
- CalculateConnections(x, z);
- }
- }
- }
-
- clampedRect = IntRect.Intersection(originalRect, gridRect);
- for (int x = clampedRect.xmin; x <= clampedRect.xmax; x++) {
- for (int z = clampedRect.ymin; z <= clampedRect.ymax; z++) {
- for (int y = 0; y < layerCount; y++) {
- int index = y*width*depth + z*width+x;
- var node = nodes[index];
- if (node == null) continue;
- if (willChangeWalkability) {
- node.Walkable = node.WalkableErosion;
- if (o.bounds.Contains((Vector3)node.position)) o.Apply(node);
- node.WalkableErosion = node.Walkable;
- } else {
- if (o.bounds.Contains((Vector3)node.position)) o.Apply(node);
- }
- }
- }
- }
-
- if (willChangeWalkability && erosion == 0) {
- clampedRect = IntRect.Intersection(affectRect, gridRect);
- for (int x = clampedRect.xmin; x <= clampedRect.xmax; x++) {
- for (int z = clampedRect.ymin; z <= clampedRect.ymax; z++) {
- CalculateConnections(x, z);
- }
- }
- } else if (willChangeWalkability && erosion > 0) {
- clampedRect = IntRect.Union(originalRect, physicsRect);
- IntRect erosionRect1 = clampedRect.Expand(erosion);
- IntRect erosionRect2 = erosionRect1.Expand(erosion);
- erosionRect1 = IntRect.Intersection(erosionRect1, gridRect);
- erosionRect2 = IntRect.Intersection(erosionRect2, gridRect);
-
- for (int x = erosionRect2.xmin; x <= erosionRect2.xmax; x++) {
- for (int z = erosionRect2.ymin; z <= erosionRect2.ymax; z++) {
- for (int y = 0; y < layerCount; y++) {
- int index = y*width*depth + z*width+x;
- var node = nodes[index];
- if (node == null) continue;
- bool tmp = node.Walkable;
- node.Walkable = node.WalkableErosion;
- if (!erosionRect1.Contains(x, z)) {
-
- node.TmpWalkable = tmp;
- }
- }
- }
- }
- for (int x = erosionRect2.xmin; x <= erosionRect2.xmax; x++) {
- for (int z = erosionRect2.ymin; z <= erosionRect2.ymax; z++) {
- CalculateConnections(x, z);
- }
- }
-
- ErodeWalkableArea(erosionRect2.xmin, erosionRect2.ymin, erosionRect2.xmax+1, erosionRect2.ymax+1);
- for (int x = erosionRect2.xmin; x <= erosionRect2.xmax; x++) {
- for (int z = erosionRect2.ymin; z <= erosionRect2.ymax; z++) {
- if (erosionRect1.Contains(x, z)) continue;
- for (int y = 0; y < layerCount; y++) {
- int index = y*width*depth + z*width+x;
- var node = nodes[index];
- if (node == null) continue;
-
- node.Walkable = node.TmpWalkable;
- }
- }
- }
-
- for (int x = erosionRect2.xmin; x <= erosionRect2.xmax; x++) {
- for (int z = erosionRect2.ymin; z <= erosionRect2.ymax; z++) {
- CalculateConnections(x, z);
- }
- }
- }
- }
- protected override IEnumerable<Progress> ScanInternal () {
-
- if (nodeSize <= 0) yield break;
- UpdateTransform();
-
- if (width > 1024 || depth > 1024) {
- Debug.LogError("One of the grid's sides is longer than 1024 nodes");
- yield break;
- }
- lastScannedWidth = width;
- lastScannedDepth = depth;
- SetUpOffsetsAndCosts();
- LevelGridNode.SetGridGraph((int)graphIndex, this);
-
- maxClimb = Mathf.Clamp(maxClimb, 0, characterHeight);
- collision = collision ?? new GraphCollision();
- collision.Initialize(transform, nodeSize);
- int progressCounter = 0;
- const int YieldEveryNNodes = 1000;
-
- layerCount = 1;
- nodes = new LevelGridNode[width*depth*layerCount];
- for (int z = 0; z < depth; z++) {
-
- if (progressCounter >= YieldEveryNNodes) {
- progressCounter = 0;
- yield return new Progress(Mathf.Lerp(0.0f, 0.8f, z/(float)depth), "Creating nodes");
- }
- progressCounter += width;
- for (int x = 0; x < width; x++) {
- RecalculateCell(x, z);
- }
- }
- for (int z = 0; z < depth; z++) {
-
- if (progressCounter >= YieldEveryNNodes) {
- progressCounter = 0;
- yield return new Progress(Mathf.Lerp(0.8f, 0.9f, z/(float)depth), "Calculating connections");
- }
- progressCounter += width;
- for (int x = 0; x < width; x++) {
- CalculateConnections(x, z);
- }
- }
- yield return new Progress(0.95f, "Calculating Erosion");
- for (int i = 0; i < nodes.Length; i++) {
- var node = nodes[i] as LevelGridNode;
- if (node == null) continue;
-
- if (!node.HasAnyGridConnections()) {
- node.Walkable = false;
- node.WalkableErosion = node.Walkable;
- }
- }
- ErodeWalkableArea();
- }
-
- protected struct HeightSample {
- public Vector3 position;
- public RaycastHit hit;
- public float height;
- public bool walkable;
- }
-
- class HitComparer : IComparer<RaycastHit> {
- public int Compare (RaycastHit a, RaycastHit b) {
- return a.distance.CompareTo(b.distance);
- }
- }
-
- static readonly HitComparer comparer = new HitComparer();
-
- static HeightSample[] heightSampleBuffer = new HeightSample[4];
-
-
-
-
-
-
-
-
-
-
-
-
- protected static HeightSample[] SampleHeights (GraphCollision collision, float mergeSpanRange, Vector3 position, out int numHits) {
- int raycastHits;
- var hits = collision.CheckHeightAll(position, out raycastHits);
-
- System.Array.Sort(hits, 0, raycastHits, comparer);
- if (raycastHits > heightSampleBuffer.Length) heightSampleBuffer = new HeightSample[Mathf.Max(heightSampleBuffer.Length*2, raycastHits)];
- var buffer = heightSampleBuffer;
- if (raycastHits == 0) {
- buffer[0] = new HeightSample {
- position = position,
- height = float.PositiveInfinity,
- walkable = !collision.unwalkableWhenNoGround && collision.Check(position),
- };
- numHits = 1;
- return buffer;
- } else {
- int dstIndex = 0;
- for (int i = raycastHits - 1; i >= 0; i--) {
-
- if (i > 0 && hits[i].distance - hits[i-1].distance <= mergeSpanRange) i--;
- buffer[dstIndex] = new HeightSample {
- position = hits[i].point,
- hit = hits[i],
- walkable = collision.Check(hits[i].point),
- height = i > 0 ? hits[i].distance - hits[i-1].distance : float.PositiveInfinity,
- };
- dstIndex++;
- }
- numHits = dstIndex;
- return buffer;
- }
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public override void RecalculateCell (int x, int z, bool resetPenalties = true, bool resetTags = true) {
-
- float cosAngle = Mathf.Cos(maxSlope*Mathf.Deg2Rad);
-
-
- int numHeightSamples;
- var heightSamples = SampleHeights(collision, mergeSpanRange, transform.Transform(new Vector3(x+0.5F, 0, z+0.5F)), out numHeightSamples);
- if (numHeightSamples > layerCount) {
- if (numHeightSamples > LevelGridNode.MaxLayerCount) {
- Debug.LogError("Too many layers, a maximum of " + LevelGridNode.MaxLayerCount + " are allowed (required " + numHeightSamples + ")");
- return;
- }
- AddLayers(numHeightSamples - layerCount);
- }
- int layerIndex = 0;
- for (; layerIndex < numHeightSamples; layerIndex++) {
- var sample = heightSamples[layerIndex];
- var index = z*width+x + width*depth*layerIndex;
- var node = nodes[index] as LevelGridNode;
- bool isNewNode = node == null;
- if (isNewNode) {
-
- if (nodes[index] != null) {
- nodes[index].Destroy();
- }
-
- node = new LevelGridNode(active);
- nodes[index] = node;
- node.NodeInGridIndex = z*width+x;
- node.LayerCoordinateInGrid = layerIndex;
- node.GraphIndex = graphIndex;
- }
- #if ASTAR_SET_LEVELGRIDNODE_HEIGHT
- node.height = sample.height;
- #endif
- node.position = (Int3)sample.position;
- node.Walkable = sample.walkable;
- node.WalkableErosion = node.Walkable;
- if (isNewNode || resetPenalties) {
- node.Penalty = initialPenalty;
- if (penaltyPosition) {
- node.Penalty += (uint)Mathf.RoundToInt((node.position.y-penaltyPositionOffset)*penaltyPositionFactor);
- }
- }
- if (isNewNode || resetTags) {
- node.Tag = 0;
- }
-
- if (sample.hit.normal != Vector3.zero && (penaltyAngle || cosAngle > 0.0001f)) {
-
- float angle = Vector3.Dot(sample.hit.normal.normalized, collision.up);
-
- if (resetTags && penaltyAngle) {
- node.Penalty += (uint)Mathf.RoundToInt((1F-angle)*penaltyAngleFactor);
- }
-
- if (angle < cosAngle) {
- node.Walkable = false;
- }
- }
- if (sample.height < characterHeight) {
- node.Walkable = false;
- }
- node.WalkableErosion = node.Walkable;
- }
-
- for (; layerIndex < layerCount; layerIndex++) {
- var index = z*width+x + width*depth*layerIndex;
- if (nodes[index] != null) nodes[index].Destroy();
- nodes[index] = null;
- }
- }
-
- void AddLayers (int count) {
- int newLayerCount = layerCount + count;
- if (newLayerCount > LevelGridNode.MaxLayerCount) {
- Debug.LogError("Too many layers, a maximum of " + LevelGridNode.MaxLayerCount + " are allowed (required "+newLayerCount+")");
- return;
- }
- GridNodeBase[] tmp = nodes;
- nodes = new GridNodeBase[width*depth*newLayerCount];
- tmp.CopyTo(nodes, 0);
- layerCount = newLayerCount;
- }
- protected override bool ErosionAnyFalseConnections (GraphNode baseNode) {
- var node = baseNode as LevelGridNode;
- if (neighbours == NumNeighbours.Six) {
-
- for (int i = 0; i < 6; i++) {
- if (!node.HasConnectionInDirection(hexagonNeighbourIndices[i])) {
- return true;
- }
- }
- } else {
-
- for (int i = 0; i < 4; i++) {
- if (!node.HasConnectionInDirection(i)) {
- return true;
- }
- }
- }
- return false;
- }
- public override void CalculateConnections (GridNodeBase baseNode) {
- var node = baseNode as LevelGridNode;
- CalculateConnections(node.XCoordinateInGrid, node.ZCoordinateInGrid, node.LayerCoordinateInGrid);
- }
-
-
-
-
- [System.Obsolete("Use CalculateConnections(x,z,layerIndex) or CalculateConnections(node) instead")]
- public void CalculateConnections (int x, int z, int layerIndex, LevelGridNode node) {
- CalculateConnections(x, z, layerIndex);
- }
-
- public override void CalculateConnections (int x, int z) {
- for (int i = 0; i < layerCount; i++) {
- CalculateConnections(x, z, i);
- }
- }
-
- public void CalculateConnections (int x, int z, int layerIndex) {
- var node = nodes[z*width+x + width*depth*layerIndex] as LevelGridNode;
- if (node == null) return;
- node.ResetAllGridConnections();
- if (!node.Walkable) {
- return;
- }
- var nodePos = (Vector3)node.position;
- var up = transform.WorldUpAtGraphPosition(nodePos);
- var ourY = Vector3.Dot(nodePos, up);
- float height;
- if (layerIndex == layerCount-1 || nodes[node.NodeInGridIndex + width*depth*(layerIndex+1)] == null) {
- height = float.PositiveInfinity;
- } else {
- height = System.Math.Abs(ourY - Vector3.Dot((Vector3)nodes[node.NodeInGridIndex+width*depth*(layerIndex+1)].position, up));
- }
- for (int dir = 0; dir < 4; dir++) {
- int nx = x + neighbourXOffsets[dir];
- int nz = z + neighbourZOffsets[dir];
-
- if (nx < 0 || nz < 0 || nx >= width || nz >= depth) {
- continue;
- }
-
- int nIndex = nz*width+nx;
- int conn = LevelGridNode.NoConnection;
- for (int i = 0; i < layerCount; i++) {
- GraphNode other = nodes[nIndex + width*depth*i];
- if (other != null && other.Walkable) {
- float otherHeight;
- var otherY = Vector3.Dot((Vector3)other.position, up);
-
- if (i == layerCount-1 || nodes[nIndex+width*depth*(i+1)] == null) {
- otherHeight = float.PositiveInfinity;
- } else {
- otherHeight = System.Math.Abs(otherY - Vector3.Dot((Vector3)nodes[nIndex+width*depth*(i+1)].position, up));
- }
- float bottom = Mathf.Max(otherY, ourY);
- float top = Mathf.Min(otherY+otherHeight, ourY+height);
- float dist = top-bottom;
- if (dist >= characterHeight && Mathf.Abs(otherY - ourY) <= maxClimb) {
- conn = i;
- }
- }
- }
- node.SetConnectionValue(dir, conn);
- }
- }
- public override NNInfoInternal GetNearest (Vector3 position, NNConstraint constraint, GraphNode hint) {
- if (nodes == null || depth*width*layerCount != nodes.Length) {
-
- return new NNInfoInternal();
- }
- var graphPosition = transform.InverseTransform(position);
- float xf = graphPosition.x;
- float zf = graphPosition.z;
- int x = Mathf.Clamp((int)xf, 0, width-1);
- int z = Mathf.Clamp((int)zf, 0, depth-1);
- var minNode = GetNearestNode(position, x, z, null);
- var nn = new NNInfoInternal(minNode);
- float y = transform.InverseTransform((Vector3)minNode.position).y;
- nn.clampedPosition = transform.Transform(new Vector3(Mathf.Clamp(xf, x, x+1f), y, Mathf.Clamp(zf, z, z+1f)));
- return nn;
- }
- protected override GridNodeBase GetNearestFromGraphSpace (Vector3 positionGraphSpace) {
- if (nodes == null || depth*width*layerCount != nodes.Length) {
- return null;
- }
- float xf = positionGraphSpace.x;
- float zf = positionGraphSpace.z;
- int x = Mathf.Clamp((int)xf, 0, width-1);
- int z = Mathf.Clamp((int)zf, 0, depth-1);
- var worldPos = transform.Transform(positionGraphSpace);
- return GetNearestNode(worldPos, x, z, null);
- }
- private GridNodeBase GetNearestNode (Vector3 position, int x, int z, NNConstraint constraint) {
- int index = width*z+x;
- float minDist = float.PositiveInfinity;
- GridNodeBase minNode = null;
- for (int i = 0; i < layerCount; i++) {
- var node = nodes[index + width*depth*i];
- if (node != null) {
- float dist = ((Vector3)node.position - position).sqrMagnitude;
- if (dist < minDist && (constraint == null || constraint.Suitable(node))) {
- minDist = dist;
- minNode = node;
- }
- }
- }
- return minNode;
- }
-
-
-
-
- [System.Obsolete("Use node.HasConnectionInDirection instead")]
- public static bool CheckConnection (LevelGridNode node, int dir) {
- return node.HasConnectionInDirection(dir);
- }
- protected override void SerializeExtraInfo (GraphSerializationContext ctx) {
- if (nodes == null) {
- ctx.writer.Write(-1);
- return;
- }
- ctx.writer.Write(nodes.Length);
- for (int i = 0; i < nodes.Length; i++) {
- if (nodes[i] == null) {
- ctx.writer.Write(-1);
- } else {
- ctx.writer.Write(0);
- nodes[i].SerializeNode(ctx);
- }
- }
- }
- protected override void DeserializeExtraInfo (GraphSerializationContext ctx) {
- int count = ctx.reader.ReadInt32();
- if (count == -1) {
- nodes = null;
- return;
- }
- nodes = new LevelGridNode[count];
- for (int i = 0; i < nodes.Length; i++) {
- if (ctx.reader.ReadInt32() != -1) {
- nodes[i] = new LevelGridNode(active);
- nodes[i].DeserializeNode(ctx);
- } else {
- nodes[i] = null;
- }
- }
- }
- protected override void PostDeserialization (GraphSerializationContext ctx) {
- UpdateTransform();
- lastScannedWidth = width;
- lastScannedDepth = depth;
- SetUpOffsetsAndCosts();
- LevelGridNode.SetGridGraph((int)graphIndex, this);
- if (nodes == null || nodes.Length == 0) return;
- if (width*depth*layerCount != nodes.Length) {
- Debug.LogError("Node data did not match with bounds data. Probably a change to the bounds/width/depth data was made after scanning the graph just prior to saving it. Nodes will be discarded");
- nodes = new LevelGridNode[0];
- return;
- }
- for (int i = 0; i < layerCount; i++) {
- for (int z = 0; z < depth; z++) {
- for (int x = 0; x < width; x++) {
- var node = nodes[z*width+x + width*depth*i] as LevelGridNode;
- if (node == null) {
- continue;
- }
- node.NodeInGridIndex = z*width+x;
- node.LayerCoordinateInGrid = i;
- }
- }
- }
- }
- }
-
-
-
-
- public class LevelGridNode : GridNodeBase {
- public LevelGridNode (AstarPath astar) : base(astar) {
- }
- private static LayerGridGraph[] _gridGraphs = new LayerGridGraph[0];
- public static LayerGridGraph GetGridGraph (uint graphIndex) { return _gridGraphs[(int)graphIndex]; }
- public static void SetGridGraph (int graphIndex, LayerGridGraph graph) {
-
-
- GridNode.SetGridGraph(graphIndex, graph);
- if (_gridGraphs.Length <= graphIndex) {
- var newGraphs = new LayerGridGraph[graphIndex+1];
- for (int i = 0; i < _gridGraphs.Length; i++) newGraphs[i] = _gridGraphs[i];
- _gridGraphs = newGraphs;
- }
- _gridGraphs[graphIndex] = graph;
- }
- #if ASTAR_LEVELGRIDNODE_FEW_LAYERS
- public uint gridConnections;
- #else
- public ulong gridConnections;
- #endif
- #if ASTAR_SET_LEVELGRIDNODE_HEIGHT
- public float height;
- #endif
- protected static LayerGridGraph[] gridGraphs;
- #if ASTAR_LEVELGRIDNODE_FEW_LAYERS
- public const int NoConnection = 0xF;
- private const int ConnectionMask = 0xF;
- private const int ConnectionStride = 4;
- #else
- public const int NoConnection = 0xFF;
- public const int ConnectionMask = 0xFF;
- private const int ConnectionStride = 8;
- #endif
- public const int MaxLayerCount = ConnectionMask;
-
- public void ResetAllGridConnections () {
- unchecked {
- #if ASTAR_LEVELGRIDNODE_FEW_LAYERS
- gridConnections = (uint)-1;
- #else
- gridConnections = (ulong)-1;
- #endif
- }
- AstarPath.active.hierarchicalGraph.AddDirtyNode(this);
- }
-
- public bool HasAnyGridConnections () {
- unchecked {
- #if ASTAR_LEVELGRIDNODE_FEW_LAYERS
- return gridConnections != (uint)-1;
- #else
- return gridConnections != (ulong)-1;
- #endif
- }
- }
- public override bool HasConnectionsToAllEightNeighbours {
- get {
-
- return false;
- }
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- public int LayerCoordinateInGrid { get { return nodeInGridIndex >> NodeInGridIndexLayerOffset; } set { nodeInGridIndex = (nodeInGridIndex & NodeInGridIndexMask) | (value << NodeInGridIndexLayerOffset); } }
- public void SetPosition (Int3 position) {
- this.position = position;
- }
- public override int GetGizmoHashCode () {
- return base.GetGizmoHashCode() ^ (int)(805306457UL * gridConnections);
- }
- public override GridNodeBase GetNeighbourAlongDirection (int direction) {
- int conn = GetConnectionValue(direction);
- if (conn != NoConnection) {
- LayerGridGraph graph = GetGridGraph(GraphIndex);
- return graph.nodes[NodeInGridIndex+graph.neighbourOffsets[direction] + graph.lastScannedWidth*graph.lastScannedDepth*conn];
- }
- return null;
- }
- public override void ClearConnections (bool alsoReverse) {
- if (alsoReverse) {
- LayerGridGraph graph = GetGridGraph(GraphIndex);
- int[] neighbourOffsets = graph.neighbourOffsets;
- GridNodeBase[] nodes = graph.nodes;
- for (int i = 0; i < 4; i++) {
- int conn = GetConnectionValue(i);
- if (conn != LevelGridNode.NoConnection) {
- LevelGridNode other = nodes[NodeInGridIndex+neighbourOffsets[i] + graph.lastScannedWidth*graph.lastScannedDepth*conn] as LevelGridNode;
- if (other != null) {
-
- other.SetConnectionValue((i + 2) % 4, NoConnection);
- }
- }
- }
- }
- ResetAllGridConnections();
- #if !ASTAR_GRID_NO_CUSTOM_CONNECTIONS
- base.ClearConnections(alsoReverse);
- #endif
- }
- public override void GetConnections (System.Action<GraphNode> action) {
- LayerGridGraph graph = GetGridGraph(GraphIndex);
- int[] neighbourOffsets = graph.neighbourOffsets;
- GridNodeBase[] nodes = graph.nodes;
- int index = NodeInGridIndex;
- for (int i = 0; i < 4; i++) {
- int conn = GetConnectionValue(i);
- if (conn != LevelGridNode.NoConnection) {
- GraphNode other = nodes[index+neighbourOffsets[i] + graph.lastScannedWidth*graph.lastScannedDepth*conn];
- if (other != null) action(other);
- }
- }
- #if !ASTAR_GRID_NO_CUSTOM_CONNECTIONS
- base.GetConnections(action);
- #endif
- }
-
-
-
-
-
- [System.Obsolete("Use HasConnectionInDirection instead")]
- public bool GetConnection (int i) {
- return ((gridConnections >> i*ConnectionStride) & ConnectionMask) != NoConnection;
- }
- public override bool HasConnectionInDirection (int direction) {
- return ((gridConnections >> direction*ConnectionStride) & ConnectionMask) != NoConnection;
- }
-
-
-
- public void SetConnectionValue (int dir, int value) {
- #if ASTAR_LEVELGRIDNODE_FEW_LAYERS
- gridConnections = gridConnections & ~(((uint)NoConnection << dir*ConnectionStride)) | ((uint)value << dir*ConnectionStride);
- #else
- gridConnections = gridConnections & ~(((ulong)NoConnection << dir*ConnectionStride)) | ((ulong)value << dir*ConnectionStride);
- #endif
- AstarPath.active.hierarchicalGraph.AddDirtyNode(this);
- }
-
-
-
-
-
- public int GetConnectionValue (int dir) {
- return (int)((gridConnections >> dir*ConnectionStride) & ConnectionMask);
- }
- public override void AddConnection (GraphNode node, uint cost) {
-
-
-
- if (node is LevelGridNode gn && gn.GraphIndex == GraphIndex) {
- RemoveGridConnection(gn);
- }
- base.AddConnection(node, cost);
- }
- public override void RemoveConnection (GraphNode node) {
- base.RemoveConnection(node);
-
- if (node is LevelGridNode gn && gn.GraphIndex == GraphIndex) {
- RemoveGridConnection(gn);
- }
- }
-
-
-
-
- protected void RemoveGridConnection (LevelGridNode node) {
- var nodeIndex = NodeInGridIndex;
- var gg = GetGridGraph(GraphIndex);
- for (int i = 0; i < 8; i++) {
- if (nodeIndex + gg.neighbourOffsets[i] == node.NodeInGridIndex && GetNeighbourAlongDirection(i) == node) {
- SetConnectionValue(i, NoConnection);
- break;
- }
- }
- }
- public override bool GetPortal (GraphNode other, List<Vector3> left, List<Vector3> right, bool backwards) {
- if (backwards) return true;
- LayerGridGraph graph = GetGridGraph(GraphIndex);
- int[] neighbourOffsets = graph.neighbourOffsets;
- GridNodeBase[] nodes = graph.nodes;
- int index = NodeInGridIndex;
- for (int i = 0; i < 4; i++) {
- int conn = GetConnectionValue(i);
- if (conn != LevelGridNode.NoConnection) {
- if (other == nodes[index+neighbourOffsets[i] + graph.lastScannedWidth*graph.lastScannedDepth*conn]) {
- Vector3 middle = ((Vector3)(position + other.position))*0.5f;
- Vector3 cross = Vector3.Cross(graph.collision.up, (Vector3)(other.position-position));
- cross.Normalize();
- cross *= graph.nodeSize*0.5f;
- left.Add(middle - cross);
- right.Add(middle + cross);
- return true;
- }
- }
- }
- return false;
- }
- public override void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) {
- handler.heap.Add(pathNode);
- pathNode.UpdateG(path);
- LayerGridGraph graph = GetGridGraph(GraphIndex);
- int[] neighbourOffsets = graph.neighbourOffsets;
- GridNodeBase[] nodes = graph.nodes;
- int index = NodeInGridIndex;
- for (int i = 0; i < 4; i++) {
- int conn = GetConnectionValue(i);
- if (conn != LevelGridNode.NoConnection) {
- var other = nodes[index+neighbourOffsets[i] + graph.lastScannedWidth*graph.lastScannedDepth*conn];
- PathNode otherPN = handler.GetPathNode(other);
- if (otherPN != null && otherPN.parent == pathNode && otherPN.pathID == handler.PathID) {
- other.UpdateRecursiveG(path, otherPN, handler);
- }
- }
- }
- #if !ASTAR_GRID_NO_CUSTOM_CONNECTIONS
- base.UpdateRecursiveG(path, pathNode, handler);
- #endif
- }
- public override void Open (Path path, PathNode pathNode, PathHandler handler) {
- LayerGridGraph graph = GetGridGraph(GraphIndex);
- int[] neighbourOffsets = graph.neighbourOffsets;
- uint[] neighbourCosts = graph.neighbourCosts;
- GridNodeBase[] nodes = graph.nodes;
- int index = NodeInGridIndex;
- for (int i = 0; i < 4; i++) {
- int conn = GetConnectionValue(i);
- if (conn != LevelGridNode.NoConnection) {
- GraphNode other = nodes[index+neighbourOffsets[i] + graph.lastScannedWidth*graph.lastScannedDepth*conn];
- if (!path.CanTraverse(other)) {
- continue;
- }
- PathNode otherPN = handler.GetPathNode(other);
- if (otherPN.pathID != handler.PathID) {
- otherPN.parent = pathNode;
- otherPN.pathID = handler.PathID;
- otherPN.cost = neighbourCosts[i];
- otherPN.H = path.CalculateHScore(other);
- otherPN.UpdateG(path);
- handler.heap.Add(otherPN);
- } else {
-
- uint tmpCost = neighbourCosts[i];
- #if ASTAR_NO_TRAVERSAL_COST
- if (pathNode.G + tmpCost < otherPN.G)
- #else
- if (pathNode.G + tmpCost + path.GetTraversalCost(other) < otherPN.G)
- #endif
- {
- otherPN.cost = tmpCost;
- otherPN.parent = pathNode;
- other.UpdateRecursiveG(path, otherPN, handler);
- }
- }
- }
- }
- #if !ASTAR_GRID_NO_CUSTOM_CONNECTIONS
- base.Open(path, pathNode, handler);
- #endif
- }
- public override Vector3 ClosestPointOnNode (Vector3 p) {
- var gg = GetGridGraph(GraphIndex);
-
- p = gg.transform.InverseTransform(p);
-
- int x = this.XCoordinateInGrid;
- int z = this.ZCoordinateInGrid;
-
- float y = gg.transform.InverseTransform((Vector3)position).y;
- var closestInGraphSpace = new Vector3(Mathf.Clamp(p.x, x, x+1f), y, Mathf.Clamp(p.z, z, z+1f));
-
- return gg.transform.Transform(closestInGraphSpace);
- }
- public override void SerializeNode (GraphSerializationContext ctx) {
- base.SerializeNode(ctx);
- ctx.SerializeInt3(position);
- ctx.writer.Write(gridFlags);
-
- ctx.writer.Write((ulong)gridConnections);
- }
- public override void DeserializeNode (GraphSerializationContext ctx) {
- base.DeserializeNode(ctx);
- position = ctx.DeserializeInt3();
- gridFlags = ctx.reader.ReadUInt16();
- if (ctx.meta.version < AstarSerializer.V3_9_0) {
- #if ASTAR_LEVELGRIDNODE_FEW_LAYERS
-
- gridConnections = ctx.reader.ReadUInt16() | 0xFFFF0000U;
- #else
-
- gridConnections = ctx.reader.ReadUInt32() | 0xFFFFFFFF00000000UL;
- #endif
- } else {
- #if ASTAR_LEVELGRIDNODE_FEW_LAYERS
- gridConnections = (uint)ctx.reader.ReadUInt64();
- #else
- gridConnections = ctx.reader.ReadUInt64();
- #endif
- }
- }
- }
-
-
-
-
-
- public class LayerGridGraphUpdate : GraphUpdateObject {
-
- public bool recalculateNodes;
-
- public bool preserveExistingNodes = true;
- }
- }
- #endif
|