protected WorldPath ComputePathToPosition(ArmyWithTask army, WorldPosition targetPosition, WorldPath currentPath) { if (currentPath != null && currentPath.Destination == targetPosition && currentPath.Origin == army.Garrison.WorldPosition) { for (int i = 0; i < currentPath.WorldPositions.Length; i++) { if (currentPath.WorldPositions[i] == army.Garrison.WorldPosition) { return(currentPath); } } } IPathfindingContextProvider pathfindingContextProvider = army.Garrison as IPathfindingContextProvider; if (pathfindingContextProvider == null) { return(null); } PathfindingContext pathfindingContext = pathfindingContextProvider.GenerateContext(); pathfindingContext.Greedy = true; WorldPosition worldPosition = army.Garrison.WorldPosition; PathfindingResult pathfindingResult = this.pathfindingService.FindPath(pathfindingContext, worldPosition, targetPosition, PathfindingManager.RequestMode.Default, null, PathfindingFlags.IgnoreFogOfWar, null); if (pathfindingResult == null) { return(null); } WorldPath worldPath = new WorldPath(); worldPath.Build(pathfindingResult, army.Garrison.GetPropertyValue(SimulationProperties.MovementRatio), 1, false); return(worldPath); }
protected Amplitude.Unity.Game.Orders.Order FollowPath(ArmyWithTask army, WorldPath path) { if (path == null || !path.IsValid) { return(null); } int num = -1; for (int i = 0; i < path.WorldPositions.Length; i++) { if (path.WorldPositions[i] == army.Garrison.WorldPosition) { num = i; break; } } if (num == path.Length - 1) { return(null); } if (num == -1) { return(null); } IPathfindingContextProvider pathfindingContextProvider = army.Garrison as IPathfindingContextProvider; if (pathfindingContextProvider == null) { return(null); } IGameService service = Services.GetService <IGameService>(); Diagnostics.Assert(service != null); IPathfindingService service2 = service.Game.Services.GetService <IPathfindingService>(); Diagnostics.Assert(service2 != null); WorldPosition worldPosition = WorldPosition.Invalid; int num2 = 0; for (int j = num + 1; j < path.WorldPositions.Length; j++) { if (service2.IsTilePassable(path.WorldPositions[j], pathfindingContextProvider, (PathfindingFlags)0, null) && service2.IsTileStopable(path.WorldPositions[j], pathfindingContextProvider, (PathfindingFlags)0, null)) { worldPosition = path.WorldPositions[j]; num2++; if (num2 >= 2) { break; } } } if (worldPosition == WorldPosition.Invalid) { return(null); } return(new OrderGoTo(army.Garrison.Empire.Index, army.Garrison.GUID, worldPosition) { Flags = (PathfindingFlags)0 }); }
private WorldPath GenerateNewPath() { int num = (moving && nextTile >= 0 && IsNextTilePassable()) ? nextTile : caravan.Tile; lastPathedTargetTile = destTile; WorldPath worldPath = WorldVehiclePathfinder.Instance.FindPath(num, destTile, caravan, null); if (worldPath.Found && num != caravan.Tile) { if (worldPath.NodesLeftCount >= 2 && worldPath.Peek(1) == caravan.Tile) { worldPath.ConsumeNextNode(); if (moving) { previousTileForDrawingIfInDoubt = nextTile; nextTile = caravan.Tile; nextTileCostLeft = nextTileCostTotal - nextTileCostLeft; } } else { worldPath.AddNodeAtStart(caravan.Tile); } } return(worldPath); }
public static bool Prefix(WorldPathPool __instance, ref WorldPath __result) { List <WorldPath> paths = Traverse.Create(root: __instance).Field(name: "paths").GetValue <List <WorldPath> >(); for (int i = 0; i < paths.Count; i++) { if (!paths[i].inUse) { paths[i].inUse = true; __result = paths[i]; return(false); } } if (paths.Count > Find.WorldObjects.CaravansCount + 2 + (Find.WorldObjects.RoutePlannerWaypointsCount - 1)) { //Log.ErrorOnce("WorldPathPool leak: more paths than caravans. Force-recovering.", 664788); paths.Clear(); } WorldPath worldPath = new WorldPath(); paths.Add(worldPath); worldPath.inUse = true; __result = worldPath; return(false); }
private WorldPath ComputeSafePathOpportunity(Army army, WorldPosition destination, WorldPath unsafePath) { if (this.SafePathOpportunityMax < 1f) { return(unsafePath); } bool flag = true; for (int i = 0; i < unsafePath.ControlPoints.Length; i++) { if (this.worldPositionningService.HasRetaliationFor(unsafePath.WorldPositions[(int)unsafePath.ControlPoints[i]], army.Empire)) { flag = false; break; } } if (!flag) { PathfindingContext pathfindingContext = army.GenerateContext(); pathfindingContext.Greedy = true; PathfindingResult pathfindingResult = this.pathfindingService.FindPath(pathfindingContext, army.WorldPosition, destination, PathfindingManager.RequestMode.AvoidToBeHurtByDefensiveTiles, null, this.currentFlags, null); if (pathfindingResult != null) { WorldPath worldPath = new WorldPath(); worldPath.Build(pathfindingResult, army.GetPropertyValue(SimulationProperties.MovementRatio), this.numberOfTurnForWorldPath, false); if (worldPath.IsValid && (float)worldPath.ControlPoints.Length < this.SafePathOpportunityMax * (float)unsafePath.ControlPoints.Length) { return(worldPath); } } } return(unsafePath); }
private WorldPath GenerateNewPath() { int num = (!moving || nextTile < 0 || !IsNextTilePassable()) ? warObject.Tile : nextTile; lastPathedTargetTile = destTile; WorldPath worldPath = Verse.Find.WorldPathFinder.FindPath(num, destTile, null); //caravan=null if (worldPath.Found && num != warObject.Tile) { if (worldPath.NodesLeftCount >= 2 && worldPath.Peek(1) == warObject.Tile) { worldPath.ConsumeNextNode(); if (moving) { previousTileForDrawingIfInDoubt = nextTile; nextTile = warObject.Tile; nextTileCostLeft = nextTileCostTotal - nextTileCostLeft; } } else { worldPath.AddNodeAtStart(warObject.Tile); } } return(worldPath); }
private bool CanReachPositionInTurn(Army army, WorldPosition destination, int maximumNumberOfTurns, out int numberOfTurns) { numberOfTurns = maximumNumberOfTurns; IGameService service = Services.GetService <IGameService>(); Diagnostics.Assert(service != null); IPathfindingService service2 = service.Game.Services.GetService <IPathfindingService>(); Diagnostics.Assert(service2 != null); if (army.WorldPosition.Equals(destination)) { return(true); } PathfindingContext pathfindingContext = army.GenerateContext(); pathfindingContext.Greedy = true; PathfindingResult pathfindingResult = service2.FindPath(pathfindingContext, army.WorldPosition, destination, PathfindingManager.RequestMode.Default, null, PathfindingFlags.IgnoreFogOfWar, null); if (pathfindingResult == null) { return(false); } WorldPath worldPath = new WorldPath(); worldPath.Build(pathfindingResult, army.GetPropertyValue(SimulationProperties.MovementRatio), maximumNumberOfTurns, false); numberOfTurns = worldPath.ControlPoints.Length; if (worldPath.ControlPoints.Length < maximumNumberOfTurns) { return(true); } WorldPosition left = worldPath.WorldPositions[(int)worldPath.ControlPoints[maximumNumberOfTurns - 1]]; return(left == destination && left == worldPath.WorldPositions[worldPath.Length - 1]); }
public void SetDestinationPos(Vector2 pos) { m_targetPos = pos; m_randomGeneratePos = false; StopCoroutine("FollowFoundPath"); m_path = null; PathFinderRequestManager.RequestPath(new PathRequest(transform.position, m_targetPos, PathFound)); }
public static float DaysTo(Map map, Func <Faction, bool> factionValidator) { int tile = map.Tile; Func <WorldObject, bool> woValidator = (wo) => (wo is Settlement || wo is Site s && s.parts.Any(part => part.def == SitePartDefOf.Outpost)) && wo.Faction != null && factionValidator(wo.Faction); Predicate <int> validator = (int t) => Find.World.worldObjects.ObjectsAt(t).Any(woValidator); Predicate <int> waterValidator = (int t) => Find.World.grid[t].WaterCovered; //bool factionBase = false, water = false; int foundTile; if (!TryFindClosestTile(tile, t => !Find.World.Impassable(t), validator, out foundTile)) { TryFindClosestTile(tile, t => !Find.World.Impassable(t) || waterValidator(t), waterValidator, out foundTile); } Log.Message($"Closest tile to {map} is {foundTile}:{Find.World.grid[foundTile]}"); WorldPath path = Find.WorldPathFinder.FindPath(tile, foundTile, null); float cost = 0; if (path.Found) { cost = path.TotalCost; Log.Message($"Path cost is {cost}"); path.ReleaseToPool(); } else { List <int> neighborTiles = new List <int>(); Find.World.grid.GetTileNeighbors(foundTile, neighborTiles); float bestCost = float.MaxValue; foreach (int nTile in neighborTiles) { Log.Message($"Looking at neighbor tile {nTile}:{Find.World.grid[nTile]}"); path = Find.WorldPathFinder.FindPath(tile, nTile, null); if (path.Found) { bestCost = Math.Min(bestCost, path.TotalCost); } Log.Message($"best cost is {bestCost}"); path.ReleaseToPool(); } if (bestCost == float.MaxValue) { bestCost = 0; //paranoid? } cost = bestCost + Mod.settings.islandAddedDays * 40000; Log.Message($"cost after added island days: {cost}"); } cost /= 40000; //Cost to days-ish float wealth = map.wealthWatcher.WealthTotal; return(AddedDays(cost) * WealthReduction(wealth)); }
private void PathFound(Vector3[] waypoints, bool found) { if (found && gameObject.activeSelf) { m_path = new WorldPath(waypoints, transform.position, turnDistance); StopCoroutine("FollowFoundPath"); StartCoroutine("FollowFoundPath"); } }
private IEnumerator FollowFoundPath() { int currentIndex = 0; bool exitPathFollow = false; float timeAtSamePos = 0.0f; Vector2 lasPost = transform.position; while (currentIndex < m_path.PathSize) { Vector2 currentAgentPos = transform.position; while (m_path.HasCrossedNode(currentIndex, currentAgentPos)) { currentIndex++; if (currentIndex == m_path.PathSize) { exitPathFollow = true; break; } } if (exitPathFollow || timeAtSamePos >= StuckTime) { break; } if (lasPost == (Vector2)transform.position) { timeAtSamePos += Time.deltaTime; } else { timeAtSamePos = 0.0f; } lasPost = transform.position; Vector2 targetDir = m_path.GetNodePos(currentIndex) - m_path.GetNodePos(currentIndex - 1); Vector2 currentPlayerDir = m_path.GetDirToNodeFrom(currentIndex, currentAgentPos); Vector2 dir = Vector2.Lerp(currentPlayerDir, targetDir, Time.deltaTime * turnSpeed).normalized; if (dir.sqrMagnitude == 0) { m_characterScript.SetMovementStatus(Character.MovementStatus.None); } else { m_characterScript.SetMovementStatus(Character.MovementStatus.Walk); } m_characterScript.SetDirection(dir); //Wait until next frame yield return(null); } currentIndex = 0; m_characterScript.SetDirection(new Vector2(0, 0)); m_characterScript.SetMovementStatus(Character.MovementStatus.None); m_path = null; m_startWaitingTime = Time.time; }
void Start() { LevelSettings level = GameObject.Find("World").GetComponent <LevelSettings> (); worldpath = level.worldPath; control = gameObject.GetComponent <CarControl2> (); nextPoint = worldpath.getNextPointByID(nextPointID); nextNode = worldpath.getNodeByID(nextPointID); }
public void SetFollowRandomPos() { if (m_randomGeneratePos) { return; } m_randomGeneratePos = true; StopCoroutine("FollowFoundPath"); m_path = null; }
public virtual void Reset(WorldPath worldPath) { this.WorldPath = worldPath; this.Reset(); this.Progress = 0; while (this.Progress < this.WorldPositions.Length && this.WorldPositions[this.Progress] != this.Army.WorldPosition) { this.Progress++; } this.Progress++; }
//Almost literal copy from vanilla, except Caravan object exposed here. public static int EstimatedTicksToArrive(int from, int to, WorldPath path, float nextTileCostLeft, Caravan caravan, int curTicksAbs) { List <Pawn> pawns = null; if (caravan != null) { pawns = caravan.PawnsListForReading; } return(EstimatedTicksToArrive(from, to, path, nextTileCostLeft, pawns, curTicksAbs)); }
public static int EstimatedTicksToArrive(int from, int to, int ticksPerMove) { using (WorldPath worldPath = Verse.Find.WorldPathFinder.FindPath(from, to, null)) { if (!worldPath.Found) { return(0); } return(CaravanArrivalTimeEstimator.EstimatedTicksToArrive(from, to, worldPath, 0, ticksPerMove, Verse.Find.TickManager.TicksAbs)); } }
public override void ExposeData() { base.ExposeData(); Scribe_References.Look(ref reinforcementsFrom, "reinforcementsFrom"); Scribe_Values.Look(ref ticksTillReinforcements, "ticksTillReinforcements"); Scribe_Values.Look(ref ticksSinceCrash, "ticksSinceCrash"); if (Scribe.mode == LoadSaveMode.PostLoadInit) { pathToSite = Find.WorldPathFinder.FindPath(reinforcementsFrom.Tile, Tile, null); } }
public int InitiateReinforcementsRequest(Settlement reinforcementsFrom) { this.reinforcementsFrom = reinforcementsFrom; ticksSinceCrash = 0; pathToSite = Find.WorldPathFinder.FindPath(reinforcementsFrom.Tile, Tile, null); if (reinforcementsFrom is null || !pathToSite.Found) { ticksTillReinforcements = int.MaxValue; return(-1); } return(ticksTillReinforcements = Mathf.RoundToInt(pathToSite.TotalCost * 1.5f)); }
public bool testPath(WorldPath path) { WorldGrid grid = Find.WorldGrid; WorldPath testpath = new WorldPath(); testpath = path; List <int> nodeList = (List <int>)(typeof(WorldPath).GetField("nodes", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(testpath)); typeof(WorldPath).GetField("curNodeIndex", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).SetValue(testpath, nodeList.Count - 1, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance, null, null); int nodes = testpath.NodesLeftCount; int prevtile = testpath.FirstNode; int tile; bool hasRoad = true; for (int i = 0; i < nodes - 1; i++) { if (testpath.NodesLeftCount == 1) { tile = testpath.LastNode; } else { tile = testpath.ConsumeNextNode(); } RoadDef def = grid.GetRoadDef(prevtile, tile); if (def == roadDef) { prevtile = tile; continue; } if (def != null && isNewRoadBetter(def, roadDef)) { return(false); //road creatable } else if (def == null) { return(false); //road creatable } else //if road exists, but new road is not better { //Make no changes } prevtile = tile; continue; } return(true); }
public List <WorldPath> GetSurroundingPathsExcept(WorldPath pathToIgnore) { List <WorldPath> result = new List <WorldPath>(); foreach (WorldPath path in surroundingPaths) { if (path != pathToIgnore) { result.Add(path); } } return(result); }
public void StopDead() { if (curPath != null) { curPath.ReleaseToPool(); } curPath = null; moving = false; paused = false; nextTile = warObject.Tile; previousTileForDrawingIfInDoubt = -1; nextTileCostLeft = 0f; }
//private bool autoUpdate = false; public override void OnInspectorGUI() { myTarget = target; //autoUpdate = GUILayout.Toggle(autoUpdate,"Auto Update"); if (GUILayout.Button("Generate Path")) { WorldPath path = (WorldPath)myTarget; path.Rebuild(); } DrawDefaultInspector(); }
private void Army_WorldPathChange(object sender, ArmyWorldPathChangeEventArgs e) { if (this.WorldPath != null) { this.PathRendererService.RemovePath(this.WorldPath); } this.WorldPath = this.WorldArmy.Army.WorldPath; if (this.WorldPath != null) { this.WorldPath.Rebuild(this.Army.WorldPosition, this.Army, this.Army.GetPropertyValue(SimulationProperties.MovementRatio), int.MaxValue, PathfindingFlags.IgnoreArmies, false); } this.PathRendererService.RenderPath(this.WorldPath, this.WorldArmy.Army.WorldPosition); }
public bool StartPath(int destTile, CaravanArrivalAction arrivalAction, bool repathImmediately = false, bool resetPauseStatus = true) { caravan.autoJoinable = false; if (resetPauseStatus) { paused = false; } if (arrivalAction != null && !arrivalAction.StillValid(caravan, destTile)) { return(false); } if (!IsPassable(caravan.Tile) && !TryRecoverFromUnwalkablePosition()) { return(false); } if (moving && curPath != null && this.destTile == destTile) { this.arrivalAction = arrivalAction; return(true); } if (!WorldVehicleReachability.Instance.CanReach(caravan, destTile)) { PatherFailed(); return(false); } this.destTile = destTile; this.arrivalAction = arrivalAction; caravan.Notify_DestinationOrPauseStatusChanged(); if (nextTile < 0 || !IsNextTilePassable()) { nextTile = caravan.Tile; nextTileCostLeft = 0f; previousTileForDrawingIfInDoubt = -1; } if (AtDestinationPosition()) { PatherArrived(); return(true); } if (curPath != null) { curPath.ReleaseToPool(); } curPath = null; moving = true; if (repathImmediately && TrySetNewPath() && nextTileCostLeft <= 0f && moving) { TryEnterNextPathTile(); } return(true); }
public void calculateRoadPath(FCRoadBuilderQueue queue) { if (roadDef == null) { //Log.Message("===== Road def Null ====="); return; } FactionFC faction = Find.World.GetComponent <FactionFC>(); List <WorldPath> buildQueue = new List <WorldPath>(); List <int> settlementLocations = new List <int>(); //get list of settlements foreach (SettlementFC settlement in faction.settlements) { if (settlement.planetName == queue.planetName) { settlementLocations.Add(settlement.mapLocation); } } //TO DO -- add player settlement locations here foreach (Settlement settlement in Find.World.worldObjects.Settlements) { if (settlement.Faction.IsPlayer) { settlementLocations.Add(settlement.Tile); } } //from each settlement location, pair up with every other settlement location for (int i = settlementLocations.Count() - 1; i > 0; i--) { for (int k = 0; k < (settlementLocations.Count() - 1); k++) { //Log.Message("3 - " + i + "i = k" + k); WorldPath path = Find.WorldPathFinder.FindPath(settlementLocations[i], settlementLocations[k], null, null); if (path != null && path != WorldPath.NotFound) { if (!testPath(path)) { buildQueue.Add(path); } } } settlementLocations.RemoveAt(i); } queue.ToBuild = buildQueue; //Log.Message(queue.ToBuild.Count().ToString() + " number of road paths calculated"); }
private void GenerateAncientRoads() { Find.WorldPathGrid.RecalculateAllPerceivedPathCosts(0); List <List <int> > list = GenerateProspectiveRoads(); list.Sort((List <int> lhs, List <int> rhs) => - lhs.Count.CompareTo(rhs.Count)); HashSet <int> used = new HashSet <int>(); for (int i = 0; i < list.Count; i++) { if (!list[i].Any((int elem) => used.Contains(elem))) { if (list[i].Count < 4) { break; } foreach (int item in list[i]) { used.Add(item); } for (int j = 0; j < list[i].Count - 1; j++) { float num = Find.WorldGrid.ApproxDistanceInTiles(list[i][j], list[i][j + 1]) * maximumSegmentCurviness; float costCutoff = num * 12000f; using (WorldPath worldPath = Find.WorldPathFinder.FindPath(list[i][j], list[i][j + 1], null, (float cost) => cost > costCutoff)) { if (worldPath != null && worldPath != WorldPath.NotFound) { List <int> nodesReversed = worldPath.NodesReversed; if (!((float)nodesReversed.Count > Find.WorldGrid.ApproxDistanceInTiles(list[i][j], list[i][j + 1]) * maximumSegmentCurviness)) { for (int k = 0; k < nodesReversed.Count - 1; k++) { if (Find.WorldGrid.GetRoadDef(nodesReversed[k], nodesReversed[k + 1], visibleOnly: false) != null) { Find.WorldGrid.OverlayRoad(nodesReversed[k], nodesReversed[k + 1], RoadDefOf.AncientAsphaltHighway); } else { Find.WorldGrid.OverlayRoad(nodesReversed[k], nodesReversed[k + 1], RoadDefOf.AncientAsphaltRoad); } } } } } } } } }
public void StopDead() { if (curPath != null) { curPath.ReleaseToPool(); } curPath = null; moving = false; paused = false; nextTile = caravan.Tile; previousTileForDrawingIfInDoubt = -1; arrivalAction = null; nextTileCostLeft = 0f; caravan.Notify_DestinationOrPauseStatusChanged(); }
private bool TrySetNewPath() { WorldPath worldPath = GenerateNewPath(); if (!worldPath.Found) { PatherFailed(); return(false); } if (curPath != null) { curPath.ReleaseToPool(); } curPath = worldPath; return(true); }
private bool TryTeleportInRange(AIBehaviorTree aiBehaviorTree, Army army, WorldPath path, int CurrentIndex) { List <StaticString> list = new List <StaticString>(); if (!this.armyAction_TeleportInRange.CanExecute(army, ref list, new object[0])) { return(false); } float teleportationRange = this.armyAction_TeleportInRange.GetTeleportationRange(army); PathfindingContext pathfindingContext = army.GenerateContext(); WorldPosition worldPosition = WorldPosition.Invalid; int i = path.WorldPositions.Length - 1; while (i >= CurrentIndex) { WorldPosition worldPosition2 = path.WorldPositions[i]; int distance = this.worldPositionningService.GetDistance(worldPosition2, army.WorldPosition); if (distance < 6) { return(false); } if (distance <= (int)teleportationRange && this.armyAction_TeleportInRange.CanTeleportTo(army, worldPosition2, this.pathfindingService, pathfindingContext, this.visibilityService, this.worldPositionningService)) { worldPosition = worldPosition2; if (Amplitude.Unity.Framework.Application.Preferences.EnableModdingTools) { Diagnostics.Log("executing from {0} to {1}, {2}", new object[] { army.WorldPosition, worldPosition, distance }); break; } break; } else { i--; } } this.armyAction_TeleportInRange.Execute(army, aiBehaviorTree.AICommander.Empire.PlayerControllers.AI, out this.currentTicket, null, new object[] { worldPosition }); return(true); }
public void CreateGraphNode(WorldPath road) { GraphNode graphNode = new GraphNode { Road = road, Visited = false, RoadNeighbours = road.GetNeighbouringPaths(), Neighbours = new List <GraphNode>() }; nodes.Add(graphNode); if (nodes.Count == ROAD_COUNT) { CalculateNodeNeighbours(); } }