Skip to main content

cadkit_gml/
export.rs

1//! Explicit CAD geometry projection and conversion diagnostics.
2
3use crate::native::*;
4use cadkit_core::LimitKind;
5use cadkit_core::{Document, Entity, EntityKind, Error, Point3, Result, Value};
6use serde::{Deserialize, Serialize};
7
8/// Coordinate, LoD, and resource-limit contract for CityGML export.
9#[derive(Debug, Clone, Serialize, Deserialize)]
10#[non_exhaustive]
11pub struct ExportOptions {
12    /// Identifier of the existing CRS of the source coordinates; no coordinate reprojection is performed.
13    pub srs_name: String,
14    /// Level of Detail (`0..=4`) written on generic city object geometry.
15    pub lod: u8,
16    /// Resource limits enforced before writing and on the serialized XML output.
17    #[serde(default)]
18    pub limits: cadkit_core::Limits,
19}
20
21impl ExportOptions {
22    /// Creates CityGML export options for `srs_name` and `lod` (`0..=4`) with default limits.
23    #[must_use]
24    pub fn new(srs_name: impl Into<String>, lod: u8) -> Self {
25        Self {
26            srs_name: srs_name.into(),
27            lod,
28            limits: cadkit_core::Limits::default(),
29        }
30    }
31
32    /// Replaces the CRS identifier written to `srsName`.
33    #[must_use]
34    pub fn with_srs_name(mut self, srs_name: impl Into<String>) -> Self {
35        self.srs_name = srs_name.into();
36        self
37    }
38
39    /// Replaces the target Level of Detail (`0..=4`).
40    #[must_use]
41    pub fn with_lod(mut self, lod: u8) -> Self {
42        self.lod = lod;
43        self
44    }
45
46    /// Replaces the resource limits enforced during export.
47    #[must_use]
48    pub fn with_limits(mut self, limits: cadkit_core::Limits) -> Self {
49        self.limits = limits;
50        self
51    }
52}
53
54/// Handling of geometry without a supported, exact GML representation.
55#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case")]
57pub enum UnsupportedGeometry {
58    /// Stop without output. This remains the default of the existing export API.
59    #[default]
60    Reject,
61    /// Retain the source entity JSON as metadata, omit its GML geometry and report it.
62    /// This does not embed external image files or resolve block references.
63    MetadataOnly,
64}
65
66/// A source entity whose geometry is not present in the output.
67#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
68pub struct ExportIssue {
69    /// Stable diagnostic code, currently `gml.metadata_only`.
70    pub code: String,
71    /// Zero-based source model index.
72    pub model: usize,
73    /// Zero-based top-level entity index followed by nested group child indices.
74    pub path: Vec<usize>,
75    /// Neutral entity kind; never a file-controlled native type name.
76    pub entity_type: String,
77}
78
79/// Counts of visited source entities, including group nodes.
80#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
81pub struct ExportReport {
82    /// Number of source entities visited.
83    pub entities: u64,
84    /// Entities represented by GML geometry; groups may have incomplete child geometry.
85    pub geometry_entities: u64,
86    /// Entities retained only in `cadkit.entity` metadata.
87    pub metadata_only_entities: u64,
88    /// One diagnostic for each metadata-only entity, in source traversal order.
89    pub issues: Vec<ExportIssue>,
90}
91
92struct Exporter {
93    unsupported: UnsupportedGeometry,
94    report: ExportReport,
95    max_depth: u32,
96}
97
98impl Exporter {
99    fn geometry(
100        &mut self,
101        e: &Entity,
102        model: usize,
103        path: &mut Vec<usize>,
104    ) -> Result<Option<Element>> {
105        if path.len() as u64 > u64::from(self.max_depth.min(64)) {
106            return Err(Error::limit(
107                LimitKind::Depth,
108                "CityGML export depth".into(),
109            ));
110        }
111        self.report.entities += 1;
112        let result = if let EntityKind::Group { children, .. } = &e.kind {
113            let mut multi = Element::new(GML, "gml:MultiGeometry");
114            for (i, child) in children.iter().enumerate() {
115                path.push(i);
116                if let Some(g) = self.geometry(child, model, path)? {
117                    let mut member = Element::new(GML, "gml:geometryMember");
118                    member.push(g);
119                    multi.push(member);
120                }
121                path.pop();
122            }
123            if multi.children.is_empty() {
124                Err(Error::Unsupported("CityGML group has no geometry".into()))
125            } else {
126                Ok(multi)
127            }
128        } else {
129            geometry(&e.kind)
130        };
131        match result {
132            Ok(g) => {
133                self.report.geometry_entities += 1;
134                Ok(Some(g))
135            }
136            Err(Error::Unsupported(_)) if self.unsupported == UnsupportedGeometry::MetadataOnly => {
137                self.report.metadata_only_entities += 1;
138                self.report.issues.push(ExportIssue {
139                    code: "gml.metadata_only".into(),
140                    model,
141                    path: path.clone(),
142                    entity_type: e.kind.type_name().into(),
143                });
144                Ok(None)
145            }
146            Err(e) => Err(e),
147        }
148    }
149}
150
151fn point_element(p: Point3) -> Element {
152    Element::with_text(GML, "gml:pos", format!("{} {} {}", p.x, p.y, p.z))
153}
154fn geometry(kind: &EntityKind) -> Result<Element> {
155    match kind {
156        EntityKind::Point { position } => {
157            let mut e = Element::new(GML, "gml:Point");
158            e.push(point_element(*position));
159            Ok(e)
160        }
161        EntityKind::Line { start, end } => {
162            let mut e = Element::new(GML, "gml:LineString");
163            e.push(point_element(*start));
164            e.push(point_element(*end));
165            Ok(e)
166        }
167        EntityKind::Polyline {
168            vertices, closed, ..
169        } => {
170            if vertices.len() < 2 {
171                return Err(Error::invalid(
172                    0,
173                    "CityGML line requires at least two positions",
174                ));
175            }
176            if vertices
177                .iter()
178                .any(|v| v.bulge != 0.0 || v.start_width != 0.0 || v.end_width != 0.0)
179            {
180                return Err(Error::Unsupported(
181                    "CityGML polyline bulges/widths require explicit conversion".into(),
182                ));
183            }
184            let mut points: Vec<_> = vertices.iter().map(|v| v.position).collect();
185            if *closed
186                && points.first() != points.last()
187                && let Some(first) = points.first().copied()
188            {
189                points.push(first);
190            }
191            // Closure alone does not assert a planar surface. CAD paths may cross
192            // themselves or leave the plane; only explicit Polygon/Face means area.
193            let mut e = Element::new(GML, "gml:LineString");
194            for p in points {
195                e.push(point_element(p));
196            }
197            Ok(e)
198        }
199        EntityKind::Polygon {
200            exterior,
201            interiors,
202        } => Ok(Polygon {
203            id: None,
204            exterior: exterior.clone(),
205            interiors: interiors.clone(),
206        }
207        .to_element()),
208        EntityKind::Face { points, .. } => {
209            let mut ring = points.clone();
210            if ring.first() != ring.last()
211                && let Some(first) = ring.first().copied()
212            {
213                ring.push(first);
214            }
215            Ok(Polygon {
216                id: None,
217                exterior: ring,
218                interiors: vec![],
219            }
220            .to_element())
221        }
222        EntityKind::Mesh { vertices, faces } => {
223            let mut e = Element::new(GML, "gml:MultiSurface");
224            for f in faces {
225                let mut ring = vec![];
226                for &i in f {
227                    ring.push(
228                        *vertices
229                            .get(i as usize)
230                            .ok_or_else(|| Error::invalid(0, "mesh face index outside vertices"))?,
231                    );
232                }
233                if ring.first() != ring.last()
234                    && let Some(first) = ring.first().copied()
235                {
236                    ring.push(first);
237                }
238                let mut member = Element::new(GML, "gml:surfaceMember");
239                member.push(
240                    Polygon {
241                        id: None,
242                        exterior: ring,
243                        interiors: vec![],
244                    }
245                    .to_element(),
246                );
247                e.push(member);
248            }
249            Ok(e)
250        }
251        EntityKind::Circle {
252            center,
253            radius,
254            normal,
255        } => crate::curves::circle(*center, *radius, *normal),
256        EntityKind::Arc {
257            center,
258            radius,
259            start_angle,
260            end_angle,
261            normal,
262        } => crate::curves::arc(*center, *radius, *start_angle, *end_angle, *normal),
263        other => Err(Error::Unsupported(format!(
264            "CityGML export for {} requires explicit geometry/semantic mapping",
265            other.type_name()
266        ))),
267    }
268}
269
270/// Builds one `gen:GenericCityObject` per top-level neutral entity, rejecting unsupported geometry.
271/// Coordinates are written unchanged; matching the declared CRS and units is the caller's responsibility.
272pub fn from_document(source: &Document, options: &ExportOptions) -> Result<CityGmlDocument> {
273    from_document_with_report(source, options, UnsupportedGeometry::Reject).map(|(doc, _)| doc)
274}
275
276/// Creates generic objects and reports geometry retained only as metadata.
277/// Native building/unit semantics must be supplied through `CityGmlDocument`.
278/// Invalid geometry and resource-limit errors always fail, under either policy.
279pub fn from_document_with_report(
280    source: &Document,
281    options: &ExportOptions,
282    unsupported: UnsupportedGeometry,
283) -> Result<(CityGmlDocument, ExportReport)> {
284    if options.srs_name.trim().is_empty() || options.lod > 4 {
285        return Err(Error::invalid(
286            0,
287            "CityGML export requires an explicit CRS and LoD 0..4",
288        ));
289    }
290    cadkit_core::export::validate_limits(source, &options.limits)?;
291    let mut doc = CityGmlDocument::new();
292    let mut exporter = Exporter {
293        unsupported,
294        report: ExportReport::default(),
295        max_depth: options.limits.max_depth,
296    };
297    let mut next = 0u64;
298    for (model_index, model) in source.models.iter().enumerate() {
299        for (entity_index, e) in model.entities.iter().enumerate() {
300            next = next
301                .checked_add(1)
302                .ok_or_else(|| Error::limit(LimitKind::Objects, "CityGML export objects".into()))?;
303            let mut object =
304                CityObject::new(ObjectKind::GenericCityObject, format!("cadkit_{next}"));
305            if let Some(layer) = &e.layer {
306                object.properties.push(generic_attribute(
307                    "cadkit.layer",
308                    &Value::Text(layer.clone()),
309                )?);
310            }
311            if let Some(id) = e.id {
312                object.properties.push(generic_attribute(
313                    "cadkit.id",
314                    &Value::Text(id.to_string()),
315                )?);
316            }
317            for a in &e.attributes {
318                match generic_attribute(&a.tag, &a.value) {
319                    Ok(attr) => object.properties.push(attr),
320                    Err(Error::Unsupported(_))
321                        if unsupported == UnsupportedGeometry::MetadataOnly =>
322                    {
323                        match &a.value {
324                            Value::Bool(b) => object
325                                .properties
326                                .push(generic_attribute(&a.tag, &Value::Text(b.to_string()))?),
327                            Value::List(_) => {
328                                let json = serde_json::to_string(&a.value)
329                                    .map_err(|err| Error::invalid(0, err.to_string()))?;
330                                object
331                                    .properties
332                                    .push(generic_attribute(&a.tag, &Value::Text(json))?);
333                            }
334                            Value::Null | Value::Bytes(_) => {}
335                            _ => {}
336                        }
337                    }
338                    Err(err) => return Err(err),
339                }
340            }
341            // `validate_limits` has already verified that every float in `source` is finite.
342            let metadata =
343                serde_json::to_string(e).map_err(|err| Error::invalid(0, err.to_string()))?;
344            if metadata.len() as u64 > u64::from(options.limits.max_string_bytes) {
345                return Err(Error::limit(
346                    LimitKind::StringBytes,
347                    "CityGML entity metadata bytes".into(),
348                ));
349            }
350            object
351                .properties
352                .push(generic_attribute("cadkit.entity", &Value::Text(metadata))?);
353            if !e.props.is_empty() {
354                let text = serde_json::to_string(&e.props)
355                    .map_err(|e| Error::invalid(0, e.to_string()))?;
356                object
357                    .properties
358                    .push(generic_attribute("cadkit.props", &Value::Text(text))?);
359            }
360            let first_issue = exporter.report.issues.len();
361            let geometry = exporter.geometry(e, model_index, &mut vec![entity_index])?;
362            let issues = exporter.report.issues.get(first_issue..).unwrap_or(&[]);
363            if !issues.is_empty() {
364                object.properties.push(generic_attribute(
365                    "cadkit.geometry_status",
366                    &Value::Text(
367                        if geometry.is_some() {
368                            "partial"
369                        } else {
370                            "metadata_only"
371                        }
372                        .into(),
373                    ),
374                )?);
375                let text =
376                    serde_json::to_string(issues).map_err(|e| Error::invalid(0, e.to_string()))?;
377                object.properties.push(generic_attribute(
378                    "cadkit.export_issues",
379                    &Value::Text(text),
380                )?);
381            }
382            if let Some(mut g) = geometry {
383                let mut property =
384                    Element::new(GENERICS, &format!("gen:lod{}Geometry", options.lod));
385                g.set_attribute("", "srsName", &options.srs_name);
386                g.set_attribute("", "srsDimension", "3");
387                property.push(g);
388                object.properties.push(property);
389            }
390            doc.add_object(object);
391        }
392    }
393    Ok((doc, exporter.report))
394}