cadmpeg-codec-f3d 0.1.4

Decode and encode Fusion .f3d B-rep, design, and appearance data.
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
// SPDX-License-Identifier: Apache-2.0
//! Frame SAB (ACIS binary) token streams.
//!
//! The active slice of an ASM `.smbh` or `.smb` stream uses one-byte type tags.
//! Payloads have fixed widths or length prefixes. A `0x11` tag terminates a
//! record at subtype depth zero, while `0x0f` and `0x10` delimit subtype scopes.
//! Record names join a chain of `0x0e` sub-identifiers ending in one `0x0d`
//! identifier.
//!
//! [`frame`] returns the indexed [`Record`] table consumed by
//! [`crate::brep`]. Framing every token preserves byte synchronization and
//! record extents without requiring semantic decoding of each payload.

/// A decoded SAB token. Only the payload this codec consumes is retained with a
/// typed value; all tokens are still framed so record boundaries stay exact.
#[derive(Debug, Clone, PartialEq)]
pub enum Token {
    /// `0x02` unsigned 8-bit.
    Char(u8),
    /// `0x03` signed 16-bit.
    Short(i16),
    /// `0x04` signed integer of the stream's ref width.
    Long(i64),
    /// `0x05` IEEE float32.
    Float(f32),
    /// `0x06` IEEE float64.
    Double(f64),
    /// `0x07`/`0x08`/`0x09`/`0x12` UTF-8 string.
    Str(String),
    /// `0x0a` logical true (also `reversed` in sense fields).
    True,
    /// `0x0b` logical false (also `forward` in sense fields).
    False,
    /// `0x0c` entity reference (`RecordTable` index; `-1` is null).
    Ref(i64),
    /// `0x0f` subtype-scope open.
    SubtypeOpen,
    /// `0x10` subtype-scope close.
    SubtypeClose,
    /// `0x15` enumeration / secondary integer.
    Enum(i64),
    /// `0x13` 3D position `(x, y, z)`.
    Position([f64; 3]),
    /// `0x14` 3D vector `(x, y, z)`.
    Vector3([f64; 3]),
    /// `0x16` 2D `(u, v)` vector.
    Vector2([f64; 2]),
    /// `0x17` `AutoCAD` ASM int64 attribute value.
    Int64(i64),
}

/// One framed record: its `RecordTable` index, assembled name, payload tokens
/// (the tokens after the name chain), and byte extent within the stream.
#[derive(Debug, Clone)]
pub struct Record {
    /// `RecordTable` index. `asmheader` is index 0.
    pub index: usize,
    /// Full `-`-joined record name, e.g. `cone-surface`, `body`.
    pub name: String,
    /// Leading name component used for dispatch, e.g. `cone`, `body`.
    pub head: String,
    /// Payload tokens following the name chain (subtype delimiters included).
    pub tokens: Vec<Token>,
    /// Byte offset of the record's first name-chain tag in the stream.
    pub offset: usize,
    /// Byte length of the record including its terminator.
    pub len: usize,
}

impl Record {
    /// The `chunk[i]` value: the `i`-th payload token, as topology field tables
    /// index them.
    pub fn chunk(&self, i: usize) -> Option<&Token> {
        self.tokens.get(i)
    }

    /// The `chunk[i]` as a non-null entity reference index. Returns `None` for a
    /// null reference (`-1`) or a non-reference token.
    pub fn ref_at(&self, i: usize) -> Option<i64> {
        match self.tokens.get(i) {
            Some(Token::Ref(v)) if *v >= 0 => Some(*v),
            _ => None,
        }
    }
}

/// A framing error: an unrecognized tag or a truncated token payload leaves the
/// stream un-synchronizable, so the caller falls back to metadata-only decode.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FrameError {
    /// Byte offset where framing could not continue.
    pub offset: usize,
    /// What went wrong.
    pub reason: String,
}

impl std::fmt::Display for FrameError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "SAB framing failed at byte {}: {}",
            self.offset, self.reason
        )
    }
}

/// Read one token starting at `pos`. Returns the token (or a control marker) and
/// the offset just past it. Control tags (`0x0d`/`0x0e` name tokens, `0x11`
/// terminator) are returned via [`Lexed`] so the framer can act on them.
enum Lexed {
    /// A payload token.
    Value(Token),
    /// `0x0d` identifier (name terminator).
    Ident(String),
    /// `0x0e` sub-identifier (name component).
    SubIdent(String),
    /// `0x11` record terminator.
    Terminator,
}

fn read_i(bytes: &[u8], at: usize, width: usize) -> Option<i64> {
    let slice = bytes.get(at..at + width)?;
    let v = match width {
        8 => i64::from_le_bytes(
            slice
                .try_into()
                .expect("invariant: bytes.get(at..at+width) with width=8 is an 8-byte slice"),
        ),
        4 => i32::from_le_bytes(
            slice
                .try_into()
                .expect("invariant: bytes.get(at..at+width) with width=4 is a 4-byte slice"),
        ) as i64,
        _ => return None,
    };
    Some(v)
}

fn read_f64(bytes: &[u8], at: usize) -> Option<f64> {
    let slice = bytes.get(at..at + 8)?;
    Some(f64::from_le_bytes(
        slice
            .try_into()
            .expect("invariant: bytes.get(at..at+8) is an 8-byte slice"),
    ))
}

fn read_vec3(bytes: &[u8], at: usize) -> Option<[f64; 3]> {
    Some([
        read_f64(bytes, at)?,
        read_f64(bytes, at + 8)?,
        read_f64(bytes, at + 16)?,
    ])
}

fn read_string(bytes: &[u8], start: usize, len: usize) -> Option<String> {
    let slice = bytes.get(start..start + len)?;
    Some(String::from_utf8_lossy(slice).into_owned())
}

fn lex(bytes: &[u8], pos: usize, ref_width: usize) -> Result<(Lexed, usize), FrameError> {
    let err = |reason: &str| FrameError {
        offset: pos,
        reason: reason.to_string(),
    };
    let tag = *bytes.get(pos).ok_or_else(|| err("end of stream"))?;
    let p = pos + 1;
    let truncated = || FrameError {
        offset: pos,
        reason: format!("truncated payload for tag {tag:#04x}"),
    };
    let out = match tag {
        0x02 => (
            Lexed::Value(Token::Char(*bytes.get(p).ok_or_else(truncated)?)),
            p + 1,
        ),
        0x03 => {
            let s = bytes.get(p..p + 2).ok_or_else(truncated)?;
            (
                Lexed::Value(Token::Short(i16::from_le_bytes(
                    s.try_into()
                        .expect("invariant: bytes.get(p..p+2) is a 2-byte slice"),
                ))),
                p + 2,
            )
        }
        0x04 => {
            let v = read_i(bytes, p, ref_width).ok_or_else(truncated)?;
            (Lexed::Value(Token::Long(v)), p + ref_width)
        }
        0x05 => {
            let s = bytes.get(p..p + 4).ok_or_else(truncated)?;
            (
                Lexed::Value(Token::Float(f32::from_le_bytes(
                    s.try_into()
                        .expect("invariant: bytes.get(p..p+4) is a 4-byte slice"),
                ))),
                p + 4,
            )
        }
        0x06 => (
            Lexed::Value(Token::Double(read_f64(bytes, p).ok_or_else(truncated)?)),
            p + 8,
        ),
        0x07 => {
            let len = *bytes.get(p).ok_or_else(truncated)? as usize;
            (
                Lexed::Value(Token::Str(
                    read_string(bytes, p + 1, len).ok_or_else(truncated)?,
                )),
                p + 1 + len,
            )
        }
        0x08 => {
            let s = bytes.get(p..p + 2).ok_or_else(truncated)?;
            let len = u16::from_le_bytes(
                s.try_into()
                    .expect("invariant: bytes.get(p..p+2) is a 2-byte slice"),
            ) as usize;
            (
                Lexed::Value(Token::Str(
                    read_string(bytes, p + 2, len).ok_or_else(truncated)?,
                )),
                p + 2 + len,
            )
        }
        0x09 | 0x12 => {
            let s = bytes.get(p..p + 4).ok_or_else(truncated)?;
            let len = u32::from_le_bytes(
                s.try_into()
                    .expect("invariant: bytes.get(p..p+4) is a 4-byte slice"),
            ) as usize;
            (
                Lexed::Value(Token::Str(
                    read_string(bytes, p + 4, len).ok_or_else(truncated)?,
                )),
                p + 4 + len,
            )
        }
        0x0a => (Lexed::Value(Token::True), p),
        0x0b => (Lexed::Value(Token::False), p),
        0x0c => {
            let v = read_i(bytes, p, ref_width).ok_or_else(truncated)?;
            (Lexed::Value(Token::Ref(v)), p + ref_width)
        }
        0x0d => {
            let len = *bytes.get(p).ok_or_else(truncated)? as usize;
            (
                Lexed::Ident(read_string(bytes, p + 1, len).ok_or_else(truncated)?),
                p + 1 + len,
            )
        }
        0x0e => {
            let len = *bytes.get(p).ok_or_else(truncated)? as usize;
            (
                Lexed::SubIdent(read_string(bytes, p + 1, len).ok_or_else(truncated)?),
                p + 1 + len,
            )
        }
        0x0f => (Lexed::Value(Token::SubtypeOpen), p),
        0x10 => (Lexed::Value(Token::SubtypeClose), p),
        0x11 => (Lexed::Terminator, p),
        0x13 => (
            Lexed::Value(Token::Position(read_vec3(bytes, p).ok_or_else(truncated)?)),
            p + 24,
        ),
        0x14 => (
            Lexed::Value(Token::Vector3(read_vec3(bytes, p).ok_or_else(truncated)?)),
            p + 24,
        ),
        0x15 => {
            let v = read_i(bytes, p, ref_width).ok_or_else(truncated)?;
            (Lexed::Value(Token::Enum(v)), p + ref_width)
        }
        0x16 => {
            let u = read_f64(bytes, p).ok_or_else(truncated)?;
            let v = read_f64(bytes, p + 8).ok_or_else(truncated)?;
            (Lexed::Value(Token::Vector2([u, v])), p + 16)
        }
        0x17 => {
            let v = read_i(bytes, p, 8).ok_or_else(truncated)?;
            (Lexed::Value(Token::Int64(v)), p + 8)
        }
        other => {
            return Err(FrameError {
                offset: pos,
                reason: format!("unrecognized tag {other:#04x}"),
            })
        }
    };
    Ok(out)
}

/// Byte offsets of payload tokens with `tag` inside one framed record.
pub(crate) fn payload_token_offsets(
    bytes: &[u8],
    record: &Record,
    ref_width: usize,
    tag: u8,
) -> Result<Vec<usize>, FrameError> {
    let end = record.offset + record.len;
    let mut position = record.offset;
    let mut offsets = Vec::new();
    while position < end {
        let token_offset = position;
        let (token, next) = lex(bytes, position, ref_width)?;
        if bytes[token_offset] == tag && matches!(&token, Lexed::Value(_)) {
            offsets.push(token_offset);
        }
        position = next;
        if matches!(&token, Lexed::Terminator) {
            break;
        }
    }
    Ok(offsets)
}

/// Frame `bytes[start..limit]` into an indexed record table.
///
/// `ref_width` is the stream's reference width (8 for `BinaryFile8`). Framing
/// stops at `limit`, the end of the byte slice, or the `delta_state` history
/// boundary.
pub fn frame(
    bytes: &[u8],
    start: usize,
    limit: usize,
    ref_width: usize,
) -> Result<Vec<Record>, FrameError> {
    let limit = limit.min(bytes.len());
    let mut records = Vec::new();
    let mut pos = start;
    let mut index = 0usize;

    while pos < limit {
        let rec_start = pos;
        let mut name_parts: Vec<String> = Vec::new();
        let mut tokens: Vec<Token> = Vec::new();
        let mut depth = 0i32;
        let mut name_done = false;
        let mut is_delta = false;

        loop {
            let (lexed, next) = lex(bytes, pos, ref_width)?;
            pos = next;
            match lexed {
                Lexed::Terminator if depth == 0 => break,
                Lexed::Terminator => {
                    // A terminator inside a subtype scope is not a record end;
                    // preserve nothing but keep scanning (does not occur in
                    // well-formed streams, guarded defensively).
                }
                Lexed::SubIdent(s) if !name_done => name_parts.push(s),
                Lexed::Ident(s) if !name_done => {
                    name_parts.push(s);
                    name_done = true;
                    // The history partition opens with the delta_state record;
                    // stop at its name before consuming a payload the active
                    // slice does not include.
                    if name_parts.first().is_some_and(|n| n == "delta_state") {
                        is_delta = true;
                        break;
                    }
                }
                Lexed::SubIdent(_) | Lexed::Ident(_) => {
                    // Identifier tokens after the name belong to the payload
                    // (e.g. subtype names inside a spline). Ignore for framing;
                    // they carry no value this codec reads positionally.
                }
                Lexed::Value(Token::SubtypeOpen) => {
                    depth += 1;
                    name_done = true;
                    tokens.push(Token::SubtypeOpen);
                }
                Lexed::Value(Token::SubtypeClose) => {
                    depth -= 1;
                    tokens.push(Token::SubtypeClose);
                }
                Lexed::Value(v) => {
                    name_done = true;
                    tokens.push(v);
                }
            }
        }

        if is_delta {
            break;
        }
        let name = name_parts.join("-");
        let head = name_parts.first().cloned().unwrap_or_default();

        records.push(Record {
            index,
            name,
            head,
            tokens,
            offset: rec_start,
            len: pos - rec_start,
        });
        index += 1;
    }

    Ok(records)
}