Modern Apps git

← Modern-Apps.git

measure: fix sensor permission crash and 16 KB native alignment

Commit
924982c0c670d20c57c083cae98d2b0ae50253c9
Author
Vayun Mathur <[email protected]>
When
2026-11-17 04:24 UTC (19 days ago)
Parents
e1186a7
Sensor crash: ImuRecorder registered gyro/accel with
SENSOR_DELAY_FASTEST (0 us), which throws SecurityException
("app needs to declare HIGH_SAMPLING_RATE_SENSORS") on the
owner's Pixel, killing the AR session from MeasureCamera.
Declare the normal HIGH_SAMPLING_RATE_SENSORS permission in
the manifest, request an explicit 400 Hz period
(SAMPLING_PERIOD_US = 2500) instead of 0, and treat
registration as fallible: start() now returns false on a
missing sensor, a refused registration, or SecurityException
(unregistering any half-registered pair), the camera pump
reports Limited, and the analyzer caps quality at Limited
while the IMU is down, since metric scale cannot lock
without IMU windows. That is the ArFlow Scanning state, so
anchors (Good-only) are never placed on unscaled tracking.

16 KB alignment: the APK shipped OpenCV's libopencv_java4.so
and the AAR's libc++_shared.so with PT_LOAD p_align 0x1000,
which fails on 16 KB-page devices. Per owner direction, no
third-party OpenCV AAR ships at all (verified beforehand:
4.11.0 still bundles a 4 KB libc++_shared; 4.12.0 is aligned
but rejected in favour of our own code). The per-frame CV is
now the in-tree Rust crate measure_cv, following the camera
app's stitching precedent on the shared vision_core
primitives: new Shi-Tomasi corner detection with sub-pixel
refinement (corners.rs), the existing pyramidal
Lucas-Kanade tracker plus a forward-backward check, and the
existing essential-matrix recovery (normalised eight-point,
RANSAC, cheirality) behind a minimal JNI session
(frame in, tracked pairs + relative pose out). The crate
replaces the unreferenced legacy measure_vio crate in the
same directory; its VIO orchestration, which the owner had
already found not to work on device, is deleted rather than
revived. Kotlin keeps the tested geometry above the
correspondences: VioEngine (renamed from OpenCvVioEngine,
platform/opencv -> platform/vio) still does pose chaining,
keyframe triangulation, RANSAC plane fit and IMU scale
fusion in VioMath, and ArHitProvider/HitSelector are
unchanged in shape. org.opencv is removed from the version
catalog and from measure's dependencies.

Verified: cargo test -p measure_cv (14 unit + 6 integration
tests: corner detection on synthetic patterns, LK tracking
of a shifted pattern, essential recovery on synthetic
correspondences, session reseed/reset); :measure:
testDevUnitTest (141 tests) and :measure:lintDev green;
:measure:assembleDev APK ELF-checked - every lib/arm64-v8a
.so (libmeasure_cv, graphics.path, datastore, CameraX JNI,
surface_util) has all PT_LOAD segments at p_align 0x4000,
with no libopencv_java4.so and no libc++_shared.so present;
merged manifest carries HIGH_SAMPLING_RATE_SENSORS.
Device install/launch/logcat verification on the Pixel 9
Pro is still outstanding: the adb forward at 127.0.0.1:15556
dropped during this session and ./install measure (with the
release-signing env) currently reports no device connected.

Diff

Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex c8b9b5b796..815310cee4 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3415,7 +3415,7 @@ dependencies = [ ]  [[package]]-name = "measure_vio"+name = "measure_cv" version = "0.1.0" dependencies = [  "jni",
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex e055a43d79..1133cc49d7 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -108,15 +108,9 @@ grpcKotlin = "1.5.0" # @javax.annotation.Generated referenced by grpc-java generated stubs. javaxAnnotation = "1.3.2" jsr305 = "3.0.2"-# OpenCV Android SDK for :measure's visual-inertial tracker (org.opencv:opencv, Maven-# Central — already an approved repository in settings.gradle.kts, so no new host).-# Apache-2.0, purely on-device native code: it makes no network calls at runtime, so it-# needs no SUPPLY_CHAIN_RISKS.md entry (that file covers runtime server fetches only).-# 4.10.0 over 4.11+/5.x: the newest AAR line this AGP accepts without friction, and the-# release every Android sample targets. The AAR bundles per-ABI native libraries, which-# is the APK-size cost of replacing the home-grown Rust VIO — accepted for a tracker-# that actually works on device.-opencv = "4.10.0"+# (No OpenCV entry: :measure's visual-inertial tracker runs on the in-tree Rust+# `measure_cv` crate — see measure/src/main/rust — so no third-party native CV+# library ships in the APK at all.) zxing = "3.5.4" libphonenumber = "9.0.43" brotli = "0.1.2"@@ -344,8 +338,6 @@ grpc-protoc-gen-kotlin = { module = "io.grpc:protoc-gen-grpc-kotlin", version.re javax-annotation-api = { module = "javax.annotation:javax.annotation-api", version.ref = "javaxAnnotation" } google-jsr305 = { module = "com.google.code.findbugs:jsr305", version.ref = "jsr305" } zxing-core = { module = "com.google.zxing:core", version.ref = "zxing" }-# :measure visual-inertial tracker (see the version key for provenance and the size note).-opencv = { module = "org.opencv:opencv", version.ref = "opencv" } libphonenumber = { module = "com.googlecode.libphonenumber:libphonenumber", version.ref = "libphonenumber" } brotli-dec = { module = "org.brotli:dec", version.ref = "brotli" } okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" }
measure/AGENTS.md
diff --git a/measure/AGENTS.md b/measure/AGENTS.mdindex 8b17cd390d..df9d11462f 100644--- a/measure/AGENTS.md+++ b/measure/AGENTS.md@@ -7,14 +7,14 @@ _Install: ./install measure (dev by default)._ - Gradle: :measure / dir: measure/ - Package roots present: ui, data, domain, platform - Entry files: MainActivity.kt, Route.kt, Navigation.kt-- Deps: CameraX + org.opencv:opencv 4.10.0 (Maven Central, catalog-pinned; AR tracking only — no Play Services)+- Deps: CameraX + in-tree Rust `measure_cv` CV core (no third-party native CV; AR tracking only — no Play Services) - Metadata: metadata_data/measure.md (present)-- Rust: crate present but unreferenced (legacy measure_vio, kept for reference) / screenshotTest: yes+- Rust: `measure_cv` crate wired via rustNativeLib (corners/LK/essential JNI) / screenshotTest: yes  ## Overview-**Purpose:** Offline measuring toolkit — compass, level, ruler, protractor + AR distance/area over an OpenCV visual-inertial tracker (features/LK/essential pose/triangulation/IMU scale). Real metres, no Play Services.-**Key features:** Per-tool pages (AR/compass/level/ruler/saved/settings) + diagnostics; `domain/` pure geometry (level math, tilt, polygons, units, VIO math); `platform/sensor/` IMU recording; camera intrinsics; OpenCV tracker in `platform/opencv/` behind the `ArHitProvider` seam.-**Entry points:** `Route` → `MainActivity.kt` → `Navigation.kt` → `ui/ArMeasurePage.kt` → `platform/MeasureViewModel.kt` → `platform/opencv/OpenCvVioEngine.kt` (math in `domain/VioMath.kt`).+**Purpose:** Offline measuring toolkit — compass, level, ruler, protractor + AR distance/area over a Rust visual-inertial tracker (features/LK/essential pose/triangulation/IMU scale). Real metres, no Play Services.+**Key features:** Per-tool pages (AR/compass/level/ruler/saved/settings) + diagnostics; `domain/` pure geometry (level math, tilt, polygons, units, VIO math); `platform/sensor/` IMU recording; camera intrinsics; Rust CV tracker in `platform/vio/` behind the `ArHitProvider` seam.+**Entry points:** `Route` → `MainActivity.kt` → `Navigation.kt` → `ui/ArMeasurePage.kt` → `platform/MeasureViewModel.kt` → `platform/vio/VioEngine.kt` over crate `measure_cv` (math in `domain/VioMath.kt`). **Gotchas:** VIO needs device calibration + motion — test measuring by moving, not screenshots; intrinsics vary per device.  ## Key files
measure/build.gradle.kts
diff --git a/measure/build.gradle.kts b/measure/build.gradle.ktsindex 813896971d..571b1da615 100644--- a/measure/build.gradle.kts+++ b/measure/build.gradle.kts@@ -15,15 +15,25 @@ android {     } } -// Visual-inertial tracking runs on OpenCV (org.opencv:opencv, Maven Central — see-// the catalog entry for provenance). The home-grown Rust `measure_vio` engine is no-// longer wired into the measurement flow: its crate stays in the tree at-// measure/src/main/rust/ for reference but is referenced by nothing.+androidComponents {+    onVariants { variant ->+        variant.sources.jniLibs?.addStaticSourceDirectory(+            layout.buildDirectory.dir("rustJniLibs").get().asFile.absolutePath+        )+    }+}++// Visual-inertial tracking runs on the in-tree Rust CV core (`measure_cv`:+// Shi-Tomasi corners, pyramidal Lucas-Kanade, essential-matrix pose) behind+// the ArHitProvider seam. No third-party native CV library ships in the APK,+// so there is no prebuilt .so to fail 16 KB page-size alignment. See+// measure/src/main/rust/.+rustNativeLib("measure_cv", "measure")+ dependencies {     implementation(libs.androidx.camera.core)     implementation(libs.androidx.camera.camera2)     implementation(libs.androidx.camera.lifecycle)     implementation(libs.androidx.camera.compose)     implementation(libs.androidx.datastore.preferences)-    implementation(libs.opencv) }
measure/src/main/AndroidManifest.xml
diff --git a/measure/src/main/AndroidManifest.xml b/measure/src/main/AndroidManifest.xmlindex 0631a5acd9..e8dc4b3405 100644--- a/measure/src/main/AndroidManifest.xml+++ b/measure/src/main/AndroidManifest.xml@@ -2,6 +2,9 @@ <manifest xmlns:android="http://schemas.android.com/apk/res/android">      <uses-permission android:name="android.permission.CAMERA" />+    <!-- Normal (install-time) permission required for sensor sampling periods+         below the platform threshold; ImuRecorder requests 400 Hz. -->+    <uses-permission android:name="android.permission.HIGH_SAMPLING_RATE_SENSORS" />     <uses-feature android:name="android.hardware.camera" android:required="false" />     <uses-feature android:name="android.hardware.sensor.compass" android:required="false" />     <uses-feature android:name="android.hardware.sensor.accelerometer" android:required="false" />
measure/src/main/java/com/vayunmathur/measure/domain/VioMath.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/domain/VioMath.kt b/measure/src/main/java/com/vayunmathur/measure/domain/VioMath.ktindex 47dec0fd67..c070a03d13 100644--- a/measure/src/main/java/com/vayunmathur/measure/domain/VioMath.kt+++ b/measure/src/main/java/com/vayunmathur/measure/domain/VioMath.kt@@ -5,13 +5,14 @@ import kotlin.math.sqrt import kotlin.random.Random  /**- * Pure visual-inertial geometry behind the OpenCV tracker.+ * Pure visual-inertial geometry behind the Rust CV tracker.  *- * OpenCV (in `platform/opencv/`) does the image work it is good at —- * Shi-Tomasi corners, Lucas-Kanade flow, essential-matrix recovery. The+ * The Rust core (in `platform/vio/`, crate `measure_cv`) does the+ * per-frame image work — Shi-Tomasi corners, Lucas-Kanade flow,+ * essential-matrix recovery. The  * bookkeeping that decides whether a measurement may be trusted lives  * here instead: pose chaining, triangulation, plane fitting and the- * IMU/visual scale alignment. Keeping it free of OpenCV types makes+ * IMU/visual scale alignment. Keeping it free of native types makes  * every one of those decisions unit-testable with synthetic ground  * truth, which is exactly what the home-grown Rust engine never had.  *
measure/src/main/java/com/vayunmathur/measure/platform/ArHitProvider.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/platform/ArHitProvider.kt b/measure/src/main/java/com/vayunmathur/measure/platform/ArHitProvider.ktindex 282b5ef5dc..146f0b598a 100644--- a/measure/src/main/java/com/vayunmathur/measure/platform/ArHitProvider.kt+++ b/measure/src/main/java/com/vayunmathur/measure/platform/ArHitProvider.kt@@ -2,26 +2,26 @@ package com.vayunmathur.measure.platform  import com.vayunmathur.measure.domain.HitCandidate import com.vayunmathur.measure.domain.HitSelector-import com.vayunmathur.measure.platform.opencv.OpenCvVioEngine+import com.vayunmathur.measure.platform.vio.VioEngine  /**  * Seam between the AR flow and whatever produces hit candidates.  *- * Production wraps the OpenCV visual-inertial engine; tests and+ * Production wraps the Rust visual-inertial engine; tests and  * previews use [FakeArHitProvider]. Keeping candidate *selection*  * ([HitSelector]) on this side of the seam is what makes the hit  * policy unit-testable without a device, a camera, or native code.  * The [sessionHandle] argument is retained for the seam's shape; the- * OpenCV provider resolves its engine directly and ignores it.+ * production provider resolves its engine directly and ignores it.  */ interface ArHitProvider {     /** The selected centre-reticle hit right now, or null. */     fun centreHit(sessionHandle: Long): HitCandidate? } -/** Production provider: OpenCV engine candidates through the shared selector. */-class OpenCvArHitProvider(-    private val engine: () -> OpenCvVioEngine?,+/** Production provider: Rust engine candidates through the shared selector. */+class VioArHitProvider(+    private val engine: () -> VioEngine?,     private val analysisWidth: Int,     private val analysisHeight: Int, ) : ArHitProvider {
measure/src/main/java/com/vayunmathur/measure/platform/MeasureSensorOps.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/platform/MeasureSensorOps.kt b/measure/src/main/java/com/vayunmathur/measure/platform/MeasureSensorOps.ktindex d5cb28041a..4f9337002e 100644--- a/measure/src/main/java/com/vayunmathur/measure/platform/MeasureSensorOps.kt+++ b/measure/src/main/java/com/vayunmathur/measure/platform/MeasureSensorOps.kt@@ -8,7 +8,7 @@ import com.vayunmathur.measure.domain.areaIsTrustworthy import com.vayunmathur.measure.domain.lastSegmentLengthM import com.vayunmathur.measure.domain.polylineLengthM import com.vayunmathur.measure.domain.polygonArea-import com.vayunmathur.measure.platform.opencv.OpenCvVioEngine+import com.vayunmathur.measure.platform.vio.VioEngine import com.vayunmathur.measure.domain.polygonPerimeter import kotlinx.coroutines.launch @@ -212,7 +212,7 @@ internal fun MeasureViewModel.onReticleHitImpl(     refreshFlowImpl() } -internal fun MeasureViewModel.onEngineChangedImpl(engine: OpenCvVioEngine?) {+internal fun MeasureViewModel.onEngineChangedImpl(engine: VioEngine?) {     vioEngine = engine     if (engine == null) {         arState.value = arState.value.copy(reticleHit = null)
measure/src/main/java/com/vayunmathur/measure/platform/MeasureViewModel.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/platform/MeasureViewModel.kt b/measure/src/main/java/com/vayunmathur/measure/platform/MeasureViewModel.ktindex 288425da42..f7ce5e1389 100644--- a/measure/src/main/java/com/vayunmathur/measure/platform/MeasureViewModel.kt+++ b/measure/src/main/java/com/vayunmathur/measure/platform/MeasureViewModel.kt@@ -12,7 +12,7 @@ import com.vayunmathur.measure.data.model.SavedMeasurement import com.vayunmathur.measure.data.model.TrackingQuality import com.vayunmathur.measure.data.model.UnitSystem import com.vayunmathur.measure.data.model.distanceTo-import com.vayunmathur.measure.platform.opencv.OpenCvVioEngine+import com.vayunmathur.measure.platform.vio.VioEngine import com.vayunmathur.measure.platform.sensor.ImuRecorder import com.vayunmathur.measure.platform.sensor.TiltSensor import com.vayunmathur.measure.domain.polygonArea@@ -57,15 +57,15 @@ class MeasureViewModel(app: Application) : AndroidViewModel(app),     internal val diagnosticsState = MutableStateFlow(DiagnosticsUiState())     val diagnostics: StateFlow<DiagnosticsUiState> = diagnosticsState -    /** OpenCV engine, mirrored from the AR page so reset can reach it. */-    internal var vioEngine: OpenCvVioEngine? = null+    /** Rust VIO engine, mirrored from the AR page so reset can reach it. */+    internal var vioEngine: VioEngine? = null      /**      * Whether the tracking engine can run here. A seam (not a direct      * static read) so flow tests can simulate a capable device:      * native availability is false on every JVM test host.      */-    internal var engineAvailable: Boolean = OpenCvVioEngine.available+    internal var engineAvailable: Boolean = VioEngine.available      internal var scanningSinceMs: Long? = null     internal var lostSinceMs: Long? = null@@ -145,7 +145,7 @@ class MeasureViewModel(app: Application) : AndroidViewModel(app),      fun onReticleHit(hit: com.vayunmathur.measure.domain.HitCandidate?) = onReticleHitImpl(hit) -    fun onEngineChanged(engine: OpenCvVioEngine?) = onEngineChangedImpl(engine)+    fun onEngineChanged(engine: VioEngine?) = onEngineChangedImpl(engine)      fun setUnavailableReason(reason: com.vayunmathur.measure.domain.ArUnavailableReason?) {         unavailableReason = reason
measure/src/main/java/com/vayunmathur/measure/platform/sensor/ImuRecorder.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/platform/sensor/ImuRecorder.kt b/measure/src/main/java/com/vayunmathur/measure/platform/sensor/ImuRecorder.ktindex db6afc7d84..150e0ccc82 100644--- a/measure/src/main/java/com/vayunmathur/measure/platform/sensor/ImuRecorder.kt+++ b/measure/src/main/java/com/vayunmathur/measure/platform/sensor/ImuRecorder.kt@@ -13,8 +13,14 @@ import android.hardware.SensorManager  * and the calibrated sensors apply their own time-varying correction whose changes look  * like real motion to a dead-reckoning integrator.  *- * `SENSOR_DELAY_FASTEST` requests the hardware maximum (400 Hz on the ICM45631 in recent- * Pixels). Samples are drained in batches rather than pushed individually because+ * [SAMPLING_PERIOD_US] requests 400 Hz (the hardware maximum on the ICM45631 in recent+ * Pixels) as an explicit period rather than `SENSOR_DELAY_FASTEST` (0 µs): the explicit+ * form is the documented contract for high-rate sampling and, together with the+ * `HIGH_SAMPLING_RATE_SENSORS` manifest permission, avoids the `SecurityException`+ * the platform throws for a 0 µs request without that permission. Registration is+ * still treated as fallible — a device or policy that refuses it leaves the recorder+ * stopped ([isActive] false) and the caller degrades to Limited tracking instead of+ * crashing. Samples are drained in batches rather than pushed individually because  * per-sample JNI overhead at that rate would exceed the integration work itself.  */ class ImuRecorder(context: Context) : SensorEventListener {@@ -29,23 +35,44 @@ class ImuRecorder(context: Context) : SensorEventListener {      private var lastGyro = FloatArray(3)     private var haveGyro = false++    @Volatile     private var running = false +    /** True while both sensors are registered; read cross-thread by the frame pump. */+    val isActive: Boolean get() = running+     private var sampleCount = 0L     private var firstSampleNs = 0L     private var lastSampleNs = 0L -    fun start() {-        if (running) return+    /**+     * Register both sensors at [SAMPLING_PERIOD_US]. Returns false (and leaves the+     * recorder stopped) when a sensor is missing or registration is refused —+     * including the `SecurityException` for high-rate sampling without permission —+     * so the caller can degrade to Limited tracking rather than crash.+     */+    fun start(): Boolean {+        if (running) return true         val gyro = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE_UNCALIBRATED)             ?: sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE)         val accel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER_UNCALIBRATED)             ?: sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)-        if (gyro == null || accel == null) return+        if (gyro == null || accel == null) return false -        sensorManager.registerListener(this, gyro, SensorManager.SENSOR_DELAY_FASTEST)-        sensorManager.registerListener(this, accel, SensorManager.SENSOR_DELAY_FASTEST)+        val registered = try {+            sensorManager.registerListener(this, gyro, SAMPLING_PERIOD_US) &&+                sensorManager.registerListener(this, accel, SAMPLING_PERIOD_US)+        } catch (_: SecurityException) {+            false+        }+        if (!registered) {+            // Drop a half-registered pair: one sensor alone cannot be fused.+            runCatching { sensorManager.unregisterListener(this) }+            return false+        }         running = true+        return true     }      fun stop() {@@ -112,6 +139,8 @@ class ImuRecorder(context: Context) : SensorEventListener {     }      private companion object {+        /** 400 Hz (2 500 µs): the explicit high-rate period; never 0 (`FASTEST`). */+        const val SAMPLING_PERIOD_US = 2_500         const val VALUES_PER_SAMPLE = 7         /** ~20 s of headroom at 400 Hz. */         const val MAX_PENDING_VALUES = VALUES_PER_SAMPLE * 8000
measure/src/main/java/com/vayunmathur/measure/platform/vio/ImuIntegrator.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/platform/opencv/ImuIntegrator.kt b/measure/src/main/java/com/vayunmathur/measure/platform/vio/ImuIntegrator.ktsimilarity index 98%rename from measure/src/main/java/com/vayunmathur/measure/platform/opencv/ImuIntegrator.ktrename to measure/src/main/java/com/vayunmathur/measure/platform/vio/ImuIntegrator.ktindex 0fa0013dc5..2049b6897f 100644--- a/measure/src/main/java/com/vayunmathur/measure/platform/opencv/ImuIntegrator.kt+++ b/measure/src/main/java/com/vayunmathur/measure/platform/vio/ImuIntegrator.kt@@ -1,4 +1,4 @@-package com.vayunmathur.measure.platform.opencv+package com.vayunmathur.measure.platform.vio  import com.vayunmathur.measure.domain.Vec3 import com.vayunmathur.measure.domain.rotate3
measure/src/main/java/com/vayunmathur/measure/platform/vio/MeasureCvNative.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/platform/vio/MeasureCvNative.kt b/measure/src/main/java/com/vayunmathur/measure/platform/vio/MeasureCvNative.ktnew file mode 100644index 0000000000..8a7d2bf1c5--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/platform/vio/MeasureCvNative.kt@@ -0,0 +1,108 @@+package com.vayunmathur.measure.platform.vio++import com.vayunmathur.measure.domain.Pose3+import com.vayunmathur.measure.domain.Vec3++/** One tracked correspondence, in pixels: previous -> current. */+data class CvPair(+    val prevX: Double,+    val prevY: Double,+    val currX: Double,+    val currY: Double,+)++/** Per-frame output of the Rust CV core. */+data class CvFrameFlow(+    val firstFrame: Boolean,+    val pairs: List<CvPair>,+    /** Relative pose previous -> current (`X_curr = R * X_prev + t`, unit `t`). */+    val pose: Pose3?,+    /** Feature points seeded for the next frame, after top-up. */+    val pointCount: Int,+)++/**+ * JNI bridge to the in-tree Rust CV core (`measure/src/main/rust`, crate+ * `measure_cv`): Shi-Tomasi corners, pyramidal Lucas-Kanade tracking with a+ * forward-backward check, and essential-matrix pose recovery. No third-party+ * native CV library ships in the APK.+ *+ * [available] guards every call: Compose previews, JVM unit tests and any+ * host without the `.so` degrade to "AR unavailable" rather than crashing.+ */+object MeasureCvNative {++    val available: Boolean by lazy {+        runCatching { System.loadLibrary("measure_cv") }.isSuccess+    }++    fun createSession(fx: Double, fy: Double, cx: Double, cy: Double): Long =+        if (!available) 0L else nativeCreateSession(fx, fy, cx, cy)++    fun destroySession(handle: Long) {+        if (available && handle != 0L) nativeDestroySession(handle)+    }++    fun reset(handle: Long) {+        if (available && handle != 0L) nativeReset(handle)+    }++    /**+     * Feed one luminance plane. [rowStride] is passed through so the caller+     * can hand over the CameraX `ImageProxy` Y plane without repacking it.+     * Null when the session is unavailable or the frame was rejected.+     */+    fun processFrame(+        handle: Long,+        yPlane: ByteArray,+        width: Int,+        height: Int,+        rowStride: Int,+    ): CvFrameFlow? {+        if (!available || handle == 0L) return null+        val raw = nativeProcessFrame(handle, yPlane, width, height, rowStride)+        if (raw.size < HEADER_SIZE) return null+        val pairCount = raw[0].toInt()+        val pose = if (raw[1] != 0.0) {+            val r = DoubleArray(9) { raw[4 + it] }+            val t = Vec3(raw[13], raw[14], raw[15])+            val len = kotlin.math.sqrt(t.x * t.x + t.y * t.y + t.z * t.z)+            if (len > 1e-9) Pose3(r, Vec3(t.x / len, t.y / len, t.z / len)) else null+        } else {+            null+        }+        val pairs = ArrayList<CvPair>(pairCount)+        for (i in 0 until pairCount) {+            val base = HEADER_SIZE + i * 4+            if (base + 3 >= raw.size) break+            pairs += CvPair(raw[base], raw[base + 1], raw[base + 2], raw[base + 3])+        }+        return CvFrameFlow(+            firstFrame = raw[2] != 0.0,+            pairs = pairs,+            pose = pose,+            pointCount = raw[3].toInt(),+        )+    }++    private const val HEADER_SIZE = 16++    private external fun nativeCreateSession(+        fx: Double,+        fy: Double,+        cx: Double,+        cy: Double,+    ): Long++    private external fun nativeDestroySession(handle: Long)++    private external fun nativeReset(handle: Long)++    private external fun nativeProcessFrame(+        handle: Long,+        yPlane: ByteArray,+        width: Int,+        height: Int,+        rowStride: Int,+    ): DoubleArray+}
measure/src/main/java/com/vayunmathur/measure/platform/vio/VioEngine.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/platform/opencv/OpenCvVioEngine.kt b/measure/src/main/java/com/vayunmathur/measure/platform/vio/VioEngine.ktsimilarity index 56%rename from measure/src/main/java/com/vayunmathur/measure/platform/opencv/OpenCvVioEngine.ktrename to measure/src/main/java/com/vayunmathur/measure/platform/vio/VioEngine.ktindex ab6bdb8630..0f4ba190a2 100644--- a/measure/src/main/java/com/vayunmathur/measure/platform/opencv/OpenCvVioEngine.kt+++ b/measure/src/main/java/com/vayunmathur/measure/platform/vio/VioEngine.kt@@ -1,4 +1,4 @@-package com.vayunmathur.measure.platform.opencv+package com.vayunmathur.measure.platform.vio  import com.vayunmathur.measure.data.model.TrackingQuality import com.vayunmathur.measure.domain.FittedPlane@@ -20,18 +20,6 @@ import com.vayunmathur.measure.platform.Intrinsics import kotlin.math.abs import kotlin.math.atan2 import kotlin.math.sqrt-import org.opencv.android.OpenCVLoader-import org.opencv.calib3d.Calib3d-import org.opencv.core.CvType-import org.opencv.core.Mat-import org.opencv.core.MatOfByte-import org.opencv.core.MatOfFloat-import org.opencv.core.MatOfPoint2f-import org.opencv.core.Point-import org.opencv.core.Size-import org.opencv.core.TermCriteria-import org.opencv.imgproc.Imgproc-import org.opencv.video.Video  /** Per-frame result the analyzer forwards to the ViewModel. */ data class VioFrameResult(@@ -46,41 +34,39 @@ data class VioFrameResult( private data class Landmark(val position: Vec3, var observations: Int)  /**- * OpenCV visual-inertial tracker behind the AR measurement flow.+ * Visual-inertial tracker behind the AR measurement flow.  *- * Pipeline per analysis frame (all on the camera executor thread):- * Shi-Tomasi corners (`goodFeaturesToTrack`) tracked with pyramidal- * Lucas-Kanade (`calcOpticalFlowPyrLK`) and a forward-backward- * consistency check; frame-to-frame motion from- * `findEssentialMat` + `recoverPose`, chained into a world pose;- * landmarks by DLT triangulation between keyframes (reprojection and- * parallax filtered, math in `domain/VioMath`); the dominant surface- * by RANSAC plane fit; and metric scale by aligning visual- * displacements with double-integrated IMU displacement windows.+ * Pipeline per analysis frame (all on the camera executor thread): the+ * in-tree Rust CV core (`measure_cv`, see [MeasureCvNative]) detects+ * Shi-Tomasi corners, tracks them with pyramidal Lucas-Kanade plus a+ * forward-backward consistency check, and recovers frame-to-frame+ * motion from an essential matrix (normalised eight-point + RANSAC ++ * cheirality); that pose is chained into a world pose here. Landmarks+ * by DLT triangulation between keyframes (reprojection and parallax+ * filtered, math in `domain/VioMath`); the dominant surface by RANSAC+ * plane fit; and metric scale by aligning visual displacements with+ * double-integrated IMU displacement windows.  *  * Everything visual lives in scale-free units until the IMU scale  * locks — projection is scale-invariant, so only quoted distances  * wait for the lock, mirroring the old engine's "no metric scale, no- * measurements" rule. All OpenCV handles are released per frame; a- * missing native library degrades [available] to false and the UI- * falls back to the manual tools instead of crashing.+ * measurements" rule. A missing native library degrades [available]+ * to false and the UI falls back to the manual tools instead of+ * crashing.  */-class OpenCvVioEngine(private val intrinsics: Intrinsics) {+class VioEngine(private val intrinsics: Intrinsics) {      companion object {-        /** True when the OpenCV native library loaded on this device/host. */-        val available: Boolean by lazy {-            runCatching { OpenCVLoader.initDebug() }.getOrDefault(false)-        }+        /** True when the in-tree Rust CV library loaded on this device/host. */+        val available: Boolean+            get() = MeasureCvNative.available          private const val VALUES_PER_POINT = 3-        private const val MAX_CORNERS = 220         private const val MIN_TRACKED_FOR_POSE = 15         private const val GOOD_TRACKED = 40         private const val GOOD_LANDMARKS = 20         private const val KEYFRAME_PARALLAX_PX = 24.0         private const val MAX_REPROJECTION_PX = 2.0-        private const val FB_ERROR_PX = 1.5         private const val SCALE_CONFIDENCE_MIN = 0.6         private const val SCALE_WINDOWS_MIN = 4         private const val MAX_LANDMARKS = 400@@ -94,11 +80,17 @@ class OpenCvVioEngine(private val intrinsics: Intrinsics) {         0.0, 0.0, 1.0,     ) -    private var prevGray: Mat? = null-    private var prevPoints: List<Point> = emptyList()+    /** Rust CV session handle; 0 when the native library is unavailable. */+    private val nativeHandle: Long =+        if (available) {+            MeasureCvNative.createSession(intrinsics.fx, intrinsics.fy, intrinsics.cx, intrinsics.cy)+        } else {+            0L+        }+     private var worldFromCam: Pose3 = Pose3.identity()     private var keyframePose: Pose3? = null-    private var keyframePoints: List<Point> = emptyList()+    private var keyframePoints: List<Pair<Double, Double>> = emptyList()     private var keyframeTimeNs: Long = 0L      private val landmarks = ArrayList<Landmark>()@@ -145,50 +137,31 @@ class OpenCvVioEngine(private val intrinsics: Intrinsics) {         timestampNs: Long,     ): VioFrameResult {         framesSeen++-        val gray = grayMat(yPlane, width, height, rowStride)-        try {-            val prev = prevGray ?: return firstFrame(gray)-            val tracked = track(prev, gray, prevPoints)-            if (tracked == null || tracked.first.size < MIN_TRACKED_FOR_POSE) {-                return trackingFailure(gray, tracked?.first?.size ?: 0)-            }-            val (prevPts, currPts) = tracked-            val rel = recoverRelative(prevPts, currPts)-            if (rel == null) return poseFailure(gray, currPts)-            consecutiveFailures = 0-            worldFromCam = chainPose(worldFromCam, rel)-            updateKeyframes(prevPts, currPts, timestampNs)-            // Top features back up so slow attrition never starves the tracker.-            prevPoints = if (currPts.size < MAX_CORNERS / 2) {-                mergePoints(currPts, detect(gray))-            } else {-                currPts-            }-            prevGray?.release()-            prevGray = gray.clone()-            val q = when {-                scale == null -> TrackingQuality.Initialising-                currPts.size >= GOOD_TRACKED && landmarks.size >= GOOD_LANDMARKS ->-                    TrackingQuality.Good-                else -> TrackingQuality.Limited-            }-            return result(q, currPts.size)-        } finally {-            gray.release()+        val flow = MeasureCvNative.processFrame(nativeHandle, yPlane, width, height, rowStride)+            ?: return trackingFailure(0)+        if (flow.firstFrame) {+            return result(TrackingQuality.Initialising, flow.pointCount)         }+        if (flow.pairs.size < MIN_TRACKED_FOR_POSE) {+            return trackingFailure(flow.pairs.size)+        }+        val rel = flow.pose ?: return poseFailure(flow.pairs)+        consecutiveFailures = 0+        worldFromCam = chainPose(worldFromCam, rel)+        val prevPts = flow.pairs.map { it.prevX to it.prevY }+        val currPts = flow.pairs.map { it.currX to it.currY }+        updateKeyframes(prevPts, currPts, timestampNs)+        val q = when {+            scale == null -> TrackingQuality.Initialising+            currPts.size >= GOOD_TRACKED && landmarks.size >= GOOD_LANDMARKS ->+                TrackingQuality.Good+            else -> TrackingQuality.Limited+        }+        return result(q, currPts.size)     } -    private fun firstFrame(gray: Mat): VioFrameResult {-        prevPoints = detect(gray)-        prevGray = gray.clone()-        return result(TrackingQuality.Initialising, prevPoints.size)-    }--    private fun trackingFailure(gray: Mat, trackedCount: Int): VioFrameResult {+    private fun trackingFailure(trackedCount: Int): VioFrameResult {         consecutiveFailures++-        prevPoints = detect(gray)-        prevGray?.release()-        prevGray = gray.clone()         val q = when {             consecutiveFailures >= LOST_AFTER_FAILURES -> TrackingQuality.Lost             framesSeen < 30 -> TrackingQuality.Initialising@@ -197,22 +170,19 @@ class OpenCvVioEngine(private val intrinsics: Intrinsics) {         return result(q, trackedCount)     } -    private fun poseFailure(gray: Mat, currPts: List<Point>): VioFrameResult {+    private fun poseFailure(pairs: List<CvPair>): VioFrameResult {         consecutiveFailures++-        prevPoints = currPts-        prevGray?.release()-        prevGray = gray.clone()         return result(             if (consecutiveFailures >= LOST_AFTER_FAILURES) {                 TrackingQuality.Lost             } else {                 TrackingQuality.Limited             },-            currPts.size,+            pairs.size,         )     } -    private fun updateKeyframes(prevPts: List<Point>, currPts: List<Point>, timestampNs: Long) {+    private fun updateKeyframes(prevPts: List<Pair<Double, Double>>, currPts: List<Pair<Double, Double>>, timestampNs: Long) {         val kf = keyframePose         if (kf == null) {             setKeyframe(currPts, timestampNs)@@ -295,9 +265,7 @@ class OpenCvVioEngine(private val intrinsics: Intrinsics) {     }      fun reset() {-        prevGray?.release()-        prevGray = null-        prevPoints = emptyList()+        MeasureCvNative.reset(nativeHandle)         worldFromCam = Pose3.identity()         keyframePose = null         keyframePoints = emptyList()@@ -316,125 +284,10 @@ class OpenCvVioEngine(private val intrinsics: Intrinsics) {     }      fun close() {-        prevGray?.release()-        prevGray = null-    }--    // -- OpenCV stages ---------------------------------------------------    private fun grayMat(yPlane: ByteArray, width: Int, height: Int, rowStride: Int): Mat {-        val mat = Mat(height, width, CvType.CV_8UC1)-        if (rowStride == width) {-            mat.put(0, 0, yPlane, 0, width * height)-        } else {-            val row = ByteArray(width)-            for (r in 0 until height) {-                System.arraycopy(yPlane, r * rowStride, row, 0, width)-                mat.put(r, 0, row)-            }-        }-        return mat+        MeasureCvNative.destroySession(nativeHandle)     } -    private fun detect(gray: Mat): List<Point> {-        val corners = org.opencv.core.MatOfPoint()-        try {-            Imgproc.goodFeaturesToTrack(-                gray, corners, MAX_CORNERS, 0.01, 10.0, Mat(), 3, false, 0.04,-            )-            val rough = corners.toList()-            if (rough.isEmpty()) return emptyList()-            // The Java binding returns integer-quantised corners; refine-            // to sub-pixel before LK seeds from them.-            val refined = MatOfPoint2f(*rough.toTypedArray())-            try {-                Imgproc.cornerSubPix(-                    gray, refined, Size(5.0, 5.0), Size(-1.0, -1.0),-                    TermCriteria(TermCriteria.EPS or TermCriteria.COUNT, 30, 0.01),-                )-                return refined.toList()-            } finally {-                refined.release()-            }-        } finally {-            corners.release()-        }-    }--    /** LK tracking with forward-backward check; returns (prev, curr) survivors. */-    private fun track(prev: Mat, curr: Mat, points: List<Point>): Pair<List<Point>, List<Point>>? {-        if (points.isEmpty()) return null-        val prevMat = MatOfPoint2f(*points.toTypedArray())-        val currMat = MatOfPoint2f()-        val backMat = MatOfPoint2f()-        val status = MatOfByte()-        val err = MatOfFloat()-        val backStatus = MatOfByte()-        val backErr = MatOfFloat()-        val criteria = TermCriteria(TermCriteria.EPS or TermCriteria.COUNT, 30, 0.01)-        try {-            Video.calcOpticalFlowPyrLK(-                prev, curr, prevMat, currMat, status, err, Size(21.0, 21.0), 3, criteria,-            )-            Video.calcOpticalFlowPyrLK(-                curr, prev, currMat, backMat, backStatus, backErr, Size(21.0, 21.0), 3, criteria,-            )-            val st = status.toArray()-            val bst = backStatus.toArray()-            val currList = currMat.toList()-            val backList = backMat.toList()-            val outPrev = ArrayList<Point>()-            val outCurr = ArrayList<Point>()-            for (i in points.indices) {-                if (st[i].toInt() == 0 || bst[i].toInt() == 0) continue-                val fb = points[i].distanceTo(backList[i])-                if (fb > FB_ERROR_PX) continue-                outPrev += points[i]-                outCurr += currList[i]-            }-            return outPrev to outCurr-        } catch (e: org.opencv.core.CvException) {-            return null-        } finally {-            prevMat.release(); currMat.release(); backMat.release()-            status.release(); err.release(); backStatus.release(); backErr.release()-        }-    }--    /** Essential-matrix relative pose (A -> B), or null when degenerate. */-    private fun recoverRelative(prevPts: List<Point>, currPts: List<Point>): Pose3? {-        val k = Mat(3, 3, CvType.CV_64F)-        val p1 = MatOfPoint2f(*prevPts.toTypedArray())-        val p2 = MatOfPoint2f(*currPts.toTypedArray())-        val r = Mat()-        val t = Mat()-        val mask = Mat()-        try {-            k.put(0, 0, *cameraMatrix)-            val e = Calib3d.findEssentialMat(p1, p2, k, Calib3d.RANSAC, 0.999, 1.0)-            if (e.empty()) {-                e.release()-                return null-            }-            val inliers = Calib3d.recoverPose(e, p1, p2, k, r, t, mask)-            e.release()-            if (inliers < MIN_TRACKED_FOR_POSE || r.empty() || t.empty()) return null-            val rd = DoubleArray(9)-            r.get(0, 0, rd)-            val td = DoubleArray(3)-            t.get(0, 0, td)-            val tn = sqrt(td[0] * td[0] + td[1] * td[1] + td[2] * td[2])-            if (tn < 1e-9) return null-            // recoverPose translation is unit-length by construction.-            return Pose3(rd, Vec3(td[0] / tn, td[1] / tn, td[2] / tn))-        } catch (e: org.opencv.core.CvException) {-            return null-        } finally {-            k.release(); p1.release(); p2.release(); r.release(); t.release(); mask.release()-        }-    }--    private fun onKeyframe(prevKfPose: Pose3, currPts: List<Point>, timestampNs: Long) {+    private fun onKeyframe(prevKfPose: Pose3, currPts: List<Pair<Double, Double>>, timestampNs: Long) {         val kfPoints = keyframePoints         if (kfPoints.size >= MIN_TRACKED_FOR_POSE && currPts.size >= MIN_TRACKED_FOR_POSE) {             // Correspondences survived from the keyframe are the pairs LK@@ -445,8 +298,8 @@ class OpenCvVioEngine(private val intrinsics: Intrinsics) {             val pairs = minOf(kfPoints.size, currPts.size)             var added = 0             for (i in 0 until pairs) {-                val a = kfPoints[i].x to kfPoints[i].y-                val b = currPts[i].x to currPts[i].y+                val a = kfPoints[i]+                val b = currPts[i]                 val world = triangulate(pa, a, pb, b) ?: continue                 val errA = reprojectionErrorPx(pa, world, a)                 val errB = reprojectionErrorPx(pb, world, b)@@ -463,7 +316,7 @@ class OpenCvVioEngine(private val intrinsics: Intrinsics) {         }     } -    private fun setKeyframe(points: List<Point>, timestampNs: Long) {+    private fun setKeyframe(points: List<Pair<Double, Double>>, timestampNs: Long) {         keyframePose = worldFromCam         keyframePoints = points         keyframeTimeNs = timestampNs@@ -518,28 +371,18 @@ class OpenCvVioEngine(private val intrinsics: Intrinsics) {         return Vec3(worldDir.x / len, worldDir.y / len, worldDir.z / len)     } -    private fun meanFlow(a: List<Point>, b: List<Point>): Double {+    private fun meanFlow(a: List<Pair<Double, Double>>, b: List<Pair<Double, Double>>): Double {         if (a.isEmpty()) return 0.0         val n = minOf(a.size, b.size)         var sum = 0.0         for (i in 0 until n) sum += a[i].distanceTo(b[i])         return sum / n     }--    private fun mergePoints(tracked: List<Point>, fresh: List<Point>): List<Point> {-        val out = ArrayList(tracked)-        for (p in fresh) {-            if (out.any { it.distanceTo(p) < 10.0 }) continue-            out += p-            if (out.size >= MAX_CORNERS) break-        }-        return out-    } }  private operator fun Vec3.times(s: Double): Vec3 = Vec3(x * s, y * s, z * s)-private fun Point.distanceTo(other: Point): Double {-    val dx = x - other.x-    val dy = y - other.y+private fun Pair<Double, Double>.distanceTo(other: Pair<Double, Double>): Double {+    val dx = first - other.first+    val dy = second - other.second     return sqrt(dx * dx + dy * dy) }
measure/src/main/java/com/vayunmathur/measure/ui/ArMeasurePage.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasurePage.kt b/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasurePage.ktindex 26eb4b0cc9..233931dd31 100644--- a/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasurePage.kt+++ b/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasurePage.kt@@ -22,10 +22,10 @@ import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.ui.rememberPermissionRequest import com.vayunmathur.measure.Route import com.vayunmathur.measure.domain.ArUnavailableReason-import com.vayunmathur.measure.platform.opencv.OpenCvVioEngine+import com.vayunmathur.measure.platform.vio.VioEngine import com.vayunmathur.measure.platform.CameraIntrinsicsResolver import com.vayunmathur.measure.platform.MeasureViewModel-import com.vayunmathur.measure.platform.OpenCvArHitProvider+import com.vayunmathur.measure.platform.VioArHitProvider import com.vayunmathur.measure.platform.updateDiagnosticsImpl import com.vayunmathur.measure.ui.components.MeasureBottomBar import com.vayunmathur.measure.ui.components.ANALYSIS_SIZE@@ -35,7 +35,7 @@ import kotlinx.coroutines.delay @Composable fun ArMeasurePage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) {     val state by viewModel.ar.collectAsState()-    var engine by remember { mutableStateOf<OpenCvVioEngine?>(null) }+    var engine by remember { mutableStateOf<VioEngine?>(null) }     var screenPoints by remember { mutableStateOf<List<Offset?>>(emptyList()) }     var canvasSize by remember { mutableStateOf(Size.Zero) }     val context = LocalContext.current@@ -47,7 +47,7 @@ fun ArMeasurePage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) {     // would otherwise coach "move your phone" forever (the old flow     // never called timestampsAlignWithSensors at all).     LaunchedEffect(Unit) {-        viewModel.hitProvider = OpenCvArHitProvider(+        viewModel.hitProvider = VioArHitProvider(             engine = { engine },             analysisWidth = ANALYSIS_SIZE.width,             analysisHeight = ANALYSIS_SIZE.height,@@ -108,7 +108,7 @@ fun ArMeasurePage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) {         screenPoints = screenPoints,         onCanvasSized = { canvasSize = it },         cameraContent = {-            if (cameraGranted && OpenCvVioEngine.available) {+            if (cameraGranted && VioEngine.available) {                 MeasureCamera(                     imuRecorder = viewModel.imuRecorder,                     onTrackingUpdate = { q, hasPlane ->@@ -128,7 +128,7 @@ fun ArMeasurePage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) {                                 featureCount = tracked,                                 landmarkCount = landmarks,                                 scaleConfidence = confidence,-                                nativeEngineAvailable = OpenCvVioEngine.available,+                                nativeEngineAvailable = VioEngine.available,                             )                         }                     },@@ -144,7 +144,7 @@ fun ArMeasurePage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) {  /** Explicit availability states, checked once before the session starts. */ private fun availabilityReason(context: Context): ArUnavailableReason? {-    if (!OpenCvVioEngine.available) return ArUnavailableReason.NativeEngineMissing+    if (!VioEngine.available) return ArUnavailableReason.NativeEngineMissing     val sensors = context.getSystemService(Context.SENSOR_SERVICE) as? SensorManager         ?: return ArUnavailableReason.MotionSensorsMissing     val hasGyro = sensors.getDefaultSensor(Sensor.TYPE_GYROSCOPE_UNCALIBRATED) != null ||
measure/src/main/java/com/vayunmathur/measure/ui/components/MeasureCamera.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/components/MeasureCamera.kt b/measure/src/main/java/com/vayunmathur/measure/ui/components/MeasureCamera.ktindex 1abaaedc8d..1e3ae3f517 100644--- a/measure/src/main/java/com/vayunmathur/measure/ui/components/MeasureCamera.kt+++ b/measure/src/main/java/com/vayunmathur/measure/ui/components/MeasureCamera.kt@@ -25,7 +25,7 @@ import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.repeatOnLifecycle import com.vayunmathur.measure.data.model.TrackingQuality import com.vayunmathur.measure.platform.CameraIntrinsicsResolver-import com.vayunmathur.measure.platform.opencv.OpenCvVioEngine+import com.vayunmathur.measure.platform.vio.VioEngine import com.vayunmathur.measure.platform.sensor.ImuRecorder import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.flow.MutableStateFlow@@ -41,7 +41,7 @@ typealias Diagnostics = (Double, Double, Double, Int, Int, Double) -> Unit internal val ANALYSIS_SIZE = Size(640, 480)  /**- * Camera viewfinder plus the frame pump that drives the OpenCV tracker.+ * Camera viewfinder plus the frame pump that drives the Rust VIO tracker.  *  * The analyser hands the Y plane straight to the engine. No Bitmap is  * allocated and no colour conversion happens: tracking only needs@@ -52,7 +52,7 @@ internal val ANALYSIS_SIZE = Size(640, 480) fun MeasureCamera(     imuRecorder: ImuRecorder,     onTrackingUpdate: (quality: TrackingQuality, hasPlane: Boolean) -> Unit,-    onEngineReady: (engine: OpenCvVioEngine?) -> Unit,+    onEngineReady: (engine: VioEngine?) -> Unit,     modifier: Modifier = Modifier,     onDiagnostics: Diagnostics = { _, _, _, _, _, _ -> }, ) {@@ -93,11 +93,16 @@ fun MeasureCamera(                     .also {                         it.setAnalyzer(                             executor,-                            OpenCvFrameAnalyzer(engine, imuRecorder, onTrackingUpdate, onDiagnostics),+                            VioFrameAnalyzer(engine, imuRecorder, onTrackingUpdate, onDiagnostics),                         )                     } -                imuRecorder.start()+                // Without live IMU the visual tracker can never lock metric+                // scale. Report Limited (the flow's Scanning state) instead of+                // letting a refused high-rate registration crash the session.+                if (!imuRecorder.start()) {+                    onTrackingUpdate(TrackingQuality.Limited, false)+                }                 provider.bindToLifecycle(                     lifecycleOwner,                     CameraSelector.DEFAULT_BACK_CAMERA,@@ -121,14 +126,14 @@ fun MeasureCamera(     } } -private fun createEngine(context: Context): OpenCvVioEngine? {-    if (!OpenCvVioEngine.available) return null+private fun createEngine(context: Context): VioEngine? {+    if (!VioEngine.available) return null     val intr = CameraIntrinsicsResolver.resolve(context, ANALYSIS_SIZE) ?: return null-    return OpenCvVioEngine(intr)+    return VioEngine(intr) } -internal class OpenCvFrameAnalyzer(-    private val engine: OpenCvVioEngine?,+internal class VioFrameAnalyzer(+    private val engine: VioEngine?,     private val imuRecorder: ImuRecorder,     private val onTrackingUpdate: (TrackingQuality, Boolean) -> Unit,     private val onDiagnostics: Diagnostics,@@ -161,7 +166,15 @@ internal class OpenCvFrameAnalyzer(                 rowStride = plane.rowStride,                 timestampNs = tNs,             )-            onTrackingUpdate(result.quality, result.hasPlane)+            // Cap at Limited while the IMU is down: visual tracking may run,+            // but with no IMU windows the metric scale cannot lock, so Good+            // (the only state that allows placing anchors) must not be quoted.+            val quality = if (!imuRecorder.isActive && result.quality != TrackingQuality.Lost) {+                TrackingQuality.Limited+            } else {+                result.quality+            }+            onTrackingUpdate(quality, result.hasPlane)              if (lastFrameNs != 0L) {                 frameIntervalNs = (frameIntervalNs * 3 + (tNs - lastFrameNs)) / 4
measure/src/main/rust/Cargo.toml
diff --git a/measure/src/main/rust/Cargo.toml b/measure/src/main/rust/Cargo.tomlindex 872af962e0..233e04517e 100644--- a/measure/src/main/rust/Cargo.toml+++ b/measure/src/main/rust/Cargo.toml@@ -1,12 +1,12 @@ [package]-name = "measure_vio"+name = "measure_cv" version = "0.1.0" edition = "2021"-description = "Monocular visual-inertial odometry for the measure app: metric-scale camera tracking from camera frames plus IMU, via JNI"+description = "Per-frame computer vision for the measure app's visual-inertial tracker: Shi-Tomasi corners, pyramidal Lucas-Kanade tracking and essential-matrix pose recovery, via JNI. Geometry above the correspondences (triangulation, plane fit, IMU scale) stays in Kotlin." license = "GPL-2.0-only"  [lib]-name = "measure_vio"+name = "measure_cv" crate-type = ["cdylib", "rlib"]  [dependencies]
measure/src/main/rust/src/align.rs
diff --git a/measure/src/main/rust/src/align.rs b/measure/src/main/rust/src/align.rsdeleted file mode 100644index 5c3c749871..0000000000--- a/measure/src/main/rust/src/align.rs+++ /dev/null@@ -1,348 +0,0 @@-//! Visual-inertial alignment: recovering **metric scale** and gravity.-//!-//! This is the crux of the whole app. A monocular camera reconstructs geometry only-//! up to an unknown scale factor `s`: a small room close up and a large room far away-//! produce identical images. Measuring in metres therefore requires an external-//! reference for length, and the accelerometer is it — gravity has a known magnitude-//! and the double-integrated specific force has real units.-//!-//! Given keyframe rotations (metric, orientation is directly observable) and camera-//! positions known only up to `s`, the IMU preintegration between consecutive-//! keyframes gives, for each interval `i`:-//!-//! ```text-//! s·(p_{i+1} − p_i) = R_i·Δp_i + v_i·Δt_i + ½·g·Δt_i²-//! s·(velocity change)  ⇒  R_i·Δv_i = v_{i+1} − v_i + g·Δt_i-//! ```-//!-//! Both are **linear** in the unknowns `(s, g, v_0..v_n)`, so the whole thing is one-//! least-squares solve rather than a nonlinear optimisation. This mirrors the linear-//! initialisation stage used by VINS-Mono.-//!-//! The solve is only well-conditioned when the device genuinely translated. Under pure-//! rotation every `p_i` is identical, the `s` column becomes zero, and scale is-//! unrecoverable — which is exactly why the UI has to coach a sideways motion.--use crate::preintegrate::{Preintegrated, GRAVITY};-use vision_core::linalg::{DMatrix, DVector, Matrix3, Vector3};--/// One keyframe's visual pose. `position` carries the arbitrary visual scale;-/// `rotation` is body-to-world and is already metric.-#[derive(Clone, Debug)]-pub struct KeyframePose {-    pub rotation: Matrix3<f64>,-    pub position: Vector3<f64>,-}--#[derive(Clone, Debug)]-pub struct AlignmentResult {-    /// Multiply any visual length by this to get metres.-    pub scale: f64,-    /// Gravity in the visual world frame, magnitude ~9.81.-    pub gravity: Vector3<f64>,-    pub velocities: Vec<Vector3<f64>>,-    /// 0..1 heuristic; below ~0.3 the estimate should not be shown to the user.-    pub confidence: f64,-}--/// Solve for scale, gravity and per-keyframe velocity.-///-/// `poses[i]` and `imu[i]` must line up such that `imu[i]` covers the interval from-/// keyframe `i` to `i+1`, so `imu.len() == poses.len() - 1`.-pub fn align_visual_inertial(-    poses: &[KeyframePose],-    imu: &[Preintegrated],-) -> Option<AlignmentResult> {-    let n = poses.len();-    if n < 3 || imu.len() + 1 != n {-        return None;-    }--    // Unknowns: [v_0 (3), v_1 (3), ..., v_{n-1} (3), g (3), s (1)]-    let n_unknowns = 3 * n + 4;-    let n_rows = 6 * (n - 1);-    if n_rows < n_unknowns {-        return None;-    }--    let mut a = DMatrix::<f64>::zeros(n_rows, n_unknowns);-    let mut b = DVector::zeros(n_rows);-    let g_col = 3 * n;-    let s_col = 3 * n + 3;--    for i in 0..(n - 1) {-        let pre = &imu[i];-        let dt = pre.dt;-        if dt <= 0.0 {-            return None;-        }-        let r_i = &poses[i].rotation;-        let dp = poses[i + 1].position - poses[i].position;--        // --- Position rows ----        // s·dp − v_i·Δt − ½·g·Δt² = R_i·Δp-        let row = 6 * i;-        for k in 0..3 {-            a[(row + k, 3 * i + k)] = -dt;-            a[(row + k, g_col + k)] = -0.5 * dt * dt;-            a[(row + k, s_col)] = dp[k];-        }-        let rdp = r_i * pre.delta_p;-        for k in 0..3 {-            b[row + k] = rdp[k];-        }--        // --- Velocity rows ----        // v_{i+1} − v_i − g·Δt = R_i·Δv-        let row = 6 * i + 3;-        for k in 0..3 {-            a[(row + k, 3 * i + k)] = -1.0;-            a[(row + k, 3 * (i + 1) + k)] = 1.0;-            a[(row + k, g_col + k)] = -dt;-        }-        let rdv = r_i * pre.delta_v;-        for k in 0..3 {-            b[row + k] = rdv[k];-        }-    }--    let x = solve_least_squares(&a, &b, n_rows, n_unknowns)?;--    let scale = x[s_col];-    let gravity = Vector3::new(x[g_col], x[g_col + 1], x[g_col + 2]);--    // A negative or wildly small scale means the geometry was degenerate, most often-    // because the user only rotated the phone.-    if !(scale.is_finite() && scale > 1e-4) {-        return None;-    }--    let velocities = (0..n)-        .map(|i| Vector3::new(x[3 * i], x[3 * i + 1], x[3 * i + 2]))-        .collect();--    // Gravity magnitude is the honest self-check: nothing in the solve forces it, so-    // how close it lands to 9.81 says how much the rest can be trusted.-    let g_err = (gravity.norm() - GRAVITY).abs() / GRAVITY;-    let confidence = (1.0 - g_err * 2.0).clamp(0.0, 1.0);--    Some(AlignmentResult { scale, gravity, velocities, confidence })-}--/// Normal-equations least squares: solve `AᵀA x = Aᵀb`.-///-/// The system is small (a dozen keyframes is ~40 unknowns) and reasonably conditioned-/// once there is real translation, so the squared condition number of the normal-/// equations is acceptable here and avoids implementing a dense QR.-fn solve_least_squares(-    a: &DMatrix<f64>,-    b: &DVector<f64>,-    rows: usize,-    cols: usize,-) -> Option<DVector<f64>> {-    let mut ata = DMatrix::<f64>::zeros(cols, cols);-    let mut atb = DVector::zeros(cols);--    for i in 0..cols {-        for j in i..cols {-            let mut sum = 0.0;-            for k in 0..rows {-                sum += a[(k, i)] * a[(k, j)];-            }-            ata[(i, j)] = sum;-            ata[(j, i)] = sum;-        }-        let mut sum = 0.0;-        for k in 0..rows {-            sum += a[(k, i)] * b[k];-        }-        atb[i] = sum;-    }--    // Tikhonov nudge: keeps the solve from blowing up when a direction is barely-    // excited (e.g. almost no motion along one axis) without biasing a good solve.-    for i in 0..cols {-        ata[(i, i)] += 1e-9;-    }--    ata.lu().solve(&atb)-}--/// Refine gravity by projecting it back onto the sphere of radius `GRAVITY`.-///-/// The linear solve treats gravity's three components as free, so the result is close-/// to but not exactly 9.81 m/s². Renormalising trades a little least-squares optimality-/// for a physically valid vector.-pub fn refine_gravity(g: Vector3<f64>) -> Vector3<f64> {-    let n = g.norm();-    if n < 1e-9 {-        return Vector3::new(0.0, 0.0, -GRAVITY);-    }-    g * (GRAVITY / n)-}--#[cfg(test)]-mod tests {-    use super::*;-    use crate::preintegrate::{preintegrate, ImuSample};-    use vision_core::camera::rodrigues_to_mat;--    /// Simulate a device that both translates and rotates, and return the visual-    /// poses (positions divided by `true_scale`, as a monocular reconstruction would-    /// give them) alongside the IMU preintegration for each interval.-    ///-    /// Rotation matters: with a fixed attitude, a constant linear acceleration and a-    /// tilted gravity vector produce identical accelerometer readings, so gravity and-    /// acceleration cannot be separated and scale comes out wrong. Rotating the device-    /// changes how gravity projects into the body frame and breaks that ambiguity.-    /// This is why real VIO initialisation asks the user to move *and* turn the phone.-    fn simulate(-        true_scale: f64,-        duration: f64,-        n_keyframes: usize,-        rotate: bool,-    ) -> (Vec<KeyframePose>, Vec<Preintegrated>) {-        let gravity_world = Vector3::new(0.0, 0.0, -GRAVITY);-        let imu_rate = 400.0;-        let dt = 1.0 / imu_rate;--        // Sideways sinusoidal sweep: gives genuine, varying parallax.-        let amp = 0.15;-        let omega = 2.0 * std::f64::consts::PI / duration;-        let pos_at = |t: f64| Vector3::new(amp * (omega * t).sin(), 0.0, 0.0);-        let acc_at = |t: f64| Vector3::new(-amp * omega * omega * (omega * t).sin(), 0.0, 0.0);--        // Gentle yaw sweep about the body Y axis.-        let rot_rate = if rotate { 0.6 } else { 0.0 };-        let axis = Vector3::new(0.0, 1.0, 0.0);-        let rot_at = |t: f64| rodrigues_to_mat(axis * (rot_rate * t));--        let seg = duration / (n_keyframes - 1) as f64;--        let poses: Vec<KeyframePose> = (0..n_keyframes)-            .map(|k| {-                let t = k as f64 * seg;-                KeyframePose {-                    rotation: rot_at(t),-                    position: pos_at(t) / true_scale,-                }-            })-            .collect();--        let mut pres = Vec::new();-        for k in 0..(n_keyframes - 1) {-            let t0 = k as f64 * seg;-            let n = (seg * imu_rate).round() as usize + 1;-            let samples: Vec<ImuSample> = (0..n)-                .map(|i| {-                    let t = t0 + i as f64 * dt;-                    let r = rot_at(t);-                    // Accelerometer reads specific force in the body frame.-                    let f_world = acc_at(t) - gravity_world;-                    let f_body = r.transpose() * f_world;-                    ImuSample {-                        t_ns: (t * 1e9).round() as i64,-                        gyro: axis * rot_rate,-                        accel: f_body,-                    }-                })-                .collect();-            // Raw specific-force integral: the solver cancels gravity itself.-            pres.push(preintegrate(&samples, Vector3::zeros(), Vector3::zeros()));-        }-        (poses, pres)-    }--    #[test]-    fn recovers_a_known_scale_factor() {-        let true_scale = 3.0;-        let (poses, imu) = simulate(true_scale, 1.5, 10, true);-        let r = align_visual_inertial(&poses, &imu).expect("alignment");-        assert!(-            (r.scale - true_scale).abs() / true_scale < 0.10,-            "scale {} should be near {true_scale}",-            r.scale-        );-    }--    #[test]-    fn recovered_scale_is_independent_of_the_hidden_factor() {-        // Whatever arbitrary scale the visual reconstruction happened to pick, the-        // aligner should undo exactly it.-        for &s_true in &[0.5, 2.0, 7.5] {-            let (poses, imu) = simulate(s_true, 1.5, 10, true);-            let r = align_visual_inertial(&poses, &imu)-                .unwrap_or_else(|| panic!("alignment failed for scale {s_true}"));-            assert!(-                (r.scale - s_true).abs() / s_true < 0.10,-                "scale {} should be near {s_true}",-                r.scale-            );-        }-    }--    #[test]-    fn recovers_gravity_direction() {-        let (poses, imu) = simulate(2.0, 1.5, 10, true);-        let r = align_visual_inertial(&poses, &imu).expect("alignment");-        let g = refine_gravity(r.gravity);-        assert!((g.norm() - GRAVITY).abs() < 1e-6);-        assert!(-            g[2] < -GRAVITY * 0.9,-            "gravity should point down, got {:?}",-            (g[0], g[1], g[2])-        );-    }--    #[test]-    fn reports_high_confidence_for_a_well_excited_trajectory() {-        let (poses, imu) = simulate(2.0, 1.5, 10, true);-        let r = align_visual_inertial(&poses, &imu).expect("alignment");-        assert!(r.confidence > 0.8, "confidence was {}", r.confidence);-    }--    #[test]-    fn rejects_a_stationary_sequence() {-        // No translation at all: scale is unobservable and the solve must decline-        // rather than return a confident nonsense number.-        let n = 6;-        let poses: Vec<KeyframePose> = (0..n)-            .map(|_| KeyframePose {-                rotation: Matrix3::identity(),-                position: Vector3::zeros(),-            })-            .collect();-        let gravity_world = Vector3::new(0.0, 0.0, -GRAVITY);-        let imu: Vec<Preintegrated> = (0..(n - 1))-            .map(|k| {-                let samples: Vec<ImuSample> = (0..101)-                    .map(|i| ImuSample {-                        t_ns: ((k as f64 * 0.25 + i as f64 / 400.0) * 1e9) as i64,-                        gyro: Vector3::zeros(),-                        accel: -gravity_world,-                    })-                    .collect();-                preintegrate(&samples, Vector3::zeros(), Vector3::zeros())-            })-            .collect();--        let r = align_visual_inertial(&poses, &imu);-        assert!(-            r.is_none() || r.unwrap().scale < 1e-2,-            "a stationary sequence must not yield a usable scale"-        );-    }--    #[test]-    fn rejects_too_few_keyframes() {-        let (poses, imu) = simulate(2.0, 0.4, 2, true);-        assert!(align_visual_inertial(&poses, &imu).is_none());-    }--    #[test]-    fn refine_gravity_normalises_magnitude() {-        let g = refine_gravity(Vector3::new(0.0, 0.0, -5.0));-        assert!((g.norm() - GRAVITY).abs() < 1e-9);-        assert!(g[2] < 0.0);-    }-}
measure/src/main/rust/src/corners.rs
diff --git a/measure/src/main/rust/src/corners.rs b/measure/src/main/rust/src/corners.rsnew file mode 100644index 0000000000..427ff81905--- /dev/null+++ b/measure/src/main/rust/src/corners.rs@@ -0,0 +1,229 @@+//! Shi-Tomasi corner detection ("good features to track") with sub-pixel refinement.+//!+//! The score is the smaller eigenvalue of the 3x3 structure tensor: a point only+//! scores well when intensity varies along two independent directions, which is+//! exactly the property the Lucas-Kanade tracker needs (a straight edge has one+//! near-zero eigenvalue and slides along itself — the aperture problem).+//!+//! Mirrors the parameters the tracker was tuned against: quality level 0.01 of+//! the frame's best score, at most [`MAX_CORNERS`] corners, [`MIN_DISTANCE_PX`]+//! minimum separation.++use vision_core::imgbuf::Gray;++pub const MAX_CORNERS: usize = 220;+const MIN_DISTANCE_PX: f32 = 10.0;+const QUALITY_LEVEL: f32 = 0.01;+/// Pixels excluded at the frame edge: the LK window (half-width 7) plus the+/// pyramid's coarsest level must stay inside the frame.+const BORDER: usize = 10;++/// Detect up to [`MAX_CORNERS`] corners, strongest first, refined to sub-pixel.+pub fn detect(gray: &Gray) -> Vec<(f32, f32)> {+    if gray.w < 2 * BORDER + 8 || gray.h < 2 * BORDER + 8 {+        return Vec::new();+    }+    let (w, h) = (gray.w, gray.h);+    // Central-difference gradients.+    let mut ix = vec![0f32; w * h];+    let mut iy = vec![0f32; w * h];+    for y in 1..h - 1 {+        for x in 1..w - 1 {+            let i = y * w + x;+            ix[i] = (gray.px[i + 1] as f32 - gray.px[i - 1] as f32) * 0.5;+            iy[i] = (gray.px[i + w] as f32 - gray.px[i - w] as f32) * 0.5;+        }+    }+    // Smaller structure-tensor eigenvalue per pixel (3x3 tensor window).+    let mut score = vec![0f32; w * h];+    let mut best = 0f32;+    for y in BORDER..h - BORDER {+        for x in BORDER..w - BORDER {+            let (mut sxx, mut sxy, mut syy) = (0f32, 0f32, 0f32);+            for dy in -1i32..=1 {+                for dx in -1i32..=1 {+                    let i = ((y as i32 + dy) as usize) * w + (x as i32 + dx) as usize;+                    sxx += ix[i] * ix[i];+                    sxy += ix[i] * iy[i];+                    syy += iy[i] * iy[i];+                }+            }+            let half_trace = (sxx + syy) * 0.5;+            let disc = ((half_trace * half_trace - (sxx * syy - sxy * sxy)).max(0.0)).sqrt();+            let s = half_trace - disc;+            score[y * w + x] = s;+            if s > best {+                best = s;+            }+        }+    }+    if best <= 0.0 {+        return Vec::new();+    }+    let threshold = best * QUALITY_LEVEL;+    let mut candidates: Vec<(f32, usize)> = Vec::new();+    for y in BORDER..h - BORDER {+        for x in BORDER..w - BORDER {+            let s = score[y * w + x];+            if s > threshold {+                candidates.push((s, y * w + x));+            }+        }+    }+    candidates.sort_by(|a, b| b.0.total_cmp(&a.0));++    // Greedy non-maximum suppression by minimum separation.+    let mut accepted: Vec<(f32, f32)> = Vec::new();+    'outer: for (_, idx) in candidates {+        let x = (idx % w) as f32;+        let y = (idx / w) as f32;+        for &(ax, ay) in &accepted {+            let dx = ax - x;+            let dy = ay - y;+            if dx * dx + dy * dy < MIN_DISTANCE_PX * MIN_DISTANCE_PX {+                continue 'outer;+            }+        }+        accepted.push((x, y));+        if accepted.len() >= MAX_CORNERS {+            break;+        }+    }+    accepted+        .iter()+        .map(|&(x, y)| refine_subpixel(gray, &ix, &iy, x, y))+        .collect()+}++/// Iterative sub-pixel refinement: the corner is where every gradient in the+/// window is orthogonal to the offset from the corner, i.e. solve+/// `(sum g g^T) p = sum (g g^T) q` over the 5x5 window and iterate.+fn refine_subpixel(gray: &Gray, ix: &[f32], iy: &[f32], x: f32, y: f32) -> (f32, f32) {+    let (w, h) = (gray.w as i32, gray.h as i32);+    let (mut px, mut py) = (x, y);+    for _ in 0..10 {+        let (cx, cy) = (px.round() as i32, py.round() as i32);+        let (mut a00, mut a01, mut a11, mut b0, mut b1) = (0f32, 0f32, 0f32, 0f32, 0f32);+        for dy in -2..=2i32 {+            for dx in -2..=2i32 {+                let (qx, qy) = (cx + dx, cy + dy);+                if qx < 1 || qy < 1 || qx >= w - 1 || qy >= h - 1 {+                    continue;+                }+                let i = (qy as usize) * gray.w + qx as usize;+                let (gx, gy) = (ix[i], iy[i]);+                a00 += gx * gx;+                a01 += gx * gy;+                a11 += gy * gy;+                let d = gx * qx as f32 + gy * qy as f32;+                b0 += gx * d;+                b1 += gy * d;+            }+        }+        let det = a00 * a11 - a01 * a01;+        if det.abs() < 1e-6 {+            break;+        }+        let nx = (a11 * b0 - a01 * b1) / det;+        let ny = (a00 * b1 - a01 * b0) / det;+        let moved = (nx - px).abs().max((ny - py).abs());+        px = nx.clamp(0.0, (w - 1) as f32);+        py = ny.clamp(0.0, (h - 1) as f32);+        if moved < 0.05 {+            break;+        }+    }+    // Refinement is a local correction: a result far from the detected grid+    // point means the window held no well-defined corner, so keep the+    // original integer location rather than a wandered one.+    if (px - x).abs() > 2.0 || (py - y).abs() > 2.0 {+        return (x, y);+    }+    (px, py)+}++#[cfg(test)]+mod tests {+    use super::*;++    /// Textured synthetic frame: overlapping sinusoids, corners everywhere.+    fn textured(w: usize, h: usize) -> Gray {+        let mut g = Gray::new(w, h);+        for y in 0..h {+            for x in 0..w {+                let v = ((x as f32 * 0.31).sin() * (y as f32 * 0.23).cos()+                    + (x as f32 * 0.11 + y as f32 * 0.17).sin())+                    * 60.0+                    + 128.0;+                g.px[y * w + x] = v.clamp(0.0, 255.0) as u8;+            }+        }+        g+    }++    #[test]+    fn detects_corners_on_a_textured_pattern() {+        let g = textured(320, 240);+        let pts = detect(&g);+        assert!(pts.len() >= 20, "expected many corners, got {}", pts.len());+        assert!(pts.len() <= MAX_CORNERS);+        for &(x, y) in &pts {+            assert!(x >= 0.0 && x < 320.0 && y >= 0.0 && y < 240.0);+        }+        // Sub-pixel refinement should move some points off the integer grid+        // (its accuracy is asserted directly by the square-corner test).+        let refined = pts.iter().filter(|&&(x, y)| x.fract() != 0.0 || y.fract() != 0.0).count();+        assert!(refined > 0, "no point was refined sub-pixel");+        // Minimum separation holds at detection; sub-pixel refinement may+        // then move a point by a pixel or so, so allow that slack.+        for i in 0..pts.len() {+            for j in i + 1..pts.len() {+                let dx = pts[i].0 - pts[j].0;+                let dy = pts[i].1 - pts[j].1;+                assert!(dx * dx + dy * dy >= 64.0, "corners too close");+            }+        }+    }++    #[test]+    fn finds_the_corner_of_a_synthetic_square() {+        // White square on black: its four corners must be found near the truth.+        let mut g = Gray::new(200, 200);+        for y in 60..140 {+            for x in 70..150 {+                g.px[y * 200 + x] = 255;+            }+        }+        let pts = detect(&g);+        let truth = [(70.0, 60.0), (149.0, 60.0), (70.0, 139.0), (149.0, 139.0)];+        for (tx, ty) in truth {+            let near = pts+                .iter()+                .any(|&(x, y)| (x - tx).abs() < 3.0 && (y - ty).abs() < 3.0);+            assert!(near, "no corner near ({tx},{ty}); got {pts:?}");+        }+    }++    #[test]+    fn a_flat_frame_has_no_corners() {+        let mut g = Gray::new(160, 120);+        for v in g.px.iter_mut() {+            *v = 90;+        }+        assert!(detect(&g).is_empty());+    }++    #[test]+    fn a_pure_edge_is_not_a_corner() {+        // Vertical step edge only: one gradient direction, eigenvalue ~0.+        let mut g = Gray::new(160, 120);+        for y in 0..120 {+            for x in 80..160 {+                g.px[y * 160 + x] = 255;+            }+        }+        let pts = detect(&g);+        assert!(pts.len() < 8, "edge should yield almost no corners, got {}", pts.len());+    }+}+
measure/src/main/rust/src/lib.rs
diff --git a/measure/src/main/rust/src/lib.rs b/measure/src/main/rust/src/lib.rsindex 1aaa74d3e1..71bec343c9 100644--- a/measure/src/main/rust/src/lib.rs+++ b/measure/src/main/rust/src/lib.rs@@ -1,35 +1,202 @@-//! Monocular visual-inertial odometry for the measure app.+//! Per-frame computer vision for the measure app's visual-inertial tracker. //!-//! Recovers **metric** camera motion from the rear camera plus the IMU, which is what-//! lets a tapped screen point become a real distance in metres. The camera alone can-//! only ever produce a reconstruction up to an unknown scale factor; the accelerometer-//! supplies the missing metre.+//! Our own Rust CV core, following the camera app's stitching precedent+//! (`camera/src/main/rust` + the shared `vision_core` primitives): no+//! third-party native CV library ships in the APK, so there is no+//! 4 KB-aligned prebuilt to fail on 16 KB-page devices — the `.so` is+//! linked by our own NDK toolchain, which emits 16 KB-aligned segments.+//!+//! Scope is deliberately the per-frame image work only: Shi-Tomasi corner+//! detection ([`corners`]), pyramidal Lucas-Kanade tracking with a+//! forward-backward consistency check ([`klt`]), and essential-matrix+//! pose recovery (normalised eight-point + RANSAC + cheirality,+//! [`epipolar`]). Everything above that — pose chaining, landmark+//! triangulation, plane fitting, IMU scale fusion, quality gating —+//! stays in Kotlin (`domain/VioMath.kt` and the engine that consumes+//! this crate), where it is unit-tested pure geometry. -pub mod align;+pub mod corners; pub mod epipolar; pub mod klt;-pub mod plane;-pub mod preintegrate;-pub mod triangulate;-pub mod vio; -// Not cfg-gated to Android: the host build must export the same JNI symbols or-// MeasureNative.available lies in JVM tests (library loads, every call throws).+use epipolar::{recover_pose, RelPose};+use klt::Pyramid;+use vision_core::imgbuf::Gray;++const PYRAMID_LEVELS: usize = 3;+/// Forward-backward check tolerance, in pixels (matches the tuned tracker).+const FB_MAX_ERROR_PX: f32 = 1.5;+/// Essential-matrix RANSAC iterations.+const ESSENTIAL_ITERS: usize = 200;+/// RANSAC inlier threshold in pixels, converted to calibrated units per frame.+const ESSENTIAL_THRESH_PX: f64 = 1.0;++/// One tracked correspondence, in pixels: previous -> current.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct TrackPair {+    pub prev: (f64, f64),+    pub curr: (f64, f64),+}++/// Result of processing one frame.+pub struct FrameFlow {+    /// True on the first frame of a session (points seeded, no motion yet).+    pub first_frame: bool,+    /// Tracked (and, when a pose was recovered, RANSAC-inlier) correspondences.+    pub pairs: Vec<TrackPair>,+    /// Relative pose previous -> current, `X_curr = R * X_prev + t`, unit `t`.+    pub pose: Option<RelPose>,+    /// Feature points seeded for the next frame, after top-up.+    pub point_count: usize,+}++struct Intrinsics {+    fx: f64,+    fy: f64,+    cx: f64,+    cy: f64,+}++/// A tracking session: previous frame + its feature points, nothing more.+/// All estimator state above the correspondences lives in Kotlin.+pub struct CvSession {+    intr: Intrinsics,+    prev_gray: Option<Gray>,+    prev_points: Vec<(f32, f32)>,+}++impl CvSession {+    pub fn new(fx: f64, fy: f64, cx: f64, cy: f64) -> CvSession {+        CvSession {+            intr: Intrinsics { fx, fy, cx, cy },+            prev_gray: None,+            prev_points: Vec::new(),+        }+    }++    pub fn reset(&mut self) {+        self.prev_gray = None;+        self.prev_points = Vec::new();+    }++    pub fn process_frame(&mut self, gray: &Gray) -> FrameFlow {+        let prev_gray = match self.prev_gray.take() {+            Some(p) if p.w == gray.w && p.h == gray.h => p,+            _ => {+                let pts = corners::detect(gray);+                let count = pts.len();+                self.prev_points = pts;+                self.prev_gray = Some(gray.clone());+                return FrameFlow {+                    first_frame: true,+                    pairs: Vec::new(),+                    pose: None,+                    point_count: count,+                };+            }+        };++        let prev_pyr = Pyramid::build(&prev_gray, PYRAMID_LEVELS);+        let curr_pyr = Pyramid::build(gray, PYRAMID_LEVELS);+        let forward = klt::track(&prev_pyr, &curr_pyr, &self.prev_points);+        let candidates: Vec<(f32, f32)> = forward+            .iter()+            .filter(|r| r.ok)+            .map(|r| (r.x, r.y))+            .collect();+        let backward = klt::track(&curr_pyr, &prev_pyr, &candidates);++        // Forward-backward check: a point that does not track back to where+        // it started (within tolerance) was never really tracked.+        let mut pairs: Vec<TrackPair> = Vec::new();+        let mut cand_idx = 0usize;+        for (i, f) in forward.iter().enumerate() {+            if !f.ok {+                continue;+            }+            let b = &backward[cand_idx];+            cand_idx += 1;+            if !b.ok {+                continue;+            }+            let (ox, oy) = self.prev_points[i];+            let dx = b.x - ox;+            let dy = b.y - oy;+            if dx * dx + dy * dy > FB_MAX_ERROR_PX * FB_MAX_ERROR_PX {+                continue;+            }+            pairs.push(TrackPair {+                prev: (ox as f64, oy as f64),+                curr: (f.x as f64, f.y as f64),+            });+        }++        // Essential pose on calibrated bearings; keep only RANSAC inliers+        // as correspondences when a pose was recovered.+        let mut pose = None;+        if pairs.len() >= 8 {+            let a: Vec<(f64, f64)> = pairs.iter().map(|p| self.calibrated(p.prev)).collect();+            let b: Vec<(f64, f64)> = pairs.iter().map(|p| self.calibrated(p.curr)).collect();+            let thresh = ESSENTIAL_THRESH_PX / ((self.intr.fx + self.intr.fy) * 0.5);+            if let Some((rel, inliers)) = recover_pose(&a, &b, ESSENTIAL_ITERS, thresh) {+                if inliers.len() >= 8 {+                    pairs = inliers.iter().map(|&i| pairs[i]).collect();+                    pose = Some(rel);+                }+            }+        }++        // Seed the next frame: tracked points, topped up with fresh corners+        // so slow attrition never starves the tracker.+        let mut next_points: Vec<(f32, f32)> =+            pairs.iter().map(|p| (p.curr.0 as f32, p.curr.1 as f32)).collect();+        if next_points.len() < corners::MAX_CORNERS / 2 {+            for pt in corners::detect(gray) {+                if next_points+                    .iter()+                    .all(|&(x, y)| (x - pt.0).powi(2) + (y - pt.1).powi(2) >= 100.0)+                {+                    next_points.push(pt);+                    if next_points.len() >= corners::MAX_CORNERS {+                        break;+                    }+                }+            }+        }+        let point_count = next_points.len();+        self.prev_points = next_points;+        self.prev_gray = Some(gray.clone());+        FrameFlow {+            first_frame: false,+            pairs,+            pose,+            point_count,+        }+    }++    fn calibrated(&self, px: (f64, f64)) -> (f64, f64) {+        (+            (px.0 - self.intr.cx) / self.intr.fx,+            (px.1 - self.intr.cy) / self.intr.fy,+        )+    }+}++// Not cfg-gated to Android: the host build must export the same JNI symbols+// or the Kotlin bridge's availability check lies in JVM tests. mod jni_bindings {-    use crate::preintegrate::ImuSample;-    use crate::vio::{Intrinsics, VioSession};-    use jni::objects::{JByteArray, JClass, JDoubleArray};-    use jni::sys::{jdouble, jdoubleArray, jfloat, jint, jlong};+    use crate::CvSession;+    use jni::objects::{JByteArray, JClass};+    use jni::sys::{jdouble, jdoubleArray, jlong};     use jni::{Env, EnvUnowned};     use std::collections::HashMap;     use std::sync::{Mutex, OnceLock};     use vision_core::imgbuf::Gray;-    use vision_core::linalg::Vector3; -    /// Sessions are held behind a handle rather than a raw pointer so a stale handle-    /// from Kotlin is a lookup miss instead of a use-after-free.-    fn sessions() -> &'static Mutex<HashMap<i64, VioSession>> {-        static S: OnceLock<Mutex<HashMap<i64, VioSession>>> = OnceLock::new();+    /// Sessions are held behind a handle rather than a raw pointer so a stale+    /// handle from Kotlin is a lookup miss instead of a use-after-free.+    fn sessions() -> &'static Mutex<HashMap<i64, CvSession>> {+        static S: OnceLock<Mutex<HashMap<i64, CvSession>>> = OnceLock::new();         S.get_or_init(|| Mutex::new(HashMap::new()))     } @@ -42,7 +209,7 @@ mod jni_bindings {     }      #[no_mangle]-    pub extern "system" fn Java_com_vayunmathur_measure_domain_MeasureNative_nativeCreateSession(+    pub extern "system" fn Java_com_vayunmathur_measure_platform_vio_MeasureCvNative_nativeCreateSession(         _env: EnvUnowned,         _class: JClass,         fx: jdouble,@@ -54,15 +221,12 @@ mod jni_bindings {             return 0;         }         let h = next_handle();-        sessions()-            .lock()-            .unwrap()-            .insert(h, VioSession::new(Intrinsics { fx, fy, cx, cy }));+        sessions().lock().unwrap().insert(h, CvSession::new(fx, fy, cx, cy));         h     }      #[no_mangle]-    pub extern "system" fn Java_com_vayunmathur_measure_domain_MeasureNative_nativeDestroySession(+    pub extern "system" fn Java_com_vayunmathur_measure_platform_vio_MeasureCvNative_nativeDestroySession(         _env: EnvUnowned,         _class: JClass,         handle: jlong,@@ -71,7 +235,7 @@ mod jni_bindings {     }      #[no_mangle]-    pub extern "system" fn Java_com_vayunmathur_measure_domain_MeasureNative_nativeReset(+    pub extern "system" fn Java_com_vayunmathur_measure_platform_vio_MeasureCvNative_nativeReset(         _env: EnvUnowned,         _class: JClass,         handle: jlong,@@ -81,40 +245,38 @@ mod jni_bindings {         }     } -    /// Feed one luminance plane. `row_stride` is honoured so the caller can pass the-    /// `ImageProxy` Y plane straight through without repacking it.+    /// Feed one luminance plane; `row_stride` is honoured so the caller can+    /// pass the CameraX Y plane straight through without repacking it.+    ///+    /// Returns `[pairCount, poseFlag, firstFlag, pointCount, R(9), t(3),+    /// then prevX, prevY, currX, currY per pair]`; empty for a bad handle.     #[no_mangle]     #[allow(clippy::too_many_arguments)]-    pub extern "system" fn Java_com_vayunmathur_measure_domain_MeasureNative_nativePushFrame<'l>(+    pub extern "system" fn Java_com_vayunmathur_measure_platform_vio_MeasureCvNative_nativeProcessFrame<'l>(         mut env: EnvUnowned<'l>,         _class: JClass<'l>,         handle: jlong,         y_plane: JByteArray<'l>,-        width: jint,-        height: jint,-        row_stride: jint,-        t_ns: jlong,-    ) -> jint {-        env.with_env(|env| -> jni::errors::Result<jint> {-            let lost = crate::vio::Quality::Lost as jint;+        width: jni::sys::jint,+        height: jni::sys::jint,+        row_stride: jni::sys::jint,+    ) -> jdoubleArray {+        env.with_env(|env| -> jni::errors::Result<jdoubleArray> {             let (w, h, stride) = (width as usize, height as usize, row_stride as usize);             if w == 0 || h == 0 || stride < w {-                return Ok(lost);+                return Ok(make_double_array(env, &[]));             }             let len = match env.get_array_length(&y_plane) {                 Ok(l) => l as usize,-                Err(_) => return Ok(lost),+                Err(_) => return Ok(make_double_array(env, &[])),             };             if len < stride * (h - 1) + w {-                return Ok(lost);+                return Ok(make_double_array(env, &[]));             }-             let mut buf = vec![0i8; len];             if env.get_byte_array_region(&y_plane, 0, &mut buf).is_err() {-                return Ok(lost);+                return Ok(make_double_array(env, &[]));             }--            // Repack stride -> tight, reinterpreting Java's signed bytes as luminance.             let mut gray = Gray::new(w, h);             for row in 0..h {                 let src = row * stride;@@ -123,195 +285,43 @@ mod jni_bindings {                     gray.px[dst + col] = buf[src + col] as u8;                 }             }-             let mut guard = sessions().lock().unwrap();-            match guard.get_mut(&handle) {-                Some(s) => Ok(s.push_frame(&gray, t_ns) as jint),-                None => Ok(lost),-            }-        })-        .resolve::<jni::errors::LogErrorAndDefault>()-    }--    /// Push IMU samples as a flat `[t_ns, gx, gy, gz, ax, ay, az]` array.-    ///-    /// Batched rather than one call per sample: at 400 Hz, per-sample JNI overhead-    /// would dominate the actual integration cost.-    #[no_mangle]-    pub extern "system" fn Java_com_vayunmathur_measure_domain_MeasureNative_nativePushImu<'l>(-        mut env: EnvUnowned<'l>,-        _class: JClass<'l>,-        handle: jlong,-        packed: JDoubleArray<'l>,-    ) {-        env.with_env(|env| -> jni::errors::Result<()> {-            let len = match env.get_array_length(&packed) {-                Ok(l) => l as usize,-                Err(_) => return Ok(()),-            };-            if len == 0 || len % 7 != 0 {-                return Ok(());-            }-            let mut buf = vec![0f64; len];-            if env.get_double_array_region(&packed, 0, &mut buf).is_err() {-                return Ok(());-            }-            let samples: Vec<ImuSample> = buf-                .chunks_exact(7)-                .map(|c| ImuSample {-                    t_ns: c[0] as i64,-                    gyro: Vector3::new(c[1], c[2], c[3]),-                    accel: Vector3::new(c[4], c[5], c[6]),-                })-                .collect();-            if let Some(s) = sessions().lock().unwrap().get_mut(&handle) {-                s.push_imu(&samples);-            }-            Ok(())-        })-        .resolve::<jni::errors::LogErrorAndDefault>()-    }--    /// Convert a screen tap to a metric world point.-    ///-    /// Returns `[x, y, z, onPlane]`, or an empty array when tracking is not yet-    /// metric — the caller must treat empty as "not measurable yet".-    #[no_mangle]-    pub extern "system" fn Java_com_vayunmathur_measure_domain_MeasureNative_nativeRayToWorld<'l>(-        mut env: EnvUnowned<'l>,-        _class: JClass<'l>,-        handle: jlong,-        px: jfloat,-        py: jfloat,-    ) -> jdoubleArray {-        env.with_env(|env| -> jni::errors::Result<jdoubleArray> {-            let hit = {-                let guard = sessions().lock().unwrap();-                guard.get(&handle).and_then(|s| s.ray_to_world(px, py))-            };-            let vals: Vec<f64> = match hit {-                Some((p, on_plane)) => vec![p[0], p[1], p[2], if on_plane { 1.0 } else { 0.0 }],-                None => Vec::new(),-            };-            Ok(make_double_array(env, &vals))-        })-        .resolve::<jni::errors::LogErrorAndDefault>()-    }--    /// All sane hit candidates along a screen ray, as a flat array of-    /// `[kind, x, y, z, distanceM, angularErrorDeg, normalDotUp]` per-    /// candidate (7 values each). Selection policy lives in Kotlin-    /// (HitSelector) so it is unit-testable; the engine only reports-    /// candidates that already pass its distance/angle/extent sanity.-    #[no_mangle]-    pub extern "system" fn Java_com_vayunmathur_measure_domain_MeasureNative_nativeHitTest<'l>(-        mut env: EnvUnowned<'l>,-        _class: JClass<'l>,-        handle: jlong,-        px: jfloat,-        py: jfloat,-    ) -> jdoubleArray {-        env.with_env(|env| -> jni::errors::Result<jdoubleArray> {-            let vals: Vec<f64> = {-                let guard = sessions().lock().unwrap();-                match guard.get(&handle) {-                    Some(s) => s-                        .hit_candidates(px, py)-                        .iter()-                        .flat_map(|c| {-                            [-                                c.kind as f64,-                                c.point[0],-                                c.point[1],-                                c.point[2],-                                c.distance_m,-                                c.angular_error_rad.to_degrees(),-                                c.normal_dot_up,-                            ]-                        })-                        .collect(),-                    None => Vec::new(),-                }-            };-            Ok(make_double_array(env, &vals))-        })-        .resolve::<jni::errors::LogErrorAndDefault>()-    }--    /// Diagnostics snapshot:-    /// `[quality, scaleConfidence, landmarkCount, trackedCount, hasPlane, gx, gy, gz]`.-    #[no_mangle]-    pub extern "system" fn Java_com_vayunmathur_measure_domain_MeasureNative_nativeGetState<'l>(-        mut env: EnvUnowned<'l>,-        _class: JClass<'l>,-        handle: jlong,-    ) -> jdoubleArray {-        env.with_env(|env| -> jni::errors::Result<jdoubleArray> {-            let guard = sessions().lock().unwrap();-            let vals: Vec<f64> = match guard.get(&handle) {+            let vals: Vec<f64> = match guard.get_mut(&handle) {                 Some(s) => {-                    let g = s.gravity();-                    vec![-                        s.quality() as i32 as f64,-                        s.scale_confidence(),-                        s.landmark_count() as f64,-                        s.tracked_count() as f64,-                        if s.has_plane() { 1.0 } else { 0.0 },-                        g[0],-                        g[1],-                        g[2],-                    ]+                    let flow = s.process_frame(&gray);+                    let mut v = Vec::with_capacity(16 + flow.pairs.len() * 4);+                    v.push(flow.pairs.len() as f64);+                    v.push(if flow.pose.is_some() { 1.0 } else { 0.0 });+                    v.push(if flow.first_frame { 1.0 } else { 0.0 });+                    v.push(flow.point_count as f64);+                    match &flow.pose {+                        Some(p) => {+                            for row in 0..3 {+                                for col in 0..3 {+                                    v.push(p.r[(row, col)]);+                                }+                            }+                            v.push(p.t[0]);+                            v.push(p.t[1]);+                            v.push(p.t[2]);+                        }+                        None => v.extend(std::iter::repeat_n(0.0, 12)),+                    }+                    for pair in &flow.pairs {+                        v.push(pair.prev.0);+                        v.push(pair.prev.1);+                        v.push(pair.curr.0);+                        v.push(pair.curr.1);+                    }+                    v                 }                 None => Vec::new(),             };-            drop(guard);             Ok(make_double_array(env, &vals))         })         .resolve::<jni::errors::LogErrorAndDefault>()     } -    /// Project metric world points to normalised screen coordinates.-    ///-    /// Input is a flat `[x, y, z]` array; output is `[nx, ny, visible]` per point.-    #[no_mangle]-    pub extern "system" fn Java_com_vayunmathur_measure_domain_MeasureNative_nativeProjectPoints<'l>(-        mut env: EnvUnowned<'l>,-        _class: JClass<'l>,-        handle: jlong,-        world: JDoubleArray<'l>,-        width: jdouble,-        height: jdouble,-    ) -> jdoubleArray {-        env.with_env(|env| -> jni::errors::Result<jdoubleArray> {-            let len = match env.get_array_length(&world) {-                Ok(l) => l as usize,-                Err(_) => return Ok(make_double_array(env, &[])),-            };-            if len == 0 || len % 3 != 0 || !(width > 0.0 && height > 0.0) {-                return Ok(make_double_array(env, &[]));-            }-            let mut buf = vec![0f64; len];-            if env.get_double_array_region(&world, 0, &mut buf).is_err() {-                return Ok(make_double_array(env, &[]));-            }-            let pts: Vec<Vector3<f64>> =-                buf.chunks_exact(3).map(|c| Vector3::new(c[0], c[1], c[2])).collect();--            let guard = sessions().lock().unwrap();-            let out: Vec<f64> = match guard.get(&handle) {-                Some(s) => s-                    .project_to_screen(&pts, width, height)-                    .into_iter()-                    .flat_map(|(x, y, v)| [x as f64, y as f64, if v { 1.0 } else { 0.0 }])-                    .collect(),-                None => Vec::new(),-            };-            drop(guard);-            Ok(make_double_array(env, &out))-        })-        .resolve::<jni::errors::LogErrorAndDefault>()-    }-     fn make_double_array(env: &mut Env, vals: &[f64]) -> jdoubleArray {         let arr = match env.new_double_array(vals.len()) {             Ok(a) => a,
measure/src/main/rust/src/plane.rs
diff --git a/measure/src/main/rust/src/plane.rs b/measure/src/main/rust/src/plane.rsdeleted file mode 100644index e17771d546..0000000000--- a/measure/src/main/rust/src/plane.rs+++ /dev/null@@ -1,242 +0,0 @@-//! Gravity-aligned plane fitting over the landmark cloud.-//!-//! Anchors snap to a fitted plane so that tapping "the floor" twice produces two points-//! that genuinely lie on one surface, rather than two independently noisy depths. Since-//! the alignment step gives a metric gravity vector, planes can be classified as-//! horizontal or vertical and the fit can be constrained to physically plausible-//! surfaces instead of any arbitrary orientation.--use vision_core::geometry::Lcg;-use vision_core::linalg::Vector3;--/// A plane as `n · x + d = 0` with `n` unit length.-#[derive(Clone, Debug)]-pub struct Plane {-    pub normal: Vector3<f64>,-    pub d: f64,-    pub inliers: Vec<usize>,-}--impl Plane {-    /// Signed distance from a point to the plane, in metres.-    pub fn distance(&self, p: &Vector3<f64>) -> f64 {-        self.normal.dot(p) + self.d-    }--    /// Project a point perpendicularly onto the plane.-    pub fn project(&self, p: &Vector3<f64>) -> Vector3<f64> {-        *p - self.normal * self.distance(p)-    }--    /// Intersection of the ray `origin + t·dir` with the plane, if it hits in front.-    pub fn intersect_ray(&self, origin: &Vector3<f64>, dir: &Vector3<f64>) -> Option<Vector3<f64>> {-        let denom = self.normal.dot(dir);-        if denom.abs() < 1e-9 {-            return None; // ray parallel to the plane-        }-        let t = -(self.normal.dot(origin) + self.d) / denom;-        if t <= 0.0 {-            return None; // plane is behind the camera-        }-        Some(*origin + *dir * t)-    }--    /// Angle between the plane normal and the up direction, in radians.-    pub fn tilt_from(&self, up: &Vector3<f64>) -> f64 {-        let n = up.norm();-        if n < 1e-12 {-            return 0.0;-        }-        let cos = (self.normal.dot(up) / n).clamp(-1.0, 1.0);-        cos.acos().min(std::f64::consts::PI - cos.acos())-    }-}--fn plane_through(a: &Vector3<f64>, b: &Vector3<f64>, c: &Vector3<f64>) -> Option<Plane> {-    let n = (*b - *a).cross(&(*c - *a));-    let len = n.norm();-    if len < 1e-12 {-        return None; // collinear-    }-    let normal = n / len;-    let d = -normal.dot(a);-    Some(Plane { normal, d, inliers: Vec::new() })-}--/// RANSAC plane fit.-///-/// When `up` is supplied, candidate planes whose normal is further than-/// `max_tilt_rad` from parallel or perpendicular to it are discarded. Real indoor-/// surfaces are overwhelmingly floors, walls and tabletops, so this rejects fits-/// through scattered clutter that happen to catch a few points.-pub fn fit_plane_ransac(-    points: &[Vector3<f64>],-    iters: usize,-    inlier_dist: f64,-    up: Option<Vector3<f64>>,-    max_tilt_rad: f64,-) -> Option<Plane> {-    let n = points.len();-    if n < 3 {-        return None;-    }-    let mut rng = Lcg::new(0x71A4E ^ n as u64);-    let mut best: Option<Plane> = None;--    for _ in 0..iters {-        let i = rng.next_usize(n);-        let j = rng.next_usize(n);-        let k = rng.next_usize(n);-        if i == j || j == k || i == k {-            continue;-        }-        let cand = match plane_through(&points[i], &points[j], &points[k]) {-            Some(p) => p,-            None => continue,-        };--        if let Some(ref u) = up {-            let tilt = cand.tilt_from(u);-            let horizontal = tilt < max_tilt_rad;-            let vertical = (tilt - std::f64::consts::FRAC_PI_2).abs() < max_tilt_rad;-            if !horizontal && !vertical {-                continue;-            }-        }--        let inliers: Vec<usize> = (0..n)-            .filter(|&idx| cand.distance(&points[idx]).abs() < inlier_dist)-            .collect();--        if best.as_ref().is_none_or(|b| inliers.len() > b.inliers.len()) {-            best = Some(Plane { inliers, ..cand });-        }-    }--    let best = best?;-    if best.inliers.len() < 3 {-        return None;-    }-    Some(refit_least_squares(points, &best.inliers).unwrap_or(best))-}--/// Refit a plane to all its inliers via the smallest principal direction of the-/// centred scatter matrix, which is the total-least-squares normal.-fn refit_least_squares(points: &[Vector3<f64>], inliers: &[usize]) -> Option<Plane> {-    if inliers.len() < 3 {-        return None;-    }-    let mut centroid = Vector3::zeros();-    for &i in inliers {-        centroid += points[i];-    }-    centroid /= inliers.len() as f64;--    // Symmetric 3x3 scatter matrix, accumulated as raw sums.-    let mut m = [[0.0f64; 3]; 3];-    for &i in inliers {-        let d = points[i] - centroid;-        for r in 0..3 {-            for c in 0..3 {-                m[r][c] += d[r] * d[c];-            }-        }-    }-    let mat = vision_core::linalg::Matrix3::new(-        m[0][0], m[0][1], m[0][2], m[1][0], m[1][1], m[1][2], m[2][0], m[2][1], m[2][2],-    );-    let eig = mat.symmetric_eigen();-    // Smallest eigenvalue's eigenvector is the surface normal.-    let mut min_i = 0;-    for i in 1..3 {-        if eig.eigenvalues[i] < eig.eigenvalues[min_i] {-            min_i = i;-        }-    }-    let normal = eig.eigenvectors.column(min_i);-    let len = normal.norm();-    if len < 1e-12 {-        return None;-    }-    let normal = normal / len;-    let d = -normal.dot(&centroid);-    Some(Plane { normal, d, inliers: inliers.to_vec() })-}--#[cfg(test)]-mod tests {-    use super::*;--    fn floor_points(n: usize, height: f64, noise: f64) -> Vec<Vector3<f64>> {-        let mut seed = 99u64;-        let mut next = move || {-            seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);-            ((seed >> 33) as f64 / (1u64 << 31) as f64) - 0.5-        };-        (0..n)-            .map(|_| Vector3::new(next() * 4.0, next() * 4.0, height + next() * noise))-            .collect()-    }--    #[test]-    fn fits_a_horizontal_plane() {-        let pts = floor_points(80, -1.5, 0.002);-        let p = fit_plane_ransac(&pts, 200, 0.02, None, 0.3).expect("plane");-        assert!(p.normal[2].abs() > 0.99, "normal should be vertical: {:?}", p.normal[2]);-        // Plane passes near z = -1.5, so distance from a point on it is ~0.-        assert!(p.distance(&Vector3::new(0.0, 0.0, -1.5)).abs() < 0.02);-        assert!(p.inliers.len() > 70);-    }--    #[test]-    fn ray_intersection_hits_the_floor() {-        let pts = floor_points(80, -1.5, 0.001);-        let p = fit_plane_ransac(&pts, 200, 0.02, None, 0.3).expect("plane");-        let origin = Vector3::zeros();-        let dir = Vector3::new(0.0, 0.3, -1.0);-        let hit = p.intersect_ray(&origin, &dir).expect("hit");-        assert!((hit[2] + 1.5).abs() < 0.05, "hit z = {}", hit[2]);-    }--    #[test]-    fn ray_pointing_away_from_the_plane_misses() {-        let pts = floor_points(60, -1.5, 0.001);-        let p = fit_plane_ransac(&pts, 200, 0.02, None, 0.3).expect("plane");-        // Looking up, away from the floor below.-        assert!(p.intersect_ray(&Vector3::zeros(), &Vector3::new(0.0, 0.0, 1.0)).is_none());-    }--    #[test]-    fn projection_lands_on_the_plane() {-        let pts = floor_points(60, -1.0, 0.001);-        let p = fit_plane_ransac(&pts, 200, 0.02, None, 0.3).expect("plane");-        let q = p.project(&Vector3::new(1.0, 2.0, 5.0));-        assert!(p.distance(&q).abs() < 1e-9);-    }--    #[test]-    fn gravity_constraint_rejects_a_slanted_fit() {-        // A cloud on a 45-degree ramp is neither floor nor wall, so with the-        // constraint active there should be no acceptable plane.-        let mut seed = 7u64;-        let mut next = move || {-            seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);-            ((seed >> 33) as f64 / (1u64 << 31) as f64) - 0.5-        };-        let pts: Vec<Vector3<f64>> = (0..60)-            .map(|_| {-                let x = next() * 3.0;-                let y = next() * 3.0;-                Vector3::new(x, y, x) // 45-degree slope-            })-            .collect();-        let up = Vector3::new(0.0, 0.0, 1.0);-        assert!(fit_plane_ransac(&pts, 300, 0.02, Some(up), 0.2).is_none());-    }--    #[test]-    fn too_few_points_is_none() {-        let pts = vec![Vector3::zeros(), Vector3::new(1.0, 0.0, 0.0)];-        assert!(fit_plane_ransac(&pts, 50, 0.01, None, 0.3).is_none());-    }-}
measure/src/main/rust/src/preintegrate.rs
diff --git a/measure/src/main/rust/src/preintegrate.rs b/measure/src/main/rust/src/preintegrate.rsdeleted file mode 100644index 0a7cbad427..0000000000--- a/measure/src/main/rust/src/preintegrate.rs+++ /dev/null@@ -1,237 +0,0 @@-//! IMU preintegration between keyframes.-//!-//! Integrates gyroscope and accelerometer samples into a single relative motion-//! summary `(ΔR, Δv, Δp)` covering the interval between two keyframes, expressed in-//! the *body frame of the first keyframe*.-//!-//! Gravity is **not** removed here. The accelerometer measures specific force-//! `f = Rᵀ(a − g)`, and that is integrated as-is, because the device's attitude-//! relative to gravity is not yet known at this stage. The alignment step carries-//! explicit `g` terms that cancel the gravity contribution — see `align`, whose-//! equations assume exactly this convention. Removing gravity here would double-count-//! it there.--use vision_core::camera::rodrigues_to_mat;-use vision_core::linalg::{Matrix3, Vector3};--/// Standard gravity. The alignment step solves for the gravity *direction* but-/// constrains its magnitude to this.-pub const GRAVITY: f64 = 9.80665;--#[derive(Clone, Copy, Debug)]-pub struct ImuSample {-    /// Nanoseconds on the same clock as camera frame timestamps. Android reports-    /// `SENSOR_INFO_TIMESTAMP_SOURCE = REALTIME` on supported devices, which is what-    /// makes this comparison valid at all.-    pub t_ns: i64,-    /// Angular velocity, rad/s, body frame.-    pub gyro: Vector3<f64>,-    /// Specific force, m/s², body frame. Includes the reaction to gravity.-    pub accel: Vector3<f64>,-}--/// Relative motion accumulated across an interval.-///-/// Integrated from raw specific force, so the gravity reaction is still present in-/// [`delta_v`] and [`delta_p`]. Consumers must subtract it explicitly.-#[derive(Clone, Debug)]-pub struct Preintegrated {-    pub dt: f64,-    pub delta_r: Matrix3<f64>,-    pub delta_v: Vector3<f64>,-    pub delta_p: Vector3<f64>,-    pub sample_count: usize,-}--impl Preintegrated {-    pub fn identity() -> Self {-        Preintegrated {-            dt: 0.0,-            delta_r: Matrix3::identity(),-            delta_v: Vector3::zeros(),-            delta_p: Vector3::zeros(),-            sample_count: 0,-        }-    }-}--/// Preintegrate `samples` with the given biases removed.-///-/// Uses midpoint integration: at 400 Hz the difference from a higher-order scheme is-/// far below the accelerometer's own noise floor, and midpoint avoids the systematic-/// drift that plain forward Euler accumulates over a multi-second initialisation.-pub fn preintegrate(-    samples: &[ImuSample],-    gyro_bias: Vector3<f64>,-    accel_bias: Vector3<f64>,-) -> Preintegrated {-    let mut out = Preintegrated::identity();-    if samples.len() < 2 {-        return out;-    }--    let mut r = Matrix3::identity();-    let mut v = Vector3::zeros();-    let mut p = Vector3::zeros();--    for w in samples.windows(2) {-        let (s0, s1) = (w[0], w[1]);-        let dt = (s1.t_ns - s0.t_ns) as f64 * 1e-9;-        // Reject non-monotonic or absurd gaps; a dropped batch should not corrupt-        // the whole interval.-        if !(dt > 0.0 && dt < 0.1) {-            continue;-        }--        let g0 = s0.gyro - gyro_bias;-        let g1 = s1.gyro - gyro_bias;-        let a0 = s0.accel - accel_bias;-        let a1 = s1.accel - accel_bias;--        // Midpoint angular increment.-        let w_mid = (g0 + g1) * 0.5;-        let dr = rodrigues_to_mat(w_mid * dt);-        let r_next = r * dr;--        // Midpoint specific force, rotated into the reference (first) body frame.-        let a_ref = (r * a0 + r_next * a1) * 0.5;--        p += v * dt + a_ref * (0.5 * dt * dt);-        v += a_ref * dt;-        r = r_next;--        out.dt += dt;-        out.sample_count += 1;-    }--    out.delta_r = r;-    out.delta_v = v;-    out.delta_p = p;-    out-}--/// Estimate the gyroscope bias from an interval the device was stationary for.-///-/// A stationary gyro reads pure bias, so the mean is the estimate. Callers must-/// confirm stillness first — [`is_stationary`] exists for that.-pub fn estimate_gyro_bias(samples: &[ImuSample]) -> Vector3<f64> {-    if samples.is_empty() {-        return Vector3::zeros();-    }-    let mut sum = Vector3::zeros();-    for s in samples {-        sum += s.gyro;-    }-    sum / samples.len() as f64-}--/// True when the samples look like a device at rest: little rotation, and specific-/// force close to 1 g in magnitude.-pub fn is_stationary(samples: &[ImuSample], gyro_tol: f64, accel_tol: f64) -> bool {-    if samples.len() < 2 {-        return false;-    }-    for s in samples {-        if s.gyro.norm() > gyro_tol {-            return false;-        }-        if (s.accel.norm() - GRAVITY).abs() > accel_tol {-            return false;-        }-    }-    true-}--#[cfg(test)]-mod tests {-    use super::*;--    fn constant_motion(n: usize, dt: f64, accel: Vector3<f64>, gyro: Vector3<f64>) -> Vec<ImuSample> {-        (0..n)-            .map(|i| ImuSample {-                t_ns: (i as f64 * dt * 1e9) as i64,-                gyro,-                accel,-            })-            .collect()-    }--    #[test]-    fn constant_acceleration_integrates_to_the_kinematic_answer() {-        // 1 s of 2 m/s² with no rotation: v = 2, p = 1.-        let dt = 1.0 / 400.0;-        let s = constant_motion(401, dt, Vector3::new(2.0, 0.0, 0.0), Vector3::zeros());-        let pre = preintegrate(&s, Vector3::zeros(), Vector3::zeros());--        assert!((pre.dt - 1.0).abs() < 1e-6, "dt = {}", pre.dt);-        assert!((pre.delta_v[0] - 2.0).abs() < 1e-6, "v = {}", pre.delta_v[0]);-        assert!((pre.delta_p[0] - 1.0).abs() < 1e-3, "p = {}", pre.delta_p[0]);-    }--    #[test]-    fn stationary_device_accumulates_no_motion() {-        let dt = 1.0 / 400.0;-        let s = constant_motion(401, dt, Vector3::zeros(), Vector3::zeros());-        let pre = preintegrate(&s, Vector3::zeros(), Vector3::zeros());-        assert!(pre.delta_v.norm() < 1e-9);-        assert!(pre.delta_p.norm() < 1e-9);-    }--    #[test]-    fn constant_rotation_integrates_to_the_expected_angle() {-        // 1 rad/s about Z for 1 s => 1 rad.-        let dt = 1.0 / 400.0;-        let s = constant_motion(401, dt, Vector3::zeros(), Vector3::new(0.0, 0.0, 1.0));-        let pre = preintegrate(&s, Vector3::zeros(), Vector3::zeros());-        let expected = rodrigues_to_mat(Vector3::new(0.0, 0.0, 1.0));-        for i in 0..3 {-            for j in 0..3 {-                assert!(-                    (pre.delta_r[(i, j)] - expected[(i, j)]).abs() < 1e-4,-                    "R[{i}][{j}] drifted"-                );-            }-        }-    }--    #[test]-    fn bias_is_removed_before_integration() {-        let dt = 1.0 / 400.0;-        let bias = Vector3::new(0.5, -0.2, 0.1);-        let s = constant_motion(401, dt, bias, Vector3::zeros());-        let pre = preintegrate(&s, Vector3::zeros(), bias);-        assert!(pre.delta_v.norm() < 1e-9, "bias should cancel exactly");-    }--    #[test]-    fn gyro_bias_estimate_recovers_a_constant_offset() {-        let dt = 1.0 / 400.0;-        let bias = Vector3::new(0.01, -0.02, 0.003);-        let s = constant_motion(200, dt, Vector3::new(0.0, 0.0, GRAVITY), bias);-        let est = estimate_gyro_bias(&s);-        assert!((est - bias).norm() < 1e-9);-    }--    #[test]-    fn stationary_detection_rejects_motion() {-        let dt = 1.0 / 400.0;-        let still = constant_motion(50, dt, Vector3::new(0.0, 0.0, GRAVITY), Vector3::zeros());-        assert!(is_stationary(&still, 0.05, 0.3));--        let moving = constant_motion(50, dt, Vector3::new(3.0, 0.0, GRAVITY), Vector3::zeros());-        assert!(!is_stationary(&moving, 0.05, 0.3));-    }--    #[test]-    fn irregular_timestamps_do_not_corrupt_the_interval() {-        // A dropped batch shows up as a large gap; it must be skipped, not integrated.-        let mut s = constant_motion(100, 1.0 / 400.0, Vector3::new(1.0, 0.0, 0.0), Vector3::zeros());-        s.push(ImuSample {-            t_ns: s.last().unwrap().t_ns + 5_000_000_000,-            gyro: Vector3::zeros(),-            accel: Vector3::new(1.0, 0.0, 0.0),-        });-        let pre = preintegrate(&s, Vector3::zeros(), Vector3::zeros());-        assert!(pre.dt < 0.5, "the 5 s gap should have been rejected, dt = {}", pre.dt);-    }-}
measure/src/main/rust/src/triangulate.rs
diff --git a/measure/src/main/rust/src/triangulate.rs b/measure/src/main/rust/src/triangulate.rsdeleted file mode 100644index d36c1e47bf..0000000000--- a/measure/src/main/rust/src/triangulate.rs+++ /dev/null@@ -1,216 +0,0 @@-//! Landmark triangulation.-//!-//! Turns matched observations of the same scene point across two or more camera poses-//! into a 3D position. Distances between anchors are ultimately distances between-//! triangulated landmarks, so the depth quality here sets the accuracy ceiling of the-//! whole app.--use crate::epipolar::NPt;-use vision_core::linalg::{DMatrix, Matrix3, Vector3};--/// A camera pose as world-to-camera: `x_cam = r * x_world + t`.-#[derive(Clone, Debug)]-pub struct CameraPose {-    pub r: Matrix3<f64>,-    pub t: Vector3<f64>,-}--impl CameraPose {-    pub fn identity() -> Self {-        CameraPose { r: Matrix3::identity(), t: Vector3::zeros() }-    }--    /// Camera centre in world coordinates: `C = -Rᵀ t`.-    pub fn center(&self) -> Vector3<f64> {-        let rt = self.r.transpose();-        -(rt * self.t)-    }-}--/// Direct linear triangulation from N >= 2 views.-///-/// Each view contributes two rows constraining the homogeneous world point; the-/// solution is the smallest right singular vector.-pub fn triangulate(views: &[(CameraPose, NPt)]) -> Option<Vector3<f64>> {-    if views.len() < 2 {-        return None;-    }-    let mut m = DMatrix::<f64>::zeros(2 * views.len(), 4);-    for (i, (pose, pt)) in views.iter().enumerate() {-        let (x, y) = *pt;-        for c in 0..3 {-            m[(2 * i, c)] = x * pose.r[(2, c)] - pose.r[(0, c)];-            m[(2 * i + 1, c)] = y * pose.r[(2, c)] - pose.r[(1, c)];-        }-        m[(2 * i, 3)] = x * pose.t[2] - pose.t[0];-        m[(2 * i + 1, 3)] = y * pose.t[2] - pose.t[1];-    }-    let vt = m.svd(false, true).v_t?;-    let h = vt.row(3);-    if h[3].abs() < 1e-12 {-        return None;-    }-    Some(Vector3::new(h[0] / h[3], h[1] / h[3], h[2] / h[3]))-}--/// Reprojection error of a world point in one view, in calibrated units.-pub fn reprojection_error(pose: &CameraPose, world: &Vector3<f64>, observed: NPt) -> f64 {-    let c = pose.r * *world + pose.t;-    if c[2].abs() < 1e-9 {-        return f64::MAX;-    }-    let dx = c[0] / c[2] - observed.0;-    let dy = c[1] / c[2] - observed.1;-    (dx * dx + dy * dy).sqrt()-}--/// True when the point sits in front of every camera that saw it.-pub fn is_in_front_of_all(views: &[(CameraPose, NPt)], world: &Vector3<f64>) -> bool {-    views.iter().all(|(pose, _)| {-        let c = pose.r * *world + pose.t;-        c[2] > 0.0-    })-}--/// Angle in radians between the rays from two camera centres to a point.-///-/// Small parallax means depth is poorly constrained: a landmark seen from almost the-/// same viewpoint twice has essentially unbounded depth uncertainty, so callers should-/// drop anything below roughly one degree rather than trust its position.-pub fn parallax_angle(a: &CameraPose, b: &CameraPose, world: &Vector3<f64>) -> f64 {-    let ca = a.center();-    let cb = b.center();-    let ra = *world - ca;-    let rb = *world - cb;-    let na = ra.norm();-    let nb = rb.norm();-    if na < 1e-12 || nb < 1e-12 {-        return 0.0;-    }-    let cos = (ra.dot(&rb) / (na * nb)).clamp(-1.0, 1.0);-    cos.acos()-}--/// Triangulate and accept only if the result is geometrically trustworthy.-pub fn triangulate_checked(-    views: &[(CameraPose, NPt)],-    max_reproj: f64,-    min_parallax_rad: f64,-) -> Option<Vector3<f64>> {-    let p = triangulate(views)?;-    if !is_in_front_of_all(views, &p) {-        return None;-    }-    for (pose, obs) in views {-        if reprojection_error(pose, &p, *obs) > max_reproj {-            return None;-        }-    }-    // Widest baseline available decides whether depth is observable at all.-    let mut best = 0.0f64;-    for i in 0..views.len() {-        for j in (i + 1)..views.len() {-            best = best.max(parallax_angle(&views[i].0, &views[j].0, &p));-        }-    }-    if best < min_parallax_rad {-        return None;-    }-    Some(p)-}--#[cfg(test)]-mod tests {-    use super::*;-    use vision_core::camera::rodrigues_to_mat;--    fn project(pose: &CameraPose, p: Vector3<f64>) -> NPt {-        let c = pose.r * p + pose.t;-        (c[0] / c[2], c[1] / c[2])-    }--    fn two_views(baseline: f64) -> (CameraPose, CameraPose) {-        let a = CameraPose::identity();-        let b = CameraPose {-            r: Matrix3::identity(),-            t: Vector3::new(-baseline, 0.0, 0.0),-        };-        (a, b)-    }--    #[test]-    fn recovers_a_known_point() {-        let (a, b) = two_views(0.2);-        let truth = Vector3::new(0.3, -0.1, 4.0);-        let views = vec![(a.clone(), project(&a, truth)), (b.clone(), project(&b, truth))];-        let got = triangulate(&views).expect("triangulate");-        assert!((got - truth).norm() < 1e-6, "got {:?}", (got[0], got[1], got[2]));-    }--    #[test]-    fn recovers_a_point_from_three_views() {-        let a = CameraPose::identity();-        let b = CameraPose { r: Matrix3::identity(), t: Vector3::new(-0.2, 0.0, 0.0) };-        let c = CameraPose {-            r: rodrigues_to_mat(Vector3::new(0.0, 0.05, 0.0)),-            t: Vector3::new(-0.4, 0.02, 0.0),-        };-        let truth = Vector3::new(-0.5, 0.25, 3.0);-        let views = vec![-            (a.clone(), project(&a, truth)),-            (b.clone(), project(&b, truth)),-            (c.clone(), project(&c, truth)),-        ];-        let got = triangulate(&views).expect("triangulate");-        assert!((got - truth).norm() < 1e-6);-    }--    #[test]-    fn camera_center_is_the_negated_rotated_translation() {-        let pose = CameraPose {-            r: rodrigues_to_mat(Vector3::new(0.0, 0.3, 0.0)),-            t: Vector3::new(-0.5, 0.0, 0.1),-        };-        let c = pose.center();-        // Projecting the centre back through the pose should land at the origin.-        let back = pose.r * c + pose.t;-        assert!(back.norm() < 1e-9);-    }--    #[test]-    fn zero_baseline_gives_no_parallax_and_is_rejected() {-        let a = CameraPose::identity();-        let b = CameraPose::identity();-        let truth = Vector3::new(0.0, 0.0, 3.0);-        let views = vec![(a.clone(), project(&a, truth)), (b.clone(), project(&b, truth))];-        assert!(-            triangulate_checked(&views, 1e-3, 0.01).is_none(),-            "a zero baseline must be rejected"-        );-    }--    #[test]-    fn points_behind_the_camera_are_rejected() {-        let (a, b) = two_views(0.2);-        let behind = Vector3::new(0.0, 0.0, -3.0);-        let views = vec![(a.clone(), project(&a, behind)), (b.clone(), project(&b, behind))];-        assert!(triangulate_checked(&views, 1e-3, 0.001).is_none());-    }--    #[test]-    fn parallax_grows_with_baseline() {-        let truth = Vector3::new(0.0, 0.0, 4.0);-        let (a, near) = two_views(0.05);-        let (_, far) = two_views(0.5);-        let small = parallax_angle(&a, &near, &truth);-        let large = parallax_angle(&a, &far, &truth);-        assert!(large > small * 5.0, "small {small} large {large}");-    }--    #[test]-    fn reprojection_error_is_zero_for_a_consistent_point() {-        let (a, _) = two_views(0.2);-        let truth = Vector3::new(0.1, 0.2, 2.5);-        assert!(reprojection_error(&a, &truth, project(&a, truth)) < 1e-12);-    }-}
measure/src/main/rust/src/vio.rs
diff --git a/measure/src/main/rust/src/vio.rs b/measure/src/main/rust/src/vio.rsdeleted file mode 100644index 602c78ef82..0000000000--- a/measure/src/main/rust/src/vio.rs+++ /dev/null@@ -1,484 +0,0 @@-//! The VIO session: the state machine that turns a stream of camera frames and IMU-//! samples into metric camera poses and a landmark cloud.-//!-//! Lifecycle:-//!-//! 1. **Initialising** — track features, accumulate keyframes with enough parallax, and-//!    keep preintegrating IMU. Nothing is measurable yet because scale is unknown.-//! 2. **Aligning** — once several keyframes with real translation exist, solve for-//!    metric scale and gravity, then rescale the whole map into metres.-//! 3. **Tracking** — continue tracking, triangulating new landmarks, and fitting a-//!    ground plane. Measurements are only valid from here on.-//!-//! Deliberately *not* a full sliding-window bundle adjuster with marginalisation. For a-//! measuring tool the user holds still-ish for a few seconds over a few metres, the-//! dominant error is scale estimation, not long-horizon drift, so effort belongs in-//! initialisation quality rather than in a large back-end.--use crate::align::{align_visual_inertial, refine_gravity, AlignmentResult, KeyframePose};-use crate::epipolar::{recover_pose, NPt};-use crate::klt::{track, Pyramid};-use crate::plane::{fit_plane_ransac, Plane};-use crate::preintegrate::{estimate_gyro_bias, is_stationary, preintegrate, ImuSample, Preintegrated};-use crate::triangulate::{triangulate_checked, CameraPose};-use vision_core::features::detect_and_describe;-use vision_core::imgbuf::Gray;-use vision_core::linalg::Vector3;--#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub enum Quality {-    Initialising = 0,-    Limited = 1,-    Good = 2,-    Lost = 3,-}--/// Pinhole intrinsics for the analysis-resolution stream.-#[derive(Clone, Copy, Debug)]-pub struct Intrinsics {-    pub fx: f64,-    pub fy: f64,-    pub cx: f64,-    pub cy: f64,-}--impl Intrinsics {-    /// Pixel -> calibrated bearing on the z = 1 plane.-    pub fn unproject(&self, x: f32, y: f32) -> NPt {-        ((x as f64 - self.cx) / self.fx, (y as f64 - self.cy) / self.fy)-    }-}--const MIN_FEATURES: usize = 40;-const TARGET_FEATURES: usize = 300;-const FAST_THRESHOLD: i32 = 18;-/// Redetect once tracking attrition drops the set below this fraction of target.-const REDETECT_FRACTION: f64 = 0.5;-/// Median pixel displacement a frame must show before it earns a keyframe.-const KEYFRAME_MIN_FLOW_PX: f32 = 12.0;-const MIN_KEYFRAMES_FOR_ALIGN: usize = 6;-const MAX_KEYFRAMES: usize = 20;-const MIN_PARALLAX_RAD: f64 = 0.0175; // ~1 degree-const MAX_REPROJ: f64 = 0.01;--struct Keyframe {-    pose: CameraPose,-    /// `(feature id, pixel)` observations. Ids are carried through KLT tracking-    /// so two keyframes can be matched by identity, never by list position:-    /// tracking drops and re-detects points, so index i in two keyframes is-    /// in general a different scene feature.-    points: Vec<(u64, (f32, f32))>,-    imu: Preintegrated,-}--pub struct VioSession {-    intr: Intrinsics,-    prev_pyramid: Option<Pyramid>,-    prev_points: Vec<(f32, f32)>,-    /// Feature ids parallel to `prev_points`.-    prev_ids: Vec<u64>,-    next_point_id: u64,-    keyframes: Vec<Keyframe>,-    pending_imu: Vec<ImuSample>,-    gyro_bias: Vector3<f64>,-    accel_bias: Vector3<f64>,--    /// Current camera pose, metric once aligned.-    pose: CameraPose,-    scale: f64,-    gravity: Vector3<f64>,-    landmarks: Vec<Vector3<f64>>,-    plane: Option<Plane>,-    quality: Quality,-    scale_confidence: f64,-    last_frame_ns: i64,-    frame_count: u64,-}--impl VioSession {-    pub fn new(intr: Intrinsics) -> Self {-        VioSession {-            intr,-            prev_pyramid: None,-            prev_points: Vec::new(),-            prev_ids: Vec::new(),-            next_point_id: 1,-            keyframes: Vec::new(),-            pending_imu: Vec::new(),-            gyro_bias: Vector3::zeros(),-            accel_bias: Vector3::zeros(),-            pose: CameraPose::identity(),-            scale: 1.0,-            gravity: Vector3::new(0.0, 0.0, -crate::preintegrate::GRAVITY),-            landmarks: Vec::new(),-            plane: None,-            quality: Quality::Initialising,-            scale_confidence: 0.0,-            last_frame_ns: 0,-            frame_count: 0,-        }-    }--    pub fn reset(&mut self) {-        let intr = self.intr;-        *self = VioSession::new(intr);-    }--    pub fn quality(&self) -> Quality {-        self.quality-    }-    pub fn scale_confidence(&self) -> f64 {-        self.scale_confidence-    }-    pub fn landmark_count(&self) -> usize {-        self.landmarks.len()-    }-    pub fn tracked_count(&self) -> usize {-        self.prev_points.len()-    }-    pub fn has_plane(&self) -> bool {-        self.plane.is_some()-    }-    pub fn pose(&self) -> &CameraPose {-        &self.pose-    }-    pub fn gravity(&self) -> Vector3<f64> {-        self.gravity-    }--    /// Queue IMU samples. Cheap: they are only integrated at keyframe boundaries.-    pub fn push_imu(&mut self, samples: &[ImuSample]) {-        self.pending_imu.extend_from_slice(samples);-        // Bound memory if frames stop arriving (screen off, camera stalled).-        if self.pending_imu.len() > 8000 {-            let cut = self.pending_imu.len() - 8000;-            self.pending_imu.drain(0..cut);-        }-    }--    /// Feed one camera frame. Returns the current quality.-    pub fn push_frame(&mut self, gray: &Gray, t_ns: i64) -> Quality {-        self.frame_count += 1;-        let pyramid = Pyramid::build(gray, 4);--        let prev = match self.prev_pyramid.take() {-            None => {-                // First frame: seed the feature set and the first keyframe.-                self.prev_points = detect_points(gray);-                self.prev_ids = self.fresh_ids(self.prev_points.len());-                self.prev_pyramid = Some(pyramid);-                self.last_frame_ns = t_ns;-                let points: Vec<(u64, (f32, f32))> =-                    self.prev_ids.iter().copied().zip(self.prev_points.iter().copied()).collect();-                self.keyframes.push(Keyframe {-                    pose: CameraPose::identity(),-                    points,-                    imu: Preintegrated::identity(),-                });-                return self.quality;-            }-            Some(p) => p,-        };--        let results = track(&prev, &pyramid, &self.prev_points);-        let mut kept_prev = Vec::new();-        let mut kept_now = Vec::new();-        let mut kept_ids = Vec::new();-        let mut flow = Vec::new();-        for (i, r) in results.iter().enumerate() {-            if !r.ok {-                continue;-            }-            let p = self.prev_points[i];-            kept_prev.push(p);-            kept_now.push((r.x, r.y));-            kept_ids.push(self.prev_ids.get(i).copied().unwrap_or(0));-            flow.push(((r.x - p.0).powi(2) + (r.y - p.1).powi(2)).sqrt());-        }--        if kept_now.len() < MIN_FEATURES {-            // Attrition wiped the set out. Only call this "lost" if tracking had-            // actually been established: reporting Lost during start-up would tell the-            // user to recover something that never existed, when the honest state is-            // still "initialising".-            if matches!(self.quality, Quality::Good | Quality::Limited) {-                self.quality = Quality::Lost;-                // The metric map belonged to the lost track: keyframes were-                // scaled by the old alignment and landmarks/plane refer to a-                // world frame that can no longer be re-observed. Keeping them-                // would let a later re-initialisation mix two scales in one-                // solve and keep snapping taps to a stale plane.-                self.keyframes.clear();-                self.landmarks.clear();-                self.plane = None;-                self.scale = 1.0;-                self.scale_confidence = 0.0;-                self.pose = CameraPose::identity();-                self.pending_imu.clear();-            }-            self.prev_points = detect_points(gray);-            self.prev_ids = self.fresh_ids(self.prev_points.len());-            self.prev_pyramid = Some(pyramid);-            self.last_frame_ns = t_ns;-            return self.quality;-        }--        let median_flow = median(&mut flow);-        self.prev_points = kept_now.clone();-        self.prev_ids = kept_ids;-        self.prev_pyramid = Some(pyramid);--        if self.prev_points.len() < (TARGET_FEATURES as f64 * REDETECT_FRACTION) as usize {-            // Top the set back up, keeping the survivors so continuity is preserved.-            let fresh = detect_points(gray);-            let before = self.prev_points.len();-            merge_points(&mut self.prev_points, &fresh, TARGET_FEATURES);-            let added = self.prev_points.len() - before;-            if added > 0 {-                let ids = self.fresh_ids(added);-                self.prev_ids.extend(ids);-            }-        }--        if median_flow >= KEYFRAME_MIN_FLOW_PX {-            self.add_keyframe(t_ns);-        }--        self.last_frame_ns = t_ns;-        self.quality-    }--    /// Allocate `n` fresh feature ids.-    fn fresh_ids(&mut self, n: usize) -> Vec<u64> {-        let start = self.next_point_id;-        self.next_point_id += n as u64;-        (0..n as u64).map(|i| start + i).collect()-    }--    /// Capture the gyro bias while the device is still at start-up.-    /// Biases were previously left at zero for the whole session even-    /// though preintegrate.rs already had the estimator: every interval-    /// then integrated a constant rotation offset as if it were motion.-    fn calibrate_gyro_bias_if_stationary(&mut self) {-        if self.gyro_bias.norm() > 1e-9 || self.frame_count > 120 {-            return;-        }-        if is_stationary(&self.pending_imu, 0.05, 0.5) {-            self.gyro_bias = estimate_gyro_bias(&self.pending_imu);-        }-    }--    fn add_keyframe(&mut self, t_ns: i64) {-        self.calibrate_gyro_bias_if_stationary();-        // Correspondences between the previous keyframe and now, matched by-        // feature id. Previously the relative pose was estimated between the-        // last two *frames* and then composed onto the last *keyframe*, which-        // silently dropped every frame of motion in between; and the IMU-        // interval (everything since the last keyframe) no longer matched the-        // visual interval (one frame), corrupting the alignment solve.-        let (prev_pts, now_pts): (Vec<(f32, f32)>, Vec<(f32, f32)>) = match self.keyframes.last() {-            Some(last) => {-                let current: std::collections::HashMap<u64, (f32, f32)> = self-                    .prev_ids-                    .iter()-                    .copied()-                    .zip(self.prev_points.iter().copied())-                    .collect();-                let mut a = Vec::new();-                let mut b = Vec::new();-                for (id, pt) in &last.points {-                    if let Some(now) = current.get(id) {-                        a.push(*pt);-                        b.push(*now);-                    }-                }-                (a, b)-            }-            None => (Vec::new(), Vec::new()),-        };--        if prev_pts.len() < 8 {-            // No usable chain from the previous keyframe (fresh start, or the-            // tracked set was wiped and re-detected). Re-anchor here at the-            // current pose so later keyframes chain from a known frame.-            let imu = preintegrate(&self.pending_imu, self.gyro_bias, self.accel_bias);-            self.pending_imu.clear();-            let points: Vec<(u64, (f32, f32))> =-                self.prev_ids.iter().copied().zip(self.prev_points.iter().copied()).collect();-            self.keyframes.push(Keyframe { pose: self.pose.clone(), points, imu });-            if self.keyframes.len() > MAX_KEYFRAMES {-                self.keyframes.remove(0);-            }-            let _ = t_ns;-            return;-        }--        let a: Vec<NPt> = prev_pts.iter().map(|p| self.intr.unproject(p.0, p.1)).collect();-        let b: Vec<NPt> = now_pts.iter().map(|p| self.intr.unproject(p.0, p.1)).collect();--        // Sampson threshold expressed in calibrated units: ~2 px at this focal length.-        let thresh = 2.0 / self.intr.fx;-        let (rel, _inliers) = match recover_pose(&a, &b, 200, thresh) {-            Some(v) => v,-            None => return,-        };--        // Chain the keyframe-to-keyframe relative pose onto the previous keyframe.-        let last = self.keyframes.last().map(|k| k.pose.clone()).unwrap_or_else(CameraPose::identity);-        let new_pose = CameraPose {-            r: rel.r * last.r,-            // Translation is a unit direction until alignment fixes the scale.-            t: rel.r * last.t + rel.t,-        };--        let imu = preintegrate(&self.pending_imu, self.gyro_bias, self.accel_bias);-        self.pending_imu.clear();--        let points: Vec<(u64, (f32, f32))> =-            self.prev_ids.iter().copied().zip(self.pr

Diff truncated.