public LogicManager(MainWindow _window) { graphToVisualize = null; citiesLocations = null; citiesConnections = null; defaultCitiesLocations = new CitiesLocations(); defaultCitiesConnections = new CitiesConnections(); algCitiesLocations = new CitiesLocations(); startCity = null; finalCity = null; algSpeed = Alg_Speed.Fast; algHeuristic = Heuristic.Distance; resources = _window.Resources; window = _window; graphManager = new GraphManager(window); algorithm = null; algThread = null; IsRunningAlg = false; }
/// <summary> /// Initializes a new instance of the AStar class. /// </summary> /// <param name="openSetCapacity">The max capacity of the open set.</param> /// <param name="findDistance">A delegate to find the g distance.</param> /// <param name="heuristic">A delegate to calculate the heuristic value.</param> public AStar(int openSetCapacity, FindDistance findDistance, Heuristic heuristic) { this.closed = new List<Node>(); this.open = new BlueRajaWrapper<Node>(openSetCapacity); this.findDistance = findDistance; this.heuristic = heuristic; }
// Main constructor that initializes everything except window public Algorithm(CitiesLocations _citiesLocations, CitiesConnections _citiesConnectios, City _startCity, City _finalCity, Alg_Speed _algSpeed, Heuristic _algHeuristic, ref GraphLayoutCity _graphLayout, ref TextBox _textBoxLog, ResourceDictionary _resourceDictionary, GraphManager _graphManager) { citiesLocations = _citiesLocations; citiesConnecitons = _citiesConnectios; StartCity = _startCity; FinalCity = _finalCity; AlgSpeed = _algSpeed; AlgHeuristic = _algHeuristic; graphLayout = _graphLayout; textBoxLog = _textBoxLog; resourceDictionary = _resourceDictionary; IsRunning = false; Window = null; CanContinue = false; graphManager = _graphManager; }
public SelfishGene(Heuristic scoringFunction, int popsize, int evaluations) { fitness = new BuyFit(scoringFunction); name = "SelfishGene " + scoringFunction.ToString() + " " + popsize + " {" + evaluations + "}"; popSize = popsize; this.evaluations = evaluations; }
public IndexGene(int popsize, int evaluations, Heuristic scoringFunction) { name = "Index " + scoringFunction.ToString(); popSize = popsize; depth = 5; this.evaluations = evaluations; fit = new IndexFit(scoringFunction); }
public ExactGene(int popsize, int depth, int generations, Heuristic scoringFunction) { name = "Exact " + scoringFunction.ToString(); this.popSize = popsize; this.depth = depth; this.generations = generations; fit = new ExactFit(scoringFunction); fit.depth = depth; }
// Update is called once per frame void Update() { if(ifGivenGoal.Equals(true)) { if (goalreached) { path.Clear (); } else { if(gameObject.GetComponent<CurrentNode>().currentNode.Equals(objectiveNode)) { goalreached = true; } if(path.Count == 0) { path = new Stack<GameObject>(); hr = new Heuristic(objectiveNode); path = pathfinderEnemy.AStar(gameObject.GetComponent<CurrentNode>().currentNode,objectiveNode, hr); try { goal = path.Pop(); } finally { movement(); } } else if(currentNode != previousNode) { try { goal = path.Pop(); } finally { currentNode = gameObject.GetComponent<CurrentNode>().currentNode; previousNode = gameObject.GetComponent<CurrentNode>().currentNode; movement(); } } else { movement(); currentNode = gameObject.GetComponent<CurrentNode>().currentNode; } } } }
// Use this for initialization void Start() { objectiveNode = gameObject.GetComponent<CurrentNode>().currentNode; currentNode = gameObject.GetComponent<CurrentNode>().currentNode; previousNode = gameObject.GetComponent<CurrentNode>().currentNode; hr = new Heuristic(objectiveNode); path = new Stack<GameObject>(); }
// Use this for initialization void Start() { objectiveNode = GameObject.FindGameObjectWithTag("EnemyGoal").GetComponent<SetEnemyGoal>().currentNode; currentNode = gameObject.GetComponent<CurrentNode>().currentNode; previousNode = gameObject.GetComponent<CurrentNode>().currentNode; hr = new Heuristic(objectiveNode); path = new Stack<GameObject>(); }
/// <summary> /// Print start message /// </summary> /// <param name="startCity"></param> /// <param name="finalCity"></param> /// <param name="heuristic"></param> public void PrintStartAlg(City startCity, City finalCity, Heuristic heuristic) { textBox.Dispatcher.Invoke( new Action(delegate() { textBox.Text += "--== Starting A-star algorithm ==--\n"; PrintBreak(); if (heuristic == Heuristic.Distance) { textBox.Text += string.Format("Used heuristic: Minimum Distance\n"); } else if (heuristic == Heuristic.Hops) { textBox.Text += string.Format("Used heuristic: Minimum Hops\n"); } textBox.Text += string.Format("Start city: {0}\n", startCity.getName()); textBox.Text += string.Format("Final city: {0}\n", finalCity.getName()); }), DispatcherPriority.Normal, null); }
public AStarSpaceCreationAlgorithm(Heuristic h) { m_heuristic = h; }
public IEnumerator GetPathInFrames(GameObject srcObj, GameObject dstObj, Heuristic h = null) { isFinished = false; path = new List <Vertex>(); if (srcObj == null || dstObj == null) { path = new List <Vertex>(); isFinished = true; yield break; } if (ReferenceEquals(h, null)) { h = EuclidDist; } Vertex src = GetNearestVertex(srcObj.transform.position); Vertex dst = GetNearestVertex(dstObj.transform.position); BinaryHeap <Edge> frontier = new BinaryHeap <Edge>(); Edge[] edges; Edge node, child; int size = vertices.Count; float[] distValue = new float[size]; int[] previous = new int[size]; node = new Edge(src, 0); frontier.Add(node); distValue[src.id] = 0; previous[src.id] = src.id; for (int i = 0; i < size; i++) { if (i == src.id) { continue; } distValue[i] = Mathf.Infinity; previous[i] = -1; } while (frontier.Count != 0) { yield return(null); node = frontier.Remove(); int nodeId = node.vertex.id; if (ReferenceEquals(node.vertex, dst)) { path = BuildPath(src.id, node.vertex.id, ref previous); break; } edges = GetEdges(node.vertex); foreach (Edge e in edges) { int eId = e.vertex.id; if (previous[eId] != -1) { continue; } float cost = distValue[nodeId] + e.cost; cost += h(node.vertex, e.vertex); if (cost < distValue[e.vertex.id]) { distValue[eId] = cost; previous[eId] = nodeId; frontier.Remove(e); child = new Edge(e.vertex, cost); frontier.Add(child); } } } isFinished = true; yield break; }
// Update is called once per frame void Update() { if(moveTo == true) { if(primary.GetComponent<NavAgent>().path.Count != 0 || isPrimary == true) { if (goalreached) { //goalreached = true; //Debug.Log("goal reached"); } else { if(path.Count == 0) { path = new Stack<GameObject>(); hr = new Heuristic(objectiveNode.GetComponent<CurrentNode>().currentNode); path = pathfinder.AStar(gameObject.GetComponent<CurrentNode>().currentNode,objectiveNode.GetComponent<CurrentNode>().currentNode, hr); if(isPrimary == true) { //ResetWorldInfluence(); Stack<GameObject> pathTemp = pathfinder.AStar(gameObject.GetComponent<CurrentNode>().currentNode,objectiveNode.GetComponent<CurrentNode>().currentNode, hr); InfluencePath(pathTemp); } try{ goal = path.Pop(); } finally { movement(); } } else if(currentNode != previousNode) { try{ goal = path.Pop(); } finally { currentNode = gameObject.GetComponent<CurrentNode>().currentNode; previousNode = gameObject.GetComponent<CurrentNode>().currentNode; movement(); } } else { movement(); currentNode = gameObject.GetComponent<CurrentNode>().currentNode; } } } } else { if (goalreached) { //goalreached = true; //Debug.Log("goal reached"); } else { GameObject player = GameObject.FindGameObjectWithTag("Player"); if(gameObject.GetComponent<CurrentNode>().currentNode.Equals(player.GetComponent<CurrentNode>().currentNode)) { goalreached = false; } if(path.Count == 0) { path = new Stack<GameObject>(); hr = new Heuristic(player.GetComponent<CurrentNode>().currentNode); path = pathfinder.AStar(gameObject.GetComponent<CurrentNode>().currentNode,player.GetComponent<CurrentNode>().currentNode, hr); if(isPrimary == true) { secondary.GetComponent<NavAgent>().path.Clear(); Stack<GameObject> pathTemp = pathfinder.AStar(gameObject.GetComponent<CurrentNode>().currentNode,player.GetComponent<CurrentNode>().currentNode, hr); InfluencePath(pathTemp); } try{ goal = path.Pop(); } finally { movement(); } } else if(currentNode != previousNode) { try{ goal = path.Pop(); } finally { currentNode = gameObject.GetComponent<CurrentNode>().currentNode; previousNode = gameObject.GetComponent<CurrentNode>().currentNode; movement(); } } else { movement(); currentNode = gameObject.GetComponent<CurrentNode>().currentNode; } } } }
// Use this for initialization void Start() { animator = gameObject.GetComponent<Animator>(); currentNode = gameObject.GetComponent<CurrentNode>().currentNode; previousNode = gameObject.GetComponent<CurrentNode>().currentNode; hr = new Heuristic(objectiveNode.GetComponent<CurrentNode>().currentNode); path = new Stack<GameObject>(); animator.SetBool("Moving", true); }
protected abstract IPathfinder CreateInstance(Heuristic heuristic);
protected void VisitChildren(N endNode, Heuristic <N> heuristic) { // Get current node's outgoing connections var connections = _graph.GetConnections(_current.node); // Loop through each connection in turn for (int i = 0; i < connections.Count; i++) { if (metrics != null) { metrics.VisitedNodes++; } Connection <N> connection = connections[i]; // Get the cost estimate for the node N node = connection.GetToNode(); //周围目标节点 LFloat nodeCost = _current.costSoFar + connection.GetCost(); //节点到目标的消耗 LFloat nodeHeuristic; NodeRecord <N> nodeRecord = GetNodeRecord(node); if (nodeRecord.category == CLOSED) // The node is closed // If we didn't find a shorter route, skip 已经是消耗最小的目标点 { if (nodeRecord.costSoFar <= nodeCost) { continue; } // We can use the node's old cost values to calculate its heuristic // without calling the possibly expensive heuristic function nodeHeuristic = nodeRecord.GetEstimatedTotalCost() - nodeRecord.costSoFar; } else if (nodeRecord.category == OPEN) // The node is open // If our route is no better, then skip { if (nodeRecord.costSoFar <= nodeCost) { continue; } // Remove it from the open list (it will be re-added with the new cost) _openList.Remove(nodeRecord); // We can use the node's old cost values to calculate its heuristic // without calling the possibly expensive heuristic function nodeHeuristic = nodeRecord.GetEstimatedTotalCost() - nodeRecord.costSoFar; } else // the node is unvisited // We'll need to calculate the heuristic value using the function, // since we don't have a node record with a previously calculated value { nodeHeuristic = heuristic.Estimate(node, endNode); } // Update node record's cost and connection nodeRecord.costSoFar = nodeCost; nodeRecord.connection = connection; // Add it to the open list with the estimated total cost AddToOpenList(nodeRecord, nodeCost + nodeHeuristic); } }
//int totalximpnts = 0; //int totalmimpnts = 0; //int[] xoverimpnts = new int[5]; //int[] mutimpnts = new int[5]; //int diverseChromosomes = 0; //int totalChromosomes = 0; //private void setData(int i) //{ // if (xoverimpnts.Length <= i) // { // Array.Resize(ref xoverimpnts, i + 1); // Array.Resize(ref mutimpnts, i + 1); // } // xoverimpnts[i] += BuyOrderChromosome.crossOverImprovements - totalximpnts; // totalximpnts = BuyOrderChromosome.crossOverImprovements; // mutimpnts[i] += BuyOrderChromosome.mutationImprovements - totalmimpnts; // totalmimpnts = BuyOrderChromosome.mutationImprovements; //} public SelfishGene(Heuristic scoringFunction) : this(scoringFunction, 200, 20) { }
public static List <Node> Search(Node start, Node goal, Heuristic heuristic) { List <Node> path = new List <Node>(); List <Node> opens = new List <Node>(); Dictionary <Node, Cost> costs = new Dictionary <Node, Cost>(); costs.Add(start, new Cost()); opens.Add(start); int limit = 65535; while (opens.Count > 0 && limit > 0) { limit--; Node lowestF = GetLowestF(opens, costs); opens.Remove(lowestF); if (lowestF != goal) { int count = lowestF.Count; for (int i = 0; i < count; i++) { Node neighbor = lowestF[i]; if (!costs.ContainsKey(neighbor)) { Cost cost = new Cost(); cost.parent = lowestF; cost.g = costs[lowestF].g + Distance(lowestF, neighbor, heuristic); cost.h = Distance(neighbor, goal, heuristic); cost.f = cost.g + cost.h; costs.Add(neighbor, cost); opens.Add(neighbor); } } } else { Node node = lowestF; Cost cost = costs[lowestF]; do { path.Insert(0, node); cost = costs[node]; node = cost.parent; }while(null != node); // End While-Loop break; } } Clean(path); return(path); }
public ExactGene(Heuristic fn) : this(500, 10, 20, fn) { }
/// <summary> /// Creates a best first search with the given heuristic. /// </summary> /// <param name="heuristic"></param> public ASearch(Heuristic heuristic) { this.heuristic = heuristic; }
protected override IPathfinder CreateInstance(Heuristic heuristic) { return new Dijkstra(1000, (node, neighbor) => 1); }
//the A*Ambush algorithm analyzes the path of every agent to the target and //increases the cost of that route. When an agent computes the path with A*, //it chooses a different route that the ones chosen by the other agents //creating the sense of an ambush private List <Vertex> AStarAmbush(Vertex src, Vertex dst, Lurker agent, List <Lurker> lurkers, Heuristic h = null) { int graphSize = vertices.Count; float[] extra = new float[graphSize]; float[] costs = new float[graphSize]; //initialize regular cost and extra cost variables for (int i = 0; i < graphSize; i++) { extra[i] = 1f; costs[i] = Mathf.Infinity; } //add the extra cost to each vertex that is contained in another agent's path foreach (Lurker l in lurkers) { foreach (Vertex v in l.path) { extra[v.id] += 1f; } } Edge[] successors; int[] previous = new int[graphSize]; for (int i = 0; i < graphSize; i++) { previous[i] = -1; } previous[src.id] = src.id; float cost = 0; Edge node = new Edge(src, 0); BinaryHeap <Edge> frontier = new BinaryHeap <Edge>(); //A* main loop frontier.Add(node); while (frontier.Count != 0) { if (frontier.Count == 0) { return(new List <Vertex>()); } //validate that the goal has already been reached, //otherwise it's not worth computing the costs node = frontier.Remove(); if (ReferenceEquals(node.vertex, dst)) { return(BuildPath(src.id, node.vertex.id, ref previous)); } int nodeId = node.vertex.id; if (node.cost > costs[nodeId]) { continue; } //traverse the neighbours and check whether they have been visited successors = GetEdges(node.vertex); foreach (Edge e in successors) { int eId = e.vertex.id; if (previous[eId] != -1) { continue; } //if they have not been visited add them to the frontier cost = e.cost; cost += costs[dst.id]; cost += h(e.vertex, dst); if (cost < costs[e.vertex.id]) { Edge child = new Edge(e.vertex, cost); costs[eId] = cost; previous[eId] = nodeId; frontier.Remove(e); frontier.Add(child); } } } return(new List <Vertex>()); }
public ApplicationViewModel() { ParseSQL = new RelaySimpleCommand(() => { try { if (Input_SQL == null) { Input_Valid_SQL = false; return; } String sql = Input_SQL.Replace("\n", " "); while (sql.Last() == ' ') { sql = sql.Substring(0, sql.Length - 1); } Input_Valid_SQL = true; if (sql == "") { Input_Valid_SQL = false; return; } List <State>[] stateSets = sqlParser.Parse(sql); if (!sqlParser.IsValid(stateSets)) { Input_Valid_SQL = false; return; } stateSets = sqlParser.FilterAndReverse(stateSets); TreeNode <String> tree = sqlParser.parse_tree(sql, stateSets); this.Input_RA = SqlToRa.TranslateQuery(tree); this.Parsed_SQL = sql; this.Parsed_RA_From_SQL = this.Input_RA; this.Input_Type = "ra"; return; } catch (HeuristicException e) { Console.WriteLine(e.ToString()); Error = e.Message.Replace(Environment.NewLine, "<br/>"); return; } }); ParseRA = new RelaySimpleCommand(() => { try { if (Input_RA == null) { Input_Valid_RA = false; return; } String ra = Input_RA.Replace("\n", " "); while (ra.Last() == ' ') { ra = ra.Substring(0, ra.Length - 1); } Input_Valid_RA = true; if (Input_RA == "") { Input_Valid_RA = false; return; } List <State>[] stateSets = raParser.Parse(Input_RA); if (!raParser.IsValid(stateSets)) { Input_Valid_RA = false; return; } if (this.Input_RA == this.Parsed_RA_From_SQL) { this.SQL = this.Parsed_SQL; } else { this.SQL = ""; } this.RA = Input_RA; stateSets = raParser.FilterAndReverse(stateSets); TreeNode <String> tree = raParser.parse_tree(Input_RA, stateSets); Squish(tree); this.ops = RAToOps.Translate(tree, Relations.ToDictionary(relation => relation.name)); ops = new TreeNode <Operation>(new Query()) { ops }; new Heuristic0(ops).Complete(); HeuristicsArray = new Heuristic[] { new Heuristic1(ops), new Heuristic2(ops), new Heuristic3(ops), new Heuristic4(ops), new Heuristic5(ops) }; UpdateCurrentHeuristic(); this.OpsJSON = ops.Child().ToJSON().Replace("\"", """).Replace("'", "\""); this.CurrentView = "output"; return; } catch (HeuristicException e) { Console.WriteLine(e.ToString()); Error = e.Message.Replace(Environment.NewLine, "<br/>"); return; } }); Step = new RelaySimpleCommand(() => { try { UpdateCurrentHeuristic(); if (CurrentHeuristic != null) { CurrentHeuristic.Step(); } this.OpsJSON = ops.Child().ToJSON().Replace("\"", """).Replace("'", "\""); UpdateCurrentHeuristic(); } catch (HeuristicException e) { Console.WriteLine(e.ToString()); Error = e.Message.Replace(Environment.NewLine, "<br/>"); return; } }); Complete = new RelaySimpleCommand(() => { try { UpdateCurrentHeuristic(); if (CurrentHeuristic != null) { CurrentHeuristic.Complete(); } this.OpsJSON = ops.Child().ToJSON().Replace("\"", """).Replace("'", "\""); UpdateCurrentHeuristic(); } catch (HeuristicException e) { Console.WriteLine(e.ToString()); Error = e.Message.Replace(Environment.NewLine, "<br/>"); return; } }); Reset = new RelaySimpleCommand(() => { try { List <State>[] stateSets = raParser.Parse(RA); stateSets = raParser.FilterAndReverse(stateSets); TreeNode <String> tree = raParser.parse_tree(RA, stateSets); Squish(tree); this.ops = RAToOps.Translate(tree, Relations.ToDictionary(relation => relation.name)); ops = new TreeNode <Operation>(new Query()) { ops }; new Heuristic0(ops).Complete(); HeuristicsArray = new Heuristic[] { new Heuristic1(ops), new Heuristic2(ops), new Heuristic3(ops), new Heuristic4(ops), new Heuristic5(ops) }; UpdateCurrentHeuristic(); this.OpsJSON = ops.Child().ToJSON().Replace("\"", """).Replace("'", "\""); return; } catch (HeuristicException e) { Console.WriteLine(e.ToString()); Error = e.Message.Replace(Environment.NewLine, "<br/>"); return; } }); this.DeleteRelation = new RelaySimpleCommand <Relation>(relation => { List <Relation> list = this.Relations.ToList(); list.Remove(relation); this.Relations = list.ToArray(); }); this.NewRelation = new RelaySimpleCommand <String>(relation => { List <Relation> list = this.Relations.ToList(); list.Add(new Relation(relation, new List <Field>() { new Field("", new List <String>() { }), new Field("", new List <String>() { }), new Field("", new List <String>() { }), new Field("", new List <String>() { }) })); this.Relations = list.ToArray(); }); }
public ExactFit(Heuristic scoringFunction) { this.scoringFunction = scoringFunction; }
public List <Vertex> GetPathAStar(GameObject srcObj, GameObject dstObj, Heuristic h = null) { if (srcObj == null || dstObj == null) { return(new List <Vertex>()); } if (ReferenceEquals(h, null)) { h = EuclidDist; } Vertex src = GetNearestVertex(srcObj.transform.position); Vertex dst = GetNearestVertex(dstObj.transform.position); BinaryHeap <Edge> frontier = new BinaryHeap <Edge>(); Edge[] edges; Edge node, child; int size = vertices.Count; float[] distValue = new float[size]; int[] previous = new int[size]; //add the source node to the heap(working as a priority queue) and assign //a distance value of infinity to all of them node = new Edge(src, 0); frontier.Add(node); distValue[src.id] = 0; previous[src.id] = src.id; for (int i = 0; i < size; i++) { if (i == src.id) { continue; } distValue[i] = Mathf.Infinity; previous[i] = -1; } //declare the loop for traversing the graph while (frontier.Count != 0) { //conditions for returning a path when necessary node = frontier.Remove(); int nodeId = node.vertex.id; if (ReferenceEquals(node.vertex, dst)) { return(BuildPath(src.id, node.vertex.id, ref previous)); } //get the vertex's neighbours edges = GetEdges(node.vertex); //traverse the neighbours for computing the cost function foreach (Edge e in edges) { int eId = e.vertex.id; if (previous[eId] != -1) { continue; } float cost = distValue[nodeId] + e.cost; cost += h(node.vertex, e.vertex); //expand the list of explored nodes and update the costs, if necessary if (cost < distValue[e.vertex.id]) { distValue[eId] = cost; previous[eId] = nodeId; frontier.Remove(); child = new Edge(e.vertex, cost); frontier.Add(child); } } } return(new List <Vertex>()); }
public virtual void Reset(Vector3 start, Vector3 end, OnPathDelegate callbackDelegate, bool reset = true) { if (reset) { processed = false; vectorPath = null; path = null; next = null; foundEnd = false; error = false; errorLog = ""; callback = null; current = null; duration = 0; searchIterations = 0; searchedNodes = 0; startHint = null; endHint = null; } callTime = System.DateTime.Now; callback = callbackDelegate; if (AstarPath.active == null || AstarPath.active.graphs == null) { errorLog += "No NavGraphs have been calculated yet - Don't run any pathfinding calls in Awake"; if (AstarPath.active.logPathResults != PathLog.None) { Debug.LogWarning(errorLog); } error = true; return; } pathID = AstarPath.active.GetNextPathID(); UpdateStartEnd(start, end); heuristic = AstarPath.active.heuristic; heuristicScale = AstarPath.active.heuristicScale; }
/** Reset all values to their default values. * * \note All inheriting path types (e.g ConstantPath, RandomPath, etc.) which declare their own variables need to * override this function, resetting ALL their variables to enable recycling of paths. * If this is not done, trying to use that path type for pooling might result in weird behaviour. * The best way is to reset to default values the variables declared in the extended path type and then * call this base function in inheriting types with base.Reset (). * * \warning This function should not be called manually. */ public virtual void Reset () { if (System.Object.ReferenceEquals (AstarPath.active, null)) throw new System.NullReferenceException ("No AstarPath object found in the scene. " + "Make sure there is one or do not create paths in Awake"); hasBeenReset = true; state = (int)PathState.Created; releasedNotSilent = false; pathHandler = null; callback = null; _errorLog = ""; pathCompleteState = PathCompleteState.NotCalculated; path = Pathfinding.Util.ListPool<GraphNode>.Claim(); vectorPath = Pathfinding.Util.ListPool<Vector3>.Claim(); currentR = null; duration = 0; searchIterations = 0; searchedNodes = 0; //calltime nnConstraint = PathNNConstraint.Default; next = null; heuristic = AstarPath.active.heuristic; heuristicScale = AstarPath.active.heuristicScale; enabledTags = -1; tagPenalties = null; callTime = System.DateTime.UtcNow; pathID = AstarPath.active.GetNextPathID (); hTarget = Int3.zero; hTargetNode = null; }
/* F score. The F score is the #g score + #h score, that is the cost it taken to move to this node from the start + the estimated cost to move to the end node.\n * Nodes are sorted by their F score, nodes with lower F scores are opened first */ /*public uint f { get { return g+h; } }*/ /** Calculates and updates the H score. * Calculates the H score with respect to the target position and chosen heuristic. * \param targetPosition The position to calculate the distance to. * \param heuristic Heuristic to use. The heuristic can also be hard coded using pre processor directives (check sourcecode) * \param scale Scale of the heuristic * \param nodeR NodeRun object associated with this node. */ public void UpdateH (Int3 targetPosition, Heuristic heuristic, float scale, NodeRun nodeR) { //Choose the correct heuristic, compute it and store it in the \a h variable if (heuristic == Heuristic.None) { nodeR.h = 0; return; } #if AstarFree || !ASTAR_DefinedHeuristic if (heuristic == Heuristic.Euclidean) { nodeR.h = (uint)Mathfx.RoundToInt ((position-targetPosition).magnitude*scale); } else if (heuristic == Heuristic.Manhattan) { nodeR.h = (uint)Mathfx.RoundToInt ( (Abs (position.x-targetPosition.x) + Abs (position.y-targetPosition.y) + Abs (position.z-targetPosition.z)) * scale ); } else { //if (heuristic == Heuristic.DiagonalManhattan) { int xDistance = Abs (position.x-targetPosition.x); int zDistance = Abs (position.z-targetPosition.z); if (xDistance > zDistance) { nodeR.h = (uint)(14*zDistance + 10*(xDistance-zDistance))/10; } else { nodeR.h = (uint)(14*xDistance + 10*(zDistance-xDistance))/10; } nodeR.h = (uint)Mathfx.RoundToInt (nodeR.h * scale); } #elif ASTAR_NoHeuristic nodeR.h = 0; #elif ASTAR_ManhattanHeuristic nodeR.h = (uint)Mathfx.RoundToInt ( (Abs (position.x-targetPosition.x) + Abs (position.y-targetPosition.y) + Abs (position.z-targetPosition.z)) * scale ); #elif ASTAR_DiagonalManhattanHeuristic int xDistance = Abs (position.x-targetPosition.x); int zDistance = Abs (position.z-targetPosition.z); if (xDistance > zDistance) { nodeR.h = (uint)(14*zDistance + 10*(xDistance-zDistance))/10; } else { nodeR.h = (uint)(14*xDistance + 10*(zDistance-xDistance))/10; } nodeR.h = (uint)Mathfx.RoundToInt (nodeR.h * scale); #elif ASTAR_EucledianHeuristic nodeR.h = (uint)Mathfx.RoundToInt ((position-targetPosition).magnitude*scale); #endif }
public virtual void Reset() { if (object.ReferenceEquals(AstarPath.active, null)) { throw new NullReferenceException("No AstarPath object found in the scene. Make sure there is one or do not create paths in Awake"); } this.hasBeenReset = true; this.state = PathState.Created; this.releasedNotSilent = false; this.pathHandler = null; this.callback = null; this._errorLog = string.Empty; this.pathCompleteState = PathCompleteState.NotCalculated; this.path = ListPool<GraphNode>.Claim(); this.vectorPath = ListPool<Vector3>.Claim(); this.currentR = null; this.duration = 0f; this.searchIterations = 0; this.searchedNodes = 0; this.nnConstraint = PathNNConstraint.Default; this.next = null; this.heuristic = AstarPath.active.heuristic; this.heuristicScale = AstarPath.active.heuristicScale; this.enabledTags = -1; this.tagPenalties = null; this.callTime = DateTime.UtcNow; this.pathID = AstarPath.active.GetNextPathID(); this.hTarget = Int3.zero; this.hTargetNode = null; }
/** Reset all values to their default values. * * \note All inheriting path types (e.g ConstantPath, RandomPath, etc.) which declare their own variables need to * override this function, resetting ALL their variables to enable recycling of paths. * If this is not done, trying to use that path type for pooling might result in weird behaviour. * The best way is to reset to default values the variables declared in the extended path type and then * call this base function in inheriting types with base.Reset (). * * \warning This function should not be called manually. */ public virtual void Reset() { if (AstarPath.active == null) throw new System.NullReferenceException ("No AstarPath object found in the scene. " + "Make sure there is one or do not create paths in Awake"); hasBeenReset = true; state = (int)PathState.Created; releasedNotSilent = false; runData = null; callback = null; _errorLog = ""; pathCompleteState = PathCompleteState.NotCalculated; path = Pathfinding.Util.ListPool<Node>.Claim(); vectorPath = Pathfinding.Util.ListPool<Vector3>.Claim(); currentR = null; duration = 0; searchIterations = 0; searchedNodes = 0; //calltime nnConstraint = PathNNConstraint.Default; next = null; radius = 0; walkabilityMask = -1; height = 0; turnRadius = 0; speed = 0; //heuristic = (Heuristic)0; //heuristicScale = 1F; heuristic = AstarPath.active.heuristic; heuristicScale = AstarPath.active.heuristicScale; pathID = 0; enabledTags = -1; tagPenalties = null; callTime = System.DateTime.UtcNow; pathID = AstarPath.active.GetNextPathID (); }
public static Stack<GameObject> AStar(GameObject start, GameObject end, Heuristic heuristic) { List<GameObject> connections = new List<GameObject>(); GameObject endNode = start; float endNodeCost = 0f; float endNodeHeuristic = 0.0f; NodeRecord endNodeRecord = new NodeRecord(); NodeRecord startRecord = new NodeRecord(); startRecord.node = start; startRecord.CostSoFar = 0.0f; startRecord.estimatedTotalCost = heuristic.euclideanDistanceEstimate(start); List<NodeRecord> openList = new List<NodeRecord>(); List<NodeRecord> closedList = new List<NodeRecord>(); openList.Add(startRecord); NodeRecord current = startRecord; while(openList.Count > 0) { current = getSmallestElement(openList); if(current.node.Equals(end)) { break; } connections = current.node.GetComponent<Node>().connections; foreach(GameObject connection in connections) { endNode = connection.GetComponent<Connection>().toNode; endNodeCost = current.CostSoFar+connection.GetComponent<Connection>().cost + endNode.GetComponent<Node>().cost; if(isInList(endNode, closedList)) { endNodeRecord = findNodeInList(endNode, closedList); if(endNodeRecord.CostSoFar <= endNodeCost) { continue; } closedList.Remove(endNodeRecord); endNodeHeuristic = endNodeRecord.estimatedTotalCost - endNodeRecord.CostSoFar; } else if(isInList(endNode, openList)) { endNodeRecord = findNodeInList(endNode, openList); if(endNodeRecord.CostSoFar <= endNodeCost) { continue; } endNodeHeuristic = endNodeCost - endNodeRecord.CostSoFar; } else { endNodeRecord = new NodeRecord(endNode); endNodeHeuristic = heuristic.euclideanDistanceEstimate(endNode); } endNodeRecord.CostSoFar = endNodeCost; endNodeRecord.connection = connection; endNodeRecord.estimatedTotalCost = endNodeCost + endNodeHeuristic; if(!(isInList(endNode, openList))) { openList.Add(endNodeRecord); } } openList.Remove(current); closedList.Add(current); } if(current.node != end) { return null; } else { Stack<GameObject> path = new Stack<GameObject>(); while(current.node != start) { path.Push(current.node); current = findNodeInList(current.connection.GetComponent<Connection>().fromNode, closedList); } //path.Reverse(); return path; } }
protected override IPathfinder CreateInstance(Heuristic heuristic) { return new AStar(25, (node, neighbor) => 1, heuristic); }
//private static readonly int PRIORITY_QUEUE_INIT_SIZE = 100; /** * * @param graph * @param start a node with valid coords * @param goal a node with valid coords * @param heuristic an admissible heuristic * @return null if no path found, otherwise the path */ public List<Connection> pathfindAStar(Graph graph, Node start, Node goal, Heuristic heuristic) { //long totalClosedListIterationTime = 0; //long totalOpenListIterationTime = 0; //long heuristicTime = 0; //long openAddTime = 0; //long openRemoveTime = 0; //long closedAddTime = 0; //long closedRemoveTime = 0; //long containTime = 0; int openCount = 0; //keep track of how many open nodes are visited SearchRecord startRecord = new SearchRecord (start); startRecord.setEstimatedTotalCost (heuristic.estimate (start)); //SmallestEstimatedCostComparator comparator = new SmallestEstimatedCostComparator (); //PriorityQueue<SearchRecord> openList = new PriorityQueue<SearchRecord> (PRIORITY_QUEUE_INIT_SIZE, comparator); List<SearchRecord> openList = new List<SearchRecord>(); int numNodes = graph.getNumNodes (); SearchRecord[] openListLookup = new SearchRecord[numNodes]; SearchRecord[] closedListLookup = new SearchRecord[numNodes]; openList.Add (startRecord); openCount++; openListLookup [startRecord.GetHashCode()] = startRecord; SearchRecord current = null; while (openList.Count > 0) { openList.Sort(); SearchRecord[] openListRecords = openList.ToArray(); current = openListRecords[0]; //retrieve, but do not remove //Console.WriteLine("current node: " + current); //current = openList.peek (); //retrieve, but do not remove if (current.getNode ().Equals (goal)) { break; } List<Connection> connections = graph.getConnections (current.getNode ()); foreach (Connection conn in connections) { //Console.WriteLine("checking connection " + conn); Node endNode = conn.getToNode (); double endNodeCost = current.getCostSoFar () + conn.getCost (); SearchRecord endNodeRecord = null; double endNodeHeuristic = 0.0; //create temporary SearchRecord to wrap endNode... for purposes of searching the open and closed lists SearchRecord endNodeRecordTemplate = new SearchRecord (endNode); //long containStart = System.currentTimeMillis (); bool closedListContains = (closedListLookup [endNodeRecordTemplate.GetHashCode()] != null); bool openListContains = false; //only need to determine openListContains value if closedListContains is false (due to the if/else ordering below) if (!(closedListContains)) { openListContains = (openListLookup [endNodeRecordTemplate.GetHashCode()] != null); } //long containEnd = System.currentTimeMillis (); //containTime += (containEnd - containStart); if (closedListContains) { //find end node record from closed list //long closedListIterationStart = System.currentTimeMillis (); endNodeRecord = closedListLookup [endNodeRecordTemplate.GetHashCode()]; //long closedListIterationEnd = System.currentTimeMillis (); //totalClosedListIterationTime += (closedListIterationEnd - closedListIterationStart); if (endNodeRecord.getCostSoFar () <= endNodeCost) { continue; } //long closedRemoveStart = System.currentTimeMillis (); closedListLookup [endNodeRecord.GetHashCode()] = null; //long closedRemoveEnd = System.currentTimeMillis (); //closedRemoveTime += closedRemoveEnd - closedRemoveStart; endNodeHeuristic = endNodeRecord.getEstimatedTotalCost () - endNodeRecord.getCostSoFar (); } else if (openListContains) { //find end node record from open list //long openListIterationStart = System.currentTimeMillis (); endNodeRecord = openListLookup [endNodeRecordTemplate.GetHashCode()]; //long openListIterationEnd = System.currentTimeMillis (); //totalOpenListIterationTime += (openListIterationEnd - openListIterationStart); if (endNodeRecord.getCostSoFar () <= endNodeCost) { continue; } endNodeHeuristic = endNodeRecord.getEstimatedTotalCost () - endNodeRecord.getCostSoFar (); } else { //unvisited node endNodeRecord = new SearchRecord (endNode); //long heuristicStartTime = System.currentTimeMillis (); endNodeHeuristic = heuristic.estimate (endNode); //long heuristicEndTime = System.currentTimeMillis (); //heuristicTime += (heuristicEndTime - heuristicStartTime); } //update the cost, estimate, and connection endNodeRecord.setCostSoFar (endNodeCost); endNodeRecord.setConnection (conn); //Console.WriteLine("record " + endNodeRecord + ", setting connection: " + conn); endNodeRecord.setEstimatedTotalCost (endNodeCost + endNodeHeuristic); //long containsCheckStart = System.currentTimeMillis (); bool openListContainsEndNodeRecord = (openListLookup [endNodeRecord.GetHashCode()] != null); //long containsCheckEnd = System.currentTimeMillis (); //containTime += (containsCheckEnd - containsCheckStart); if (!(openListContainsEndNodeRecord)) { //long openAddStart = System.currentTimeMillis (); openList.Add (endNodeRecord); //Console.WriteLine("Adding " + endNodeRecord + " to open list"); openList.Sort(); openCount++; openListLookup [endNodeRecord.GetHashCode()] = endNodeRecord; //long openAddEnd = System.currentTimeMillis (); //openAddTime += (openAddEnd - openAddStart); } } //long openRemoveStart = System.currentTimeMillis (); //openList.Sort(); openList.Remove(current); //RemoveAt(0); //openList.poll (); //NOTE: current is always the head of the open list... old code: //openList.remove(current); openListLookup [current.GetHashCode()] = null; //long openRemoveEnd = System.currentTimeMillis (); //openRemoveTime += (openRemoveEnd - openRemoveStart); //long closedAddStart = System.currentTimeMillis (); closedListLookup [current.GetHashCode()] = current; //long closedAddEnd = System.currentTimeMillis (); //closedAddTime += (closedAddEnd - closedAddStart); } if (!(current.getNode ().Equals (goal))) { return null; } else { List<Connection> reversePath = new List<Connection> (); //retrieve path while (!(current.getNode().Equals(start))) { //Console.WriteLine("adding to reversePath: " + current.getConnection()); reversePath.Add (current.getConnection ()); Node fromNode = current.getConnection ().getFromNode (); SearchRecord placeholder = new SearchRecord (fromNode); SearchRecord previous = closedListLookup [placeholder.GetHashCode()]; if (previous == null) { String to = (placeholder.getConnection ().getToNode () != null) ? placeholder.getConnection ().getToNode ().ToString () : "null"; String from = (placeholder.getConnection ().getFromNode () != null) ? placeholder.getConnection ().getFromNode ().ToString () : "null"; //Console.WriteLine ("retrieving path NPE. Data: Placeholder connection from: " + from + ", placeholder connection to: " + to + ", goal: " + goal + ", start: " + start); } //find SearchRecord for fromNode in the closed list current = previous; } //reverse the path List<Connection> path = new List<Connection> (); //Enumerator enumerator = reversePath.GetEnumerator(); //Iterator<Connection> reverseIt = reversePath.iterator (); //while (enumerator.hasNext()) { foreach (Connection reverseConn in reversePath) { //Console.WriteLine("reverseConn " + reverseConn); //Connection reverseConn = reverseIt.next (); //path.addFirst (reverseConn); path.Insert(0, reverseConn); } // System.out.println("total closed it time: " + totalClosedListIterationTime); // System.out.println("total open it time: " + totalOpenListIterationTime); // System.out.println("heuristic time: " + heuristicTime); // System.out.println("open add time: " + openAddTime); // System.out.println("open remove time: " + openRemoveTime); // System.out.println("closed add time: " + closedAddTime); // System.out.println("contain time: " + containTime); // System.out.println("closed remove time: " + closedRemoveTime); // long sum = totalClosedListIterationTime + totalOpenListIterationTime + heuristicTime + openAddTime + openRemoveTime + closedAddTime + containTime + closedRemoveTime; // System.out.println("total accounted time: " + sum); // System.out.println("open nodes visited: " + openCount); return path; } }
public virtual void UpdateH(Int3 targetPosition, Heuristic heuristic, float scale) { //Choose the correct heuristic, compute it and store it in the \a h variable if (heuristic == Heuristic.None) { h = 0; return; } if (heuristic == Heuristic.Manhattan) { h = Mathfx.RoundToInt ( (Abs (position.x-targetPosition.x) + Abs (position.y-targetPosition.y) + Abs (position.z-targetPosition.z)) * scale ); } else if (heuristic == Heuristic.DiagonalManhattan) { int xDistance = Abs (position.x-targetPosition.x); int zDistance = Abs (position.z-targetPosition.z); if (xDistance > zDistance) { h = (14*zDistance + 10*(xDistance-zDistance))/10; } else { h = (14*xDistance + 10*(zDistance-xDistance))/10; } h = Mathfx.RoundToInt (h * scale); } else { h = Mathfx.RoundToInt ((position-targetPosition).magnitude*scale); } }
/** Reset all values to their default values. * * \note All inheriting path types (e.g ConstantPath, RandomPath, etc.) which declare their own variables need to * override this function, resetting ALL their variables to enable recycling of paths. * If this is not done, trying to use that path type for pooling might result in weird behaviour. * The best way is to reset to default values the variables declared in the extended path type and then * call this base function in inheriting types with base.Reset (). * * \warning This function should not be called manually. */ public virtual void Reset () { #if ASTAR_POOL_DEBUG pathTraceInfo = "This path was got from the pool or created from here (stacktrace):\n"; pathTraceInfo += System.Environment.StackTrace; #endif if (AstarPath.active == null) throw new System.NullReferenceException ("No AstarPath object found in the scene. " + "Make sure there is one or do not create paths in Awake"); hasBeenReset = true; state = (int)PathState.Created; releasedNotSilent = false; pathHandler = null; callback = null; _errorLog = ""; pathCompleteState = PathCompleteState.NotCalculated; path = Pathfinding.Util.ListPool<GraphNode>.Claim(); vectorPath = Pathfinding.Util.ListPool<Vector3>.Claim(); currentR = null; duration = 0; searchIterations = 0; searchedNodes = 0; //calltime nnConstraint = PathNNConstraint.Default; next = null; radius = 0; walkabilityMask = -1; height = 0; turnRadius = 0; speed = 0; //heuristic = (Heuristic)0; //heuristicScale = 1F; heuristic = AstarPath.active.heuristic; heuristicScale = AstarPath.active.heuristicScale; pathID = 0; enabledTags = -1; tagPenalties = null; callTime = System.DateTime.UtcNow; pathID = AstarPath.active.GetNextPathID (); hTarget = Int3.zero; }
public IndexGene(int popsize, int depth, int generations, Heuristic scoringFunction) { name = "Index " + scoringFunction.ToString(); popSize = popsize; this.depth = depth; this.generations = generations; fit = new IndexFit(scoringFunction); }