From 23969e39d8d25a18fe14af15b293f853a05fd1e9 Mon Sep 17 00:00:00 2001 From: Adam <196335+anieto@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:46:10 -0600 Subject: [PATCH 01/18] Place NodeVision markers by estimated elevation --- .../FieldTools/FieldToolsScreen.swift | 3 + .../NodeDetail/NodeDetailScreen.swift | 2 +- .../NodeVision/NodeVisionScreen.swift | 248 ++++++++++++++---- CoreScopeViewer/Models/FieldGeometry.swift | 6 +- .../Resources/Localizable.xcstrings | 6 +- CoreScopeViewerTests/FieldGeometryTests.swift | 70 +++++ .../android/core/model/FieldGeometry.kt | 6 +- .../android/feature/nodes/NodeDetailScreen.kt | 1 + .../feature/nodevision/NodeVisionScreen.kt | 201 ++++++++++---- .../app/src/main/res/values-es/strings.xml | 2 +- .../src/main/res/values-pt-rBR/strings.xml | 2 +- android/app/src/main/res/values/strings.xml | 2 +- .../nodescope/android/FieldGeometryTest.kt | 63 +++++ 13 files changed, 494 insertions(+), 118 deletions(-) diff --git a/CoreScopeViewer/Features/FieldTools/FieldToolsScreen.swift b/CoreScopeViewer/Features/FieldTools/FieldToolsScreen.swift index 32a1da9..70fd374 100644 --- a/CoreScopeViewer/Features/FieldTools/FieldToolsScreen.swift +++ b/CoreScopeViewer/Features/FieldTools/FieldToolsScreen.swift @@ -571,6 +571,9 @@ struct FieldToolsScreen: View { NodeVisionScreen(name: target.name, target: coordinate, repeaterKey: { if case .node(let node) = target { return node.publicKey } return nil + }(), role: { + if case .node(let node) = target { return node.role } + return nil }()) } } diff --git a/CoreScopeViewer/Features/NodeDetail/NodeDetailScreen.swift b/CoreScopeViewer/Features/NodeDetail/NodeDetailScreen.swift index 778947a..3a8b258 100644 --- a/CoreScopeViewer/Features/NodeDetail/NodeDetailScreen.swift +++ b/CoreScopeViewer/Features/NodeDetail/NodeDetailScreen.swift @@ -76,7 +76,7 @@ struct NodeDetailScreen: View { let item = FieldCatalogItem.node(displayedNode) if let coordinate = item.coordinate { NodeVisionScreen(name: item.name, target: coordinate, - repeaterKey: displayedNode.publicKey) + repeaterKey: displayedNode.publicKey, role: displayedNode.role) } } diff --git a/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift b/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift index 532f6e5..055f553 100644 --- a/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift +++ b/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift @@ -6,6 +6,7 @@ struct NodeVisionScreen: View { private let initialName: String? private let initialTarget: FieldCoordinate? private let initialRepeaterKey: String? + private let initialRole: String? private let catalog: [MeshNode] private let discoveryRegion: String? private let catalogIsLoading: Bool @@ -32,11 +33,12 @@ struct NodeVisionScreen: View { @State private var showsDiagnostics = false #endif - init(name: String? = nil, target: FieldCoordinate? = nil, repeaterKey: String? = nil, catalog: [MeshNode] = [], discoveryRegion: String? = nil, + init(name: String? = nil, target: FieldCoordinate? = nil, repeaterKey: String? = nil, role: String? = nil, catalog: [MeshNode] = [], discoveryRegion: String? = nil, catalogIsLoading: Bool = false) { initialName = name initialTarget = target initialRepeaterKey = repeaterKey + initialRole = role self.catalog = catalog self.discoveryRegion = discoveryRegion self.catalogIsLoading = catalogIsLoading @@ -47,12 +49,35 @@ struct NodeVisionScreen: View { private var target: FieldCoordinate? { focusedNode.flatMap { FieldCatalogItem.node($0).coordinate } ?? initialTarget } private var repeaterKey: String? { focusedNode?.publicKey ?? initialRepeaterKey } @Environment(AnalyzerSettings.self) private var settings - @State private var antennaElevation: Double? + @State private var displayedAltitude: Double? + @State private var ground: [VisionTerrainPoint: Double] = [:] + @State private var terrain = VisionTerrainCache(provider: OpenMeteoElevationProvider()) + + private var spotlightPoint: VisionTerrainPoint? { + target.flatMap { VisionTerrainPoint(key: repeaterKey ?? "", coordinate: $0) } + } + + private var terrainPoints: Set { + var points = Set(nearbyNodes.compactMap { terrainPoint(for: $0.node) }) + if let spotlightPoint { points.insert(spotlightPoint) } + return points + } + + private func terrainPoint(for node: MeshNode) -> VisionTerrainPoint? { + FieldCatalogItem.node(node).coordinate.flatMap { VisionTerrainPoint(key: node.publicKey, coordinate: $0) } + } + + private var spotlightHeight: VisionAntennaHeight { + VisionAntennaHeight(role: focusedNode?.role ?? initialRole, reported: installHeight) + } + + private var antennaElevation: Double? { + spotlightPoint.flatMap { ground[$0] }.map { $0 + spotlightHeight.meters } + } @State private var installHeight: Double? @State private var targetStatus: String? @State private var verticalArrowShown = false @State private var bottomOverlayHeight: CGFloat = 0 - @State private var elevationProvider = OpenMeteoElevationProvider() @Environment(\.isHingedDevice) private var isHingedDevice @Environment(\.colorScheme) private var colorScheme @Environment(\.dismiss) private var dismiss @@ -103,7 +128,7 @@ struct NodeVisionScreen: View { VStack(alignment: .leading, spacing: 16) { Text("The compass shows where the camera is pointing. Markers show node names and distances from you. Smaller markers follow the node’s direction and may stagger vertically to keep labels readable.") Text("Tap a marker to preview a node. Choose Spotlight node to highlight it as you pan. Choosing a node from Nearby spotlights it immediately. Edge arrows show which way to turn or tilt when the highlighted node is outside the camera view.") - Text("When enough elevation data is available, NodeVision uses it to place the focused marker vertically. “Elevation Uncertain” means its height on screen is a rough guide.") + Text("When the phone’s altitude is accurate enough, NodeVision places markers by estimated antenna elevation. Without a reported height, it assumes a typical rooftop or handheld height.") Divider() VStack(alignment: .leading, spacing: 8) { Label("Location privacy", systemImage: "info.circle") @@ -193,22 +218,20 @@ struct NodeVisionScreen: View { if backend.sourceSession.isCurrent, !Task.isCancelled { repeaterMetadata = metadata } } .task(id: "\(settings.sourceSession.id)|\(repeaterKey ?? "")") { - antennaElevation = nil installHeight = nil targetStatus = nil - guard let repeaterKey, let target, settings.sourceIsReady else { return } + guard let repeaterKey, settings.sourceIsReady else { return } let backend = AnalyzerBackendFactory.make(settings: settings) let metadata = await FieldCatalogRepository.shared.repeaterMetadata(for: backend) guard backend.sourceSession.isCurrent, !Task.isCancelled else { return } let reported = metadata[repeaterKey] targetStatus = reported?.status - guard let height = reported?.applicableHeightMeters(), - let point = try? NodePlannerCoordinate(latitude: target.latitude, longitude: target.longitude) else { return } - installHeight = height - let terrain = try? await elevationProvider.elevations(for: [point, point]) - guard backend.sourceSession.isCurrent, !Task.isCancelled, - let ground = terrain?.samples.first?.elevationMeters else { return } - antennaElevation = ground + height + installHeight = reported?.applicableHeightMeters() + } + .task(id: terrainPoints) { + let resolved = await terrain.resolve(terrainPoints) + guard !Task.isCancelled else { return } + ground = resolved } .task(id: needsLocation) { if needsLocation { location.start() } else { location.stop() } @@ -238,7 +261,13 @@ struct NodeVisionScreen: View { regionalCatalog.configure(settings: settings) await regionalCatalog.loadNodes(region: discoveryRegion) } - .onChange(of: discoveryCatalog) { refreshDiscoveryNodes() } + .onChange(of: discoveryCatalog) { + if let key = focusedNode?.publicKey, + let updated = discoveryCatalog.first(where: { $0.publicKey == key }) { + focusedNode = updated + } + refreshDiscoveryNodes() + } .onChange(of: repeaterMetadata.reportedStatuses) { refreshDiscoveryNodes() } .onChange(of: showsLiveCamera && cameraAvailable, initial: true) { _, keepsScreenAwake in if keepsScreenAwake { @@ -329,18 +358,25 @@ struct NodeVisionScreen: View { let offscreen = offset.map { abs($0 * pane.size.width / 2) > max(0, edge + (arrowShown ? -6 : 6)) } ?? false let showSettings = location.status == .denied || AVCaptureDevice.authorizationStatus(for: .video) == .denied let truncatedName = fullNameHeight > markerNameHeight + 1 + let nearDistance = max(5, fix?.horizontalAccuracyMeters ?? 0) + let distances = nearbyNodes.map(\.geometry.distanceMeters) + [geometry?.distanceMeters].compactMap { $0 } + let closestDistance = distances.filter { $0 > nearDistance }.min() + let altitude = stableVisionAltitude(previous: displayedAltitude, current: fix?.altitudeMeters, + distance: closestDistance) + let mode = VisionElevationMode(altitude: altitude, accuracy: fix?.verticalAccuracyMeters, + distances: distances, nearDistance: nearDistance) let placement = markerHeight(size: pane.size, insets: insets, distance: geometry?.distanceMeters, - fix: fix, pitch: heading?.pitchDegrees) + mode: mode, pitch: heading?.pitchDegrees) let verticalEdge = placement.edge let useVerticalArrow = verticalEdge != nil && (!offscreen || abs(placement.offset ?? 0) > abs(offset ?? 0)) let showsBottomArrow = cameraAvailable && !near && offset != nil && useVerticalArrow && verticalEdge == .below - let markerVisible = cameraAvailable && !near && offset != nil && !offscreen && verticalEdge == nil + let markerVisible = placement.y != nil && cameraAvailable && !near && offset != nil && !offscreen && verticalEdge == nil let discoveryMarkers = discoveryMarkers(size: pane.size, insets: insets, fix: fix, - heading: heading, tangent: tangent, + heading: heading, tangent: tangent, mode: mode, focusedX: markerVisible ? offset.map { pane.size.width * (1 + $0) / 2 } : nil, - focusedY: placement.y, focusedWidth: markerWidth) + focusedY: placement.y ?? 0, focusedWidth: markerWidth) ZStack { Rectangle().fill(.background) if cameraAvailable { @@ -357,9 +393,10 @@ struct NodeVisionScreen: View { } .animation(reduceMotion ? nil : .easeInOut(duration: 0.24), value: Set(discoveryMarkers.map(\.id))) - if cameraAvailable, !near, !showsBottomArrow, let offset { + .id(mode == .guide) + if cameraAvailable, !near, !showsBottomArrow, let offset, placement.y != nil || offscreen { direction(offset, offscreen: offscreen, verticalEdge: useVerticalArrow ? verticalEdge : nil, - markerWidth: markerWidth, markerY: placement.y, estimated: placement.offset != nil, + markerWidth: markerWidth, markerY: placement.y ?? pane.size.height * 0.43, estimated: mode != .guide, approximate: placement.approximate, size: pane.size, geometry: geometry) } VStack(spacing: 0) { @@ -488,8 +525,12 @@ struct NodeVisionScreen: View { } else if targetStatus == "decommissioned" { Text("Owner reported: Decommissioned").font(.caption) } - if !markerVisible, placement.approximate { - Text("Approx. elevation").font(.caption) + if !markerVisible { + if placement.approximate { + Text("Approx. elevation").font(.caption) + } else if mode == .guide { + Text("Elevation Uncertain").font(.caption) + } } if cameraFailed { Text("Camera unavailable. You can return to the guide.") @@ -543,6 +584,7 @@ struct NodeVisionScreen: View { } .clipped() .onChange(of: verticalEdge != nil, initial: true) { _, value in verticalArrowShown = value } + .onChange(of: altitude, initial: true) { displayedAltitude = altitude } } } } @@ -569,6 +611,7 @@ struct NodeVisionScreen: View { let candidate: NearbyNode let x: CGFloat let y: CGFloat + let approximate: Bool let rowOffset: CGFloat let width: CGFloat let tier: Int @@ -577,20 +620,15 @@ struct NodeVisionScreen: View { } private func discoveryMarkers(size: CGSize, insets: EdgeInsets, fix: FieldLocationSample?, - heading: FieldHeadingSample?, tangent: Double?, + heading: FieldHeadingSample?, tangent: Double?, mode: VisionElevationMode, focusedX: CGFloat?, focusedY: CGFloat, focusedWidth: CGFloat) -> [DiscoveryMarker] { guard isDiscovery, cameraAvailable, let fix, let heading, let tangent, tangent > 0, let pitch = heading.pitchDegrees, let verticalTangent = optics?.halfHeightTangent(size), verticalTangent > 0 else { return [] } - let minY = insets.top + 130 + let minY = insets.top + 166 let maxY = size.height - insets.bottom - 100 guard minY < maxY else { return [] } - let vertical = FieldGeometry.cameraBearingGuideOffset(pitch: pitch, halfHeightTangent: verticalTangent) - let y = size.height * (1 - vertical) / 2 - guard (minY...maxY).contains(y) else { return [] } let selectedID = inspectedNode?.publicKey - let rowSpacing: CGFloat = 92 - let rowYs = [y, y + rowSpacing <= maxY ? y + rowSpacing : y - rowSpacing] var occupied: [CGRect] = [] if let focusedX { occupied.append(CGRect(x: focusedX - focusedWidth / 2, y: focusedY - 88, @@ -611,12 +649,21 @@ struct NodeVisionScreen: View { let left = x - width / 2 - 5 let paddedWidth = width + 10 guard left >= insets.leading, left + paddedWidth <= size.width - insets.trailing else { return } - // Stagger labels vertically without changing the projected bearing. - for rowY in rowYs where rowY >= minY { + let height = VisionAntennaHeight(role: candidate.node.role, + reported: repeaterMetadata[candidate.node.publicKey]?.applicableHeightMeters()) + let antenna = terrainPoint(for: candidate.node).flatMap { ground[$0] }.map { $0 + height.meters } + let distance = candidate.geometry.distanceMeters + guard let vertical = mode.offset(distance: distance, antenna: antenna, pitch: pitch, + tangent: verticalTangent) else { return } + let y = min(max(size.height * CGFloat(1 - vertical) / 2, minY), maxY) + let approximate = mode.isApproximate(distance: distance, height: height) + let nudges: [CGFloat] = mode == .guide ? [0, y + 92 <= maxY ? 92 : -92] : [0, 24, -24, 48, -48, 72, -72, 92, -92] + for nudge in nudges { + let rowY = min(max(y + nudge, minY), maxY) let bounds = CGRect(x: left, y: rowY - 84, width: paddedWidth, height: 88) guard !occupied.contains(where: { $0.intersects(bounds) }) else { continue } occupied.append(bounds) - markers.append(DiscoveryMarker(candidate: candidate, x: x, y: y, + markers.append(DiscoveryMarker(candidate: candidate, x: x, y: y, approximate: approximate, rowOffset: rowY - y, width: width, tier: tier)) break } @@ -651,7 +698,10 @@ struct NodeVisionScreen: View { .padding(.bottom, 9) .background { overlaySurface(NodeVisionMarkerShape()) } .overlay { - if selected { NodeVisionMarkerShape().stroke(nodeNameColor, lineWidth: 2) } + if selected || marker.approximate { + NodeVisionMarkerShape().stroke(nodeNameColor, style: StrokeStyle( + lineWidth: selected ? 2 : 1, dash: marker.approximate ? [4, 3] : [])) + } } .contentShape(Rectangle()) .opacity(marker.tier == 2 && !selected ? 0.90 : 1) @@ -849,31 +899,21 @@ struct NodeVisionScreen: View { } private func markerHeight(size: CGSize, insets: EdgeInsets, distance: Double?, - fix: FieldLocationSample?, pitch: Double?) -> (y: CGFloat, approximate: Bool, decision: String, offset: Double?, edge: VerticalEdge?) { + mode: VisionElevationMode, pitch: Double?) -> (y: CGFloat?, approximate: Bool, decision: String, offset: Double?, edge: VerticalEdge?) { let fallback = size.height * 0.43 + let modeName = mode == .guide ? "All markers: pitch guide" : "All markers: elevation" guard let pitch, let tangent = optics?.halfHeightTangent(size), tangent > 0 else { - return (fallback, false, "Guide: waiting for pitch or camera", nil, nil) + return (nil, false, modeName + " · waiting for pitch or camera", nil, nil) } - let estimatedOffset: Double? - let decision: String - var approximate = false - if let distance, let antennaElevation, let altitude = fix?.altitudeMeters, - let accuracy = fix?.verticalAccuracyMeters { - estimatedOffset = FieldGeometry.cameraVerticalOffset( - distance: distance, antennaElevation: antennaElevation, phoneElevation: altitude, - phoneAccuracy: accuracy, pitch: pitch, halfHeightTangent: tangent - ) - let uncertainty = FieldGeometry.cameraElevationUncertainty(distance: distance, phoneAccuracy: accuracy) - approximate = estimatedOffset != nil && uncertainty > 8 - decision = estimatedOffset == nil ? "Guide: accuracy or viewing angle" : approximate ? "Approximate estimate" : "Elevation estimate" - } else { - estimatedOffset = nil - decision = antennaElevation == nil ? "Guide: antenna elevation unavailable" : "Guide: phone altitude unavailable" + guard let distance, let offset = mode.offset(distance: distance, antenna: antennaElevation, + pitch: pitch, tangent: tangent) else { + return (nil, false, modeName + " · spotlight unplaced", nil, nil) } - let offset = estimatedOffset ?? FieldGeometry.cameraBearingGuideOffset(pitch: pitch, halfHeightTangent: tangent) + let approximate = mode.isApproximate(distance: distance, height: spotlightHeight) + let estimatedOffset = mode == .guide ? nil : offset let minimumY = insets.top + 166 let maximumY = size.height - insets.bottom - 100 - guard maximumY >= minimumY else { return (fallback, false, "Guide: short viewfinder", nil, nil) } + guard maximumY >= minimumY else { return (fallback, approximate, modeName + " · short viewfinder", nil, nil) } let projectedY = size.height * (1 - offset) / 2 let buffer: CGFloat = verticalArrowShown ? -6 : 6 let edge: VerticalEdge? @@ -881,7 +921,7 @@ struct NodeVisionScreen: View { else if projectedY < minimumY - buffer { edge = .above } else if projectedY > maximumY + buffer { edge = .below } else { edge = nil } - return (min(max(projectedY, minimumY), maximumY), approximate, decision, estimatedOffset, edge) + return (min(max(projectedY, minimumY), maximumY), approximate, modeName, estimatedOffset, edge) } #if DEBUG @@ -1088,3 +1128,105 @@ private struct NodeVisionPreview: UIViewRepresentable { } } } + + +struct VisionAntennaHeight { + let meters: Double + let approximate: Bool + + init(role: String?, reported: Double?) { + let role = role == "room-server" ? GlossaryTerm.roomServer : role.flatMap { GlossaryTerm(role: $0) } + let reported = role == .repeater ? reported : nil + let preset: CoverageHeightPreset = role == .repeater || role == .roomServer ? .rooftop : .handheld + meters = reported ?? preset.meters + approximate = reported == nil + } +} + +enum VisionElevationMode: Equatable { + case guide + case elevation(altitude: Double, accuracy: Double) + + init(altitude: Double?, accuracy: Double?, distances: [Double], nearDistance: Double) { + guard let altitude, altitude.isFinite, let accuracy, accuracy.isFinite, accuracy > 0, + distances.filter({ $0 > nearDistance }).allSatisfy({ + FieldGeometry.cameraElevationUncertainty(distance: $0, phoneAccuracy: accuracy) <= 30 + }) else { + self = .guide + return + } + self = .elevation(altitude: altitude, accuracy: accuracy) + } + + func offset(distance: Double, antenna: Double?, pitch: Double, tangent: Double) -> Double? { + switch self { + case .guide: + FieldGeometry.cameraBearingGuideOffset(pitch: pitch, halfHeightTangent: tangent) + case let .elevation(altitude, accuracy): + antenna.flatMap { + FieldGeometry.cameraVerticalOffset(distance: distance, antennaElevation: $0, phoneElevation: altitude, + phoneAccuracy: accuracy, pitch: pitch, halfHeightTangent: tangent, clampAngle: true) + } + } + } + + func isApproximate(distance: Double, height: VisionAntennaHeight) -> Bool { + guard case let .elevation(_, accuracy) = self else { return false } + return height.approximate || FieldGeometry.cameraElevationUncertainty(distance: distance, phoneAccuracy: accuracy) > 8 + } +} + +struct VisionTerrainPoint: Hashable, Sendable { + let key: String + let coordinate: NodePlannerCoordinate + + init?(key: String, coordinate: FieldCoordinate) { + guard let point = try? NodePlannerCoordinate(latitude: coordinate.latitude, longitude: coordinate.longitude) + else { return nil } + self.key = key.lowercased() + self.coordinate = point + } +} + +actor VisionTerrainCache { + private let provider: any NodePlannerElevationProviding + private var elevations: [VisionTerrainPoint: Double] = [:] + private var attempted: Set = [] + + init(provider: any NodePlannerElevationProviding) { + self.provider = provider + } + + func resolve(_ points: Set) async -> [VisionTerrainPoint: Double] { + let missing = points.subtracting(attempted).sorted { + ($0.key, $0.coordinate.latitude, $0.coordinate.longitude) < + ($1.key, $1.coordinate.latitude, $1.coordinate.longitude) + } + for start in stride(from: 0, to: missing.count, by: OpenMeteoElevationProvider.maximumBatchSize) { + guard !Task.isCancelled else { break } + let batch = missing[start.. = [] + let coordinates = batch.map(\.coordinate).filter { seen.insert($0).inserted } + let request = coordinates.count == 1 ? coordinates + coordinates : coordinates + let profile = try? await provider.elevations(for: request) + guard !Task.isCancelled else { break } + attempted.formUnion(batch) + guard let profile else { continue } + var ground: [NodePlannerCoordinate: Double] = [:] + for sample in profile.samples where sample.elevationMeters.isFinite { + ground[sample.coordinate] = sample.elevationMeters + } + for point in batch { + elevations[point] = ground[point.coordinate] + } + } + return elevations + } +} + +/// Ignore altitude changes that move even the closest eligible marker less than 0.15°. +func stableVisionAltitude(previous: Double?, current: Double?, distance: Double?) -> Double? { + guard let current, current.isFinite else { return nil } + guard let previous, let distance else { return current } + return atan2(abs(current - previous), distance) < 0.15 * .pi / 180 ? previous : current +} diff --git a/CoreScopeViewer/Models/FieldGeometry.swift b/CoreScopeViewer/Models/FieldGeometry.swift index ad79725..6d2809a 100644 --- a/CoreScopeViewer/Models/FieldGeometry.swift +++ b/CoreScopeViewer/Models/FieldGeometry.swift @@ -147,15 +147,15 @@ enum FieldGeometry { /// Project a height estimate only when combined vertical uncertainty is small enough to be useful. static func cameraVerticalOffset( distance: Double, antennaElevation: Double, phoneElevation: Double, - phoneAccuracy: Double, pitch: Double, halfHeightTangent: Double + phoneAccuracy: Double, pitch: Double, halfHeightTangent: Double, clampAngle: Bool = false ) -> Double? { guard [distance, antennaElevation, phoneElevation, phoneAccuracy, pitch, halfHeightTangent].allSatisfy(\.isFinite), distance > 0, phoneAccuracy > 0, halfHeightTangent > 0, cameraElevationUncertainty(distance: distance, phoneAccuracy: phoneAccuracy) <= 30 else { return nil } let curvature = distance * distance / (2 * earthRadiusMeters) let angle = atan2(antennaElevation - phoneElevation - curvature, distance).degrees - pitch - guard abs(angle) < 89 else { return nil } - return tan(angle.radians) / halfHeightTangent + guard clampAngle || abs(angle) < 89 else { return nil } + return tan(min(max(angle, -89), 89).radians) / halfHeightTangent } /// Core Motion true-north coordinates are X north, Y west, Z up. diff --git a/CoreScopeViewer/Resources/Localizable.xcstrings b/CoreScopeViewer/Resources/Localizable.xcstrings index b462b88..49cc4d9 100644 --- a/CoreScopeViewer/Resources/Localizable.xcstrings +++ b/CoreScopeViewer/Resources/Localizable.xcstrings @@ -33013,18 +33013,18 @@ } } }, - "When enough elevation data is available, NodeVision uses it to place the focused marker vertically. “Elevation Uncertain” means its height on screen is a rough guide." : { + "When the phone’s altitude is accurate enough, NodeVision places markers by estimated antenna elevation. Without a reported height, it assumes a typical rooftop or handheld height." : { "localizations" : { "es" : { "stringUnit" : { "state" : "translated", - "value" : "Cuando hay suficientes datos de elevación, NodeVision los usa para colocar el marcador destacado en el eje vertical. «Elevación incierta» significa que su altura en pantalla es orientativa." + "value" : "Cuando la altitud del teléfono es lo bastante precisa, NodeVision coloca los marcadores según la elevación estimada de la antena. Si no se ha indicado la altura, usa una altura típica de azotea o de dispositivo de mano." } }, "pt-BR" : { "stringUnit" : { "state" : "translated", - "value" : "Quando há dados de elevação suficientes, o NodeVision os usa para posicionar o marcador destacado na vertical. “Elevação incerta” indica que a altura na tela é apenas uma referência." + "value" : "Quando a altitude do celular é precisa o suficiente, o NodeVision posiciona os marcadores pela elevação estimada da antena. Sem uma altura informada, usa uma altura típica de telhado ou de dispositivo portátil." } } } diff --git a/CoreScopeViewerTests/FieldGeometryTests.swift b/CoreScopeViewerTests/FieldGeometryTests.swift index 2f4e98b..5c56d44 100644 --- a/CoreScopeViewerTests/FieldGeometryTests.swift +++ b/CoreScopeViewerTests/FieldGeometryTests.swift @@ -1,3 +1,4 @@ +import Foundation import simd import Testing @testable import CoreScopeViewer @@ -160,3 +161,72 @@ struct FieldGeometryTests { #expect(FieldGeometry.deviceAxesUseMatrixRows(rows: turned, gravity: SIMD3(0, 0, -1)) == nil) } } + + +struct NodeVisionElevationTests { + @Test func reportedAndDefaultHeights() { + #expect(VisionAntennaHeight(role: "repeater", reported: 12).meters == 12) + #expect(!VisionAntennaHeight(role: "repeater", reported: 12).approximate) + for role in ["repeater", "room", "room-server"] { + #expect(VisionAntennaHeight(role: role, reported: nil).meters == CoverageHeightPreset.rooftop.meters) + #expect(VisionAntennaHeight(role: role, reported: nil).approximate) + } + #expect(VisionAntennaHeight(role: "companion", reported: 12).meters == CoverageHeightPreset.handheld.meters) + } + + @Test func placementModeAppliesToEveryMarker() { + let distances = [30.0, 500] + for mode in [ + VisionElevationMode(altitude: nil, accuracy: 2, distances: distances, nearDistance: 5), + VisionElevationMode(altitude: 100, accuracy: 10, distances: distances, nearDistance: 5) + ] { + #expect(mode == .guide) + #expect(mode.offset(distance: 30, antenna: nil, pitch: 2, tangent: 0.5) == + mode.offset(distance: 500, antenna: 150, pitch: 2, tangent: 0.5)) + } + let mode = VisionElevationMode(altitude: 100, accuracy: 2, distances: [500], nearDistance: 5) + #expect(mode == .elevation(altitude: 100, accuracy: 2)) + #expect(mode.offset(distance: 500, antenna: nil, pitch: 2, tangent: 0.5) == nil) + #expect(mode.offset(distance: 500, antenna: 150, pitch: 2, tangent: 0.5) != nil) + } + + @Test func altitudeDeadbandAccumulatesChanges() { + let stable = stableVisionAltitude(previous: 100, current: 100.2, distance: 100) + #expect(stable == 100) + #expect(stableVisionAltitude(previous: stable, current: 100.3, distance: 100) == 100.3) + #expect(stableVisionAltitude(previous: stable, current: nil, distance: 100) == nil) + } + + @Test func terrainBatchesCacheByNodeAndCoordinateAndKeepSuccessfulBatches() async throws { + let provider = VisionTestTerrainProvider() + let cache = VisionTerrainCache(provider: provider) + let points = try Set((0..<101).map { index in + let coordinate = try #require(FieldCoordinate(latitude: Double(index) / 100, longitude: 0)) + return try #require(VisionTerrainPoint(key: String(format: "%03d", index), coordinate: coordinate)) + }) + let first = await cache.resolve(points) + #expect(first.count == 100) + #expect(await provider.requests.map(\.count) == [100, 2]) + let cachedPoints = Set(first.keys) + _ = await cache.resolve(points) + #expect(await provider.requests.count == 2) + let coordinate = try #require(FieldCoordinate(latitude: 2, longitude: 0)) + let moved = try #require(VisionTerrainPoint(key: "000", coordinate: coordinate)) + let updated = await cache.resolve(cachedPoints.union([moved])) + #expect(updated[moved] == 42) + #expect(await provider.requests.last == [moved.coordinate, moved.coordinate]) + } +} + +private actor VisionTestTerrainProvider: NodePlannerElevationProviding { + private(set) var requests: [[NodePlannerCoordinate]] = [] + + func elevations(for coordinates: [NodePlannerCoordinate]) async throws -> NodePlannerTerrainProfile { + requests.append(coordinates) + if requests.count == 2 { throw NodePlannerElevationError.unavailable } + return NodePlannerTerrainProfile( + samples: coordinates.map { NodePlannerTerrainSample(coordinate: $0, elevationMeters: 42) }, + provenance: NodePlannerElevationProvenance(fetchedAt: .now, origin: .network) + ) + } +} diff --git a/android/app/src/main/java/org/nodescope/android/core/model/FieldGeometry.kt b/android/app/src/main/java/org/nodescope/android/core/model/FieldGeometry.kt index b150e66..4437caf 100644 --- a/android/app/src/main/java/org/nodescope/android/core/model/FieldGeometry.kt +++ b/android/app/src/main/java/org/nodescope/android/core/model/FieldGeometry.kt @@ -109,14 +109,14 @@ object FieldGeometry { /** Project a height estimate only when combined vertical uncertainty is small enough to be useful. */ fun cameraVerticalOffset( distance: Double, antennaElevation: Double, phoneElevation: Double, - phoneAccuracy: Double, pitch: Double, halfHeightTangent: Double, + phoneAccuracy: Double, pitch: Double, halfHeightTangent: Double, clampAngle: Boolean = false, ): Double? { if (!listOf(distance, antennaElevation, phoneElevation, phoneAccuracy, pitch, halfHeightTangent).all(Double::isFinite) || distance <= 0 || phoneAccuracy <= 0 || halfHeightTangent <= 0 || cameraElevationUncertainty(distance, phoneAccuracy) > 30) return null val curvature = distance * distance / (2 * EARTH_RADIUS_METERS) val angle = Math.toDegrees(atan2(antennaElevation - phoneElevation - curvature, distance)) - pitch - if (kotlin.math.abs(angle) >= 89) return null - return kotlin.math.tan(Math.toRadians(angle)) / halfHeightTangent + if (!clampAngle && kotlin.math.abs(angle) >= 89) return null + return kotlin.math.tan(Math.toRadians(angle.coerceIn(-89.0, 89.0))) / halfHeightTangent } } diff --git a/android/app/src/main/java/org/nodescope/android/feature/nodes/NodeDetailScreen.kt b/android/app/src/main/java/org/nodescope/android/feature/nodes/NodeDetailScreen.kt index d5d56c6..f1756c6 100644 --- a/android/app/src/main/java/org/nodescope/android/feature/nodes/NodeDetailScreen.kt +++ b/android/app/src/main/java/org/nodescope/android/feature/nodes/NodeDetailScreen.kt @@ -133,6 +133,7 @@ fun NodeDetailScreen( target = visionCoordinate, antennaHeight = metadata.value?.applicableHeightMeters(), initialStatus = metadata.value?.status, + targetRole = node?.role, ) { showsNodeVision = false } diff --git a/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt b/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt index 61129bf..4b268d0 100644 --- a/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt +++ b/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt @@ -43,9 +43,13 @@ import android.net.Uri import android.os.SystemClock import android.os.Build import android.location.altitude.AltitudeConverter +import androidx.compose.ui.draw.alpha +import org.nodescope.android.feature.coverage.CoverageHeightPreset +import org.nodescope.android.feature.linkprofile.LinkTerrainProviding import java.io.File import java.io.IOException import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.withContext import org.nodescope.android.feature.linkprofile.LinkTerrainProvider import org.nodescope.android.feature.linkprofile.ProfileCoordinate @@ -123,6 +127,7 @@ internal fun NodeVisionScreen( target: FieldCoordinate? = null, antennaHeight: Double? = null, initialStatus: String? = null, + targetRole: String? = null, catalog: List = emptyList(), catalogIsLoading: Boolean = false, loadMetadata: suspend () -> Map = { emptyMap() }, @@ -152,7 +157,8 @@ internal fun NodeVisionScreen( val focusedNode = catalog.firstOrNull { it.publicKey == focusedKey } val visionTarget = focusedNode?.visionCoordinate() ?: target val visionName = focusedNode?.displayName ?: name.orEmpty() - val visionHeight = focusedNode?.let { repeaterMetadata[it.publicKey.lowercase()]?.applicableHeightMeters() } ?: antennaHeight + val reportedHeight = focusedNode?.let { repeaterMetadata[it.publicKey.lowercase()]?.applicableHeightMeters() } ?: antennaHeight + val visionHeight = visionAntennaHeight(focusedNode?.role ?: targetRole, reportedHeight) val ownerStatus = when (focusedNode?.let { repeaterMetadata[it.publicKey.lowercase()]?.status } ?: initialStatus) { "maintenance" -> R.string.nodevision_owner_maintenance "decommissioned" -> R.string.nodevision_owner_decommissioned @@ -214,22 +220,23 @@ internal fun NodeVisionScreen( } val trueHeading = if (heading != null && declination != null) heading.degrees + declination else null - var antennaElevation by remember(visionTarget, visionHeight) { mutableStateOf(null) } - LaunchedEffect(visionTarget, visionHeight) { - if (visionHeight == null || visionTarget == null) return@LaunchedEffect - val point = ProfileCoordinate(visionTarget.latitude, visionTarget.longitude) - val provider = LinkTerrainProvider(File(context.cacheDir, "nodevision-elevation.json")) - antennaElevation = try { - provider.profile(listOf(point, point)).points.firstOrNull()?.elevationMeters?.plus(visionHeight) - } catch (_: IOException) { - null - } catch (_: IllegalArgumentException) { - null + val spotlightPoint = visionTarget?.let { VisionTerrainPoint(focusedNode?.publicKey.orEmpty().lowercase(), it) } + val terrainPoints = remember(nearby, spotlightPoint) { + buildSet { + nearby.mapNotNullTo(this) { it.node.terrainPoint() } + spotlightPoint?.let { add(it) } } } + val terrain = remember(context) { + VisionTerrainCache(LinkTerrainProvider(File(context.cacheDir, "nodevision-elevation.json"))) + } + var ground by remember(terrain) { mutableStateOf>(emptyMap()) } + LaunchedEffect(terrain, terrainPoints) { ground = terrain.resolve(terrainPoints) } + val antennaElevation = spotlightPoint?.let(ground::get)?.plus(visionHeight.meters) + var altitude by remember { mutableStateOf(null) } - LaunchedEffect(fix, active, antennaElevation) { - if (fix == null || !active || antennaElevation == null || Build.VERSION.SDK_INT < 34) { + LaunchedEffect(fix, active) { + if (fix == null || !active || Build.VERSION.SDK_INT < 34) { altitude = null return@LaunchedEffect } @@ -245,6 +252,7 @@ internal fun NodeVisionScreen( } } + var displayedAltitude by remember { mutableStateOf(null) } var optics by remember { mutableStateOf(null) } var cameraFailed by remember { mutableStateOf(false) } var showsDiagnostics by rememberSaveable { mutableStateOf(false) } @@ -314,16 +322,18 @@ internal fun NodeVisionScreen( val verticalTangent = projection?.halfHeightTangent val targetElevation = antennaElevation val phoneAltitude = altitude?.takeIf { now - it.fixTime <= 3_000 } - val verticalOffset = if (geometry != null && targetElevation != null && phoneAltitude != null && - heading != null && verticalTangent != null) { - FieldGeometry.cameraVerticalOffset(geometry.distanceMeters, targetElevation, - phoneAltitude.meters, phoneAltitude.accuracy, heading.pitch, verticalTangent) - } else null - val approximate = verticalOffset != null && phoneAltitude != null && geometry != null && - FieldGeometry.cameraElevationUncertainty(geometry.distanceMeters, phoneAltitude.accuracy) > 8 - val markerOffset = verticalOffset ?: if (heading != null && verticalTangent != null && verticalTangent > 0) { - FieldGeometry.cameraBearingGuideOffset(heading.pitch, verticalTangent) + val nearDistance = maxOf(5.0, fix?.accuracy?.toDouble() ?: 0.0) + val distances = nearby.map { it.geometry.distanceMeters } + listOfNotNull(geometry?.distanceMeters) + val closestDistance = distances.filter { it > nearDistance }.minOrNull() + val stableAltitude = stableVisionAltitude(displayedAltitude, phoneAltitude?.meters, closestDistance) + SideEffect { displayedAltitude = stableAltitude } + val mode = visionElevationMode(stableAltitude, phoneAltitude?.accuracy, distances, nearDistance) + val markerOffset = if (geometry != null && heading != null && verticalTangent != null && verticalTangent > 0) { + mode.offset(geometry.distanceMeters, targetElevation, heading.pitch, verticalTangent) } else null + val verticalOffset = markerOffset.takeUnless { mode == VisionElevationMode.Guide } + val approximate = markerOffset != null && geometry != null && + mode.isApproximate(geometry.distanceMeters, visionHeight) val safeTop = WindowInsets.safeDrawing.asPaddingValues().calculateTopPadding() val safeBottom = WindowInsets.safeDrawing.asPaddingValues().calculateBottomPadding() val minimumY = safeTop + 166.dp @@ -340,21 +350,25 @@ internal fun NodeVisionScreen( else -> null } val useVerticalArrow = verticalEdge != null && (!offscreen || abs(verticalOffset ?: 0.0) > abs(offset ?: 0.0)) - val markerVisible = showCamera && offset != null && !offscreen && verticalEdge == null + val markerVisible = markerOffset != null && showCamera && offset != null && !offscreen && verticalEdge == null val discoveryMarkers = if (discovery && showCamera && fix != null && projection != null && trueHeading != null && heading != null && verticalTangent != null && maximumY >= minimumY) { - val guide = FieldGeometry.cameraBearingGuideOffset(heading.pitch, verticalTangent) - val y = maxHeight.value * (projection.centerY - guide / 2) discoveryMarkers(discoveryNodes, inspectedKey, focusedKey, fix.accuracy.toDouble(), - trueHeading, projection, paneWidth.value.toDouble(), y, + trueHeading, projection, paneWidth.value.toDouble(), maxHeight.value.toDouble(), + heading.pitch, mode, + antenna = { node -> + val height = visionAntennaHeight(node.role, + repeaterMetadata[node.publicKey.lowercase()]?.applicableHeightMeters()) + node.terrainPoint()?.let(ground::get)?.plus(height.meters) to height + }, if (markerVisible) paneWidth.value / 2 + pixel else null, markerY.value.toDouble(), markerWidth.value.toDouble(), minimumY.value.toDouble(), maximumY.value.toDouble()) } else emptyList() - val retainedMarkers = remember { mutableStateMapOf() } + val retainedMarkers = remember(mode == VisionElevationMode.Guide) { mutableStateMapOf() } val visibleMarkers = discoveryMarkers.associateBy { it.node.publicKey } SideEffect { retainedMarkers.putAll(visibleMarkers) } (retainedMarkers.keys + visibleMarkers.keys).forEach { markerKey -> - key(markerKey) { + key(markerKey, mode == VisionElevationMode.Guide) { val marker = visibleMarkers[markerKey] ?: retainedMarkers.getValue(markerKey) val visible = markerKey in visibleMarkers val visibility = remember { MutableTransitionState(false) } @@ -382,6 +396,7 @@ internal fun NodeVisionScreen( shadowElevation = 4.dp, ) { Column(Modifier.background(overlayTint) + .alpha(if (marker.approximate) 0.84f else 1f) .padding(bottom = 9.dp).padding(horizontal = 6.dp, vertical = 4.dp), horizontalAlignment = Alignment.CenterHorizontally) { Text(marker.node.displayName, fontFamily = MonaspaceNeon, @@ -397,7 +412,7 @@ internal fun NodeVisionScreen( } } val showsTargetCard = visionTarget != null && inspectedNode == null && - (!markerVisible || truncatedName || status != null || showSettings || visionHeight != null || ownerStatus != null) + (!markerVisible || truncatedName || status != null || showSettings || reportedHeight != null || ownerStatus != null) var targetCardTop by remember { mutableStateOf(null) } var discoveryControlsTop by remember { mutableStateOf(null) } SideEffect { verticalArrowShown = showCamera && offset != null && verticalEdge != null } @@ -434,7 +449,7 @@ internal fun NodeVisionScreen( ) { Icon(icon, stringResource(label), Modifier.size(48.dp).padding(8.dp), tint = accent) } - } else { + } else if (markerVisible) { // The bottom of the tip stays on the bearing band when the label wraps. Box(Modifier.offset(x = maxWidth / 2 + pixel.dp - markerWidth / 2, y = markerY - 88.dp) .width(markerWidth).height(88.dp), contentAlignment = Alignment.BottomCenter) { @@ -448,7 +463,7 @@ internal fun NodeVisionScreen( overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center, onTextLayout = { truncatedName = it.hasVisualOverflow }) geometry?.let { Text(stringResource(R.string.nodevision_distance_away, formatDistance(it.distanceMeters / 1000, distanceUnit)), style = MaterialTheme.typography.labelSmall, fontFamily = MonaspaceNeon) } - if (approximate || verticalOffset == null) Text(stringResource( + if (approximate || mode == VisionElevationMode.Guide) Text(stringResource( if (approximate) R.string.nodevision_approx_elevation else R.string.nodevision_elevation_uncertain), style = MaterialTheme.typography.labelSmall, fontFamily = androidx.compose.ui.text.font.FontFamily.Default, color = supportingText) } @@ -508,14 +523,9 @@ internal fun NodeVisionScreen( } HorizontalDivider(color = MaterialTheme.colorScheme.primary.copy(alpha = 0.25f)) if (BuildConfig.DEBUG && showsDiagnostics) { - val decision = when { - heading == null || verticalTangent == null -> "Guide: waiting for pitch or camera" - targetElevation == null -> "Guide: antenna elevation unavailable" - phoneAltitude == null -> "Guide: phone altitude unavailable" - verticalOffset == null -> "Guide: accuracy or viewing angle" - approximate -> "Approximate estimate" - else -> "Elevation estimate" - } + val decision = if (mode == VisionElevationMode.Guide) "All markers: pitch guide" + else if (targetElevation == null) "All markers: elevation · spotlight unplaced" + else "All markers: elevation" val readout = "Phone ${debugMeters(phoneAltitude?.meters)} ±${debugMeters(phoneAltitude?.accuracy)} · " + "Antenna ${debugMeters(targetElevation)}\n$decision" Text(readout, Modifier.padding(5.dp), style = MaterialTheme.typography.labelSmall) @@ -561,8 +571,8 @@ internal fun NodeVisionScreen( Text(stringResource(R.string.nodevision_distance_away, formatDistance(it.distanceMeters / 1000, distanceUnit)), style = MaterialTheme.typography.labelSmall, fontFamily = MonaspaceNeon) } - if (visionHeight != null) { - val height = if (distanceUnit.usesFeet) visionHeight * 3.28084 else visionHeight + if (reportedHeight != null) { + val height = if (distanceUnit.usesFeet) reportedHeight * 3.28084 else reportedHeight val formattedHeight = java.text.NumberFormat.getNumberInstance().apply { maximumFractionDigits = 1 }.format(height) Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) { Icon(Icons.Default.ArrowUpward, contentDescription = null, Modifier.size(14.dp), @@ -575,7 +585,8 @@ internal fun NodeVisionScreen( } } ownerStatus?.let { Text(stringResource(it), style = MaterialTheme.typography.bodySmall) } - if (!markerVisible && approximate) Text(stringResource(R.string.nodevision_approx_elevation), + if (!markerVisible && (approximate || mode == VisionElevationMode.Guide)) Text(stringResource( + if (approximate) R.string.nodevision_approx_elevation else R.string.nodevision_elevation_uncertain), style = MaterialTheme.typography.bodySmall) status?.let { Text(stringResource(it)) } if (showSettings) TextButton(onClick = { @@ -781,23 +792,21 @@ internal fun NodeVisionScreen( private data class NearbyVisionNode(val node: MeshNode, val geometry: FieldGeometryResult) private data class DiscoveryMarker( - val node: MeshNode, val distance: Double, val x: Double, val y: Double, val width: Double, val tier: Int, + val node: MeshNode, val distance: Double, val x: Double, val y: Double, val width: Double, val tier: Int, val approximate: Boolean, ) private fun discoveryMarkers( nearby: List, inspectedKey: String?, focusedKey: String?, horizontalAccuracy: Double, - heading: Double, projection: VisionOptics, paneWidth: Double, y: Double, + heading: Double, projection: VisionOptics, paneWidth: Double, paneHeight: Double, + pitch: Double, mode: VisionElevationMode, antenna: (MeshNode) -> Pair, focusedX: Double?, focusedY: Double, focusedWidth: Double, minimumY: Double, maximumY: Double, ): List { - if (y !in minimumY..maximumY) return emptyList() val available = if (focusedX == null) 5 else 4 data class Bounds(val left: Double, val right: Double, val top: Double, val bottom: Double) { fun overlaps(other: Bounds): Boolean = left < other.right && right > other.left && top < other.bottom && bottom > other.top } - val rowSpacing = 92.0 - val rowYs = listOf(y, if (y + rowSpacing <= maximumY) y + rowSpacing else y - rowSpacing) val occupied = mutableListOf() if (focusedX != null) { occupied.add(Bounds(focusedX - focusedWidth / 2, focusedX + focusedWidth / 2, focusedY - 88, focusedY)) @@ -818,13 +827,19 @@ private fun discoveryMarkers( val left = x - width / 2 - 5 val right = x + width / 2 + 5 if (left < 0 || right > paneWidth) return - // Stagger labels vertically without changing the projected bearing. - for (rowY in rowYs) { - if (rowY < minimumY) continue + val (elevation, height) = antenna(candidate.node) + val distance = candidate.geometry.distanceMeters + val vertical = mode.offset(distance, elevation, pitch, projection.halfHeightTangent) ?: return + val y = (paneHeight * (projection.centerY - vertical / 2)).coerceIn(minimumY, maximumY) + val approximate = mode.isApproximate(distance, height) + val nudges = if (mode == VisionElevationMode.Guide) listOf(0.0, if (y + 92 <= maximumY) 92.0 else -92.0) + else listOf(0.0, 24.0, -24.0, 48.0, -48.0, 72.0, -72.0, 92.0, -92.0) + for (nudge in nudges) { + val rowY = (y + nudge).coerceIn(minimumY, maximumY) val bounds = Bounds(left, right, rowY - 84, rowY + 4) if (occupied.any { it.overlaps(bounds) }) continue occupied.add(bounds) - markers.add(DiscoveryMarker(candidate.node, candidate.geometry.distanceMeters, x, rowY, width, tier)) + markers.add(DiscoveryMarker(candidate.node, candidate.geometry.distanceMeters, x, rowY, width, tier, approximate)) break } } @@ -1109,3 +1124,85 @@ private fun VisionCamera(modifier: Modifier, update: (VisionOptics?, Boolean) -> } } } + + +internal data class VisionAntennaHeight(val meters: Double, val approximate: Boolean) + +internal fun visionAntennaHeight(role: String?, reported: Double?): VisionAntennaHeight { + val normalized = role?.lowercase() + val height = reported.takeIf { normalized == "repeater" } + val preset = when (normalized) { + "repeater", "room", "room server", "room_server", "roomserver", "room-server" -> CoverageHeightPreset.ROOFTOP + else -> CoverageHeightPreset.HANDHELD + } + return VisionAntennaHeight(height ?: preset.meters, height == null) +} + +internal sealed interface VisionElevationMode { + data object Guide : VisionElevationMode + data class Elevation(val altitude: Double, val accuracy: Double) : VisionElevationMode + + fun offset(distance: Double, antenna: Double?, pitch: Double, tangent: Double): Double? = when (this) { + Guide -> FieldGeometry.cameraBearingGuideOffset(pitch, tangent) + is Elevation -> antenna?.let { + FieldGeometry.cameraVerticalOffset(distance, it, altitude, accuracy, pitch, tangent, clampAngle = true) + } + } + + fun isApproximate(distance: Double, height: VisionAntennaHeight): Boolean = + this is Elevation && (height.approximate || FieldGeometry.cameraElevationUncertainty(distance, accuracy) > 8) +} + +internal fun visionElevationMode( + altitude: Double?, accuracy: Double?, distances: List, nearDistance: Double, +): VisionElevationMode { + if (altitude == null || !altitude.isFinite() || accuracy == null || !accuracy.isFinite() || accuracy <= 0 || + distances.any { it > nearDistance && FieldGeometry.cameraElevationUncertainty(it, accuracy) > 30 }) { + return VisionElevationMode.Guide + } + return VisionElevationMode.Elevation(altitude, accuracy) +} + +internal data class VisionTerrainPoint(val key: String, val coordinate: ProfileCoordinate) { + constructor(key: String, coordinate: FieldCoordinate) : + this(key, ProfileCoordinate(coordinate.latitude, coordinate.longitude)) +} + +private fun MeshNode.terrainPoint(): VisionTerrainPoint? = + visionCoordinate()?.let { VisionTerrainPoint(publicKey.lowercase(), it) } + +internal class VisionTerrainCache(private val provider: LinkTerrainProviding) { + private val elevations = mutableMapOf() + private val attempted = mutableSetOf() + + suspend fun resolve(points: Set): Map { + val missing = points.filterNot(attempted::contains) + .sortedWith(compareBy({ it.key }, { it.coordinate.latitude }, { it.coordinate.longitude })) + for (batch in missing.chunked(100)) { + val coordinates = batch.map { it.coordinate }.distinct() + val request = if (coordinates.size == 1) coordinates + coordinates else coordinates + val profile = try { + provider.profile(request) + } catch (_: IOException) { + null + } catch (_: IllegalArgumentException) { + null + } + kotlin.coroutines.coroutineContext.ensureActive() + attempted.addAll(batch) + if (profile == null) continue + val ground = request.zip(profile.points).associate { (coordinate, point) -> coordinate to point.elevationMeters } + for (point in batch) { + ground[point.coordinate]?.takeIf(Double::isFinite)?.let { elevations[point] = it } + } + } + return elevations.toMap() + } +} + +/** Ignore altitude changes that move even the closest eligible marker less than 0.15°. */ +internal fun stableVisionAltitude(previous: Double?, current: Double?, distance: Double?): Double? { + if (current == null || !current.isFinite()) return null + if (previous == null || distance == null) return current + return if (kotlin.math.atan2(abs(current - previous), distance) < Math.toRadians(0.15)) previous else current +} diff --git a/android/app/src/main/res/values-es/strings.xml b/android/app/src/main/res/values-es/strings.xml index 1089c8a..4d4091b 100644 --- a/android/app/src/main/res/values-es/strings.xml +++ b/android/app/src/main/res/values-es/strings.xml @@ -2018,7 +2018,7 @@ No se encontraron nodos cercanos. La brújula muestra hacia dónde apunta la cámara. Los marcadores muestran el nombre de cada nodo y la distancia hasta él. Los marcadores pequeños siguen la dirección del nodo y pueden colocarse a distintas alturas para que las etiquetas se lean bien. Toca un marcador para ver una vista previa del nodo. Elige «Destacar nodo» para resaltarlo al girar la cámara. Si eliges un nodo desde Cercanos, se destaca de inmediato. Cuando el nodo destacado queda fuera de la vista, las flechas en los bordes indican hacia dónde girar o inclinar la cámara. - Cuando hay suficientes datos de elevación, NodeVision los usa para colocar el marcador destacado en el eje vertical. «Elevación incierta» significa que su altura en pantalla es orientativa. + Cuando la altitud del teléfono es lo bastante precisa, NodeVision coloca los marcadores según la elevación estimada de la antena. Si no se ha indicado la altura, usa una altura típica de azotea o de dispositivo de mano. Nodos a 10 mi o menos Nodos a 10 km o menos Destacar nodo diff --git a/android/app/src/main/res/values-pt-rBR/strings.xml b/android/app/src/main/res/values-pt-rBR/strings.xml index bfe1f68..b53032e 100644 --- a/android/app/src/main/res/values-pt-rBR/strings.xml +++ b/android/app/src/main/res/values-pt-rBR/strings.xml @@ -2018,7 +2018,7 @@ Nenhum nó próximo foi encontrado. A bússola mostra para onde a câmera aponta. Os marcadores mostram o nome de cada nó e a distância até ele. Os marcadores menores seguem a direção do nó e podem aparecer em alturas diferentes para facilitar a leitura. Toque em um marcador para ver uma prévia do nó. Escolha “Destacar nó” para realçá-lo ao girar a câmera. Ao escolher um nó em Próximos, ele é destacado na hora. Quando o nó destacado sai da área visível, as setas nas bordas indicam para onde girar ou inclinar a câmera. - Quando há dados de elevação suficientes, o NodeVision os usa para posicionar o marcador destacado na vertical. “Elevação incerta” indica que a altura na tela é apenas uma referência. + Quando a altitude do celular é precisa o suficiente, o NodeVision posiciona os marcadores pela elevação estimada da antena. Sem uma altura informada, usa uma altura típica de telhado ou de dispositivo portátil. Nós a até 10 mi de você Nós a até 10 km de você Destacar nó diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 2ed3a4e..acf77af 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -2004,7 +2004,7 @@ No nearby nodes found. The compass shows where the camera is pointing. Markers show node names and distances from you. Smaller markers follow the node’s direction and may stagger vertically to keep labels readable. Tap a marker to preview a node. Choose Spotlight node to highlight it as you pan. Choosing a node from Nearby spotlights it immediately. Edge arrows show which way to turn or tilt when the highlighted node is outside the camera view. - When enough elevation data is available, NodeVision uses it to place the focused marker vertically. “Elevation Uncertain” means its height on screen is a rough guide. + When the phone’s altitude is accurate enough, NodeVision places markers by estimated antenna elevation. Without a reported height, it assumes a typical rooftop or handheld height. Nodes within 10 mi of you Nodes within 10 km of you Spotlight node diff --git a/android/app/src/test/java/org/nodescope/android/FieldGeometryTest.kt b/android/app/src/test/java/org/nodescope/android/FieldGeometryTest.kt index d19f142..234b120 100644 --- a/android/app/src/test/java/org/nodescope/android/FieldGeometryTest.kt +++ b/android/app/src/test/java/org/nodescope/android/FieldGeometryTest.kt @@ -4,6 +4,20 @@ import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test +import java.io.IOException +import kotlinx.coroutines.runBlocking +import org.nodescope.android.feature.nodevision.VisionAntennaHeight +import org.nodescope.android.feature.nodevision.VisionElevationMode +import org.nodescope.android.feature.nodevision.VisionTerrainCache +import org.nodescope.android.feature.nodevision.VisionTerrainPoint +import org.nodescope.android.feature.nodevision.stableVisionAltitude +import org.nodescope.android.feature.nodevision.visionAntennaHeight +import org.nodescope.android.feature.nodevision.visionElevationMode +import org.nodescope.android.feature.coverage.CoverageHeightPreset +import org.nodescope.android.feature.linkprofile.ElevationPoint +import org.nodescope.android.feature.linkprofile.LinkTerrainProviding +import org.nodescope.android.feature.linkprofile.ProfileCoordinate +import org.nodescope.android.feature.linkprofile.TerrainProfile import org.nodescope.android.feature.nodevision.VisionHeadingWarmup import org.nodescope.android.core.model.FieldCardinalDirection import org.nodescope.android.core.model.FieldCoordinate @@ -110,3 +124,52 @@ class FieldGeometryTest { assertNull(warmup.settledHeading(20.0, 770)) } } + + +class NodeVisionElevationTest { + @Test fun reportedAndDefaultHeights() { + assertEquals(VisionAntennaHeight(12.0, false), visionAntennaHeight("repeater", 12.0)) + for (role in listOf("repeater", "room", "room-server")) { + assertEquals(VisionAntennaHeight(CoverageHeightPreset.ROOFTOP.meters, true), visionAntennaHeight(role, null)) + } + assertEquals(VisionAntennaHeight(CoverageHeightPreset.HANDHELD.meters, true), visionAntennaHeight("companion", 12.0)) + } + + @Test fun placementModeAppliesToEveryMarker() { + val distances = listOf(30.0, 500.0) + for (mode in listOf(visionElevationMode(null, 2.0, distances, 5.0), + visionElevationMode(100.0, 10.0, distances, 5.0))) { + assertEquals(VisionElevationMode.Guide, mode) + assertEquals(mode.offset(30.0, null, 2.0, 0.5), mode.offset(500.0, 150.0, 2.0, 0.5)) + } + val mode = visionElevationMode(100.0, 2.0, listOf(500.0), 5.0) + assertEquals(VisionElevationMode.Elevation(100.0, 2.0), mode) + assertNull(mode.offset(500.0, null, 2.0, 0.5)) + assertTrue(mode.offset(500.0, 150.0, 2.0, 0.5) != null) + } + + @Test fun altitudeDeadbandAccumulatesChanges() { + val stable = stableVisionAltitude(100.0, 100.2, 100.0) + assertEquals(100.0, stable) + assertEquals(100.3, stableVisionAltitude(stable, 100.3, 100.0)) + assertNull(stableVisionAltitude(stable, null, 100.0)) + } + + @Test fun terrainBatchesCacheByNodeAndCoordinateAndKeepSuccessfulBatches() = runBlocking { + val requests = mutableListOf>() + val cache = VisionTerrainCache(LinkTerrainProviding { coordinates -> + requests.add(coordinates) + if (requests.size == 2) throw IOException() + TerrainProfile(coordinates.map { ElevationPoint(0.0, 42.0) }, 0, "network", coordinates) + }) + val points = (0..100).map { VisionTerrainPoint(it.toString().padStart(3, '0'), ProfileCoordinate(it / 100.0, 0.0)) }.toSet() + val first = cache.resolve(points) + assertEquals(100, first.size) + assertEquals(listOf(100, 2), requests.map { it.size }) + cache.resolve(points) + assertEquals(2, requests.size) + val moved = VisionTerrainPoint("000", ProfileCoordinate(2.0, 0.0)) + assertEquals(42.0, cache.resolve(first.keys + moved)[moved]) + assertEquals(listOf(moved.coordinate, moved.coordinate), requests.last()) + } +} From 6deeba9fce01cd5bed85d2b8ec64a58bde90d9a7 Mon Sep 17 00:00:00 2001 From: Adam <196335+anieto@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:08:55 -0600 Subject: [PATCH 02/18] Hide discovery markers beyond the viewfinder edge --- .../Features/NodeVision/NodeVisionScreen.swift | 10 +++++++++- CoreScopeViewerTests/FieldGeometryTests.swift | 7 +++++++ .../android/feature/nodevision/NodeVisionScreen.kt | 9 ++++++++- .../java/org/nodescope/android/FieldGeometryTest.kt | 8 ++++++++ 4 files changed, 32 insertions(+), 2 deletions(-) diff --git a/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift b/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift index 055f553..2a732cf 100644 --- a/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift +++ b/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift @@ -655,7 +655,9 @@ struct NodeVisionScreen: View { let distance = candidate.geometry.distanceMeters guard let vertical = mode.offset(distance: distance, antenna: antenna, pitch: pitch, tangent: verticalTangent) else { return } - let y = min(max(size.height * CGFloat(1 - vertical) / 2, minY), maxY) + let projectedY = size.height * CGFloat(1 - vertical) / 2 + guard let y = discoveryMarkerY(projectedY: projectedY, paneHeight: size.height, + minimumY: minY, maximumY: maxY) else { return } let approximate = mode.isApproximate(distance: distance, height: height) let nudges: [CGFloat] = mode == .guide ? [0, y + 92 <= maxY ? 92 : -92] : [0, 24, -24, 48, -48, 72, -72, 92, -92] for nudge in nudges { @@ -1230,3 +1232,9 @@ func stableVisionAltitude(previous: Double?, current: Double?, distance: Double? guard let previous, let distance else { return current } return atan2(abs(current - previous), distance) < 0.15 * .pi / 180 ? previous : current } + +/// Clamp to the label-safe area while the node is in or just outside the viewfinder. +func discoveryMarkerY(projectedY: CGFloat, paneHeight: CGFloat, minimumY: CGFloat, maximumY: CGFloat) -> CGFloat? { + guard (-24...(paneHeight + 24)).contains(projectedY) else { return nil } + return min(max(projectedY, minimumY), maximumY) +} diff --git a/CoreScopeViewerTests/FieldGeometryTests.swift b/CoreScopeViewerTests/FieldGeometryTests.swift index 5c56d44..60d7320 100644 --- a/CoreScopeViewerTests/FieldGeometryTests.swift +++ b/CoreScopeViewerTests/FieldGeometryTests.swift @@ -164,6 +164,13 @@ struct FieldGeometryTests { struct NodeVisionElevationTests { + @Test func discoveryMarkersLeaveTheEdgesWhenTiltedFartherAway() { + #expect(discoveryMarkerY(projectedY: -24, paneHeight: 800, minimumY: 166, maximumY: 700) == 166) + #expect(discoveryMarkerY(projectedY: 824, paneHeight: 800, minimumY: 166, maximumY: 700) == 700) + #expect(discoveryMarkerY(projectedY: -25, paneHeight: 800, minimumY: 166, maximumY: 700) == nil) + #expect(discoveryMarkerY(projectedY: 825, paneHeight: 800, minimumY: 166, maximumY: 700) == nil) + } + @Test func reportedAndDefaultHeights() { #expect(VisionAntennaHeight(role: "repeater", reported: 12).meters == 12) #expect(!VisionAntennaHeight(role: "repeater", reported: 12).approximate) diff --git a/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt b/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt index 4b268d0..4280560 100644 --- a/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt +++ b/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt @@ -830,7 +830,8 @@ private fun discoveryMarkers( val (elevation, height) = antenna(candidate.node) val distance = candidate.geometry.distanceMeters val vertical = mode.offset(distance, elevation, pitch, projection.halfHeightTangent) ?: return - val y = (paneHeight * (projection.centerY - vertical / 2)).coerceIn(minimumY, maximumY) + val projectedY = paneHeight * (projection.centerY - vertical / 2) + val y = discoveryMarkerY(projectedY, paneHeight, minimumY, maximumY) ?: return val approximate = mode.isApproximate(distance, height) val nudges = if (mode == VisionElevationMode.Guide) listOf(0.0, if (y + 92 <= maximumY) 92.0 else -92.0) else listOf(0.0, 24.0, -24.0, 48.0, -48.0, 72.0, -72.0, 92.0, -92.0) @@ -1206,3 +1207,9 @@ internal fun stableVisionAltitude(previous: Double?, current: Double?, distance: if (previous == null || distance == null) return current return if (kotlin.math.atan2(abs(current - previous), distance) < Math.toRadians(0.15)) previous else current } + +/** Clamp to the label-safe area while the node is in or just outside the viewfinder. */ +internal fun discoveryMarkerY(projectedY: Double, paneHeight: Double, minimumY: Double, maximumY: Double): Double? { + if (projectedY !in -24.0..(paneHeight + 24)) return null + return projectedY.coerceIn(minimumY, maximumY) +} diff --git a/android/app/src/test/java/org/nodescope/android/FieldGeometryTest.kt b/android/app/src/test/java/org/nodescope/android/FieldGeometryTest.kt index 234b120..374de2a 100644 --- a/android/app/src/test/java/org/nodescope/android/FieldGeometryTest.kt +++ b/android/app/src/test/java/org/nodescope/android/FieldGeometryTest.kt @@ -10,6 +10,7 @@ import org.nodescope.android.feature.nodevision.VisionAntennaHeight import org.nodescope.android.feature.nodevision.VisionElevationMode import org.nodescope.android.feature.nodevision.VisionTerrainCache import org.nodescope.android.feature.nodevision.VisionTerrainPoint +import org.nodescope.android.feature.nodevision.discoveryMarkerY import org.nodescope.android.feature.nodevision.stableVisionAltitude import org.nodescope.android.feature.nodevision.visionAntennaHeight import org.nodescope.android.feature.nodevision.visionElevationMode @@ -127,6 +128,13 @@ class FieldGeometryTest { class NodeVisionElevationTest { + @Test fun discoveryMarkersLeaveTheEdgesWhenTiltedFartherAway() { + assertEquals(166.0, discoveryMarkerY(-24.0, 800.0, 166.0, 700.0)) + assertEquals(700.0, discoveryMarkerY(824.0, 800.0, 166.0, 700.0)) + assertNull(discoveryMarkerY(-25.0, 800.0, 166.0, 700.0)) + assertNull(discoveryMarkerY(825.0, 800.0, 166.0, 700.0)) + } + @Test fun reportedAndDefaultHeights() { assertEquals(VisionAntennaHeight(12.0, false), visionAntennaHeight("repeater", 12.0)) for (role in listOf("repeater", "room", "room-server")) { From bacbae2c704f815def1a0f438776c27a87473291 Mon Sep 17 00:00:00 2001 From: Adam <196335+anieto@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:14:30 -0600 Subject: [PATCH 03/18] Explain approximate placement in NodeVision help --- CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift | 2 +- CoreScopeViewer/Resources/Localizable.xcstrings | 6 +++--- android/app/src/main/res/values-es/strings.xml | 2 +- android/app/src/main/res/values-pt-rBR/strings.xml | 2 +- android/app/src/main/res/values/strings.xml | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift b/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift index 2a732cf..b8f9071 100644 --- a/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift +++ b/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift @@ -128,7 +128,7 @@ struct NodeVisionScreen: View { VStack(alignment: .leading, spacing: 16) { Text("The compass shows where the camera is pointing. Markers show node names and distances from you. Smaller markers follow the node’s direction and may stagger vertically to keep labels readable.") Text("Tap a marker to preview a node. Choose Spotlight node to highlight it as you pan. Choosing a node from Nearby spotlights it immediately. Edge arrows show which way to turn or tilt when the highlighted node is outside the camera view.") - Text("When the phone’s altitude is accurate enough, NodeVision places markers by estimated antenna elevation. Without a reported height, it assumes a typical rooftop or handheld height.") + Text("When the phone’s altitude is accurate enough, NodeVision places markers by estimated antenna elevation. Without a reported height, it assumes a typical rooftop or handheld height. A dashed outline marks an approximate placement based on a default height or a less precise phone altitude.") Divider() VStack(alignment: .leading, spacing: 8) { Label("Location privacy", systemImage: "info.circle") diff --git a/CoreScopeViewer/Resources/Localizable.xcstrings b/CoreScopeViewer/Resources/Localizable.xcstrings index 49cc4d9..55099aa 100644 --- a/CoreScopeViewer/Resources/Localizable.xcstrings +++ b/CoreScopeViewer/Resources/Localizable.xcstrings @@ -33013,18 +33013,18 @@ } } }, - "When the phone’s altitude is accurate enough, NodeVision places markers by estimated antenna elevation. Without a reported height, it assumes a typical rooftop or handheld height." : { + "When the phone’s altitude is accurate enough, NodeVision places markers by estimated antenna elevation. Without a reported height, it assumes a typical rooftop or handheld height. A dashed outline marks an approximate placement based on a default height or a less precise phone altitude." : { "localizations" : { "es" : { "stringUnit" : { "state" : "translated", - "value" : "Cuando la altitud del teléfono es lo bastante precisa, NodeVision coloca los marcadores según la elevación estimada de la antena. Si no se ha indicado la altura, usa una altura típica de azotea o de dispositivo de mano." + "value" : "Cuando la altitud del teléfono es lo bastante precisa, NodeVision coloca los marcadores según la elevación estimada de la antena. Si no se ha indicado la altura, usa una altura típica de azotea o de dispositivo de mano. Un contorno discontinuo indica una posición aproximada basada en una altura predeterminada o en una altitud del teléfono menos precisa." } }, "pt-BR" : { "stringUnit" : { "state" : "translated", - "value" : "Quando a altitude do celular é precisa o suficiente, o NodeVision posiciona os marcadores pela elevação estimada da antena. Sem uma altura informada, usa uma altura típica de telhado ou de dispositivo portátil." + "value" : "Quando a altitude do celular é precisa o suficiente, o NodeVision posiciona os marcadores pela elevação estimada da antena. Sem uma altura informada, usa uma altura típica de telhado ou de dispositivo portátil. Um contorno tracejado indica uma posição aproximada baseada em uma altura padrão ou em uma altitude do celular menos precisa." } } } diff --git a/android/app/src/main/res/values-es/strings.xml b/android/app/src/main/res/values-es/strings.xml index 4d4091b..4e6ad0a 100644 --- a/android/app/src/main/res/values-es/strings.xml +++ b/android/app/src/main/res/values-es/strings.xml @@ -2018,7 +2018,7 @@ No se encontraron nodos cercanos. La brújula muestra hacia dónde apunta la cámara. Los marcadores muestran el nombre de cada nodo y la distancia hasta él. Los marcadores pequeños siguen la dirección del nodo y pueden colocarse a distintas alturas para que las etiquetas se lean bien. Toca un marcador para ver una vista previa del nodo. Elige «Destacar nodo» para resaltarlo al girar la cámara. Si eliges un nodo desde Cercanos, se destaca de inmediato. Cuando el nodo destacado queda fuera de la vista, las flechas en los bordes indican hacia dónde girar o inclinar la cámara. - Cuando la altitud del teléfono es lo bastante precisa, NodeVision coloca los marcadores según la elevación estimada de la antena. Si no se ha indicado la altura, usa una altura típica de azotea o de dispositivo de mano. + Cuando la altitud del teléfono es lo bastante precisa, NodeVision coloca los marcadores según la elevación estimada de la antena. Si no se ha indicado la altura, usa una altura típica de azotea o de dispositivo de mano. Una etiqueta más tenue indica una posición aproximada basada en una altura predeterminada o en una altitud del teléfono menos precisa. Nodos a 10 mi o menos Nodos a 10 km o menos Destacar nodo diff --git a/android/app/src/main/res/values-pt-rBR/strings.xml b/android/app/src/main/res/values-pt-rBR/strings.xml index b53032e..04f8aaa 100644 --- a/android/app/src/main/res/values-pt-rBR/strings.xml +++ b/android/app/src/main/res/values-pt-rBR/strings.xml @@ -2018,7 +2018,7 @@ Nenhum nó próximo foi encontrado. A bússola mostra para onde a câmera aponta. Os marcadores mostram o nome de cada nó e a distância até ele. Os marcadores menores seguem a direção do nó e podem aparecer em alturas diferentes para facilitar a leitura. Toque em um marcador para ver uma prévia do nó. Escolha “Destacar nó” para realçá-lo ao girar a câmera. Ao escolher um nó em Próximos, ele é destacado na hora. Quando o nó destacado sai da área visível, as setas nas bordas indicam para onde girar ou inclinar a câmera. - Quando a altitude do celular é precisa o suficiente, o NodeVision posiciona os marcadores pela elevação estimada da antena. Sem uma altura informada, usa uma altura típica de telhado ou de dispositivo portátil. + Quando a altitude do celular é precisa o suficiente, o NodeVision posiciona os marcadores pela elevação estimada da antena. Sem uma altura informada, usa uma altura típica de telhado ou de dispositivo portátil. Um rótulo mais discreto indica uma posição aproximada baseada em uma altura padrão ou em uma altitude do celular menos precisa. Nós a até 10 mi de você Nós a até 10 km de você Destacar nó diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index acf77af..1063073 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -2004,7 +2004,7 @@ No nearby nodes found. The compass shows where the camera is pointing. Markers show node names and distances from you. Smaller markers follow the node’s direction and may stagger vertically to keep labels readable. Tap a marker to preview a node. Choose Spotlight node to highlight it as you pan. Choosing a node from Nearby spotlights it immediately. Edge arrows show which way to turn or tilt when the highlighted node is outside the camera view. - When the phone’s altitude is accurate enough, NodeVision places markers by estimated antenna elevation. Without a reported height, it assumes a typical rooftop or handheld height. + When the phone’s altitude is accurate enough, NodeVision places markers by estimated antenna elevation. Without a reported height, it assumes a typical rooftop or handheld height. A dimmer label marks an approximate placement based on a default height or a less precise phone altitude. Nodes within 10 mi of you Nodes within 10 km of you Spotlight node From 65c0e4e14b568d29d9964e17d44c791de87a6e67 Mon Sep 17 00:00:00 2001 From: Adam <196335+anieto@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:38:30 -0600 Subject: [PATCH 04/18] Explain uncertain phone altitude in NodeVision --- .../NodeVision/NodeVisionScreen.swift | 21 ++++++------ .../Resources/Localizable.xcstrings | 32 +++++++++++++++++++ .../feature/nodevision/NodeVisionScreen.kt | 13 +++++--- .../app/src/main/res/values-es/strings.xml | 2 ++ .../src/main/res/values-pt-rBR/strings.xml | 2 ++ android/app/src/main/res/values/strings.xml | 2 ++ 6 files changed, 58 insertions(+), 14 deletions(-) diff --git a/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift b/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift index b8f9071..eb9b6ea 100644 --- a/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift +++ b/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift @@ -128,6 +128,7 @@ struct NodeVisionScreen: View { VStack(alignment: .leading, spacing: 16) { Text("The compass shows where the camera is pointing. Markers show node names and distances from you. Smaller markers follow the node’s direction and may stagger vertically to keep labels readable.") Text("Tap a marker to preview a node. Choose Spotlight node to highlight it as you pan. Choosing a node from Nearby spotlights it immediately. Edge arrows show which way to turn or tilt when the highlighted node is outside the camera view.") + Text("When your phone’s altitude is missing or too uncertain, markers show which way to turn. Their height on screen doesn’t indicate whether a node is above or below you.") Text("When the phone’s altitude is accurate enough, NodeVision places markers by estimated antenna elevation. Without a reported height, it assumes a typical rooftop or handheld height. A dashed outline marks an approximate placement based on a default height or a less precise phone altitude.") Divider() VStack(alignment: .leading, spacing: 8) { @@ -430,6 +431,14 @@ struct NodeVisionScreen: View { if cameraAvailable, let heading, let tangent { compass(heading: heading.trueHeadingDegrees, tangent: tangent, width: pane.size.width) } + if cameraAvailable, heading != nil, tangent != nil, fix != nil, mode == .guide, + target != nil || !discoveryMarkers.isEmpty { + Text("Phone altitude uncertain") + .font(.caption) + .foregroundStyle(supportingTextColor) + .padding(.horizontal, 16) + .padding(.vertical, 4) + } } .padding(.top, insets.top) .background { @@ -525,12 +534,8 @@ struct NodeVisionScreen: View { } else if targetStatus == "decommissioned" { Text("Owner reported: Decommissioned").font(.caption) } - if !markerVisible { - if placement.approximate { - Text("Approx. elevation").font(.caption) - } else if mode == .guide { - Text("Elevation Uncertain").font(.caption) - } + if !markerVisible, placement.approximate { + Text("Approx. elevation").font(.caption) } if cameraFailed { Text("Camera unavailable. You can return to the guide.") @@ -987,10 +992,6 @@ struct NodeVisionScreen: View { if let geometry { distance(geometry, style: .caption) } if approximate { Text("Approx. elevation").font(.caption2).foregroundStyle(supportingTextColor) - } else if !estimated { - Label("Elevation Uncertain", systemImage: "arrow.left.and.right") - .font(.caption2).foregroundStyle(supportingTextColor) - .accessibilityLabel("Elevation Uncertain. Use the marker for left or right direction.") } } .multilineTextAlignment(.center) diff --git a/CoreScopeViewer/Resources/Localizable.xcstrings b/CoreScopeViewer/Resources/Localizable.xcstrings index 55099aa..a1e0721 100644 --- a/CoreScopeViewer/Resources/Localizable.xcstrings +++ b/CoreScopeViewer/Resources/Localizable.xcstrings @@ -21575,6 +21575,22 @@ } } }, + "Phone altitude uncertain" : { + "localizations" : { + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Altitud del teléfono incierta" + } + }, + "pt-BR" : { + "stringUnit" : { + "state" : "translated", + "value" : "Altitude do celular incerta" + } + } + } + }, "Place a transmitter to find nearby known nodes." : { "localizations" : { "es" : { @@ -33029,6 +33045,22 @@ } } }, + "When your phone’s altitude is missing or too uncertain, markers show which way to turn. Their height on screen doesn’t indicate whether a node is above or below you." : { + "localizations" : { + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Cuando no se dispone de la altitud del teléfono o es demasiado imprecisa, los marcadores indican hacia dónde girar. Su altura en pantalla no indica si un nodo está por encima o por debajo de ti." + } + }, + "pt-BR" : { + "stringUnit" : { + "state" : "translated", + "value" : "Quando a altitude do celular está indisponível ou é imprecisa demais, os marcadores mostram para onde virar. A altura deles na tela não indica se um nó está acima ou abaixo de você." + } + } + } + }, "Where do I find my node’s public key?" : { "localizations" : { "es" : { diff --git a/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt b/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt index 4280560..bfb447f 100644 --- a/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt +++ b/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt @@ -463,8 +463,7 @@ internal fun NodeVisionScreen( overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center, onTextLayout = { truncatedName = it.hasVisualOverflow }) geometry?.let { Text(stringResource(R.string.nodevision_distance_away, formatDistance(it.distanceMeters / 1000, distanceUnit)), style = MaterialTheme.typography.labelSmall, fontFamily = MonaspaceNeon) } - if (approximate || mode == VisionElevationMode.Guide) Text(stringResource( - if (approximate) R.string.nodevision_approx_elevation else R.string.nodevision_elevation_uncertain), + if (approximate) Text(stringResource(R.string.nodevision_approx_elevation), style = MaterialTheme.typography.labelSmall, fontFamily = androidx.compose.ui.text.font.FontFamily.Default, color = supportingText) } } @@ -521,6 +520,12 @@ internal fun NodeVisionScreen( Box(Modifier.align(Alignment.BottomCenter).padding(bottom = 3.dp).size(3.dp, 15.dp).background(accent, shape = androidx.compose.foundation.shape.CircleShape)) } } + if (showCamera && trueHeading != null && projection != null && fix != null && + mode == VisionElevationMode.Guide && (visionTarget != null || discoveryMarkers.isNotEmpty())) { + Text(stringResource(R.string.nodevision_phone_altitude_uncertain), + Modifier.padding(horizontal = 16.dp, vertical = 4.dp), + style = MaterialTheme.typography.bodySmall, color = supportingText) + } HorizontalDivider(color = MaterialTheme.colorScheme.primary.copy(alpha = 0.25f)) if (BuildConfig.DEBUG && showsDiagnostics) { val decision = if (mode == VisionElevationMode.Guide) "All markers: pitch guide" @@ -585,8 +590,7 @@ internal fun NodeVisionScreen( } } ownerStatus?.let { Text(stringResource(it), style = MaterialTheme.typography.bodySmall) } - if (!markerVisible && (approximate || mode == VisionElevationMode.Guide)) Text(stringResource( - if (approximate) R.string.nodevision_approx_elevation else R.string.nodevision_elevation_uncertain), + if (!markerVisible && approximate) Text(stringResource(R.string.nodevision_approx_elevation), style = MaterialTheme.typography.bodySmall) status?.let { Text(stringResource(it)) } if (showSettings) TextButton(onClick = { @@ -756,6 +760,7 @@ internal fun NodeVisionScreen( verticalArrangement = Arrangement.spacedBy(12.dp)) { Text(stringResource(R.string.nodevision_help_markers)) Text(stringResource(R.string.nodevision_help_focus)) + Text(stringResource(R.string.nodevision_help_phone_altitude)) Text(stringResource(R.string.nodevision_help_elevation)) HorizontalDivider() Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { diff --git a/android/app/src/main/res/values-es/strings.xml b/android/app/src/main/res/values-es/strings.xml index 4e6ad0a..2c8eb90 100644 --- a/android/app/src/main/res/values-es/strings.xml +++ b/android/app/src/main/res/values-es/strings.xml @@ -2001,6 +2001,7 @@ Algunos propietarios indican deliberadamente una ubicación a poca distancia de la instalación real para evitar que se pueda identificar su domicilio u otro lugar privado. NodeVision apunta hacia la ubicación indicada. Nodo por encima del campo de visión Nodo por debajo del campo de visión + Altitud del teléfono incierta Elevación incierta %1$s m %1$s ft @@ -2018,6 +2019,7 @@ No se encontraron nodos cercanos. La brújula muestra hacia dónde apunta la cámara. Los marcadores muestran el nombre de cada nodo y la distancia hasta él. Los marcadores pequeños siguen la dirección del nodo y pueden colocarse a distintas alturas para que las etiquetas se lean bien. Toca un marcador para ver una vista previa del nodo. Elige «Destacar nodo» para resaltarlo al girar la cámara. Si eliges un nodo desde Cercanos, se destaca de inmediato. Cuando el nodo destacado queda fuera de la vista, las flechas en los bordes indican hacia dónde girar o inclinar la cámara. + Cuando no se dispone de la altitud del teléfono o es demasiado imprecisa, los marcadores indican hacia dónde girar. Su altura en pantalla no indica si un nodo está por encima o por debajo de ti. Cuando la altitud del teléfono es lo bastante precisa, NodeVision coloca los marcadores según la elevación estimada de la antena. Si no se ha indicado la altura, usa una altura típica de azotea o de dispositivo de mano. Una etiqueta más tenue indica una posición aproximada basada en una altura predeterminada o en una altitud del teléfono menos precisa. Nodos a 10 mi o menos Nodos a 10 km o menos diff --git a/android/app/src/main/res/values-pt-rBR/strings.xml b/android/app/src/main/res/values-pt-rBR/strings.xml index 04f8aaa..eb70b2d 100644 --- a/android/app/src/main/res/values-pt-rBR/strings.xml +++ b/android/app/src/main/res/values-pt-rBR/strings.xml @@ -2001,6 +2001,7 @@ Alguns proprietários informam intencionalmente uma localização a uma curta distância da instalação real para evitar que sua residência ou outro local privado seja identificado. O NodeVision aponta para a localização informada. Alvo acima da área visível Alvo abaixo da área visível + Altitude do celular incerta Elevação incerta %1$s m %1$s ft @@ -2018,6 +2019,7 @@ Nenhum nó próximo foi encontrado. A bússola mostra para onde a câmera aponta. Os marcadores mostram o nome de cada nó e a distância até ele. Os marcadores menores seguem a direção do nó e podem aparecer em alturas diferentes para facilitar a leitura. Toque em um marcador para ver uma prévia do nó. Escolha “Destacar nó” para realçá-lo ao girar a câmera. Ao escolher um nó em Próximos, ele é destacado na hora. Quando o nó destacado sai da área visível, as setas nas bordas indicam para onde girar ou inclinar a câmera. + Quando a altitude do celular está indisponível ou é imprecisa demais, os marcadores mostram para onde virar. A altura deles na tela não indica se um nó está acima ou abaixo de você. Quando a altitude do celular é precisa o suficiente, o NodeVision posiciona os marcadores pela elevação estimada da antena. Sem uma altura informada, usa uma altura típica de telhado ou de dispositivo portátil. Um rótulo mais discreto indica uma posição aproximada baseada em uma altura padrão ou em uma altitude do celular menos precisa. Nós a até 10 mi de você Nós a até 10 km de você diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 1063073..76d43de 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -1987,6 +1987,7 @@ Some node owners intentionally set the reported location a short distance from the actual installation to keep their home or another private location from being pinpointed. NodeVision points toward the reported location. Target above the view Target below the view + Phone altitude uncertain Elevation Uncertain %1$s m %1$s ft @@ -2004,6 +2005,7 @@ No nearby nodes found. The compass shows where the camera is pointing. Markers show node names and distances from you. Smaller markers follow the node’s direction and may stagger vertically to keep labels readable. Tap a marker to preview a node. Choose Spotlight node to highlight it as you pan. Choosing a node from Nearby spotlights it immediately. Edge arrows show which way to turn or tilt when the highlighted node is outside the camera view. + When your phone’s altitude is missing or too uncertain, markers show which way to turn. Their height on screen doesn’t indicate whether a node is above or below you. When the phone’s altitude is accurate enough, NodeVision places markers by estimated antenna elevation. Without a reported height, it assumes a typical rooftop or handheld height. A dimmer label marks an approximate placement based on a default height or a less precise phone altitude. Nodes within 10 mi of you Nodes within 10 km of you From 5ed48796456096d8bc09c9c07bcfcb81566c4de8 Mon Sep 17 00:00:00 2001 From: Adam <196335+anieto@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:19:03 -0600 Subject: [PATCH 05/18] Strengthen NodeVision marker borders --- .../NodeVision/NodeVisionScreen.swift | 31 ++++++++------ .../feature/nodevision/NodeVisionScreen.kt | 40 +++++++++++++++---- .../app/src/main/res/values-es/strings.xml | 2 +- .../src/main/res/values-pt-rBR/strings.xml | 2 +- android/app/src/main/res/values/strings.xml | 2 +- 5 files changed, 55 insertions(+), 22 deletions(-) diff --git a/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift b/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift index eb9b6ea..4c7a9af 100644 --- a/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift +++ b/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift @@ -703,15 +703,8 @@ struct NodeVisionScreen: View { .frame(width: marker.width) .frame(minHeight: 44) .padding(.bottom, 9) - .background { overlaySurface(NodeVisionMarkerShape()) } - .overlay { - if selected || marker.approximate { - NodeVisionMarkerShape().stroke(nodeNameColor, style: StrokeStyle( - lineWidth: selected ? 2 : 1, dash: marker.approximate ? [4, 3] : [])) - } - } + .background { markerSurface(approximate: marker.approximate, emphasized: selected) } .contentShape(Rectangle()) - .opacity(marker.tier == 2 && !selected ? 0.90 : 1) } .buttonStyle(.plain) .accessibilityAddTraits(selected ? .isSelected : []) @@ -860,15 +853,29 @@ struct NodeVisionScreen: View { .foregroundStyle(nodeNameColor) } - private func overlaySurface(_ shape: S, pinned: Bool = false) -> some View { + private func markerSurface(approximate: Bool, emphasized: Bool, spotlight: Bool = false) -> some View { + let shape = NodeVisionMarkerShape() + let width: CGFloat = emphasized ? 3 : 2 + let borderColor = spotlight && colorScheme == .dark ? NodeScopeStyle.activity : nodeNameColor + let backing = colorScheme == .dark ? NodeScopeStyle.deepNavy : Color(uiColor: .systemBackground) + return overlaySurface(shape, drawsBorder: false) + .overlay { shape.stroke(backing, lineWidth: width + 2) } + .overlay { + shape.stroke(borderColor, style: StrokeStyle( + lineWidth: width, lineCap: .round, lineJoin: .round, dash: approximate ? [7, 6] : [])) + } + } + + private func overlaySurface(_ shape: S, drawsBorder: Bool = true) -> some View { return shape.fill(.regularMaterial) .overlay { shape.fill(colorScheme == .light ? Color(uiColor: .systemBackground).opacity(0.85) : .clear) } .overlay { shape.fill(overlayGradient) } .overlay { - shape.stroke(pinned ? NodeScopeStyle.activity : NodeScopeStyle.signal.opacity(0.4), - lineWidth: pinned ? (colorScheme == .light ? 2 : 1.5) : 1) + if drawsBorder { + shape.stroke(NodeScopeStyle.signal.opacity(0.4), lineWidth: 1) + } } .shadow(color: .black.opacity(0.24), radius: 5, x: 0, y: 2) } @@ -999,7 +1006,7 @@ struct NodeVisionScreen: View { .padding(.vertical, 5) .frame(maxWidth: markerWidth) .padding(.bottom, 9) - .background { overlaySurface(NodeVisionMarkerShape(), pinned: true) } + .background { markerSurface(approximate: approximate, emphasized: true, spotlight: true) } } .frame(width: markerWidth, height: 88, alignment: .bottom) .position(x: size.width / 2 + pixel, y: markerY - 44) diff --git a/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt b/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt index bfb447f..48c3f6d 100644 --- a/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt +++ b/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt @@ -43,7 +43,14 @@ import android.net.Uri import android.os.SystemClock import android.os.Build import android.location.altitude.AltitudeConverter -import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.drawWithCache +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Outline +import androidx.compose.ui.graphics.PathEffect +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.StrokeJoin +import androidx.compose.ui.graphics.drawscope.Stroke import org.nodescope.android.feature.coverage.CoverageHeightPreset import org.nodescope.android.feature.linkprofile.LinkTerrainProviding import java.io.File @@ -265,12 +272,13 @@ internal fun NodeVisionScreen( val onSurface = MaterialTheme.colorScheme.onSurface val lightOverlay = surface.luminance() >= 0.5f val supportingText = lerp(onSurface, surface, if (lightOverlay) 0.10f else 0.22f) - val markerBorder = BorderStroke(if (lightOverlay) 2.dp else 1.5.dp, accent) val density = LocalDensity.current val markerShape = remember(density) { with(density) { visionMarkerShape(10.dp.toPx(), 9.dp.toPx(), 8.dp.toPx()) } } val blue = MaterialTheme.colorScheme.primary + val markerInk = if (lightOverlay) lerp(blue, onSurface, 0.25f) else blue + val spotlightInk = if (lightOverlay) markerInk else accent val overlayTint = if (lightOverlay) { Brush.verticalGradient(listOf(blue.copy(alpha = 0.16f), blue.copy(alpha = 0.07f))) } else { @@ -391,12 +399,11 @@ internal fun NodeVisionScreen( expandsInspection = false }, shape = markerShape, - color = surface.copy(alpha = if (marker.tier == 2 && !selected) 0.90f else 0.98f), - border = if (selected) BorderStroke(2.dp, blue) else overlayBorder, + color = surface.copy(alpha = 0.98f), shadowElevation = 4.dp, ) { Column(Modifier.background(overlayTint) - .alpha(if (marker.approximate) 0.84f else 1f) + .visionMarkerBorder(markerShape, markerInk, surface, marker.approximate, selected) .padding(bottom = 9.dp).padding(horizontal = 6.dp, vertical = 4.dp), horizontalAlignment = Alignment.CenterHorizontally) { Text(marker.node.displayName, fontFamily = MonaspaceNeon, @@ -455,9 +462,12 @@ internal fun NodeVisionScreen( .width(markerWidth).height(88.dp), contentAlignment = Alignment.BottomCenter) { Surface( color = surface.copy(alpha = 0.98f), shape = markerShape, - border = markerBorder, shadowElevation = 4.dp, + shadowElevation = 4.dp, ) { - Column(Modifier.background(overlayTint).padding(bottom = 9.dp).padding(horizontal = 9.dp, vertical = 5.dp), horizontalAlignment = Alignment.CenterHorizontally) { + Column(Modifier.background(overlayTint) + .visionMarkerBorder(markerShape, spotlightInk, surface, approximate, emphasized = true) + .padding(bottom = 9.dp).padding(horizontal = 9.dp, vertical = 5.dp), + horizontalAlignment = Alignment.CenterHorizontally) { Text(visionName, style = MaterialTheme.typography.titleSmall, fontFamily = MonaspaceNeon, color = MaterialTheme.colorScheme.primary, maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center, @@ -1218,3 +1228,19 @@ internal fun discoveryMarkerY(projectedY: Double, paneHeight: Double, minimumY: if (projectedY !in -24.0..(paneHeight + 24)) return null return projectedY.coerceIn(minimumY, maximumY) } + +private fun Modifier.visionMarkerBorder( + shape: Shape, ink: Color, backing: Color, approximate: Boolean, emphasized: Boolean, +): Modifier = drawWithCache { + // The marker shape is a GenericShape. Draw inside the clipped Surface so the full width stays visible. + val path = (shape.createOutline(size, layoutDirection, this) as Outline.Generic).path + val width = if (emphasized) 3.dp.toPx() else 2.dp.toPx() + val baseStroke = Stroke(width = 2 * (width + 1.dp.toPx()), join = StrokeJoin.Round) + val pattern = if (approximate) PathEffect.dashPathEffect(floatArrayOf(7.dp.toPx(), 6.dp.toPx())) else null + val stroke = Stroke(width = 2 * width, cap = StrokeCap.Butt, join = StrokeJoin.Round, pathEffect = pattern) + onDrawWithContent { + drawContent() + drawPath(path, backing, style = baseStroke) + drawPath(path, ink, style = stroke) + } +} diff --git a/android/app/src/main/res/values-es/strings.xml b/android/app/src/main/res/values-es/strings.xml index 2c8eb90..d580711 100644 --- a/android/app/src/main/res/values-es/strings.xml +++ b/android/app/src/main/res/values-es/strings.xml @@ -2020,7 +2020,7 @@ La brújula muestra hacia dónde apunta la cámara. Los marcadores muestran el nombre de cada nodo y la distancia hasta él. Los marcadores pequeños siguen la dirección del nodo y pueden colocarse a distintas alturas para que las etiquetas se lean bien. Toca un marcador para ver una vista previa del nodo. Elige «Destacar nodo» para resaltarlo al girar la cámara. Si eliges un nodo desde Cercanos, se destaca de inmediato. Cuando el nodo destacado queda fuera de la vista, las flechas en los bordes indican hacia dónde girar o inclinar la cámara. Cuando no se dispone de la altitud del teléfono o es demasiado imprecisa, los marcadores indican hacia dónde girar. Su altura en pantalla no indica si un nodo está por encima o por debajo de ti. - Cuando la altitud del teléfono es lo bastante precisa, NodeVision coloca los marcadores según la elevación estimada de la antena. Si no se ha indicado la altura, usa una altura típica de azotea o de dispositivo de mano. Una etiqueta más tenue indica una posición aproximada basada en una altura predeterminada o en una altitud del teléfono menos precisa. + Cuando la altitud del teléfono es lo bastante precisa, NodeVision coloca los marcadores según la elevación estimada de la antena. Si no se ha indicado la altura, usa una altura típica de azotea o de dispositivo de mano. Un contorno discontinuo indica una posición aproximada basada en una altura predeterminada o en una altitud del teléfono menos precisa. Nodos a 10 mi o menos Nodos a 10 km o menos Destacar nodo diff --git a/android/app/src/main/res/values-pt-rBR/strings.xml b/android/app/src/main/res/values-pt-rBR/strings.xml index eb70b2d..e2e7790 100644 --- a/android/app/src/main/res/values-pt-rBR/strings.xml +++ b/android/app/src/main/res/values-pt-rBR/strings.xml @@ -2020,7 +2020,7 @@ A bússola mostra para onde a câmera aponta. Os marcadores mostram o nome de cada nó e a distância até ele. Os marcadores menores seguem a direção do nó e podem aparecer em alturas diferentes para facilitar a leitura. Toque em um marcador para ver uma prévia do nó. Escolha “Destacar nó” para realçá-lo ao girar a câmera. Ao escolher um nó em Próximos, ele é destacado na hora. Quando o nó destacado sai da área visível, as setas nas bordas indicam para onde girar ou inclinar a câmera. Quando a altitude do celular está indisponível ou é imprecisa demais, os marcadores mostram para onde virar. A altura deles na tela não indica se um nó está acima ou abaixo de você. - Quando a altitude do celular é precisa o suficiente, o NodeVision posiciona os marcadores pela elevação estimada da antena. Sem uma altura informada, usa uma altura típica de telhado ou de dispositivo portátil. Um rótulo mais discreto indica uma posição aproximada baseada em uma altura padrão ou em uma altitude do celular menos precisa. + Quando a altitude do celular é precisa o suficiente, o NodeVision posiciona os marcadores pela elevação estimada da antena. Sem uma altura informada, usa uma altura típica de telhado ou de dispositivo portátil. Um contorno tracejado indica uma posição aproximada baseada em uma altura padrão ou em uma altitude do celular menos precisa. Nós a até 10 mi de você Nós a até 10 km de você Destacar nó diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 76d43de..80b54f9 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -2006,7 +2006,7 @@ The compass shows where the camera is pointing. Markers show node names and distances from you. Smaller markers follow the node’s direction and may stagger vertically to keep labels readable. Tap a marker to preview a node. Choose Spotlight node to highlight it as you pan. Choosing a node from Nearby spotlights it immediately. Edge arrows show which way to turn or tilt when the highlighted node is outside the camera view. When your phone’s altitude is missing or too uncertain, markers show which way to turn. Their height on screen doesn’t indicate whether a node is above or below you. - When the phone’s altitude is accurate enough, NodeVision places markers by estimated antenna elevation. Without a reported height, it assumes a typical rooftop or handheld height. A dimmer label marks an approximate placement based on a default height or a less precise phone altitude. + When the phone’s altitude is accurate enough, NodeVision places markers by estimated antenna elevation. Without a reported height, it assumes a typical rooftop or handheld height. A dashed outline marks an approximate placement based on a default height or a less precise phone altitude. Nodes within 10 mi of you Nodes within 10 km of you Spotlight node From c81499e4700c18bb9c6a75e579db7cfa259e1235 Mon Sep 17 00:00:00 2001 From: Adam <196335+anieto@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:22:12 -0600 Subject: [PATCH 06/18] Restore orange Spotlight borders in light mode --- CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift | 2 +- .../nodescope/android/feature/nodevision/NodeVisionScreen.kt | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift b/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift index 4c7a9af..03d652a 100644 --- a/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift +++ b/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift @@ -856,7 +856,7 @@ struct NodeVisionScreen: View { private func markerSurface(approximate: Bool, emphasized: Bool, spotlight: Bool = false) -> some View { let shape = NodeVisionMarkerShape() let width: CGFloat = emphasized ? 3 : 2 - let borderColor = spotlight && colorScheme == .dark ? NodeScopeStyle.activity : nodeNameColor + let borderColor = spotlight ? NodeScopeStyle.activity : nodeNameColor let backing = colorScheme == .dark ? NodeScopeStyle.deepNavy : Color(uiColor: .systemBackground) return overlaySurface(shape, drawsBorder: false) .overlay { shape.stroke(backing, lineWidth: width + 2) } diff --git a/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt b/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt index 48c3f6d..7b7ef56 100644 --- a/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt +++ b/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt @@ -278,7 +278,6 @@ internal fun NodeVisionScreen( } val blue = MaterialTheme.colorScheme.primary val markerInk = if (lightOverlay) lerp(blue, onSurface, 0.25f) else blue - val spotlightInk = if (lightOverlay) markerInk else accent val overlayTint = if (lightOverlay) { Brush.verticalGradient(listOf(blue.copy(alpha = 0.16f), blue.copy(alpha = 0.07f))) } else { @@ -465,7 +464,7 @@ internal fun NodeVisionScreen( shadowElevation = 4.dp, ) { Column(Modifier.background(overlayTint) - .visionMarkerBorder(markerShape, spotlightInk, surface, approximate, emphasized = true) + .visionMarkerBorder(markerShape, accent, surface, approximate, emphasized = true) .padding(bottom = 9.dp).padding(horizontal = 9.dp, vertical = 5.dp), horizontalAlignment = Alignment.CenterHorizontally) { Text(visionName, style = MaterialTheme.typography.titleSmall, fontFamily = MonaspaceNeon, From ada9175dd2f39a27063465255d63da890a551a00 Mon Sep 17 00:00:00 2001 From: Adam <196335+anieto@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:27:38 -0600 Subject: [PATCH 07/18] Match Spotlight and discovery marker widths --- .../NodeVision/NodeVisionScreen.swift | 19 +++++++++++--- .../feature/nodevision/NodeVisionScreen.kt | 25 +++++++++++++------ 2 files changed, 33 insertions(+), 11 deletions(-) diff --git a/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift b/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift index 03d652a..8f3e0bb 100644 --- a/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift +++ b/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift @@ -354,7 +354,8 @@ struct NodeVisionScreen: View { } } } - let markerWidth = min(192, max(0, pane.size.width - 32)) + let markerWidth = min(Self.markerWidth(tier: Self.markerTier(distance: geometry?.distanceMeters ?? 0)), + max(0, pane.size.width - 32)) let edge = max(0, pane.size.width / 2 - markerWidth / 2 - 8) let offscreen = offset.map { abs($0 * pane.size.width / 2) > max(0, edge + (arrowShown ? -6 : 6)) } ?? false let showSettings = location.status == .denied || AVCaptureDevice.authorizationStatus(for: .video) == .denied @@ -612,6 +613,16 @@ struct NodeVisionScreen: View { }.sorted { ($0.geometry.distanceMeters, $0.node.publicKey) < ($1.geometry.distanceMeters, $1.node.publicKey) } } + private static func markerTier(distance: Double) -> Int { + if distance < 500 { return 0 } + if distance < 2_000 { return 1 } + return 2 + } + + private static func markerWidth(tier: Int) -> CGFloat { + [132, 112, 96][tier] + } + private struct DiscoveryMarker: Identifiable { let candidate: NearbyNode let x: CGFloat @@ -648,8 +659,8 @@ struct NodeVisionScreen: View { let offset = FieldGeometry.cameraHorizontalOffset(bearing: bearing, heading: heading.trueHeadingDegrees, halfWidthTangent: tangent), abs(offset) < 1 else { return } - let tier = candidate.geometry.distanceMeters < 500 ? 0 : candidate.geometry.distanceMeters < 2_000 ? 1 : 2 - let width: CGFloat = [132, 112, 96][tier] + let tier = Self.markerTier(distance: candidate.geometry.distanceMeters) + let width = Self.markerWidth(tier: tier) let x = size.width * CGFloat(1 + offset) / 2 let left = x - width / 2 - 5 let paddedWidth = width + 10 @@ -1004,7 +1015,7 @@ struct NodeVisionScreen: View { .multilineTextAlignment(.center) .padding(.horizontal, 9) .padding(.vertical, 5) - .frame(maxWidth: markerWidth) + .frame(width: markerWidth) .padding(.bottom, 9) .background { markerSurface(approximate: approximate, emphasized: true, spotlight: true) } } diff --git a/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt b/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt index 7b7ef56..ff7e3bd 100644 --- a/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt +++ b/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt @@ -311,7 +311,8 @@ internal fun NodeVisionScreen( val offset = if (!near && bearing != null && trueHeading != null && tangent != null && projection != null) { FieldGeometry.cameraHorizontalOffset(bearing, trueHeading, tangent)?.plus(projection.centerX * 2 - 1) } else null - val markerWidth = minOf(192.dp, (paneWidth - 32.dp).coerceAtLeast(0.dp)) + val markerWidth = minOf(visionMarkerWidth(visionMarkerTier(geometry?.distanceMeters ?: 0.0)).dp, + (paneWidth - 32.dp).coerceAtLeast(0.dp)) val pixel = (offset ?: 0.0) * paneWidth.value / 2 val limit = (paneWidth.value / 2 - markerWidth.value / 2 - 8).coerceAtLeast(0f) val offscreen = abs(pixel) > (limit + if (edge) -6 else 6).coerceAtLeast(0f) @@ -392,6 +393,7 @@ internal fun NodeVisionScreen( ) { Box(Modifier.width(marker.width.dp).height(80.dp), contentAlignment = Alignment.BottomCenter) { Surface( + modifier = Modifier.fillMaxWidth(), enabled = visible, onClick = { inspectedKey = marker.node.publicKey @@ -460,6 +462,7 @@ internal fun NodeVisionScreen( Box(Modifier.offset(x = maxWidth / 2 + pixel.dp - markerWidth / 2, y = markerY - 88.dp) .width(markerWidth).height(88.dp), contentAlignment = Alignment.BottomCenter) { Surface( + modifier = Modifier.fillMaxWidth(), color = surface.copy(alpha = 0.98f), shape = markerShape, shadowElevation = 4.dp, ) { @@ -805,6 +808,18 @@ internal fun NodeVisionScreen( } private data class NearbyVisionNode(val node: MeshNode, val geometry: FieldGeometryResult) +private fun visionMarkerTier(distance: Double): Int = when { + distance < 500 -> 0 + distance < 2_000 -> 1 + else -> 2 +} + +private fun visionMarkerWidth(tier: Int): Double = when (tier) { + 0 -> 132.0 + 1 -> 112.0 + else -> 96.0 +} + private data class DiscoveryMarker( val node: MeshNode, val distance: Double, val x: Double, val y: Double, val width: Double, val tier: Int, val approximate: Boolean, ) @@ -832,12 +847,8 @@ private fun discoveryMarkers( val bearing = candidate.geometry.initialBearingDegrees ?: return val offset = FieldGeometry.cameraHorizontalOffset(bearing, heading, projection.halfWidthTangent) ?: return val x = paneWidth * (projection.centerX + offset / 2) - val tier = when { - candidate.geometry.distanceMeters < 500 -> 0 - candidate.geometry.distanceMeters < 2_000 -> 1 - else -> 2 - } - val width = when (tier) { 0 -> 132.0; 1 -> 112.0; else -> 96.0 } + val tier = visionMarkerTier(candidate.geometry.distanceMeters) + val width = visionMarkerWidth(tier) val left = x - width / 2 - 5 val right = x + width / 2 + 5 if (left < 0 || right > paneWidth) return From 7e4bac2ae88969ccc88666b6f254d717e0c7057b Mon Sep 17 00:00:00 2001 From: Adam <196335+anieto@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:36:25 -0600 Subject: [PATCH 08/18] Match Spotlight and discovery label typography --- .../NodeVision/NodeVisionScreen.swift | 21 ++++++++++++------- .../feature/nodevision/NodeVisionScreen.kt | 11 ++++++---- 2 files changed, 20 insertions(+), 12 deletions(-) diff --git a/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift b/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift index 8f3e0bb..a50b767 100644 --- a/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift +++ b/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift @@ -354,7 +354,8 @@ struct NodeVisionScreen: View { } } } - let markerWidth = min(Self.markerWidth(tier: Self.markerTier(distance: geometry?.distanceMeters ?? 0)), + let markerTier = Self.markerTier(distance: geometry?.distanceMeters ?? 0) + let markerWidth = min(Self.markerWidth(tier: markerTier), max(0, pane.size.width - 32)) let edge = max(0, pane.size.width / 2 - markerWidth / 2 - 8) let offscreen = offset.map { abs($0 * pane.size.width / 2) > max(0, edge + (arrowShown ? -6 : 6)) } ?? false @@ -398,7 +399,7 @@ struct NodeVisionScreen: View { .id(mode == .guide) if cameraAvailable, !near, !showsBottomArrow, let offset, placement.y != nil || offscreen { direction(offset, offscreen: offscreen, verticalEdge: useVerticalArrow ? verticalEdge : nil, - markerWidth: markerWidth, markerY: placement.y ?? pane.size.height * 0.43, estimated: mode != .guide, + markerWidth: markerWidth, markerTier: markerTier, markerY: placement.y ?? pane.size.height * 0.43, estimated: mode != .guide, approximate: placement.approximate, size: pane.size, geometry: geometry) } VStack(spacing: 0) { @@ -623,6 +624,10 @@ struct NodeVisionScreen: View { [132, 112, 96][tier] } + private static func markerNameFont(tier: Int) -> Font { + .monaspace(tier == 0 ? .subheadline : .caption).weight(.semibold) + } + private struct DiscoveryMarker: Identifiable { let candidate: NearbyNode let x: CGFloat @@ -703,7 +708,7 @@ struct NodeVisionScreen: View { } label: { VStack(spacing: 2) { Text(FieldCatalogItem.node(node).name) - .font(.monaspace(marker.tier == 0 ? .subheadline : .caption).weight(.semibold)) + .font(Self.markerNameFont(tier: marker.tier)) .foregroundStyle(nodeNameColor) .lineLimit(2) distance(marker.candidate.geometry, style: .caption2) @@ -973,7 +978,7 @@ struct NodeVisionScreen: View { .accessibilityLabel(edge == .above ? "Target above the view" : "Target below the view") } - private func direction(_ offset: Double, offscreen: Bool, verticalEdge: VerticalEdge?, markerWidth: CGFloat, + private func direction(_ offset: Double, offscreen: Bool, verticalEdge: VerticalEdge?, markerWidth: CGFloat, markerTier: Int, markerY: CGFloat, estimated: Bool, approximate: Bool, size: CGSize, geometry: FieldGeometryResult?) -> some View { let pixel = offset * size.width / 2 @@ -1005,16 +1010,16 @@ struct NodeVisionScreen: View { .hidden() .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { fullNameHeight = $0 } } - .font(.monaspace(.subheadline).weight(.semibold)) + .font(Self.markerNameFont(tier: markerTier)) .foregroundStyle(nodeNameColor) - if let geometry { distance(geometry, style: .caption) } + if let geometry { distance(geometry, style: .caption2) } if approximate { Text("Approx. elevation").font(.caption2).foregroundStyle(supportingTextColor) } } .multilineTextAlignment(.center) - .padding(.horizontal, 9) - .padding(.vertical, 5) + .padding(.horizontal, 6) + .padding(.vertical, 4) .frame(width: markerWidth) .padding(.bottom, 9) .background { markerSurface(approximate: approximate, emphasized: true, spotlight: true) } diff --git a/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt b/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt index ff7e3bd..179e465 100644 --- a/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt +++ b/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt @@ -277,6 +277,8 @@ internal fun NodeVisionScreen( with(density) { visionMarkerShape(10.dp.toPx(), 9.dp.toPx(), 8.dp.toPx()) } } val blue = MaterialTheme.colorScheme.primary + val typography = MaterialTheme.typography + fun markerNameStyle(tier: Int) = if (tier == 0) typography.titleSmall else typography.labelMedium val markerInk = if (lightOverlay) lerp(blue, onSurface, 0.25f) else blue val overlayTint = if (lightOverlay) { Brush.verticalGradient(listOf(blue.copy(alpha = 0.16f), blue.copy(alpha = 0.07f))) @@ -311,7 +313,8 @@ internal fun NodeVisionScreen( val offset = if (!near && bearing != null && trueHeading != null && tangent != null && projection != null) { FieldGeometry.cameraHorizontalOffset(bearing, trueHeading, tangent)?.plus(projection.centerX * 2 - 1) } else null - val markerWidth = minOf(visionMarkerWidth(visionMarkerTier(geometry?.distanceMeters ?: 0.0)).dp, + val markerTier = visionMarkerTier(geometry?.distanceMeters ?: 0.0) + val markerWidth = minOf(visionMarkerWidth(markerTier).dp, (paneWidth - 32.dp).coerceAtLeast(0.dp)) val pixel = (offset ?: 0.0) * paneWidth.value / 2 val limit = (paneWidth.value / 2 - markerWidth.value / 2 - 8).coerceAtLeast(0f) @@ -408,7 +411,7 @@ internal fun NodeVisionScreen( .padding(bottom = 9.dp).padding(horizontal = 6.dp, vertical = 4.dp), horizontalAlignment = Alignment.CenterHorizontally) { Text(marker.node.displayName, fontFamily = MonaspaceNeon, - style = if (marker.tier == 0) MaterialTheme.typography.titleSmall else MaterialTheme.typography.labelMedium, + style = markerNameStyle(marker.tier), color = blue, maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center) Text(stringResource(R.string.nodevision_distance_away, formatDistance(marker.distance / 1000, distanceUnit)), style = MaterialTheme.typography.labelSmall, fontFamily = MonaspaceNeon, @@ -468,9 +471,9 @@ internal fun NodeVisionScreen( ) { Column(Modifier.background(overlayTint) .visionMarkerBorder(markerShape, accent, surface, approximate, emphasized = true) - .padding(bottom = 9.dp).padding(horizontal = 9.dp, vertical = 5.dp), + .padding(bottom = 9.dp).padding(horizontal = 6.dp, vertical = 4.dp), horizontalAlignment = Alignment.CenterHorizontally) { - Text(visionName, style = MaterialTheme.typography.titleSmall, fontFamily = MonaspaceNeon, + Text(visionName, style = markerNameStyle(markerTier), fontFamily = MonaspaceNeon, color = MaterialTheme.colorScheme.primary, maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center, onTextLayout = { truncatedName = it.hasVisualOverflow }) From 69dce5fb34cc3e990f911540084dc65a8c6ef555 Mon Sep 17 00:00:00 2001 From: Adam <196335+anieto@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:42:17 -0600 Subject: [PATCH 09/18] Brighten NodeVision node names in dark mode --- .../Features/NodeVision/NodeVisionScreen.swift | 18 ++++++++++++------ .../feature/nodevision/NodeVisionScreen.kt | 9 +++++---- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift b/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift index a50b767..cb21cbe 100644 --- a/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift +++ b/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift @@ -521,7 +521,7 @@ struct NodeVisionScreen: View { if let installHeight { HStack(spacing: 8) { Image(systemName: "arrow.up.and.down") - .foregroundStyle(nodeNameColor) + .foregroundStyle(overlayInk) .accessibilityHidden(true) Text("Reported install height") .foregroundStyle(supportingTextColor) @@ -580,7 +580,7 @@ struct NodeVisionScreen: View { } } .buttonStyle(.bordered) - .tint(nodeNameColor) + .tint(overlayInk) .padding(.bottom, insets.bottom + 8) } } @@ -745,11 +745,13 @@ struct NodeVisionScreen: View { } } label: { HStack { - Text(item.name).font(.monaspace(.subheadline).weight(.semibold)) + Text(item.name) + .font(.monaspace(.subheadline).weight(.semibold)) + .foregroundStyle(nodeNameColor) Spacer(minLength: 10) Image(systemName: expandsInspection ? "chevron.down" : "chevron.up") } - .foregroundStyle(nodeNameColor) + .foregroundStyle(overlayInk) .frame(minHeight: 44) .contentShape(Rectangle()) } @@ -836,6 +838,10 @@ struct NodeVisionScreen: View { } private var nodeNameColor: Color { + colorScheme == .dark ? overlayInk.mix(with: .white, by: 0.55) : overlayInk + } + + private var overlayInk: Color { colorScheme == .dark ? NodeScopeStyle.signal : NodeScopeStyle.signal.mix(with: NodeScopeStyle.deepNavy, by: 0.45) @@ -866,13 +872,13 @@ struct NodeVisionScreen: View { .contentShape(Capsule()) } .buttonStyle(.plain) - .foregroundStyle(nodeNameColor) + .foregroundStyle(overlayInk) } private func markerSurface(approximate: Bool, emphasized: Bool, spotlight: Bool = false) -> some View { let shape = NodeVisionMarkerShape() let width: CGFloat = emphasized ? 3 : 2 - let borderColor = spotlight ? NodeScopeStyle.activity : nodeNameColor + let borderColor = spotlight ? NodeScopeStyle.activity : overlayInk let backing = colorScheme == .dark ? NodeScopeStyle.deepNavy : Color(uiColor: .systemBackground) return overlaySurface(shape, drawsBorder: false) .overlay { shape.stroke(backing, lineWidth: width + 2) } diff --git a/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt b/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt index 179e465..b49446d 100644 --- a/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt +++ b/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt @@ -277,6 +277,7 @@ internal fun NodeVisionScreen( with(density) { visionMarkerShape(10.dp.toPx(), 9.dp.toPx(), 8.dp.toPx()) } } val blue = MaterialTheme.colorScheme.primary + val nodeNameColor = if (lightOverlay) blue else lerp(blue, onSurface, 0.55f) val typography = MaterialTheme.typography fun markerNameStyle(tier: Int) = if (tier == 0) typography.titleSmall else typography.labelMedium val markerInk = if (lightOverlay) lerp(blue, onSurface, 0.25f) else blue @@ -412,7 +413,7 @@ internal fun NodeVisionScreen( horizontalAlignment = Alignment.CenterHorizontally) { Text(marker.node.displayName, fontFamily = MonaspaceNeon, style = markerNameStyle(marker.tier), - color = blue, maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center) + color = nodeNameColor, maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center) Text(stringResource(R.string.nodevision_distance_away, formatDistance(marker.distance / 1000, distanceUnit)), style = MaterialTheme.typography.labelSmall, fontFamily = MonaspaceNeon, textAlign = TextAlign.Center) @@ -474,7 +475,7 @@ internal fun NodeVisionScreen( .padding(bottom = 9.dp).padding(horizontal = 6.dp, vertical = 4.dp), horizontalAlignment = Alignment.CenterHorizontally) { Text(visionName, style = markerNameStyle(markerTier), fontFamily = MonaspaceNeon, - color = MaterialTheme.colorScheme.primary, maxLines = 2, + color = nodeNameColor, maxLines = 2, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center, onTextLayout = { truncatedName = it.hasVisualOverflow }) geometry?.let { Text(stringResource(R.string.nodevision_distance_away, formatDistance(it.distanceMeters / 1000, distanceUnit)), style = MaterialTheme.typography.labelSmall, fontFamily = MonaspaceNeon) } @@ -585,7 +586,7 @@ internal fun NodeVisionScreen( ) { Column(Modifier.background(overlayTint).padding(horizontal = 14.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(4.dp), horizontalAlignment = Alignment.CenterHorizontally) { if (!markerVisible || truncatedName) { - Text(visionName, style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary, textAlign = TextAlign.Center) + Text(visionName, style = MaterialTheme.typography.titleSmall, color = nodeNameColor, textAlign = TextAlign.Center) } if (!markerVisible) geometry?.let { Text(stringResource(R.string.nodevision_distance_away, formatDistance(it.distanceMeters / 1000, distanceUnit)), @@ -637,7 +638,7 @@ internal fun NodeVisionScreen( .verticalScroll(rememberScrollState()).padding(horizontal = 12.dp, vertical = 8.dp)) { Row(verticalAlignment = Alignment.CenterVertically) { Text(inspectedNode.displayName, Modifier.weight(1f).clickable { expandsInspection = !expandsInspection }, - style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary) + style = MaterialTheme.typography.titleSmall, color = nodeNameColor) IconButton(onClick = { expandsInspection = !expandsInspection }) { Icon(if (expandsInspection) Icons.Default.ExpandMore else Icons.Default.ExpandLess, stringResource(if (expandsInspection) R.string.nodevision_collapse_details else R.string.nodevision_expand_details)) From cf4d9940c16b78dc2701219642c0b22f461b220c Mon Sep 17 00:00:00 2001 From: Adam <196335+anieto@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:02:28 -0600 Subject: [PATCH 10/18] Record NodeVision absolute altitude follow-up --- ROADMAP.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/ROADMAP.md b/ROADMAP.md index cf326de..efccce8 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -473,6 +473,13 @@ Estimated Coverage shipped through 0.11.0. It includes: ## After 1.0 +- Evaluate Core Motion absolute altitude in NodeVision on supported iPhones. + First, log `CMAbsoluteAltitudeData` altitude and uncertainty alongside Core + Location readings in DEBUG. Compare stationary jitter, the response to a + known stair climb, and time spent in direction-only mode. Verify the altitude + reference matches the terrain data before using the Core Motion reading for + placement. Keep Core Location and the existing direction-only fallback for + unavailable, stale, or uncertain readings. - Expand packet details with raw hex, decoded fields, propagation timing, and a clearer per-observer observation timeline. - Add grouped and observation-level packet views where they improve diagnosis. From 4fe42d061d34f0bae81a8f6b163c5369b8ee876c Mon Sep 17 00:00:00 2001 From: Adam <196335+anieto@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:41:09 -0600 Subject: [PATCH 11/18] Preview marker borders in About NodeVision --- .../NodeVision/NodeVisionScreen.swift | 27 +++++++++++++++++++ .../Resources/Localizable.xcstrings | 16 +++++++++++ .../feature/nodevision/NodeVisionScreen.kt | 20 ++++++++++++++ .../app/src/main/res/values-es/strings.xml | 1 + .../src/main/res/values-pt-rBR/strings.xml | 1 + android/app/src/main/res/values/strings.xml | 1 + 6 files changed, 66 insertions(+) diff --git a/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift b/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift index cb21cbe..40ab8e5 100644 --- a/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift +++ b/CoreScopeViewer/Features/NodeVision/NodeVisionScreen.swift @@ -130,6 +130,7 @@ struct NodeVisionScreen: View { Text("Tap a marker to preview a node. Choose Spotlight node to highlight it as you pan. Choosing a node from Nearby spotlights it immediately. Edge arrows show which way to turn or tilt when the highlighted node is outside the camera view.") Text("When your phone’s altitude is missing or too uncertain, markers show which way to turn. Their height on screen doesn’t indicate whether a node is above or below you.") Text("When the phone’s altitude is accurate enough, NodeVision places markers by estimated antenna elevation. Without a reported height, it assumes a typical rooftop or handheld height. A dashed outline marks an approximate placement based on a default height or a less precise phone altitude.") + markerStylePreview Divider() VStack(alignment: .leading, spacing: 8) { Label("Location privacy", systemImage: "info.circle") @@ -875,6 +876,32 @@ struct NodeVisionScreen: View { .foregroundStyle(overlayInk) } + private var markerStylePreview: some View { + ViewThatFits(in: .horizontal) { + HStack(alignment: .top, spacing: 24) { + markerStyleExample("Higher-confidence elevation", approximate: false) + markerStyleExample("Approx. elevation", approximate: true) + } + .fixedSize(horizontal: true, vertical: false) + + VStack(alignment: .leading, spacing: 12) { + markerStyleExample("Higher-confidence elevation", approximate: false) + markerStyleExample("Approx. elevation", approximate: true) + } + } + } + + private func markerStyleExample(_ label: LocalizedStringKey, approximate: Bool) -> some View { + HStack(spacing: 10) { + markerSurface(approximate: approximate, emphasized: false) + .frame(width: 38, height: 28) + .accessibilityHidden(true) + Text(label) + .font(.caption) + .fixedSize(horizontal: false, vertical: true) + } + } + private func markerSurface(approximate: Bool, emphasized: Bool, spotlight: Bool = false) -> some View { let shape = NodeVisionMarkerShape() let width: CGFloat = emphasized ? 3 : 2 diff --git a/CoreScopeViewer/Resources/Localizable.xcstrings b/CoreScopeViewer/Resources/Localizable.xcstrings index a1e0721..02c01b8 100644 --- a/CoreScopeViewer/Resources/Localizable.xcstrings +++ b/CoreScopeViewer/Resources/Localizable.xcstrings @@ -13620,6 +13620,22 @@ } } }, + "Higher-confidence elevation" : { + "localizations" : { + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Elevación de mayor confianza" + } + }, + "pt-BR" : { + "stringUnit" : { + "state" : "translated", + "value" : "Elevação mais confiável" + } + } + } + }, "Highlights in version %@" : { "localizations" : { "es" : { diff --git a/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt b/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt index b49446d..115003a 100644 --- a/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt +++ b/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt @@ -778,6 +778,12 @@ internal fun NodeVisionScreen( Text(stringResource(R.string.nodevision_help_focus)) Text(stringResource(R.string.nodevision_help_phone_altitude)) Text(stringResource(R.string.nodevision_help_elevation)) + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + VisionMarkerStyleExample(R.string.nodevision_higher_confidence_elevation, + markerShape, markerInk, surface, overlayTint, approximate = false) + VisionMarkerStyleExample(R.string.nodevision_approx_elevation, + markerShape, markerInk, surface, overlayTint, approximate = true) + } HorizontalDivider() Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Row(horizontalArrangement = Arrangement.spacedBy(8.dp), @@ -1243,6 +1249,20 @@ internal fun discoveryMarkerY(projectedY: Double, paneHeight: Double, minimumY: return projectedY.coerceIn(minimumY, maximumY) } +@Composable +private fun VisionMarkerStyleExample( + label: Int, shape: Shape, ink: Color, backing: Color, tint: Brush, approximate: Boolean, +) { + Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) { + Surface(shape = shape, color = backing) { + Box(Modifier.size(width = 38.dp, height = 28.dp) + .background(tint) + .visionMarkerBorder(shape, ink, backing, approximate, emphasized = false)) + } + Text(stringResource(label), style = MaterialTheme.typography.bodySmall) + } +} + private fun Modifier.visionMarkerBorder( shape: Shape, ink: Color, backing: Color, approximate: Boolean, emphasized: Boolean, ): Modifier = drawWithCache { diff --git a/android/app/src/main/res/values-es/strings.xml b/android/app/src/main/res/values-es/strings.xml index d580711..cb6f2d6 100644 --- a/android/app/src/main/res/values-es/strings.xml +++ b/android/app/src/main/res/values-es/strings.xml @@ -1995,6 +1995,7 @@ Objetivo a la izquierda Objetivo a la derecha Abrir ajustes + Elevación de mayor confianza Elevación aprox. Acerca de NodeVision Privacidad de la ubicación diff --git a/android/app/src/main/res/values-pt-rBR/strings.xml b/android/app/src/main/res/values-pt-rBR/strings.xml index e2e7790..df4d690 100644 --- a/android/app/src/main/res/values-pt-rBR/strings.xml +++ b/android/app/src/main/res/values-pt-rBR/strings.xml @@ -1995,6 +1995,7 @@ Alvo à esquerda Alvo à direita Abrir ajustes + Elevação mais confiável Elevação aprox. Sobre o NodeVision Privacidade da localização diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 80b54f9..e1ba3e7 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -1981,6 +1981,7 @@ Target to the left Target to the right Open Settings + Higher-confidence elevation Approx. elevation About NodeVision Location privacy From e7b7b2ce3b778e1c513daadba57d0a824fb5b10a Mon Sep 17 00:00:00 2001 From: Adam <196335+anieto@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:58:03 -0600 Subject: [PATCH 12/18] Reopen Android Spotlight preview from its marker --- .../android/feature/nodevision/NodeVisionScreen.kt | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt b/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt index 115003a..96ce9cf 100644 --- a/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt +++ b/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt @@ -5,6 +5,7 @@ import androidx.compose.animation.core.MutableTransitionState import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut +import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.heading import androidx.compose.ui.semantics.semantics import androidx.compose.ui.layout.onGloballyPositioned @@ -465,8 +466,14 @@ internal fun NodeVisionScreen( // The bottom of the tip stays on the bearing band when the label wraps. Box(Modifier.offset(x = maxWidth / 2 + pixel.dp - markerWidth / 2, y = markerY - 88.dp) .width(markerWidth).height(88.dp), contentAlignment = Alignment.BottomCenter) { + val reopenPreview = if (focusedNode != null && inspectedKey != focusedNode.publicKey) { + Modifier.clickable(role = Role.Button) { + inspectedKey = focusedNode.publicKey + expandsInspection = true + } + } else Modifier Surface( - modifier = Modifier.fillMaxWidth(), + modifier = Modifier.fillMaxWidth().then(reopenPreview), color = surface.copy(alpha = 0.98f), shape = markerShape, shadowElevation = 4.dp, ) { From f6c0ff492b4012b87a85fcb49ae929c41780a343 Mon Sep 17 00:00:00 2001 From: Adam <196335+anieto@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:01:22 -0600 Subject: [PATCH 13/18] Explain the map-free Android Link Profile fallback --- .../android/feature/linkprofile/LinkProfileScreen.kt | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/android/app/src/main/java/org/nodescope/android/feature/linkprofile/LinkProfileScreen.kt b/android/app/src/main/java/org/nodescope/android/feature/linkprofile/LinkProfileScreen.kt index 3776cec..cfd024d 100644 --- a/android/app/src/main/java/org/nodescope/android/feature/linkprofile/LinkProfileScreen.kt +++ b/android/app/src/main/java/org/nodescope/android/feature/linkprofile/LinkProfileScreen.kt @@ -156,7 +156,12 @@ fun LinkProfileScreen(model: LinkProfileViewModel, distanceUnit: DistanceUnit = // Side and lower panels: the header stays put while everything under it scrolls. val panel: @Composable (Modifier) -> Unit = { modifier -> Column(modifier.meshPageBackground()) { - Box(Modifier.padding(16.dp)) { header() } + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + if (!BuildConfig.MAPS_CONFIGURED) { + Text(stringResource(R.string.map_unavailable), style = MaterialTheme.typography.bodySmall) + } + header() + } Column(Modifier.weight(1f).verticalScroll(scroll).padding(horizontal = 16.dp).padding(bottom = 16.dp)) { details() } } } From 69c4d6a3c358b54b6557a7a5e6566cb07043dfb0 Mon Sep 17 00:00:00 2001 From: Adam <196335+anieto@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:26:53 -0600 Subject: [PATCH 14/18] Remove the Google Maps beta label --- android/app/build.gradle.kts | 4 ++-- android/app/src/main/AndroidManifest.xml | 2 +- .../java/org/nodescope/android/feature/map/GoogleMapEngine.kt | 2 +- .../java/org/nodescope/android/feature/map/MapProvider.kt | 2 +- .../main/java/org/nodescope/android/feature/map/MapScreen.kt | 2 +- android/app/src/main/res/values-es/strings.xml | 2 +- android/app/src/main/res/values-pt-rBR/strings.xml | 2 +- android/app/src/main/res/values/strings.xml | 2 +- 8 files changed, 9 insertions(+), 9 deletions(-) diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index a7340b4..5eb01fb 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -12,7 +12,7 @@ val localProperties = Properties().apply { } val cartoKey = providers.environmentVariable("CARTO_API_KEY") .orElse(localProperties.getProperty("CARTO_API_KEY", "")).get() -/** Optional Google Maps (beta) provider; without a key only CARTO is offered. */ +/** Optional Google Maps provider; without a key only CARTO is offered. */ val googleMapsKey = providers.environmentVariable("GOOGLE_MAPS_API_KEY") .orElse(localProperties.getProperty("GOOGLE_MAPS_API_KEY", "")).get() /** Release signing comes only from the git-ignored local.properties; without it, release builds are unsigned. */ @@ -160,7 +160,7 @@ dependencies { implementation("com.squareup.okhttp3:okhttp:4.12.0") // OpenGL supports the full API 26+ device range, including non-Vulkan GPUs. implementation("org.maplibre.gl:android-sdk-opengl:13.6.1") - // Google Maps (beta): the native SDK with ordinary markers and no map ID (the free Maps SDK SKU). + // Google Maps: the native SDK with ordinary markers and no map ID (the free Maps SDK SKU). implementation("com.google.android.gms:play-services-maps:20.0.0") implementation("com.google.maps.android:android-maps-utils:4.0.0") // QR encoding for MeshCore contact codes (iOS uses Core Image's built-in generator). diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index c1c4b65..db43c03 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -7,7 +7,7 @@ - + diff --git a/android/app/src/main/java/org/nodescope/android/feature/map/GoogleMapEngine.kt b/android/app/src/main/java/org/nodescope/android/feature/map/GoogleMapEngine.kt index 91e6c48..3d08637 100644 --- a/android/app/src/main/java/org/nodescope/android/feature/map/GoogleMapEngine.kt +++ b/android/app/src/main/java/org/nodescope/android/feature/map/GoogleMapEngine.kt @@ -42,7 +42,7 @@ import kotlin.coroutines.resume import kotlin.math.hypot /* - * Google Maps (beta), the native Maps SDK: ordinary markers and no map ID, so map loads stay in + * Google Maps, the native Maps SDK: ordinary markers and no map ID, so map loads stay in * the free Maps SDK SKU. A map ID, cloud styling or advanced markers would bill as Dynamic Maps. */ diff --git a/android/app/src/main/java/org/nodescope/android/feature/map/MapProvider.kt b/android/app/src/main/java/org/nodescope/android/feature/map/MapProvider.kt index 209ea66..ae31a26 100644 --- a/android/app/src/main/java/org/nodescope/android/feature/map/MapProvider.kt +++ b/android/app/src/main/java/org/nodescope/android/feature/map/MapProvider.kt @@ -4,7 +4,7 @@ import android.content.Context import androidx.core.content.edit import org.nodescope.android.BuildConfig -/** Who draws the map: CARTO (the default) or, when the build has a key, Google Maps (beta). */ +/** Who draws the map: CARTO (the default) or, when the build has a key, Google Maps. */ enum class MapProvider { CARTO, GOOGLE } /** diff --git a/android/app/src/main/java/org/nodescope/android/feature/map/MapScreen.kt b/android/app/src/main/java/org/nodescope/android/feature/map/MapScreen.kt index 79b309e..7dd1992 100644 --- a/android/app/src/main/java/org/nodescope/android/feature/map/MapScreen.kt +++ b/android/app/src/main/java/org/nodescope/android/feature/map/MapScreen.kt @@ -80,7 +80,7 @@ fun MapScreen(snapshot: AnalyzerSnapshot?, focusedKey: String? = null, onNode: ( var search by remember { mutableStateOf(false) } var layersOpen by remember { mutableStateOf(false) } val context = LocalContext.current - // CARTO, or Google Maps (beta) when this build has a key; remembered across launches. + // CARTO, or Google Maps when this build has a key; remembered across launches. var providerChoice by remember { mutableStateOf(loadMapProvider(context)) } fun choose(choice: MapProviderChoice) { providerChoice = choice; saveMapProvider(context, choice) } // A picked CARTO style sticks; until then it follows the app theme. diff --git a/android/app/src/main/res/values-es/strings.xml b/android/app/src/main/res/values-es/strings.xml index cb6f2d6..4c80c7c 100644 --- a/android/app/src/main/res/values-es/strings.xml +++ b/android/app/src/main/res/values-es/strings.xml @@ -29,7 +29,7 @@ Aún puedes explorar nodos en Explorar y elegir tu analizador en Ajustes. Estándar CARTO - Google Maps · Beta + Google Maps Mapa Satélite Terreno diff --git a/android/app/src/main/res/values-pt-rBR/strings.xml b/android/app/src/main/res/values-pt-rBR/strings.xml index df4d690..1dea736 100644 --- a/android/app/src/main/res/values-pt-rBR/strings.xml +++ b/android/app/src/main/res/values-pt-rBR/strings.xml @@ -29,7 +29,7 @@ Você ainda pode explorar nós em Explorar e escolher seu analisador em Ajustes. Padrão CARTO - Google Maps · Beta + Google Maps Mapa Satélite Terreno diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index e1ba3e7..c09ada0 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -29,7 +29,7 @@ You can still browse nodes in Explore and choose your analyzer in Settings. Standard CARTO - Google Maps · Beta + Google Maps Map Satellite Terrain From 0a2b20932c7cd73eec29987cfe1546047a1660a6 Mon Sep 17 00:00:00 2001 From: Adam <196335+anieto@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:37:20 -0600 Subject: [PATCH 15/18] Default to Google Maps on supported Android devices --- .../android/feature/map/MapProvider.kt | 19 ++++++++++++++----- .../android/feature/map/MapScreen.kt | 4 ++-- .../org/nodescope/android/MapEngineTest.kt | 13 +++++++++---- 3 files changed, 25 insertions(+), 11 deletions(-) diff --git a/android/app/src/main/java/org/nodescope/android/feature/map/MapProvider.kt b/android/app/src/main/java/org/nodescope/android/feature/map/MapProvider.kt index ae31a26..9a6b484 100644 --- a/android/app/src/main/java/org/nodescope/android/feature/map/MapProvider.kt +++ b/android/app/src/main/java/org/nodescope/android/feature/map/MapProvider.kt @@ -2,9 +2,11 @@ package org.nodescope.android.feature.map import android.content.Context import androidx.core.content.edit +import com.google.android.gms.common.ConnectionResult +import com.google.android.gms.common.GoogleApiAvailability import org.nodescope.android.BuildConfig -/** Who draws the map: CARTO (the default) or, when the build has a key, Google Maps. */ +/** The supported Android map providers. */ enum class MapProvider { CARTO, GOOGLE } /** @@ -17,15 +19,22 @@ data class MapProviderChoice(val provider: MapProvider = MapProvider.CARTO, val fun cartoStyle(darkTheme: Boolean) = cartoStyle ?: if (darkTheme) 2 else 0 } -/** A saved Google choice falls back to CARTO in a build without a Google key. */ -internal fun MapProviderChoice.available(googleConfigured: Boolean) = if (googleConfigured) this else copy(provider = MapProvider.CARTO) +internal fun googleMapsAvailable(context: Context): Boolean = + BuildConfig.GOOGLE_MAPS_CONFIGURED && + GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS + +/** A fallback changes the active provider while leaving the saved preference intact. */ +internal fun resolveMapProvider(saved: MapProvider?, googleAvailable: Boolean): MapProvider = + if (googleAvailable) saved ?: MapProvider.GOOGLE else MapProvider.CARTO fun loadMapProvider(context: Context): MapProviderChoice { val prefs = context.getSharedPreferences("map-provider", Context.MODE_PRIVATE) - val provider = MapProvider.entries.firstOrNull { it.name == prefs.getString("provider", null) } ?: MapProvider.CARTO + val savedProvider = prefs.getString("provider", null) + val provider = resolveMapProvider(MapProvider.entries.firstOrNull { it.name == savedProvider }, + googleMapsAvailable(context)) val type = GoogleMapType.entries.firstOrNull { it.name == prefs.getString("googleType", null) } ?: GoogleMapType.MAP val style = prefs.getInt("cartoStyle", -1).takeIf { it in 0..2 } - return MapProviderChoice(provider, type, style).available(BuildConfig.GOOGLE_MAPS_CONFIGURED) + return MapProviderChoice(provider, type, style) } fun saveMapProvider(context: Context, choice: MapProviderChoice) { diff --git a/android/app/src/main/java/org/nodescope/android/feature/map/MapScreen.kt b/android/app/src/main/java/org/nodescope/android/feature/map/MapScreen.kt index 7dd1992..a65d151 100644 --- a/android/app/src/main/java/org/nodescope/android/feature/map/MapScreen.kt +++ b/android/app/src/main/java/org/nodescope/android/feature/map/MapScreen.kt @@ -80,7 +80,7 @@ fun MapScreen(snapshot: AnalyzerSnapshot?, focusedKey: String? = null, onNode: ( var search by remember { mutableStateOf(false) } var layersOpen by remember { mutableStateOf(false) } val context = LocalContext.current - // CARTO, or Google Maps when this build has a key; remembered across launches. + // Google Maps when supported, with the user’s map selection remembered across launches. var providerChoice by remember { mutableStateOf(loadMapProvider(context)) } fun choose(choice: MapProviderChoice) { providerChoice = choice; saveMapProvider(context, choice) } // A picked CARTO style sticks; until then it follows the app theme. @@ -840,7 +840,7 @@ internal fun MapLayersMenu(expanded: Boolean, onDismiss: () -> Unit, choice: Map onChoose: (MapProviderChoice) -> Unit) { val mode = choice.cartoStyle(darkTheme) DropdownMenu(expanded, onDismiss) { - val google = BuildConfig.GOOGLE_MAPS_CONFIGURED + val google = googleMapsAvailable(LocalContext.current) // Grouped by provider when there is more than one. if (google) MenuSectionHeader(stringResource(R.string.map_provider_carto)) listOf(R.string.standard, R.string.light, R.string.dark).forEachIndexed { index, label -> diff --git a/android/app/src/test/java/org/nodescope/android/MapEngineTest.kt b/android/app/src/test/java/org/nodescope/android/MapEngineTest.kt index 14850fb..db9a7e7 100644 --- a/android/app/src/test/java/org/nodescope/android/MapEngineTest.kt +++ b/android/app/src/test/java/org/nodescope/android/MapEngineTest.kt @@ -56,10 +56,15 @@ class MapEngineTest { assertEquals(21.0, fitCamera(CameraTarget.Bounds(30.0, -97.0, 30.0, -97.0), 500, 500, FramingInsets(0, 0, 0, 0), density).zoom, 1e-9) } - @Test fun savedGoogleChoiceFallsBackToCartoWithoutAKey() { - val google = MapProviderChoice(MapProvider.GOOGLE, GoogleMapType.SATELLITE) - assertEquals(MapProvider.CARTO, google.available(false).provider) - assertEquals(google, google.available(true)) + @Test fun googleIsTheDefaultWhenAvailable() { + assertEquals(MapProvider.GOOGLE, resolveMapProvider(null, googleAvailable = true)) + assertEquals(MapProvider.CARTO, resolveMapProvider(null, googleAvailable = false)) + } + + @Test fun savedProviderIsHonoredWhenAvailable() { + assertEquals(MapProvider.CARTO, resolveMapProvider(MapProvider.CARTO, googleAvailable = true)) + assertEquals(MapProvider.GOOGLE, resolveMapProvider(MapProvider.GOOGLE, googleAvailable = true)) + assertEquals(MapProvider.CARTO, resolveMapProvider(MapProvider.GOOGLE, googleAvailable = false)) } @Test fun mapLoadErrorsSayWhyTheMapFailed() { From ad6a989b80dd116511892967736debd773884abc Mon Sep 17 00:00:00 2001 From: Adam <196335+anieto@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:22:09 -0600 Subject: [PATCH 16/18] Reopen Android Spotlight preview from the compact card --- .../feature/nodevision/NodeVisionScreen.kt | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt b/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt index 96ce9cf..7ed061a 100644 --- a/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt +++ b/android/app/src/main/java/org/nodescope/android/feature/nodevision/NodeVisionScreen.kt @@ -163,6 +163,12 @@ internal fun NodeVisionScreen( } val inspectedNode = catalog.firstOrNull { it.publicKey == inspectedKey } val focusedNode = catalog.firstOrNull { it.publicKey == focusedKey } + val reopenPreview = if (focusedNode != null && inspectedKey != focusedNode.publicKey) { + Modifier.clickable(role = Role.Button, onClickLabel = stringResource(R.string.nodevision_expand_details)) { + inspectedKey = focusedNode.publicKey + expandsInspection = true + } + } else Modifier val visionTarget = focusedNode?.visionCoordinate() ?: target val visionName = focusedNode?.displayName ?: name.orEmpty() val reportedHeight = focusedNode?.let { repeaterMetadata[it.publicKey.lowercase()]?.applicableHeightMeters() } ?: antennaHeight @@ -466,12 +472,6 @@ internal fun NodeVisionScreen( // The bottom of the tip stays on the bearing band when the label wraps. Box(Modifier.offset(x = maxWidth / 2 + pixel.dp - markerWidth / 2, y = markerY - 88.dp) .width(markerWidth).height(88.dp), contentAlignment = Alignment.BottomCenter) { - val reopenPreview = if (focusedNode != null && inspectedKey != focusedNode.publicKey) { - Modifier.clickable(role = Role.Button) { - inspectedKey = focusedNode.publicKey - expandsInspection = true - } - } else Modifier Surface( modifier = Modifier.fillMaxWidth().then(reopenPreview), color = surface.copy(alpha = 0.98f), shape = markerShape, @@ -586,7 +586,8 @@ internal fun NodeVisionScreen( targetCardTop = with(density) { coordinates.positionInParent().y.toDp() } } .windowInsetsPadding(WindowInsets.safeDrawing.only(WindowInsetsSides.Bottom + WindowInsetsSides.Horizontal)) - .padding(horizontal = 16.dp).padding(bottom = if (discovery) 66.dp else 8.dp).widthIn(max = 340.dp), + .padding(horizontal = 16.dp).padding(bottom = if (discovery) 66.dp else 8.dp).widthIn(max = 340.dp) + .then(reopenPreview), color = surface.copy(alpha = 0.97f), shape = MaterialTheme.shapes.medium, border = overlayBorder, shadowElevation = 4.dp, From 3c0d5dfb1ca2cef02683d7c48bdb7e0467bf2614 Mon Sep 17 00:00:00 2001 From: Adam <196335+anieto@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:16:17 -0600 Subject: [PATCH 17/18] Update Android UI test call sites for current APIs --- .../java/org/nodescope/android/ConsistencyUiTest.kt | 2 +- .../java/org/nodescope/android/FoundationUiTest.kt | 4 ++-- .../java/org/nodescope/android/LinkProfileUiTest.kt | 11 +++++++---- .../java/org/nodescope/android/MapControlsUiTest.kt | 4 ++-- 4 files changed, 12 insertions(+), 9 deletions(-) diff --git a/android/app/src/androidTest/java/org/nodescope/android/ConsistencyUiTest.kt b/android/app/src/androidTest/java/org/nodescope/android/ConsistencyUiTest.kt index f2214f4..7a4da06 100644 --- a/android/app/src/androidTest/java/org/nodescope/android/ConsistencyUiTest.kt +++ b/android/app/src/androidTest/java/org/nodescope/android/ConsistencyUiTest.kt @@ -49,7 +49,7 @@ class ConsistencyUiTest { @Test fun pausedSettingsUsesAccurateStatusAndConsistentHeadings() { compose.setContent { NodeScopeTheme(Appearance.DARK) { Surface(Modifier.fillMaxSize().systemBarsPadding()) { - SettingsScreen(AppPreferences(), LiveConnection.PAUSED, null, null, {}, {}, {}, {}, {}, {}) + SettingsScreen(AppPreferences(), LiveConnection.PAUSED, null, null, {}, {}, {}, {}, {}, {}, onMapLab = {}) } } } compose.onNodeWithText("Appearance").assertIsDisplayed() diff --git a/android/app/src/androidTest/java/org/nodescope/android/FoundationUiTest.kt b/android/app/src/androidTest/java/org/nodescope/android/FoundationUiTest.kt index 206d15c..3abc19a 100644 --- a/android/app/src/androidTest/java/org/nodescope/android/FoundationUiTest.kt +++ b/android/app/src/androidTest/java/org/nodescope/android/FoundationUiTest.kt @@ -221,7 +221,7 @@ class FoundationUiTest { var preferences by remember { mutableStateOf(AppPreferences()) } NodeScopeTheme(preferences.appearance) { SettingsScreen(preferences, LiveConnection.LIVE, null, null, { selected = it; preferences = preferences.copy(appearance = it) }, - {}, {}, {}, {}, {}) + {}, {}, {}, {}, {}, onMapLab = {}) } } compose.onNodeWithText("Dark").performClick().assertIsSelected() @@ -234,7 +234,7 @@ class FoundationUiTest { MeshNode("one", "North", "repeater", lastSeen = "2026-01-01T00:00:00Z"), MeshNode("two", "South", "sensor", lastSeen = "2026-01-01T00:00:00Z"), ) - compose.setContent { NodeScopeTheme(Appearance.SYSTEM) { NodeBrowser(nodes, 2, { selected = it }) } } + compose.setContent { NodeScopeTheme(Appearance.SYSTEM) { NodeBrowser(nodes, 2, onNode = { selected = it }) } } compose.onNodeWithText("Search name, public key, or role").performTextInput("SENSOR") compose.onNodeWithText("North").assertDoesNotExist() compose.onNodeWithText("South").performClick() diff --git a/android/app/src/androidTest/java/org/nodescope/android/LinkProfileUiTest.kt b/android/app/src/androidTest/java/org/nodescope/android/LinkProfileUiTest.kt index 2753399..c7e7936 100644 --- a/android/app/src/androidTest/java/org/nodescope/android/LinkProfileUiTest.kt +++ b/android/app/src/androidTest/java/org/nodescope/android/LinkProfileUiTest.kt @@ -101,18 +101,21 @@ class LinkProfileUiTest { @Test fun settingsUnitIsUsedWhenOpeningPlanner() { val preferences = mutableStateOf(org.nodescope.android.core.storage.AppPreferences( - onboarded = true, destination = "SETTINGS", distanceUnit = DistanceUnit.METRIC)) + onboarded = true, destination = "SETTINGS", storedDistanceUnit = DistanceUnit.METRIC)) compose.setContent { - CompositionLocalProvider(LocalDensity provides Density(3f, 1f)) { + CompositionLocalProvider( + LocalDensity provides Density(3f, 1f), + LocalDistanceUnit provides preferences.value.distanceUnit, + ) { NodeScopeTheme(Appearance.LIGHT) { org.nodescope.android.app.AppShell(preferences.value, org.nodescope.android.core.network.SessionState(), {}, {}, {}, {}, {}, nodeLibrary = org.nodescope.android.core.storage.NodeLibrary(), - onDistanceUnit = { preferences.value = preferences.value.copy(distanceUnit = it) }) + onDistanceUnit = { preferences.value = preferences.value.copy(storedDistanceUnit = it) }) } } } - compose.onNodeWithText("Imperial (mi)").performScrollTo().performClick() + compose.onNodeWithText("US (mi, ft)").performScrollTo().performClick() compose.runOnIdle { assertEquals(DistanceUnit.IMPERIAL, preferences.value.distanceUnit) } compose.onNodeWithText("Explore").performClick() compose.onNodeWithText("Node Planner").performScrollTo().performClick() diff --git a/android/app/src/androidTest/java/org/nodescope/android/MapControlsUiTest.kt b/android/app/src/androidTest/java/org/nodescope/android/MapControlsUiTest.kt index aef55d0..160b042 100644 --- a/android/app/src/androidTest/java/org/nodescope/android/MapControlsUiTest.kt +++ b/android/app/src/androidTest/java/org/nodescope/android/MapControlsUiTest.kt @@ -16,7 +16,7 @@ import org.junit.Test import org.nodescope.android.core.design.NodeScopeTheme import org.nodescope.android.core.model.MeshNode import org.nodescope.android.core.storage.Appearance -import org.nodescope.android.feature.map.MapNodeSelectionSheet +import org.nodescope.android.feature.map.MapNodePreview import org.nodescope.android.feature.map.ReplayControls import org.nodescope.android.feature.map.ReplayRoute import java.io.File @@ -28,7 +28,7 @@ class MapControlsUiTest { var opened = false var visible by mutableStateOf(true) compose.setContent { NodeScopeTheme(Appearance.LIGHT) { - if (visible) MapNodeSelectionSheet( + if (visible) MapNodePreview( MeshNode("test-node", "A long repeater name in the neighborhood", "repeater", lastSeen = "2026-09-26T12:00:00Z"), onDetails = { opened = true; visible = false }, onDismiss = { visible = false }) } } From f6e4d50ba174f0ed67922b74b83dc2e4ae528cd9 Mon Sep 17 00:00:00 2001 From: Adam <196335+anieto@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:17:29 -0600 Subject: [PATCH 18/18] Use min-SDK-safe Android APIs for units and contact links --- .../java/org/nodescope/android/core/model/FieldContracts.kt | 2 +- .../java/org/nodescope/android/core/storage/Preferences.kt | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/android/app/src/main/java/org/nodescope/android/core/model/FieldContracts.kt b/android/app/src/main/java/org/nodescope/android/core/model/FieldContracts.kt index b72a024..fbd657e 100644 --- a/android/app/src/main/java/org/nodescope/android/core/model/FieldContracts.kt +++ b/android/app/src/main/java/org/nodescope/android/core/model/FieldContracts.kt @@ -88,7 +88,7 @@ sealed interface FieldQrCode { } private fun decode(value: String): String? = runCatching { - URLDecoder.decode(value, Charsets.UTF_8) + URLDecoder.decode(value, Charsets.UTF_8.name()) }.getOrNull() private fun publicKey(value: String): String? = value.lowercase().takeIf { key -> diff --git a/android/app/src/main/java/org/nodescope/android/core/storage/Preferences.kt b/android/app/src/main/java/org/nodescope/android/core/storage/Preferences.kt index 6bf0516..0ca41bb 100644 --- a/android/app/src/main/java/org/nodescope/android/core/storage/Preferences.kt +++ b/android/app/src/main/java/org/nodescope/android/core/storage/Preferences.kt @@ -23,14 +23,14 @@ enum class DistanceUnit { companion object { fun defaultUnit(locale: Locale = Locale.getDefault()): DistanceUnit { - if (Build.VERSION.SDK_INT >= 24) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { return when (LocaleData.getMeasurementSystem(ULocale.forLocale(locale))) { LocaleData.MeasurementSystem.US -> IMPERIAL LocaleData.MeasurementSystem.UK -> UK else -> METRIC } } - // The host JVM has no Android ICU. Keep region mapping available to local unit tests. + // Older Android versions and the host JVM use the region mapping. return when (locale.country) { "US", "LR" -> IMPERIAL "GB", "MM" -> UK