measure: new app
- Commit
4f7238f7206686a838480681774825b2a2ccc241- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-05 04:25 UTC (4 months ago)
- Parents
30d8725
Diff
Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex bf681d4576..59a9698ff9 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -196,6 +196,7 @@ dependencies = [ "jni", "jpeg-decoder", "jpeg-encoder",+ "vision_core", ] [[package]]@@ -980,6 +981,14 @@ dependencies = [ "digest 0.10.7", ] +[[package]]+name = "measure_vio"+version = "0.1.0"+dependencies = [+ "jni",+ "vision_core",+]+ [[package]] name = "memchr" version = "2.8.3"@@ -1680,6 +1689,13 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]]+name = "vision_core"+version = "0.1.0"+dependencies = [+ "jpeg-decoder",+]+ [[package]] name = "vpn_wireguard" version = "0.1.0"
Cargo.toml
diff --git a/Cargo.toml b/Cargo.tomlindex ca7e436b17..00196d5023 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -11,6 +11,8 @@ members = [ "vpn/src/main/rust", "library/e2ee-p2p/src/main/rust", "library/jni-http/src/main/rust",+ "library/vision/src/main/rust",+ "measure/src/main/rust", "messages/src/main/rust", "youpipe/src/main/rust", "third_party/om-file-format-sys",
README.md
diff --git a/README.md b/README.mdindex 17d14b0379..c621f7c0de 100644--- a/README.md+++ b/README.md@@ -52,6 +52,7 @@ Though some apps may have exceptions, generally a 64-bit device running at least | **Health** | [Homepage](https://ma.vayunmathur.com/apps/health) | [](https://f-droid.org/packages/com.vayunmathur.health) | [](https://api.vayunmathur.com/obtainium-link?name=Health&packageName=com.vayunmathur.health&apk=health-release.apk) | | **Keyboard** | [Homepage](https://ma.vayunmathur.com/apps/keyboard) | [MA Repo](https://ma.vayunmathur.com/fdroid) | [](https://api.vayunmathur.com/obtainium-link?name=Keyboard&packageName=com.vayunmathur.keyboard&apk=keyboard-release.apk) | | **Maps** | [Homepage](https://ma.vayunmathur.com/apps/maps) | In Progress | In Progress |+| **Measure** | [Homepage](https://ma.vayunmathur.com/apps/measure) | In Progress | In Progress | | **Messages** | [Homepage](https://ma.vayunmathur.com/apps/messages) | In Progress | In Progress | | **Music** | [Homepage](https://ma.vayunmathur.com/apps/music) | [MA Repo](https://ma.vayunmathur.com/fdroid) | [](https://api.vayunmathur.com/obtainium-link?name=Music&packageName=com.vayunmathur.music&apk=music-release.apk) | | **MusicBrainz** | [Homepage](https://ma.vayunmathur.com/apps/musicbrainz) | [MA Repo](https://ma.vayunmathur.com/fdroid) | [](https://api.vayunmathur.com/obtainium-link?name=MusicBrainz&packageName=com.vayunmathur.musicbrainz&apk=musicbrainz-release.apk) |
astronomy/src/main/java/com/vayunmathur/astronomy/ui/AstronomyViewModel.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/AstronomyViewModel.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/AstronomyViewModel.ktindex 634d6d6bda..75e8c24b10 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/AstronomyViewModel.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/AstronomyViewModel.kt@@ -7,9 +7,9 @@ import com.vayunmathur.astronomy.data.CatalogRepository import com.vayunmathur.astronomy.data.model.PlanetId import com.vayunmathur.astronomy.R import com.vayunmathur.astronomy.domain.engine.*-import com.vayunmathur.astronomy.domain.sensor.DeviceOrientation+import com.vayunmathur.library.sensor.DeviceOrientation import com.vayunmathur.astronomy.domain.sensor.LocationProvider-import com.vayunmathur.astronomy.domain.sensor.OrientationManager+import com.vayunmathur.library.sensor.OrientationManager import com.vayunmathur.library.util.DataStoreUtils import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job
camera/src/main/rust/Cargo.toml
diff --git a/camera/src/main/rust/Cargo.toml b/camera/src/main/rust/Cargo.tomlindex ccbcc8c0d1..f12252bc74 100644--- a/camera/src/main/rust/Cargo.toml+++ b/camera/src/main/rust/Cargo.toml@@ -11,6 +11,10 @@ crate-type = ["cdylib", "rlib"] [dependencies] jni.workspace = true+# Shared CV primitives (linalg / imgbuf / features / geometry / camera) now live in+# library/vision/src/main/rust so measure's VIO engine can reuse them. The `jpeg`+# feature keeps Rgba::from_jpeg available for the panorama pipeline.+vision_core = { path = "../../../../library/vision/src/main/rust", features = ["jpeg"] } # image crate 0.25 removed – pulled moxcms/pxfm/bytemuck; now jpeg-decoder + jpeg-encoder (trivial 1-function) jpeg-decoder = { version = "0.3.2", default-features = false } jpeg-encoder = { version = "0.6.1", default-features = false }
camera/src/main/rust/src/lib.rs
diff --git a/camera/src/main/rust/src/lib.rs b/camera/src/main/rust/src/lib.rsindex d1d2fa0c9d..810ac01611 100644--- a/camera/src/main/rust/src/lib.rs+++ b/camera/src/main/rust/src/lib.rs@@ -1,11 +1,13 @@ //! Camera stitching native library: feature-based panorama stitcher + night //! burst aligner, exposed to Kotlin via JNI. Replaces the OpenCV dependency.+//!+//! The linear algebra, image buffers, feature detection and homography geometry+//! now live in the shared `vision_core` crate (library/vision/src/main/rust) so the+//! measure app's VIO engine can reuse them. They are re-exported here under their+//! original paths, which is why the rest of this crate still says `crate::linalg`.++pub use vision_core::{camera, features, geometry, imgbuf, linalg}; -mod linalg;-mod imgbuf;-mod features;-mod geometry;-mod camera; mod matching; mod estimator; mod bundle;
library/src/main/java/com/vayunmathur/library/sensor/OrientationManager.kt
diff --git a/library/src/main/java/com/vayunmathur/library/sensor/OrientationManager.kt b/library/src/main/java/com/vayunmathur/library/sensor/OrientationManager.ktindex a08bf7a15a..44732e85b5 100644--- a/library/src/main/java/com/vayunmathur/library/sensor/OrientationManager.kt+++ b/library/src/main/java/com/vayunmathur/library/sensor/OrientationManager.kt@@ -1,4 +1,4 @@-package com.vayunmathur.astronomy.domain.sensor+package com.vayunmathur.library.sensor import android.content.Context import android.hardware.GeomagneticField@@ -8,7 +8,6 @@ import android.hardware.SensorEventListener import android.hardware.SensorManager import android.view.Surface import android.view.WindowManager-import com.vayunmathur.astronomy.domain.engine.AltAz import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlin.math.*@@ -22,11 +21,11 @@ data class DeviceOrientation( val declinationDeg: Double = 0.0, // "Window" model: the view looks where the BACK of the phone points, i.e. the // device -Z axis (the camera's optical axis), expressed in world ENU. Hold the- // phone up like a pane of glass and the sky drawn matches what's behind it (and+ // phone up like a pane of glass and what is drawn matches what's behind it (and // what the AR camera sees). Flat screen-up => back faces the ground => nadir; // vertical => horizon; back facing the zenith => alt +90.- // viewRotationDeg is the true roll about that -Z axis, so content stays fixed to- // the sky as the phone rolls.+ // viewRotationDeg is the true roll about that -Z axis, so world-anchored content+ // stays fixed as the phone rolls. val pointingAzTrueDeg: Double = azimuthTrueDeg, val pointingAltDeg: Double = 0.0, val viewRotationDeg: Double = 0.0@@ -34,7 +33,6 @@ data class DeviceOrientation( val pointingAzRad get() = Math.toRadians(pointingAzTrueDeg) val pointingAltRad get() = Math.toRadians(pointingAltDeg) val viewRotationRad get() = Math.toRadians(viewRotationDeg)- val pointingAltAz get() = AltAz(pointingAzRad, pointingAltRad) } class OrientationManager(private val context: Context) : SensorEventListener {
library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.ktindex ce137854a9..561944e2c3 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt@@ -3,7 +3,10 @@ package com.vayunmathur.library.ui import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AcUnit import androidx.compose.material.icons.filled.DeliveryDining+import androidx.compose.material.icons.filled.Explore import androidx.compose.material.icons.filled.Restaurant+import androidx.compose.material.icons.filled.SquareFoot+import androidx.compose.material.icons.filled.Straighten import androidx.compose.material.icons.filled.CloudSync import androidx.compose.material.icons.filled.Compress import androidx.compose.material.icons.filled.Dehaze@@ -1219,3 +1222,18 @@ fun IconRestaurant(modifier: Modifier = Modifier, tint: Color = LocalContentColo @Composable fun IconDeliveryDining(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) = AppIcon(Icons.Filled.DeliveryDining, "Courier", modifier, tint)++/** Compass rose — the compass tool. */+@Composable+fun IconCompass(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.Explore, "Compass", modifier, tint)++/** Ruler — the on-screen ruler tool. */+@Composable+fun IconRuler(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.Straighten, "Ruler", modifier, tint)++/** Corner with dimension marks — area and perimeter measurement. */+@Composable+fun IconArea(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.SquareFoot, "Area", modifier, tint)
library/vision/src/main/rust/Cargo.toml
diff --git a/library/vision/src/main/rust/Cargo.toml b/library/vision/src/main/rust/Cargo.tomlnew file mode 100644index 0000000000..18cd99433f--- /dev/null+++ b/library/vision/src/main/rust/Cargo.toml@@ -0,0 +1,20 @@+[package]+name = "vision_core"+version = "0.1.0"+edition = "2021"+description = "Shared computer-vision primitives: dependency-free linear algebra, image buffers, ORB/FAST/BRIEF features, and homography geometry"+license = "GPL-2.0-only"++[lib]+name = "vision_core"+crate-type = ["rlib"]++[features]+default = []+# JPEG decoding is only needed by the camera app's panorama pipeline. Left off by+# default so consumers that just want the CV primitives (e.g. measure's VIO engine)+# pull no image codecs at all.+jpeg = ["dep:jpeg-decoder"]++[dependencies]+jpeg-decoder = { version = "0.3.2", default-features = false, optional = true }
library/vision/src/main/rust/src/features.rs
diff --git a/library/vision/src/main/rust/src/features.rs b/library/vision/src/main/rust/src/features.rsindex 288a225ad9..560b6e0674 100644--- a/library/vision/src/main/rust/src/features.rs+++ b/library/vision/src/main/rust/src/features.rs@@ -228,7 +228,7 @@ pub fn detect_and_describe_orb(g: &Gray, max_features: usize, threshold: i32) -> let mut nfeatures_per_level = Vec::with_capacity(actual_levels); let mut sum = 0usize;- for level in 0..actual_levels - 1 {+ for _level in 0..actual_levels - 1 { let cnt = ndesired_per_scale.round() as usize; nfeatures_per_level.push(cnt); sum += cnt;
library/vision/src/main/rust/src/geometry.rs
diff --git a/library/vision/src/main/rust/src/geometry.rs b/library/vision/src/main/rust/src/geometry.rsindex 59c6cc7adb..b415d94861 100644--- a/library/vision/src/main/rust/src/geometry.rs+++ b/library/vision/src/main/rust/src/geometry.rs@@ -4,12 +4,14 @@ use crate::linalg::{DMatrix, Matrix3, Vector3}; pub type Pt = (f32, f32); -struct Lcg(u64);+/// Small deterministic LCG for RANSAC sampling. Public so other crates in the+/// workspace (measure's VIO engine) get reproducible sampling without pulling `rand`.+pub struct Lcg(u64); impl Lcg {- fn new(seed: u64) -> Self {+ pub fn new(seed: u64) -> Self { Lcg(seed | 1) }- fn next_usize(&mut self, n: usize) -> usize {+ pub fn next_usize(&mut self, n: usize) -> usize { self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); ((self.0 >> 33) as usize) % n.max(1) }
library/vision/src/main/rust/src/imgbuf.rs
diff --git a/library/vision/src/main/rust/src/imgbuf.rs b/library/vision/src/main/rust/src/imgbuf.rsindex e7c658b777..e1db283864 100644--- a/library/vision/src/main/rust/src/imgbuf.rs+++ b/library/vision/src/main/rust/src/imgbuf.rs@@ -23,6 +23,11 @@ impl Rgba { /// Decode JPEG/PNG bytes into an RGBA buffer. /// Previously used `image` crate which pulled moxcms, pxfm, bytemuck, etc for this single call. /// Now uses jpeg-decoder directly (armv8-only, minimal pure Rust, already in pdf_render).+ ///+ /// Behind the `jpeg` feature: consumers that only want the CV primitives (the+ /// measure app's VIO engine feeds raw camera luminance and never sees a JPEG)+ /// should not have to link a codec.+ #[cfg(feature = "jpeg")] pub fn from_jpeg(bytes: &[u8]) -> Option<Rgba> { use std::io::Cursor; let mut decoder = jpeg_decoder::Decoder::new(Cursor::new(bytes));
library/vision/src/main/rust/src/lib.rs
diff --git a/library/vision/src/main/rust/src/lib.rs b/library/vision/src/main/rust/src/lib.rsnew file mode 100644index 0000000000..992c930ffb--- /dev/null+++ b/library/vision/src/main/rust/src/lib.rs@@ -0,0 +1,13 @@+//! Shared computer-vision primitives, extracted from the camera app's panorama+//! stitcher so the measure app's visual-inertial odometry engine can reuse them.+//!+//! Everything here is deliberately dependency-free apart from an optional JPEG+//! decoder behind the `jpeg` feature: the linear algebra, image buffers, feature+//! detection and homography estimation are all hand-rolled so the whole CV stack+//! stays auditable and adds no transitive crates.++pub mod linalg;+pub mod imgbuf;+pub mod features;+pub mod geometry;+pub mod camera;
library/vision/src/main/rust/src/linalg.rs
diff --git a/library/vision/src/main/rust/src/linalg.rs b/library/vision/src/main/rust/src/linalg.rsindex 2d1e2ea9e9..c3a2973927 100644--- a/library/vision/src/main/rust/src/linalg.rs+++ b/library/vision/src/main/rust/src/linalg.rs@@ -129,6 +129,43 @@ impl Matrix3<f64> { /// Eigen-decomposition of a **symmetric** matrix via cyclic Jacobi. /// `eigenvectors`' columns are the (unit) eigenvectors; eigenvalues are /// unordered (matching `nalgebra::SymmetricEigen`).+ /// As [`Matrix3::svd`], but with singular values in **descending** order and+ /// `u` / `v_t` permuted to match.+ ///+ /// Plain `svd()` inherits the Jacobi eigensolver's arbitrary ordering, which is+ /// harmless for callers that only form `U·Vᵀ` (orthonormalization) but wrong for+ /// anyone indexing a specific singular direction — e.g. taking the null vector as+ /// `u.column(2)`, or forcing the smallest singular value to zero. `DMatrix::svd`+ /// already sorts; this makes the 3×3 path consistent with it.+ pub fn svd_sorted(&self) -> Svd {+ let s = self.svd(true, true);+ let (u, vt) = match (s.u, s.v_t) {+ (Some(u), Some(vt)) => (u, vt),+ _ => return s,+ };+ let sigma = s.singular_values;+ let mut order = [0usize, 1, 2];+ order.sort_by(|&a, &b| sigma[b].total_cmp(&sigma[a]));++ let mut nu = Matrix3::zeros();+ let mut nv = Matrix3::zeros();+ for (rank, &src) in order.iter().enumerate() {+ nu.set_column(rank, u.column(src));+ // Row `src` of v_t is the corresponding right singular vector.+ let r = Vector3::new(vt[(src, 0)], vt[(src, 1)], vt[(src, 2)]);+ nv.set_column(rank, r);+ }+ Svd {+ u: Some(nu),+ v_t: Some(nv.transpose()),+ singular_values: Vector3::new(+ sigma[order[0]],+ sigma[order[1]],+ sigma[order[2]],+ ),+ }+ }+ pub fn symmetric_eigen(&self) -> SymmetricEigen { let (evals, evecs) = jacobi_sym(&self.d, 3); SymmetricEigen {@@ -474,6 +511,13 @@ impl Mul<f64> for Vector3<f64> { } } +impl std::ops::Add<Vector3<f64>> for Vector3<f64> {+ type Output = Vector3<f64>;+ fn add(self, o: Vector3<f64>) -> Vector3<f64> {+ Vector3::new(self.x + o.x, self.y + o.y, self.z + o.z)+ }+}+ impl std::ops::Sub<Vector3<f64>> for Vector3<f64> { type Output = Vector3<f64>; fn sub(self, o: Vector3<f64>) -> Vector3<f64> {
measure/build.gradle.kts
diff --git a/measure/build.gradle.kts b/measure/build.gradle.ktsnew file mode 100644index 0000000000..d663dc4c00--- /dev/null+++ b/measure/build.gradle.kts@@ -0,0 +1,35 @@+plugins {+ id("common-conventions-app")+ // Listing screenshots come from Compose previews (src/screenshotTest), not from an+ // instrumented test on a device. Same `:measure:metadata` task name either way.+ id("common-conventions-preview-metadata")+}++launcherIcon {+ symbol = "straighten"+}++android {+ defaultConfig {+ applicationId = "com.vayunmathur.measure"+ }+}++androidComponents {+ onVariants { variant ->+ variant.sources.jniLibs?.addStaticSourceDirectory(+ layout.buildDirectory.dir("rustJniLibs").get().asFile.absolutePath+ )+ }+}++// Visual-inertial odometry engine (Rust). See measure/src/main/rust/.+rustNativeLib("measure_vio", "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)+}
measure/src/main/AndroidManifest.xml
diff --git a/measure/src/main/AndroidManifest.xml b/measure/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..bad6caef6a--- /dev/null+++ b/measure/src/main/AndroidManifest.xml@@ -0,0 +1,34 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++ <uses-permission android:name="android.permission.CAMERA" />+ <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" />+ <uses-feature android:name="android.hardware.sensor.gyroscope" android:required="false" />++ <application+ android:allowBackup="true"+ android:dataExtractionRules="@xml/data_extraction_rules"+ android:icon="@mipmap/ic_launcher"+ android:label="@string/app_name"+ android:roundIcon="@mipmap/ic_launcher"+ android:supportsRtl="true"+ android:theme="@style/Theme.General">+ <activity+ android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+ android:name=".MainActivity"+ android:exported="true"+ android:theme="@style/Theme.General">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>+ <!-- Surfaces an in-app settings entry on the system App Info page. -->+ <intent-filter>+ <action android:name="android.intent.action.APPLICATION_PREFERENCES" />+ <category android:name="android.intent.category.DEFAULT" />+ </intent-filter>+ </activity>+ </application>+</manifest>
measure/src/main/java/com/vayunmathur/measure/MainActivity.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/MainActivity.kt b/measure/src/main/java/com/vayunmathur/measure/MainActivity.ktnew file mode 100644index 0000000000..aed88cb1e3--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/MainActivity.kt@@ -0,0 +1,87 @@+package com.vayunmathur.measure++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.viewModels+import androidx.compose.runtime.Composable+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.util.DialogPage+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.NavKey+import com.vayunmathur.library.util.openSettingsIfRequested+import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.measure.ui.MeasureViewModel+import com.vayunmathur.measure.ui.pages.ArMeasurePage+import com.vayunmathur.measure.ui.pages.CompassPage+import com.vayunmathur.measure.ui.pages.DiagnosticsPage+import com.vayunmathur.measure.ui.pages.LevelPage+import com.vayunmathur.measure.ui.pages.RulerPage+import com.vayunmathur.measure.ui.pages.SavedMeasurementsPage+import com.vayunmathur.measure.ui.pages.SettingsPage+import kotlinx.serialization.Serializable++class MainActivity : ComponentActivity() {+ private val viewModel: MeasureViewModel by viewModels()++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ enableEdgeToEdge()+ setContent {+ DynamicTheme {+ Navigation(viewModel)+ }+ }+ }++ // Sensors run only while the app is in front. The compass and level are useless+ // in the background, and the magnetometer is not free to keep polling.+ override fun onStart() {+ super.onStart()+ viewModel.startSensors()+ }++ override fun onStop() {+ super.onStop()+ viewModel.stopSensors()+ }+}++@Serializable+sealed interface Route : NavKey {+ @Serializable data object Compass : Route+ @Serializable data object Level : Route+ @Serializable data object Ruler : Route++ /**+ * Camera is requested here rather than at app launch: the sensor tools are fully+ * usable without it, so gating the whole app on CAMERA would be a permission prompt+ * most sessions never need.+ */+ @Serializable data object ArMeasure : Route++ @Serializable data object Saved : Route+ @Serializable data object Settings : Route+ @Serializable data object Diagnostics : Route+}++@Composable+fun Navigation(viewModel: MeasureViewModel) {+ val backStack = rememberNavBackStack<Route>(Route.Compass)+ // Land on settings when opened from the system App Info page.+ backStack.openSettingsIfRequested(Route.Settings)+ MainNavigation(backStack) {+ // No ListPage metadata: these are single full-screen tools, not list-detail+ // pairs. Marking them as list panes makes the adaptive strategy split a wide+ // window in two and squeeze the tool into the left third with an empty pane+ // beside it, which is what landscape looked like before.+ entry<Route.Compass> { CompassPage(backStack, viewModel) }+ entry<Route.Level> { LevelPage(backStack, viewModel) }+ entry<Route.Ruler> { RulerPage(backStack, viewModel) }+ entry<Route.ArMeasure> { ArMeasurePage(backStack, viewModel) }+ entry<Route.Saved> { SavedMeasurementsPage(backStack, viewModel) }+ entry<Route.Settings>(metadata = DialogPage()) { SettingsPage(backStack, viewModel) }+ entry<Route.Diagnostics>(metadata = DialogPage()) { DiagnosticsPage(backStack, viewModel) }+ }+}
measure/src/main/java/com/vayunmathur/measure/data/model/Models.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/data/model/Models.kt b/measure/src/main/java/com/vayunmathur/measure/data/model/Models.ktnew file mode 100644index 0000000000..28d04736b1--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/data/model/Models.kt@@ -0,0 +1,49 @@+package com.vayunmathur.measure.data.model++enum class UnitSystem { Metric, Imperial }++/** How far the visual-inertial estimator has got, and therefore what the UI may show. */+enum class TrackingQuality {+ /**+ * No metric scale yet. Monocular VIO needs genuine translation to triangulate; pure+ * rotation leaves the reconstruction scale-free, so measurements are withheld here.+ */+ Initialising,++ /** Tracking, but with few landmarks or weak parallax — distances may drift. */+ Limited,++ Good,++ /** Tracking lost entirely; anchors placed before this point are no longer trustworthy. */+ Lost,+}++/** A 3D point in the tracker's metric world frame, in metres, gravity-aligned (+Y up). */+data class Anchor(+ val id: Long,+ val x: Double,+ val y: Double,+ val z: Double,+ /** True when the point was snapped to the fitted plane rather than free-placed. */+ val onPlane: Boolean = false,+)++fun Anchor.distanceTo(other: Anchor): Double {+ val dx = x - other.x+ val dy = y - other.y+ val dz = z - other.z+ return kotlin.math.sqrt(dx * dx + dy * dy + dz * dz)+}++enum class MeasurementKind { Distance, Area, Perimeter, Angle, Height }++data class SavedMeasurement(+ val id: Long,+ val label: String,+ val kind: MeasurementKind,+ /** Metres, square metres, or degrees depending on [kind]. Always stored in SI. */+ val value: Double,+ val recordedAtEpochMs: Long,+ val framePath: String? = null,+)
measure/src/main/java/com/vayunmathur/measure/domain/CameraIntrinsics.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/domain/CameraIntrinsics.kt b/measure/src/main/java/com/vayunmathur/measure/domain/CameraIntrinsics.ktnew file mode 100644index 0000000000..d80051aebc--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/domain/CameraIntrinsics.kt@@ -0,0 +1,99 @@+package com.vayunmathur.measure.domain++import android.content.Context+import android.hardware.camera2.CameraCharacteristics+import android.hardware.camera2.CameraManager+import android.util.Size++/**+ * Pinhole intrinsics for the analysis stream, in analysis-resolution pixels.+ */+data class Intrinsics(+ val fx: Double,+ val fy: Double,+ val cx: Double,+ val cy: Double,+ /** True when these came from the factory calibration rather than an FOV estimate. */+ val calibrated: Boolean,+)++/**+ * Resolves camera intrinsics for un-projecting pixels into rays.+ *+ * Prefers `LENS_INTRINSIC_CALIBRATION`, which recent Pixels populate with per-device+ * factory values — far better than deriving a focal length from the advertised FOV,+ * which ignores lens distortion and manufacturing spread. Falls back to focal length+ * and sensor size when the calibration tag is absent.+ *+ * The calibration is expressed against the sensor's **active array**, so it must be+ * rescaled to whatever resolution the analysis stream actually delivers.+ */+object CameraIntrinsicsResolver {++ fun resolve(context: Context, analysisSize: Size, cameraId: String? = null): Intrinsics? {+ val manager = context.getSystemService(Context.CAMERA_SERVICE) as? CameraManager+ ?: return null+ val id = cameraId ?: firstBackCameraId(manager) ?: return null+ val chars = runCatching { manager.getCameraCharacteristics(id) }.getOrNull() ?: return null++ val activeArray = chars.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE)+ ?: return null+ val arrayW = activeArray.width().toDouble()+ val arrayH = activeArray.height().toDouble()+ if (arrayW <= 0 || arrayH <= 0) return null++ // The analysis stream is centre-cropped to its own aspect ratio before being+ // scaled down, so the two axes generally do not share a scale factor.+ val scaleX = analysisSize.width / arrayW+ val scaleY = analysisSize.height / arrayH++ val calibration = chars.get(CameraCharacteristics.LENS_INTRINSIC_CALIBRATION)+ if (calibration != null && calibration.size >= 4) {+ val fx = calibration[0].toDouble() * scaleX+ val fy = calibration[1].toDouble() * scaleY+ val cx = calibration[2].toDouble() * scaleX+ val cy = calibration[3].toDouble() * scaleY+ if (fx > 1.0 && fy > 1.0) {+ return Intrinsics(fx, fy, cx, cy, calibrated = true)+ }+ }++ // Fallback: focal length in millimetres against physical sensor size.+ val focalMm = chars.get(CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS)+ ?.firstOrNull()?.toDouble() ?: return null+ val physical = chars.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE) ?: return null+ if (physical.width <= 0f || physical.height <= 0f) return null++ val fxPx = focalMm / physical.width * arrayW * scaleX+ val fyPx = focalMm / physical.height * arrayH * scaleY+ return Intrinsics(+ fx = fxPx,+ fy = fyPx,+ cx = analysisSize.width / 2.0,+ cy = analysisSize.height / 2.0,+ calibrated = false,+ )+ }++ /**+ * True when camera frame timestamps share the `elapsedRealtimeNanos` clock the+ * sensors use. Without this the two streams cannot be fused and VIO will not+ * converge, so the UI should refuse rather than produce silent nonsense.+ */+ fun timestampsAlignWithSensors(context: Context, cameraId: String? = null): Boolean {+ val manager = context.getSystemService(Context.CAMERA_SERVICE) as? CameraManager+ ?: return false+ val id = cameraId ?: firstBackCameraId(manager) ?: return false+ val chars = runCatching { manager.getCameraCharacteristics(id) }.getOrNull() ?: return false+ return chars.get(CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE) ==+ CameraCharacteristics.SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME+ }++ private fun firstBackCameraId(manager: CameraManager): String? =+ runCatching {+ manager.cameraIdList.firstOrNull { id ->+ manager.getCameraCharacteristics(id)+ .get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK+ }+ }.getOrNull()+}
measure/src/main/java/com/vayunmathur/measure/domain/LevelMath.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/domain/LevelMath.kt b/measure/src/main/java/com/vayunmathur/measure/domain/LevelMath.ktnew file mode 100644index 0000000000..048afb0520--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/domain/LevelMath.kt@@ -0,0 +1,69 @@+package com.vayunmathur.measure.domain++import com.vayunmathur.measure.domain.sensor.HeldOrientation+import kotlin.math.abs+import kotlin.math.atan2+import kotlin.math.roundToInt+import kotlin.math.sqrt++/**+ * Pure gravity-to-tilt maths, split out from the sensor plumbing so every device+ * orientation can be unit tested without physically turning a phone.+ */+object LevelMath {++ /** |z| this close to 1 g means the screen faces up or down. */+ const val FLAT_GRAVITY_THRESHOLD = 8.0++ data class Reading(+ val pitchDeg: Double,+ val rollDeg: Double,+ val edgeAngleDeg: Double,+ val quadrant: Int,+ val isFlat: Boolean,+ val orientation: HeldOrientation,+ )++ /**+ * @param x gravity along the device X axis (positive toward the right edge)+ * @param y gravity along the device Y axis (positive toward the top edge)+ * @param z gravity along the device Z axis (positive out of the screen)+ */+ fun fromGravity(x: Double, y: Double, z: Double): Reading {+ val pitch = Math.toDegrees(atan2(y, sqrt(x * x + z * z)))+ val roll = Math.toDegrees(atan2(-x, sqrt(y * y + z * z)))++ // In-plane gravity angle: 0 upright, 90 on the left side, 180 upside down.+ // Uses the gravity vector alone and never the display rotation, which is what+ // makes the reading independent of whether auto-rotate is enabled.+ val inPlane = Math.toDegrees(atan2(x, -y))+ val quadrant = (inPlane / 90.0).roundToInt()+ val edge = inPlane - quadrant * 90.0++ val flat = abs(z) > FLAT_GRAVITY_THRESHOLD+ val orientation = if (flat) {+ HeldOrientation.Flat+ } else {+ when (((quadrant % 4) + 4) % 4) {+ 1 -> HeldOrientation.LandscapeLeft+ 2 -> HeldOrientation.PortraitUpsideDown+ 3 -> HeldOrientation.LandscapeRight+ else -> HeldOrientation.Portrait+ }+ }++ return Reading(pitch, roll, edge, quadrant, flat, orientation)+ }++ /**+ * How far to rotate the edge bubble so it reads horizontally in the real world.+ *+ * With auto-rotate on, the activity has already turned with the device and no+ * correction is needed. With it off, the activity stays put while the device turns,+ * and the difference is exactly what has to be undone.+ */+ fun uiRotation(quadrant: Int, displayRotationDeg: Int): Float {+ val deviceDeg = ((quadrant % 4) + 4) % 4 * 90+ return (((deviceDeg - displayRotationDeg) % 360 + 360) % 360).toFloat()+ }+}
measure/src/main/java/com/vayunmathur/measure/domain/MeasureNative.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/domain/MeasureNative.kt b/measure/src/main/java/com/vayunmathur/measure/domain/MeasureNative.ktnew file mode 100644index 0000000000..512aa726a1--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/domain/MeasureNative.kt@@ -0,0 +1,103 @@+package com.vayunmathur.measure.domain++/**+ * JNI bridge to the Rust visual-inertial odometry engine (`measure/src/main/rust`).+ *+ * [available] guards every call: Compose previews, unit tests and any non-arm64 host+ * have no `.so` to load, and the measure UI degrades to "AR unavailable" rather than+ * crashing. Same pattern as the astronomy engine's native bridge.+ */+object MeasureNative {++ val available: Boolean = runCatching { System.loadLibrary("measure_vio") }.isSuccess++ /** Quality codes mirroring the Rust `vio::Quality` discriminants. */+ const val QUALITY_INITIALISING = 0+ const val QUALITY_LIMITED = 1+ const val QUALITY_GOOD = 2+ const val QUALITY_LOST = 3++ /** Returns a session handle, or 0 on failure. */+ 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 first.+ */+ fun pushFrame(+ handle: Long,+ yPlane: ByteArray,+ width: Int,+ height: Int,+ rowStride: Int,+ timestampNs: Long,+ ): Int =+ if (!available || handle == 0L) QUALITY_LOST+ else nativePushFrame(handle, yPlane, width, height, rowStride, timestampNs)++ /**+ * Push a batch of IMU samples packed as `[tNs, gx, gy, gz, ax, ay, az]` per sample.+ * Batched because at 400 Hz per-sample JNI overhead would exceed the integration cost.+ */+ fun pushImu(handle: Long, packed: DoubleArray) {+ if (available && handle != 0L && packed.isNotEmpty()) nativePushImu(handle, packed)+ }++ /**+ * Screen tap to metric world point: `[x, y, z, onPlane]`, or null while tracking+ * has no metric scale yet.+ */+ fun rayToWorld(handle: Long, px: Float, py: Float): DoubleArray? {+ if (!available || handle == 0L) return null+ return nativeRayToWorld(handle, px, py)?.takeIf { it.size == 4 }+ }++ /**+ * `[quality, scaleConfidence, landmarkCount, trackedCount, hasPlane, gx, gy, gz]`,+ * or null when the handle is unknown.+ */+ fun getState(handle: Long): DoubleArray? {+ if (!available || handle == 0L) return null+ return nativeGetState(handle)?.takeIf { it.size == 8 }+ }++ /**+ * Project metric world points to normalised screen coordinates.+ * Input is a flat `[x, y, z]` array; output is `[nx, ny, visible]` per point.+ */+ fun projectPoints(handle: Long, world: DoubleArray, width: Double, height: Double): DoubleArray {+ if (!available || handle == 0L || world.isEmpty()) return DoubleArray(0)+ return nativeProjectPoints(handle, world, width, height) ?: DoubleArray(0)+ }++ 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 nativePushFrame(+ handle: Long,+ yPlane: ByteArray,+ width: Int,+ height: Int,+ rowStride: Int,+ timestampNs: Long,+ ): Int++ private external fun nativePushImu(handle: Long, packed: DoubleArray)+ private external fun nativeRayToWorld(handle: Long, px: Float, py: Float): DoubleArray?+ private external fun nativeGetState(handle: Long): DoubleArray?+ private external fun nativeProjectPoints(+ handle: Long,+ world: DoubleArray,+ width: Double,+ height: Double,+ ): DoubleArray?+}
measure/src/main/java/com/vayunmathur/measure/domain/Polygon.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/domain/Polygon.kt b/measure/src/main/java/com/vayunmathur/measure/domain/Polygon.ktnew file mode 100644index 0000000000..6a540aec17--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/domain/Polygon.kt@@ -0,0 +1,84 @@+package com.vayunmathur.measure.domain++import com.vayunmathur.measure.data.model.Anchor+import com.vayunmathur.measure.data.model.distanceTo+import kotlin.math.abs+import kotlin.math.sqrt++/**+ * Area of a polygon whose vertices are 3D points assumed to be roughly coplanar.+ *+ * Uses the vector cross-product form of the shoelace formula, which works directly in+ * 3D and needs no projection onto a fitted plane. Anchors snapped to the same plane are+ * exactly coplanar; free-placed ones are only approximately so, and this degrades+ * gracefully rather than requiring a separate code path.+ */+fun polygonArea(vertices: List<Anchor>): Double {+ if (vertices.size < 3) return 0.0+ var cx = 0.0+ var cy = 0.0+ var cz = 0.0+ val origin = vertices[0]+ for (i in 1 until vertices.size - 1) {+ val a = vertices[i]+ val b = vertices[i + 1]+ val ux = a.x - origin.x+ val uy = a.y - origin.y+ val uz = a.z - origin.z+ val vx = b.x - origin.x+ val vy = b.y - origin.y+ val vz = b.z - origin.z+ cx += uy * vz - uz * vy+ cy += uz * vx - ux * vz+ cz += ux * vy - uy * vx+ }+ return 0.5 * sqrt(cx * cx + cy * cy + cz * cz)+}++/** Total edge length. When [closed], includes the edge from the last vertex back to the first. */+fun polygonPerimeter(vertices: List<Anchor>, closed: Boolean): Double {+ if (vertices.size < 2) return 0.0+ var total = 0.0+ for (i in 0 until vertices.size - 1) {+ total += vertices[i].distanceTo(vertices[i + 1])+ }+ if (closed && vertices.size >= 3) {+ total += vertices.last().distanceTo(vertices.first())+ }+ return total+}++/**+ * How far the vertices deviate from a best-fit plane, in metres.+ *+ * Reported so the UI can warn that an area figure is unreliable: a "room" whose corners+ * are 20 cm out of plane was not tapped on one surface, and its area is meaningless.+ */+fun planarityError(vertices: List<Anchor>): Double {+ if (vertices.size < 4) return 0.0+ val n = vertices.size+ val cx = vertices.sumOf { it.x } / n+ val cy = vertices.sumOf { it.y } / n+ val cz = vertices.sumOf { it.z } / n++ // Normal from the two widest-spread edges off the centroid.+ val a = vertices[0]+ val b = vertices[n / 3]+ val c = vertices[2 * n / 3]+ val ux = b.x - a.x+ val uy = b.y - a.y+ val uz = b.z - a.z+ val vx = c.x - a.x+ val vy = c.y - a.y+ val vz = c.z - a.z+ var nx = uy * vz - uz * vy+ var ny = uz * vx - ux * vz+ var nz = ux * vy - uy * vx+ val len = sqrt(nx * nx + ny * ny + nz * nz)+ if (len < 1e-12) return 0.0+ nx /= len+ ny /= len+ nz /= len++ return vertices.maxOf { abs((it.x - cx) * nx + (it.y - cy) * ny + (it.z - cz) * nz) }+}
measure/src/main/java/com/vayunmathur/measure/domain/Units.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/domain/Units.kt b/measure/src/main/java/com/vayunmathur/measure/domain/Units.ktnew file mode 100644index 0000000000..7ee2040628--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/domain/Units.kt@@ -0,0 +1,124 @@+package com.vayunmathur.measure.domain++import com.vayunmathur.measure.data.model.UnitSystem+import kotlin.math.abs+import kotlin.math.roundToInt+import kotlin.math.roundToLong++/**+ * Length, area and angle formatting shared by every tool.+ *+ * All values enter in SI (metres, square metres) and are converted at the display edge, so+ * no tool has to care which unit system is active.+ */+object Units {++ const val MM_PER_INCH = 25.4+ const val MM_PER_FOOT = 304.8+ private const val M2_PER_FT2 = 0.09290304++ /** Denominator for fractional-inch display. Sixteenths is the tape-measure convention. */+ private const val FRACTION_DENOMINATOR = 16++ fun formatLength(+ metres: Double,+ system: UnitSystem,+ fractionalInches: Boolean = true,+ ): String = when (system) {+ UnitSystem.Metric -> formatMetric(metres)+ UnitSystem.Imperial -> formatImperial(metres, fractionalInches)+ }++ private fun formatMetric(metres: Double): String {+ val mm = metres * 1000.0+ return when {+ abs(mm) < 10.0 -> "%.1f mm".format(mm)+ abs(mm) < 1000.0 -> "%.0f mm".format(mm)+ abs(metres) < 10.0 -> "%.3f m".format(metres)+ else -> "%.2f m".format(metres)+ }+ }++ private fun formatImperial(metres: Double, fractional: Boolean): String {+ val totalInches = metres * 1000.0 / MM_PER_INCH+ if (!fractional) {+ return if (abs(totalInches) < 12.0) {+ "%.2f in".format(totalInches)+ } else {+ "%.2f ft".format(totalInches / 12.0)+ }+ }+ return formatFractionalInches(totalInches)+ }++ /**+ * Renders inches the way a tape measure reads: whole feet, whole inches, and a reduced+ * sixteenth. Reduction matters — `3/16` is correct but `8/16` should read `1/2`.+ */+ fun formatFractionalInches(totalInches: Double): String {+ val negative = totalInches < 0+ val abs = abs(totalInches)++ val sixteenths = (abs * FRACTION_DENOMINATOR).roundToLong()+ var wholeInches = sixteenths / FRACTION_DENOMINATOR+ val remainder = (sixteenths % FRACTION_DENOMINATOR).toInt()++ val feet = wholeInches / 12+ wholeInches %= 12++ val sb = StringBuilder()+ if (negative) sb.append('-')+ if (feet > 0) {+ sb.append(feet).append("' ")+ }+ sb.append(wholeInches)+ if (remainder > 0) {+ var num = remainder+ var den = FRACTION_DENOMINATOR+ while (num % 2 == 0 && den % 2 == 0) {+ num /= 2+ den /= 2+ }+ sb.append(' ').append(num).append('/').append(den)+ }+ sb.append('"')+ return sb.toString()+ }++ fun formatArea(squareMetres: Double, system: UnitSystem): String = when (system) {+ UnitSystem.Metric -> if (squareMetres < 1.0) {+ "%.0f cm²".format(squareMetres * 10_000.0)+ } else {+ "%.2f m²".format(squareMetres)+ }+ UnitSystem.Imperial -> {+ val ft2 = squareMetres / M2_PER_FT2+ if (ft2 < 1.0) "%.0f in²".format(ft2 * 144.0) else "%.2f ft²".format(ft2)+ }+ }++ fun formatAngle(degrees: Double): String = "%.1f°".format(degrees)++ /** Compass bearings read better as whole degrees; sub-degree precision is noise anyway. */+ fun formatBearing(degrees: Double): String = "%03d°".format(normalizeDegrees(degrees).roundToInt() % 360)++ fun normalizeDegrees(deg: Double): Double = ((deg % 360.0) + 360.0) % 360.0++ /**+ * Shortest signed delta between two bearings, in `[-180, 180)`.+ *+ * An exact half-turn is ambiguous — +180 and −180 describe the same rotation — and+ * this convention resolves it to −180.+ */+ fun bearingDelta(from: Double, to: Double): Double = ((to - from + 540.0) % 360.0) - 180.0++ private val CARDINALS = listOf(+ "N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE",+ "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW",+ )++ fun cardinal(degrees: Double): String {+ val idx = ((normalizeDegrees(degrees) / 22.5) + 0.5).toInt() % 16+ return CARDINALS[idx]+ }+}
measure/src/main/java/com/vayunmathur/measure/domain/sensor/ImuRecorder.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/domain/sensor/ImuRecorder.kt b/measure/src/main/java/com/vayunmathur/measure/domain/sensor/ImuRecorder.ktnew file mode 100644index 0000000000..39347e84c8--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/domain/sensor/ImuRecorder.kt@@ -0,0 +1,119 @@+package com.vayunmathur.measure.domain.sensor++import android.content.Context+import android.hardware.Sensor+import android.hardware.SensorEvent+import android.hardware.SensorEventListener+import android.hardware.SensorManager++/**+ * Collects gyroscope and accelerometer samples for the VIO engine.+ *+ * Prefers the **uncalibrated** variants: the engine estimates and removes bias itself,+ * 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+ * per-sample JNI overhead at that rate would exceed the integration work itself.+ */+class ImuRecorder(context: Context) : SensorEventListener {++ private val sensorManager =+ context.getSystemService(Context.SENSOR_SERVICE) as SensorManager++ private val lock = Any()++ /** Interleaved `[tNs, gx, gy, gz, ax, ay, az]`, matching the JNI packing. */+ private val pending = ArrayList<Double>(VALUES_PER_SAMPLE * 512)++ private var lastGyro = FloatArray(3)+ private var haveGyro = false+ private var running = false++ private var sampleCount = 0L+ private var firstSampleNs = 0L+ private var lastSampleNs = 0L++ fun start() {+ if (running) return+ 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++ sensorManager.registerListener(this, gyro, SensorManager.SENSOR_DELAY_FASTEST)+ sensorManager.registerListener(this, accel, SensorManager.SENSOR_DELAY_FASTEST)+ running = true+ }++ fun stop() {+ if (!running) return+ sensorManager.unregisterListener(this)+ running = false+ synchronized(lock) { pending.clear() }+ haveGyro = false+ }++ /** Effective sample rate since the first sample, for the diagnostics screen. */+ fun rateHz(): Double {+ val span = (lastSampleNs - firstSampleNs) * 1e-9+ return if (span > 0.1) sampleCount / span else 0.0+ }++ fun lastTimestampNs(): Long = lastSampleNs++ /** Take everything queued so far, leaving the buffer empty. */+ fun drain(): DoubleArray = synchronized(lock) {+ if (pending.isEmpty()) return DoubleArray(0)+ val out = DoubleArray(pending.size)+ for (i in pending.indices) out[i] = pending[i]+ pending.clear()+ out+ }++ override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}++ override fun onSensorChanged(event: SensorEvent) {+ when (event.sensor.type) {+ Sensor.TYPE_GYROSCOPE_UNCALIBRATED, Sensor.TYPE_GYROSCOPE -> {+ lastGyro[0] = event.values[0]+ lastGyro[1] = event.values[1]+ lastGyro[2] = event.values[2]+ haveGyro = true+ }++ Sensor.TYPE_ACCELEROMETER_UNCALIBRATED, Sensor.TYPE_ACCELEROMETER -> {+ // The accelerometer drives sample emission, pairing each reading with+ // the most recent gyro value. The two sensors are not synchronised, and+ // interpolating between gyro samples at 400 Hz would buy accuracy far+ // below the noise floor.+ if (!haveGyro) return+ synchronized(lock) {+ if (pending.size >= MAX_PENDING_VALUES) {+ // Camera stalled or screen off: drop the oldest half rather+ // than grow without bound.+ pending.subList(0, pending.size / 2).clear()+ }+ pending.add(event.timestamp.toDouble())+ pending.add(lastGyro[0].toDouble())+ pending.add(lastGyro[1].toDouble())+ pending.add(lastGyro[2].toDouble())+ pending.add(event.values[0].toDouble())+ pending.add(event.values[1].toDouble())+ pending.add(event.values[2].toDouble())+ }+ if (sampleCount == 0L) firstSampleNs = event.timestamp+ lastSampleNs = event.timestamp+ sampleCount+++ }+ }+ }++ private companion object {+ 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/domain/sensor/TiltSensor.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/domain/sensor/TiltSensor.kt b/measure/src/main/java/com/vayunmathur/measure/domain/sensor/TiltSensor.ktnew file mode 100644index 0000000000..2114d421fd--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/domain/sensor/TiltSensor.kt@@ -0,0 +1,163 @@+package com.vayunmathur.measure.domain.sensor++import android.content.Context+import android.hardware.Sensor+import android.hardware.SensorEvent+import android.hardware.SensorEventListener+import android.hardware.SensorManager+import android.view.Surface+import android.view.WindowManager+import com.vayunmathur.measure.domain.LevelMath+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow++/** Which device edge is pointing at the ground, derived purely from gravity. */+enum class HeldOrientation(val label: String) {+ Portrait("Portrait"),+ PortraitUpsideDown("Portrait, upside down"),+ LandscapeLeft("Landscape, left edge down"),+ LandscapeRight("Landscape, right edge down"),+ Flat("Flat"),+}++data class Tilt(+ /** Front-to-back tilt for the flat 2D bubble, in degrees. */+ val pitchDeg: Double,+ /** Side-to-side tilt for the flat 2D bubble, in degrees. */+ val rollDeg: Double,+ /**+ * Deviation of the down-facing edge from level, in degrees.+ *+ * Measured against the nearest quarter turn, so it reads correctly whether the+ * phone is held upright, upside down, or on either side.+ */+ val edgeAngleDeg: Double,+ /** True when the device is lying close to flat, where the 2D bubble is the useful view. */+ val isFlat: Boolean,+ val orientation: HeldOrientation,+ /**+ * Rotation to apply to the edge bubble so it stays horizontal in the real world.+ *+ * Compensates for the gap between how the device is physically held and how the+ * activity happens to be rotated, which is why the level does not depend on+ * auto-rotate being enabled.+ */+ val uiRotationDeg: Float,+)++/**+ * Gravity-derived tilt for the bubble level.+ *+ * Uses `TYPE_GRAVITY` in preference to the raw accelerometer: the fused gravity sensor+ * has already had linear acceleration removed, so the bubble does not lurch when the+ * phone is set down. Falls back to the accelerometer where gravity is unavailable.+ *+ * `SENSOR_DELAY_UI` rather than `GAME` — a spirit level is read by eye, and the faster+ * rate only adds jitter and power draw.+ */+class TiltSensor(context: Context) : SensorEventListener {++ private val sensorManager =+ context.getSystemService(Context.SENSOR_SERVICE) as SensorManager++ @Suppress("DEPRECATION")+ private val windowManager =+ context.getSystemService(Context.WINDOW_SERVICE) as WindowManager?++ private val _tilt = MutableStateFlow<Tilt?>(null)+ val tilt: StateFlow<Tilt?> = _tilt++ private var sx = 0.0+ private var sy = 0.0+ private var sz = 0.0+ private var first = true+ private var running = false++ /** Calibration offsets, subtracted from every reading. */+ private var pitchOffset = 0.0+ private var rollOffset = 0.0+ private var edgeOffset = 0.0++ private var lastRawPitch = 0.0+ private var lastRawRoll = 0.0+ private var lastRawEdge = 0.0++ fun start() {+ if (running) return+ val sensor = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY)+ ?: sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)+ ?: return+ sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI)+ running = true+ first = true+ }++ fun stop() {+ if (!running) return+ sensorManager.unregisterListener(this)+ running = false+ }++ fun setCalibration(pitch: Double, roll: Double, edge: Double) {+ pitchOffset = pitch+ rollOffset = roll+ edgeOffset = edge+ }++ /** Zero the level against whatever surface the device is resting on right now. */+ fun captureZero(): Triple<Double, Double, Double> {+ pitchOffset = lastRawPitch+ rollOffset = lastRawRoll+ edgeOffset = lastRawEdge+ return Triple(pitchOffset, rollOffset, edgeOffset)+ }++ fun clearCalibration() {+ pitchOffset = 0.0+ rollOffset = 0.0+ edgeOffset = 0.0+ }++ override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}++ override fun onSensorChanged(event: SensorEvent) {+ val x = event.values[0].toDouble()+ val y = event.values[1].toDouble()+ val z = event.values[2].toDouble()++ if (first) {+ sx = x; sy = y; sz = z+ first = false+ } else {+ sx += (x - sx) * ALPHA+ sy += (y - sy) * ALPHA+ sz += (z - sz) * ALPHA+ }++ val r = LevelMath.fromGravity(sx, sy, sz)+ lastRawPitch = r.pitchDeg+ lastRawRoll = r.rollDeg+ lastRawEdge = r.edgeAngleDeg++ _tilt.value = Tilt(+ pitchDeg = r.pitchDeg - pitchOffset,+ rollDeg = r.rollDeg - rollOffset,+ edgeAngleDeg = r.edgeAngleDeg - edgeOffset,+ isFlat = r.isFlat,+ orientation = r.orientation,+ uiRotationDeg = LevelMath.uiRotation(r.quadrant, displayRotationDeg()),+ )+ }++ @Suppress("DEPRECATION")+ private fun displayRotationDeg(): Int = when (windowManager?.defaultDisplay?.rotation) {+ Surface.ROTATION_90 -> 90+ Surface.ROTATION_180 -> 180+ Surface.ROTATION_270 -> 270+ else -> 0+ }++ private companion object {+ const val ALPHA = 0.2+ }+}
measure/src/main/java/com/vayunmathur/measure/ui/MeasureUiContract.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/MeasureUiContract.kt b/measure/src/main/java/com/vayunmathur/measure/ui/MeasureUiContract.ktnew file mode 100644index 0000000000..5d4b55234e--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/ui/MeasureUiContract.kt@@ -0,0 +1,196 @@+package com.vayunmathur.measure.ui++import com.vayunmathur.measure.data.model.Anchor+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.domain.sensor.HeldOrientation++/**+ * The UI contract between [MeasureViewModel] and the pages in `ui.pages`.+ *+ * Pages take a state value plus an actions interface rather than the ViewModel itself, so+ * they can be rendered by a `@Preview` — which is what the store listing images are+ * generated from (see `src/screenshotTest`). It lives beside the ViewModel rather than in+ * `ui.pages` so the dependency runs one way: `ui.pages` depends on `ui`, and the ViewModel+ * implements these interfaces.+ *+ * Every actions method has a no-op default body, so [CompassActions.Noop] and friends are+ * the whole implementation a preview needs.+ */++/**+ * Compass dial state. Both azimuths are carried so the dial can switch between them+ * without a round trip to the sensor layer, and [declinationDeg] is shown outright+ * because the difference is the entire reason the toggle exists.+ */+data class CompassUiState(+ val azimuthTrueDeg: Double = 0.0,+ val azimuthMagDeg: Double = 0.0,+ val declinationDeg: Double = 0.0,+ val useTrueNorth: Boolean = true,+ /** Null until a location fix resolves; declination is unknown until then. */+ val hasLocation: Boolean = false,+ /** Mirrors SensorManager.SENSOR_STATUS_* — drives the figure-8 calibration prompt. */+ val accuracy: Int = 3,+ /** Bearing the user has pinned, in degrees, or null when not holding one. */+ val heldBearingDeg: Double? = null,+ val tiltWarning: Boolean = false,+)++interface CompassActions {+ fun setUseTrueNorth(v: Boolean) {}+ fun holdBearing() {}+ fun clearHeldBearing() {}++ companion object {+ val Noop: CompassActions = object : CompassActions {}+ }+}++/**+ * Bubble level state. Every angle is already zero-offset corrected by the binder, so+ * the page draws them directly.+ */+data class LevelUiState(+ val pitchDeg: Double = 0.0,+ val rollDeg: Double = 0.0,+ /**+ * Deviation of the down-facing edge from level, measured against the nearest+ * quarter turn so it reads correctly in portrait, upside down, or on either side.+ */+ val edgeAngleDeg: Double = 0.0,+ /** True when the device is flat enough that the 2D surface bubble is the useful view. */+ val isFlat: Boolean = false,+ val orientation: HeldOrientation = HeldOrientation.Portrait,+ /** Rotation keeping the edge bubble horizontal in the real world. */+ val uiRotationDeg: Float = 0f,+ val isCalibrated: Boolean = false,+ val unitSystem: UnitSystem = UnitSystem.Metric,+)++interface LevelActions {+ fun calibrateZero() {}+ fun clearCalibration() {}++ companion object {+ val Noop: LevelActions = object : LevelActions {}+ }+}++/**+ * On-screen ruler state. [pixelsPerMm] is derived from the display's reported physical+ * pixel density.+ */+data class RulerUiState(+ val pixelsPerMm: Float = 1f,+ val unitSystem: UnitSystem = UnitSystem.Metric,+)++/**+ * AR measurement state.+ *+ * [quality] gates the whole screen: monocular visual-inertial odometry cannot recover+ * metric scale from rotation alone, so until the user has translated the device enough to+ * triangulate, every distance would be scale-free and therefore meaningless. The page shows+ * the initialisation coach instead of anchors while [quality] is [TrackingQuality.Initialising].+ */+data class ArMeasureUiState(+ val quality: TrackingQuality = TrackingQuality.Initialising,+ val anchors: List<Anchor> = emptyList(),+ /** Metres. Null when fewer than two anchors are placed. */+ val distanceM: Double? = null,+ /** Square metres. Null unless the polygon is closed with three or more anchors. */+ val areaM2: Double? = null,+ /** Metres. Null unless the polygon is closed. */+ val perimeterM: Double? = null,+ val polygonClosed: Boolean = false,+ /** True once a gravity-aligned plane has been fitted and anchors can snap to it. */+ val hasPlane: Boolean = false,+ val unitSystem: UnitSystem = UnitSystem.Metric,+ val cameraPermissionGranted: Boolean = false,+)++interface ArMeasureActions {+ /** Screen-space tap, normalised to 0..1 on both axes so the page need not know the resolution. */+ fun placeAnchor(nx: Float, ny: Float) {}+ fun undoAnchor() {}+ fun clearAnchors() {}+ fun closePolygon() {}+ fun saveCurrentMeasurement(label: String) {}+ fun resetTracking() {}++ companion object {+ val Noop: ArMeasureActions = object : ArMeasureActions {}+ }+}++/** Saved measurement list state. */+data class SavedUiState(+ val measurements: List<SavedMeasurement> = emptyList(),+ val unitSystem: UnitSystem = UnitSystem.Metric,+)++interface SavedActions {+ fun delete(id: Long) {}+ fun rename(id: Long, label: String) {}+ fun exportAll() {}++ companion object {+ val Noop: SavedActions = object : SavedActions {}+ }+}++/** Everything the settings screen draws. */+data class SettingsUiState(+ val unitSystem: UnitSystem = UnitSystem.Metric,+ /** Show imperial lengths as 1/16" fractions rather than decimal inches. */+ val useFractionalInches: Boolean = true,+ val useTrueNorth: Boolean = true,+ val levelCalibrated: Boolean = false,+ val showDiagnostics: Boolean = false,+ val hapticsEnabled: Boolean = true,+ val keepScreenOn: Boolean = true,+)++interface SettingsActions {+ fun setUnitSystem(v: UnitSystem) {}+ fun setUseFractionalInches(v: Boolean) {}+ fun setUseTrueNorth(v: Boolean) {}+ fun setShowDiagnostics(v: Boolean) {}+ fun setHapticsEnabled(v: Boolean) {}+ fun setKeepScreenOn(v: Boolean) {}+ fun clearLevelCalibration() {}++ companion object {+ val Noop: SettingsActions = object : SettingsActions {}+ }+}++/**+ * Diagnostics state, shown only when [SettingsUiState.showDiagnostics] is on.+ *+ * [timestampSkewMs] is the gap between the camera frame clock and the IMU clock. On devices+ * reporting SENSOR_INFO_TIMESTAMP_SOURCE = REALTIME this should sit near zero; a large or+ * drifting value means the two streams cannot be fused and tracking will not converge.+ */+data class DiagnosticsUiState(+ val featureCount: Int = 0,+ val trackedCount: Int = 0,+ val imuRateHz: Double = 0.0,+ val frameRateHz: Double = 0.0,+ val timestampSkewMs: Double = 0.0,+ val nativeEngineAvailable: Boolean = false,+ val focalPx: Double = 0.0,+ val principalPointPx: Pair<Double, Double> = 0.0 to 0.0,+ val landmarkCount: Int = 0,+ val scaleConfidence: Double = 0.0,+)++interface DiagnosticsActions {+ fun resetTracking() {}++ companion object {+ val Noop: DiagnosticsActions = object : DiagnosticsActions {}+ }+}
measure/src/main/java/com/vayunmathur/measure/ui/MeasureViewModel.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/MeasureViewModel.kt b/measure/src/main/java/com/vayunmathur/measure/ui/MeasureViewModel.ktnew file mode 100644index 0000000000..4230622ffa--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/ui/MeasureViewModel.kt@@ -0,0 +1,363 @@+package com.vayunmathur.measure.ui++import android.app.Application+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.library.sensor.OrientationManager+import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.measure.data.model.Anchor+import com.vayunmathur.measure.data.model.MeasurementKind+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.domain.MeasureNative+import com.vayunmathur.measure.domain.sensor.ImuRecorder+import com.vayunmathur.measure.domain.sensor.TiltSensor+import com.vayunmathur.measure.domain.polygonArea+import com.vayunmathur.measure.domain.polygonPerimeter+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.launch++/**+ * Owns the sensor lifecycles and the VIO session, and implements every actions+ * interface in the UI contract so pages can stay previewable.+ */+class MeasureViewModel(app: Application) : AndroidViewModel(app),+ CompassActions, LevelActions,+ ArMeasureActions, SavedActions, SettingsActions, DiagnosticsActions {++ private val ds = DataStoreUtils.getInstance(app)++ val orientationManager = OrientationManager(app)+ val tiltSensor = TiltSensor(app)+ val imuRecorder = ImuRecorder(app)++ private val _compass = MutableStateFlow(CompassUiState())+ val compass: StateFlow<CompassUiState> = _compass++ private val _level = MutableStateFlow(LevelUiState())+ val level: StateFlow<LevelUiState> = _level++ private val _ruler = MutableStateFlow(RulerUiState())+ val ruler: StateFlow<RulerUiState> = _ruler++ private val _ar = MutableStateFlow(ArMeasureUiState())+ val ar: StateFlow<ArMeasureUiState> = _ar++ private val _saved = MutableStateFlow(SavedUiState())+ val saved: StateFlow<SavedUiState> = _saved++ private val _settings = MutableStateFlow(SettingsUiState())+ val settings: StateFlow<SettingsUiState> = _settings++ private val _diagnostics = MutableStateFlow(DiagnosticsUiState())+ val diagnostics: StateFlow<DiagnosticsUiState> = _diagnostics++ private var nextAnchorId = 1L+ private var nextMeasurementId = 1L++ init {+ loadPreferences()+ observeSensors()+ }++ private fun loadPreferences() {+ val imperial = ds.getBoolean(KEY_IMPERIAL, false)+ val system = if (imperial) UnitSystem.Imperial else UnitSystem.Metric+ val fractional = ds.getBoolean(KEY_FRACTIONAL, true)+ val trueNorth = ds.getBoolean(KEY_TRUE_NORTH, true)+ val diagnostics = ds.getBoolean(KEY_DIAGNOSTICS, false)+ val haptics = ds.getBoolean(KEY_HAPTICS, true)+ val keepOn = ds.getBoolean(KEY_KEEP_SCREEN_ON, true)+ val levelPitch = ds.getDouble(KEY_LEVEL_PITCH)+ val levelRoll = ds.getDouble(KEY_LEVEL_ROLL)+ val levelEdge = ds.getDouble(KEY_LEVEL_EDGE)++ if (levelPitch != null && levelRoll != null) {+ tiltSensor.setCalibration(levelPitch, levelRoll, levelEdge ?: 0.0)+ }++ _settings.value = SettingsUiState(+ unitSystem = system,+ useFractionalInches = fractional,+ useTrueNorth = trueNorth,+ levelCalibrated = levelPitch != null,+ showDiagnostics = diagnostics,+ hapticsEnabled = haptics,+ keepScreenOn = keepOn,+ )+ _compass.value = _compass.value.copy(useTrueNorth = trueNorth)+ _ruler.value = _ruler.value.copy(unitSystem = system)+ _level.value = _level.value.copy(+ unitSystem = system,+ isCalibrated = levelPitch != null,+ )+ _ar.value = _ar.value.copy(unitSystem = system)+ _saved.value = _saved.value.copy(unitSystem = system)+ }++ private fun observeSensors() {+ viewModelScope.launch {+ orientationManager.orientation.collect { o ->+ if (o == null) return@collect+ _compass.value = _compass.value.copy(+ azimuthTrueDeg = o.azimuthTrueDeg,+ azimuthMagDeg = o.azimuthMagDeg,+ declinationDeg = o.declinationDeg,+ accuracy = o.accuracy,+ hasLocation = o.declinationDeg != 0.0,+ )+ }+ }+ viewModelScope.launch {+ tiltSensor.tilt.collect { t ->+ if (t == null) return@collect+ _level.value = _level.value.copy(+ pitchDeg = t.pitchDeg,+ rollDeg = t.rollDeg,+ edgeAngleDeg = t.edgeAngleDeg,+ isFlat = t.isFlat,+ orientation = t.orientation,+ uiRotationDeg = t.uiRotationDeg,+ )+ // Gravity-derived tilt, not the orientation pitch: OrientationManager's+ // remap targets the AR "window" model, where a phone lying flat reads+ // near -90 rather than 0, which would keep this warning permanently on.+ _compass.value = _compass.value.copy(+ tiltWarning = kotlin.math.abs(t.pitchDeg) > COMPASS_TILT_LIMIT_DEG ||+ kotlin.math.abs(t.rollDeg) > COMPASS_TILT_LIMIT_DEG,+ )+ }+ }+ }++ fun startSensors() {+ orientationManager.start()+ tiltSensor.start()+ }++ fun stopSensors() {+ orientationManager.stop()+ tiltSensor.stop()+ }++ /** Set the observer location so magnetic declination can be resolved. */+ fun updateLocation(lat: Double, lon: Double) {+ orientationManager.updateLocation(lat, lon)+ }++ // ---- CompassActions ----++ override fun setUseTrueNorth(v: Boolean) {+ _compass.value = _compass.value.copy(useTrueNorth = v)+ _settings.value = _settings.value.copy(useTrueNorth = v)+ persistBoolean(KEY_TRUE_NORTH, v)+ }++ override fun holdBearing() {+ val s = _compass.value+ val bearing = if (s.useTrueNorth) s.azimuthTrueDeg else s.azimuthMagDeg+ _compass.value = s.copy(heldBearingDeg = bearing)+ }++ override fun clearHeldBearing() {+ _compass.value = _compass.value.copy(heldBearingDeg = null)+ }++ // ---- LevelActions ----++ override fun calibrateZero() {+ val (pitch, roll, edge) = tiltSensor.captureZero()+ _level.value = _level.value.copy(isCalibrated = true)+ _settings.value = _settings.value.copy(levelCalibrated = true)+ viewModelScope.launch {+ ds.setDouble(KEY_LEVEL_PITCH, pitch)+ ds.setDouble(KEY_LEVEL_ROLL, roll)+ ds.setDouble(KEY_LEVEL_EDGE, edge)+ }+ }++ override fun clearCalibration() {+ tiltSensor.clearCalibration()+ _level.value = _level.value.copy(isCalibrated = false)+ _settings.value = _settings.value.copy(levelCalibrated = false)+ viewModelScope.launch {+ ds.setDouble(KEY_LEVEL_PITCH, Double.NaN)+ ds.setDouble(KEY_LEVEL_ROLL, Double.NaN)+ ds.setDouble(KEY_LEVEL_EDGE, Double.NaN)+ }+ }++ /** Ruler scale, taken from the display's reported physical pixel density. */+ fun setPixelsPerMm(v: Float) {+ if (v > 0f) _ruler.value = _ruler.value.copy(pixelsPerMm = v)+ }++ // ---- ArMeasureActions ----++ fun onTrackingUpdate(quality: TrackingQuality, hasPlane: Boolean) {+ _ar.value = _ar.value.copy(quality = quality, hasPlane = hasPlane)+ }++ fun setCameraPermission(granted: Boolean) {+ _ar.value = _ar.value.copy(cameraPermissionGranted = granted)+ }++ /** Called by the AR page with a world point resolved by the native engine. */+ fun addResolvedAnchor(x: Double, y: Double, z: Double, onPlane: Boolean) {+ val anchor = Anchor(nextAnchorId++, x, y, z, onPlane)+ val anchors = _ar.value.anchors + anchor+ _ar.value = _ar.value.copy(anchors = anchors).recomputed()+ }++ override fun undoAnchor() {+ val anchors = _ar.value.anchors.dropLast(1)+ _ar.value = _ar.value.copy(anchors = anchors, polygonClosed = false).recomputed()+ }++ override fun clearAnchors() {+ _ar.value = _ar.value.copy(+ anchors = emptyList(),+ distanceM = null,+ areaM2 = null,+ perimeterM = null,+ polygonClosed = false,+ )+ }++ override fun closePolygon() {+ if (_ar.value.anchors.size < 3) return+ _ar.value = _ar.value.copy(polygonClosed = true).recomputed()+ }++ override fun saveCurrentMeasurement(label: String) {+ val s = _ar.value+ val (kind, value) = when {+ s.polygonClosed && s.areaM2 != null -> MeasurementKind.Area to s.areaM2+ s.distanceM != null -> MeasurementKind.Distance to s.distanceM+ else -> return+ }+ val m = SavedMeasurement(+ id = nextMeasurementId++,+ label = label.ifBlank { "Measurement" },+ kind = kind,+ value = value ?: return,+ recordedAtEpochMs = System.currentTimeMillis(),+ )+ _saved.value = _saved.value.copy(measurements = _saved.value.measurements + m)+ }++ override fun resetTracking() {+ clearAnchors()+ _ar.value = _ar.value.copy(quality = TrackingQuality.Initialising, hasPlane = false)+ }++ /**+ * Recompute derived measurements from the anchor list.+ *+ * Distance is between the last two anchors; area and perimeter only once the+ * polygon is explicitly closed, since an open chain has no meaningful area.+ */+ private fun ArMeasureUiState.recomputed(): ArMeasureUiState {+ val distance = if (anchors.size >= 2) {+ anchors[anchors.size - 2].distanceTo(anchors[anchors.size - 1])+ } else {+ null+ }+ val area = if (polygonClosed && anchors.size >= 3) polygonArea(anchors) else null+ val perimeter = if (polygonClosed && anchors.size >= 3) {+ polygonPerimeter(anchors, closed = true)+ } else {+ null+ }+ return copy(distanceM = distance, areaM2 = area, perimeterM = perimeter)+ }++ // ---- SavedActions ----++ override fun delete(id: Long) {+ _saved.value = _saved.value.copy(+ measurements = _saved.value.measurements.filterNot { it.id == id }+ )+ }++ override fun rename(id: Long, label: String) {+ _saved.value = _saved.value.copy(+ measurements = _saved.value.measurements.map {+ if (it.id == id) it.copy(label = label) else it+ }+ )+ }++ // ---- SettingsActions ----++ override fun setUnitSystem(v: UnitSystem) {+ _settings.value = _settings.value.copy(unitSystem = v)+ _ruler.value = _ruler.value.copy(unitSystem = v)+ _level.value = _level.value.copy(unitSystem = v)+ _ar.value = _ar.value.copy(unitSystem = v)+ _saved.value = _saved.value.copy(unitSystem = v)+ persistBoolean(KEY_IMPERIAL, v == UnitSystem.Imperial)+ }++ override fun setUseFractionalInches(v: Boolean) {+ _settings.value = _settings.value.copy(useFractionalInches = v)+ persistBoolean(KEY_FRACTIONAL, v)+ }++ override fun setShowDiagnostics(v: Boolean) {+ _settings.value = _settings.value.copy(showDiagnostics = v)+ persistBoolean(KEY_DIAGNOSTICS, v)+ }++ override fun setHapticsEnabled(v: Boolean) {+ _settings.value = _settings.value.copy(hapticsEnabled = v)+ persistBoolean(KEY_HAPTICS, v)+ }++ override fun setKeepScreenOn(v: Boolean) {+ _settings.value = _settings.value.copy(keepScreenOn = v)+ persistBoolean(KEY_KEEP_SCREEN_ON, v)+ }++ override fun clearLevelCalibration() = clearCalibration()++ // ---- DiagnosticsActions ----++ fun updateDiagnostics(update: DiagnosticsUiState.() -> DiagnosticsUiState) {+ _diagnostics.value = _diagnostics.value.update()+ }++ private fun persistBoolean(key: String, value: Boolean) {+ viewModelScope.launch { ds.setBoolean(key, value) }+ }++ override fun onCleared() {+ stopSensors()+ imuRecorder.stop()+ }++ companion object {+ private const val COMPASS_TILT_LIMIT_DEG = 35.0++ private const val KEY_IMPERIAL = "measure_imperial"+ private const val KEY_FRACTIONAL = "measure_fractional_inches"+ private const val KEY_TRUE_NORTH = "measure_true_north"+ private const val KEY_DIAGNOSTICS = "measure_show_diagnostics"+ private const val KEY_HAPTICS = "measure_haptics"+ private const val KEY_KEEP_SCREEN_ON = "measure_keep_screen_on"+ private const val KEY_LEVEL_PITCH = "measure_level_pitch_offset"+ private const val KEY_LEVEL_ROLL = "measure_level_roll_offset"+ private const val KEY_LEVEL_EDGE = "measure_level_edge_offset"+ }+}++/** Quality code from the native engine mapped onto the UI enum. */+fun trackingQualityFrom(code: Int): TrackingQuality = when (code) {+ MeasureNative.QUALITY_LIMITED -> TrackingQuality.Limited+ MeasureNative.QUALITY_GOOD -> TrackingQuality.Good+ MeasureNative.QUALITY_LOST -> TrackingQuality.Lost+ else -> TrackingQuality.Initialising+}
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.ktnew file mode 100644index 0000000000..86cd9284d9--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/ui/components/MeasureCamera.kt@@ -0,0 +1,188 @@+package com.vayunmathur.measure.ui.components++import android.content.Context+import android.util.Size+import androidx.camera.compose.CameraXViewfinder+import androidx.camera.core.CameraSelector+import androidx.camera.core.ImageAnalysis+import androidx.camera.core.ImageProxy+import androidx.camera.core.Preview+import androidx.camera.core.SurfaceRequest+import androidx.camera.core.resolutionselector.ResolutionSelector+import androidx.camera.core.resolutionselector.ResolutionStrategy+import androidx.camera.lifecycle.ProcessCameraProvider+import androidx.camera.lifecycle.awaitInstance+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalLifecycleOwner+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.repeatOnLifecycle+import com.vayunmathur.measure.domain.CameraIntrinsicsResolver+import com.vayunmathur.measure.domain.MeasureNative+import com.vayunmathur.measure.domain.sensor.ImuRecorder+import kotlinx.coroutines.awaitCancellation+import kotlinx.coroutines.flow.MutableStateFlow+import java.util.concurrent.Executors++/**+ * Per-frame diagnostics: frame rate, camera/IMU clock skew, IMU rate, tracked feature+ * count, landmark count and scale confidence.+ */+typealias Diagnostics = (Double, Double, Double, Int, Int, Double) -> Unit++/** Analysis resolution: enough texture for tracking, cheap enough to run every frame. */+private val ANALYSIS_SIZE = Size(640, 480)++/**+ * Camera viewfinder plus the frame pump that drives the VIO engine.+ *+ * The analyser hands the Y plane straight to JNI. No Bitmap is allocated and no colour+ * conversion happens: tracking only needs luminance, and an RGB conversion every frame+ * would dominate the pipeline's cost.+ */+@Composable+fun MeasureCamera(+ imuRecorder: ImuRecorder,+ onTrackingUpdate: (quality: Int, hasPlane: Boolean) -> Unit,+ onSessionReady: (handle: Long) -> Unit,+ modifier: Modifier = Modifier,+ onDiagnostics: Diagnostics = { _, _, _, _, _, _ -> },+) {+ val context = LocalContext.current+ val lifecycleOwner = LocalLifecycleOwner.current+ val surfaceRequest = remember { MutableStateFlow<SurfaceRequest?>(null) }+ val surfaceReqState by surfaceRequest.collectAsState()++ LaunchedEffect(lifecycleOwner) {+ lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {+ val executor = Executors.newSingleThreadExecutor()+ var provider: ProcessCameraProvider? = null+ val handle = createSession(context)+ onSessionReady(handle)+ try {+ provider = ProcessCameraProvider.awaitInstance(context)+ provider.unbindAll()++ val preview = Preview.Builder().build()+ preview.setSurfaceProvider { req -> surfaceRequest.value = req }++ val analysis = ImageAnalysis.Builder()+ .setResolutionSelector(+ ResolutionSelector.Builder()+ .setResolutionStrategy(+ ResolutionStrategy(+ ANALYSIS_SIZE,+ ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER,+ )+ )+ .build()+ )+ // Tracking must act on the newest frame; a backlog would feed the+ // estimator stale motion and make it diverge.+ .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)+ .setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888)+ .build()+ .also {+ it.setAnalyzer(+ executor,+ VioFrameAnalyzer(handle, imuRecorder, onTrackingUpdate, onDiagnostics),+ )+ }++ imuRecorder.start()+ provider.bindToLifecycle(+ lifecycleOwner,+ CameraSelector.DEFAULT_BACK_CAMERA,+ preview,+ analysis,+ )+ awaitCancellation()+ } finally {+ imuRecorder.stop()+ provider?.unbindAll()+ executor.shutdown()+ MeasureNative.destroySession(handle)+ surfaceRequest.value = null+ onSessionReady(0L)+ }+ }+ }++ surfaceReqState?.let { req ->+ CameraXViewfinder(surfaceRequest = req, modifier = modifier.fillMaxSize())+ }+}++private fun createSession(context: Context): Long {+ val intr = CameraIntrinsicsResolver.resolve(context, ANALYSIS_SIZE) ?: return 0L+ return MeasureNative.createSession(intr.fx, intr.fy, intr.cx, intr.cy)+}++private class VioFrameAnalyzer(+ private val handle: Long,+ private val imuRecorder: ImuRecorder,+ private val onTrackingUpdate: (Int, Boolean) -> Unit,+ private val onDiagnostics: Diagnostics,+) : ImageAnalysis.Analyzer {++ private var buffer: ByteArray? = null+ private var lastFrameNs = 0L+ private var frameIntervalNs = 0L++ override fun analyze(image: ImageProxy) {+ try {+ if (handle == 0L) return++ // Drain IMU first so every sample older than this frame is already queued,+ // which is what lets the engine preintegrate over the correct interval.+ val imu = imuRecorder.drain()+ if (imu.isNotEmpty()) MeasureNative.pushImu(handle, imu)++ val plane = image.planes[0]+ val src = plane.buffer+ val needed = src.remaining()+ val dst = buffer?.takeIf { it.size >= needed } ?: ByteArray(needed).also { buffer = it }+ src.get(dst, 0, needed)++ val tNs = image.imageInfo.timestamp+ val quality = MeasureNative.pushFrame(+ handle = handle,+ yPlane = dst,+ width = image.width,+ height = image.height,+ rowStride = plane.rowStride,+ timestampNs = tNs,+ )++ val state = MeasureNative.getState(handle)+ val hasPlane = state != null && state[4] > 0.5+ onTrackingUpdate(quality, hasPlane)++ if (lastFrameNs != 0L) {+ frameIntervalNs = (frameIntervalNs * 3 + (tNs - lastFrameNs)) / 4+ }+ lastFrameNs = tNs+ val fps = if (frameIntervalNs > 0) 1e9 / frameIntervalNs else 0.0+ // Camera and IMU share the REALTIME clock on supported devices, so this gap+ // should stay near zero. A large or growing value means the streams cannot+ // be fused and tracking will not converge.+ val skewMs = (tNs - imuRecorder.lastTimestampNs()) / 1e6+ onDiagnostics(+ fps,+ skewMs,+ imuRecorder.rateHz(),+ state?.get(3)?.toInt() ?: 0,+ state?.get(2)?.toInt() ?: 0,+ state?.get(1) ?: 0.0,+ )+ } finally {+ image.close()+ }+ }+}
measure/src/main/java/com/vayunmathur/measure/ui/pages/ArMeasurePage.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/pages/ArMeasurePage.kt b/measure/src/main/java/com/vayunmathur/measure/ui/pages/ArMeasurePage.ktnew file mode 100644index 0000000000..667629b2c0--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/ui/pages/ArMeasurePage.kt@@ -0,0 +1,370 @@+package com.vayunmathur.measure.ui.pages++import android.Manifest+import android.content.pm.PackageManager+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.Canvas+import androidx.compose.foundation.background+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.onSizeChanged+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.unit.dp+import androidx.core.content.ContextCompat+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconSettings+import com.vayunmathur.library.ui.IconUndo+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.measure.Route+import com.vayunmathur.measure.data.model.TrackingQuality+import com.vayunmathur.measure.domain.MeasureNative+import com.vayunmathur.measure.domain.Units+import com.vayunmathur.measure.ui.ArMeasureActions+import com.vayunmathur.measure.ui.ArMeasureUiState+import com.vayunmathur.measure.ui.MeasureViewModel+import com.vayunmathur.measure.ui.components.MeasureCamera+import com.vayunmathur.measure.ui.trackingQualityFrom+import kotlinx.coroutines.delay++@Composable+fun ArMeasurePage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) {+ val state by viewModel.ar.collectAsState()+ var sessionHandle by remember { mutableLongStateOf(0L) }+ var screenPoints by remember { mutableStateOf<List<Offset>>(emptyList()) }+ var canvasSize by remember { mutableStateOf(Size.Zero) }++ val cameraGranted = rememberCameraPermission { viewModel.setCameraPermission(it) }++ // Reproject anchors whenever the anchor set or the pose changes. Projection lives+ // in the engine because it owns the current pose and the intrinsics.+ LaunchedEffect(state.anchors, state.quality, canvasSize) {+ if (sessionHandle == 0L || canvasSize == Size.Zero || state.anchors.isEmpty()) {+ screenPoints = emptyList()+ return@LaunchedEffect+ }+ while (true) {+ val flat = DoubleArray(state.anchors.size * 3)+ state.anchors.forEachIndexed { i, a ->+ flat[i * 3] = a.x+ flat[i * 3 + 1] = a.y+ flat[i * 3 + 2] = a.z+ }+ val projected = MeasureNative.projectPoints(+ sessionHandle,+ flat,+ canvasSize.width.toDouble(),+ canvasSize.height.toDouble(),+ )+ screenPoints = projected.toList().chunked(3).map { c ->+ Offset(c[0].toFloat() * canvasSize.width, c[1].toFloat() * canvasSize.height)+ }+ delay(PROJECTION_INTERVAL_MS)+ }+ }++ ArMeasureContent(+ state = state,+ actions = viewModel,+ screenPoints = screenPoints,+ onCanvasSized = { canvasSize = it },+ onTap = { nx, ny ->+ if (canvasSize != Size.Zero) {+ val hit = MeasureNative.rayToWorld(+ sessionHandle,+ nx * canvasSize.width,+ ny * canvasSize.height,+ )+ if (hit != null) {+ viewModel.addResolvedAnchor(hit[0], hit[1], hit[2], hit[3] > 0.5)+ }+ }+ },+ cameraContent = {+ if (cameraGranted && MeasureNative.available) {+ MeasureCamera(+ imuRecorder = viewModel.imuRecorder,+ onTrackingUpdate = { q, hasPlane ->+ viewModel.onTrackingUpdate(trackingQualityFrom(q), hasPlane)+ },+ onSessionReady = { sessionHandle = it },+ onDiagnostics = { fps, skew, imuHz, tracked, landmarks, confidence ->+ viewModel.updateDiagnostics {+ copy(+ frameRateHz = fps,+ timestampSkewMs = skew,+ imuRateHz = imuHz,+ trackedCount = tracked,+ featureCount = tracked,+ landmarkCount = landmarks,+ scaleConfidence = confidence,+ nativeEngineAvailable = MeasureNative.available,+ )+ }+ },+ modifier = Modifier.fillMaxSize(),+ )+ }+ },+ onOpenSettings = { backStack.add(Route.Settings) },+ bottomBar = { MeasureBottomBar(backStack, Route.ArMeasure) },+ )+}++/** Requests CAMERA lazily, so the four sensor tools never trigger a camera prompt. */+@Composable+private fun rememberCameraPermission(onResult: (Boolean) -> Unit): Boolean {+ val context = LocalContext.current+ var granted by remember {+ mutableStateOf(+ ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) ==+ PackageManager.PERMISSION_GRANTED+ )+ }+ val launcher = rememberLauncherForActivityResult(+ ActivityResultContracts.RequestPermission()+ ) { result ->+ granted = result+ onResult(result)+ }+ LaunchedEffect(Unit) {+ onResult(granted)+ if (!granted) launcher.launch(Manifest.permission.CAMERA)+ }+ return granted+}++private const val PROJECTION_INTERVAL_MS = 33L++@Composable+fun ArMeasureContent(+ state: ArMeasureUiState,+ actions: ArMeasureActions,+ screenPoints: List<Offset> = emptyList(),+ onCanvasSized: (Size) -> Unit = {},+ onTap: (Float, Float) -> Unit = { _, _ -> },+ cameraContent: @Composable () -> Unit = {},+ onOpenSettings: () -> Unit = {},+ bottomBar: @Composable () -> Unit = {},+) {+ AppScaffold(+ title = "Measure",+ actions = { IconButton(onClick = onOpenSettings) { IconSettings() } },+ bottomBar = bottomBar,+ ) { padding ->+ Box(Modifier.fillMaxSize().padding(padding)) {++ if (!MeasureNative.available) {+ UnavailableNotice(+ "AR measuring needs the native tracking engine, which isn't available " ++ "on this device."+ )+ return@Box+ }+ if (!state.cameraPermissionGranted) {+ UnavailableNotice("Camera access is needed to measure in AR.")+ return@Box+ }++ cameraContent()++ ArOverlay(+ state = state,+ screenPoints = screenPoints,+ onCanvasSized = onCanvasSized,+ onTap = onTap,+ modifier = Modifier.fillMaxSize(),+ )++ Column(+ modifier = Modifier.align(Alignment.TopCenter).padding(12.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(6.dp),+ ) {+ TrackingBanner(state.quality, state.hasPlane)+ }++ Column(+ modifier = Modifier.align(Alignment.BottomCenter).padding(16.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ ReadoutCard(state)+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ OutlinedButton(+ onClick = { actions.undoAnchor() },+ enabled = state.anchors.isNotEmpty(),+ ) { IconUndo() }+ OutlinedButton(+ onClick = { actions.closePolygon() },+ enabled = state.anchors.size >= 3 && !state.polygonClosed,+ ) { Text("Close shape") }+ OutlinedButton(+ onClick = { actions.clearAnchors() },+ enabled = state.anchors.isNotEmpty(),+ ) { Text("Clear") }+ }+ }+ }+ }+}++/**+ * Coaching banner.+ *+ * While initialising this is not decoration — monocular visual-inertial tracking cannot+ * recover metric scale from rotation alone, so the user genuinely has to translate the+ * device before any distance exists. Saying so plainly is more useful than a spinner.+ */+@Composable+private fun TrackingBanner(quality: TrackingQuality, hasPlane: Boolean) {+ val (message, color) = when (quality) {+ TrackingQuality.Initialising ->+ "Move the phone sideways and turn it slightly to start tracking" to+ MaterialTheme.colorScheme.tertiaryContainer++ TrackingQuality.Limited ->+ "Tracking is weak — move slowly and keep texture in view" to+ MaterialTheme.colorScheme.tertiaryContainer++ TrackingQuality.Lost ->+ "Tracking lost — point at a textured surface to recover" to+ MaterialTheme.colorScheme.errorContainer++ TrackingQuality.Good ->+ (if (hasPlane) "Ready — tap to place points" else "Ready — no surface found yet") to+ MaterialTheme.colorScheme.primaryContainer+ }+ Box(+ Modifier+ .clip(RoundedCornerShape(12.dp))+ .background(color)+ .padding(horizontal = 14.dp, vertical = 8.dp)+ ) {+ Text(message, style = MaterialTheme.typography.bodyMedium)+ }+}++@Composable+private fun ReadoutCard(state: ArMeasureUiState) {+ if (state.distanceM == null && state.areaM2 == null) return+ Box(+ Modifier+ .clip(RoundedCornerShape(12.dp))+ .background(MaterialTheme.colorScheme.surface.copy(alpha = 0.85f))+ .padding(horizontal = 16.dp, vertical = 10.dp)+ ) {+ Column(horizontalAlignment = Alignment.CenterHorizontally) {+ state.distanceM?.let {+ Text(+ Units.formatLength(it, state.unitSystem),+ style = MaterialTheme.typography.headlineSmall,+ )+ }+ state.areaM2?.let {+ Text(+ "Area ${Units.formatArea(it, state.unitSystem)}",+ style = MaterialTheme.typography.bodyMedium,+ )+ }+ state.perimeterM?.let {+ Text(+ "Perimeter ${Units.formatLength(it, state.unitSystem)}",+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+ }+}++/**+ * Anchor and edge overlay.+ *+ * Anchors are drawn from screen positions the engine projected from their world+ * coordinates, so this layer holds no projection maths and stays previewable.+ */+@Composable+private fun ArOverlay(+ state: ArMeasureUiState,+ screenPoints: List<Offset>,+ onCanvasSized: (Size) -> Unit,+ onTap: (Float, Float) -> Unit,+ modifier: Modifier = Modifier,+) {+ val primary = MaterialTheme.colorScheme.primary+ val onPrimary = MaterialTheme.colorScheme.onPrimary+ val measurable = state.quality == TrackingQuality.Good ||+ state.quality == TrackingQuality.Limited++ Canvas(+ modifier+ .onSizeChanged { onCanvasSized(Size(it.width.toFloat(), it.height.toFloat())) }+ .pointerInput(measurable) {+ if (!measurable) return@pointerInput+ detectTapGestures { pos ->+ onTap(pos.x / size.width, pos.y / size.height)+ }+ }+ ) {+ // Reticle at the centre, showing where a tap would land.+ if (measurable) {+ val c = Offset(size.width / 2f, size.height / 2f)+ drawCircle(primary.copy(alpha = 0.9f), 6f, c)+ drawCircle(primary.copy(alpha = 0.4f), 22f, c, style = Stroke(2f))+ }++ for (i in 0 until screenPoints.size - 1) {+ drawLine(primary, screenPoints[i], screenPoints[i + 1], 4f)+ }+ if (state.polygonClosed && screenPoints.size >= 3) {+ drawLine(primary, screenPoints.last(), screenPoints.first(), 4f)+ }+ for (p in screenPoints) {+ drawCircle(primary, 12f, p)+ drawCircle(onPrimary, 5f, p)+ }+ }+}++@Composable+private fun UnavailableNotice(message: String) {+ Column(+ modifier = Modifier.fillMaxSize().padding(32.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.Center,+ ) {+ Text("AR measure unavailable", style = MaterialTheme.typography.titleMedium)+ Text(+ message,+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+}+
measure/src/main/java/com/vayunmathur/measure/ui/pages/CompassPage.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/pages/CompassPage.kt b/measure/src/main/java/com/vayunmathur/measure/ui/pages/CompassPage.ktnew file mode 100644index 0000000000..a9f961751c--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/ui/pages/CompassPage.kt@@ -0,0 +1,258 @@+package com.vayunmathur.measure.ui.pages++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.collectAsState+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.graphics.drawscope.rotate+import androidx.compose.ui.text.TextMeasurer+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.rememberTextMeasurer+import androidx.compose.ui.text.drawText+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.ui.IconSettings+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.measure.Route+import com.vayunmathur.measure.domain.Units+import com.vayunmathur.measure.ui.CompassActions+import com.vayunmathur.measure.ui.CompassUiState+import com.vayunmathur.measure.ui.MeasureViewModel+import kotlin.math.cos+import kotlin.math.sin++@Composable+fun CompassPage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) {+ val state by viewModel.compass.collectAsState()+ CompassContent(+ state = state,+ actions = viewModel,+ onOpenSettings = { backStack.add(Route.Settings) },+ bottomBar = { MeasureBottomBar(backStack, Route.Compass) },+ )+}++@Composable+fun CompassContent(+ state: CompassUiState,+ actions: CompassActions,+ onOpenSettings: () -> Unit = {},+ bottomBar: @Composable () -> Unit = {},+) {+ val heading = if (state.useTrueNorth && state.hasLocation) {+ state.azimuthTrueDeg+ } else {+ state.azimuthMagDeg+ }+ AppScaffold(+ title = "Compass",+ actions = { IconButton(onClick = onOpenSettings) { IconSettings() } },+ bottomBar = bottomBar,+ ) { padding ->+ Column(+ modifier = Modifier.fillMaxSize().padding(padding).padding(16.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(12.dp),+ ) {+ Text(+ "${Units.formatBearing(heading)} ${Units.cardinal(heading)}",+ style = MaterialTheme.typography.displaySmall,+ )+ Text(+ // Without a location fix declination is unknown, so "true north" would+ // be a claim the app cannot back up.+ if (state.useTrueNorth && state.hasLocation) "True north" else "Magnetic north",+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )++ CompassDial(+ headingDeg = heading,+ heldBearingDeg = state.heldBearingDeg,+ // Height-driven so the dial shrinks to fit a landscape window rather+ // than pushing the controls off the bottom.+ modifier = Modifier+ .weight(1f)+ .aspectRatio(1f, matchHeightConstraintsFirst = true)+ .padding(8.dp),+ )++ if (state.accuracy < ACCURACY_HIGH) {+ Text(+ "Compass needs calibration — move the phone in a figure-8",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.error,+ )+ }+ if (state.tiltWarning) {+ Text(+ "Hold the phone flat for an accurate bearing",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.error,+ )+ }+ if (state.hasLocation) {+ Text(+ "Declination ${Units.formatAngle(state.declinationDeg)}",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ } else {+ Text(+ "No location — showing magnetic north only",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }++ Spacer(Modifier.height(4.dp))+ Column(+ verticalArrangement = Arrangement.spacedBy(8.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ OutlinedButton(+ onClick = { actions.setUseTrueNorth(!state.useTrueNorth) },+ enabled = state.hasLocation,+ ) {+ Text(if (state.useTrueNorth) "Show magnetic" else "Show true north")+ }+ OutlinedButton(+ onClick = {+ if (state.heldBearingDeg == null) actions.holdBearing()+ else actions.clearHeldBearing()+ }+ ) {+ Text(if (state.heldBearingDeg == null) "Hold bearing" else "Release bearing")+ }+ }+ }+ }+}++/**+ * Compass rose. The dial rotates opposite the heading so north stays physically north+ * while the fixed top index reads the current bearing.+ */+@Composable+private fun CompassDial(+ headingDeg: Double,+ heldBearingDeg: Double?,+ modifier: Modifier = Modifier,+) {+ val measurer = rememberTextMeasurer()+ val onSurface = MaterialTheme.colorScheme.onSurface+ val variant = MaterialTheme.colorScheme.onSurfaceVariant+ val primary = MaterialTheme.colorScheme.primary+ val error = MaterialTheme.colorScheme.error++ Box(modifier) {+ Canvas(Modifier.fillMaxSize()) {+ val radius = size.minDimension / 2f+ val center = Offset(size.width / 2f, size.height / 2f)++ drawCircle(variant.copy(alpha = 0.3f), radius, center, style = Stroke(2f))++ rotate(-headingDeg.toFloat(), center) {+ drawTicks(center, radius, onSurface, variant)+ drawCardinals(measurer, center, radius, onSurface, error)+ if (heldBearingDeg != null) {+ drawHeldBearing(center, radius, heldBearingDeg.toFloat(), primary)+ }+ }++ // Fixed index at the top: the bearing is whatever sits under it.+ val p = Path().apply {+ moveTo(center.x, center.y - radius - 2f)+ lineTo(center.x - 14f, center.y - radius + 22f)+ lineTo(center.x + 14f, center.y - radius + 22f)+ close()+ }+ drawPath(p, primary)+ }+ }+}++private fun DrawScope.drawTicks(center: Offset, radius: Float, major: Color, minor: Color) {+ for (deg in 0 until 360 step 5) {+ val isMajor = deg % 30 == 0+ val len = if (isMajor) radius * 0.10f else radius * 0.05f+ val rad = Math.toRadians(deg.toDouble() - 90.0)+ val cosA = cos(rad).toFloat()+ val sinA = sin(rad).toFloat()+ drawLine(+ color = if (isMajor) major else minor.copy(alpha = 0.5f),+ start = Offset(center.x + cosA * (radius - len), center.y + sinA * (radius - len)),+ end = Offset(center.x + cosA * radius, center.y + sinA * radius),+ strokeWidth = if (isMajor) 3f else 1.5f,+ )+ }+}++private fun DrawScope.drawCardinals(+ measurer: TextMeasurer,+ center: Offset,+ radius: Float,+ normal: Color,+ northColor: Color,+) {+ val labels = listOf(0 to "N", 90 to "E", 180 to "S", 270 to "W")+ for ((deg, label) in labels) {+ val rad = Math.toRadians(deg.toDouble() - 90.0)+ val r = radius * 0.78f+ val style = TextStyle(+ fontSize = 20.sp,+ color = if (label == "N") northColor else normal,+ )+ val layout = measurer.measure(label, style)+ drawText(+ layout,+ topLeft = Offset(+ center.x + cos(rad).toFloat() * r - layout.size.width / 2f,+ center.y + sin(rad).toFloat() * r - layout.size.height / 2f,+ ),+ )+ }+}++private fun DrawScope.drawHeldBearing(+ center: Offset,+ radius: Float,+ bearingDeg: Float,+ color: Color,+) {+ val rad = Math.toRadians(bearingDeg.toDouble() - 90.0)+ drawLine(+ color = color,+ start = center,+ end = Offset(+ center.x + cos(rad).toFloat() * radius,+ center.y + sin(rad).toFloat() * radius,+ ),+ strokeWidth = 4f,+ )+}++private const val ACCURACY_HIGH = 3+
measure/src/main/java/com/vayunmathur/measure/ui/pages/LevelPage.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/pages/LevelPage.kt b/measure/src/main/java/com/vayunmathur/measure/ui/pages/LevelPage.ktnew file mode 100644index 0000000000..4b5a7ecba1--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/ui/pages/LevelPage.kt@@ -0,0 +1,213 @@+package com.vayunmathur.measure.ui.pages++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.rotate+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconSettings+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.measure.Route+import com.vayunmathur.measure.domain.Units+import com.vayunmathur.measure.domain.sensor.HeldOrientation+import com.vayunmathur.measure.ui.LevelActions+import com.vayunmathur.measure.ui.LevelUiState+import com.vayunmathur.measure.ui.MeasureViewModel+import kotlin.math.abs+import kotlin.math.hypot+import kotlin.math.min++@Composable+fun LevelPage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) {+ val state by viewModel.level.collectAsState()+ LevelContent(+ state = state,+ actions = viewModel,+ onOpenSettings = { backStack.add(Route.Settings) },+ bottomBar = { MeasureBottomBar(backStack, Route.Level) },+ )+}++@Composable+fun LevelContent(+ state: LevelUiState,+ actions: LevelActions,+ onOpenSettings: () -> Unit = {},+ bottomBar: @Composable () -> Unit = {},+) {+ AppScaffold(+ title = "Level",+ actions = { IconButton(onClick = onOpenSettings) { IconSettings() } },+ bottomBar = bottomBar,+ ) { padding ->+ Column(+ modifier = Modifier.fillMaxSize().padding(padding).padding(16.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(16.dp),+ ) {+ val isLevel = if (state.isFlat) {+ abs(state.pitchDeg) < LEVEL_TOLERANCE_DEG && abs(state.rollDeg) < LEVEL_TOLERANCE_DEG+ } else {+ abs(state.edgeAngleDeg) < LEVEL_TOLERANCE_DEG+ }++ Text(+ if (state.isFlat) {+ "${Units.formatAngle(state.pitchDeg)} / ${Units.formatAngle(state.rollDeg)}"+ } else {+ Units.formatAngle(state.edgeAngleDeg)+ },+ style = MaterialTheme.typography.displaySmall,+ color = if (isLevel) {+ MaterialTheme.colorScheme.primary+ } else {+ MaterialTheme.colorScheme.onSurface+ },+ )+ Text(+ if (state.isFlat) "Surface level" else state.orientation.label,+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )++ if (state.isFlat) {+ SurfaceBubble(+ pitchDeg = state.pitchDeg,+ rollDeg = state.rollDeg,+ // Sized from the leftover height, not the width: a width-driven+ // square is taller than a landscape window and pushes the controls+ // off the bottom.+ modifier = Modifier+ .weight(1f)+ .aspectRatio(1f, matchHeightConstraintsFirst = true)+ .padding(16.dp),+ )+ } else {+ EdgeBubble(+ angleDeg = state.edgeAngleDeg,+ // Keeps the bar horizontal in the real world whether or not the+ // activity rotated with the device.+ uiRotationDeg = state.uiRotationDeg,+ modifier = Modifier.fillMaxWidth().weight(1f),+ )+ }++ OutlinedButton(onClick = {+ if (state.isCalibrated) actions.clearCalibration() else actions.calibrateZero()+ }) {+ Text(if (state.isCalibrated) "Clear calibration" else "Set zero here")+ }+ if (state.isCalibrated) {+ Text(+ "Zeroed against a reference surface",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+ }+}++/** Circular two-axis bubble, used when the phone lies flat. */+@Composable+private fun SurfaceBubble(pitchDeg: Double, rollDeg: Double, modifier: Modifier = Modifier) {+ val outline = MaterialTheme.colorScheme.outline+ val primary = MaterialTheme.colorScheme.primary+ val surfaceVariant = MaterialTheme.colorScheme.surfaceVariant+ val level = abs(pitchDeg) < LEVEL_TOLERANCE_DEG && abs(rollDeg) < LEVEL_TOLERANCE_DEG++ Canvas(modifier) {+ val radius = size.minDimension / 2f+ val center = Offset(size.width / 2f, size.height / 2f)+ drawCircle(surfaceVariant, radius, center)+ drawCircle(outline, radius, center, style = Stroke(2f))+ // Inner ring marks the in-tolerance zone. Sized to the bubble so "inside the+ // ring" and "reads level" agree; a ring scaled to the tolerance angle alone+ // would be a couple of pixels across and useless to aim at.+ val bubbleRadius = min(radius * 0.18f, 44f)+ drawCircle(outline, bubbleRadius * 1.35f, center, style = Stroke(2f))+ drawLine(outline, Offset(center.x - radius, center.y), Offset(center.x + radius, center.y), 1f)+ drawLine(outline, Offset(center.x, center.y - radius), Offset(center.x, center.y + radius), 1f)++ // Bubble floats toward the raised side, like a real spirit level.+ val nx = (rollDeg / MAX_DISPLAY_DEG).coerceIn(-1.0, 1.0).toFloat()+ val ny = (-pitchDeg / MAX_DISPLAY_DEG).coerceIn(-1.0, 1.0).toFloat()+ val mag = hypot(nx, ny).coerceAtMost(1f)+ val norm = hypot(nx, ny)+ val dirX = if (norm > 0f) nx / norm else 0f+ val dirY = if (norm > 0f) ny / norm else 0f+ val travel = radius - bubbleRadius+ val pos = Offset(center.x + dirX * mag * travel, center.y + dirY * mag * travel)++ drawCircle(+ color = if (level) primary else primary.copy(alpha = 0.6f),+ radius = bubbleRadius,+ center = pos,+ )+ }+}++/**+ * Single-axis bubble for a phone stood on any of its four edges.+ *+ * [angleDeg] is already measured against the nearest quarter turn, so this reads the+ * same whether the phone is upright, upside down, or on its side.+ */+@Composable+private fun EdgeBubble(angleDeg: Double, uiRotationDeg: Float, modifier: Modifier = Modifier) {+ val outline = MaterialTheme.colorScheme.outline+ val primary = MaterialTheme.colorScheme.primary+ val surfaceVariant = MaterialTheme.colorScheme.surfaceVariant+ val level = abs(angleDeg) < LEVEL_TOLERANCE_DEG++ Canvas(modifier.rotate(uiRotationDeg)) {+ val barHeight = min(size.height, 90f.coerceAtLeast(size.height * 0.4f))+ val top = (size.height - barHeight) / 2f+ val w = size.width++ drawRoundRect(+ color = surfaceVariant,+ topLeft = Offset(0f, top),+ size = androidx.compose.ui.geometry.Size(w, barHeight),+ cornerRadius = CornerRadius(barHeight / 2f),+ )+ drawLine(outline, Offset(w / 2f, top), Offset(w / 2f, top + barHeight), 2f)++ val bubbleRadius = barHeight * 0.35f+ drawCircle(+ outline,+ bubbleRadius * 1.3f,+ Offset(w / 2f, top + barHeight / 2f),+ style = Stroke(2f),+ )++ val n = (angleDeg / MAX_DISPLAY_DEG).coerceIn(-1.0, 1.0).toFloat()+ val cx = w / 2f + n * (w / 2f - bubbleRadius)+ drawCircle(+ color = if (level) primary else primary.copy(alpha = 0.6f),+ radius = bubbleRadius,+ center = Offset(cx, top + barHeight / 2f),+ )+ }+}++/** Deflection at which the bubble reaches the edge of its travel. */+private const val MAX_DISPLAY_DEG = 15.0+private const val LEVEL_TOLERANCE_DEG = 0.35
measure/src/main/java/com/vayunmathur/measure/ui/pages/MeasureBottomBar.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/pages/MeasureBottomBar.kt b/measure/src/main/java/com/vayunmathur/measure/ui/pages/MeasureBottomBar.ktnew file mode 100644index 0000000000..97d4922a13--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/ui/pages/MeasureBottomBar.kt@@ -0,0 +1,26 @@+package com.vayunmathur.measure.ui.pages++import androidx.compose.runtime.Composable+import com.vayunmathur.library.ui.IconArea+import com.vayunmathur.library.ui.IconCompass+import com.vayunmathur.library.ui.IconRuler+import com.vayunmathur.library.ui.IconToolsLevel+import com.vayunmathur.library.util.BottomBarItem+import com.vayunmathur.library.util.BottomNavBar+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.measure.Route++/** The four tools, as one tab bar shared by every top-level page. */+@Composable+fun MeasureBottomBar(backStack: NavBackStack<Route>, current: Route) {+ BottomNavBar(+ backStack = backStack,+ pages = listOf(+ BottomBarItem("Compass", Route.Compass) { IconCompass() },+ BottomBarItem("Level", Route.Level) { IconToolsLevel() },+ BottomBarItem("Ruler", Route.Ruler) { IconRuler() },+ BottomBarItem("Measure", Route.ArMeasure) { IconArea() },+ ),+ currentPage = current,+ )+}
measure/src/main/java/com/vayunmathur/measure/ui/pages/RulerPage.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/pages/RulerPage.kt b/measure/src/main/java/com/vayunmathur/measure/ui/pages/RulerPage.ktnew file mode 100644index 0000000000..73648aa11a--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/ui/pages/RulerPage.kt@@ -0,0 +1,182 @@+package com.vayunmathur.measure.ui.pages++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.gestures.detectDragGestures+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.drawText+import androidx.compose.ui.text.rememberTextMeasurer+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconSettings+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.measure.Route+import com.vayunmathur.measure.data.model.UnitSystem+import com.vayunmathur.measure.domain.Units+import com.vayunmathur.measure.ui.MeasureViewModel+import com.vayunmathur.measure.ui.RulerUiState++@Composable+fun RulerPage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) {+ val state by viewModel.ruler.collectAsState()+ val context = LocalContext.current++ // ydpi is the display's reported *physical* vertical pixel density, which is a+ // better basis for a real-world scale than density * 160 — the latter is a+ // rendering bucket rounded to a standard step, not a measurement.+ LaunchedEffect(context) {+ val metrics = context.resources.displayMetrics+ val dpi = metrics.ydpi.takeIf { it > 1f } ?: (metrics.density * 160f)+ viewModel.setPixelsPerMm(dpi / Units.MM_PER_INCH.toFloat())+ }++ RulerContent(+ state = state,+ onOpenSettings = { backStack.add(Route.Settings) },+ bottomBar = { MeasureBottomBar(backStack, Route.Ruler) },+ )+}++@Composable+fun RulerContent(+ state: RulerUiState,+ onOpenSettings: () -> Unit = {},+ bottomBar: @Composable () -> Unit = {},+) {+ var markerY by remember { mutableFloatStateOf(0f) }++ AppScaffold(+ title = "Ruler",+ actions = { IconButton(onClick = onOpenSettings) { IconSettings() } },+ bottomBar = bottomBar,+ ) { padding ->+ Column(+ modifier = Modifier.fillMaxSize().padding(padding),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ val fromTopMm = markerY / state.pixelsPerMm++ Text(+ Units.formatLength(fromTopMm / 1000.0, state.unitSystem),+ style = MaterialTheme.typography.headlineMedium,+ modifier = Modifier.padding(top = 8.dp),+ )+ Text(+ "Drag the line; read against either edge",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.padding(bottom = 4.dp),+ )++ RulerScale(+ pixelsPerMm = state.pixelsPerMm,+ unitSystem = state.unitSystem,+ markerY = markerY,+ onMarkerChange = { markerY = it },+ onHeightChange = { h -> if (markerY == 0f) markerY = h / 2f },+ modifier = Modifier.fillMaxWidth().weight(1f),+ )+ }+ }+}++/**+ * Vertical scale down both edges with a draggable measuring marker.+ *+ * Both scales run top-down and read identically, so an object can be laid against+ * whichever edge of the phone is convenient. They deliberately do *not* mirror: opposed+ * scales would be rotationally symmetric, so turning the phone around would give the+ * same reading back and the second scale would earn nothing.+ *+ * Tick spacing is driven by the physical pixel density rather than by dp: dp is a+ * rendering convenience, not a unit of length.+ */+@Composable+private fun RulerScale(+ pixelsPerMm: Float,+ unitSystem: UnitSystem,+ markerY: Float,+ onMarkerChange: (Float) -> Unit,+ onHeightChange: (Float) -> Unit,+ modifier: Modifier = Modifier,+) {+ val measurer = rememberTextMeasurer()+ val onSurface = MaterialTheme.colorScheme.onSurface+ val primary = MaterialTheme.colorScheme.primary+ val variant = MaterialTheme.colorScheme.onSurfaceVariant++ Canvas(+ modifier.pointerInput(Unit) {+ detectDragGestures { change, _ ->+ onMarkerChange(change.position.y.coerceIn(0f, size.height.toFloat()))+ }+ }+ ) {+ onHeightChange(size.height)++ val metric = unitSystem == UnitSystem.Metric+ // Metric: a tick every mm. Imperial: every 1/16 inch.+ val minorStepPx = if (metric) pixelsPerMm else pixelsPerMm * Units.MM_PER_INCH.toFloat() / 16f+ val majorEvery = if (metric) 10 else 16+ val midEvery = if (metric) 5 else 8+ if (minorStepPx <= 0.5f) return@Canvas++ val maxTickLen = size.width * 0.24f++ // `leftEdge` only changes which side the ticks grow from; both scales measure+ // the same distance from the top.+ fun drawEdge(leftEdge: Boolean) {+ var i = 0+ while (true) {+ val y = i * minorStepPx+ if (y > size.height) break+ val isMajor = i % majorEvery == 0+ val isMid = i % midEvery == 0+ val len = when {+ isMajor -> maxTickLen+ isMid -> maxTickLen * 0.62f+ else -> maxTickLen * 0.36f+ }+ val start = if (leftEdge) Offset(0f, y) else Offset(size.width - len, y)+ val end = if (leftEdge) Offset(len, y) else Offset(size.width, y)+ drawLine(+ color = if (isMajor) onSurface else variant,+ start = start,+ end = end,+ strokeWidth = if (isMajor) 3f else 1.5f,+ )+ if (isMajor && i > 0) {+ val label = if (metric) "${i / 10}" else "${i / 16}"+ val layout = measurer.measure(label, TextStyle(fontSize = 13.sp, color = onSurface))+ val lx = if (leftEdge) len + 8f else size.width - len - 8f - layout.size.width+ drawText(layout, topLeft = Offset(lx, y - layout.size.height / 2f))+ }+ i+++ }+ }++ drawEdge(leftEdge = true)+ drawEdge(leftEdge = false)++ drawLine(primary, Offset(0f, markerY), Offset(size.width, markerY), 3f)+ }+}
measure/src/main/java/com/vayunmathur/measure/ui/pages/SettingsPage.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/pages/SettingsPage.kt b/measure/src/main/java/com/vayunmathur/measure/ui/pages/SettingsPage.ktnew file mode 100644index 0000000000..127b2826f2--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/ui/pages/SettingsPage.kt@@ -0,0 +1,261 @@+package com.vayunmathur.measure.ui.pages++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.SettingsDivider+import com.vayunmathur.library.ui.SettingsRow+import com.vayunmathur.library.ui.SettingsSection+import com.vayunmathur.library.ui.SettingsSwitchRow+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.measure.Route+import com.vayunmathur.measure.data.model.MeasurementKind+import com.vayunmathur.measure.data.model.SavedM
Diff truncated.