Skip to main content

cumulus3d_cli/
session.rs

1/*
2 * session.rs
3 *
4 * Copyright (c) 2026 ParkSangWoo
5 *
6 * Author(s):
7 *
8 *      ParkSangWoo <dev.parksangwoo@gmail.com>
9 *
10 *
11 * This file is part of cumulus3d.
12 *
13 * Licensed under the Apache License, Version 2.0 (the "License");
14 * you may not use this file except in compliance with the License.
15 * You may obtain a copy of the License at
16 *
17 *      http://www.apache.org/licenses/LICENSE-2.0
18 *
19 * Unless required by applicable law or agreed to in writing, software
20 * distributed under the License is distributed on an "AS IS" BASIS,
21 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 * See the License for the specific language governing permissions and
23 * limitations under the License.
24 *
25 * SPDX-License-Identifier: Apache-2.0
26 */
27
28//! State value and reducer: [`Session`] + [`step`] / [`poll`] / [`command`] / [`finish`].
29//!
30//! Each time the frame bundle of one position ([`FrameSet`]) arrives, it performs features -> matching of new pairs -> (first model /
31//! continued registration + triangulation)
32//! -> on zone completion, preview (foreground) densification + refinement (background thread: BA -> GPS ENU alignment -> densification),
33//! and emits that process as per-stage [`Event`]s. It writes no files or logs (run.log lines also go out as [`Event::Log`]).
34//!
35//! # State and sharing
36//! `Session` is a value. `step(&s, frames)` returns a new `Session` and `s` can still be used.
37//! Models, image lists, correspondence graphs etc. are shared via `Arc` / copy on write. However, the feature store is append-only shared
38//! data,
39//! so calling `step` twice from the same earlier value with different frames mixes up the store (rewind with [`Command::ResetFrom`]).
40//! Background refinement results (refined models and point clouds) and the event version number are also shared by the whole session
41//! lineage.
42//!
43//! # Event delivery
44//! - Default: foreground events go out in the return vector of that call; background refinement events accumulate in an internal inbox
45//!   and go out
46//!   at the front of the return vector of the next `step`/`poll`/`command`/`finish`.
47//! - If a receiver is set with [`Session::set_sink`], **all** events (foreground and background) are delivered to it in version order as
48//!   soon as they are emitted.
49//!   In that case the foreground events in the return vector are copies of what was already delivered (do not deliver them again). The
50//!   receiver must not block
51//!   (it is called inside an internal lock).
52//! - `meta.version` increases monotonically across the whole session lineage and gives the emission order (= timeline order).
53//!
54//! # Rules for reproducing run.log and timeline (for output hooks)
55//! - The timeline text is given by [`Event::timeline_text`], and it is also written to run.log in the same place as `[HH:MM:SS] text`.
56//! - [`Event::Log`] is one run.log line at that place (with a `[HH:MM:SS] ` prefix if `stamped`).
57//! - [`Event::Warning`]/[`Event::Error`] go out together with a `Log` of the same content, so do not write them to run.log separately.
58//! - The stage times of [`Event::Finished`] have no post-processing ("post") time (post-processing is done by the output hook).
59
60use crate::densewrap::{dense_model, DenseConfig};
61use crate::events::{Command, Event, Frame, Meta, ZoneRange};
62use crate::intrinsics::IntrinsicsPrior;
63use crate::post::fit_shared_points;
64use crate::util::StageTimes;
65use cumulus3d_align::shared::NameFilter;
66use cumulus3d_align::{align_to_gps, EnuOrigin, ModelAlignerOptions};
67use cumulus3d_ba::{bundle_adjust, BaConfig};
68use cumulus3d_core::analyzer::ModelStats;
69use cumulus3d_core::io::ply::PointCloud;
70use cumulus3d_core::io::GpsRecord;
71use cumulus3d_core::{Camera, CameraId, FeatureStore, ImageId, MatchGraph, MatchGraphOptions, Reconstruction, Rigid3};
72use cumulus3d_features::{CameraMode, ExtractionOptions, FeatureExtractor, ImageReport, ImageStatus, SiftEngine};
73use cumulus3d_matching::{match_pairs, MatcherBackend, PairMatchingOptions};
74use cumulus3d_sfm::{
75    global_mapper, register_images, triangulate_points, GlobalSfmOptions, PointTriangulatorOptions, RegistrationOptions, TriangulationScope,
76};
77use rayon::prelude::*;
78use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
79use std::path::PathBuf;
80use std::sync::{Arc, Mutex, MutexGuard};
81use std::thread::JoinHandle;
82use std::time::{Instant, SystemTime};
83
84/// One image of one position.
85#[derive(Clone, Debug, PartialEq, Eq)]
86pub struct FrameImage {
87    /// Camera name (e.g. `camF`). The same name uses the same camera intrinsics.
88    pub camera: String,
89    /// Image name (path relative to `image_root`, e.g. `camF/camF_0000.jpg`).
90    pub name: String,
91}
92
93/// Frame bundle of one position (one image per camera).
94#[derive(Clone, Debug, Default)]
95pub struct FrameSet {
96    /// Images per camera.
97    pub images: Vec<FrameImage>,
98    /// GPS records that came with this bundle (appended after `gps` in the settings).
99    pub gps: Vec<GpsRecord>,
100}
101
102impl FrameSet {
103    /// As a (camera, name) list.
104    pub fn new<C: Into<String>, N: Into<String>>(images: impl IntoIterator<Item = (C, N)>) -> Self {
105        Self { images: images.into_iter().map(|(c, n)| FrameImage { camera: c.into(), name: n.into() }).collect(), gps: Vec::new() }
106    }
107}
108
109/// Session settings.
110#[derive(Clone)]
111pub struct SessionConfig {
112    /// Input image folder (base of the image names).
113    pub image_root: PathBuf,
114    /// GPS records (alignment order = this order).
115    pub gps: Vec<GpsRecord>,
116    /// Zone size and overlap (in units of positions).
117    pub span: usize,
118    /// Zone overlap (number of positions).
119    pub overlap: usize,
120    /// Total number of known positions. If set, the last zones are closed at the last position; if not, they are closed in [`finish`].
121    pub total_positions: Option<usize>,
122    /// Triangulate only newly registered images.
123    pub incremental_triangulation: bool,
124    /// Fix the ENU origin to the first GPS record (default: the first common record at each alignment).
125    pub fixed_enu_origin: bool,
126    /// RANSAC seed for two-view geometry and GPS alignment.
127    pub seed: Option<u64>,
128    /// Feature extraction options.
129    pub extraction: ExtractionOptions,
130    /// SIFT backend.
131    pub sift: Arc<dyn SiftEngine>,
132    /// Descriptor matching backend.
133    pub matcher: Arc<dyn MatcherBackend>,
134    /// Densification settings (None = skip densification, point-cloud events carry `dense: false`).
135    pub dense: Option<DenseConfig>,
136    /// Number of per-position rewind points kept for [`Command::ResetFrom`] (0 = no rewind, saves memory).
137    pub history: usize,
138    /// Decode input frames to RGB and emit them as [`Event::FrameDecoded`] before processing (off by default).
139    pub decode_frames: bool,
140    /// Stable display (default off). No preview densification; the refinement of zone K waits for zone K−1, takes the
141    /// cameras already shown by it (pose and intrinsics, copied exactly) as fixed in its bundle adjustment, and is not
142    /// re-aligned to GPS, so a zone never moves after it is shown and the space only grows. The coordinate frame is
143    /// the first refined zone's (local). `AllRefinedDone::chain` is the final model aligned to GPS (ENU) once.
144    pub stable_display: bool,
145    /// Stable display: standard deviation (m) of the GPS position prior on each newly placed camera. ≤ 0 disables
146    /// the prior (then the shown frame is local and drifts with the chain).
147    pub gps_prior_sigma: f64,
148    /// Stable display: until settled, every refined zone re-adjusts all earlier cameras and the intrinsics (shown zones are
149    /// re-placed). Once the largest relative focal change between two consecutive refined models is below this (default
150    /// 0.01 = 1 %), the display settles: from then on shown cameras and intrinsics are frozen.
151    pub settle_tol: f64,
152    /// Stable display: the display settles by force at this zone at the latest (default 3).
153    pub settle_max_zone: usize,
154    /// Soft intrinsics prior (see [`crate::intrinsics`]): every camera starts from the prior values as soon as it exists and
155    /// each refinement pulls its refined parameters back towards them. None = off.
156    pub intrinsics_prior: Option<Arc<IntrinsicsPrior>>,
157}
158
159impl SessionConfig {
160    /// Defaults: zone 12 / overlap 2, SIFT up to 8192 features and input 3200, CPU SIFT and matching, no densification, rewind 8.
161    pub fn new(image_root: impl Into<PathBuf>) -> Self {
162        let mut extraction = ExtractionOptions::default();
163        extraction.sift.max_num_features = 8192;
164        extraction.reader.max_image_size = 3200;
165        Self {
166            image_root: image_root.into(),
167            gps: Vec::new(),
168            span: 12,
169            overlap: 2,
170            total_positions: None,
171            incremental_triangulation: false,
172            fixed_enu_origin: false,
173            seed: None,
174            extraction,
175            sift: Arc::new(cumulus3d_features::CpuSift::default()),
176            matcher: Arc::new(cumulus3d_matching::CpuMatcher::default()),
177            dense: None,
178            history: 8,
179            decode_frames: false,
180            stable_display: false,
181            gps_prior_sigma: 1.0,
182            settle_tol: 0.01,
183            settle_max_zone: 3,
184            intrinsics_prior: None,
185        }
186    }
187}
188
189/// Reducer input.
190#[derive(Clone, Debug)]
191pub enum Input {
192    /// Frame bundle of the next position.
193    Frames(FrameSet),
194    /// A command that changes the state.
195    Command(Command),
196    /// Only collect background events.
197    Poll,
198    /// One line to run.log (`Event::Log`).
199    Log(String),
200    /// Close the remaining zones -> wait for background jobs -> summary. Later inputs only produce warnings.
201    Finish,
202}
203
204impl From<FrameSet> for Input {
205    fn from(f: FrameSet) -> Self {
206        Input::Frames(f)
207    }
208}
209
210impl From<Command> for Input {
211    fn from(c: Command) -> Self {
212        Input::Command(c)
213    }
214}
215
216/// The session as a reducer driven by [`crate::pipeline::Pipeline`]. `finish` closes the remaining zones and waits for all background
217/// refinement jobs.
218impl crate::pipeline::Reducer for Session {
219    type Input = Input;
220    fn step(&mut self, input: Input) -> Vec<Event> {
221        self.apply(input)
222    }
223    fn prelude(&mut self, input: &Input) -> Vec<Event> {
224        let Input::Frames(fs) = input else { return Vec::new() };
225        let sh = self.shared.clone();
226        let mut evs = Vec::new();
227        {
228            let mut out = Out { sh: &sh, fg: Some(&mut evs), guard: None };
229            self.announce(fs, &mut out);
230        }
231        evs
232    }
233    fn poll(&mut self) -> Vec<Event> {
234        self.apply(Input::Poll)
235    }
236    fn command(&mut self, c: Command) -> Vec<Event> {
237        self.apply(Input::Command(c))
238    }
239    fn finish(&mut self) -> Vec<Event> {
240        self.apply(Input::Finish)
241    }
242}
243
244/// Immediate-delivery receiver.
245pub type EventSink = Arc<dyn Fn(Event) + Send + Sync>;
246
247/// Zone preview result.
248#[derive(Clone, Debug)]
249pub struct PreviewZone {
250    /// Zone range.
251    pub range: ZoneRange,
252    /// Preview model (zone 0 is the GPS-aligned one).
253    pub model: Arc<Reconstruction>,
254    /// Preview dense point cloud (None if densification was not run).
255    pub cloud: Option<Arc<PointCloud>>,
256    /// Point-cloud coordinate frame ("gps" | "refined_K" | "unaligned").
257    pub frame: String,
258}
259
260/// Zone refined result (present from the time the pose is finalized; the point cloud exists once densification finishes).
261#[derive(Clone, Debug)]
262pub struct RefinedZone {
263    /// Zone range.
264    pub range: ZoneRange,
265    /// Model after BA + GPS alignment.
266    pub model: Arc<Reconstruction>,
267    /// Refined dense point cloud (None before densification finishes or if it is skipped).
268    pub cloud: Option<Arc<PointCloud>>,
269    /// Whether refined densification has finished.
270    pub done: bool,
271    generation: u64,
272}
273
274// ---------------------------------------------------------------- Event emission
275
276struct EmitState {
277    version: u64,
278    sink: Option<EventSink>,
279    inbox: Vec<Event>,
280}
281
282struct Emitter(Mutex<EmitState>);
283
284impl Emitter {
285    fn lock(&self) -> MutexGuard<'_, EmitState> {
286        self.0.lock().unwrap_or_else(|e| e.into_inner())
287    }
288
289    /// Attaches version and time and emits it. If `fg` is present, also puts it in the return vector.
290    fn emit(&self, make: impl FnOnce(Meta) -> Event, fg: Option<&mut Vec<Event>>) {
291        let mut st = self.lock();
292        st.version += 1;
293        let ev = make(Meta { version: st.version, at: SystemTime::now() });
294        match (&st.sink, fg) {
295            (Some(s), fg) => {
296                let s = s.clone();
297                if let Some(v) = fg {
298                    v.push(ev.clone());
299                }
300                s(ev);
301            }
302            (None, Some(v)) => v.push(ev),
303            (None, None) => st.inbox.push(ev),
304        }
305    }
306}
307
308/// Immutable settings + background state shared by the session lineage.
309struct Shared {
310    cfg: SessionConfig,
311    extractor: FeatureExtractor,
312    emitter: Emitter,
313    times: StageTimes,
314    bg: Mutex<Background>,
315    start: Mutex<Option<Instant>>,
316}
317
318#[derive(Default)]
319struct Background {
320    jobs: Vec<JoinHandle<()>>,
321    ready: BTreeMap<usize, RefinedZone>,
322    generation: BTreeMap<usize, u64>,
323    /// Stable display: the zone at which the display settled (shown cameras and intrinsics frozen from the next zone on).
324    settled: Option<usize>,
325    /// Stable display: image-name set each zone was densified with (to densify it again while settling).
326    zone_keep: BTreeMap<usize, Arc<HashSet<String>>>,
327    /// Stable display: the model each zone's cloud was densified with (its intrinsics decide whether to densify again).
328    dense_basis: BTreeMap<usize, Arc<Reconstruction>>,
329    /// Stable display: zone -> generation of the last refine job of that zone that ran to its end.
330    finished: BTreeMap<usize, u64>,
331}
332
333/// Marks a stable-display refine job as finished (also on panic) so the next zone's settle work can proceed.
334struct FinishMark<'a> {
335    sh: &'a Shared,
336    zone: usize,
337    generation: u64,
338}
339
340impl Drop for FinishMark<'_> {
341    fn drop(&mut self) {
342        self.sh.bg().finished.insert(self.zone, self.generation);
343    }
344}
345
346impl Shared {
347    fn bg(&self) -> MutexGuard<'_, Background> {
348        self.bg.lock().unwrap_or_else(|e| e.into_inner())
349    }
350
351    fn generation(&self, zone: usize) -> u64 {
352        self.bg().generation.get(&zone).copied().unwrap_or(0)
353    }
354
355    /// Discard a zone result: raise the generation so that later results and events of in-flight jobs are dropped.
356    fn invalidate(&self, zone: usize) {
357        let mut bg = self.bg();
358        *bg.generation.entry(zone).or_insert(0) += 1;
359        bg.ready.remove(&zone);
360        bg.zone_keep.remove(&zone);
361        bg.dense_basis.remove(&zone);
362    }
363
364    fn aligner_options(&self, gps: &[GpsRecord]) -> ModelAlignerOptions {
365        let mut o = ModelAlignerOptions { max_error: 3.0, ..Default::default() };
366        o.ransac.random_seed = self.cfg.seed;
367        if self.cfg.fixed_enu_origin {
368            if let Some(g) = gps.first() {
369                o.origin = EnuOrigin::Explicit { lat: g.lat, lon: g.lon, alt: g.alt };
370            }
371        }
372        o
373    }
374
375    /// ENU alignment using the GPS of registered images. On failure, keep the model as is and warn (design decision: do not stop).
376    /// Waits for the refined pose of zone `k` (stable display orders refinements). None if it does not arrive
377    /// (zone invalidated or refinement failed) within the time limit, or the generation changed.
378    fn wait_refined(&self, k: usize, generation: u64) -> Option<Arc<Reconstruction>> {
379        let t0 = Instant::now();
380        let me = k + 1;
381        loop {
382            if let Some(z) = self.bg().ready.get(&k) {
383                return Some(z.model.clone());
384            }
385            if self.generation(me) != generation || t0.elapsed().as_secs() > 1800 {
386                return None;
387            }
388            std::thread::sleep(std::time::Duration::from_millis(20));
389        }
390    }
391
392    /// Waits until the refine job of zone `k` has run to its end (stable display, settling: earlier zones are only
393    /// re-placed once nothing else writes them). False on timeout or when zone `me` (generation `generation`) was invalidated.
394    fn wait_finished(&self, k: usize, me: usize, generation: u64) -> bool {
395        let t0 = Instant::now();
396        loop {
397            {
398                let bg = self.bg();
399                if bg.finished.get(&k).is_some_and(|g| *g == bg.generation.get(&k).copied().unwrap_or(0)) {
400                    return true;
401                }
402            }
403            if self.generation(me) != generation || t0.elapsed().as_secs() > 1800 {
404                return false;
405            }
406            std::thread::sleep(std::time::Duration::from_millis(20));
407        }
408    }
409
410    /// Stable display, not yet settled: zone `k`'s adjustment moved the earlier cameras, so every shown zone `j < k` is
411    /// placed into `model` again. A zone whose cloud was made with intrinsics differing by `settle_tol` or more from
412    /// `model`'s is densified again; otherwise its cloud is moved with the Sim3 from its previous model to `model`.
413    /// The zone is emitted again (`ZoneRefinedPose` + `ZoneRefined`) under its own generation.
414    fn replace_shown(&self, k: usize, generation: u64, model: &Arc<Reconstruction>, st: &ModelStats) {
415        if !self.wait_finished(k - 1, k, generation) {
416            return;
417        }
418        for j in 0..k {
419            let snap = {
420                let bg = self.bg();
421                let gj = bg.generation.get(&j).copied().unwrap_or(0);
422                bg.ready
423                    .get(&j)
424                    .filter(|z| z.generation == gj)
425                    .map(|z| (z.clone(), gj, bg.zone_keep.get(&j).cloned(), bg.dense_basis.get(&j).cloned()))
426            };
427            let Some((z, gj, keep, basis)) = snap else { continue };
428            let mut out = Out { sh: self, fg: None, guard: Some((j, gj)) };
429            let change = basis.as_ref().map_or(0.0, |b| intrinsics_change(b.cameras(), model.cameras()));
430            let mut basis_new = None;
431            let cloud = z.cloud.as_ref().map(|old| {
432                if change >= self.cfg.settle_tol {
433                    if let Some(c) = keep.as_ref().and_then(|keep| self.dense_region("refined", j, model, keep, &mut out)) {
434                        out.log(format!("[settle] 구역 {j} 다시 조밀화 (내부값 변화 {:.2}%)", change * 100.0));
435                        basis_new = Some(model.clone());
436                        return c;
437                    }
438                }
439                // Shared 3D points seen by zone j's images first, then all shared points, then the camera-center fit.
440                let by_points = keep
441                    .as_ref()
442                    .and_then(|keep| {
443                        let keep = keep.clone();
444                        let filter: NameFilter = Arc::new(move |n: &str| keep.contains(n));
445                        fit_shared_points(&z.model, model, Some(filter), MIN_SHARED_PAIRS)
446                    })
447                    .or_else(|| fit_shared_points(&z.model, model, None, MIN_SHARED_PAIRS));
448                let mut c = (**old).clone();
449                if let Some((f, n)) = by_points {
450                    let t = f.sim3;
451                    cumulus3d_align::transform_cloud(&mut c, &t);
452                    out.log(format!(
453                        "[settle] 구역 {j} 점군 이동: 공유 점 {n}, 잔차 중앙 {:.3}m, 축척 {:.4}, 이동 {:.2}m",
454                        f.median,
455                        t.scale,
456                        t.translation.norm()
457                    ));
458                } else {
459                    let t = keep.as_ref().and_then(|keep| sim3_between(&z.model, model, |n| keep.contains(n)));
460                    match t {
461                        Some(t) => {
462                            cumulus3d_align::transform_cloud(&mut c, &t);
463                            out.log(format!(
464                                "[settle] 구역 {j} 점군 이동(카메라 중심 대체): 이동 {:.3}m 축척 {:.4}",
465                                t.translation.norm(),
466                                t.scale
467                            ));
468                        }
469                        None => out.log(format!("[settle] 구역 {j} 점군 이동 생략: 공통 영상 부족")),
470                    }
471                }
472                Arc::new(c)
473            });
474            {
475                let mut bg = self.bg();
476                if bg.generation.get(&j).copied().unwrap_or(0) != gj {
477                    continue;
478                }
479                let Some(r) = bg.ready.get_mut(&j).filter(|r| r.generation == gj) else { continue };
480                r.model = model.clone();
481                r.cloud = cloud.clone();
482                r.done = true;
483                if let Some(b) = basis_new {
484                    bg.dense_basis.insert(j, b);
485                }
486            }
487            let (range, m) = (z.range, model.clone());
488            let (registered, mean_reproj_px) = (st.registered_image_count, st.mean_reprojection_error);
489            out.emit(|meta| Event::ZoneRefinedPose { meta, range, registered, mean_reproj_px, model: m });
490            let m = model.clone();
491            out.emit(|meta| Event::ZoneRefined { meta, range, dense: cloud.is_some(), cloud: cloud.unwrap_or_default(), model: m });
492        }
493    }
494
495    fn align_enu(&self, rec: &mut Reconstruction, what: &str, gps_all: &[GpsRecord], out: &mut Out) -> bool {
496        let names: BTreeSet<String> = rec.registered_images().into_iter().filter_map(|i| rec.image(i).map(|im| im.name.clone())).collect();
497        let gps: Vec<GpsRecord> = gps_all.iter().filter(|g| names.contains(&g.name)).cloned().collect();
498        let opts = self.aligner_options(gps_all);
499        let t0 = Instant::now();
500        let r = align_to_gps(rec, &gps, &opts);
501        out.stage("align", what, t0);
502        match r {
503            Ok(a) => {
504                out.log(format!(
505                    "[align] {what}: 공통 {} 인라이어 {} 오차 평균 {:.3}m 중앙 {:.3}m 축척 {:.4}",
506                    a.common.len(),
507                    a.num_inliers,
508                    a.mean_error,
509                    a.median_error,
510                    a.sim3.scale
511                ));
512                true
513            }
514            Err(e) => {
515                out.warn(format!("[align] {what}: 정렬 실패({e}) — 정렬 없이 계속"));
516                false
517            }
518        }
519    }
520
521    /// Densification (excluding images outside the zone). None if densification is off or fails.
522    fn dense_region(&self, kind: &str, k: usize, model: &Reconstruction, keep: &HashSet<String>, out: &mut Out) -> Option<Arc<PointCloud>> {
523        let dense = self.cfg.dense.as_ref()?;
524        let what = format!("{kind} {k}");
525        let t = Instant::now();
526        let r = dense_model(model, |n| keep.contains(n), &self.cfg.image_root, dense);
527        let total = t.elapsed();
528        match r {
529            Ok(run) => {
530                self.times.add("undistort", run.undistort_time);
531                self.times.add("densify", run.densify_time);
532                let tm = &run.output.timings;
533                out.stamped(format!(
534                    "[time] dense {what}: 전체 {:.1}s (왜곡 보정+장면 {:.1}s, 대기 {:.1}s, 조밀화 {:.1}s = 이웃 {:.1} 준비 {:.1} 깊이 {:.1} 필터 {:.1} 융합 {:.1}, 캐시 적중 {})",
535                    total.as_secs_f64(),
536                    run.undistort_time.as_secs_f64(),
537                    run.lock_wait.as_secs_f64(),
538                    run.densify_time.as_secs_f64(),
539                    tm.neighbors.as_secs_f64(),
540                    tm.prepare.as_secs_f64(),
541                    tm.depth().as_secs_f64(),
542                    tm.filter.as_secs_f64(),
543                    tm.fusion.as_secs_f64(),
544                    run.output.cache_hits
545                ));
546                out.log(format!("[dense] {kind} {k} frames {} points {}", run.frames, run.output.cloud.len()));
547                let mut cloud = run.output.cloud;
548                // Same value as the PLY round trip: white if there is no color.
549                if !cloud.is_empty() && cloud.colors.is_empty() {
550                    cloud.colors = vec![[255, 255, 255]; cloud.len()];
551                }
552                Some(Arc::new(cloud))
553            }
554            Err(e) => {
555                out.warn(format!("[dense] {kind} {k} 실패: {e}"));
556                None
557            }
558        }
559    }
560
561    /// Background refinement job: copy -> BA -> ENU alignment -> (adoptable) -> densification.
562    fn refine_job(
563        self: Arc<Self>,
564        range: ZoneRange,
565        mut rec: Reconstruction,
566        generation: u64,
567        gps: Arc<Vec<GpsRecord>>,
568        keep: Arc<HashSet<String>>,
569    ) {
570        let k = range.zone;
571        let sh = &*self;
572        let mut out = Out { sh, fg: None, guard: Some((k, generation)) };
573        let _finish = FinishMark { sh, zone: k, generation };
574        out.emit(|meta| Event::RefineStarted { meta, zone: k });
575        let mut ba = BaConfig::default();
576        // Stable display: the previous zone's model, and whether the display is still settling (intrinsics and shown
577        // cameras free) in this zone.
578        let mut prev: Option<Arc<Reconstruction>> = None;
579        let mut settling = false;
580        if sh.cfg.stable_display {
581            let mut bg = sh.bg();
582            if bg.generation.get(&k).copied().unwrap_or(0) == generation {
583                bg.zone_keep.insert(k, keep.clone());
584            }
585        }
586        if sh.cfg.stable_display {
587            let targets = if sh.cfg.gps_prior_sigma > 0.0 { enu_targets(&rec, &gps) } else { HashMap::new() };
588            if k == 0 {
589                // Bring the first model into ENU once; every later zone is placed in this frame.
590                let (src, dst): (Vec<_>, Vec<_>) = targets.iter().filter_map(|(id, g)| rec.projection_center(*id).map(|c| (c, *g))).unzip();
591                if src.len() >= 3 {
592                    if let Some(t) = cumulus3d_align::umeyama(&src, &dst, true) {
593                        rec.transform(&t);
594                        out.log(format!("[stable] refined 0: ENU 초기 정렬 GPS {} 개, 축척 {:.4}", src.len(), t.scale));
595                    }
596                }
597                settling = true;
598            } else {
599                prev = sh.wait_refined(k - 1, generation);
600                settling = sh.bg().settled.is_none();
601                match (&prev, settling) {
602                    (Some(p), false) => {
603                        let (n, scale) = anchor_to_shown(&mut rec, p, &mut ba);
604                        out.log(format!("[stable] refined {k}: 고정 영상 {n}, 이전 구역에 맞춘 축척 {scale:.4}"));
605                    }
606                    (Some(p), true) => {
607                        let scale = sim3_onto_shown(&mut rec, p).map_or(1.0, |(t, _)| t.scale);
608                        out.log(format!("[stable] refined {k}: 정착 전 — 모든 자세·내부값 자유, 이전 구역에 맞춘 축척 {scale:.4}"));
609                    }
610                    (None, _) => out.warn(format!("[stable] refined {k}: 앞 구역 결과 없음 — 고정 없이 조정")),
611                }
612            }
613            let sigma = sh.cfg.gps_prior_sigma;
614            for (id, g) in &targets {
615                if !ba.constant_poses.contains(id) {
616                    ba.position_priors.insert(*id, (*g, sigma));
617                }
618            }
619            if !ba.position_priors.is_empty() {
620                out.log(format!("[stable] refined {k}: GPS 위치 제약 {} 개 (σ {sigma} m)", ba.position_priors.len()));
621            }
622        }
623        if let Some(pr) = &sh.cfg.intrinsics_prior {
624            for (cid, cam) in rec.cameras() {
625                if !ba.constant_cameras.contains(cid) {
626                    if let Some(p) = pr.ba_prior(cam) {
627                        ba.intrinsics_priors.insert(*cid, p);
628                    }
629                }
630            }
631            if !ba.intrinsics_priors.is_empty() {
632                out.log(format!(
633                    "[prior] refined {k}: 내부값 사전 카메라 {} 개 (초점 σ {} 상대, 왜곡 σ {})",
634                    ba.intrinsics_priors.len(),
635                    pr.focal_sigma,
636                    pr.dist_sigma
637                ));
638            }
639        }
640        let t0 = Instant::now();
641        let r = bundle_adjust(&mut rec, &ba);
642        out.stage("ba", &format!("refined {k}"), t0);
643        match r {
644            Ok(s) => out.log(format!(
645                "[ba] refined {k}: 반복 {} 비용 {:.4e} → {:.4e} ({:?}), RMS {:.3}px",
646                s.num_iterations,
647                s.initial_cost,
648                s.final_cost,
649                s.termination,
650                s.rms_reprojection_error()
651            )),
652            Err(e) => out.warn(format!("[ba] refined {k} 실패: {e}")),
653        }
654        // Settling BA moved the whole model (gauge freedom); bring it back into the previously shown frame.
655        if let (true, Some(p)) = (settling && k > 0, &prev) {
656            match fit_shared_points(&rec, p, None, MIN_SHARED_PAIRS) {
657                Some((f, n)) => {
658                    let t = f.sim3;
659                    rec.transform(&t);
660                    out.log(format!(
661                        "[settle] refined {k}: 화면 좌표계 재정렬 공유 점 {n}, 잔차 중앙 {:.3}m, 축척 {:.4}, 이동 {:.2}m",
662                        f.median,
663                        t.scale,
664                        t.translation.norm()
665                    ));
666                }
667                None => match sim3_onto_shown(&mut rec, p) {
668                    Some((t, _)) => out.log(format!(
669                        "[settle] refined {k}: 화면 좌표계 재정렬 (카메라 중심 대체) 축척 {:.4}, 이동 {:.2}m",
670                        t.scale,
671                        t.translation.norm()
672                    )),
673                    None => out.warn(format!("[settle] refined {k}: 화면 좌표계 재정렬 생략: 공통 영상 부족")),
674                },
675            }
676        }
677        let adjusted = Arc::new(rec.clone());
678        out.emit(|meta| Event::ZoneAdjusted { meta, zone: k, model: adjusted });
679        if !sh.cfg.stable_display {
680            sh.align_enu(&mut rec, &format!("refined {k}"), &gps, &mut out);
681        }
682        let st = ModelStats::compute(&rec);
683        // Settle decision (before the pose is published, so the next zone sees it).
684        let mut settle_now = false;
685        if settling {
686            let change = prev.as_ref().map(|p| intrinsics_change(p.cameras(), rec.cameras()));
687            let forced = k >= sh.cfg.settle_max_zone;
688            settle_now = forced || change.is_some_and(|c| c < sh.cfg.settle_tol);
689            let verdict = match (settle_now, forced) {
690                (true, true) => "강제 고정",
691                (true, false) => "고정",
692                _ => "정착 중",
693            };
694            match change {
695                Some(c) => out.log(format!("[settle] refined {k}: 내부값 변화 {:.2}% → {verdict}", c * 100.0)),
696                None => out.log(format!("[settle] refined {k}: → {verdict}")),
697            }
698        }
699        let model = Arc::new(rec);
700        {
701            let mut bg = sh.bg();
702            if bg.generation.get(&k).copied().unwrap_or(0) == generation {
703                if settle_now {
704                    bg.settled = Some(k);
705                }
706                bg.ready.insert(k, RefinedZone { range, model: model.clone(), cloud: None, done: false, generation });
707            }
708        }
709        let m = model.clone();
710        out.emit(|meta| Event::ZoneRefinedPose {
711            meta,
712            range,
713            registered: st.registered_image_count,
714            mean_reproj_px: st.mean_reprojection_error,
715            model: m,
716        });
717        let cloud = sh.dense_region("refined", k, &model, &keep, &mut out);
718        {
719            let mut bg = sh.bg();
720            if bg.generation.get(&k).copied().unwrap_or(0) == generation {
721                if let Some(z) = bg.ready.get_mut(&k).filter(|z| z.generation == generation) {
722                    z.cloud = cloud.clone();
723                    z.done = true;
724                }
725                bg.dense_basis.insert(k, model.clone());
726            }
727        }
728        let m = model.clone();
729        out.emit(|meta| Event::ZoneRefined { meta, range, dense: cloud.is_some(), cloud: cloud.unwrap_or_default(), model: m });
730        // Still settling: the earlier cameras moved with this adjustment, so the zones already shown are placed again.
731        if settling && k > 0 {
732            sh.replace_shown(k, generation, &model, &st);
733        }
734    }
735}
736
737/// Event exit (foreground: return vector, background: receiver/inbox). The background drops events when the zone generation changes.
738struct Out<'a> {
739    sh: &'a Shared,
740    fg: Option<&'a mut Vec<Event>>,
741    guard: Option<(usize, u64)>,
742}
743
744impl Out<'_> {
745    fn emit(&mut self, make: impl FnOnce(Meta) -> Event) {
746        if let Some((k, g)) = self.guard {
747            if self.sh.generation(k) != g {
748                return;
749            }
750        }
751        self.sh.emitter.emit(make, self.fg.as_deref_mut());
752    }
753
754    fn log(&mut self, line: impl Into<String>) {
755        let line = line.into();
756        self.emit(|meta| Event::Log { meta, line, stamped: false });
757    }
758
759    fn stamped(&mut self, line: impl Into<String>) {
760        let line = line.into();
761        self.emit(|meta| Event::Log { meta, line, stamped: true });
762    }
763
764    /// run.log line + a warning with the same content.
765    fn warn(&mut self, line: String) {
766        self.log(line.clone());
767        self.emit(|meta| Event::Warning { meta, message: line });
768    }
769
770    /// Accumulate stage time + a `[time] stage target: seconds` line.
771    fn stage(&mut self, stage: &str, what: &str, t0: Instant) {
772        let d = t0.elapsed();
773        self.sh.times.add(stage, d);
774        self.stamped(format!("[time] {stage} {what}: {:.3}s", d.as_secs_f64()));
775    }
776}
777
778// ---------------------------------------------------------------- State value
779
780#[derive(Clone)]
781struct Checkpoint {
782    /// The state right after processing up to this position.
783    position: usize,
784    chain: Option<Reconstruction>,
785    adopted: Option<usize>,
786    cam_ids: Arc<BTreeMap<String, CameraId>>,
787    graph: Arc<MatchGraph>,
788    gps_len: usize,
789}
790
791/// Incremental reconstruction state value.
792#[derive(Clone)]
793pub struct Session {
794    shared: Arc<Shared>,
795    store: Arc<FeatureStore>,
796    graph: Arc<MatchGraph>,
797    frames: Arc<Vec<Vec<FrameImage>>>,
798    position_of: Arc<HashMap<String, usize>>,
799    ingested: usize,
800    cam_ids: Arc<BTreeMap<String, CameraId>>,
801    gps: Arc<Vec<GpsRecord>>,
802    chain: Option<Reconstruction>,
803    adopted: Option<usize>,
804    arrived: BTreeMap<usize, ZoneRange>,
805    previews: Arc<BTreeMap<usize, PreviewZone>>,
806    checkpoints: VecDeque<Checkpoint>,
807    started: bool,
808    finished: bool,
809    failed: Option<String>,
810    /// Positions whose frames were already emitted (so the same bundle is not emitted twice).
811    announced: Option<usize>,
812}
813
814/// The new state and events after processing the next frame bundle.
815pub fn step(session: &Session, frames: FrameSet) -> (Session, Vec<Event>) {
816    session.clone().advance(Input::Frames(frames))
817}
818
819/// Collect background refinement events (when there is no receiver). The state does not change.
820pub fn poll(session: &Session) -> (Session, Vec<Event>) {
821    session.clone().advance(Input::Poll)
822}
823
824/// Command handling.
825pub fn command(session: &Session, cmd: Command) -> (Session, Vec<Event>) {
826    session.clone().advance(Input::Command(cmd))
827}
828
829/// Close the remaining zones -> wait for background jobs -> summary.
830pub fn finish(session: &Session) -> (Session, Vec<Event>) {
831    session.clone().advance(Input::Finish)
832}
833
834impl Session {
835    /// Create an empty session from the settings.
836    pub fn new(cfg: SessionConfig) -> Self {
837        let extractor = FeatureExtractor::with_backend(cfg.sift.clone());
838        let gps = Arc::new(cfg.gps.clone());
839        let shared = Arc::new(Shared {
840            cfg,
841            extractor,
842            emitter: Emitter(Mutex::new(EmitState { version: 0, sink: None, inbox: Vec::new() })),
843            times: StageTimes::default(),
844            bg: Mutex::new(Background::default()),
845            start: Mutex::new(None),
846        });
847        Self {
848            shared,
849            store: Arc::new(FeatureStore::new()),
850            graph: Arc::new(MatchGraph::new()),
851            frames: Arc::new(Vec::new()),
852            position_of: Arc::new(HashMap::new()),
853            ingested: 0,
854            cam_ids: Arc::new(BTreeMap::new()),
855            gps,
856            chain: None,
857            adopted: None,
858            arrived: BTreeMap::new(),
859            previews: Arc::new(BTreeMap::new()),
860            checkpoints: VecDeque::new(),
861            started: false,
862            announced: None,
863            finished: false,
864            failed: None,
865        }
866    }
867
868    /// Set/clear the immediate-delivery receiver (shared by the session lineage). When set, background events accumulated so far are
869    /// delivered first.
870    pub fn set_sink(&self, sink: Option<EventSink>) {
871        let mut st = self.shared.emitter.lock();
872        if let Some(s) = &sink {
873            for ev in std::mem::take(&mut st.inbox) {
874                s(ev);
875            }
876        }
877        st.sink = sink;
878    }
879
880    /// Emit an event from outside (e.g. a hook runner) in this session's version order. If there is no receiver, it accumulates in the
881    /// inbox.
882    pub fn emit_external(&self, make: impl FnOnce(Meta) -> Event) {
883        self.shared.emitter.emit(make, None);
884    }
885
886    /// State transition (owned version, no copying). `step`/`poll`/`command`/`finish` are thin wrappers around this.
887    pub fn advance(mut self, input: Input) -> (Session, Vec<Event>) {
888        let evs = self.apply(input);
889        (self, evs)
890    }
891
892    /// In-place state transition. Returned events are in version order (events emitted by background jobs in the meantime are also
893    /// inserted in place).
894    pub fn apply(&mut self, input: Input) -> Vec<Event> {
895        let sh = self.shared.clone();
896        let mut evs: Vec<Event> = Vec::new();
897        {
898            let mut out = Out { sh: &sh, fg: Some(&mut evs), guard: None };
899            if self.finished {
900                if !matches!(input, Input::Poll) {
901                    out.emit(|meta| Event::Warning { meta, message: "세션이 이미 끝남 — 입력 무시".into() });
902                }
903            } else {
904                if !matches!(input, Input::Poll) {
905                    self.ensure_started(&mut out);
906                }
907                match input {
908                    Input::Frames(fs) => {
909                        self.announce(&fs, &mut out);
910                        if let Some(e) = &self.failed {
911                            let message = format!("이전 오류로 중단된 세션 — 프레임 무시 ({e})");
912                            out.emit(|meta| Event::Warning { meta, message });
913                        } else if let Err(e) = self.process_frames(fs, &mut out) {
914                            self.failed = Some(e.clone());
915                            out.emit(|meta| Event::Error { meta, message: e });
916                        }
917                    }
918                    Input::Command(c) => self.apply_command(c, &mut out),
919                    Input::Poll => {}
920                    Input::Log(line) => out.log(line),
921                    Input::Finish => {
922                        if self.failed.is_none() {
923                            self.finish_session(&mut out);
924                        }
925                        self.finished = true;
926                    }
927                }
928            }
929        }
930        // Merge, in version order, the events that background jobs put into the inbox during (and before) this call.
931        let bg = std::mem::take(&mut sh.emitter.lock().inbox);
932        if !bg.is_empty() {
933            evs.extend(bg);
934            evs.sort_by_key(|e| e.meta().version);
935        }
936        evs
937    }
938
939    // ------------------------------------------------------------ Queries
940
941    /// Number of processed positions.
942    pub fn positions(&self) -> usize {
943        self.frames.len()
944    }
945    /// Frame bundle per position.
946    pub fn frames(&self) -> &[Vec<FrameImage>] {
947        &self.frames
948    }
949    /// Position of an image name.
950    pub fn position_of(&self, name: &str) -> Option<usize> {
951        self.position_of.get(name).copied()
952    }
953    /// Current chain model (None before the first model).
954    pub fn model(&self) -> Option<&Reconstruction> {
955        self.chain.as_ref()
956    }
957    /// The last refined zone adopted as the chain reference.
958    pub fn adopted(&self) -> Option<usize> {
959        self.adopted
960    }
961    /// Feature store.
962    pub fn store(&self) -> &FeatureStore {
963        &self.store
964    }
965    /// Correspondence graph.
966    pub fn graph(&self) -> &MatchGraph {
967        &self.graph
968    }
969    /// Session settings.
970    pub fn config(&self) -> &SessionConfig {
971        &self.shared.cfg
972    }
973    /// Zones that have arrived (been processed).
974    pub fn arrived_zones(&self) -> Vec<ZoneRange> {
975        self.arrived.values().copied().collect()
976    }
977    /// Per-zone preview results.
978    pub fn previews(&self) -> &BTreeMap<usize, PreviewZone> {
979        &self.previews
980    }
981    /// Per-zone refined results (those with finalized poses, the current value shared with background jobs).
982    pub fn refined(&self) -> BTreeMap<usize, RefinedZone> {
983        self.shared.bg().ready.clone()
984    }
985    /// Number of background refinement jobs not yet finished.
986    pub fn pending_jobs(&self) -> usize {
987        self.shared.bg().jobs.iter().filter(|j| !j.is_finished()).count()
988    }
989    /// The last event version issued.
990    pub fn version(&self) -> u64 {
991        self.shared.emitter.lock().version
992    }
993    /// Fatal error (feature extraction, matching, first model failure). If set, later frames are ignored.
994    pub fn failed(&self) -> Option<&str> {
995        self.failed.as_deref()
996    }
997    /// Whether `Finish` was handled.
998    pub fn is_finished(&self) -> bool {
999        self.finished
1000    }
1001
1002    // ------------------------------------------------------------ Processing
1003
1004    fn ensure_started(&mut self, out: &mut Out) {
1005        if self.started {
1006            return;
1007        }
1008        self.started = true;
1009        *self.shared.start.lock().unwrap_or_else(|e| e.into_inner()) = Some(Instant::now());
1010        let positions = self.shared.cfg.total_positions;
1011        out.emit(|meta| Event::Started { meta, positions });
1012    }
1013
1014    /// Decode the next position's frames to RGB and emit them as [`Event::FrameDecoded`] (once per position, cameras in parallel).
1015    fn announce(&mut self, fs: &FrameSet, out: &mut Out) {
1016        let sh = self.shared.clone();
1017        let p = self.frames.len();
1018        if !sh.cfg.decode_frames || self.finished || self.failed.is_some() || self.announced == Some(p) {
1019            return;
1020        }
1021        self.ensure_started(out);
1022        self.announced = Some(p);
1023        let decoded: Vec<Result<Frame, String>> = fs
1024            .images
1025            .par_iter()
1026            .map(|im| {
1027                let path = sh.cfg.image_root.join(&im.name);
1028                let img = image::ImageReader::open(&path)
1029                    .and_then(|r| r.with_guessed_format())
1030                    .map_err(|e| format!("{}: {e}", path.display()))?
1031                    .decode()
1032                    .map_err(|e| format!("{}: 디코딩 실패: {e}", path.display()))?
1033                    .into_rgb8();
1034                let gps = fs.gps.iter().chain(self.gps.iter()).find(|g| g.name == im.name).cloned();
1035                let (width, height) = img.dimensions();
1036                Ok(Frame {
1037                    position: p,
1038                    camera: im.camera.clone(),
1039                    name: im.name.clone(),
1040                    path,
1041                    width,
1042                    height,
1043                    rgb: Arc::from(img.into_raw()),
1044                    gps,
1045                })
1046            })
1047            .collect();
1048        for d in decoded {
1049            match d {
1050                Ok(f) => {
1051                    let frame = Arc::new(f);
1052                    out.emit(|meta| Event::FrameDecoded { meta, frame });
1053                }
1054                Err(e) => out.emit(|meta| Event::Warning { meta, message: format!("[frame] {e}") }),
1055            }
1056        }
1057    }
1058
1059    fn process_frames(&mut self, fs: FrameSet, out: &mut Out) -> Result<(), String> {
1060        let sh = self.shared.clone();
1061        let cfg = &sh.cfg;
1062        let p = self.frames.len();
1063        let names: Vec<String> = fs.images.iter().map(|i| i.name.clone()).collect();
1064        {
1065            let pos = Arc::make_mut(&mut self.position_of);
1066            for n in &names {
1067                pos.insert(n.clone(), p);
1068            }
1069        }
1070        Arc::make_mut(&mut self.frames).push(fs.images.clone());
1071        self.ingested += fs.images.len();
1072        if !fs.gps.is_empty() {
1073            Arc::make_mut(&mut self.gps).extend(fs.gps);
1074        }
1075        out.emit(|meta| Event::FrameIngested { meta, position: p, images: names });
1076
1077        // 1) Features: for the first bundle, one camera per folder; afterwards the same camera id.
1078        let t0 = Instant::now();
1079        let r = self.extract(p, &fs.images, out);
1080        out.stage("feature", &format!("pos {p}"), t0);
1081        r?;
1082
1083        // 2) Match only pairs that involve a new image.
1084        let pairs: Vec<(ImageId, ImageId)> = pairs_for(&self.frames, p)
1085            .into_iter()
1086            .filter_map(|(a, b)| Some((self.store.image_id_by_name(&a)?, self.store.image_id_by_name(&b)?)))
1087            .collect();
1088        let mut mopts = PairMatchingOptions::default();
1089        mopts.geometry.ransac.random_seed = cfg.seed;
1090        let t0 = Instant::now();
1091        let st = match_pairs(&self.store, &pairs, &mopts, cfg.matcher.as_ref());
1092        out.stage("matching", &format!("pos {p} ({} pairs)", pairs.len()), t0);
1093        let st = st.map_err(|e| e.to_string())?;
1094        Arc::make_mut(&mut self.graph).update_from_store(&self.store, &MatchGraphOptions::default());
1095        out.log(format!(
1096            "[match] pos {p}: 짝 {} 매칭 {} 유효 기하 {} (그래프 영상 {})",
1097            pairs.len(),
1098            st.num_matched,
1099            st.num_valid_geometries,
1100            self.graph.image_ids().len()
1101        ));
1102        let (np, nv, nm) = (pairs.len(), st.num_valid_geometries, st.num_matched);
1103        out.emit(|meta| Event::PairsMatched { meta, pairs: np, verified: nv, position: p, matched: nm });
1104
1105        // 3) Registration.
1106        let (span, ovl) = (cfg.span, cfg.overlap);
1107        if p + 1 < span + ovl {
1108            self.checkpoint(p);
1109            return Ok(());
1110        }
1111        if p + 1 == span + ovl {
1112            let t0 = Instant::now();
1113            let o = global_mapper(&self.store, &self.graph, &GlobalSfmOptions::script());
1114            out.stage("mapper", &format!("pos {p}"), t0);
1115            let o = o.map_err(|e| e.to_string())?;
1116            if let Some(f) = &o.failure {
1117                out.warn(format!("[mapper] 실패 보고: {f}"));
1118            }
1119            out.log(format!("[mapper] {:?}", o.summary));
1120            let rec = o.reconstruction;
1121            let model = Arc::new(rec.clone());
1122            let registered = rec.registered_image_count();
1123            out.emit(|meta| Event::ModelInitialized { meta, registered, position: p, model });
1124            let ids = rec.registered_images();
1125            self.emit_registered(&rec, &ids, out);
1126            self.chain = Some(rec);
1127        } else {
1128            // If a new refined model has appeared, continue registering on top of it.
1129            let mut k = self.adopted.map_or(0, |a| a + 1);
1130            loop {
1131                let r = sh.bg().ready.get(&k).map(|z| z.model.clone());
1132                let Some(r) = r else { break };
1133                self.chain = Some((*r).clone());
1134                self.adopted = Some(k);
1135                out.emit(|meta| Event::BaseAdopted { meta, zone: k });
1136                k += 1;
1137            }
1138            if let Some(base) = &self.chain {
1139                let mut reg = base.clone();
1140                let t0 = Instant::now();
1141                let rr = register_images(&mut reg, &self.store, &self.graph, &RegistrationOptions::default());
1142                out.stage("registration", &format!("pos {p}"), t0);
1143                match rr {
1144                    Ok(rep) => {
1145                        let new_ids = rep.registered();
1146                        out.log(format!("[register] pos {p}: 시도 {} 등록 {}", rep.attempts.len(), new_ids.len()));
1147                        let scope = if cfg.incremental_triangulation {
1148                            TriangulationScope::Images(new_ids.clone())
1149                        } else {
1150                            TriangulationScope::AllRegistered
1151                        };
1152                        let topts = PointTriangulatorOptions { clear_points: false, scope, ..Default::default() };
1153                        let t0 = Instant::now();
1154                        let tr = triangulate_points(&mut reg, &self.graph, &topts);
1155                        out.stage("triangulation", &format!("pos {p}"), t0);
1156                        match tr {
1157                            Ok(t) => {
1158                                out.log(format!(
1159                                    "[triangulate] pos {p}: 생성 {} 연장 {} 완성 {} 병합 {} 필터 {} (점 {})",
1160                                    t.num_created,
1161                                    t.num_continued,
1162                                    t.num_completed,
1163                                    t.num_merged,
1164                                    t.num_filtered,
1165                                    reg.num_points3d()
1166                                ));
1167                                self.emit_registered(&reg, &new_ids, out);
1168                                self.chain = Some(reg);
1169                            }
1170                            Err(e) => out.warn(format!("[triangulate] pos {p} 실패: {e} (이전 모델 유지)")),
1171                        }
1172                    }
1173                    Err(e) => out.warn(format!("[register] pos {p} 실패: {e}")),
1174                }
1175            }
1176        }
1177        let registered = self.chain.as_ref().map_or(0, |r| r.registered_image_count());
1178        let expected = self.ingested;
1179        out.emit(|meta| Event::PositionDone { meta, position: p, registered, expected });
1180
1181        // 4) Zone completion -> preview (foreground) + refinement (background).
1182        for z in zones_ending_at(p, span, ovl, cfg.total_positions) {
1183            if !self.arrived.contains_key(&z.zone) {
1184                self.process_zone(z, out);
1185            }
1186        }
1187        self.checkpoint(p);
1188        Ok(())
1189    }
1190
1191    fn extract(&mut self, p: usize, images: &[FrameImage], out: &mut Out) -> Result<(), String> {
1192        let sh = self.shared.clone();
1193        let cfg = &sh.cfg;
1194        if self.cam_ids.is_empty() {
1195            let names: Vec<String> = images.iter().map(|i| i.name.clone()).collect();
1196            let mut o = cfg.extraction.clone();
1197            o.reader.camera_mode = CameraMode::PerFolder;
1198            let rep = sh.extractor.extract_files(&self.store, &cfg.image_root, &names, &o).map_err(|e| e.to_string())?;
1199            report_extraction(&rep, p, out);
1200            let cams = Arc::make_mut(&mut self.cam_ids);
1201            for im in images {
1202                let s = self.store.image_by_name(&im.name).ok_or_else(|| format!("{} 첫 영상 특징 추출 실패", im.camera))?;
1203                cams.insert(im.camera.clone(), s.camera_id);
1204            }
1205            self.apply_intrinsics_prior(out)?;
1206        } else {
1207            for im in images {
1208                let mut o = cfg.extraction.clone();
1209                let known = self.cam_ids.get(&im.camera).copied();
1210                o.reader.camera_mode = known.map_or(CameraMode::PerFolder, CameraMode::Existing);
1211                let rep = sh
1212                    .extractor
1213                    .extract_files(&self.store, &cfg.image_root, std::slice::from_ref(&im.name), &o)
1214                    .map_err(|e| e.to_string())?;
1215                report_extraction(&rep, p, out);
1216                if known.is_none() {
1217                    if let Some(s) = self.store.image_by_name(&im.name) {
1218                        Arc::make_mut(&mut self.cam_ids).insert(im.camera.clone(), s.camera_id);
1219                    }
1220                    self.apply_intrinsics_prior(out)?;
1221                }
1222            }
1223        }
1224        Ok(())
1225    }
1226
1227    /// Soft intrinsics prior: sets the store's cameras to the prior values (before any registration or model uses them).
1228    /// A camera without an entry is left alone; an entry whose length differs from the camera model's is an error.
1229    fn apply_intrinsics_prior(&self, out: &mut Out) -> Result<(), String> {
1230        let Some(pr) = &self.shared.cfg.intrinsics_prior else { return Ok(()) };
1231        for mut cam in self.store.cameras() {
1232            let before = cam.params.clone();
1233            if pr.apply(&mut cam)? && cam.params != before {
1234                out.log(format!("[prior] 카메라 {}: 내부값 초기화 {} → {}", cam.camera_id, fmt_params(&before), fmt_params(&cam.params)));
1235                self.store.update_camera(cam).map_err(|e| e.to_string())?;
1236            }
1237        }
1238        Ok(())
1239    }
1240
1241    fn emit_registered(&self, rec: &Reconstruction, ids: &[ImageId], out: &mut Out) {
1242        for &id in ids {
1243            let (Some(im), Some(pose)) = (rec.image(id), rec.world_to_cam(id)) else { continue };
1244            let image = im.name.clone();
1245            let position = self.position_of(&image).unwrap_or(usize::MAX);
1246            out.emit(|meta| Event::FrameRegistered { meta, position, image, image_id: id, cam_from_world: pose });
1247        }
1248    }
1249
1250    /// Zone arrival: preview (foreground, only zone 0 is GPS-aligned) + start the refinement job (background).
1251    fn process_zone(&mut self, range: ZoneRange, out: &mut Out) {
1252        let sh = self.shared.clone();
1253        let k = range.zone;
1254        let snap = self.chain.clone().unwrap_or_default();
1255        let m = Arc::new(snap.clone());
1256        out.emit(|meta| Event::ZoneArrived { meta, range, model: m });
1257        if sh.cfg.stable_display {
1258            let keep: Arc<HashSet<String>> =
1259                Arc::new(self.position_of.iter().filter(|(_, p)| **p >= range.lo && **p < range.hi).map(|(n, _)| n.clone()).collect());
1260            let generation = sh.generation(k);
1261            let (sh2, gps) = (sh.clone(), self.gps.clone());
1262            let h = std::thread::spawn(move || sh2.refine_job(range, snap, generation, gps, keep));
1263            sh.bg().jobs.push(h);
1264            self.arrived.insert(k, range);
1265            return;
1266        }
1267        let mut preview = snap.clone();
1268        let mut frame = match self.adopted {
1269            Some(j) => format!("refined_{j}"),
1270            None => "unaligned".to_string(),
1271        };
1272        if k == 0 && sh.align_enu(&mut preview, "preview 0", &self.gps, out) {
1273            frame = "gps".to_string();
1274        }
1275        let keep: Arc<HashSet<String>> =
1276            Arc::new(self.position_of.iter().filter(|(_, p)| **p >= range.lo && **p < range.hi).map(|(n, _)| n.clone()).collect());
1277        let generation = sh.generation(k);
1278        {
1279            let (sh2, gps, keep) = (sh.clone(), self.gps.clone(), keep.clone());
1280            let h = std::thread::spawn(move || sh2.refine_job(range, snap, generation, gps, keep));
1281            sh.bg().jobs.push(h);
1282        }
1283        let cloud = sh.dense_region("preview", k, &preview, &keep, out);
1284        let model = Arc::new(preview);
1285        self.arrived.insert(k, range);
1286        Arc::make_mut(&mut self.previews)
1287            .insert(k, PreviewZone { range, model: model.clone(), cloud: cloud.clone(), frame: frame.clone() });
1288        out.emit(|meta| Event::ZonePreview { meta, range, dense: cloud.is_some(), cloud: cloud.unwrap_or_default(), model, frame });
1289    }
1290
1291    fn checkpoint(&mut self, position: usize) {
1292        let n = self.shared.cfg.history;
1293        if n == 0 {
1294            return;
1295        }
1296        self.checkpoints.push_back(Checkpoint {
1297            position,
1298            chain: self.chain.clone(),
1299            adopted: self.adopted,
1300            cam_ids: self.cam_ids.clone(),
1301            graph: self.graph.clone(),
1302            gps_len: self.gps.len(),
1303        });
1304        while self.checkpoints.len() > n {
1305            self.checkpoints.pop_front();
1306        }
1307    }
1308
1309    fn drop_zone(&mut self, k: usize, out: &mut Out) {
1310        self.arrived.remove(&k);
1311        Arc::make_mut(&mut self.previews).remove(&k);
1312        self.shared.invalidate(k);
1313        out.emit(|meta| Event::ZoneInvalidated { meta, zone: k });
1314    }
1315
1316    fn apply_command(&mut self, cmd: Command, out: &mut Out) {
1317        match cmd {
1318            Command::ResetFrom(p) => self.reset_from(p, out),
1319            Command::InvalidateZone(k) => {
1320                let Some(range) = self.arrived.get(&k).copied() else {
1321                    out.emit(|meta| Event::Warning {
1322                        meta, message: format!("구역 {k} 은 아직 도착하지 않음 — 무효화할 것 없음")
1323                    });
1324                    return;
1325                };
1326                self.drop_zone(k, out);
1327                // Rebuild with the current chain.
1328                self.process_zone(range, out);
1329            }
1330        }
1331    }
1332
1333    /// Discard the state after position p: roll the store, graph and chain back to right after position p-1, and invalidate the zones
1334    /// closed after that.
1335    fn reset_from(&mut self, p: usize, out: &mut Out) {
1336        let npos = self.frames.len();
1337        if p > npos {
1338            out.emit(|meta| Event::Warning { meta, message: format!("ResetFrom({p}): 처리한 위치 {npos} 보다 큼 — 무시") });
1339            return;
1340        }
1341        let cp = if p == 0 {
1342            None
1343        } else {
1344            match self.checkpoints.iter().find(|c| c.position + 1 == p) {
1345                Some(c) => Some(c.clone()),
1346                None => {
1347                    out.emit(|meta| Event::Warning {
1348                        meta, message: format!("ResetFrom({p}): 되감기 지점 없음(history 부족) — 무시")
1349                    });
1350                    return;
1351                }
1352            }
1353        };
1354        let gone: Vec<usize> = self.arrived.iter().filter(|(_, r)| r.hi.saturating_sub(1) >= p).map(|(k, _)| *k).collect();
1355        for k in gone {
1356            self.drop_zone(k, out);
1357        }
1358        let pos = self.position_of.clone();
1359        self.store = Arc::new(self.store.retain_copy(|im| pos.get(&im.name).is_some_and(|q| *q < p)));
1360        Arc::make_mut(&mut self.frames).truncate(p);
1361        Arc::make_mut(&mut self.position_of).retain(|_, q| *q < p);
1362        self.ingested = self.frames.iter().map(|f| f.len()).sum();
1363        self.checkpoints.retain(|c| c.position < p);
1364        match cp {
1365            Some(c) => {
1366                self.chain = c.chain;
1367                self.adopted = c.adopted;
1368                self.cam_ids = c.cam_ids;
1369                self.graph = c.graph;
1370                Arc::make_mut(&mut self.gps).truncate(c.gps_len);
1371            }
1372            None => {
1373                self.chain = None;
1374                self.adopted = None;
1375                self.cam_ids = Arc::new(BTreeMap::new());
1376                self.graph = Arc::new(MatchGraph::new());
1377                self.gps = Arc::new(self.shared.cfg.gps.clone());
1378            }
1379        }
1380        out.emit(|meta| Event::Reset { meta, position: p });
1381    }
1382
1383    fn finish_session(&mut self, out: &mut Out) {
1384        let sh = self.shared.clone();
1385        let (span, ovl) = (sh.cfg.span, sh.cfg.overlap);
1386        // If the total count was unknown, close the remaining zones at the last position.
1387        let npos = self.frames.len();
1388        if npos > 0 && npos >= span + ovl {
1389            for z in zones_upto(npos, span, ovl) {
1390                if !self.arrived.contains_key(&z.zone) {
1391                    self.process_zone(z, out);
1392                }
1393            }
1394        }
1395        out.emit(|meta| Event::AllPositionsDone { meta });
1396        loop {
1397            let jobs = std::mem::take(&mut sh.bg().jobs);
1398            if jobs.is_empty() {
1399                break;
1400            }
1401            for j in jobs {
1402                let _ = j.join();
1403            }
1404        }
1405        let chain = match (&self.chain, sh.cfg.stable_display) {
1406            (Some(c), true) => {
1407                // Final outputs in ENU through one GPS alignment of a copy of the whole model (with or without GPS priors the
1408                // display frame is the first shown zone's frame); the display chain itself stays untouched. On failure the
1409                // display-frame chain is handed on.
1410                let mut enu = c.clone();
1411                if sh.align_enu(&mut enu, "final (stable display)", &self.gps, out) {
1412                    // Display → ENU scale on the camera centers: close to the zone-0 initial ENU fit (1.0 when the display frame
1413                    // stayed ENU through the GPS priors); a large gap means the frame drifted.
1414                    match display_to_enu_scale(c, &enu) {
1415                        Some(s) => out.log(format!("[stable] 표시→ENU 축척 {s:.4} (1.0 이면 표시 좌표계가 ENU 와 같음)")),
1416                        None => out.log("[stable] 표시→ENU 축척: 공통 영상 부족".to_string()),
1417                    }
1418                    Some(Arc::new(enu))
1419                } else {
1420                    out.warn(
1421                        "[align] final (stable display): GPS 정렬 실패 — 표시 좌표계 모델을 그대로 넘김(final_frame/ 은 표시 좌표계)"
1422                            .to_string(),
1423                    );
1424                    Some(Arc::new(c.clone()))
1425                }
1426            }
1427            (c, _) => c.clone().map(Arc::new),
1428        };
1429        out.emit(|meta| Event::AllRefinedDone { meta, chain });
1430        let pipeline_secs = sh.start.lock().unwrap_or_else(|e| e.into_inner()).map_or(0.0, |t| t.elapsed().as_secs_f64());
1431        let stage_times = sh.times.snapshot().into_iter().map(|(k, (d, n))| (k, d, n)).collect();
1432        let chain_stats = self.chain.as_ref().map(|c| ModelStats::compute(c).lines()).unwrap_or_default();
1433        out.emit(|meta| Event::Finished { meta, pipeline_secs, stage_times, chain_stats });
1434    }
1435}
1436
1437fn report_extraction(rep: &[ImageReport], position: usize, out: &mut Out) {
1438    for r in rep {
1439        match &r.status {
1440            ImageStatus::Extracted { image_id, camera_id, num_features } => {
1441                out.log(format!("[feature] {} id {image_id} cam {camera_id} 특징 {num_features}", r.name));
1442                let (image, image_id, count) = (r.name.clone(), *image_id, *num_features);
1443                out.emit(|meta| Event::FeaturesExtracted { meta, image, count, position, image_id });
1444            }
1445            ImageStatus::AlreadyExists { image_id } => out.log(format!("[feature] {} id {image_id} 이미 있음", r.name)),
1446            ImageStatus::Failed { error } => out.warn(format!("[feature] {} 실패: {error}", r.name)),
1447        }
1448    }
1449}
1450
1451fn fmt_params(p: &[f64]) -> String {
1452    format!("[{}]", p.iter().map(|x| format!("{x:.5}")).collect::<Vec<_>>().join(" "))
1453}
1454
1455/// Scale of the Sim3 (Umeyama on the projection centers of the images registered in both) taking `display` to `enu`.
1456fn display_to_enu_scale(display: &Reconstruction, enu: &Reconstruction) -> Option<f64> {
1457    let (mut src, mut dst) = (Vec::new(), Vec::new());
1458    for id in display.registered_images() {
1459        let name = display.image(id)?.name.clone();
1460        let Some(eid) = enu.image_by_name(&name).map(|im| im.image_id) else { continue };
1461        if let (Some(a), Some(b)) = (display.projection_center(id), enu.projection_center(eid)) {
1462            src.push(a);
1463            dst.push(b);
1464        }
1465    }
1466    if src.len() < 3 {
1467        return None;
1468    }
1469    cumulus3d_align::umeyama(&src, &dst, true).map(|t| t.scale)
1470}
1471
1472/// ENU positions (origin = first GPS record) of the registered images of `rec` that have a GPS record.
1473fn enu_targets(rec: &Reconstruction, gps: &[GpsRecord]) -> HashMap<ImageId, cumulus3d_core::Vec3> {
1474    let Some(o) = gps.first() else { return HashMap::new() };
1475    let frame = cumulus3d_align::EnuFrame::new(o.lat, o.lon, o.alt);
1476    let by_name: HashMap<&str, &GpsRecord> = gps.iter().map(|g| (g.name.as_str(), g)).collect();
1477    rec.registered_images()
1478        .into_iter()
1479        .filter_map(|id| {
1480            let g = by_name.get(rec.image(id)?.name.as_str())?;
1481            Some((id, frame.lla_to_enu(g.lat, g.lon, g.alt)))
1482        })
1483        .collect()
1484}
1485
1486/// Brings `rec` into the frame of the already shown model `shown` (Sim3 on the projection centers of the images registered
1487/// in both). Returns the Sim3 and, for each shared image, its pose in `shown`.
1488fn sim3_onto_shown(rec: &mut Reconstruction, shown: &Reconstruction) -> Option<(cumulus3d_core::Sim3, Vec<(ImageId, Rigid3)>)> {
1489    let mut pairs = Vec::new();
1490    for id in rec.registered_images() {
1491        let Some(name) = rec.image(id).map(|im| im.name.clone()) else { continue };
1492        let Some(sid) = shown.image_by_name(&name).map(|im| im.image_id) else { continue };
1493        if let (Some(a), Some(b), Some(pose)) = (rec.projection_center(id), shown.projection_center(sid), shown.world_to_cam(sid)) {
1494            pairs.push((id, a, b, pose));
1495        }
1496    }
1497    let (src, dst): (Vec<_>, Vec<_>) = pairs.iter().map(|(_, a, b, _)| (*a, *b)).unzip();
1498    let t = cumulus3d_align::umeyama(&src, &dst, true)?;
1499    rec.transform(&t);
1500    Some((t, pairs.into_iter().map(|(id, _, _, pose)| (id, pose)).collect()))
1501}
1502
1503/// Stable display, settled: brings `rec` into the frame of the already shown model `shown`, then copies the shown poses and
1504/// the camera intrinsics exactly and marks them constant in `ba`. Returns (fixed image count, Sim3 scale).
1505fn anchor_to_shown(rec: &mut Reconstruction, shown: &Reconstruction, ba: &mut BaConfig) -> (usize, f64) {
1506    let Some((t, poses)) = sim3_onto_shown(rec, shown) else { return (0, 1.0) };
1507    for (id, pose) in &poses {
1508        if rec.set_world_to_cam(*id, *pose).is_ok() {
1509            ba.constant_poses.insert(*id);
1510        }
1511    }
1512    for (cid, cam) in shown.cameras() {
1513        if let Some(c) = rec.camera_mut(*cid) {
1514            *c = cam.clone();
1515            ba.constant_cameras.insert(*cid);
1516        }
1517    }
1518    (ba.constant_poses.len(), t.scale)
1519}
1520
1521/// Fewest shared 3D points for which a point-based Sim3 fit is trusted over the camera-center fit.
1522const MIN_SHARED_PAIRS: usize = 20;
1523
1524/// Sim3 taking `from` into the frame of `to` (umeyama with scale on the projection centers of the images, accepted by
1525/// `keep`, registered in both). None with fewer than 3 common images.
1526fn sim3_between(from: &Reconstruction, to: &Reconstruction, keep: impl Fn(&str) -> bool) -> Option<cumulus3d_core::Sim3> {
1527    let (mut src, mut dst) = (Vec::new(), Vec::new());
1528    for id in from.registered_images() {
1529        let Some(name) = from.image(id).map(|im| im.name.as_str()).filter(|n| keep(n)) else { continue };
1530        let Some(tid) = to.image_by_name(name).map(|im| im.image_id) else { continue };
1531        if let (Some(a), Some(b)) = (from.projection_center(id), to.projection_center(tid)) {
1532            src.push(a);
1533            dst.push(b);
1534        }
1535    }
1536    if src.len() < 3 {
1537        return None;
1538    }
1539    cumulus3d_align::umeyama(&src, &dst, true)
1540}
1541
1542/// Largest relative change of a focal parameter (fx, fy; just f for single-focal models) over the cameras present in both
1543/// `a` and `b`, as a fraction of `a`'s value. Infinite when a camera changed its model kind; 0 when no camera is shared.
1544pub fn intrinsics_change(a: &BTreeMap<CameraId, Camera>, b: &BTreeMap<CameraId, Camera>) -> f64 {
1545    let mut worst = 0.0f64;
1546    for (id, ca) in a {
1547        let Some(cb) = b.get(id) else { continue };
1548        if ca.model != cb.model {
1549            return f64::INFINITY;
1550        }
1551        for &s in ca.model.focal_slots() {
1552            let (fa, fb) = (ca.params[s], cb.params[s]);
1553            worst = worst.max(if fa != 0.0 {
1554                ((fb - fa) / fa).abs()
1555            } else if fb != 0.0 {
1556                f64::INFINITY
1557            } else {
1558                0.0
1559            });
1560        }
1561    }
1562    worst
1563}
1564
1565/// Pairing rule: same camera at position gaps 1..5, 8, 16 / different cameras at position difference 0..4. Only pairs involving an image
1566/// of position p, as sorted name pairs.
1567pub fn pairs_for(frames: &[Vec<FrameImage>], p: usize) -> Vec<(String, String)> {
1568    let mut pr = BTreeSet::new();
1569    let Some(cur) = frames.get(p) else { return Vec::new() };
1570    for im in cur {
1571        for d in [1usize, 2, 3, 4, 5, 8, 16] {
1572            if p >= d {
1573                if let Some(o) = frames[p - d].iter().find(|x| x.camera == im.camera) {
1574                    pr.insert((o.name.clone(), im.name.clone()));
1575                }
1576            }
1577        }
1578    }
1579    for a in cur {
1580        for fq in &frames[p.saturating_sub(4)..=p] {
1581            for b in fq {
1582                if a.camera == b.camera {
1583                    continue;
1584                }
1585                let (x, y) = (a.name.clone(), b.name.clone());
1586                pr.insert(if x <= y { (x, y) } else { (y, x) });
1587            }
1588        }
1589    }
1590    pr.into_iter().collect()
1591}
1592
1593/// Zones: start = 0, span, ...; [start-ovl, start+span+ovl) intersect [0, total). Completion position = hi-1.
1594pub fn zones_upto(total: usize, span: usize, ovl: usize) -> Vec<ZoneRange> {
1595    let mut v = Vec::new();
1596    let mut start = 0;
1597    let mut k = 0;
1598    while start < total {
1599        v.push(ZoneRange { zone: k, lo: start.saturating_sub(ovl), hi: (start + span + ovl).min(total) });
1600        k += 1;
1601        start += span.max(1);
1602    }
1603    v
1604}
1605
1606/// Zones closed at position p (if the total count is unknown, only zones that are not truncated).
1607fn zones_ending_at(p: usize, span: usize, ovl: usize, total: Option<usize>) -> Vec<ZoneRange> {
1608    let mut v = Vec::new();
1609    let mut k = 0;
1610    loop {
1611        let start = k * span.max(1);
1612        if start > p || total.is_some_and(|n| start >= n) {
1613            break;
1614        }
1615        let hi = total.map_or(start + span + ovl, |n| (start + span + ovl).min(n));
1616        if hi == p + 1 {
1617            v.push(ZoneRange { zone: k, lo: start.saturating_sub(ovl), hi });
1618        }
1619        k += 1;
1620    }
1621    v
1622}
1623
1624#[cfg(test)]
1625mod tests {
1626    use super::*;
1627
1628    fn frames(n: usize) -> Vec<Vec<FrameImage>> {
1629        (0..n)
1630            .map(|p| {
1631                ["camF", "camR", "camL"]
1632                    .iter()
1633                    .map(|c| FrameImage { camera: c.to_string(), name: format!("{c}/{c}_{:04}.jpg", p * 3) })
1634                    .collect()
1635            })
1636            .collect()
1637    }
1638
1639    #[test]
1640    fn zones_match_regions() {
1641        let z = |v: Vec<ZoneRange>| v.into_iter().map(|r| (r.zone, r.lo, r.hi)).collect::<Vec<_>>();
1642        assert_eq!(z(zones_upto(26, 12, 2)), vec![(0, 0, 14), (1, 10, 26), (2, 22, 26)]);
1643        // Collecting the zones closed at each position gives the same list.
1644        let mut all = Vec::new();
1645        for p in 0..26 {
1646            all.extend(zones_ending_at(p, 12, 2, Some(26)));
1647        }
1648        all.sort_by_key(|r| r.zone);
1649        assert_eq!(z(all), z(zones_upto(26, 12, 2)));
1650        // If the total count is unknown, only non-truncated zones are closed at a position.
1651        assert_eq!(z(zones_ending_at(13, 12, 2, None)), vec![(0, 0, 14)]);
1652        assert_eq!(z(zones_ending_at(25, 12, 2, None)), vec![(1, 10, 26)]);
1653        assert!(zones_ending_at(25, 12, 2, Some(40)).iter().any(|r| r.zone == 1));
1654    }
1655
1656    #[test]
1657    fn intrinsics_change_is_max_relative_focal_change() {
1658        use cumulus3d_core::CameraModelKind;
1659        let cam = |id: CameraId, model: CameraModelKind, params: Vec<f64>| Camera::new(id, model, 4000, 3000, params).unwrap();
1660        let single = |id, f: f64| cam(id, CameraModelKind::SingleFocalRadial, vec![f, 2000.0, 1500.0, 0.1]);
1661        let pinhole = |id, fx: f64, fy: f64| cam(id, CameraModelKind::Pinhole, vec![fx, fy, 2000.0, 1500.0]);
1662        let map = |v: Vec<Camera>| v.into_iter().map(|c| (c.camera_id, c)).collect::<BTreeMap<_, _>>();
1663        let a = map(vec![single(1, 1000.0), pinhole(2, 2000.0, 2000.0)]);
1664        assert_eq!(intrinsics_change(&a, &a), 0.0);
1665        // Principal point / distortion changes do not count; the worst focal parameter of any camera does.
1666        let b = map(vec![single(1, 1005.0), pinhole(2, 2000.0, 2040.0), single(3, 1.0)]);
1667        assert!((intrinsics_change(&a, &b) - 0.02).abs() < 1e-12);
1668        let c = map(vec![single(1, 990.0), pinhole(2, 2000.0, 2000.0)]);
1669        assert!((intrinsics_change(&a, &c) - 0.01).abs() < 1e-12);
1670        // No shared camera: nothing changed; model kind change: infinite.
1671        assert_eq!(intrinsics_change(&a, &map(vec![single(9, 5.0)])), 0.0);
1672        assert!(intrinsics_change(&a, &map(vec![pinhole(1, 1000.0, 1000.0)])).is_infinite());
1673    }
1674
1675    #[test]
1676    fn pair_rule() {
1677        let f = frames(20);
1678        assert_eq!(pairs_for(&f, 0).len(), 3);
1679        let p17 = pairs_for(&f, 17);
1680        assert_eq!(p17.len(), 21 + 27);
1681        assert!(p17.contains(&("camF/camF_0003.jpg".to_string(), "camF/camF_0051.jpg".to_string())));
1682    }
1683}