imodfile 0.2.1

A pure-Rust IMOD model file decoder/encoder — binary & ASCII, with Python bindings
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
//! Data model types mirroring the IMOD C structures.

use std::io::Seek;

use crate::chunk_ids::*;

// ── Point iterator types ──

/// Iterator over all points in a model, yielding `(object, contour, point, &Ipoint)`.
#[derive(Clone)]
pub struct ImodPointsIter<'a> {
    obj_idx: usize,
    cont_idx: usize,
    pt_idx: usize,
    model: &'a Imod,
}

impl<'a> Iterator for ImodPointsIter<'a> {
    type Item = (usize, usize, usize, &'a Ipoint);

    fn next(&mut self) -> Option<Self::Item> {
        while self.obj_idx < self.model.obj.len() {
            let obj = &self.model.obj[self.obj_idx];
            while self.cont_idx < obj.cont.len() {
                let cont = &obj.cont[self.cont_idx];
                if self.pt_idx < cont.pts.len() {
                    let item = (self.obj_idx, self.cont_idx, self.pt_idx, &cont.pts[self.pt_idx]);
                    self.pt_idx += 1;
                    return Some(item);
                }
                self.pt_idx = 0;
                self.cont_idx += 1;
            }
            self.cont_idx = 0;
            self.obj_idx += 1;
        }
        None
    }
}

/// Iterator over all points in an object, yielding `(contour, point, &Ipoint)`.
#[derive(Clone)]
pub struct IobjPointsIter<'a> {
    cont_idx: usize,
    pt_idx: usize,
    obj: &'a Iobj,
}

impl<'a> Iterator for IobjPointsIter<'a> {
    type Item = (usize, usize, &'a Ipoint);

    fn next(&mut self) -> Option<Self::Item> {
        while self.cont_idx < self.obj.cont.len() {
            let cont = &self.obj.cont[self.cont_idx];
            if self.pt_idx < cont.pts.len() {
                let item = (self.cont_idx, self.pt_idx, &cont.pts[self.pt_idx]);
                self.pt_idx += 1;
                return Some(item);
            }
            self.pt_idx = 0;
            self.cont_idx += 1;
        }
        None
    }
}

// ── Primitive types ──

/// A 3D point with single-precision coordinates.
///
/// Stored as three `f32` values representing
/// the X, Y, and Z position in the model's coordinate space.
/// Coordinates are typically in pixels relative to the image volume origin.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Ipoint {
    /// X coordinate (column / width axis).
    pub x: f32,
    /// Y coordinate (row / height axis).
    pub y: f32,
    /// Z coordinate (slice / depth axis).
    pub z: f32,
}

impl Default for Ipoint {
    fn default() -> Self {
        Ipoint {
            x: 0.0,
            y: 0.0,
            z: 0.0,
        }
    }
}

/// Current-index triple tracking the selected object, contour, and point.
///
/// Used by IMOD's GUI to remember the cursor position.  All fields default to `-1`
/// (nothing selected).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Iindex {
    /// Currently selected object index, or `-1` if none.
    pub object: i32,
    /// Currently selected contour index within that object, or `-1`.
    pub contour: i32,
    /// Currently selected point index within that contour, or `-1`.
    pub point: i32,
}

impl Default for Iindex {
    fn default() -> Self {
        Iindex {
            object: -1,
            contour: -1,
            point: -1,
        }
    }
}

/// A single clipping plane defined by the equation `Ax + By + Cz + D = 0`.
///
/// Points on the side of the plane toward which the normal points are kept;
/// points on the other side are clipped (hidden).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Iplane {
    /// Coefficient A of the plane equation.
    pub a: f32,
    /// Coefficient B of the plane equation.
    pub b: f32,
    /// Coefficient C of the plane equation.
    pub c: f32,
    /// Coefficient D of the plane equation (offset from origin).
    pub d: f32,
}

impl Default for Iplane {
    fn default() -> Self {
        Iplane {
            a: 0.0,
            b: 0.0,
            c: -1.0,
            d: 0.0,
        }
    }
}

/// A set of clipping planes (up to [`IMOD_CLIPSIZE`]).
///
/// Each active plane has a corresponding `normal` (direction) and `point`
/// (a point on the plane).  The plane is defined as
/// `dot(normal, (P - point)) >= 0` for kept geometry.
#[derive(Debug, Clone, PartialEq)]
pub struct IclipPlanes {
    /// Number of active clip planes (0 to [`IMOD_CLIPSIZE`]).
    pub count: i32,
    /// Bit flags controlling clip behaviour.
    pub flags: u32,
    /// Transpose/rotation flags for the clip matrix.
    pub trans: u32,
    /// Plane-select bits.
    pub plane: u32,
    /// Plane normals (one [`Ipoint`] per active plane, up to [`IMOD_CLIPSIZE`]).
    ///
    /// Each normal points toward the **kept** side of its plane.
    pub normal: Vec<Ipoint>,
    /// A point on each clip plane (one per active plane, up to [`IMOD_CLIPSIZE`]).
    pub point: Vec<Ipoint>,
}

impl Default for IclipPlanes {
    fn default() -> Self {
        let mut normal = Vec::with_capacity(IMOD_CLIPSIZE);
        let mut point = Vec::with_capacity(IMOD_CLIPSIZE);
        for _ in 0..IMOD_CLIPSIZE {
            normal.push(Ipoint {
                x: 0.0,
                y: 0.0,
                z: -1.0,
            });
            point.push(Ipoint::default());
        }
        IclipPlanes {
            count: 0,
            flags: 0,
            trans: 0,
            plane: 0,
            normal,
            point,
        }
    }
}

// ── Label types ──

/// A single label item within an [`Ilabel`] list.
///
/// Pairs a name with an index (typically a point or contour index).
#[derive(Debug, Clone, PartialEq)]
pub struct IlabelItem {
    /// Display name for this label item.
    pub name: String,
    /// Index this label refers to (e.g. point index within a contour).
    pub index: i32,
}

/// A label list that can belong to an object or contour.
///
/// Labels attach human-readable names to individual points or sub-regions.
/// The optional `name` is the label-group name; the `items` vec holds individual
/// labelled entries.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Ilabel {
    /// Optional group name for this label set.
    pub name: Option<String>,
    /// Individual label entries (point annotations, etc.).
    pub items: Vec<IlabelItem>,
}

// ── Generic storage ──

/// A single item in the IMOD general-purpose storage system.
///
/// Storage items are key–value pairs with type-flexible values
/// (either `f32` or `i32`).  The `flags` field indicates how to interpret
/// the payload.
#[derive(Debug, Clone, PartialEq)]
pub struct IstoreItem {
    /// Interpretation flags for this storage item.
    pub flags: u32,
    /// Application-defined index/key for this item.
    pub index: i32,
    /// Floating-point value (valid when `flags` indicates a float).
    pub value_f: f32,
    /// Integer value (valid when `flags` indicates an int).
    pub value_i: i32,
}

/// General-purpose storage container attached to a model, object, contour, or mesh.
///
/// IMOD uses this for application-specific metadata that doesn't fit into
/// the standard fields — e.g. custom properties from plug-ins.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Istore {
    /// Storage items (key–value pairs).
    pub items: Vec<IstoreItem>,
}

// ── Mesh parameters ──

/// Meshing parameters controlling automatic surface generation.
///
/// These are used by IMOD's mesh-generation algorithm and correspond
/// to the [`ID_MEPA`] chunk content.
#[derive(Debug, Clone, PartialEq)]
pub struct ImeshParams {
    /// Nine integer flags controlling meshing behaviour.
    pub flags: [i32; 9],
    /// Ten overlap thresholds for mesh generation (one per axis/direction).
    pub overlap: [f32; 10],
    /// Z-levels to skip when capping the mesh.
    pub cap_skip_zlist: Vec<i32>,
}

impl Default for ImeshParams {
    fn default() -> Self {
        ImeshParams {
            flags: [0; 9],
            overlap: [0.0; 10],
            cap_skip_zlist: Vec::new(),
        }
    }
}

// ── Mesh ──

/// A mesh: triangle/quad strips with vertex and index lists.
///
/// Vertices (`vert`) are 3D coordinates; indices (`list`) reference vertices.
/// Special sentinel values in the index list control primitive boundaries:
///
/// | Value | Meaning |
/// |-------|---------|
/// | `-1`  | End of list / end of strip |
/// | `-21` | Begin polygon (triangle/quad) |
/// | `-22` | End polygon |
/// | `-23` | Begin vertex/normal polygon pair |
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Imesh {
    /// Vertex coordinates (list of 3D points).
    pub vert: Vec<Ipoint>,
    /// Index list into `vert` (includes sentinel values for topology).
    pub list: Vec<i32>,
    /// Number of vertices (should equal `vert.len()`).
    pub vsize: i32,
    /// Length of the index list (should equal `list.len()`).
    pub lsize: i32,
    /// Mesh flags (bit field).
    pub flag: u32,
    /// Time index for time-series data.
    pub time: u16,
    /// Surface index this mesh belongs to.
    pub surf: u16,
    /// General-purpose storage attached to this mesh.
    pub store: Istore,
}

// ── Contour ──

/// A contour: a series of connected 3D points with optional per-point sizes.
///
/// Contours are the fundamental drawing primitive in IMOD.  They can represent
/// open paths (e.g. membrane traces) or closed polygons (e.g. object boundaries).
/// Per-point `sizes` allows variable-width display.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Icont {
    /// Point coordinates (in model/pixel coordinates).
    pub pts: Vec<Ipoint>,
    /// Number of points (should equal `pts.len()`).
    pub psize: i32,
    /// Contour bit flags.
    ///
    /// Common values:
    /// - `0x10` — scan-line pairs (contour stores line segments, not open/closed)
    /// - `0x08` — draw on all Z planes
    /// - `0x04` — wild contour (not confined to a single Z plane)
    pub flags: u32,
    /// Time index for time-series contour data (1-based when set; 0 = no time).
    pub time: i32,
    /// Surface index grouping contours within an object.
    pub surf: i32,
    /// Per-point sizes for variable-width display.
    ///
    /// When `Some`, the length must equal `psize`.  A value of `-1.0` means
    /// "use default size" for that point.
    pub sizes: Option<Vec<f32>>,
    /// Optional label attached to this contour.
    pub label: Option<Ilabel>,
    /// General-purpose storage attached to this contour.
    pub store: Istore,
}

// ── Object flags ──

/// Draw contour as open (not closed to the first point).
pub const IMOD_OBJFLAG_OPEN: u32 = 0x001;
/// Fill contour polygons with colour.
pub const IMOD_OBJFLAG_FILL: u32 = 0x002;
/// Display as scattered points rather than connected contours.
pub const IMOD_OBJFLAG_SCAT: u32 = 0x004;
/// Flip surface normals (inside-out rendering).
pub const IMOD_OBJFLAG_OUT: u32 = 0x008;
/// Draw mesh in 3-D view.
pub const IMOD_OBJFLAG_MESH: u32 = 0x010;
/// Hide lines in 3-D mode (surface-only display).
pub const IMOD_OBJFLAG_NOLINE: u32 = 0x020;
/// Light both sides of surfaces.
pub const IMOD_OBJFLAG_TWO_SIDE: u32 = 0x040;
/// Use fill colour (from `fillred`/`fillgreen`/`fillblue`) for polygons.
pub const IMOD_OBJFLAG_FCOLOR: u32 = 0x080;
/// Object is hidden (not displayed).
pub const IMOD_OBJFLAG_OFF: u32 = 0x100;
/// Draw the object's label text in the model window.
pub const IMOD_OBJFLAG_DRAW_LABEL: u32 = 0x200;
/// Scale line width with zoom level.
pub const IMOD_OBJFLAG_SCALE_WDTH: u32 = 0x400;
/// Object contours have time indices.
pub const IMOD_OBJFLAG_TIME: u32 = 0x800;
/// Use the `valblack` / `valwhite` range for colour mapping.
pub const IMOD_OBJFLAG_USE_VALUE: u32 = 0x1000;
/// Use material colour (from `ambient`/`diffuse`/`specular`) for display.
pub const IMOD_OBJFLAG_MCOLOR: u32 = 0x2000;
/// Use fill colour for individual points.
pub const IMOD_OBJFLAG_FCOLOR_PNT: u32 = 0x4000;
/// Display points on every Z section, not only the current one.
pub const IMOD_OBJFLAG_PNT_ON_SEC: u32 = 0x8000;
/// Enable anti-aliased point/line drawing.
pub const IMOD_OBJFLAG_ANTI_ALIAS: u32 = 0x10000;

// ── Object ──

/// A model object: contains contours, meshes, material properties, and clips.
///
/// Objects are the top-level grouping unit within a model.  Each object has
/// its own display settings (colour, line width, material, clip planes, etc.)
/// and holds a list of contours and meshes.
#[derive(Debug, Clone, PartialEq)]
pub struct Iobj {
    /// Object name (max [`IOBJ_STRSIZE`] bytes when serialised).
    pub name: String,
    /// Extra integer array (16 entries, padded to 64 bytes in the binary format).
    ///
    /// In the IMOD C struct this is a fixed-size `int extra[16]` field used for
    /// backward-compatible extensions.  Most entries are zero; the first few may
    /// carry contour count, flags, axis, and draw mode on older files.
    pub extra: Vec<i32>,
    /// Contours belonging to this object.
    pub cont: Vec<Icont>,
    /// Meshes belonging to this object.
    pub mesh: Vec<Imesh>,
    /// Number of contours (should track `cont.len()`).
    pub contsize: i32,
    /// Number of real meshes (non-thickness meshes, should track `mesh.len()`).
    pub meshsize: i32,
    /// Surface count for mesh subdivision.
    pub surfsize: i32,
    /// Object bit flags (see [`IMOD_OBJFLAG_OPEN`] etc.).
    pub flags: u32,
    /// Slice axis: `0` = Z (default), `1` = Y, `2` = X.
    pub axis: i32,
    /// 3-D drawing mode (`1` = filled, `2` = mesh, etc.).
    pub drawmode: i32,
    /// Object colour — red component in `[0, 1]`.
    pub red: f32,
    /// Object colour — green component in `[0, 1]`.
    pub green: f32,
    /// Object colour — blue component in `[0, 1]`.
    pub blue: f32,
    /// Point-draw size (radius in pixels).
    pub pdrawsize: i32,
    /// Symbol shape for points (`0` = circle, `1` = square, etc.).
    pub symbol: u8,
    /// Symbol size multiplier.
    pub symsize: u8,
    /// Line width for 2-D display (pixels).
    pub linewidth2: u8,
    /// Line width for 3-D display (pixels).
    pub linewidth: u8,
    /// Line style (`0` = solid, `1` = dashed, etc.).
    pub linesty: u8,
    /// Symbol flags (bit field for symbol drawing options).
    pub symflags: u8,
    /// Symbol padding byte (reserved).
    pub sympad: u8,
    /// Object transparency (`0` = opaque, `255` = fully transparent).
    pub trans: u8,
    /// Material ambient intensity (`0`–`255`).
    pub ambient: u8,
    /// Material diffuse intensity (`0`–`255`).
    pub diffuse: u8,
    /// Material specular intensity (`0`–`255`).
    pub specular: u8,
    /// Material shininess exponent (`0`–`255`).
    pub shininess: u8,
    /// Fill colour — red component (`0`–`255`).
    pub fillred: u8,
    /// Fill colour — green component (`0`–`255`).
    pub fillgreen: u8,
    /// Fill colour — blue component (`0`–`255`).
    pub fillblue: u8,
    /// Mesh quality / subdivision level.
    pub quality: u8,
    /// Material flags word 2 (extended material properties).
    pub mat2: i32,
    /// Black (low) value for colour-mapped display.
    pub valblack: u8,
    /// White (high) value for colour-mapped display.
    pub valwhite: u8,
    /// Material flags word 2 as a byte-sized value (legacy field).
    pub matflags2: i32,
    /// Mesh thickness in pixels (when rendered as thickened mesh).
    pub mesh_thickness: u8,
    /// Clipping planes applied to this object.
    pub clips: IclipPlanes,
    /// Optional label for this object.
    pub label: Option<Ilabel>,
    /// Optional meshing parameters for automatic surface generation.
    pub mesh_param: Option<ImeshParams>,
    /// General-purpose storage attached to this object.
    pub store: Istore,
}

impl Iobj {
    /// Iterate over every point in this object with its indices.
    ///
    /// Yields `(contour_index, point_index, &Ipoint)`.
    #[must_use]
    pub fn points(&self) -> IobjPointsIter<'_> {
        IobjPointsIter {
            cont_idx: 0,
            pt_idx: 0,
            obj: self,
        }
    }
}

impl Default for Iobj {
    fn default() -> Self {
        Iobj {
            name: String::new(),
            extra: vec![0; IOBJ_EXSIZE],
            cont: Vec::new(),
            mesh: Vec::new(),
            contsize: 0,
            meshsize: 0,
            surfsize: 0,
            flags: IMOD_OBJFLAG_DRAW_LABEL | IMOD_OBJFLAG_SCALE_WDTH,
            axis: 0,
            drawmode: 1,
            red: 0.5,
            green: 0.5,
            blue: 0.5,
            pdrawsize: 0,
            symbol: 0,
            symsize: 3,
            linewidth2: 1,
            linewidth: 1,
            linesty: 0,
            symflags: 0,
            sympad: 0,
            trans: 0,
            ambient: 102,
            diffuse: 255,
            specular: 127,
            shininess: 4,
            fillred: 0,
            fillgreen: 0,
            fillblue: 0,
            quality: 0,
            mat2: 0,
            valblack: 0,
            valwhite: 255,
            matflags2: 0,
            mesh_thickness: 0,
            clips: IclipPlanes::default(),
            label: None,
            mesh_param: None,
            store: Istore::default(),
        }
    }
}

// ── Slicer angles ──

/// Slicer angle/time data from the IMOD slicer window.
///
/// Each entry records a rotation angle and centre position at a given time point,
/// used for controlling the oblique-slicer tool.
#[derive(Debug, Clone, PartialEq)]
pub struct SlicerAngles {
    /// Time point index.
    pub time: i32,
    /// Three rotation angles (pitch, yaw, roll in degrees).
    pub angles: [f32; 3],
    /// Rotation centre in model coordinates.
    pub center: Ipoint,
    /// Label identifying this angle set (max [`ANGLE_STRSIZE`] bytes).
    pub label: String,
}

impl Default for SlicerAngles {
    fn default() -> Self {
        SlicerAngles {
            time: 0,
            angles: [0.0; 3],
            center: Ipoint::default(),
            label: String::new(),
        }
    }
}

// ── Reference image ──

/// Reference image transforms for image alignment.
///
/// Used when a model is transformed relative to its original image stack
/// (e.g. after alignment or rotation in the IMOD tilt-series workflow).
#[derive(Debug, Clone, PartialEq)]
pub struct IrefImage {
    /// Current scale factors applied to the image relative to the reference.
    pub cscale: Ipoint,
    /// Current translation applied to the image relative to the reference.
    pub ctrans: Ipoint,
    /// Current rotation applied to the image relative to the reference.
    pub crot: Ipoint,
    /// Original translation (before alignment).
    pub otrans: Ipoint,
    /// Original rotation (before alignment).
    pub orot: Ipoint,
}

impl Default for IrefImage {
    fn default() -> Self {
        IrefImage {
            cscale: Ipoint {
                x: 1.0,
                y: 1.0,
                z: 1.0,
            },
            ctrans: Ipoint::default(),
            crot: Ipoint::default(),
            otrans: Ipoint::default(),
            orot: Ipoint::default(),
        }
    }
}

// ── View ──

/// A camera/view configuration.
///
/// Stores the perspective, orientation, and clip settings for one saved
/// camera position in the 3-D viewer.
#[derive(Debug, Clone, PartialEq)]
pub struct Iview {
    /// Vertical field of view in degrees.
    pub fovy: f32,
    /// Viewing radius (in model units).
    pub rad: f32,
    /// Display aspect ratio (width / height).
    pub aspect: f32,
    /// Near clipping plane distance.
    pub cnear: f32,
    /// Far clipping plane distance.
    pub cfar: f32,
    /// Camera rotation (Euler angles in degrees).
    pub rot: Ipoint,
    /// Camera translation in model coordinates.
    pub trans: Ipoint,
    /// Camera scale factors per axis.
    pub scale: Ipoint,
    /// World-mode flags controlling light and coordinate-space settings.
    ///
    /// Default is `0x0010` (`VIEW_WORLD_LIGHT`).
    pub world: u32,
    /// 4×4 view matrix (row-major, identity = default).
    pub mat: [f32; 16],
    /// View label (max [`VIEW_STRSIZE`] bytes).
    pub label: String,
    /// X position of the light source.
    pub lightx: f32,
    /// Y position of the light source.
    pub lighty: f32,
    /// Z position of the light source / focal plane distance.
    pub plax: f32,
    /// Depth-cue start distance (where dimming begins).
    pub dcstart: f32,
    /// Depth-cue end distance (where dimming is complete).
    pub dcend: f32,
    /// Clip planes applied to this view.
    pub clips: IclipPlanes,
    /// Per-object view override data (raw bytes for each object).
    pub objview: Vec<u8>,
    /// Number of object-view overrides.
    pub objvsize: i32,
}

impl Default for Iview {
    fn default() -> Self {
        let mut mat = [0.0f32; 16];
        mat[0] = 1.0;
        mat[5] = 1.0;
        mat[10] = 1.0;
        mat[15] = 1.0;
        Iview {
            fovy: 0.0,
            rad: 1.0,
            aspect: 1.0,
            cnear: 0.0,
            cfar: 1.0,
            rot: Ipoint::default(),
            trans: Ipoint::default(),
            scale: Ipoint {
                x: 1.0,
                y: 1.0,
                z: 1.0,
            },
            world: 0x0010, // VIEW_WORLD_LIGHT
            mat,
            label: String::new(),
            lightx: 0.0,
            lighty: 0.0,
            plax: 5.0,
            dcstart: 0.0,
            dcend: 1.0,
            clips: IclipPlanes::default(),
            objview: Vec::new(),
            objvsize: 0,
        }
    }
}

// ── Model flags ──

/// Model has been flipped in Y and Z (image orientation flag).
pub const IMODF_FLIPYZ: u32 = 0x0001;
/// File was saved as "new to 3dmod" format (IMOD ≥ 4.0).
pub const IMODF_NEW_TO_3DMOD: u32 = 0x0002;
/// Tilt-series alignment is valid.
pub const IMODF_TILTOK: u32 = 0x0004;
/// The old transform origin is relative to the image centre.
pub const IMODF_OTRANS_ORIGIN: u32 = 0x0008;
/// Z values stored as `z - 0.5` (IMOD convention for pixel centres).
pub const IMODF_Z_FROM_MINUSPT5: u32 = 0x0010;
/// Material block 1 stores byte values (not integers).
pub const IMODF_MAT1_IS_BYTES: u32 = 0x0020;
/// Model supports multiple clip planes per object.
pub const IMODF_MULTIPLE_CLIP: u32 = 0x0040;
/// Model stores mesh thickness data.
pub const IMODF_HAS_MESH_THICK: u32 = 0x0080;
/// Image was rotated 90° around X when loaded.
pub const IMODF_ROT90X: u32 = 0x0100;

// ── Top-level model ──

/// The top-level IMOD model structure.
///
/// A model holds a list of objects, image dimensions, coordinate transforms,
/// view settings, slicer angles, and general-purpose storage.
///
/// ## Round-trip note
///
/// The binary writer always ORs the flags
/// [`IMODF_MAT1_IS_BYTES`] | [`IMODF_MULTIPLE_CLIP`] | [`IMODF_HAS_MESH_THICK`]
/// into the stored value, matching the behaviour of the IMOD C library
/// (`imodel_write`).  After a write–read cycle, these three flag bits will
/// always be set regardless of their original value.
#[derive(Debug, Clone, PartialEq)]
pub struct Imod {
    /// Model name (max `IMOD_STRSIZE` bytes when serialised).
    /// Default is `"IMOD-NewModel"`.
    pub name: String,
    /// List of objects in this model.
    pub obj: Vec<Iobj>,
    /// Number of objects (should track `obj.len()`).
    pub objsize: i32,
    /// Model-level bit flags (see [`IMODF_FLIPYZ`] etc.).
    pub flags: u32,
    /// Default 3-D drawing mode for new objects.
    pub drawmode: i32,
    /// GUI mouse mode at save time.
    pub mousemode: i32,
    /// Black (low) image level for display mapping.
    pub blacklevel: i32,
    /// White (high) image level for display mapping.
    pub whitelevel: i32,
    /// Image width in pixels (X dimension).
    pub xmax: i32,
    /// Image height in pixels (Y dimension).
    pub ymax: i32,
    /// Image depth in pixels / slices (Z dimension).
    pub zmax: i32,
    /// X offset applied to model coordinates (in pixels).
    pub xoffset: f32,
    /// Y offset applied to model coordinates.
    pub yoffset: f32,
    /// Z offset applied to model coordinates.
    pub zoffset: f32,
    /// X scale factor applied to model coordinates.
    pub xscale: f32,
    /// Y scale factor applied to model coordinates.
    pub yscale: f32,
    /// Z scale factor applied to model coordinates.
    pub zscale: f32,
    /// Currently selected object/contour/point index.
    pub cindex: Iindex,
    /// Current time index for time-series data.
    pub ctime: i32,
    /// Maximum time index across all objects.
    pub tmax: i32,
    /// Pixel size in physical units (e.g. nanometres per pixel).
    pub pixsize: f32,
    /// Units flag: `0` = unspecified, `1` = mm, `2` = µm, `3` = nm.
    pub units: i32,
    /// Checksum (unused in practice, written as 0).
    pub csum: u32,
    /// Model rotation angle α (Euler / scene-rotation angle).
    pub alpha: f32,
    /// Model rotation angle β.
    pub beta: f32,
    /// Model rotation angle γ.
    pub gamma: f32,
    /// Saved camera views.
    pub view: Vec<Iview>,
    /// Index of the currently active view.
    pub cview: i32,
    /// Number of views (should track `view.len()`).
    pub viewsize: i32,
    /// Index of the currently selected object group.
    pub cur_obj_group: i32,
    /// Index of the currently selected mesh surface.
    pub cur_mesh_surf: i32,
    /// X/Y binning factor (for montage / large-image support).
    pub xybin: i32,
    /// Z binning factor.
    pub zbin: i32,
    /// Optional reference-image transforms.
    pub ref_image: Option<IrefImage>,
    /// Slicer angle/time records.
    pub slicer_angles: Vec<SlicerAngles>,
    /// General-purpose storage attached to this model.
    pub store: Istore,
}

impl Default for Imod {
    fn default() -> Self {
        Imod {
            name: "IMOD-NewModel".to_string(),
            obj: Vec::new(),
            objsize: 0,
            flags: IMODF_NEW_TO_3DMOD | IMODF_Z_FROM_MINUSPT5,
            drawmode: 1,
            mousemode: 0,
            blacklevel: 0,
            whitelevel: 255,
            xmax: 1,
            ymax: 1,
            zmax: 1,
            xoffset: 0.0,
            yoffset: 0.0,
            zoffset: 0.0,
            xscale: 1.0,
            yscale: 1.0,
            zscale: 1.0,
            cindex: Iindex::default(),
            ctime: 0,
            tmax: 0,
            pixsize: 1.0,
            units: 0,
            csum: 0,
            alpha: 0.0,
            beta: 0.0,
            gamma: 0.0,
            view: Vec::new(),
            cview: 0,
            viewsize: 0,
            cur_obj_group: -1,
            cur_mesh_surf: -1,
            xybin: 1,
            zbin: 1,
            ref_image: None,
            slicer_angles: Vec::new(),
            store: Istore::default(),
        }
    }
}

impl Imod {
    /// Iterate over every point in the model with its indices.
    ///
    /// Yields `(object_index, contour_index, point_index, &Ipoint)`.
    ///
    /// ```rust
    /// use imodfile::{Imod, Iobj, Icont, Ipoint};
    /// let mut model = Imod::default();
    /// model.obj.push(Iobj {
    ///     name: "test".into(),
    ///     cont: vec![Icont {
    ///         psize: 2,
    ///         pts: vec![
    ///             Ipoint { x: 1.0, y: 2.0, z: 3.0 },
    ///             Ipoint { x: 4.0, y: 5.0, z: 6.0 },
    ///         ],
    ///         ..Icont::default()
    ///     }],
    ///     ..Iobj::default()
    /// });
    /// for (oi, ci, pi, pt) in model.points() {
    ///     println!("obj {oi} cont {ci} pt {pi}: {} {} {}", pt.x, pt.y, pt.z);
    /// }
    /// assert_eq!(model.points().count(), 2);
    /// ```
    #[must_use]
    pub fn points(&self) -> ImodPointsIter<'_> {
        ImodPointsIter {
            obj_idx: 0,
            cont_idx: 0,
            pt_idx: 0,
            model: self,
        }
    }

    /// Open a model file by path, auto-detecting binary vs ASCII format.
    ///
    /// This is the simplest way to read a model:
    ///
    /// ```no_run
    /// use imodfile::Imod;
    /// let model = Imod::load("model.mod").unwrap();
    /// println!("{} objects", model.obj.len());
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`crate::error::ImodError::Io`] if the file cannot be opened,
    /// [`crate::error::ImodError::InvalidMagic`] if the format is not recognised,
    /// or [`crate::error::ImodError::CorruptData`] if the file is truncated or malformed.
    pub fn load(path: &str) -> crate::error::ImodResult<Self> {
        let file = std::fs::File::open(path).map_err(|e| {
            crate::error::ImodError::Io(std::io::Error::new(
                e.kind(),
                format!("cannot open {}: {}", path, e),
            ))
        })?;
        let mut reader = std::io::BufReader::new(file);

        // Try binary; fall back to ASCII on magic mismatch
        let result = crate::binary::read_binary(&mut reader);
        match result {
            Ok(model) => Ok(model),
            Err(crate::error::ImodError::InvalidMagic) => {
                reader.rewind().map_err(crate::error::ImodError::Io)?;
                crate::ascii::read_ascii(&mut reader)
            }
            Err(e) => Err(e),
        }
    }

    /// Save model to a file path.  Uses binary format unless the path
    /// ends with `.txt` or `.ascii` (then ASCII).
    ///
    /// ```no_run
    /// use imodfile::Imod;
    /// let model = Imod::load("input.mod").unwrap();
    /// model.save("output.mod").unwrap();
    /// model.save("output.txt").unwrap();   // ASCII
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`crate::error::ImodError::Io`] if the file cannot be created or written.
    pub fn save(&self, path: &str) -> crate::error::ImodResult<()> {
        let file = std::fs::File::create(path).map_err(|e| {
            crate::error::ImodError::Io(std::io::Error::new(
                e.kind(),
                format!("cannot create {}: {}", path, e),
            ))
        })?;
        let want_ascii = path.ends_with(".txt") || path.ends_with(".ascii");
        if want_ascii {
            let mut writer = std::io::BufWriter::new(file);
            crate::ascii::write_ascii(&mut writer, self)
        } else {
            let mut writer = std::io::BufWriter::new(file);
            crate::binary::write_binary(&mut writer, self)
        }
    }

    /// Write all contour points to a text file, one `x y z` per line
    /// with empty rows between contours.
    ///
    /// ```no_run
    /// use imodfile::Imod;
    /// let model = Imod::load("model.mod").unwrap();
    /// model.save_points("points.txt").unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`std::io::Error`] if the file cannot be created or written.
    pub fn save_points(&self, path: &str) -> std::io::Result<()> {
        let file = std::fs::File::create(path)?;
        let mut writer = std::io::BufWriter::new(file);
        self.write_points(&mut writer)
    }

    /// Return all points from all objects/contours, one point per line.
    ///
    /// Contours are separated by an empty row.  Each line is `x y z`.
    /// Scattered-point objects use the same format as regular contours.
    ///
    /// ```
    /// use imodfile::{Imod, Iobj, Icont, Ipoint};
    /// let mut model = Imod::default();
    /// model.obj.push(Iobj {
    ///     name: "test".into(),
    ///     cont: vec![Icont {
    ///         psize: 2,
    ///         pts: vec![
    ///             Ipoint { x: 1.0, y: 2.0, z: 3.0 },
    ///             Ipoint { x: 4.0, y: 5.0, z: 6.0 },
    ///         ],
    ///         ..Icont::default()
    ///     }],
    ///     ..Iobj::default()
    /// });
    /// let out = model.to_points();
    /// assert!(out.starts_with("1 2 3"));
    /// assert!(out.contains("4 5 6"));
    /// ```
    #[must_use]
    pub fn to_points(&self) -> String {
        use std::fmt::Write;
        let mut out = String::new();
        for obj in &self.obj {
            for (ci, cont) in obj.cont.iter().enumerate() {
                if ci > 0 {
                    out.push('\n');
                }
                for pt in &cont.pts {
                    let _ = writeln!(out, "{} {} {}", pt.x, pt.y, pt.z);
                }
            }
        }
        out
    }

    /// Write all points from all objects/contours to a writer.
    ///
    /// Contours are separated by an empty row.
    ///
    /// ```
    /// use std::io::Cursor;
    /// use imodfile::{Imod, Iobj, Icont, Ipoint};
    /// let mut model = Imod::default();
    /// model.obj.push(Iobj {
    ///     name: "test".into(),
    ///     cont: vec![Icont {
    ///         psize: 1,
    ///         pts: vec![Ipoint { x: 7.0, y: 8.0, z: 9.0 }],
    ///         ..Icont::default()
    ///     }],
    ///     ..Iobj::default()
    /// });
    /// let mut buf = Vec::new();
    /// model.write_points(&mut Cursor::new(&mut buf)).unwrap();
    /// assert!(String::from_utf8_lossy(&buf).contains("7 8 9"));
    /// ```
    pub fn write_points<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
        for obj in &self.obj {
            for (ci, cont) in obj.cont.iter().enumerate() {
                if ci > 0 {
                    writeln!(writer)?;
                }
                for pt in &cont.pts {
                    writeln!(writer, "{} {} {}", pt.x, pt.y, pt.z)?;
                }
            }
        }
        Ok(())
    }
}