private void HandlePlayerUpdateResponse(PlayerUpdateResponse obj) { var isUpdated = this.PlayerUpdateResponse != null; this.PlayerUpdateResponse = obj; SetInitializedIfReady(); InvokeStateChanged(EventArgs.Empty); }
private void HandlePlayerUpdateResponse(PlayerUpdateResponse obj) { _logger.LogInformation("HandlePlayerUpdateResponse Message={0}", obj); if (OnPlayerUpdateResponse != null) { OnPlayerUpdateResponse(obj); } }
public async Task<PlayerUpdateResponse> HumanLikeWalking(GeoCoordinate targetLocation, double walkingSpeedInKilometersPerHour, Func<Task> functionExecutedWhileWalking) { var speedInMetersPerSecond = walkingSpeedInKilometersPerHour / 3.6; var sourceLocation = new GeoCoordinate(_client.CurrentLat, _client.CurrentLng); var distanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation); Logger.ColoredConsoleWrite(ConsoleColor.DarkCyan, $"Distance to target location: {distanceToTarget:0.##} meters. Will take {distanceToTarget / speedInMetersPerSecond:0.##} seconds!"); var nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, targetLocation); var nextWaypointDistance = speedInMetersPerSecond; var waypoint = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing); //Initial walking var requestSendDateTime = DateTime.Now; //var result = // await // _client.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude, _client.getSettingHandle().DefaultAltitude); if (functionExecutedWhileWalking != null) await functionExecutedWhileWalking(); do { var millisecondsUntilGetUpdatePlayerLocationResponse = (DateTime.Now - requestSendDateTime).TotalMilliseconds; sourceLocation = new GeoCoordinate(_client.CurrentLat, _client.CurrentLng); var currentDistanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation); if (currentDistanceToTarget < 40) { if (speedInMetersPerSecond > SpeedDownTo) { Logger.ColoredConsoleWrite(ConsoleColor.DarkCyan, $"We are within 40 meters of the target. Speeding down to 10 km/h to not pass the target."); speedInMetersPerSecond = SpeedDownTo; } } nextWaypointDistance = Math.Min(currentDistanceToTarget, millisecondsUntilGetUpdatePlayerLocationResponse / 1000 * speedInMetersPerSecond); nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, targetLocation); waypoint = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing); requestSendDateTime = DateTime.Now; result = await _client.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude, _client.getSettingHandle().DefaultAltitude); await Task.Delay(Math.Min((int)(distanceToTarget / speedInMetersPerSecond * 1000), 3000)); } while (LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation) >= 30); return result; }
internal PlayerUpdateEventArgs(LavaPlayer player, PlayerUpdateResponse response) { Player = player; Track = player.Track; Position = response.State.Position; player.UpdatePlayer(x => { player.Track.WithPosition((long)response.State.Position.TotalMilliseconds); player.LastUpdate = response.State.Time; }); }
private PlayerUpdateResponse MakePlayerUpdateResponse(Models.PlayerState playerState) { var ret = new PlayerUpdateResponse() { GameId = playerState.GameState.GameId, PlayerId = playerState.PlayerId }; ret.CardId = playerState.PlayerCardCardId; ret.PlayerPublicId = playerState.PlayerStateId; ret.IsDealer = playerState.PlayerId == playerState.GameState.PlayerId; ret.IsSuccess = true; return(ret); }
private void InvokeOnPlayerUpdate(PlayerUpdateResponse response) { if (EventManager != null) { try { EventManager.HandlePlayerUpdate(response); } catch (Exception ex) { _logger.LogError(ex, nameof(InvokeOnPlayerUpdate)); } } }
public async Task <PlayerUpdateResponse> UpdatePlayerLocation(double lat, double lng) { PlayerUpdateResponse updateResponse = null; if (_currentLat >= lat) { while (_currentLat > lat) { SetCoordinates(_currentLat -= _settings.StepDistance, _currentLng); updateResponse = await DoWalk(); await Task.Delay(100); } } else { while (_currentLat < lat) { SetCoordinates(_currentLat += _settings.StepDistance, _currentLng); updateResponse = await DoWalk(); await Task.Delay(100); } } if (_currentLng >= lng) { while (_currentLng > lng) { SetCoordinates(_currentLat, _currentLng -= _settings.StepDistance); updateResponse = await DoWalk(); await Task.Delay(100); } } else { while (_currentLng < lng) { SetCoordinates(_currentLat, _currentLng += _settings.StepDistance); updateResponse = await DoWalk(); await Task.Delay(100); } } return(updateResponse); }
private void ProcessPlayerUpdate(ref Utf8JsonReader reader, out PlayerUpdateResponse playerUpdateResponse) { // {"op":"playerUpdate","state":{"position":4720,"time":1566866929606},"guildId":"522440206494728203"} playerUpdateResponse = new PlayerUpdateResponse(); while (reader.Read()) { switch (reader.TokenType) { case JsonTokenType.PropertyName when reader.ValueTextEquals("guildId"): reader.Read(); playerUpdateResponse.GuildId = ulong.Parse(reader.GetString()); break; case JsonTokenType.PropertyName when reader.ValueTextEquals("state"): var state = new PlayerState(); while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { playerUpdateResponse.State = state; break; } if (reader.TokenType != JsonTokenType.PropertyName) { continue; } if (reader.ValueTextEquals("time") && reader.Read()) { state.Time = DateTimeOffset.FromUnixTimeMilliseconds(reader.GetInt64()); } else if (reader.ValueTextEquals("position") && reader.Read()) { state.Position = TimeSpan.FromMilliseconds(reader.GetInt64()); } } break; } } }
public async Task <PlayerUpdateResponse> MoveEH(GeoCoordinate destination, double walkingSpeedInKilometersPerHour, Func <Task <bool> > functionExecutedWhileWalking, Func <Task <bool> > functionExecutedWhileWalking2, CancellationToken cancellationToken, ISession session) { GeoCoordinate currentLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude, _client.CurrentAltitude); PlayerUpdateResponse result = new PlayerUpdateResponse(); List <GeoCoordinate> waypoints = new List <GeoCoordinate>(); var routingResponse = Routing.GetRoute(currentLocation, destination); foreach (var item in routingResponse.Coordinates) { //0 = lat, 1 = long (MAYBE NOT THO?) waypoints.Add(new GeoCoordinate(item.ToArray()[1], item.ToArray()[0])); } Navigation navi = new Navigation(_client, UpdatePositionEvent); for (var x = 0; x < waypoints.Count; x++) { var nextSpeed = session.Client.rnd.NextInRange(session.LogicSettings.WalkingSpeedMin, session.LogicSettings.WalkingSpeedMax) * session.Settings.MoveSpeedFactor; await navi.HumanPathWalking(waypoints.ToArray()[x], nextSpeed, functionExecutedWhileWalking, functionExecutedWhileWalking2, cancellationToken); UpdatePositionEvent?.Invoke(waypoints.ToArray()[x].Latitude, waypoints.ToArray()[x].Longitude, waypoints.ToArray()[x].Altitude); //Console.WriteLine("Hit waypoint " + x); } var curcoord = new GeoCoordinate(session.Client.CurrentLatitude, session.Client.CurrentLongitude); if (!(LocationUtils.CalculateDistanceInMeters(curcoord, destination) > 40)) { return(result); } { var nextSpeed = session.Client.rnd.NextInRange(session.LogicSettings.WalkingSpeedMin, session.LogicSettings.WalkingSpeedMax) * session.Settings.MoveSpeedFactor; await navi.HumanPathWalking(destination, nextSpeed, functionExecutedWhileWalking, functionExecutedWhileWalking2, cancellationToken); } return(result); }
public async Task <PlayerUpdateResponse> Walk(GeoCoordinate targetLocation, Func <Task <bool> > functionExecutedWhileWalking, ISession session, CancellationToken cancellationToken) { GetGoogleInstance(session); _minStepLengthInMeters = session.LogicSettings.DefaultStepLength; var currentLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude, _client.CurrentAltitude); var googleResult = _googleDirectionsService.GetDirections(currentLocation, new List <GeoCoordinate>(), targetLocation); if (googleResult.Directions.status.Equals("OVER_QUERY_LIMIT")) { return(await RedirectToHumanStrategy(targetLocation, functionExecutedWhileWalking, session, cancellationToken)); } var googleWalk = GoogleWalk.Get(googleResult); PlayerUpdateResponse result = null; var points = googleWalk.Waypoints; //filter google defined waypoints and remove those that are too near to the previous ones var waypointsDists = new Dictionary <Tuple <GeoCoordinate, GeoCoordinate>, double>(); var minWaypointsDistance = RandomizeStepLength(_minStepLengthInMeters); Logger.Write($"Generating waypoints, will remove those with distance form previous less than: {minWaypointsDistance.ToString("0.000")}", LogLevel.Debug, force: true); for (var i = 0; i < points.Count; i++) { if (i > 0) { var dist = LocationUtils.CalculateDistanceInMeters(points[i - 1], points[i]); waypointsDists[new Tuple <GeoCoordinate, GeoCoordinate>(points[i - 1], points[i])] = dist; Logger.Write($"WP{i-1}-{i}: {{{points[i-1].Latitude},{points[i-1].Longitude}}} -{{{points[i].Latitude},{points[i].Longitude}}}, dist: {dist.ToString("0.000")}", LogLevel.Debug, force: true); } } var tooNearPoints = waypointsDists.Where(kvp => kvp.Value < minWaypointsDistance).Select(kvp => kvp.Key.Item1).ToList(); foreach (var tooNearPoint in tooNearPoints) { points.Remove(tooNearPoint); } if (points.Any()) //check if first waypoint is the current location (this is what google returns), in such case remove it! { var firstStep = points.First(); if (firstStep == currentLocation) { points.Remove(points.First()); } } var stringifiedPath = string.Join(",\n", points.Select(point => $"{{lat: {point.Latitude}, lng: {point.Longitude}}}")); session.EventDispatcher.Send(new PathEvent { IsCalculated = true, StringifiedPath = stringifiedPath }); var walkedPointsList = new List <GeoCoordinate>(); foreach (var nextStep in points) { Logger.Write($"Leading to a next google waypoint: {{lat: {nextStep.Latitude}, lng: {nextStep.Longitude}}}", LogLevel.Debug, force: true); currentLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); if (_currentWalkingSpeed <= 0) { _currentWalkingSpeed = session.LogicSettings.WalkingSpeedInKilometerPerHour; } if (session.LogicSettings.UseWalkingSpeedVariant) { _currentWalkingSpeed = session.Navigation.VariantRandom(session, _currentWalkingSpeed); } var speedInMetersPerSecond = _currentWalkingSpeed / 3.6; var nextStepBearing = LocationUtils.DegreeBearing(currentLocation, nextStep); //particular steps are limited by minimal length, first step is calculated from the original speed per second (distance in 1s) var nextStepDistance = Math.Max(RandomizeStepLength(_minStepLengthInMeters), speedInMetersPerSecond); Logger.Write($"Distance to walk in the next position update: {nextStepDistance.ToString("0.00")}m bearing: {nextStepBearing.ToString("0.00")}", LogLevel.Debug, force: true); var waypoint = LocationUtils.CreateWaypoint(currentLocation, nextStepDistance, nextStepBearing); walkedPointsList.Add(waypoint); var previousLocation = currentLocation; //store the current location for comparison and correction purposes var requestSendDateTime = DateTime.Now; result = await _client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude, waypoint.Altitude); var realDistanceToTarget = LocationUtils.CalculateDistanceInMeters(currentLocation, targetLocation); Logger.Write($"Real remaining distance to target: {realDistanceToTarget.ToString("0.00")}m", LogLevel.Debug, force: true); if (realDistanceToTarget < 10) { break; } do { cancellationToken.ThrowIfCancellationRequested(); var msToPositionChange = (DateTime.Now - requestSendDateTime).TotalMilliseconds; currentLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); var currentDistanceToWaypoint = LocationUtils.CalculateDistanceInMeters(currentLocation, nextStep); realDistanceToTarget = LocationUtils.CalculateDistanceInMeters(currentLocation, targetLocation); Logger.Write($"Actual position: {{lat: {currentLocation.Latitude}, lng: {currentLocation.Longitude}}}, reached in {msToPositionChange.ToString("0.00")}ms, distance from the next waypoint: {currentDistanceToWaypoint.ToString("0.000")}m, distance from the target: {realDistanceToTarget.ToString("0.000")}m", LogLevel.Debug, force: true); var realSpeedinMperS = nextStepDistance / (msToPositionChange / 1000); var realDistanceWalked = LocationUtils.CalculateDistanceInMeters(previousLocation, currentLocation); //if the real calculated speed is lower than the one expected, we will raise the speed for the following step double speedRaise = 0; if (realSpeedinMperS < speedInMetersPerSecond) { speedRaise = speedInMetersPerSecond - realSpeedinMperS; } double distanceRaise = 0; if (realDistanceWalked < nextStepDistance) { distanceRaise = nextStepDistance - realDistanceWalked; } Logger.Write($"Actual/Expected speed: {realSpeedinMperS.ToString("0.00")}/{speedInMetersPerSecond.ToString("0.00")}m/s, actual/expected distance: {realDistanceWalked.ToString("0.00")}/{nextStepDistance.ToString("0.00")}m, next speed and dist raise by {speedRaise.ToString("0.00")}m/s and {distanceRaise.ToString("0.00")}m", LogLevel.Debug, force: true); var realDistanceToTargetSpeedDown = LocationUtils.CalculateDistanceInMeters(currentLocation, targetLocation); if (realDistanceToTargetSpeedDown < 40) { if (speedInMetersPerSecond > SpeedDownTo) { speedInMetersPerSecond = SpeedDownTo; } } if (session.LogicSettings.UseWalkingSpeedVariant) { _currentWalkingSpeed = session.Navigation.VariantRandom(session, _currentWalkingSpeed); speedInMetersPerSecond = _currentWalkingSpeed / 3.6; } speedInMetersPerSecond += speedRaise; nextStepBearing = LocationUtils.DegreeBearing(currentLocation, nextStep); //setting next step distance is limited by the target and the next waypoint distance (we don't want to miss them) //also the minimal step length is used as we don't want to spend minutes jumping by cm lengths nextStepDistance = Math.Min(Math.Min(realDistanceToTarget, currentDistanceToWaypoint), //also add the distance raise (bot overhead corrections) to the normal step length Math.Max(RandomizeStepLength(_minStepLengthInMeters) + distanceRaise, (msToPositionChange / 1000) * speedInMetersPerSecond) + distanceRaise); // After a correct waypoint, get a random imprecise point in 5 meters around player - more realistic //var impreciseLocation = GenerateUnaccurateGeocoordinate(waypoint, nextWaypointBearing); Logger.Write($"Distance to walk in the next position update: {nextStepDistance.ToString("0.00")}, bearing: {nextStepBearing.ToString("0.00")}, speed: {speedInMetersPerSecond.ToString("0.00")}", LogLevel.Debug, force: true); waypoint = LocationUtils.CreateWaypoint(currentLocation, nextStepDistance, nextStepBearing); walkedPointsList.Add(waypoint); previousLocation = currentLocation; //store the current location for comparison and correction purposes requestSendDateTime = DateTime.Now; result = await _client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude, waypoint.Altitude); UpdatePositionEvent?.Invoke(waypoint.Latitude, waypoint.Longitude); if (functionExecutedWhileWalking != null) { await functionExecutedWhileWalking(); // look for pokemon } } while (LocationUtils.CalculateDistanceInMeters(currentLocation, nextStep) >= 2); UpdatePositionEvent?.Invoke(nextStep.Latitude, nextStep.Longitude); } stringifiedPath = string.Join(",\n", walkedPointsList.Select(point => $"{{lat: {point.Latitude}, lng: {point.Longitude}}}")); session.EventDispatcher.Send(new PathEvent { IsCalculated = false, StringifiedPath = stringifiedPath }); return(result); }
public async Task <PlayerUpdateResponse> Move(GeoCoordinate targetLocation, Func <Task <bool> > functionExecutedWhileWalking, ISession session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (!session.LogicSettings.DisableHumanWalking) { PlayerUpdateResponse result = null; List <GeoCoordinate> points = new List <GeoCoordinate>(); var route = Route(session, new GeoCoordinate( _client.CurrentLatitude, _client.CurrentLongitude, _client.CurrentAltitude), targetLocation); foreach (var item in route) { points.Add(new GeoCoordinate(item.ToArray()[1], item.ToArray()[0])); } for (int i = 0; i < points.Count; i++) { var speedInMetersPerSecond = session.LogicSettings.UseWalkingSpeedVariant ? MajorWalkingSpeedVariant(session) : session.LogicSettings.WalkingSpeedInKilometerPerHour / 3.6; var sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); var nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, points.ToArray()[i]); var nextWaypointDistance = speedInMetersPerSecond; var waypoint = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing); var requestSendDateTime = DateTime.Now; result = await _client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude, waypoint.Altitude); UpdatePositionEvent?.Invoke(waypoint.Latitude, waypoint.Longitude); var realDistanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation); if (realDistanceToTarget < 30) { break; } do { cancellationToken.ThrowIfCancellationRequested(); var millisecondsUntilGetUpdatePlayerLocationResponse = (DateTime.Now - requestSendDateTime).TotalMilliseconds; sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); var currentDistanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, points.ToArray()[i]); var realDistanceToTargetSpeedDown = LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation); if (realDistanceToTargetSpeedDown < 40) { if (speedInMetersPerSecond > SpeedDownTo) { speedInMetersPerSecond = SpeedDownTo; } } if (session.LogicSettings.UseWalkingSpeedVariant) { speedInMetersPerSecond = MinorWalkingSpeedVariant(session); } nextWaypointDistance = Math.Min(currentDistanceToTarget, millisecondsUntilGetUpdatePlayerLocationResponse / 1000 * speedInMetersPerSecond); nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, points.ToArray()[i]); waypoint = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing); requestSendDateTime = DateTime.Now; result = await _client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude, waypoint.Altitude); UpdatePositionEvent?.Invoke(waypoint.Latitude, waypoint.Longitude); if (functionExecutedWhileWalking != null) { await functionExecutedWhileWalking(); // look for pokemon } } while (LocationUtils.CalculateDistanceInMeters(sourceLocation, points.ToArray()[i]) >= 2); UpdatePositionEvent?.Invoke(points.ToArray()[i].Latitude, points.ToArray()[i].Longitude); } return(result); } var curLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); var dist = LocationUtils.CalculateDistanceInMeters(curLocation, targetLocation); if (dist >= 100) { var nextWaypointDistance = dist * 70 / 100; var nextWaypointBearing = LocationUtils.DegreeBearing(curLocation, targetLocation); var waypoint = LocationUtils.CreateWaypoint(curLocation, nextWaypointDistance, nextWaypointBearing); var sentTime = DateTime.Now; var result = await _client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude, waypoint.Altitude); UpdatePositionEvent?.Invoke(waypoint.Latitude, waypoint.Longitude); do { cancellationToken.ThrowIfCancellationRequested(); var millisecondsUntilGetUpdatePlayerLocationResponse = (DateTime.Now - sentTime).TotalMilliseconds; curLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); var currentDistanceToTarget = LocationUtils.CalculateDistanceInMeters(curLocation, targetLocation); dist = LocationUtils.CalculateDistanceInMeters(curLocation, targetLocation); if (dist >= 100) { nextWaypointDistance = dist * 70 / 100; } else { nextWaypointDistance = dist; } nextWaypointBearing = LocationUtils.DegreeBearing(curLocation, targetLocation); waypoint = LocationUtils.CreateWaypoint(curLocation, nextWaypointDistance, nextWaypointBearing); sentTime = DateTime.Now; result = await _client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude, waypoint.Altitude); UpdatePositionEvent?.Invoke(waypoint.Latitude, waypoint.Longitude); if (functionExecutedWhileWalking != null) { await functionExecutedWhileWalking(); // look for pokemon } } while (LocationUtils.CalculateDistanceInMeters(curLocation, targetLocation) >= 10); return(result); } else { var result = await _client.Player.UpdatePlayerLocation(targetLocation.Latitude, targetLocation.Longitude, LocationUtils.getElevation(targetLocation.Latitude, targetLocation.Longitude)); UpdatePositionEvent?.Invoke(targetLocation.Latitude, targetLocation.Longitude); if (functionExecutedWhileWalking != null) { await functionExecutedWhileWalking(); // look for pokemon } return(result); } }
public async Task <PlayerUpdateResponse> Walk(GeoCoordinate targetLocation, Func <Task <bool> > functionExecutedWhileWalking, ISession session, CancellationToken cancellationToken) { GetGoogleInstance(session); var sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude, _client.CurrentAltitude); var googleResult = _googleDirectionsService.GetDirections(sourceLocation, new List <GeoCoordinate>(), targetLocation); if (googleResult.Directions.status.Equals("OVER_QUERY_LIMIT")) { return(await RedirectToHumanStrategy(targetLocation, functionExecutedWhileWalking, session, cancellationToken)); } session.EventDispatcher.Send(new NewPathToDestinyEvent { GoogleData = googleResult }); var googleWalk = GoogleWalk.Get(googleResult); PlayerUpdateResponse result = null; List <GeoCoordinate> points = googleWalk.Waypoints; foreach (var nextStep in points) { var speedInMetersPerSecond = session.LogicSettings.UseWalkingSpeedVariant ? MajorWalkingSpeedVariant(session) : session.LogicSettings.WalkingSpeedInKilometerPerHour / 3.6; sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); var nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, nextStep); var nextWaypointDistance = speedInMetersPerSecond; var waypoint = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing); var requestSendDateTime = DateTime.Now; result = await _client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude, waypoint.Altitude); UpdatePositionEvent?.Invoke(waypoint.Latitude, waypoint.Longitude); var realDistanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation); if (realDistanceToTarget < 10) { break; } do { cancellationToken.ThrowIfCancellationRequested(); var millisecondsUntilGetUpdatePlayerLocationResponse = (DateTime.Now - requestSendDateTime).TotalMilliseconds; sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); var currentDistanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, nextStep); var realDistanceToTargetSpeedDown = LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation); if (realDistanceToTargetSpeedDown < 40) { if (speedInMetersPerSecond > SpeedDownTo) { speedInMetersPerSecond = SpeedDownTo; } } if (session.LogicSettings.UseWalkingSpeedVariant) { speedInMetersPerSecond = MinorWalkingSpeedVariant(session); } nextWaypointDistance = Math.Min(currentDistanceToTarget, millisecondsUntilGetUpdatePlayerLocationResponse / 1000 * speedInMetersPerSecond); nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, nextStep); waypoint = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing); requestSendDateTime = DateTime.Now; result = await _client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude, waypoint.Altitude); UpdatePositionEvent?.Invoke(waypoint.Latitude, waypoint.Longitude); if (functionExecutedWhileWalking != null) { await functionExecutedWhileWalking(); // look for pokemon } } while (LocationUtils.CalculateDistanceInMeters(sourceLocation, nextStep) >= 2); UpdatePositionEvent?.Invoke(nextStep.Latitude, nextStep.Longitude); } return(result); }
private void PlayerUpdateReceived(object sender, PlayerUpdateResponse e) { throw new System.NotImplementedException(); }
public async Task <PlayerUpdateResponse> Move(GeoCoordinate targetLocation, Func <Task <bool> > functionExecutedWhileWalking, ISession session, CancellationToken cancellationToken, bool forceDisableHumanWalking = false) { cancellationToken.ThrowIfCancellationRequested(); if (!session.LogicSettings.DisableHumanWalking && !forceDisableHumanWalking) { PlayerUpdateResponse result = null; var points = new List <GeoCoordinate>(); var route = Route(session, new GeoCoordinate( _client.CurrentLatitude, _client.CurrentLongitude, _client.CurrentAltitude), targetLocation); foreach (var item in route) { points.Add(new GeoCoordinate(item.ToArray()[1], item.ToArray()[0])); } OnGetHumanizeRouteEvent(points, targetLocation); for (var i = 0; i < points.Count; i++) { var speedInMetersPerSecond = session.LogicSettings.UseWalkingSpeedVariant ? MajorWalkingSpeedVariant(session) : session.LogicSettings.WalkingSpeedInKilometerPerHour / 3.6; var sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); var nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, points.ToArray()[i]); var nextWaypointDistance = speedInMetersPerSecond; var waypoint = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing); var requestSendDateTime = DateTime.Now; result = await _client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude, waypoint.Altitude, (float)waypoint.Speed); UpdatePositionEvent?.Invoke(waypoint.Latitude, waypoint.Longitude); var realDistanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation); if (realDistanceToTarget < 30) { break; } do { cancellationToken.ThrowIfCancellationRequested(); var millisecondsUntilGetUpdatePlayerLocationResponse = (DateTime.Now - requestSendDateTime).TotalMilliseconds; sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); var currentDistanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, points.ToArray()[i]); var realDistanceToTargetSpeedDown = LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation); if (realDistanceToTargetSpeedDown < 40) { if (speedInMetersPerSecond > SpeedDownTo) { speedInMetersPerSecond = SpeedDownTo; } } if (session.LogicSettings.UseWalkingSpeedVariant) { speedInMetersPerSecond = MinorWalkingSpeedVariant(session); } nextWaypointDistance = Math.Min(currentDistanceToTarget, millisecondsUntilGetUpdatePlayerLocationResponse / 1000 * speedInMetersPerSecond); nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, points.ToArray()[i]); waypoint = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing); requestSendDateTime = DateTime.Now; result = await _client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude, waypoint.Altitude, (float)waypoint.Speed); UpdatePositionEvent?.Invoke(waypoint.Latitude, waypoint.Longitude); if (functionExecutedWhileWalking != null) { await functionExecutedWhileWalking(); // look for pokemon } } while (LocationUtils.CalculateDistanceInMeters(sourceLocation, points.ToArray()[i]) >= 2); UpdatePositionEvent?.Invoke(points.ToArray()[i].Latitude, points.ToArray()[i].Longitude); } return(result); } else { var sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); var nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, targetLocation); var nextWaypointDistance = session.LogicSettings.UseWalkingSpeedVariant ? MajorWalkingSpeedVariant(session) : session.LogicSettings.WalkingSpeedInKilometerPerHour / 3.6; ; ; var waypoint = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing); //Initial walking var requestSendDateTime = DateTime.Now; var result = await _client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude, waypoint.Altitude, (float)waypoint.Speed); UpdatePositionEvent?.Invoke(waypoint.Latitude, waypoint.Longitude); do { var speedInMetersPerSecond = session.LogicSettings.UseWalkingSpeedVariant ? MajorWalkingSpeedVariant(session) : session.LogicSettings.WalkingSpeedInKilometerPerHour / 3.6; cancellationToken.ThrowIfCancellationRequested(); var millisecondsUntilGetUpdatePlayerLocationResponse = (DateTime.Now - requestSendDateTime).TotalMilliseconds; sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); var currentDistanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation); if (currentDistanceToTarget < 40) { if (speedInMetersPerSecond > SpeedDownTo) { //Logger.Write("We are within 40 meters of the target. Speeding down to 10 km/h to not pass the target.", LogLevel.Info); speedInMetersPerSecond = SpeedDownTo; } } nextWaypointDistance = Math.Min(currentDistanceToTarget, millisecondsUntilGetUpdatePlayerLocationResponse / 1000 * speedInMetersPerSecond); nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, targetLocation); waypoint = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing); requestSendDateTime = DateTime.Now; result = await _client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude, waypoint.Altitude, (float)waypoint.Speed); UpdatePositionEvent?.Invoke(waypoint.Latitude, waypoint.Longitude); if (functionExecutedWhileWalking != null) { await functionExecutedWhileWalking(); // look for pokemon } } while (LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation) >= 30); return(result); } }
/// <summary> /// /// </summary> /// <param name="destination">Desired location to move</param> /// <param name="walkingSpeedMin">Minimal walking speed during the move</param> /// <param name="walkingSpeedMax">Maximal walking speed during the move</param> /// <param name="functionExecutedWhileWalking">Functions #1 to be exec while walking, like task or smth</param> /// <param name="functionExecutedWhileWalking2">Functions #1 to be exec while walking, like task or smth</param> /// <param name="cancellationToken">regular session cancelation token</param> /// <param name="session">ISession param of the bot, to detect which bot started it</param> /// <param name="direct">Directly move to the point, skip routing services</param> /// <param name="waypointsToVisit">Waypoints to visit during the move, required to redure Google Directions API usage</param> /// <param name="eggWalker"></param> /// <returns></returns> internal async Task <PlayerUpdateResponse> Move(GeoCoordinate destination, double walkingSpeedMin, double walkingSpeedMax, Func <Task <bool> > functionExecutedWhileWalking, Func <Task <bool> > functionExecutedWhileWalking2, CancellationToken cancellationToken, ISession session, bool direct = false, List <GeoCoordinate> waypointsToVisit = null, EggWalker eggWalker = null) { var currentLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude, _client.CurrentAltitude); var result = new PlayerUpdateResponse(); if (session.LogicSettings.UseHumanPathing) { var waypoints = new List <GeoCoordinate>(); if (!direct) { RoutingResponse routingResponse = null; try { switch (session.LogicSettings.RoutingService) { case RoutingService.MobBot: routingResponse = Routing.GetRoute(currentLocation, destination, session); break; case RoutingService.OpenLs: routingResponse = OsmRouting.GetRoute(currentLocation, destination, session); break; case RoutingService.GoogleDirections: routingResponse = GoogleRouting.GetRoute(currentLocation, destination, session, waypointsToVisit); break; case RoutingService.MapzenValhalla: routingResponse = MapzenRouting.GetRoute(currentLocation, destination, session, waypointsToVisit); break; } } catch (NullReferenceException ex) { session.EventDispatcher.Send(new DebugEvent { Message = ex.ToString() }); routingResponse = new RoutingResponse(); } if (routingResponse?.Coordinates != null) { foreach (var item in routingResponse.Coordinates) { if (item == null) { continue; } //0 = lat, 1 = long (MAYBE NOT THO?) switch (session.LogicSettings.RoutingService) { case RoutingService.MobBot: waypoints.Add(new GeoCoordinate(item[1], item[0])); break; case RoutingService.OpenLs: waypoints.Add(new GeoCoordinate(item.ToArray()[1], item.ToArray()[0], item.ToArray()[2])); break; case RoutingService.GoogleDirections: waypoints.Add(new GeoCoordinate(item[0], item[1])); break; case RoutingService.MapzenValhalla: waypoints.Add(new GeoCoordinate(item[0], item[1])); break; } } if ((session.LogicSettings.RoutingService == RoutingService.GoogleDirections || session.LogicSettings.RoutingService == RoutingService.MobBot || session.LogicSettings.RoutingService == RoutingService.MapzenValhalla) && session.LogicSettings.UseMapzenApiElevation) { waypoints = await session.MapzenApi.FillAltitude(waypoints); } } } if (waypoints.Count == 0) { waypoints.Add(destination); } else if (waypoints.Count > 1) { var nextPath = waypoints.Select(item => Tuple.Create(item.Latitude, item.Longitude)).ToList(); session.EventDispatcher.Send(new NextRouteEvent { Coords = nextPath }); destination = waypoints.Last(); } var navi = new Navigation(_client, UpdatePositionEvent); var waypointsArr = waypoints.ToArray(); long nextMaintenceStamp = 0; //MILD REWRITE TO USE HUMANPATHWALKING; foreach (var t in waypointsArr) { if (session.ForceMoveTo != null) { return(await ForceMoveTask.Execute(session, cancellationToken)); } // skip waypoints under 5 meters var sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); var distanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, t); if (distanceToTarget <= 5) { continue; } var nextSpeed = RandomExtensions.NextInRange(session.Client.rnd, walkingSpeedMin, walkingSpeedMax) * session.Settings.MoveSpeedFactor; session.State = BotState.Walk; result = await navi.HumanPathWalking(session, t, nextSpeed, functionExecutedWhileWalking, functionExecutedWhileWalking2, cancellationToken); if (session.Runtime.BreakOutOfPathing) { return(result); } UpdatePositionEvent?.Invoke(t.Latitude, t.Longitude, t.Altitude); if (nextMaintenceStamp < DateTime.UtcNow.ToUnixTime()) { await MaintenanceTask.Execute(session, cancellationToken); nextMaintenceStamp = DateTime.UtcNow.AddMinutes(3).ToUnixTime(); } if (eggWalker != null) { await eggWalker.ApplyDistance(distanceToTarget, cancellationToken); } } session.State = BotState.Idle; var curcoord = new GeoCoordinate(session.Client.CurrentLatitude, session.Client.CurrentLongitude); if (LocationUtils.CalculateDistanceInMeters(curcoord, destination) > 40) { var nextSpeed = RandomExtensions.NextInRange(session.Client.rnd, walkingSpeedMin, walkingSpeedMax) * session.Settings.MoveSpeedFactor; result = await navi.HumanPathWalking(session, destination, nextSpeed, functionExecutedWhileWalking, functionExecutedWhileWalking2, cancellationToken); } await MaintenanceTask.Execute(session, cancellationToken); } else { if (destination.Latitude.Equals(session.Runtime.lastPokeStopCoordinate.Latitude) && destination.Longitude.Equals(session.Runtime.lastPokeStopCoordinate.Longitude)) { session.Runtime.BreakOutOfPathing = true; } if (session.Runtime.BreakOutOfPathing) { await MaintenanceTask.Execute(session, cancellationToken); return(result); } var navi = new Navigation(_client, UpdatePositionEvent); var curcoord = new GeoCoordinate(session.Client.CurrentLatitude, session.Client.CurrentLongitude); if (LocationUtils.CalculateDistanceInMeters(curcoord, destination) > 40) { var nextSpeed = RandomExtensions.NextInRange(session.Client.rnd, walkingSpeedMin, walkingSpeedMax) * session.Settings.MoveSpeedFactor; result = await navi.HumanPathWalking(session, destination, nextSpeed, functionExecutedWhileWalking, functionExecutedWhileWalking2, cancellationToken); } } session.State = BotState.Idle; await MaintenanceTask.Execute(session, cancellationToken); return(result); }
/// <summary> /// /// </summary> /// <param name="destination">Desired location to move</param> /// <param name="walkingSpeedMin">Minimal walking speed during the move</param> /// <param name="walkingSpeedMax">Maximal walking speed during the move</param> /// <param name="functionExecutedWhileWalking">Functions #1 to be exec while walking, like task or smth</param> /// <param name="functionExecutedWhileWalking2">Functions #1 to be exec while walking, like task or smth</param> /// <param name="cancellationToken">regular session cancelation token</param> /// <param name="session">ISession param of the bot, to detect which bot started it</param> /// <param name="direct">Directly move to the point, skip routing services</param> /// <param name="waypointsToVisit">Waypoints to visit during the move, required to redure Google Directions API usage</param> /// <param name="sendRoute">Send route to the bot</param> /// <returns></returns> internal async Task <PlayerUpdateResponse> Move(GeoCoordinate destination, double walkingSpeedMin, double walkingSpeedMax, Func <Task <bool> > functionExecutedWhileWalking, Func <Task <bool> > functionExecutedWhileWalking2, CancellationToken cancellationToken, ISession session, bool direct = false, List <GeoCoordinate> waypointsToVisit = null, bool sendRoute = true) { var currentLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude, _client.CurrentAltitude); var customRouteStartState = session.LogicSettings.UseCustomRoute; var result = new PlayerUpdateResponse(); var waypoints = waypointsToVisit; if (waypoints == null || !waypoints.Any()) { waypoints = new List <GeoCoordinate> { destination }; } if (session.LogicSettings.UseHumanPathing) { waypoints = await CreateHumanRoute(destination, cancellationToken, session, direct, waypointsToVisit, currentLocation); } if (waypoints.Count == 0) { waypoints = waypointsToVisit ?? new List <GeoCoordinate> { destination } } ; else if (waypoints.Count > 1 && sendRoute) { var nextPath = waypoints.Select(item => Tuple.Create(item.Latitude, item.Longitude)).ToList(); session.EventDispatcher.Send(new NextRouteEvent { Coords = nextPath }); destination = waypoints.Last(); } var navi = new Navigation(_client, UpdatePositionEvent); var waypointsArr = waypoints.ToArray(); long nextMaintenceStamp = 0; //MILD REWRITE TO USE HUMANPATHWALKING; long nextBuddyStamp = 0; foreach (var t in waypointsArr) { if (customRouteStartState != session.LogicSettings.UseCustomRoute) //custom route setting changed { return(result); } if (session.ForceMoveTo != null) { return(await ForceMoveTask.Execute(session, cancellationToken)); } // skip waypoints under 5 meters var sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); var distanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, t); if (distanceToTarget <= 5) { continue; } var nextSpeed = RandomExtensions.NextInRange(session.Client.Rnd, walkingSpeedMin, walkingSpeedMax); session.State = BotState.Walk; result = await navi.HumanPathWalking(session, t, nextSpeed, functionExecutedWhileWalking, functionExecutedWhileWalking2, cancellationToken); if (session.Runtime.BreakOutOfPathing || session.ForceMoveJustDone) { return(result); } UpdatePositionEvent?.Invoke(t.Latitude, t.Longitude, t.Altitude); if (nextMaintenceStamp < DateTime.UtcNow.ToUnixTime() || session.Runtime.StopsHit > 100) { await MaintenanceTask.Execute(session, cancellationToken); nextMaintenceStamp = DateTime.UtcNow.AddMinutes(3).ToUnixTime(); } if (nextBuddyStamp < DateTime.UtcNow.ToUnixTime() || session.Runtime.StopsHit > 100) { await GetBuddyWalkedTask.Execute(session, cancellationToken); nextBuddyStamp = DateTime.UtcNow.AddMinutes(2).ToUnixTime(); } await ActionQueueTask.Execute(session, cancellationToken); if (session.EggWalker != null && nextSpeed * session.Settings.MoveSpeedFactor < 12) { await session.EggWalker.ApplyDistance(distanceToTarget, cancellationToken); } } session.State = BotState.Idle; var curcoord = new GeoCoordinate(session.Client.CurrentLatitude, session.Client.CurrentLongitude); if (LocationUtils.CalculateDistanceInMeters(curcoord, destination) > 40) { var nextSpeed = RandomExtensions.NextInRange(session.Client.Rnd, walkingSpeedMin, walkingSpeedMax) * session.Settings.MoveSpeedFactor; result = await navi.HumanPathWalking(session, destination, nextSpeed, functionExecutedWhileWalking, functionExecutedWhileWalking2, cancellationToken); } await ActionQueueTask.Execute(session, cancellationToken); await MaintenanceTask.Execute(session, cancellationToken); session.State = BotState.Idle; await ActionQueueTask.Execute(session, cancellationToken); await MaintenanceTask.Execute(session, cancellationToken); return(result); }
/// <summary> /// Provides a safe way to invoke the <see cref="PlayerUpdateReceived" /> event. /// </summary> /// <param name="value"></param> public void RaisePlayerUpdateReceived(PlayerUpdateResponse value) => PlayerUpdateReceived?.Invoke(this, value);
internal PlayerUpdateEventArgs(LavaPlayer player, PlayerUpdateResponse response) { Player = player; Track = player.Track; Position = response.State.Position; }
public async Task <PlayerUpdateResponse> Move(GeoCoordinate destination, double walkingSpeedMin, double walkingSpeedMax, Func <Task <bool> > functionExecutedWhileWalking, Func <Task <bool> > functionExecutedWhileWalking2, CancellationToken cancellationToken, ISession session, bool direct = false) { var currentLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude, _client.CurrentAltitude); var result = new PlayerUpdateResponse(); if (session.LogicSettings.UseHumanPathing) { ////initial coordinate generaton ////prepare the result object for further manipulation + return ////initial time //var requestSendDateTime = DateTime.Now; //var distanceToDest = LocationUtils.CalculateDistanceInMeters(currentLocation, destination); //double metersPerInterval = 0.5; //approximate meters for each interval/waypoint to be spaced from the last. //////get distance ofc //////create segments //var segments = Math.Floor(distanceToDest / metersPerInterval); List <GeoCoordinate> waypoints = new List <GeoCoordinate>(); ////get differences in lat / long //var latDiff = Math.Abs(currentLocation.Latitude - destination.Latitude); //var lonDiff = Math.Abs(currentLocation.Longitude - destination.Longitude); //var latAdd = latDiff / segments; //var lonAdd = latDiff / segments; //var lastLat = currentLocation.Latitude; //var lastLon = currentLocation.Longitude; ////generate waypoints old code -goes in straight line basically //for (int i = 0; i < segments; i++) //{ // //TODO: add altitude calculations into everything // lastLat += latAdd; // lastLon += lonAdd; // waypoints.Add(new GeoCoordinate(lastLat, lastLon, currentLocation.Altitude)); //} //TODO: refactor the generation of waypoint code to break the waypoints given to us by the routing information down into segements like above. //generate waypoints new code if (!direct) { //var routingResponse = OsmRouting.GetRoute(currentLocation, destination, session); //waypoints = routingResponse.Coordinates; RoutingResponse routingResponse; try { routingResponse = !session.LogicSettings.UseOpenLsRouting ? Routing.GetRoute(currentLocation, destination) : OsmRouting.GetRoute(currentLocation, destination, session); } catch (NullReferenceException ex) { session.EventDispatcher.Send(new DebugEvent { Message = ex.ToString() }); routingResponse = new RoutingResponse(); } if (routingResponse?.Coordinates != null) { foreach (var item in routingResponse.Coordinates) { if (item == null) { continue; } //0 = lat, 1 = long (MAYBE NOT THO?) waypoints.Add(!session.LogicSettings.UseOpenLsRouting ? new GeoCoordinate(item.ToArray()[1], item.ToArray()[0], session.LogicSettings.UseMapzenApiElevation ? session.MapzenApi.GetAltitude(item.ToArray()[1], item.ToArray()[0]) : 0) : new GeoCoordinate(item.ToArray()[1], item.ToArray()[0], item.ToArray()[2])); } } } if (waypoints.Count == 0) { waypoints.Add(destination); } else if (waypoints.Count > 1) { var nextPath = waypoints.Select(item => Tuple.Create(item.Latitude, item.Longitude)).ToList(); session.EventDispatcher.Send(new NextRouteEvent { Coords = nextPath }); } //var timeSinceMoveStart = DateTime.Now.Ticks; //double curAcceleration = 1.66; //Lets assume we accelerate at 1.66 m/s ish. TODO: Fuzz this a bit //double curWalkingSpeed = 0; //double maxWalkingSpeed = (session.LogicSettings.WalkingSpeedInKilometerPerHour / 3.6); //Get movement speed in meters ////TODO: Maybe update SensorInfo to replicate/mimic movement, or is it fine as is? //bool StopWalking = false; //double TimeToAccelerate = GetAccelerationTime(curWalkingSpeed, maxWalkingSpeed, curAcceleration); ////double InitialMove = getDistanceTraveledAccelerating(TimeToAccelerate, curAcceleration, curWalkingSpeed); //double MoveLeft = curWalkingSpeed; //bool NeedMoreMove = false; //bool StopMove = false; //int UpdateInterval = 1; // in seconds - any more than this breaks the calculations for distance and such. It all relys on taking ~1 second to perform the actions needed, pretty much. //makes you appear to move slower if you're catching pokemon, hitting stops, etc. //This feels like more human behavior. Dunnomateee Navigation navi = new Navigation(_client, UpdatePositionEvent); var waypointsArr = waypoints.ToArray(); //MILD REWRITE TO USE HUMANPATHWALKING; foreach (var t in waypointsArr) { if (session.ForceMoveTo != null) { return(await ForceMoveTask.Execute(session, cancellationToken)); } // skip waypoints under 5 meters var sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); var distanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, t); if (distanceToTarget <= 5) { continue; } var nextSpeed = session.Client.rnd.NextInRange(walkingSpeedMin, walkingSpeedMax) * session.Settings.MoveSpeedFactor; result = await navi.HumanPathWalking(t, nextSpeed, functionExecutedWhileWalking, functionExecutedWhileWalking2, cancellationToken); if (RuntimeSettings.BreakOutOfPathing) { return(result); } UpdatePositionEvent?.Invoke(t.Latitude, t.Longitude, t.Altitude); //Console.WriteLine("Hit waypoint " + x); } var curcoord = new GeoCoordinate(session.Client.CurrentLatitude, session.Client.CurrentLongitude); if (LocationUtils.CalculateDistanceInMeters(curcoord, destination) > 40) { var nextSpeed = session.Client.rnd.NextInRange(walkingSpeedMin, walkingSpeedMax) * session.Settings.MoveSpeedFactor; result = await navi.HumanPathWalking(destination, nextSpeed, functionExecutedWhileWalking, functionExecutedWhileWalking2, cancellationToken); } } else { if (destination.Latitude.Equals(RuntimeSettings.lastPokeStopCoordinate.Latitude) && destination.Longitude.Equals(RuntimeSettings.lastPokeStopCoordinate.Longitude)) { RuntimeSettings.BreakOutOfPathing = true; } if (RuntimeSettings.BreakOutOfPathing) { await MaintenanceTask.Execute(session, cancellationToken); return(result); } var navi = new Navigation(_client, UpdatePositionEvent); var curcoord = new GeoCoordinate(session.Client.CurrentLatitude, session.Client.CurrentLongitude); if (LocationUtils.CalculateDistanceInMeters(curcoord, destination) > 40) { var nextSpeed = session.Client.rnd.NextInRange(walkingSpeedMin, walkingSpeedMax) * session.Settings.MoveSpeedFactor; result = await navi.HumanPathWalking(destination, nextSpeed, functionExecutedWhileWalking, functionExecutedWhileWalking2, cancellationToken); } } await MaintenanceTask.Execute(session, cancellationToken); return(result); }
public async Task <PlayerUpdateResponse> DoWalk(List <GeoCoordinate> points, ISession session, Func <Task> functionExecutedWhileWalking, GeoCoordinate sourceLocation, GeoCoordinate targetLocation, CancellationToken cancellationToken, double walkSpeed = 0.0) { PlayerUpdateResponse result = null; var currentLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude, _client.CurrentAltitude); //filter google defined waypoints and remove those that are too near to the previous ones var waypointsDists = new Dictionary <Tuple <GeoCoordinate, GeoCoordinate>, double>(); var minWaypointsDistance = RandomizeStepLength(_minStepLengthInMeters); for (var i = 0; i < points.Count; i++) { if (i > 0) { var dist = LocationUtils.CalculateDistanceInMeters(points[i - 1], points[i]); waypointsDists[new Tuple <GeoCoordinate, GeoCoordinate>(points[i - 1], points[i])] = dist; } } var tooNearPoints = waypointsDists.Where(kvp => kvp.Value < minWaypointsDistance).Select(kvp => kvp.Key.Item1).ToList(); foreach (var tooNearPoint in tooNearPoints) { points.Remove(tooNearPoint); } if (points.Any()) //check if first waypoint is the current location (this is what google returns), in such case remove it! { var firstStep = points.First(); if (firstStep == currentLocation) { points.Remove(points.First()); } } var walkedPointsList = new List <GeoCoordinate>(); foreach (var nextStep in points) { currentLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); if (_currentWalkingSpeed <= 0) { _currentWalkingSpeed = session.LogicSettings.WalkingSpeedInKilometerPerHour; } if (session.LogicSettings.UseWalkingSpeedVariant && walkSpeed == 0) { _currentWalkingSpeed = session.Navigation.VariantRandom(session, _currentWalkingSpeed); } var speedInMetersPerSecond = (walkSpeed > 0 ? walkSpeed : _currentWalkingSpeed) / 3.6; var nextStepBearing = LocationUtils.DegreeBearing(currentLocation, nextStep); //particular steps are limited by minimal length, first step is calculated from the original speed per second (distance in 1s) var nextStepDistance = Math.Max(RandomizeStepLength(_minStepLengthInMeters), speedInMetersPerSecond); var waypoint = LocationUtils.CreateWaypoint(currentLocation, nextStepDistance, nextStepBearing); walkedPointsList.Add(waypoint); var previousLocation = currentLocation; //store the current location for comparison and correction purposes var requestSendDateTime = DateTime.Now; result = await LocationUtils.UpdatePlayerLocationWithAltitude(session, waypoint, (float)speedInMetersPerSecond); var realDistanceToTarget = LocationUtils.CalculateDistanceInMeters(currentLocation, targetLocation); if (realDistanceToTarget < 30) { break; } do { cancellationToken.ThrowIfCancellationRequested(); var msToPositionChange = (DateTime.Now - requestSendDateTime).TotalMilliseconds; currentLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); var currentDistanceToWaypoint = LocationUtils.CalculateDistanceInMeters(currentLocation, nextStep); realDistanceToTarget = LocationUtils.CalculateDistanceInMeters(currentLocation, targetLocation); var realSpeedinMperS = nextStepDistance / (msToPositionChange / 1000); var realDistanceWalked = LocationUtils.CalculateDistanceInMeters(previousLocation, currentLocation); //if the real calculated speed is lower than the one expected, we will raise the speed for the following step double speedRaise = 0; if (realSpeedinMperS < speedInMetersPerSecond) { speedRaise = speedInMetersPerSecond - realSpeedinMperS; } double distanceRaise = 0; if (realDistanceWalked < nextStepDistance) { distanceRaise = nextStepDistance - realDistanceWalked; } var realDistanceToTargetSpeedDown = LocationUtils.CalculateDistanceInMeters(currentLocation, targetLocation); if (realDistanceToTargetSpeedDown < 40) { if (speedInMetersPerSecond > SpeedDownTo) { speedInMetersPerSecond = SpeedDownTo; } } if (session.LogicSettings.UseWalkingSpeedVariant && walkSpeed == 0) { _currentWalkingSpeed = session.Navigation.VariantRandom(session, _currentWalkingSpeed); speedInMetersPerSecond = _currentWalkingSpeed / 3.6; } speedInMetersPerSecond += speedRaise; if (walkSpeed > 0) { speedInMetersPerSecond = walkSpeed / 3.6; } nextStepBearing = LocationUtils.DegreeBearing(currentLocation, nextStep); //setting next step distance is limited by the target and the next waypoint distance (we don't want to miss them) //also the minimal step length is used as we don't want to spend minutes jumping by cm lengths nextStepDistance = Math.Min(Math.Min(realDistanceToTarget, currentDistanceToWaypoint), //also add the distance raise (bot overhead corrections) to the normal step length Math.Max(RandomizeStepLength(_minStepLengthInMeters) + distanceRaise, (msToPositionChange / 1000) * speedInMetersPerSecond) + distanceRaise); waypoint = LocationUtils.CreateWaypoint(currentLocation, nextStepDistance, nextStepBearing); walkedPointsList.Add(waypoint); previousLocation = currentLocation; //store the current location for comparison and correction purposes requestSendDateTime = DateTime.Now; result = await LocationUtils.UpdatePlayerLocationWithAltitude(session, waypoint, (float)speedInMetersPerSecond); UpdatePositionEvent?.Invoke(waypoint.Latitude, waypoint.Longitude); if (functionExecutedWhileWalking != null) { await functionExecutedWhileWalking(); // look for pokemon } } while (LocationUtils.CalculateDistanceInMeters(currentLocation, nextStep) >= 2); UpdatePositionEvent?.Invoke(nextStep.Latitude, nextStep.Longitude); } return(result); }
public void HandlePlayerUpdate(PlayerUpdateResponse resp) { _ = _hubContext.Clients.Group(TopicName(resp.GameId, resp.PlayerId)).SendAsync("OnPlayerUpdateResponse", resp); }