Skip to main content

gondola_core/geometry/
gdml.rs

1//! Streaming parser for the subset of GDML used by the 
2//! GAPS geometry.
3//!
4//! GDML requires every element to be defined before it is 
5//! referenced (define -> materials -> solids -> structure), 
6//! so all references are resolved while reading.
7// This file is part of gaps-online-software and published 
8// under the GPLv3 license
9
10use crate::prelude::*;
11
12use std::io::BufRead;
13
14use glam::DVec3;
15use quick_xml::events::{
16  BytesStart,
17  Event,
18};
19use quick_xml::Reader;
20
21/// Parse a GDML file
22pub fn parse_gdml_file(path : &Path) -> Result<Geometry, GeometryError> {
23  let file = File::open(path)?;
24  parse(Reader::from_reader(BufReader::new(file)))
25}
26
27/// Parse GDML from a string
28pub fn parse_gdml_str(gdml : &str) -> Result<Geometry, GeometryError> {
29  parse(Reader::from_str(gdml))
30}
31
32//------------------------------------------------------------
33
34/// Error without position, the position is added
35/// by the main loop
36type Res<T> = Result<T, String>;
37
38#[derive(Debug, Copy, Clone, PartialEq)]
39enum Section {
40  None,
41  Define,
42  Materials,
43  Solids,
44  Structure,
45  Setup,
46}
47
48/// The GDML element which is currently being read and
49/// can have children
50enum Open {
51  Material  { name : String, density : Option<f64> },
52  Tessellated(TessellatedBuilder),
53  Boolean(BooleanBuilder),
54  Volume(VolumeBuilder),
55  Physvol(VolumeBuilder, PhysvolBuilder),
56}
57
58struct TessellatedBuilder {
59  name      : String,
60  lunit     : f64,
61  vertices  : Vec<DVec3>,
62  triangles : Vec<[u32; 3]>,
63  /// define name -> index in vertices
64  index     : HashMap<String, u32>,
65}
66
67struct BooleanBuilder {
68  name     : String,
69  op       : BooleanOp,
70  first    : Option<SolidId>,
71  second   : Option<SolidId>,
72  position : DVec3,
73  angles   : DVec3,
74}
75
76struct VolumeBuilder {
77  name      : String,
78  material  : Option<MaterialId>,
79  solid     : Option<SolidId>,
80  daughters : Vec<Placement>,
81  auxiliary : Vec<(String, String)>,
82}
83
84struct PhysvolBuilder {
85  name       : String,
86  copynumber : i64,
87  volume     : Option<VolumeId>,
88  position   : DVec3,
89  angles     : DVec3,
90}
91
92#[derive(Default)]
93struct Parser {
94  /// define section, in mm and rad
95  positions    : HashMap<String, DVec3>,
96  rotations    : HashMap<String, DVec3>,
97  material_ids : HashMap<String, MaterialId>,
98  solid_ids    : HashMap<String, SolidId>,
99  volume_ids   : HashMap<String, VolumeId>,
100  materials    : Vec<Material>,
101  solids       : Vec<Solid>,
102  volumes      : Vec<Volume>,
103  world        : Option<VolumeId>,
104}
105
106fn parse<R: BufRead>(mut reader : Reader<R>) -> Result<Geometry, GeometryError> {
107  let mut parser  = Parser::default();
108  let mut section = Section::None;
109  let mut open    : Option<Open> = None;
110  let mut buf     = Vec::new();
111  loop {
112    let pos   = reader.buffer_position();
113    let event = reader.read_event_into(&mut buf)?;
114    let invalid = |msg : String| GeometryError::Gdml { pos, msg };
115    match event {
116      Event::Start(e) => {
117        parser.start(&e, &mut section, &mut open).map_err(invalid)?;
118      }
119      Event::Empty(e) => {
120        parser.start(&e, &mut section, &mut open).map_err(invalid)?;
121        parser.end(e.name().as_ref(), &mut section, &mut open).map_err(invalid)?;
122      }
123      Event::End(e) => {
124        parser.end(e.name().as_ref(), &mut section, &mut open).map_err(invalid)?;
125      }
126      Event::Eof => break,
127      _ => (),
128    }
129    buf.clear();
130  }
131  let world = parser.world.ok_or_else(|| GeometryError::Gdml {
132    pos : reader.buffer_position(),
133    msg : String::from("No world volume defined in <setup>"),
134  })?;
135  Geometry::new(parser.materials, parser.solids, parser.volumes, world)
136}
137
138impl Parser {
139  fn start(&mut self, e : &BytesStart, section : &mut Section, open : &mut Option<Open>) -> Res<()> {
140    let tag   = String::from_utf8_lossy(e.name().as_ref()).into_owned();
141    let attrs = Attributes::new(e)?;
142    match (*section, tag.as_str()) {
143      (_, "gdml")                     => (),
144      (Section::None, "define")       => *section = Section::Define,
145      (Section::None, "materials")    => *section = Section::Materials,
146      (Section::None, "solids")       => *section = Section::Solids,
147      (Section::None, "structure")    => *section = Section::Structure,
148      (Section::None, "setup")        => *section = Section::Setup,
149      (Section::Define, _)            => self.define(&tag, &attrs)?,
150      (Section::Materials, _)         => self.material_start(&tag, &attrs, open)?,
151      (Section::Solids, _)            => self.solid_start(&tag, &attrs, open)?,
152      (Section::Structure, _)         => self.structure_start(&tag, &attrs, open)?,
153      (Section::Setup, "world")       => {
154        self.world = Some(lookup(&self.volume_ids, attrs.get("ref")?, "volume")?);
155      }
156      (section, _) => return Err(format!("Unexpected element <{tag}> in section {section:?}")),
157    }
158    Ok(())
159  }
160
161  fn end(&mut self, tag : &[u8], section : &mut Section, open : &mut Option<Open>) -> Res<()> {
162    match tag {
163      b"define" | b"materials" | b"solids" | b"structure" | b"setup" => {
164        if open.is_some() {
165          return Err(format!("Section {:?} closed while an element is still open", section));
166        }
167        *section = Section::None;
168      }
169      b"material" => {
170        if let Some(Open::Material {name, density}) = open.take() {
171          let density = density.ok_or_else(|| format!("Material {name} has no density <D>"))?;
172          self.material_ids.insert(name.clone(), self.materials.len());
173          self.materials.push(Material { name, density });
174        }
175      }
176      b"tessellated" => {
177        if let Some(Open::Tessellated(t)) = open.take() {
178          self.push_solid(t.name, Shape::Tessellated {
179            vertices  : t.vertices,
180            triangles : t.triangles,
181          });
182        }
183      }
184      b"union" | b"intersection" | b"subtraction" => {
185        if let Some(Open::Boolean(b)) = open.take() {
186          let first  = b.first.ok_or_else(|| format!("Boolean solid {} has no <first>", b.name))?;
187          let second = b.second.ok_or_else(|| format!("Boolean solid {} has no <second>", b.name))?;
188          self.push_solid(b.name, Shape::Boolean {
189            op               : b.op,
190            first,
191            second,
192            second_transform : Transform::from_gdml(b.position, b.angles),
193          });
194        }
195      }
196      b"physvol" => {
197        if let Some(Open::Physvol(mut v, p)) = open.take() {
198          let volume = p.volume.ok_or_else(|| format!("physvol {} has no <volumeref>", p.name))?;
199          v.daughters.push(Placement {
200            name       : p.name,
201            copynumber : p.copynumber,
202            volume,
203            transform  : Transform::from_gdml(p.position, p.angles),
204          });
205          *open = Some(Open::Volume(v));
206        }
207      }
208      b"volume" if *section == Section::Structure => {
209        if let Some(Open::Volume(v)) = open.take() {
210          let material = v.material.ok_or_else(|| format!("Volume {} has no <materialref>", v.name))?;
211          let solid    = v.solid.ok_or_else(|| format!("Volume {} has no <solidref>", v.name))?;
212          self.volume_ids.insert(v.name.clone(), self.volumes.len());
213          self.volumes.push(Volume {
214            name      : v.name,
215            material,
216            solid,
217            daughters : v.daughters,
218            auxiliary : v.auxiliary,
219          });
220        }
221      }
222      _ => (),
223    }
224    Ok(())
225  }
226
227  fn define(&mut self, tag : &str, attrs : &Attributes) -> Res<()> {
228    match tag {
229      "position" => {
230        let name = attrs.get("name")?.to_string();
231        let pos  = attrs.vec3(length_unit(attrs.get_or("unit", "mm"))?)?;
232        self.positions.insert(name, pos);
233      }
234      "rotation" => {
235        let name = attrs.get("name")?.to_string();
236        let rot  = attrs.vec3(angle_unit(attrs.get_or("unit", "rad"))?)?;
237        self.rotations.insert(name, rot);
238      }
239      // constants, variables, matrices, ... would require
240      // an expression evaluator
241      _ => return Err(format!("Unsupported element <{tag}> in <define>")),
242    }
243    Ok(())
244  }
245
246  fn material_start(&mut self, tag : &str, attrs : &Attributes, open : &mut Option<Open>) -> Res<()> {
247    match (tag, open.as_mut()) {
248      ("material", None) => {
249        *open = Some(Open::Material { name : attrs.get("name")?.to_string(), density : None });
250      }
251      ("D", Some(Open::Material { density, .. })) => {
252        *density = Some(attrs.f64("value")? * density_unit(attrs.get_or("unit", "g/cm3"))?);
253      }
254      // elements and isotopes as well as the composition
255      // and other properties of the materials are not needed
256      // for the column density
257      _ => (),
258    }
259    Ok(())
260  }
261
262  fn solid_start(&mut self, tag : &str, attrs : &Attributes, open : &mut Option<Open>) -> Res<()> {
263    match open.as_mut() {
264      None => match tag {
265        "tessellated" => {
266          *open = Some(Open::Tessellated(TessellatedBuilder {
267            name      : attrs.get("name")?.to_string(),
268            lunit     : length_unit(attrs.get_or("lunit", "mm"))?,
269            vertices  : Vec::new(),
270            triangles : Vec::new(),
271            index     : HashMap::new(),
272          }));
273        }
274        "box" => {
275          let lunit = length_unit(attrs.get_or("lunit", "mm"))?;
276          // GDML gives the full lengths
277          let half_lengths = 0.5*attrs.vec3(lunit)?;
278          self.push_solid(attrs.get("name")?.to_string(), Shape::Box { half_lengths });
279        }
280        "tube" => {
281          let lunit = length_unit(attrs.get_or("lunit", "mm"))?;
282          let aunit = angle_unit(attrs.get_or("aunit", "rad"))?;
283          let shape = Shape::Tube {
284            rmin      : attrs.f64_or("rmin", 0.0)? * lunit,
285            rmax      : attrs.f64("rmax")? * lunit,
286            // GDML gives the full length
287            half_z    : 0.5*attrs.f64("z")? * lunit,
288            start_phi : attrs.f64_or("startphi", 0.0)? * aunit,
289            delta_phi : attrs.f64("deltaphi")? * aunit,
290          };
291          self.push_solid(attrs.get("name")?.to_string(), shape);
292        }
293        "union" | "intersection" | "subtraction" => {
294          let op = match tag {
295            "union"        => BooleanOp::Union,
296            "intersection" => BooleanOp::Intersection,
297            _              => BooleanOp::Subtraction,
298          };
299          *open = Some(Open::Boolean(BooleanBuilder {
300            name     : attrs.get("name")?.to_string(),
301            op,
302            first    : None,
303            second   : None,
304            position : DVec3::ZERO,
305            angles   : DVec3::ZERO,
306          }));
307        }
308        _ => return Err(format!("Unsupported solid <{tag}>")),
309      },
310      Some(Open::Tessellated(t)) => {
311        let vertex = |t : &mut TessellatedBuilder, positions : &HashMap<String, DVec3>, key : &str| -> Res<u32> {
312          let name = attrs.get(key)?;
313          if let Some(k) = t.index.get(name) {
314            return Ok(*k);
315          }
316          let pos = *positions.get(name).ok_or_else(|| format!("Unknown vertex {name}"))?;
317          let k   = t.vertices.len() as u32;
318          // as in Geant4, the lunit of the solid is applied
319          // on top of the unit of the position
320          t.vertices.push(pos*t.lunit);
321          t.index.insert(name.to_string(), k);
322          Ok(k)
323        };
324        if attrs.get_or("type", "ABSOLUTE") != "ABSOLUTE" {
325          return Err(format!("Facets of type {} are not supported", attrs.get_or("type", "")));
326        }
327        match tag {
328          "triangular" => {
329            let a = vertex(t, &self.positions, "vertex1")?;
330            let b = vertex(t, &self.positions, "vertex2")?;
331            let c = vertex(t, &self.positions, "vertex3")?;
332            t.triangles.push([a, b, c]);
333          }
334          "quadrangular" => {
335            let a = vertex(t, &self.positions, "vertex1")?;
336            let b = vertex(t, &self.positions, "vertex2")?;
337            let c = vertex(t, &self.positions, "vertex3")?;
338            let d = vertex(t, &self.positions, "vertex4")?;
339            t.triangles.push([a, b, c]);
340            t.triangles.push([a, c, d]);
341          }
342          _ => return Err(format!("Unsupported element <{tag}> in <tessellated>")),
343        }
344      }
345      Some(Open::Boolean(b)) => match tag {
346        "first"       => b.first    = Some(lookup(&self.solid_ids, attrs.get("ref")?, "solid")?),
347        "second"      => b.second   = Some(lookup(&self.solid_ids, attrs.get("ref")?, "solid")?),
348        "position"    => b.position = attrs.vec3(length_unit(attrs.get_or("unit", "mm"))?)?,
349        "rotation"    => b.angles   = attrs.vec3(angle_unit(attrs.get_or("unit", "rad"))?)?,
350        "positionref" => b.position = *self.positions.get(attrs.get("ref")?)
351                                        .ok_or_else(|| format!("Unknown position {}", attrs.get("ref").unwrap()))?,
352        "rotationref" => b.angles   = *self.rotations.get(attrs.get("ref")?)
353                                        .ok_or_else(|| format!("Unknown rotation {}", attrs.get("ref").unwrap()))?,
354        _ => return Err(format!("Unsupported element <{tag}> in boolean solid {}", b.name)),
355      },
356      Some(_) => return Err(format!("Unexpected element <{tag}> in <solids>")),
357    }
358    Ok(())
359  }
360
361  fn structure_start(&mut self, tag : &str, attrs : &Attributes, open : &mut Option<Open>) -> Res<()> {
362    match open.as_mut() {
363      None => match tag {
364        "volume" => {
365          *open = Some(Open::Volume(VolumeBuilder {
366            name      : attrs.get("name")?.to_string(),
367            material  : None,
368            solid     : None,
369            daughters : Vec::new(),
370            auxiliary : Vec::new(),
371          }));
372        }
373        _ => return Err(format!("Unsupported element <{tag}> in <structure>")),
374      },
375      Some(Open::Volume(v)) => match tag {
376        "materialref" => v.material = Some(lookup(&self.material_ids, attrs.get("ref")?, "material")?),
377        "solidref"    => v.solid    = Some(lookup(&self.solid_ids, attrs.get("ref")?, "solid")?),
378        "auxiliary"   => v.auxiliary.push((attrs.get("auxtype")?.to_string(),
379                                           attrs.get_or("auxvalue", "").to_string())),
380        "physvol"     => {
381          let p = PhysvolBuilder {
382            name       : attrs.get_or("name", "").to_string(),
383            copynumber : attrs.get_or("copynumber", "0").parse::<i64>()
384                           .map_err(|_| format!("Invalid copynumber {}", attrs.get_or("copynumber", "")))?,
385            volume     : None,
386            position   : DVec3::ZERO,
387            angles     : DVec3::ZERO,
388          };
389          let Some(Open::Volume(v)) = open.take() else { unreachable!() };
390          *open = Some(Open::Physvol(v, p));
391        }
392        _ => return Err(format!("Unsupported element <{tag}> in volume {}", v.name)),
393      },
394      Some(Open::Physvol(_, p)) => match tag {
395        "volumeref"   => p.volume   = Some(lookup(&self.volume_ids, attrs.get("ref")?, "volume")?),
396        "position"    => p.position = attrs.vec3(length_unit(attrs.get_or("unit", "mm"))?)?,
397        "rotation"    => p.angles   = attrs.vec3(angle_unit(attrs.get_or("unit", "rad"))?)?,
398        "positionref" => p.position = *self.positions.get(attrs.get("ref")?)
399                                        .ok_or_else(|| format!("Unknown position {}", attrs.get("ref").unwrap()))?,
400        "rotationref" => p.angles   = *self.rotations.get(attrs.get("ref")?)
401                                        .ok_or_else(|| format!("Unknown rotation {}", attrs.get("ref").unwrap()))?,
402        // scale (reflections) and file (external geometry)
403        _ => return Err(format!("Unsupported element <{tag}> in physvol {}", p.name)),
404      },
405      Some(_) => return Err(format!("Unexpected element <{tag}> in <structure>")),
406    }
407    Ok(())
408  }
409
410  fn push_solid(&mut self, name : String, shape : Shape) {
411    self.solid_ids.insert(name.clone(), self.solids.len());
412    self.solids.push(Solid { name, shape });
413  }
414}
415
416fn lookup(ids : &HashMap<String, usize>, name : &str, what : &str) -> Res<usize> {
417  ids.get(name).copied().ok_or_else(|| format!("Reference to unknown {what} {name}"))
418}
419
420//------------------------------------------------------------
421
422/// Attributes of an element as (key, value) strings.
423/// Elements have only a few attributes, so a linear
424/// search is fine.
425struct Attributes {
426  pairs : Vec<(String, String)>,
427}
428
429impl Attributes {
430  fn new(e : &BytesStart) -> Res<Self> {
431    let mut pairs = Vec::new();
432    for attr in e.attributes() {
433      let attr  = attr.map_err(|err| err.to_string())?;
434      let key   = String::from_utf8_lossy(attr.key.as_ref()).into_owned();
435      let value = attr.unescape_value().map_err(|err| err.to_string())?.into_owned();
436      pairs.push((key, value));
437    }
438    Ok(Self { pairs })
439  }
440
441  fn find(&self, key : &str) -> Option<&str> {
442    self.pairs.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str())
443  }
444
445  fn get(&self, key : &str) -> Res<&str> {
446    self.find(key).ok_or_else(|| format!("Missing attribute {key}"))
447  }
448
449  fn get_or<'a>(&'a self, key : &str, default : &'a str) -> &'a str {
450    self.find(key).unwrap_or(default)
451  }
452
453  fn f64(&self, key : &str) -> Res<f64> {
454    let value = self.get(key)?;
455    value.trim().parse::<f64>()
456      .map_err(|_| format!("Attribute {key}=\"{value}\" is not a number (expressions are not supported)"))
457  }
458
459  fn f64_or(&self, key : &str, default : f64) -> Res<f64> {
460    match self.find(key) {
461      None    => Ok(default),
462      Some(_) => self.f64(key),
463    }
464  }
465
466  /// x, y, z (each defaulting to 0) multiplied by unit
467  fn vec3(&self, unit : f64) -> Res<DVec3> {
468    Ok(DVec3::new(self.f64_or("x", 0.0)?, self.f64_or("y", 0.0)?, self.f64_or("z", 0.0)?) * unit)
469  }
470}
471
472/// in mm
473fn length_unit(unit : &str) -> Res<f64> {
474  match unit {
475    "nm" => Ok(1e-6),
476    "um" => Ok(1e-3),
477    "mm" => Ok(1.0),
478    "cm" => Ok(10.0),
479    "m"  => Ok(1000.0),
480    "km" => Ok(1e6),
481    _    => Err(format!("Unknown length unit {unit}")),
482  }
483}
484
485/// in rad
486fn angle_unit(unit : &str) -> Res<f64> {
487  match unit {
488    "rad"            => Ok(1.0),
489    "mrad"           => Ok(1e-3),
490    "deg" | "degree" => Ok(std::f64::consts::PI/180.0),
491    _                => Err(format!("Unknown angle unit {unit}")),
492  }
493}
494
495/// in g/cm3
496fn density_unit(unit : &str) -> Res<f64> {
497  match unit {
498    "g/cm3"  => Ok(1.0),
499    "mg/cm3" => Ok(1e-3),
500    "kg/m3"  => Ok(1e-3),
501    "g/mm3"  => Ok(1e3),
502    _        => Err(format!("Unknown density unit {unit}")),
503  }
504}
505
506//------------------------------------------------------------
507
508#[cfg(test)]
509mod tests {
510  use super::*;
511
512  const GDML : &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
513<gdml>
514  <define>
515    <position name="v0" unit="mm" x="0" y="0" z="0"/>
516    <position name="v1" unit="cm" x="1" y="0" z="0"/>
517    <position name="v2" unit="mm" x="0" y="10" z="0"/>
518    <position name="v3" unit="mm" x="0" y="0" z="10"/>
519    <rotation name="r90" unit="deg" x="0" y="0" z="90"/>
520  </define>
521  <materials>
522    <isotope N="1" Z="1" name="H1"><atom unit="g/mole" value="1.007"/></isotope>
523    <material name="Vacuum" state="gas">
524      <D unit="g/cm3" value="1e-25"/>
525      <atom unit="g/mole" value="1.0"/>
526    </material>
527    <material name="Alu" Z="13">
528      <T unit="K" value="293.15"/>
529      <D unit="kg/m3" value="2699"/>
530    </material>
531  </materials>
532  <solids>
533    <tessellated aunit="deg" lunit="mm" name="Tet">
534      <triangular vertex1="v0" vertex2="v2" vertex3="v1"/>
535      <triangular vertex1="v0" vertex2="v1" vertex3="v3"/>
536      <triangular vertex1="v0" vertex2="v3" vertex3="v2"/>
537      <triangular vertex1="v1" vertex2="v2" vertex3="v3"/>
538    </tessellated>
539    <box lunit="cm" name="World" x="100" y="100" z="100"/>
540    <tube aunit="deg" deltaphi="360" lunit="mm" name="Ring" rmax="50" rmin="48" startphi="0" z="2"/>
541    <box lunit="mm" name="Slab" x="10" y="20" z="2"/>
542    <intersection name="RingPart">
543      <first ref="Ring"/>
544      <second ref="Slab"/>
545      <position name="RingPart_pos" unit="mm" x="0" y="36.5" z="0"/>
546    </intersection>
547  </solids>
548  <structure>
549    <volume name="TetVol">
550      <materialref ref="Alu"/>
551      <solidref ref="Tet"/>
552      <auxiliary auxtype="SensDet" auxunit="mm" auxvalue="SimpleDet/ActiveDetectorSD"/>
553    </volume>
554    <volume name="RingVol">
555      <materialref ref="Alu"/>
556      <solidref ref="RingPart"/>
557    </volume>
558    <volume name="WorldVol">
559      <materialref ref="Vacuum"/>
560      <solidref ref="World"/>
561      <physvol copynumber="7" name="tet0">
562        <volumeref ref="TetVol"/>
563        <position name="tet0_pos" unit="mm" x="100" y="0" z="0"/>
564        <rotationref ref="r90"/>
565      </physvol>
566      <physvol name="ring0">
567        <volumeref ref="RingVol"/>
568        <position name="ring0_pos" unit="mm" x="0" y="0" z="-5"/>
569      </physvol>
570    </volume>
571  </structure>
572  <setup name="Default" version="1.0">
573    <world ref="WorldVol"/>
574  </setup>
575</gdml>
576"#;
577
578  #[test]
579  fn parse_example() {
580    let geo = parse_gdml_str(GDML).unwrap();
581    assert_eq!(geo.materials.len(), 2);
582    assert!((geo.materials[1].density - 2.699).abs() < 1e-12);
583    assert_eq!(geo.solids.len(), 5);
584    let Shape::Tessellated { vertices, triangles } = &geo.solids[0].shape else { panic!() };
585    // vertices are shared between the facets
586    assert_eq!(vertices.len(), 4);
587    assert_eq!(triangles.len(), 4);
588    assert_eq!(vertices[2], DVec3::new(10.0, 0.0, 0.0));
589    assert_eq!(geo.solids[1].shape, Shape::Box { half_lengths : DVec3::splat(500.0) });
590    let Shape::Tube { half_z, delta_phi, .. } = geo.solids[2].shape else { panic!() };
591    assert_eq!(half_z, 1.0);
592    assert!((delta_phi - 2.0*std::f64::consts::PI).abs() < 1e-12);
593    let Shape::Boolean { op, first, second, second_transform } = geo.solids[4].shape else { panic!() };
594    assert_eq!((op, first, second), (BooleanOp::Intersection, 2, 3));
595    assert_eq!(second_transform.translation, DVec3::new(0.0, 36.5, 0.0));
596
597    let world = geo.world_volume();
598    assert_eq!(world.name, "WorldVol");
599    assert_eq!(world.daughters.len(), 2);
600    assert_eq!(world.daughters[0].copynumber, 7);
601    // ring0 has no copynumber, which defaults to 0
602    assert_eq!(world.daughters[1].copynumber, 0);
603    assert_eq!(geo.volumes[0].auxiliary[0].1, "SimpleDet/ActiveDetectorSD");
604
605    let placements = geo.world_placements();
606    assert_eq!(placements.len(), 3);
607    // local x of the tetrahedron ends up along -y, see Transform::from_gdml
608    let p = placements[1].transform.apply_point(DVec3::new(10.0, 0.0, 0.0));
609    assert!((p - DVec3::new(100.0, -10.0, 0.0)).length() < 1e-9);
610    assert_eq!(geo.density(placements[2].volume), 2.699);
611
612    assert_eq!(geo.placements_by_copynumber.len(), 2);
613    assert_eq!(geo.placement(7), Some(&placements[1]));
614    assert_eq!(geo.placement(0).unwrap().volume, 1);
615    assert_eq!(geo.placement(8), None);
616  }
617
618  #[test]
619  fn duplicate_copynumber_is_an_error() {
620    let gdml = GDML.replace(r#"<physvol name="ring0">"#, r#"<physvol copynumber="7" name="ring0">"#);
621    assert!(matches!(parse_gdml_str(&gdml), Err(GeometryError::DuplicateCopynumber(7))));
622  }
623
624  #[test]
625  fn cache_roundtrip() {
626    let geo  = parse_gdml_str(GDML).unwrap();
627    let path = std::env::temp_dir().join(format!("gaps-geometry-test-{}.bin", std::process::id()));
628    geo.write_cache(&path).unwrap();
629    let cached = Geometry::read_cache(&path).unwrap();
630    std::fs::remove_file(&path).unwrap();
631    assert_eq!(geo, cached);
632  }
633
634  #[test]
635  fn unsupported_is_an_error() {
636    let gdml = GDML.replace(r#"<rotation name="r90""#, r#"<constant name="c" value="1"/><rotation name="r90""#);
637    assert!(parse_gdml_str(&gdml).unwrap_err().to_string().contains("<constant>"));
638    let gdml = GDML.replace(r#"x="100" y="100""#, r#"x="2*50" y="100""#);
639    assert!(parse_gdml_str(&gdml).unwrap_err().to_string().contains("expressions"));
640    let gdml = GDML.replace(r#"<volumeref ref="RingVol"/>"#, r#"<volumeref ref="Nope"/>"#);
641    assert!(parse_gdml_str(&gdml).is_err());
642  }
643}