imodfile 0.1.0

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
//! Binary IMOD format writer.
//!
//! All integer and float values are stored in **big-endian** byte order
//! (per the IMOD binary specification).
//! The file is structured as a sequence of tagged chunks, each with a 4-byte
//! ID and a 4-byte data-size, followed by the chunk's payload.

use std::io::{Write, Seek};

use crate::chunk_ids::*;
use crate::error::ImodResult;
use crate::model::*;

// ═════════════════════════════════════════════════════════════════════════════
//  Helper I/O traits
// ═════════════════════════════════════════════════════════════════════════════

trait WriteImod: Write + Seek {
    fn write_u32(&mut self, v: u32) -> ImodResult<()> {
        self.write_all(&v.to_be_bytes())?;
        Ok(())
    }

    fn write_i32(&mut self, v: i32) -> ImodResult<()> {
        self.write_all(&v.to_be_bytes())?;
        Ok(())
    }

    fn write_f32(&mut self, v: f32) -> ImodResult<()> {
        self.write_all(&v.to_be_bytes())?;
        Ok(())
    }

    fn write_u16(&mut self, v: u16) -> ImodResult<()> {
        self.write_all(&v.to_be_bytes())?;
        Ok(())
    }

    fn write_u8(&mut self, v: u8) -> ImodResult<()> {
        self.write_all(&[v])?;
        Ok(())
    }

    fn write_i32s(&mut self, v: &[i32]) -> ImodResult<()> {
        for &val in v {
            self.write_i32(val)?;
        }
        Ok(())
    }

    fn write_f32s(&mut self, v: &[f32]) -> ImodResult<()> {
        for &val in v {
            self.write_f32(val)?;
        }
        Ok(())
    }

    fn write_bytes(&mut self, data: &[u8]) -> ImodResult<()> {
        self.write_all(data)?;
        Ok(())
    }

    fn write_padded_string(&mut self, s: &str, len: usize) -> ImodResult<()> {
        let mut buf = vec![0u8; len];
        let bytes = s.as_bytes();
        let copy_len = bytes.len().min(len);
        buf[..copy_len].copy_from_slice(&bytes[..copy_len]);
        self.write_all(&buf)?;
        Ok(())
    }
}

impl<T: Write + Seek> WriteImod for T {}

/// Write an IMOD model to a binary writer.
pub fn write_binary<W: Write + Seek>(writer: &mut W, model: &Imod) -> ImodResult<()> {
    // Set writing flags (same as C imodel_write: mod->flags |= IMODF_MAT1_IS_BYTES | ...)
    let write_flags = model.flags
        | IMODF_MAT1_IS_BYTES
        | IMODF_MULTIPLE_CLIP
        | IMODF_HAS_MESH_THICK;

    // Magic + version
    writer.write_u32(ID_IMOD)?;
    writer.write_u32(ID_VERSION_V12)?;

    // Name
    writer.write_padded_string(&model.name, IMOD_STRSIZE)?;

    // 9 ints
    writer.write_i32s(&[
        model.xmax,
        model.ymax,
        model.zmax,
        model.objsize,
        write_flags as i32,
        model.drawmode,
        model.mousemode,
        model.blacklevel,
        model.whitelevel,
    ])?;

    // 6 floats: offsets + scales
    writer.write_f32s(&[
        model.xoffset,
        model.yoffset,
        model.zoffset,
        model.xscale,
        model.yscale,
        model.zscale,
    ])?;

    // 5 ints: cindex + ctime + tmax
    writer.write_i32s(&[
        model.cindex.object,
        model.cindex.contour,
        model.cindex.point,
        model.ctime,
        model.tmax,
    ])?;

    writer.write_f32(model.pixsize)?;
    writer.write_i32(model.units)?;
    writer.write_u32(model.csum)?;

    writer.write_f32s(&[model.alpha, model.beta, model.gamma])?;

    // Objects
    for obj in &model.obj {
        write_object(writer, obj, model.flags)?;
    }

    // Views
    for view in &model.view {
        write_view(writer, view)?;
    }

    // Slicer angles
    for slan in &model.slicer_angles {
        write_slicer_angles(writer, slan)?;
    }

    // Model store
    if !model.store.items.is_empty() {
        write_store(writer, ID_MOST, &model.store)?;
    }

    // End marker
    writer.write_u32(ID_IEOF)?;
    writer.flush()?;
    Ok(())
}

fn write_object<W: WriteImod>(writer: &mut W, obj: &Iobj, _flags: u32) -> ImodResult<()> {
    writer.write_u32(ID_OBJT)?;
    writer.write_padded_string(&obj.name, IOBJ_STRSIZE)?;

    // Write extra + 4 more ints (contsize, flags, axis, drawmode)
    for &e in &obj.extra {
        writer.write_i32(e)?;
    }
    writer.write_i32(obj.contsize)?;
    writer.write_u32(obj.flags)?;
    writer.write_i32(obj.axis)?;
    writer.write_i32(obj.drawmode)?;

    writer.write_f32(obj.red)?;
    writer.write_f32(obj.green)?;
    writer.write_f32(obj.blue)?;
    writer.write_i32(obj.pdrawsize)?;

    // 8 symbol bytes
    writer.write_u8(obj.symbol)?;
    writer.write_u8(obj.symsize)?;
    writer.write_u8(obj.linewidth2)?;
    writer.write_u8(obj.linewidth)?;
    writer.write_u8(obj.linesty)?;
    writer.write_u8(obj.symflags)?;
    writer.write_u8(obj.sympad)?;
    writer.write_u8(obj.trans)?;

    // Number of real (non-thickness) meshes
    let num_real = obj.mesh.iter().filter(|m| m.flag & 0x80000000 == 0).count() as i32;
    writer.write_i32(num_real)?;
    writer.write_i32(obj.surfsize)?;

    // Object label
    if let Some(ref label) = obj.label {
        write_label(writer, ID_OLBL, label)?;
    }

    // Contours
    for cont in &obj.cont {
        write_contour(writer, cont)?;
    }

    // Meshes
    for mesh in &obj.mesh {
        write_mesh(writer, mesh)?;
    }

    // Clip planes
    if obj.clips.count > 0 {
        write_clip_planes(writer, &obj.clips)?;
    }

    // Material
    writer.write_u32(ID_IMAT)?;
    writer.write_u32(SIZE_IMAT)?;
    // 4 bytes: ambient, diffuse, specular, shininess
    writer.write_u8(obj.ambient)?;
    writer.write_u8(obj.diffuse)?;
    writer.write_u8(obj.specular)?;
    writer.write_u8(obj.shininess)?;
    // 4 bytes: fillred, fillgreen, fillblue, quality
    writer.write_u8(obj.fillred)?;
    writer.write_u8(obj.fillgreen)?;
    writer.write_u8(obj.fillblue)?;
    writer.write_u8(obj.quality)?;
    // 4 bytes: mat2
    writer.write_i32(obj.mat2)?;
    // 4 bytes: valblack, valwhite, matflags2 as byte, mesh_thickness
    writer.write_u8(obj.valblack)?;
    writer.write_u8(obj.valwhite)?;
    writer.write_u8(obj.matflags2 as u8)?;
    writer.write_u8(obj.mesh_thickness)?;

    // Mesh params
    if let Some(ref mp) = obj.mesh_param {
        writer.write_u32(ID_MEPA)?;
        writer.write_u32(9 * 4 + 10 * 4)?; // 9 ints + 10 floats = 76
        for &f in &mp.flags {
            writer.write_i32(f)?;
        }
        for &f in &mp.overlap {
            writer.write_f32(f)?;
        }

        if !mp.cap_skip_zlist.is_empty() {
            writer.write_u32(ID_SKLI)?;
            writer.write_u32((mp.cap_skip_zlist.len() * 4) as u32)?;
            for &v in &mp.cap_skip_zlist {
                writer.write_i32(v)?;
            }
        }
    }

    // Object store
    if !obj.store.items.is_empty() {
        write_store(writer, ID_OBST, &obj.store)?;
    }

    Ok(())
}

fn write_contour<W: WriteImod>(writer: &mut W, cont: &Icont) -> ImodResult<()> {
    writer.write_u32(ID_CONT)?;
    writer.write_i32(cont.psize)?;
    writer.write_u32(cont.flags)?;
    writer.write_i32(cont.time)?;
    writer.write_i32(cont.surf)?;

    // Points as 3 floats each
    for pt in &cont.pts {
        writer.write_f32(pt.x)?;
        writer.write_f32(pt.y)?;
        writer.write_f32(pt.z)?;
    }

    // Label
    if let Some(ref label) = cont.label {
        write_label(writer, ID_LABL, label)?;
    }

    // Point sizes
    if let Some(ref sizes) = cont.sizes {
        writer.write_u32(ID_SIZE)?;
        writer.write_u32((cont.psize as u32) * 4)?;
        for &s in sizes {
            writer.write_f32(s)?;
        }
    }

    // Contour store
    if !cont.store.items.is_empty() {
        write_store(writer, ID_COST, &cont.store)?;
    }

    Ok(())
}

fn write_mesh<W: WriteImod>(writer: &mut W, mesh: &Imesh) -> ImodResult<()> {
    writer.write_u32(ID_MESH)?;
    writer.write_i32(mesh.vsize)?;
    writer.write_i32(mesh.lsize)?;
    writer.write_u32(mesh.flag)?;
    writer.write_u16(mesh.time)?;
    writer.write_u16(mesh.surf)?;

    // Vertices as 3 floats each
    for pt in &mesh.vert {
        writer.write_f32(pt.x)?;
        writer.write_f32(pt.y)?;
        writer.write_f32(pt.z)?;
    }

    // Index list
    for &idx in &mesh.list {
        writer.write_i32(idx)?;
    }

    // Mesh store
    if !mesh.store.items.is_empty() {
        write_store(writer, ID_MEST, &mesh.store)?;
    }

    Ok(())
}

fn write_label<W: WriteImod>(writer: &mut W, tag: u32, label: &Ilabel) -> ImodResult<()> {
    writer.write_u32(tag)?;

    // Calculate padded label name length
    let name_bytes = label.name.as_deref().unwrap_or("").as_bytes();
    let name_len_actual = name_bytes.len() + 1; // include NUL
    let name_len_padded = ((name_len_actual + 3) / 4) * 4;
    let name_pad = name_len_padded - name_len_actual;

    // Item sizes
    let mut total = 4 + 4; // nl + name_len
    total += name_len_padded as u32;
    for item in &label.items {
        let item_bytes = item.name.as_bytes();
        let item_actual = item_bytes.len() + 1;
        let item_padded = ((item_actual + 3) / 4) * 4;
        total += 4 + 4; // index + item_len
        total += item_padded as u32;
    }

    writer.write_u32(total)?;

    // Number of labels
    writer.write_i32(label.items.len() as i32)?;

    // Padded name length + name data
    writer.write_i32(name_len_padded as i32)?;
    writer.write_bytes(name_bytes)?;
    writer.write_u8(0)?;
    for _ in 0..name_pad {
        writer.write_u8(0)?;
    }

    // Items
    for item in &label.items {
        writer.write_i32(item.index)?;
        let item_bytes = item.name.as_bytes();
        let item_actual = item_bytes.len() + 1;
        let item_padded = ((item_actual + 3) / 4) * 4;
        let item_pad = item_padded - item_actual;

        writer.write_i32(item_padded as i32)?;
        writer.write_bytes(item_bytes)?;
        writer.write_u8(0)?;
        for _ in 0..item_pad {
            writer.write_u8(0)?;
        }
    }

    Ok(())
}

fn write_clip_planes<W: WriteImod>(writer: &mut W, clips: &IclipPlanes) -> ImodResult<()> {
    writer.write_u32(ID_CLIP)?;
    let data_size = SIZE_CLIP + 24 * (clips.count.max(1) as u32 - 1);
    writer.write_u32(data_size)?;

    writer.write_u8(clips.count as u8)?;
    let flags_bytes = clips.flags.to_le_bytes();
    writer.write_bytes(&flags_bytes[..3])?;

    for i in 0..clips.count.max(1) as usize {
        let idx = i.min(clips.normal.len().saturating_sub(1));
        writer.write_f32(clips.normal[idx].x)?;
        writer.write_f32(clips.normal[idx].y)?;
        writer.write_f32(clips.normal[idx].z)?;
        writer.write_f32(clips.point[idx].x)?;
        writer.write_f32(clips.point[idx].y)?;
        writer.write_f32(clips.point[idx].z)?;
    }

    Ok(())
}

fn write_view<W: WriteImod>(writer: &mut W, view: &Iview) -> ImodResult<()> {
    writer.write_u32(ID_VIEW)?;

    // Calculate size
    let size = 4 + 4 + 4 + 4 + 4 // fovy, rad, aspect, cnear, cfar
        + VIEW_STRSIZE as u32 // label
        + 4 + 4 + 4 + 4 // lightx, lighty, dcstart, dcend, world
        + 4 // world
        + 16 * 4 // mat
        + 3 * 4 // scale
        + 3 * 4 // trans
        + 3 * 4 // rot
        + 4 + 4 + 4 + 4 // clips: count, flags, trans, plane
        + (view.clips.count.max(0) as u32) * 24; // normals + points

    writer.write_u32(size)?;

    writer.write_f32(view.fovy)?;
    writer.write_f32(view.rad)?;
    writer.write_f32(view.aspect)?;
    writer.write_f32(view.cnear)?;
    writer.write_f32(view.cfar)?;
    writer.write_padded_string(&view.label, VIEW_STRSIZE)?;
    writer.write_f32(view.lightx)?;
    writer.write_f32(view.lighty)?;
    writer.write_f32(view.dcstart)?;
    writer.write_f32(view.dcend)?;
    writer.write_u32(view.world)?;

    for &m in &view.mat {
        writer.write_f32(m)?;
    }

    writer.write_f32(view.scale.x)?;
    writer.write_f32(view.scale.y)?;
    writer.write_f32(view.scale.z)?;
    writer.write_f32(view.trans.x)?;
    writer.write_f32(view.trans.y)?;
    writer.write_f32(view.trans.z)?;
    writer.write_f32(view.rot.x)?;
    writer.write_f32(view.rot.y)?;
    writer.write_f32(view.rot.z)?;

    // Clips
    writer.write_i32(view.clips.count)?;
    writer.write_u32(view.clips.flags)?;
    writer.write_u32(view.clips.trans)?;
    writer.write_u32(view.clips.plane)?;
    if view.clips.count > 0 {
        let n = view.clips.count as usize;
        for i in 0..n {
            writer.write_f32(view.clips.normal[i].x)?;
            writer.write_f32(view.clips.normal[i].y)?;
            writer.write_f32(view.clips.normal[i].z)?;
        }
        for i in 0..n {
            writer.write_f32(view.clips.point[i].x)?;
            writer.write_f32(view.clips.point[i].y)?;
            writer.write_f32(view.clips.point[i].z)?;
        }
    }

    Ok(())
}

fn write_slicer_angles<W: WriteImod>(writer: &mut W, slan: &SlicerAngles) -> ImodResult<()> {
    writer.write_u32(ID_SLAN)?;
    writer.write_u32(SIZE_SLAN)?;
    writer.write_i32(slan.time)?;
    writer.write_f32(slan.angles[0])?;
    writer.write_f32(slan.angles[1])?;
    writer.write_f32(slan.angles[2])?;
    writer.write_f32(slan.center.x)?;
    writer.write_f32(slan.center.y)?;
    writer.write_f32(slan.center.z)?;
    writer.write_padded_string(&slan.label, ANGLE_STRSIZE)?;
    Ok(())
}

fn write_store<W: WriteImod>(writer: &mut W, tag: u32, store: &Istore) -> ImodResult<()> {
    if store.items.is_empty() {
        return Ok(());
    }
    writer.write_u32(tag)?;

    let data_size = 4 + (store.items.len() * 16) as u32; // 4 for count + 16 per item
    writer.write_u32(data_size)?;

    writer.write_i32(store.items.len() as i32)?;
    for item in &store.items {
        writer.write_u32(item.flags)?;
        writer.write_i32(item.index)?;
        writer.write_f32(item.value_f)?;
        writer.write_i32(item.value_i)?;
    }

    Ok(())
}