-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTLLocator.m
616 lines (546 loc) · 22.1 KB
/
TLLocator.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
//
// TLLocator.m
// Mercatalog
//
// Created by Nathan Vander Wilt on 10/9/08.
// Copyright 2008 __MyCompanyName__. All rights reserved.
//
#import "TLLocator.h"
#import "TLLibraryHost.h"
#import "TLTrack.h"
#import "TLPhoto.h"
#import "TLWaypoint.h"
#import "TLLocation.h"
#import "TLTimestamp.h"
#import "TLCocoaToolbag.h"
#include "TLFloat.h"
#include "TLGeoidGeometry.h"
#pragma mark Interpolation factors
static const double TLLocatorHomeAcceleration = 0.025;
static const double TLLocatorSnapTolerance = 0.2;
static TLProjectionGeoidRef TLLocatorInterpolationGeoid(void);
static TLLocation* TLLocatorInterpolate(TLTimestamp* targetTimestamp,
TLWaypoint* earlierWaypoint,
TLWaypoint* laterWaypoint,
TLLocation* homeLocation,
BOOL interpolateWhenPossible);
#pragma mark Main implementation
@implementation TLLocator
#pragma mark Class defaults
+ (TLLocation*)timbuktu {
// based on to http://en.wikipedia.org/wiki/Timbuktu
TLCoordinate timbuktuCoord = TLCoordinateMake(16.7759,-3.0094);
TLCoordinateAccuracy timbuktuHorzAccuracy = 4200.0;
TLCoordinateAltitude timbuktuAltitude = 261.0;
return [TLLocation locationWithCoordinate:timbuktuCoord
horizontalAccuracy:timbuktuHorzAccuracy
altitude:timbuktuAltitude
verticalAccuracy:TLCoordinateAccuracyUnknown];
}
+ (TLLocation*)timeZoneCity {
/* Information about the closest city chosen in time zone preferences is stored under key
com.apple.TimeZonePref.Last_Selected_City in /Library/Preferences/.GlobalPreferences:
CFArrayRef info = CFPreferencesCopyValue(CFSTR("com.apple.TimeZonePref.Last_Selected_City"),
kCFPreferencesAnyApplication,
kCFPreferencesAnyUser,
kCFPreferencesCurrentHost); */
enum TL_TimeZoneCityIndexes {
TLTimeZoneCityLatitude = 0,
TLTimeZoneCityLongitude,
TLTimeZoneCityUnknownIntString,
TLTimeZoneCityZoneName,
TLTimeZoneCityCountryCode,
TLTimeZoneCityCityName1,
TLTimeZoneCityNationName1,
TLTimeZoneCityCityName2,
TLTimeZoneCityNationName2
};
NSArray* cityInfo = [[NSUserDefaults standardUserDefaults]
arrayForKey:@"com.apple.TimeZonePref.Last_Selected_City"];
NSString* latString = [cityInfo objectAtIndex:TLTimeZoneCityLatitude];
NSString* lonString = [cityInfo objectAtIndex:TLTimeZoneCityLongitude];
TLLocation* cityLocation = nil;
if ([latString isKindOfClass:[NSString class]] &&
[lonString isKindOfClass:[NSString class]])
{
TLCoordinateDegrees latitude = [latString doubleValue];
TLCoordinateDegrees longitude = [lonString doubleValue];
if (TLFloatBetweenInclusive(latitude, -90.0, 90.0) &&
TLFloatBetweenInclusive(longitude, -180.0, 180.0) &&
!(latitude == 0.0 && longitude == 0.0))
{
TLCoordinate cityCoord = TLCoordinateMake(latitude, longitude);
const TLCoordinateAccuracy cityAccuracy = 10000.0;
cityLocation = [TLLocation locationWithCoordinate:cityCoord
horizontalAccuracy:cityAccuracy];
}
}
return cityLocation;
}
+ (TLLocation*)defaultHomeBase {
TLLocation* defaultHomeBase = [self timeZoneCity];
if (!defaultHomeBase) {
defaultHomeBase = [self timbuktu];
}
return defaultHomeBase;
}
#pragma mark Lifecycle
- (id)init {
self = [super init];
if (self) {
// ...
}
return self;
}
- (void)dealloc {
// ...
[super dealloc];
}
#pragma mark Accessors
@synthesize modelContext;
- (NSArray*)evidenceTracks {
TLLibraryHost* host = [TLLibraryHost libraryHostForContext:[self modelContext]];
return [host allTracks];
}
- (NSArray*)evidencePhotos {
TLLibraryHost* host = [TLLibraryHost libraryHostForContext:[self modelContext]];
return [host evidencePhotos];
}
- (TLLocation*)homeBase {
TLLibraryHost* host = [TLLibraryHost libraryHostForContext:[self modelContext]];
return [host homeBase];
}
static NSComparisonResult TLCompareTrackStartTimes(TLTrack* track1,
TLTrack* track2,
void* info)
{
(void)info;
NSDate* date1 = [track1 startDate];
NSDate* date2 = [track2 startDate];
return [date1 compare:date2];
}
// NOTE: this may return value equal to array count, use with caution!
- (NSUInteger)trackInsertionIndex:(NSMutableArray*)activeTracks
forStartDate:(NSDate*)targetDate
{
[activeTracks sortUsingFunction:TLCompareTrackStartTimes context:NULL];
NSTimeInterval targetTime = [targetDate timeIntervalSinceReferenceDate];
NSUInteger firstLaterTrackIdx = 0;
for (TLTrack* track in activeTracks) {
// update scan position and break if found
NSTimeInterval trackTime = [[track startDate] timeIntervalSinceReferenceDate];
if (trackTime > targetTime) break;
++firstLaterTrackIdx;
}
return firstLaterTrackIdx;
}
static NSComparisonResult TLComparePhotoTimestamps(TLPhoto* photo1,
TLPhoto* photo2,
void* info)
{
(void)info;
NSDate* date1 = [[photo1 timestamp] time];
NSDate* date2 = [[photo2 timestamp] time];
return [date1 compare:date2];
}
// NOTE: this may return value equal to array count, use with caution!
- (NSUInteger)photoInsertionIndex:(NSMutableArray*)activePhotos
forTimestamp:(TLTimestamp*)targetTimestamp
{
[activePhotos sortUsingFunction:TLComparePhotoTimestamps context:NULL];
NSTimeInterval targetTime = [[targetTimestamp time] timeIntervalSinceReferenceDate];
NSUInteger firstLaterPhotoIdx = 0;
for (TLPhoto* photo in activePhotos) {
// update scan position and break if found
NSTimeInterval photoTime = [[[photo timestamp] time] timeIntervalSinceReferenceDate];
if (photoTime > targetTime) break;
++firstLaterPhotoIdx;
}
return firstLaterPhotoIdx;
}
- (NSUInteger)waypointInsertionIndex:(NSArray*)waypoints
forDate:(NSDate*)targetDate
{
NSTimeInterval targetTime = [targetDate timeIntervalSinceReferenceDate];
NSUInteger firstLaterWaypointIdx = 0;
for (TLWaypoint* waypoint in waypoints) {
NSDate* waypointDate = [[waypoint timestamp] time];
NSTimeInterval waypointTime = [waypointDate timeIntervalSinceReferenceDate];
if (waypointTime > targetTime) break;
++firstLaterWaypointIdx;
}
return firstLaterWaypointIdx;
}
- (NSMapTable*)locateTimestamps:(NSMapTable*) timestampObjects {
NSSet* keys = TLNSMapTableAllKeys(timestampObjects);
NSMapTable* locations = [NSMapTable mapTableWithStrongToStrongObjects];
for (id key in keys) {
TLTimestamp* timestamp = [timestampObjects objectForKey:key];
TLLocation* location = [self locationAtTimestamp:timestamp];
[locations setObject:location forKey:key];
}
return locations;
}
- (TLLocation*)locationAtTimestamp:(TLTimestamp*)targetTimestamp {
TLWaypoint* prevWaypoint = nil;
TLWaypoint* nextWaypoint = nil;
BOOL forceInterpolation = NO;
// find closest track(s) evidence
NSMutableArray* activeTracks = [NSMutableArray arrayWithArray:[self evidenceTracks]];
NSDate* targetDate = [targetTimestamp time];
NSUInteger laterTrackIdx = [self trackInsertionIndex:activeTracks
forStartDate:targetDate];
if (laterTrackIdx > 0) {
TLTrack* earlierTrack = [activeTracks objectAtIndex:(laterTrackIdx - 1)];
NSArray* waypoints = [earlierTrack waypoints];
NSUInteger laterWaypointIdx = [self waypointInsertionIndex:waypoints
forDate:targetDate];
if (laterWaypointIdx < [waypoints count]) {
nextWaypoint = [waypoints objectAtIndex:laterWaypointIdx];
// assume we will also get prevWaypoint from this track
forceInterpolation = YES;
}
if (laterWaypointIdx > 0) {
prevWaypoint = [waypoints objectAtIndex:(laterWaypointIdx - 1)];
}
else {
// track, but none of its waypoints, before targetTimestamp!?
NSLog(@"Tracklog evidence inconsistency, handling gracefully.");
forceInterpolation = NO;
}
}
if (!nextWaypoint && laterTrackIdx < [activeTracks count]) {
TLTrack* laterTrack = [activeTracks objectAtIndex:laterTrackIdx];
NSArray* waypoints = [laterTrack waypoints];
if ([waypoints count]) {
nextWaypoint = [waypoints objectAtIndex:0];
}
}
if (!forceInterpolation) {
// use photo evidence when helpful
NSMutableArray* activePhotos = [NSMutableArray arrayWithArray:[self evidencePhotos]];
NSUInteger laterPhotoIdx = [self photoInsertionIndex:activePhotos
forTimestamp:targetTimestamp];
if (laterPhotoIdx > 0) {
TLPhoto* earlierPhoto = [activePhotos objectAtIndex:(laterPhotoIdx - 1)];
NSDate* photoDate = [[earlierPhoto timestamp] time];
NSDate* prevDate = [[prevWaypoint timestamp] time];
// use photo as waypoint if later than prevWaypoint
if (!prevDate || [photoDate isGreaterThan:prevDate]) {
prevWaypoint = [TLWaypoint waypointWithLocation:[earlierPhoto location]
timestamp:[earlierPhoto timestamp]];
}
}
if (laterPhotoIdx < [activePhotos count]) {
TLPhoto* laterPhoto = [activePhotos objectAtIndex:laterPhotoIdx];
NSDate* photoDate = [[laterPhoto timestamp] time];
NSDate* nextDate = [[nextWaypoint timestamp] time];
// use photo as waypoint if earlier than nextWaypoint
if (!nextWaypoint || [photoDate isLessThan:nextDate]) {
nextWaypoint = [TLWaypoint waypointWithLocation:[laterPhoto location]
timestamp:[laterPhoto timestamp]];
}
}
}
return TLLocatorInterpolate(targetTimestamp,
prevWaypoint,
nextWaypoint,
[self homeBase],
forceInterpolation);
}
- (void)addTimestamps:(NSMutableSet*)timestamps
forLocation:(TLLocation*)targetLocation
inTrack:(TLTrack*)track
{
TLCoordinateAltitude targetAltitude = [targetLocation altitude];
bool useAltitudes = (targetAltitude != TLCoordinateAltitudeUnknown);
if (!useAltitudes) {
targetAltitude = 0.0;
}
TLCoordinate targetCoord = [targetLocation originalCoordinate];
TLPlanetPoint targetPoint = TLGeoidGetPlanetPoint(TLProjectionGeoidWGS84, targetCoord, targetAltitude);
TLMetersECEF targetDistance = [targetLocation horizontalAccuracy];
TLMetersECEF targetDistanceSqd = targetDistance * targetDistance;
TLPlanetPoint prevPoint = TLPlanetPointZero;
NSDate* prevDate = nil;
TLTimestamp* closestGroupTimestamp = nil; // reset to nil if not in group
TLMetersECEF closestGroupDistanceSqd = 0.0;
for (TLWaypoint* waypoint in [track waypoints]) {
TLCoordinate currentCoord = [[waypoint location] originalCoordinate];
TLCoordinateAltitude currentAltitude = 0.0;
if (useAltitudes) {
currentAltitude = [[waypoint location] altitude];
}
TLPlanetPoint currentPoint = TLGeoidGetPlanetPoint(TLProjectionGeoidWGS84, currentCoord, currentAltitude);
NSDate* currentDate = [[waypoint timestamp] time];
if (!prevDate) {
prevPoint = currentPoint;
prevDate = currentDate;
TLMetersECEF distanceSqd = TLPlanetPointDistanceSquared(targetPoint, currentPoint);
if (TLFloatLessThanOrEqual(distanceSqd, targetDistanceSqd)) {
closestGroupTimestamp = [TLTimestamp timestampWithTime:currentDate
accuracy:TLTimestampAccuracyUnknown];
}
continue;
}
double lineTravel = TLPlanetClosestTravel(targetPoint, prevPoint, currentPoint);
double segmentTravel = TLFloatClampNaive(lineTravel, 0.0, 1.0);
TLPlanetPoint segmentPoint = TLPlanetPointWithTravel(prevPoint, currentPoint, segmentTravel);
TLMetersECEF distanceSqd = TLPlanetPointDistanceSquared(targetPoint, segmentPoint);
if (TLFloatLessThanOrEqual(distanceSqd, targetDistanceSqd)) {
NSTimeInterval timeDifference = [currentDate timeIntervalSinceDate:prevDate];
NSTimeInterval timeTravel = segmentTravel * timeDifference;
NSDate* targetDate = [prevDate addTimeInterval:timeTravel];
// TODO: calculate accuracy
TLTimestamp* targetTimestamp = [TLTimestamp timestampWithTime:targetDate
accuracy:TLTimestampAccuracyUnknown];
// find closest timestmp in contiguous run of "hit" segments
if (!closestGroupTimestamp || distanceSqd < closestGroupDistanceSqd) {
closestGroupTimestamp = targetTimestamp;
closestGroupDistanceSqd = distanceSqd;
}
}
else if (closestGroupTimestamp) {
// emit timestamp once we know it's the closest in a group
[timestamps addObject:closestGroupTimestamp];
closestGroupTimestamp = nil;
}
prevPoint = currentPoint;
prevDate = currentDate;
}
if (closestGroupTimestamp) {
[timestamps addObject:closestGroupTimestamp];
}
}
- (NSSet*)trackTimestampsAtLocation:(TLLocation*)targetLocation {
NSMutableSet* timestamps = [NSMutableSet set];
for (TLTrack* track in [self evidenceTracks]) {
[self addTimestamps:timestamps forLocation:targetLocation inTrack:track];
}
return timestamps;
}
@end
#pragma mark Interpolation helpers
/* This is fluidDensity * referenceArea * dragCoefficient based on
http://en.wikipedia.org/w/index.php?title=Density&oldid=250615493#Density_of_air and
http://en.wikipedia.org/w/index.php?title=Automobile_drag_coefficient&oldid=250352393 */
static const double TLLocatorDragFactor = 1.204 * 0.219;
/* From http://en.wikipedia.org/w/index.php?title=Aptera_Typ-1&oldid=250277514
and http://hypertextbook.com/facts/2003/AlexSchlessingerman.shtml */
static const double TLLocatorUserMass = 671.3 + 70.0;
/* From Advanced Automotive Technology: Visions of a Super-efficient Family Car, 1995, p. 165
available at http://www.princeton.edu/~ota/disk1/1995/9514/9514.PDF */
static const double TLLocatorRegainingEfficiency = 0.218;
TLProjectionGeoidRef TLLocatorInterpolationGeoid() {
return TLProjectionGeoidWGS84;
}
/* Minimum acceleration necessary to go same distance covered by traveling
at requiredVelocity for availableTime, but starting and ending at baseVelocity. */
static double TLLocatorMinAcceleration(double baseVelocity,
double requiredVelocity,
NSTimeInterval availableTime)
{
/* The distance covered at requiredVelocity in availableTime can also be covered
by constant acceleration attaining a maximum velocity halfway through the time,
followed by equal magnitude constant deceleration back to the baseVelocity.
This maximum velocity is double the difference above the baseVelocity, just as
an isoceles triangle must be double in height to equal the area of a rectangle
with the same base width.
(See http://en.wikipedia.org/w/index.php?title=Standard_gravity&oldid=251108683 and
http://en.wikipedia.org/w/index.php?title=G-force&oldid=250938464#NASA_g-tolerance_data
for information about human-tolerable acceleration magnitudes.) */
double velocityDifference = requiredVelocity - baseVelocity;
double differrenceToMaxVelocity = 2.0 * velocityDifference;
NSTimeInterval halfTime = availableTime / 2.0;
return fabs(differrenceToMaxVelocity / halfTime);
}
/* Unrecovered work done accelerating to cover the extra targetDistance from
the baseDistance, starting and ending at the velocity implied by baseDistance. */
static double TLLocatorWorkFromAccelerating(TLMetersECEF baseDistance,
TLMetersECEF targetDistance,
NSTimeInterval duration)
{
/* While theoretically the energy (=work) expended acceleration might be
recaptured while decelerating, this is not wholly the case even with a
vehicle capable of regenerative braking. */
double baseVelocity = baseDistance / duration;
double averageVelocity = targetDistance / duration;
double necessaryAcceleration = TLLocatorMinAcceleration(baseVelocity,
averageVelocity,
duration);
double necessaryForce = TLLocatorUserMass * necessaryAcceleration;
double distanceAccelerating = averageVelocity * (duration / 2.0);
double regainableWork = necessaryForce * distanceAccelerating;
return (1.0 - TLLocatorRegainingEfficiency) * regainableWork;
}
/* Work needed to go distance during duration. */
static double TLLocatorWorkRequired(TLMetersECEF distance, NSTimeInterval duration) {
/* Work calculated from force due to drag according to
http://en.wikipedia.org/w/index.php?title=Drag_equation&oldid=244349467 */
double velocity = distance / duration;
double velocitySqd = velocity * velocity;
double force = TLLocatorDragFactor * velocitySqd / 2.0;
return force * distance;
}
static double TLLocatorWorkBetweenWaypoints(TLWaypoint* earlierWaypoint,
TLWaypoint* laterWaypoint,
TLMetersECEF* distancePtr,
NSTimeInterval* durationPtr,
TLTimestamp* targetTimestamp,
TLLocation** interpolatedLocationPtr)
{
TLProjectionGeoidRef geoid = TLLocatorInterpolationGeoid();
TLLocation* earlierLocation = [earlierWaypoint location];
TLLocation* laterLocation = [laterWaypoint location];
TLCoordinateAltitude prevAltitude = [earlierLocation altitude];
TLCoordinateAltitude nextAltitude = [laterLocation altitude];
BOOL useAltitudes = (prevAltitude != TLCoordinateAltitudeUnknown &&
nextAltitude != TLCoordinateAltitudeUnknown);
if (!useAltitudes) {
prevAltitude = 0.0;
nextAltitude = 0.0;
}
TLPlanetPoint prevPoint = TLGeoidGetPlanetPoint(geoid,
[earlierLocation originalCoordinate],
prevAltitude);
TLPlanetPoint nextPoint = TLGeoidGetPlanetPoint(geoid,
[laterLocation originalCoordinate],
nextAltitude);
TLMetersECEF distance = TLPlanetPointDistance(prevPoint, nextPoint);
if (distancePtr) *distancePtr = distance;
NSDate* prevDate = [[earlierWaypoint timestamp] time];
NSDate* nextDate = [[laterWaypoint timestamp] time];
NSTimeInterval duration = [nextDate timeIntervalSinceDate:prevDate];
if (durationPtr) *durationPtr = duration;
if (targetTimestamp && interpolatedLocationPtr) {
NSTimeInterval durationToTarget = [[targetTimestamp time] timeIntervalSinceDate:prevDate];
double ratio = durationToTarget / duration;
TLPlanetPoint interpolatedPoint = TLPlanetPointWithTravel(prevPoint, nextPoint, ratio);
// TODO: calculate accuracy
TLCoordinateAltitude altitude = TLCoordinateAltitudeUnknown;
TLCoordinate coord = TLGeoidGetCoordinate(geoid,
interpolatedPoint,
(useAltitudes ? &altitude : NULL));
*interpolatedLocationPtr = [TLLocation locationWithCoordinate:coord
horizontalAccuracy:TLCoordinateAccuracyUnknown
altitude:altitude
verticalAccuracy:TLCoordinateAccuracyUnknown];
}
return TLLocatorWorkRequired(distance, duration);
}
#pragma mark Interpolation
TLLocation* TLLocatorInterpolate(TLTimestamp* targetTimestamp,
TLWaypoint* earlierWaypoint,
TLWaypoint* laterWaypoint,
TLLocation* homeLocation,
BOOL interpolateWhenPossible)
{
TLLocation* locationBetween = nil;
TLMetersECEF distanceBetween = 0.0;
NSTimeInterval durationBetween = 0.0;
double acceptedSnapWork = 0.0;
double snapEarlierWork = 0.0;
double snapLaterWork = 0.0;
if (earlierWaypoint && laterWaypoint) {
// how much work to go straight between waypoints?
double workBetween = TLLocatorWorkBetweenWaypoints(earlierWaypoint,
laterWaypoint,
&distanceBetween,
&durationBetween,
targetTimestamp,
&locationBetween);
if (interpolateWhenPossible) return locationBetween;
acceptedSnapWork = workBetween * (1.0 + TLLocatorSnapTolerance);
// what if we stayed at earlier location?
TLLocation* snapEarlierLocation = [earlierWaypoint location];
TLWaypoint* snapEarlierWaypoint = [TLWaypoint waypointWithLocation:snapEarlierLocation
timestamp:targetTimestamp];
NSTimeInterval snapEarlierDurationLeft = 0.0;
snapEarlierWork += TLLocatorWorkBetweenWaypoints(snapEarlierWaypoint,
laterWaypoint,
NULL,
&snapEarlierDurationLeft,
nil, NULL);
snapEarlierWork += TLLocatorWorkFromAccelerating(0.0,
distanceBetween,
snapEarlierDurationLeft);
// what if we were already at later location?
TLLocation* snapLaterLocation = [laterWaypoint location];
TLWaypoint* snapLaterWaypoint = [TLWaypoint waypointWithLocation:snapLaterLocation
timestamp:targetTimestamp];
NSTimeInterval snapLaterDurationLeft = 0.0;
snapLaterWork += TLLocatorWorkBetweenWaypoints(earlierWaypoint,
snapLaterWaypoint,
NULL,
&snapLaterDurationLeft,
nil, NULL);
snapLaterWork += TLLocatorWorkFromAccelerating(0.0,
distanceBetween,
snapLaterDurationLeft);
}
double snapHomeWork = 0.0;
double acceptedHomeWork = 0.0;
if (earlierWaypoint && homeLocation) {
// what if we went home?, part 1
TLTimestamp* homeTimestamp = targetTimestamp;
TLWaypoint* homeWaypoint = [TLWaypoint waypointWithLocation:homeLocation
timestamp:homeTimestamp];
TLMetersECEF distanceHome = 0.0;
NSTimeInterval durationHome = 0.0;
snapHomeWork += TLLocatorWorkBetweenWaypoints(earlierWaypoint,
homeWaypoint,
&distanceHome,
&durationHome,
nil, NULL);
snapHomeWork += TLLocatorWorkFromAccelerating(distanceBetween,
distanceHome,
durationHome);
double homeForce = TLLocatorUserMass * TLLocatorHomeAcceleration;
acceptedHomeWork += homeForce * distanceHome;
}
if (homeLocation && laterWaypoint) {
// what if we went home?, part 2
TLTimestamp* homeTimestamp = targetTimestamp;
TLWaypoint* homeWaypoint = [TLWaypoint waypointWithLocation:homeLocation
timestamp:homeTimestamp];
TLMetersECEF distanceHome = 0.0;
NSTimeInterval durationHome = 0.0;
snapHomeWork += TLLocatorWorkBetweenWaypoints(homeWaypoint,
laterWaypoint,
&distanceHome,
&durationHome,
nil, NULL);
snapHomeWork += TLLocatorWorkFromAccelerating(distanceBetween,
distanceHome,
durationHome);
double homeForce = TLLocatorUserMass * TLLocatorHomeAcceleration;
acceptedHomeWork += homeForce * distanceHome;
}
// decide which location to use
TLLocation* location = nil;
if (snapHomeWork < acceptedHomeWork) {
location = [homeLocation perturbedLocation];
}
else if (snapEarlierWork < acceptedSnapWork) {
location = [[earlierWaypoint location] perturbedLocation];
}
else if (snapLaterWork < acceptedSnapWork) {
location = [[laterWaypoint location] perturbedLocation];
}
else if (locationBetween) {
location = locationBetween;
}
else {
double netHomeWork = snapHomeWork - acceptedHomeWork;
if (earlierWaypoint && snapEarlierWork < netHomeWork) {
location = [[earlierWaypoint location] perturbedLocation];
}
else if (laterWaypoint && snapLaterWork < netHomeWork) {
location = [[laterWaypoint location] perturbedLocation];
}
else {
location = [homeLocation perturbedLocation];
}
}
return location;
}