Esempio n. 1
0
        private static List <NodePointer> GetNeighbours(IReadOnlyArray2D <DefinitionNode> nodeArray, int gridX, int gridY, GenerateNodeGridConnections generateNodeGridConnections)
        {
            var neighbours = new List <NodePointer>();

            for (var y = -1; y <= 1; y++)
            {
                for (var x = -1; x <= 1; x++)
                {
                    if (x == 0 && y == 0)
                    {
                        continue;                                       //Skip the center since this is the node we are adding neighbours to.
                    }
                    var checkX = gridX + x;
                    var checkY = gridY + y;

                    if (checkX >= 0 && checkX < nodeArray.Width && checkY >= 0 && checkY < nodeArray.Height)
                    {
                        if (generateNodeGridConnections == GenerateNodeGridConnections.NoDiagonal)
                        {
                            if (x == 1 && y == 1 || x == -1 && y == 1 || x == -1 && y == -1 || x == 1 && y == -1)
                            {
                                continue;
                            }
                        }
                        var p = new NodePointer(nodeArray.Width * checkY + checkX);
                        neighbours.Add(p);
                    }
                }
            }
            return(neighbours);
        }
Esempio n. 2
0
        public NodePath FindPath(IPathfindNodeNetwork <AstarNode> nodeNetwork, IPathRequest pathRequest, out bool succes)
        {
            var pathfindingNetwork = nodeNetwork.GetCollisionLayerNetwork(pathRequest.CollisionCategory);
            var startNode          = NodePointer.Dereference(pathRequest.PathStart.Index, pathfindingNetwork);
            var endNode            = NodePointer.Dereference(pathRequest.PathEnd.Index, pathfindingNetwork);
            var path = FindPath(pathfindingNetwork, startNode, endNode, pathRequest.AgentSize, pathRequest.CollisionCategory);

            if (path == null)
            {
                succes = false;
                return(new NodePath(new[] { startNode.DefinitionNode }, nodeNetwork.DefinitionNodeNetwork.Transformer));
            }
            succes = true;
            switch (nodeNetwork.DefinitionNodeNetwork)
            {
            case IDefinitionNodeGrid definitionNodeGrid:
                var offset = GridClearanceHelper.GridNodeOffset(pathRequest.AgentSize, definitionNodeGrid.Transformer.Scale);
                return(new NodePath(path.ToArray(), definitionNodeGrid.Transformer));

            case IDefinitionNodeNetwork definitionNodeNetwork:
                return(new NodePath(path.ToArray(), definitionNodeNetwork.Transformer));

            default:
                throw new NotSupportedException($"{nodeNetwork.DefinitionNodeNetwork.GetType()} is not supported");
            }
        }
Esempio n. 3
0
        private void Draw(IDrawDevice device, IReadOnlyList <ICollisionLayerNode> network, IDefinitionNodeNetwork definitionNodeNetwork)
        {
            var canvas = new Canvas(device, new CanvasBuffer());

            canvas.State.ZOffset = -8;
            for (var i = 0; i < network.Count; i++)
            {
                var node = network[i];
                canvas.State.ColorTint = ColorRgba.LightGrey;
                var nodeWorldPosition = definitionNodeNetwork.Transformer.ToWorld(node.DefinitionNode.Position);
                canvas.FillCircle(nodeWorldPosition.X, nodeWorldPosition.Y, NodeSize);
                canvas.State.ColorTint = ColorRgba.VeryLightGrey;
                if (node.DefinitionNode.Connections != null)
                {
                    canvas.State.ColorTint = new ColorRgba(199, 21, 133);
                    foreach (var connection in node.DefinitionNode.Connections)
                    {
                        var toNode = NodePointer.Dereference(connection.To, definitionNodeNetwork);
                        var vector = (definitionNodeNetwork.Transformer.ToWorld(toNode.Position) - nodeWorldPosition) * 0.5f;                         //Times 0.5f so we can see the connections in both directions.
                        canvas.DrawDashLine(nodeWorldPosition.X, nodeWorldPosition.Y, nodeWorldPosition.X + vector.X, nodeWorldPosition.Y + vector.Y);
                    }
                    if (!float.IsNaN(node.Clearance))
                    {
                        canvas.State.ColorTint = ColorRgba.Black;
                        canvas.DrawText(node.Clearance.ToString(), nodeWorldPosition.X, nodeWorldPosition.Y, -1f, Alignment.Center);
                    }
                }
            }
        }
		/// <summary>
		/// Constructs a <see cref="ParentOfSpecification"/> specification matching the given <paramref name="childPointer"/> and <paramref name="depth"/>.
		/// </summary>
		/// <param name="childPointer">The pointer of the parent.</param>
		/// <param name="depth">The depth from which to select.</param>
		/// <exception cref="ArgumentNullException">Thrown if <paramref name="childPointer"/> is null.</exception>
		public static ParentOfSpecification Child(NodePointer childPointer, int? depth = 1)
		{
			// validate arguments
			if (childPointer == null)
				throw new ArgumentNullException("childPointer");

			return new ParentOfSpecification(childPointer, depth);
		}
		/// <summary>
		/// Constructs a <see cref="ChildOfSpecification"/> specification matching the given <paramref name="parentPointer"/> and <paramref name="depth"/>.
		/// </summary>
		/// <param name="parentPointer">The pointer of the parent.</param>
		/// <param name="depth">The depth from which to select.</param>
		/// <exception cref="ArgumentNullException">Thrown if <paramref name="parentPointer"/> is null.</exception>
		public static ChildOfSpecification Parent(NodePointer parentPointer, int? depth = 1)
		{
			// validate arguments
			if (parentPointer == null)
				throw new ArgumentNullException("parentPointer");

			return new ChildOfSpecification(parentPointer, depth);
		}
		/// <summary>
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="pointer">The <see cref="NodePointer"/>.</param>
		/// <param name="depth">The depth from which to get the path.</param>
		/// <param name="separator">The separator to use.</param>
		/// <returns>Returns the path.</returns>
		public string Evaluate(IMansionContext context, NodePointer pointer, int depth, string separator)
		{
			// validate arguments
			if (context == null)
				throw new ArgumentNullException("context");
			if (pointer == null)
				throw new ArgumentNullException("pointer");
			return string.Join(separator, pointer.Path.Skip(depth).TakeWhile((x, y) => y != (pointer.Depth - depth - 1)));
		}
		/// <summary>
		/// Constructs this specification.
		/// </summary>
		/// <param name="childPointer">The pointer of the parent.</param>
		/// <param name="depth">The depth from which to select.</param>
		/// <exception cref="ArgumentNullException">Thrown if <paramref name="childPointer"/> is null.</exception>
		private ParentOfSpecification(NodePointer childPointer, int? depth = 1)
		{
			// validate argument
			if (childPointer == null)
				throw new ArgumentNullException("childPointer");

			// set values
			ChildPointer = childPointer;
			Depth = depth;
		}
		/// <summary>
		/// Constructs this specification.
		/// </summary>
		/// <param name="parentPointer">The pointer of the parent.</param>
		/// <param name="depth">The depth from which to select.</param>
		/// <exception cref="ArgumentNullException">Thrown if <paramref name="parentPointer"/> is null.</exception>
		private ChildOfSpecification(NodePointer parentPointer, int? depth = 1)
		{
			// validate argument
			if (parentPointer == null)
				throw new ArgumentNullException("parentPointer");

			// set values
			ParentPointer = parentPointer;
			Depth = depth;
		}
		/// <summary>
		/// Prepares an insert query.
		/// </summary>
		/// <param name="context"></param>
		/// <param name="connection">The connection.</param>
		/// <param name="transaction">The transaction.</param>
		/// <param name="pointer"></param>
		/// <param name="newParentPointer"></param>
		/// <returns></returns>
		public void Prepare(IMansionContext context, SqlConnection connection, SqlTransaction transaction, NodePointer pointer, NodePointer newParentPointer)
		{
			// validate arguments
			if (connection == null)
				throw new ArgumentNullException("connection");
			if (transaction == null)
				throw new ArgumentNullException("transaction");
			if (pointer == null)
				throw new ArgumentNullException("pointer");
			if (newParentPointer == null)
				throw new ArgumentNullException("newParentPointer");

			// retrieve the schema
			var type = typeService.Load(context, pointer.Type);
			var schema = Resolver.Resolve(context, type);

			// create the commands
			command = connection.CreateCommand();
			command.CommandType = CommandType.Text;
			command.Transaction = transaction;
			var query = new StringBuilder();

			// calculate the new parent pointer
			var newPointer = NodePointer.ChangeParent(newParentPointer, pointer);

			// update the path
			query.AppendFormat(@"UPDATE [{0}] SET
							[parentPointer] = @newPointer + RIGHT( [parentPointer], LEN( [parentPointer] ) - @oldPointerLength ),
							[parentPath] = @newPath + RIGHT( [parentPath], LEN( [parentPath] ) - @oldPathLength ),
							[parentStructure] = @newStructure + RIGHT( [parentStructure], LEN( [parentStructure] ) - @oldStructureLength ),
							[depth] = (LEN(@newPointer + RIGHT( [parentPointer], LEN( [parentPointer] ) - @oldPointerLength )) - LEN(REPLACE(@newPointer + RIGHT( [parentPointer], LEN( [parentPointer] ) - @oldPointerLength ), '-', ''))) + 1
							WHERE ( [parentId] = @id OR [parentPointer] LIKE @oldPointer ); ", schema.RootTable.Name);
			query.AppendFormat(@"UPDATE [{0}] SET
							[parentId] = @newParentId,
							[parentPointer] = @newParentPointer,
							[parentPath] = @newParentPath,
							[parentStructure] = @newParentStructure,
							[depth] = (LEN(@newParentPointer) - LEN(REPLACE(@newParentPointer, '-', ''))) + 1
							WHERE [id] = @id ", schema.RootTable.Name);
			command.AddParameter(pointer.PointerString.Length + 1, "oldPointerLength");
			command.AddParameter(newPointer.PointerString + NodePointer.PointerSeparator, "newPointer");
			command.AddParameter(pointer.PathString.Length + 1, "oldPathLength");
			command.AddParameter(newPointer.PathString + NodePointer.PathSeparator, "newPath");
			command.AddParameter(pointer.StructureString.Length + 1, "oldStructureLength");
			command.AddParameter(newPointer.StructureString + NodePointer.StructureSeparator, "newStructure");
			command.AddParameter(pointer.PointerString + NodePointer.PointerSeparator, "oldPointer");
			command.AddParameter(newPointer.Id, "id");
			command.AddParameter(newParentPointer.Id, "newParentId");
			command.AddParameter(newParentPointer.PointerString + NodePointer.PointerSeparator, "newParentPointer");
			command.AddParameter(newParentPointer.PathString + NodePointer.PathSeparator, "newParentPath");
			command.AddParameter(newParentPointer.StructureString + NodePointer.StructureSeparator, "newParentStructure");

			// execute
			command.CommandText = query.ToString();
		}
		/// <summary>
		/// </summary>
		/// <param name="context"></param>
		/// <param name="candidateParent"></param>
		/// <param name="childPointer"></param>
		/// <returns></returns>
		public bool Evaluate(IMansionContext context, NodePointer candidateParent, NodePointer childPointer)
		{
			// validate arguments
			if (context == null)
				throw new ArgumentNullException("context");
			if (candidateParent == null)
				throw new ArgumentNullException("candidateParent");
			if (childPointer == null)
				throw new ArgumentNullException("childPointer");
			return candidateParent.Id.Equals(childPointer.Parent.Id);
		}
		/// <summary>
		/// Prepares an insert query.
		/// </summary>
		/// <param name="context"></param>
		/// <param name="connection">The connection.</param>
		/// <param name="transaction">The transaction.</param>
		/// <param name="parent"></param>
		/// <param name="properties"></param>
		/// <returns></returns>
		public void Prepare(IMansionContext context, SqlConnection connection, SqlTransaction transaction, NodePointer parent, IPropertyBag properties)
		{
			// validate arguments
			if (connection == null)
				throw new ArgumentNullException("connection");
			if (transaction == null)
				throw new ArgumentNullException("transaction");
			if (parent == null)
				throw new ArgumentNullException("parent");
			if (properties == null)
				throw new ArgumentNullException("properties");

			// get the values
			var name = properties.Get<string>(context, "name", null);
			if (string.IsNullOrWhiteSpace(name))
				throw new InvalidOperationException("The node must have a name");
			var typeName = properties.Get<string>(context, "type", null);
			if (string.IsNullOrWhiteSpace(typeName))
				throw new InvalidOperationException("The node must have a type");

			// retrieve the type
			var type = typeService.Load(context, typeName);

			// get the schema of the root type
			var schema = Resolver.Resolve(context, type);

			// set the full text property
			SqlServerUtilities.PopulateFullTextColumn(context, type, properties, properties);

			// create the new pointer
			name = NodePointer.MakeSafeName(name);
			var newPointer = NodePointer.Parse(string.Join(NodePointer.PointerSeparator, new[] {parent.PointerString, 0.ToString(CultureInfo.InvariantCulture)}), string.Join(NodePointer.StructureSeparator, new[] {parent.StructureString, type.Name}), string.Join(NodePointer.PathSeparator, new[] {parent.PathString, name}));
			properties.Set("_newPointer", newPointer);

			// create the commands
			command = connection.CreateCommand();
			command.CommandType = CommandType.Text;
			command.Transaction = transaction;

			// prepare the query
			var queryBuilder = new ModificationQueryBuilder(command);

			// loop through all the tables in the schema and let them prepare for insert
			foreach (var table in schema.Tables)
				table.ToInsertStatement(context, queryBuilder, properties);

			// finish the complete insert statement
			queryBuilder.AppendQuery("SELECT @ScopeIdentity");

			// set the command text
			command.CommandText = queryBuilder.ToStatement();
		}
Esempio n. 12
0
		/// <summary>
		/// This method is called just before a node is copied in the repository.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="originalParentPointer">The <see cref="NodePointer"/> of the parent <see cref="Node"/> from which <paramref name="node"/> was copied.</param>
		/// <param name="targetParentPointer">The <see cref="NodePointer"/> of the parent <see cref="Node"/> to which <paramref name="node"/> was copied.</param>
		/// <param name="node">The copied node.</param>
		public void AfterCopy(IMansionContext context, NodePointer originalParentPointer, NodePointer targetParentPointer, Node node)
		{
			// validate arguments
			if (context == null)
				throw new ArgumentNullException("context");
			if (originalParentPointer == null)
				throw new ArgumentNullException("originalParentPointer");
			if (targetParentPointer == null)
				throw new ArgumentNullException("targetParentPointer");
			if (node == null)
				throw new ArgumentNullException("node");

			// invoke template method
			DoAfterCopy(context, originalParentPointer, targetParentPointer, node);
		}
Esempio n. 13
0
		/// <summary>
		/// This method is called just before a node is copied in the repository.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="originalParentPointer">The <see cref="NodePointer"/> of the parent <see cref="Node"/> from which <paramref name="pointer"/> is being copied.</param>
		/// <param name="targetParentPointer">The <see cref="NodePointer"/> of the parent <see cref="Node"/> to which <paramref name="pointer"/> is being copied.</param>
		/// <param name="pointer">The pointer to the node being copied.</param>
		public void BeforeCopy(IMansionContext context, NodePointer originalParentPointer, NodePointer targetParentPointer, NodePointer pointer)
		{
			// validate arguments
			if (context == null)
				throw new ArgumentNullException("context");
			if (originalParentPointer == null)
				throw new ArgumentNullException("originalParentPointer");
			if (targetParentPointer == null)
				throw new ArgumentNullException("targetParentPointer");
			if (pointer == null)
				throw new ArgumentNullException("pointer");

			// invoke template method
			DoBeforeCopy(context, originalParentPointer, targetParentPointer, pointer);
		}
Esempio n. 14
0
        private static List <DefinitionNode> RetracePath(AstarNode[] pathfindingNetwork, AstarNode startGridNode, AstarNode endGridNode)
        {
            var path        = new List <DefinitionNode>();
            var currentNode = endGridNode;

            while (true)
            {
                path.Add(currentNode.DefinitionNode);
                if (currentNode == startGridNode)
                {
                    break;
                }
                currentNode = NodePointer.Dereference(currentNode.Parent, pathfindingNetwork);
            }
            path.Reverse();
            return(path);
        }
Esempio n. 15
0
        public bool FindPath(DijkstraNode[] pathfindingNetwork, DijkstraNode targetNode, DijkstraNode startNode, IPathRequest pathRequest)
        {
            if (targetNode.Clearance < pathRequest.AgentSize)
            {
                return(false);
            }
            ResetNetwork(pathfindingNetwork);
            var openSet   = new MaxHeap <DijkstraNode>(pathfindingNetwork.Length);
            var closedSet = new HashSet <DijkstraNode>();

            openSet.Add(targetNode);
            targetNode.GCost = 0f;
            while (openSet.Count > 0)
            {
                var currentNode = openSet.RemoveFirst();
                closedSet.Add(currentNode);

                foreach (var connection in currentNode.DefinitionNode.Connections)
                {
                    var toNode = NodePointer.Dereference(connection.To, pathfindingNetwork);
                    if ((connection.CollisionCategory & pathRequest.CollisionCategory) != 0 || closedSet.Contains(toNode))
                    {
                        continue;
                    }

                    if (toNode.Clearance < pathRequest.AgentSize)
                    {
                        toNode.GCost = float.NaN;
                    }
                    else
                    {
                        var newMovementCostToNeighbour = currentNode.GCost + GetDistance(currentNode.DefinitionNode, toNode.DefinitionNode) * currentNode.DefinitionNode.MovementCostModifier;
                        if (newMovementCostToNeighbour < toNode.GCost || !openSet.Contains(toNode))
                        {
                            toNode.GCost = newMovementCostToNeighbour;
                            if (!openSet.Contains(toNode))
                            {
                                openSet.Add(toNode);
                            }
                        }
                    }
                }
            }
            return(true);
        }
Esempio n. 16
0
        public PotentialField FindPath(DijkstraNodeGrid dijkstraNodeNetwork, IPathRequest pathRequest, out bool succes)
        {
            try
            {
                if (pathRequest.AgentSize % 2 == 0)
                {
                    throw new InvalidAgentSizeException("Potential fields only support uneven agent sizes such as 1,3,5 etc.");
                }

                if (_potentialFieldCache == null || !_potentialFieldCache.TryGetValue(pathRequest, out var potentialField))
                {
                    var sw = Stopwatch.StartNew();
                    var pathfindingNetwork = dijkstraNodeNetwork.GetCollisionLayerNetwork(pathRequest.CollisionCategory);
                    var startNode          = NodePointer.Dereference(pathRequest.PathStart.Index, pathfindingNetwork);
                    var targetNode         = NodePointer.Dereference(pathRequest.PathEnd.Index, pathfindingNetwork);
                    if (_dijkstraAlgorithm.FindPath(pathfindingNetwork, targetNode, startNode, pathRequest))
                    {
                        potentialField = FindPath(dijkstraNodeNetwork, pathfindingNetwork, targetNode, pathRequest);
                    }
                    else
                    {
                        potentialField = new PotentialField(dijkstraNodeNetwork.DefinitionNodeGrid.Transformer, (Point2)targetNode.DefinitionNode.Position);
                    }
                    _potentialFieldCache?.Add(pathRequest, potentialField);
                    Debug.WriteLine($"Potentialfield created in {sw.ElapsedMilliseconds} ms.");
                }
                var nodeWorldPosition = potentialField.GridTransformer.ToWorld(pathRequest.PathStart.Position);
                var offset            = GridClearanceHelper.GridNodeOffset(pathRequest.AgentSize, dijkstraNodeNetwork.DefinitionNodeGrid.Transformer.Scale);
                succes = potentialField.GetHeading(nodeWorldPosition + offset).Length > 0;
                return(potentialField);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                Debugger.Break();
                succes = false;
                return(null);
            }
        }
		/// <summary>
		/// Prepares an insert query.
		/// </summary>
		/// <param name="context"></param>
		/// <param name="connection">The connection.</param>
		/// <param name="transaction">The transaction.</param>
		/// <param name="pointer"></param>
		/// <returns></returns>
		public void Prepare(IMansionContext context, SqlConnection connection, SqlTransaction transaction, NodePointer pointer)
		{
			// validate arguments
			if (connection == null)
				throw new ArgumentNullException("connection");
			if (transaction == null)
				throw new ArgumentNullException("transaction");
			if (pointer == null)
				throw new ArgumentNullException("pointer");

			// retrieve the schema
			var type = typeService.Load(context, pointer.Type);
			var schema = Resolver.Resolve(context, type);

			// create the commands
			command = connection.CreateCommand();
			command.CommandType = CommandType.Text;
			command.Transaction = transaction;

			command.CommandText = string.Format(@"DELETE FROM [{0}] WHERE [{0}].[parentPointer] LIKE @pointer; DELETE FROM [{0}] WHERE [{0}].[id] = @id", schema.RootTable.Name);
			command.Parameters.AddWithValue("pointer", pointer.PointerString + NodePointer.PointerSeparator + "%");
			command.Parameters.AddWithValue("id", pointer.Id);
		}
Esempio n. 18
0
		/// <summary>
		/// This method is called just before a node is copied in the repository.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="originalParentPointer">The <see cref="NodePointer"/> of the parent <see cref="Node"/> from which <paramref name="pointer"/> is being copied.</param>
		/// <param name="targetParentPointer">The <see cref="NodePointer"/> of the parent <see cref="Node"/> to which <paramref name="pointer"/> is being copied.</param>
		/// <param name="pointer">The pointer to the node being copied.</param>
		protected virtual void DoBeforeCopy(IMansionContext context, NodePointer originalParentPointer, NodePointer targetParentPointer, NodePointer pointer)
		{
		}
Esempio n. 19
0
		/// <summary>
		/// This method is called just before a node is copied in the repository.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="originalParentPointer">The <see cref="NodePointer"/> of the parent <see cref="Node"/> from which <paramref name="node"/> was copied.</param>
		/// <param name="targetParentPointer">The <see cref="NodePointer"/> of the parent <see cref="Node"/> to which <paramref name="node"/> was copied.</param>
		/// <param name="node">The copied node.</param>
		protected virtual void DoAfterCopy(IMansionContext context, NodePointer originalParentPointer, NodePointer targetParentPointer, Node node)
		{
		}
        /// <summary>
        /// Creates the tree structure from the <paramref name="navigationItemNodeset"/>.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="navigationNode"></param>
        /// <param name="navigationItemNodeset"></param>
        /// <param name="currentPagePointer"></param>
        /// <returns></returns>
        private Leaf BuildTreeStructure(IMansionContext context, Node navigationNode, Nodeset navigationItemNodeset, NodePointer currentPagePointer)
        {
            // first sort the set by depth ASC, than order ASC
            var sortedSet = navigationItemNodeset.Nodes.OrderBy(x => x, new ComparisonComparer<Node>((x, y) =>
                                                                                                     {
                                                                                                     	// first compare on depth
                                                                                                     	var depthComparison = x.Pointer.Depth.CompareTo(y.Pointer.Depth);
                                                                                                     	if (depthComparison != 0)
                                                                                                     		return depthComparison;

                                                                                                     	// next compare on order
                                                                                                     	return x.Order.CompareTo(y.Order);
                                                                                                     }));

            // create the parent leaf
            var rootLeaf = Leaf.Create(context, navigationNode);
            var leafSet = new List<Leaf> {rootLeaf};

            // loop over the sorted set
            foreach (var leafNode in sortedSet)
            {
                // find the parent leaf
                var parentLeaf = leafSet.Single(candidate => candidate.Node.Pointer == leafNode.Pointer.Parent);

                // create the leaf
                var leaf = Leaf.Create(context, leafNode, parentLeaf);
                if (leaf == null)
                    continue;

                // add the leaf to the parent leaf
                parentLeaf.Add(leaf);

                // add the leaf to the set
                leafSet.Add(leaf);
            }

            // find the deepest node who has an internal link and is parent of or equal to the current page pointer
            var activeLeaf = ((IEnumerable<Leaf>) leafSet).Reverse().Where(x => x.HasTarget && (currentPagePointer.IsChildOf(x.TargetNode.Pointer) || currentPagePointer == x.TargetNode.Pointer)).FirstOrDefault();
            if (activeLeaf != null)
                activeLeaf.SetActive();

            // return the parent leaf
            return rootLeaf;
        }
Esempio n. 21
0
 /// <summary>
 /// Creates a new <see cref="NodeConnection"/>.
 /// </summary>
 /// <param name="to">Where this connection is going to</param>
 /// <param name="collisionCategory">The <see cref="PathfindaxCollisionCategory"/> of this <see cref="NodeConnection"/></param>
 public NodeConnection(NodePointer to, PathfindaxCollisionCategory collisionCategory = PathfindaxCollisionCategory.None)
 {
     To = to;
     CollisionCategory = collisionCategory;
 }
Esempio n. 22
0
		/// <summary>
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="pointer">The <see cref="NodePointer"/>.</param>
		/// <param name="depth">The depth from which to get the path.</param>
		/// <returns>Returns the path.</returns>
		public string Evaluate(IMansionContext context, NodePointer pointer, int depth)
		{
			return Evaluate(context, pointer, depth, " / ");
		}
		/// <summary>
		/// Copies an existing node in this repository to a new node.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="pointer">The pointer to the node which will be copied.</param>
		/// <param name="targetParentPointer">The pointer to the parent to which the copied node is added.</param>
		/// <returns>Returns the copied node.</returns>
		protected override Node DoCopyNode(IMansionContext context, NodePointer pointer, NodePointer targetParentPointer)
		{
			// get the type of this node
			var listeners = GetListeners(context, pointer.Type);

			// fire the on before copy
			var originalParentPointer = pointer.Parent;
			foreach (var listener in listeners.OfType<NodeListener>())
				listener.BeforeCopy(context, originalParentPointer, targetParentPointer, pointer);

			// execute the derived class
			var node = DecoratedRepository.CopyNode(context, pointer, targetParentPointer);

			// fire the on after copy
			foreach (var listener in listeners.OfType<NodeListener>())
				listener.AfterCopy(context, originalParentPointer, targetParentPointer, node);

			return node;
		}
Esempio n. 24
0
		/// <summary>
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="pointer">The <see cref="NodePointer"/>.</param>
		/// <returns>Returns the path.</returns>
		public string Evaluate(IMansionContext context, NodePointer pointer)
		{
			return Evaluate(context, pointer, 0);
		}
Esempio n. 25
0
		/// <summary>
		/// Copies an existing node in this repository to a new node.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="pointer">The pointer to the node which will be copied.</param>
		/// <param name="newParentPointer">The pointer to the parent to which the copied node is added.</param>
		/// <returns>Returns the copied node.</returns>
		protected abstract Node DoCopyNode(IMansionContext context, NodePointer pointer, NodePointer newParentPointer);
		/// <summary>
		/// Copies an existing node in this repository to a new node.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="pointer">The pointer to the node which will be copied.</param>
		/// <param name="newParentPointer">The pointer to the parent to which the copied node is added.</param>
		/// <returns>Returns the copied node.</returns>
		protected override Node DoCopyNode(IMansionContext context, NodePointer pointer, NodePointer newParentPointer)
		{
			// copy the node
			var record = storageEngine.CopyNode(context, pointer, newParentPointer);

			// index the record
			foreach (var indexer in indexEngines)
				indexer.Index(context, record);

			// return the record
			return record;
		}
		/// <summary>
		/// Copies an existing node in this repository to a new node.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="pointer">The pointer to the node which will be copied.</param>
		/// <param name="targetParentPointer">The pointer to the parent to which the copied node is added.</param>
		/// <returns>Returns the copied node.</returns>
		protected override Node DoCopyNode(IMansionContext context, NodePointer pointer, NodePointer targetParentPointer)
		{
			// excute derived class
			var node = DecoratedRepository.CopyNode(context, pointer, targetParentPointer);

			// clear the cache for the given node
			node.ClearFromCache(cachingService);

			return node;
		}
		/// <summary>
		/// Copies an existing node in this repository to a new node.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="pointer">The pointer to the node which will be copied.</param>
		/// <param name="targetParentPointer">The pointer to the parent to which the copied node is added.</param>
		/// <returns>Returns the copied node.</returns>
		protected override Node DoCopyNode(IMansionContext context, NodePointer pointer, NodePointer targetParentPointer)
		{
			// create a query to retrieve the new node
			var selectQuery = new Query();

			// build the query
			using (var connection = CreateConnection())
			using (var transaction = connection.BeginTransaction())
			{
				// retrieve the nodes
				// TODO: retrieve the nodes within the same transaction
				var nodeToCopy = RetrieveSingleNode(context, new Query().Add(new IsPropertyEqualSpecification("id", pointer.Id)));
				if (nodeToCopy == null)
					throw new ArgumentNullException(string.Format("Could not find node with pointer '{0}'", pointer));
				var targetParentNode = RetrieveSingleNode(context, new Query().Add(new IsPropertyEqualSpecification("id", targetParentPointer.Id)));
				if (targetParentNode == null)
					throw new ArgumentNullException(string.Format("Could not find node with pointer '{0}'", targetParentPointer));

				// create the copy query
				using (var command = context.Nucleus.CreateInstance<CopyNodeCommand>())
				{
					// init the command
					command.Prepare(context, connection, transaction, nodeToCopy, targetParentNode);

					// execute the command
					try
					{
						// execute the query

						var copiedNodeId = command.Execute();

						selectQuery.Add(new IsPropertyEqualSpecification("id", copiedNodeId));

						// woohoo it worked!
						transaction.Commit();
					}
					catch (Exception)
					{
						// something terrible happened, revert everything
						transaction.Rollback();
						throw;
					}
				}
			}

			// return the created node
			return RetrieveSingleNode(context, selectQuery);
		}
 void Start()
 {
     // instances
     nodePointer  = GetComponent <NodePointer>();
     lineRenderer = GetComponent <LineRenderer>();
 }
Esempio n. 30
0
		/// <summary>
		/// Copies an existing node in this repository to a new node.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="pointer">The pointer to the node which will be copied.</param>
		/// <param name="targetParentPointer">The pointer to the parent to which the copied node is added.</param>
		/// <returns>Returns the copied node.</returns>
		public Node CopyNode(IMansionContext context, NodePointer pointer, NodePointer targetParentPointer)
		{
			// validate arguments
			if (context == null)
				throw new ArgumentNullException("context");
			if (pointer == null)
				throw new ArgumentNullException("pointer");
			if (targetParentPointer == null)
				throw new ArgumentNullException("targetParentPointer");
			CheckDisposed();

			// invoke template method
			return DoCopyNode(context, pointer, targetParentPointer);
		}
Esempio n. 31
0
        private static List <DefinitionNode> FindPath(AstarNode[] pathfindingNetwork, AstarNode startNode, AstarNode targetNode, float neededClearance, PathfindaxCollisionCategory collisionCategory)
        {
            try
            {
                var sw = new Stopwatch();
                sw.Start();

                var pathSucces = false;
                if (startNode == targetNode)
                {
                    return(new List <DefinitionNode> {
                        targetNode.DefinitionNode
                    });
                }
                if (startNode.Clearance >= neededClearance && targetNode.Clearance >= neededClearance)
                {
                    var openSet          = new MaxHeap <AstarNode>(pathfindingNetwork.Length);
                    var closedSet        = new HashSet <AstarNode>();
                    var itterations      = 0;
                    var neighbourUpdates = 0;
                    openSet.Add(startNode);
                    while (openSet.Count > 0)
                    {
                        itterations++;
                        var currentNode = openSet.RemoveFirst();
                        closedSet.Add(currentNode);

                        if (currentNode == targetNode)
                        {
                            sw.Stop();
                            Debug.WriteLine($"NodePath found in {sw.ElapsedMilliseconds} ms. Itterations: {itterations} Neighbourupdates: {neighbourUpdates}");
                            pathSucces = true;
                            break;
                        }

                        foreach (var connection in currentNode.DefinitionNode.Connections)
                        {
                            var toNode = NodePointer.Dereference(connection.To, pathfindingNetwork);
                            if ((connection.CollisionCategory & collisionCategory) != 0 || closedSet.Contains(toNode))
                            {
                                continue;
                            }

                            if (toNode.Clearance >= neededClearance)
                            {
                                var newMovementCostToNeighbour = currentNode.GCost + GetDistance(currentNode.DefinitionNode, toNode.DefinitionNode) * currentNode.DefinitionNode.MovementCostModifier;
                                if (newMovementCostToNeighbour < toNode.GCost || !openSet.Contains(toNode))
                                {
                                    toNode.GCost  = newMovementCostToNeighbour;
                                    toNode.HCost  = GetDistance(toNode.DefinitionNode, targetNode.DefinitionNode);
                                    toNode.Parent = currentNode.DefinitionNode.Index;
                                    neighbourUpdates++;
                                    if (!openSet.Contains(toNode))
                                    {
                                        openSet.Add(toNode);
                                    }
                                }
                            }
                        }
                    }
                }
                if (pathSucces)
                {
                    return(RetracePath(pathfindingNetwork, startNode, targetNode));
                }
                Debug.WriteLine("Did not find a path :(");
                return(null);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                Debugger.Break();
                return(null);
            }
        }
		/// <summary>
		/// Moves an existing node in this repository to a new parent node.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="pointer">The pointer to the node which will be moved.</param>
		/// <param name="newParentPointer">The pointer to the parent to which the node is moved.</param>
		/// <returns>Returns the moved node.</returns>m
		protected override Node DoMoveNode(IMansionContext context, NodePointer pointer, NodePointer newParentPointer)
		{
			return repository.MoveNode(context, pointer, newParentPointer);
		}
		/// <summary>
		/// Moves an existing node in this repository to a new parent node.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="pointer">The pointer to the node which will be moved.</param>
		/// <param name="newParentPointer">The pointer to the parent to which the node is moved.</param>
		/// <returns>Returns the moved node.</returns>
		/// <exception cref="ArgumentNullException">Thrown if <paramref name="context"/>, <paramref name="pointer"/> or <paramref name="newParentPointer"/> is null.</exception>
		public Node MoveNode(IMansionContext context, NodePointer pointer, NodePointer newParentPointer)
		{
			// validate arguments
			if (context == null)
				throw new ArgumentNullException("context");
			if (pointer == null)
				throw new ArgumentNullException("pointer");
			if (newParentPointer == null)
				throw new ArgumentNullException("newParentPointer");

			// invoke template method
			return DoMoveNode(context, pointer, newParentPointer);
		}
		/// <summary>
		/// Copies an existing node in this repository to a new node.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="pointer">The pointer to the node which will be copied.</param>
		/// <param name="targetParentPointer">The pointer to the parent to which the copied node is added.</param>
		/// <returns>Returns the copied node.</returns>
		protected override Node DoCopyNode(IMansionContext context, NodePointer pointer, NodePointer targetParentPointer)
		{
			return repository.CopyNode(context, pointer, targetParentPointer);
		}
		/// <summary>
		/// Moves an existing node in this repository to a new parent node.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="pointer">The pointer to the node which will be moved.</param>
		/// <param name="newParentPointer">The pointer to the parent to which the node is moved.</param>
		/// <returns>Returns the moved node.</returns>m
		protected override Node DoMoveNode(IMansionContext context, NodePointer pointer, NodePointer newParentPointer)
		{
			// build the query
			using (var connection = CreateConnection())
			using (var transaction = connection.BeginTransaction())
			using (var command = context.Nucleus.CreateInstance<MoveNodeCommand>())
			{
				// init the command
				command.Prepare(context, connection, transaction, pointer, newParentPointer);

				// execute the command
				try
				{
					// execute the query
					command.Execute();

					// woohoo it worked!
					transaction.Commit();
				}
				catch (Exception)
				{
					// something terrible happened, revert everything
					transaction.Rollback();
					throw;
				}
			}

			// return the moved node
			var selectQuery = new Query().Add(new IsPropertyEqualSpecification("id", pointer.Id));
			return RetrieveSingleNode(context, selectQuery);
		}