ifc-lite-core 2.1.6

High-performance IFC/STEP parser for building 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
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! Fast Direct Parsing Module
//!
//! Provides zero-allocation parsing for coordinate lists and index arrays.
//! This bypasses the Token/AttributeValue pipeline for massive speedups
//! on tessellation-heavy IFC files.
//!
//! Performance: 3-5x faster than standard path for IfcTriangulatedFaceSet

/// Check if byte is a digit, minus sign, or decimal point (start of number)
#[inline(always)]
fn is_number_start(b: u8) -> bool {
    b.is_ascii_digit() || b == b'-' || b == b'.'
}

/// Estimate number of floats in coordinate data
#[inline]
fn estimate_float_count(bytes: &[u8]) -> usize {
    // Rough estimate: ~8 bytes per float on average (including delimiters)
    bytes.len() / 8
}

/// Estimate number of integers in index data
#[inline]
fn estimate_int_count(bytes: &[u8]) -> usize {
    // Rough estimate: ~4 bytes per integer on average
    bytes.len() / 4
}

/// Parse coordinate list directly from raw bytes to `Vec<f32>`
///
/// This parses IFC coordinate data like:
/// `((0.,0.,150.),(0.,40.,140.),...)`
///
/// Returns flattened f32 array: [x0, y0, z0, x1, y1, z1, ...]
///
/// # Performance
/// - Zero intermediate allocations (no Token, no AttributeValue)
/// - Uses fast-float for SIMD-accelerated parsing
/// - Pre-allocates result vector
#[inline]
pub fn parse_coordinates_direct(bytes: &[u8]) -> Vec<f32> {
    let mut result = Vec::with_capacity(estimate_float_count(bytes));
    let mut pos = 0;
    let len = bytes.len();

    while pos < len {
        // Skip to next number using SIMD-accelerated search
        while pos < len && !is_number_start(bytes[pos]) {
            pos += 1;
        }
        if pos >= len {
            break;
        }

        // Parse float directly
        match fast_float::parse_partial::<f32, _>(&bytes[pos..]) {
            Ok((value, consumed)) if consumed > 0 => {
                result.push(value);
                pos += consumed;
            }
            _ => {
                // Skip this character and continue
                pos += 1;
            }
        }
    }

    result
}

/// Parse coordinate list directly from raw bytes to `Vec<f64>`
///
/// Same as parse_coordinates_direct but with f64 precision.
#[inline]
pub fn parse_coordinates_direct_f64(bytes: &[u8]) -> Vec<f64> {
    let mut result = Vec::with_capacity(estimate_float_count(bytes));
    let mut pos = 0;
    let len = bytes.len();

    while pos < len {
        while pos < len && !is_number_start(bytes[pos]) {
            pos += 1;
        }
        if pos >= len {
            break;
        }

        match fast_float::parse_partial::<f64, _>(&bytes[pos..]) {
            Ok((value, consumed)) if consumed > 0 => {
                result.push(value);
                pos += consumed;
            }
            _ => {
                pos += 1;
            }
        }
    }

    result
}

/// Parse index list directly from raw bytes to `Vec<u32>`
///
/// This parses IFC face index data like:
/// `((1,2,3),(2,1,4),...)`
///
/// Automatically converts from 1-based IFC indices to 0-based.
///
/// # Performance
/// - Zero intermediate allocations
/// - Uses inline integer parsing
#[inline]
pub fn parse_indices_direct(bytes: &[u8]) -> Vec<u32> {
    let mut result = Vec::with_capacity(estimate_int_count(bytes));
    let mut pos = 0;
    let len = bytes.len();

    while pos < len {
        // Skip to next digit
        while pos < len && !bytes[pos].is_ascii_digit() {
            pos += 1;
        }
        if pos >= len {
            break;
        }

        // Parse integer inline (avoiding any allocation)
        let mut value: u32 = 0;
        while pos < len && bytes[pos].is_ascii_digit() {
            value = value
                .wrapping_mul(10)
                .wrapping_add((bytes[pos] - b'0') as u32);
            pos += 1;
        }

        // Convert from 1-based to 0-based
        result.push(value.saturating_sub(1));
    }

    result
}

/// Parse a single entity's coordinate list attribute
///
/// Takes the raw bytes of an entity line like:
/// `#78=IFCCARTESIANPOINTLIST3D(((0.,0.,150.),(0.,40.,140.),...));`
///
/// And extracts just the coordinate data.
#[inline]
pub fn extract_coordinate_list_from_entity(bytes: &[u8]) -> Option<Vec<f32>> {
    // Find the opening '((' which starts the coordinate list
    let start = memchr::memmem::find(bytes, b"((")?;

    // Find matching closing '))'
    let end = memchr::memmem::rfind(bytes, b"))")?;

    if end <= start {
        return None;
    }

    // Parse the coordinate data
    Some(parse_coordinates_direct(&bytes[start..end + 2]))
}

/// Parse face indices from IfcTriangulatedFaceSet entity
///
/// Finds the CoordIndex attribute (4th attribute, 0-indexed as 3)
/// in an entity like:
/// `#77=IFCTRIANGULATEDFACESET(#78,$,$,((1,2,3),(2,1,4),...),$);`
#[inline]
pub fn extract_face_indices_from_entity(bytes: &[u8]) -> Option<Vec<u32>> {
    // Count commas to find the 4th attribute (CoordIndex)
    // Format: IFCTRIANGULATEDFACESET(Coordinates,Normals,Closed,CoordIndex,PnIndex)
    let mut paren_depth = 0;
    let mut comma_count = 0;
    let mut attr_start = None;
    let mut attr_end = None;

    for (i, &b) in bytes.iter().enumerate() {
        match b {
            b'(' => {
                if paren_depth == 1 && comma_count == 3 && attr_start.is_none() {
                    attr_start = Some(i);
                }
                paren_depth += 1;
            }
            b')' => {
                paren_depth -= 1;
                if paren_depth == 1
                    && comma_count == 3
                    && attr_start.is_some()
                    && attr_end.is_none()
                {
                    attr_end = Some(i + 1);
                }
            }
            b',' if paren_depth == 1 => {
                if comma_count == 3 && attr_end.is_none() && attr_start.is_some() {
                    attr_end = Some(i);
                }
                comma_count += 1;
                if comma_count == 3 {
                    // Next character starts the 4th attribute
                }
            }
            _ => {}
        }
    }

    let start = attr_start?;
    let end = attr_end?;

    if end <= start {
        return None;
    }

    Some(parse_indices_direct(&bytes[start..end]))
}

/// Fast path checker - determines if entity type benefits from direct parsing
#[inline]
pub fn should_use_fast_path(type_name: &str) -> bool {
    matches!(
        type_name.to_uppercase().as_str(),
        "IFCCARTESIANPOINTLIST3D"
            | "IFCTRIANGULATEDFACESET"
            | "IFCPOLYGONALFACESET"
            | "IFCINDEXEDPOLYGONALFACE"
    )
}

/// Extract entity type name from raw bytes
///
/// From `#77=IFCTRIANGULATEDFACESET(...)` extracts `IFCTRIANGULATEDFACESET`
#[inline]
pub fn extract_entity_type_name(bytes: &[u8]) -> Option<&str> {
    // Find '=' position
    let eq_pos = bytes.iter().position(|&b| b == b'=')?;
    // Find '(' position after '='
    let paren_pos = bytes[eq_pos..].iter().position(|&b| b == b'(')?;
    let type_start = eq_pos + 1;
    let type_end = eq_pos + paren_pos;

    if type_end <= type_start {
        return None;
    }

    std::str::from_utf8(&bytes[type_start..type_end]).ok()
}

/// Extract the first entity reference from an entity's first attribute
///
/// From `#77=IFCTRIANGULATEDFACESET(#78,...)` extracts `78`
#[inline]
pub fn extract_first_entity_ref(bytes: &[u8]) -> Option<u32> {
    // Find opening paren
    let paren_pos = bytes.iter().position(|&b| b == b'(')?;
    let content = &bytes[paren_pos + 1..];

    // Find '#' which marks entity reference
    let hash_pos = content.iter().position(|&b| b == b'#')?;
    let id_start = hash_pos + 1;

    // Parse the ID number
    let mut id: u32 = 0;
    let mut i = id_start;
    while i < content.len() && content[i].is_ascii_digit() {
        id = id.wrapping_mul(10).wrapping_add((content[i] - b'0') as u32);
        i += 1;
    }

    if i > id_start {
        Some(id)
    } else {
        None
    }
}

/// Mesh data for fast path processing (avoiding full Mesh struct dependency)
#[derive(Debug, Clone)]
pub struct FastMeshData {
    pub positions: Vec<f32>,
    pub indices: Vec<u32>,
}

/// Process IfcTriangulatedFaceSet directly from raw bytes
///
/// This completely bypasses the Token/AttributeValue pipeline for
/// maximum performance on tessellation geometry.
///
/// # Arguments
/// * `faceset_bytes` - Raw bytes of the IfcTriangulatedFaceSet entity
/// * `get_entity_bytes` - Function to retrieve raw bytes for a given entity ID
///
/// # Returns
/// FastMeshData with positions and indices, or None if parsing fails
#[inline]
pub fn process_triangulated_faceset_direct<F>(
    faceset_bytes: &[u8],
    get_entity_bytes: F,
) -> Option<FastMeshData>
where
    F: Fn(u32) -> Option<Vec<u8>>,
{
    // Extract coordinate entity reference from first attribute
    let coord_entity_id = extract_first_entity_ref(faceset_bytes)?;

    // Get raw bytes of coordinate list entity
    let coord_bytes = get_entity_bytes(coord_entity_id)?;

    // Parse coordinates directly
    let positions = parse_coordinates_direct(&coord_bytes);

    // Extract and parse indices from attribute 3 (CoordIndex)
    let indices = extract_face_indices_from_entity(faceset_bytes)?;

    Some(FastMeshData { positions, indices })
}

/// Extract entity IDs from a list attribute without full parsing
///
/// From `(#1,#2,#3)` extracts `[1, 2, 3]`
#[inline]
pub fn extract_entity_refs_from_list(bytes: &[u8]) -> Vec<u32> {
    let mut ids = Vec::with_capacity(16);
    let mut i = 0;
    let len = bytes.len();

    while i < len {
        // Find next '#'
        while i < len && bytes[i] != b'#' {
            i += 1;
        }
        if i >= len {
            break;
        }
        i += 1; // Skip '#'

        // Parse ID
        let mut id: u32 = 0;
        while i < len && bytes[i].is_ascii_digit() {
            id = id.wrapping_mul(10).wrapping_add((bytes[i] - b'0') as u32);
            i += 1;
        }
        if id > 0 {
            ids.push(id);
        }
    }

    ids
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_coordinates_direct() {
        let bytes = b"((0.,0.,150.),(0.,40.,140.),(100.,0.,0.))";
        let coords = parse_coordinates_direct(bytes);

        assert_eq!(coords.len(), 9);
        assert!((coords[0] - 0.0).abs() < 0.001);
        assert!((coords[1] - 0.0).abs() < 0.001);
        assert!((coords[2] - 150.0).abs() < 0.001);
        assert!((coords[3] - 0.0).abs() < 0.001);
        assert!((coords[4] - 40.0).abs() < 0.001);
        assert!((coords[5] - 140.0).abs() < 0.001);
    }

    #[test]
    fn test_parse_indices_direct() {
        let bytes = b"((1,2,3),(2,1,4),(5,6,7))";
        let indices = parse_indices_direct(bytes);

        assert_eq!(indices.len(), 9);
        // Should be 0-based (1-based converted)
        assert_eq!(indices[0], 0); // 1 -> 0
        assert_eq!(indices[1], 1); // 2 -> 1
        assert_eq!(indices[2], 2); // 3 -> 2
        assert_eq!(indices[3], 1); // 2 -> 1
        assert_eq!(indices[4], 0); // 1 -> 0
        assert_eq!(indices[5], 3); // 4 -> 3
    }

    #[test]
    fn test_parse_scientific_notation() {
        let bytes = b"((1.5E-10,2.0e+5,-3.14))";
        let coords = parse_coordinates_direct(bytes);

        assert_eq!(coords.len(), 3);
        assert!((coords[0] - 1.5e-10).abs() < 1e-15);
        assert!((coords[1] - 2.0e5).abs() < 1.0);
        assert!((coords[2] - (-std::f32::consts::PI)).abs() < 0.01);
    }

    #[test]
    fn test_parse_negative_numbers() {
        let bytes = b"((-1.0,-2.5,3.0))";
        let coords = parse_coordinates_direct(bytes);

        assert_eq!(coords.len(), 3);
        assert!((coords[0] - (-1.0)).abs() < 0.001);
        assert!((coords[1] - (-2.5)).abs() < 0.001);
        assert!((coords[2] - 3.0).abs() < 0.001);
    }

    #[test]
    fn test_extract_coordinate_list() {
        let entity = b"#78=IFCCARTESIANPOINTLIST3D(((0.,0.,150.),(100.,0.,0.)));";
        let coords = extract_coordinate_list_from_entity(entity).unwrap();

        assert_eq!(coords.len(), 6);
        assert!((coords[0] - 0.0).abs() < 0.001);
        assert!((coords[2] - 150.0).abs() < 0.001);
        assert!((coords[3] - 100.0).abs() < 0.001);
    }

    #[test]
    fn test_should_use_fast_path() {
        assert!(should_use_fast_path("IFCCARTESIANPOINTLIST3D"));
        assert!(should_use_fast_path("IFCTRIANGULATEDFACESET"));
        assert!(should_use_fast_path("IfcTriangulatedFaceSet"));
        assert!(!should_use_fast_path("IFCWALL"));
        assert!(!should_use_fast_path("IFCEXTRUDEDAREASOLID"));
    }
}