From 67f1eb21c8f9cbe9a388dc4492eb4c7acc67a166 Mon Sep 17 00:00:00 2001 From: Travis Curtsinger <93950613+tcurtsinger@users.noreply.github.com> Date: Mon, 28 Sep 2026 13:41:50 -0500 Subject: [PATCH 1/8] Locate every radar site and decide the source from zoom and position The site catalog now carries latitude and longitude for all 155 sites: 150 from nexrad-model's registry (a Rust test keeps them in sync) and 5 the registry lacks (KBHX, KDOX, KHDC, KLGX, PAPD) from api.weather.gov. decideAutoSource is the pure Phase B policy: a covering Site replaces National at zoom 9 (center within 200 km), a displayed Site is kept down to zoom 8.5 and within 230 km, the likely Site preloads from zoom 8, and moving between Sites always passes through National. A picked Site is preferred while the view stays inside its coverage. Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/acquisition.rs | 41 + src/data/radar-sites.json | 1567 ++++++++++++-------- src/data/radarSites.ts | 10 +- src/radar-session/autoSourcePolicy.test.ts | 62 + src/radar-session/autoSourcePolicy.ts | 82 + 5 files changed, 1133 insertions(+), 629 deletions(-) create mode 100644 src/radar-session/autoSourcePolicy.test.ts create mode 100644 src/radar-session/autoSourcePolicy.ts diff --git a/src-tauri/src/acquisition.rs b/src-tauri/src/acquisition.rs index 5fb8295..38200d6 100644 --- a/src-tauri/src/acquisition.rs +++ b/src-tauri/src/acquisition.rs @@ -798,6 +798,47 @@ fn retain_newest( mod tests { use super::*; + #[test] + fn radar_site_catalog_locations_match_the_nexrad_registry() { + #[derive(Deserialize)] + struct LocatedSite { + id: String, + latitude: f64, + longitude: f64, + } + #[derive(Deserialize)] + struct LocatedCatalog { + sites: Vec, + } + // Absent from nexrad-model's registry; sourced from api.weather.gov. + const NWS_SOURCED: [&str; 5] = ["KBHX", "KDOX", "KHDC", "KLGX", "PAPD"]; + let catalog: LocatedCatalog = serde_json::from_str(RADAR_SITE_CATALOG_JSON).unwrap(); + assert_eq!(catalog.sites.len(), 155); + for site in &catalog.sites { + assert!( + (-90.0..=90.0).contains(&site.latitude) + && (-180.0..=180.0).contains(&site.longitude), + "{} has an invalid location", + site.id + ); + match nexrad_model::meta::registry::site_by_id(&site.id) { + Some(entry) => { + assert!( + (f64::from(entry.latitude) - site.latitude).abs() < 1e-3 + && (f64::from(entry.longitude) - site.longitude).abs() < 1e-3, + "{} location drifted from the nexrad-model registry", + site.id + ); + } + None => assert!( + NWS_SOURCED.contains(&site.id.as_str()), + "{} has no registry location and no recorded source", + site.id + ), + } + } + } + const S3_XML: &str = r#" false diff --git a/src/data/radar-sites.json b/src/data/radar-sites.json index 7f68e02..e56fd38 100644 --- a/src/data/radar-sites.json +++ b/src/data/radar-sites.json @@ -1,629 +1,942 @@ { - "verifiedAt": "2026-08-02", - "sources": [ - "https://www.roc.noaa.gov/build-loaded.php", - "https://unidata-nexrad-level2-chunks.s3.amazonaws.com/?list-type=2\u0026delimiter=%2F\u0026max-keys=1000" - ], - "sites": [ - { - "id": "KABR", - "name": "Aberdeen, SD" - }, - { - "id": "KABX", - "name": "Albuquerque, NM" - }, - { - "id": "KAKQ", - "name": "Wakefield, VA" - }, - { - "id": "KAMA", - "name": "Amarillo, TX" - }, - { - "id": "KAMX", - "name": "Miami, FL" - }, - { - "id": "KAPX", - "name": "Gaylord/Alpena, MI" - }, - { - "id": "KARX", - "name": "La Crosse, WI" - }, - { - "id": "KATX", - "name": "Seattle, WA" - }, - { - "id": "KBBX", - "name": "Beale AFB, CA" - }, - { - "id": "KBGM", - "name": "Binghamton, NY" - }, - { - "id": "KBHX", - "name": "Eureka, CA" - }, - { - "id": "KBIS", - "name": "Bismarck, ND" - }, - { - "id": "KBLX", - "name": "Billings, MT" - }, - { - "id": "KBMX", - "name": "Birmingham, AL" - }, - { - "id": "KBOX", - "name": "Boston, MA" - }, - { - "id": "KBRO", - "name": "Brownsville, TX" - }, - { - "id": "KBUF", - "name": "Buffalo, NY" - }, - { - "id": "KBYX", - "name": "Key West, FL" - }, - { - "id": "KCAE", - "name": "Columbia, SC" - }, - { - "id": "KCBW", - "name": "Caribou, ME" - }, - { - "id": "KCBX", - "name": "Boise, ID" - }, - { - "id": "KCCX", - "name": "State College, PA" - }, - { - "id": "KCLE", - "name": "Cleveland, OH" - }, - { - "id": "KCLX", - "name": "Charleston, SC" - }, - { - "id": "KCRP", - "name": "Corpus Christi, TX" - }, - { - "id": "KCXX", - "name": "Burlington, VT" - }, - { - "id": "KCYS", - "name": "Cheyenne, WY" - }, - { - "id": "KDAX", - "name": "Sacramento, CA" - }, - { - "id": "KDDC", - "name": "Dodge City, KS" - }, - { - "id": "KDFX", - "name": "Laughlin AFB, TX" - }, - { - "id": "KDGX", - "name": "Jackson, MS" - }, - { - "id": "KDIX", - "name": "Philadelphia, PA" - }, - { - "id": "KDLH", - "name": "Duluth, MN" - }, - { - "id": "KDMX", - "name": "Des Moines, IA" - }, - { - "id": "KDOX", - "name": "Dover AFB, DE" - }, - { - "id": "KDTX", - "name": "Detroit, MI" - }, - { - "id": "KDVN", - "name": "Davenport, IA" - }, - { - "id": "KDYX", - "name": "Dyess AFB, TX" - }, - { - "id": "KEAX", - "name": "Kansas City, MO" - }, - { - "id": "KEMX", - "name": "Tucson, AZ" - }, - { - "id": "KENX", - "name": "Albany, NY" - }, - { - "id": "KEOX", - "name": "Ft Rucker (Novosel), AL" - }, - { - "id": "KEPZ", - "name": "El Paso, TX" - }, - { - "id": "KESX", - "name": "Las Vegas, NV" - }, - { - "id": "KEVX", - "name": "Eglin AFB, FL" - }, - { - "id": "KEWX", - "name": "San Antonio, TX" - }, - { - "id": "KEYX", - "name": "Edwards AFB, CA" - }, - { - "id": "KFCX", - "name": "Blacksburg, VA" - }, - { - "id": "KFDR", - "name": "Altus AFB, OK" - }, - { - "id": "KFDX", - "name": "Cannon AFB, NM" - }, - { - "id": "KFFC", - "name": "Atlanta, GA" - }, - { - "id": "KFSD", - "name": "Sioux Falls, SD" - }, - { - "id": "KFSX", - "name": "Flagstaff, AZ" - }, - { - "id": "KFTG", - "name": "Denver, CO" - }, - { - "id": "KFWS", - "name": "Ft Worth, TX" - }, - { - "id": "KGGW", - "name": "Glasgow, MT" - }, - { - "id": "KGJX", - "name": "Grand Junction, CO" - }, - { - "id": "KGLD", - "name": "Goodland, KS" - }, - { - "id": "KGRB", - "name": "Green Bay, WI" - }, - { - "id": "KGRK", - "name": "Ft Hood (Cavazos), TX" - }, - { - "id": "KGRR", - "name": "Grand Rapids, MI" - }, - { - "id": "KGSP", - "name": "Greer, SC" - }, - { - "id": "KGWX", - "name": "Columbus AFB, MS" - }, - { - "id": "KGYX", - "name": "Portland, ME" - }, - { - "id": "KHDC", - "name": "New Orleans/Hammond, LA" - }, - { - "id": "KHDX", - "name": "Holloman AFB, NM" - }, - { - "id": "KHGX", - "name": "Houston, TX" - }, - { - "id": "KHNX", - "name": "San Joaquin, CA" - }, - { - "id": "KHPX", - "name": "Ft Campbell, KY" - }, - { - "id": "KHTX", - "name": "Huntsville/Hytop, AL" - }, - { - "id": "KICT", - "name": "Wichita, KS" - }, - { - "id": "KICX", - "name": "Cedar City, UT" - }, - { - "id": "KILN", - "name": "Cincinnati, OH" - }, - { - "id": "KILX", - "name": "Lincoln, IL" - }, - { - "id": "KIND", - "name": "Indianapolis, IN" - }, - { - "id": "KINX", - "name": "Tulsa, OK" - }, - { - "id": "KIWA", - "name": "Phoenix, AZ" - }, - { - "id": "KIWX", - "name": "North Webster, IN" - }, - { - "id": "KJAX", - "name": "Jacksonville, FL" - }, - { - "id": "KJGX", - "name": "Robins AFB, GA" - }, - { - "id": "KJKL", - "name": "Jackson, KY" - }, - { - "id": "KLBB", - "name": "Lubbock, TX" - }, - { - "id": "KLCH", - "name": "Lake Charles, LA" - }, - { - "id": "KLGX", - "name": "Langley Hill, WA" - }, - { - "id": "KLNX", - "name": "North Platte, NE" - }, - { - "id": "KLOT", - "name": "Chicago, IL" - }, - { - "id": "KLRX", - "name": "Elko, NV" - }, - { - "id": "KLSX", - "name": "St Louis, MO" - }, - { - "id": "KLTX", - "name": "Wilmington, NC" - }, - { - "id": "KLVX", - "name": "Louisville, KY" - }, - { - "id": "KLWX", - "name": "Sterling VA (DC)" - }, - { - "id": "KLZK", - "name": "Little Rock, AR" - }, - { - "id": "KMAF", - "name": "Midland/Odessa, TX" - }, - { - "id": "KMAX", - "name": "Medford, OR" - }, - { - "id": "KMHX", - "name": "Morehead City, NC" - }, - { - "id": "KMKX", - "name": "Milwaukee, WI" - }, - { - "id": "KMLB", - "name": "Melbourne, FL" - }, - { - "id": "KMOB", - "name": "Mobile, AL" - }, - { - "id": "KMPX", - "name": "Minneapolis, MN" - }, - { - "id": "KMQT", - "name": "Marquette, MI" - }, - { - "id": "KMRX", - "name": "Morristown, TN" - }, - { - "id": "KMSX", - "name": "Missoula, MT" - }, - { - "id": "KMTX", - "name": "Salt Lake City, UT" - }, - { - "id": "KMUX", - "name": "San Francisco, CA" - }, - { - "id": "KMVX", - "name": "Grand Forks, ND" - }, - { - "id": "KMXX", - "name": "Maxwell AFB, AL" - }, - { - "id": "KNKX", - "name": "San Diego, CA" - }, - { - "id": "KNQA", - "name": "Memphis, TN" - }, - { - "id": "KOAX", - "name": "Omaha, NE" - }, - { - "id": "KOHX", - "name": "Nashville, TN" - }, - { - "id": "KOKX", - "name": "New York, NY" - }, - { - "id": "KOTX", - "name": "Spokane, WA" - }, - { - "id": "KPAH", - "name": "Paducah, KY" - }, - { - "id": "KPBZ", - "name": "Pittsburgh, PA" - }, - { - "id": "KPDT", - "name": "Pendleton, OR" - }, - { - "id": "KPOE", - "name": "Ft Polk (Johnson), LA" - }, - { - "id": "KPUX", - "name": "Pueblo, CO" - }, - { - "id": "KRAX", - "name": "Raleigh/Durham, NC" - }, - { - "id": "KRGX", - "name": "Reno, NV" - }, - { - "id": "KRIW", - "name": "Riverton, WY" - }, - { - "id": "KRLX", - "name": "Charleston, WV" - }, - { - "id": "KRTX", - "name": "Portland, OR" - }, - { - "id": "KSFX", - "name": "Pocatello, ID" - }, - { - "id": "KSGF", - "name": "Springfield, MO" - }, - { - "id": "KSHV", - "name": "Shreveport, LA" - }, - { - "id": "KSJT", - "name": "San Angelo, TX" - }, - { - "id": "KSOX", - "name": "Santa Ana Mtn., CA" - }, - { - "id": "KSRX", - "name": "Fort Smith, AR" - }, - { - "id": "KTBW", - "name": "Tampa Bay, FL" - }, - { - "id": "KTFX", - "name": "Great Falls, MT" - }, - { - "id": "KTLH", - "name": "Tallahassee, FL" - }, - { - "id": "KTLX", - "name": "Oklahoma City, OK" - }, - { - "id": "KTWX", - "name": "Topeka, KS" - }, - { - "id": "KTYX", - "name": "Ft Drum, NY" - }, - { - "id": "KUDX", - "name": "Rapid City, SD" - }, - { - "id": "KUEX", - "name": "Hastings, NE" - }, - { - "id": "KVAX", - "name": "Moody AFB, GA" - }, - { - "id": "KVBX", - "name": "Vandenberg SFB, CA" - }, - { - "id": "KVNX", - "name": "Vance AFB, OK" - }, - { - "id": "KVTX", - "name": "Los Angeles, CA" - }, - { - "id": "KVWX", - "name": "Evansville, IN" - }, - { - "id": "KYUX", - "name": "Yuma/Phoenix, AZ" - }, - { - "id": "PABC", - "name": "Bethel, AK" - }, - { - "id": "PACG", - "name": "Sitka, AK" - }, - { - "id": "PAEC", - "name": "Nome, AK" - }, - { - "id": "PAHG", - "name": "Anchorage/Kenai, AK" - }, - { - "id": "PAIH", - "name": "Middleton Island, AK" - }, - { - "id": "PAKC", - "name": "King Salmon, AK" - }, - { - "id": "PAPD", - "name": "Fairbanks, AK" - }, - { - "id": "PGUA", - "name": "Andersen AFB, Guam" - }, - { - "id": "PHKI", - "name": "South Kauai, HI" - }, - { - "id": "PHKM", - "name": "Kamuela, HI" - }, - { - "id": "PHMO", - "name": "Molokai, HI" - }, - { - "id": "PHWA", - "name": "South Shore, HI" - }, - { - "id": "TJUA", - "name": "San Juan, PR" - } - ] + "verifiedAt": "2026-08-02", + "sources": [ + "https://www.roc.noaa.gov/build-loaded.php", + "https://unidata-nexrad-level2-chunks.s3.amazonaws.com/?list-type=2&delimiter=%2F&max-keys=1000", + "nexrad-model 1.0.0-rc.2 meta::registry (site coordinates)", + "https://api.weather.gov/radar/stations (coordinates for KBHX, KDOX, KHDC, KLGX, PAPD)" + ], + "sites": [ + { + "id": "KABR", + "name": "Aberdeen, SD", + "latitude": 45.4558, + "longitude": -98.4131 + }, + { + "id": "KABX", + "name": "Albuquerque, NM", + "latitude": 35.1497, + "longitude": -106.8239 + }, + { + "id": "KAKQ", + "name": "Wakefield, VA", + "latitude": 36.9839, + "longitude": -77.0072 + }, + { + "id": "KAMA", + "name": "Amarillo, TX", + "latitude": 35.2333, + "longitude": -101.7092 + }, + { + "id": "KAMX", + "name": "Miami, FL", + "latitude": 25.6111, + "longitude": -80.4128 + }, + { + "id": "KAPX", + "name": "Gaylord/Alpena, MI", + "latitude": 44.9072, + "longitude": -84.7197 + }, + { + "id": "KARX", + "name": "La Crosse, WI", + "latitude": 43.8228, + "longitude": -91.1911 + }, + { + "id": "KATX", + "name": "Seattle, WA", + "latitude": 48.1944, + "longitude": -122.4958 + }, + { + "id": "KBBX", + "name": "Beale AFB, CA", + "latitude": 39.4961, + "longitude": -121.6317 + }, + { + "id": "KBGM", + "name": "Binghamton, NY", + "latitude": 42.1997, + "longitude": -75.9847 + }, + { + "id": "KBHX", + "name": "Eureka, CA", + "latitude": 40.49833, + "longitude": -124.29215 + }, + { + "id": "KBIS", + "name": "Bismarck, ND", + "latitude": 46.7708, + "longitude": -100.7603 + }, + { + "id": "KBLX", + "name": "Billings, MT", + "latitude": 45.8536, + "longitude": -108.6069 + }, + { + "id": "KBMX", + "name": "Birmingham, AL", + "latitude": 33.1722, + "longitude": -86.7698 + }, + { + "id": "KBOX", + "name": "Boston, MA", + "latitude": 41.9558, + "longitude": -71.1369 + }, + { + "id": "KBRO", + "name": "Brownsville, TX", + "latitude": 25.9158, + "longitude": -97.4189 + }, + { + "id": "KBUF", + "name": "Buffalo, NY", + "latitude": 42.9486, + "longitude": -78.7369 + }, + { + "id": "KBYX", + "name": "Key West, FL", + "latitude": 24.5975, + "longitude": -81.7031 + }, + { + "id": "KCAE", + "name": "Columbia, SC", + "latitude": 33.9486, + "longitude": -81.1186 + }, + { + "id": "KCBW", + "name": "Caribou, ME", + "latitude": 46.0392, + "longitude": -67.8067 + }, + { + "id": "KCBX", + "name": "Boise, ID", + "latitude": 43.4908, + "longitude": -116.2358 + }, + { + "id": "KCCX", + "name": "State College, PA", + "latitude": 40.9231, + "longitude": -78.0039 + }, + { + "id": "KCLE", + "name": "Cleveland, OH", + "latitude": 41.4131, + "longitude": -81.8597 + }, + { + "id": "KCLX", + "name": "Charleston, SC", + "latitude": 32.6556, + "longitude": -81.0425 + }, + { + "id": "KCRP", + "name": "Corpus Christi, TX", + "latitude": 27.7842, + "longitude": -97.5111 + }, + { + "id": "KCXX", + "name": "Burlington, VT", + "latitude": 44.5111, + "longitude": -73.1667 + }, + { + "id": "KCYS", + "name": "Cheyenne, WY", + "latitude": 41.1519, + "longitude": -104.8061 + }, + { + "id": "KDAX", + "name": "Sacramento, CA", + "latitude": 38.5011, + "longitude": -121.6778 + }, + { + "id": "KDDC", + "name": "Dodge City, KS", + "latitude": 37.7608, + "longitude": -99.9689 + }, + { + "id": "KDFX", + "name": "Laughlin AFB, TX", + "latitude": 29.2722, + "longitude": -100.2803 + }, + { + "id": "KDGX", + "name": "Jackson, MS", + "latitude": 32.28, + "longitude": -89.9844 + }, + { + "id": "KDIX", + "name": "Philadelphia, PA", + "latitude": 39.9469, + "longitude": -74.4108 + }, + { + "id": "KDLH", + "name": "Duluth, MN", + "latitude": 46.8369, + "longitude": -92.2097 + }, + { + "id": "KDMX", + "name": "Des Moines, IA", + "latitude": 41.7311, + "longitude": -93.7228 + }, + { + "id": "KDOX", + "name": "Dover AFB, DE", + "latitude": 38.82555, + "longitude": -75.44 + }, + { + "id": "KDTX", + "name": "Detroit, MI", + "latitude": 42.6997, + "longitude": -83.4717 + }, + { + "id": "KDVN", + "name": "Davenport, IA", + "latitude": 41.6117, + "longitude": -90.5808 + }, + { + "id": "KDYX", + "name": "Dyess AFB, TX", + "latitude": 32.5386, + "longitude": -99.2544 + }, + { + "id": "KEAX", + "name": "Kansas City, MO", + "latitude": 38.8103, + "longitude": -94.2644 + }, + { + "id": "KEMX", + "name": "Tucson, AZ", + "latitude": 31.8939, + "longitude": -110.6303 + }, + { + "id": "KENX", + "name": "Albany, NY", + "latitude": 42.5864, + "longitude": -74.0639 + }, + { + "id": "KEOX", + "name": "Ft Rucker (Novosel), AL", + "latitude": 31.4606, + "longitude": -85.4592 + }, + { + "id": "KEPZ", + "name": "El Paso, TX", + "latitude": 31.8731, + "longitude": -106.6978 + }, + { + "id": "KESX", + "name": "Las Vegas, NV", + "latitude": 35.7011, + "longitude": -114.8914 + }, + { + "id": "KEVX", + "name": "Eglin AFB, FL", + "latitude": 30.5644, + "longitude": -85.9214 + }, + { + "id": "KEWX", + "name": "San Antonio, TX", + "latitude": 29.7039, + "longitude": -98.0286 + }, + { + "id": "KEYX", + "name": "Edwards AFB, CA", + "latitude": 35.0978, + "longitude": -117.5608 + }, + { + "id": "KFCX", + "name": "Blacksburg, VA", + "latitude": 37.0242, + "longitude": -80.2744 + }, + { + "id": "KFDR", + "name": "Altus AFB, OK", + "latitude": 34.3622, + "longitude": -98.9764 + }, + { + "id": "KFDX", + "name": "Cannon AFB, NM", + "latitude": 34.635, + "longitude": -103.6297 + }, + { + "id": "KFFC", + "name": "Atlanta, GA", + "latitude": 33.3636, + "longitude": -84.5658 + }, + { + "id": "KFSD", + "name": "Sioux Falls, SD", + "latitude": 43.5878, + "longitude": -96.7289 + }, + { + "id": "KFSX", + "name": "Flagstaff, AZ", + "latitude": 34.5744, + "longitude": -111.1983 + }, + { + "id": "KFTG", + "name": "Denver, CO", + "latitude": 39.7867, + "longitude": -104.5458 + }, + { + "id": "KFWS", + "name": "Ft Worth, TX", + "latitude": 32.5731, + "longitude": -97.3031 + }, + { + "id": "KGGW", + "name": "Glasgow, MT", + "latitude": 48.2064, + "longitude": -106.6253 + }, + { + "id": "KGJX", + "name": "Grand Junction, CO", + "latitude": 39.0622, + "longitude": -108.2139 + }, + { + "id": "KGLD", + "name": "Goodland, KS", + "latitude": 39.3669, + "longitude": -101.7003 + }, + { + "id": "KGRB", + "name": "Green Bay, WI", + "latitude": 44.4986, + "longitude": -88.1111 + }, + { + "id": "KGRK", + "name": "Ft Hood (Cavazos), TX", + "latitude": 30.7217, + "longitude": -97.3828 + }, + { + "id": "KGRR", + "name": "Grand Rapids, MI", + "latitude": 42.8939, + "longitude": -85.5447 + }, + { + "id": "KGSP", + "name": "Greer, SC", + "latitude": 34.8833, + "longitude": -82.22 + }, + { + "id": "KGWX", + "name": "Columbus AFB, MS", + "latitude": 33.8967, + "longitude": -88.3289 + }, + { + "id": "KGYX", + "name": "Portland, ME", + "latitude": 43.8914, + "longitude": -70.2567 + }, + { + "id": "KHDC", + "name": "New Orleans/Hammond, LA", + "latitude": 30.5196, + "longitude": -90.4074 + }, + { + "id": "KHDX", + "name": "Holloman AFB, NM", + "latitude": 33.0769, + "longitude": -106.12 + }, + { + "id": "KHGX", + "name": "Houston, TX", + "latitude": 29.4719, + "longitude": -95.0792 + }, + { + "id": "KHNX", + "name": "San Joaquin, CA", + "latitude": 36.3142, + "longitude": -119.6322 + }, + { + "id": "KHPX", + "name": "Ft Campbell, KY", + "latitude": 36.7369, + "longitude": -87.285 + }, + { + "id": "KHTX", + "name": "Huntsville/Hytop, AL", + "latitude": 34.9306, + "longitude": -86.0833 + }, + { + "id": "KICT", + "name": "Wichita, KS", + "latitude": 37.6544, + "longitude": -97.4428 + }, + { + "id": "KICX", + "name": "Cedar City, UT", + "latitude": 37.5911, + "longitude": -112.8622 + }, + { + "id": "KILN", + "name": "Cincinnati, OH", + "latitude": 39.4203, + "longitude": -83.8217 + }, + { + "id": "KILX", + "name": "Lincoln, IL", + "latitude": 40.1506, + "longitude": -89.3369 + }, + { + "id": "KIND", + "name": "Indianapolis, IN", + "latitude": 39.7075, + "longitude": -86.2803 + }, + { + "id": "KINX", + "name": "Tulsa, OK", + "latitude": 36.175, + "longitude": -95.5647 + }, + { + "id": "KIWA", + "name": "Phoenix, AZ", + "latitude": 33.2892, + "longitude": -111.67 + }, + { + "id": "KIWX", + "name": "North Webster, IN", + "latitude": 41.3586, + "longitude": -85.7 + }, + { + "id": "KJAX", + "name": "Jacksonville, FL", + "latitude": 30.4847, + "longitude": -81.7019 + }, + { + "id": "KJGX", + "name": "Robins AFB, GA", + "latitude": 32.6756, + "longitude": -83.3511 + }, + { + "id": "KJKL", + "name": "Jackson, KY", + "latitude": 37.5908, + "longitude": -83.3131 + }, + { + "id": "KLBB", + "name": "Lubbock, TX", + "latitude": 33.6542, + "longitude": -101.8142 + }, + { + "id": "KLCH", + "name": "Lake Charles, LA", + "latitude": 30.1253, + "longitude": -93.2158 + }, + { + "id": "KLGX", + "name": "Langley Hill, WA", + "latitude": 47.11689, + "longitude": -124.10663 + }, + { + "id": "KLNX", + "name": "North Platte, NE", + "latitude": 41.9578, + "longitude": -100.5761 + }, + { + "id": "KLOT", + "name": "Chicago, IL", + "latitude": 41.6044, + "longitude": -88.0847 + }, + { + "id": "KLRX", + "name": "Elko, NV", + "latitude": 40.74, + "longitude": -116.8025 + }, + { + "id": "KLSX", + "name": "St Louis, MO", + "latitude": 38.6986, + "longitude": -90.6828 + }, + { + "id": "KLTX", + "name": "Wilmington, NC", + "latitude": 33.9892, + "longitude": -78.4292 + }, + { + "id": "KLVX", + "name": "Louisville, KY", + "latitude": 37.9753, + "longitude": -85.9439 + }, + { + "id": "KLWX", + "name": "Sterling VA (DC)", + "latitude": 38.9753, + "longitude": -77.4778 + }, + { + "id": "KLZK", + "name": "Little Rock, AR", + "latitude": 34.8364, + "longitude": -92.2622 + }, + { + "id": "KMAF", + "name": "Midland/Odessa, TX", + "latitude": 31.9433, + "longitude": -102.1892 + }, + { + "id": "KMAX", + "name": "Medford, OR", + "latitude": 42.0811, + "longitude": -122.7167 + }, + { + "id": "KMHX", + "name": "Morehead City, NC", + "latitude": 34.7761, + "longitude": -76.8764 + }, + { + "id": "KMKX", + "name": "Milwaukee, WI", + "latitude": 42.9678, + "longitude": -88.5506 + }, + { + "id": "KMLB", + "name": "Melbourne, FL", + "latitude": 28.1133, + "longitude": -80.6542 + }, + { + "id": "KMOB", + "name": "Mobile, AL", + "latitude": 30.6794, + "longitude": -88.2397 + }, + { + "id": "KMPX", + "name": "Minneapolis, MN", + "latitude": 44.8489, + "longitude": -93.5653 + }, + { + "id": "KMQT", + "name": "Marquette, MI", + "latitude": 46.5314, + "longitude": -87.5486 + }, + { + "id": "KMRX", + "name": "Morristown, TN", + "latitude": 36.1686, + "longitude": -83.4017 + }, + { + "id": "KMSX", + "name": "Missoula, MT", + "latitude": 47.0411, + "longitude": -113.9864 + }, + { + "id": "KMTX", + "name": "Salt Lake City, UT", + "latitude": 41.2628, + "longitude": -112.4478 + }, + { + "id": "KMUX", + "name": "San Francisco, CA", + "latitude": 37.1553, + "longitude": -121.8983 + }, + { + "id": "KMVX", + "name": "Grand Forks, ND", + "latitude": 47.5281, + "longitude": -97.3256 + }, + { + "id": "KMXX", + "name": "Maxwell AFB, AL", + "latitude": 32.5367, + "longitude": -85.7897 + }, + { + "id": "KNKX", + "name": "San Diego, CA", + "latitude": 32.9189, + "longitude": -117.0419 + }, + { + "id": "KNQA", + "name": "Memphis, TN", + "latitude": 35.3447, + "longitude": -89.8733 + }, + { + "id": "KOAX", + "name": "Omaha, NE", + "latitude": 41.3203, + "longitude": -96.3667 + }, + { + "id": "KOHX", + "name": "Nashville, TN", + "latitude": 36.2472, + "longitude": -86.5625 + }, + { + "id": "KOKX", + "name": "New York, NY", + "latitude": 40.8656, + "longitude": -72.8639 + }, + { + "id": "KOTX", + "name": "Spokane, WA", + "latitude": 47.6806, + "longitude": -117.6267 + }, + { + "id": "KPAH", + "name": "Paducah, KY", + "latitude": 37.0683, + "longitude": -88.7722 + }, + { + "id": "KPBZ", + "name": "Pittsburgh, PA", + "latitude": 40.5317, + "longitude": -80.0183 + }, + { + "id": "KPDT", + "name": "Pendleton, OR", + "latitude": 45.6906, + "longitude": -118.8528 + }, + { + "id": "KPOE", + "name": "Ft Polk (Johnson), LA", + "latitude": 31.1556, + "longitude": -92.9756 + }, + { + "id": "KPUX", + "name": "Pueblo, CO", + "latitude": 38.4594, + "longitude": -104.1817 + }, + { + "id": "KRAX", + "name": "Raleigh/Durham, NC", + "latitude": 35.6656, + "longitude": -78.4903 + }, + { + "id": "KRGX", + "name": "Reno, NV", + "latitude": 39.7542, + "longitude": -119.4622 + }, + { + "id": "KRIW", + "name": "Riverton, WY", + "latitude": 43.0661, + "longitude": -108.4772 + }, + { + "id": "KRLX", + "name": "Charleston, WV", + "latitude": 38.3111, + "longitude": -81.7231 + }, + { + "id": "KRTX", + "name": "Portland, OR", + "latitude": 45.715, + "longitude": -122.9653 + }, + { + "id": "KSFX", + "name": "Pocatello, ID", + "latitude": 43.1058, + "longitude": -112.6861 + }, + { + "id": "KSGF", + "name": "Springfield, MO", + "latitude": 37.2353, + "longitude": -93.4006 + }, + { + "id": "KSHV", + "name": "Shreveport, LA", + "latitude": 32.4508, + "longitude": -93.8411 + }, + { + "id": "KSJT", + "name": "San Angelo, TX", + "latitude": 31.3714, + "longitude": -100.4925 + }, + { + "id": "KSOX", + "name": "Santa Ana Mtn., CA", + "latitude": 33.8178, + "longitude": -117.6358 + }, + { + "id": "KSRX", + "name": "Fort Smith, AR", + "latitude": 35.2906, + "longitude": -94.3619 + }, + { + "id": "KTBW", + "name": "Tampa Bay, FL", + "latitude": 27.7056, + "longitude": -82.4017 + }, + { + "id": "KTFX", + "name": "Great Falls, MT", + "latitude": 47.4597, + "longitude": -111.3853 + }, + { + "id": "KTLH", + "name": "Tallahassee, FL", + "latitude": 30.3975, + "longitude": -84.3289 + }, + { + "id": "KTLX", + "name": "Oklahoma City, OK", + "latitude": 35.3331, + "longitude": -97.2778 + }, + { + "id": "KTWX", + "name": "Topeka, KS", + "latitude": 38.9969, + "longitude": -96.2325 + }, + { + "id": "KTYX", + "name": "Ft Drum, NY", + "latitude": 43.7558, + "longitude": -75.68 + }, + { + "id": "KUDX", + "name": "Rapid City, SD", + "latitude": 44.125, + "longitude": -102.8297 + }, + { + "id": "KUEX", + "name": "Hastings, NE", + "latitude": 40.3208, + "longitude": -98.4419 + }, + { + "id": "KVAX", + "name": "Moody AFB, GA", + "latitude": 30.89, + "longitude": -83.0019 + }, + { + "id": "KVBX", + "name": "Vandenberg SFB, CA", + "latitude": 34.8383, + "longitude": -120.3978 + }, + { + "id": "KVNX", + "name": "Vance AFB, OK", + "latitude": 36.7406, + "longitude": -98.1278 + }, + { + "id": "KVTX", + "name": "Los Angeles, CA", + "latitude": 34.4114, + "longitude": -119.1794 + }, + { + "id": "KVWX", + "name": "Evansville, IN", + "latitude": 38.2603, + "longitude": -87.7247 + }, + { + "id": "KYUX", + "name": "Yuma/Phoenix, AZ", + "latitude": 32.4953, + "longitude": -114.6567 + }, + { + "id": "PABC", + "name": "Bethel, AK", + "latitude": 60.7919, + "longitude": -161.8764 + }, + { + "id": "PACG", + "name": "Sitka, AK", + "latitude": 56.8525, + "longitude": -135.5294 + }, + { + "id": "PAEC", + "name": "Nome, AK", + "latitude": 64.5114, + "longitude": -165.295 + }, + { + "id": "PAHG", + "name": "Anchorage/Kenai, AK", + "latitude": 60.7258, + "longitude": -151.3514 + }, + { + "id": "PAIH", + "name": "Middleton Island, AK", + "latitude": 59.4614, + "longitude": -146.3031 + }, + { + "id": "PAKC", + "name": "King Salmon, AK", + "latitude": 58.6794, + "longitude": -156.6297 + }, + { + "id": "PAPD", + "name": "Fairbanks, AK", + "latitude": 65.03511, + "longitude": -147.5014 + }, + { + "id": "PGUA", + "name": "Andersen AFB, Guam", + "latitude": 13.4544, + "longitude": 144.8111 + }, + { + "id": "PHKI", + "name": "South Kauai, HI", + "latitude": 21.8939, + "longitude": -159.5522 + }, + { + "id": "PHKM", + "name": "Kamuela, HI", + "latitude": 20.1253, + "longitude": -155.7781 + }, + { + "id": "PHMO", + "name": "Molokai, HI", + "latitude": 21.1328, + "longitude": -157.1803 + }, + { + "id": "PHWA", + "name": "South Shore, HI", + "latitude": 19.095, + "longitude": -155.5689 + }, + { + "id": "TJUA", + "name": "San Juan, PR", + "latitude": 18.1156, + "longitude": -66.0781 + } + ], + "locationsVerifiedAt": "2026-09-28" } diff --git a/src/data/radarSites.ts b/src/data/radarSites.ts index 3a9f4a2..cc83cfa 100644 --- a/src/data/radarSites.ts +++ b/src/data/radarSites.ts @@ -8,14 +8,20 @@ import catalog from "./radar-sites.json"; export interface RadarSiteOption { readonly id: string; readonly name: string; + readonly latitude: number; + readonly longitude: number; } export const RADAR_SITES: readonly RadarSiteOption[] = catalog.sites; -const RADAR_SITE_IDS = new Set(RADAR_SITES.map((site) => site.id)); +const RADAR_SITES_BY_ID = new Map(RADAR_SITES.map((site) => [site.id, site])); export function isSupportedRadarSite(value: string): boolean { - return RADAR_SITE_IDS.has(value); + return RADAR_SITES_BY_ID.has(value); +} + +export function radarSiteById(id: string): RadarSiteOption | undefined { + return RADAR_SITES_BY_ID.get(id); } export function filterRadarSites( diff --git a/src/radar-session/autoSourcePolicy.test.ts b/src/radar-session/autoSourcePolicy.test.ts new file mode 100644 index 0000000..176b3e0 --- /dev/null +++ b/src/radar-session/autoSourcePolicy.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from "vitest"; +import { RADAR_SITES } from "../data/radarSites"; +import { decideAutoSource, sameAutoSource } from "./autoSourcePolicy"; + +const KTLX = { longitude: -97.2778, latitude: 35.3331 }; +const OKC_METRO = { longitude: -97.52, latitude: 35.47 }; +const GULF = { longitude: -89.5, latitude: 25.0 }; +const national = { kind: "national" } as const; +const ktlx = { kind: "site", siteIcao: "KTLX" } as const; + +describe("decideAutoSource", () => { + it("keeps National at regional zooms and preloads the nearest Site near the threshold", () => { + expect(decideAutoSource({ zoom: 6, center: OKC_METRO, visible: national }, RADAR_SITES)) + .toEqual({ target: national }); + expect(decideAutoSource({ zoom: 8.2, center: OKC_METRO, visible: national }, RADAR_SITES)) + .toEqual({ target: national, preload: "KTLX" }); + }); + + it("switches to the nearest covering Site once zoomed in", () => { + expect(decideAutoSource({ zoom: 9, center: OKC_METRO, visible: national }, RADAR_SITES)) + .toEqual({ target: ktlx }); + }); + + it("stays on National over areas no Site covers", () => { + expect(decideAutoSource({ zoom: 11, center: GULF, visible: national }, RADAR_SITES)) + .toEqual({ target: national }); + }); + + it("holds a displayed Site between the exit and enter zooms", () => { + expect(decideAutoSource({ zoom: 8.7, center: KTLX, visible: ktlx }, RADAR_SITES)) + .toEqual({ target: ktlx }); + expect(decideAutoSource({ zoom: 8.4, center: KTLX, visible: ktlx }, RADAR_SITES)) + .toEqual({ target: national }); + }); + + it("returns to National when the view leaves the displayed Site's coverage", () => { + // Amarillo is ~380 km from KTLX; its own radar is the better one. + const amarillo = { longitude: -101.83, latitude: 35.22 }; + expect(decideAutoSource({ zoom: 10, center: amarillo, visible: ktlx }, RADAR_SITES)) + .toEqual({ target: national }); + expect(decideAutoSource({ zoom: 10, center: amarillo, visible: national }, RADAR_SITES).target) + .toEqual({ kind: "site", siteIcao: "KAMA" }); + }); + + it("prefers the picked Site over a nearer one while inside its coverage", () => { + // Between KTLX and Vance AFB (KVNX); KVNX is nearer here. + const between = { longitude: -97.9, latitude: 36.3 }; + expect(decideAutoSource({ zoom: 10, center: between, visible: national }, RADAR_SITES).target) + .toEqual({ kind: "site", siteIcao: "KVNX" }); + expect(decideAutoSource( + { zoom: 10, center: between, visible: national, preferredSite: "KTLX" }, + RADAR_SITES, + ).target).toEqual(ktlx); + }); + + it("compares sources by kind and site", () => { + expect(sameAutoSource(national, { kind: "national" })).toBe(true); + expect(sameAutoSource(ktlx, { kind: "site", siteIcao: "KTLX" })).toBe(true); + expect(sameAutoSource(ktlx, { kind: "site", siteIcao: "KINX" })).toBe(false); + expect(sameAutoSource(ktlx, national)).toBe(false); + }); +}); diff --git a/src/radar-session/autoSourcePolicy.ts b/src/radar-session/autoSourcePolicy.ts new file mode 100644 index 0000000..6c45caf --- /dev/null +++ b/src/radar-session/autoSourcePolicy.ts @@ -0,0 +1,82 @@ +import type { RadarSiteOption } from "../data/radarSites"; +import { rangeBearing, type LngLatPoint } from "../radar-renderer/geo"; + +/** Zoom at which a covering Site replaces the ~1 km National mosaic. */ +export const AUTO_SITE_ENTER_ZOOM = 9; +/** Below this zoom a displayed Site hands back to National (hysteresis). */ +export const AUTO_SITE_EXIT_ZOOM = 8.5; +/** From this zoom the likely Site is fetched ahead so the switch is instant. */ +export const AUTO_SITE_PRELOAD_ZOOM = 8; +/** The view center must be this close to a Site to switch to it. */ +export const AUTO_SITE_ENTER_RANGE_M = 200_000; +/** A displayed Site is kept while the view center stays this close to it. */ +export const AUTO_SITE_KEEP_RANGE_M = 230_000; + +export type AutoSource = + | { readonly kind: "national" } + | { readonly kind: "site"; readonly siteIcao: string }; + +export interface AutoSourceInput { + readonly zoom: number; + readonly center: LngLatPoint; + readonly visible: AutoSource; + /** Site the operator picked; preferred while the view stays inside its coverage. */ + readonly preferredSite?: string; +} + +export interface AutoSourceDecision { + readonly target: AutoSource; + /** Site worth fetching ahead of the switch, only while National is displayed. */ + readonly preload?: string; +} + +const NATIONAL: AutoSource = { kind: "national" }; + +/** + * Zoom decides the source. Moving between Sites always passes through + * National, so only one Site is ever loaded. + */ +export function decideAutoSource( + input: AutoSourceInput, + sites: readonly RadarSiteOption[], +): AutoSourceDecision { + const { zoom, center, visible } = input; + if (visible.kind === "site") { + const current = sites.find((site) => site.id === visible.siteIcao); + const stays = current + && zoom >= AUTO_SITE_EXIT_ZOOM + && distanceM(center, current) <= AUTO_SITE_KEEP_RANGE_M; + return { target: stays ? visible : NATIONAL }; + } + const candidate = candidateSite(center, input.preferredSite, sites); + if (!candidate) return { target: NATIONAL }; + if (zoom >= AUTO_SITE_ENTER_ZOOM) return { target: { kind: "site", siteIcao: candidate } }; + if (zoom >= AUTO_SITE_PRELOAD_ZOOM) return { target: NATIONAL, preload: candidate }; + return { target: NATIONAL }; +} + +export function sameAutoSource(left: AutoSource, right: AutoSource): boolean { + return left.kind === right.kind + && (left.kind === "national" || left.siteIcao === (right as { siteIcao: string }).siteIcao); +} + +function candidateSite( + center: LngLatPoint, + preferredSite: string | undefined, + sites: readonly RadarSiteOption[], +): string | undefined { + const preferred = preferredSite ? sites.find((site) => site.id === preferredSite) : undefined; + if (preferred && distanceM(center, preferred) <= AUTO_SITE_KEEP_RANGE_M) return preferred.id; + let nearest: { id: string; distance: number } | undefined; + for (const site of sites) { + const distance = distanceM(center, site); + if (distance <= AUTO_SITE_ENTER_RANGE_M && (!nearest || distance < nearest.distance)) { + nearest = { id: site.id, distance }; + } + } + return nearest?.id; +} + +function distanceM(center: LngLatPoint, site: RadarSiteOption): number { + return rangeBearing(center, { longitude: site.longitude, latitude: site.latitude }).rangeM; +} From 3851d6e014f00c3ad9ece58e8eeb611ddc060281 Mon Sep 17 00:00:00 2001 From: Travis Curtsinger <93950613+tcurtsinger@users.noreply.github.com> Date: Mon, 28 Sep 2026 13:43:45 -0500 Subject: [PATCH 2/8] Give the Site layer a cross-fade and keep National beneath it The Site shader gains u_opacity. Like the display mode it changes only shading, never the paint receipt, so a Site can draw its first frame at opacity 0 and fade in over National. fadeOpacity eases between values across animation frames and stops when superseded. National is now always inserted, and re-inserted after context loss, below the Site stack, so the fading Site layer is the upper one. Co-Authored-By: Claude Opus 5.5 --- src/App.tsx | 11 ++++-- src/national-radar/NationalGridLayer.ts | 6 ++-- src/radar-renderer/RadarCustomLayer.ts | 35 +++++++++++++++++- src/radar-renderer/fade.test.ts | 47 +++++++++++++++++++++++++ src/radar-renderer/fade.ts | 42 ++++++++++++++++++++++ 5 files changed, 135 insertions(+), 6 deletions(-) create mode 100644 src/radar-renderer/fade.test.ts create mode 100644 src/radar-renderer/fade.ts diff --git a/src/App.tsx b/src/App.tsx index 6f13c98..11385db 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1350,9 +1350,15 @@ export function App() { const ensureNationalLayer = () => { if (nationalLayer && nationalWorkingSet) return; + // National always sits below the Site stack so a Site can fade over it. + const nationalBeforeLayerId = () => ( + instance.getLayer(RANGE_LAYER_ID) + ? RANGE_LAYER_ID + : radarContextAnchorLayerId(instance.getStyle().layers ?? []) + ); nationalLayer = new NationalGridLayer({ displayMode: displayModeRef.current, - recoveryBeforeLayerId: radarContextAnchorLayerId(instance.getStyle().layers ?? []), + recoveryBeforeLayerId: nationalBeforeLayerId, onSnapshot(renderer) { setPlaybackError((current) => playbackErrorAfterRendererStatus(current, renderer.status)); if (renderer.displayMode !== displayModeRef.current) { @@ -1373,8 +1379,7 @@ export function App() { activeClientForNational(), nationalLayer, ); - const beforeId = radarContextAnchorLayerId(instance.getStyle().layers ?? []); - addLayer(instance, nationalLayer, beforeId); + addLayer(instance, nationalLayer, nationalBeforeLayerId()); nationalLayerRef.current = nationalLayer; nationalWorkingSetRef.current = nationalWorkingSet; }; diff --git a/src/national-radar/NationalGridLayer.ts b/src/national-radar/NationalGridLayer.ts index a15556f..808c20c 100644 --- a/src/national-radar/NationalGridLayer.ts +++ b/src/national-radar/NationalGridLayer.ts @@ -203,7 +203,8 @@ export interface NationalGridRendererSnapshot { export interface NationalGridLayerOptions { displayMode?: RadarDisplayMode; - recoveryBeforeLayerId?: string; + /** Layer to re-insert before after context loss; resolved at restore time. */ + recoveryBeforeLayerId?: string | (() => string | undefined); uploadBudgetMs?: number; onSnapshot?(snapshot: NationalGridRendererSnapshot): void; } @@ -1488,7 +1489,8 @@ export class NationalGridLayer implements CustomLayerInterface { if (!map || !this.recovering) return; try { if (!map.getLayer(this.id)) { - const preferred = this.options.recoveryBeforeLayerId; + const option = this.options.recoveryBeforeLayerId; + const preferred = typeof option === "function" ? option() : option; const beforeId = preferred && map.getLayer(preferred) ? preferred : map.getStyle().layers?.find((layer) => layer.type === "symbol")?.id; diff --git a/src/radar-renderer/RadarCustomLayer.ts b/src/radar-renderer/RadarCustomLayer.ts index 7c24ab1..5c51041 100644 --- a/src/radar-renderer/RadarCustomLayer.ts +++ b/src/radar-renderer/RadarCustomLayer.ts @@ -38,6 +38,7 @@ uniform int u_radial_count; uniform int u_azimuth_lookup_size; uniform int u_smooth_display; uniform vec4 u_range_folded_color; +uniform float u_opacity; in vec2 v_mercator; out vec4 frag_color; @@ -151,7 +152,7 @@ void main() { uint status = texelFetch(u_statuses, ivec2(gateIndex, radialIndex), 0).r; if (status == uint(1)) discard; if (status == uint(2)) { - frag_color = u_range_folded_color; + frag_color = u_range_folded_color * u_opacity; return; } if (u_smooth_display == 1) { @@ -185,11 +186,14 @@ void main() { gateCoordinate ); if (frag_color.a <= 0.0) discard; + // Premultiplied colors fade correctly by scaling every channel. + frag_color *= u_opacity; return; } uint rawCode = texelFetch(u_raw_codes, ivec2(gateIndex, radialIndex), 0).r; frag_color = texelFetch(u_palette, ivec2(int(rawCode), 0), 0); if (frag_color.a <= 0.0) discard; + frag_color *= u_opacity; }`; export interface RadarRendererCapabilities { @@ -303,6 +307,8 @@ export interface RadarCustomLayerOptions { onSnapshot(snapshot: RadarRendererSnapshot): void; recoveryBeforeLayerId?: string; displayMode?: RadarDisplayMode; + /** Initial opacity; a Site that will fade in starts at 0. */ + opacity?: number; } interface Uniforms { @@ -320,6 +326,7 @@ interface Uniforms { smoothDisplay: WebGLUniformLocation; radialMetadata: WebGLUniformLocation; rangeFoldedColor: WebGLUniformLocation; + opacity: WebGLUniformLocation; } interface RadarFrameResources { @@ -396,6 +403,7 @@ export class RadarCustomLayer implements CustomLayerInterface { private selectionSequence = 1; private selectedAt = 0; private displayMode: RadarDisplayMode; + private opacity: number; private presentationEnabled = true; private peakGpuResourceBytes = 0; private frameUploadCount = 0; @@ -426,6 +434,7 @@ export class RadarCustomLayer implements CustomLayerInterface { this.models = models; this.selectedObservationId = models[0].observationId; this.displayMode = validateRadarDisplayMode(options.displayMode ?? "smooth"); + this.opacity = validateRadarOpacity(options.opacity ?? 1); } private models: RadarSweepCpuModel[]; @@ -444,6 +453,21 @@ export class RadarCustomLayer implements CustomLayerInterface { return this.displayMode; } + /** + * Cross-fade control. Like the display mode it changes only shading, so it + * neither invalidates nor replaces the authoritative paint receipt. + */ + setOpacity(opacity: number): void { + const next = validateRadarOpacity(opacity); + if (next === this.opacity) return; + this.opacity = next; + this.map?.triggerRepaint(); + } + + getOpacity(): number { + return this.opacity; + } + setDisplayMode(displayMode: RadarDisplayMode): void { const nextMode = validateRadarDisplayMode(displayMode); if (nextMode === this.displayMode) return; @@ -625,6 +649,7 @@ export class RadarCustomLayer implements CustomLayerInterface { gl.uniform1i(this.uniforms.lookupSize, model.azimuthLookup.length); const smoothDisplay = shouldSmoothRadarDisplay(this.displayMode, model.product); gl.uniform1i(this.uniforms.smoothDisplay, smoothDisplay ? 1 : 0); + gl.uniform1f(this.uniforms.opacity, this.opacity); const alpha = RANGE_FOLDED_COLOR[3] / 255; gl.uniform4f( this.uniforms.rangeFoldedColor, @@ -2031,9 +2056,17 @@ function resolveUniforms(gl: WebGL2RenderingContext, program: WebGLProgram): Uni smoothDisplay: requireUniform(gl, program, "u_smooth_display"), radialMetadata: requireUniform(gl, program, "u_radial_metadata"), rangeFoldedColor: requireUniform(gl, program, "u_range_folded_color"), + opacity: requireUniform(gl, program, "u_opacity"), }; } +function validateRadarOpacity(value: number): number { + if (!Number.isFinite(value) || value < 0 || value > 1) { + throw new RadarRendererError("radar opacity must be between 0 and 1"); + } + return value; +} + function validateRadarDisplayMode(value: string): RadarDisplayMode { if (value !== "smooth" && value !== "native") { throw new TypeError("radar display mode must be Smooth or Native"); diff --git a/src/radar-renderer/fade.test.ts b/src/radar-renderer/fade.test.ts new file mode 100644 index 0000000..0c8cd3f --- /dev/null +++ b/src/radar-renderer/fade.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from "vitest"; +import { fadeOpacity } from "./fade"; + +function clock(stepMs: number) { + let time = 0; + return { + now: () => time, + nextFrame: async () => { time += stepMs; }, + }; +} + +describe("fadeOpacity", () => { + it("eases monotonically from start to target and ends exactly on target", async () => { + const applied: number[] = []; + const done = await fadeOpacity((value) => applied.push(value), 0, 1, { durationMs: 300, ...clock(16) }); + expect(done).toBe(true); + expect(applied[0]).toBe(0); + expect(applied.at(-1)).toBe(1); + expect(applied.every((value, index) => index === 0 || value >= applied[index - 1])).toBe(true); + expect(applied.length).toBeGreaterThan(10); + }); + + it("fades out as well as in", async () => { + const applied: number[] = []; + await fadeOpacity((value) => applied.push(value), 1, 0, { durationMs: 100, ...clock(25) }); + expect(applied[0]).toBe(1); + expect(applied.at(-1)).toBe(0); + }); + + it("jumps straight to the target for a zero duration", async () => { + const applied: number[] = []; + await fadeOpacity((value) => applied.push(value), 0, 1, { durationMs: 0, ...clock(16) }); + expect(applied).toEqual([0, 1]); + }); + + it("stops without reaching the target once superseded", async () => { + const applied: number[] = []; + let frames = 0; + const done = await fadeOpacity((value) => applied.push(value), 0, 1, { + durationMs: 300, + ...clock(16), + isCurrent: () => (frames += 1) < 4, + }); + expect(done).toBe(false); + expect(applied.at(-1)).toBeLessThan(1); + }); +}); diff --git a/src/radar-renderer/fade.ts b/src/radar-renderer/fade.ts new file mode 100644 index 0000000..aa0c41e --- /dev/null +++ b/src/radar-renderer/fade.ts @@ -0,0 +1,42 @@ +export interface FadeOptions { + durationMs: number; + /** Returns false once a newer switch owns the layer; the fade then stops. */ + isCurrent?: () => boolean; + now?: () => number; + nextFrame?: () => Promise; +} + +/** + * Eases opacity from one value to another across animation frames. Resolves + * true once the target opacity has had a frame to draw, or false if the fade + * was superseded part-way. + */ +export async function fadeOpacity( + apply: (opacity: number) => void, + from: number, + to: number, + options: FadeOptions, +): Promise { + const now = options.now ?? (() => performance.now()); + const nextFrame = options.nextFrame ?? animationFrame; + const current = options.isCurrent ?? (() => true); + const started = now(); + apply(from); + while (true) { + await nextFrame(); + if (!current()) return false; + const progress = options.durationMs <= 0 + ? 1 + : Math.min(1, (now() - started) / options.durationMs); + const eased = progress * progress * (3 - 2 * progress); + apply(from + (to - from) * eased); + if (progress >= 1) { + await nextFrame(); + return current(); + } + } +} + +function animationFrame(): Promise { + return new Promise((resolve) => globalThis.requestAnimationFrame(() => resolve())); +} From 2e6ff6a4d6613405ba82280c78081057557895db Mon Sep 17 00:00:00 2001 From: Travis Curtsinger <93950613+tcurtsinger@users.noreply.github.com> Date: Mon, 28 Sep 2026 13:51:38 -0500 Subject: [PATCH 3/8] Switch between National and Site by zoom, with preload and cross-fade Zoom now decides the source. After a camera move the operator makes, the policy may fade a covering Site in over National (zoom 9, center within 200 km), keep it down to zoom 8.5 and within 230 km, or fade it back out to the resident National. Moving between Sites passes through National. - From zoom 8 the likely Site's newest scan is fetched ahead on the Site lane; the switch reuses that generation and paints without a network wait. Only one automatic switch runs at a time, and a Site that just failed is not retried for a minute. - The Site paints its first frame at opacity 0, fades in over 300 ms (instant under reduced motion), and only then becomes the displayed source. Leaving it, National paints underneath first and the Site fades out before it is removed. National keeps playing until the Site covers it. - Automatic switches never move the camera. The picker flies to a Site at zoom 9.5 (preloading during the flight from National), picking National zooms out to the country, recenter uses the same targets, and the camera is restored at launch. Co-Authored-By: Claude Opus 5.5 --- .../national-phase4-packaged-validation.mjs | 6 +- ...tional-phase4-packaged-validation.test.mjs | 7 +- src/App.tsx | 473 +++++++++++++++--- src/radar-session/SiteLevel2Session.ts | 4 +- 4 files changed, 413 insertions(+), 77 deletions(-) diff --git a/scripts/national-phase4-packaged-validation.mjs b/scripts/national-phase4-packaged-validation.mjs index 2255ba6..b67a338 100644 --- a/scripts/national-phase4-packaged-validation.mjs +++ b/scripts/national-phase4-packaged-validation.mjs @@ -206,8 +206,10 @@ export function validateResidentHandoff(handoff) { "bulkIpcBytes", ].every((field) => Number.isSafeInteger(before[field]) && after[field] === before[field]); if (!quiet) failures.push("National reveal performs no acquisition, decode, or bulk transfer"); - if (!(handoff?.reveal?.revealMs >= 0 && handoff.reveal.revealMs <= 250)) { - failures.push("National reveal completes within 250 ms"); + // The switch deliberately includes the Site fade-out; the reveal itself stays within 250 ms. + const fadeMs = handoff?.reveal?.fadeMs ?? 0; + if (!(handoff?.reveal?.revealMs >= 0 && fadeMs >= 0 && handoff.reveal.revealMs <= 250 + fadeMs)) { + failures.push("National reveal completes within 250 ms plus the fade"); } return failures; } diff --git a/scripts/national-phase4-packaged-validation.test.mjs b/scripts/national-phase4-packaged-validation.test.mjs index b3b8742..378cc2f 100644 --- a/scripts/national-phase4-packaged-validation.test.mjs +++ b/scripts/national-phase4-packaged-validation.test.mjs @@ -81,8 +81,8 @@ describe("National Phase 4 packaged acceptance", () => { ); const slow = validReport().residentHandoff; - slow.reveal.revealMs = 400; - expect(validateResidentHandoff(slow)).toContain("National reveal completes within 250 ms"); + slow.reveal.revealMs = 600; + expect(validateResidentHandoff(slow)).toContain("National reveal completes within 250 ms plus the fade"); const report = validReport(); delete report.residentHandoff; @@ -345,7 +345,8 @@ function validReport() { reveal: { activityBefore: nationalActivity(), activityAfter: nationalActivity(), - revealMs: 34, + revealMs: 334, + fadeMs: 300, }, after: { painted: { source: { kind: "national", domain: "conus" }, generation: 8 } }, renderer: { diff --git a/src/App.tsx b/src/App.tsx index 11385db..d86465a 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -16,7 +16,6 @@ import type { import fixtureManifest from "../fixtures/manifest.json"; import openFreeMapDarkStyle from "./data/openFreeMapDarkStyle.json"; import { radarContextAnchorLayerId } from "./data/radarMapContext"; -import { RADAR_SITES } from "./data/radarSites"; import { configureMapLibreWorker } from "./mapWorker"; import { mapReadinessError, updateMapReadiness, type MapReadiness } from "./mapReadiness"; import { assertChunkMatchesManifest } from "./packed-grid/packedGrid"; @@ -101,6 +100,7 @@ import { SiteLevel2Session, } from "./radar-session/SiteLevel2Session"; import { NationalMrmsSession, type NationalMrmsPaintResult } from "./radar-session/NationalMrmsSession"; +import { RADAR_SITES, radarSiteById, type RadarSiteOption } from "./data/radarSites"; import { commonResidencyReadyForInteraction, NationalGridLayer, @@ -129,6 +129,12 @@ import { } from "./national-radar/NationalRollbackLoop"; import { colorForReflectivity } from "./radar-renderer/palette"; import { RadarChrome } from "./ui/RadarChrome"; +import { fadeOpacity } from "./radar-renderer/fade"; +import { + decideAutoSource, + sameAutoSource, + type AutoSource, +} from "./radar-session/autoSourcePolicy"; import { frameAgePresentation, nationalHistoryStatus, @@ -167,6 +173,17 @@ const RADAR_SOURCE_STORAGE_KEY = "mistr.radarSource"; const RADAR_DISPLAY_MODE_STORAGE_KEY = "mistr.radarDisplayMode"; const RADAR_ENGINE_PREPARING_ERROR = "Radar engine is still preparing the resident loop"; const LIVE_POLL_RETRY_MS = 15_000; +const CAMERA_STORAGE_KEY = "mistr.camera"; +/** Zoom the picker and recenter use for a Site: past the automatic switch threshold. */ +const SITE_DETAIL_ZOOM = 9.5; +const SOURCE_FADE_MS = 300; +const CAMERA_FLIGHT_MS = 1_200; +/** A preloaded Site scan older than this is refetched at the switch. */ +const SITE_PREFETCH_MAX_AGE_MS = 5 * 60_000; +/** An automatic switch to a Site that just failed waits this long before retrying. */ +const AUTO_SITE_RETRY_MS = 60_000; +const CONUS_BOUNDS: [[number, number], [number, number]] = [[-125.0, 24.0], [-66.5, 50.0]]; +const CAMERA_PADDING = { top: 100, right: 88, bottom: 124, left: 88 }; // Starting a source from scratch cancels the other lane. Site requests use // beginSiteLane instead, so a resident National survives them. @@ -202,6 +219,7 @@ export function App() { const siteLevel2SessionRef = useRef | null>(null); const nationalMrmsSessionRef = useRef | null>(null); const radarModelRef = useRef(null); + const autoSourceRef = useRef(null); const inspectionMarkerRef = useRef(null); const inspectionPointRef = useRef<{ longitude: number; latitude: number } | null>(null); const interrogationObservationRef = useRef(null); @@ -269,8 +287,7 @@ export function App() { instance = new maplibregl.Map({ container: mapContainer.current, style: structuredClone(MAP_STYLE), - center: DEFAULT_CENTER, - zoom: 5.8, + ...initialMapCamera(startupSourceRef.current), bearing: 0, pitch: 0, attributionControl: false, @@ -284,6 +301,8 @@ export function App() { canvasContextAttributes: { antialias: false }, }); instance.addControl(new maplibregl.AttributionControl({ compact: true }), "top-right"); + const created = instance; + created.on("moveend", () => storeCamera(created)); instance.once("style.load", () => { instance?.setProjection({ type: "mercator" }); setRadarHostReady(true); @@ -332,7 +351,6 @@ export function App() { let nationalGeneration = 0; let nationalResident = false; let hiddenNationalRequestError: string | null = null; - let resumeNationalPlaybackAfterSiteFailure = false; const revealedNationalReports = new WeakSet(); let nationalMrmsSession: NationalMrmsSession | null = null; let lastNationalRestorationAfterSiteFailure: Promise | null = null; @@ -343,6 +361,7 @@ export function App() { let latestNationalPhase3: NationalPhase3Report | null = null; let staticNationalDiagnostic = false; let clickHandler: ((event: MapMouseEvent) => void) | null = null; + let autoSourceMoveHandlerForCleanup: ((event: { originalEvent?: unknown }) => void) | null = null; let latestReport: Phase4Report | null = null; let activeScenario: Promise | null = null; let startupAcquisition: Promise | null = null; @@ -750,7 +769,6 @@ export function App() { instance.on("click", clickHandler); setInterrogation(null); setInspectionState("idle"); - focusRadar(instance, diagnosticModel); globalThis.__MISTR_PHASE4__ = { report: () => ({ ...latestReport!, @@ -979,7 +997,6 @@ export function App() { paintedModel, createAlignmentReport(paintedModel), ); - if (!appendingHistory && !prependingHistory) focusRadar(instance, paintedModel); } catch (diagnosticError) { report = { ...report, @@ -1107,57 +1124,50 @@ export function App() { pollingSession: number; } | null = null; + const nextSiteGeneration = () => Math.max( + transferGeneration + 1, + (layer?.getSnapshot().generation ?? transferGeneration) + 1, + (nationalLayer?.getSnapshot().generation ?? transferGeneration) + 1, + ); + const startSiteFromNational = async ( site: string, generation: number, ): Promise => { if (!client) throw new Error("selected-site transfer client is unavailable"); const activeClient = client; - const assertSiteTransitionStillCurrent = () => { + const siteTransitionIsCurrent = () => { const transition = radarSessionCoordinatorRef.current!.snapshot().transition; - if ( - transition?.generation !== generation - || transition.requestedSource.kind !== "site" - || transition.requestedSource.siteIcao !== site - ) { - throw new RadarSourceSupersededError( - "Site transition was superseded while National activity settled", - ); - } + return transition?.generation === generation + && transition.requestedSource.kind === "site" + && transition.requestedSource.siteIcao === site; }; - assertSiteTransitionStillCurrent(); + if (!siteTransitionIsCurrent()) { + throw new RadarSourceSupersededError("Site transition was superseded before it began"); + } queuedScrubRef.current = null; - // National keeps acquiring on its own lane and becomes resident once - // the Site paints; only its playback settles here. - const playbackToSettle = nationalPlaybackController; - resumeNationalPlaybackAfterSiteFailure = playbackToSettle - ? await playbackToSettle.pauseAndWait(false) - : false; - assertSiteTransitionStillCurrent(); + // National keeps acquiring and playing on its own lane until the Site + // has faded in over it; then it becomes resident. + const prefetched = takePrefetchedSite(site, generation); transferGeneration = generation; livePollingSession += 1; const pollingSession = livePollingSession; - await activeClient.begin("site", generation); - if (failNextSiteFromNationalForDiagnostics) { - failNextSiteFromNationalForDiagnostics = false; - throw new Error("diagnostic Site transition failure after the Site lane began"); + let sweep: PrefetchedSiteSweep; + if (prefetched) { + sweep = prefetched; + } else { + await activeClient.begin("site", generation); + if (failNextSiteFromNationalForDiagnostics) { + failNextSiteFromNationalForDiagnostics = false; + throw new Error("diagnostic Site transition failure after the Site lane began"); + } + sweep = await acquireSiteSweep(activeClient, site, generation); } - const lease = await activeClient.requestPhase5Live(site, false, 180); + const { model, evidence } = sweep; + const fadeMs = sourceFadeMs(); let createdLayer: RadarCustomLayer | null = null; let createdController: ResidentPlaybackController | null = null; try { - const model = createRadarSweepCpuModel(lease.packed); - if (model.sourceKind !== "nexrad_level2_chunks" || model.siteIcao !== site) { - throw new Error("live response does not match the requested NEXRAD site/source"); - } - const evidence = await activeClient.phase5LiveEvidence(model.observationId); - if ( - evidence.observationId !== model.observationId - || evidence.safe.generation !== generation - || evidence.safe.site !== site - ) { - throw new Error("live evidence does not match the decoded response"); - } if (transferGeneration !== generation) { throw new RadarSourceSupersededError("Site bootstrap was superseded before GPU staging"); } @@ -1166,6 +1176,8 @@ export function App() { createdLayer = new RadarCustomLayer([model], { displayMode: displayModeRef.current, recoveryBeforeLayerId: ANCHOR_LAYER_ID, + // The first frame paints invisibly, then fades in over National. + opacity: fadeMs > 0 ? 0 : 1, onSnapshot(renderer) { setPlaybackError((current) => playbackErrorAfterRendererStatus(current, renderer.status)); synchronizePaintedDisplay(renderer); @@ -1193,6 +1205,12 @@ export function App() { if (transferGeneration !== generation || receipt.generation !== generation) { throw new RadarSourceSupersededError("Site bootstrap was superseded before paint acceptance"); } + const fadingLayer = createdLayer; + const faded = await fadeOpacity((value) => fadingLayer.setOpacity(value), 0, 1, { + durationMs: fadeMs, + isCurrent: () => siteTransitionIsCurrent() && transferGeneration === generation, + }); + if (!faded) throw new RadarSourceSupersededError("Site fade-in was superseded"); const nextHistory = beginLiveHistory(model, generation); residentLiveHistory = nextHistory; const cursor = { @@ -1206,7 +1224,7 @@ export function App() { display, evidence, receipt, - transferTiming: lease.timing, + transferTiming: sweep.timing, renderer: createdLayer.getSnapshot(), history: liveHistoryReport(nextHistory), }; @@ -1222,11 +1240,204 @@ export function App() { playbackControllerRef.current = null; } throw error; + } + }; + + const acquireSiteSweep = async ( + activeClient: PackedSweepTransferClient, + site: string, + generation: number, + ): Promise => { + const lease = await activeClient.requestPhase5Live(site, false, 180); + try { + const model = createRadarSweepCpuModel(lease.packed); + if (model.sourceKind !== "nexrad_level2_chunks" || model.siteIcao !== site) { + throw new Error("live response does not match the requested NEXRAD site/source"); + } + const evidence = await activeClient.phase5LiveEvidence(model.observationId); + if ( + evidence.observationId !== model.observationId + || evidence.safe.generation !== generation + || evidence.safe.site !== site + ) { + throw new Error("live evidence does not match the decoded response"); + } + return { site, generation, model, evidence, timing: lease.timing, fetchedAtUnixMs: Date.now() }; } finally { await lease.release(); } }; + // --- Automatic source switching ------------------------------------------ + // Zoom decides the source; only camera moves the operator makes (or an + // explicit picker/recenter flight) are evaluated, never programmatic ones. + let preferredSite: string | undefined; + let evaluateOnNextMove = false; + let pendingAutoEvaluation = false; + // An automatic switch may wait on a preload before its transition begins. + let autoSwitchInFlight = false; + let prefetchedSite: PrefetchedSiteSweep | null = null; + let prefetchInFlight: { site: string; promise: Promise } | null = null; + let prefetchSession = 0; + const autoSiteFailures = new Map(); + let lastAutoDecision: { target: AutoSource; preload?: string; atUnixMs: number } | null = null; + + const prefetchIsUsable = (sweep: PrefetchedSiteSweep | null, site: string) => Boolean( + sweep + && sweep.site === site + && Date.now() - sweep.fetchedAtUnixMs <= SITE_PREFETCH_MAX_AGE_MS + && client?.isActive("site") + && client.laneGeneration("site") === sweep.generation, + ); + + const takePrefetchedSite = (site: string, generation: number): PrefetchedSiteSweep | null => { + const sweep = prefetchedSite; + prefetchedSite = null; + prefetchSession += 1; + return sweep && sweep.generation === generation && prefetchIsUsable(sweep, site) ? sweep : null; + }; + + const prefetchSite = (site: string): Promise => { + const activeClient = client; + const snapshot = radarSessionCoordinatorRef.current!.snapshot(); + if ( + !activeClient + || cancelled + || snapshot.transition + || snapshot.painted?.source.kind !== "national" + || layer + || !radarSiteById(site) + ) return Promise.resolve(); + if (prefetchInFlight?.site === site) return prefetchInFlight.promise; + if (prefetchIsUsable(prefetchedSite, site)) return Promise.resolve(); + const token = ++prefetchSession; + prefetchedSite = null; + const generation = nextSiteGeneration(); + transferGeneration = generation; + const entry: { site: string; promise: Promise } = { site, promise: Promise.resolve() }; + entry.promise = (async () => { + try { + await beginSiteLane(activeClient, generation); + const sweep = await acquireSiteSweep(activeClient, site, generation); + if (token === prefetchSession) prefetchedSite = sweep; + } catch { + // Preloading is best-effort; the switch fetches if nothing is ready. + } finally { + if (prefetchInFlight === entry) prefetchInFlight = null; + } + })(); + prefetchInFlight = entry; + return entry.promise; + }; + + const startSiteSession = async (site: string, options: { persistOnPaint?: boolean } = {}) => { + if (!siteLevel2Session) throw new Error("selected-site session is unavailable"); + if (prefetchInFlight?.site === site) await prefetchInFlight.promise; + const residentGeneration = prefetchIsUsable(prefetchedSite, site) + ? prefetchedSite!.generation + : undefined; + return siteLevel2Session.start(site, { ...options, residentGeneration }); + }; + + const settleAutoSwitch = () => { + autoSwitchInFlight = false; + if (!pendingAutoEvaluation) return; + pendingAutoEvaluation = false; + evaluateAutoSource(); + }; + + const evaluateAutoSource = () => { + if (cancelled || !siteLevel2Session || !nationalMrmsSession) return; + const snapshot = radarSessionCoordinatorRef.current!.snapshot(); + if (snapshot.transition || autoSwitchInFlight) { + pendingAutoEvaluation = true; + return; + } + const painted = snapshot.painted; + if (!painted) return; + const visible: AutoSource = painted.source.kind === "national" + ? { kind: "national" } + : { kind: "site", siteIcao: painted.source.siteIcao }; + const center = instance.getCenter(); + const decision = decideAutoSource({ + zoom: instance.getZoom(), + center: { longitude: center.lng, latitude: center.lat }, + visible, + preferredSite, + }, RADAR_SITES); + lastAutoDecision = { ...decision, atUnixMs: Date.now() }; + if (sameAutoSource(decision.target, visible)) { + if (decision.preload) void prefetchSite(decision.preload); + return; + } + if (decision.target.kind === "national") { + autoSwitchInFlight = true; + void nationalMrmsSession.start().then(settleAutoSwitch, (error: unknown) => { + if (!isRadarSourceSuperseded(error)) { + setNationalRequestError(error instanceof Error ? error.message : String(error)); + } + settleAutoSwitch(); + }); + return; + } + const target = decision.target.siteIcao; + const failedAt = autoSiteFailures.get(target); + if (failedAt !== undefined && Date.now() - failedAt < AUTO_SITE_RETRY_MS) return; + autoSwitchInFlight = true; + void startSiteSession(target).then(settleAutoSwitch, (error: unknown) => { + if (!isRadarSourceSuperseded(error)) { + autoSiteFailures.set(target, Date.now()); + setSiteRequestError(error instanceof Error ? error.message : String(error)); + } + settleAutoSwitch(); + }); + }; + + const autoSourceMoveHandler = (event: { originalEvent?: unknown }) => { + if (!event.originalEvent && !evaluateOnNextMove) return; + evaluateOnNextMove = false; + evaluateAutoSource(); + }; + instance.on("moveend", autoSourceMoveHandler); + autoSourceMoveHandlerForCleanup = autoSourceMoveHandler; + autoSourceRef.current = { + setPreferredSite(site) { + preferredSite = site; + }, + prefetch(site) { + void prefetchSite(site); + }, + evaluateAfterNextMove() { + evaluateOnNextMove = true; + }, + }; + globalThis.__MISTR_AUTO_SOURCE__ = { + evaluate: evaluateAutoSource, + state: () => ({ + preferredSite: preferredSite ?? null, + lastDecision: lastAutoDecision, + prefetchedSite: prefetchedSite + ? { site: prefetchedSite.site, generation: prefetchedSite.generation, fetchedAtUnixMs: prefetchedSite.fetchedAtUnixMs } + : null, + prefetchInFlight: prefetchInFlight?.site ?? null, + siteOpacity: layer?.getOpacity() ?? null, + }), + prefetch: (site) => prefetchSite(normalizeRadarSite(site)), + }; + + const fadeOutSiteLayer = async (isCurrent: () => boolean) => { + const siteLayer = layer; + if (!siteLayer) return; + const faded = await fadeOpacity((value) => siteLayer.setOpacity(value), siteLayer.getOpacity(), 0, { + durationMs: sourceFadeMs(), + isCurrent, + }); + if (!faded) { + siteLayer.setOpacity(1); + throw new RadarSourceSupersededError("National switch was superseded during the fade"); + } + }; + const acceptSiteBootstrap = (report: Phase5Report) => { const pending = pendingSiteBootstrap; if (!pending || pending.report !== report) return; @@ -1245,7 +1456,6 @@ export function App() { inspectionPointRef.current = null; interrogationObservationRef.current = null; updateDiagnosticSources(instance, model, createAlignmentReport(model)); - focusRadar(instance, model); if (!hideNationalBehindSite()) teardownNational(); continueLiveBackfillAndPolling(model.siteIcao, pollingSession); radarSessionCoordinatorRef.current!.synchronizePaint( @@ -1260,13 +1470,10 @@ export function App() { || sourceState.transition || sourceState.painted?.source.kind !== "national" ) return; - // National never stopped acquiring on its lane; only the failed Site - // lane and the paused National playback need attention. + // National never stopped acquiring or playing; only the failed Site + // lane needs releasing. if (client?.isActive("site")) void client.cancel("site").catch(() => {}); - const resume = resumeNationalPlaybackAfterSiteFailure; - resumeNationalPlaybackAfterSiteFailure = false; const restoration = (async () => { - if (resume) await nationalPlaybackController?.play(); if (!latestNationalPhase3) throw new Error("National radar is no longer displayed"); return latestNationalPhase3; })(); @@ -1280,11 +1487,7 @@ export function App() { if (!layer) throw new Error("selected-site renderer is unavailable"); siteLevel2Session = new SiteLevel2Session({ coordinator: radarSessionCoordinatorRef.current!, - nextGeneration: () => Math.max( - transferGeneration + 1, - (layer?.getSnapshot().generation ?? transferGeneration) + 1, - (nationalLayer?.getSnapshot().generation ?? transferGeneration) + 1, - ), + nextGeneration: () => nextSiteGeneration(), acquireAndPaint: async (siteIcao, generation) => { // A National layer may exist only as partial staging while Site is // still the authoritative paint. Reuse that painted Site renderer @@ -1425,7 +1628,6 @@ export function App() { nationalPlaybackController?.pause(); activeLayer.setVisibility("resident"); nationalResident = true; - resumeNationalPlaybackAfterSiteFailure = false; nationalInspectionLookupQueueForCleanup?.cancelPending(); return true; }; @@ -1853,8 +2055,13 @@ export function App() { if (!receipt.presented || receipt.generation !== generation) { throw new Error("National reveal did not paint the resident history"); } + await fadeOutSiteLayer(() => { + const current = radarSessionCoordinatorRef.current!.snapshot().transition; + return current?.generation === generation && current.requestedSource.kind === "national"; + }); } catch (error) { if (nationalResident && nationalLayer === activeLayer) activeLayer.setVisibility("resident"); + layer?.setOpacity(1); throw error; } const report: NationalPhase3Report = { @@ -1904,7 +2111,6 @@ export function App() { inspectionRequestRef.current = null; nationalInspectionLookupQueue.cancelPending(); nationalPlaybackController?.acceptHistory(nationalObservations, report.workingSet.receipt); - focusNational(instance); }; nationalMrmsSession = new NationalMrmsSession({ @@ -1973,6 +2179,14 @@ export function App() { historyWorkingSet.receipt, ); ownershipCheck(); + await fadeOutSiteLayer(() => { + try { + ownershipCheck(); + return true; + } catch { + return false; + } + }); const workingSet = workingSetWithReceipt({ ...historyWorkingSet, receipt: authoritativeReceipt, @@ -2075,7 +2289,6 @@ export function App() { nationalInspectionLookupQueue.cancelPending(); removeSiteAfterNationalPaint(); setLiveHistoryStatus(staticNationalDiagnostic ? "partial" : "loading"); - focusNational(instance); if (!staticNationalDiagnostic) { void runNationalBackfill(report.workingSet.receipt.generation); } @@ -2593,6 +2806,7 @@ export function App() { activityBefore, activityAfter: await client.nationalHistoryActivitySnapshot(), revealMs, + fadeMs: sourceFadeMs(), }; } finally { release(); @@ -2802,6 +3016,9 @@ export function App() { if (playbackControllerRef.current === controller) playbackControllerRef.current = null; if (radarLayerRef.current === layer) radarLayerRef.current = null; if (clickHandler) instance.off("click", clickHandler); + if (autoSourceMoveHandlerForCleanup) instance.off("moveend", autoSourceMoveHandlerForCleanup); + autoSourceRef.current = null; + if (globalThis.__MISTR_AUTO_SOURCE__) delete globalThis.__MISTR_AUTO_SOURCE__; if (globalThis.__MISTR_PHASE4__) delete globalThis.__MISTR_PHASE4__; if (globalThis.__MISTR_PHASE5__) delete globalThis.__MISTR_PHASE5__; if (globalThis.__MISTR_PHASE6__) delete globalThis.__MISTR_PHASE6__; @@ -3017,6 +3234,21 @@ export function App() { inspectionPointRef.current = null; interrogationObservationRef.current = null; inspectionRequestRef.current = null; + // The picker flies to the Site; zoom then keeps it displayed. From National + // the Site preloads during the flight and the landing switches to it. + const auto = autoSourceRef.current; + auto?.setPreferredSite(normalized); + const instance = map.current; + const location = radarSiteById(normalized); + if (instance && location) { + auto?.evaluateAfterNextMove(); + flyToSite(instance, location); + } + const painted = radarSessionCoordinatorRef.current?.snapshot().painted; + if (auto && instance && location && painted?.source.kind === "national") { + auto.prefetch(normalized); + return; + } void session.start(normalized).then( () => { setSiteRequestError(null); @@ -3050,6 +3282,15 @@ export function App() { inspectionPointRef.current = null; interrogationObservationRef.current = null; inspectionRequestRef.current = null; + // Picking National zooms out to the country; the landing switches source. + const auto = autoSourceRef.current; + auto?.setPreferredSite(undefined); + const instance = map.current; + if (auto && instance) { + auto.evaluateAfterNextMove(); + flyToNational(instance); + return; + } void session.start().then( () => setNationalRequestError(null), (error: unknown) => { @@ -3061,12 +3302,14 @@ export function App() { const recenterRadar = () => { const instance = map.current; - if (instance && paintedRadarSource.kind === "national") { - focusNational(instance); + if (!instance) return; + autoSourceRef.current?.evaluateAfterNextMove(); + if (paintedRadarSource.kind === "national") { + flyToNational(instance); return; } - const model = radarModelRef.current; - if (instance && model) focusRadar(instance, model); + const location = radarSiteById(paintedRadarSource.siteIcao); + if (location) flyToSite(instance, location); }; const selectDisplayMode = (mode: RadarDisplayMode) => { @@ -3187,17 +3430,93 @@ function focusRadar(instance: MapLibreMap, model: RadarSweepCpuModel): void { ); } -function focusNational(instance: MapLibreMap): void { - instance.fitBounds( - [[-125.0, 24.0], [-66.5, 50.0]], - { - bearing: 0, - duration: 0, - maxZoom: 5.5, - padding: { top: 100, right: 88, bottom: 124, left: 88 }, - pitch: 0, - }, - ); +interface AutoSourceHandle { + setPreferredSite(site: string | undefined): void; + prefetch(site: string): void; + evaluateAfterNextMove(): void; +} + +interface PrefetchedSiteSweep { + site: string; + generation: number; + model: RadarSweepCpuModel; + evidence: Phase5LiveTransferEvidence; + timing: TransferTiming; + fetchedAtUnixMs: number; +} + +function prefersReducedMotion(): boolean { + try { + return globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false; + } catch { + return false; + } +} + +function sourceFadeMs(): number { + return prefersReducedMotion() ? 0 : SOURCE_FADE_MS; +} + +function flyToSite(instance: MapLibreMap, site: RadarSiteOption): void { + instance.flyTo({ + center: [site.longitude, site.latitude], + zoom: Math.max(instance.getZoom(), SITE_DETAIL_ZOOM), + bearing: 0, + pitch: 0, + duration: prefersReducedMotion() ? 0 : CAMERA_FLIGHT_MS, + essential: true, + }); +} + +function flyToNational(instance: MapLibreMap): void { + instance.fitBounds(CONUS_BOUNDS, { + bearing: 0, + pitch: 0, + maxZoom: 5.5, + padding: CAMERA_PADDING, + duration: prefersReducedMotion() ? 0 : CAMERA_FLIGHT_MS, + }); +} + +function initialMapCamera( + startupSource: RadarSourceKey, +): Pick { + const stored = restoreCamera(); + if (stored) return stored; + if (startupSource.kind === "site") { + const site = radarSiteById(startupSource.siteIcao); + if (site) return { center: [site.longitude, site.latitude], zoom: SITE_DETAIL_ZOOM }; + return { center: DEFAULT_CENTER, zoom: SITE_DETAIL_ZOOM }; + } + return { bounds: CONUS_BOUNDS, fitBoundsOptions: { padding: CAMERA_PADDING, maxZoom: 5.5 } }; +} + +function restoreCamera(): { center: [number, number]; zoom: number } | null { + try { + const value = JSON.parse(globalThis.localStorage?.getItem(CAMERA_STORAGE_KEY) ?? "null"); + if ( + value + && Number.isFinite(value.longitude) && Math.abs(value.longitude) <= 180 + && Number.isFinite(value.latitude) && Math.abs(value.latitude) <= 85 + && Number.isFinite(value.zoom) && value.zoom >= 0 && value.zoom <= 22 + ) return { center: [value.longitude, value.latitude], zoom: value.zoom }; + } catch { + // A missing or malformed camera falls back to the startup source. + } + return null; +} + +function storeCamera(instance: MapLibreMap): void { + try { + const center = instance.getCenter(); + globalThis.localStorage?.setItem(CAMERA_STORAGE_KEY, JSON.stringify({ + longitude: center.lng, + latitude: center.lat, + zoom: instance.getZoom(), + })); + } catch { + // Camera memory is a convenience; storage failure changes nothing else. + } } function mapBounds(instance: MapLibreMap) { @@ -3581,6 +3900,7 @@ export interface NationalPhase4ResidentHandoffReport { activityBefore: NationalHistoryActivitySnapshot; activityAfter: NationalHistoryActivitySnapshot; revealMs: number; + fadeMs: number; } | undefined; after: RadarSessionSnapshot; renderer: NationalGridRendererSnapshot | null; @@ -3870,6 +4190,17 @@ declare global { sourceState(): import("./radar-session/RadarSessionCoordinator").RadarSessionSnapshot | null; isolateRadarForEvidence(): void; }; + var __MISTR_AUTO_SOURCE__: undefined | { + evaluate(): void; + state(): { + preferredSite: string | null; + lastDecision: { target: AutoSource; preload?: string; atUnixMs: number } | null; + prefetchedSite: { site: string; generation: number; fetchedAtUnixMs: number } | null; + prefetchInFlight: string | null; + siteOpacity: number | null; + }; + prefetch(site: string): Promise; + }; var __MISTR_NATIONAL_PHASE4__: undefined | { report(): NationalPhase4Report; startNational(): Promise; diff --git a/src/radar-session/SiteLevel2Session.ts b/src/radar-session/SiteLevel2Session.ts index 8b11e5c..29c1488 100644 --- a/src/radar-session/SiteLevel2Session.ts +++ b/src/radar-session/SiteLevel2Session.ts @@ -28,6 +28,8 @@ export type SiteLevel2AcquireAndPaint = ( export interface SiteLevel2StartOptions { readonly persistOnPaint?: boolean; + /** Reuse the generation of a Site scan already fetched ahead of the switch. */ + readonly residentGeneration?: number; } /** @@ -71,7 +73,7 @@ export class SiteLevel2Session { const transition = this.coordinator.beginTransition( source, this.nextGeneration(), - { persistOnPaint: options.persistOnPaint }, + { persistOnPaint: options.persistOnPaint, residentGeneration: options.residentGeneration }, ); try { const result = await acquireAndPaint(source.siteIcao, transition.generation); From 93f5f85116a5fc301a0c0f938a4992a0cc9536b7 Mon Sep 17 00:00:00 2001 From: Travis Curtsinger <93950613+tcurtsinger@users.noreply.github.com> Date: Mon, 28 Sep 2026 13:54:16 -0500 Subject: [PATCH 4/8] Prove the zoom-driven handoff in the packaged National gate proveZoomHandoff preloads KTLX at zoom 8.3, requires zoom 9.6 to fade the preloaded Site in over resident National without moving the camera, and zoom 7.5 to fade back to the same National history with the Site removed. The resident-handoff timing allows for the deliberate fade-out. docs/32 records the Phase B policy, switching, camera, and known limits; PRODUCT and DESIGN note that zoom now decides the source. Co-Authored-By: Claude Opus 5.5 --- DESIGN.md | 2 +- PRODUCT.md | 2 + docs/32_SEAMLESS_RADAR_HANDOFF.md | 40 +++++++++++ scripts/national-phase4-packaged-cdp.mjs | 7 ++ .../national-phase4-packaged-validation.mjs | 40 +++++++++++ ...tional-phase4-packaged-validation.test.mjs | 57 +++++++++++++++ src/App.tsx | 71 +++++++++++++++++++ 7 files changed, 218 insertions(+), 1 deletion(-) diff --git a/DESIGN.md b/DESIGN.md index d34a49b..77cb982 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -173,7 +173,7 @@ A 10px status mark beside the frame age shows that a notice exists without a banner: a hollow Scan Cyan ring for information, a solid Danger dot for a problem. Hovering or focusing it reveals the notice text above the playback bar. -- **Top changes where and how radar is drawn:** explicit National/Site source selection, Site station selection, source-aware recenter, and the real `Smooth`/`Native` spatial display choice; other controls appear only after they become real capabilities. +- **Top changes where and how radar is drawn:** explicit National/Site source selection, Site station selection, source-aware recenter, and the real `Smooth`/`Native` spatial display choice; other controls appear only after they become real capabilities. *(Owner decision, 2026-09-28: zoom decides the source — picking a Site flies to it at zoom 9.5, picking National zooms out to the country, and zooming across ~9 cross-fades between them. See [docs/32](docs/32_SEAMLESS_RADAR_HANDOFF.md).)* - **Sides stay clear:** no application menu, placeholder alert control, or control chain competes with radar. - **Bottom controls when:** playback, measured time, numeric age, and inspection value. diff --git a/PRODUCT.md b/PRODUCT.md index b867c55..671cece 100644 --- a/PRODUCT.md +++ b/PRODUCT.md @@ -26,6 +26,8 @@ The product earns additional capabilities only when they improve live storm insp ## Approved National Direction +*Owner decision (2026-09-28): zoom decides the source. Zooming past about 9 over a Site's coverage cross-fades to that Site; zooming out returns to the resident National mosaic. See [Seamless radar handoff](docs/32_SEAMLESS_RADAR_HANDOFF.md).* + National radar is the approved next product milestone. Merged Phases 1 through 4 established the typed source coordinator, strict NOAA MRMS acquisition and numeric decoding, `PackedGrid v1`, the explicit `National`/`Site` choice, a 20-observation CONUS loop, exact Rust-owned interrogation, quality-locked playback, and atomic source handoff. Phase 4 is merged. National now provides 20 exact chronological observations, newest-first visible startup, predecessor backfill, strictly newer polling, bounded all-frame overview residency, direct scrubbing, and common-quality playback. Once two complete observations are usable, background backfill keeps Play and direct scrubbing available; only the bounded atomic residency swap or graphics recovery may hold those controls briefly. A post-merge visual-fidelity correction prepares the finest complete all-frame viewport level that fits the 200 MiB GPU target before regional playback begins: exact factor 1 first, factor 2 as the bounded fallback, and factor 4 only for the country overview or when finer all-frame coverage cannot fit. Smooth and Native use the same selected numeric level; Smooth filters its appearance but never invents source resolution. The approved phased product and engineering contract is [National Radar Implementation Plan](docs/26_NATIONAL_RADAR_IMPLEMENTATION_PLAN.md). diff --git a/docs/32_SEAMLESS_RADAR_HANDOFF.md b/docs/32_SEAMLESS_RADAR_HANDOFF.md index 46e39b6..c9784b1 100644 --- a/docs/32_SEAMLESS_RADAR_HANDOFF.md +++ b/docs/32_SEAMLESS_RADAR_HANDOFF.md @@ -49,3 +49,43 @@ The Site layer gains a 320 MiB GPU ceiling (a 60-frame loop is about 152 MiB, ab - Unit: broker lane isolation (Rust), client lane isolation, coordinator/session reveal, and a fake-WebGL state-machine suite for hidden commits, reveal, downgrade, a hidden fence finishing after reveal, recovery while hidden, and reveal waiting out a commit. - Packaged (`npm run test:national:phase4:packaged`): `proveFailedSiteKeepsNational` (same generation, no backfill restart, playback resumed) and `proveResidentHandoff` (National resident while the Site paints; reveal under the original generation with zero network, decode, and bulk IPC activity within 250 ms; the Site layer removed). + +## Phase B — zoom decides the source + +**Date:** 2026-09-28. **Status:** Implemented; native packaged validation pending. + +### Policy + +`decideAutoSource` (`src/radar-session/autoSourcePolicy.ts`) is a pure function of zoom, view center, the displayed source, and the operator's picked Site: + +| Condition | Result | +|---|---| +| National shown, zoom ≥ 9, a Site within 200 km of the center | Switch to the nearest such Site (or the picked Site while within 230 km) | +| National shown, zoom ≥ 8 and < 9, same Site condition | Stay on National; preload that Site | +| Site shown, zoom ≥ 8.5 and center within 230 km of it | Stay on the Site | +| Site shown, otherwise | Return to National | + +Moving between Sites always passes through National, so only one Site layer exists. Site coordinates live in `src/data/radar-sites.json`: 150 from nexrad-model's registry (a Rust test keeps them in sync) and 5 from api.weather.gov. + +Only camera moves the operator makes are evaluated (MapLibre events with an `originalEvent`), plus the landing of an explicit picker or recenter flight. Programmatic cameras, including every packaged harness camera, never switch sources. + +### Switching + +- **Preload:** the likely Site's newest scan is fetched on the Site lane while National is shown. The switch reuses that generation (`SiteLevel2Session.start({ residentGeneration })`) and paints without a network wait. A preload older than 5 minutes is refetched. +- **Fade in:** the Site's first frame paints at `u_opacity = 0`, then fades to 1 over 300 ms (instant under reduced motion). Only then does the coordinator accept it, so the timeline follows a fully visible frame. National keeps playing underneath until it becomes resident. +- **Fade out:** National paints underneath first (a reveal, or a fresh acquisition), then the Site fades to 0 and is removed. +- **Layer order:** National is always inserted, and re-inserted after context loss, below the Site stack, so only the upper layer fades. +- **Guards:** one automatic switch runs at a time; a Site that just failed is not retried automatically for a minute. + +### Camera + +Automatic switches never move the camera. The picker flies to a Site at zoom 9.5 (preloading during the flight when National is shown) and makes it preferred; picking National zooms out to the country; recenter uses the same targets. The camera is stored on every move and restored at launch. + +### Known limits + +- At the end of a fade-in, National disappears everywhere, including outside the Site's range ring, so corners of a wide view briefly lose echo. +- Playback time is not yet carried across a switch (Phase C); a Site starts at its newest scan. + +### Validation + +`proveZoomHandoff` in the National packaged gate: at zoom 8.3 over KTLX the Site preloads; at 9.6 the Site fades in under the preloaded generation with National resident and the camera untouched; at 7.5 the same National history returns, the Site layer is removed, and the camera is untouched. diff --git a/scripts/national-phase4-packaged-cdp.mjs b/scripts/national-phase4-packaged-cdp.mjs index b50acc7..94cd21f 100644 --- a/scripts/national-phase4-packaged-cdp.mjs +++ b/scripts/national-phase4-packaged-cdp.mjs @@ -233,6 +233,12 @@ try { 300_000, ); + const zoomHandoff = await evaluate( + serialized("window.__MISTR_NATIONAL_PHASE4__.proveZoomHandoff('KTLX')"), + true, + 300_000, + ); + await evaluate(serialized("window.__MISTR_NATIONAL_PHASE4__.startSite('KTLX')"), true, 300_000); await delay(500); const restoredSite = { @@ -258,6 +264,7 @@ try { transferSnapshot, failedSiteRecovery, residentHandoff, + zoomHandoff, restoredSite, }; report.failures = validateNationalPhase4Acceptance(report); diff --git a/scripts/national-phase4-packaged-validation.mjs b/scripts/national-phase4-packaged-validation.mjs index b67a338..f57236a 100644 --- a/scripts/national-phase4-packaged-validation.mjs +++ b/scripts/national-phase4-packaged-validation.mjs @@ -157,6 +157,7 @@ export function validateNationalPhase4Acceptance(report) { || failedSite?.renderer?.contextEpoch !== failedSite?.rendererBeforeFailure?.contextEpoch ) failures.push("failed Site transition keeps the active National session"); failures.push(...validateResidentHandoff(report.residentHandoff)); + failures.push(...validateZoomHandoff(report.zoomHandoff)); const site = report.restoredSite; if ( site?.sourceState?.painted?.source?.kind !== "site" @@ -214,6 +215,45 @@ export function validateResidentHandoff(handoff) { return failures; } +function sameCamera(left, right) { + return Boolean(left && right) + && Math.abs(left.longitude - right.longitude) < 1e-6 + && Math.abs(left.latitude - right.latitude) < 1e-6 + && Math.abs(left.zoom - right.zoom) < 1e-6; +} + +// Zooming in past the threshold fades the preloaded Site in over resident +// National; zooming out fades back to that same National history. Neither +// switch moves the camera. +export function validateZoomHandoff(handoff) { + const failures = []; + const site = handoff?.site; + const preloaded = handoff?.preloaded; + const afterSite = handoff?.afterSite; + const fadeMs = handoff?.fadeMs ?? 0; + if ( + !site + || preloaded?.site !== site + || afterSite?.sourceState?.painted?.source?.kind !== "site" + || afterSite?.sourceState?.painted?.source?.siteIcao !== site + || afterSite?.sourceState?.painted?.generation !== preloaded?.generation + || afterSite?.siteOpacity !== 1 + || afterSite?.nationalRenderer?.visibility !== "resident" + || !sameCamera(afterSite?.camera, afterSite?.cameraSet) + || !(handoff?.siteSwitchMs >= 0 && handoff.siteSwitchMs <= 1_500 + fadeMs) + ) failures.push("zooming in fades the preloaded Site in without moving the camera"); + const afterNational = handoff?.afterNational; + if ( + afterNational?.sourceState?.painted?.source?.kind !== "national" + || afterNational?.sourceState?.painted?.generation !== handoff?.nationalGenerationBefore + || afterNational?.siteLayerPresent !== false + || afterNational?.nationalRenderer?.visibility !== "visible" + || !sameCamera(afterNational?.camera, afterNational?.cameraSet) + || !(handoff?.nationalSwitchMs >= 0 && handoff.nationalSwitchMs <= 750 + fadeMs) + ) failures.push("zooming out fades back to the resident National without moving the camera"); + return failures; +} + export function validateNationalPartialPlaybackChrome(chrome) { const failures = []; if (!stablePlaybackChrome(chrome)) failures.push("stable partial-history playback chrome"); diff --git a/scripts/national-phase4-packaged-validation.test.mjs b/scripts/national-phase4-packaged-validation.test.mjs index 378cc2f..f1682fa 100644 --- a/scripts/national-phase4-packaged-validation.test.mjs +++ b/scripts/national-phase4-packaged-validation.test.mjs @@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"; import { validateNationalPhase4Acceptance, validateResidentHandoff, + validateZoomHandoff, } from "./national-phase4-packaged-validation.mjs"; function nationalActivity() { @@ -91,6 +92,40 @@ describe("National Phase 4 packaged acceptance", () => { ); }); + it("requires zoom to fade between the preloaded Site and resident National without moving the camera", () => { + expect(validateZoomHandoff(validReport().zoomHandoff)).toEqual([]); + + const unpreloaded = validReport().zoomHandoff; + unpreloaded.afterSite.sourceState.painted.generation = 14; + expect(validateZoomHandoff(unpreloaded)).toContain( + "zooming in fades the preloaded Site in without moving the camera", + ); + + const moved = validReport().zoomHandoff; + moved.afterSite.camera.zoom = 7.5; + expect(validateZoomHandoff(moved)).toContain( + "zooming in fades the preloaded Site in without moving the camera", + ); + + const reacquired = validReport().zoomHandoff; + reacquired.afterNational.sourceState.painted.generation = 15; + expect(validateZoomHandoff(reacquired)).toContain( + "zooming out fades back to the resident National without moving the camera", + ); + + const lingering = validReport().zoomHandoff; + lingering.afterNational.siteLayerPresent = true; + expect(validateZoomHandoff(lingering)).toContain( + "zooming out fades back to the resident National without moving the camera", + ); + + const report = validReport(); + delete report.zoomHandoff; + expect(validateNationalPhase4Acceptance(report)).toContain( + "zooming in fades the preloaded Site in without moving the camera", + ); + }); + it("permits bounded exact point refresh while sharp playback stays transfer-free", () => { const report = validReport(); report.activePlayback.activityAfter.pointLookupDecodes = 8; @@ -358,6 +393,28 @@ function validReport() { backfillStartCountAfter: 1, siteLayerRemoved: true, }, + zoomHandoff: { + site: "KTLX", + fadeMs: 300, + nationalGenerationBefore: 8, + preloaded: { site: "KTLX", generation: 13, fetchedAtUnixMs: 1 }, + siteSwitchMs: 420, + afterSite: { + sourceState: { painted: { source: { kind: "site", siteIcao: "KTLX" }, generation: 13 } }, + camera: { longitude: -97.2778, latitude: 35.3331, zoom: 9.6 }, + cameraSet: { longitude: -97.2778, latitude: 35.3331, zoom: 9.6 }, + siteOpacity: 1, + nationalRenderer: { visibility: "resident" }, + }, + nationalSwitchMs: 340, + afterNational: { + sourceState: { painted: { source: { kind: "national", domain: "conus" }, generation: 8 } }, + camera: { longitude: -97.2778, latitude: 35.3331, zoom: 7.5 }, + cameraSet: { longitude: -97.2778, latitude: 35.3331, zoom: 7.5 }, + siteLayerPresent: false, + nationalRenderer: { visibility: "visible" }, + }, + }, restoredSite: { sourceState: { painted: { source: { kind: "site", siteIcao: "KTLX" } }, transition: null }, display: { lastComplete: { site: "KTLX" } }, diff --git a/src/App.tsx b/src/App.tsx index d86465a..9de31f3 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -2825,6 +2825,76 @@ export function App() { siteLayerRemoved: !instance.getLayer(DIAGNOSTIC_LAYER_IDS.radar), }; }, + async proveZoomHandoff(site = "KTLX") { + const location = radarSiteById(normalizeRadarSite(site)); + const auto = globalThis.__MISTR_AUTO_SOURCE__; + if (!location || !auto || !nationalLayer) { + throw new Error("zoom handoff diagnostic is unavailable"); + } + const coordinator = radarSessionCoordinatorRef.current!; + if (coordinator.snapshot().painted?.source.kind !== "national") { + throw new Error("National must be displayed before the zoom handoff proof"); + } + const waitFor = async (condition: () => boolean, timeoutMs: number, label: string) => { + const started = performance.now(); + while (!condition()) { + if (performance.now() - started > timeoutMs) throw new Error(`${label} timed out`); + await waitMilliseconds(50); + } + }; + const camera = () => { + const center = instance.getCenter(); + return { longitude: center.lng, latitude: center.lat, zoom: instance.getZoom() }; + }; + const settled = (kind: "site" | "national") => { + const snapshot = coordinator.snapshot(); + return !snapshot.transition && snapshot.painted?.source.kind === kind; + }; + const nationalGenerationBefore = nationalGeneration; + const center: [number, number] = [location.longitude, location.latitude]; + + instance.jumpTo({ center, zoom: 8.3, bearing: 0, pitch: 0 }); + auto.evaluate(); + await waitFor(() => auto.state().prefetchedSite?.site === location.id, 120_000, "Site preload"); + const preloaded = auto.state().prefetchedSite; + + instance.jumpTo({ center, zoom: 9.6, bearing: 0, pitch: 0 }); + const siteCameraSet = camera(); + const siteStarted = performance.now(); + auto.evaluate(); + await waitFor(() => settled("site"), 60_000, "zoom-in switch"); + const siteSwitchMs = performance.now() - siteStarted; + const afterSite = { + sourceState: coordinator.snapshot(), + camera: camera(), + cameraSet: siteCameraSet, + siteOpacity: layer?.getOpacity() ?? null, + nationalRenderer: nationalLayer?.getSnapshot() ?? null, + }; + + instance.jumpTo({ center, zoom: 7.5, bearing: 0, pitch: 0 }); + const nationalCameraSet = camera(); + const nationalStarted = performance.now(); + auto.evaluate(); + await waitFor(() => settled("national"), 60_000, "zoom-out switch"); + const nationalSwitchMs = performance.now() - nationalStarted; + return { + site: location.id, + fadeMs: sourceFadeMs(), + nationalGenerationBefore, + preloaded, + siteSwitchMs, + afterSite, + nationalSwitchMs, + afterNational: { + sourceState: coordinator.snapshot(), + camera: camera(), + cameraSet: nationalCameraSet, + siteLayerPresent: Boolean(instance.getLayer(DIAGNOSTIC_LAYER_IDS.radar)), + nationalRenderer: nationalLayer?.getSnapshot() ?? null, + }, + }; + }, async waitForHistory(frameCount = MAX_LIVE_HISTORY_FRAMES, timeoutMs = 300_000) { if (!Number.isSafeInteger(frameCount) || frameCount < 1 || frameCount > MAX_LIVE_HISTORY_FRAMES) { throw new RangeError("National history wait requires 1 to 60 observations"); @@ -4207,6 +4277,7 @@ declare global { startSite(site?: string): Promise; proveFailedSiteKeepsNational(site?: string): Promise; proveResidentHandoff(site?: string): Promise; + proveZoomHandoff(site?: string): Promise; waitForHistory(frameCount?: number, timeoutMs?: number): Promise; beginResidentEvidence(): Promise; endResidentEvidence(): void; From 6d0b801e8abd1a192e760c7dea2e471312df9629 Mon Sep 17 00:00:00 2001 From: Travis Curtsinger <93950613+tcurtsinger@users.noreply.github.com> Date: Mon, 28 Sep 2026 13:55:32 -0500 Subject: [PATCH 5/8] Switch source even when a picker or recenter flight has nowhere to go A flight to where the camera already is may never emit moveend, so the landing evaluation never ran. The picker, National choice, and recenter now evaluate immediately when the camera is not moving after the call. Co-Authored-By: Claude Opus 5.5 --- src/App.tsx | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index 9de31f3..d2a169e 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1410,6 +1410,12 @@ export function App() { evaluateAfterNextMove() { evaluateOnNextMove = true; }, + evaluateIfSettled() { + // A flight to where the camera already is may never emit moveend. + if (instance.isMoving()) return; + evaluateOnNextMove = false; + evaluateAutoSource(); + }, }; globalThis.__MISTR_AUTO_SOURCE__ = { evaluate: evaluateAutoSource, @@ -3317,6 +3323,7 @@ export function App() { const painted = radarSessionCoordinatorRef.current?.snapshot().painted; if (auto && instance && location && painted?.source.kind === "national") { auto.prefetch(normalized); + auto.evaluateIfSettled(); return; } void session.start(normalized).then( @@ -3359,6 +3366,7 @@ export function App() { if (auto && instance) { auto.evaluateAfterNextMove(); flyToNational(instance); + auto.evaluateIfSettled(); return; } void session.start().then( @@ -3376,10 +3384,11 @@ export function App() { autoSourceRef.current?.evaluateAfterNextMove(); if (paintedRadarSource.kind === "national") { flyToNational(instance); - return; + } else { + const location = radarSiteById(paintedRadarSource.siteIcao); + if (location) flyToSite(instance, location); } - const location = radarSiteById(paintedRadarSource.siteIcao); - if (location) flyToSite(instance, location); + autoSourceRef.current?.evaluateIfSettled(); }; const selectDisplayMode = (mode: RadarDisplayMode) => { @@ -3504,6 +3513,7 @@ interface AutoSourceHandle { setPreferredSite(site: string | undefined): void; prefetch(site: string): void; evaluateAfterNextMove(): void; + evaluateIfSettled(): void; } interface PrefetchedSiteSweep { From c60321dd4056e5d0548708e65bc6b887ac64b82b Mon Sep 17 00:00:00 2001 From: Travis Curtsinger <93950613+tcurtsinger@users.noreply.github.com> Date: Mon, 28 Sep 2026 13:59:17 -0500 Subject: [PATCH 6/8] Isolate the sharp-playback evidence window from background acquisition The packaged gate released its resident-evidence reservation before measuring active playback, so a newer MRMS frame committing during the 1.5 s window (every ~2 minutes) failed "zero sharp-playback transfer and upload work". The measurement now holds the same reservation the scrub evidence uses. Co-Authored-By: Claude Opus 5.5 --- scripts/national-phase4-packaged-cdp.mjs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/scripts/national-phase4-packaged-cdp.mjs b/scripts/national-phase4-packaged-cdp.mjs index 94cd21f..b48bd45 100644 --- a/scripts/national-phase4-packaged-cdp.mjs +++ b/scripts/national-phase4-packaged-cdp.mjs @@ -170,6 +170,15 @@ try { ); const detailScreenshot = await captureScreenshot(); + // Hold background acquisition off for the measurement, as the scrub + // evidence does: a newer MRMS frame arriving is product behavior, not + // work done by sharp playback. + await evaluate( + "window.__MISTR_NATIONAL_PHASE4__.beginResidentEvidence()", + true, + 300_000, + ); + residentEvidenceHeld = true; await evaluate("window.__MISTR_NATIONAL_PHASE4__.play()", true, 300_000); await waitForReport( "report.playback?.playing===true && report.renderer?.presentationFactor===1", @@ -202,6 +211,8 @@ try { true, 60_000, ); + await evaluate("window.__MISTR_NATIONAL_PHASE4__.endResidentEvidence()"); + residentEvidenceHeld = false; const activePlayback = { ...activePlaybackDuring, activityBefore: playbackActivityBefore, From 887f77e19eb276d4545a4d0e724d7b9360e61358 Mon Sep 17 00:00:00 2001 From: Travis Curtsinger <93950613+tcurtsinger@users.noreply.github.com> Date: Mon, 28 Sep 2026 14:03:46 -0500 Subject: [PATCH 7/8] Record every inspection readout change in the partial-history chrome gate Exact point lookups now settle within one 16 ms polling interval, so the gate could miss the neutral "--.- dBZ" pending state entirely and fail at random. A MutationObserver on the playback bar records every readout change during the window; the gate's requirements are unchanged. Co-Authored-By: Claude Opus 5.5 --- scripts/national-phase4-packaged-cdp.mjs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/scripts/national-phase4-packaged-cdp.mjs b/scripts/national-phase4-packaged-cdp.mjs index b48bd45..944bcb9 100644 --- a/scripts/national-phase4-packaged-cdp.mjs +++ b/scripts/national-phase4-packaged-cdp.mjs @@ -398,6 +398,20 @@ async function observePlaybackChrome(durationMs) { return value?{left:value.left,top:value.top,width:value.width,height:value.height}:null; }; const samples=[]; + // Exact point lookups can settle within one polling interval, so also + // record every readout change as it happens. + const observed=[]; + const readout=()=>{ + const sample=document.querySelector('.sample-readout'); + return { + sampleText:sample?.textContent?.trim()??'', + sampleState:sample?.dataset.inspectionState??null, + sampleBusy:sample?.getAttribute('aria-busy')??null, + }; + }; + const observer=new MutationObserver(()=>observed.push(readout())); + const bar=document.querySelector('.playback-bar'); + if(bar) observer.observe(bar,{subtree:true,childList:true,characterData:true,attributes:true,attributeFilter:['data-inspection-state','aria-busy']}); const deadline=performance.now()+${durationMs}; while(performance.now()sample.sampleState==='pending'); + observer.disconnect(); + const readouts=[...samples,...observed]; + const pending=readouts.filter(sample=>sample.sampleState==='pending'); return { innerWidth, innerHeight, @@ -444,7 +460,8 @@ async function observePlaybackChrome(durationMs) { timelineMaxRectDelta:maxRectDelta('timeline'), telemetryMaxRectDelta:maxRectDelta('telemetry'), sampleReadoutMaxRectDelta:maxRectDelta('sampleReadout'), - distinctSampleTexts:[...new Set(samples.map(sample=>sample.sampleText))], + observedReadoutChangeCount:observed.length, + distinctSampleTexts:[...new Set(readouts.map(sample=>sample.sampleText))], distinctAnnouncements:[...new Set(samples.map(sample=>sample.announcement))], }; })()`), true, durationMs + 30_000); From 2d5cd1fc11cff1f684ff8881b08cc4a6cca4e60f Mon Sep 17 00:00:00 2001 From: Travis Curtsinger <93950613+tcurtsinger@users.noreply.github.com> Date: Mon, 28 Sep 2026 14:37:36 -0500 Subject: [PATCH 8/8] Finish Site-to-Site hops and route every pick through the zoom policy - A switch that succeeds re-checks the same camera, so a pan from one Site's coverage into another's runs both legs (Site, National, Site) from one camera move instead of stopping on National. - A camera move made during a manual switch is evaluated once that switch ends. - Picking a Site while another Site is shown flies there and fades through National, instead of replacing the frames in place. The policy now hops a displayed Site to National when a different picked Site covers the center at detail zoom, and drops a pick once the view leaves its range. - Picking National always flies out to the country, even when National is already shown. - The packaged zoom proof adds a KTLX to KFWS pan and requires the KTLX > national > KFWS sequence with the camera untouched. Co-Authored-By: Claude Opus 5.5 --- docs/32_SEAMLESS_RADAR_HANDOFF.md | 9 +- .../national-phase4-packaged-validation.mjs | 14 +++ ...tional-phase4-packaged-validation.test.mjs | 23 ++++ src/App.tsx | 105 +++++++++++++----- src/radar-session/autoSourcePolicy.test.ts | 32 ++++++ src/radar-session/autoSourcePolicy.ts | 30 +++-- 6 files changed, 172 insertions(+), 41 deletions(-) diff --git a/docs/32_SEAMLESS_RADAR_HANDOFF.md b/docs/32_SEAMLESS_RADAR_HANDOFF.md index c9784b1..3eae31f 100644 --- a/docs/32_SEAMLESS_RADAR_HANDOFF.md +++ b/docs/32_SEAMLESS_RADAR_HANDOFF.md @@ -62,12 +62,13 @@ The Site layer gains a 320 MiB GPU ceiling (a 60-frame loop is about 152 MiB, ab |---|---| | National shown, zoom ≥ 9, a Site within 200 km of the center | Switch to the nearest such Site (or the picked Site while within 230 km) | | National shown, zoom ≥ 8 and < 9, same Site condition | Stay on National; preload that Site | +| Site shown, zoom ≥ 9, a different picked Site within 230 km of the center | Return to National (then on to the picked Site) | | Site shown, zoom ≥ 8.5 and center within 230 km of it | Stay on the Site | | Site shown, otherwise | Return to National | -Moving between Sites always passes through National, so only one Site layer exists. Site coordinates live in `src/data/radar-sites.json`: 150 from nexrad-model's registry (a Rust test keeps them in sync) and 5 from api.weather.gov. +Moving between Sites always passes through National, so only one Site layer exists. A switch that succeeds re-checks the same camera, so one pan into another Site's coverage runs both legs. A pick stops applying once the center leaves its 230 km range. Site coordinates live in `src/data/radar-sites.json`: 150 from nexrad-model's registry (a Rust test keeps them in sync) and 5 from api.weather.gov. -Only camera moves the operator makes are evaluated (MapLibre events with an `originalEvent`), plus the landing of an explicit picker or recenter flight. Programmatic cameras, including every packaged harness camera, never switch sources. +Only camera moves the operator makes are evaluated (MapLibre events with an `originalEvent`), plus the landing of an explicit picker or recenter flight. A move made while any switch is running is evaluated once it ends. Programmatic cameras, including every packaged harness camera, never switch sources. ### Switching @@ -79,7 +80,7 @@ Only camera moves the operator makes are evaluated (MapLibre events with an `ori ### Camera -Automatic switches never move the camera. The picker flies to a Site at zoom 9.5 (preloading during the flight when National is shown) and makes it preferred; picking National zooms out to the country; recenter uses the same targets. The camera is stored on every move and restored at launch. +Automatic switches never move the camera. The picker flies to a Site at zoom 9.5 (preloading during the flight when National is shown) and makes it preferred, so the landing switches to it from National or from another Site; picking National always zooms out to the country, even when National is already shown; recenter uses the same targets. The camera is stored on every move and restored at launch. ### Known limits @@ -88,4 +89,4 @@ Automatic switches never move the camera. The picker flies to a Site at zoom 9.5 ### Validation -`proveZoomHandoff` in the National packaged gate: at zoom 8.3 over KTLX the Site preloads; at 9.6 the Site fades in under the preloaded generation with National resident and the camera untouched; at 7.5 the same National history returns, the Site layer is removed, and the camera is untouched. +`proveZoomHandoff` in the National packaged gate: at zoom 8.3 over KTLX the Site preloads; at 9.6 the Site fades in under the preloaded generation with National resident and the camera untouched; one jump to KFWS at 9.6 goes KTLX, National, KFWS with no further move; at 7.5 the same National history returns, the Site layer is removed, and the camera is untouched. diff --git a/scripts/national-phase4-packaged-validation.mjs b/scripts/national-phase4-packaged-validation.mjs index f57236a..a0b98dc 100644 --- a/scripts/national-phase4-packaged-validation.mjs +++ b/scripts/national-phase4-packaged-validation.mjs @@ -242,6 +242,20 @@ export function validateZoomHandoff(handoff) { || !sameCamera(afterSite?.camera, afterSite?.cameraSet) || !(handoff?.siteSwitchMs >= 0 && handoff.siteSwitchMs <= 1_500 + fadeMs) ) failures.push("zooming in fades the preloaded Site in without moving the camera"); + const hop = handoff?.afterHop; + const hopSources = hop?.sources ?? []; + if ( + !hop?.site + || hop.site === site + || hop?.sourceState?.painted?.source?.kind !== "site" + || hop?.sourceState?.painted?.source?.siteIcao !== hop.site + || hop?.sourceState?.transition + || hopSources.join(">") !== `${site}>national>${hop.site}` + || hop?.siteOpacity !== 1 + || hop?.nationalRenderer?.visibility !== "resident" + || !sameCamera(hop?.camera, hop?.cameraSet) + || !(hop?.switchMs >= 0) + ) failures.push("panning into another Site's coverage fades through National to that Site"); const afterNational = handoff?.afterNational; if ( afterNational?.sourceState?.painted?.source?.kind !== "national" diff --git a/scripts/national-phase4-packaged-validation.test.mjs b/scripts/national-phase4-packaged-validation.test.mjs index f1682fa..3288e1a 100644 --- a/scripts/national-phase4-packaged-validation.test.mjs +++ b/scripts/national-phase4-packaged-validation.test.mjs @@ -107,6 +107,19 @@ describe("National Phase 4 packaged acceptance", () => { "zooming in fades the preloaded Site in without moving the camera", ); + const direct = validReport().zoomHandoff; + direct.afterHop.sources = ["KTLX", "KFWS"]; + expect(validateZoomHandoff(direct)).toContain( + "panning into another Site's coverage fades through National to that Site", + ); + + const strandedOnNational = validReport().zoomHandoff; + strandedOnNational.afterHop.sources = ["KTLX", "national"]; + strandedOnNational.afterHop.sourceState.painted = { source: { kind: "national" }, generation: 8 }; + expect(validateZoomHandoff(strandedOnNational)).toContain( + "panning into another Site's coverage fades through National to that Site", + ); + const reacquired = validReport().zoomHandoff; reacquired.afterNational.sourceState.painted.generation = 15; expect(validateZoomHandoff(reacquired)).toContain( @@ -406,6 +419,16 @@ function validReport() { siteOpacity: 1, nationalRenderer: { visibility: "resident" }, }, + afterHop: { + site: "KFWS", + switchMs: 4200, + sources: ["KTLX", "national", "KFWS"], + sourceState: { painted: { source: { kind: "site", siteIcao: "KFWS" }, generation: 15 } }, + camera: { longitude: -97.3031, latitude: 32.5731, zoom: 9.6 }, + cameraSet: { longitude: -97.3031, latitude: 32.5731, zoom: 9.6 }, + siteOpacity: 1, + nationalRenderer: { visibility: "resident" }, + }, nationalSwitchMs: 340, afterNational: { sourceState: { painted: { source: { kind: "national", domain: "conus" }, generation: 8 } }, diff --git a/src/App.tsx b/src/App.tsx index d2a169e..f30bc99 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -362,6 +362,7 @@ export function App() { let staticNationalDiagnostic = false; let clickHandler: ((event: MapMouseEvent) => void) | null = null; let autoSourceMoveHandlerForCleanup: ((event: { originalEvent?: unknown }) => void) | null = null; + let unsubscribeAutoSourceFlush: (() => void) | null = null; let latestReport: Phase4Report | null = null; let activeScenario: Promise | null = null; let startupAcquisition: Promise | null = null; @@ -1339,9 +1340,11 @@ export function App() { return siteLevel2Session.start(site, { ...options, residentGeneration }); }; - const settleAutoSwitch = () => { + // A switch that succeeded re-checks the same camera: Site to Site goes + // through National, and the second leg needs no further camera move. + const settleAutoSwitch = (succeeded: boolean) => { autoSwitchInFlight = false; - if (!pendingAutoEvaluation) return; + if (!succeeded && !pendingAutoEvaluation) return; pendingAutoEvaluation = false; evaluateAutoSource(); }; @@ -1366,17 +1369,18 @@ export function App() { preferredSite, }, RADAR_SITES); lastAutoDecision = { ...decision, atUnixMs: Date.now() }; + if (decision.preferenceSpent) preferredSite = undefined; if (sameAutoSource(decision.target, visible)) { if (decision.preload) void prefetchSite(decision.preload); return; } if (decision.target.kind === "national") { autoSwitchInFlight = true; - void nationalMrmsSession.start().then(settleAutoSwitch, (error: unknown) => { + void nationalMrmsSession.start().then(() => settleAutoSwitch(true), (error: unknown) => { if (!isRadarSourceSuperseded(error)) { setNationalRequestError(error instanceof Error ? error.message : String(error)); } - settleAutoSwitch(); + settleAutoSwitch(false); }); return; } @@ -1384,12 +1388,12 @@ export function App() { const failedAt = autoSiteFailures.get(target); if (failedAt !== undefined && Date.now() - failedAt < AUTO_SITE_RETRY_MS) return; autoSwitchInFlight = true; - void startSiteSession(target).then(settleAutoSwitch, (error: unknown) => { + void startSiteSession(target).then(() => settleAutoSwitch(true), (error: unknown) => { if (!isRadarSourceSuperseded(error)) { autoSiteFailures.set(target, Date.now()); setSiteRequestError(error instanceof Error ? error.message : String(error)); } - settleAutoSwitch(); + settleAutoSwitch(false); }); }; @@ -1400,6 +1404,12 @@ export function App() { }; instance.on("moveend", autoSourceMoveHandler); autoSourceMoveHandlerForCleanup = autoSourceMoveHandler; + // A camera move made during a manual switch is evaluated once it ends. + unsubscribeAutoSourceFlush = radarSessionCoordinatorRef.current!.subscribe((snapshot) => { + if (snapshot.transition || autoSwitchInFlight || !pendingAutoEvaluation) return; + pendingAutoEvaluation = false; + queueMicrotask(evaluateAutoSource); + }); autoSourceRef.current = { setPreferredSite(site) { preferredSite = site; @@ -2831,10 +2841,11 @@ export function App() { siteLayerRemoved: !instance.getLayer(DIAGNOSTIC_LAYER_IDS.radar), }; }, - async proveZoomHandoff(site = "KTLX") { + async proveZoomHandoff(site = "KTLX", nextSite = "KFWS") { const location = radarSiteById(normalizeRadarSite(site)); + const nextLocation = radarSiteById(normalizeRadarSite(nextSite)); const auto = globalThis.__MISTR_AUTO_SOURCE__; - if (!location || !auto || !nationalLayer) { + if (!location || !nextLocation || !auto || !nationalLayer) { throw new Error("zoom handoff diagnostic is unavailable"); } const coordinator = radarSessionCoordinatorRef.current!; @@ -2878,7 +2889,42 @@ export function App() { nationalRenderer: nationalLayer?.getSnapshot() ?? null, }; - instance.jumpTo({ center, zoom: 7.5, bearing: 0, pitch: 0 }); + // Panning at detail zoom into another Site's coverage fades through + // National and on to that Site from one camera move. + const nextCenter: [number, number] = [nextLocation.longitude, nextLocation.latitude]; + const hopSources: string[] = []; + const stopWatchingHop = coordinator.subscribe((snapshot) => { + const painted = snapshot.painted?.source; + const label = !painted ? "none" : painted.kind === "site" ? painted.siteIcao : "national"; + if (hopSources.at(-1) !== label) hopSources.push(label); + }); + instance.jumpTo({ center: nextCenter, zoom: 9.6, bearing: 0, pitch: 0 }); + const hopCameraSet = camera(); + const hopStarted = performance.now(); + let afterHop; + try { + auto.evaluate(); + await waitFor( + () => settled("site") && coordinator.snapshot().painted?.source.kind === "site" + && (coordinator.snapshot().painted?.source as { siteIcao?: string }).siteIcao === nextLocation.id, + 120_000, + "Site to Site pan", + ); + afterHop = { + site: nextLocation.id, + switchMs: performance.now() - hopStarted, + sources: [...hopSources], + sourceState: coordinator.snapshot(), + camera: camera(), + cameraSet: hopCameraSet, + siteOpacity: layer?.getOpacity() ?? null, + nationalRenderer: nationalLayer?.getSnapshot() ?? null, + }; + } finally { + stopWatchingHop(); + } + + instance.jumpTo({ center: nextCenter, zoom: 7.5, bearing: 0, pitch: 0 }); const nationalCameraSet = camera(); const nationalStarted = performance.now(); auto.evaluate(); @@ -2891,6 +2937,7 @@ export function App() { preloaded, siteSwitchMs, afterSite, + afterHop, nationalSwitchMs, afterNational: { sourceState: coordinator.snapshot(), @@ -3093,6 +3140,7 @@ export function App() { if (radarLayerRef.current === layer) radarLayerRef.current = null; if (clickHandler) instance.off("click", clickHandler); if (autoSourceMoveHandlerForCleanup) instance.off("moveend", autoSourceMoveHandlerForCleanup); + unsubscribeAutoSourceFlush?.(); autoSourceRef.current = null; if (globalThis.__MISTR_AUTO_SOURCE__) delete globalThis.__MISTR_AUTO_SOURCE__; if (globalThis.__MISTR_PHASE4__) delete globalThis.__MISTR_PHASE4__; @@ -3311,7 +3359,8 @@ export function App() { interrogationObservationRef.current = null; inspectionRequestRef.current = null; // The picker flies to the Site; zoom then keeps it displayed. From National - // the Site preloads during the flight and the landing switches to it. + // the Site preloads during the flight and the landing switches to it; from + // another Site the landing fades through National first. const auto = autoSourceRef.current; auto?.setPreferredSite(normalized); const instance = map.current; @@ -3321,8 +3370,8 @@ export function App() { flyToSite(instance, location); } const painted = radarSessionCoordinatorRef.current?.snapshot().painted; - if (auto && instance && location && painted?.source.kind === "national") { - auto.prefetch(normalized); + if (auto && instance && location && painted) { + if (painted.source.kind === "national") auto.prefetch(normalized); auto.evaluateIfSettled(); return; } @@ -3346,20 +3395,21 @@ export function App() { return; } const sourceState = radarSessionCoordinatorRef.current?.snapshot(); - if ( - sourceState?.transition?.requestedSource.kind === "national" - || (sourceState?.painted?.source.kind === "national" && !sourceState.transition) - ) return; - setNationalRequestError(null); - setSiteRequestError(null); - setInterrogation(null); - setInspectionState("idle"); - inspectionMarkerRef.current?.remove(); - inspectionMarkerRef.current = null; - inspectionPointRef.current = null; - interrogationObservationRef.current = null; - inspectionRequestRef.current = null; - // Picking National zooms out to the country; the landing switches source. + const alreadyNational = sourceState?.transition?.requestedSource.kind === "national" + || (sourceState?.painted?.source.kind === "national" && !sourceState.transition); + if (!alreadyNational) { + setNationalRequestError(null); + setSiteRequestError(null); + setInterrogation(null); + setInspectionState("idle"); + inspectionMarkerRef.current?.remove(); + inspectionMarkerRef.current = null; + inspectionPointRef.current = null; + interrogationObservationRef.current = null; + inspectionRequestRef.current = null; + } + // Picking National zooms out to the country, even when National is already + // displayed; the landing switches source if needed. const auto = autoSourceRef.current; auto?.setPreferredSite(undefined); const instance = map.current; @@ -3369,6 +3419,7 @@ export function App() { auto.evaluateIfSettled(); return; } + if (alreadyNational) return; void session.start().then( () => setNationalRequestError(null), (error: unknown) => { @@ -4287,7 +4338,7 @@ declare global { startSite(site?: string): Promise; proveFailedSiteKeepsNational(site?: string): Promise; proveResidentHandoff(site?: string): Promise; - proveZoomHandoff(site?: string): Promise; + proveZoomHandoff(site?: string, nextSite?: string): Promise; waitForHistory(frameCount?: number, timeoutMs?: number): Promise; beginResidentEvidence(): Promise; endResidentEvidence(): void; diff --git a/src/radar-session/autoSourcePolicy.test.ts b/src/radar-session/autoSourcePolicy.test.ts index 176b3e0..20d8195 100644 --- a/src/radar-session/autoSourcePolicy.test.ts +++ b/src/radar-session/autoSourcePolicy.test.ts @@ -53,6 +53,38 @@ describe("decideAutoSource", () => { ).target).toEqual(ktlx); }); + it("hops a displayed Site to National when a nearby Site is picked", () => { + // KVNX is ~110 km from KTLX, well inside KTLX's own keep range. + const kvnx = { longitude: -98.1281, latitude: 36.7408 }; + expect(decideAutoSource({ zoom: 9.5, center: kvnx, visible: ktlx }, RADAR_SITES)) + .toEqual({ target: ktlx }); + expect(decideAutoSource( + { zoom: 9.5, center: kvnx, visible: ktlx, preferredSite: "KVNX" }, + RADAR_SITES, + )).toEqual({ target: national }); + expect(decideAutoSource( + { zoom: 9.5, center: kvnx, visible: national, preferredSite: "KVNX" }, + RADAR_SITES, + )).toEqual({ target: { kind: "site", siteIcao: "KVNX" } }); + // Below the enter zoom the displayed Site holds rather than dropping to National. + expect(decideAutoSource( + { zoom: 8.7, center: kvnx, visible: ktlx, preferredSite: "KVNX" }, + RADAR_SITES, + )).toEqual({ target: ktlx }); + }); + + it("marks the pick spent once the view leaves its coverage", () => { + const amarillo = { longitude: -101.83, latitude: 35.22 }; + expect(decideAutoSource( + { zoom: 10, center: amarillo, visible: ktlx, preferredSite: "KTLX" }, + RADAR_SITES, + )).toEqual({ target: national, preferenceSpent: true }); + expect(decideAutoSource( + { zoom: 10, center: KTLX, visible: ktlx, preferredSite: "KTLX" }, + RADAR_SITES, + )).toEqual({ target: ktlx }); + }); + it("compares sources by kind and site", () => { expect(sameAutoSource(national, { kind: "national" })).toBe(true); expect(sameAutoSource(ktlx, { kind: "site", siteIcao: "KTLX" })).toBe(true); diff --git a/src/radar-session/autoSourcePolicy.ts b/src/radar-session/autoSourcePolicy.ts index 6c45caf..b6466b2 100644 --- a/src/radar-session/autoSourcePolicy.ts +++ b/src/radar-session/autoSourcePolicy.ts @@ -28,6 +28,8 @@ export interface AutoSourceDecision { readonly target: AutoSource; /** Site worth fetching ahead of the switch, only while National is displayed. */ readonly preload?: string; + /** The view has left the preferred Site's coverage, so the pick no longer applies. */ + readonly preferenceSpent?: true; } const NATIONAL: AutoSource = { kind: "national" }; @@ -41,18 +43,29 @@ export function decideAutoSource( sites: readonly RadarSiteOption[], ): AutoSourceDecision { const { zoom, center, visible } = input; + const preferred = input.preferredSite + ? sites.find((site) => site.id === input.preferredSite) + : undefined; + const preferenceHolds = Boolean( + preferred && distanceM(center, preferred) <= AUTO_SITE_KEEP_RANGE_M, + ); + const spent = input.preferredSite && !preferenceHolds ? { preferenceSpent: true as const } : {}; if (visible.kind === "site") { + // A picked Site replaces the displayed one by way of National. + if (preferenceHolds && preferred!.id !== visible.siteIcao && zoom >= AUTO_SITE_ENTER_ZOOM) { + return { target: NATIONAL }; + } const current = sites.find((site) => site.id === visible.siteIcao); const stays = current && zoom >= AUTO_SITE_EXIT_ZOOM && distanceM(center, current) <= AUTO_SITE_KEEP_RANGE_M; - return { target: stays ? visible : NATIONAL }; + return { target: stays ? visible : NATIONAL, ...spent }; } - const candidate = candidateSite(center, input.preferredSite, sites); - if (!candidate) return { target: NATIONAL }; - if (zoom >= AUTO_SITE_ENTER_ZOOM) return { target: { kind: "site", siteIcao: candidate } }; - if (zoom >= AUTO_SITE_PRELOAD_ZOOM) return { target: NATIONAL, preload: candidate }; - return { target: NATIONAL }; + const candidate = preferenceHolds ? preferred!.id : nearestCoveringSite(center, sites); + if (!candidate) return { target: NATIONAL, ...spent }; + if (zoom >= AUTO_SITE_ENTER_ZOOM) return { target: { kind: "site", siteIcao: candidate }, ...spent }; + if (zoom >= AUTO_SITE_PRELOAD_ZOOM) return { target: NATIONAL, preload: candidate, ...spent }; + return { target: NATIONAL, ...spent }; } export function sameAutoSource(left: AutoSource, right: AutoSource): boolean { @@ -60,13 +73,10 @@ export function sameAutoSource(left: AutoSource, right: AutoSource): boolean { && (left.kind === "national" || left.siteIcao === (right as { siteIcao: string }).siteIcao); } -function candidateSite( +function nearestCoveringSite( center: LngLatPoint, - preferredSite: string | undefined, sites: readonly RadarSiteOption[], ): string | undefined { - const preferred = preferredSite ? sites.find((site) => site.id === preferredSite) : undefined; - if (preferred && distanceM(center, preferred) <= AUTO_SITE_KEEP_RANGE_M) return preferred.id; let nearest: { id: string; distance: number } | undefined; for (const site of sites) { const distance = distanceM(center, site);