Modern Apps git

← Modern-Apps.git

measure: testable AR hit/flow seams from audit

Commit
f92a3bb0a6ca18b3fd2d24504e854447b8021b88
Author
Vayun Mathur <[email protected]>
When
2026-11-17 01:57 UTC (19 days ago)
Parents
428a82e
Diagnosis of the AR feature (owner: "rarely if ever works"), audited
end to end before rebuilding. Stack: NOT ARCore/Play Services. It is
CameraX (640x480 Y-plane only) + gyroscope/accelerometer IMU into a
from-scratch Rust monocular VIO engine (measure_vio: FAST/KLT
tracking, epipolar pose recovery, two-view triangulation, a linear
VINS-style visual-inertial alignment for metric scale, RANSAC plane
fit). No depth, no descriptors/bundle-adjustment/loop-closure, no
relocalisation. ARCore was rejected for the rebuild: it is a Play
Services binary that would break this app's "no Play Services,
real metres offline" premise (measure/AGENTS.md) and is absent from
SUPPLY_CHAIN_RISKS.md and the version catalog; google() is in
settings but adding the dep also needs the shared catalog, outside
measure/ scope. The fix therefore rebuilds the flawed layers around
the engine already in the tree.

Ranked root causes (evidence in file:line at origin/main):

1. Hit test returns garbage confidently (vio.rs ray_to_world).
   With no plane it returns the landmark with the smallest
   perpendicular distance to the ray with NO threshold: any tap
   snaps to some sparse landmark however far off-ray. With a plane
   it intersects one infinite fitted plane with no distance range,
   no extent/hull check and no hit-distance sanity, so taps metres
   beyond the observed surface still "land". Only gate was quality
   != Initialising/Lost.
2. Reticle lies (ArMeasureContent/ArMeasurePage). The overlay draws
   a centre reticle implying placement there, but placement uses
   the raw finger tap ray at the tap instant. There is no
   continuously evaluated centre hit to snap to.
3. Placement allowed on unproven scale. The page gates taps on
   Good OR Limited; Limited is alignment confidence 0.3..0.6
   (try_align) / few landmarks (rebuild_map), i.e. the metre itself
   is a guess, yet anchors placed then are saved as real distances.
   IMU gyro/accel bias is never estimated (preintegrate.rs has
   estimate_gyro_bias; vio.rs keeps both biases at zero forever),
   and the pinhole model ignores LENS_DISTORTION entirely.
4. Initialisation can coach forever with no exit. Alignment needs
   6 keyframes with real translation and confidence >= 0.3; in low
   texture / pure rotation / misaligned clocks it never converges.
   CameraIntrinsicsResolver.timestampsAlignWithSensors exists but
   is never called, so devices whose camera clock cannot fuse with
   the IMU coach eternally. Session-create failure (handle 0) makes
   every tap silently no-op (page only acts when hit != null).
5. No availability model. Native-lib missing and camera-denied are
   two dead-end notices; unsupported/misaligned devices get the
   same dead camera view. No manual fallback from the AR page,
   although the app already ships a physical ruler tool.
6. Measurement math undersells and overclaims. distanceM is only
   the LAST segment, not the polyline the user tapped out;
   planarityError() exists in domain/Polygon.kt but is never
   called, so bent, non-planar "areas" are quoted as exact; area
   only appears after explicit close with no trustworthiness check.
   Anchors are bare points (plane anchor only by snap), so drift
   in the single global pose moves every saved number silently.
7. Tests cannot catch any of this: existing tests place synthetic
   anchors straight into the ViewModel. Hit selection, flow gating,
   reticle behaviour and fallbacks had no seams and no tests.

This commit adds only the pure, testable seams the rebuild uses,
with unit tests; no behaviour change yet:
- domain/ArHit.kt: HitCandidate (Plane/FeaturePoint) + HitSelector
  with distance range, feature angular threshold and floor/wall
  normal sanity, plane-preferred. Fixes cause 1 as policy.
- domain/ArFlow.kt: sealed ArFlowState (Unavailable/NoSession/
  Scanning/Searching/Ready/TrackingLost) derived purely from
  availability, session, quality, reticle hit and clocks; only
  Ready (Good + sane hit) can place. Fixes causes 2,3,4,5 as state.
- domain/MeasureMath.kt: segments with world midpoints, open
  polyline length, last-segment length, and area trustworthiness
  via the previously dead planarityError. Fixes cause 6.

Verified: new ArHitSelectorTest, ArFlowTest, MeasureMathTest cover
threshold rejection, plane preference, Limited-never-ready,
scanning/lost timeouts, segment/midpoint math and bent-quad area
rejection. Full module verification runs with the rebuild commits.

Diff

measure/src/main/java/com/vayunmathur/measure/domain/ArFlow.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/domain/ArFlow.kt b/measure/src/main/java/com/vayunmathur/measure/domain/ArFlow.ktnew file mode 100644index 0000000000..c5eef947cb--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/domain/ArFlow.kt@@ -0,0 +1,90 @@+package com.vayunmathur.measure.domain++import com.vayunmathur.measure.data.model.TrackingQuality++/** Why AR cannot run at all on this device/session, in user terms. */+enum class ArUnavailableReason {+    NativeEngineMissing,+    CameraPermissionDenied,+    CameraTimestampMismatch,+    MotionSensorsMissing,+}++/**+ * The AR measuring flow as one typed state, replacing the old implicit+ * mess of a quality enum plus a hasPlane flag plus null checks in the+ * page. The UI renders exactly one of these; placement is only possible+ * from [Ready], which is only reached with solid tracking and a sane+ * hit, so "tap does nothing" states are unrepresentable.+ */+sealed interface ArFlowState {+    data class Unavailable(val reason: ArUnavailableReason) : ArFlowState++    /** Engine/session not created yet (or camera not yet running). */+    data object NoSession : ArFlowState++    /**+     * Tracking is not solid yet. [timedOut] flips after+     * [ArFlow.INITIALISING_TIMEOUT_MS] so the UI can offer the manual+     * fallback instead of coaching forever.+     */+    data class Scanning(val timedOut: Boolean = false) : ArFlowState++    /** Tracking is solid but the centre ray currently hits nothing sane. */+    data object Searching : ArFlowState++    /** Solid tracking and a selected hit under the reticle. */+    data class Ready(val hit: HitCandidate) : ArFlowState++    /** Tracking was solid and is now lost; anchors are already cleared. */+    data class TrackingLost(val timedOut: Boolean = false) : ArFlowState+}++object ArFlow {+    const val INITIALISING_TIMEOUT_MS = 25_000L+    const val LOST_TIMEOUT_MS = 15_000L++    /**+     * Derive the flow state. Pure, so the whole machine is unit-testable+     * with fake quality/hit inputs and fake clocks.+     *+     * Anchors may only be placed when this returns [ArFlowState.Ready]:+     * the old flow allowed Limited tracking (scale confidence as low as+     * 0.3) to place points, which baked a guess at the metre into every+     * saved distance.+     */+    fun derive(+        unavailable: ArUnavailableReason?,+        hasSession: Boolean,+        quality: TrackingQuality,+        reticleHit: HitCandidate?,+        scanningSinceMs: Long?,+        lostSinceMs: Long?,+        nowMs: Long,+    ): ArFlowState {+        if (unavailable != null) return ArFlowState.Unavailable(unavailable)+        if (!hasSession) return ArFlowState.NoSession+        return when (quality) {+            TrackingQuality.Initialising -> ArFlowState.Scanning(+                timedOut = scanningSinceMs != null &&+                    nowMs - scanningSinceMs >= INITIALISING_TIMEOUT_MS,+            )+            TrackingQuality.Limited -> ArFlowState.Scanning(+                timedOut = scanningSinceMs != null &&+                    nowMs - scanningSinceMs >= INITIALISING_TIMEOUT_MS,+            )+            TrackingQuality.Lost -> ArFlowState.TrackingLost(+                timedOut = lostSinceMs != null &&+                    nowMs - lostSinceMs >= LOST_TIMEOUT_MS,+            )+            TrackingQuality.Good ->+                if (reticleHit != null) ArFlowState.Ready(reticleHit)+                else ArFlowState.Searching+        }+    }++    /** True in states where the "move your phone to scan" coach shows. */+    fun isScanning(state: ArFlowState): Boolean = state is ArFlowState.Scanning++    fun canPlace(state: ArFlowState): Boolean = state is ArFlowState.Ready+}
measure/src/main/java/com/vayunmathur/measure/domain/ArHit.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/domain/ArHit.kt b/measure/src/main/java/com/vayunmathur/measure/domain/ArHit.ktnew file mode 100644index 0000000000..8edf363054--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/domain/ArHit.kt@@ -0,0 +1,91 @@+package com.vayunmathur.measure.domain++import kotlin.math.sqrt++/** A metric 3D point in the tracker world frame (metres, gravity-aligned). */+data class Vec3(val x: Double, val y: Double, val z: Double) {+    fun distanceTo(other: Vec3): Double {+        val dx = x - other.x+        val dy = y - other.y+        val dz = z - other.z+        return sqrt(dx * dx + dy * dy + dz * dz)+    }++    operator fun minus(other: Vec3): Vec3 = Vec3(x - other.x, y - other.y, z - other.z)+    operator fun plus(other: Vec3): Vec3 = Vec3(x + other.x, y + other.y, z + other.z)+    fun midpoint(other: Vec3): Vec3 = Vec3((x + other.x) / 2, (y + other.y) / 2, (z + other.z) / 2)+    fun isFinite(): Boolean = x.isFinite() && y.isFinite() && z.isFinite()+}++enum class HitKind { Plane, FeaturePoint }++/**+ * One candidate hit from a hit-test provider, before selection.+ *+ * [angularErrorDeg] is the angle between the centre ray and the candidate+ * (0 for a plane intersection on the ray itself). [normalDotUp] is the+ * absolute dot of the surface normal with gravity-up for plane hits, so+ * 1 = horizontal floor/ceiling, 0 = vertical wall; null for point hits.+ */+data class HitCandidate(+    val kind: HitKind,+    val position: Vec3,+    val distanceM: Double,+    val angularErrorDeg: Double = 0.0,+    val normalDotUp: Double? = null,+)++/**+ * Selects the one hit a reticle/placement may use, or null.+ *+ * This is the policy the old native ray cast lacked: it returned the+ * nearest landmark by perpendicular distance with no threshold at all,+ * so any tap snapped to some sparse point however far off-ray it was,+ * and it intersected a single infinite fitted plane with no distance+ * or extent check. Every candidate must now pass distance and angle+ * sanity, and a real plane hit on the ray always wins over a point+ * that merely happens to lie near it.+ */+object HitSelector {+    data class Config(+        val minDistanceM: Double = 0.15,+        val maxDistanceM: Double = 8.0,+        val maxFeatureAngleDeg: Double = 2.5,+        /** Prefer a plane even over a slightly closer feature point. */+        val preferPlane: Boolean = true,+    )++    val Default = Config()++    fun select(candidates: List<HitCandidate>, config: Config = Default): HitCandidate? {+        val sane = candidates.filter { isSane(it, config) }+        if (sane.isEmpty()) return null+        val planes = sane.filter { it.kind == HitKind.Plane }+        if (config.preferPlane && planes.isNotEmpty()) {+            return planes.minByOrNull { it.distanceM }+        }+        val features = sane.filter { it.kind == HitKind.FeaturePoint }+        if (features.isNotEmpty()) {+            return features.minWithOrNull(+                compareBy<HitCandidate> { it.angularErrorDeg }.thenBy { it.distanceM }+            )+        }+        return planes.minByOrNull { it.distanceM }+    }++    fun isSane(candidate: HitCandidate, config: Config = Default): Boolean {+        if (!candidate.position.isFinite()) return false+        if (!candidate.distanceM.isFinite()) return false+        if (candidate.distanceM < config.minDistanceM) return false+        if (candidate.distanceM > config.maxDistanceM) return false+        return when (candidate.kind) {+            HitKind.Plane -> {+                val n = candidate.normalDotUp+                // Reject slanted fits: a plane is a floor/ceiling or a wall,+                // never a 45-degree ramp through clutter.+                n == null || n > 0.85 || n < 0.15+            }+            HitKind.FeaturePoint -> candidate.angularErrorDeg <= config.maxFeatureAngleDeg+        }+    }+}
measure/src/main/java/com/vayunmathur/measure/domain/MeasureMath.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/domain/MeasureMath.kt b/measure/src/main/java/com/vayunmathur/measure/domain/MeasureMath.ktnew file mode 100644index 0000000000..0b167caeb3--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/domain/MeasureMath.kt@@ -0,0 +1,44 @@+package com.vayunmathur.measure.domain++import com.vayunmathur.measure.data.model.Anchor+import com.vayunmathur.measure.data.model.distanceTo++/** One measured edge between consecutive anchors. */+data class Segment(+    val startIndex: Int,+    val lengthM: Double,+    /** World-space midpoint, for the on-screen distance label. */+    val midpoint: Vec3,+)++fun Anchor.toVec3(): Vec3 = Vec3(x, y, z)++/** Every consecutive edge, in placement order (the open polyline). */+fun segmentsOf(anchors: List<Anchor>): List<Segment> {+    if (anchors.size < 2) return emptyList()+    return (0 until anchors.size - 1).map { i ->+        val a = anchors[i]+        val b = anchors[i + 1]+        Segment(+            startIndex = i,+            lengthM = a.distanceTo(b),+            midpoint = a.toVec3().midpoint(b.toVec3()),+        )+    }+}++/** Total length of the open polyline through all anchors, in metres. */+fun polylineLengthM(anchors: List<Anchor>): Double? =+    if (anchors.size < 2) null else segmentsOf(anchors).sumOf { it.lengthM }++/** Length of the most recent edge, in metres. */+fun lastSegmentLengthM(anchors: List<Anchor>): Double? =+    segmentsOf(anchors).lastOrNull()?.lengthM++/**+ * Area is only trustworthy for a (near-)planar polygon. The old flow+ * quoted an area for any closed tap loop however bent out of plane it+ * was; callers must now check this warning before presenting a number.+ */+fun areaIsTrustworthy(anchors: List<Anchor>, maxPlanarityErrorM: Double = 0.05): Boolean =+    anchors.size >= 3 && planarityError(anchors) <= maxPlanarityErrorM
measure/src/test/java/com/vayunmathur/measure/domain/ArFlowTest.kt
diff --git a/measure/src/test/java/com/vayunmathur/measure/domain/ArFlowTest.kt b/measure/src/test/java/com/vayunmathur/measure/domain/ArFlowTest.ktnew file mode 100644index 0000000000..237e324c1e--- /dev/null+++ b/measure/src/test/java/com/vayunmathur/measure/domain/ArFlowTest.kt@@ -0,0 +1,67 @@+package com.vayunmathur.measure.domain++import com.vayunmathur.measure.data.model.TrackingQuality+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertIs+import kotlin.test.assertTrue++class ArFlowTest {++    private val hit = HitCandidate(HitKind.Plane, Vec3(0.0, -1.0, -2.0), 2.2)++    private fun derive(+        unavailable: ArUnavailableReason? = null,+        hasSession: Boolean = true,+        quality: TrackingQuality = TrackingQuality.Good,+        reticleHit: HitCandidate? = hit,+        scanningSinceMs: Long? = null,+        lostSinceMs: Long? = null,+        nowMs: Long = 0L,+    ) = ArFlow.derive(unavailable, hasSession, quality, reticleHit, scanningSinceMs, lostSinceMs, nowMs)++    @Test fun unavailableAlwaysWins() {+        val s = derive(unavailable = ArUnavailableReason.CameraTimestampMismatch)+        assertEquals(ArFlowState.Unavailable(ArUnavailableReason.CameraTimestampMismatch), s)+        assertFalse(ArFlow.canPlace(s))+    }++    @Test fun noSessionBeforeEngineStarts() {+        assertEquals(ArFlowState.NoSession, derive(hasSession = false))+    }++    @Test fun initialisingAndLimitedAreScanningNeverReady() {+        // Even with a hit present, Limited must not place: its scale is a guess.+        assertIs<ArFlowState.Scanning>(derive(quality = TrackingQuality.Initialising))+        assertIs<ArFlowState.Scanning>(derive(quality = TrackingQuality.Limited))+        assertFalse(ArFlow.canPlace(derive(quality = TrackingQuality.Limited)))+    }++    @Test fun goodWithoutHitIsSearchingGoodWithHitIsReady() {+        assertEquals(ArFlowState.Searching, derive(reticleHit = null))+        val ready = derive()+        assertIs<ArFlowState.Ready>(ready)+        assertTrue(ArFlow.canPlace(ready))+    }++    @Test fun scanningTimesOutIntoFallbackOffer() {+        val s = derive(+            quality = TrackingQuality.Initialising,+            scanningSinceMs = 0L,+            nowMs = ArFlow.INITIALISING_TIMEOUT_MS,+        )+        assertIs<ArFlowState.Scanning>(s)+        assertTrue(s.timedOut)+    }++    @Test fun lostTimesOutIndependently() {+        val s = derive(+            quality = TrackingQuality.Lost,+            lostSinceMs = 0L,+            nowMs = ArFlow.LOST_TIMEOUT_MS + 1,+        )+        assertIs<ArFlowState.TrackingLost>(s)+        assertTrue(s.timedOut)+    }+}
measure/src/test/java/com/vayunmathur/measure/domain/ArHitSelectorTest.kt
diff --git a/measure/src/test/java/com/vayunmathur/measure/domain/ArHitSelectorTest.kt b/measure/src/test/java/com/vayunmathur/measure/domain/ArHitSelectorTest.ktnew file mode 100644index 0000000000..3851c15fee--- /dev/null+++ b/measure/src/test/java/com/vayunmathur/measure/domain/ArHitSelectorTest.kt@@ -0,0 +1,55 @@+package com.vayunmathur.measure.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlin.test.assertFalse++class ArHitSelectorTest {++    private fun plane(dist: Double, dotUp: Double? = 1.0) =+        HitCandidate(HitKind.Plane, Vec3(0.0, 0.0, -dist), dist, 0.0, dotUp)++    private fun feature(dist: Double, angleDeg: Double) =+        HitCandidate(HitKind.FeaturePoint, Vec3(0.1, 0.0, -dist), dist, angleDeg, null)++    @Test fun emptyCandidatesYieldNoHit() {+        assertNull(HitSelector.select(emptyList()))+    }++    @Test fun planeOnTheRayWinsOverFeaturePoints() {+        val hit = HitSelector.select(listOf(feature(1.0, 0.1), plane(2.0)))+        assertEquals(HitKind.Plane, hit?.kind)+    }++    @Test fun featureBeyondAngleThresholdIsRejected() {+        // The old native cast returned this unconditionally.+        assertNull(HitSelector.select(listOf(feature(1.0, 20.0))))+    }++    @Test fun featureWithinThresholdIsSelectedByAngle() {+        val hit = HitSelector.select(listOf(feature(1.0, 2.0), feature(3.0, 0.5)))+        assertEquals(0.5, hit?.angularErrorDeg)+    }++    @Test fun tooCloseAndTooFarHitsAreRejected() {+        assertNull(HitSelector.select(listOf(plane(0.05))))+        assertNull(HitSelector.select(listOf(plane(20.0))))+        assertNull(HitSelector.select(listOf(feature(0.01, 0.0))))+    }++    @Test fun slantedPlaneIsRejectedButFloorAndWallPass() {+        assertFalse(HitSelector.isSane(plane(1.0, dotUp = 0.7))) // ~45 deg ramp+        assertTrue(HitSelector.isSane(plane(1.0, dotUp = 0.99)))+        assertTrue(HitSelector.isSane(plane(1.0, dotUp = 0.02)))+    }++    @Test fun nonFiniteHitsAreRejected() {+        assertNull(+            HitSelector.select(+                listOf(HitCandidate(HitKind.Plane, Vec3(Double.NaN, 0.0, 0.0), 1.0))+            )+        )+    }+}
measure/src/test/java/com/vayunmathur/measure/domain/MeasureMathTest.kt
diff --git a/measure/src/test/java/com/vayunmathur/measure/domain/MeasureMathTest.kt b/measure/src/test/java/com/vayunmathur/measure/domain/MeasureMathTest.ktnew file mode 100644index 0000000000..7114e175c8--- /dev/null+++ b/measure/src/test/java/com/vayunmathur/measure/domain/MeasureMathTest.kt@@ -0,0 +1,42 @@+package com.vayunmathur.measure.domain++import com.vayunmathur.measure.data.model.Anchor+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++class MeasureMathTest {++    private fun a(id: Long, x: Double, y: Double, z: Double) = Anchor(id, x, y, z, onPlane = true)++    @Test fun segmentsCarryLengthsAndMidpoints() {+        val anchors = listOf(a(1, 0.0, 0.0, 0.0), a(2, 3.0, 4.0, 0.0), a(3, 3.0, 4.0, 12.0))+        val segments = segmentsOf(anchors)+        assertEquals(2, segments.size)+        assertEquals(5.0, segments[0].lengthM)+        assertEquals(12.0, segments[1].lengthM)+        assertEquals(Vec3(1.5, 2.0, 0.0), segments[0].midpoint)+        assertEquals(17.0, polylineLengthM(anchors))+        assertEquals(12.0, lastSegmentLengthM(anchors))+    }++    @Test fun fewerThanTwoAnchorsHaveNoSegments() {+        assertTrue(segmentsOf(emptyList()).isEmpty())+        assertNull(polylineLengthM(listOf(a(1, 0.0, 0.0, 0.0))))+        assertNull(lastSegmentLengthM(emptyList()))+    }++    @Test fun flatSquareAreaIsTrustworthyBentQuadIsNot() {+        val flat = listOf(+            a(1, 0.0, 0.0, 0.0), a(2, 1.0, 0.0, 0.0),+            a(3, 1.0, 0.0, 1.0), a(4, 0.0, 0.0, 1.0),+        )+        assertTrue(areaIsTrustworthy(flat))+        val bent = flat.mapIndexed { i, anchor ->+            if (i == 3) anchor.copy(z = 0.4) else anchor+        }+        assertFalse(areaIsTrustworthy(bent))+    }+}