示例#1
0
 Waypoints[] ConvertTargets(Object[] targets)
 {
     Waypoints[] result =new Waypoints[targets.Length];
     for(int i = 0; i < targets.Length; i++){
         result[i] = targets[i] as Waypoints;
     }
     return result;
 }
示例#2
0
 // Use this for initialization
 void Start()
 {
     // FIXME Set target should be called from another script
     SetTarget(Target);
     GotCar = false;
     GameObject WaypointObject = GameObject.Find("Waypoints");
     WaypointScript = WaypointObject.GetComponent<Waypoints>();
 }
示例#3
0
 // Use this for initialization
 void Awake()
 {
     if(!next){
         Debug.LogWarning("There is no next waypoint");
     }
     if(isStart){
         start = this;
     }
 }
        public void Save_CheckIfTheItemsArePersist_ResultTheSameTripCollection()
        {
            WaypointsRepository repository = WaypointsRepositoryFactory.Create();

            Waypoints waypoints = new Waypoints();
            waypoints.Add(CreateWaypoint());

            Task.Run(() => repository.SaveAsync(waypoints)).Wait();

            Waypoints savedWaypoints = null;
            Task.Run(() => savedWaypoints = repository.LoadAsync().Result).Wait();

            Assert.AreEqual(1, savedWaypoints.Count);
            Assert.IsNotNull(savedWaypoints[0].Position);
        }
示例#5
0
    void Update()
    {
        //direçao atual
        Vector3 dir =
            destino-this.transform.position;
        //anula o y
        dir.y = 0;

        //se a distancia (magnitude) for pequena, chegou no destino
        if(dir.magnitude < 0.5f){

            //escolhe um destino aleatorio
            //isso pode virar uma funçao que escolhe algum dos waypoints a frente dele
            //se nao tiver nenhum waypoint na frente dele ai sim ele pode escolher algum atraz
            way = way.nexts[Random.Range(0,way.nexts.Count)];

            //nova direçao pro novo alvo
            Vector3 newDir =
                (way.transform.position-
                    this.transform.position).normalized;

            //o destino fica ao lado do waypoint
            //so pegar a direçao e girar 90º em y
            //pra girar um vetor vc multiplica por um quaternion
            //o desvio diz quanto vai desviar pro lado (positivo ou negativo)
            destino = way.transform.position +
                Quaternion.Euler(0,90,0) * newDir * desvio;

            //guarda a nova direçao ignorando o y
            dir = newDir;
            dir.y = 0;

        }

        //rotaciona o personagem para ficar de frente pro destino
        this.transform.rotation = Quaternion.LookRotation(dir, Vector3.up);

        //usa a velocidade atual e muda apenas x e z
        //o y e controlado pela gravidade
        Vector3 vel = this.GetComponent<Rigidbody>().velocity;
        dir = dir.normalized;
        vel.x = dir.x * speed;
        vel.z = dir.z * speed;
        this.GetComponent<Rigidbody>().velocity = vel;
    }
示例#6
0
        public MainPageViewModel(IUiService uiService, MenuBarViewModel menuBarViewModel)
            : base(uiService)
        {
            AddLocationsPopup = menuBarViewModel;

            IsAddLocationsPopupVisible = false;
            LoadAddLocationsPopupMenuItems();

            DisplayName = "Where Am I";

            WaypointsRepository repository = WaypointsRepositoryFactory.Create();
            Waypoints waypoints = new Waypoints();
            waypoints.Add(CreateWaypoint());

            Waypoints savedWaypoints = null;
            Task.Run(() => savedWaypoints = repository.LoadAsync().Result).Wait();

            //TODO: Delete!!!
            if (savedWaypoints.Count == 0)
            {
                savedWaypoints.PopulateWithMockData();
                repository.SaveAsync(savedWaypoints);
            }

            WaypointList = new ObservableCollection<Waypoint>(savedWaypoints.ToArray());
            var location = GetCurrentLocation();
            if (location == null)
            {
                MessageDialog message = new MessageDialog("GPSLocationNotResolved");
                Task.Run(() => message.ShowAsync()).Wait();
            }
            else
            {
                CurrentLocationLatitude = location.Latitude;
                CurrentLocationLongitude = location.Longitude;
            }
        }
示例#7
0
 void Start()
 {
     Wpoints      = GameObject.FindGameObjectWithTag("Waypoints").GetComponent <Waypoints>();
     maxIndex     = Wpoints.waypoints.Length;
     timeBtwShots = startTimeBtwShots;
 }
示例#8
0
        }   // end of GenerateMap

        #endregion

        #region Search Target

        /// <summary>
        /// Search target mode
        /// </summary>

        void SearchTarget()
        {
            WayPoint nextWaypoint = null;

            //set behavior
            //if (TargetFound)
            //{
            //    State = DriveState.GotoBall;
            //    return;
            //}
            if (Waypoints.Count == 0 && usePathGen && !goToSafe)
            {
                State    = DriveState.GenerateSearchPath;
                Speed    = 0;
                Steering = 0;
                GenerateSearchPath();
                usePathGen = false;
                goToSafe   = true;
                State      = DriveState.SearchTarget;
            }
            else if (Waypoints.Count == 0 && !usePathGen)
            {
                //State = DriveState.Idle;
            }
            if (Waypoints.Count > 0 && Waypoints.TryPeek(out nextWaypoint))
            {
                if (nextWaypoint != null)
                {
                    WayPoint currentLocation = new WayPoint(Latitude, Longitude, 0);
                    WaypointVector       = new Vector2d(currentLocation, nextWaypoint);
                    NextWaypointDistance = WayPoint.GetDistance(this.Latitude, this.Longitude, nextWaypoint.Lat, nextWaypoint.Long);

                    //// ************* Obstacle Avoidance Code ******************
                    nextWaypoint = obstacleAvoidance(nextWaypoint, currentLocation);
                    // Everything is in meters and radians
                    //if (Settings.UseVision)
                    //{
                    //    if (AvoidanceVector.magnitude > 0)
                    //    {
                    //        SumVector = new Vector2d(currentLocation, nextWaypoint);
                    //        SumVector.magnitude /= SumVector.magnitude; //Normalize(Check if normalize is needed)
                    //        SumVector.magnitude *= Alpha * MaxSpeed; // Influence(Check if maxspeed is needed)
                    //        AvoidanceVector.angle = (AvoidanceVector.angle + 90 + Heading);// Make Lidar data relative to robot position
                    //        SumVector += AvoidanceVector; //combine Avoidance and Attraction vector
                    //        SumVector.magnitude = Math.Max(ReachWaypointZone + 1, SumVector.magnitude); //set the minimum vector length to 4 meters
                    //        nextWaypoint = WayPoint.Projection(currentLocation, SumVector.angle, SumVector.magnitude);
                    //    }

                    //}

                    /*if (Settings.DriveMode == DriveMode.Autonomous)
                     * {
                     *  Speed =
                     * }*/
                    NextWaypointBearing = WayPoint.GetBearing(this.Latitude, this.Longitude, nextWaypoint.Lat, nextWaypoint.Long);
                    //calculate difference angle
                    double errorWaypoint = NextWaypointBearing - Heading;
                    if (errorWaypoint > Math.PI)
                    {
                        errorWaypoint -= Math.PI * 2.0;
                    }
                    else if (errorWaypoint < -Math.PI)
                    {
                        errorWaypoint += Math.PI * 2.0;
                    }
                    NextWaypointBearingError = errorWaypoint;
                }
                //else
                // State = DriveState.Idle;

                if (imu.GoodData)
                {
                    //if use gps only to drive
                    //apply steer control
                    double TempSteering = NextWaypointBearingError * SteerRatio / Math.PI;
                    // SteerPID.Feed(error);
                    Steering = CloseBoundary ? Math.Min(Math.Max(TempSteering, -1000), 1000)
                                        : Math.Min(Math.Max(TempSteering * OutsideSteerRatio, -1000), 1000);
                    //set speed
                    Speed = InsideBoundary ? FullSpeed : FullSpeed * OutsideSpeedRatio;
                }
                else
                {
                    //set all to 0 if no gps lock
                    Speed    = 0;
                    Steering = 0;
                }
                //only reach target when drive auto
                if (Settings.DriveMode == DriveMode.Autonomous || Settings.DriveMode == DriveMode.SemiAutonomous)
                {
                    //check if reached
                    if (NextWaypointDistance < ReachWaypointZone)
                    {
                        Waypoints.TryDequeue(out nextWaypoint);
                    }

                    //TargetDistance = WayPoint.GetDistance(this.Latitude, this.Longitude, TargetWaypoint.Lat, TargetWaypoint.Long);

                    //if (TargetDistance < ReachWaypointZone)
                    //    State=DriveState.GrabPayloadManual;
                }
            }
            else
            {
                Speed    = 0;
                Steering = 0;
                State    = DriveState.Idle;
            }
        }
 private void OnDeleteSelectedItem(object obj)
 {
     WaypointList.Remove(SelectedWaypointItem);
     var availableWaipoints = new Waypoints();
     availableWaipoints.AddRange(WaypointList);
     Task.Run(() => _repository.SaveAsync(availableWaipoints));
     NotifyOfPropertyChange(() => WaypointList);
 }
示例#10
0
 public void AddWaypoint (TrackPoint waypoint)
 {
     Waypoints.Add (waypoint);
 }
    private void SpawnSpheres()
    {
        float dx = -54.7146f;
        float dy = y;
        float dz = z;

        for (var i = 0; i < 8; i++)
        {
            var o = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            o.tag = "Drug";
            o.transform.localScale = new Vector3(SphereSize, SphereSize, SphereSize);

            var          color = new Color(200, 0, 0, 255);
            MeshRenderer gameObjectRenderer = o.GetComponent <MeshRenderer>();

            Material newMaterial = new Material(Shader.Find("Standard"));
            newMaterial.color           = color;
            gameObjectRenderer.material = newMaterial;

            o.AddComponent <Movement>();
            var parent = GameObject.Find("Panel17").transform;
            o.transform.parent = parent;
            Movement so = o.GetComponent <Movement>();
            so.lerpTime = so.lerpTime - subtract;

            o.transform.localScale = new Vector3(2f, 2f, 2f);

            if (i % 2 == 0)
            {
                so.waypoints = Waypoints.GetWaypoints("Urinary");
                o.transform.localPosition = new Vector3(-54.7146f, 2.1792f, -267.04f);
            }

            else
            {
                so.waypoints = Waypoints.GetWaypoints("Urinary2");
                o.transform.localPosition = new Vector3(-18f, 2.2f, -267.04f);
            }

            subtract -= .15f;



            //o.transform.localPosition = new Vector3(-54.7146f, 2.1792f, -267.04f);
            dx += 2.2f;
        }

        /*for (var i = 0; i < 4; i++)
         * {
         *  //var planePos = GameObject.Find("Plane").bounds;
         *  var o = GameObject.CreatePrimitive(PrimitiveType.Sphere);
         *  o.tag = "Drug";
         *  o.transform.localScale = new Vector3(SphereSize, SphereSize, SphereSize);
         *
         *  var color = new Color(200, 0, 0, 255);
         *  MeshRenderer gameObjectRenderer = o.GetComponent<MeshRenderer>();
         *
         *  Material newMaterial = new Material(Shader.Find("Standard"));
         *  newMaterial.color = color;
         *  gameObjectRenderer.material = newMaterial;
         *
         *  //var type = Type.GetType( "Movement" );
         *  o.AddComponent<Movement>();
         *  var parent = GameObject.Find("Panel17").transform;
         *  o.transform.parent = parent;
         *  Movement mov = o.GetComponent<Movement>();
         *  mov.lerpTime = .5f;
         *
         *  mov.waypoints = Waypoints.GetWaypoints("Urinary2");
         *
         *
         *
         *  o.transform.localScale = new Vector3(2f, 2f, 2f);
         *  o.transform.localPosition = new Vector3(-18f, 2.2f, -267.04f);
         *  dx += 2.2f;
         * }*/
    }
示例#12
0
        protected override QueryStringParametersList GetQueryStringParameters()
        {
            if (string.IsNullOrWhiteSpace(Origin))
            {
                throw new ArgumentException("Must specify an Origin");
            }
            if (string.IsNullOrWhiteSpace(Destination))
            {
                throw new ArgumentException("Must specify a Destination");
            }
            if (!Enum.IsDefined(typeof(AvoidWay), Avoid))
            {
                throw new ArgumentException("Invalid enumeration value for 'Avoid'");
            }
            if (!Enum.IsDefined(typeof(TravelMode), TravelMode))
            {
                throw new ArgumentException("Invalid enumeration value for 'TravelMode'");
            }

            if (TravelMode == TravelMode.Transit && (DepartureTime == default(DateTime) && ArrivalTime == default(DateTime)))
            {
                throw new ArgumentException("You must set either DepatureTime or ArrivalTime when TravelMode = Transit");
            }

            var parameters = base.GetQueryStringParameters();

            parameters.Add("origin", Origin);
            parameters.Add("destination", Destination);
            parameters.Add("mode", TravelMode.ToString().ToLower());

            if (Alternatives)
            {
                parameters.Add("alternatives", "true");
            }

            if (Avoid != AvoidWay.Nothing)
            {
                parameters.Add("avoid", Avoid.ToString().ToLower());
            }

            if (!string.IsNullOrWhiteSpace(Language))
            {
                parameters.Add("language", Language);
            }

            if (!string.IsNullOrWhiteSpace(Region))
            {
                parameters.Add("region", Region);
            }

            if (Waypoints != null && Waypoints.Any())
            {
                IEnumerable <string> waypoints;

                if (OptimizeWaypoints)
                {
                    const string optimizeWaypoints = "optimize:true";

                    waypoints = new string[] { optimizeWaypoints }.Concat(Waypoints);
                }
                else
                {
                    waypoints = Waypoints;
                }

                parameters.Add("waypoints", string.Join("|", waypoints));
            }

            if (ArrivalTime != default(DateTime))
            {
                parameters.Add("arrival_time", UnixTimeConverter.DateTimeToUnixTimestamp(ArrivalTime).ToString(CultureInfo.InvariantCulture));
            }

            if (DepartureTime != default(DateTime))
            {
                parameters.Add("departure_time", UnixTimeConverter.DateTimeToUnixTimestamp(DepartureTime).ToString(CultureInfo.InvariantCulture));
            }

            return(parameters);
        }
示例#13
0
 public SaveResult(Waypoints waypoints)
 {
     _waypoints = waypoints;
 }
示例#14
0
 void Start()
 {
     Wpoints = GameObject.FindGameObjectWithTag("Waypoints").GetComponent <Waypoints>();
 }
示例#15
0
 public Vector2[] GetWaypoints()
 {
     return(Waypoints.ToArray());
 }
示例#16
0
 public void SetWaypoint(Waypoints waypoint)
 {
     wps [wp].gameObject.SetActive(true);
     wps [wp].newWaypoint.Invoke();
 }
示例#17
0
 // Start is called before the first frame update
 void Start()
 {
     command.onClick.AddListener(TaskOnClick);
     remove = (removeButtons)FindObjectOfType(typeof(removeButtons));
     waypoints = (Waypoints)FindObjectOfType(typeof(Waypoints));
 }
示例#18
0
 /// <summary>   Reloads this object. </summary>
 ///
 /// <remarks>   Bunny 2, 3/14/2014. </remarks>
 public void Reload()
 {
     XmlSerializationHelper.Serialize(waypointFile, _Waypoints);
     _Waypoints = XmlSerializationHelper.Deserialize<Waypoints>(waypointFile);
 }
示例#19
0
 // Start est appelé juste avant qu'une méthode Update soit appelée pour la première fois
 protected override void Start()
 {
     base.Start();
     this.waypoints      = Waypoints.GetPoints();
     this.WaypointTarget = waypoints[waypointIndex];
 }
示例#20
0
 Equals(Waypoints, other.Waypoints) &&
示例#21
0
 internal void Restart(DataWaypoint newOrigin)
 {
     Waypoints.Clear();
     Waypoints.AddLast(newOrigin);
 }
示例#22
0
 public void Reload()
 {
     XmlSerializationHelper.Serialize(InterProcessCom.ConfigPath + "\\waypoints.xml", _Waypoints);
     _Waypoints = XmlSerializationHelper.Deserialize<Waypoints>(InterProcessCom.ConfigPath + "\\waypoints.xml");
 }
示例#23
0
 /// <summary>
 /// Create a TripEventArgs for a Trigger or Signal origin,
 /// with the given visitor identifier and origin info.
 /// </summary>
 /// <param name="visitorId"></param>
 /// <param name="tripOrigin"></param>
 public TripEventArgs(IDisposable visitorId, DataWaypoint tripOrigin)
 {
     VisitorIdentifier = visitorId;
     Waypoints.AddLast(tripOrigin);
 }
示例#24
0
        /// <summary>
        /// Update the active route for the character
        /// </summary>
        private async void UpdateActiveRoute()
        {
            if (Waypoints.Count == 0)
            {
                return;
            }


            {
                // new routing

                string start = string.Empty;
                string end   = Location;

                Application.Current.Dispatcher.Invoke((Action)(() =>
                {
                    lock (ActiveRouteLock)
                    {
                        if (Location == Waypoints[0])
                        {
                            Waypoints.RemoveAt(0);
                        }
                    }

                    ActiveRoute.Clear();
                }), DispatcherPriority.Normal);

                // loop through all the waypoints
                for (int i = 0; i < Waypoints.Count; i++)
                {
                    start = end;
                    end   = Waypoints[i];

                    List <Navigation.RoutePoint> sysList = Navigation.Navigate(start, end, UseAnsiblexGates, false, NavigationMode);

                    if (sysList != null)
                    {
                        Application.Current.Dispatcher.Invoke((Action)(() =>
                        {
                            lock (ActiveRouteLock)
                            {
                                foreach (Navigation.RoutePoint s in sysList)
                                {
                                    ActiveRoute.Add(s);
                                }
                            }
                        }), DispatcherPriority.Normal, null);
                    }
                }
            }

            if (esiRouteNeedsUpdate && !esiRouteUpdating)
            {
                esiRouteNeedsUpdate = false;
                esiRouteUpdating    = true;

                List <long> WayPointsToAdd = new List <long>();

                lock (ActiveRouteLock)
                {
                    foreach (Navigation.RoutePoint rp in ActiveRoute)
                    {
                        // explicitly add interim waypoints for ansiblex gates or actual waypoints
                        if (rp.GateToTake == Navigation.GateType.Ansibex || Waypoints.Contains(rp.SystemName))
                        {
                            long wayPointSysID = EveManager.Instance.GetEveSystem(rp.SystemName).ID;

                            if (rp.GateToTake == Navigation.GateType.Ansibex)
                            {
                                foreach (JumpBridge jb in EveManager.Instance.JumpBridges)
                                {
                                    if (jb.From == rp.SystemName)
                                    {
                                        if (jb.FromID != 0)
                                        {
                                            wayPointSysID = jb.FromID;
                                        }
                                        break;
                                    }

                                    if (jb.To == rp.SystemName)
                                    {
                                        if (jb.ToID != 0)
                                        {
                                            wayPointSysID = jb.ToID;
                                        }
                                        break;
                                    }
                                }
                            }
                            WayPointsToAdd.Add(wayPointSysID);
                        }
                    }
                }

                bool firstRoute = true;

                foreach (long SysID in WayPointsToAdd)
                {
                    ESI.NET.EsiClient esiClient = EveManager.Instance.ESIClient;
                    esiClient.SetCharacterData(ESIAuthData);

                    ESI.NET.EsiResponse <string> esr = await esiClient.UserInterface.Waypoint(SysID, false, firstRoute);

                    if (EVEData.ESIHelpers.ValidateESICall(esr))
                    {
                        //                        routeNeedsUpdate = true;
                    }
                    firstRoute = false;

                    // with a shorter wait, ive found the occasional out of order route
                    Thread.Sleep(200);
                }

                esiRouteUpdating = false;
            }
        }
 public void Init(EdgeCollider2D edgePath, ShipStats shipStats)
 {
     this.shipStats = shipStats;
     waypoints      = new Waypoints();
     waypoints.Init(enemyBehaviour, edgePath);
 }
示例#26
0
 // Use this for initialization
 void Start()
 {
     waypointscript = gameObject.GetComponentInParent <Waypoints> ();
 }
示例#27
0
        private Waypoints GetWaypointsList(string fname, bool reverse)
        {
            float len = 0;
            Waypoints waypoints = new Waypoints(fname);
            Vector3D v_prev = MakeVector(dgWaypoints.Rows[0]);
            waypoints.Add(v_prev);

            for (int i = 1; i < dgWaypoints.Rows.Count - 1; i++)
            {
                Vector3D v_cur = MakeVector(dgWaypoints.Rows[i]);
                len += v_prev.GetDistanceTo(v_cur);
                waypoints.Add(v_cur);
                v_prev = v_cur;
            }

            if (reverse)
                waypoints.List.Reverse();

            return waypoints;
        }
示例#28
0
 /// <summary>
 /// Clears the waypoints and grid.
 /// </summary>
 public void ClearWaypointsAndGrid()
 {
     Waypoints.Clear();
 }
示例#29
0
 public void SeekWaypoint(int i, Waypoints Waypoint)
 {
     AIRacerScript.AIRacerList[i].DesiredPosition = Waypoint.CentrePosition;
     AIRacerScript.AIRacerList[i].SteeringForce   = AISteeringBehaviour.SeekOrFlee(AIRacerScript.AIRacerList[i].CurrentPosition, AIRacerScript.AIRacerList[i].DesiredPosition,
                                                                                   AIRacerScript.AIRacerList[i].CurrentMaxSpeed, AIRacerScript.AIRacerList[i].CurrentDirection, true);
 }
示例#30
0
    /// <summary>
    /// Spawn an enemy NPC type
    /// </summary>
    /// <param name="parent">The parent GameObject where this gameObject should be spawned</param>
    /// <param name="spawnPoint">Where in the World this gameObject should spawn</param>
    /// <param name="pathogensController">The PathogensController used to control the NPC</param>
    /// <param name="pathogenObject">The data of the pathogen we are spawining</param>
    /// <param name="waypoints">The list of waypoints the cell should follow</param>
    public void SpawnEnemy(Transform parent, Transform spawnPoint, PathogensController pathogensController, PathogenObject pathogenObject, Waypoints waypoints)
    {
        var newEnemy = Instantiate(pathogenPrefab, spawnPoint.position, spawnPoint.rotation, parent);

        newEnemy.controller         = pathogensController;
        newEnemy.pathogenObject     = pathogenObject;
        newEnemy.waypointsContainer = waypoints.transform;

        EnemyPoints = newEnemy.pathogenObject.pathogenReward;

        // Execute the spawning callback
        newEnemy.onEnemySpawned?.Invoke();
        newEnemy.onEnemyDestroyed.AddListener(() => -- AliveEnemiesCount);
    }
示例#31
0
        public override bool add(GpxModel oldModel, GpxModel newModel, PasteMode mode)
        {
            bool retVal = true;
            int  index  = -1;

            switch (mode)
            {
            case PasteMode.BEGINNING: {
                if (newModel is GpxTrackModel trkModel)
                {
                    trkModel.Parent = this;
                    Tracks.Insert(0, trkModel);
                }
                if (newModel is GpxRouteModel rteModel)
                {
                    rteModel.Parent = this;
                    Routes.Insert(0, rteModel);
                }
                if (newModel is GpxWaypointModel wptModel)
                {
                    wptModel.Parent = this;
                    Waypoints.Insert(0, wptModel);
                }
                break;
            }

            case PasteMode.BEFORE: {
                if (newModel is GpxTrackModel trkModel)
                {
                    index = Tracks.IndexOf((GpxTrackModel)oldModel);
                    if (index == -1)
                    {
                        retVal = false;
                    }
                    else
                    {
                        trkModel.Parent = this;
                        Tracks.Insert(index, trkModel);
                    }
                }
                if (newModel is GpxRouteModel rteModel)
                {
                    index = Routes.IndexOf((GpxRouteModel)oldModel);
                    if (index == -1)
                    {
                        retVal = false;
                    }
                    else
                    {
                        rteModel.Parent = this;
                        Routes.Insert(index, rteModel);
                    }
                }
                if (newModel is GpxWaypointModel wptModel)
                {
                    index = Waypoints.IndexOf((GpxWaypointModel)oldModel);
                    if (index == -1)
                    {
                        retVal = false;
                    }
                    else
                    {
                        wptModel.Parent = this;
                        Waypoints.Insert(index, wptModel);
                    }
                }
                break;
            }

            case PasteMode.AFTER: {
                if (newModel is GpxTrackModel trkModel)
                {
                    index           = Tracks.IndexOf((GpxTrackModel)oldModel);
                    trkModel.Parent = this;
                    Tracks.Insert(index + 1, trkModel);
                }
                if (newModel is GpxRouteModel rteModel)
                {
                    index           = Routes.IndexOf((GpxRouteModel)oldModel);
                    rteModel.Parent = this;
                    Routes.Insert(index + 1, rteModel);
                }
                if (newModel is GpxWaypointModel wptModel)
                {
                    index           = Waypoints.IndexOf((GpxWaypointModel)oldModel);
                    wptModel.Parent = this;
                    Waypoints.Insert(index + 1, wptModel);
                }
                break;
            }

            case PasteMode.END: {
                if (newModel is GpxTrackModel trkModel)
                {
                    trkModel.Parent = this;
                    Tracks.Add(trkModel);
                }
                if (newModel is GpxRouteModel rteModel)
                {
                    rteModel.Parent = this;
                    Routes.Add(rteModel);
                }
                if (newModel is GpxWaypointModel wptModel)
                {
                    wptModel.Parent = this;
                    Waypoints.Add(wptModel);
                }
                break;
            }
            }
            return(retVal);
        }
示例#32
0
        /// <summary>
        /// Drive to safe zone
        /// </summary>
        void DriveToSafeZone()
        {
            WayPoint nextWaypoint = null;

            //set behavior
            if (Waypoints.Count > 0 && Waypoints.TryPeek(out nextWaypoint))
            {
                if (nextWaypoint != null)
                {
                    NextWaypointBearing  = WayPoint.GetBearing(this.Latitude, this.Longitude, nextWaypoint.Lat, nextWaypoint.Long);
                    NextWaypointDistance = WayPoint.GetDistance(this.Latitude, this.Longitude, nextWaypoint.Lat, nextWaypoint.Long);
                    //calculate difference angle
                    double errorWaypoint = NextWaypointBearing - Heading;
                    if (errorWaypoint > Math.PI)
                    {
                        errorWaypoint -= Math.PI * 2.0;
                    }
                    else if (errorWaypoint < -Math.PI)
                    {
                        errorWaypoint += Math.PI * 2.0;
                    }
                    NextWaypointBearingError = errorWaypoint;

                    //vision
                    VisionWayPoint   nextVisionWaypoint  = null;
                    VisionWayPoint[] tempVisionWaypoints = VisionWaypoints.ToArray();
                    if (tempVisionWaypoints.Length > 0)
                    {
                        nextVisionWaypoint = tempVisionWaypoints[0];
                        NextVisionBearing  = WayPoint.GetBearing(this.Latitude, this.Longitude
                                                                 , nextVisionWaypoint.X, nextVisionWaypoint.Y);
                        NextVisionDistance = WayPoint.GetDistance(this.Latitude, this.Longitude
                                                                  , nextVisionWaypoint.X, nextVisionWaypoint.Y);
                        //calculate difference angle
                        double errorVision = NextVisionBearing - Heading;
                        if (errorVision > Math.PI)
                        {
                            errorVision -= Math.PI * 2.0;
                        }
                        else if (errorVision < -Math.PI)
                        {
                            errorVision += Math.PI * 2.0;
                        }
                        NextVisionBearingError = errorVision;
                    }

                    if (imu.GoodData)
                    {
                        //wait for distance to reach
                        if (NextWaypointDistance < ReachWaypointZone && InsideSafeZone)
                        {
                            //when reach stop and wait for drop
                            Speed    = 0;
                            Steering = 0;
                            //clear waypoints and wait drop
                            Waypoints  = new System.Collections.Concurrent.ConcurrentQueue <WayPoint>();
                            this.State = DriveState.WaitDrop;
                        }
                        //if use vision to drive
                        if (Settings.UseVision && nextVisionWaypoint != null)
                        {
                            //avoid 500 500
                            if (nextVisionWaypoint.X > 360.0 || nextVisionWaypoint.Y > 360.0)
                            {
                                WayPoint wp = WayPoint.GenerateRandomWaypoint(SafeZone);
                                if (wp != null)
                                {
                                    WayPoint temp;
                                    Waypoints.TryDequeue(out temp);
                                    Waypoints.Enqueue(wp);
                                    return;
                                }
                            }
                            //apply steer control
                            double TempSteering = 0;
                            //apply speed control
                            double TempSpeed = 0;
                            //determine behavior
                            TempSteering        = NextVisionBearingError * SteerRatio / Math.PI;
                            TempSpeed           = FullSpeed;
                            TargetApporachCount = 0;
                            Steering            = CloseBoundary ? Math.Min(Math.Max(TempSteering, -1000), 1000)
                                : Math.Min(Math.Max(TempSteering * OutsideSteerRatio, -1000), 1000);
                            //set speed
                            Speed = InsideBoundary ? TempSpeed : TempSpeed * OutsideSpeedRatio;
                        }
                        //if use gps only to drive
                        else
                        {
                            //apply steer control
                            double TempSteering = NextWaypointBearingError * SteerRatio / Math.PI;
                            // SteerPID.Feed(error);
                            Steering = CloseBoundary ? Math.Min(Math.Max(TempSteering, -1000), 1000)
                                : Math.Min(Math.Max(TempSteering * OutsideSteerRatio, -1000), 1000);
                            //set speed
                            Speed = InsideBoundary ? FullSpeed : FullSpeed * OutsideSpeedRatio;
                        }
                    }
                    else
                    {
                        //set all to 0 if no gps lock
                        Speed    = 0;
                        Steering = 0;
                    }
                }
            }
            else
            {
                //if target not found
                if (Waypoints.Count == 0)
                {
                    WayPoint wp = WayPoint.GetCenter(SafeZone);
                    if (wp != null)
                    {
                        Waypoints.Enqueue(wp);
                    }
                }
                //set all to 0 if no waypoints
                Speed    = 0;
                Steering = 0;
            }
        }
示例#33
0
        /// <summary>
        /// Removes all elements in scope from the instance.
        /// </summary>
        /// <param name="theTier">The tier to remove the elements from.</param>
        /// <param name="xMin">The min x-value of the scope.</param>
        /// <param name="xMax">The max x-value of the scope.</param>
        /// <param name="yMin">The min y-value of the scope.</param>
        /// <param name="yMax">The max y-value of the scope.</param>
        public void ModRemoveWaypoints(ITierInfo theTier, double xMin, double yMin, double xMax, double yMax)
        {
            Tier tier = theTier as Tier;
            // Remove waypoints
            List <Waypoint> remWaypoints = Waypoints.Where(w => w.Tier == tier && xMin <= w.X && w.X <= xMax && yMin <= w.Y && w.Y <= yMax).ToList();

            // Remove all of them
            foreach (var waypoint in remWaypoints)
            {
                // Remove the waypoint - the waypoint graph handles all cascading path removals
                waypoint.Tier.RemoveWaypoint(waypoint);
                // Remove all elements that were connected to the waypoint
                foreach (var guard in Semaphores.SelectMany(s => s.Guards).Where(guard => guard.From == waypoint || guard.To == waypoint).ToArray())
                {
                    guard.Semaphore.UnregisterGuard(guard);
                    if (guard.Semaphore.Guards.Count() == 0)
                    {
                        Semaphores.Remove(guard.Semaphore);
                    }
                }
                foreach (var station in InputStations.Where(s => s.Waypoint == waypoint).ToArray())
                {
                    station.Tier.RemoveInputStation(station);
                    InputStations.Remove(station);
                }
                foreach (var station in OutputStations.Where(s => s.Waypoint == waypoint).ToArray())
                {
                    station.Tier.RemoveOutputStation(station);
                    OutputStations.Remove(station);
                }
                foreach (var pod in Pods.Where(p => p.Waypoint == waypoint).ToArray())
                {
                    pod.Tier.RemovePod(pod);
                    Pods.Remove(pod);
                }
                foreach (var elevator in Elevators.Where(e => e.ConnectedPoints.Contains(waypoint)))
                {
                    elevator.UnregisterPoint(waypoint);
                    if (elevator.ConnectedPoints.Count == 0)
                    {
                        Elevators.Remove(elevator);
                    }
                }
                // Make sure it is not on the list of storage locations anymore
                if (waypoint.PodStorageLocation)
                {
                    ResourceManager.RemovePodStorageLocation(waypoint);
                }
                // Finally remove from the overall waypoint list
                Waypoints.Remove(waypoint);
            }
            // Also remove movables in scope
            List <Bot> remBots = Bots.Where(b => b.Tier == tier && xMin <= b.X && b.X <= xMax && yMin <= b.Y && b.Y <= yMax).ToList();

            foreach (var bot in remBots)
            {
                Bots.Remove(bot);
                bot.Tier.RemoveBot(bot);
            }
            List <Pod> remPods = Pods.Where(p => p.Tier == tier && xMin <= p.X && p.X <= xMax && yMin <= p.Y && p.Y <= yMax).ToList();

            foreach (var pod in remPods)
            {
                Pods.Remove(pod);
                pod.Tier.RemovePod(pod);
            }
        }
示例#34
0
 void Awake()
 {
     waypoints = FindObjectOfType <Waypoints>();
 }
示例#35
0
        public bool CreatePathInsideBoundary(IntPoint startPointIn, IntPoint endPointIn, Polygon pathThatIsInside, bool optomizePath = true)
        {
            double z = startPointIn.Z;

            startPointIn.Z = 0;
            endPointIn.Z   = 0;
            if (BoundaryPolygons == null || BoundaryPolygons.Count == 0)
            {
                return(false);
            }

            // neither needed to be moved
            if (BoundaryPolygons.FindIntersection(startPointIn, endPointIn, BoundaryEdgeQuadTrees) == Intersection.None &&
                BoundaryPolygons.PointIsInside((startPointIn + endPointIn) / 2, BoundaryEdgeQuadTrees, BoundaryPointQuadTrees))
            {
                return(true);
            }

            removePointList.Dispose();

            pathThatIsInside.Clear();

            //Check if we are inside the boundaries
            IntPointNode startPlanNode = null;
            var          lastAddedNode = GetWayPointInside(startPointIn, out startPlanNode);

            IntPointNode endPlanNode   = null;
            var          lastToAddNode = GetWayPointInside(endPointIn, out endPlanNode);

            long startToEndDistanceSqrd  = (endPointIn - startPointIn).LengthSquared();
            long moveStartInDistanceSqrd = (startPlanNode.Position - lastAddedNode.Position).LengthSquared();
            long moveEndInDistanceSqrd   = (endPlanNode.Position - lastToAddNode.Position).LengthSquared();

            if (startToEndDistanceSqrd < moveStartInDistanceSqrd ||
                startToEndDistanceSqrd < moveEndInDistanceSqrd)
            {
                return(true);
            }

            var crossings = new List <Tuple <int, int, IntPoint> >(BoundaryPolygons.FindCrossingPoints(lastAddedNode.Position, lastToAddNode.Position, BoundaryEdgeQuadTrees));

            crossings.Sort(new PolygonAndPointDirectionSorter(lastAddedNode.Position, lastToAddNode.Position));
            foreach (var crossing in crossings.SkipSame())
            {
                IntPointNode crossingNode = Waypoints.FindNode(crossing.Item3, findNodeDist);
                // for every crossing try to connect it up in the waypoint data
                if (crossingNode == null)
                {
                    crossingNode = AddTempWayPoint(removePointList, crossing.Item3);
                    // also connect it to the next and prev points on the polygon it came from
                    HookUpToEdge(crossingNode, crossing.Item1, crossing.Item2);
                }

                if (lastAddedNode != crossingNode &&
                    BoundaryPolygons.PointIsInside((lastAddedNode.Position + crossingNode.Position) / 2, BoundaryEdgeQuadTrees, BoundaryPointQuadTrees))
                {
                    Waypoints.AddPathLink(lastAddedNode, crossingNode);
                }
                else if (crossingNode.Links.Count == 0)
                {
                    // link it to the edge it is on
                    HookUpToEdge(crossingNode, crossing.Item1, crossing.Item2);
                }
                lastAddedNode = crossingNode;
            }

            if (lastAddedNode != lastToAddNode &&
                BoundaryPolygons.PointIsInside((lastAddedNode.Position + lastToAddNode.Position) / 2, BoundaryEdgeQuadTrees))
            {
                // connect the last crossing to the end node
                Waypoints.AddPathLink(lastAddedNode, lastToAddNode);
            }

            Path <IntPointNode> path = Waypoints.FindPath(startPlanNode, endPlanNode, true);

            foreach (var node in path.Nodes.SkipSamePosition())
            {
                pathThatIsInside.Add(new IntPoint(node.Position, z));
            }

            if (path.Nodes.Length == 0)
            {
                if (saveBadPathToDisk)
                {
                    WriteErrorForTesting(startPointIn, endPointIn, 0);
                }
                CalculatedPath?.Invoke(this, pathThatIsInside, startPointIn, endPointIn);
                return(false);
            }

            if (optomizePath)
            {
                OptomizePathPoints(pathThatIsInside);
            }

            if (saveBadPathToDisk)
            {
                AllPathSegmentsAreInsideOutlines(pathThatIsInside, startPointIn, endPointIn, true);
            }

            CalculatedPath?.Invoke(this, pathThatIsInside, startPointIn, endPointIn);
            return(true);
        }
示例#36
0
        /// <summary>
        /// Moves the object to its specified waypoints, updating its coordinate.
        /// </summary>
        /// <param name="diff">The amount of milliseconds the object is supposed to move</param>
        public void Move(float diff, bool useTarget = false)
        {
            // no waypoints remained - clear the Waypoints
            if (WaypointIndex >= Waypoints.Count)
            {
                Waypoints.RemoveAll(v => v != Waypoints[0]);
            }

            // TODO: Remove dependency of Target. In fact, just remove Target altogether.
            if (Target == null)
            {
                _direction = new Vector2();

                return;
            }

            // current position
            var cur = new Vector2(X, Y);

            var next = new Vector2(Target.X, Target.Y);

            var goingTo = next - cur;

            _direction = Vector2.Normalize(goingTo);

            // usually doesn't happen
            if (float.IsNaN(_direction.X) || float.IsNaN(_direction.Y))
            {
                _direction = new Vector2(0, 0);
            }

            var moveSpeed = GetMoveSpeed();

            var deltaMovement = moveSpeed * 0.001f * diff;

            var xx = _direction.X * deltaMovement;
            var yy = _direction.Y * deltaMovement;

            X += xx;
            Y += yy;

            // (X, Y) have now moved to the next position
            cur = new Vector2(X, Y);

            // Check if we reached the next waypoint
            // REVIEW (of previous code): (deltaMovement * 2) being used here is problematic; if the server lags, the diff will be much greater than the usual values
            if ((cur - next).LengthSquared() < MOVEMENT_EPSILON * MOVEMENT_EPSILON)
            {
                if (this is IProjectile && !Target.IsSimpleTarget)
                {
                    return;
                }

                // remove this waypoint because we have reached it
                if (++WaypointIndex >= Waypoints.Count)
                {
                    Target = null;
                }
                else
                {
                    Target = new Target(Waypoints[WaypointIndex]);
                }
            }
        }
示例#37
0
        public PathFinder(Polygons outlinePolygons, long avoidInset, IntRect?stayInsideBounds = null)
        {
            if (outlinePolygons.Count == 0)
            {
                return;
            }

            OutlinePolygons = FixWinding(outlinePolygons);
            OutlinePolygons = Clipper.CleanPolygons(OutlinePolygons, avoidInset / 60);
            InsetAmount     = avoidInset;
            if (stayInsideBounds != null)
            {
                var boundary = stayInsideBounds.Value;
                OutlinePolygons.Add(new Polygon()
                {
                    new IntPoint(boundary.minX, boundary.minY),
                    new IntPoint(boundary.maxX, boundary.minY),
                    new IntPoint(boundary.maxX, boundary.maxY),
                    new IntPoint(boundary.minX, boundary.maxY),
                });

                OutlinePolygons = FixWinding(OutlinePolygons);
            }

            BoundaryPolygons = OutlinePolygons.Offset(stayInsideBounds == null ? -avoidInset : -2 * avoidInset);
            BoundaryPolygons = FixWinding(BoundaryPolygons);

            OutlineEdgeQuadTrees  = OutlinePolygons.GetEdgeQuadTrees();
            OutlinePointQuadTrees = OutlinePolygons.GetPointQuadTrees();

            BoundaryEdgeQuadTrees  = BoundaryPolygons.GetEdgeQuadTrees();
            BoundaryPointQuadTrees = BoundaryPolygons.GetPointQuadTrees();

            foreach (var polygon in BoundaryPolygons)
            {
                Waypoints.AddPolygon(polygon);
            }

            // hook up path segments between the separate islands
            if (simpleHookup)             // do a simple hookup
            {
                for (int indexA = 0; indexA < BoundaryPolygons.Count; indexA++)
                {
                    var polyA = BoundaryPolygons[indexA];
                    if (polyA.GetWindingDirection() > 0)
                    {
                        Func <int, Polygon, bool> ConsiderPolygon = (polyIndex, poly) =>
                        {
                            return(polyIndex != indexA &&
                                   poly.GetWindingDirection() > 0);
                        };

                        // find the closest two points between A and any other polygon
                        IntPoint bestAPos = polyA.Center();
                        Func <int, IntPoint, bool> ConsiderPoint = (polyIndex, edgeEnd) =>
                        {
                            if (OutlinePolygons.PointIsInside((bestAPos + edgeEnd) / 2, OutlineEdgeQuadTrees, OutlinePointQuadTrees))
                            {
                                return(true);
                            }
                            return(false);
                        };

                        var bestBPoly = BoundaryPolygons.FindClosestPoint(bestAPos, ConsiderPolygon, ConsiderPoint);
                        if (bestBPoly.polyIndex == -1)
                        {
                            // find one that intersects
                            bestBPoly = BoundaryPolygons.FindClosestPoint(bestAPos, ConsiderPolygon);
                        }
                        if (bestBPoly.polyIndex != -1)
                        {
                            bestAPos = polyA.FindClosestPoint(bestBPoly.Item3).Item2;
                            var      bestBResult = BoundaryPolygons[bestBPoly.Item1].FindClosestPoint(bestAPos, ConsiderPoint);
                            IntPoint bestBPos    = new IntPoint();
                            if (bestBResult.index != -1)
                            {
                                bestBPos = bestBResult.Item2;
                            }
                            else
                            {
                                // find one that intersects
                                bestBPos = BoundaryPolygons[bestBPoly.Item1].FindClosestPoint(bestAPos).Item2;
                            }
                            bestAPos = polyA.FindClosestPoint(bestBPos).Item2;
                            bestBPos = BoundaryPolygons[bestBPoly.Item1].FindClosestPoint(bestAPos).Item2;

                            // hook the polygons up along this connection
                            IntPointNode nodeA = Waypoints.FindNode(bestAPos);
                            IntPointNode nodeB = Waypoints.FindNode(bestBPos);
                            Waypoints.AddPathLink(nodeA, nodeB);
                        }
                    }
                }
            }
            else             // hook up using thin lines code
            {
                // this is done with merge close edges and finding candidates
                // then joining the ends of the merged segments with the closest points
                Polygons thinLines;
                if (OutlinePolygons.FindThinLines(avoidInset * 2, 0, out thinLines))
                {
                    ThinLinePolygons = thinLines;
                    for (int thinIndex = 0; thinIndex < thinLines.Count; thinIndex++)
                    {
                        var thinPolygon = thinLines[thinIndex];
                        if (thinPolygon.Count > 1)
                        {
                            Waypoints.AddPolygon(thinPolygon, false);
                        }
                    }

                    Polygons allPolygons = new Polygons(thinLines);
                    allPolygons.AddRange(BoundaryPolygons);
                    for (int thinIndex = 0; thinIndex < thinLines.Count; thinIndex++)
                    {
                        var thinPolygon = thinLines[thinIndex];
                        if (thinPolygon.Count > 1)
                        {
                            // now hook up the start and end of this polygon to the existing way points
                            var closestStart = allPolygons.FindClosestPoint(thinPolygon[0], (polyIndex, poly) => { return(polyIndex == thinIndex); });
                            var closestEnd   = allPolygons.FindClosestPoint(thinPolygon[thinPolygon.Count - 1], (polyIndex, poly) => { return(polyIndex == thinIndex); });                          // last point
                            if (OutlinePolygons.PointIsInside((closestStart.Item3 + closestEnd.Item3) / 2, OutlineEdgeQuadTrees))
                            {
                                IntPointNode nodeA = Waypoints.FindNode(closestStart.Item3);
                                IntPointNode nodeB = Waypoints.FindNode(closestEnd.Item3);
                                if (nodeA != null && nodeB != null)
                                {
                                    Waypoints.AddPathLink(nodeA, nodeB);
                                }
                            }
                        }
                    }
                }
            }

            removePointList = new WayPointsToRemove(Waypoints);
        }
示例#38
0
 // Start is called before the first frame update
 void Start()
 {
     command   = (Command)FindObjectOfType(typeof(Command));
     waypoints = (Waypoints)FindObjectOfType(typeof(Waypoints));
     remove    = (removeButtons)FindObjectOfType(typeof(removeButtons));
 }
        public IEnumerable<IResult> Save()
        {
            var waypoint = new Waypoint
            {
                Title = this.Title,
                CreatedDate = DateTime.Now,
                Description = this.Description,
                Position = new GPSPosition { Latitude = this.Latitude, Longitude = this.Longitude, },
            };
            var waypoints = new Waypoints ();
            waypoints.Add(waypoint);

            yield return new SaveResult(waypoints);

            GoBack();
        }
示例#40
0
 public Navigation()
 {
     var filepath = InterProcessCom.ConfigPath + "\\waypoints.xml";
     _Waypoints = !File.Exists(filepath) ? new Waypoints() : XmlSerializationHelper.Deserialize<Waypoints>(filepath);
 }
示例#41
0
 public NavigationState(Waypoints waypoints, string lfs, string tooltip_text)
     : this(waypoints, _default_step_dist, lfs, tooltip_text)
 {
 }
示例#42
0
 public NavigationState(Waypoints waypoints, float step_dist, string lfs, string tooltip_text)
 {
     _wp = waypoints;
     Init(lfs, step_dist, tooltip_text);
 }
示例#43
0
        public string GetWayPointText()
        {
            string ClipboardText = "Waypoints\n==============\n";

            lock (ActiveRouteLock)
            {
                foreach (Navigation.RoutePoint rp in ActiveRoute)
                {
                    string WayPointText  = string.Empty;
                    long   wayPointSysID = EveManager.Instance.GetEveSystem(rp.SystemName).ID;
                    // explicitly add interim waypoints for ansiblex gates or actual waypoints
                    if (rp.GateToTake == Navigation.GateType.Ansibex)
                    {
                        bool isSystemLink = true;

                        if (rp.GateToTake == Navigation.GateType.Ansibex)
                        {
                            string GateDesto = string.Empty;

                            foreach (JumpBridge jb in EveManager.Instance.JumpBridges)
                            {
                                if (jb.From == rp.SystemName)
                                {
                                    if (jb.FromID != 0)
                                    {
                                        wayPointSysID = jb.FromID;
                                        isSystemLink  = false;
                                    }

                                    GateDesto = jb.To;
                                    break;
                                }

                                if (jb.To == rp.SystemName)
                                {
                                    if (jb.ToID != 0)
                                    {
                                        wayPointSysID = jb.ToID;
                                        isSystemLink  = false;
                                    }

                                    GateDesto = jb.From;
                                    break;
                                }
                            }

                            if (isSystemLink)
                            {
                                WayPointText = "Ansiblex: <url=showinfo:5//" + wayPointSysID + ">" + rp.SystemName + " » " + GateDesto + " </url>\n";
                            }
                            else
                            {
                                WayPointText = "Ansiblex: <url=showinfo:35841//" + wayPointSysID + ">" + rp.SystemName + " » " + GateDesto + "</url>\n";
                            }
                        }
                    }

                    if (Waypoints.Contains(rp.SystemName))
                    {
                        // regular waypoint
                        wayPointSysID = EveManager.Instance.GetEveSystem(rp.SystemName).ID;

                        WayPointText = "<url=showinfo:5//" + wayPointSysID + ">" + rp.SystemName + "</url>\n";
                    }

                    ClipboardText += WayPointText;
                }
            }

            return(ClipboardText);
        }