forked from Scottish-Tech-Army/Soundscape-Android
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGeoEngine.kt
More file actions
1071 lines (956 loc) · 46.1 KB
/
Copy pathGeoEngine.kt
File metadata and controls
1071 lines (956 loc) · 46.1 KB
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.scottishtecharmy.soundscape.geoengine
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import android.content.res.Configuration
import android.location.Location
import android.net.Uri
import android.util.Log
import androidx.preference.PreferenceManager
import com.google.android.gms.location.DeviceOrientation
import com.google.firebase.crashlytics.FirebaseCrashlytics
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import org.scottishtecharmy.soundscape.MainActivity
import org.scottishtecharmy.soundscape.MainActivity.Companion.MOBILITY_KEY
import org.scottishtecharmy.soundscape.MainActivity.Companion.PLACES_AND_LANDMARKS_KEY
import org.scottishtecharmy.soundscape.R
import org.scottishtecharmy.soundscape.audio.AudioType
import org.scottishtecharmy.soundscape.audio.NativeAudioEngine
import org.scottishtecharmy.soundscape.database.local.RealmConfiguration
import org.scottishtecharmy.soundscape.database.local.dao.RoutesDao
import org.scottishtecharmy.soundscape.database.repository.RoutesRepository
import org.scottishtecharmy.soundscape.geoengine.callouts.AutoCallout
import org.scottishtecharmy.soundscape.geoengine.filters.MapMatchFilter
import org.scottishtecharmy.soundscape.geoengine.mvttranslation.Way
import org.scottishtecharmy.soundscape.geoengine.utils.FeatureTree
import org.scottishtecharmy.soundscape.geoengine.utils.GpxRecorder
import org.scottishtecharmy.soundscape.geoengine.utils.RelativeDirections
import org.scottishtecharmy.soundscape.geoengine.utils.ResourceMapper
import org.scottishtecharmy.soundscape.geoengine.utils.getCompassLabelFacingDirection
import org.scottishtecharmy.soundscape.geoengine.utils.getCompassLabelFacingDirectionAlong
import org.scottishtecharmy.soundscape.geoengine.utils.getDistanceToFeature
import org.scottishtecharmy.soundscape.geoengine.utils.getFovTriangle
import org.scottishtecharmy.soundscape.geoengine.utils.getRelativeDirectionsPolygons
import org.scottishtecharmy.soundscape.geoengine.utils.getTriangleForDirection
import org.scottishtecharmy.soundscape.geoengine.utils.polygonContainsCoordinates
import org.scottishtecharmy.soundscape.geoengine.utils.removeDuplicateOsmIds
import org.scottishtecharmy.soundscape.geojsonparser.geojson.Feature
import org.scottishtecharmy.soundscape.geojsonparser.geojson.FeatureCollection
import org.scottishtecharmy.soundscape.geojsonparser.geojson.LngLatAlt
import org.scottishtecharmy.soundscape.geojsonparser.geojson.Point
import org.scottishtecharmy.soundscape.geojsonparser.geojson.Polygon
import org.scottishtecharmy.soundscape.locationprovider.DirectionProvider
import org.scottishtecharmy.soundscape.locationprovider.LocationProvider
import org.scottishtecharmy.soundscape.locationprovider.phoneHeldFlat
import org.scottishtecharmy.soundscape.network.PhotonSearchProvider
import org.scottishtecharmy.soundscape.screens.home.data.LocationDescription
import org.scottishtecharmy.soundscape.services.SoundscapeService
import org.scottishtecharmy.soundscape.utils.getCurrentLocale
import org.scottishtecharmy.soundscape.utils.toLocationDescriptions
import java.io.File
import java.util.Locale
import kotlin.math.abs
import kotlin.time.TimeSource
import kotlin.time.measureTime
import kotlin.toString
import org.scottishtecharmy.soundscape.geoengine.utils.rulers.CheapRuler
data class PositionedString(
val text : String,
val location : LngLatAlt? = null,
val earcon : String? = null,
val type: AudioType = AudioType.STANDARD,
val heading: Double? = null
)
class GeoEngine {
private val coroutineScope = CoroutineScope(Job())
// Location update job
private var locationMonitoringJob: Job? = null
private var audioEngineUpdateJob: Job? = null
private var markerMonitoringJob: Job? = null
val gridState = ProtomapsGridState()
internal lateinit var locationProvider : LocationProvider
private lateinit var directionProvider : DirectionProvider
private var mapMatchFilter = MapMatchFilter()
// Resource string locale configuration
private lateinit var configLocale: Locale
private lateinit var configuration: Configuration
lateinit var localizedContext: Context
private lateinit var sharedPreferences: SharedPreferences
private lateinit var sharedPreferencesListener : SharedPreferences.OnSharedPreferenceChangeListener
private var inVehicle = false
private var inMotion = false
// Flag to indicate that the app is running on screen
var appInForeground = false
private lateinit var autoCallout: AutoCallout
private var autoCalloutDisabled = false
fun toggleAutoCallouts() {
autoCalloutDisabled.xor(true)
}
private val streetPreview = StreetPreview()
var phoneHeldFlat = false
var lastPhoneHeading : Double? = null
var beaconLocation: LngLatAlt? = null
fun updateBeaconLocation(location: LngLatAlt?) {
beaconLocation = location
}
var ruler = CheapRuler(0.0)
/**
* Create a UserGeometry data object using the passed in location and orientation values
* @param location The Android location to use
* @param orientation The Android DeviceOrientation to use
*/
private fun createUserGeometry(
location: Location?,
orientation: DeviceOrientation?,
headingMode: UserGeometry.HeadingMode,
mapMatchFilter: MapMatchFilter? = null,
) : UserGeometry {
var latLng = LngLatAlt(0.0, 0.0)
if(location != null) {
latLng = LngLatAlt(location.longitude, location.latitude)
}
if(ruler.needsReplacing(latLng.latitude))
ruler = CheapRuler(latLng.latitude)
phoneHeldFlat = phoneHeldFlat(orientation)
lastPhoneHeading = orientation?.headingDegrees?.toDouble()
val phoneHeading =
if (appInForeground or phoneHeldFlat)
lastPhoneHeading
else
null
// TODO: The travelHeading and speed calculations are important when trying
// to work out if the phone is moving or not. With these changes, there are
// still times when the phone is deemed to be moving, purely due to GPS
// jumps causing a "speed" and a "heading". It may be possible to Kalman
// filter these, a better method is required.
var travelHeading: Double? = null
if(location?.bearing != null) {
if(location.hasBearingAccuracy()) {
if(location.bearingAccuracyDegrees < 45.0)
travelHeading = location.bearing.toDouble()
} else {
travelHeading = location.bearing.toDouble()
}
}
var speed = 0.0
if(location?.speed != null) {
if(location.hasSpeedAccuracy()) {
// If the accuracy range encompasses zero, then we can't use it.
val lowestSpeed = location.speed - location.speedAccuracyMetersPerSecond
if(lowestSpeed > 0.1) {
speed = location.speed.toDouble()
}
} else {
// No accuracy available
speed = location.speed.toDouble()
}
}
return UserGeometry(
location = latLng,
phoneHeading = phoneHeading,
fovDistance = 50.0,
speed = speed,
headingMode = headingMode,
ruler = ruler,
travelHeading = travelHeading,
mapMatchedWay = mapMatchFilter?.matchedWay,
mapMatchedLocation = mapMatchFilter?.matchedLocation,
currentBeacon = beaconLocation,
inStreetPreview = streetPreview.running
)
}
private fun getCurrentUserGeometry(
headingMode: UserGeometry.HeadingMode
) : UserGeometry {
return createUserGeometry(
location = locationProvider.locationFlow.value,
orientation = directionProvider.orientationFlow.value,
headingMode = headingMode,
mapMatchFilter = mapMatchFilter
)
}
fun updateRecordingState(recordState: Boolean) {
gpxRecorder = if(recordState) {
GpxRecorder()
} else {
null
}
}
fun getRecordingShareUri(context: Context) : Uri? {
val ret = gpxRecorder?.getShareUri(context)
return ret
}
@OptIn(ExperimentalCoroutinesApi::class)
fun start(
application: Application,
newLocationProvider: LocationProvider,
newDirectionProvider: DirectionProvider,
soundscapeService: SoundscapeService,
) {
sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(application.applicationContext)
recordTravel = sharedPreferences.getBoolean(MainActivity.RECORD_TRAVEL_KEY, false)
updateRecordingState(recordTravel)
sharedPreferencesListener =
SharedPreferences.OnSharedPreferenceChangeListener { preferences, key ->
if (sharedPreferences == preferences) {
if(key == MainActivity.RECORD_TRAVEL_KEY) {
Log.e(TAG, "RECORD_TRAVEL_KEY changed")
recordTravel = sharedPreferences.getBoolean(MainActivity.RECORD_TRAVEL_KEY, false)
updateRecordingState(recordTravel)
}
}
}
sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferencesListener)
val recordingsStoragePath = application.applicationContext.filesDir.toString() + "/recordings/"
val recordingsStorageDir = File(recordingsStoragePath)
if (!recordingsStorageDir.exists()) {
recordingsStorageDir.mkdirs()
}
gridState.start(application)
configLocale = getCurrentLocale()
configuration = Configuration(application.applicationContext.resources.configuration)
configuration.setLocale(configLocale)
localizedContext = application.applicationContext.createConfigurationContext(configuration)
autoCallout = AutoCallout(localizedContext, sharedPreferences)
locationProvider = newLocationProvider
directionProvider = newDirectionProvider
startMonitoringLocation(soundscapeService)
streetPreview.start()
// Monitor markers in the database so we can create a tree to search
markerMonitoringJob?.cancel()
markerMonitoringJob = coroutineScope.launch {
val realm = RealmConfiguration.getMarkersInstance()
val routesDao = RoutesDao(realm)
val routesRepository = RoutesRepository(routesDao)
routesRepository.getMarkerFlow().collect { markers ->
val featureCollection = FeatureCollection()
for (marker in markers) {
val geoFeature = Feature()
geoFeature.geometry =
Point(marker.location!!.longitude, marker.location!!.latitude)
val properties : HashMap<String, Any?> = hashMapOf()
properties["name"] = marker.addressName
properties["description"] = marker.fullAddress
geoFeature.properties = properties
val foreign : HashMap<String, Any?> = hashMapOf()
foreign["category"] ="marker"
geoFeature.foreign = foreign
featureCollection.addFeature(geoFeature)
}
runBlocking {
withContext(gridState.treeContext) {
gridState.markerTree = FeatureTree(featureCollection)
Log.e(TAG, "Marker tree size ${featureCollection.features.size}")
}
}
}
}
}
fun stop() {
streetPreview.stop()
locationMonitoringJob?.cancel()
audioEngineUpdateJob?.cancel()
markerMonitoringJob?.cancel()
gridState.stop()
locationProvider.destroy()
directionProvider.destroy()
sharedPreferences.unregisterOnSharedPreferenceChangeListener(sharedPreferencesListener)
}
private var recordTravel = false
private var gpxRecorder: GpxRecorder? = null
/**
* The gridState is called each time the location changes. It checks if the location
* has moved away from the center of the current tile grid and if it has calculates a new grid.
*/
fun createSuperCategoriesSet() : Set<String> {
val enabledCategories = emptySet<String>().toMutableSet()
if (sharedPreferences.getBoolean(PLACES_AND_LANDMARKS_KEY, true))
enabledCategories.add(PLACES_AND_LANDMARKS_KEY)
if (sharedPreferences.getBoolean(MOBILITY_KEY, true))
enabledCategories.add(MOBILITY_KEY)
return enabledCategories
}
private fun updateAudioEngineGeometry(
soundscapeService: SoundscapeService,
userGeometry: UserGeometry
) {
// Send the update to the audio engine. This affects the direction and sound
// of the audio beacon.
soundscapeService.audioEngine.updateGeometry(
userGeometry.location.latitude,
userGeometry.location.longitude,
userGeometry.presentationHeading()
)
}
@OptIn(ExperimentalCoroutinesApi::class)
private fun startMonitoringLocation(soundscapeService: SoundscapeService) {
Log.e(TAG, "startTileGridService")
locationMonitoringJob?.cancel()
locationMonitoringJob = coroutineScope.launch {
locationProvider.locationFlow.collect { newLocation ->
newLocation?.let { location ->
// Add location to crash dumps
FirebaseCrashlytics.getInstance().setCustomKey("latitude", newLocation.latitude)
FirebaseCrashlytics.getInstance().setCustomKey("longitude", newLocation.longitude)
// Update the grid state
val updated = gridState.locationUpdate(
LngLatAlt(location.longitude, location.latitude),
createSuperCategoriesSet()
)
runBlocking {
withContext(gridState.treeContext) {
// Update the nearest road filter with our new location
val mapMatchTime = measureTime {
mapMatchFilter.filter(
LngLatAlt(location.longitude, location.latitude),
gridState,
FeatureCollection(),
false
)
}
val matchedWay = mapMatchFilter.matchedWay
println("MapMatch: $mapMatchTime to get ${matchedWay?.getName()}")
}
}
if(updated) {
// The grid updated, if we're in StreetPreview and were initializing, the
// service needs to update the state to ON.
soundscapeService.tileGridUpdated()
}
// So long as the AudioEngine is not already busy, run any auto callouts that we
// need. Auto Callouts use the direction of travel if there is one, otherwise
// falling back to use the phone direction.
if(!soundscapeService.isAudioEngineBusy() && !autoCalloutDisabled) {
val callouts =
autoCallout.updateLocation(getCurrentUserGeometry(UserGeometry.HeadingMode.CourseAuto), gridState)
if (callouts.isNotEmpty()) {
// Tell the service that we've got some callouts to tell the user about
soundscapeService.speakCallout(callouts, false)
}
// Save the location data to a file if enabled
gpxRecorder?.storeLocation(location)
}
}
}
}
// This job collects the incoming orientation and location flows, combines them into a
// UserGeometry and uses it to update the audio engine. If no flow change arrives within
// 100ms, then it updates the audio engine with the last values received.
audioEngineUpdateJob?.cancel()
audioEngineUpdateJob = coroutineScope.launch {
var lastGeometry : UserGeometry? = null
while(true) {
val geometry = withTimeoutOrNull(100) {
combine(
directionProvider.orientationFlow,
locationProvider.locationFlow,
) { orientation: DeviceOrientation?, location: Location? ->
createUserGeometry(
location = location,
orientation = orientation,
headingMode = UserGeometry.HeadingMode.CourseAuto
)
}.collect { geometry ->
lastGeometry = geometry
updateAudioEngineGeometry(soundscapeService, geometry)
}
}
if(geometry == null) {
// Timeout
lastGeometry?.let { last ->
// We may need to overwrite the phone heading if the phone has been locked
// or unlocked but with no heading update.
if (appInForeground or phoneHeldFlat)
last.phoneHeading = lastPhoneHeading
else
last.phoneHeading = null
updateAudioEngineGeometry(soundscapeService, last) }
}
}
}
}
@OptIn(ExperimentalCoroutinesApi::class)
fun myLocation() : List<PositionedString> {
// getCurrentDirection() from the direction provider has a default of 0.0
// even if we don't have a valid current direction.
var results : MutableList<PositionedString> = mutableListOf()
if (!locationProvider.hasValidLocation()) {
val noLocationString =
localizedContext.getString(R.string.general_error_location_services_find_location_error)
results.add(PositionedString(
text = noLocationString,
type = AudioType.STANDARD)
)
} else {
// Check if we have a valid heading
val userGeometry = getCurrentUserGeometry(UserGeometry.HeadingMode.CourseAuto)
val orientation = userGeometry.heading()
orientation?.let { heading ->
// Run the code within the treeContext to protect it from changes to the trees whilst it's
// running.
results = runBlocking {
withContext(gridState.treeContext) {
val list: MutableList<PositionedString> = mutableListOf()
val nearestRoad = userGeometry.mapMatchedWay
if (nearestRoad != null) {
var roadName = nearestRoad.getName(null, gridState, localizedContext)
val facingDirectionAlongRoad =
getCompassLabelFacingDirectionAlong(
localizedContext,
heading.toInt(),
roadName.toString(),
inMotion,
inVehicle
)
list.add(PositionedString(
text = facingDirectionAlongRoad,
type = AudioType.STANDARD))
} else {
val facingDirection =
getCompassLabelFacingDirection(
localizedContext,
heading.toInt(),
inMotion,
inVehicle
)
list.add(PositionedString(
text = facingDirection,
type = AudioType.STANDARD)
)
}
list
}
}
}
}
return results
}
suspend fun searchResult(searchString: String) =
withContext(Dispatchers.IO) {
val location = getCurrentUserGeometry(UserGeometry.HeadingMode.CourseAuto).location
try {
return@withContext PhotonSearchProvider
.getInstance()
.getSearchResults(
searchString = searchString,
latitude = location.latitude,
longitude = location.longitude,
).execute()
.body()
} catch (e: Exception) {
Log.e(TAG, "Error getting search results:", e)
return@withContext null
}
}
@OptIn(ExperimentalCoroutinesApi::class)
fun whatsAroundMe() : List<PositionedString> {
// Duplicate original Soundscape behaviour:
// In findCalloutsFor it tries to get a POI in each quadrant. It starts off searching
// within 200m and keeps increasing by 200m until it hits the maximum of 1000m. It only
// plays out a single POI per quadrant.
var results : MutableList<PositionedString> = mutableListOf()
val timeSource = TimeSource.Monotonic
val gridStartTime = timeSource.markNow()
if (!locationProvider.hasValidLocation()) {
val noLocationString =
localizedContext.getString(R.string.general_error_location_services_find_location_error)
results.add(PositionedString(
text = noLocationString,
type = AudioType.STANDARD)
)
} else {
// Run the code within the treeContext to protect it from changes to the trees whilst it's
// running.
results = runBlocking {
withContext(gridState.treeContext) {
val userGeometry = getCurrentUserGeometry(UserGeometry.HeadingMode.CourseAuto)
// Direction order is: behind(0) left(1) ahead(2) right(3)
val featuresByDirection: Array<Feature?> = arrayOfNulls(4)
val directionsNeeded = setOf(0, 1, 2, 3).toMutableSet()
// We want to use places and landmarks only
// We already have a FeatureTree containing the POI that we wish to search on
val featureTree = gridState.getFeatureTree(TreeId.PLACES_AND_LANDMARKS)
for (distance in 200..1000 step 200) {
// Get Polygons for this FOV distance
val individualRelativePolygons = getRelativeDirectionsPolygons(
UserGeometry(
userGeometry.location,
userGeometry.heading(),
distance.toDouble()
), RelativeDirections.INDIVIDUAL
)
val direction = directionsNeeded.iterator()
while (direction.hasNext()) {
val dir = direction.next()
val triangle = getTriangleForDirection(individualRelativePolygons, dir)
// Get the 4 nearest features in this direction. This allows us to de-duplicate
// across the other directions.
val featureCollection = featureTree.getNearestCollectionWithinTriangle(triangle, 4, userGeometry.ruler)
if (featureCollection.features.isNotEmpty()) {
// We found features in this direction, find the nearest one which
// we are not already calling out in another direction.
for(feature in featureCollection) {
var duplicate = false
val featureName = getTextForFeature(localizedContext, feature).text
for (otherFeature in featuresByDirection) {
if (otherFeature == null) continue
val otherName = getTextForFeature(localizedContext, otherFeature).text
if (featureName == otherName) duplicate = true
}
if (!duplicate) {
// We've found a new feature, remember it and remove it from
// the set of directions to search
featuresByDirection[dir] = feature
direction.remove()
break
}
}
}
}
// We've found all the directions, so no need to look any further afield
if (directionsNeeded.isEmpty()) break
}
// We've tried to get a POI in all directions, now return the ones we have into
// callouts
val list: MutableList<PositionedString> = mutableListOf()
for (feature in featuresByDirection) {
if(feature == null) continue
val poiLocation = getDistanceToFeature(userGeometry.location, feature, userGeometry.ruler)
val name = getTextForFeature(localizedContext, feature)
val text = "${name.text}. ${formatDistance(poiLocation.distance, localizedContext)}"
list.add(
PositionedString(
text,
poiLocation.point,
NativeAudioEngine.EARCON_SENSE_POI,
AudioType.LOCALIZED,
)
)
}
list
}
}
}
val gridFinishTime = timeSource.markNow()
Log.e(GridState.TAG, "Time to calculate AroundMe: ${gridFinishTime - gridStartTime}")
return results
}
@OptIn(ExperimentalCoroutinesApi::class)
fun aheadOfMe() : List<PositionedString> {
var results : MutableList<PositionedString> = mutableListOf()
if (!locationProvider.hasValidLocation()) {
val noLocationString =
localizedContext.getString(R.string.general_error_location_services_find_location_error)
results.add(PositionedString(
text = noLocationString,
type = AudioType.STANDARD)
)
} else {
results = runBlocking {
withContext(gridState.treeContext) {
// Return the nearest 5 POI within 1000m in the direction that we are heading
val userGeometry = getCurrentUserGeometry(UserGeometry.HeadingMode.HeadAuto)
userGeometry.fovDistance = 1000.0
val triangle = getFovTriangle(userGeometry)
val featureTree = gridState.getFeatureTree(TreeId.PLACES_AND_LANDMARKS)
val featuresAhead = featureTree.getNearestCollectionWithinTriangle(triangle, 5, userGeometry.ruler)
val list: MutableList<PositionedString> = mutableListOf()
for (feature in featuresAhead) {
val poiLocation = getDistanceToFeature(userGeometry.location, feature, userGeometry.ruler)
val name = getTextForFeature(localizedContext, feature)
val text = "${name.text}. ${formatDistance(poiLocation.distance, localizedContext)}"
list.add(
PositionedString(
text,
poiLocation.point,
NativeAudioEngine.EARCON_SENSE_POI,
AudioType.LOCALIZED,
)
)
}
if(list.isEmpty()) {
list.add(
PositionedString(
text = localizedContext.getString(R.string.callouts_nothing_to_call_out_now),
type = AudioType.STANDARD
)
)
}
list
}
}
}
return results
}
@OptIn(ExperimentalCoroutinesApi::class)
fun nearbyMarkers() : List<PositionedString> {
// Search database for nearby markers and call them out
var results : MutableList<PositionedString> = mutableListOf()
val timeSource = TimeSource.Monotonic
val gridStartTime = timeSource.markNow()
if (!locationProvider.hasValidLocation()) {
val noLocationString =
localizedContext.getString(R.string.general_error_location_services_find_location_error)
results.add(PositionedString(
text = noLocationString,
type = AudioType.STANDARD)
)
} else {
// Run the code within the treeContext to protect it from changes to the trees whilst it's
// running.
results = runBlocking {
withContext(gridState.treeContext) {
val userGeometry = getCurrentUserGeometry(UserGeometry.HeadingMode.CourseAuto)
// Simply get 4 nearest markers
val nearestMarkers = gridState.markerTree?.getNearestCollection(
userGeometry.location,
2000.0,
4,
userGeometry.ruler
)
val list: MutableList<PositionedString> = mutableListOf()
if(nearestMarkers != null) {
for (feature in nearestMarkers.features) {
val markerLocation = getDistanceToFeature(userGeometry.location, feature, userGeometry.ruler)
val name = feature.properties?.get("name")
val text = "$name. ${
formatDistance(
markerLocation.distance,
localizedContext
)
}"
list.add(
PositionedString(
text,
markerLocation.point,
NativeAudioEngine.EARCON_SENSE_POI,
AudioType.LOCALIZED,
)
)
}
}
list
}
}
}
val gridFinishTime = timeSource.markNow()
Log.e(GridState.TAG, "Time to calculate NearbyMarkers: ${gridFinishTime - gridStartTime}")
return results
}
fun streetPreviewGo() : List<StreetPreviewChoice> {
return streetPreviewGoInternal()
}
@OptIn(ExperimentalCoroutinesApi::class)
private fun streetPreviewGoWander() {
// Run the code within the treeContext to protect it from changes to the trees whilst it's
// running.
val engine = this
CoroutineScope(Job()).launch(gridState.treeContext) {
// Get our current location and figure out what GO means
val userGeometry = getCurrentUserGeometry(UserGeometry.HeadingMode.Phone)
val choices = streetPreview.getDirectionChoices(engine, userGeometry.location)
var heading = 0.0
if(choices.isNotEmpty()) {
// We want to choose a direction roughly in the forward direction if possible. We
// need to know which road we're coming in on.
val lastHeading = streetPreview.getLastHeading()
// Default to a random road
heading = choices.random().heading
if(!lastHeading.isNaN()) {
// If we came in on a road, then try and keep going in that direction
val trimmedChoices = mutableListOf<StreetPreviewChoice>()
for (choice in choices) {
if ((choice.heading != lastHeading) && (!choice.heading.isNaN())) {
// Don't add the road we just came in on, or any with a NaN heading.
trimmedChoices.add(choice)
// We want to skew results in favour of continuing onwards so add multiple
// times if the choice is in a direction that's fairly opposite to the road
// we're currently on.
if(abs(choice.heading - lastHeading) > 140.0) {
trimmedChoices.add(choice)
trimmedChoices.add(choice)
trimmedChoices.add(choice)
}
}
}
if(trimmedChoices.isNotEmpty()) {
heading = trimmedChoices.random().heading
}
}
}
// Update the heading with the random one that was chosen
userGeometry.phoneHeading = heading
streetPreview.go(userGeometry, engine)
}
}
@OptIn(ExperimentalCoroutinesApi::class)
private fun streetPreviewGoInternal() : List<StreetPreviewChoice> {
// Run the code within the treeContext to protect it from changes to the trees whilst it's
// running. We want to return the new set of choices so that these can be sent up to the UI.
val engine = this
val results = runBlocking {
withContext(gridState.treeContext) {
// Get our current location and figure out what GO means
val userGeometry = getCurrentUserGeometry(UserGeometry.HeadingMode.Phone)
val newLocation = streetPreview.go(userGeometry, engine)
if(newLocation != null) {
streetPreview.getDirectionChoices(engine, newLocation)
} else {
streetPreview.getDirectionChoices(engine, userGeometry.location)
}
}
}
return results
}
private suspend fun reverseGeocodeResult(location: LngLatAlt) =
withContext(Dispatchers.IO) {
try {
return@withContext PhotonSearchProvider
.getInstance()
.reverseGeocodeLocation(
latitude = location.latitude,
longitude = location.longitude
).execute()
.body()
} catch(e: Exception) {
Log.e(TAG, "Error getting reverse geocode result:", e)
return@withContext null
}
}
/**
* getLocationDescription returns a LocationDescription object for the current location. This
* is basically a reverse geocode. It initially tries to generate it from local tile data, but
* falls back to geocoding via the Photon server if network is available.
* @param location to reverse geocode
* @param preserveLocation ensures that the returned LocationDescription contains the passed in
* location rather than overwriting it with the location of a POI that it geocoded to.
* @return a LocationDescription object containing an address of the location
*/
@OptIn(ExperimentalCoroutinesApi::class)
fun getLocationDescription(location: LngLatAlt,
preserveLocation: Boolean = true) : LocationDescription? {
var geocode: LocationDescription?
// If the location is within our current TileGrid, then we can make our own description of
// the location.
geocode = runBlocking {
withContext(gridState.treeContext) {
localReverseGeocode(location, gridState, localizedContext)
}
}
if(geocode != null) return geocode
// If we have network, then we should be able to do a reverse geocode via the photon server
// TODO: Check for network first
// TODO: The geocode result takes too long to have it done inline like this. We need to
// move it into the user of the LocationDescription so that it can update dynamically if
// and when the request succeeds. Disable for now.
if(false) {
geocode = runBlocking {
withContext(Dispatchers.IO) {
val result = reverseGeocodeResult(location)
// The geocode result includes the location for the POI. In the case of something
// like a park this could be a long way from the point that was passed in.
val ld = result?.features?.toLocationDescriptions()
if (!ld.isNullOrEmpty()) {
if(preserveLocation) {
val overwritten = ld.first()
overwritten.location = location
if(overwritten.name.isNotEmpty()) {
overwritten.name = localizedContext.getString(R.string.directions_near_name).format(overwritten.name)
overwritten
}
else {
null
}
} else {
ld.first()
}
} else
null
}
}
if (geocode != null)
return geocode
}
// TODO: If we don't have network, and the location is outside of our current TileGrid, then we could see
// if the tiles are cached and we can create a temporary TileGrid, but this needs some debugging
//
// // Rustle up a TileGrid for this location
// val tempGrid = if(SOUNDSCAPE_TILE_BACKEND) SoundscapeBackendGridState() else ProtomapsGridState()
// geocode = runBlocking {
// withContext(tempGrid.treeContext) {
// // TODO: Should we create our own tileClient - we'll need an application context
// tempGrid.tileClient = gridState.tileClient
// tempGrid.locationUpdate(location, createSuperCategoriesSet())
// localReverseGeocode(location, tempGrid, localizedContext)
// }
// }
// if(geocode != null) return geocode
return LocationDescription(
name = "New location",
location = location
)
}
companion object {
private const val TAG = "GeoEngine"
}
}
data class TextForFeature(val text: String = "", val generic: Boolean= false)
/**
* getNameForFeature returns text describing the feature for callouts. Usually it returns a name
* or if it doesn't have one then a localized description of the type of feature it is e.g. bike
* parking, or style. Some types of Feature have more info e.g. bus stops and railway stations
* @param feature to evaluate
* @return a NameForFeature object containing the name and a flag indicating if it is a generic
* name from the OSM tag rather than an actual name.
*/
fun getTextForFeature(localizedContext: Context?, feature: Feature) : TextForFeature {
var generic = false
val name = feature.properties?.get("name") as String?
val featureValue = feature.foreign?.get("feature_value")
val isMarker = feature.foreign?.get("category") == "marker"
if(localizedContext == null) {
return TextForFeature(name.toString(), false)
}
if(isMarker) {
// If the feature is a Marker, return the unadulterated name along with prefix indicating
// that it's a Marker.
return if(name != null)
TextForFeature(localizedContext.getString(R.string.markers_marker_with_name, name), false)
else
TextForFeature(localizedContext.getString(R.string.markers_generic_name), false)
}
var text = name
val namedTransit = when (featureValue) {
"bus_stop" -> Pair(R.string.osm_tag_bus_stop_named, R.string.osm_tag_bus_stop)
"station" -> Pair(R.string.osm_tag_train_station_named, R.string.osm_tag_train_station)
"tram_stop" -> Pair(R.string.osm_tag_tram_stop_named, R.string.osm_tag_tram_stop)
"subway" -> Pair(R.string.osm_tag_subway_named, R.string.osm_tag_subway)
"ferry_terminal" -> Pair(R.string.osm_tag_ferry_terminal_named, R.string.osm_tag_ferry_terminal)
else -> null
}
if(namedTransit != null) {
text = if (name != null)
localizedContext.getString(namedTransit.first, name)
else
localizedContext.getString(namedTransit.second)
}
if (text == null) {
val osmClass =
feature.properties?.get("class") as String? ?: return TextForFeature("", true)
val id = ResourceMapper.getResourceId(osmClass)
text = if (id == null) {
osmClass.replace("_", " ")
} else {
localizedContext.getString(id)
}
generic = true
}
val capitalizedText = text.replaceFirstChar {
if (it.isLowerCase())
it.titlecase(localizedContext.resources.configuration.getLocales().get(0))
else
it.toString()
}
return TextForFeature(capitalizedText, generic)
}
/**
* We're going to round metric as documented for iOS:
* For metric units, we round all distances less than 1000 meters to the nearest 5 meters and all
* distances over 1000 meters to the nearest 50 meters.
*
* The iOS imperial docs are wrong, and in fact distances are all in feet and we can round in the
* same way as metric.
*
*/
fun formatDistance(distance: Double, localizedContext: Context) : String {
// TODO - Add setting for imperial/metric
val metric = true
var units = distance
var bigUnitDivisor = 100
if(!metric) {
// Imperial units used are feet
units = (distance * 1.09361 * 3)
bigUnitDivisor = (176*3)
}
val roundToNearest = if (units < 1000) 5.0 else 50.0
val roundedDistance =
((units + (roundToNearest / 2)) / roundToNearest).toInt() * roundToNearest
if (roundedDistance < 1000) {
return localizedContext.getString(
if(metric) R.string.distance_format_meters else R.string.distance_format_feet,
roundedDistance.toInt().toString()
)
} else {
val bigUnits = (roundedDistance.toInt() / 10).toFloat() / bigUnitDivisor