viewport-lib 0.12.2

3D viewport rendering library
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
//! CPU-side isoline (contour line) extraction from triangulated surfaces.
//!
//! An **isoline** is the set of points on a surface where a scalar field equals
//! a given value (the *isovalue*).  This module implements a per-triangle
//! edge-walk algorithm: for each triangle it checks which edges are crossed by
//! the isovalue, linearly interpolates the crossing position, and emits a
//! 2-point line segment.
//!
//! The extracted segments are returned in a form that can be passed directly to
//! the existing [`crate::renderer::PolylineItem`] / polyline pipeline : no new
//! GPU pipeline or shader is needed.
//!
//! # Usage
//!
//! ```ignore
//! let item = IsolineItem {
//!     positions: mesh_positions.clone(),
//!     indices:   mesh_indices.clone(),
//!     scalars:   per_vertex_pressure.clone(),
//!     isovalues: vec![100.0, 200.0, 300.0],
//!     color:     [1.0, 1.0, 0.0, 1.0],
//!     line_width: 1.5,
//!     ..IsolineItem::default()
//! };
//! let (positions, strip_lengths) = extract_isolines(&item);
//! // feed into PolylineItem …
//! ```

/// Describes a contour-line extraction request for one mesh / scalar field.
///
/// `IsolineItem` is `#[non_exhaustive]` so future fields can be added without
/// breaking existing callers that construct it via `Default::default()` +
/// field assignment.
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct IsolineItem {
    /// Mesh vertex positions in local (object) space.  Must be the same length
    /// as `scalars`.
    pub positions: Vec<[f32; 3]>,

    /// Triangle indices into `positions`.  Length must be a multiple of 3.
    pub indices: Vec<u32>,

    /// Per-vertex scalar values for the field to contour.  Must be the same
    /// length as `positions`.
    pub scalars: Vec<f32>,

    /// Isovalues at which contour lines are extracted.  Each value produces an
    /// independent set of line segments.
    pub isovalues: Vec<f32>,

    /// RGBA colour applied to every line segment.  Defaults to opaque white.
    pub color: [f32; 4],

    /// Line width in pixels.  Defaults to `1.0`.
    pub line_width: f32,

    /// Model matrix that transforms local-space positions to world space.
    /// Defaults to [`glam::Mat4::IDENTITY`].
    pub model_matrix: glam::Mat4,

    /// Small offset along the surface face normal applied to extracted vertices
    /// to prevent z-fighting with the underlying mesh.  Defaults to `0.001`.
    pub depth_bias: f32,
}

impl Default for IsolineItem {
    fn default() -> Self {
        Self {
            positions: Vec::new(),
            indices: Vec::new(),
            scalars: Vec::new(),
            isovalues: Vec::new(),
            color: [1.0, 1.0, 1.0, 1.0],
            line_width: 1.0,
            model_matrix: glam::Mat4::IDENTITY,
            depth_bias: 0.001,
        }
    }
}

// ---------------------------------------------------------------------------
// Extraction
// ---------------------------------------------------------------------------

/// Extract isoline segments from a triangulated surface for all isovalues
/// specified in `item`.
///
/// Returns `(positions, strip_lengths)` suitable for constructing a
/// [`crate::renderer::PolylineItem`]:
/// - `positions` : world-space positions of every line-segment endpoint,
///   concatenated.
/// - `strip_lengths` : number of vertices per strip.  Every segment is
///   emitted as an independent 2-vertex strip, so each entry is `2`.
///
/// If `item` has empty `positions`, `indices`, or `scalars` the function
/// returns `(vec![], vec![])` immediately.
pub fn extract_isolines(item: &IsolineItem) -> (Vec<[f32; 3]>, Vec<u32>) {
    // Fast-exit guards.
    if item.positions.is_empty()
        || item.indices.is_empty()
        || item.scalars.is_empty()
        || item.isovalues.is_empty()
    {
        return (Vec::new(), Vec::new());
    }

    // Validate consistency : mismatched arrays are a caller bug; skip silently.
    if item.scalars.len() != item.positions.len() {
        return (Vec::new(), Vec::new());
    }

    // Pre-allocate conservatively.
    let tri_count = item.indices.len() / 3;
    let iso_count = item.isovalues.len();
    let mut out_positions: Vec<[f32; 3]> = Vec::with_capacity(tri_count * iso_count * 2);
    let mut strip_lengths: Vec<u32> = Vec::with_capacity(tri_count * iso_count);

    for &iso in &item.isovalues {
        extract_for_isovalue(item, iso, &mut out_positions, &mut strip_lengths);
    }

    (out_positions, strip_lengths)
}

// ---------------------------------------------------------------------------
// Per-isovalue inner loop
// ---------------------------------------------------------------------------

/// Edge-walk for a single isovalue.  Appends results to the caller's output
/// vecs to avoid per-isovalue allocations.
fn extract_for_isovalue(
    item: &IsolineItem,
    iso: f32,
    out_positions: &mut Vec<[f32; 3]>,
    strip_lengths: &mut Vec<u32>,
) {
    let positions = &item.positions;
    let scalars = &item.scalars;
    let model = item.model_matrix;
    let bias = item.depth_bias;

    let tri_count = item.indices.len() / 3;

    for tri_idx in 0..tri_count {
        let i0 = item.indices[tri_idx * 3] as usize;
        let i1 = item.indices[tri_idx * 3 + 1] as usize;
        let i2 = item.indices[tri_idx * 3 + 2] as usize;

        // Bounds check : skip malformed index data.
        if i0 >= positions.len() || i1 >= positions.len() || i2 >= positions.len() {
            continue;
        }

        let p0 = glam::Vec3::from(positions[i0]);
        let p1 = glam::Vec3::from(positions[i1]);
        let p2 = glam::Vec3::from(positions[i2]);

        let s0 = scalars[i0];
        let s1 = scalars[i1];
        let s2 = scalars[i2];

        // Face normal for depth bias.  Skip degenerate (zero-area) triangles.
        let edge_a = p1 - p0;
        let edge_b = p2 - p0;
        let cross = edge_a.cross(edge_b);
        let len_sq = cross.length_squared();
        if len_sq < f32::EPSILON {
            continue; // degenerate triangle
        }
        let face_normal = cross / len_sq.sqrt();

        // Collect crossing points on the 3 edges.
        let edges = [(p0, p1, s0, s1), (p1, p2, s1, s2), (p2, p0, s2, s0)];
        let mut crossings: [Option<glam::Vec3>; 3] = [None; 3];

        for (edge_slot, &(ea, eb, sa, sb)) in edges.iter().enumerate() {
            if let Some(p) = edge_crossing(ea, eb, sa, sb, iso) {
                crossings[edge_slot] = Some(p);
            }
        }

        // Collect the valid crossing points.
        let pts: Vec<glam::Vec3> = crossings.iter().filter_map(|&c| c).collect();

        // We need exactly 2 points to form a line segment.
        if pts.len() < 2 {
            continue;
        }

        // If more than 2 (rare due to vertex exactly on isovalue), take first 2.
        let a = pts[0];
        let b = pts[1];

        // Apply depth bias along the face normal (local space), then transform
        // to world space using the model matrix.
        let bias_vec = face_normal * bias;
        let wa = transform_point(model, a + bias_vec);
        let wb = transform_point(model, b + bias_vec);

        out_positions.push(wa);
        out_positions.push(wb);
        strip_lengths.push(2);
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Returns the interpolated position where the isovalue `iso` crosses the
/// directed edge from `pa` (scalar `sa`) to `pb` (scalar `sb`), or `None`
/// if the edge does not cross `iso`.
///
/// The edge is considered crossing when one endpoint is strictly below `iso`
/// and the other is at or above `iso`.  If both endpoints are equal the edge
/// is skipped.
#[inline]
fn edge_crossing(pa: glam::Vec3, pb: glam::Vec3, sa: f32, sb: f32, iso: f32) -> Option<glam::Vec3> {
    // Skip if scalars are equal : no direction.
    if (sb - sa).abs() < f32::EPSILON {
        return None;
    }

    let crosses = (sa < iso && sb >= iso) || (sb < iso && sa >= iso);
    if !crosses {
        return None;
    }

    let t = (iso - sa) / (sb - sa);
    Some(pa + t * (pb - pa))
}

/// Apply a 4×4 model matrix to a 3-D point (homogeneous w=1, divide by w).
#[inline]
fn transform_point(m: glam::Mat4, p: glam::Vec3) -> [f32; 3] {
    m.transform_point3(p).to_array()
}

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

    fn simple_triangle_item(scalars: Vec<f32>, isovalues: Vec<f32>) -> IsolineItem {
        // Right triangle in XY plane: (0,0,0), (1,0,0), (0,1,0)
        IsolineItem {
            positions: vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
            indices: vec![0, 1, 2],
            scalars,
            isovalues,
            depth_bias: 0.0,
            ..IsolineItem::default()
        }
    }

    // -- edge_crossing tests --

    #[test]
    fn edge_crossing_midpoint() {
        let a = glam::Vec3::ZERO;
        let b = glam::Vec3::X;
        let p = edge_crossing(a, b, 0.0, 1.0, 0.5).unwrap();
        assert!((p.x - 0.5).abs() < 1e-5);
        assert!(p.y.abs() < 1e-5);
    }

    #[test]
    fn edge_crossing_same_side_returns_none() {
        let a = glam::Vec3::ZERO;
        let b = glam::Vec3::X;
        assert!(edge_crossing(a, b, 0.0, 0.5, 1.0).is_none());
    }

    #[test]
    fn edge_crossing_equal_scalars_returns_none() {
        let a = glam::Vec3::ZERO;
        let b = glam::Vec3::X;
        assert!(edge_crossing(a, b, 0.5, 0.5, 0.5).is_none());
    }

    #[test]
    fn edge_crossing_at_endpoint() {
        let a = glam::Vec3::ZERO;
        let b = glam::Vec3::X;
        // iso exactly at sb : sa < iso, sb >= iso -> should cross
        let p = edge_crossing(a, b, 0.0, 1.0, 1.0).unwrap();
        assert!((p.x - 1.0).abs() < 1e-5);
    }

    // -- extract_isolines tests --

    #[test]
    fn extract_empty_positions_returns_empty() {
        let item = IsolineItem::default();
        let (pos, strips) = extract_isolines(&item);
        assert!(pos.is_empty());
        assert!(strips.is_empty());
    }

    #[test]
    fn extract_mismatched_scalars_returns_empty() {
        let item = IsolineItem {
            positions: vec![[0.0; 3]; 3],
            indices: vec![0, 1, 2],
            scalars: vec![0.0, 1.0], // wrong length
            isovalues: vec![0.5],
            ..IsolineItem::default()
        };
        let (pos, _) = extract_isolines(&item);
        assert!(pos.is_empty());
    }

    #[test]
    fn extract_single_triangle_linear_ramp() {
        // Scalars: 0, 1, 0. Iso at 0.5 should cross edges 0-1 and 1-2.
        let item = simple_triangle_item(vec![0.0, 1.0, 0.0], vec![0.5]);
        let (pos, strips) = extract_isolines(&item);
        assert_eq!(strips.len(), 1);
        assert_eq!(strips[0], 2);
        assert_eq!(pos.len(), 2);
    }

    #[test]
    fn extract_isovalue_outside_range_no_segments() {
        let item = simple_triangle_item(vec![0.0, 0.5, 0.25], vec![10.0]);
        let (pos, strips) = extract_isolines(&item);
        assert!(pos.is_empty());
        assert!(strips.is_empty());
    }

    #[test]
    fn extract_multiple_isovalues() {
        // Scalars from 0 to 1 across vertices. Two isovalues should each produce segments.
        let item = simple_triangle_item(vec![0.0, 1.0, 0.0], vec![0.25, 0.75]);
        let (pos, strips) = extract_isolines(&item);
        assert_eq!(strips.len(), 2);
        assert_eq!(pos.len(), 4);
    }

    #[test]
    fn extract_degenerate_triangle_skipped() {
        // Three coincident points : zero-area triangle
        let item = IsolineItem {
            positions: vec![[0.0; 3]; 3],
            indices: vec![0, 1, 2],
            scalars: vec![0.0, 1.0, 0.0],
            isovalues: vec![0.5],
            depth_bias: 0.0,
            ..IsolineItem::default()
        };
        let (pos, _) = extract_isolines(&item);
        assert!(pos.is_empty());
    }

    #[test]
    fn extract_out_of_bounds_indices_skipped() {
        let item = IsolineItem {
            positions: vec![[0.0; 3]; 3],
            indices: vec![0, 1, 99], // 99 is out of bounds
            scalars: vec![0.0, 1.0, 0.0],
            isovalues: vec![0.5],
            ..IsolineItem::default()
        };
        let (pos, _) = extract_isolines(&item);
        assert!(pos.is_empty());
    }

    #[test]
    fn extract_model_matrix_transforms_output() {
        let item = IsolineItem {
            positions: vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
            indices: vec![0, 1, 2],
            scalars: vec![0.0, 1.0, 0.0],
            isovalues: vec![0.5],
            model_matrix: glam::Mat4::from_translation(glam::Vec3::new(10.0, 0.0, 0.0)),
            depth_bias: 0.0,
            ..IsolineItem::default()
        };
        let (pos, _) = extract_isolines(&item);
        // All output positions should be translated by +10 on X
        for p in &pos {
            assert!(p[0] > 9.0, "expected translated X, got {}", p[0]);
        }
    }

    #[test]
    fn extract_two_triangles_sharing_edge() {
        // Two triangles forming a quad, with a linear ramp across them
        let item = IsolineItem {
            positions: vec![
                [0.0, 0.0, 0.0],
                [1.0, 0.0, 0.0],
                [1.0, 1.0, 0.0],
                [0.0, 1.0, 0.0],
            ],
            indices: vec![0, 1, 2, 0, 2, 3],
            scalars: vec![0.0, 1.0, 1.0, 0.0],
            isovalues: vec![0.5],
            depth_bias: 0.0,
            ..IsolineItem::default()
        };
        let (pos, strips) = extract_isolines(&item);
        assert_eq!(strips.len(), 2); // one segment per triangle
        assert_eq!(pos.len(), 4);
    }

    #[test]
    fn extract_empty_isovalues_returns_empty() {
        let item = simple_triangle_item(vec![0.0, 1.0, 0.0], vec![]);
        let (pos, strips) = extract_isolines(&item);
        assert!(pos.is_empty());
        assert!(strips.is_empty());
    }
}