diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..671a084 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,6 @@ +{ + "attribution": { + "commit": "", + "pr": "" + } +} diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 1c511f7..3e55946 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -54,8 +54,29 @@ jobs: fi - name: Build core and compose locally + env: + HEAD_REF: ${{ github.head_ref }} run: | - git clone --depth 1 https://github.com/MapConductor/android-sdk-core.git _core + # コア側に PR と同名のブランチがあるなら、そちらを組む。 + # + # ここを default ブランチ固定にしていると、**コアの未マージな変更に追随する + # PR は永久に赤いまま**になる。実際 CameraBearing をコアへ足したとき、 + # プロバイダ側の PR が 10 本まとめて Unresolved reference で落ちた。 + # コアが先にマージされるまで待つ、という運用は取り込み順の事故を呼ぶので、 + # 同名ブランチがあれば拾う形にしてある(無ければ従来どおり default)。 + clone_matching() { + repo="$1"; dir="$2" + url="https://github.com/MapConductor/$repo.git" + if [ -n "$HEAD_REF" ] && git ls-remote --exit-code --heads "$url" "$HEAD_REF" >/dev/null 2>&1; then + echo "$repo: matching branch $HEAD_REF" + git clone --depth 1 --branch "$HEAD_REF" "$url" "$dir" + else + echo "$repo: default branch" + git clone --depth 1 "$url" "$dir" + fi + } + + clone_matching android-sdk-core _core cd _core ./gradlew --no-daemon publishToMavenLocal cd .. @@ -69,7 +90,7 @@ jobs: } EOF - git clone --depth 1 https://github.com/MapConductor/android-sdk-compose.git _compose + clone_matching android-sdk-compose _compose cd _compose ./gradlew --no-daemon publishToMavenLocal cd .. diff --git a/api/android-for-here.api b/api/android-for-here.api index 2c009fb..9bf0e09 100644 --- a/api/android-for-here.api +++ b/api/android-for-here.api @@ -156,6 +156,9 @@ public final class com.mapconductor.here.HereMapViewController extends com.mapco public final class com.mapconductor.here.HereMapViewController$Companion { } public final class com.mapconductor.here.HereMapViewControllerCameraKt { + public static final double viewportHeightDp(com.mapconductor.here.HereMapViewController); + public static final java.lang.Double verticalFov(com.mapconductor.here.HereMapViewController); + public static final com.mapconductor.core.map.MapCameraPosition toNativeCamera(com.mapconductor.here.HereMapViewController, com.mapconductor.core.map.MapCameraPosition); public static final void handleMoveCamera(com.mapconductor.here.HereMapViewController, com.mapconductor.core.map.MapCameraPosition); public static final void handleAnimateCamera(com.mapconductor.here.HereMapViewController, com.mapconductor.core.map.MapCameraPosition, long); public static final void handleFitBounds(com.mapconductor.here.HereMapViewController, com.mapconductor.core.features.GeoRectBounds, int); @@ -172,7 +175,7 @@ public final class com.mapconductor.here.HereMapViewControllerStore extends com. public final void initSDK(android.content.Context); } public final class com.mapconductor.here.HereMapViewKt { - public static final void HereMapView(com.mapconductor.here.HereViewState, androidx.compose.ui.Modifier, com.mapconductor.core.marker.MarkerTilingOptions, com.mapconductor.core.map.CameraRestriction, kotlin.jvm.functions.Function2, ? extends java.lang.Object>, kotlin.jvm.functions.Function1, kotlin.Unit>, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, com.mapconductor.core.map.MapProjection, kotlin.jvm.functions.Function3, androidx.compose.runtime.Composer, int, int, int); + public static final void HereMapView(com.mapconductor.here.HereViewState, androidx.compose.ui.Modifier, com.mapconductor.core.marker.MarkerTilingOptions, com.mapconductor.core.map.CameraRestriction, kotlin.jvm.functions.Function2, ? extends java.lang.Object>, kotlin.jvm.functions.Function1, kotlin.Unit>, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, com.mapconductor.core.map.MapProjection, com.mapconductor.core.map.MapViewStyle, kotlin.jvm.functions.Function1, kotlin.Unit>, kotlin.jvm.functions.Function3, androidx.compose.runtime.Composer, int, int, int); } public final class com.mapconductor.here.HereMapViewSaver extends com.mapconductor.compose.map.BaseMapViewSaver { public com.mapconductor.here.HereMapViewSaver(); @@ -184,6 +187,17 @@ public final class com.mapconductor.here.HereMapViewSaver extends com.mapconduct public com.mapconductor.core.map.MapViewStateInterface createState(java.lang.String, android.os.Bundle, com.mapconductor.core.map.MapCameraPosition); public java.lang.String getStateId(com.mapconductor.core.map.MapViewStateInterface); } +public final class com.mapconductor.here.HereOverlayStacking { + public static final com.mapconductor.here.HereOverlayStacking INSTANCE; + public final int polygonDrawOrder(int); + public final int circleDrawOrder(int); + public final int polylineDrawOrder(int); + public final com.here.sdk.mapview.MapLayerPriority rasterPriority(); + public final com.here.sdk.mapview.MapLayerPriority groundImagePriority(); + public final com.here.sdk.mapview.MapLayerPriority polygonTilePriority(); + public final com.here.sdk.mapview.MapLayerPriority polygonTilePriority(java.lang.String); + public final com.here.sdk.mapview.MapLayerPriority polylineTilePriority(java.lang.String); +} public final class com.mapconductor.here.HereTypeAliasKt { } public final class com.mapconductor.here.HereViewControllerStoreKt { @@ -197,6 +211,9 @@ public final class com.mapconductor.here.HereViewHolder implements com.mapconduc public androidx.compose.ui.geometry.Offset toScreenOffset-x-9fifI(com.mapconductor.core.features.GeoPointInterface); public java.lang.Object fromScreenOffset-3MmeM6k(long, kotlin.coroutines.Continuation); public com.mapconductor.core.features.GeoPoint fromScreenOffsetSync-k-4lQ0M(long); + public com.mapconductor.core.projection.ProjectedPoint toProjectedPoint(com.mapconductor.core.features.GeoPointInterface); + public com.mapconductor.core.features.GeoPoint fromProjectedPoint(com.mapconductor.core.projection.ProjectedPoint); + public com.mapconductor.core.projection.MapCoordinateSystem getCoordinateSystem(); public java.lang.Object getMapView(); public java.lang.Object getMap(); } @@ -311,6 +328,7 @@ public final class com.mapconductor.here.marker.HereMarkerController$Companion { public final class com.mapconductor.here.marker.HereMarkerRenderer extends com.mapconductor.core.marker.AbstractMarkerOverlayRenderer { public com.mapconductor.here.marker.HereMarkerRenderer(com.mapconductor.here.HereViewHolder, kotlinx.coroutines.CoroutineScope); public com.mapconductor.here.marker.HereMarkerRenderer(com.mapconductor.here.HereViewHolder, kotlinx.coroutines.CoroutineScope, int, kotlin.jvm.internal.DefaultConstructorMarker); + protected java.lang.Object applyDrawOrder(java.util.List>, kotlin.coroutines.Continuation); public boolean getSupportsAnimationOverlay(); public void setMarkerVisible(com.mapconductor.core.marker.MarkerEntityInterface, boolean); public void setMarkerPosition(com.mapconductor.core.marker.MarkerEntityInterface, com.mapconductor.core.features.GeoPoint); @@ -400,11 +418,13 @@ final class com.mapconductor.here.raster.HereRasterLayerOverlayRenderer$TileSpec public final java.lang.String getSourceName(); public final java.lang.String getLayerName(); public final java.util.List getStorageLevels(); + public final java.lang.String getLocalTemplate(); public final com.here.sdk.mapview.datasource.TileUrlProviderCallback component1(); public final java.lang.String component2(); public final java.lang.String component3(); public final java.util.List component4(); - public final com.mapconductor.here.raster.HereRasterLayerOverlayRenderer$TileSpec copy(com.here.sdk.mapview.datasource.TileUrlProviderCallback, java.lang.String, java.lang.String, java.util.List); + public final java.lang.String component5(); + public final com.mapconductor.here.raster.HereRasterLayerOverlayRenderer$TileSpec copy(com.here.sdk.mapview.datasource.TileUrlProviderCallback, java.lang.String, java.lang.String, java.util.List, java.lang.String); public java.lang.String toString(); public int hashCode(); public boolean equals(java.lang.Object); @@ -413,9 +433,26 @@ final class com.mapconductor.here.raster.HereRasterTileProxyProvider implements public static final com.mapconductor.here.raster.HereRasterTileProxyProvider$Companion Companion; public com.mapconductor.here.raster.HereRasterTileProxyProvider(com.mapconductor.core.raster.RasterLayerState); public byte[] renderTile(com.mapconductor.core.tileserver.TileRequest); + public byte[] renderTile(com.mapconductor.core.tileserver.TileRequest, kotlin.jvm.functions.Function0); } public final class com.mapconductor.here.raster.HereRasterTileProxyProvider$Companion { } +final class com.mapconductor.here.raster.LocalRasterTileSource implements com.here.sdk.mapview.datasource.RasterTileSource { + public static final int RENDER_WIDTH; + public static final long TEN_YEARS_MS; + public com.mapconductor.here.raster.LocalRasterTileSource(com.mapconductor.core.tileserver.LocalTileServer, java.lang.String, java.util.List); + public com.here.sdk.mapview.datasource.TileSource$DataVersion getDataVersion(com.here.sdk.mapview.datasource.TileKey); + public void addListener(com.here.sdk.mapview.datasource.TileSource$Listener); + public void removeListener(com.here.sdk.mapview.datasource.TileSource$Listener); + public com.here.sdk.mapview.datasource.TilingScheme getTilingScheme(); + public java.util.List getStorageLevels(); + public com.here.sdk.mapview.datasource.TileSource$LoadTileRequestHandle loadTile(com.here.sdk.mapview.datasource.TileKey, com.here.sdk.mapview.datasource.RasterTileSource$LoadResultHandler); +} +final class com.mapconductor.here.raster.LocalRasterTileSource$Companion { + public final kotlinx.coroutines.CoroutineDispatcher getRenderDispatcher(); + public final com.here.sdk.mapview.datasource.TileSource$DataVersion getVERSION(); + public final com.here.sdk.mapview.datasource.TileSource$TileMetadata getMETADATA(); +} public final class com.mapconductor.here.zoom.ZoomAltitudeConverter extends com.mapconductor.core.zoom.AbstractZoomAltitudeConverter { public static final com.mapconductor.here.zoom.ZoomAltitudeConverter$Companion Companion; public static final double HERE_ZOOM_TO_GOOGLE_ZOOM_AT_EQUATOR; diff --git a/build.gradle.kts b/build.gradle.kts index af80bd2..e170901 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -97,6 +97,15 @@ dependencies { ), ), ) + // 実機テスト(HereMapViewSaverTest)は MapScheme などを実行時に読むので、テスト APK には同梱する。 + androidTestImplementation( + fileTree( + mapOf( + "dir" to rootDir.resolve("libs").toString(), + "include" to arrayOf("heresdk*.jar", "heresdk*.aar"), + ), + ), + ) if (findProject(":android-sdk-compose") != null) { api(project(":android-sdk-compose")) } else { diff --git a/gradle.properties b/gradle.properties index 26d9949..8b1a332 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,10 +3,10 @@ android.useAndroidX=true kotlin.code.style=official android.nonTransitiveRClass=true -compileSdk=35 +compileSdk=37 minSdk=26 javaVersion=17 jvmTarget=17 -libraryVersion=1.3.1 +libraryVersion=1.4.0 android.generateSyncIssueWhenLibraryConstraintsAreEnabled=false diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 353e813..f15f5ea 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,12 +1,15 @@ [versions] -coroutines = "1.9.0" -composeLibs = "1.7.8" -agp = "9.2.1" -kotlin = "2.0.21" +coroutines = "1.11.0" +composeLibs = "1.12.1" +# material3 は compose-ui とは別のバージョン系列。composeLibs(ui 系)を流用すると +# 存在しない material3:1.7.8 を要求してクラスパスごと解決に失敗する。 +material3 = "1.4.0" +agp = "9.4.1" +kotlin = "2.4.20" -composeBom = "2025.02.00" -lifecycleRuntimeKtx = "2.8.7" -activityCompose = "1.9.3" +composeBom = "2026.09.00" +lifecycleRuntimeKtx = "2.11.0" +activityCompose = "1.13.0" ktLint = "14.2.0" junit = "4.13.2" @@ -27,7 +30,10 @@ androidx-lifecycle-common-java8 = { group = "androidx.lifecycle", name = "lifecy # Sample app androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" } -androidx-material3 = { group = "androidx.compose.material3", name = "material3", version.ref = "composeLibs" } +androidx-material3 = { group = "androidx.compose.material3", name = "material3", version.ref = "material3" } +# sample-app が Icons.AutoMirrored を使う。material3 は material-icons を推移的に持ってこないので +# 明示的に足す。版は compose BOM 任せ(集約ビルドの catalog と同じ形)。 +androidx-material-icons-core = { group = "androidx.compose.material", name = "material-icons-core" } androidx-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling", version.ref = "composeLibs" } # Test diff --git a/sample-app/build.gradle.kts b/sample-app/build.gradle.kts index a995c93..7c9ef69 100644 --- a/sample-app/build.gradle.kts +++ b/sample-app/build.gradle.kts @@ -64,6 +64,7 @@ dependencies { implementation(libs.androidx.ui) implementation(libs.androidx.ui.tooling.preview) implementation(libs.androidx.material3) + implementation(libs.androidx.material.icons.core) debugImplementation(platform(libs.androidx.compose.bom)) debugImplementation(libs.androidx.ui.tooling) } diff --git a/src/androidTest/java/com/mapconductor/here/HereMapViewSaverTest.kt b/src/androidTest/java/com/mapconductor/here/HereMapViewSaverTest.kt new file mode 100644 index 0000000..283b8c5 --- /dev/null +++ b/src/androidTest/java/com/mapconductor/here/HereMapViewSaverTest.kt @@ -0,0 +1,85 @@ +package com.mapconductor.here + +import androidx.compose.runtime.saveable.Saver +import androidx.compose.runtime.saveable.SaverScope +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.here.sdk.mapview.MapScheme +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.AttributionRule +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapUISettings +import org.junit.Assert.assertEquals +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import android.os.Bundle +import android.os.Parcel + +/** + * 回転などの構成変更で state が [HereMapViewSaver] を通って作り直されても、デザイン(id・ + * attributionRules ほか)と uiSettings・カメラが落ちないこと。Bundle は実機の Parcel を一度通す。 + */ +@RunWith(AndroidJUnit4::class) +class HereMapViewSaverTest { + private val rules = + listOf(AttributionRule("© test"), AttributionRule("© ranged", minZoom = 3, maxZoom = 15)) + + private val camera = + MapCameraPosition( + position = GeoPoint(21.38, -157.93), + zoom = 12.0, + bearing = 20.0, + tilt = 10.0, + ) + + @Test + fun keepsCustomDesignWithAttributionRules() { + val design = HereMapDesign.Custom(MapScheme.SATELLITE, rules) + val state = HereViewState(id = "here-1", mapDesignType = design, cameraPosition = camera) + state.uiSettings = MapUISettings(rotateGesture = false, tiltGesture = false) + + val restored = roundTrip(HereMapViewSaver().createSaver(), state) + + val actual = restored.mapDesignType + assertTrue(actual is HereMapDesign.Custom) + assertEquals(MapScheme.SATELLITE, actual.id) + assertEquals(rules, actual.attributionRules) + assertCommon(restored, "here-1") + } + + @Test + fun keepsPresetDesignAsTheSameObject() { + val state = HereViewState(id = "here-2", mapDesignType = HereMapDesign.LiteNight) + assertSame(HereMapDesign.LiteNight, roundTrip(HereMapViewSaver().createSaver(), state).mapDesignType) + } + + private fun assertCommon( + restored: com.mapconductor.core.map.MapViewStateInterface<*>, + id: String, + ) { + assertEquals(id, restored.id) + assertEquals(false, restored.uiSettings.rotateGesture) + assertEquals(false, restored.uiSettings.tiltGesture) + assertEquals(true, restored.uiSettings.scrollGesture) + assertEquals(12.0, restored.cameraPosition.zoom, 1e-9) + assertEquals(20.0, restored.cameraPosition.bearing, 1e-9) + assertEquals(21.38, restored.cameraPosition.position.latitude, 1e-9) + } + + private fun roundTrip( + saver: Saver, + value: T, + ): T { + val saved = with(saver) { SaverScope { true }.save(value) }!! + // 一度 Parcel に書いて読み戻す(プロセスが落ちたあとの復元と同じ経路)。 + val parcel = Parcel.obtain() + try { + parcel.writeBundle(saved) + parcel.setDataPosition(0) + return saver.restore(parcel.readBundle(javaClass.classLoader)!!)!! + } finally { + parcel.recycle() + } + } +} diff --git a/src/main/java/com/mapconductor/here/HereMapView.kt b/src/main/java/com/mapconductor/here/HereMapView.kt index fe90bd8..4854c23 100644 --- a/src/main/java/com/mapconductor/here/HereMapView.kt +++ b/src/main/java/com/mapconductor/here/HereMapView.kt @@ -1,15 +1,11 @@ package com.mapconductor.here import androidx.compose.runtime.Composable -import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.node.Ref import androidx.compose.ui.platform.LocalContext -import androidx.lifecycle.DefaultLifecycleObserver -import androidx.lifecycle.LifecycleOwner -import androidx.lifecycle.compose.LocalLifecycleOwner import com.here.sdk.mapview.MapProjection as HereMapProjection import com.here.sdk.mapview.MapRenderMode import com.here.sdk.mapview.MapView @@ -22,6 +18,7 @@ import com.mapconductor.core.map.CameraRestriction import com.mapconductor.core.map.MapCameraPosition import com.mapconductor.core.map.MapCameraPositionInterface import com.mapconductor.core.map.MapProjection +import com.mapconductor.core.map.MapViewStyle import com.mapconductor.core.marker.MarkerEventControllerInterface import com.mapconductor.core.marker.MarkerOverlayRendererInterface import com.mapconductor.core.marker.MarkerRenderingStrategyInterface @@ -43,7 +40,6 @@ import com.mapconductor.here.raster.HereRasterLayerController import com.mapconductor.here.raster.HereRasterLayerOverlayRenderer import java.util.concurrent.atomic.AtomicBoolean import android.annotation.SuppressLint -import android.view.ViewGroup import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.suspendCancellableCoroutine @@ -63,6 +59,15 @@ fun HereMapView( onCameraMove: OnCameraMoveHandler? = null, onCameraMoveEnd: OnCameraMoveHandler? = null, projection: MapProjection = MapProjection.Globe, + /** + * How the map looks, when the app states it rather than naming a design. + * + * A vector style *is* the basemap. `com.mapconductor:vectorstyle` builds + * one; what happens underneath depends on this backend and the app does + * not have to know. + */ + style: MapViewStyle? = null, + onStyleDiagnostics: ((List) -> Unit)? = null, content: (@Composable HereViewScope.() -> Unit)? = null, ) { // Warmup the tile server early to reduce latency for raster layers @@ -72,7 +77,6 @@ fun HereMapView( val scope = remember { HereViewScope() } val controllerRef = remember { Ref() } val context = LocalContext.current - val lifecycle = LocalLifecycleOwner.current.lifecycle val registry = remember { scope.buildRegistry() } val cameraState = remember { mutableStateOf(state.cameraPosition) } // Capture the desired initial camera before any early camera callbacks can overwrite state. @@ -139,6 +143,10 @@ fun HereMapView( controller.setMapClickListener(onMapClick) controller.setMapLongClickListener(onMapLongClick) state.setController(controller) + // コントローラの既定値(NormalDay)のままリスナーを繋ぐと、それが state へ返り、 + // アプリが渡した(あるいは回転後に復元した)デザインが NormalDay に化ける。 + // 下の loadScene は state のデザインを読むので、その前に揃えておく。 + controller.mapDesignType = state.mapDesignType controller.setMapDesignTypeChangeListener(state::onMapDesignTypeChange) cameraRestriction?.let { controller.setCameraRestriction(it) } @@ -210,50 +218,18 @@ fun HereMapView( scope = scope, registry = registry, onMapLoaded = onMapLoaded, - customDisposableEffect = { _, holderRef -> - - // HERE specific DisposableEffect logic - DisposableEffect(lifecycle) { - val stateId = state.id // from BaseMapViewState - val observer = - object : DefaultLifecycleObserver { - override fun onResume(owner: LifecycleOwner) { - // Do not call here to keep the MapView instance - // holderRef.value?.mapView?.onResume() - } - - override fun onPause(owner: LifecycleOwner) { - // Do not call here to keep the MapView instance - // holderRef.value?.mapView?.onPause() - } - - override fun onDestroy(owner: LifecycleOwner) { - val currentHolder = holderRef.value - if (currentHolder != null) { - val activity = context.findActivity() - if (activity?.isChangingConfigurations == true) { - (currentHolder.mapView.parent as? ViewGroup)?.removeView(currentHolder.mapView) - } else { - // Ensure these calls are safe if mapView might be null or already destroyed - currentHolder.mapView.onPause() - currentHolder.mapView.onDestroy() - // Real teardown: free overlay controllers (tile-server - // routes, marker managers) and cancel the controller scope. - HereMapViewControllerStore.get(stateId)?.destroy() - HereMapViewControllerStore.remove(stateId) // Clean up from your store - } - } - } - } - lifecycle.addObserver(observer) - onDispose { - lifecycle.removeObserver(observer) - } - } + // Created resumed in viewProvider, so paused before it is destroyed. A + // MapView left alive keeps its render loop and, through its listeners, + // the controller with every overlay. + onDestroyMapView = { mapView -> + mapView.onPause() + mapView.onDestroy() }, // Pass content if it needs to be rendered within the overlay providers in MapViewBase, // or handle it here if it's specific to HereMapView structure before calling MapViewBase. // For now, assuming content relates to overlay definitions. + style = style, + onStyleDiagnostics = onStyleDiagnostics, content = content, // This might need adjustment based on how overlays are handled ) } diff --git a/src/main/java/com/mapconductor/here/HereMapViewController.kt b/src/main/java/com/mapconductor/here/HereMapViewController.kt index e2f132d..e2e5d8d 100644 --- a/src/main/java/com/mapconductor/here/HereMapViewController.kt +++ b/src/main/java/com/mapconductor/here/HereMapViewController.kt @@ -1,5 +1,14 @@ package com.mapconductor.here +import com.mapconductor.core.circle.CIRCLE_TILE_LAYER_ID +import com.mapconductor.core.map.CameraPaddingEmulation +import com.mapconductor.core.map.MapPaddings +import com.mapconductor.core.map.MapPaddingsInterface +import com.mapconductor.core.circle.CircleTiler +import com.mapconductor.core.circle.circleTileRasterLayerState +import com.mapconductor.core.polygon.POLYGON_TILE_LAYER_ID +import com.mapconductor.core.polygon.PolygonTiler +import com.mapconductor.core.polygon.polygonTileRasterLayerState import HereMapDesignTypeChangeHandler import HereMapViewControllerInterface import com.here.sdk.core.Point2D @@ -29,7 +38,10 @@ import com.mapconductor.core.marker.StrategyMarkerController import com.mapconductor.core.marker.dispatchGeoMarkerClick import com.mapconductor.core.polygon.OnPolygonEventHandler import com.mapconductor.core.polyline.OnPolylineEventHandler +import com.mapconductor.core.polyline.POLYLINE_TILE_LAYER_ID import com.mapconductor.core.polyline.PolylineState +import com.mapconductor.core.polyline.PolylineTiler +import com.mapconductor.core.polyline.polylineTileRasterLayerState import com.mapconductor.here.circle.HereCircleController import com.mapconductor.here.groundimage.HereGroundImageController import com.mapconductor.here.marker.HereMarkerController @@ -68,6 +80,18 @@ class HereMapViewController( internal var markerAnimateStartListener: OnMarkerEventHandler? = null internal var markerAnimateEndListener: OnMarkerEventHandler? = null internal var lastRequestedCameraPosition: MapCameraPosition? = null + + /** + * 今カメラに付いているパディング(dp)。 + * + * HERE の principal point は使わない。flyTo のアニメーションに載らず、付けた瞬間に + * 画面が跳ぶため。代わりにカメラ中心をずらして再現し([CameraPaddingEmulation])、 + * 読むときに元へ戻すためにここで覚えておく。 + */ + internal var cameraPaddings: MapPaddingsInterface = MapPaddings.Zeros + + /** 最後に測れたカメラの焦点距離(px)。HERE は地図の大きさによらず一定。 */ + internal var focalLengthPx: Double? = null internal val cameraRequestGeneration = AtomicLong(0L) // HERE's MapCameraListener provides only continuous updates. Synthesize a "move end" after an idle window @@ -88,6 +112,8 @@ class HereMapViewController( groundImageController.clear() circleController.clear() rasterLayerController.clear() + // 拡張モジュール(クラスタリングなど)が登録した Strategy のマーカーも消す。 + clearStrategyMarkerControllers() } override fun setMarkerAnimationOverlayHost(host: MarkerAnimationOverlayHost?) { @@ -167,6 +193,41 @@ class HereMapViewController( } }, ) + + // Many polygons are drawn as raster tiles, shown through the same RasterLayer + // controller as the marker tiles (upsert / removeById, never the app's layers). + polygonController.tiler = + PolygonTiler().apply { + onTemplate = { template, tileSize -> + if (template != null) { + rasterLayerController.upsert(polygonTileRasterLayerState(template, tileSize)) + } else { + rasterLayerController.removeById(POLYGON_TILE_LAYER_ID) + } + } + } + + // Many polylines too: the same raster layer path, in the polyline band. + polylineController.tiler = + PolylineTiler().apply { + onTemplate = { template, tileSize -> + if (template != null) { + rasterLayerController.upsert(polylineTileRasterLayerState(template, tileSize)) + } else { + rasterLayerController.removeById(POLYLINE_TILE_LAYER_ID) + } + } + } + circleController.tiler = + CircleTiler().apply { + onTemplate = { template, tileSize -> + if (template != null) { + rasterLayerController.upsert(circleTileRasterLayerState(template, tileSize)) + } else { + rasterLayerController.removeById(CIRCLE_TILE_LAYER_ID) + } + } + } } override fun moveCamera(position: MapCameraPosition) = handleMoveCamera(position) @@ -238,7 +299,7 @@ class HereMapViewController( polygonController.clickListener = listener } - private var mapDesignType: HereMapDesignType = HereMapDesign.NormalDay + internal var mapDesignType: HereMapDesignType = HereMapDesign.NormalDay private var mapDesignTypeChangeListener: HereMapDesignTypeChangeHandler? = null override fun applyUISettings(settings: MapUISettings) { diff --git a/src/main/java/com/mapconductor/here/HereMapViewControllerCamera.kt b/src/main/java/com/mapconductor/here/HereMapViewControllerCamera.kt index 805c619..f90343c 100644 --- a/src/main/java/com/mapconductor/here/HereMapViewControllerCamera.kt +++ b/src/main/java/com/mapconductor/here/HereMapViewControllerCamera.kt @@ -11,8 +11,12 @@ import com.here.sdk.mapview.MapCameraAnimationFactory import com.here.sdk.mapview.MapMeasure import com.here.time.Duration import com.mapconductor.core.features.GeoRectBounds +import com.mapconductor.core.map.CameraPaddingEmulation import com.mapconductor.core.map.MapCameraPosition import com.mapconductor.core.map.VisibleRegion +import com.mapconductor.core.spherical.Spherical +import kotlin.math.atan +import kotlin.math.hypot import kotlin.time.Duration.Companion.milliseconds import kotlinx.coroutines.delay import kotlinx.coroutines.launch @@ -21,11 +25,52 @@ import kotlinx.coroutines.launch // HERE は「動き終わった」を通知しないので、更新が止まったところを // デバウンスで作っている。範囲制限もネイティブ API が無く、停止時に // 矩形内へクランプして再適用する。 + +/** 地図の高さ(dp)。パディングのエミュレーションで遠近を解くのに使う。 */ +internal fun HereMapViewController.viewportHeightDp(): Double { + val density = holder.mapView.resources.displayMetrics.density + return holder.mapView.height / density.toDouble() +} + +/** + * HERE のカメラの縦方向の視野角(度)。SDK に取得 API が無いので、今のカメラから測る。 + * + * ピンホールカメラでは、注視点で横に 1 m ずらすと `焦点距離 / 注視点までの距離` px 動く。 + * HERE は注視点までの距離([MapCamera.State.distanceToTargetInMeters])を返すので、 + * 横の 1 m が何 px かを投影で測れば焦点距離が出る。TB520FU では地図の大きさ・向き・ + * 画面密度によらず約 3550 px で、縦の視野角は縦長の全画面で約 45°、横長で約 29°。 + */ +internal fun HereMapViewController.verticalFov(): Double? { + val height = holder.mapView.height + if (height <= 0) return null + val state = holder.mapView.camera.state + val target = state.targetCoordinates.toGeoPoint() + val sideways = Spherical.computeOffset(target, 100.0, state.orientationAtTarget.bearing + 90.0) + val a = holder.mapView.geoToViewCoordinates(target.toGeoCoordinates()) + val b = holder.mapView.geoToViewCoordinates(sideways.toGeoCoordinates()) + if (a != null && b != null && state.distanceToTargetInMeters > 0) { + val pxPerMeter = hypot(b.x - a.x, b.y - a.y) / 100.0 + if (pxPerMeter > 0) focalLengthPx = state.distanceToTargetInMeters * pxPerMeter + } + val f = focalLengthPx ?: return null + return Math.toDegrees(2 * atan((height / 2.0) / f)) +} + +/** パディングを中心のずらしに置き換えたカメラ。paddings が null なら今のパディングを使い続ける。 */ +internal fun HereMapViewController.toNativeCamera(position: MapCameraPosition): MapCameraPosition { + position.paddings?.let { cameraPaddings = it } + return CameraPaddingEmulation.toNativeCamera( + position.copy(paddings = cameraPaddings), + verticalFov(), + viewportHeightDp(), + ) +} + internal fun HereMapViewController.handleMoveCamera(position: MapCameraPosition) { lastRequestedCameraPosition = position val request = cameraRequestGeneration.incrementAndGet() val camera = this.holder.mapView.camera - val adjustCameraUpdate = position.toMapCameraUpdate() + val adjustCameraUpdate = toNativeCamera(position).toMapCameraUpdate() camera.applyUpdate(adjustCameraUpdate) @@ -47,7 +92,7 @@ internal fun HereMapViewController.handleAnimateCamera( cameraRequestGeneration.incrementAndGet() val camera = this.holder.mapView.camera - val display = position.toHereDisplayCamera() + val display = toNativeCamera(position).toHereDisplayCamera() // bowFactor > 0: 最初にズームアウト → 到達時にズームイン // bowFactor < 0: 最初にズームイン → 到達時にズームアウト(ややレア) @@ -180,7 +225,12 @@ internal fun HereMapViewController.getMapCameraPosition(cameraState: MapCamera.S farRight = holder.fromScreenOffsetSync(Offset(mapWidth, 0.0f)), ) val logicalCamera = - HereCameraStateSnapshot(cameraState, lastRequestedCameraPosition?.tilt).toMapCameraPosition() + CameraPaddingEmulation.fromNativeCamera( + HereCameraStateSnapshot(cameraState, lastRequestedCameraPosition?.tilt).toMapCameraPosition(), + cameraPaddings, + verticalFov(), + viewportHeightDp(), + ) return@let logicalCamera.copy(visibleRegion = visibleRegion) } } diff --git a/src/main/java/com/mapconductor/here/HereOverlayStacking.kt b/src/main/java/com/mapconductor/here/HereOverlayStacking.kt new file mode 100644 index 0000000..571998b --- /dev/null +++ b/src/main/java/com/mapconductor/here/HereOverlayStacking.kt @@ -0,0 +1,60 @@ +package com.mapconductor.here + +import com.here.sdk.mapview.MapLayerPriority +import com.here.sdk.mapview.MapLayerPriorityBuilder + +/** + * 重なり順(ラスター < GroundImage < ポリゴン < サークル < ポリライン < マーカー)。 + * + * HERE では: + * - ポリゴン・サークル・ポリラインは map item で、`drawOrder` を 1 本の数で比べる。 + * 帯ごとに区間を分けて割り当てる(帯の中は zIndex の順)。 + * - ラスターと GroundImage は MapLayer。既定の優先度だと map item より上に描かれて + * ポリゴン等を覆うので、ベースマップのレイヤー(ルートの手前)に入れる。 + * ラスター → GroundImage の順になるよう、別々のレイヤーの手前を指定する。 + * - マーカーは map item の上に描かれる(drawOrder はマーカーどうしの順)。 + */ +internal object HereOverlayStacking { + private const val BAND = 340 + + fun polygonDrawOrder(zIndex: Int): Int = zIndex.coerceIn(0, BAND - 1) + + fun circleDrawOrder(zIndex: Int): Int = BAND + zIndex.coerceIn(0, BAND - 1) + + fun polylineDrawOrder(zIndex: Int): Int = 2 * BAND + zIndex.coerceIn(0, 1023 - 2 * BAND) + + /** ラスター: ベースマップの "route" レイヤーの手前(GroundImage より下)。 */ + fun rasterPriority(): MapLayerPriority = MapLayerPriorityBuilder().renderedBeforeLayer(RASTER_ANCHOR).build() + + /** GroundImage: "traffic_on_route" レイヤーの手前(ラスターより上、map item より下)。 */ + fun groundImagePriority(): MapLayerPriority = MapLayerPriorityBuilder().renderedBeforeLayer(GROUND_IMAGE_ANCHOR).build() + + /** + * ポリゴンのタイル(SDK が描くラスター): ポリゴンの帯の一番下。GroundImage のアンカー + * "traffic_on_route" の直後(GroundImage より上、map item より下)。 + */ + fun polygonTilePriority(): MapLayerPriority = polygonTilePriority(beforeLayer = null) + + /** [polygonTilePriority]; when the polyline tiles are already on the map, just below them ([beforeLayer]). */ + fun polygonTilePriority(beforeLayer: String?): MapLayerPriority = + if (beforeLayer != null) { + MapLayerPriorityBuilder().renderedBeforeLayer(beforeLayer).build() + } else { + MapLayerPriorityBuilder().renderedAfterLayer(GROUND_IMAGE_ANCHOR).build() + } + + /** + * ポリラインのタイル(SDK が描くラスター): ポリゴンのタイルの上([afterLayer]、無ければ + * GroundImage のアンカーの直後)、map item の下。 + * + * HERE の map item(ポリゴン・サークル・ポリライン)は 1 枚の層にまとめて描かれ、 + * MapLayer をサークルとポリラインの間に挟めない。map item の下に置くので、ネイティブの + * ポリゴン・サークルもこのタイルの上に来る(帯の決まりからの、HERE だけの差)。 + * マーカーとマーカーのタイルより下、ポリゴンのタイルより上は守る。 + */ + fun polylineTilePriority(afterLayer: String?): MapLayerPriority = + MapLayerPriorityBuilder().renderedAfterLayer(afterLayer ?: GROUND_IMAGE_ANCHOR).build() + + private const val RASTER_ANCHOR = "route" + private const val GROUND_IMAGE_ANCHOR = "traffic_on_route" +} diff --git a/src/main/java/com/mapconductor/here/HereViewStateImpl.kt b/src/main/java/com/mapconductor/here/HereViewStateImpl.kt index e21f0f0..d087c75 100644 --- a/src/main/java/com/mapconductor/here/HereViewStateImpl.kt +++ b/src/main/java/com/mapconductor/here/HereViewStateImpl.kt @@ -5,12 +5,14 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable +import com.here.sdk.mapview.MapScheme import com.mapconductor.compose.map.BaseMapViewSaver import com.mapconductor.core.map.MapCameraPosition import com.mapconductor.core.map.MapCameraPositionInterface import com.mapconductor.core.map.MapPaddings import com.mapconductor.core.map.MapPaddingsInterface import com.mapconductor.core.map.MapViewState +import com.mapconductor.core.map.MapViewStateBundle import com.mapconductor.core.map.MapViewStateInterface import java.util.UUID import android.app.Activity @@ -26,7 +28,10 @@ class HereViewState( cameraPosition: MapCameraPosition = MapCameraPosition.Default, ) : MapViewState(cameraPosition), HereViewStateInterface { - private var controller: HereMapViewControllerInterface? = null + // Read through the base so that letting go of the controller there (MapViewBase + // does it when the map is torn down) leaves nothing behind here. + private val controller: HereMapViewControllerInterface? + get() = attachedMapController as? HereMapViewControllerInterface private var _mapDesignType: HereMapDesignType = mapDesignType @@ -41,7 +46,6 @@ class HereViewState( override fun getMapViewHolder(): HereViewHolder? = super.getMapViewHolder() as? HereViewHolder internal fun setController(controller: HereMapViewControllerInterface) { - this.controller = controller // controller.setMapDesignType(_mapDesignType) attachController(controller) } @@ -60,28 +64,49 @@ class HereMapViewSaver : BaseMapViewSaver() { state: HereViewState, bundle: Bundle, ) { - bundle.putInt("id", state.mapDesignType.getValue().value) + val design = state.mapDesignType + val scheme = design.getValue().value + bundle.putInt("id", scheme) + // 定義済み(NormalDay など)以外は Custom として戻す。id だけだと Custom の + // attributionRules が落ちる。 + bundle.putBoolean(KEY_CUSTOM, design !== presetOrNull(scheme)) + MapViewStateBundle.putAttributionRules(bundle, design.attributionRules) } override fun createState( stateId: String, mapDesignBundle: Bundle?, cameraPosition: MapCameraPosition, - ): HereViewState = - HereViewState( + ): HereViewState { + val scheme = mapDesignBundle?.getInt("id", HereMapDesign.NormalDay.id.value) ?: HereMapDesign.NormalDay.id.value + val preset = presetOrNull(scheme) + val mapScheme = MapScheme.values().firstOrNull { it.value == scheme } + val design = + if ((mapDesignBundle?.getBoolean(KEY_CUSTOM) == true || preset == null) && mapScheme != null) { + HereMapDesign.Custom( + id = mapScheme, + attributionRules = MapViewStateBundle.getAttributionRules(mapDesignBundle), + ) + } else { + preset ?: HereMapDesign.NormalDay + } + return HereViewState( id = stateId, - mapDesignType = - HereMapDesign.create( - id = mapDesignBundle?.getInt("id") ?: HereMapDesign.NormalDay.id.value, - ), + mapDesignType = design, cameraPosition = cameraPosition, ) + } + + private fun presetOrNull(scheme: Int): HereMapDesign? = runCatching { HereMapDesign.create(scheme) }.getOrNull() override fun getCameraPaddings(): MapPaddingsInterface? = MapPaddings.Zeros override fun getStateId(state: HereViewState): String = state.id } +// 公開 API の門番(javap)にコンパニオンの定数が載らないよう、ファイル private にする。 +private const val KEY_CUSTOM = "custom" + @Composable fun rememberHereMapViewState( mapDesign: HereMapDesign = HereMapDesign.NormalDay, diff --git a/src/main/java/com/mapconductor/here/MapCameraPosition.kt b/src/main/java/com/mapconductor/here/MapCameraPosition.kt index 90150a7..395f9a1 100644 --- a/src/main/java/com/mapconductor/here/MapCameraPosition.kt +++ b/src/main/java/com/mapconductor/here/MapCameraPosition.kt @@ -7,6 +7,7 @@ import com.here.sdk.mapview.MapCameraUpdate import com.here.sdk.mapview.MapCameraUpdateFactory import com.here.sdk.mapview.MapMeasure import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.CameraBearing import com.mapconductor.core.map.MapCameraPosition import com.mapconductor.core.map.MapCameraPositionInterface import com.mapconductor.core.spherical.Spherical @@ -30,7 +31,7 @@ internal fun MapCameraPosition.toHereDisplayCamera(): HereDisplayCamera { target = GeoPoint.from(position), tiltDeg = tilt, hereZoomLevel = ZoomAltitudeConverter.googleZoomToHereZoom(zoom, position.latitude), - bearing = bearing, + bearing = CameraBearing.toNativeHeading(bearing), ) } // tilt < 0: HERE cannot represent upward pitch directly. @@ -40,13 +41,13 @@ internal fun MapCameraPosition.toHereDisplayCamera(): HereDisplayCamera { val hereZoomOrig = ZoomAltitudeConverter.googleZoomToHereZoom(zoom, position.latitude) val altitude = converter.zoomLevelToAltitude(hereZoomOrig, position.latitude, 0.0) val distanceForward = altitude * tan(tiltAbsRad) - val target = Spherical.computeOffset(position, distanceForward, bearing) + val target = Spherical.computeOffset(position, distanceForward, CameraBearing.toNativeHeading(bearing)) val adjustedHereZoom = converter.altitudeToZoomLevel(altitude / cos(tiltAbsRad), target.latitude, 0.0) return HereDisplayCamera( target = target, tiltDeg = tiltAbsDeg, hereZoomLevel = adjustedHereZoom, - bearing = bearing, + bearing = CameraBearing.toNativeHeading(bearing), ) } @@ -71,6 +72,7 @@ fun MapCameraPosition.Companion.from(position: MapCameraPositionInterface): MapC tilt = position.tilt, paddings = position.paddings, visibleRegion = position.visibleRegion, + fov = position.fov, ) } @@ -93,7 +95,7 @@ internal fun MapCamera.State.toMapCameraPosition(logicalTiltHint: Double?): MapC return MapCameraPosition( position = position, zoom = ourZoom, - bearing = orientationAtTarget.bearing, + bearing = CameraBearing.bearingFromNativeHeading(orientationAtTarget.bearing), tilt = pitch, visibleRegion = null, ) @@ -114,7 +116,7 @@ internal fun MapCamera.State.toMapCameraPosition(logicalTiltHint: Double?): MapC return MapCameraPosition( position = originalCenter, zoom = originalGoogleZoom, - bearing = bear, + bearing = CameraBearing.bearingFromNativeHeading(bear), tilt = -pitchAbsDeg, visibleRegion = null, ) diff --git a/src/main/java/com/mapconductor/here/circle/HereCircleOverlayRenderer.kt b/src/main/java/com/mapconductor/here/circle/HereCircleOverlayRenderer.kt index 650c875..37c5811 100644 --- a/src/main/java/com/mapconductor/here/circle/HereCircleOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/here/circle/HereCircleOverlayRenderer.kt @@ -15,6 +15,7 @@ import com.mapconductor.core.features.normalize import com.mapconductor.core.geometry.circleToRing import com.mapconductor.core.geometry.closeRing import com.mapconductor.here.HereActualCircle +import com.mapconductor.here.HereOverlayStacking import com.mapconductor.here.HereViewHolder import com.mapconductor.here.toGeoCoordinates import kotlinx.coroutines.CoroutineScope @@ -36,7 +37,7 @@ class HereCircleOverlayRenderer( Color.valueOf(state.strokeColor.toArgb()), lineWidth, ).apply { - drawOrder = (state.zIndex ?: 0).coerceIn(0, 511) + drawOrder = HereOverlayStacking.circleDrawOrder(state.zIndex ?: 0) } coroutine.launch { holder.map.addMapPolygon(mapCircle) @@ -96,7 +97,7 @@ class HereCircleOverlayRenderer( ) } if (finger.zIndex != prevFinger.zIndex) { - current.circle.drawOrder = (current.state.zIndex ?: 0).coerceIn(0, 511) + current.circle.drawOrder = HereOverlayStacking.circleDrawOrder(current.state.zIndex ?: 0) } circle diff --git a/src/main/java/com/mapconductor/here/groundimage/HereGroundImageOverlayRenderer.kt b/src/main/java/com/mapconductor/here/groundimage/HereGroundImageOverlayRenderer.kt index 55f48f4..3783659 100644 --- a/src/main/java/com/mapconductor/here/groundimage/HereGroundImageOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/here/groundimage/HereGroundImageOverlayRenderer.kt @@ -12,6 +12,7 @@ import com.mapconductor.core.groundimage.GroundImageState import com.mapconductor.core.groundimage.GroundImageTileProvider import com.mapconductor.core.tileserver.LocalTileServer import com.mapconductor.here.HereActualGroundImage +import com.mapconductor.here.HereOverlayStacking import com.mapconductor.here.HereViewHolder import android.util.Log import kotlinx.coroutines.CoroutineScope @@ -136,6 +137,8 @@ class HereGroundImageOverlayRenderer( MapLayerBuilder() .withName(layerName) .withDataSource(config.name, MapContentType.RASTER_IMAGE) + // GroundImage の帯(ラスターの上、ポリゴン等の map item の下)。 + .withPriority(HereOverlayStacking.groundImagePriority()) .forMap(holder.mapView.hereMap) .build() HereGroundImageHandle( diff --git a/src/main/java/com/mapconductor/here/marker/HereMarkerController.kt b/src/main/java/com/mapconductor/here/marker/HereMarkerController.kt index c65698c..b797825 100644 --- a/src/main/java/com/mapconductor/here/marker/HereMarkerController.kt +++ b/src/main/java/com/mapconductor/here/marker/HereMarkerController.kt @@ -1,353 +1,387 @@ -package com.mapconductor.here.marker - -import com.mapconductor.core.controller.OnCameraChangeReceiverInterface -import com.mapconductor.core.map.MapCameraPosition -import com.mapconductor.core.marker.AbstractMarkerController -import com.mapconductor.core.marker.BitmapIcon -import com.mapconductor.core.marker.DefaultMarkerIcon -import com.mapconductor.core.marker.MarkerEntity -import com.mapconductor.core.marker.MarkerEntityInterface -import com.mapconductor.core.marker.MarkerIngestionEngine -import com.mapconductor.core.marker.MarkerManager -import com.mapconductor.core.marker.MarkerOverlayRendererInterface -import com.mapconductor.core.marker.MarkerState -import com.mapconductor.core.marker.MarkerTileRasterLayerCallback -import com.mapconductor.core.marker.MarkerTileRenderer -import com.mapconductor.core.marker.MarkerTilingOptions -import com.mapconductor.core.marker.MarkerViewportSwitch -import com.mapconductor.core.raster.RasterLayerSource -import com.mapconductor.core.raster.RasterLayerState -import com.mapconductor.core.raster.TileScheme -import com.mapconductor.core.tileserver.TileServerRegistry -import com.mapconductor.here.HereActualMarker -import com.mapconductor.here.HereViewHolder -import java.util.UUID -import android.os.SystemClock -import kotlinx.coroutines.launch -import kotlinx.coroutines.sync.withPermit - -class HereMarkerController private constructor( - markerManager: MarkerManager, - renderer: HereMarkerRenderer, - private val markerTiling: MarkerTilingOptions, -) : AbstractMarkerController( - markerManager = markerManager, - renderer = renderer, - ), - OnCameraChangeReceiverInterface { - private val defaultMarkerIcon: BitmapIcon = DefaultMarkerIcon().toBitmapIcon() - private val tiledMarkerIds = LinkedHashSet() - - @Volatile - private var lastKnownZoom: Double = 0.0 - - private val tileServer = TileServerRegistry.get() - private var markerTileRenderer: MarkerTileRenderer? = null - private var markerTileGroupId: String? = null - private var markerTileRasterLayerState: RasterLayerState? = null - private var rasterLayerCallback: MarkerTileRasterLayerCallback? = null - private var cacheVersion: Int = 0 - - /** - * ビューポート内が少ないときだけタイルをやめてネイティブマーカーで描く切り替え器。 - * - * レンダラ/マネージャ/semaphore を共有するので、コントローラと同じ排他の下で動く。 - */ - private val viewportSwitch = - MarkerViewportSwitch( - markerManager = markerManager, - renderer = renderer, - defaultMarkerIcon = defaultMarkerIcon, - semaphore = semaphore, - policy = markerTiling.viewport, - setTileLayerVisible = ::setTileLayerVisible, - invalidateTiles = ::updateRasterLayerSource, - ) - - fun setRasterLayerCallback(callback: MarkerTileRasterLayerCallback?) { - rasterLayerCallback = callback - } - - override suspend fun add(data: List) { - // ingest はタイル担当 entity を marker = null で登録し直すので、先に昇格を戻す。 - // semaphore は再入不可なので withPermit の外で呼ぶこと。 - viewportSwitch.retract() - semaphore.withPermit { - val tilingEnabled = - markerTiling.enabled && data.size >= markerManager.minMarkerCount - val result = - MarkerIngestionEngine.ingest( - data = data, - markerManager = markerManager, - renderer = renderer, - defaultMarkerIcon = defaultMarkerIcon, - tilingEnabled = tilingEnabled, - tiledMarkerIds = tiledMarkerIds, - shouldTile = { state -> !state.draggable && state.getAnimation() == null }, - ) - - if (result.tiledDataChanged) { - syncTiledOverlay() - } else if (result.hasTiledMarkers) { - if (markerTileRenderer == null || markerTileRasterLayerState == null) { - syncTiledOverlay() - } - } else { - removeTileOverlay() - } - } - viewportSwitch.requestReapply() - } - - override suspend fun update(state: MarkerState) { - if (!markerManager.hasEntity(state.id)) return - - // 昇格中の 1 件なら先に取り下げる(下で marker = null 登録があるため)。 - // 昇格していないマーカー(ドラッグ中など)では何もしないので、ドラッグは素通りする。 - if (viewportSwitch.isPromoted(state.id)) viewportSwitch.release(state.id) - - val prevEntity = markerManager.getEntity(state.id) ?: return - val currentFinger = state.fingerPrint() - val prevFinger = prevEntity.fingerPrint - if (currentFinger == prevFinger) return - - semaphore.withPermit { - val tilingEnabled = - markerTiling.enabled && markerManager.allEntities().size >= markerManager.minMarkerCount - val wantsTiled = tilingEnabled && !state.draggable && state.getAnimation() == null - val wasTiled = tiledMarkerIds.contains(state.id) - val markerIcon = state.icon?.toBitmapIcon() ?: defaultMarkerIcon - - if (wantsTiled) { - if (!wasTiled) { - prevEntity.marker?.let { renderer.onRemove(listOf(prevEntity)) } - tiledMarkerIds.add(state.id) - } - markerManager.updateEntity( - MarkerEntity( - marker = null, - state = state, - visible = prevEntity.visible, - isRendered = true, - // tiling を立てないと MarkerTileRenderer の絞り込みから漏れ、 - // タイル昇格したのにタイルへ描かれないマーカーになる。 - tiling = true, - ), - ) - renderer.onPostProcess() - syncTiledOverlay() - return@withPermit - } - - if (wasTiled) { - tiledMarkerIds.remove(state.id) - } - - val params = - object : MarkerOverlayRendererInterface.ChangeParamsInterface { - override val current: MarkerEntityInterface = - MarkerEntity( - marker = prevEntity.marker, - state = state, - visible = prevEntity.visible, - isRendered = true, - ) - override val bitmapIcon: BitmapIcon = markerIcon - override val prev: MarkerEntityInterface = prevEntity - } - val markers = renderer.onChange(listOf(params)) - markers.firstOrNull()?.let { actual -> - markerManager.updateEntity( - MarkerEntity( - marker = actual, - state = state, - visible = prevEntity.visible, - isRendered = true, - ), - ) - if (prevFinger.animation != currentFinger.animation) { - state.getAnimation()?.let { renderer.onAnimate(markerManager.getEntity(state.id)!!) } - } - } - renderer.onPostProcess() - - if (tiledMarkerIds.isNotEmpty()) { - syncTiledOverlay() - } else { - removeTileOverlay() - } - } - viewportSwitch.requestReapply() - } - - override suspend fun clear() { - viewportSwitch.destroy() - semaphore.withPermit { - val entities = markerManager.allEntities() - val toRemove = entities.filter { it.marker != null } - if (toRemove.isNotEmpty()) { - renderer.onRemove(toRemove) - } - markerManager.clear() - tiledMarkerIds.clear() - removeTileOverlay() - } - } - - override suspend fun onCameraChanged(mapCameraPosition: MapCameraPosition) { - // 判定と昇格は debounce したうえで切り替え器の中で走る(パン中は動かない)。 - viewportSwitch.onCameraChanged(mapCameraPosition) - lastKnownZoom = mapCameraPosition.zoom - } - - /** - * マーカータイルのラスターレイヤの表示だけを切り替える。 - * - * source(URL)には触らない。触るとタイルを取り直すことになり、切り替えのたびに - * タイルキャッシュを捨てるのと同じになる。 - */ - private suspend fun setTileLayerVisible(visible: Boolean) { - val current = markerTileRasterLayerState ?: return - if (current.visible == visible) return - val newState = current.copy(visible = visible) - markerTileRasterLayerState = newState - rasterLayerCallback?.onRasterLayerUpdate(newState) - } - - override fun destroy() { - viewportSwitch.destroy() - // Clean up tile server registration - // Unregister this map's route only. Never stop the server here: it is - // a process-wide singleton shared by all map controllers and overlay - // modules; stopping it breaks tile loading for every other live map. - markerTileGroupId?.let { groupId -> - tileServer.unregister(groupId) - } - markerTileGroupId = null - markerTileRenderer = null - - (renderer as HereMarkerRenderer).coroutine.launch { - rasterLayerCallback?.onRasterLayerUpdate(null) - } - markerTileRasterLayerState = null - super.destroy() - } - - private suspend fun updateRasterLayerSource() { - val groupId = markerTileGroupId ?: return - val tileRenderer = markerTileRenderer ?: return - val oldState = markerTileRasterLayerState ?: return - cacheVersion = (cacheVersion + 1) and 0x7fffffff - tileRenderer.invalidate() - val cacheBuster = "${cacheVersion}_${SystemClock.elapsedRealtime()}" - - val newState = - oldState.copy( - source = - RasterLayerSource.UrlTemplate( - template = "${tileServer.urlTemplate(groupId, tileRenderer.tileSize)}?cb=$cacheBuster", - tileSize = tileRenderer.tileSize, - maxZoom = 22, - scheme = TileScheme.XYZ, - ), - id = oldState.id, - ) - markerTileRasterLayerState = newState - rasterLayerCallback?.onRasterLayerUpdate(newState) - } - - private suspend fun syncTiledOverlay() { - if (tiledMarkerIds.isEmpty()) { - removeTileOverlay() - return - } - if (!markerTiling.enabled) { - removeTileOverlay() - tiledMarkerIds.clear() - return - } - - getOrCreateTileRenderer() - updateRasterLayerSource() - } - - private fun getOrCreateTileRenderer(): MarkerTileRenderer { - markerTileRenderer?.let { return it } - - val groupId = UUID.randomUUID().toString() - markerTileGroupId = groupId - - // HERE displays one raster tile over 512 logical px, so render tiles at - // 512 with no extra icon scale: icons match regular MapMarker size 1:1. - // (256 gets upscaled 2x -> icons appear double size; 1024 doubles the - // render/PNG-encode cost for no visible gain.) - val tileScale = 1.0 - val outputTileSize = 512 - - cacheVersion = (cacheVersion + 1) and 0x7fffffff - val tileRenderer = - MarkerTileRenderer( - markerManager = markerManager, - tileSize = outputTileSize, - cacheSizeBytes = markerTiling.cacheSize, - debugTileOverlay = markerTiling.debugTileOverlay, - iconScaleCallback = markerTiling.iconScaleCallback, - extraIconScale = tileScale, - ) - markerTileRenderer = tileRenderer - - tileServer.register(groupId, tileRenderer) - - markerTileRasterLayerState = - RasterLayerState( - id = "marker-tile-$groupId", - source = - RasterLayerSource.UrlTemplate( - template = "${tileServer.urlTemplate(groupId, tileRenderer.tileSize)}?cb=$cacheVersion", - tileSize = tileRenderer.tileSize, - maxZoom = 22, - scheme = TileScheme.XYZ, - ), - opacity = 1.0f, - visible = true, - ) - - return tileRenderer - } - - private suspend fun removeTileOverlay() { - markerTileGroupId?.let { groupId -> - tileServer.unregister(groupId) - } - markerTileGroupId = null - markerTileRenderer = null - - rasterLayerCallback?.onRasterLayerUpdate(null) - markerTileRasterLayerState = null - } - - companion object { - fun create( - holder: HereViewHolder, - markerTiling: MarkerTilingOptions = MarkerTilingOptions.Default, - ): HereMarkerController { - val renderer = - HereMarkerRenderer( - holder = holder, - ) - val markerManager = - MarkerManager.defaultManager( - minMarkerCount = markerTiling.minMarkerCount, - ) - val controller = - HereMarkerController( - markerManager = markerManager, - renderer = renderer, - markerTiling = markerTiling, - ) - // HERE camera zoom is updated via onCameraChanged; initialize a best-effort value. - controller.lastKnownZoom = holder.mapView.camera.state.zoomLevel - return controller - } - } -} +package com.mapconductor.here.marker + +import com.mapconductor.core.controller.OnCameraChangeReceiverInterface +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.marker.AbstractMarkerController +import com.mapconductor.core.marker.BitmapIcon +import com.mapconductor.core.marker.DefaultMarkerIcon +import com.mapconductor.core.marker.MarkerEntity +import com.mapconductor.core.marker.MarkerEntityInterface +import com.mapconductor.core.marker.MarkerIngestionEngine +import com.mapconductor.core.marker.MarkerManager +import com.mapconductor.core.marker.MarkerOverlayRendererInterface +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.marker.MarkerTileRasterLayerCallback +import com.mapconductor.core.marker.MarkerTileRenderer +import com.mapconductor.core.marker.MarkerTilingOptions +import com.mapconductor.core.marker.MarkerViewportSwitch +import com.mapconductor.core.raster.RasterLayerSource +import com.mapconductor.core.raster.RasterLayerState +import com.mapconductor.core.raster.TileScheme +import com.mapconductor.core.tileserver.TileServerRegistry +import com.mapconductor.here.HereActualMarker +import com.mapconductor.here.HereViewHolder +import java.util.UUID +import kotlin.time.Duration.Companion.milliseconds +import android.os.SystemClock +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.withPermit + +class HereMarkerController private constructor( + markerManager: MarkerManager, + renderer: HereMarkerRenderer, + private val markerTiling: MarkerTilingOptions, +) : AbstractMarkerController( + markerManager = markerManager, + renderer = renderer, + ), + OnCameraChangeReceiverInterface { + private val defaultMarkerIcon: BitmapIcon = DefaultMarkerIcon().toBitmapIcon() + private val tiledMarkerIds = LinkedHashSet() + + @Volatile + private var lastKnownZoom: Double = 0.0 + + private val tileServer = TileServerRegistry.get() + private var markerTileRenderer: MarkerTileRenderer? = null + private var markerTileGroupId: String? = null + private var markerTileRasterLayerState: RasterLayerState? = null + private var rasterLayerCallback: MarkerTileRasterLayerCallback? = null + private var cacheVersion: Int = 0 + + /** + * ビューポート内が少ないときだけタイルをやめてネイティブマーカーで描く切り替え器。 + * + * レンダラ/マネージャ/semaphore を共有するので、コントローラと同じ排他の下で動く。 + */ + private val viewportSwitch = + MarkerViewportSwitch( + markerManager = markerManager, + renderer = renderer, + defaultMarkerIcon = defaultMarkerIcon, + semaphore = semaphore, + policy = markerTiling.viewport, + setTileLayerVisible = ::setTileLayerVisible, + invalidateTiles = ::updateRasterLayerSource, + ) + + fun setRasterLayerCallback(callback: MarkerTileRasterLayerCallback?) { + rasterLayerCallback = callback + } + + override suspend fun add(data: List) { + // ingest はタイル担当 entity を marker = null で登録し直すので、先に昇格を戻す。 + // semaphore は再入不可なので withPermit の外で呼ぶこと。 + viewportSwitch.retract() + semaphore.withPermit { + val tilingEnabled = + markerTiling.enabled && data.size >= markerManager.minMarkerCount + val result = + MarkerIngestionEngine.ingest( + data = data, + markerManager = markerManager, + renderer = renderer, + defaultMarkerIcon = defaultMarkerIcon, + tilingEnabled = tilingEnabled, + tiledMarkerIds = tiledMarkerIds, + shouldTile = { state -> !state.draggable && state.getAnimation() == null }, + ) + + if (result.tiledDataChanged) { + syncTiledOverlay() + } else if (result.hasTiledMarkers) { + if (markerTileRenderer == null || markerTileRasterLayerState == null) { + syncTiledOverlay() + } + } else { + removeTileOverlay() + } + } + viewportSwitch.requestReapply() + } + + override suspend fun update(state: MarkerState) { + if (!markerManager.hasEntity(state.id)) return + + // 昇格中の 1 件なら先に取り下げる(下で marker = null 登録があるため)。 + // 昇格していないマーカー(ドラッグ中など)では何もしないので、ドラッグは素通りする。 + if (viewportSwitch.isPromoted(state.id)) viewportSwitch.release(state.id) + + val prevEntity = markerManager.getEntity(state.id) ?: return + val currentFinger = state.fingerPrint() + val prevFinger = prevEntity.fingerPrint + if (currentFinger == prevFinger) return + + semaphore.withPermit { + // 件数だけが要る。allEntities() は全件の写しを作るので、ラベルの付け替えのように + // 数十本が続けて変わると、そのたびに 14 万件を写すことになる。 + val tilingEnabled = + markerTiling.enabled && markerManager.getMemoryStats().entityCount >= markerManager.minMarkerCount + val wantsTiled = tilingEnabled && !state.draggable && state.getAnimation() == null + val wasTiled = tiledMarkerIds.contains(state.id) + + if (wantsTiled) { + if (!wasTiled) { + prevEntity.marker?.let { renderer.onRemove(listOf(prevEntity)) } + tiledMarkerIds.add(state.id) + } + markerManager.updateEntity( + MarkerEntity( + marker = null, + state = state, + visible = prevEntity.visible, + isRendered = true, + // tiling を立てないと MarkerTileRenderer の絞り込みから漏れ、 + // タイル昇格したのにタイルへ描かれないマーカーになる。 + tiling = true, + ), + ) + // タイル担当のままなら、ネイティブのマーカーには何も起きていない。onPostProcess は + // 全件を写してネイティブ分を描き直すので(14 万件で 1 回 50ms)、ネイティブから + // タイルへ移ったときだけ呼ぶ。 + if (!wasTiled) renderer.onPostProcess() + scheduleTileRefresh() + return@withPermit + } + + if (wasTiled) { + tiledMarkerIds.remove(state.id) + } + // ネイティブマーカーとして描くときだけ焼き込む。タイル担当なら要らない。 + val markerIcon = state.icon?.toBitmapIcon() ?: defaultMarkerIcon + + val params = + object : MarkerOverlayRendererInterface.ChangeParamsInterface { + override val current: MarkerEntityInterface = + MarkerEntity( + marker = prevEntity.marker, + state = state, + visible = prevEntity.visible, + isRendered = true, + ) + override val bitmapIcon: BitmapIcon = markerIcon + override val prev: MarkerEntityInterface = prevEntity + } + val markers = renderer.onChange(listOf(params)) + markers.firstOrNull()?.let { actual -> + markerManager.updateEntity( + MarkerEntity( + marker = actual, + state = state, + visible = prevEntity.visible, + isRendered = true, + ), + ) + if (prevFinger.animation != currentFinger.animation) { + state.getAnimation()?.let { renderer.onAnimate(markerManager.getEntity(state.id)!!) } + } + } + renderer.onPostProcess() + + if (tiledMarkerIds.isNotEmpty()) { + scheduleTileRefresh() + } else { + removeTileOverlay() + } + } + viewportSwitch.requestReapply() + } + + private var tileRefreshJob: Job? = null + + /** + * 1 本ずつの変更からの描き直しを 1 回にまとめる。 + * + * ラベルの付け替えのように数十本が続けて変わると、1 本ごとにラスターソースを差し替え、 + * そのたびに地図が見えているタイルを全部取り直していた(MapLibre・Pixel 5a で 45 回、 + * 描き直したタイル 494 枚、最後のタイルまで 6 秒)。続けて来た変更は + * [TILE_REFRESH_COALESCE] の間に受けて、まとめて 1 回だけ差し替える。 + */ + private fun scheduleTileRefresh() { + if (tileRefreshJob?.isActive == true) return + tileRefreshJob = + (renderer as HereMarkerRenderer).coroutine.launch { + delay(TILE_REFRESH_COALESCE) + semaphore.withPermit { syncTiledOverlay() } + } + } + + override suspend fun clear() { + viewportSwitch.destroy() + semaphore.withPermit { + val entities = markerManager.allEntities() + val toRemove = entities.filter { it.marker != null } + if (toRemove.isNotEmpty()) { + renderer.onRemove(toRemove) + } + markerManager.clear() + tiledMarkerIds.clear() + removeTileOverlay() + } + } + + override suspend fun onCameraChanged(mapCameraPosition: MapCameraPosition) { + // 判定と昇格は debounce したうえで切り替え器の中で走る(パン中は動かない)。 + viewportSwitch.onCameraChanged(mapCameraPosition) + lastKnownZoom = mapCameraPosition.zoom + } + + /** + * マーカータイルのラスターレイヤの表示だけを切り替える。 + * + * source(URL)には触らない。触るとタイルを取り直すことになり、切り替えのたびに + * タイルキャッシュを捨てるのと同じになる。 + */ + private suspend fun setTileLayerVisible(visible: Boolean) { + val current = markerTileRasterLayerState ?: return + if (current.visible == visible) return + val newState = current.copy(visible = visible) + markerTileRasterLayerState = newState + rasterLayerCallback?.onRasterLayerUpdate(newState) + } + + override fun destroy() { + viewportSwitch.destroy() + // 待っている描き直しが後から走ると、外したタイル経路をまた登録してしまう。 + tileRefreshJob?.cancel() + // Clean up tile server registration + // Unregister this map's route only. Never stop the server here: it is + // a process-wide singleton shared by all map controllers and overlay + // modules; stopping it breaks tile loading for every other live map. + markerTileGroupId?.let { groupId -> + tileServer.unregister(groupId) + } + markerTileGroupId = null + markerTileRenderer = null + + (renderer as HereMarkerRenderer).coroutine.launch { + rasterLayerCallback?.onRasterLayerUpdate(null) + } + markerTileRasterLayerState = null + super.destroy() + } + + private suspend fun updateRasterLayerSource() { + val groupId = markerTileGroupId ?: return + val tileRenderer = markerTileRenderer ?: return + val oldState = markerTileRasterLayerState ?: return + cacheVersion = (cacheVersion + 1) and 0x7fffffff + tileRenderer.invalidate() + val cacheBuster = "${cacheVersion}_${SystemClock.elapsedRealtime()}" + + val newState = + oldState.copy( + source = + RasterLayerSource.UrlTemplate( + template = "${tileServer.urlTemplate(groupId, tileRenderer.tileSize)}?cb=$cacheBuster", + tileSize = tileRenderer.tileSize, + maxZoom = 22, + scheme = TileScheme.XYZ, + ), + id = oldState.id, + ) + markerTileRasterLayerState = newState + rasterLayerCallback?.onRasterLayerUpdate(newState) + } + + private suspend fun syncTiledOverlay() { + if (tiledMarkerIds.isEmpty()) { + removeTileOverlay() + return + } + if (!markerTiling.enabled) { + removeTileOverlay() + tiledMarkerIds.clear() + return + } + + getOrCreateTileRenderer() + updateRasterLayerSource() + } + + private fun getOrCreateTileRenderer(): MarkerTileRenderer { + markerTileRenderer?.let { return it } + + val groupId = UUID.randomUUID().toString() + markerTileGroupId = groupId + + // HERE displays one raster tile over 512 logical px, so render tiles at + // 512 with no extra icon scale: icons match regular MapMarker size 1:1. + // (256 gets upscaled 2x -> icons appear double size; 1024 doubles the + // render/PNG-encode cost for no visible gain.) + val tileScale = 1.0 + val outputTileSize = 512 + + cacheVersion = (cacheVersion + 1) and 0x7fffffff + val tileRenderer = + MarkerTileRenderer( + markerManager = markerManager, + tileSize = outputTileSize, + cacheSizeBytes = markerTiling.cacheSize, + debugTileOverlay = markerTiling.debugTileOverlay, + iconScaleCallback = markerTiling.iconScaleCallback, + declutterPx = markerTiling.declutterPx, + extraIconScale = tileScale, + ) + markerTileRenderer = tileRenderer + + tileServer.register(groupId, tileRenderer) + + markerTileRasterLayerState = + RasterLayerState( + id = "marker-tile-$groupId", + source = + RasterLayerSource.UrlTemplate( + template = "${tileServer.urlTemplate(groupId, tileRenderer.tileSize)}?cb=$cacheVersion", + tileSize = tileRenderer.tileSize, + maxZoom = 22, + scheme = TileScheme.XYZ, + ), + opacity = 1.0f, + visible = true, + ) + + return tileRenderer + } + + private suspend fun removeTileOverlay() { + markerTileGroupId?.let { groupId -> + tileServer.unregister(groupId) + } + markerTileGroupId = null + markerTileRenderer = null + + rasterLayerCallback?.onRasterLayerUpdate(null) + markerTileRasterLayerState = null + } + + companion object { + /** 続けて来る変更を 1 回の描き直しにまとめる窓。1 フレーム分。 */ + private val TILE_REFRESH_COALESCE = 16.milliseconds + + fun create( + holder: HereViewHolder, + markerTiling: MarkerTilingOptions = MarkerTilingOptions.Default, + ): HereMarkerController { + val renderer = + HereMarkerRenderer( + holder = holder, + ) + val markerManager = + MarkerManager.defaultManager( + minMarkerCount = markerTiling.minMarkerCount, + ) + val controller = + HereMarkerController( + markerManager = markerManager, + renderer = renderer, + markerTiling = markerTiling, + ) + // HERE camera zoom is updated via onCameraChanged; initialize a best-effort value. + controller.lastKnownZoom = holder.mapView.camera.state.zoomLevel + return controller + } + } +} diff --git a/src/main/java/com/mapconductor/here/marker/HereMarkerRenderer.kt b/src/main/java/com/mapconductor/here/marker/HereMarkerRenderer.kt index 92a8e4d..d9c393f 100644 --- a/src/main/java/com/mapconductor/here/marker/HereMarkerRenderer.kt +++ b/src/main/java/com/mapconductor/here/marker/HereMarkerRenderer.kt @@ -2,11 +2,11 @@ package com.mapconductor.here.marker import com.here.sdk.core.Metadata import com.here.sdk.mapview.MapMarker -import com.mapconductor.core.calculateZIndex import com.mapconductor.core.features.GeoPoint import com.mapconductor.core.marker.AbstractMarkerOverlayRenderer import com.mapconductor.core.marker.MarkerEntityInterface import com.mapconductor.core.marker.MarkerOverlayRendererInterface +import com.mapconductor.core.marker.MarkerState import com.mapconductor.here.HereActualMarker import com.mapconductor.here.HereViewHolder import com.mapconductor.here.toAnchor2D @@ -16,6 +16,7 @@ import java.io.Serializable import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext class HereMarkerRenderer( holder: HereViewHolder, @@ -27,8 +28,32 @@ class HereMarkerRenderer( holder = holder, coroutine = coroutine, ) { - private fun resolveDrawOrder(state: com.mapconductor.core.marker.MarkerState): Int = - state.zIndex ?: calculateZIndex(state.position) + // HERE の drawOrder は整数で、しかも小さい値でしか効かない(タブレットの実機で 2849 は + // 効き、4274 以上は無視されて足した順になった)。zIndex と位置を 1 つの値に詰める余地が + // 無いので、全マーカーを [drawOrderOf](zIndex が第 1 キー、同じなら画面で下が手前)で + // 並べた順位を 0..[MAX_DRAW_ORDER] に割り振る。足す・変える・地図が回るたびに振り直す。 + private val live = LinkedHashMap>() + + private fun track( + marker: MapMarker, + state: MarkerState, + ) = synchronized(live) { live[state.id] = marker to state } + + private suspend fun assignDrawOrders() { + val sorted = synchronized(live) { live.values.toList() }.sortedBy { (_, state) -> drawOrderOf(state) } + if (sorted.isEmpty()) return + val last = (sorted.size - 1).coerceAtLeast(1).toLong() + withContext(coroutine.coroutineContext) { + sorted.forEachIndexed { i, (marker, _) -> + // 数が多いと順位を間引く(隣どうしが同じ値になり、その間だけ足した順になる)。 + val order = if (sorted.size <= MAX_DRAW_ORDER + 1) i else (i * MAX_DRAW_ORDER / last).toInt() + if (marker.drawOrder != order) marker.drawOrder = order + } + } + } + + // 地図が回ったら、今の向きで順位を振り直す。 + override suspend fun applyDrawOrder(entities: List>) = assignDrawOrders() override val supportsAnimationOverlay: Boolean = true @@ -65,7 +90,6 @@ class HereMarkerRenderer( params.bitmapIcon.toMapImage(), params.bitmapIcon.toAnchor2D(), ).apply { - drawOrder = resolveDrawOrder(params.state) metadata = Metadata().apply { // Always include MapConductor marker id @@ -74,6 +98,7 @@ class HereMarkerRenderer( putExtras(params.state.extra) } } + track(marker, params.state) return@map marker } @@ -84,6 +109,7 @@ class HereMarkerRenderer( } override suspend fun onRemove(data: List>) { + synchronized(live) { data.forEach { live.remove(it.state.id) } } coroutine.launch { val markers: List = data.mapNotNull { params -> params.marker } if (markers.isNotEmpty()) { @@ -93,7 +119,7 @@ class HereMarkerRenderer( } override suspend fun onPostProcess() { - // Do nothing here + assignDrawOrders() } override suspend fun onChange( @@ -111,13 +137,16 @@ class HereMarkerRenderer( } marker.coordinates = GeoPoint.from(params.current.state.position).toGeoCoordinates() - marker.drawOrder = resolveDrawOrder(params.current.state) + track(marker, params.current.state) // Hereはマーカーを再作成しなくてよいので、同じマーカーのインスタンスを返す marker } } +/** マーカーの drawOrder に使う上限。実機で効いた最大(2849)より小さく取る。 */ +private const val MAX_DRAW_ORDER = 2047 + // Convert MarkerState.extra into HERE Metadata entries. // Supports Map by best-effort type mapping; otherwise stores value as string under key "mc:extra". private fun Metadata.putExtras(extra: Serializable?) { diff --git a/src/main/java/com/mapconductor/here/polygon/HerePolygonOverlayRenderer.kt b/src/main/java/com/mapconductor/here/polygon/HerePolygonOverlayRenderer.kt index 8862948..1b602f3 100644 --- a/src/main/java/com/mapconductor/here/polygon/HerePolygonOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/here/polygon/HerePolygonOverlayRenderer.kt @@ -9,6 +9,7 @@ import com.mapconductor.core.ResourceProvider import com.mapconductor.core.features.GeoPoint import com.mapconductor.core.features.GeoPointInterface import com.mapconductor.core.features.GeoRectBounds +import com.mapconductor.core.geometry.densifyPolygonRing import com.mapconductor.core.normalizeLng import com.mapconductor.core.polygon.AbstractPolygonOverlayRenderer import com.mapconductor.core.polygon.PolygonEntityInterface @@ -16,6 +17,7 @@ import com.mapconductor.core.polygon.PolygonState import com.mapconductor.core.polygon.splitPolygonWithHolesIntoSimpleRings import com.mapconductor.core.polygon.unionHoles import com.mapconductor.here.HereActualPolygon +import com.mapconductor.here.HereOverlayStacking import com.mapconductor.here.HereViewHolder import android.util.Log import kotlinx.coroutines.CoroutineScope @@ -144,7 +146,7 @@ class HerePolygonOverlayRenderer( } } if (finger.zIndex != prevFinger.zIndex) { - polygon.forEach { it.drawOrder = current.state.zIndex.coerceIn(0, 511) } + polygon.forEach { it.drawOrder = HereOverlayStacking.polygonDrawOrder(current.state.zIndex) } } polygon @@ -160,7 +162,7 @@ class HerePolygonOverlayRenderer( val strokeWidth = ResourceProvider.dpToPx(state.strokeWidth) val transparentFill = Color.valueOf(0f, 0f, 0f, 0f) val fillColor = Color.valueOf(state.fillColor.toArgb()) - val order = state.zIndex.coerceIn(0, 511) + val order = HereOverlayStacking.polygonDrawOrder(state.zIndex) buildList { // 塗り: 穴を持たないピース群へ分解し、1 ピース 1 枚で塗る。 @@ -230,22 +232,17 @@ class HerePolygonOverlayRenderer( Color.valueOf(state.fillColor.toArgb()), Color.valueOf(state.strokeColor.toArgb()), outlineWidth, - ).apply { drawOrder = state.zIndex.coerceIn(0, 511) } + ).apply { drawOrder = HereOverlayStacking.polygonDrawOrder(state.zIndex) } } private fun toRing( points: List, geodesic: Boolean, ): List = - ( - if (geodesic) { - com.mapconductor.core.spherical - .WGS84Geodesic - .createInterpolatePoints(points) - } else { - points - } - ).map { GeoCoordinates(it.latitude, normalizeLng(it.longitude)) } + // 閉じる辺(末尾 → 先頭)も他の辺と同じく補間する(塗りと輪郭が同じネイティブポリゴン)。 + // geodesic は大圏、geodesic=false は緯度経度の線形補間(ポリラインの false と同じ線)。 + densifyPolygonRing(points, geodesic) + .map { GeoCoordinates(it.latitude, normalizeLng(it.longitude)) } .let { pts -> if (pts.size >= 2 && pts.first() == pts.last()) pts.dropLast(1) else pts } /** [toRing] と同じ補間・正規化を、分割へ渡すため GeoPointInterface のまま返す。 */ @@ -253,15 +250,9 @@ class HerePolygonOverlayRenderer( points: List, geodesic: Boolean, ): List = - ( - if (geodesic) { - com.mapconductor.core.spherical - .WGS84Geodesic - .createInterpolatePoints(points) - } else { - points - } - ).map { GeoPoint(latitude = it.latitude, longitude = normalizeLng(it.longitude)) } + // 閉じる辺(末尾 → 先頭)も他の辺と同じく補間する(塗りと輪郭が同じネイティブポリゴン)。 + // geodesic は大圏、geodesic=false は緯度経度の線形補間(ポリラインの false と同じ線)。 + densifyPolygonRing(points, geodesic).map { GeoPoint(latitude = it.latitude, longitude = normalizeLng(it.longitude)) } private fun boundsOf(points: List): GeoRectBounds? { if (points.isEmpty()) return null diff --git a/src/main/java/com/mapconductor/here/polyline/HerePolylineOverlayRenderer.kt b/src/main/java/com/mapconductor/here/polyline/HerePolylineOverlayRenderer.kt index 6bc12e1..df4398a 100644 --- a/src/main/java/com/mapconductor/here/polyline/HerePolylineOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/here/polyline/HerePolylineOverlayRenderer.kt @@ -16,6 +16,7 @@ import com.mapconductor.core.polyline.PolylineState import com.mapconductor.core.spherical.Planar import com.mapconductor.core.spherical.WGS84Geodesic import com.mapconductor.here.HereActualPolyline +import com.mapconductor.here.HereOverlayStacking import com.mapconductor.here.HereViewHolder import com.mapconductor.here.toGeoCoordinates import kotlinx.coroutines.CoroutineScope @@ -32,7 +33,7 @@ class HerePolylineOverlayRenderer( val representation = createRepresentation(state) val mapPolyline = MapPolyline(geoPolyline, representation).apply { - drawOrder = (state.zIndex + 512).coerceIn(512, 1023) + drawOrder = HereOverlayStacking.polylineDrawOrder(state.zIndex) } coroutine.launch { @@ -66,7 +67,7 @@ class HerePolylineOverlayRenderer( } if (finger.zIndex != prevFinger.zIndex) { - polyline.drawOrder = (current.state.zIndex + 512).coerceIn(512, 1023) + polyline.drawOrder = HereOverlayStacking.polylineDrawOrder(current.state.zIndex) needsReAdd = true } diff --git a/src/main/java/com/mapconductor/here/raster/HereRasterLayerOverlayRenderer.kt b/src/main/java/com/mapconductor/here/raster/HereRasterLayerOverlayRenderer.kt index 19b2b7b..4b15c86 100644 --- a/src/main/java/com/mapconductor/here/raster/HereRasterLayerOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/here/raster/HereRasterLayerOverlayRenderer.kt @@ -3,11 +3,19 @@ package com.mapconductor.here.raster import com.here.sdk.mapview.MapContentType import com.here.sdk.mapview.MapLayer import com.here.sdk.mapview.MapLayerBuilder +import com.here.sdk.mapview.MapLayerPriority +import com.here.sdk.mapview.MapLayerPriorityBuilder import com.here.sdk.mapview.datasource.RasterDataSource import com.here.sdk.mapview.datasource.RasterDataSourceConfiguration +import com.here.sdk.mapview.datasource.RasterTileSource +import com.here.sdk.mapview.datasource.TileKey +import com.here.sdk.mapview.datasource.TileSource import com.here.sdk.mapview.datasource.TileUrlProviderCallback import com.here.sdk.mapview.datasource.TileUrlProviderFactory import com.here.sdk.mapview.datasource.TilingScheme +import com.mapconductor.core.polygon.POLYGON_TILE_LAYER_ID +import com.mapconductor.core.circle.CIRCLE_TILE_LAYER_ID +import com.mapconductor.core.polyline.POLYLINE_TILE_LAYER_ID import com.mapconductor.core.raster.RasterLayerEntityInterface import com.mapconductor.core.raster.RasterLayerOverlayRendererInterface import com.mapconductor.core.raster.RasterLayerSource @@ -16,10 +24,13 @@ import com.mapconductor.core.raster.TileScheme import com.mapconductor.core.tileserver.LocalTileServer import com.mapconductor.core.tileserver.TileProviderInterface import com.mapconductor.core.tileserver.TileRequest +import com.mapconductor.here.HereOverlayStacking import com.mapconductor.here.HereViewHolder import java.io.ByteArrayOutputStream import java.net.HttpURLConnection import java.net.URL +import java.util.Date +import java.util.concurrent.atomic.AtomicBoolean import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Canvas @@ -28,6 +39,10 @@ import android.util.Log import android.util.LruCache import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch class HereRasterLayerOverlayRenderer( private val holder: HereViewHolder, @@ -83,33 +98,51 @@ class HereRasterLayerOverlayRenderer( } val urlProvider = tileSpec.provider val storageLevels = tileSpec.storageLevels - val dataSourceProvider = - RasterDataSourceConfiguration.Provider( - urlProvider, - TilingScheme.QUAD_TREE_MERCATOR, - storageLevels, - ) - dataSourceProvider.hasAlphaChannel = true - val cache = - RasterDataSourceConfiguration.Cache( - holder.mapView.context.cacheDir.absolutePath, - ) - val config = - RasterDataSourceConfiguration( - tileSpec.sourceName, - dataSourceProvider, - cache, - ) - val dataSource = RasterDataSource(holder.mapView.mapContext, config) + // Tiles this process draws are handed over in process. HERE fetches + // through its own network stack and, while the device reports no + // connectivity, does not fetch at all -- not even from 127.0.0.1 -- + // so a URL-fed source goes blank the moment the network is away. + // A tile source is asked for bytes and answered from the same + // providers, with no network in between. + val localTemplate = tileSpec.localTemplate + val dataSource = + if (localTemplate != null) { + RasterDataSource( + holder.mapView.mapContext, + tileSpec.sourceName, + LocalRasterTileSource(tileServer, localTemplate, storageLevels), + ) + } else { + val dataSourceProvider = + RasterDataSourceConfiguration.Provider( + urlProvider, + TilingScheme.QUAD_TREE_MERCATOR, + storageLevels, + ) + dataSourceProvider.hasAlphaChannel = true + val cache = + RasterDataSourceConfiguration.Cache( + holder.mapView.context.cacheDir.absolutePath, + ) + val config = + RasterDataSourceConfiguration( + tileSpec.sourceName, + dataSourceProvider, + cache, + ) + RasterDataSource(holder.mapView.mapContext, config) + } return try { val layer = MapLayerBuilder() .withName(tileSpec.layerName) - .withDataSource(config.name, MapContentType.RASTER_IMAGE) + .withDataSource(tileSpec.sourceName, MapContentType.RASTER_IMAGE) + .withPriority(priorityFor(state)) .forMap(holder.mapView.hereMap) .build() layer.setEnabled(state.visible) + if (isShapeTileLayer(state.id)) shapeTileLayers.add(state.id) HereRasterLayerHandle( dataSource = dataSource, layer = layer, @@ -125,6 +158,41 @@ class HereRasterLayerOverlayRenderer( } } + /** The SDK's shape tile layers on the map now (their ids), so each can be placed against the other. */ + private val shapeTileLayers = java.util.Collections.synchronizedSet(HashSet()) + + /** + * アプリのラスターはラスターの帯(GroundImage・map item の下)。マーカーのタイルは + * マーカーの帯なので、ポリゴン等の map item より上(最後に描く)。ポリゴンのタイルは + * ポリゴンの帯の一番下(GroundImage の上、map item の下)。ポリラインのタイルはその上 + * ([HereOverlayStacking.polylineTilePriority])。どちらも版が変わるたびに作り直すので、 + * もう片方があればそれを基準に置き、作った順に左右されないようにする。 + */ + private fun priorityFor(state: RasterLayerState): MapLayerPriority = + if (state.id.startsWith("marker-tile-")) { + MapLayerPriorityBuilder().renderedLast().build() + } else if (state.id == POLYGON_TILE_LAYER_ID) { + HereOverlayStacking.polygonTilePriority( + beforeLayer = layerNameOf(CIRCLE_TILE_LAYER_ID).takeIf { CIRCLE_TILE_LAYER_ID in shapeTileLayers } + ?: layerNameOf(POLYLINE_TILE_LAYER_ID).takeIf { POLYLINE_TILE_LAYER_ID in shapeTileLayers }, + ) + } else if (state.id == CIRCLE_TILE_LAYER_ID) { + HereOverlayStacking.polygonTilePriority( + beforeLayer = layerNameOf(POLYLINE_TILE_LAYER_ID).takeIf { POLYLINE_TILE_LAYER_ID in shapeTileLayers }, + ) + } else if (state.id == POLYLINE_TILE_LAYER_ID) { + HereOverlayStacking.polylineTilePriority( + afterLayer = layerNameOf(CIRCLE_TILE_LAYER_ID).takeIf { CIRCLE_TILE_LAYER_ID in shapeTileLayers } + ?: layerNameOf(POLYGON_TILE_LAYER_ID).takeIf { POLYGON_TILE_LAYER_ID in shapeTileLayers }, + ) + } else { + HereOverlayStacking.rasterPriority() + } + + private fun layerNameOf(id: String) = "raster-layer-$id" + + private fun isShapeTileLayer(id: String) = id == POLYGON_TILE_LAYER_ID || id == CIRCLE_TILE_LAYER_ID || id == POLYLINE_TILE_LAYER_ID + private fun updateLayer( handle: HereRasterLayerHandle, state: RasterLayerState, @@ -134,6 +202,7 @@ class HereRasterLayerOverlayRenderer( private fun removeLayer(entity: RasterLayerEntityInterface) { val handle = entity.layer + if (isShapeTileLayer(entity.state.id)) shapeTileLayers.remove(entity.state.id) handle.routeId?.let { tileServer.unregister(it) } handle.layer.destroy() handle.dataSource.destroy() @@ -179,6 +248,13 @@ class HereRasterLayerOverlayRenderer( sourceName = "raster-source-${state.id}", layerName = "raster-layer-${state.id}", storageLevels = buildStorageLevels(source.minZoom, source.maxZoom), + // The proxy route is local by construction; a direct + // template is local when it is one of the server's own. + localTemplate = + template.takeIf { + it.startsWith(tileServer.baseUrl + "/") && + (routeId != null || source.scheme != TileScheme.TMS) + }, ) } is RasterLayerSource.TileJson -> { @@ -235,9 +311,96 @@ class HereRasterLayerOverlayRenderer( val sourceName: String, val layerName: String, val storageLevels: List, + /** The XYZ template on this process's tile server, when the tiles come from there. */ + val localTemplate: String? = null, ) } +/** + * A HERE tile source answered from this process's tile server, with no HTTP + * hop and no dependence on the device's connectivity. + */ +private class LocalRasterTileSource( + private val tileServer: LocalTileServer, + private val template: String, + private val levels: List, +) : RasterTileSource { + override fun getDataVersion(tileKey: TileKey): TileSource.DataVersion = VERSION + + override fun addListener(listener: TileSource.Listener) {} + + override fun removeListener(listener: TileSource.Listener) {} + + override fun getTilingScheme(): TilingScheme = TilingScheme.QUAD_TREE_MERCATOR + + override fun getStorageLevels(): List = levels + + override fun loadTile( + tileKey: TileKey, + handler: RasterTileSource.LoadResultHandler, + ): TileSource.LoadTileRequestHandle { + // Exactly one answer per request, whatever happens. A request HERE + // cancels is still one it is waiting on: leave it unanswered and the + // slot is never freed, and after a few gestures HERE stops asking for + // tiles at all -- the map keeps the last picture and looks frozen. + val answered = AtomicBoolean(false) + + fun answer(bytes: ByteArray?) { + if (!answered.compareAndSet(false, true)) return + if (bytes != null) handler.loaded(tileKey, bytes, METADATA) else handler.failed(tileKey) + } + // HERE counts rows from the south (Tokyo at z12 is row 2483, not + // 1612); the templates count from the north, as XYZ does. + val row = (1 shl tileKey.level) - 1 - tileKey.y + val url = + template + .replace("{z}", tileKey.level.toString()) + .replace("{x}", tileKey.x.toString()) + .replace("{y}", row.toString()) + val job = + scope.launch { + answer(runCatching { tileServer.renderLocalTile(url) { !isActive } }.getOrNull()) + } + // Cancelled, or the coroutine never ran: answered from a render + // thread rather than from whichever thread cancelled it. + job.invokeOnCompletion { if (!answered.get()) scope.launch { answer(null) } } + return TileSource.LoadTileRequestHandle { job.cancel() } + } + + /** + * Renders run here and nowhere else. + * + * HERE asks for a screenful at once and every one of those is a tile to + * draw. On `Dispatchers.Default` they take every thread the rest of the + * SDK shares -- camera callbacks, overlays, the vector renderer itself -- + * and the map stops answering gestures while it fills. This is the same + * width, and the same reasoning, as the tile server's own worker pool, + * which is what the HTTP path went through. + */ + private val scope = CoroutineScope(SupervisorJob() + renderDispatcher) + + private companion object { + @OptIn(ExperimentalCoroutinesApi::class) + val renderDispatcher = Dispatchers.Default.limitedParallelism(RENDER_WIDTH) + + /** Tile rendering is CPU-bound; more workers than cores adds contention, not throughput. */ + const val RENDER_WIDTH = 8 + + val VERSION = TileSource.DataVersion(0, 0) + + /** + * Tiles drawn here change only with their URL, so they are given a + * long life -- but a plausible one. A date near the end of `Long` + * does not survive the trip into the SDK: every tile came back + * already expired, the same one was asked for again every 400 ms, + * and after a pinch the map stopped asking for tiles at all. + */ + val METADATA = TileSource.TileMetadata(VERSION, Date(System.currentTimeMillis() + TEN_YEARS_MS)) + + const val TEN_YEARS_MS = 10L * 365 * 24 * 60 * 60 * 1000 + } +} + data class HereRasterLayerHandle( val dataSource: RasterDataSource, val layer: MapLayer,