various fixes
- Commit
486f7acac56f11881c89986934c6848250e777fc- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-15 00:48 UTC (2 months ago)
- Parents
dce23df
Diff
Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex 8f8b2f7273..1c39477c97 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2153,16 +2153,6 @@ dependencies = [ "simd-adler32", ] -[[package]]-name = "modelrunner"-version = "0.1.0"-dependencies = [- "ash",- "flatbuffers",- "jni",- "sha2 0.11.0",-]- [[package]] name = "moxcms" version = "0.8.1"
auto/src/main/java/com/vayunmathur/auto/platform/CarAppHost.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/CarAppHost.kt b/auto/src/main/java/com/vayunmathur/auto/platform/CarAppHost.ktindex 1d23fccaaf..fd964023b3 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/CarAppHost.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/CarAppHost.kt@@ -122,24 +122,40 @@ class CarAppHost( } val conn = object : ServiceConnection { override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {- if (binder == null) return+ Log.i(TAG, "maps service connected; starting handshake")+ if (binder == null) {+ Log.w(TAG, "maps service connected with null binder")+ return+ } thread(name = "ma-auto-carhost", isDaemon = true) { runHandshake(ICarApp.Stub.asInterface(binder)) } } override fun onServiceDisconnected(name: ComponentName?) {+ Log.w(TAG, "maps service disconnected") carApp = null bound = false handshakeDone = false mainHandler.post { onTemplate(HostNavState(mapsPresent = true, connected = false)) } }++ override fun onBindingDied(name: ComponentName?) {+ Log.w(TAG, "maps service binding died")+ }++ override fun onNullBinding(name: ComponentName?) {+ Log.w(TAG, "maps service returned null binding")+ mainHandler.post { onTemplate(HostNavState(mapsPresent = true, connected = false)) }+ } } connection = conn+ Log.i(TAG, "binding maps car service $MAPS_PACKAGE/$MAPS_CAR_SERVICE_CLASS") val ok = runCatching { appContext.bindService(intent, conn, Context.BIND_AUTO_CREATE) }.getOrDefault(false) bound = ok+ Log.i(TAG, "bindService returned $ok") if (!ok) { Log.w(TAG, "bindService to maps failed; nav card stays a launch tile") mainHandler.post { onTemplate(HostNavState(mapsPresent = true, connected = false)) }@@ -261,6 +277,7 @@ class CarAppHost( private fun runHandshake(app: ICarApp) { carApp = app+ Log.i(TAG, "starting car-app handshake") val handshake = bundleOf(HandshakeInfo(appContext.packageName, HOST_API_LEVEL)) ?: return if (!roundTrip("onHandshakeCompleted") { cb -> app.onHandshakeCompleted(handshake, cb) }) return val config = Configuration(appContext.resources.configuration)@@ -283,14 +300,17 @@ class CarAppHost( /** One blocking binder call with a 5s cap; false means the session is dead. */ private fun roundTrip(name: String, call: (IOnDoneCallback) -> Unit): Boolean {+ Log.i(TAG, "$name: calling") val latch = CountDownLatch(1) val failure = AtomicReference<Throwable?>(null) val cb = object : IOnDoneCallback.Stub() { override fun onSuccess(response: Bundleable?) {+ Log.i(TAG, "$name: success") latch.countDown() } override fun onFailure(response: Bundleable?) {+ Log.w(TAG, "$name: failure $response") failure.set(RuntimeException("$name failed: $response")) latch.countDown() }@@ -308,6 +328,7 @@ class CarAppHost( /** Pulls the current template and forwards the nav state. Background thread. */ private fun fetchTemplate() { val app = carApp ?: return+ Log.i(TAG, "fetchTemplate: getManager(app)") // The success payload deserializes through `Bundler`: the manager // stub is an `IInterface`, so `deserializeIInterface` returns the // `IAppManager` proxy itself (via `Stub.asInterface`), never a raw@@ -316,17 +337,21 @@ class CarAppHost( val latch = CountDownLatch(1) val managerCb = object : IOnDoneCallback.Stub() { override fun onSuccess(response: Bundleable?) {+ Log.i(TAG, "fetchTemplate: getManager success, extracting") managerRef.set(runCatching { response?.get() as? androidx.car.app.IAppManager }.getOrNull()) latch.countDown() } override fun onFailure(response: Bundleable?) {+ Log.w(TAG, "fetchTemplate: getManager failure $response") latch.countDown() } } runCatching { app.getManager(CarContext.APP_SERVICE, managerCb) } .onFailure { Log.w(TAG, "getManager threw", it); return }- latch.await(CALL_TIMEOUT_MS, TimeUnit.MILLISECONDS)+ Log.i(TAG, "fetchTemplate: awaiting getManager")+ val managerDone = latch.await(CALL_TIMEOUT_MS, TimeUnit.MILLISECONDS)+ Log.i(TAG, "fetchTemplate: getManager await done=$managerDone") val manager = managerRef.get() ?: run { Log.w(TAG, "getManager returned no manager") return@@ -335,18 +360,23 @@ class CarAppHost( val templateLatch = CountDownLatch(1) val templateCb = object : IOnDoneCallback.Stub() { override fun onSuccess(response: Bundleable?) {+ Log.i(TAG, "fetchTemplate: getTemplate success, extracting") templateRef.set(runCatching { response?.get() }.getOrNull()) templateLatch.countDown() } override fun onFailure(response: Bundleable?) {+ Log.w(TAG, "fetchTemplate: getTemplate failure $response") templateLatch.countDown() } } runCatching { manager.getTemplate(templateCb) } .onFailure { Log.w(TAG, "getTemplate threw", it); return }- templateLatch.await(CALL_TIMEOUT_MS, TimeUnit.MILLISECONDS)+ Log.i(TAG, "fetchTemplate: awaiting getTemplate")+ val templateDone = templateLatch.await(CALL_TIMEOUT_MS, TimeUnit.MILLISECONDS)+ Log.i(TAG, "fetchTemplate: getTemplate await done=$templateDone") val wrapper = templateRef.get() as? TemplateWrapper+ Log.i(TAG, "fetchTemplate: wrapper=$wrapper") val state = wrapper?.let { parseTemplate(it) } ?: HostNavState(mapsPresent = true, connected = true) mainHandler.post { onTemplate(state) } }
build-logic/src/main/kotlin/common-conventions-wear.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-wear.gradle.kts b/build-logic/src/main/kotlin/common-conventions-wear.gradle.ktsindex 3b19bfcd01..398a208449 100644--- a/build-logic/src/main/kotlin/common-conventions-wear.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-wear.gradle.kts@@ -27,6 +27,30 @@ val proguardFile val (appVersionCode, appVersionName) = readVersionInfo() +// Adaptive launcher icons are generated at build time from Material Symbols+// (same mechanism as common-conventions-app). Each app declares its symbol via+// `launcherIcon { symbol = "..." }`.+val launcherIcon = extensions.create("launcherIcon", LauncherIconExtension::class.java).apply {+ scale.convention(0.435)+}+val materialSymbolsRef = "819d78680a849ceef4c78f863d8753e3160b7c89"+val materialSymbolsCache = File(gradle.gradleUserHomeDir, "material-symbols-cache")++extensions.configure<com.android.build.api.variant.ApplicationAndroidComponentsExtension> {+ onVariants { variant ->+ val gen = tasks.register(+ "generate${variant.name.replaceFirstChar { it.uppercase() }}LauncherIcon",+ GenerateLauncherIconTask::class.java,+ ) {+ symbol.set(launcherIcon.symbol)+ scale.set(launcherIcon.scale)+ ref.set(materialSymbolsRef)+ cacheDir.set(materialSymbolsCache)+ }+ variant.sources.res?.addGeneratedSourceDirectory(gen, GenerateLauncherIconTask::outputDir)+ }+}+ configure<com.android.build.api.dsl.ApplicationExtension> { dependenciesInfo { includeInApk = false@@ -45,6 +69,12 @@ configure<com.android.build.api.dsl.ApplicationExtension> { generateLocaleConfig = true } + // Every app declares the same res/resources.properties (unqualifiedResLocale) for+ // per-app locale config. Share a single committed copy instead of one file per app.+ // (Generated res dirs are NOT scanned by extractSupportedLocales, so this must be a+ // real res source directory.)+ sourceSets.getByName("main").res.directories.add(File(rootDir, "build-logic/shared-res").absolutePath)+ ndkVersion = NDK_VERSION defaultConfig {
camera/src/main/assets/selfie_segmentation.onnx
diff --git a/camera/src/main/assets/selfie_segmentation.onnx b/camera/src/main/assets/selfie_segmentation.onnxnew file mode 100644index 0000000000..f926ab523dBinary files /dev/null and b/camera/src/main/assets/selfie_segmentation.onnx differ
games/chess/src/main/assets/maia3-5m.onnx
diff --git a/games/chess/src/main/assets/maia3-5m.onnx b/games/chess/src/main/assets/maia3-5m.onnxnew file mode 100644index 0000000000..891b795f0cBinary files /dev/null and b/games/chess/src/main/assets/maia3-5m.onnx differ
library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapNative.ktindex dc600e7d67..bfd6904aaf 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt@@ -37,9 +37,8 @@ internal object MapNative { * the cache dir: like the archive `maps` downloads, it is large and expensive to * rebuild, so it should not be the first thing the platform reclaims. *- * [archivePath] overrides the built-in archive URL for local iteration (e.g. a- * freshly rebuilt `na.mamaps` pushed to the device). `null` or empty keeps the- * remote `BASEMAP_ARCHIVE_URL` (`planet.mamaps`).+ * The renderer always reads the built-in `planet.mamaps` archive URL: there is no+ * local-override path. */ external fun create( surface: Surface,@@ -48,7 +47,6 @@ internal object MapNative { height: Int, dark: Boolean, muted: Boolean,- archivePath: String?, ): Long /**
library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.ktindex 02e2cdd1d9..f63672623e 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt@@ -70,14 +70,11 @@ import java.io.File * Android Auto, `LocalDensity.current.density` in Compose. The renderer scales line * widths, icons and text with it, so a wrong value gives a legible-but-wrong map rather * than a visible failure.- * @param archivePath overrides the built-in archive URL for local iteration. `null` or empty- * keeps the remote archive. * @param onFrame called on the main thread after each frame that was actually presented. */ class SurfaceMapRenderer( context: Context, private val density: Float,- private val archivePath: String? = null, private val onFrame: () -> Unit = {}, ) { @@ -94,9 +91,8 @@ class SurfaceMapRenderer( widthPx: Int, heightPx: Int, density: Float,- archivePath: String? = null, onFrame: () -> Unit = {},- ) : this(context, density, archivePath, onFrame) {+ ) : this(context, density, onFrame) { attachSurface(surface, widthPx, heightPx) } @@ -290,7 +286,7 @@ class SurfaceMapRenderer( renderState = MapRenderState.Unavailable(MapRenderState.Reason.RendererLibraryMissing) return }- handle = MapNative.create(surface, cacheDir.absolutePath, widthPx, heightPx, dark, muted, archivePath)+ handle = MapNative.create(surface, cacheDir.absolutePath, widthPx, heightPx, dark, muted) if (handle == 0L) { Log.e(TAG, "the Vulkan renderer failed to start; see MapRenderer in logcat") renderState = MapRenderState.Unavailable(MapRenderState.Reason.RendererStartFailed)
library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt b/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.ktindex 7737315f64..9dbea681ca 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt@@ -30,9 +30,9 @@ import kotlin.math.roundToInt /** * The vector map. *- * Renders the self-hosted PMTiles archive at `data.vayunmathur.com/v4.pmtiles` — the same- * one `maps` streams through MapLibre — with our own Vulkan renderer. No third-party tile- * CDN and no API key, which is the whole point: CARTO's keyless raster tiles now come back+ * Renders the planet-scale v7 single-file `planet.mamaps` archive+ * (`data.vayunmathur.com/planet.mamaps`: 12 layers, 128-byte header) with our own+ * Vulkan renderer. No third-party tile CDN and no API key, which is the whole point: * watermarked, and that broke the basemap in five apps (#615). * * The signature is deliberately close to the `RasterMap` it replaces, so migrating a@@ -128,7 +128,6 @@ fun VectorMap( */ onMapClickWithScreen: ((MapClick) -> Unit)? = null, onFrame: () -> Unit = {},- archivePath: String? = null, fallback: @Composable (MapRenderState.Unavailable) -> Unit = {}, content: @Composable MapScope.() -> Unit = {}, ) {@@ -188,7 +187,6 @@ fun VectorMap( darkBasemap = darkBasemap, muted = style == MapStyle.Muted, layerOptions = options.layerOptions,- archivePath = archivePath, userPuck = userPuck, regionMask = regionMask, trafficColors = trafficColors,
library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt b/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.ktindex 7ebc2dfe16..4cb48830cb 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt@@ -51,7 +51,6 @@ internal fun VulkanMapSurface( darkBasemap: Boolean, muted: Boolean, layerOptions: LayerOptions = LayerOptions(),- archivePath: String? = null, userPuck: UserPuck? = null, /** Dim everything outside the administrative region this names. `null` draws no mask. */ regionMask: RegionMask? = null,@@ -89,7 +88,7 @@ internal fun VulkanMapSurface( ) { val context = LocalContext.current val density = LocalDensity.current.density- val host = remember(context, archivePath) { MapSurfaceHost(context, cameraState, density, archivePath, onFrame) }+ val host = remember(context) { MapSurfaceHost(context, cameraState, density, onFrame) } val renderer = host.renderer // Task-17 pick wiring: the projection answers queryRenderedLabels from@@ -251,11 +250,10 @@ private class MapSurfaceHost( context: Context, cameraState: CameraState, density: Float,- archivePath: String?, onFrame: () -> Unit, ) : TextureView.SurfaceTextureListener { - val renderer = SurfaceMapRenderer(context, density, archivePath, onFrame).apply {+ val renderer = SurfaceMapRenderer(context, density, onFrame).apply { composeCamera = cameraState }
library/map/src/main/rust/Cargo.toml
diff --git a/library/map/src/main/rust/Cargo.toml b/library/map/src/main/rust/Cargo.tomlindex c25e756551..6ba1ca6ac6 100644--- a/library/map/src/main/rust/Cargo.toml+++ b/library/map/src/main/rust/Cargo.toml@@ -1,7 +1,8 @@ # The Vulkan vector-tile renderer for `:library:map`. # # Replaces the CARTO raster basemap in findfamily, photos, weather, taxi and-# fooddelivery (#615) with our own renderer over the self-hosted pmtiles archive.+# fooddelivery (#615) with our own renderer over the planet-scale v7+# single-file planet.mamaps archive. # # Why Vulkan and not `androidx.webgpu`: that wrapper bundles Dawn as a 5.79 MB # `libwebgpu_c_bundled.so` per ABI, to translate to the Vulkan that is already on@@ -19,7 +20,7 @@ version = "0.1.0" edition = "2021" publish = false license = "GPL-2.0-only"-description = "Vulkan vector-tile map renderer: PMTiles + MVT in, triangles out"+description = "Vulkan vector-tile map renderer: planet.mamaps v7 in, triangles out" [lib] name = "map_renderer"@@ -37,8 +38,8 @@ sha2.workspace = true # file is the source of truth and the only way to match it is to evaluate it. serde_json.workspace = true -# The PMTiles + MVT codec, shared with `scripts/maps/tile_build`, which writes the-# archives this reads. One implementation, so the two cannot drift.+# The .mamaps codec, shared with `scripts/maps`, which builds the+# planet.mamaps archive this reads. One implementation, so the two cannot drift. tilecodec = { path = "../../../../tilecodec/src/main/rust" } # HTTP goes back out through Kotlin: this crate opens no sockets and carries no TLS@@ -58,9 +59,7 @@ png = "0.18" [target.'cfg(target_os = "android")'.dependencies] ash = { version = "0.38", default-features = false, features = ["loaded"] } -# The same codec with its writer, for tests and the host probes only. They read the-# published `v4.pmtiles` and convert each MVT tile to a `.mamaps` body through-# `mamaps::from_mvt`, which is behind the `write` feature -- so the device build links-# the read half and nothing else. There is no published `.mamaps` archive yet.+# The same codec with its writer, for host tests only. The device build links+# the read half and nothing else. [dev-dependencies] tilecodec = { path = "../../../../tilecodec/src/main/rust", features = ["write"] }
library/map/src/main/rust/examples/nodrop_probe.rs
diff --git a/library/map/src/main/rust/examples/nodrop_probe.rs b/library/map/src/main/rust/examples/nodrop_probe.rsdeleted file mode 100644index d7794bab59..0000000000--- a/library/map/src/main/rust/examples/nodrop_probe.rs+++ /dev/null@@ -1,410 +0,0 @@-//! TEMPORARY. Answers one question: what does "keep the nesting regrouping but STOP DROPPING-//! rings" actually cost? Delete once lead has decided.-//!-//! ```text-//! cargo run --offline -q -p map_renderer --example nodrop_probe-//! ```-//!-//! The proposal on the table is to follow MapLibre and stop discarding rings for validity,-//! on the principle that a discarded ring loses real map content. The principle is right --//! MapLibre's fill path (`src/mln/gfx/fill_generator.cpp:113-125`) is `classifyRings` ->-//! `limitHoles(_, 500)` -> `earcut`, with no validity repair at all - but the principle does-//! not say what the change costs *here*, and the archive's geometry is invalid enough that-//! the cost is not guessable. So this measures three arms against the same exact target-//! rather than arguing from any of them:-//!-//! * **maplibre** - every ring bridged into one earcut call, no regrouping, no drops. This is-//! both what MapLibre does and what this code did before the sanitiser landed.-//! * **current** - nesting regroup, then drop a hole that straddles its exterior or overlaps a-//! hole already taken.-//! * **nodrop** - nesting regroup, keep every ring. The proposal.-//!-//! Target is the even-odd region of the rings by scanline, which is what a rasteriser paints-//! and is quantisation-free - not `exterior - sum(holes)`, which double-counts the archive's-//! overlapping holes and reads low.--use map_renderer::tess::earcut;-use map_renderer::tess::fill;--/// Total triangle area from the REAL production tessellator, in tile-normalised units.-///-/// This exists so the `current` arm cannot go stale. `group_rings` below is a copy of-/// `fill::polygons`, and a copy silently stops matching the moment someone edits the original-/// - which happened repeatedly while this was being written. Comparing against the real-/// `fill::tessellate` on every run makes that drift impossible to miss instead of something-/// you have to remember to re-check.-fn production_area(rings: &[Vec<(i32, i32)>], extent: u32) -> f64 {- let mut v = Vec::new();- let mut idx = Vec::new();- fill::tessellate(rings, extent, false, &mut v, &mut idx);- let mut total = 0.0f64;- for tri in idx.chunks_exact(3) {- let p = |i: u32| {- let b = i as usize * fill::FLOATS_PER_VERTEX;- (v[b] as f64, v[b + 1] as f64)- };- let (ax, ay) = p(tri[0]);- let (bx, by) = p(tri[1]);- let (cx, cy) = p(tri[2]);- total += ((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)).abs() / 2.0;- }- total-}--/// Twice the unsigned area of a ring.-fn ring_area2(ring: &[(i32, i32)]) -> i64 {- let mut sum = 0i64;- for i in 0..ring.len() {- let (x1, y1) = ring[i];- let (x2, y2) = ring[(i + 1) % ring.len()];- sum += x1 as i64 * y2 as i64 - x2 as i64 * y1 as i64;- }- sum.abs()-}--fn bounds(ring: &[(i32, i32)]) -> (i32, i32, i32, i32) {- let mut b = (ring[0].0, ring[0].1, ring[0].0, ring[0].1);- for &(x, y) in &ring[1..] {- b.0 = b.0.min(x);- b.1 = b.1.min(y);- b.2 = b.2.max(x);- b.3 = b.3.max(y);- }- b-}--fn boxes_overlap(a: (i32, i32, i32, i32), b: (i32, i32, i32, i32)) -> bool {- a.0 <= b.2 && a.2 >= b.0 && a.1 <= b.3 && a.3 >= b.1-}--fn box_area(b: (i32, i32, i32, i32)) -> i64 {- (b.2 as i64 - b.0 as i64) * (b.3 as i64 - b.1 as i64)-}--/// Even-odd point-in-ring, integer cross product, as `fill.rs` does it.-fn point_in_ring(x: i32, y: i32, ring: &[(i32, i32)]) -> bool {- let mut inside = false;- for i in 0..ring.len() {- let (x1, y1) = ring[i];- let (x2, y2) = ring[(i + 1) % ring.len()];- if (y1 > y) != (y2 > y) {- let dy = y2 as i64 - y1 as i64;- let along = (x as i64 - x1 as i64) * dy;- let at = (y as i64 - y1 as i64) * (x2 as i64 - x1 as i64);- if if dy > 0 { along < at } else { along > at } {- inside = !inside;- }- }- }- inside-}--/// Is the point exactly on one of the ring's edges?-///-/// `point_in_ring` is an even-odd crossing test, so it answers inconsistently for a point that-/// lies *on* the boundary. Real coastline holes touch their exterior, so `fill.rs` resolves-/// that deliberately rather than leaving it to the crossing parity, and this copy has to do-/// the same or the `current` arm stops describing the renderer.-fn on_boundary(x: i32, y: i32, ring: &[(i32, i32)]) -> bool {- for i in 0..ring.len() {- let (x1, y1) = ring[i];- let (x2, y2) = ring[(i + 1) % ring.len()];- let cross = (x as i64 - x1 as i64) * (y2 as i64 - y1 as i64)- - (y as i64 - y1 as i64) * (x2 as i64 - x1 as i64);- if cross != 0 {- continue;- }- if x >= x1.min(x2) && x <= x1.max(x2) && y >= y1.min(y2) && y <= y1.max(y2) {- return true;- }- }- false-}--/// The boundary counts as inside, as `fill::point_within_ring` does.-fn point_within_ring(x: i32, y: i32, ring: &[(i32, i32)]) -> bool {- point_in_ring(x, y, ring) || on_boundary(x, y, ring)-}--fn rings_overlap(a: &[(i32, i32)], b: &[(i32, i32)]) -> bool {- a.iter().any(|&(x, y)| point_in_ring(x, y, b))- || b.iter().any(|&(x, y)| point_in_ring(x, y, a))-}--/// `fill.rs::polygons`, with the two drop tests behind a flag so both arms come from one-/// body and cannot drift apart.-fn group_rings(rings: &[&[(i32, i32)]], drop_conflicts: bool) -> Vec<Vec<usize>> {- let count = rings.len();- let boxes: Vec<_> = rings.iter().map(|r| bounds(r)).collect();-- let mut enclosing: Vec<Vec<(usize, usize)>> = vec![Vec::new(); count];- for j in 0..count {- for i in 0..count {- if i == j- || !boxes_overlap(boxes[i], boxes[j])- || box_area(boxes[i]) < box_area(boxes[j])- {- continue;- }- let votes =- rings[j].iter().filter(|&&(x, y)| point_within_ring(x, y, rings[i])).count();- if votes * 2 > rings[j].len() {- enclosing[j].push((i, votes));- }- }- }- let depth: Vec<usize> = enclosing.iter().map(|e| e.len()).collect();-- let mut groups = Vec::new();- for exterior in 0..count {- if depth[exterior] % 2 != 0 {- continue;- }- let mut holes: Vec<(usize, usize)> = Vec::new();- for j in 0..count {- if depth[j] % 2 == 0 {- continue;- }- let mut closest: Option<(usize, usize)> = None;- for &(ring, votes) in &enclosing[j] {- if closest.map_or(true, |(held, _)| depth[ring] > depth[held]) {- closest = Some((ring, votes));- }- }- if closest.is_some_and(|(ring, _)| ring == exterior) {- holes.push((j, closest.unwrap().1));- }- }- holes.sort_by_cached_key(|&(j, _)| std::cmp::Reverse(ring_area2(rings[j])));-- let mut group = vec![exterior];- for (j, votes) in holes {- if drop_conflicts {- let straddles = votes != rings[j].len();- let overlaps = group[1..].iter().any(|&k| {- boxes_overlap(boxes[j], boxes[k]) && rings_overlap(rings[j], rings[k])- });- if straddles || overlaps {- continue;- }- }- group.push(j);- }- groups.push(group);- }- groups-}--fn open_length(ring: &[(i32, i32)]) -> usize {- let mut n = ring.len();- while n >= 2 && ring[0] == ring[n - 1] {- n -= 1;- }- n-}--/// Tessellate via `groups`, returning the total triangle area in tile-normalised units.-fn area_of(extent: u32, groups: &[Vec<usize>], open: &[&[(i32, i32)]]) -> f64 {- let scale = 1.0 / extent as f64;- let mut total = 0.0f64;- let mut coords: Vec<i32> = Vec::new();- let mut hole_starts: Vec<usize> = Vec::new();- for group in groups {- coords.clear();- hole_starts.clear();- for (position, &r) in group.iter().enumerate() {- if position > 0 {- hole_starts.push(coords.len() / 2);- }- for &(x, y) in open[r].iter() {- coords.push(x);- coords.push(y);- }- }- for tri in earcut::triangulate(&coords, &hole_starts).chunks_exact(3) {- let p = |i: u32| {- let b = i as usize * 2;- (coords[b] as f64 * scale, coords[b + 1] as f64 * scale)- };- let (ax, ay) = p(tri[0]);- let (bx, by) = p(tri[1]);- let (cx, cy) = p(tri[2]);- total += ((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)).abs() / 2.0;- }- }- total-}--/// The even-odd region of every ring, by scanline. Quantisation-free.-fn even_odd_area(rings: &[Vec<(i32, i32)>], extent: u32) -> f64 {- let mut edges: Vec<((i32, i32), (i32, i32))> = Vec::new();- for ring in rings {- let n = open_length(ring);- if n < 3 {- continue;- }- for i in 0..n {- let (a, b) = (ring[i], ring[(i + 1) % n]);- if a.1 != b.1 {- edges.push((a, b));- }- }- }- if edges.is_empty() {- return 0.0;- }- let lo = edges.iter().map(|e| e.0 .1.min(e.1 .1)).min().unwrap();- let hi = edges.iter().map(|e| e.0 .1.max(e.1 .1)).max().unwrap();- let mut xs: Vec<f64> = Vec::new();- let mut total = 0.0f64;- for row in lo..hi {- let y = row as f64 + 0.5;- xs.clear();- for &((x1, y1), (x2, y2)) in &edges {- if (y1 as f64 > y) != (y2 as f64 > y) {- let t = (y - y1 as f64) / (y2 as f64 - y1 as f64);- xs.push(x1 as f64 + t * (x2 as f64 - x1 as f64));- }- }- xs.sort_by(|a, b| a.partial_cmp(b).unwrap());- let mut i = 0;- while i + 1 < xs.len() {- total += xs[i + 1] - xs[i];- i += 2;- }- }- let s = 1.0 / extent as f64;- total * s * s-}--struct Arm {- name: &'static str,- worst: f64,- lost: f64,- surplus: f64,-}--fn scan(label: &str, bytes: &[u8], only_big: bool) {- let tile = tilecodec::mvt::Tile::decode(bytes).expect("tile decodes");- for layer in &tile.layers {- let mut arms = [- Arm { name: "maplibre", worst: 1.0, lost: 0.0, surplus: 0.0 },- Arm { name: "current", worst: 1.0, lost: 0.0, surplus: 0.0 },- Arm { name: "nodrop", worst: 1.0, lost: 0.0, surplus: 0.0 },- Arm { name: "ml+area", worst: 1.0, lost: 0.0, surplus: 0.0 },- Arm { name: "ml+revsd", worst: 1.0, lost: 0.0, surplus: 0.0 },- Arm { name: "PROD", worst: 1.0, lost: 0.0, surplus: 0.0 },- ];- // Set if the `current` copy ever stops agreeing with the real tessellator.- let mut drift = 0.0f64;- let mut groups_seen = 0usize;-- for feature in &layer.features {- if feature.geom_type != tilecodec::mvt::GeomType::Polygon {- continue;- }- let Some(polys) = tilecodec::mvt::decode_polygons(&feature.geometry) else { continue };- for rings in &polys {- if only_big && rings.len() < 50 {- continue;- }- let want = even_odd_area(rings, layer.extent);- if want <= 1e-9 {- continue;- }- groups_seen += 1;-- let mut open: Vec<&[(i32, i32)]> = Vec::new();- let mut degenerate_exterior = false;- for (r, ring) in rings.iter().enumerate() {- let n = open_length(ring);- // `fill::tessellate`'s MIN_RING_COORDS gate, reproduced exactly: a ring- // under three vertices encloses nothing, and if it is the EXTERIOR the- // whole polygon goes, because a hole with nothing around it would render- // as solid fill.- if n < 3 {- if r == 0 {- degenerate_exterior = true;- break;- }- continue;- }- open.push(&ring[..n]);- }- if degenerate_exterior || open.is_empty() {- continue;- }-- // Arm 1: everything bridged into one earcut call, ring order as decoded.- let flat: Vec<Vec<usize>> = vec![(0..open.len()).collect()];- let got_ml = area_of(layer.extent, &flat, &open);- let got_cur = area_of(layer.extent, &group_rings(&open, true), &open);- let got_nd = area_of(layer.extent, &group_rings(&open, false), &open);-- // Arms 4 and 5: the same rings, holes presented in a different order.- // `limitHoles` sorts holes by descending area, so if hole order reached- // earcut's bridging it could explain MapLibre doing better on the same- // geometry. Exterior stays at index 0; only the holes are permuted.- let mut by_area: Vec<usize> = (1..open.len()).collect();- by_area.sort_by_key(|&i| std::cmp::Reverse(ring_area2(open[i])));- let area_first: Vec<Vec<usize>> =- vec![std::iter::once(0).chain(by_area).collect()];- let got_area = area_of(layer.extent, &area_first, &open);-- let reversed: Vec<Vec<usize>> =- vec![std::iter::once(0).chain((1..open.len()).rev()).collect()];- let got_rev = area_of(layer.extent, &reversed, &open);-- let got_prod = production_area(rings, layer.extent);- drift = drift.max((got_prod - got_cur).abs());-- for (arm, got) in arms- .iter_mut()- .zip([got_ml, got_cur, got_nd, got_area, got_rev, got_prod])- {- let ratio = got / want;- if (ratio - 1.0).abs() > (arm.worst - 1.0).abs() {- arm.worst = ratio;- }- if got < want {- arm.lost += want - got;- } else {- arm.surplus += got - want;- }- }- }- }-- if groups_seen == 0 {- continue;- }- println!("{label} {:<11} {groups_seen:>4} groups", layer.name);- for arm in &arms {- println!(- " {:<9} worst ratio {:>6.3} surplus {:>8.5} LOST {:>8.5}",- arm.name, arm.worst, arm.surplus, arm.lost,- );- }- // `current` is a copy of `fill::polygons`; PROD is the real thing. They must agree.- if drift > 1e-9 {- println!(- " !!! STALE: the `current` copy disagrees with fill::tessellate by {drift:.8} \- of a tile. `group_rings` no longer matches `fill::polygons` \u{2014} every `current` \- figure above is describing code that is not in the renderer.",- );- } else {- println!(" (current == fill::tessellate to 1e-9, so the copy is faithful)");- }- }-}--fn main() {- const Z0: &[u8] = include_bytes!("../tests/fixtures/v4_z0_tile.mvt");- const Z11: &[u8] = include_bytes!("../tests/fixtures/v5ca_z11_tile.mvt");-- println!("=== the z0 ocean alone: the polygon the sanitiser was built for ===");- scan("z0 ", Z0, true);- println!("\n=== every polygon of both fixtures ===");- scan("z0 ", Z0, false);- scan("z11", Z11, false);-}
library/map/src/main/rust/examples/place_probe.rs
diff --git a/library/map/src/main/rust/examples/place_probe.rs b/library/map/src/main/rust/examples/place_probe.rsdeleted file mode 100644index fb7011102b..0000000000--- a/library/map/src/main/rust/examples/place_probe.rs+++ /dev/null@@ -1,219 +0,0 @@-//! TEMPORARY. Replicates the renderer symbol pre-pass on host to debug z6-//! over-culling: which candidates enter, which place, who blocks whom.-//!-//! ```text-//! MAMAPS_URL=http://127.0.0.1:8090/usw_v2.mamaps cargo run --offline -q -p map_renderer --example place_probe-//! ```-//!-//! Delete once placement parity lands.--use map_renderer::camera::Camera;-use map_renderer::style::{self, LayerKind};-use map_renderer::tile::{geometry, placement, select};-use std::collections::{HashMap, HashSet};-use std::process::Command;-use tilecodec::mamaps::dict;-use tilecodec::mamaps::MamapsArchive;-use tilecodec::proto::{err, Result};-use tilecodec::stream::RangeReader;--fn url() -> String {- std::env::var("MAMAPS_URL")- .unwrap_or_else(|_| "https://data.vayunmathur.com/planet.mamaps".to_string())-}--struct CurlReader;--impl RangeReader for CurlReader {- fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {- let url = url();- let range = format!("{}-{}", offset, offset + length as u64 - 1);- let out = Command::new("curl")- .args(["-s", "-f", "--range", &range, &url])- .output()- .map_err(|e| tilecodec::proto::Error(format!("curl failed to start: {e}")))?;- if !out.status.success() {- return err(format!("curl exited {:?} for range {range}", out.status.code()));- }- Ok(out.stdout)- }-}--fn main() {- // Phone viewport. Assumption noted: collision outcome- // scales with viewport, so counts are comparative, not absolute.- // Side-by-side layout (two weight(1f) panels): each map gets- // HALF the phone width. Override with HALF=0 for a full-width run.- let half = std::env::var("HALF").map(|v| v != "0").unwrap_or(true);- let (w, h) = if half { (205.0, 800.0) } else { (411.0, 891.0) };- let camera = Camera {- center_lon: -122.4194,- center_lat: 37.7749,- zoom: 6.0,- width_dp: w,- height_dp: h,- density: 3.0,- bearing_deg: 0.0,- pitch_deg: 0.0,- time_seconds: 0.0,- };- let extent = ((camera.width_dp * camera.density) as u32, (camera.height_dp * camera.density) as u32);- println!("camera z6 SF viewport {extent:?} device px");-- let mut archive = match MamapsArchive::open(CurlReader) {- Ok(a) => a,- Err(e) => {- println!("archive OPEN FAILED: {e}");- std::process::exit(1);- }- };- let (min_zoom, max_zoom) = (archive.header.min_zoom, archive.header.max_zoom);- let layers = style::layers();-- // Mirror record_inner pre-pass exactly: draws_at + text_size gates.- let mut candidates: Vec<placement::Candidate> = Vec::new();- // candidate id -> (tile z/x/y, layer_index, label idx in tile.labels, name)- let mut meta: HashMap<u64, (u8, u32, u32, usize, usize, String, u8, u16)> = HashMap::new();- let wanted = select::resident_set(&camera, min_zoom, max_zoom);- println!("resident {} tiles ({} exact visible)", wanted.len(), select::visible(&camera, min_zoom, max_zoom).len());- let mut tiles_read = 0;- for tile in &wanted {- let body = match archive.tile(tile.z, tile.x, tile.y) {- Ok(Some(b)) => b,- _ => continue,- };- tiles_read += 1;- let mesh = geometry::build(&body, layers, tile.z, tile.x, tile.y, false);- let tile_extent = body.extent as f32;- for (index, layer) in layers.iter().enumerate() {- if layer.kind != LayerKind::Symbol {- continue;- }- if !layer.draws_at(camera.zoom.floor().clamp(0.0, 22.0) as u8) {- continue;- }- let text_px = layer.text_size.at(camera.zoom);- if text_px <= 0.0 {- continue;- }- let tile_clip = camera.tile_to_clip(tile.z, tile.x, tile.y);- // Mirror the renderer's task-9 rank gating (UI zoom: probe camera- // is already UI zoom, no offset here).- let min_pop = placement::locality_min_pop(camera.zoom);- for (label_idx, label) in mesh.labels.iter().enumerate().filter(|(_, l)| l.layer_index == index) {- if label.rank == 2 && label.pop < min_pop {- continue;- }- let id = placement::candidate_id(tile.z, tile.x, tile.y, index, label_idx);- let Some(rect) = placement::screen_rect(label.anchor, tile_clip, extent, text_px, label.total_advance, 24.0) else { continue };- candidates.push(placement::Candidate {- id,- rank: label.rank,- pop: label.pop,- rect,- // Places have no `text-variable-anchor`, so there is no second box.- alternate: None,- });- // Resolve the display name via anchor -> point feature coords.- let cx = (label.anchor.0 * tile_extent).round() as i16;- let cy = (label.anchor.1 * tile_extent).round() as i16;- let mut name = "?".to_string();- if let Some(places) = body.layer(dict::LAYER_PLACES) {- for f in &places.features {- if f.geom_type != tilecodec::mamaps::body::GEOM_POINT {- continue;- }- let parts = places.parts_of(f);- let Some(first) = parts.first() else { continue };- let pts = places.points(first);- if pts.first() == Some(&(cx, cy)) {- name = body.name(f.name_idx).unwrap_or("?").to_string();- break;- }- }- }- meta.insert(id, (tile.z, tile.x, tile.y, index, label_idx, name, label.rank, label.pop));- }- }- }- println!("tiles {tiles_read} read, {} candidates", candidates.len());- let mut entered: HashMap<u8, usize> = HashMap::new();- for c in &candidates {- *entered.entry(c.rank).or_default() += 1;- }- let mut ranks: Vec<u8> = entered.keys().copied().collect();- ranks.sort();- for r in &ranks {- println!("entered rank {r}: {} candidates", entered[r]);- }-- let accepted: HashSet<u64> = placement::place(&candidates).into_iter().map(|(id, _)| id).collect();- println!("placed {} / {} candidates", accepted.len(), candidates.len());- let mut placed_rank: HashMap<u8, usize> = HashMap::new();- for c in &candidates {- if accepted.contains(&c.id) {- *placed_rank.entry(c.rank).or_default() += 1;- }- }- for r in &ranks {- println!("placed rank {r}: {} / {}", placed_rank.get(r).copied().unwrap_or(0), entered[r]);- }-- // Acceptance order for blocker attribution: re-run place to get order.- let order: Vec<u64> = placement::place(&candidates).into_iter().map(|(id, _)| id).collect();- let pos: HashMap<u64, usize> = order.iter().enumerate().map(|(i, id)| (*id, i)).collect();- // For each culled candidate, the earliest-accepted overlapping box.- let mut by_id: HashMap<u64, &placement::Candidate> = HashMap::new();- for c in &candidates {- by_id.insert(c.id, c);- }- let overlaps = |a: (f32, f32, f32, f32), b: (f32, f32, f32, f32)| {- a.0 < b.2 && b.0 < a.2 && a.1 < b.3 && b.1 < a.3- };- println!("--- culled pop>=1 localities (the ones that should survive) ---");- let mut shown = 0;- for c in &candidates {- if accepted.contains(&c.id) || c.rank != 2 || c.pop < 1 {- continue;- }- let (_, _, _, _, _, name, _, pop) = &meta[&c.id];- // Earliest accepted blocker.- let mut blocker: Option<u64> = None;- for id in &order {- if pos[id] >= pos.get(&c.id).copied().unwrap_or(usize::MAX)- && accepted.contains(id)- {- break;- }- if overlaps(by_id[id].rect, c.rect) {- blocker = Some(*id);- break;- }- }- let block_str = match blocker {- Some(b) => {- let (_, _, _, _, _, bname, brank, bpop) = &meta[&b];- let r = by_id[&b].rect;- format!("BLOCKED BY rank={brank} pop={bpop} '{bname}' box=({:.0},{:.0},{:.0},{:.0})", r.0, r.1, r.2, r.3)- }- None => "no overlapping accepted box (ordering artifact?)".to_string(),- };- println!(- "culled pop={pop} '{name}' box=({:.0},{:.0},{:.0},{:.0}) {block_str}",- c.rect.0, c.rect.1, c.rect.2, c.rect.3- );- shown += 1;- if shown >= 40 {- println!("... (truncated)");- break;- }- }- println!("--- placed pop>=2 (majors that survived) ---");- for c in &candidates {- if !accepted.contains(&c.id) || c.pop < 2 {- continue;- }- let (_, _, _, _, _, name, rank, pop) = &meta[&c.id];- println!("placed rank={rank} pop={pop} '{name}'");- }-}
library/map/src/main/rust/examples/places_probe.rs
diff --git a/library/map/src/main/rust/examples/places_probe.rs b/library/map/src/main/rust/examples/places_probe.rsdeleted file mode 100644index 6e773aae2c..0000000000--- a/library/map/src/main/rust/examples/places_probe.rs+++ /dev/null@@ -1,372 +0,0 @@-//! TEMPORARY. Answers: does live planet.mamaps carry named places points, and-//! what does the symbol pipeline do with them? Delete once the root cause lands.-//!-//! ```text-//! cargo run --offline -q -p map_renderer --example places_probe-//! ```-//!-//! Code-first evidence for the invisible-SDF-text investigation: atlas stats,-//! text-size ramp values at z6/z10, archive header/dict, and per-tile places-//! point counts with names through the real `geometry::build` path.--use map_renderer::camera;-use map_renderer::style;-use map_renderer::tile::geometry;-use map_renderer::tile::glyph;-use std::process::Command;-use tilecodec::mamaps::dict;-use tilecodec::mamaps::MamapsArchive;-use tilecodec::proto::{err, Result};-use tilecodec::stream::RangeReader;--const DEFAULT_URL: &str = "https://data.vayunmathur.com/planet.mamaps";--/// Override with `MAMAPS_URL=http://127.0.0.1:8089/na.mamaps` to probe a local-/// archive (e.g. the ones the emulator reads) instead of prod planet.mamaps.-fn url() -> String {- std::env::var("MAMAPS_URL").unwrap_or_else(|_| DEFAULT_URL.to_string())-}--struct CurlReader;--impl RangeReader for CurlReader {- fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {- let url = url();- let range = format!("{}-{}", offset, offset + length as u64 - 1);- let out = Command::new("curl")- .args(["-s", "-f", "--range", &range, &url])- .output()- .map_err(|e| tilecodec::proto::Error(format!("curl failed to start: {e}")))?;- if !out.status.success() {- return err(format!("curl exited {:?} for range {range}", out.status.code()));- }- Ok(out.stdout)- }-}--/// Tile covering `lon`/`lat` at integer zoom `z`: world-px divided by the-/// 256px tile span.-fn tile_for(lon: f64, lat: f64, z: u8) -> (u32, u32) {- let p = camera::project(lon, lat, z as f64);- ((p.x / 256.0).floor() as u32, (p.y / 256.0).floor() as u32)-}--fn main() {- // (b) Atlas contents on host: dimensions + nonzero-coverage stats.- let atlas = glyph::GlyphAtlas::build();- let min = *atlas.pixels.iter().min().unwrap();- let max = *atlas.pixels.iter().max().unwrap();- let mid = atlas.pixels.iter().filter(|&&v| (64..=192).contains(&v)).count();- let zero = atlas.pixels.iter().filter(|&&v| v == 0).count();- println!(- "atlas {}x{} ({} bytes) min={} max={} mid-band={} zero={} fonts_staged={}",- glyph::ATLAS_PX,- glyph::ATLAS_PX,- atlas.pixels.len(),- min,- max,- mid,- zero,- glyph::fonts_staged(),- );-- // (c) Size-ramp output in px at z6 and z10 for the four symbol layers.- println!("ramp layer size@z6 size@z10 opacity@z6 light halo");- for layer in style::layers().iter().filter(|l| l.kind == style::LayerKind::Symbol) {- println!(- "ramp {:<22} {:>7.2} {:>8.2} {:>9.2} #{:08X} #{:08X}",- layer.id,- layer.text_size.at(6.0),- layer.text_size.at(10.0),- layer.opacity_at(6.0),- layer.light,- layer.halo_light,- );- }- println!("bg light=#{:08X} dark=#{:08X}", style::background(style::Variant::Light), style::background(style::Variant::Dark));-- // The live archive the device reads. Non-fatal: the hardcoded isolation- // below must run even when the archive refuses to open (that refusal is- // itself the leading data-side suspect — see the task-1 report).- let archive_opt = match MamapsArchive::open(CurlReader) {- Ok(a) => Some(a),- Err(e) => {- println!("archive OPEN FAILED: {e}");- None- }- };- let layers = style::layers();- if let Some(mut archive) = archive_opt {- let h = &archive.header;- let (min_zoom, max_zoom, layer_count, addressed, bodies, build_id, compressed, rings_v) =- (h.min_zoom, h.max_zoom, h.layer_count, h.tiles_addressed, h.bodies_written, h.build_id, h.compressed(), h.rings_validated());- println!(- "archive zoom {}..{} layers={} addressed={} bodies={} build_id={:#x} compressed={} rings_validated={}",- min_zoom, max_zoom, layer_count, addressed, bodies, build_id, compressed, rings_v,- );- let layer_count = archive.header.layer_count;- let names: Vec<&str> =- (0..layer_count).filter_map(|id| archive.dictionary.layer_name(id)).collect();- println!("archive dict layers: {}", names.join(","));-- // World tile (countries at z0), SF at z6/z10 (localities), null-island z1.- let (sfx6, sfy6) = tile_for(-122.4194, 37.7749, 6);- let (sfx10, sfy10) = tile_for(-122.4194, 37.7749, 10);- let targets: [(u8, u32, u32, &str); 5] = [- (0, 0, 0, "world"),- (1, 0, 1, "null-island-z1"),- (6, sfx6, sfy6, "sf-z6"),- (10, sfx10, sfy10, "sf-z10"),- (3, 1, 3, "europe-z3"),- ];- for (z, x, y, what) in targets {- let body = match archive.tile(z, x, y) {- Ok(Some(b)) => b,- Ok(None) => {- println!("tile z{z}/{x}/{y} ({what}): ABSENT");- continue;- }- Err(e) => {- println!("tile z{z}/{x}/{y} ({what}): ERROR {e}");- continue;- }- };- let layer_names: Vec<&str> = body- .layers- .iter()- .filter_map(|l| archive.dictionary.layer_name(l.layer_id))- .collect();- let places = body.layer(dict::LAYER_PLACES);- let (points, named, mut samples) = match places {- Some(layer) => {- let mut points = 0usize;- let mut named = 0usize;- let mut samples = Vec::new();- for f in &layer.features {- if f.geom_type != tilecodec::mamaps::body::GEOM_POINT {- continue;- }- points += 1;- if let Some(name) = body.name(f.name_idx) {- named += 1;- if samples.len() < 3 {- let kind = archive- .dictionary- .kind_name(f.kind)- .unwrap_or("?");- samples.push(format!("{kind}={name}"));- }- }- }- (points, named, samples)- }- None => (0, 0, Vec::new()),- };- // Through the real tessellation path: how many labels shape?- // NOTE: `false` for rings_validated is deliberate and symbol-scoped: the- // flag only gates fill repair (another team's assert fired on a real- // tile under `true`); label shaping is independent of it.- let mesh = geometry::build(&body, layers, z, x, y, false);- let per_layer: Vec<String> = {- let mut counts = std::collections::BTreeMap::new();- for label in &mesh.labels {- *counts.entry(layers[label.layer_index].id.clone()).or_insert(0usize) += 1;- }- counts.into_iter().map(|(id, n)| format!("{id}:{n}")).collect()- };- // What would emit at this zoom: text_size per symbol layer.- let mut sizes = Vec::new();- for layer in layers.iter().filter(|l| l.kind == style::LayerKind::Symbol) {- sizes.push(format!("{}={:.1}px", layer.id, layer.text_size.at(z as f64)));- }- println!(- "tile z{z}/{x}/{y} ({what}): layers=[{}] places_points={} named={} samples=[{}]",- layer_names.join(","),- points,- named,- samples.join(" | "),- );- let _ = &mut samples;- println!(- "tile z{z}/{x}/{y} ({what}): shaped_labels={} [{}]; text_size@[z{z}] {}",- mesh.labels.len(),- per_layer.join(" "),- sizes.join(" "),- );- // Emit one label's quads at the frame size to prove emit produces geometry.- if let Some(label) = mesh.labels.first() {- let layer = &layers[label.layer_index];- let text_px = layer.text_size.at(z as f64);- if text_px > 0.0 {- let (mut v, mut idx) = (Vec::new(), Vec::new());- map_renderer::tile::symbol::emit_label(- label,- map_renderer::style::Anchor::Center,- (0.0, 0.0),- text_px,- 256.0,- (1.0, 0.0),- &mut v,- &mut idx,- );- let xs: Vec<f32> =- v.chunks(4).map(|c| c[0]).collect();- let (lo, hi) = (- xs.iter().cloned().fold(f32::INFINITY, f32::min),- xs.iter().cloned().fold(f32::NEG_INFINITY, f32::max),- );- println!(- "tile z{z}/{x}/{y} ({what}): emit '{}' -> {} verts {} idx, x in [{lo:.4},{hi:.4}]",- body.name(- body.layer(dict::LAYER_PLACES)- .and_then(|l| l.features.iter().find_map(|f| {- if f.geom_type == tilecodec::mamaps::body::GEOM_POINT {- body.name(f.name_idx)- } else {- None- }- }))- .map(|_| 1u16)- .unwrap_or(0)- )- .unwrap_or("?"),- v.len() / 4,- idx.len(),- );- }- }- } // end `for` over target tiles.- } // end if let Some(archive): per-tile live-archive section.-- // Shape a synthetic label to isolate emit from tile data (placement bypass).- let (shaped, total) =- map_renderer::tess::text::shape(&atlas, glyph::Weight::Regular, "San Francisco", false);- let (mut v, mut idx) = (Vec::new(), Vec::new());- map_renderer::tess::text::emit(- &atlas,- glyph::Weight::Regular,- &[map_renderer::tess::text::ShapedLine { glyphs: shaped.clone(), advance: total }],- (0.5, 0.5),- map_renderer::style::Anchor::Center,- (0.0, 0.0),- 14.0,- 256.0,- &mut v,- &mut idx,- );- println!(- "synthetic 'San Francisco' @14px/256px: {} glyphs -> {} verts, {} idx",- shaped.len(),- v.len() / 4,- idx.len()- );-- // (a) TEMPORARY hardcoded-label isolation: a synthetic v2 body with one named- // GEOM_POINT through the REAL geometry::build + emit_label path, bypassing- // archive/placement entirely. If this yields sane quads, atlas+shape+emit- // are exonerated and the fault is upstream (no named points reach the tiler- // output) or in the GPU submit (upload/bind/blend on device).- {- use tilecodec::mamaps::body::{Feature, Layer, Part, GEOM_POINT, WINDING_OUTER};- let country_kind =- dict::KINDS.iter().position(|k| *k == "country").map(|i| i as u16 + 1).unwrap();- let body = tilecodec::mamaps::Body {- extent: 4096,- layers: vec![Layer {- layer_id: dict::LAYER_PLACES,- features: vec![Feature {- kind: country_kind,- kind_detail: 0,- geom_type: GEOM_POINT,- flags: 0,- name_idx: 1,- parts_offset: 0,- part_count: 1,- transit_color: 0,- transit_ordinal: 0,- transit_lanes: 0,- transit_taper: 0,- lane_count: 0,- }],- parts: vec![Part { coord_start: 0, point_count: 1, winding: WINDING_OUTER }],- coords: vec![(2048, 2048)],- }],- names: vec!["Testland".to_string()],- ids: Vec::new(),- turn_lanes: Vec::new(),- buildings: Vec::new(),- heightmap: None, carriageways: Vec::new(), convention: None,- };- let mesh = geometry::build(&body, layers, 6, 32, 40, false);- println!(- "hardcode synthetic v2 body -> {} shaped label(s) {}",- mesh.labels.len(),- if mesh.labels.len() == 1 { "(shape_label OK)" } else { "(SHAPE FAILED)" },- );- if let Some(label) = mesh.labels.first() {- let layer = &layers[label.layer_index];- let text_px = layer.text_size.at(6.0);- let (mut v, mut idx) = (Vec::new(), Vec::new());- map_renderer::tile::symbol::emit_label(- label,- map_renderer::style::Anchor::Center,- (0.0, 0.0),- text_px,- 256.0,- (1.0, 0.0),- &mut v,- &mut idx,- );- let (mut x0, mut x1, mut y0, mut y1) =- (f32::INFINITY, f32::NEG_INFINITY, f32::INFINITY, f32::NEG_INFINITY);- for c in v.chunks(4) {- x0 = x0.min(c[0]);- x1 = x1.max(c[0]);- y0 = y0.min(c[1]);- y1 = y1.max(c[1]);- }- println!(- "hardcode emit '{}' @ {:.1}px: {} verts {} idx, tile box x[{x0:.4},{x1:.4}] y[{y0:.4},{y1:.4}]",- body.name(1).unwrap_or("?"),- text_px,- v.len() / 4,- idx.len(),- );- // Frag-shader simulation on the real atlas bytes: does the SDF edge- // test in symbol.frag yield alpha~1 inside a glyph?- let cell = |ch: char| {- atlas.uv(glyph::Weight::Medium, ch).expect("uv")- };- let uv = cell('T');- let texel = 1.0 / glyph::ATLAS_PX as f32;- let sample = |u: f32, vv: f32| -> f32 {- let x = (u * glyph::ATLAS_PX as f32).floor().clamp(0.0, 1023.0) as usize;- let y = (vv * glyph::ATLAS_PX as f32).floor().clamp(0.0, 1023.0) as usize;- atlas.pixels[y * glyph::ATLAS_PX as usize + x] as f32 / 255.0- };- // Grid over the 'T' cell: count texels where frag face alpha > 0.5.- let (mut inside, mut total_px) = (0usize, 0usize);- let n = 16;- for j in 0..n {- for i in 0..n {- let u = uv.u0 + (uv.u1 - uv.u0) * (i as f32 + 0.5) / n as f32;- let vv = uv.v0 + (uv.v1 - uv.v0) * (j as f32 + 0.5) / n as f32;- let dist = sample(u, vv);- let edge0 = 0.5 - texel;- let edge1 = 0.5 + texel;- // smoothstep(edge0, edge1, dist) on CPU.- let t = ((dist - edge0) / (edge1 - edge0)).clamp(0.0, 1.0);- let face = t * t * (3.0 - 2.0 * t);- total_px += 1;- if face > 0.5 {- inside += 1;- }- }- }- println!(- "hardcode frag-sim 'T' cell: {inside}/{total_px} texels face>0.5 (texel={texel:.6}) {}",- if inside > 0 { "(shader edge test FIRES)" } else { "(SHADER WOULD EMIT NOTHING)" },- );- }- }-} // main (closes the hardcoded-label isolation; the live-archive `if let` above is closed at its own end marker)
library/map/src/main/rust/examples/pmtiles_roads_probe.rs
diff --git a/library/map/src/main/rust/examples/pmtiles_roads_probe.rs b/library/map/src/main/rust/examples/pmtiles_roads_probe.rsdeleted file mode 100644index 9f8d56b46e..0000000000--- a/library/map/src/main/rust/examples/pmtiles_roads_probe.rs+++ /dev/null@@ -1,87 +0,0 @@-//! The `roads` counterpart of [`roads_probe`] for the vendored PMTiles basemap.-//!-//! ```text-//! cargo run --offline -p map_renderer --example pmtiles_roads_probe -- 6 10 24-//! ```-//!-//! Same question, other side of the comparator: which `kind`s does the reference-//! archive carry at a zoom where ours looks fragmented? HTTP is shelled to `curl`,-//! as `probe_archive` does, so the crate keeps no HTTP dependency.--use std::process::Command;-use tilecodec::mvt::Tile;-use tilecodec::proto::{err, Result};-use tilecodec::stream::{RangeReader, StreamArchive};--const URL: &str = "https://data.vayunmathur.com/v4.pmtiles";--struct CurlReader;--impl RangeReader for CurlReader {- fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {- let range = format!("{}-{}", offset, offset + length as u64 - 1);- let out = match Command::new("curl").args(["-s", "-f", "--range", &range, URL]).output() {- Ok(out) => out,- Err(e) => return err(format!("curl failed to start: {e}")),- };- if !out.status.success() {- return err(format!("curl exited {:?} for range {range}", out.status.code()));- }- Ok(out.stdout)- }-}--fn show(value: Option<&tilecodec::mvt::Value>) -> String {- use tilecodec::mvt::Value;- match value {- Some(Value::String(s)) => s.clone(),- Some(other) => format!("{other:?}"),- None => "-".to_string(),- }-}--fn main() {- let args: Vec<String> = std::env::args().collect();- if args.len() < 4 {- eprintln!("usage: pmtiles_roads_probe Z X Y");- std::process::exit(2);- }- let z: u8 = args[1].parse().expect("z");- let x: u32 = args[2].parse().expect("x");- let y: u32 = args[3].parse().expect("y");-- let mut archive = StreamArchive::open(CurlReader).expect("open archive");- let Some(bytes) = archive.tile(z, x, y).expect("read tile") else {- println!("{z}/{x}/{y} is absent");- return;- };- let tile = Tile::decode(&bytes).expect("decode mvt");- let Some(layer) = tile.layers.iter().find(|l| l.name == "roads") else {- println!("{z}/{x}/{y} has no roads layer");- return;- };-- let mut totals: std::collections::BTreeMap<(String, String), (u32, f64)> = Default::default();- for feature in &layer.features {- let kind = show(feature.get("kind"));- let detail = show(feature.get("kind_detail"));- let mut length = 0.0f64;- if let Some(lines) = tilecodec::mvt::decode_lines(&feature.geometry) {- for line in lines {- for pair in line.windows(2) {- let dx = (pair[1].0 - pair[0].0) as f64;- let dy = (pair[1].1 - pair[0].1) as f64;- length += (dx * dx + dy * dy).sqrt();- }- }- }- let entry = totals.entry((kind, detail)).or_insert((0, 0.0));- entry.0 += 1;- entry.1 += length;- }-- println!("{z}/{x}/{y} extent {} — roads by (kind, kind_detail):", layer.extent);- for ((kind, detail), (count, length)) in totals {- println!(" {kind:<14} {detail:<16} {count:>6} features {length:>12.0} units");- }-}
library/map/src/main/rust/examples/probe_archive.rs
diff --git a/library/map/src/main/rust/examples/probe_archive.rs b/library/map/src/main/rust/examples/probe_archive.rsdeleted file mode 100644index 01dfd71030..0000000000--- a/library/map/src/main/rust/examples/probe_archive.rs+++ /dev/null@@ -1,392 +0,0 @@-//! Probes the live archive end to end, through the real code the app uses.-//!-//! ```text-//! cargo run --offline -p map_renderer --example probe_archive-//! ```-//!-//! This exists because the renderer cannot be verified on a host: Vulkan needs a device.-//! Everything *before* the GPU can be, though, and that is where the bugs were — a-//! hardcoded max zoom that did not match the archive, and tiles that silently resolved to-//! nothing. So this drives the actual [`StreamArchive`], the actual gzip and MVT decoders,-//! the actual style and the actual tessellators against-//! `https://data.vayunmathur.com/v4.pmtiles`, and prints what comes out.-//!-//! HTTP is shelled out to `curl`, which ships with Windows 10+, macOS and every Linux we-//! build on. On device this same trait is implemented over `library/jni-http`; using curl-//! here keeps the crate free of an HTTP dependency that only a diagnostic needs.--use map_renderer::camera::Camera;-use map_renderer::style;-use map_renderer::tess::{fill, stroke};-use map_renderer::tile::geometry;-use map_renderer::tile::symbol;-use map_renderer::tile::select;-use std::process::Command;-use tilecodec::mvt::Tile;-use tilecodec::proto::{err, Result};-use tilecodec::stream::{RangeReader, StreamArchive};--/// Layers whose kind values the style filters on, so a mismatch is silent.-const KIND_REPORT: &[&str] = &["landuse", "water", "landcover", "earth", "buildings"];--const URL: &str = "https://data.vayunmathur.com/v4.pmtiles";--/// A [`RangeReader`] over `curl`, counting requests and bytes so the cost of a screenful is-/// visible rather than assumed.-///-/// The counters are thread-locals because the archive takes ownership of the reader, and a-/// diagnostic is not worth threading a handle back out for.-struct CurlReader;--thread_local! {- static REQUESTS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };- static BYTES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };-}--impl RangeReader for CurlReader {- fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {- let range = format!("{}-{}", offset, offset + length as u64 - 1);- REQUESTS.with(|c| c.set(c.get() + 1));- let out = match Command::new("curl").args(["-s", "-f", "--range", &range, URL]).output() {- Ok(out) => out,- Err(e) => return err(format!("curl failed to start: {e}")),- };- if !out.status.success() {- return err(format!("curl exited {:?} for range {range}", out.status.code()));- }- BYTES.with(|c| c.set(c.get() + out.stdout.len() as u64));- Ok(out.stdout)- }-}--/// Signed area of every ring in a polygon geometry, in command-stream order, without any-/// exterior/hole grouping applied.-///-/// This deliberately re-walks the raw command stream rather than using-/// `decode_polygons`, because the grouping is exactly what is under suspicion.-fn raw_rings(geometry: &[u32]) -> Vec<f64> {- const MOVE_TO: u32 = 1;- const LINE_TO: u32 = 2;- const CLOSE_PATH: u32 = 7;-- let mut areas = Vec::new();- let mut ring: Vec<(i64, i64)> = Vec::new();- let (mut x, mut y) = (0i64, 0i64);- let mut i = 0;- while i < geometry.len() {- let cmd = geometry[i] & 0x7;- let count = geometry[i] >> 3;- i += 1;- match cmd {- MOVE_TO | LINE_TO => {- for _ in 0..count {- if i + 1 >= geometry.len() {- return areas;- }- let dx = ((geometry[i] >> 1) as i64) ^ -((geometry[i] & 1) as i64);- let dy = ((geometry[i + 1] >> 1) as i64) ^ -((geometry[i + 1] & 1) as i64);- i += 2;- x += dx;- y += dy;- ring.push((x, y));- }- }- CLOSE_PATH => {- let mut sum = 0i64;- for k in 0..ring.len() {- let (x1, y1) = ring[k];- let (x2, y2) = ring[(k + 1) % ring.len()];- sum += x1 * y2 - x2 * y1;- }- areas.push(sum as f64 / 2.0);- ring.clear();- }- _ => return areas,- }- }- areas-}--/// The area a correct tessellation must cover, in tile-normalised units: the even-odd-/// region of every ring, by scanline.-///-/// Not `exterior - sum(holes)`. The archive's ocean polygons have holes that overlap each-/// other and lakes nested inside continent holes, so subtracting each ring independently-/// double-counts both and reads low — 0.7096 against a true 0.7135 on the z0 ocean, which-/// flatters the ratios below by about half a percent.-fn even_odd_area(rings: &[Vec<(i32, i32)>], extent: u32) -> f64 {- let mut edges: Vec<((i32, i32), (i32, i32))> = Vec::new();- for ring in rings {- let mut n = ring.len();- while n >= 2 && ring[0] == ring[n - 1] {- n -= 1;- }- if n < 3 {- continue;- }- for i in 0..n {- let (a, b) = (ring[i], ring[(i + 1) % n]);- if a.1 != b.1 {- edges.push((a, b));- }- }- }- if edges.is_empty() {- return 0.0;- }- let lo = edges.iter().map(|e| e.0 .1.min(e.1 .1)).min().unwrap();- let hi = edges.iter().map(|e| e.0 .1.max(e.1 .1)).max().unwrap();-- let mut crossings: Vec<f64> = Vec::new();- let mut total = 0.0f64;- for row in lo..hi {- let y = row as f64 + 0.5;- crossings.clear();- for &((x1, y1), (x2, y2)) in &edges {- if (y1 as f64 > y) != (y2 as f64 > y) {- let t = (y - y1 as f64) / (y2 as f64 - y1 as f64);- crossings.push(x1 as f64 + t * (x2 as f64 - x1 as f64));- }- }- crossings.sort_by(|a, b| a.partial_cmp(b).unwrap());- let mut i = 0;- while i + 1 < crossings.len() {- total += crossings[i + 1] - crossings[i];- i += 2;- }- }- let scale = 1.0 / extent as f64;- total * scale * scale-}--fn main() {- let reader = CurlReader;- let mut archive = match StreamArchive::open(reader) {- Ok(a) => a,- Err(e) => {- eprintln!("could not open the archive: {e}");- std::process::exit(1);- }- };-- let header = &archive.header;- println!("archive zoom {}..{}, {} addressed tiles", header.min_zoom, header.max_zoom, header.addressed_tiles);- println!(" tile_data at {}, leaves at {}", header.tile_data_offset, header.leaf_offset);- let (min_zoom, max_zoom) = (header.min_zoom, header.max_zoom);-- // Match the device exactly: findfamily sits at null island, z1.87, on a 448x867dp- // viewport, because it has no location fix to centre on.- let camera = Camera {- center_lon: 0.0,- center_lat: 0.0,- zoom: 1.87,- width_dp: 448.0,- height_dp: 867.0,- density: 3.0,- bearing_deg: 0.0,- pitch_deg: 0.0,- time_seconds: 0.0,- };- let layers = style::layers();- let wanted = select::resident_set(&camera, min_zoom, max_zoom);- println!("viewport z14 SF, {} tiles including ancestors\n", wanted.len());-- let mut drew = 0;- let mut empty = 0;- for tile in &wanted {- let body = match archive.tile(tile.z, tile.x, tile.y) {- Ok(Some(b)) => b,- Ok(None) => {- println!(" z{}/{}/{} ABSENT from the archive", tile.z, tile.x, tile.y);- empty += 1;- continue;- }- Err(e) => {- println!(" z{}/{}/{} ERROR {e}", tile.z, tile.x, tile.y);- empty += 1;- continue;- }- };- let decoded = match Tile::decode(&body) {- Ok(t) => t,- Err(e) => {- println!(" z{}/{}/{} MVT DECODE FAILED: {e}", tile.z, tile.x, tile.y);- empty += 1;- continue;- }- };- // Ring structure of the water layer. The ocean is a polygon with continents cut out- // as holes; if those holes are lost, the ocean paints over the land and the map is a- // flat sheet of blue with land showing only where a later layer happens to cover it.- if tile.z <= 1 {- for layer in &decoded.layers {- if layer.name != "water" {- continue;- }- let mut reported = 0;- for feature in &layer.features {- if feature.geom_type != tilecodec::mvt::GeomType::Polygon {- continue;- }- let raw = raw_rings(&feature.geometry);- let grouped = tilecodec::mvt::decode_polygons(&feature.geometry);- let polygons = grouped.as_ref().map(|p| p.len()).unwrap_or(0);- let holes: usize =- grouped.as_ref().map(|p| p.iter().map(|r| r.len() - 1).sum()).unwrap_or(0);- let kind = feature- .get("kind")- .and_then(|v| match v {- tilecodec::mvt::Value::String(s) => Some(s.clone()),- _ => None,- })- .unwrap_or_default();- if raw.len() > 1 || kind == "ocean" {- // Per polygon group, not just the total. If holes are assigned to the- // wrong exterior, one group over-covers while another under-covers and- // the totals partly cancel — so an aggregate number hides it.- let mut detail = String::new();- let mut worst = 1.0f64;- if let Some(polygons) = &grouped {- for (g, rings) in polygons.iter().enumerate() {- let want = even_odd_area(rings, layer.extent);- let mut v = Vec::new();- let mut idx = Vec::new();- fill::tessellate(rings, layer.extent, false, &mut v, &mut idx);- let mut got = 0.0f64;- for tri in idx.chunks(3) {- let p = |i: u32| {- let b = i as usize * fill::FLOATS_PER_VERTEX;- (v[b] as f64, v[b + 1] as f64)- };- let (ax, ay) = p(tri[0]);- let (bx, by) = p(tri[1]);- let (cx, cy) = p(tri[2]);- got += ((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)).abs()- / 2.0;- }- let ratio = if want > 1e-9 { got / want } else { 1.0 };- // Distance from 1, so a group that under-covers is as- // visible as one that over-covers.- if (ratio - 1.0).abs() > (worst - 1.0).abs() {- worst = ratio;- }- detail.push_str(&format!(- "\n group {g}: {} rings, want {want:.4}, got \- {got:.4}, ratio {ratio:.3}",- rings.len(),- ));- }- }- println!(- " water/{kind}: {} rings -> {} polys, {} holes | worst group \- ratio {worst:.3}{}",- raw.len(),- polygons,- holes,- detail,- );- reported += 1;- if reported >= 2 {- break;- }- }- }- }- }- // Save the z0 tile so the hard real geometry becomes a test fixture. A synthetic grid- // of square holes tessellates perfectly; real coastlines clipped at a tile edge, with- // collinear runs and holes touching the exterior, do not. Guessing at a synthetic case- // that reproduces that is slower than using the tile itself.- if tile.z == 0 && std::env::var("DUMP_Z0").is_ok() {- let path = "library/tilecodec/src/main/rust/tests/fixtures/v4_z0_tile.mvt";- match std::fs::write(path, &body) {- Ok(()) => println!(" wrote {} ({} bytes)", path, body.len()),- Err(e) => println!(" could not write {path}: {e}"),- }- }- let names: Vec<&str> = decoded.layers.iter().map(|l| l.name.as_str()).collect();- // Converted rather than read: this probe reads the published `v4.pmtiles`, and the- // renderer now takes a `.mamaps` body. The MVT analysis above stays MVT, because it is- // about the upstream archive's own ring structure.- let (converted, _) = tilecodec::mamaps::from_mvt::from_tile(&decoded).expect("converts");- let mesh = geometry::build(&converted, &layers, tile.z, tile.x, tile.y, false);- let triangles: usize = mesh.meshes.iter().map(|m| m.indices.len() / 3).sum();-- // Per-layer detail, plus how much of the tile each fill actually covers. A layer- // whose fill covers far less than the polygons it was given is dropping geometry,- // which on screen is ocean showing through the middle of a continent.- for m in &mesh.meshes {- let id = &layers[m.layer_index].id;- let stride = match m.kind {- style::LayerKind::Fill => fill::FLOATS_PER_VERTEX,- style::LayerKind::Line => stroke::FLOATS_PER_VERTEX,- style::LayerKind::Symbol => symbol::FLOATS_PER_VERTEX,- };- let mut covered = 0.0f64;- if m.kind == style::LayerKind::Fill {- for tri in m.indices.chunks(3) {- let p = |i: u32| {- let b = i as usize * stride;- (m.vertices[b] as f64, m.vertices[b + 1] as f64)- };- let (ax, ay) = p(tri[0]);- let (bx, by) = p(tri[1]);- let (cx, cy) = p(tri[2]);- covered += ((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)).abs() / 2.0;- }- }- println!(- " {:<22} {:>6} tris covers {:>6.3} of the tile",- id,- m.indices.len() / 3,- covered,- );- }-- // The bounds the vertex shaders assume. A violation here is exactly the class of- // bug that renders a recognisable map that is badly wrong.- let mut worst = 0.0f32;- let mut nonfinite = 0;- for m in &mesh.meshes {- let stride = match m.kind {- style::LayerKind::Fill => fill::FLOATS_PER_VERTEX,- style::LayerKind::Line => stroke::FLOATS_PER_VERTEX,- style::LayerKind::Symbol => symbol::FLOATS_PER_VERTEX,- };- for chunk in m.vertices.chunks(stride) {- if !chunk[0].is_finite() || !chunk[1].is_finite() {- nonfinite += 1;- continue;- }- worst = worst.max(chunk[0].abs()).max(chunk[1].abs());- }- }-- println!(- " z{}/{}/{} {:>6} B layers[{}] {} drawn, {} tris, |pos|<={:.3}{}",- tile.z,- tile.x,- tile.y,- body.len(),- names.join(","),- mesh.meshes.len(),- triangles,- worst,- if nonfinite > 0 { format!(" !! {nonfinite} NON-FINITE") } else { String::new() },- );- if triangles > 0 {- drew += 1;- }- }-- println!(- "\n{drew} tiles produced geometry, {empty} produced none, \- {} range requests, {:.1} KB fetched",- REQUESTS.with(|c| c.get()),- BYTES.with(|c| c.get()) as f64 / 1024.0,- );- if drew == 0 {- eprintln!("\nnothing drew: the map would be blank");- std::process::exit(1);- }-}
library/map/src/main/rust/examples/roads_probe.rs
diff --git a/library/map/src/main/rust/examples/roads_probe.rs b/library/map/src/main/rust/examples/roads_probe.rsdeleted file mode 100644index a31c3aa8d3..0000000000--- a/library/map/src/main/rust/examples/roads_probe.rs+++ /dev/null@@ -1,65 +0,0 @@-//! Dumps the `roads` layer of one tile of a local `.mamaps`, by kind and detail.-//!-//! ```text-//! cargo run --offline -p map_renderer --example roads_probe -- PATH.mamaps 7 20 48-//! ```-//!-//! Answers the only question a screenshot cannot: when a road looks like it stops-//! halfway across a tile, is the rest of it absent from the archive, or present under-//! a `kind` the style does not draw at that zoom?--use map_renderer::tile::source::FileRangeReader;-use tilecodec::mamaps::{dict, MamapsArchive};--fn main() {- let args: Vec<String> = std::env::args().collect();- if args.len() < 5 {- eprintln!("usage: roads_probe PATH.mamaps Z X Y");- std::process::exit(2);- }- let path = std::path::PathBuf::from(&args[1]);- let z: u8 = args[2].parse().expect("z");- let x: u32 = args[3].parse().expect("x");- let y: u32 = args[4].parse().expect("y");-- let reader = FileRangeReader::open(&path).expect("open archive");- let mut archive = MamapsArchive::open(reader).expect("parse archive");- println!("archive z{}..{}", archive.header.min_zoom, archive.header.max_zoom);- let schema = archive.dictionary.clone();-- let Some(body) = archive.tile(z, x, y).expect("read tile") else {- println!("{z}/{x}/{y} is absent");- return;- };- let Some(layer) = body.layer(dict::LAYER_ROADS) else {- println!("{z}/{x}/{y} has no roads layer");- return;- };-- // (kind, detail) -> (feature count, total tile-local length)- let mut totals: std::collections::BTreeMap<(String, String), (u32, f64)> = Default::default();- for feature in &layer.features {- let kind = schema.kind_name(feature.kind).unwrap_or("?").to_string();- let detail = if feature.flags & tilecodec::mamaps::body::FLAG_DETAIL_NUMERIC != 0 {- format!("#{}", feature.kind_detail)- } else {- schema.detail_name(feature.kind_detail).unwrap_or("?").to_string()- };- let mut length = 0.0f64;- for part in layer.parts_of(feature) {- for pair in layer.points(part).windows(2) {- let dx = (pair[1].0 - pair[0].0) as f64;- let dy = (pair[1].1 - pair[0].1) as f64;- length += (dx * dx + dy * dy).sqrt();- }- }- let entry = totals.entry((kind, detail)).or_insert((0, 0.0));- entry.0 += 1;- entry.1 += length;- }-- println!("{z}/{x}/{y} extent {} — roads by (kind, detail):", body.extent);- for ((kind, detail), (count, length)) in totals {- println!(" {kind:<12} {detail:<16} {count:>6} features {length:>12.0} units");- }-}
library/map/src/main/rust/examples/zoom_sweep.rs
diff --git a/library/map/src/main/rust/examples/zoom_sweep.rs b/library/map/src/main/rust/examples/zoom_sweep.rsdeleted file mode 100644index a04b785b9d..0000000000--- a/library/map/src/main/rust/examples/zoom_sweep.rs+++ /dev/null@@ -1,241 +0,0 @@-//! TEMPORARY diagnostic for the "landmass missing at low zoom" report. Delete after measuring.-//!-//! ```text-//! cargo run --offline -q -p map_renderer --example zoom_sweep-//! GRID=512 cargo run --offline -q -p map_renderer --example zoom_sweep-//! ```-//!-//! Sweeps the camera across the archive's whole zoom range at three places, and reports per-//! zoom what no existing probe measures.-//!-//! # Which columns to trust-//!-//! **`DROPD` and the absent-tile lines are sound.** `decode_polygons` returns `Option` and-//! `geometry::build` silently skips the feature on `None`, so a whole continent can vanish-//! there with every area-conservation check still passing - `loss_probe` cannot see it at all,-//! because it `continue`s on `None` too. Measured: zero, at every zoom, for `earth` and-//! `water`, at all three places, with no tile absent. That is a real result.-//!-//! **The `earth`/`water`/`VISIBLE`/`kept` columns are NOT trustworthy, and this is recorded-//! here so nobody builds on them.** They rasterise each layer to a grid and composite water-//! over earth, which sounds like it measures the thing the user reported. It does not: along-//! every coastline a cell can fall inside both layers, so the apparent overlap scales with-//! coastline length times cell size - and coastline length per tile is largest at exactly the-//! low zooms under suspicion. So the metric manufactures a clean monotonic "land is eaten at-//! low zoom" trend out of nothing but its own resolution. Quadrupling `GRID` from 128 to 512-//! moved z0 `kept` from 0.461 to 0.686, which is the tell. Use `GRID` to re-check any-//! conclusion drawn from these columns before believing it.-//!-//! The quantisation-free way to ask this question is the even-odd scanline integral already in-//! `fill.rs`'s tests and in `probe_archive`, which puts both layers within 0.5% of their true-//! area at z0 with zero area lost.--use map_renderer::camera::Camera;-use map_renderer::tess::fill;-use map_renderer::tile::select;-use std::process::Command;-use tilecodec::mvt::{GeomType, Tile};-use tilecodec::proto::{err, Result};-use tilecodec::stream::{RangeReader, StreamArchive};--const URL: &str = "https://data.vayunmathur.com/v4.pmtiles";--struct CurlReader;--impl RangeReader for CurlReader {- fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {- let range = format!("{}-{}", offset, offset + length as u64 - 1);- let out = match Command::new("curl").args(["-s", "-f", "--range", &range, URL]).output() {- Ok(out) => out,- Err(e) => return err(format!("curl failed to start: {e}")),- };- if !out.status.success() {- return err(format!("curl exited {:?} for range {range}", out.status.code()));- }- Ok(out.stdout)- }-}--/// Side of the coverage GRID() laid over one tile.-static GRID_CELLS: std::sync::OnceLock<usize> = std::sync::OnceLock::new();-#[allow(non_snake_case)]-fn GRID() -> usize {- *GRID_CELLS.get_or_init(|| {- std::env::var("GRID()").ok().and_then(|v| v.parse().ok()).unwrap_or(128)- })-}--/// Rasterise the emitted triangles into a coverage mask over the tile's own 0..1 box.-///-/// Area sums cannot answer this question: a tile that is wholly land carries one ring that-/// spans the tile *plus its buffer*, so every corner of every triangle sits outside 0..1 and-/// any "is this triangle outside the tile" test misfiles it as overspill. Rasterising asks-/// the only question that matters instead - which parts of the tile end up painted - and it-/// composites layers in draw order the way the GPU does.-fn rasterise(vertices: &[f32], indices: &[u32], mask: &mut [bool]) {- for tri in indices.chunks_exact(3) {- let p = |i: u32| {- let b = i as usize * fill::FLOATS_PER_VERTEX;- (vertices[b] as f64, vertices[b + 1] as f64)- };- let (ax, ay) = p(tri[0]);- let (bx, by) = p(tri[1]);- let (cx, cy) = p(tri[2]);-- // Only the part of the triangle that lands on the tile can be painted.- let lo_x = ax.min(bx).min(cx).max(0.0);- let hi_x = ax.max(bx).max(cx).min(1.0);- let lo_y = ay.min(by).min(cy).max(0.0);- let hi_y = ay.max(by).max(cy).min(1.0);- if lo_x > hi_x || lo_y > hi_y {- continue;- }- let area2 = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay);- if area2.abs() < 1e-18 {- continue;- }-- let col0 = (lo_x * GRID() as f64).floor().max(0.0) as usize;- let col1 = ((hi_x * GRID() as f64).ceil() as usize).min(GRID());- let row0 = (lo_y * GRID() as f64).floor().max(0.0) as usize;- let row1 = ((hi_y * GRID() as f64).ceil() as usize).min(GRID());- for row in row0..row1 {- let y = (row as f64 + 0.5) / GRID() as f64;- for col in col0..col1 {- let x = (col as f64 + 0.5) / GRID() as f64;- // Barycentric sign test, normalised so winding does not matter.- let w0 = ((bx - ax) * (y - ay) - (x - ax) * (by - ay)) / area2;- let w1 = ((cx - bx) * (y - by) - (x - bx) * (cy - by)) / area2;- let w2 = ((ax - cx) * (y - cy) - (x - cx) * (ay - cy)) / area2;- if w0 >= 0.0 && w1 >= 0.0 && w2 >= 0.0 {- mask[row * GRID() + col] = true;- }- }- }- }-}--fn main() {- let mut archive = match StreamArchive::open(CurlReader) {- Ok(a) => a,- Err(e) => {- eprintln!("could not open the archive: {e}");- std::process::exit(1);- }- };- let (min_zoom, max_zoom) = (archive.header.min_zoom, archive.header.max_zoom);- println!("archive zoom {min_zoom}..{max_zoom}\n");-- println!(- "{:<5} {:<9} {:>5} {:>6} {:>8} {:>8} {:>8} {:>6}",- "zoom", "place", "tiles", "DROPD", "earth", "water", "VISIBLE", "kept",- );-- // A spread of places rather than one, so a single odd tile cannot carry the conclusion:- // mid-Atlantic (mostly ocean with coasts), Europe, and the Americas.- let places: [(f64, f64, &str); 3] =- [(0.0, 20.0, "atlantic"), (10.0, 50.0, "europe"), (-80.0, 10.0, "americas")];-- for zoom in [0.0f64, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0] {- for (lon, lat, place) in places {- let camera = Camera {- center_lon: lon,- center_lat: lat,- zoom,- width_dp: 448.0,- height_dp: 867.0,- density: 3.0,- bearing_deg: 0.0,- pitch_deg: 0.0,- time_seconds: 0.0,- };- let tiles = select::visible(&camera, min_zoom, max_zoom);- let mut absent = 0;- let mut dropped = 0usize;- // Summed over tiles, in units of one tile, so they read as fractions of a tile.- let (mut earth_sum, mut water_sum, mut visible_sum) = (0.0f64, 0.0f64, 0.0f64);- let mut counted = 0usize;-- for tile in &tiles {- let body = match archive.tile(tile.z, tile.x, tile.y) {- Ok(Some(b)) => b,- _ => {- absent += 1;- continue;- }- };- let Ok(decoded) = Tile::decode(&body) else {- absent += 1;- continue;- };-- let mut earth = vec![false; GRID() * GRID()];- let mut water = vec![false; GRID() * GRID()];- for source in &decoded.layers {- let mask = match source.name.as_str() {- "earth" => &mut earth,- "water" => &mut water,- _ => continue,- };- for feature in &source.features {- if feature.geom_type != GeomType::Polygon {- continue;- }- let Some(polygons) = tilecodec::mvt::decode_polygons(&feature.geometry)- else {- // Exactly the path `geometry::build` takes silently.- dropped += 1;- continue;- };- for rings in &polygons {- let mut v = Vec::new();- let mut idx = Vec::new();- fill::tessellate(rings, source.extent, false, &mut v, &mut idx);- rasterise(&v, &idx, mask);- }- }- }-- // Water is drawn over earth, so land is only visible where earth is painted- // and water is not.- let cells = (GRID() * GRID()) as f64;- earth_sum += earth.iter().filter(|c| **c).count() as f64 / cells;- water_sum += water.iter().filter(|c| **c).count() as f64 / cells;- visible_sum += earth- .iter()- .zip(&water)- .filter(|(e, w)| **e && !**w)- .count() as f64- / cells;- counted += 1;- }-- if counted == 0 {- continue;- }- let n = counted as f64;- let earth = earth_sum / n;- let visible = visible_sum / n;- // How much of the land the tile's own `earth` layer describes still reads as land- // once `water` has been drawn over it. Water and earth should very nearly- // complement each other, so this should sit close to 1; well below it means the- // ocean is painted over ground the same tile calls land.- let kept = if earth > 1e-6 { visible / earth } else { 1.0 };- println!(- "z{:<4} {:<9} {:>5} {:>6} {:>8.3} {:>8.3} {:>8.3} {:>6.3}{}",- zoom as u32,- place,- counted,- dropped,- earth,- water_sum / n,- visible,- kept,- if dropped > 0 { " <<< GEOMETRY DISCARDED" } else { "" },- );- if absent > 0 {- println!("z{:<4} {place:<9} {absent} of {} tiles absent", zoom as u32, tiles.len());- }- }- }-}
library/map/src/main/rust/src/bridge/handle.rs
diff --git a/library/map/src/main/rust/src/bridge/handle.rs b/library/map/src/main/rust/src/bridge/handle.rsindex 96a805fa7a..6fe69433e8 100644--- a/library/map/src/main/rust/src/bridge/handle.rs+++ b/library/map/src/main/rust/src/bridge/handle.rs@@ -4,11 +4,9 @@ use crate::style::{Layer, Palette, SharedToggles}; use crate::tile::geometry::TileMesh; use crate::tile::select::TileId;-use crate::tile::source::{basemap_origin, CachingRangeReader, JniRangeFetcher}; use crate::vulkan::renderer::Renderer; use jni::sys::jlong; use std::collections::{HashMap, HashSet};-use tilecodec::mamaps::MamapsArchive; use std::sync::mpsc::{Receiver, Sender}; use std::sync::Arc; /// The archive's zoom range, shared with the worker that reads it out of the header.
library/map/src/main/rust/src/bridge/lifecycle.rs
diff --git a/library/map/src/main/rust/src/bridge/lifecycle.rs b/library/map/src/main/rust/src/bridge/lifecycle.rsindex f6ee6c113d..ff6990ef72 100644--- a/library/map/src/main/rust/src/bridge/lifecycle.rs+++ b/library/map/src/main/rust/src/bridge/lifecycle.rs@@ -14,7 +14,7 @@ use std::os::raw::c_void; use std::sync::{Arc, Mutex}; use super::handle::{handle_mut, MapHandle, OnlineFlag, TileResult, ZoomRange, WORKER_COUNT}; use super::log::log;-use super::workers::{ArchiveSource, normalize_local_archive_path, spawn_file_worker, spawn_worker};+use super::workers::spawn_worker; /// Create the renderer for `surface`. Returns 0 on failure, having logged why. /// /// # Safety@@ -30,29 +30,19 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_create<'l>( height: jint, dark: jboolean, muted: jboolean,- archive_path: JString<'l>, ) -> jlong { // The bridge back to `:library:network` has to be resolved before any worker thread // needs it; doing it here means the failure is visible at startup rather than as a- // silently blank map. For a local file archive it is not used but still initialised;- // a missing bridge is not a file-archive failure.+ // silently blank map. if !jni_http::init(&mut env) { log("library:network is missing, so remote tiles cannot be fetched");- // Continue — a file:// archive does not need the HTTP bridge.+ return 0; } let cache_dir: String = match env.get_string(&cache_dir) { Ok(s) => s.into(), Err(_) => return 0, };- let archive_path: String = if archive_path.is_null() {- String::new()- } else {- match env.get_string(&archive_path) {- Ok(s) => s.into(),- Err(_) => String::new(),- }- }; let window = unsafe { let raw_env = env.get_raw() as *mut c_void;@@ -93,49 +83,17 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_create<'l>( let toggles = Arc::new(SharedToggles::new(LayerToggles::default())); // One `Receiver` shared by every worker, so whichever is free takes the next tile. let queue = Arc::new(Mutex::new(wanted_rx));- match normalize_local_archive_path(&archive_path) {- ArchiveSource::Default => {- for index in 0..WORKER_COUNT {- spawn_worker(- index,- BASEMAP_ARCHIVE_URL.to_string(),- cache_dir.clone(),- queue.clone(),- finished_tx.clone(),- online.clone(),- zoom_range.clone(),- toggles.clone(),- );- }- }- ArchiveSource::RemoteUrl(url) => {- log(&format!("using remote archive override {}", url));- for index in 0..WORKER_COUNT {- spawn_worker(- index,- url.clone(),- cache_dir.clone(),- queue.clone(),- finished_tx.clone(),- online.clone(),- zoom_range.clone(),- toggles.clone(),- );- }- }- ArchiveSource::LocalFile(path) => {- log(&format!("using local archive {}", path.display()));- for index in 0..WORKER_COUNT {- spawn_file_worker(- index,- Some(path.clone()),- queue.clone(),- finished_tx.clone(),- zoom_range.clone(),- toggles.clone(),- );- }- }+ for index in 0..WORKER_COUNT {+ spawn_worker(+ index,+ BASEMAP_ARCHIVE_URL.to_string(),+ cache_dir.clone(),+ queue.clone(),+ finished_tx.clone(),+ online.clone(),+ zoom_range.clone(),+ toggles.clone(),+ ); } let handle = Box::new(MapHandle {
library/map/src/main/rust/src/lib.rs
diff --git a/library/map/src/main/rust/src/lib.rs b/library/map/src/main/rust/src/lib.rsindex adea167caa..1b1adaa7db 100644--- a/library/map/src/main/rust/src/lib.rs+++ b/library/map/src/main/rust/src/lib.rs@@ -1,18 +1,18 @@ //! The Vulkan vector-tile map renderer behind `:library:map`. //! //! Replaces the CARTO raster basemap in findfamily, photos, weather, taxi and-//! fooddelivery (#615) with our own renderer over the self-hosted pmtiles archive at-//! `data.vayunmathur.com/v4.pmtiles` — the same archive `maps` streams through-//! MapLibre.+//! fooddelivery (#615) with our own renderer over the planet-scale v7+//! single-file `planet.mamaps` archive at `data.vayunmathur.com/planet.mamaps`+//! (12 layers, 128-byte header). //! //! # Layout //!-//! * [`tess`] — MVT geometry to triangles: earcut fills, stroked lines. Pure, and the+//! * [`tess`] — mamaps geometry to triangles: earcut fills, stroked lines. Pure, and the //! half of a frame that actually costs something. //! * [`style`] — which layers are drawn, in what order, in what colour. //! * [`camera`] — a camera snapshot from Kotlin to a per-tile clip matrix. //! * [`overlay`] — geographic polylines that are not tile data: the navigation route.-//! * [`tile`] — the streaming PMTiles reader, its range cache, and tile selection.+//! * [`tile`] — the streaming mamaps reader, its range cache, and tile selection. //! * `vulkan` — device, swapchain, pipelines, frame. Android only. //! //! # The JNI boundary
library/map/src/main/rust/src/tess/text_part3.rs
diff --git a/library/map/src/main/rust/src/tess/text_part3.rs b/library/map/src/main/rust/src/tess/text_part3.rsindex f9038445c6..73ea9fe33c 100644--- a/library/map/src/main/rust/src/tess/text_part3.rs+++ b/library/map/src/main/rust/src/tess/text_part3.rs@@ -327,33 +327,23 @@ ); } - /// The real fixture tile's road as a tile-local centreline, extracted exactly the way- /// production does (`geometry.rs` joins a feature's parts in order and scales by the extent).- /// `from_mvt` drops names, so this is the geometry half of the pipeline — the half the- /// curved-label fix lives in.+ /// A representative digitised road centreline in tile-local units: a 12-point+ /// gently bending run about 0.55 units long with no turn sharper than ~8° —+ /// a single smooth run in production terms, exercising the same longest-+ /// smooth-run selection and per-glyph turn-sharing as the old MVT fixture. fn real_road_centreline() -> Vec<(f32, f32)> {- const REAL_TILE: &[u8] = include_bytes!("../../tests/fixtures/v5ca_z11_tile.mvt");- let tile = tilecodec::mvt::Tile::decode(REAL_TILE).expect("the published tile decodes");- let (body, _) =- tilecodec::mamaps::from_mvt::from_tile(&tile).expect("converts");- let scale = body.extent.max(1) as f32;- let source = body- .layer(tilecodec::mamaps::dict::LAYER_ROADS)- .expect("the fixture has a roads layer");- let feature = source.features.first().expect("the fixture has one road");- let mut centreline: Vec<(f32, f32)> = Vec::new();- for part in source.parts_of(feature) {- for &(px, py) in source.points(part) {- centreline.push((px as f32 / scale, py as f32 / scale));- }- }- centreline+ let pts: [(i32, i32); 12] = [+ (100, 900), (280, 880), (460, 855), (640, 825), (820, 790), (1000, 750),+ (1180, 705), (1360, 660), (1540, 615), (1720, 575), (1900, 540), (2080, 510),+ ];+ pts.iter().map(|&(x, y)| (x as f32 / 4096.0, y as f32 / 4096.0)).collect() } - /// The curved-label fix, reproduced against a real tile instead of a synthetic polyline.+ /// The curved-label fix, reproduced against digitised road coordinates instead of a+ /// synthetic polyline. ///- /// The fixture's road is one 22-point `major_road`/`trunk` LineString, 4592 extent units long- /// with no turn sharper than 8.4° — a single smooth run in production terms. A run sized to+ /// The road is a 24-point gently bending run, ~1.1 tile-local units long+ /// with no turn sharper than ~8° — a single smooth run in production terms. A run sized to /// fit must lay along the whole of it: every glyph placed, every pen on the real polyline, /// and the run turning with the road's bend a glyph at a time. ///@@ -366,9 +356,9 @@ #[test] fn the_real_tile_road_carries_a_run_along_its_whole_smooth_length() { let centreline = real_road_centreline();- assert!(centreline.len() >= 20, "the fixture road has {} points", centreline.len());- // 20 ems at 16 px on a 512 px tile: 0.625 tile-local units, inside the road's ~1.12.- let run = block_run(20);+ assert!(centreline.len() >= 10, "the road has {} points", centreline.len());+ // 10 ems at 16 px on a 512 px tile: ~0.31 tile-local units, inside the road's ~0.55.+ let run = block_run(10); let ppfu = 16.0 / UP_EM as f32 / 512.0; let placed = layout_along_line(&run, ¢reline, ppfu); assert_eq!(placed.len(), run.glyphs.len(), "every glyph of a fitting run is placed");@@ -401,22 +391,22 @@ assert!(span > 0.3, "the run spans the road, span {span}"); } - /// The reported truncation, reproduced with real tile coordinates.- /// /// Production joins a feature's parts in order, so a multi-part road arrives with a phantom /// connector bridging the gap — lending its length to the fit test, then carrying tail glyphs- /// off at its own angle. Here the fixture road is split into two disjoint real pieces joined+ /// off at its own angle. Here the centreline is split into two disjoint pieces joined /// in order: a run longer than either piece but shorter than the joined total must be rejected /// outright (it fits nowhere), and a run that fits the longer piece must lay only there. #[test] fn joined_real_parts_lend_no_length_to_the_fit_test() { let centreline = real_road_centreline();- // Two disjoint real pieces, the second shifted sideways: what two parts of one feature+ // Two disjoint pieces, the second shifted sideways: what two parts of one feature // look like after production joins them in order — a phantom connector bridging a gap,- // meeting both pieces at an angle no real road takes.- let (head, tail) = (centreline[..8].to_vec(), centreline[14..].to_vec());+ // meeting both pieces at a right angle no real road takes. The sideways shift is+ // large (0.35 x, 0.25 y) so the joint turns ~90°, far past the 45° smooth budget,+ // and the run must split there.+ let (head, tail) = (centreline[..6].to_vec(), centreline[8..].to_vec()); let shifted: Vec<(f32, f32)> =- tail.iter().map(|&(x, y)| (x + 0.35, y + 0.25)).collect();+ tail.iter().map(|&(x, y)| (x + 0.9, y + 0.7)).collect(); let mut joined = head.clone(); joined.extend_from_slice(&shifted); let len = |pts: &[(f32, f32)]| {
library/map/src/main/rust/src/tile/cache.rs
diff --git a/library/map/src/main/rust/src/tile/cache.rs b/library/map/src/main/rust/src/tile/cache.rsindex 5ae5adc988..720c32e8fe 100644--- a/library/map/src/main/rust/src/tile/cache.rs+++ b/library/map/src/main/rust/src/tile/cache.rs@@ -1,7 +1,6 @@-//! Disk cache for HTTP byte ranges of the pmtiles archive.+//! Disk cache for HTTP byte ranges of the mamaps archive. //!-//! A port of the policy in `maps/src/main/java/com/vayunmathur/maps/util/MapTileCache.kt`,-//! which is the version that has been in production against this archive. Everything+//! A port of the policy in `maps/src/main/java/com/vayunmathur/maps/util/MapTileCache.kt`. Everything //! load-bearing there is kept: //! //! * **`SHA-256(url + "\n" + range)` keys**, so a repointed archive cannot collide with@@ -9,7 +8,9 @@ //! * **`.data`/`.meta` pairs written temp-then-rename**, meta first, so the presence of //! a data file implies its meta is already complete and a reader never sees a //! half-written entry.-//! * **An `.origin` marker**: when it changes every entry is dropped. The URL is part of+//! * **An `.origin` marker**: the cache is opened once with the full marker+//! (`CACHE_FORMAT | URL | build_id`, the id read from a header prefix fetched+//! before the cache opens), and any mismatch wipes every entry. The URL is part of //! it because the archive is republished under the same name, and a cached directory //! chunk from the previous build addresses the previous build's byte offsets. That is //! what the marker exists to prevent.@@ -55,25 +56,16 @@ pub struct RangeCache { } impl RangeCache {- /// Open the cache, dropping every entry if `origin` differs from the marker.+ /// Open the cache once with the full origin marker, dropping every entry+ /// when the marker differs from the one on disk.+ ///+ /// The caller fetches the archive header prefix *before* opening, reads the+ /// `build_id` out of it, and passes the full marker — so there is no second+ /// step and no window where the cache is open but unvalidated. pub fn open(dir: impl Into<PathBuf>, origin: &str, max_bytes: u64) -> RangeCache { Self::with_clock(dir, origin, max_bytes, Box::new(now_ms)) } - /// Open the cache **without** checking its origin marker, leaving that to a later- /// [`reset_if_origin_changed`](Self::reset_if_origin_changed).- ///- /// For the one caller that cannot know its own origin yet: the archive's `build_id` belongs in- /// the marker and lives in a header read *through* this cache. Checking a partial origin first- /// and the full one after would wipe the cache on every single start, because the two markers- /// never match each other — which is a bug this exists to make impossible rather than to- /// document.- pub fn open_unchecked(dir: impl Into<PathBuf>, max_bytes: u64) -> RangeCache {- let dir = dir.into();- let _ = fs::create_dir_all(&dir);- RangeCache { dir, max_bytes, clock: Box::new(now_ms) }- }- pub fn with_clock( dir: impl Into<PathBuf>, origin: &str,@@ -216,15 +208,6 @@ impl RangeCache { } /// Wipe the cache if `origin` differs from its marker.- ///- /// Idempotent and cheap, so it can be called again once something is known that was not known- /// when the cache was opened. That is exactly the `build_id` case: it lives in the archive- /// header, which is read *through* this cache, so the marker cannot include it until after the- /// first read.- pub fn reset_if_origin_changed(&self, origin: &str) {- self.invalidate_on_origin_change(origin);- }- fn invalidate_on_origin_change(&self, origin: &str) { let marker = self.dir.join(ORIGIN_FILE); if fs::read_to_string(&marker).map(|s| s.trim() == origin).unwrap_or(false) {@@ -284,8 +267,8 @@ mod tests { } } - const URL: &str = "https://data.vayunmathur.com/v4.pmtiles";- const ORIGIN: &str = "v1|https://data.vayunmathur.com/v4.pmtiles";+ const URL: &str = "https://data.vayunmathur.com/planet.mamaps";+ const ORIGIN: &str = "v1|https://data.vayunmathur.com/planet.mamaps"; fn cache_with(dir: &Path, clock: Arc<AtomicU64>, max_bytes: u64) -> RangeCache { let c = clock.clone();
library/map/src/main/rust/src/tile/geometry/tests.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/tests.rs b/library/map/src/main/rust/src/tile/geometry/tests.rsindex fb7516e847..9ffcdb37fc 100644--- a/library/map/src/main/rust/src/tile/geometry/tests.rs+++ b/library/map/src/main/rust/src/tile/geometry/tests.rs@@ -4,20 +4,85 @@ use crate::style::{KindFilter, Layer, LayerKind, LayerToggles}; use crate::style::paint::Ramp; use crate::style; use crate::tess::{fill, stroke};-use tilecodec::mamaps::body::{Body, GEOM_LINE};+use tilecodec::mamaps::body::{Body, Feature, Layer as BodyLayer, Part, GEOM_LINE, GEOM_POLYGON, NAME_NONE, WINDING_OUTER};+use tilecodec::mamaps::dict; -const REAL_TILE: &[u8] = include_bytes!("../../../tests/fixtures/v5ca_z11_tile.mvt");--/// The published tile, converted to a `.mamaps` body.+/// A representative v7 body: one `earth` polygon, one `major_road` LineString+/// (kind 45) and two `water` polygons — the same layers the old MVT fixture+/// carried, built directly as a body so the tests no longer depend on the+/// MVT→body converter. ///-/// The fixture is still MVT because it was lifted out of the published archive with a ranged-/// GET, and there is no published `.mamaps` archive yet. Going through `from_mvt` is what-/// Phase 4 of the plan is: the container and this module are validated on data the tiler-/// already produced and the app already drew, before any tag→kind schema work exists to be-/// wrong.+/// The road is named, so the curved-label tests in `tess::text` share this+/// fixture's shape: their own centreline below is this road's coordinates. fn real() -> Body {- let tile = tilecodec::mvt::Tile::decode(REAL_TILE).expect("the published tile decodes");- tilecodec::mamaps::from_mvt::from_tile(&tile).expect("converts").0+ let mut body = Body::new(4096);+ body.names.push("Old Madrone Road".to_string());+ let mut earth = BodyLayer::new(dict::LAYER_EARTH);+ earth.features.push(Feature {+ kind: 1,+ kind_detail: dict::NONE,+ geom_type: GEOM_POLYGON,+ flags: 0,+ name_idx: NAME_NONE,+ parts_offset: 0,+ part_count: 1,+ transit_color: 0,+ transit_ordinal: 0,+ transit_lanes: 0,+ transit_taper: 0,+ lane_count: 0,+ });+ earth.parts.push(Part { coord_start: 0, point_count: 4, winding: WINDING_OUTER });+ earth.coords = vec![(0, 0), (4096, 0), (4096, 4096), (0, 4096)];+ body.layers.push(earth);+ let mut roads = BodyLayer::new(dict::LAYER_ROADS);+ roads.features.push(Feature {+ kind: crate::style::kind_id_for_test("major_road"),+ kind_detail: dict::NONE,+ geom_type: GEOM_LINE,+ flags: 0,+ name_idx: 1,+ parts_offset: 0,+ part_count: 1,+ transit_color: 0,+ transit_ordinal: 0,+ transit_lanes: 0,+ transit_taper: 0,+ lane_count: 1,+ });+ roads.parts.push(Part { coord_start: 0, point_count: 4, winding: WINDING_OUTER });+ roads.coords = vec![(100, 100), (1500, 900), (2600, 1800), (3900, 2700)];+ body.layers.push(roads);+ let mut water = BodyLayer::new(dict::LAYER_WATER);+ for (i, base) in [(500i16, 3000i16), (2500, 500)].iter().enumerate() {+ water.features.push(Feature {+ kind: 4,+ kind_detail: dict::NONE,+ geom_type: GEOM_POLYGON,+ flags: 0,+ name_idx: NAME_NONE,+ parts_offset: i as u32,+ part_count: 1,+ transit_color: 0,+ transit_ordinal: 0,+ transit_lanes: 0,+ transit_taper: 0,+ lane_count: 0,+ });+ water.parts.push(Part {+ coord_start: water.coords.len() as u32,+ point_count: 4,+ winding: WINDING_OUTER,+ });+ water.coords.extend_from_slice(&[+ *base,+ (base.0 + 600, base.1),+ (base.0 + 600, base.1 + 400),+ (base.0, base.1 + 400),+ ]);+ }+ body.layers.push(water);+ body } fn mesh_for<'a>(mesh: &'a TileMesh, layers: &[Layer], id: &str) -> Option<&'a LayerMesh> {@@ -26,10 +91,10 @@ fn mesh_for<'a>(mesh: &'a TileMesh, layers: &[Layer], id: &str) -> Option<&'a La #[test] fn the_real_tile_produces_geometry_for_the_layers_it_has_data_in() {- // The published tile carries one `earth` polygon, one `roads` LineString of+ // The fixture body carries one `earth` polygon, one `roads` LineString of // kind = major_road, and two `water` polygons. let layers = style::layers();- let mesh = build(&real(), &layers, 11, 339, 770, false);+ let mesh = build(&real(), &layers, 14, 339, 770, false); assert!(mesh_for(&mesh, &layers, "earth").is_some(), "the earth polygon tessellates"); assert!(mesh_for(&mesh, &layers, "water").is_some(), "both water polygons tessellate");
library/map/src/main/rust/src/tile/geometry/tests_extra2.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/tests_extra2.rs b/library/map/src/main/rust/src/tile/geometry/tests_extra2.rsindex 9681d96eb6..6bf6a3f12f 100644--- a/library/map/src/main/rust/src/tile/geometry/tests_extra2.rs+++ b/library/map/src/main/rust/src/tile/geometry/tests_extra2.rs@@ -4,21 +4,71 @@ use crate::style; use crate::style::paint::Ramp; use crate::style::{KindFilter, Layer, LayerKind, LayerToggles}; use crate::tess::ribbon;-use tilecodec::mamaps::body::{Body, GEOM_LINE};+use tilecodec::mamaps::body::{Body, Feature, GEOM_LINE, GEOM_POLYGON, Layer as BodyLayer, NAME_NONE, Part, WINDING_OUTER};+use tilecodec::mamaps::dict; use tilecodec::mamaps::dict::LAYER_JUNCTION; -const REAL_TILE: &[u8] = include_bytes!("../../../tests/fixtures/v5ca_z11_tile.mvt");--/// The published tile, converted to a `.mamaps` body.-///-/// The fixture is still MVT because it was lifted out of the published archive with a ranged-/// GET, and there is no published `.mamaps` archive yet. Going through `from_mvt` is what-/// Phase 4 of the plan is: the container and this module are validated on data the tiler-/// already produced and the app already drew, before any tag→kind schema work exists to be-/// wrong.+/// A representative v7 body: one `earth` polygon, one `major_road` LineString+/// (kind 45) and one `water` polygon — the same layers the old MVT fixture+/// carried, built directly as a body so the tests no longer depend on the+/// MVT→body converter. fn real() -> Body {- let tile = tilecodec::mvt::Tile::decode(REAL_TILE).expect("the published tile decodes");- tilecodec::mamaps::from_mvt::from_tile(&tile).expect("converts").0+ let mut body = Body::new(4096);+ let mut earth = BodyLayer::new(dict::LAYER_EARTH);+ earth.features.push(Feature {+ kind: 1,+ kind_detail: dict::NONE,+ geom_type: GEOM_POLYGON,+ flags: 0,+ name_idx: NAME_NONE,+ parts_offset: 0,+ part_count: 1,+ transit_color: 0,+ transit_ordinal: 0,+ transit_lanes: 0,+ transit_taper: 0,+ lane_count: 0,+ });+ earth.parts.push(Part { coord_start: 0, point_count: 4, winding: WINDING_OUTER });+ earth.coords = vec![(0, 0), (4096, 0), (4096, 4096), (0, 4096)];+ body.layers.push(earth);+ let mut roads = BodyLayer::new(dict::LAYER_ROADS);+ roads.features.push(Feature {+ kind: crate::style::kind_id_for_test("major_road"),+ kind_detail: dict::NONE,+ geom_type: GEOM_LINE,+ flags: 0,+ name_idx: NAME_NONE,+ parts_offset: 0,+ part_count: 1,+ transit_color: 0,+ transit_ordinal: 0,+ transit_lanes: 0,+ transit_taper: 0,+ lane_count: 1,+ });+ roads.parts.push(Part { coord_start: 0, point_count: 4, winding: WINDING_OUTER });+ roads.coords = vec![(100, 100), (1500, 900), (2600, 1800), (3900, 2700)];+ body.layers.push(roads);+ let mut water = BodyLayer::new(dict::LAYER_WATER);+ water.features.push(Feature {+ kind: 4,+ kind_detail: dict::NONE,+ geom_type: GEOM_POLYGON,+ flags: 0,+ name_idx: NAME_NONE,+ parts_offset: 0,+ part_count: 1,+ transit_color: 0,+ transit_ordinal: 0,+ transit_lanes: 0,+ transit_taper: 0,+ lane_count: 0,+ });+ water.parts.push(Part { coord_start: 0, point_count: 4, winding: WINDING_OUTER });+ water.coords = vec![(500, 3000), (1100, 3000), (1100, 3400), (500, 3400)];+ body.layers.push(water);+ body } fn mesh_for<'a>(mesh: &'a TileMesh, layers: &[Layer], id: &str) -> Option<&'a LayerMesh> {
library/map/src/main/rust/src/tile/geometry/tests_extra3.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/tests_extra3.rs b/library/map/src/main/rust/src/tile/geometry/tests_extra3.rsindex 762583c832..77915ef7d5 100644--- a/library/map/src/main/rust/src/tile/geometry/tests_extra3.rs+++ b/library/map/src/main/rust/src/tile/geometry/tests_extra3.rs@@ -5,21 +5,52 @@ use crate::style; use crate::style::paint::Ramp; use crate::style::{KindFilter, Layer, LayerKind, LayerToggles}; use crate::tess::{roof, terrain};-use tilecodec::mamaps::body::{Body, GEOM_LINE, GEOM_POLYGON};+use tilecodec::mamaps::body::{Body, Feature, GEOM_LINE, GEOM_POLYGON, Layer as BodyLayer, NAME_NONE, Part, WINDING_OUTER};+use tilecodec::mamaps::dict; use tilecodec::mamaps::dict::LAYER_TRAFFIC; -const REAL_TILE: &[u8] = include_bytes!("../../../tests/fixtures/v5ca_z11_tile.mvt");--/// The published tile, converted to a `.mamaps` body.-///-/// The fixture is still MVT because it was lifted out of the published archive with a ranged-/// GET, and there is no published `.mamaps` archive yet. Going through `from_mvt` is what-/// Phase 4 of the plan is: the container and this module are validated on data the tiler-/// already produced and the app already drew, before any tag→kind schema work exists to be-/// wrong.+/// A representative v7 body: one `earth` polygon and one `water` polygon —+/// the same layers the old MVT fixture carried, built directly as a body so+/// the tests no longer depend on the MVT→body converter. fn real() -> Body {- let tile = tilecodec::mvt::Tile::decode(REAL_TILE).expect("the published tile decodes");- tilecodec::mamaps::from_mvt::from_tile(&tile).expect("converts").0+ let mut body = Body::new(4096);+ let mut earth = BodyLayer::new(dict::LAYER_EARTH);+ earth.features.push(Feature {+ kind: 1,+ kind_detail: dict::NONE,+ geom_type: GEOM_POLYGON,+ flags: 0,+ name_idx: NAME_NONE,+ parts_offset: 0,+ part_count: 1,+ transit_color: 0,+ transit_ordinal: 0,+ transit_lanes: 0,+ transit_taper: 0,+ lane_count: 0,+ });+ earth.parts.push(Part { coord_start: 0, point_count: 4, winding: WINDING_OUTER });+ earth.coords = vec![(0, 0), (4096, 0), (4096, 4096), (0, 4096)];+ body.layers.push(earth);+ let mut water = BodyLayer::new(dict::LAYER_WATER);+ water.features.push(Feature {+ kind: 4,+ kind_detail: dict::NONE,+ geom_type: GEOM_POLYGON,+ flags: 0,+ name_idx: NAME_NONE,+ parts_offset: 0,+ part_count: 1,+ transit_color: 0,+ transit_ordinal: 0,+ transit_lanes: 0,+ transit_taper: 0,+ lane_count: 0,+ });+ water.parts.push(Part { coord_start: 0, point_count: 4, winding: WINDING_OUTER });+ water.coords = vec![(500, 3000), (1100, 3000), (1100, 3400), (500, 3400)];+ body.layers.push(water);+ body } fn mesh_for<'a>(mesh: &'a TileMesh, layers: &[Layer], id: &str) -> Option<&'a LayerMesh> {
library/map/src/main/rust/src/tile/source/caching.rs
diff --git a/library/map/src/main/rust/src/tile/source/caching.rs b/library/map/src/main/rust/src/tile/source/caching.rsindex a8c44d6e82..e773ee9c42 100644--- a/library/map/src/main/rust/src/tile/source/caching.rs+++ b/library/map/src/main/rust/src/tile/source/caching.rs@@ -34,13 +34,6 @@ impl<F: RangeFetcher> CachingRangeReader<F> { self.online.store(online, std::sync::atomic::Ordering::Relaxed); } - /// Re-check the cache's origin marker, now that the archive's `build_id` is known.- ///- /// See [`crate::tile::source::basemap_origin`] for why this is a second step rather than part of opening the cache.- pub fn reset_origin(&self, origin: &str) {- self.cache.reset_if_origin_changed(origin);- }- fn is_online(&self) -> bool { self.online.load(std::sync::atomic::Ordering::Relaxed) }@@ -79,19 +72,10 @@ impl<F: RangeFetcher> RangeReader for CachingRangeReader<F> { let response = match self.fetcher.fetch(&self.url, &range) { Ok(r) => r,- Err(e) => {- // Went offline mid-session: a stale entry is far better than a hole.- if let Some(entry) = cached {- return Ok(entry.body);- }- return Err(e);- }+ Err(e) => return Err(e), }; if !(200..300).contains(&response.status) {- if let Some(entry) = cached {- return Ok(entry.body);- } return err(format!( "range request for {range} of {} failed with HTTP {}", self.url, response.status
library/map/src/main/rust/src/tile/source/file.rs
diff --git a/library/map/src/main/rust/src/tile/source/file.rs b/library/map/src/main/rust/src/tile/source/file.rsdeleted file mode 100644index c6b049492d..0000000000--- a/library/map/src/main/rust/src/tile/source/file.rs+++ /dev/null@@ -1,73 +0,0 @@-use tilecodec::proto::Result;-use tilecodec::stream::RangeReader;--/// A local file as a [`RangeReader`], for `file://` archives pushed to the device.-///-/// Each worker opens its **own** handle, so `read(offset, length)` is `read_at` and needs no-/// seek lock. Placed here (beside [`crate::tile::source::CachingRangeReader`]) so the bridge can choose between this-/// and the network path without the codec crate depending on Android.-///-/// Short reads are returned short — the same contract `CachingRangeReader` and the `RangeReader`-/// trait use — and `exact` in `mamaps::read` turns a short body into a parse error.-pub struct FileRangeReader {- file: std::fs::File,-}--impl FileRangeReader {- pub fn open(path: &std::path::Path) -> Result<Self> {- let file = std::fs::File::open(path)- .map_err(|e| tilecodec::proto::Error(format!("cannot open local archive {}: {e}", path.display())))?;- Ok(FileRangeReader { file })- }-}--impl RangeReader for FileRangeReader {- fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {- if length == 0 {- return Ok(Vec::new());- }- self.read_at(offset, length)- }-}--#[cfg(target_os = "android")]-impl FileRangeReader {- fn read_at(&self, offset: u64, length: u32) -> Result<Vec<u8>> {- use std::os::unix::fs::FileExt;- let mut buf = vec![0u8; length as usize];- let mut got = 0usize;- while got < buf.len() {- let n = self.file.read_at(&mut buf[got..], offset + got as u64).map_err(|e| {- tilecodec::proto::Error(format!("local archive read at {offset}+{got} failed: {e}"))- })?;- if n == 0 {- break;- }- got += n;- }- buf.truncate(got);- Ok(buf)- }-}--#[cfg(not(target_os = "android"))]-impl FileRangeReader {- fn read_at(&self, offset: u64, length: u32) -> Result<Vec<u8>> {- use std::io::{Read, Seek, SeekFrom};- let mut file = &self.file;- file.seek(SeekFrom::Start(offset))- .map_err(|e| tilecodec::proto::Error(format!("local archive seek at {offset} failed: {e}")))?;- let mut buf = vec![0u8; length as usize];- let mut got = 0usize;- while got < buf.len() {- let n = file.read(&mut buf[got..])- .map_err(|e| tilecodec::proto::Error(format!("local archive read at {offset}+{got} failed: {e}")))?;- if n == 0 {- break;- }- got += n;- }- buf.truncate(got);- Ok(buf)- }-}
library/map/src/main/rust/src/tile/source/mod.rs
diff --git a/library/map/src/main/rust/src/tile/source/mod.rs b/library/map/src/main/rust/src/tile/source/mod.rsindex d57417012e..bdf54d45c3 100644--- a/library/map/src/main/rust/src/tile/source/mod.rs+++ b/library/map/src/main/rust/src/tile/source/mod.rs@@ -1,19 +1,14 @@-//! The byte source under the PMTiles reader: the disk cache in front of Kotlin's HTTP+//! The byte source under the mamaps reader: the disk cache in front of Kotlin's HTTP //! stack. //! //! # The policy //!-//! Ported from `maps/.../util/MapTileCache.kt`, the version that has been in production-//! against this archive:-//! //! * A cached range is served without touching the network when it is **fresh**, or //! whenever the device is **offline** — stale but usable, so a previously-viewed area //! keeps rendering with no network.-//! * A failed fetch falls back to a stale entry rather than leaving a hole in the map.-//! * **Only a 206 whose body is exactly the requested length is stored.** A `200`-//! whole-file reply to a range request is what produced the "Prefix string too short"-//! pmtiles failures the original records at `MapTileCache.kt:287-290`; caching one-//! poisons every later read of that range.+//! * A failed fetch or a non-2xx status is an error: the reader never serves a stale+//! entry for a range whose refetch failed.+//! * **Only a 206 whose body is exactly the requested length is stored.** //! //! # Why HTTP goes back out through Kotlin //!@@ -25,7 +20,6 @@ mod caching; mod fetch;-mod file; mod retry; mod urls; @@ -36,6 +30,5 @@ pub use caching::CachingRangeReader; #[cfg(target_os = "android")] pub use fetch::JniRangeFetcher; pub use fetch::{RangeFetcher, RangeResponse};-pub use file::FileRangeReader; pub use retry::{RETRY_BASE_MS, RETRY_MAX_MS, retry_delay_ms};-pub use urls::{BASEMAP_ARCHIVE_URL, BASEMAP_PMTILES_URL, CACHE_FORMAT, basemap_origin};+pub use urls::{BASEMAP_ARCHIVE_URL, CACHE_FORMAT, basemap_origin};
library/map/src/main/rust/src/tile/source/tests.rs
diff --git a/library/map/src/main/rust/src/tile/source/tests.rs b/library/map/src/main/rust/src/tile/source/tests.rsindex a7b5826641..90f524132e 100644--- a/library/map/src/main/rust/src/tile/source/tests.rs+++ b/library/map/src/main/rust/src/tile/source/tests.rs@@ -89,7 +89,7 @@ impl RangeFetcher for Fake { } } -const URL: &str = BASEMAP_PMTILES_URL;+const URL: &str = BASEMAP_ARCHIVE_URL; fn reader(dir: &std::path::Path, clock: Arc<AtomicU64>, fetcher: Fake) -> CachingRangeReader<Fake> { let c = clock.clone();@@ -204,8 +204,10 @@ fn a_stale_entry_is_served_offline_rather_than_failing() { assert!
Diff truncated.