Skip to main content

visloc_io/colmap/
mod.rs

1use nalgebra::{Point2, Point3, Quaternion, UnitQuaternion, Vector3};
2use std::collections::BTreeMap;
3use std::fs;
4use std::num::{ParseFloatError, ParseIntError};
5use std::path::Path;
6use thiserror::Error;
7use visloc_core::geometry::Pose;
8use visloc_core::types::{
9    Camera, CameraModel, Frame, Keyframe, Landmark, LandmarkDescriptorStore, Observation,
10    VisualMap, VisualMapValidationReport,
11};
12use visloc_localization::{DescriptorProvider, MapProvider};
13use visloc_vision::features::FeatureSet;
14use visloc_vision::stereo_vo::StereoFeature;
15
16use crate::descriptors::{read_landmark_descriptors_txt, DescriptorStoreError};
17
18#[derive(Debug, Error)]
19pub enum ColmapError {
20    #[error("I/O error: {0}")]
21    Io(#[from] std::io::Error),
22    #[error("integer parse error: {0}")]
23    ParseInt(#[from] ParseIntError),
24    #[error("float parse error: {0}")]
25    ParseFloat(#[from] ParseFloatError),
26    #[error("invalid COLMAP line in {file}: {line}")]
27    InvalidLine { file: &'static str, line: String },
28    #[error("invalid COLMAP binary in {file}: {message}")]
29    InvalidBinary { file: &'static str, message: String },
30    #[error("invalid COLMAP export input: {0}")]
31    InvalidExportInput(String),
32}
33
34/// A merged multi-view landmark for COLMAP export: `(world_position,
35/// observations)` where each observation is `(frame, left_keypoint_index,
36/// pixel)`. See [`write_colmap_reconstruction_for_3dgs`].
37pub type ReconstructionLandmark = (Point3<f64>, Vec<(usize, usize, Point2<f64>)>);
38
39/// Summary of a [`write_colmap_text_model_for_3dgs`] call.
40#[derive(Debug, Clone, PartialEq)]
41pub struct ColmapExportSummary {
42    /// Number of camera viewpoints written to `images.txt`.
43    pub frame_count: usize,
44    /// Number of distinct 3D landmarks written to `points3D.txt`.
45    pub landmark_count: usize,
46    /// Total number of (frame, keypoint) observations written across all
47    /// landmark TRACK[] tails in `points3D.txt`.
48    pub observation_count: usize,
49}
50
51#[derive(Debug, Error)]
52pub enum ColmapMapProviderError {
53    #[error("COLMAP error: {0}")]
54    Colmap(#[from] ColmapError),
55    #[error("descriptor store error: {0}")]
56    DescriptorStore(#[from] DescriptorStoreError),
57    #[error("COLMAP map validation failed: {0:?}")]
58    InvalidMap(VisualMapValidationReport),
59}
60
61#[derive(Debug, Clone, PartialEq)]
62pub struct ColmapMapProvider {
63    pub map: VisualMap,
64    pub descriptor_store: Option<LandmarkDescriptorStore>,
65}
66
67impl ColmapMapProvider {
68    pub fn from_text_model_dir(path: impl AsRef<Path>) -> Result<Self, ColmapMapProviderError> {
69        Ok(Self {
70            map: read_colmap_text_model(path)?,
71            descriptor_store: None,
72        })
73    }
74
75    pub fn from_binary_model_dir(path: impl AsRef<Path>) -> Result<Self, ColmapMapProviderError> {
76        Ok(Self {
77            map: read_colmap_binary_model(path)?,
78            descriptor_store: None,
79        })
80    }
81
82    pub fn from_text_model_dir_validated(
83        path: impl AsRef<Path>,
84    ) -> Result<Self, ColmapMapProviderError> {
85        let provider = Self::from_text_model_dir(path)?;
86        provider
87            .validate_map()
88            .into_result()
89            .map_err(ColmapMapProviderError::InvalidMap)?;
90        Ok(provider)
91    }
92
93    pub fn from_binary_model_dir_validated(
94        path: impl AsRef<Path>,
95    ) -> Result<Self, ColmapMapProviderError> {
96        let provider = Self::from_binary_model_dir(path)?;
97        provider
98            .validate_map()
99            .into_result()
100            .map_err(ColmapMapProviderError::InvalidMap)?;
101        Ok(provider)
102    }
103
104    pub fn from_text_model_dir_with_descriptors(
105        model_path: impl AsRef<Path>,
106        descriptor_path: impl AsRef<Path>,
107    ) -> Result<Self, ColmapMapProviderError> {
108        Ok(Self {
109            map: read_colmap_text_model(model_path)?,
110            descriptor_store: Some(read_landmark_descriptors_txt(descriptor_path)?),
111        })
112    }
113
114    pub fn from_text_model_dir_with_descriptors_validated(
115        model_path: impl AsRef<Path>,
116        descriptor_path: impl AsRef<Path>,
117    ) -> Result<Self, ColmapMapProviderError> {
118        let provider = Self::from_text_model_dir_with_descriptors(model_path, descriptor_path)?;
119        provider
120            .validate_for_localization()
121            .into_result()
122            .map_err(ColmapMapProviderError::InvalidMap)?;
123        Ok(provider)
124    }
125
126    pub fn validate_map(&self) -> VisualMapValidationReport {
127        self.map.validate()
128    }
129
130    pub fn validate_for_localization(&self) -> VisualMapValidationReport {
131        self.map
132            .validate_with_descriptors(self.descriptor_store.as_ref())
133    }
134}
135
136impl MapProvider for ColmapMapProvider {
137    fn visual_map(&self) -> &VisualMap {
138        &self.map
139    }
140}
141
142impl DescriptorProvider for ColmapMapProvider {
143    fn landmark_descriptor_store(&self) -> Option<&LandmarkDescriptorStore> {
144        self.descriptor_store.as_ref()
145    }
146}
147
148pub fn read_colmap_text_model(path: impl AsRef<Path>) -> Result<VisualMap, ColmapError> {
149    let path = path.as_ref();
150    let mut map = VisualMap::new();
151
152    let cameras = parse_cameras_txt(&fs::read_to_string(path.join("cameras.txt"))?)?;
153    map.cameras = cameras
154        .into_iter()
155        .map(|camera| (camera.id, camera))
156        .collect();
157
158    let landmarks = parse_points3d_txt(&fs::read_to_string(path.join("points3D.txt"))?)?;
159    map.landmarks = landmarks
160        .into_iter()
161        .map(|landmark| (landmark.id, landmark))
162        .collect();
163
164    let keyframes = parse_images_txt(&fs::read_to_string(path.join("images.txt"))?)?;
165    map.keyframes = keyframes
166        .into_iter()
167        .map(|keyframe| (keyframe.frame.id, keyframe))
168        .collect();
169
170    Ok(map)
171}
172
173pub fn read_colmap_binary_model(path: impl AsRef<Path>) -> Result<VisualMap, ColmapError> {
174    let path = path.as_ref();
175    let mut map = VisualMap::new();
176
177    let cameras = parse_cameras_bin(&fs::read(path.join("cameras.bin"))?)?;
178    map.cameras = cameras
179        .into_iter()
180        .map(|camera| (camera.id, camera))
181        .collect();
182
183    let landmarks = parse_points3d_bin(&fs::read(path.join("points3D.bin"))?)?;
184    map.landmarks = landmarks
185        .into_iter()
186        .map(|landmark| (landmark.id, landmark))
187        .collect();
188
189    let keyframes = parse_images_bin(&fs::read(path.join("images.bin"))?)?;
190    map.keyframes = keyframes
191        .into_iter()
192        .map(|keyframe| (keyframe.frame.id, keyframe))
193        .collect();
194
195    Ok(map)
196}
197
198pub fn write_colmap_text_model(map: &VisualMap, path: impl AsRef<Path>) -> Result<(), ColmapError> {
199    let path = path.as_ref();
200    for camera in map.cameras.values() {
201        validated_colmap_camera_record(camera)?;
202    }
203    fs::create_dir_all(path)?;
204    fs::write(path.join("cameras.txt"), format_cameras_txt(map))?;
205    fs::write(path.join("images.txt"), format_images_txt(map))?;
206    fs::write(path.join("points3D.txt"), format_points3d_txt(map))?;
207    Ok(())
208}
209
210/// Binary counterpart of [`write_colmap_text_model`]: saves a `VisualMap` as
211/// COLMAP `cameras.bin`, `images.bin`, and `points3D.bin` under `path`.
212///
213/// The records mirror the text writer exactly — cameras go through
214/// [`colmap_camera_record`], images are named `image_<id>.jpg` and list every
215/// keypoint with its observed `POINT3D_ID` (or `-1`), and each point's
216/// `TRACK[]` comes from `Landmark::observations` sorted by
217/// `(frame_id, keypoint_index)` with white RGB and zero error. Ids that do not
218/// fit COLMAP's 32-bit camera/image id or track fields are rejected with
219/// [`ColmapError::InvalidExportInput`] before any file is written.
220pub fn write_colmap_binary_model(
221    map: &VisualMap,
222    path: impl AsRef<Path>,
223) -> Result<(), ColmapError> {
224    let path = path.as_ref();
225    let cameras_bytes = format_cameras_bin(map)?;
226    let images_bytes = format_images_bin(map)?;
227    let points_bytes = format_points3d_bin(map)?;
228    fs::create_dir_all(path)?;
229    fs::write(path.join("cameras.bin"), cameras_bytes)?;
230    fs::write(path.join("images.bin"), images_bytes)?;
231    fs::write(path.join("points3D.bin"), points_bytes)?;
232    Ok(())
233}
234
235fn u32_id(value: u64, what: &str) -> Result<u32, ColmapError> {
236    u32::try_from(value).map_err(|_| {
237        ColmapError::InvalidExportInput(format!(
238            "{what} {value} does not fit in u32 (COLMAP binary models use 32-bit ids)"
239        ))
240    })
241}
242
243fn format_cameras_bin(map: &VisualMap) -> Result<Vec<u8>, ColmapError> {
244    let mut cameras = map.cameras.values().collect::<Vec<_>>();
245    cameras.sort_by_key(|camera| camera.id);
246    let mut bytes = Vec::new();
247    bytes.extend_from_slice(&(cameras.len() as u64).to_le_bytes());
248    for camera in cameras {
249        let (model, params) = validated_colmap_camera_record(camera)?;
250        let model_id = colmap_id_from_camera_model(&model)?;
251        bytes.extend_from_slice(&u32_id(camera.id, "camera id")?.to_le_bytes());
252        bytes.extend_from_slice(&model_id.to_le_bytes());
253        bytes.extend_from_slice(&u64::from(camera.width).to_le_bytes());
254        bytes.extend_from_slice(&u64::from(camera.height).to_le_bytes());
255        for param in params {
256            bytes.extend_from_slice(&param.to_le_bytes());
257        }
258    }
259    Ok(bytes)
260}
261
262fn format_images_bin(map: &VisualMap) -> Result<Vec<u8>, ColmapError> {
263    let mut keyframes = map.keyframes.values().collect::<Vec<_>>();
264    keyframes.sort_by_key(|keyframe| keyframe.frame.id);
265    let mut bytes = Vec::new();
266    bytes.extend_from_slice(&(keyframes.len() as u64).to_le_bytes());
267    for keyframe in keyframes {
268        let frame = &keyframe.frame;
269        bytes.extend_from_slice(&u32_id(frame.id, "image id")?.to_le_bytes());
270        let pose = frame.pose.clone().unwrap_or_default();
271        let q = pose.world_to_camera.rotation.quaternion();
272        let t = pose.world_to_camera.translation;
273        for value in [q.w, q.i, q.j, q.k, t.x, t.y, t.z] {
274            bytes.extend_from_slice(&value.to_le_bytes());
275        }
276        bytes.extend_from_slice(&u32_id(frame.camera_id, "camera id")?.to_le_bytes());
277        bytes.extend_from_slice(format!("image_{}.jpg", frame.id).as_bytes());
278        bytes.push(0);
279
280        let mut landmark_by_keypoint = BTreeMap::new();
281        for observation in &keyframe.observations {
282            landmark_by_keypoint
283                .entry(observation.keypoint_index)
284                .or_insert(observation.landmark_id);
285        }
286        bytes.extend_from_slice(&(frame.keypoints.len() as u64).to_le_bytes());
287        for (keypoint_index, xy) in frame.keypoints.iter().enumerate() {
288            bytes.extend_from_slice(&xy.x.to_le_bytes());
289            bytes.extend_from_slice(&xy.y.to_le_bytes());
290            let point3d_id = match landmark_by_keypoint.get(&keypoint_index) {
291                Some(&landmark_id) => i64::try_from(landmark_id).map_err(|_| {
292                    ColmapError::InvalidExportInput(format!(
293                        "landmark id {landmark_id} does not fit in COLMAP's signed POINT3D_ID"
294                    ))
295                })?,
296                None => -1,
297            };
298            bytes.extend_from_slice(&point3d_id.to_le_bytes());
299        }
300    }
301    Ok(bytes)
302}
303
304fn format_points3d_bin(map: &VisualMap) -> Result<Vec<u8>, ColmapError> {
305    let mut landmarks = map.landmarks.values().collect::<Vec<_>>();
306    landmarks.sort_by_key(|landmark| landmark.id);
307    let mut bytes = Vec::new();
308    bytes.extend_from_slice(&(landmarks.len() as u64).to_le_bytes());
309    for landmark in landmarks {
310        bytes.extend_from_slice(&landmark.id.to_le_bytes());
311        for value in [
312            landmark.position.x,
313            landmark.position.y,
314            landmark.position.z,
315        ] {
316            bytes.extend_from_slice(&value.to_le_bytes());
317        }
318        bytes.extend_from_slice(&[255u8, 255u8, 255u8]);
319        bytes.extend_from_slice(&0.0f64.to_le_bytes());
320        let mut observations = landmark.observations.iter().collect::<Vec<_>>();
321        observations.sort_by_key(|observation| (observation.frame_id, observation.keypoint_index));
322        bytes.extend_from_slice(&(observations.len() as u64).to_le_bytes());
323        for observation in observations {
324            bytes.extend_from_slice(&u32_id(observation.frame_id, "track image id")?.to_le_bytes());
325            let keypoint_index = u32_id(observation.keypoint_index as u64, "track POINT2D_IDX")?;
326            bytes.extend_from_slice(&keypoint_index.to_le_bytes());
327        }
328    }
329    Ok(bytes)
330}
331
332/// Write a COLMAP text model suitable for bootstrapping a 3D Gaussian
333/// Splatting (3DGS) / NeRF training pipeline.
334///
335/// The writer materialises `cameras.txt`, `images.txt`, and `points3D.txt`
336/// under `out_dir` from a stereo VO output:
337///
338/// - `camera`: shared intrinsics (replicated as a single COLMAP camera id).
339///   Trailing radial `[k1, k2]` on a `Pinhole` is exported as `OPENCV`
340///   (see [`colmap_camera_record`]); any other params must already match the
341///   COLMAP layout for `camera.model`, otherwise the export is rejected
342/// - `poses`: per-frame `world_to_camera` SE3 (one COLMAP image entry each)
343/// - `left_features`: left keypoints per frame; only the keypoints that
344///   participate in a stereo feature are written to the per-image 2D point
345///   list, paired with the matching 3D landmark id
346/// - `stereo_per_frame`: triangulated stereo features whose `point_cam`
347///   (left-camera frame) is lifted through `pose.camera_to_world()` and
348///   aggregated into the sparse `points3D.txt` cloud
349/// - `image_name(frame_idx)` supplies the image filename to embed in
350///   `images.txt`; this must match the filenames the downstream trainer
351///   (gaussian-splatting / nerfstudio) will find under `<dataset>/images/`
352///
353/// Each stereo feature contributes one COLMAP landmark with one observation;
354/// temporal tracks are NOT merged across frames (the trainer optimises the
355/// gaussian primitives anyway, so a slightly denser cloud with duplicated
356/// landmark ids is the simpler, lower-friction MVP).
357pub fn write_colmap_text_model_for_3dgs<F>(
358    out_dir: impl AsRef<Path>,
359    camera: &Camera,
360    poses: &[Pose],
361    left_features: &[FeatureSet],
362    stereo_per_frame: &[Vec<StereoFeature>],
363    image_name: F,
364) -> Result<ColmapExportSummary, ColmapError>
365where
366    F: Fn(usize) -> String,
367{
368    if poses.len() != left_features.len() || poses.len() != stereo_per_frame.len() {
369        return Err(ColmapError::InvalidExportInput(format!(
370            "input length mismatch: poses={}, left_features={}, stereo_per_frame={}",
371            poses.len(),
372            left_features.len(),
373            stereo_per_frame.len(),
374        )));
375    }
376
377    // Reject CameraModel::Unknown(name) that the binary counterpart would
378    // also reject, so a caller driving both writers off the same input
379    // either gets both files or the same structured error from each.
380    let (colmap_model, colmap_params) = validated_colmap_camera_record(camera)?;
381
382    let out_dir = out_dir.as_ref();
383    fs::create_dir_all(out_dir)?;
384
385    // cameras.txt — one shared camera.
386    let mut cameras_text = String::from("# CAMERA_ID MODEL WIDTH HEIGHT PARAMS[]\n");
387    cameras_text.push_str(&format_camera_line(camera, &colmap_model, &colmap_params));
388    fs::write(out_dir.join("cameras.txt"), cameras_text)?;
389
390    // Aggregate world-frame landmarks (deduplication is intentionally skipped
391    // — see the doc comment above).
392    let mut landmark_count: u64 = 0;
393    let mut observation_count: usize = 0;
394    // For each frame, record `(left_keypoint_index, landmark_id)` so the
395    // images.txt second line can emit POINTS2D[] in the COLMAP-mandated
396    // `X Y POINT3D_ID` triples.
397    let mut frame_landmarks: Vec<Vec<(usize, u64)>> = Vec::with_capacity(poses.len());
398    let mut points3d_text =
399        String::from("# POINT3D_ID X Y Z R G B ERROR TRACK[] as IMAGE_ID POINT2D_IDX\n");
400
401    for (frame_idx, (pose, features)) in poses.iter().zip(stereo_per_frame.iter()).enumerate() {
402        let cam_to_world = pose.camera_to_world();
403        let mut per_frame: Vec<(usize, u64)> = Vec::with_capacity(features.len());
404        for feature in features {
405            landmark_count += 1;
406            let landmark_id = landmark_count;
407            let world_point = cam_to_world.transform_point(&feature.point_cam);
408            points3d_text.push_str(&format!(
409                "{} {} {} {} 255 255 255 0 {} {}\n",
410                landmark_id,
411                format_f64(world_point.x),
412                format_f64(world_point.y),
413                format_f64(world_point.z),
414                frame_idx,
415                feature.left_index,
416            ));
417            observation_count += 1;
418            per_frame.push((feature.left_index, landmark_id));
419        }
420        frame_landmarks.push(per_frame);
421    }
422    fs::write(out_dir.join("points3D.txt"), points3d_text)?;
423
424    // images.txt — alternating header line + 2D point list.
425    let mut images_text = String::from(
426        "# IMAGE_ID QW QX QY QZ TX TY TZ CAMERA_ID NAME\n# POINTS2D[] as X Y POINT3D_ID\n",
427    );
428    for (frame_idx, (pose, features)) in poses.iter().zip(left_features.iter()).enumerate() {
429        let q = pose.world_to_camera.rotation.quaternion();
430        let t = pose.world_to_camera.translation;
431        let name = image_name(frame_idx);
432        validate_colmap_image_name(&name, frame_idx)?;
433        images_text.push_str(&format!(
434            "{} {} {} {} {} {} {} {} {} {}\n",
435            frame_idx,
436            format_f64(q.w),
437            format_f64(q.i),
438            format_f64(q.j),
439            format_f64(q.k),
440            format_f64(t.x),
441            format_f64(t.y),
442            format_f64(t.z),
443            camera.id,
444            name,
445        ));
446        // Emit one `X Y POINT3D_ID` triple per left keypoint that participates
447        // in a triangulated stereo feature; the rest map to POINT3D_ID = -1.
448        let mut by_kp: Vec<(usize, u64)> = frame_landmarks[frame_idx].clone();
449        by_kp.sort_by_key(|(kp, _)| *kp);
450        let mut tokens: Vec<String> = Vec::with_capacity(features.len());
451        for (kp_idx, kp) in features.keypoints.iter().enumerate() {
452            let landmark_id = by_kp
453                .iter()
454                .find(|(observed, _)| *observed == kp_idx)
455                .map_or_else(
456                    || "-1".to_owned(),
457                    |(_, landmark_id)| landmark_id.to_string(),
458                );
459            tokens.push(format!(
460                "{} {} {}",
461                format_f64(kp.x),
462                format_f64(kp.y),
463                landmark_id
464            ));
465        }
466        images_text.push_str(&tokens.join(" "));
467        images_text.push('\n');
468    }
469    fs::write(out_dir.join("images.txt"), images_text)?;
470
471    Ok(ColmapExportSummary {
472        frame_count: poses.len(),
473        landmark_count: landmark_count as usize,
474        observation_count,
475    })
476}
477
478/// Binary counterpart of [`write_colmap_text_model_for_3dgs`]. Writes
479/// `cameras.bin`, `images.bin`, and `points3D.bin` under `out_dir` in
480/// the same little-endian layout COLMAP's reference reader expects (see
481/// [`parse_cameras_bin`], [`parse_images_bin`], [`parse_points3d_bin`]
482/// for the exact byte layouts). Useful for downstream trainers that
483/// only ingest the binary form (Inria 3DGS / nerfstudio both accept it
484/// transparently). All other semantics — single shared camera, sparse
485/// per-frame stereo landmarks lifted through `pose.camera_to_world()`,
486/// `frame_idx` as the COLMAP image id, `image_name(frame_idx)` for the
487/// `NAME` field — match the text writer exactly.
488pub fn write_colmap_binary_model_for_3dgs<F>(
489    out_dir: impl AsRef<Path>,
490    camera: &Camera,
491    poses: &[Pose],
492    left_features: &[FeatureSet],
493    stereo_per_frame: &[Vec<StereoFeature>],
494    image_name: F,
495) -> Result<ColmapExportSummary, ColmapError>
496where
497    F: Fn(usize) -> String,
498{
499    if poses.len() != left_features.len() || poses.len() != stereo_per_frame.len() {
500        return Err(ColmapError::InvalidExportInput(format!(
501            "input length mismatch: poses={}, left_features={}, stereo_per_frame={}",
502            poses.len(),
503            left_features.len(),
504            stereo_per_frame.len(),
505        )));
506    }
507
508    let out_dir = out_dir.as_ref();
509    fs::create_dir_all(out_dir)?;
510
511    // cameras.bin — single shared camera (matches the text writer).
512    let (colmap_model, colmap_params) = validated_colmap_camera_record(camera)?;
513    let model_id = colmap_id_from_camera_model(&colmap_model)?;
514    let camera_id_u32 = u32::try_from(camera.id).map_err(|_| {
515        ColmapError::InvalidExportInput(format!(
516            "camera id {} does not fit in u32 (COLMAP binary cameras use u32 ids)",
517            camera.id
518        ))
519    })?;
520    let mut cameras_bytes: Vec<u8> = Vec::new();
521    cameras_bytes.extend_from_slice(&1u64.to_le_bytes());
522    cameras_bytes.extend_from_slice(&camera_id_u32.to_le_bytes());
523    cameras_bytes.extend_from_slice(&model_id.to_le_bytes());
524    cameras_bytes.extend_from_slice(&(camera.width as u64).to_le_bytes());
525    cameras_bytes.extend_from_slice(&(camera.height as u64).to_le_bytes());
526    for param in &colmap_params {
527        cameras_bytes.extend_from_slice(&param.to_le_bytes());
528    }
529    fs::write(out_dir.join("cameras.bin"), cameras_bytes)?;
530
531    // Aggregate world-frame landmarks (deduplication is intentionally skipped
532    // — see the doc comment on `write_colmap_text_model_for_3dgs`).
533    let mut landmark_count: u64 = 0;
534    let mut observation_count: usize = 0;
535    let mut frame_landmarks: Vec<Vec<(usize, u64)>> = Vec::with_capacity(poses.len());
536    // We hold landmark records in memory so we can write the total count up
537    // front (the binary format requires `count` before the records).
538    let mut landmark_records: Vec<(u64, Point3<f64>, u32, u32)> = Vec::new();
539
540    for (frame_idx, (pose, features)) in poses.iter().zip(stereo_per_frame.iter()).enumerate() {
541        let image_id_u32 = u32::try_from(frame_idx).map_err(|_| {
542            ColmapError::InvalidExportInput(format!(
543                "frame index {frame_idx} does not fit in u32 (COLMAP binary uses u32 image ids)"
544            ))
545        })?;
546        let cam_to_world = pose.camera_to_world();
547        let mut per_frame: Vec<(usize, u64)> = Vec::with_capacity(features.len());
548        for feature in features {
549            landmark_count += 1;
550            let landmark_id = landmark_count;
551            let world_point = cam_to_world.transform_point(&feature.point_cam);
552            let kp_index_u32 = u32::try_from(feature.left_index).map_err(|_| {
553                ColmapError::InvalidExportInput(format!(
554                    "left keypoint index {} does not fit in u32",
555                    feature.left_index
556                ))
557            })?;
558            landmark_records.push((landmark_id, world_point, image_id_u32, kp_index_u32));
559            observation_count += 1;
560            per_frame.push((feature.left_index, landmark_id));
561        }
562        frame_landmarks.push(per_frame);
563    }
564
565    // points3D.bin: u64 count, then for each landmark:
566    //   u64 id, f64 x y z, u8 r g b (3 bytes), f64 error, u64 track_length,
567    //   [u32 image_id, u32 point2d_idx]*
568    let mut points_bytes: Vec<u8> = Vec::new();
569    points_bytes.extend_from_slice(&(landmark_records.len() as u64).to_le_bytes());
570    for (landmark_id, position, image_id_u32, kp_index_u32) in &landmark_records {
571        points_bytes.extend_from_slice(&landmark_id.to_le_bytes());
572        points_bytes.extend_from_slice(&position.x.to_le_bytes());
573        points_bytes.extend_from_slice(&position.y.to_le_bytes());
574        points_bytes.extend_from_slice(&position.z.to_le_bytes());
575        points_bytes.extend_from_slice(&[255u8, 255u8, 255u8]); // white RGB
576        points_bytes.extend_from_slice(&0.0f64.to_le_bytes()); // error
577        points_bytes.extend_from_slice(&1u64.to_le_bytes()); // track length
578        points_bytes.extend_from_slice(&image_id_u32.to_le_bytes());
579        points_bytes.extend_from_slice(&kp_index_u32.to_le_bytes());
580    }
581    fs::write(out_dir.join("points3D.bin"), points_bytes)?;
582
583    // images.bin: u64 count, then for each image:
584    //   u32 frame_id, f64 qw qx qy qz, f64 tx ty tz, u32 camera_id,
585    //   NULL-terminated NAME, u64 points2d_count, [f64 x, f64 y, i64 point3d_id]*
586    let mut images_bytes: Vec<u8> = Vec::new();
587    images_bytes.extend_from_slice(&(poses.len() as u64).to_le_bytes());
588    for (frame_idx, (pose, features)) in poses.iter().zip(left_features.iter()).enumerate() {
589        let image_id_u32 = u32::try_from(frame_idx).map_err(|_| {
590            ColmapError::InvalidExportInput(format!(
591                "frame index {frame_idx} does not fit in u32 (COLMAP binary uses u32 image ids)"
592            ))
593        })?;
594        images_bytes.extend_from_slice(&image_id_u32.to_le_bytes());
595        let q = pose.world_to_camera.rotation.quaternion();
596        let t = pose.world_to_camera.translation;
597        for v in [q.w, q.i, q.j, q.k, t.x, t.y, t.z] {
598            images_bytes.extend_from_slice(&v.to_le_bytes());
599        }
600        images_bytes.extend_from_slice(&camera_id_u32.to_le_bytes());
601        let name = image_name(frame_idx);
602        validate_colmap_image_name(&name, frame_idx)?;
603        images_bytes.extend_from_slice(name.as_bytes());
604        images_bytes.push(0u8); // NUL terminator
605
606        let by_kp = &frame_landmarks[frame_idx];
607        images_bytes.extend_from_slice(&(features.keypoints.len() as u64).to_le_bytes());
608        for (kp_idx, kp) in features.keypoints.iter().enumerate() {
609            images_bytes.extend_from_slice(&kp.x.to_le_bytes());
610            images_bytes.extend_from_slice(&kp.y.to_le_bytes());
611            let landmark_id = by_kp
612                .iter()
613                .find(|(observed, _)| *observed == kp_idx)
614                .map_or(-1, |(_, lid)| *lid as i64);
615            images_bytes.extend_from_slice(&landmark_id.to_le_bytes());
616        }
617    }
618    fs::write(out_dir.join("images.bin"), images_bytes)?;
619
620    Ok(ColmapExportSummary {
621        frame_count: poses.len(),
622        landmark_count: landmark_count as usize,
623        observation_count,
624    })
625}
626
627/// Write a COLMAP text model from a *merged-track* sparse reconstruction.
628///
629/// Unlike [`write_colmap_text_model_for_3dgs`] — which lifts one fresh landmark
630/// per frame (every `POINT3D` has a single-element `TRACK[]`) — this writer takes
631/// landmarks that are already merged across views by a global bundle adjustment:
632/// each `landmarks[i]` is `(world_position, observations)` where `observations`
633/// is the full `(frame, left_keypoint_index, pixel)` track. The emitted
634/// `points3D.txt` therefore carries genuine multi-view `TRACK[]` tails, which is
635/// what lets a downstream 3DGS optimizer converge to crisp geometry instead of
636/// the per-frame depth-lift fog.
637///
638/// `left_features[frame]` supplies the full keypoint list so `images.txt` can map
639/// each keypoint to its `POINT3D_ID` (or `-1` when untracked); the COLMAP
640/// `POINT2D_IDX` recorded in each track equals the keypoint index, since
641/// `POINTS2D[]` is emitted in keypoint order.
642pub fn write_colmap_reconstruction_for_3dgs<F>(
643    out_dir: impl AsRef<Path>,
644    camera: &Camera,
645    poses: &[Pose],
646    left_features: &[FeatureSet],
647    landmarks: &[ReconstructionLandmark],
648    image_name: F,
649) -> Result<ColmapExportSummary, ColmapError>
650where
651    F: Fn(usize) -> String,
652{
653    if poses.len() != left_features.len() {
654        return Err(ColmapError::InvalidExportInput(format!(
655            "input length mismatch: poses={}, left_features={}",
656            poses.len(),
657            left_features.len(),
658        )));
659    }
660    let (colmap_model, colmap_params) = validated_colmap_camera_record(camera)?;
661
662    let out_dir = out_dir.as_ref();
663    fs::create_dir_all(out_dir)?;
664
665    // cameras.txt — one shared camera.
666    let mut cameras_text = String::from("# CAMERA_ID MODEL WIDTH HEIGHT PARAMS[]\n");
667    cameras_text.push_str(&format_camera_line(camera, &colmap_model, &colmap_params));
668    fs::write(out_dir.join("cameras.txt"), cameras_text)?;
669
670    // For each frame, map left-keypoint index -> assigned POINT3D_ID so the
671    // images.txt second line can emit the `X Y POINT3D_ID` triples.
672    let mut frame_kp_to_point: Vec<std::collections::HashMap<usize, u64>> =
673        vec![std::collections::HashMap::new(); poses.len()];
674    let mut observation_count: usize = 0;
675
676    // points3D.txt — one line per merged landmark, with the full multi-view TRACK[].
677    let mut points3d_text =
678        String::from("# POINT3D_ID X Y Z R G B ERROR TRACK[] as IMAGE_ID POINT2D_IDX\n");
679    for (idx, (position, observations)) in landmarks.iter().enumerate() {
680        let point_id = (idx as u64) + 1;
681        points3d_text.push_str(&format!(
682            "{} {} {} {} 255 255 255 0",
683            point_id,
684            format_f64(position.x),
685            format_f64(position.y),
686            format_f64(position.z),
687        ));
688        for &(frame, left_idx, _) in observations {
689            if frame >= poses.len() {
690                continue;
691            }
692            // POINT2D_IDX == keypoint index, because images.txt emits POINTS2D[]
693            // in keypoint order below.
694            points3d_text.push_str(&format!(" {} {}", frame, left_idx));
695            frame_kp_to_point[frame].insert(left_idx, point_id);
696            observation_count += 1;
697        }
698        points3d_text.push('\n');
699    }
700    fs::write(out_dir.join("points3D.txt"), points3d_text)?;
701
702    // images.txt — alternating header line + 2D point list.
703    let mut images_text = String::from(
704        "# IMAGE_ID QW QX QY QZ TX TY TZ CAMERA_ID NAME\n# POINTS2D[] as X Y POINT3D_ID\n",
705    );
706    for (frame_idx, (pose, features)) in poses.iter().zip(left_features.iter()).enumerate() {
707        let q = pose.world_to_camera.rotation.quaternion();
708        let t = pose.world_to_camera.translation;
709        let name = image_name(frame_idx);
710        validate_colmap_image_name(&name, frame_idx)?;
711        images_text.push_str(&format!(
712            "{} {} {} {} {} {} {} {} {} {}\n",
713            frame_idx,
714            format_f64(q.w),
715            format_f64(q.i),
716            format_f64(q.j),
717            format_f64(q.k),
718            format_f64(t.x),
719            format_f64(t.y),
720            format_f64(t.z),
721            camera.id,
722            name,
723        ));
724        let kp_to_point = &frame_kp_to_point[frame_idx];
725        let mut tokens: Vec<String> = Vec::with_capacity(features.keypoints.len());
726        for (kp_idx, kp) in features.keypoints.iter().enumerate() {
727            let point_id = kp_to_point
728                .get(&kp_idx)
729                .map_or_else(|| "-1".to_owned(), |id| id.to_string());
730            tokens.push(format!(
731                "{} {} {}",
732                format_f64(kp.x),
733                format_f64(kp.y),
734                point_id
735            ));
736        }
737        images_text.push_str(&tokens.join(" "));
738        images_text.push('\n');
739    }
740    fs::write(out_dir.join("images.txt"), images_text)?;
741
742    Ok(ColmapExportSummary {
743        frame_count: poses.len(),
744        landmark_count: landmarks.len(),
745        observation_count,
746    })
747}
748
749/// Write a merged-track COLMAP text model with one calibrated camera per
750/// output image.  This is the multi-camera counterpart to
751/// [`write_colmap_reconstruction_for_3dgs`]; all camera ids and intrinsics are
752/// retained, and each `images.txt` header points at the camera corresponding
753/// to that frame.  The legacy single-camera writer is intentionally untouched.
754pub fn write_colmap_reconstruction_for_3dgs_with_cameras<F>(
755    out_dir: impl AsRef<Path>,
756    cameras: &[Camera],
757    poses: &[Pose],
758    left_features: &[FeatureSet],
759    landmarks: &[ReconstructionLandmark],
760    image_name: F,
761) -> Result<ColmapExportSummary, ColmapError>
762where
763    F: Fn(usize) -> String,
764{
765    if cameras.len() != poses.len() || poses.len() != left_features.len() {
766        return Err(ColmapError::InvalidExportInput(format!(
767            "input length mismatch: cameras={}, poses={}, left_features={}",
768            cameras.len(),
769            poses.len(),
770            left_features.len(),
771        )));
772    }
773    let mut unique_cameras = BTreeMap::<u64, Camera>::new();
774    for camera in cameras {
775        validated_colmap_camera_record(camera)?;
776        if camera.width == 0 || camera.height == 0 || camera.params.iter().any(|p| !p.is_finite()) {
777            return Err(ColmapError::InvalidExportInput(format!(
778                "camera {} has invalid dimensions or non-finite parameters",
779                camera.id
780            )));
781        }
782        if let Some(previous) = unique_cameras.insert(camera.id, camera.clone()) {
783            if previous != *camera {
784                return Err(ColmapError::InvalidExportInput(format!(
785                    "camera id {} is assigned incompatible definitions",
786                    camera.id
787                )));
788            }
789        }
790    }
791
792    let out_dir = out_dir.as_ref();
793    fs::create_dir_all(out_dir)?;
794
795    let mut cameras_text = String::from("# CAMERA_ID MODEL WIDTH HEIGHT PARAMS[]\n");
796    for camera in unique_cameras.values() {
797        let (model, params) = colmap_camera_record(camera);
798        cameras_text.push_str(&format_camera_line(camera, &model, &params));
799    }
800    fs::write(out_dir.join("cameras.txt"), cameras_text)?;
801
802    // Each keypoint's landmark id (0: none; ids start at 1), checked in
803    // landmark order so the first bad observation is the one reported.
804    let mut frame_kp_to_point: Vec<Vec<u64>> = left_features
805        .iter()
806        .map(|features| vec![0; features.keypoints.len()])
807        .collect();
808    let mut observation_count = 0usize;
809    for (landmark_index, (_, observations)) in landmarks.iter().enumerate() {
810        let point_id = landmark_index as u64 + 1;
811        for &(frame, keypoint, _) in observations {
812            if frame >= poses.len() || keypoint >= left_features[frame].keypoints.len() {
813                return Err(ColmapError::InvalidExportInput(format!(
814                    "landmark {} references invalid observation ({}, {})",
815                    point_id, frame, keypoint
816                )));
817            }
818            let slot = &mut frame_kp_to_point[frame][keypoint];
819            if *slot != 0 {
820                return Err(ColmapError::InvalidExportInput(format!(
821                    "keypoint ({}, {}) belongs to multiple exported landmarks",
822                    frame, keypoint
823                )));
824            }
825            *slot = point_id;
826            observation_count += 1;
827        }
828    }
829    let names: Vec<String> = (0..poses.len()).map(&image_name).collect();
830    for (frame, name) in names.iter().enumerate() {
831        validate_colmap_image_name(name, frame)?;
832    }
833
834    // The two large files, formatted in parallel chunks and joined in order.
835    let mut points3d_text =
836        String::from("# POINT3D_ID X Y Z R G B ERROR TRACK[] as IMAGE_ID POINT2D_IDX\n");
837    points3d_text.push_str(&format_in_chunks(landmarks.len(), |range, out| {
838        for landmark_index in range {
839            let (position, observations) = &landmarks[landmark_index];
840            push_display(out, landmark_index as u64 + 1);
841            for v in [position.x, position.y, position.z] {
842                out.push(' ');
843                push_f64(out, v);
844            }
845            out.push_str(" 255 255 255 0");
846            for &(frame, keypoint, _) in observations {
847                out.push(' ');
848                push_display(out, frame);
849                out.push(' ');
850                push_display(out, keypoint);
851            }
852            out.push('\n');
853        }
854    }));
855    fs::write(out_dir.join("points3D.txt"), points3d_text)?;
856
857    let mut images_text = String::from(
858        "# IMAGE_ID QW QX QY QZ TX TY TZ CAMERA_ID NAME\n# POINTS2D[] as X Y POINT3D_ID\n",
859    );
860    images_text.push_str(&format_in_chunks(poses.len(), |range, out| {
861        for frame in range {
862            let q = poses[frame].world_to_camera.rotation.quaternion();
863            let t = poses[frame].world_to_camera.translation;
864            push_display(out, frame);
865            for v in [q.w, q.i, q.j, q.k, t.x, t.y, t.z] {
866                out.push(' ');
867                push_f64(out, v);
868            }
869            out.push(' ');
870            push_display(out, cameras[frame].id);
871            out.push(' ');
872            out.push_str(&names[frame]);
873            out.push('\n');
874            let point_ids = &frame_kp_to_point[frame];
875            for (keypoint, pixel) in left_features[frame].keypoints.iter().enumerate() {
876                if keypoint > 0 {
877                    out.push(' ');
878                }
879                push_f64(out, pixel.x);
880                out.push(' ');
881                push_f64(out, pixel.y);
882                out.push(' ');
883                match point_ids[keypoint] {
884                    0 => out.push_str("-1"),
885                    id => push_display(out, id),
886                }
887            }
888            out.push('\n');
889        }
890    }));
891    fs::write(out_dir.join("images.txt"), images_text)?;
892
893    Ok(ColmapExportSummary {
894        frame_count: poses.len(),
895        landmark_count: landmarks.len(),
896        observation_count,
897    })
898}
899
900pub fn format_cameras_txt(map: &VisualMap) -> String {
901    let mut output = String::from("# CAMERA_ID MODEL WIDTH HEIGHT PARAMS[]\n");
902    let mut cameras = map.cameras.values().collect::<Vec<_>>();
903    cameras.sort_by_key(|camera| camera.id);
904    for camera in cameras {
905        let (model, params) = colmap_camera_record(camera);
906        output.push_str(&format_camera_line(camera, &model, &params));
907    }
908    output
909}
910
911pub fn format_images_txt(map: &VisualMap) -> String {
912    let mut output = String::from(
913        "# IMAGE_ID QW QX QY QZ TX TY TZ CAMERA_ID NAME\n# POINTS2D[] as X Y POINT3D_ID\n",
914    );
915    let mut keyframes = map.keyframes.values().collect::<Vec<_>>();
916    keyframes.sort_by_key(|keyframe| keyframe.frame.id);
917    for keyframe in keyframes {
918        let pose = keyframe.frame.pose.clone().unwrap_or_default();
919        let q = pose.world_to_camera.rotation.quaternion();
920        let t = pose.world_to_camera.translation;
921        output.push_str(&format!(
922            "{} {} {} {} {} {} {} {} {} image_{}.jpg\n",
923            keyframe.frame.id,
924            format_f64(q.w),
925            format_f64(q.i),
926            format_f64(q.j),
927            format_f64(q.k),
928            format_f64(t.x),
929            format_f64(t.y),
930            format_f64(t.z),
931            keyframe.frame.camera_id,
932            keyframe.frame.id,
933        ));
934
935        let mut observation_by_keypoint = keyframe
936            .observations
937            .iter()
938            .map(|observation| (observation.keypoint_index, observation.landmark_id))
939            .collect::<Vec<_>>();
940        observation_by_keypoint.sort_by_key(|(keypoint_index, _)| *keypoint_index);
941        let point_tokens = keyframe
942            .frame
943            .keypoints
944            .iter()
945            .enumerate()
946            .map(|(keypoint_index, xy)| {
947                let landmark_id = observation_by_keypoint
948                    .iter()
949                    .find(|(observed_index, _)| *observed_index == keypoint_index)
950                    .map_or_else(
951                        || "-1".to_owned(),
952                        |(_, landmark_id)| landmark_id.to_string(),
953                    );
954                format!("{} {} {}", format_f64(xy.x), format_f64(xy.y), landmark_id)
955            })
956            .collect::<Vec<_>>();
957        output.push_str(&point_tokens.join(" "));
958        output.push('\n');
959    }
960    output
961}
962
963pub fn format_points3d_txt(map: &VisualMap) -> String {
964    let mut output =
965        String::from("# POINT3D_ID X Y Z R G B ERROR TRACK[] as IMAGE_ID POINT2D_IDX\n");
966    let mut landmarks = map.landmarks.values().collect::<Vec<_>>();
967    landmarks.sort_by_key(|landmark| landmark.id);
968    for landmark in landmarks {
969        output.push_str(&format!(
970            "{} {} {} {} 255 255 255 0",
971            landmark.id,
972            format_f64(landmark.position.x),
973            format_f64(landmark.position.y),
974            format_f64(landmark.position.z),
975        ));
976        let mut observations = landmark.observations.iter().collect::<Vec<_>>();
977        observations.sort_by_key(|observation| (observation.frame_id, observation.keypoint_index));
978        for observation in observations {
979            output.push_str(&format!(
980                " {} {}",
981                observation.frame_id, observation.keypoint_index
982            ));
983        }
984        output.push('\n');
985    }
986    output
987}
988
989pub fn parse_cameras_txt(contents: &str) -> Result<Vec<Camera>, ColmapError> {
990    let mut cameras = Vec::new();
991    for line in contents.lines().map(str::trim) {
992        if line.is_empty() || line.starts_with('#') {
993            continue;
994        }
995        let tokens = line.split_whitespace().collect::<Vec<_>>();
996        if tokens.len() < 5 {
997            return Err(ColmapError::InvalidLine {
998                file: "cameras.txt",
999                line: line.to_owned(),
1000            });
1001        }
1002        let id = tokens[0].parse()?;
1003        let model = CameraModel::from_colmap_name(tokens[1]);
1004        let width = tokens[2].parse()?;
1005        let height = tokens[3].parse()?;
1006        let params = tokens[4..]
1007            .iter()
1008            .map(|value| value.parse::<f64>())
1009            .collect::<Result<Vec<_>, _>>()?;
1010        cameras.push(Camera {
1011            id,
1012            model,
1013            width,
1014            height,
1015            params,
1016        });
1017    }
1018    Ok(cameras)
1019}
1020
1021pub fn parse_points3d_txt(contents: &str) -> Result<Vec<Landmark>, ColmapError> {
1022    let mut landmarks = Vec::new();
1023    for line in contents.lines().map(str::trim) {
1024        if line.is_empty() || line.starts_with('#') {
1025            continue;
1026        }
1027        let tokens = line.split_whitespace().collect::<Vec<_>>();
1028        if tokens.len() < 8 {
1029            return Err(ColmapError::InvalidLine {
1030                file: "points3D.txt",
1031                line: line.to_owned(),
1032            });
1033        }
1034        landmarks.push(Landmark::new(
1035            tokens[0].parse()?,
1036            Point3::new(tokens[1].parse()?, tokens[2].parse()?, tokens[3].parse()?),
1037        ));
1038    }
1039    Ok(landmarks)
1040}
1041
1042pub fn parse_images_txt(contents: &str) -> Result<Vec<Keyframe>, ColmapError> {
1043    let mut keyframes = Vec::new();
1044    let mut lines = contents
1045        .lines()
1046        .map(str::trim)
1047        .filter(|line| !line.starts_with('#'));
1048
1049    while let Some(header) = lines.next() {
1050        if header.is_empty() {
1051            continue;
1052        }
1053
1054        let tokens = header.split_whitespace().collect::<Vec<_>>();
1055        if tokens.len() < 10 {
1056            return Err(ColmapError::InvalidLine {
1057                file: "images.txt",
1058                line: header.to_owned(),
1059            });
1060        }
1061
1062        let frame_id = tokens[0].parse()?;
1063        let qw = tokens[1].parse()?;
1064        let qx = tokens[2].parse()?;
1065        let qy = tokens[3].parse()?;
1066        let qz = tokens[4].parse()?;
1067        let tx = tokens[5].parse()?;
1068        let ty = tokens[6].parse()?;
1069        let tz = tokens[7].parse()?;
1070        let camera_id = tokens[8].parse()?;
1071        let points_line = lines.next().unwrap_or("");
1072
1073        let mut frame = Frame::new(frame_id, camera_id);
1074        frame.pose = Some(Pose::from_world_to_camera(
1075            UnitQuaternion::from_quaternion(Quaternion::new(qw, qx, qy, qz)),
1076            Vector3::new(tx, ty, tz),
1077        ));
1078
1079        let point_tokens = points_line.split_whitespace().collect::<Vec<_>>();
1080        if point_tokens.len() % 3 != 0 {
1081            return Err(ColmapError::InvalidLine {
1082                file: "images.txt",
1083                line: points_line.to_owned(),
1084            });
1085        }
1086
1087        let mut observations = Vec::new();
1088        for (keypoint_index, chunk) in point_tokens.chunks(3).enumerate() {
1089            let xy = Point2::new(chunk[0].parse()?, chunk[1].parse()?);
1090            frame.keypoints.push(xy);
1091
1092            let point_id = chunk[2].parse::<i64>()?;
1093            if point_id >= 0 {
1094                observations.push(Observation {
1095                    frame_id,
1096                    landmark_id: point_id as u64,
1097                    keypoint_index,
1098                    xy,
1099                });
1100            }
1101        }
1102
1103        keyframes.push(Keyframe {
1104            frame,
1105            observations,
1106        });
1107    }
1108
1109    Ok(keyframes)
1110}
1111
1112pub fn parse_cameras_bin(contents: &[u8]) -> Result<Vec<Camera>, ColmapError> {
1113    // A camera record contains the fixed fields plus at least the two
1114    // parameters required by every model accepted by `camera_model_from_colmap_id`
1115    // (EQUIRECTANGULAR's width and height; the others take three or more).
1116    const MIN_CAMERA_RECORD_BYTES: usize = 4 + 4 + 8 + 8 + (2 * 8);
1117    let mut reader = BinaryReader::new("cameras.bin", contents);
1118    let camera_count = reader.read_count_with_min_bytes("camera_count", MIN_CAMERA_RECORD_BYTES)?;
1119    let mut cameras = Vec::new();
1120    reader.try_reserve(&mut cameras, camera_count, "camera_count")?;
1121
1122    for _ in 0..camera_count {
1123        let id = reader.read_u32()? as u64;
1124        let model_id = reader.read_i32()?;
1125        let width = u32::try_from(reader.read_u64()?).map_err(|_| ColmapError::InvalidBinary {
1126            file: "cameras.bin",
1127            message: "camera width does not fit in u32".to_owned(),
1128        })?;
1129        let height = u32::try_from(reader.read_u64()?).map_err(|_| ColmapError::InvalidBinary {
1130            file: "cameras.bin",
1131            message: "camera height does not fit in u32".to_owned(),
1132        })?;
1133        let (model, parameter_count) = camera_model_from_colmap_id(model_id)?;
1134        let mut params = Vec::with_capacity(parameter_count);
1135        for _ in 0..parameter_count {
1136            params.push(reader.read_f64()?);
1137        }
1138        cameras.push(Camera {
1139            id,
1140            model,
1141            width,
1142            height,
1143            params,
1144        });
1145    }
1146
1147    reader.finish()?;
1148    Ok(cameras)
1149}
1150
1151pub fn parse_images_bin(contents: &[u8]) -> Result<Vec<Keyframe>, ColmapError> {
1152    Ok(parse_images_bin_records(contents)?
1153        .into_iter()
1154        .map(|(keyframe, _name)| keyframe)
1155        .collect())
1156}
1157
1158/// `(IMAGE_ID, NAME)` of every image in an `images.bin`, in file order.
1159/// [`parse_images_bin`] drops the names (a [`Keyframe`] has none).
1160pub fn parse_images_bin_names(contents: &[u8]) -> Result<Vec<(u64, String)>, ColmapError> {
1161    Ok(parse_images_bin_records(contents)?
1162        .into_iter()
1163        .map(|(keyframe, name)| (keyframe.frame.id, name))
1164        .collect())
1165}
1166
1167fn parse_images_bin_records(contents: &[u8]) -> Result<Vec<(Keyframe, String)>, ColmapError> {
1168    // An image with an empty NAME and no POINTS2D still occupies these fixed
1169    // fields. Each POINTS2D entry is two f64 coordinates plus one i64 id.
1170    const MIN_IMAGE_RECORD_BYTES: usize = 4 + (7 * 8) + 4 + 1 + 8;
1171    const IMAGE_POINT2D_BYTES: usize = 3 * 8;
1172    let mut reader = BinaryReader::new("images.bin", contents);
1173    let image_count = reader.read_count_with_min_bytes("image_count", MIN_IMAGE_RECORD_BYTES)?;
1174    let mut keyframes = Vec::new();
1175    reader.try_reserve(&mut keyframes, image_count, "image_count")?;
1176
1177    for _ in 0..image_count {
1178        let frame_id = reader.read_u32()? as u64;
1179        let qw = reader.read_f64()?;
1180        let qx = reader.read_f64()?;
1181        let qy = reader.read_f64()?;
1182        let qz = reader.read_f64()?;
1183        let tx = reader.read_f64()?;
1184        let ty = reader.read_f64()?;
1185        let tz = reader.read_f64()?;
1186        let camera_id = reader.read_u32()? as u64;
1187        let name = reader.read_null_terminated_string()?;
1188
1189        let mut frame = Frame::new(frame_id, camera_id);
1190        frame.pose = Some(Pose::from_world_to_camera(
1191            UnitQuaternion::from_quaternion(Quaternion::new(qw, qx, qy, qz)),
1192            Vector3::new(tx, ty, tz),
1193        ));
1194
1195        let point_count = reader.read_count_with_min_bytes("point_count", IMAGE_POINT2D_BYTES)?;
1196        reader.try_reserve(&mut frame.keypoints, point_count, "point_count keypoints")?;
1197        let mut observations = Vec::new();
1198        reader.try_reserve(&mut observations, point_count, "point_count observations")?;
1199        for keypoint_index in 0..point_count {
1200            let xy = Point2::new(reader.read_f64()?, reader.read_f64()?);
1201            frame.keypoints.push(xy);
1202
1203            let point_id = reader.read_i64()?;
1204            if point_id >= 0 {
1205                observations.push(Observation {
1206                    frame_id,
1207                    landmark_id: point_id as u64,
1208                    keypoint_index,
1209                    xy,
1210                });
1211            }
1212        }
1213
1214        keyframes.push((
1215            Keyframe {
1216                frame,
1217                observations,
1218            },
1219            name,
1220        ));
1221    }
1222
1223    reader.finish()?;
1224    Ok(keyframes)
1225}
1226
1227pub fn parse_points3d_bin(contents: &[u8]) -> Result<Vec<Landmark>, ColmapError> {
1228    Ok(parse_points3d_bin_with_colors(contents)?
1229        .into_iter()
1230        .map(|(landmark, _rgb)| landmark)
1231        .collect())
1232}
1233
1234/// [`parse_points3d_bin`] with each point's `[R, G, B]` colour, which a
1235/// [`Landmark`] does not carry.
1236pub fn parse_points3d_bin_with_colors(
1237    contents: &[u8],
1238) -> Result<Vec<(Landmark, [u8; 3])>, ColmapError> {
1239    // A POINT3D record contains id, xyz, RGB, error, and track_length before
1240    // its variable-length track entries. Each track entry is (image_id,
1241    // point2D_idx), two u32 values.
1242    const MIN_POINT3D_RECORD_BYTES: usize = 8 + (3 * 8) + 3 + 8 + 8;
1243    const POINT3D_TRACK_ENTRY_BYTES: usize = 2 * 4;
1244    let mut reader = BinaryReader::new("points3D.bin", contents);
1245    let point_count =
1246        reader.read_count_with_min_bytes("point3D_count", MIN_POINT3D_RECORD_BYTES)?;
1247    let mut landmarks = Vec::new();
1248    reader.try_reserve(&mut landmarks, point_count, "point3D_count")?;
1249
1250    for _ in 0..point_count {
1251        let id = reader.read_u64()?;
1252        let position = Point3::new(reader.read_f64()?, reader.read_f64()?, reader.read_f64()?);
1253        let rgb = reader.read_array::<3>()?;
1254        let _error = reader.read_f64()?;
1255        let track_length =
1256            reader.read_count_with_min_bytes("track_length", POINT3D_TRACK_ENTRY_BYTES)?;
1257        for _ in 0..track_length {
1258            let _image_id = reader.read_u32()?;
1259            let _point2d_index = reader.read_u32()?;
1260        }
1261        landmarks.push((Landmark::new(id, position), rgb));
1262    }
1263
1264    reader.finish()?;
1265    Ok(landmarks)
1266}
1267
1268/// Number of `PARAMS[]` the COLMAP camera model carries in `cameras.txt` /
1269/// `cameras.bin`, or `None` for models COLMAP does not define.
1270fn colmap_param_count(model: &CameraModel) -> Option<usize> {
1271    model.colmap_param_count()
1272}
1273
1274/// Map a camera onto the `(model, params)` record COLMAP expects.
1275///
1276/// visloc keeps self-calibrated radial distortion as two trailing `[k1, k2]`
1277/// slots on a `Pinhole` (see [`Camera::pinhole_radial`]) or a 6-parameter
1278/// `OpenCv`. COLMAP's `PINHOLE` has exactly four parameters and `OPENCV`
1279/// exactly eight, so writing those params verbatim produces a model file
1280/// that COLMAP rejects (or whose distortion other readers silently drop).
1281/// Such cameras are exported as `OPENCV` with `p1 = p2 = 0`, which is the
1282/// identical projection; an all-zero distortion tail on a `Pinhole`
1283/// collapses back to plain `PINHOLE`. Every other camera is returned as is.
1284pub fn colmap_camera_record(camera: &Camera) -> (CameraModel, Vec<f64>) {
1285    let params = &camera.params;
1286    match camera.model {
1287        CameraModel::Pinhole if params.len() > 4 && params[4..].iter().all(|&k| k == 0.0) => {
1288            (CameraModel::Pinhole, params[..4].to_vec())
1289        }
1290        CameraModel::Pinhole | CameraModel::OpenCv if params.len() > 4 && params.len() < 8 => {
1291            let mut opencv = params.clone();
1292            opencv.resize(8, 0.0);
1293            (CameraModel::OpenCv, opencv)
1294        }
1295        _ => (camera.model.clone(), params.clone()),
1296    }
1297}
1298
1299/// [`colmap_camera_record`] plus the checks every fallible writer needs: the
1300/// model must exist in COLMAP and carry exactly COLMAP's parameter count.
1301fn validated_colmap_camera_record(camera: &Camera) -> Result<(CameraModel, Vec<f64>), ColmapError> {
1302    let (model, params) = colmap_camera_record(camera);
1303    colmap_id_from_camera_model(&model)?;
1304    let expected = colmap_param_count(&model).ok_or_else(|| {
1305        ColmapError::InvalidExportInput(format!(
1306            "camera {} model {} is not a COLMAP camera model",
1307            camera.id,
1308            camera_model_to_colmap_name(&model)
1309        ))
1310    })?;
1311    if params.len() != expected {
1312        return Err(ColmapError::InvalidExportInput(format!(
1313            "camera {} model {} needs {expected} params for COLMAP, got {}",
1314            camera.id,
1315            camera_model_to_colmap_name(&model),
1316            params.len()
1317        )));
1318    }
1319    Ok((model, params))
1320}
1321
1322/// One `cameras.txt` line (with trailing newline).
1323fn format_camera_line(camera: &Camera, model: &CameraModel, params: &[f64]) -> String {
1324    let mut line = format!(
1325        "{} {} {} {}",
1326        camera.id,
1327        camera_model_to_colmap_name(model),
1328        camera.width,
1329        camera.height,
1330    );
1331    for param in params {
1332        line.push_str(&format!(" {}", format_f64(*param)));
1333    }
1334    line.push('\n');
1335    line
1336}
1337
1338fn camera_model_to_colmap_name(model: &CameraModel) -> &str {
1339    match model {
1340        CameraModel::Pinhole => "PINHOLE",
1341        CameraModel::SimplePinhole => "SIMPLE_PINHOLE",
1342        CameraModel::SimpleRadial => "SIMPLE_RADIAL",
1343        CameraModel::Radial => "RADIAL",
1344        CameraModel::OpenCv => "OPENCV",
1345        CameraModel::FullOpenCv => "FULL_OPENCV",
1346        CameraModel::OpenCvFisheye => "OPENCV_FISHEYE",
1347        CameraModel::SimpleRadialFisheye => "SIMPLE_RADIAL_FISHEYE",
1348        CameraModel::RadialFisheye => "RADIAL_FISHEYE",
1349        CameraModel::ThinPrismFisheye => "THIN_PRISM_FISHEYE",
1350        CameraModel::Fov => "FOV",
1351        CameraModel::Equirectangular => "EQUIRECTANGULAR",
1352        // Double Sphere is not a COLMAP model; the writers reject it through
1353        // `colmap_id_from_camera_model` before this name is ever emitted.
1354        CameraModel::DoubleSphere => "DOUBLE_SPHERE",
1355        CameraModel::Unknown(name) => name.as_str(),
1356    }
1357}
1358
1359fn format_f64(value: f64) -> String {
1360    let formatted = format!("{value:.12}");
1361    formatted
1362        .trim_end_matches('0')
1363        .trim_end_matches('.')
1364        .to_owned()
1365}
1366
1367/// Appends [`format_f64`]'s text without allocating.
1368fn push_f64(out: &mut String, value: f64) {
1369    use std::fmt::Write;
1370    let start = out.len();
1371    write!(out, "{value:.12}").expect("writing to a String cannot fail");
1372    let trimmed = out[start..]
1373        .trim_end_matches('0')
1374        .trim_end_matches('.')
1375        .len();
1376    out.truncate(start + trimmed);
1377}
1378
1379fn push_display(out: &mut String, value: impl std::fmt::Display) {
1380    use std::fmt::Write;
1381    write!(out, "{value}").expect("writing to a String cannot fail");
1382}
1383
1384/// `format(0..count)` split into contiguous ranges formatted on scoped
1385/// threads, the pieces joined in order: the same text as one sequential
1386/// call.
1387fn format_in_chunks(
1388    count: usize,
1389    format: impl Fn(std::ops::Range<usize>, &mut String) + Sync,
1390) -> String {
1391    let threads = std::thread::available_parallelism()
1392        .map_or(1, |n| n.get())
1393        .min(count.div_ceil(256).max(1));
1394    if threads <= 1 {
1395        let mut out = String::new();
1396        format(0..count, &mut out);
1397        return out;
1398    }
1399    let format = &format;
1400    let pieces: Vec<String> = std::thread::scope(|scope| {
1401        (0..threads)
1402            .map(|k| {
1403                let range = k * count / threads..(k + 1) * count / threads;
1404                scope.spawn(move || {
1405                    let mut out = String::new();
1406                    format(range, &mut out);
1407                    out
1408                })
1409            })
1410            .collect::<Vec<_>>()
1411            .into_iter()
1412            .map(|handle| handle.join().expect("formatting thread panicked"))
1413            .collect()
1414    });
1415    let mut out = String::with_capacity(pieces.iter().map(String::len).sum());
1416    for piece in pieces {
1417        out.push_str(&piece);
1418    }
1419    out
1420}
1421
1422/// Reject image NAME characters that would corrupt either writer surface.
1423///
1424/// - NUL terminates the binary NAME field early, silently truncating it.
1425/// - ASCII whitespace breaks the text format's space-separated tokens.
1426/// - LF / CR would inject a spurious image record into the text file (the
1427///   reader's alternating header + 2D-points line layout depends on
1428///   exactly one image per pair of lines).
1429///
1430/// Sharing the rule across both writers means any `image_name` closure
1431/// accepted by one is also accepted by the other — what makes it safe to
1432/// drive the text/binary writers from a single VO run against the same
1433/// input (as the KITTI → COLMAP → 3DGS smoke harness does).
1434fn validate_colmap_image_name(name: &str, frame_idx: usize) -> Result<(), ColmapError> {
1435    if let Some(bad_idx) = name
1436        .bytes()
1437        .position(|b| matches!(b, 0 | b' ' | b'\t' | b'\n' | b'\r'))
1438    {
1439        return Err(ColmapError::InvalidExportInput(format!(
1440            "image name for frame {frame_idx} contains an invalid character at byte {bad_idx} (NUL or ASCII whitespace would corrupt the COLMAP export); got {name:?}"
1441        )));
1442    }
1443    Ok(())
1444}
1445
1446fn colmap_id_from_camera_model(model: &CameraModel) -> Result<i32, ColmapError> {
1447    Ok(match model {
1448        CameraModel::SimplePinhole => 0,
1449        CameraModel::Pinhole => 1,
1450        CameraModel::SimpleRadial => 2,
1451        CameraModel::Radial => 3,
1452        CameraModel::OpenCv => 4,
1453        CameraModel::FullOpenCv => 6,
1454        CameraModel::OpenCvFisheye => 5,
1455        CameraModel::Fov => 7,
1456        CameraModel::SimpleRadialFisheye => 8,
1457        CameraModel::RadialFisheye => 9,
1458        CameraModel::ThinPrismFisheye => 10,
1459        CameraModel::Equirectangular => 17,
1460        CameraModel::DoubleSphere => {
1461            return Err(ColmapError::InvalidExportInput(
1462                "Double Sphere is not a COLMAP camera model".to_owned(),
1463            ));
1464        }
1465        CameraModel::Unknown(name) => match name.as_str() {
1466            "OPENCV_FISHEYE" => 5,
1467            "FULL_OPENCV" => 6,
1468            "FOV" => 7,
1469            "SIMPLE_RADIAL_FISHEYE" => 8,
1470            "RADIAL_FISHEYE" => 9,
1471            "THIN_PRISM_FISHEYE" => 10,
1472            other => {
1473                return Err(ColmapError::InvalidExportInput(format!(
1474                    "cannot encode CameraModel::Unknown({other:?}) as a COLMAP binary model id"
1475                )));
1476            }
1477        },
1478    })
1479}
1480
1481fn camera_model_from_colmap_id(model_id: i32) -> Result<(CameraModel, usize), ColmapError> {
1482    match model_id {
1483        0 => Ok((CameraModel::SimplePinhole, 3)),
1484        1 => Ok((CameraModel::Pinhole, 4)),
1485        2 => Ok((CameraModel::SimpleRadial, 4)),
1486        3 => Ok((CameraModel::Radial, 5)),
1487        4 => Ok((CameraModel::OpenCv, 8)),
1488        5 => Ok((CameraModel::OpenCvFisheye, 8)),
1489        6 => Ok((CameraModel::FullOpenCv, 12)),
1490        7 => Ok((CameraModel::Fov, 5)),
1491        8 => Ok((CameraModel::SimpleRadialFisheye, 4)),
1492        9 => Ok((CameraModel::RadialFisheye, 5)),
1493        10 => Ok((CameraModel::ThinPrismFisheye, 12)),
1494        17 => Ok((CameraModel::Equirectangular, 2)),
1495        other => Err(ColmapError::InvalidBinary {
1496            file: "cameras.bin",
1497            message: format!("unsupported camera model id {other}"),
1498        }),
1499    }
1500}
1501
1502#[cfg(test)]
1503#[allow(clippy::items_after_test_module)]
1504mod multi_camera_writer_tests {
1505    use super::*;
1506
1507    #[test]
1508    fn fisheye_camera_models_round_trip_through_colmap_ids() {
1509        for (model, id, parameter_count) in [
1510            (CameraModel::OpenCvFisheye, 5, 8),
1511            (CameraModel::FullOpenCv, 6, 12),
1512            (CameraModel::Fov, 7, 5),
1513            (CameraModel::SimpleRadialFisheye, 8, 4),
1514            (CameraModel::RadialFisheye, 9, 5),
1515            (CameraModel::ThinPrismFisheye, 10, 12),
1516        ] {
1517            assert_eq!(colmap_id_from_camera_model(&model).unwrap(), id);
1518            let (decoded, count) = camera_model_from_colmap_id(id).unwrap();
1519            assert_eq!(decoded, model);
1520            assert_eq!(count, parameter_count);
1521            assert_eq!(
1522                camera_model_to_colmap_name(&model),
1523                decoded.colmap_name().unwrap()
1524            );
1525        }
1526        // Double Sphere is not a COLMAP model.
1527        assert!(colmap_id_from_camera_model(&CameraModel::DoubleSphere).is_err());
1528    }
1529
1530    #[test]
1531    fn reconstruction_writer_preserves_per_image_camera_ids() {
1532        let root =
1533            std::env::temp_dir().join(format!("visloc_multi_camera_writer_{}", std::process::id()));
1534        let _ = fs::remove_dir_all(&root);
1535        let cameras = vec![
1536            Camera::pinhole(7, 100, 80, 50.0, 50.0, 50.0, 40.0),
1537            Camera::pinhole(9, 200, 160, 100.0, 80.0, 100.0, 80.0),
1538        ];
1539        let poses = vec![Pose::default(), Pose::default()];
1540        let features = vec![
1541            FeatureSet::new(vec![Point2::new(50.0, 40.0)], vec![vec![1.0]]).unwrap(),
1542            FeatureSet::new(vec![Point2::new(100.0, 80.0)], vec![vec![2.0]]).unwrap(),
1543        ];
1544        let landmarks = vec![
1545            (
1546                Point3::new(0.0, 0.0, 5.0),
1547                vec![(0usize, 0usize, Point2::new(50.0, 40.0))],
1548            ),
1549            (
1550                Point3::new(0.0, 0.0, 5.0),
1551                vec![(1usize, 0usize, Point2::new(100.0, 80.0))],
1552            ),
1553        ];
1554        let summary = write_colmap_reconstruction_for_3dgs_with_cameras(
1555            &root,
1556            &cameras,
1557            &poses,
1558            &features,
1559            &landmarks,
1560            |index| format!("image_{index}.png"),
1561        )
1562        .unwrap();
1563        assert_eq!(summary.frame_count, 2);
1564        assert_eq!(
1565            parse_cameras_txt(&fs::read_to_string(root.join("cameras.txt")).unwrap())
1566                .unwrap()
1567                .iter()
1568                .map(|camera| camera.id)
1569                .collect::<Vec<_>>(),
1570            vec![7, 9]
1571        );
1572        let headers = fs::read_to_string(root.join("images.txt"))
1573            .unwrap()
1574            .lines()
1575            .filter(|line| !line.starts_with('#') && !line.trim().is_empty())
1576            .step_by(2)
1577            .map(|line| {
1578                line.split_whitespace()
1579                    .nth(8)
1580                    .unwrap()
1581                    .parse::<u64>()
1582                    .unwrap()
1583            })
1584            .collect::<Vec<_>>();
1585        assert_eq!(headers, vec![7, 9]);
1586        let _ = fs::remove_dir_all(root);
1587    }
1588}
1589
1590struct BinaryReader<'a> {
1591    file: &'static str,
1592    contents: &'a [u8],
1593    offset: usize,
1594}
1595
1596impl<'a> BinaryReader<'a> {
1597    const fn new(file: &'static str, contents: &'a [u8]) -> Self {
1598        Self {
1599            file,
1600            contents,
1601            offset: 0,
1602        }
1603    }
1604
1605    fn read_u32(&mut self) -> Result<u32, ColmapError> {
1606        Ok(u32::from_le_bytes(self.read_array()?))
1607    }
1608
1609    fn read_i32(&mut self) -> Result<i32, ColmapError> {
1610        Ok(i32::from_le_bytes(self.read_array()?))
1611    }
1612
1613    fn read_u64(&mut self) -> Result<u64, ColmapError> {
1614        Ok(u64::from_le_bytes(self.read_array()?))
1615    }
1616
1617    fn read_i64(&mut self) -> Result<i64, ColmapError> {
1618        Ok(i64::from_le_bytes(self.read_array()?))
1619    }
1620
1621    fn read_f64(&mut self) -> Result<f64, ColmapError> {
1622        Ok(f64::from_le_bytes(self.read_array()?))
1623    }
1624
1625    /// Read a count and reject it before any allocation or long iteration when
1626    /// the remaining input cannot contain even the minimum-sized records.
1627    /// The bound is derived from this input's remaining bytes rather than a
1628    /// fixed model-size limit, so valid large models remain supported.
1629    fn read_count_with_min_bytes(
1630        &mut self,
1631        field: &'static str,
1632        min_record_bytes: usize,
1633    ) -> Result<usize, ColmapError> {
1634        let raw = self.read_u64()?;
1635        let count = usize::try_from(raw).map_err(|_| ColmapError::InvalidBinary {
1636            file: self.file,
1637            message: format!("{field}={raw} does not fit in usize"),
1638        })?;
1639        let required_bytes =
1640            count
1641                .checked_mul(min_record_bytes)
1642                .ok_or_else(|| ColmapError::InvalidBinary {
1643                    file: self.file,
1644                    message: format!("{field}={count} overflows minimum record-byte calculation"),
1645                })?;
1646        let remaining_bytes = self.contents.len().saturating_sub(self.offset);
1647        if required_bytes > remaining_bytes {
1648            return Err(ColmapError::InvalidBinary {
1649                file: self.file,
1650                message: format!("{field}={count} requires at least {required_bytes} remaining byte(s), but only {remaining_bytes} remain"),
1651            });
1652        }
1653        Ok(count)
1654    }
1655
1656    fn try_reserve<T>(
1657        &self,
1658        values: &mut Vec<T>,
1659        additional: usize,
1660        field: &'static str,
1661    ) -> Result<(), ColmapError> {
1662        values
1663            .try_reserve(additional)
1664            .map_err(|error| ColmapError::InvalidBinary {
1665                file: self.file,
1666                message: format!("{field}={additional} allocation failed: {error:?}"),
1667            })
1668    }
1669
1670    fn read_null_terminated_string(&mut self) -> Result<String, ColmapError> {
1671        let start = self.offset;
1672        while self.offset < self.contents.len() && self.contents[self.offset] != 0 {
1673            self.offset += 1;
1674        }
1675        if self.offset >= self.contents.len() {
1676            return Err(ColmapError::InvalidBinary {
1677                file: self.file,
1678                message: "unterminated string".to_owned(),
1679            });
1680        }
1681        let name = std::str::from_utf8(&self.contents[start..self.offset])
1682            .map_err(|error| ColmapError::InvalidBinary {
1683                file: self.file,
1684                message: format!("invalid UTF-8 string: {error}"),
1685            })?
1686            .to_owned();
1687        self.offset += 1;
1688        Ok(name)
1689    }
1690
1691    fn finish(&self) -> Result<(), ColmapError> {
1692        if self.offset == self.contents.len() {
1693            Ok(())
1694        } else {
1695            Err(ColmapError::InvalidBinary {
1696                file: self.file,
1697                message: format!(
1698                    "{} trailing byte(s) after parsing",
1699                    self.contents.len() - self.offset
1700                ),
1701            })
1702        }
1703    }
1704
1705    fn read_array<const N: usize>(&mut self) -> Result<[u8; N], ColmapError> {
1706        let bytes = self.read_bytes(N)?;
1707        let mut array = [0; N];
1708        array.copy_from_slice(bytes);
1709        Ok(array)
1710    }
1711
1712    fn read_bytes(&mut self, byte_count: usize) -> Result<&'a [u8], ColmapError> {
1713        let end =
1714            self.offset
1715                .checked_add(byte_count)
1716                .ok_or_else(|| ColmapError::InvalidBinary {
1717                    file: self.file,
1718                    message: "reader offset overflow".to_owned(),
1719                })?;
1720        if end > self.contents.len() {
1721            return Err(ColmapError::InvalidBinary {
1722                file: self.file,
1723                message: format!("unexpected end of file at byte {}", self.offset),
1724            });
1725        }
1726        let bytes = &self.contents[self.offset..end];
1727        self.offset = end;
1728        Ok(bytes)
1729    }
1730}