public void Should_Not_Consider_Lap_Five_As_Best_Pilot_Lap() { List <Lap> bestLap = new List <Lap>(); bestLap.Add(new Lap() { LapTime = "1:02.769", LapNumber = 1 }); bestLap.Add(new Lap() { LapTime = "1:02.770", LapNumber = 2 }); bestLap.Add(new Lap() { LapTime = "1:02.771", LapNumber = 3 }); bestLap.Add(new Lap() { LapTime = "1:02.772", LapNumber = 4 }); bestLap.Add(new Lap() { LapTime = "1:02.768", LapNumber = 5 }); BestLapDetail bestLapDetail = Lap.GetBestLap(bestLap); Assert.False(bestLapDetail.LapNumber == 5, "Best Lap could not be >5"); }
public void Should_Fail_Best_Pilot_Lap() { List <Lap> bestLap = new List <Lap>(); bestLap.Add(new Lap() { LapTime = "1:02.769", LapNumber = 1 }); bestLap.Add(new Lap() { LapTime = "1:02.770", LapNumber = 2 }); bestLap.Add(new Lap() { LapTime = "1:02.771", LapNumber = 3 }); bestLap.Add(new Lap() { LapTime = "1:02.772", LapNumber = 4 }); bestLap.Add(new Lap() { LapTime = "1:02.773", LapNumber = 5 }); BestLapDetail bestLapDetail = Lap.GetBestLap(bestLap); Assert.False(bestLapDetail.LapNumber == 2, "Not a best Lap"); }
public static Activity Parse(XElement element) { if (element.Name.LocalName != "Activity") { return(null); } var activity = new Activity(); var sportValue = element.Attributes().Where(d => d.Name.LocalName == "Sport").Select(a => a.Value).FirstOrDefault(); activity.Sport = sportValue; var creatorElement = element.Descendants().Where(d => d.Name.LocalName == "Creator").FirstOrDefault(); if (creatorElement != null) { var nameValue = creatorElement.Descendants().Where(d => d.Name.LocalName == "Name").Select(a => a.Value).FirstOrDefault(); var idValue = creatorElement.Descendants().Where(d => d.Name.LocalName == "UnitId").Select(a => a.Value).FirstOrDefault(); activity.Creator = $"{nameValue} {idValue}"; } var lapElements = element.Descendants().Where(d => d.Name.LocalName == "Lap").ToList(); var laps = lapElements.Select(e => Lap.Parse(e)).Where(t => t != null).ToList(); activity.Laps = laps.ToArray(); return(activity); }
public static async void SaveLapAsync(Lap lap) { await Task.CompletedTask; DbContext.Laps.Add(lap); DbContext.SaveChanges(); }
public void AddLap(Lap l) { if (_laps.Contains(l) == false) { _laps.Add(l); } }
public static LearningApi Useimageedge(this LearningApi a) { Lap alg = new Lap(); a.AddModule(alg, "Useimageedge"); return(a); }
public TrackFileSection625M UnpackTrackSectionLaps() { if (this.PacketLength < TrackHeaderLength) { return(null); } TrackFileSection625M section = new TrackFileSection625M(); ReadHeader(section, 0); section.LapCount = this.PacketData[6]; section.TrackPointCount = ReadInt16(25); section.StartPointIndex = ReadInt16(27); section.EndPointIndex = ReadInt16(29); int offset = TrackHeaderLength; while (offset <= this.PacketLength - TrackLapLength) { Lap lap = new Lap(); lap.EndTime = TimeSpan.FromSeconds(FromGlobTime(ReadInt32(offset))); lap.LapTime = TimeSpan.FromSeconds(FromGlobTime(ReadInt32(offset + 4))); lap.LapDistanceMeters = ReadInt32(offset + 8); lap.LapCalories = ReadInt16(offset + 12); lap.MaximumSpeed = FromGlobSpeed(ReadInt16(offset + 14)); lap.MaximumHeartRate = this.PacketData[offset + 16]; lap.AverageHeartRate = this.PacketData[offset + 17]; //lap.StartPointIndex = ReadInt16(18); //lap.EndPointIndex = ReadInt16(20); section.Laps.Add(lap); offset += TrackLapLength; } return(section); }
public bool SubmitLap(Lap lap, int sessionid) { string url = "https://racingleaguecharts.com/laps.xml?"; string param = "session_id=" + sessionid + "&lap_number=" + lap.LapNumber + "§or_1=" + lap.Sector1 + "§or_2=" + lap.Sector2 + "&total=" + lap.LapTime.ToString("n3") + "&speed=" + lap.TopSpeed + "&fuel=" + lap.FuelRemaining + "&position=" + lap.RacePosition; Console.WriteLine(url + param); Http web = new Http(url + param); web.HTTPMethod = Http.Method.POST; web.Go(); if (web.StatusCode == 200) { Console.WriteLine(web.Response); return(true); } else { return(false); // TODO: Save the lap for later submission. } }
public string GetLastLap([FromQuery(Name = "token")] string token, string identifier) { try { SessionManager sessionManager = new SessionManager(Server.TeamServer.ObjectManager, Server.TeamServer.TokenIssuer.ValidateToken(token)); Session session = sessionManager.LookupSession(identifier); Stint stint = session.GetCurrentStint(); if (stint != null) { Lap lap = stint.GetCurrentLap(); if (lap != null) { return(lap.Identifier.ToString()); } else if (stint.Nr > 1) { lap = sessionManager.LookupStint(session, stint.Nr - 1).GetCurrentLap(); if (lap != null) { return(lap.Identifier.ToString()); } } } return(""); } catch (Exception exception) { return("Error: " + exception.Message); } }
public Lap AddLap([FromBody] Lap value) { //new sector 1 if (value.LapTime == null && value.Sector2 == null) { while (db.Laps.Any(lap => lap.CompetitorId == value.CompetitorId && lap.LapTime == null)) { var delLap = db.Laps.FirstOrDefault(lap => lap.CompetitorId == value.CompetitorId && lap.LapTime == null); db.Laps.Remove(delLap); db.SaveChanges(); } } if (value.LapTime == null) { SendNewLapAsync(value); } else { SendLapCompletedAsync(value); } db.Laps.Add(value); db.SaveChanges(); return(value); }
private void ProcessSharp(int m) { var cho = _image[_fChoose.ChoosedFile]; byte[,,] res = null; string type = ""; switch (m) { case 0: res = new Robert(cho).RobertData; type = "-罗伯特锐化最终图"; break; case 1: res = new Sobel(cho).SobelData; type = "-Sobel锐化最终图"; break; case 2: res = new Lap(cho).Lapla; type = "-拉普拉斯锐化最终图"; break; } AddNewPic(res, cho.FileName + type, false); }
public static RoundPosition ParseRating(string line, DateTime roundStartTime) { var parts = line.Split(new[] { ' ', '\t', '[', ']', 'L', 'F' }, StringSplitOptions.RemoveEmptyEntries); var riderId = parts[0]; var finished = line.StartsWith('F'); if (parts.Length == 1) { return(RoundPosition.FromLaps(riderId, new Lap[0], false)); } var lapCount = int.Parse(parts[1]); if (parts.Length - lapCount < 2) { throw new FormatException( $"Input should be in format: <rider_number> <number_of_laps> [<lap_time1> ... <lap_time_number_of_laps]. Found lapCount={lapCount} but {parts.Length - 2} lap times"); } Lap prevLap = null; var laps = parts.Skip(2) .Select((x, i) => { var cp = new Checkpoint(riderId, roundStartTime + TimeSpanExt.Parse(x)); var l = prevLap?.CreateNext(cp) ?? new Lap(cp, roundStartTime); prevLap = l; return(l); }); return(RoundPosition.FromLaps(riderId, laps, finished)); }
public void Handler() { var serializer = Serializer.Create(); var calculate = Calculate.Create(); var template = serializer.GetTemplateConfig(_path); for (int line = 1; line < LapRepository.GetLengthLines(); line++) { var averageLap = Convert.ToDecimal(LapRepository.ReadLine(line, template.RootObjectConfigModel.AverageLap.startIndex, template.RootObjectConfigModel.AverageLap.length)); var raceTracks = Convert.ToInt32(LapRepository.ReadLine(line, template.RootObjectConfigModel.Laps.startIndex, template.RootObjectConfigModel.Laps.length)); var arrivalTime = LapRepository.ReadLine(line, template.RootObjectConfigModel.ArrivalTime.startIndex, template.RootObjectConfigModel.ArrivalTime.length); var circuitTime = LapRepository.ReadLine(line, template.RootObjectConfigModel.CircuitTime.startIndex, template.RootObjectConfigModel.CircuitTime.length); var id = Convert.ToInt64(LapRepository.ReadLine(line, template.RootObjectConfigModel.PilotId.startIndex, template.RootObjectConfigModel.PilotId.length)); var name = LapRepository.ReadLine(line, template.RootObjectConfigModel.PilotName.startIndex, template.RootObjectConfigModel.PilotName.length); var driver = Driver.Create(id, name); var lap = Lap.Create(arrivalTime, raceTracks, circuitTime, averageLap, driver.Id); lap.SetArrivalTimeInMinutes(calculate.ConvertHourToMinute(lap.ArrivalTime)); lap.SetCircuitTimeInSeconds(calculate.ConvertMinutesToSeconds(lap.CircuitTime)); LapRepository.AddDriver(driver); LapRepository.AddLap(lap); } }
private ZAMsettings() { UserProfiles = new SortedList <string, UserProfile>(); Collectors = new SortedList <string, Collector>(); Splits = new Splits(); Laps = new Lap(); }
public IHttpActionResult PutLap(int id, Lap lap) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != lap.ID) { return(BadRequest()); } db.Entry(lap).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!LapExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
private static List <TimeSpan> GetMaxLapTimeDurations(IEnumerable <Session> sessions) { var maxLapTimeDurations = new List <TimeSpan>(); foreach (var session in sessions) { var count = 0; Lap previousLap = null; foreach (var lap in session.Laps) { if (previousLap != null && (lap.LapType == LapType.Lap || lap.LapType == LapType.Stop)) { var duration = lap.Time - previousLap.Time; if (maxLapTimeDurations.Count <= count) { maxLapTimeDurations.Add(duration); } else if (maxLapTimeDurations[count] < duration) { maxLapTimeDurations[count] = duration; } count++; } previousLap = lap; } } return(maxLapTimeDurations); }
public void Process() { if (Race != null && Race.UnprocessedLaps != null) { foreach (string UnprocessedLap in Race.UnprocessedLaps) { string ul = UnprocessedLap; ul = PartString(ul, ProcessRaceFieldLength.Hour, out string hour); ul = PartString(ul, ProcessRaceFieldLength.RacerCode, out string racerCode); ul = PartString(ul, GetFirstNumberOccurrenceIndex(ul), out string racerName); ul = PartString(ul, ProcessRaceFieldLength.LapNumber, out string lapNumber); ul = PartString(ul, ProcessRaceFieldLength.LapTime, out string lapTime); string lapAVGSpeed = ul; if (racerCode.Length > 2) { racerCode = racerCode.Substring(0, 3); } if (!TryGetRacer(racerCode, out Racer racer)) { racer = CreateRacer(racerCode, racerName); Race.AddRacer(racer); } Lap lap = CreateLap(hour, lapNumber, lapTime, lapAVGSpeed); if (lap.LapNumber <= 4 && racer.Laps.Count < 4) { racer.AddLap(CreateLap(hour, lapNumber, lapTime, lapAVGSpeed)); } } } }
public void ManualDnf_WithRiderOnTrack_ShouldEndLap() { Beacon martijnBeacon = new Beacon(new byte[] { 0, 0, 0, 0, 0, 1 }, 0); Rider martijn = new Rider("Martijn", martijnBeacon); subject.AddRider(martijn); //rider enters start box startId.EmitIdEvent(martijn, new DateTime(2000, 1, 1, 1, 1, 1)); //Martijn triggers timing gate timer.EmitTriggerEvent(100, "Timer", 0, new DateTime(2000, 1, 1, 1, 2, 1)); subject.AddEvent(new ManualDNFEventArgs(DateTime.Now, martijn.Name, "staff")); source.Cancel(); race.Wait(); Assert.AreEqual(0, endId.KnownRiders.Count); Assert.AreEqual(1, subject.Laps.Count); Lap lap = subject.Laps[0]; Assert.IsTrue(lap.End is ManualDNFEvent); Assert.AreEqual(-1, lap.GetLapTime()); Assert.IsFalse(lap.Disqualified); }
public void Should_Return_Valid_Object_Line_Format_One() { string mockLine = "23:49:08.277 038 – F.MASSA 1 1:02.852 44,275"; var lap = Lap.BuildLapObject(mockLine); Assert.NotNull(lap); }
public EditLapAction(Lap lap, Lap oldLap, Session session) { this.lap = lap; this.session = session; this.oldLap = oldLap; this.newLap = (Lap)lap.Clone(); }
public void ValidateLap(Lap lap) { if (lap == null) { throw new Exception("Not a valid lap..."); } }
public void DeleteLap(Lap lap) { if (lap != null) { lap.Delete(); } }
public void Should_Return_Valid_Object_Line_Format_Two() { string mockLine = "23:49:11.075 002 – K.RAIKKONEN 1 1:04.108 43,408"; var lap = Lap.BuildLapObject(mockLine); Assert.NotNull(lap); }
private static bool IsPauseLapComparedTo(int lapIndex, List <Lap> laps, Lap intervalLap) { var lap = laps[lapIndex]; if (lap.ElapsedTime < 10) { return(false); } var isSlowerThanIntervalLap = lap.AverageSpeed < intervalLap.AverageSpeed; var isLessThanDoubleDistanceOfIntervalLap = lap.Distance < intervalLap.Distance * 2; var isGreatDistanceDifference = Math.Abs(lap.Distance - intervalLap.Distance) > Math.Max(lap.Distance, intervalLap.Distance) * 0.5; var isShortLap = lap.Distance < 500; var isStationary = lap.MovingTime < lap.ElapsedTime / 2; var isShortAndStationary = isShortLap && isStationary; var isShortAndSlower = isShortLap && isSlowerThanIntervalLap; var isLongAndSlowerAndDifferent = !isShortLap && isSlowerThanIntervalLap && isLessThanDoubleDistanceOfIntervalLap && isGreatDistanceDifference; var isIdenticalInDistance = Math.Abs(lap.Distance - intervalLap.Distance) < 20; var isIdenticalInDuration = Math.Abs(lap.ElapsedTime - intervalLap.ElapsedTime) < 10; var isIdentical = lap.Distance > 100 && isIdenticalInDistance && isIdenticalInDuration; if (isIdentical) { return(false); } return(isShortAndStationary || isShortAndSlower || isLongAndSlowerAndDifferent); }
public void Should_Return_Four_Valid_Laps() { List <Lap> totalValidLaps = new List <Lap>(); totalValidLaps.Add(new Lap() { LapNumber = 1 }); totalValidLaps.Add(new Lap() { LapNumber = 2 }); totalValidLaps.Add(new Lap() { LapNumber = 3 }); totalValidLaps.Add(new Lap() { LapNumber = 4 }); totalValidLaps.Add(new Lap() { LapNumber = 5 }); Assert.Equal(4, Lap.GetTotalValidLaps(totalValidLaps).ToList().Count); }
public void AddLap(GarminUnit garmin, Lap lap) { var l = new Laps() { AvgCadence = lap.AvgCadence, AvgHeartRage = lap.AvgHeartRate, Calories = lap.CaloriesBurned, EndLat = lap.End.lat, EndLon = lap.End.lon, GarminUnit = (int)garmin.ID, Index = lap.Index, Intensity = lap.Intensity, MaxHeartRage = lap.MaxHeartRate, MaxSpeed = lap.MaxSpeed, StartLat = lap.Begin.lat, StartLon = lap.Begin.lon, StartTime = lap.StartTime., TotalDist = lap.TotalDistance, TotalTime = lap.TotalTime, TriggerMethod = lap.TriggerMethod }; database.Laps.InsertOnSubmit(l); database.SubmitChanges(); } }
static IList <Driver> PopulateDrivers(string[] laps) { List <Driver> drivers = new List <Driver>(); try{ foreach (var lap in laps.Skip(1)) { string[] lapProps = lap.Split("\t"); string[] driverProps = lapProps[1].Split(" – "); Lap l = new Lap(lapProps[0], lapProps[2], lapProps[3], lapProps[4]); Driver d = new Driver(driverProps[0], driverProps[1]); if (!drivers.Exists(x => x.Id == int.Parse(driverProps[0]))) { d.Laps = new List <Lap>(); d.Laps.Add(l); drivers.Add(d); } else { Driver existingDriver = drivers.First(x => x.Id == int.Parse(driverProps[0])); existingDriver.Laps.Add(l); } } return(drivers); }catch (Exception e) { Console.WriteLine("Problem to get drivers properties"); Console.WriteLine(e.Message); return(drivers); } }
public void CompareTo_ShouldConsiderDNFSlower() { Beacon martijnBeacon = new Beacon(new byte[] { 0, 0, 0, 0, 0, 1 }, 2); Rider martijn = new Rider("Martijn", martijnBeacon); //make a regular lap IdEvent startId = new IdEvent(DateTime.Now, martijn, "StartId", Direction.Enter); TimingEvent startTiming = new TimingEvent(DateTime.Now, martijn, 100, 0); IdEvent endId = new IdEvent(DateTime.Now, martijn, "EndId", Direction.Enter); TimingEvent endTiming = new TimingEvent(DateTime.Now, martijn, 200, 1); FinishedEvent finish = new FinishedEvent(startId, startTiming, endTiming, endId); Lap normalLap = new Lap(finish); //make a DNF lap IdEvent dnfStartId = new IdEvent(DateTime.Now, martijn, "StartId", Direction.Enter); ManualDNFEvent manualDnf = new ManualDNFEvent(dnfStartId, "staff"); UnitDNFEvent unitDnf = new UnitDNFEvent(finish, dnfStartId); Lap manualDnfLap = new Lap(manualDnf); Lap unitDnfLap = new Lap(unitDnf); //a dnf lap should always be slower (bigger) than a finished lap Assert.AreEqual(1, manualDnfLap.CompareTo(normalLap)); Assert.AreEqual(-1, normalLap.CompareTo(manualDnfLap)); Assert.AreEqual(1, unitDnfLap.CompareTo(normalLap)); Assert.AreEqual(-1, normalLap.CompareTo(unitDnfLap)); //dnf laps have no mutual ordering Assert.AreEqual(1, manualDnfLap.CompareTo(unitDnfLap)); Assert.AreEqual(1, unitDnfLap.CompareTo(manualDnfLap)); }
public void GetFastestLap_NoLaps_ReturnsLapWithZeros() { Lap fastestLap = _lapTimer.GetFastestLap(); TimeSpan zeroTime = new TimeSpan(0); Assert.Equal(0, fastestLap.Number); Assert.Equal(zeroTime, fastestLap.Time); }
public Lap LookupLap(Guid identifier) { Lap lap = FindLap(identifier); ValidateLap(lap); return(lap); }
public TelemetryLapComplete(Aggregates.Telemetry tel, TelemetryDriver driver, Lap lap) { Telemetry = tel; Driver = driver; Lap = lap; }
private void ResetMouseHoverHandle() { mouseHoverHandle = null; activeLap = null; if (activeHandle != null) { // reset handle drawer to standard handle drawer activeHandle.MarkerDrawer = CurrentSession.Settings.MarkerDrawers[MarkerType.Handle]; } activeHandle = null; }
public ILap GetLapTime(int l) { if (rFactor.Simulator.Modules.Times_History_LapTimes == false) return new Lap(0, 0, 0, 0); int lapsbase = __LapsData.ToInt32(); float start = rFactor.Game.ReadFloat(new IntPtr(lapsbase + l*0x04*0x06)); float s1 = rFactor.Game.ReadFloat(new IntPtr(lapsbase + 0x04 + l*0x04*0x06)); float s2 = rFactor.Game.ReadFloat(new IntPtr(lapsbase + 0x08 + l*0x04*0x06)); float s3 = rFactor.Game.ReadFloat(new IntPtr(lapsbase + 0x0C + l*0x04*0x06)); s3 -= s2; s2 -= s1; Lap lap = new Lap(l, s1, s2, s3); return lap; }
public List<ILap> GetLapTimes() { List<ILap> laps = new List<ILap>(); if (rFactor.Simulator.Modules.Times_History_LapTimes == false) return laps; int lapsbase = __LapsData.ToInt32(); for (int l = 0; l < this.Laps + 1; l++) { float start = rFactor.Game.ReadFloat(new IntPtr(lapsbase + l * 0x04 * 0x06)); float s1 = rFactor.Game.ReadFloat(new IntPtr(lapsbase + 0x04 + l * 0x04 * 0x06)); float s2 = rFactor.Game.ReadFloat(new IntPtr(lapsbase + 0x08 + l * 0x04 * 0x06)); float s3 = rFactor.Game.ReadFloat(new IntPtr(lapsbase + 0x0C + l * 0x04 * 0x06)); s3 -= s2; s2 -= s1; Lap lap = new Lap(l, s1, s2, s3); laps.Add(lap); } return laps; }
public LapAdded(ScoringDriver driver, Lap lap) { Driver = driver; Lap = lap; }
public DeleteLapAction(Lap lap, Session session) { this.lap = lap; this.session = session; }
/* private void ImportGPX10() { if (BeginWork != null) BeginWork(this, new EventArgs()); NumberFormatInfo nfi = new NumberFormatInfo(); nfi.NumberDecimalSeparator = "."; XmlTextReader sr = new XmlTextReader(fileName); XmlSerializer xSerializer = new XmlSerializer(typeof(gpx10Type)); gpx10Type gpx = (gpx10Type)xSerializer.Deserialize(sr); sr.Close(); XmlNamespaceManager nsManager = new XmlNamespaceManager(sr.NameTable); nsManager.AddNamespace("st", "urn:uuid:D0EB2ED5-49B6-44e3-B13C-CF15BE7DD7DD"); importResult = new ImportResult(); // route List<RouteSegment> routeSegments = new List<RouteSegment>(); foreach (gpxTrk trk in gpx.trk) { for (int i = trk.trkseg.GetLowerBound(0); i <= trk.trkseg.GetUpperBound(0); i++) { RouteSegment routeSegment = new RouteSegment(); for (int j = trk.trkseg.GetLowerBound(1); j <= trk.trkseg.GetUpperBound(1); j++) { gpxTrkTrksegTrkpt wpt = trk.trkseg[i][j]; double lat = (double)wpt.lat; double lon = (double)wpt.lon; DateTime time = wpt.time; double? heartRate = null; double? altitude = null; routeSegment.Waypoints.Add(new Waypoint(time, new LongLat(lon, lat), altitude, heartRate)); } routeSegments.Add(routeSegment); } } importResult.Route = new Route(routeSegments); // laps LapCollection laps = new LapCollection(); importResult.Laps = laps; if (EndWork != null) EndWork(this, new EventArgs()); } */ private void ImportGPX11() { ImportResult = new ImportResult(); var isGPX10 = (GPXUtil.GetGPXVersion(fileName) == GPXVersion.GPX10); string gpx10convertedFileName = null; string polarConvertedFileName = null; var originalFileName = fileName; if (BeginWork != null) BeginWork(this, new EventArgs()); // check if the file is in gpx 1.0 format and convert it to gpx 1.1 if necessary if (isGPX10) { gpx10convertedFileName = Path.GetTempFileName(); GPXUtil.ConvertGPX10ToGPX11(fileName, gpx10convertedFileName); fileName = gpx10convertedFileName; } // check if the file is an invalid Polar ProTrainer file and correct if necessary if (PolarProTrainerUtil.IsPolarProTrainerGPXFile(fileName)) { polarConvertedFileName = Path.GetTempFileName(); PolarProTrainerUtil.CorrectPolarProTrainerGPXFile(fileName, polarConvertedFileName); fileName = polarConvertedFileName; } var nfi = new NumberFormatInfo { NumberDecimalSeparator = "." }; var sr = new XmlTextReader(fileName); var xSerializer = new XmlSerializer(typeof(gpx11Type)); var gpx11 = (gpx11Type)xSerializer.Deserialize(sr); sr.Close(); var nsManager = new XmlNamespaceManager(sr.NameTable); // add namespace for split times and heart rates (from SportsTracks software) nsManager.AddNamespace("st", "urn:uuid:D0EB2ED5-49B6-44e3-B13C-CF15BE7DD7DD"); // add namespace for map reading information (QuickRoute native) nsManager.AddNamespace("mr", "http://www.matstroeng.se/quickroute/map-reading"); // pre-store heart rates in dictionary (if present) var heartRates = new Dictionary<DateTime, double>(); // pre-store map-readings in map reading collection (if present) var mapReadings = new List<DateTime>(); if (gpx11.extensions != null && gpx11.extensions.Any != null) { foreach (var element in gpx11.extensions.Any) { if (element.Name == "st:activity") { var nodes = element.SelectNodes("st:heartRateTrack/st:heartRate[@time and @bpm]", nsManager); if (nodes != null) { foreach (XmlNode node in nodes) { DateTime time; double bpm; if (DateTime.TryParse(node.Attributes["time"].Value, out time) && double.TryParse(node.Attributes["bpm"].Value, NumberStyles.Any, nfi, out bpm)) { time = time.ToUniversalTime(); if(!heartRates.ContainsKey(time)) heartRates.Add(time, bpm); } } } } if(element.Name == "mr:map-reading") { DateTime start, end; if (DateTime.TryParse(element.Attributes["start"].Value, out start) && DateTime.TryParse(element.Attributes["end"].Value, out end)) { mapReadings.Add(start.ToUniversalTime()); mapReadings.Add(end.ToUniversalTime()); } } } } mapReadings = FilterMapReadings(mapReadings); // QuickRoute route var noOfWaypoints = 0; var noOfWaypointsWithTimes = 0; var routeSegments = new List<RouteSegment>(); // first use GPX track if (gpx11.trk != null) { foreach (var trk in gpx11.trk) { // Garmin Training Center exports each lap as a separate trkseg with end time of trkseg n equal to start time of trkseg n+1 // handle this issue foreach (var trkseg in trk.trkseg) { var routeSegment = new RouteSegment(); wptType lastWpt = null; if (trkseg.trkpt != null) { foreach (var wpt in trkseg.trkpt) { if (lastWpt == null || wpt.time != lastWpt.time) { if (wpt.extensions != null && wpt.extensions.Any != null && wpt.extensions.Any[0].LocalName == "timerPaused") { // new route segment ahead if (routeSegment.Waypoints.Count > 0) routeSegments.Add(routeSegment); routeSegment = new RouteSegment(); } else { var lat = (double)wpt.lat; var lon = (double)wpt.lon; double? heartRate = null; double? altitude = null; // check for heartrate in SportsTracks extensions if (heartRates.ContainsKey(wpt.time)) heartRate = heartRates[wpt.time]; // check for heartrate in Garmin Trackpoint Extensions heartRate = GetGarminHeartRateFromWaypoint(wpt) ?? heartRate; if (wpt.eleSpecified) { altitude = (double?)wpt.ele; } if (wpt.timeSpecified) { routeSegment.Waypoints.Add(new Waypoint(wpt.time, new LongLat(lon, lat), altitude, heartRate, null)); noOfWaypointsWithTimes++; lastWpt = wpt; } } noOfWaypoints++; } } } if (routeSegment.Waypoints.Count > 0) routeSegments.Add(routeSegment); } } } // if no GPX track - use GPX route if (noOfWaypointsWithTimes == 0 && gpx11.rte != null) { foreach (var route in gpx11.rte) { var routeSegment = new RouteSegment(); foreach (var rtept in route.rtept) { if (rtept.extensions != null && rtept.extensions.Any != null && rtept.extensions.Any[0].LocalName == "timerPaused") { // new route segment ahead if (routeSegment.Waypoints.Count > 0) routeSegments.Add(routeSegment); routeSegment = new RouteSegment(); } else { var lat = (double) rtept.lat; var lon = (double) rtept.lon; double? heartRate = null; double? altitude = null; if (heartRates.ContainsKey(rtept.time)) heartRate = heartRates[rtept.time]; if (rtept.eleSpecified) { altitude = (double?) rtept.ele; } if (rtept.timeSpecified) { routeSegment.Waypoints.Add(new Waypoint(rtept.time, new LongLat(lon, lat), altitude, heartRate, null)); noOfWaypointsWithTimes++; } } noOfWaypoints++; } if (routeSegment.Waypoints.Count > 0) routeSegments.Add(routeSegment); } } // add map reading waypoints routeSegments = Route.AddMapReadingWaypoints(routeSegments, mapReadings); // concat route segments if they are close enough (oddly enough, Garmin Training Center v2 seems to create a trkseg for each lap) var lapsFromConcatenatedRouteSegments = new List<Lap>(); if (routeSegments.Count > 0) { var concatenatedRouteSegments = new List<RouteSegment>() { routeSegments[0] }; for (var i = 1; i < routeSegments.Count; i++) { if (concatenatedRouteSegments[concatenatedRouteSegments.Count - 1].LastWaypoint.Time.AddSeconds(10) > routeSegments[i].FirstWaypoint.Time) { lapsFromConcatenatedRouteSegments.Add(new Lap(concatenatedRouteSegments[concatenatedRouteSegments.Count - 1].LastWaypoint.Time, LapType.Lap)); concatenatedRouteSegments[concatenatedRouteSegments.Count - 1].Waypoints.AddRange(routeSegments[i].Waypoints); } } routeSegments = concatenatedRouteSegments; } importResult.Succeeded = (noOfWaypointsWithTimes > 0); if (ImportResult.Succeeded) { importResult.Route = new Route(routeSegments); // laps var laps = new LapCollection(); var startTime = ImportResult.Route.FirstWaypoint.Time; // from GPX st:split if (gpx11.extensions != null && gpx11.extensions.Any != null) { foreach (var element in gpx11.extensions.Any) { if (element.Name == "st:activity") { var nodes = element.SelectNodes("st:splits/st:split[@time]", nsManager); if (nodes != null) { foreach (XmlNode node in nodes) { var elapsedTime = double.Parse(node.Attributes["time"].Value, nfi); var lap = new Lap(startTime.AddSeconds(elapsedTime), LapType.Lap); laps.Add(lap); } } } } } // from GPX waypoints if (gpx11.wpt != null && laps.Count == 0) { foreach (var waypoint in gpx11.wpt) { if (waypoint.timeSpecified) { laps.Add(new Lap(waypoint.time, LapType.Lap)); } } } laps.AddRange(lapsFromConcatenatedRouteSegments); foreach (var rs in routeSegments) { laps.Add(new Lap(rs.FirstWaypoint.Time, LapType.Start)); laps.Add(new Lap(rs.LastWaypoint.Time, LapType.Stop)); } importResult.Laps = laps; } else { if (noOfWaypoints == 0) { importResult.Error = ImportError.NoWaypoints; } else if (noOfWaypointsWithTimes == 0) { importResult.Error = ImportError.NoWaypointTimes; } } if (gpx10convertedFileName != null) { File.Delete(gpx10convertedFileName); fileName = originalFileName; } if (polarConvertedFileName != null) { File.Delete(polarConvertedFileName); fileName = originalFileName; } // import Polar HRM file with same base file name as the gpx file, if existing var extension = new FileInfo(fileName).Extension; if(extension != "") { string hrmFileName = new FileInfo(fileName).FullName.Replace(extension, ".hrm"); if(File.Exists(hrmFileName)) { new PolarHRMImporter().AddLapsAndHRData(hrmFileName, importResult); } } if (EndWork != null) EndWork(this, new EventArgs()); }
private static Session ReadSession(BinaryReader reader, int length) { List<DateTime> mapReadingList = null; Route route = null; HandleCollection handles = null; LongLat projectionOrigin = null; LapCollection laps = null; var startPos = reader.BaseStream.Position; SessionInfo sessionInfo = null; DateTime lastTime; while (reader.BaseStream.Position < startPos + length) { var tag = (Tags)reader.ReadByte(); var tagLength = Convert.ToInt32(reader.ReadUInt32()); switch (tag) { case Tags.Route: var attributes = reader.ReadUInt16(); var extraWaypointAttributesLength = reader.ReadUInt16(); var routeSegments = new List<RouteSegment>(); var segmentCount = reader.ReadUInt32(); lastTime = DateTime.MinValue; for (var i = 0; i < segmentCount; i++) { var rs = new RouteSegment(); var waypointCount = reader.ReadUInt32(); for (var j = 0; j < waypointCount; j++) { var w = new Waypoint(); w.LongLat = ReadLongLat(reader); w.Time = ReadTime(lastTime, reader); lastTime = w.Time; if ((attributes & (UInt16)WaypointAttribute.HeartRate) == (UInt16)WaypointAttribute.HeartRate) { w.HeartRate = reader.ReadByte(); } if ((attributes & (UInt16)WaypointAttribute.Altitude) == (UInt16)WaypointAttribute.Altitude) { w.Altitude = reader.ReadInt16(); } reader.BaseStream.Position += extraWaypointAttributesLength; // for forward compatibility rs.Waypoints.Add(w); } routeSegments.Add(rs); } route = new Route(routeSegments); break; case Tags.Handles: handles = new HandleCollection(); var handleCount = reader.ReadUInt32(); var handleMarkerDrawer = SessionSettings.CreateDefaultMarkerDrawers()[MarkerType.Handle]; for (var i = 0; i < handleCount; i++) { var handle = new Handle(); // transformation matrix handle.TransformationMatrix = new GeneralMatrix(3, 3); for (var j = 0; j < 9; j++) { handle.TransformationMatrix.SetElement(j / 3, j % 3, reader.ReadDouble()); } // parameterized location var segmentIndex = Convert.ToInt32(reader.ReadUInt32()); var value = reader.ReadDouble(); handle.ParameterizedLocation = new ParameterizedLocation(segmentIndex, value); // pixel location handle.Location = new PointD(reader.ReadDouble(), reader.ReadDouble()); // type handle.Type = (Handle.HandleType)reader.ReadInt16(); // use default marker drawer handle.MarkerDrawer = handleMarkerDrawer; handles.Add(handle); } break; case Tags.ProjectionOrigin: projectionOrigin = ReadLongLat(reader); break; case Tags.Laps: laps = new LapCollection(); var lapCount = reader.ReadUInt32(); for (var i = 0; i < lapCount; i++) { var lap = new Lap(); lap.Time = DateTime.FromBinary(reader.ReadInt64()); lap.LapType = (LapType)reader.ReadByte(); laps.Add(lap); } break; case Tags.SessionInfo: sessionInfo = new SessionInfo(); sessionInfo.Person = new SessionPerson(); sessionInfo.Person.Name = ReadString(reader); sessionInfo.Person.Club = ReadString(reader); sessionInfo.Person.Id = reader.ReadUInt32(); sessionInfo.Description = ReadString(reader); // when more fields are added, check so that tagLength is not passed break; case Tags.MapReadingInfo: mapReadingList = new List<DateTime>(); lastTime = DateTime.MinValue; var startPosition = reader.BaseStream.Position; while (reader.BaseStream.Position - startPosition < tagLength) { var time = ReadTime(lastTime, reader); mapReadingList.Add(time); lastTime = time; } break; default: reader.BaseStream.Position += tagLength; break; } } if(mapReadingList != null && route != null) route = new Route(Route.AddMapReadingWaypoints(route.Segments, mapReadingList)); var session = new Session( route, laps, new Size(0, 0), handles != null && handles.Count > 0 ? handles[0].TransformationMatrix : null, projectionOrigin, new SessionSettings()); if (handles != null) { foreach (var h in handles) { session.AddHandle(h); } } if (sessionInfo != null) session.SessionInfo = sessionInfo; return session; }
public void DrawActiveHandle(ParameterizedLocation pl) { // mouse hover over route if (activeHandle != null) { // reset handle drawer to standard handle drawer activeHandle.MarkerDrawer = CurrentSession.Settings.MarkerDrawers[MarkerType.Handle]; } activeHandle = null; activeLap = null; PointD routeLocation = CurrentSession.AdjustedRoute.GetLocationFromParameterizedLocation(pl); if (pl != null) { GeneralMatrix transformationMatrix = CurrentSession.GetTransformationMatrixFromParameterizedLocation(pl); mouseHoverHandle = new Handle(pl, routeLocation, transformationMatrix, CurrentSession.Settings.MarkerDrawers[MarkerType.MouseHover]); } else { mouseHoverHandle = null; } DrawMap(MapDrawingFlags.Markers); }
private void CheckMouseHovering() { // location of mouse pointer in original map coordinates PointD mouseLocation = new PointD((mouseInfo.MouseMoveArgs.X + scrX.Value - origo.X), (mouseInfo.MouseMoveArgs.Y + scrY.Value - origo.Y)) / zoom; double distanceToRoute; ParameterizedLocation closestPL = CurrentSession.AdjustedRoute.GetClosestParameterizedLocation(mouseLocation, out distanceToRoute); if (!movingActiveHandleNow && !movingActiveLapNow) { if (closestPL == null) { // not close to route if(mouseHoverHandle != null) { ResetMouseHoverHandle(); DrawMap(MapDrawingFlags.Markers); } return; } // check if close to existing handle double closestHandleDistance = 0; double closestLapDistance = 0; Handle closestHandle = null; Lap closestLap = null; // Shift key prevents check if close to handle or lap bool shiftDown = (ModifierKeys & Keys.Shift) == Keys.Shift; PointD routeLocation = CurrentSession.AdjustedRoute.GetLocationFromParameterizedLocation(closestPL); if (!shiftDown && currentMouseTool == MouseTool.AdjustRoute) closestHandle = GetClosestHandle(routeLocation, out closestHandleDistance); if (!shiftDown) closestLap = GetClosestLap(routeLocation, out closestLapDistance); if (distanceToRoute >= ROUTE_CLOSENESS_TOLERANCE) { // not close to route ResetMouseHoverHandle(); if (RouteMouseHover != null) RouteMouseHover(this, new RouteMouseHoverEventArgs(closestPL, false)); } else if (closestHandle != null && closestHandleDistance < ROUTE_CLOSENESS_TOLERANCE && !(closestLap != null && closestLapDistance * 1.00001 < closestHandleDistance)) { // close to existing handle, use it as active handle if (activeHandle != null) { // reset previous handle drawer activeHandle.MarkerDrawer = CurrentSession.Settings.MarkerDrawers[MarkerType.Handle]; } activeHandle = closestHandle; activeHandleOldLocation = activeHandle.Location; activeHandleOffset = mouseLocation - activeHandle.Location; activeHandle.MarkerDrawer = CurrentSession.Settings.MarkerDrawers[MarkerType.ActiveHandle]; mouseHoverHandle = null; activeLap = null; if (RouteMouseHover != null) RouteMouseHover(this, new RouteMouseHoverEventArgs(activeHandle.ParameterizedLocation, true)); } else if (closestLap != null && closestLapDistance < LAP_CLOSENESS_TOLERANCE) { // close to existing lap, create a mouse hover over this lap ParameterizedLocation pl = CurrentSession.Route.GetParameterizedLocationFromTime(closestLap.Time); PointD lapLocation = CurrentSession.AdjustedRoute.GetLocationFromParameterizedLocation(pl); GeneralMatrix transformationMatrix = CurrentSession.GetTransformationMatrixFromParameterizedLocation(pl); mouseHoverHandle = new Handle(pl, closestLap.Time, lapLocation, transformationMatrix, CurrentSession.Settings.MarkerDrawers[MarkerType.MouseHover]); if (RouteMouseHover != null) RouteMouseHover(this, new RouteMouseHoverEventArgs(pl, true)); activeLap = closestLap; } else { // mouse hover over route if (activeHandle != null) { // reset handle drawer to standard handle drawer activeHandle.MarkerDrawer = CurrentSession.Settings.MarkerDrawers[MarkerType.Handle]; } activeHandle = null; activeLap = null; GeneralMatrix transformationMatrix = CurrentSession.GetTransformationMatrixFromParameterizedLocation(closestPL); mouseHoverHandle = new Handle(closestPL, routeLocation, transformationMatrix, CurrentSession.Settings.MarkerDrawers[MarkerType.MouseHover]); if (RouteMouseHover != null) RouteMouseHover(this, new RouteMouseHoverEventArgs(closestPL, true)); } DrawMap(MapDrawingFlags.Markers); } else if (movingActiveHandleNow) { activeHandle.Location = mouseLocation - activeHandleOffset; CurrentSession.UpdateHandle(activeHandle); DrawMap(MapDrawingFlags.Route | MapDrawingFlags.Markers); } else if (movingActiveLapNow) { if (closestPL == null) return; // not close to the route activeLap.Time = CurrentSession.Route.GetTimeFromParameterizedLocation(closestPL); DrawMap(MapDrawingFlags.Markers); } }
/// <summary> /// Makes the route line for the specified lap to appear in a different alpha adjustment than the rest of the course /// </summary> /// <param name="session"></param> /// <param name="lap"></param> /// <param name="lapAlphaAdjustment"></param> /// <param name="courseAlphaAdjustment"></param> /// <param name="defaultAlphaAdjustment"></param> public void AlphaAdjustLap(Session session, Lap lap, double lapAlphaAdjustment, double courseAlphaAdjustment, double defaultAlphaAdjustment) { Route r = session.Route; bool lapExists = session.Laps.Contains(lap) && lap.LapType != LapType.Start; int lapIndex = 0; if (lapExists) { // get the index of the lap for (int i = 0; i < session.Laps.Count; i++) { if (session.Laps[i] == lap) { lapIndex = i; break; } } Lap lastLap = session.Laps[lapIndex - 1]; var aac = new List<AlphaAdjustmentChange>(); if (r.FirstWaypoint.Time < lastLap.Time) aac.Add(new AlphaAdjustmentChange(r.GetParameterizedLocationFromTime(r.FirstWaypoint.Time), courseAlphaAdjustment)); aac.Add(new AlphaAdjustmentChange(r.GetParameterizedLocationFromTime(lastLap.Time), lapAlphaAdjustment)); aac.Add(new AlphaAdjustmentChange(r.GetParameterizedLocationFromTime(lap.Time), courseAlphaAdjustment)); session.AlphaAdjustmentChanges = aac; DrawMap(MapDrawingFlags.Markers | MapDrawingFlags.Route); } else { var aac = new List<AlphaAdjustmentChange>(); aac.Add(new AlphaAdjustmentChange(r.GetParameterizedLocationFromTime(r.FirstWaypoint.Time), defaultAlphaAdjustment)); session.AlphaAdjustmentChanges = aac; DrawMap(MapDrawingFlags.Markers | MapDrawingFlags.Route); } }
public void DeleteLap(Lap lap) { ExecuteAction(new DeleteLapAction(lap, CurrentSession)); DrawMap(MapDrawingFlags.Markers); }
public void Import() { importResult = new ImportResult(); if (BeginWork != null) BeginWork(this, new EventArgs()); StreamReader reader = new StreamReader(FileName); RouteSegment rs = new RouteSegment(); LapCollection laps = new LapCollection(); int i; string[] atoms; string line; for (i = 0; i < 3; i++) reader.ReadLine(); // start time atoms = reader.ReadLine().Split("\t".ToCharArray()); DateTime startTime = DateTime.MinValue; int firstColonPosition = atoms[1].IndexOf(":"); int lastColonPosition = atoms[1].LastIndexOf(":"); int length = lastColonPosition + 2 - firstColonPosition + 2 + 1; if (length > 0) { if(DateTime.TryParse(atoms[1].Substring(firstColonPosition - 2, lastColonPosition + 2 - firstColonPosition + 2 + 1), out startTime)) { startTime = startTime.ToUniversalTime(); } } // go to start of coordinates i = 0; while (i < 5 && !reader.EndOfStream) { line = reader.ReadLine(); if (line == "") i++; } reader.ReadLine(); reader.ReadLine(); // read all coordinates while (!reader.EndOfStream) { line = reader.ReadLine(); if (line == "") break; atoms = line.Split("\t".ToCharArray()); Waypoint w = new Waypoint(); w.Time = startTime.AddSeconds(Convert.ToInt32(atoms[0])); w.LongLat = new LongLat(ParseFRWDLongLatString(atoms[5]), ParseFRWDLongLatString(atoms[4])); double altitude; double.TryParse(LocalizeDecimalString(atoms[6]), out altitude); w.Altitude = altitude; double heartRate; double.TryParse(LocalizeDecimalString(atoms[9]), out heartRate); w.HeartRate = heartRate; rs.Waypoints.Add(w); if (atoms[1] != "") { // lap Lap lap = new Lap(); lap.LapType = LapType.Lap; lap.Time = w.Time; laps.Add(lap); } } if (laps.Count > 0) laps[0].LapType = LapType.Start; if (laps.Count > 1) laps[laps.Count - 1].LapType = LapType.Stop; importResult.Laps = laps; List<RouteSegment> routeSegments = new List<RouteSegment>(); if(rs.Waypoints.Count > 0) { routeSegments.Add(rs); importResult.Route = new Route(routeSegments); importResult.Succeeded = true; } else { importResult.Succeeded = false; importResult.Error = ImportError.NoWaypoints; } reader.Close(); if (EndWork != null) EndWork(this, new EventArgs()); }
private void CanvasPanel_MouseDown(object sender, MouseEventArgs e) { mouseInfo.MouseDownArgs = e; if (e.Button == MouseButtons.Right && (scrXPanel.Visible || scrY.Visible)) { // move map BeginMoveMapWithMouse(); } else { switch (currentMouseTool) { case MouseTool.AdjustRoute: #region AdjustRoute // is there a mouse hover handle? if (mouseHoverHandle != null) { // transform mouse hover handle to adjustment handle activeHandle = mouseHoverHandle; activeHandleOldLocation = activeHandle.Location; PointD mouseLocation = new PointD((mouseInfo.MouseDownArgs.X + scrX.Value - origo.X), (mouseInfo.MouseDownArgs.Y + scrY.Value - origo.Y)) / zoom; activeHandleOffset = mouseLocation - mouseHoverHandle.Location; BeginActiveHandleMoving(); } else if (activeHandle != null) { if ((ModifierKeys & Keys.Control) == Keys.Control) { // delete active handle DeleteActiveHandle(); } else { BeginActiveHandleMoving(); activeHandle.MarkerDrawer = CurrentSession.Settings.MarkerDrawers[MarkerType.MovingActiveHandle]; } } else { BeginMoveMapWithMouse(); } break; #endregion case MouseTool.ZoomIn: break; case MouseTool.ZoomOut: ZoomOut(); break; case MouseTool.Cut: #region Cut // cut route // determine the handle where we should cut Handle cutHandle = null; if (activeHandle != null) { cutHandle = activeHandle; } else if (mouseHoverHandle != null) { cutHandle = mouseHoverHandle; } else { BeginMoveMapWithMouse(); } if (cutHandle != null) { // if not at a lap, round time to nearest second DateTime cutTime; if (cutHandle.Time.HasValue) { cutTime = cutHandle.Time.Value; } else { cutTime = CurrentSession.Route.GetTimeFromParameterizedLocation(cutHandle.ParameterizedLocation); cutTime = new DateTime(TimeSpan.TicksPerSecond * (long)Math.Round((double)cutTime.Ticks / TimeSpan.TicksPerSecond), cutTime.Kind); // round to nearest second } Cut(cutHandle.ParameterizedLocation, cutTime); } break; #endregion case MouseTool.Lap: #region Lap if ((ModifierKeys & Keys.Control) == Keys.Control) { // Ctrl pressed: delete lap if (activeLap != null && activeLap.LapType == LapType.Lap) { // delete lap ExecuteAction(new DeleteLapAction(activeLap, CurrentSession)); DrawMap(MapDrawingFlags.Markers); } else if(activeLap == null) { BeginMoveMapWithMouse(); } } else { if (activeLap != null && activeLap.LapType == LapType.Lap) { // Close to lap: begin move lap movingActiveLapNow = true; oldActiveLap = (Lap)activeLap.Clone(); } else if(activeLap == null) { // add lap Handle addLapHandle = null; if (activeHandle != null) { addLapHandle = activeHandle; } else if (mouseHoverHandle != null) { addLapHandle = mouseHoverHandle; } else { BeginMoveMapWithMouse(); } if (addLapHandle != null) { bool showLapTimeForm = ((ModifierKeys & Keys.Shift) == Keys.Shift); AddLap(addLapHandle.ParameterizedLocation, showLapTimeForm); } } } break; default: BeginMoveMapWithMouse(); break; #endregion } } }
public ILap GetLapTime(int l) { int lapsbase = __LapsData.ToInt32(); float start = rFactor.Game.ReadFloat(new IntPtr(lapsbase + l*0x04*0x06)); float s1 = rFactor.Game.ReadFloat(new IntPtr(lapsbase + 0x04 + l*0x04*0x06)); float s2 = rFactor.Game.ReadFloat(new IntPtr(lapsbase + 0x08 + l*0x04*0x06)); float s3 = rFactor.Game.ReadFloat(new IntPtr(lapsbase + 0x0C + l*0x04*0x06)); s3 -= s2; s2 -= s1; Lap lap = new Lap(l, s1, s2, s3); return lap; }
public void TestMethod1() { Lap lap = new Lap(); Assert.AreEqual(lap, lap); }
public AddLapAction(Lap lap, Session session) { this.lap = lap; this.session = session; }