pyrucast 0.11.0

Finite-element library in Rust, inspired by cast3m, exposed to Python
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
//! Sweep / extrusion mesh-construction operators.
//!
//! - [`qua4_between`] — sweep between two SEG2 contours, producing a
//!   strip of QUA4 elements (one per source segment per layer).
//! - [`extrude`] — translate every cell of a mesh along a vector by
//!   `n_layers` layers, bumping element dimension (SEG2 → QUA4,
//!   TRI3 → PENTA6, QUA4 → HEX8).
//! - [`revolve`] — the same layered sweep, but rotating about a centre
//!   (2-D) or an axis (3-D); a full turn closes the ring.
//! - [`solid_between`] — the 3-D companion of [`qua4_between`]: sweep
//!   between two matching surface meshes (TRI3 → PENTA6, QUA4 → HEX8).

use crate::aggregate::Aggregate;
use crate::atoms::ElementType;
use crate::atoms::NodeId;
use crate::containers::mesh::{Mesh, SubMesh};
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;

/// Sweep between two SEG2 contour meshes to produce a QUA4 strip.
///
/// `n_layers` ≥ 1 transverse layers are interpolated between `mesh_a`
/// and `mesh_b` to produce the intermediate node layers. Endpoint
/// nodes from both meshes are re-used (refcount incremented);
/// intermediate nodes are created at evenly spaced positions.
///
/// QUA4 node order per element (counterclockwise, `mesh_a` side first):
/// `[k][j]`, `[k][j+1]`, `[k+1][j+1]`, `[k+1][j]`.
pub fn qua4_between(mesh_a: &Mesh, mesh_b: &Mesh, n_layers: usize) -> Result<Mesh> {
    if n_layers == 0 {
        return Err(PyrucastError::Message("sweep: n_layers must be ≥ 1".into()));
    }
    if mesh_a.len() != 1 {
        return Err(PyrucastError::Message(
            "sweep: mesh_a must have exactly one submesh".into(),
        ));
    }
    if mesh_b.len() != 1 {
        return Err(PyrucastError::Message(
            "sweep: mesh_b must have exactly one submesh".into(),
        ));
    }
    let sm_a = mesh_a.get(0)?;
    let sm_b = mesh_b.get(0)?;
    let coords_a = sm_a.read().coords();
    let coords_b = sm_b.read().coords();
    if !coords_a.same_object(&coords_b) {
        return Err(PyrucastError::Message(
            "sweep: meshes are attached to different Coords".into(),
        ));
    }

    // Guards held for the read pass; the `Coords` write comes after.
    let (a, b) = (sm_a.read(), sm_b.read());
    let (et_a, n_elems, conn_a) = (a.element_type(), a.cell_count(), a.connectivity());
    let (et_b, n_elems_b, conn_b) = (b.element_type(), b.cell_count(), b.connectivity());

    if et_a != ElementType::SEG2 {
        return Err(PyrucastError::Message(
            "sweep: mesh_a must be a SEG2 mesh".into(),
        ));
    }
    if et_b != ElementType::SEG2 {
        return Err(PyrucastError::Message(
            "sweep: mesh_b must be a SEG2 mesh".into(),
        ));
    }
    if n_elems != n_elems_b {
        return Err(PyrucastError::Message(format!(
            "sweep: mesh_a has {} elements but mesh_b has {}",
            n_elems, n_elems_b
        )));
    }

    let coords = coords_a;
    let n_cols = n_elems + 1;

    // Column j: first node of elem 0 (j=0), or second node of elem j-1 (j≥1).
    let col_ids_a: Vec<NodeId> = std::iter::once(conn_a[0])
        .chain((1..=n_elems).map(|j| conn_a[2 * j - 1]))
        .collect();
    let col_ids_b: Vec<NodeId> = std::iter::once(conn_b[0])
        .chain((1..=n_elems).map(|j| conn_b[2 * j - 1]))
        .collect();

    let coords_a: Vec<Vec<f64>> = col_ids_a
        .iter()
        .map(|&id| -> Result<Vec<f64>> { Ok(coords.read().position(id)?.to_vec()) })
        .collect::<Result<_>>()?;
    let coords_b: Vec<Vec<f64>> = col_ids_b
        .iter()
        .map(|&id| -> Result<Vec<f64>> { Ok(coords.read().position(id)?.to_vec()) })
        .collect::<Result<_>>()?;

    // The intermediate layers — layer 0 is `mesh_a`'s own nodes and layer
    // `n_layers` is `mesh_b`'s — laid out flat and created in one locked pass:
    // interpolating a million nodes must not mean a million write locks.
    let inner = n_layers.saturating_sub(1);
    let dim = coords.read().dim() as usize;
    let mut flat: Vec<f64> = Vec::with_capacity(inner * n_cols * dim);
    for k in 1..n_layers {
        let t = k as f64 / n_layers as f64;
        for j in 0..n_cols {
            flat.extend(
                coords_a[j]
                    .iter()
                    .zip(coords_b[j].iter())
                    .map(|(&ca, &cb)| ca + t * (cb - ca)),
            );
        }
    }
    let first = coords.write().add_nodes(&flat)?.start;
    // Node at layer k, column j.
    let at = |k: usize, j: usize| -> NodeId {
        if k == 0 {
            col_ids_a[j]
        } else if k == n_layers {
            col_ids_b[j]
        } else {
            NodeId(first + ((k - 1) * n_cols + j) as u32)
        }
    };

    let mut conn: Vec<NodeId> = Vec::with_capacity(n_layers * n_elems * 4);
    for k in 0..n_layers {
        for j in 0..n_elems {
            conn.extend_from_slice(&[at(k, j), at(k, j + 1), at(k + 1, j + 1), at(k + 1, j)]);
        }
    }
    let sm = SubMesh::from_connectivity(coords.clone(), ElementType::QUA4, conn)?;
    // The connectivity owns the fresh nodes now; hand back the unit
    // `add_nodes` handed us.
    let owned: Vec<NodeId> = (first..first + (inner * n_cols) as u32)
        .map(NodeId)
        .collect();
    coords.write().decref_all(&owned)?;
    Ok(Mesh::from_submesh(sm))
}

// ---------------------------------------------------------------------------
// Layered sweeps (`extrude`, `revolve`)
// ---------------------------------------------------------------------------

/// The node columns of a mesh: every distinct node, once.
///
/// A layered sweep works column by column — each column is one node of the
/// source mesh, replicated once per layer — so nodes shared between cells of
/// the source stay shared in the swept mesh.
struct Columns {
    /// Distinct node ids, in first-seen connectivity order.
    ids: Vec<NodeId>,
    /// Column index of each id.
    index: std::collections::HashMap<NodeId, usize>,
    /// Current position of each column.
    positions: Vec<Vec<f64>>,
}

impl Columns {
    /// Column index of `id` (every id of the source mesh has one).
    fn of(&self, id: NodeId) -> usize {
        self.index[&id]
    }
}

/// Collect the node columns of `mesh`, erroring out (as `op`) if it is empty.
fn columns(mesh: &Mesh, op: &str) -> Result<Columns> {
    let coords = mesh.coords()?;
    let mut index: std::collections::HashMap<NodeId, usize> = std::collections::HashMap::new();
    let mut ids: Vec<NodeId> = Vec::new();
    for sm in mesh {
        for &id in sm.read().connectivity() {
            index.entry(id).or_insert_with(|| {
                let col = ids.len();
                ids.push(id);
                col
            });
        }
    }
    if ids.is_empty() {
        return Err(PyrucastError::Message(format!("{op}: mesh has no cells")));
    }
    let positions: Vec<Vec<f64>> = ids
        .iter()
        .map(|&id| -> Result<Vec<f64>> { Ok(coords.read().position(id)?.to_vec()) })
        .collect::<Result<_>>()?;
    Ok(Columns {
        ids,
        index,
        positions,
    })
}

/// Sweep `mesh` into `n_layers` layers of cells, layer `k` sitting where
/// `place(base_position, k)` puts it.
///
/// Layer 0 re-uses the source nodes (refcount incremented); layers `1..` are
/// newly created — except when `closed` is set, where the last layer *is*
/// layer 0 again, so a sweep that comes back onto its start (a full turn)
/// closes on itself instead of duplicating a node layer.
///
/// Each submesh of `mesh` yields one submesh of the result, cells ordered
/// layer by layer. Element mapping and node ordering:
/// - SEG2 → QUA4: `bot[0], bot[1], top[1], top[0]`
/// - TRI3 → PENTA6: `bot[0..3], top[0..3]`
/// - QUA4 → HEX8: `bot[0..4], top[0..4]`
fn layered(
    mesh: &Mesh,
    cols: &Columns,
    n_layers: usize,
    closed: bool,
    op: &str,
    place: impl Fn(&[f64], usize) -> Vec<f64>,
) -> Result<Mesh> {
    let coords = mesh.coords()?;
    let n_cols = cols.ids.len();

    // Layer 0 is the source's own nodes; layers 1..=last_created are new, and
    // a closed sweep comes back onto layer 0 instead of a duplicate. They are
    // laid out flat and created in one locked pass — a swept solid is where a
    // node-at-a-time creation costs the most.
    let last_created = if closed { n_layers - 1 } else { n_layers };
    let mut flat: Vec<f64> = Vec::new();
    for k in 1..=last_created {
        for c in 0..n_cols {
            flat.extend_from_slice(&place(&cols.positions[c], k));
        }
    }
    let first = coords.write().add_nodes(&flat)?.start;
    // Node at layer k, column col.
    let at = |k: usize, col: usize| -> NodeId {
        if k == 0 || (closed && k == n_layers) {
            cols.ids[col]
        } else {
            NodeId(first + ((k - 1) * n_cols + col) as u32)
        }
    };

    let mut result = Mesh::empty();
    for sm_handle in mesh {
        // Guard held for this zone's pass: what follows only reads.
        let s = sm_handle.read();
        let (et, n_cells, conn) = (s.element_type(), s.cell_count(), s.connectivity());
        let npc = et.nodes_per_cell();

        let swept_et = match et {
            ElementType::SEG2 => ElementType::QUA4,
            ElementType::TRI3 => ElementType::PENTA6,
            ElementType::QUA4 => ElementType::HEX8,
            _ => {
                return Err(PyrucastError::Message(format!(
                    "{op}: cannot sweep {et} elements (supported: SEG2, TRI3, QUA4)"
                )))
            }
        };
        let dim = coords.read().dim() as usize;
        if swept_et.topological_dim() > dim {
            return Err(PyrucastError::Message(format!(
                "{op}: sweeping {et} elements produces {swept_et}, which needs 3-D coordinates \
                 (the mesh is {dim}-D)"
            )));
        }

        let mut out: Vec<NodeId> =
            Vec::with_capacity(n_layers * n_cells * swept_et.nodes_per_cell());
        for k in 0..n_layers {
            for ci in 0..n_cells {
                let cell = &conn[ci * npc..(ci + 1) * npc];
                let bot = |i: usize| at(k, cols.of(cell[i]));
                let top = |i: usize| at(k + 1, cols.of(cell[i]));

                match et {
                    ElementType::SEG2 => {
                        out.extend_from_slice(&[bot(0), bot(1), top(1), top(0)]);
                    }
                    ElementType::TRI3 => {
                        out.extend_from_slice(&[bot(0), bot(1), bot(2), top(0), top(1), top(2)]);
                    }
                    ElementType::QUA4 => {
                        out.extend_from_slice(&[
                            bot(0),
                            bot(1),
                            bot(2),
                            bot(3),
                            top(0),
                            top(1),
                            top(2),
                            top(3),
                        ]);
                    }
                    _ => unreachable!(),
                }
            }
        }

        result.add_sub(Handle::new(SubMesh::from_connectivity(
            coords.clone(),
            swept_et,
            out,
        )?))?;
    }

    // The swept zones own the fresh nodes now; hand back the unit `add_nodes`
    // handed us.
    let owned: Vec<NodeId> = (first..first + (last_created * n_cols) as u32)
        .map(NodeId)
        .collect();
    coords.write().decref_all(&owned)?;
    Ok(result)
}

/// Extrude a mesh by `n_layers` layers along `direction`.
///
/// `direction` is the **total** displacement vector; each intermediate
/// layer is placed at an evenly spaced fraction. Supported element types:
/// SEG2 → QUA4, TRI3 → PENTA6, QUA4 → HEX8. Other types produce an error.
///
/// Nodes shared between cells in the source mesh remain shared in the
/// extruded mesh. Source nodes are re-used (refcount incremented);
/// intermediate layer nodes are newly created.
///
/// Node ordering:
/// - QUA4: `bot[0], bot[1], top[1], top[0]`
/// - PENTA6: `bot[0..3], top[0..3]`
/// - HEX8: `bot[0..4], top[0..4]`
pub fn extrude(mesh: &Mesh, direction: &[f64], n_layers: usize) -> Result<Mesh> {
    if n_layers == 0 {
        return Err(PyrucastError::Message(
            "extrude: n_layers must be ≥ 1".into(),
        ));
    }
    let dim = mesh.coords()?.read().dim() as usize;
    if direction.len() != dim {
        return Err(PyrucastError::Message(format!(
            "extrude: direction has {} components but node dimension is {}",
            direction.len(),
            dim
        )));
    }

    let cols = columns(mesh, "extrude")?;
    let step: Vec<f64> = direction.iter().map(|&d| d / n_layers as f64).collect();
    layered(mesh, &cols, n_layers, false, "extrude", |base, k| {
        base.iter()
            .zip(step.iter())
            .map(|(&c, &s)| c + k as f64 * s)
            .collect()
    })
}

/// Revolve a mesh by `n_layers` layers over a total `angle` (radians) — the
/// rotational companion of [`extrude`].
///
/// Every node is swept along the circle it describes about the rotation
/// centre (2-D) or axis (3-D), and consecutive angular positions are linked
/// by one layer of cells: SEG2 → QUA4, TRI3 → PENTA6, QUA4 → HEX8.
///
/// - **2-D** (`center` has 2 components): revolution about the point
///   `center`, counterclockwise for a positive `angle`; `axis` is ignored.
///   Only SEG2 sources make sense there (a surface would sweep a 3-D solid,
///   which 2-D coordinates cannot hold).
/// - **3-D** (`center` has 3 components): revolution about the line through
///   `center` directed by `axis` (Rodrigues' formula, right-handed about
///   `axis`); `axis` is required and need not be normalized.
///
/// `angle` runs up to a full turn (`|angle| ≤ 2π`); a full turn **closes**
/// the sweep — the last node layer is the first one again, so the ring has
/// no seam and no duplicated nodes.
///
/// No node may sit on the axis: it would collapse one edge of every cell
/// touching it into a degenerate (zero-Jacobian) element.
///
/// Nodes shared between cells in the source mesh remain shared in the result.
/// Source nodes are re-used (refcount incremented); the other layers are
/// newly created. Node ordering per layer is [`extrude`]'s.
///
/// A negative `angle` sweeps the cells the other way round and turns them
/// inside out, just as an `extrude` against the surface normal does — call
/// [`orient`](fn@super::orient) on the result, or revolve by a positive
/// angle from the mirrored source.
pub fn revolve(
    mesh: &Mesh,
    angle: f64,
    n_layers: usize,
    center: &[f64],
    axis: Option<&[f64]>,
) -> Result<Mesh> {
    const TWO_PI: f64 = std::f64::consts::TAU;
    // Relative slack on the full-turn test: enough to catch a 360° written
    // as `2 * PI` or accumulated in degrees, tight enough not to swallow a
    // deliberately-not-quite-closed sweep.
    const TURN_TOL: f64 = 1e-9;

    if n_layers == 0 {
        return Err(PyrucastError::Message(
            "revolve: n_layers must be ≥ 1".into(),
        ));
    }
    if !angle.is_finite() || angle == 0.0 {
        return Err(PyrucastError::Message(
            "revolve: angle must be a non-zero, finite number of radians".into(),
        ));
    }
    if angle.abs() > TWO_PI * (1.0 + TURN_TOL) {
        return Err(PyrucastError::Message(format!(
            "revolve: angle {angle} rad exceeds a full turn (|angle| ≤ 2π); \
             revolve by 2π to close the ring"
        )));
    }
    let closed = (angle.abs() - TWO_PI).abs() <= TWO_PI * TURN_TOL;

    let dim = mesh.coords()?.read().dim() as usize;
    if center.len() != dim {
        return Err(PyrucastError::Message(format!(
            "revolve: center has {} components but the mesh is {}-D",
            center.len(),
            dim
        )));
    }

    // Unit axis (3-D only); in 2-D the rotation is fully set by `center`.
    let unit_axis: Option<[f64; 3]> = match dim {
        2 => None,
        3 => {
            let axis = axis.ok_or_else(|| {
                PyrucastError::Message("revolve: a 3-D mesh needs a rotation axis".into())
            })?;
            if axis.len() != 3 {
                return Err(PyrucastError::Message(format!(
                    "revolve: axis has {} components but must be 3-D",
                    axis.len()
                )));
            }
            let norm = (axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]).sqrt();
            if norm == 0.0 {
                return Err(PyrucastError::Message(
                    "revolve: axis must be non-zero".into(),
                ));
            }
            Some([axis[0] / norm, axis[1] / norm, axis[2] / norm])
        }
        other => {
            return Err(PyrucastError::Message(format!(
                "revolve: only 2-D and 3-D meshes are supported (got {other}-D)"
            )))
        }
    };

    let cols = columns(mesh, "revolve")?;

    // Every node must be off the axis, else the cells touching it collapse.
    // The test is relative to the widest radius, so it is scale-free.
    let radius = |p: &[f64]| -> f64 {
        match unit_axis {
            None => ((p[0] - center[0]).powi(2) + (p[1] - center[1]).powi(2)).sqrt(),
            Some(u) => {
                let v = [p[0] - center[0], p[1] - center[1], p[2] - center[2]];
                let along = v[0] * u[0] + v[1] * u[1] + v[2] * u[2];
                (v.iter().map(|x| x * x).sum::<f64>() - along * along)
                    .max(0.0)
                    .sqrt()
            }
        }
    };
    let radii: Vec<f64> = cols.positions.iter().map(|p| radius(p)).collect();
    let max_radius = radii.iter().cloned().fold(0.0, f64::max);
    if max_radius == 0.0 || radii.iter().any(|&r| r <= 1e-10 * max_radius) {
        return Err(PyrucastError::Message(
            "revolve: some node lies on the rotation axis, which would collapse \
             the cells touching it (move the source off the axis)"
                .into(),
        ));
    }

    let step = angle / n_layers as f64;
    layered(mesh, &cols, n_layers, closed, "revolve", |base, k| {
        let theta = step * k as f64;
        let (cos, sin) = (theta.cos(), theta.sin());
        match unit_axis {
            None => {
                let (x, y) = (base[0] - center[0], base[1] - center[1]);
                vec![center[0] + cos * x - sin * y, center[1] + sin * x + cos * y]
            }
            Some(u) => {
                let v = [
                    base[0] - center[0],
                    base[1] - center[1],
                    base[2] - center[2],
                ];
                // Rodrigues: v' = v cosθ + (u×v) sinθ + u (u·v)(1−cosθ).
                let cross = [
                    u[1] * v[2] - u[2] * v[1],
                    u[2] * v[0] - u[0] * v[2],
                    u[0] * v[1] - u[1] * v[0],
                ];
                let dot = u[0] * v[0] + u[1] * v[1] + u[2] * v[2];
                let k = dot * (1.0 - cos);
                vec![
                    center[0] + v[0] * cos + cross[0] * sin + u[0] * k,
                    center[1] + v[1] * cos + cross[1] * sin + u[1] * k,
                    center[2] + v[2] * cos + cross[2] * sin + u[2] * k,
                ]
            }
        }
    })
}

/// Sweep between two matching surface meshes to produce a solid mesh —
/// the 3-D companion of [`qua4_between`].
///
/// Cell `i` of `mesh_a` is paired with cell `i` of `mesh_b`, node by node
/// (local node `j` of one matches local node `j` of the other), just as
/// [`qua4_between`] pairs two SEG2 contours. `n_layers` ≥ 1 layers of solid
/// cells are built between the two faces; intermediate node layers are
/// linearly interpolated. Endpoint nodes from both meshes are re-used
/// (refcount incremented); intermediate nodes are created.
///
/// Both meshes must be single-submesh meshes of the **same** surface
/// element type (TRI3 or QUA4), with the same number of cells, attached to
/// the same `Coords`. The node correspondence read off the connectivity
/// must be consistent — a node shared by two cells of `mesh_a` must map to
/// the same node of `mesh_b` in both.
///
/// Element mapping and node ordering (bottom face = `mesh_a` side):
/// - TRI3 → PENTA6: `bot[0..3], top[0..3]`
/// - QUA4 → HEX8: `bot[0..4], top[0..4]`
pub fn solid_between(mesh_a: &Mesh, mesh_b: &Mesh, n_layers: usize) -> Result<Mesh> {
    if n_layers == 0 {
        return Err(PyrucastError::Message(
            "sweep_solid: n_layers must be ≥ 1".into(),
        ));
    }
    if mesh_a.len() != 1 || mesh_b.len() != 1 {
        return Err(PyrucastError::Message(
            "sweep_solid: both meshes must have exactly one submesh".into(),
        ));
    }
    let sm_a = mesh_a.get(0)?;
    let sm_b = mesh_b.get(0)?;
    let coords = sm_a.read().coords();
    let coords_b = sm_b.read().coords();
    if !coords.same_object(&coords_b) {
        return Err(PyrucastError::Message(
            "sweep_solid: meshes are attached to different Coords".into(),
        ));
    }

    // Guards held for the read pass; the `Coords` write comes after.
    let (a, b) = (sm_a.read(), sm_b.read());
    let (et_a, conn_a) = (a.element_type(), a.connectivity());
    let (et_b, conn_b) = (b.element_type(), b.connectivity());
    if et_a != et_b {
        return Err(PyrucastError::Message(format!(
            "sweep_solid: element types differ ({et_a} vs {et_b})"
        )));
    }
    let solid_et = match et_a {
        ElementType::TRI3 => ElementType::PENTA6,
        ElementType::QUA4 => ElementType::HEX8,
        other => {
            return Err(PyrucastError::Message(format!(
                "sweep_solid: unsupported surface type {other} (supported: TRI3, QUA4)"
            )))
        }
    };
    let npc = et_a.nodes_per_cell();
    let n_cells = conn_a.len() / npc;
    if conn_b.len() / npc != n_cells {
        return Err(PyrucastError::Message(format!(
            "sweep_solid: mesh_a has {} cells but mesh_b has {}",
            n_cells,
            conn_b.len() / npc
        )));
    }

    // Node correspondence: unique mesh_a node → paired mesh_b node, plus a
    // stable column order (first-seen). A shared node must map consistently.
    let mut pair: std::collections::HashMap<NodeId, NodeId> = std::collections::HashMap::new();
    let mut col_map: std::collections::HashMap<NodeId, usize> = std::collections::HashMap::new();
    let mut cols_a: Vec<NodeId> = Vec::new();
    let mut cols_b: Vec<NodeId> = Vec::new();
    for (&a_id, &b_id) in conn_a.iter().zip(conn_b.iter()) {
        match pair.get(&a_id) {
            Some(&existing) if existing != b_id => {
                return Err(PyrucastError::Message(
                    "sweep_solid: inconsistent node correspondence between the two meshes".into(),
                ));
            }
            Some(_) => {}
            None => {
                pair.insert(a_id, b_id);
                col_map.insert(a_id, cols_a.len());
                cols_a.push(a_id);
                cols_b.push(b_id);
            }
        }
    }

    let n_cols = cols_a.len();
    let base_a: Vec<Vec<f64>> = cols_a
        .iter()
        .map(|&id| -> Result<Vec<f64>> { Ok(coords.read().position(id)?.to_vec()) })
        .collect::<Result<_>>()?;
    let base_b: Vec<Vec<f64>> = cols_b
        .iter()
        .map(|&id| -> Result<Vec<f64>> { Ok(coords.read().position(id)?.to_vec()) })
        .collect::<Result<_>>()?;

    // Layer 0 is `mesh_a`'s own nodes and layer `n_layers` is `mesh_b`'s; the
    // interpolated layers in between are laid out flat and created in one
    // locked pass.
    let inner = n_layers.saturating_sub(1);
    let mut flat: Vec<f64> = Vec::new();
    for k in 1..n_layers {
        let t = k as f64 / n_layers as f64;
        for c in 0..n_cols {
            flat.extend(
                base_a[c]
                    .iter()
                    .zip(base_b[c].iter())
                    .map(|(&ca, &cb)| ca + t * (cb - ca)),
            );
        }
    }
    let first = coords.write().add_nodes(&flat)?.start;
    // Node at layer k, column col.
    let at = |k: usize, c: usize| -> NodeId {
        if k == 0 {
            cols_a[c]
        } else if k == n_layers {
            cols_b[c]
        } else {
            NodeId(first + ((k - 1) * n_cols + c) as u32)
        }
    };

    let col = |id: NodeId| *col_map.get(&id).unwrap();
    let mut out: Vec<NodeId> = Vec::with_capacity(n_layers * n_cells * solid_et.nodes_per_cell());
    for k in 0..n_layers {
        for ci in 0..n_cells {
            let cell = &conn_a[ci * npc..(ci + 1) * npc];
            let bot = |i: usize| at(k, col(cell[i]));
            let top = |i: usize| at(k + 1, col(cell[i]));
            match et_a {
                ElementType::TRI3 => {
                    out.extend_from_slice(&[bot(0), bot(1), bot(2), top(0), top(1), top(2)]);
                }
                ElementType::QUA4 => {
                    out.extend_from_slice(&[
                        bot(0),
                        bot(1),
                        bot(2),
                        bot(3),
                        top(0),
                        top(1),
                        top(2),
                        top(3),
                    ]);
                }
                _ => unreachable!(),
            }
        }
    }
    let sm_out = SubMesh::from_connectivity(coords.clone(), solid_et, out)?;
    // The solid owns the fresh nodes now; hand back the unit `add_nodes`
    // handed us.
    let owned: Vec<NodeId> = (first..first + (inner * n_cols) as u32)
        .map(NodeId)
        .collect();
    coords.write().decref_all(&owned)?;
    Ok(Mesh::from_submesh(sm_out))
}