1mod curves;
4mod export;
5mod geometry;
6mod mapping;
7pub mod native;
8pub mod tkgm;
9pub mod validate;
10mod xml;
11
12use cadkit_core::LimitKind;
13use cadkit_core::{Document, Error, Format, ReadOptions, Result, Summary};
14pub use export::{
15 ExportIssue, ExportOptions, ExportReport, UnsupportedGeometry, from_document,
16 from_document_with_report,
17};
18pub use geometry::{GeometryIssue, geometry_issues};
19pub use mapping::{ImportOptions, to_document};
20pub use native::CityGmlDocument;
21pub use validate::{ValidationOptions, ValidationReport, validate};
22
23pub fn sniff(bytes: &[u8]) -> bool {
25 use quick_xml::{NsReader, events::Event, name::ResolveResult};
26 let mut reader = NsReader::from_reader(bytes.get(..bytes.len().min(65536)).unwrap_or(&[]));
27 for _ in 0..64 {
28 match reader.read_resolved_event() {
29 Ok((ResolveResult::Bound(ns), Event::Start(e) | Event::Empty(e))) => {
30 return ns.as_ref() == native::CORE.as_bytes()
31 && e.local_name().as_ref() == b"CityModel";
32 }
33 Ok((_, Event::Decl(_) | Event::Comment(_) | Event::Text(_))) => {}
34 _ => return false,
35 }
36 }
37 false
38}
39
40pub fn inspect(bytes: &[u8], options: &ReadOptions) -> Result<Summary> {
42 use quick_xml::{NsReader, events::Event, name::ResolveResult};
43 if bytes.len() as u64 > options.limits.max_input_bytes {
44 return Err(Error::limit(
45 LimitKind::InputBytes,
46 "CityGML input bytes".into(),
47 ));
48 }
49 let head = bytes.get(..bytes.len().min(65536)).unwrap_or(&[]);
50 let mut reader = NsReader::from_reader(head);
51 let mut saw_root = false;
52 let mut in_bounded_by = false;
53 let mut srs_name: Option<String> = None;
54 let mut srs_dim: Option<String> = None;
55
56 let capture_srs = |e: &quick_xml::events::BytesStart<'_>,
57 srs_name: &mut Option<String>,
58 srs_dim: &mut Option<String>| {
59 for attr in e.attributes().flatten() {
60 let local = attr.key.local_name();
61 let slot = if local.as_ref() == b"srsName" && srs_name.is_none() {
62 Some(&mut *srs_name)
63 } else if local.as_ref() == b"srsDimension" && srs_dim.is_none() {
64 Some(&mut *srs_dim)
65 } else {
66 None
67 };
68 let Some(target) = slot else { continue };
69 let Ok(raw) = std::str::from_utf8(attr.value.as_ref()) else {
70 continue;
71 };
72 let Ok(val) = quick_xml::escape::unescape(raw) else {
73 continue;
74 };
75 let trimmed = val.trim();
76 if !trimmed.is_empty() {
77 *target = Some(trimmed.to_owned());
78 }
79 }
80 };
81
82 for _ in 0..256 {
83 match reader.read_resolved_event() {
84 Ok((res, Event::Start(e))) => {
85 if !saw_root {
86 let ResolveResult::Bound(ns) = res else {
87 return Err(Error::UnknownFormat);
88 };
89 if ns.as_ref() == native::CORE.as_bytes()
90 && e.local_name().as_ref() == b"CityModel"
91 {
92 saw_root = true;
93 capture_srs(&e, &mut srs_name, &mut srs_dim);
94 } else {
95 return Err(Error::UnknownFormat);
96 }
97 } else {
98 if let ResolveResult::Bound(ns) = res
99 && ns.as_ref() == native::GML.as_bytes()
100 && e.local_name().as_ref() == b"boundedBy"
101 {
102 in_bounded_by = true;
103 }
104 capture_srs(&e, &mut srs_name, &mut srs_dim);
105 if srs_name.is_some() {
106 break;
107 }
108 }
109 }
110 Ok((res, Event::Empty(e))) => {
111 if !saw_root {
112 let ResolveResult::Bound(ns) = res else {
113 return Err(Error::UnknownFormat);
114 };
115 if ns.as_ref() == native::CORE.as_bytes()
116 && e.local_name().as_ref() == b"CityModel"
117 {
118 saw_root = true;
119 capture_srs(&e, &mut srs_name, &mut srs_dim);
120 break;
121 }
122 return Err(Error::UnknownFormat);
123 }
124 capture_srs(&e, &mut srs_name, &mut srs_dim);
125 if srs_name.is_some() {
126 break;
127 }
128 }
129 Ok((ResolveResult::Bound(ns), Event::End(e))) => {
130 if in_bounded_by
131 && ns.as_ref() == native::GML.as_bytes()
132 && e.local_name().as_ref() == b"boundedBy"
133 && srs_name.is_some()
134 {
135 break;
136 }
137 }
138 Ok((_, Event::Decl(_) | Event::Comment(_) | Event::Text(_))) => {}
139 Ok((_, Event::Eof)) => break,
140 Ok(_) if saw_root => {}
141 _ => return Err(Error::UnknownFormat),
142 }
143 }
144
145 if !saw_root {
146 return Err(Error::UnknownFormat);
147 }
148
149 let is_3d = match srs_dim.as_deref() {
150 Some("2") => Some(false),
151 _ => Some(true),
152 };
153 let units = srs_name.as_deref().and_then(mapping::infer_srs_units);
154 Ok(Summary::new(Format::CityGml, "2.0")
155 .with_is_3d(is_3d)
156 .with_units(units)
157 .with_codepage(Some("UTF-8".into())))
158}
159
160pub fn read_native(bytes: &[u8], options: &ReadOptions) -> Result<CityGmlDocument> {
162 let doc = xml::parse(bytes, options)?;
163 validate(
164 &doc,
165 &ValidationOptions {
166 limits: options.limits,
167 geometry: false,
168 ..Default::default()
169 },
170 )?;
171 Ok(doc)
172}
173
174pub fn read_native_json(text: &str, options: &ReadOptions) -> Result<CityGmlDocument> {
176 if text.len() as u64 > options.limits.max_input_bytes {
177 return Err(cadkit_core::Error::limit(
178 LimitKind::InputBytes,
179 "CityGML JSON input bytes".into(),
180 ));
181 }
182 let doc =
183 serde_json::from_str(text).map_err(|e| cadkit_core::Error::invalid(0, e.to_string()))?;
184 validate(
185 &doc,
186 &ValidationOptions {
187 limits: options.limits,
188 geometry: false,
189 ..Default::default()
190 },
191 )?;
192 Ok(doc)
193}
194
195pub fn read(bytes: &[u8], options: &ReadOptions) -> Result<Document> {
197 to_document(
198 &read_native(bytes, options)?,
199 &ImportOptions::default(),
200 options,
201 )
202}
203
204pub fn write(doc: &CityGmlDocument, options: &ValidationOptions) -> Result<Vec<u8>> {
206 validate(doc, options)?;
207 xml::serialize(doc, &ReadOptions::default().with_limits(options.limits))
208}
209
210pub fn write_document(doc: &Document, options: &ExportOptions) -> Result<Vec<u8>> {
212 write(
213 &from_document(doc, options)?,
214 &ValidationOptions {
215 limits: options.limits,
216 ..Default::default()
217 },
218 )
219}
220
221pub fn write_document_with_report(
225 doc: &Document,
226 options: &ExportOptions,
227 unsupported: UnsupportedGeometry,
228) -> Result<(Vec<u8>, ExportReport)> {
229 let (native, report) = from_document_with_report(doc, options, unsupported)?;
230 let bytes = write(
231 &native,
232 &ValidationOptions {
233 limits: options.limits,
234 ..Default::default()
235 },
236 )?;
237 Ok((bytes, report))
238}