public static List <DoubleCoords> SplitEllipseIntoLines(List <Coordinates> ellipse) { List <DoubleCoords> lines = new(); var sorted = ellipse.OrderBy( a => a, Comparer <Coordinates> .Create((a, b) => a.Y != b.Y ? a.Y - b.Y : a.X - b.X) ); int minX = int.MaxValue; int maxX = int.MinValue; Coordinates?prev = null; foreach (var point in sorted) { if (prev.HasValue && point.Y != prev.Value.Y) { int prevY = prev.Value.Y; lines.Add(new DoubleCoords(new(minX, prevY), new(maxX, prevY))); minX = int.MaxValue; maxX = int.MinValue; } minX = Math.Min(point.X, minX); maxX = Math.Max(point.X, maxX); prev = point; } lines.Add(new DoubleCoords(new(minX, prev.Value.Y), new(maxX, prev.Value.Y))); return(lines); }
/// <summary> /// Clsoest point to vehicle from a certain point relative to vehicle state /// </summary> /// <param name="c"></param> /// <param name="state"></param> /// <param name="distance"></param> /// <returns></returns> public Coordinates?ClosestPointTo(Coordinates c, VehicleState state, out double distance) { Coordinates[] rel = this.StateMonitor.Observed.relativePoints; Coordinates? closest = null; double dist = double.MaxValue; for (int i = 0; i < rel.Length; i++) { if (!closest.HasValue) { Coordinates tmp = this.TransformCoordAbs(rel[i], state); closest = tmp; dist = tmp.DistanceTo(c); } else { Coordinates tmp = this.TransformCoordAbs(rel[i], state); double tmpDist = tmp.DistanceTo(c); if (tmpDist < dist) { dist = tmpDist; closest = tmp; } } } distance = dist; return(closest); }
/// <summary> /// Returns a free parking spot for the given airbase. /// </summary> /// <param name="airbaseID">Internal ID of the airbase in DCS World</param> /// <param name="lastSpotCoordinates">Coordinates of the last aircraft spot</param> /// <param name="airbaseID">Coordinates of the selected parking spot</param> /// <returns>A parking spot ID, or -1 if none found or if airbase doesn't exist</returns> public int GetFreeParkingSpot(int airbaseID, Coordinates?lastSpotCoordinates, out Coordinates parkingSpotCoordinates) { parkingSpotCoordinates = new Coordinates(); if (!AirbaseParkingSpots.ContainsKey(airbaseID) || (AirbaseParkingSpots[airbaseID].Count == 0)) { return(-1); } DBEntryTheaterAirbase[] airbaseDB = (from DBEntryTheaterAirbase ab in TheaterDB.Airbases where ab.DCSID == airbaseID select ab).ToArray(); if (airbaseDB.Length == 0) { return(-1); // No airbase with proper DCSID } DBEntryTheaterAirbaseParkingSpot?parkingSpot = null; if (lastSpotCoordinates != null) //find nearest spot distance wise in attempt to cluster { parkingSpot = AirbaseParkingSpots[airbaseID].Aggregate((acc, x) => acc.Coordinates.GetDistanceFrom(lastSpotCoordinates.Value) > x.Coordinates.GetDistanceFrom(lastSpotCoordinates.Value) && x.Coordinates.GetDistanceFrom(lastSpotCoordinates.Value) != 0 ? x : acc); } else { parkingSpot = Toolbox.RandomFrom(AirbaseParkingSpots[airbaseID]); } AirbaseParkingSpots[airbaseID].Remove(parkingSpot.Value); parkingSpotCoordinates = parkingSpot.Value.Coordinates; return(parkingSpot.Value.DCSID); }
private void GetNearestSpawn(UnitSide side, SpawnType type, Coordinates coordinates, Action <Coordinates?> callBack) { if (spawnPointsDic.TryGetValue(side, out var dic) == false) { callBack(null); return; } double length = double.MaxValue; Coordinates?target = null; foreach (var kvp in dic) { if (kvp.Value.Side != side || kvp.Value.SpawnType != type) { continue; } var diff = coordinates - kvp.Value.Position; var mag = diff.SqrMagnitude(); if (mag < length) { target = kvp.Value.Position; length = mag; } } callBack(target); }
// TODO: initialiser les propriétés public TownHall(string name, int lifepoints, int maxLifePoints, bool attack, SerializableDictionary <ResourcesType, int> resources, Coordinates?position) : base(name, lifepoints, maxLifePoints, attack) { ProductionQueue = new ConcurrentQueue <IProductable>(); Stock = resources; Position = position.GetValueOrDefault(); }
public static Model Read(UniGLTF.GltfData data, Coordinates?coords = default) { var storage = new Vrm10Storage(data); var model = Load(storage, Path.GetFileName(data.TargetPath), coords.GetValueOrDefault(Coordinates.Vrm1)); model.ConvertCoordinate(Coordinates.Unity); return(model); }
/// <summary> /// Sets the distance away property of this object calculated from the specified location object. /// </summary> /// <param name="loc">Location object to calculate distance away with.</param> public void SetDistanceAway(Coordinates?loc) { if (loc == null) { return; } _DistanceAway = this.GetDistanceTo(loc); }
private static Tuple <Coordinates, Coordinates> GetSpawnAndDestination( UnitMaker unitMaker, MissionTemplateRecord template, DBEntryTheater theaterDB, List <Coordinates> usedCoordinates, Coordinates landbaseCoordinates, Coordinates objectivesCenter, double carrierPathDeg) { var travelMinMax = new MinMaxD(Database.Instance.Common.CarrierGroup.CourseLength, Database.Instance.Common.CarrierGroup.CourseLength * 2); Coordinates?carrierGroupCoordinates = null; Coordinates?destinationPath = null; var iteration = 0; var maxDistance = 25; while (iteration < 100) { carrierGroupCoordinates = unitMaker.SpawnPointSelector.GetRandomSpawnPoint( new SpawnPointType[] { SpawnPointType.Sea }, landbaseCoordinates, new MinMaxD(10, maxDistance), objectivesCenter, new MinMaxD(10, 99999), GeneratorTools.GetSpawnPointCoalition(template, Side.Ally)); if (!carrierGroupCoordinates.HasValue) { maxDistance += 25; continue; } var minDist = usedCoordinates.Aggregate(99999999.0, (acc, x) => x.GetDistanceFrom(carrierGroupCoordinates.Value) < acc ? x.GetDistanceFrom(carrierGroupCoordinates.Value) : acc); if (minDist < Database.Instance.Common.CarrierGroup.ShipSpacing) { continue; } destinationPath = Coordinates.FromAngleAndDistance(carrierGroupCoordinates.Value, travelMinMax, carrierPathDeg); if (ShapeManager.IsPosValid(destinationPath.Value, theaterDB.WaterCoordinates, theaterDB.WaterExclusionCoordinates)) { break; } iteration++; if (iteration > 10) { maxDistance += 1; } } if (!carrierGroupCoordinates.HasValue) { throw new BriefingRoomException($"Carrier spawnpoint could not be found."); } if (!destinationPath.HasValue) { throw new BriefingRoomException($"Carrier destination could not be found."); } if (!ShapeManager.IsPosValid(destinationPath.Value, theaterDB.WaterCoordinates, theaterDB.WaterExclusionCoordinates)) { throw new BriefingRoomException($"Carrier waypoint is on shore"); } return(new(carrierGroupCoordinates.Value, destinationPath.Value)); }
private static void GenerateFOB( UnitMaker unitMaker, ZoneMaker zoneMaker, MissionTemplateFlightGroupRecord flightGroup, Dictionary <string, UnitMakerGroupInfo> carrierDictionary, DCSMission mission, MissionTemplateRecord template, Coordinates landbaseCoordinates, Coordinates objectivesCenter) { DBEntryTheater theaterDB = Database.Instance.GetEntry <DBEntryTheater>(template.ContextTheater); if (theaterDB == null) { return; // Theater doesn't exist. Should never happen. } Coordinates?spawnPoint = unitMaker.SpawnPointSelector.GetRandomSpawnPoint( new SpawnPointType[] { SpawnPointType.LandLarge }, landbaseCoordinates, new MinMaxD(5, template.FlightPlanObjectiveDistance), objectivesCenter, new MinMaxD(10, template.FlightPlanObjectiveDistance / 2), template.ContextPlayerCoalition); if (!spawnPoint.HasValue) { BriefingRoom.PrintToLog($"No spawn point found for FOB air defense unit groups", LogMessageErrorLevel.Warning); return; } DBEntryUnit unitDB = Database.Instance.GetEntry <DBEntryUnit>(flightGroup.Carrier); if (unitDB == null) { return; // Unit doesn't exist or is not a carrier } double radioFrequency = 127.5 + carrierDictionary.Count; var FOBNames = new List <string> { "FOB_London", "FOB_Dallas", "FOB_Paris", "FOB_Moscow", "FOB_Berlin" }; UnitMakerGroupInfo?groupInfo = unitMaker.AddUnitGroup( unitDB.Families[0], 1, Side.Ally, "GroupStatic", "UnitStaticFOB", spawnPoint.Value, 0, "FOBCallSignIndex".ToKeyValuePair(FOBNames.IndexOf(flightGroup.Carrier) + 1), "RadioBand".ToKeyValuePair((int)RadioModulation.AM), "RadioFrequency".ToKeyValuePair(GeneratorTools.GetRadioFrenquency(radioFrequency))); if (!groupInfo.HasValue || (groupInfo.Value.UnitsID.Length == 0)) { return; // Couldn't generate group } zoneMaker.AddCTLDPickupZone(spawnPoint.Value, true); mission.Briefing.AddItem( DCSMissionBriefingItemType.Airbase, $"{unitDB.UIDisplayName}\t-\t{GeneratorTools.FormatRadioFrequency(radioFrequency)}\t\t"); carrierDictionary.Add(flightGroup.Carrier, groupInfo.Value); // This bit limits FOBS to one per game think about how we can fix this }
internal void GenerateMissionFeature(DCSMission mission, string featureID, string objectiveName, int objectiveIndex, int objectiveGroupID, Coordinates objectiveCoordinates, Side objectiveTargetSide, bool hideEnemy = false) { DBEntryFeatureObjective featureDB = Database.Instance.GetEntry <DBEntryFeatureObjective>(featureID); if (featureDB == null) // Feature doesn't exist { BriefingRoom.PrintToLog($"Objective feature {featureID} not found.", LogMessageErrorLevel.Warning); return; } double spawnDistance = Math.Max(1.0, featureDB.UnitGroupSpawnDistance) * Toolbox.NM_TO_METERS; Coordinates coordinates; if (featureDB.UnitGroupFlags.HasFlag(FeatureUnitGroupFlags.SpawnOnObjective)) { coordinates = objectiveCoordinates + Coordinates.CreateRandom(10, 50); } else { Coordinates?spawnPoint = _unitMaker.SpawnPointSelector.GetRandomSpawnPoint( featureDB.UnitGroupValidSpawnPoints, objectiveCoordinates, new MinMaxD(spawnDistance * .75, spawnDistance * 1.5)); if (!spawnPoint.HasValue) // No spawn point found { BriefingRoom.PrintToLog($"No spawn point found for objective feature {featureID}.", LogMessageErrorLevel.Warning); return; } coordinates = spawnPoint.Value; } Coordinates coordinates2 = coordinates + Coordinates.CreateRandom(10, 20) * Toolbox.NM_TO_METERS; Dictionary <string, object> extraSettings = new Dictionary <string, object>(StringComparer.InvariantCultureIgnoreCase); extraSettings.AddIfKeyUnused("ObjectiveName", objectiveName); extraSettings.AddIfKeyUnused("ObjectiveIndex", objectiveIndex + 1); extraSettings.AddIfKeyUnused("ObjectiveGroupID", objectiveGroupID); if (featureID == "TargetDesignationLaser") { var laserCode = _template.OptionsMission.Contains("SingleLaserCode") ? 1688 : getNextLaserCode(); extraSettings.AddIfKeyUnused("LASERCODE", laserCode); mission.Briefing.AddItem(DCSMissionBriefingItemType.JTAC, $"{objectiveName}\t{laserCode}"); } UnitMakerGroupInfo?groupInfo = AddMissionFeature( featureDB, mission, coordinates, coordinates2, ref extraSettings, objectiveTargetSide, hideEnemy); AddBriefingRemarkFromFeature(featureDB, mission, false, groupInfo, extraSettings); }
/// <summary> /// Sets teh second point /// </summary> /// <param name="p1"></param> /// <param name="secondaryTool"></param> public void VSetP2(Coordinates p2, IEditorTool secondaryTool) { this.p2 = p2; this.SetP2 = true; if (secondaryTool != null && secondaryTool is PointAnalysisTool) { PointAnalysisTool pat = (PointAnalysisTool)secondaryTool; pat.Save.Add(p2); } }
private Coordinates?GetLandCoordinates( SpawnPointType[] validTypes, Coordinates distanceOrigin1, MinMaxD distanceFrom1, Coordinates?distanceOrigin2 = null, MinMaxD?distanceFrom2 = null, Coalition?coalition = null ) { var validSP = (from DBEntryTheaterSpawnPoint pt in SpawnPoints where validTypes.Contains(pt.PointType) select pt); Coordinates?[] distanceOrigin = new Coordinates?[] { distanceOrigin1, distanceOrigin2 }; MinMaxD?[] distanceFrom = new MinMaxD?[] { distanceFrom1, distanceFrom2 }; for (int i = 0; i < 2; i++) // Remove spawn points too far or too close from distanceOrigin1 and distanceOrigin2 { if (validSP.Count() == 0) { return(null); } if (!distanceFrom[i].HasValue || !distanceOrigin[i].HasValue) { continue; } var searchRange = distanceFrom[i].Value * Toolbox.NM_TO_METERS; // convert distance to meters IEnumerable <DBEntryTheaterSpawnPoint> validSPInRange = (from DBEntryTheaterSpawnPoint s in validSP select s); int iterationsLeft = MAX_RADIUS_SEARCH_ITERATIONS; do { Coordinates origin = distanceOrigin[i].Value; validSPInRange = (from DBEntryTheaterSpawnPoint s in validSP where searchRange.Contains(origin.GetDistanceFrom(s.Coordinates)) && CheckNotInHostileCoords(s.Coordinates, coalition) select s); searchRange = new MinMaxD(searchRange.Min * 0.9, Math.Max(100, searchRange.Max * 1.1)); validSP = (from DBEntryTheaterSpawnPoint s in validSPInRange select s); iterationsLeft--; } while ((validSPInRange.Count() == 0) && (iterationsLeft > 0)); } if (validSP.Count() == 0) { return(null); } DBEntryTheaterSpawnPoint selectedSpawnPoint = Toolbox.RandomFrom(validSP.ToArray()); SpawnPoints.Remove(selectedSpawnPoint); // Remove spawn point so it won't be used again return(selectedSpawnPoint.Coordinates); }
internal Coordinates?GetRandomSpawnPoint( SpawnPointType[] validTypes, Coordinates distanceOrigin1, MinMaxD distanceFrom1, Coordinates?distanceOrigin2 = null, MinMaxD?distanceFrom2 = null, Coalition?coalition = null) { if (validTypes.Contains(SpawnPointType.Air) || validTypes.Contains(SpawnPointType.Sea)) { return(GetAirOrSeaCoordinates(validTypes, distanceOrigin1, distanceFrom1, distanceOrigin2, distanceFrom2, coalition)); } return(GetLandCoordinates(validTypes, distanceOrigin1, distanceFrom1, distanceOrigin2, distanceFrom2, coalition)); }
public void SetDistanceAway_StateUnderTest_ExpectedBehavior() { // Arrange var businessResponse = new BusinessResponse(); Coordinates?loc = null; // Act businessResponse.SetDistanceAway(loc); // Assert Assert.IsNotNull(businessResponse); }
public bool Equals(Coordinates?other) { if (ReferenceEquals(null, other)) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return(RowIndex == other.RowIndex && ColumnIndex == other.ColumnIndex); }
public void GetDistanceTo_StateUnderTest_ExpectedBehavior() { // Arrange var businessResponse = new BusinessResponse(); Coordinates?loc = null; // Act var result = businessResponse.GetDistanceTo(loc); // Assert Assert.IsNotNull(businessResponse); }
/// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns>true if the current object is equal to the <paramref name="other">other</paramref> parameter; otherwise, false.</returns> /// <autogeneratedoc /> public bool Equals(Coordinates?other) { if (ReferenceEquals(null, other)) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return(Latitude.Equals(other.Latitude) && Longitude.Equals(other.Longitude)); }
/// <summary> /// Sets teh first point /// </summary> /// <param name="p1"></param> /// <param name="secondaryTool"></param> public void VSetP1(Coordinates p1, IEditorTool secondaryTool) { this.SetP1 = true; this.p1 = p1; if (secondaryTool != null && secondaryTool is PointAnalysisTool) { PointAnalysisTool pat = (PointAnalysisTool)secondaryTool; pat.Save = new List <Coordinates>(); pat.Save.Add(p1); } }
private Coordinates?GetAirOrSeaCoordinates( SpawnPointType[] validTypes, Coordinates distanceOrigin1, MinMaxD distanceFrom1, Coordinates?distanceOrigin2 = null, MinMaxD?distanceFrom2 = null, Coalition?coalition = null) { var searchRange = distanceFrom1 * Toolbox.NM_TO_METERS; MinMaxD?secondSearchRange = null; if (distanceOrigin2.HasValue && distanceFrom2.HasValue) { secondSearchRange = distanceFrom2.Value * Toolbox.NM_TO_METERS; } var iterations = 0; do { var coordOptionsLinq = Enumerable.Range(0, 50) .Select(x => Coordinates.CreateRandom(distanceOrigin1, searchRange)) .Where(x => CheckNotInHostileCoords(x, coalition) && CheckNotInNoSpawnCoords(x)); if (secondSearchRange.HasValue) { coordOptionsLinq = coordOptionsLinq.Where(x => secondSearchRange.Value.Contains(distanceOrigin2.Value.GetDistanceFrom(x))); } if (validTypes.First() == SpawnPointType.Sea) //sea position { coordOptionsLinq = coordOptionsLinq.Where(x => ShapeManager.IsPosValid(x, TheaterDB.WaterCoordinates, TheaterDB.WaterExclusionCoordinates)); } var coordOptions = coordOptionsLinq.ToList(); if (coordOptions.Count > 0) { return(Toolbox.RandomFrom(coordOptions)); } searchRange = new MinMaxD(searchRange.Min * 0.9, searchRange.Max * 1.1); if (secondSearchRange.HasValue) { secondSearchRange = new MinMaxD(secondSearchRange.Value.Min * 0.9, secondSearchRange.Value.Max * 1.1); } iterations++; } while (iterations < MAX_RADIUS_SEARCH_ITERATIONS); return(null); }
private string SetupTryDeliverStock(Coordinates?coords, decimal?credit) { // arrange ConditionallyAssignCredit(credit); if (coords.HasValue) { controlUnit.State.SelectProduct(coords.Value); } Action action = () => controlUnit.State.TryDeliverProduct(); // act return(TestHelperMethods.CaptureConsoleOutput(action)); }
private Coordinates GetNearestSpawnCoordinates(MissionTemplateRecord template, Coordinates coreCoordinates, DBEntryObjectiveTarget targetDB) { Coordinates?spawnPoint = UnitMaker.SpawnPointSelector.GetNearestSpawnPoint( targetDB.ValidSpawnPoints, coreCoordinates); if (!spawnPoint.HasValue) { throw new BriefingRoomException($"Failed to spawn objective unit group. {String.Join(",", targetDB.ValidSpawnPoints.Select(x => x.ToString()).ToList())} Please try again (Consider Adusting Flight Plan)"); } Coordinates objectiveCoordinates = spawnPoint.Value; return(objectiveCoordinates); }
/// <summary> /// Resets values /// </summary> /// <param name="secondaryTool"></param> public void Reset(IEditorTool secondaryTool) { this.p1 = null; this.p2 = null; this.p3 = null; this.SetP1 = false; this.SetP2 = false; this.SetP3 = false; if (secondaryTool != null && secondaryTool is PointAnalysisTool) { PointAnalysisTool pat = (PointAnalysisTool)secondaryTool; pat.Save = new List <Coordinates>(); } }
/// <summary> /// What to do when mouse button is lifted up /// </summary> /// <param name="e"></param> protected override void OnMouseUp(MouseEventArgs e) { #region Left if (e.Button == MouseButtons.Left) { if (this.selected != null && this.selected is CarDisplayObject && this.isDragging) { this.isDragging = false; this.temporaryCoordinate = null; Cursor.Current = Cursors.Default; } else if (this.selected != null && this.selected is SimObstacle && this.isDragging) { this.isDragging = false; this.temporaryCoordinate = null; Cursor.Current = Cursors.Default; } // if the user is dragging else if (isDragging) { isDragging = false; Cursor.Current = Cursors.Default; } // redraw this.Invalidate(); } #endregion #region Right if (e.Button == MouseButtons.Left) { if (this.selected != null && this.selected is SimObstacle && this.isDragging && this.temporaryCoordinate.HasValue) { this.isDragging = false; this.temporaryCoordinate = null; Cursor.Current = Cursors.Default; } } #endregion base.OnMouseUp(e); }
static void Main(string[] args) { string boundsInput; List <Rover> rovers = new List <Rover>(); Console.WriteLine("Please enter the Bounds"); boundsInput = Console.ReadLine(); GlobalBounds = InputValidator.ValidateBoundsInputAndReturnCoordinates(boundsInput); if (GlobalBounds != null) { Console.WriteLine("Enter the # of Rovers"); var numOfRovers = int.Parse(Console.ReadLine()); for (int i = 0; i < numOfRovers; i++) { Console.WriteLine("Enter the Current Postion for Rover " + i); var initialPosition = InputValidator.ValidateRoverCurrentLocation(Console.ReadLine()); if (initialPosition != null) { var rover = new Rover(initialPosition.Value.Coords, initialPosition.Value.Direction); rovers.Add(rover); Console.WriteLine("\n"); Console.WriteLine("Enter the Instructions for Rover " + i); var instructions = InputValidator.ValidateInstructions(Console.ReadLine()); if (instructions != null && instructions.Length > 0) { rovers[i].Navigate(instructions); } } } Console.WriteLine("\n"); for (int i = 0; i < rovers.Count; i++) { Console.WriteLine(string.Format("Rover {0} Coordinates {1} {2} {3}", i, rovers[i].CurrentCoordinates.X, rovers[i].CurrentCoordinates.Y, rovers[i].CurrentDirection)); } } }
void SetFieldQueryClientSystem(Coordinates?point) { if (point == null) { Debug.LogErrorFormat("There is no SpawnPoint type:{0}", SpawnType.Start); return; } this.startPoint = point.Value; var pos = startPoint.ToUnityVector(); var fieldSystem = Worker.World.GetExistingSystem <FieldQueryClientSystem>(); if (fieldSystem != null) { fieldSystem.OnQueriedEvent += CreatePlayerRequest; fieldSystem.SetXZPosition(pos.x, pos.z); } }
private void HandlePositionPicking() { if (!MapView.MapIsEnabled || !this.vessel.isActiveVessel) { // No longer in map mode. StopPickingVirtualTarget(keepTarget: false); return; } CelestialBody pickingBody = this.m_virtualTarget.Location.Body; MapObject planetariumTarget = PlanetariumCamera.fetch.target; if (planetariumTarget.celestialBody != pickingBody || this.CurrentBody != pickingBody) { StopPickingVirtualTarget(keepTarget: false); return; } Coordinates?mouseCoords = pickingBody.GetMouseCoordinates(); if (mouseCoords == null) { Screen.showCursor = true; this.m_isMouseOverPickingBody = false; return; } // Position to pick. Screen.showCursor = false; this.m_isMouseOverPickingBody = true; // ReSharper disable once PossibleNullReferenceException this.m_virtualTarget.SetLocation(new GlobalLocation(pickingBody, mouseCoords.Value)); // IMPORTANT: Don't cancel on right click as the right mouse button is used // to rotate the camera. // IMPORTANT: We need to use "ButtonDown" here (instead of "ButtonUp"). Otherwise // "ButtonUp" would immediately be true after start picking (because this is triggered // by "ButtonUp" in the same frame). if (Input.GetMouseButtonDown(MouseButtons.Left)) { StopPickingVirtualTarget(keepTarget: true); } }
/// <summary> /// Check where turns intersect the subpath furthese along it /// </summary> /// <param name="aiSubpath"></param> /// <param name="iTraversableWaypoint"></param> /// <returns></returns> private Coordinates?TurnIntersects(LinePath aiSubpath, ITraversableWaypoint iTraversableWaypoint, out ArbiterInterconnect interconnect) { Line aiSub = new Line(aiSubpath.StartPoint.Location, aiSubpath.EndPoint.Location); double distance = 0.0; Coordinates?furthest = null; interconnect = null; foreach (ArbiterInterconnect ai in iTraversableWaypoint.OutgoingConnections) { Line iLine = new Line(ai.InterconnectPath.StartPoint.Location, ai.InterconnectPath.EndPoint.Location); Coordinates intersect; bool doesIntersect = aiSub.Intersect(iLine, out intersect); if (doesIntersect && (ai.IsInside(intersect) || ai.InterconnectPath.GetClosestPoint(intersect).Equals(ai.InterconnectPath.EndPoint))) { if (!furthest.HasValue) { furthest = intersect; distance = intersect.DistanceTo(aiSubpath.EndPoint.Location); interconnect = ai; } else { double tmpDist = intersect.DistanceTo(aiSubpath.EndPoint.Location); if (tmpDist < distance) { furthest = intersect; distance = tmpDist; interconnect = ai; } } } } if (furthest.HasValue) { return(furthest.Value); } else { return(null); } }
/// <summary> /// Gets the distance away from a specified location object. /// </summary> /// <param name="loc">Location object to calculate distance away with.</param> /// <returns>Distance amount.</returns> public double GetDistanceTo(Coordinates?loc) { if (loc != null) { var r = IsMetric ? 6371 : 3960; var dLat = ToRadian(this.Coordinates?.Latitude ?? 0 - loc.Latitude); var dLon = ToRadian(this.Coordinates?.Longitude ?? 0 - loc.Longitude); var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(ToRadian(loc.Latitude)) * Math.Cos(ToRadian(this.Coordinates?.Latitude ?? 0)) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2); var c = 2 * Math.Asin(Math.Min(1, Math.Sqrt(a))); var d = r * c; return(Math.Round(d, DistanceDecimalPlaces)); } else { return(double.NaN); } }
internal void AddCTLDPickupZone(Coordinates coordinates, bool onTop = false) { var coords = coordinates; if (!onTop) { var spawnPoints = new List <SpawnPointType> { SpawnPointType.LandLarge }.ToArray(); Coordinates?newCoords = _unitMaker.SpawnPointSelector.GetNearestSpawnPoint(spawnPoints, coordinates); if (!newCoords.HasValue) { throw new BriefingRoomException("Can't find suitable zone Coordinates!"); } coords = newCoords.Value; } AddToList($"pickzone{CTLDZoneCount}", coords, 500); CTLDZoneCount++; }
internal void GenerateMissionFeature(DCSMission mission, string featureID, Coordinates initialCoordinates, Coordinates objectivesCenter) { DBEntryFeatureMission featureDB = Database.Instance.GetEntry <DBEntryFeatureMission>(featureID); if (featureDB == null) // Feature doesn't exist { BriefingRoom.PrintToLog($"Mission feature {featureID} not found.", LogMessageErrorLevel.Warning); return; } Coalition coalition = featureDB.UnitGroupFlags.HasFlag(FeatureUnitGroupFlags.Friendly) ? _template.ContextPlayerCoalition : _template.ContextPlayerCoalition.GetEnemy(); Coordinates pointSearchCenter = Coordinates.Lerp(initialCoordinates, objectivesCenter, featureDB.UnitGroupSpawnDistance); Coordinates?spawnPoint = _unitMaker.SpawnPointSelector.GetRandomSpawnPoint( featureDB.UnitGroupValidSpawnPoints, pointSearchCenter, featureDB.UnitGroupFlags.HasFlag(FeatureUnitGroupFlags.AwayFromMissionArea) ? new MinMaxD(50, 100) : new MinMaxD(0, 5), coalition: featureDB.UnitGroupFlags.HasFlag(FeatureUnitGroupFlags.IgnoreBorders) ? null : coalition ); if (!spawnPoint.HasValue) // No spawn point found { BriefingRoom.PrintToLog($"No spawn point found for mission feature {featureID}.", LogMessageErrorLevel.Warning); return; } var goPoint = spawnPoint.Value; if (featureDB.UnitGroupFlags.HasFlag(FeatureUnitGroupFlags.MoveTowardObjectives)) { goPoint = objectivesCenter; } else if (featureDB.UnitGroupFlags.HasFlag(FeatureUnitGroupFlags.MoveTowardPlayerBase)) { goPoint = initialCoordinates; } Coordinates coordinates2 = goPoint + Coordinates.CreateRandom(5, 20) * Toolbox.NM_TO_METERS; Dictionary <string, object> extraSettings = new Dictionary <string, object>(); UnitMakerGroupInfo? groupInfo = AddMissionFeature(featureDB, mission, spawnPoint.Value, coordinates2, ref extraSettings); AddBriefingRemarkFromFeature(featureDB, mission, false, groupInfo, extraSettings); }
/// <summary> /// finish the wrapping and cretae the intersection /// </summary> public void FinalizeIntersection() { // finalize the intersection polygon Polygon sq = this.CreateSquarePolygon(this.WrapInitial.Value, this.WrapFinal.Value).Inflate(1.0); Polygon interPoly = this.CreateIntersectionPolygon(sq); // check poly not null if (interPoly != null) { // inflate the inter poly interPoly = interPoly.Inflate(0.05); // retreive all exits involved in this intersection Dictionary<IAreaSubtypeWaypointId, ITraversableWaypoint> exits = this.IntersectionExits(sq); // make sure the inter contains an exit if (exits.Count > 0) { // make stopped exits, necessarily these are arbiter waypoints not perimeter points List<ArbiterStoppedExit> ases = this.CreateStoppedExits(exits.Values); // construct intersection id ITraversableWaypoint[] exitArray = new ITraversableWaypoint[exits.Count]; exits.Values.CopyTo(exitArray, 0); ArbiterIntersectionId aii = new ArbiterIntersectionId(exitArray[0].Exits[0].InterconnectId); // determine incoming lanes Dictionary<ArbiterLane, LinePath.PointOnPath> incoming = this.DetermineIncoming(interPoly); // create the intersection ArbiterIntersection ai = new ArbiterIntersection( interPoly, ases, this.DetermineInvolved(exits.Values, incoming), incoming, exits, interPoly.Center, aii, arn, this.IntersectionEntries(sq) ); // create safety zones this.CreateSafetyImplicitZones(ai); // update poly //this.UpdateIntersectionPolygon(ai); /*List<Polygon> ps = new List<Polygon>(); foreach (ITraversableWaypoint itw in exits.Values) { foreach (ArbiterInterconnect ait in itw.Exits) { ps.Add(ait.TurnPolygon); } } ai.IntersectionPolygon = this.GetIntersectionPolygon(ps, ai.AllExits, ai.AllEntries);*/ //ai.IntersectionPolygon = UrbanChallenge.Arbiter.Core.Common.Tools.PolygonToolkit.PolygonUnion(ps); try { List<Polygon> ps = new List<Polygon>(); foreach (ITraversableWaypoint itw in exits.Values) { foreach (ArbiterInterconnect ait in itw.Exits) { ps.Add(ait.TurnPolygon); } } ai.IntersectionPolygon = this.GetIntersectionPolygon(ps, ai.AllExits, ai.AllEntries); if (ai.IntersectionPolygon.IsComplex) { EditorOutput.WriteLine("Intersection polygon complex, defaulting"); throw new Exception("complex polygon exception"); } } catch (Exception) { EditorOutput.WriteLine("Error in union polygon generation, using better default"); try { this.UpdateIntersectionPolygon(ai); } catch (Exception) { EditorOutput.WriteLine("Error in my simple polygon generation, plain default"); List<Coordinates> cs = new List<Coordinates>(); foreach (ITraversableWaypoint itw in ai.AllEntries.Values) cs.Add(itw.Position); foreach (ITraversableWaypoint itw in ai.AllExits.Values) { cs.Add(itw.Position); foreach (ArbiterInterconnect aint in itw.Exits) { cs.AddRange(aint.TurnPolygon); } } ai.IntersectionPolygon = Polygon.GrahamScan(cs); } } try { // add intersection arn.ArbiterIntersections.Add(aii, ai); // add to exit lookup foreach (IAreaSubtypeWaypointId awi in exits.Keys) { if (arn.IntersectionLookup.ContainsKey(awi)) arn.IntersectionLookup[awi] = ai; else arn.IntersectionLookup.Add(awi, ai); } // add to display objects arn.DisplayObjects.Add(ai); rd.AddDisplayObject(ai); } catch (Exception e) { EditorOutput.WriteLine("Error adding intersection: " + aii.ToString()); EditorOutput.WriteLine("Error adding intersection: " + e.ToString()); } } } // reset the tool this.it.ResetIcons(); this.WrapFinal = null; this.WrapInitial = null; }
/// <summary> /// What to do when user clicks display /// </summary> /// <param name="e"></param> protected override void OnMouseDown(MouseEventArgs e) { #region Hit Test // filter for vehicles or obstacles DisplayObjectFilter dof = delegate(IDisplayObject target) { // check if target is network object if (target is CarDisplayObject || target is SimObstacle) return true; else return false; }; // perform the hit test over the filter HitTestResult htr = this.HitTest(transform.GetWorldPoint(new PointF(e.X, e.Y)), dof); // check current selection if need to set as not selected if (this.selected != null && (htr.Hit && !this.selected.Equals(htr.DisplayObject)) || (!htr.Hit)) { if (this.selected != null) { // remove current selection this.selected.Selected = SelectionType.NotSelected; } this.selected = null; this.Simulation.simEngine.SetPropertyGridDefault(); } #endregion #region Left if (e.Button == MouseButtons.Left) { // check if we hit a vehicle if (htr.Hit && htr.DisplayObject is SimVehicle) { // display obj CarDisplayObject cdo = (CarDisplayObject)htr.DisplayObject; // set the vehicles as selected cdo.Selected = SelectionType.SingleSelected; this.selected = cdo; this.Simulation.simEngine.propertyGrid.SelectedObject = cdo; // check if we can move the vehicle if (!((SimVehicle)cdo).VehicleState.IsBound) { // set dragging isDragging = true; Cursor.Current = Cursors.Hand; // set temp this.temporaryCoordinate = cdo.Position; } // redraw this.Invalidate(); } // check if hit obstacle else if (htr.Hit && htr.DisplayObject is SimObstacle) { // set selected this.selected = htr.DisplayObject; this.selected.Selected = SelectionType.SingleSelected; this.Simulation.simEngine.propertyGrid.SelectedObject = this.selected; // check if can move if (((SimObstacle)htr.DisplayObject).MoveAllowed) { // set dragging isDragging = true; Cursor.Current = Cursors.Hand; // set temp this.temporaryCoordinate = ((SimObstacle)this.selected).Position; } // redraw this.Invalidate(); } else { controlTag = new Point(e.X, e.Y); isDragging = true; Cursor.Current = Cursors.Hand; } } #endregion #region Right else if (e.Button == MouseButtons.Right) { if (htr.Hit && htr.DisplayObject is CarDisplayObject) { this.selected = htr.DisplayObject; this.Simulation.simEngine.propertyGrid.SelectedObject = this.selected; this.vehicleContextMenuStrip1.Show(this, e.X, e.Y); ((CarDisplayObject)this.selected).Selected = SelectionType.SingleSelected; } else if (htr.Hit && htr.DisplayObject is SimObstacle) { // set selected this.selected = htr.DisplayObject; this.selected.Selected = SelectionType.SingleSelected; this.Simulation.simEngine.propertyGrid.SelectedObject = this.selected; // check if we can move the obstacle if (((SimObstacle)htr.DisplayObject).MoveAllowed) { // set dragging isDragging = true; Cursor.Current = Cursors.Hand; // set temp this.temporaryCoordinate = transform.GetWorldPoint(new PointF(e.X, e.Y)) - ((SimObstacle)this.selected).Position; } // redraw this.Invalidate(); } } #endregion base.OnMouseDown(e); this.Invalidate(); }
public DNode() { val = 1.0 / 0.0; prev = null; visited = false; }