1use crate::step_ids::IdAllocator;
17use crate::step_text::quoted;
18
19use super::add_types::GlobalId;
20use super::identity::{Identity, Made};
21use super::types::{ExportingApplication, ValidationFinding};
22use super::placement::fmt;
23use super::props_synth::ref_list;
24use super::tessellation::Emit;
25
26pub const SKELETON_SCHEMA: &str = "IFC4";
28
29#[derive(Debug, Clone)]
31#[non_exhaustive]
32pub struct SkeletonRoot {
33 pub global_id: GlobalId,
34 pub name: Option<String>,
35}
36
37#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
39#[non_exhaustive]
40pub enum MapUnit {
41 #[default]
42 Metre,
43 Foot,
45 UsSurveyFoot,
47}
48
49#[derive(Debug, Clone)]
57#[non_exhaustive]
58pub struct MapConversion {
59 pub crs_name: String,
61 pub map_unit: MapUnit,
66 pub eastings: f64,
67 pub northings: f64,
68 pub orthogonal_height: f64,
69 pub x_axis_abscissa: f64,
70 pub x_axis_ordinate: f64,
71 pub scale: Option<f64>,
73}
74
75#[derive(Debug, Clone)]
77#[non_exhaustive]
78pub struct Skeleton {
79 pub project: SkeletonRoot,
80 pub site: SkeletonRoot,
81 pub building: SkeletonRoot,
82 pub true_north: Option<[f64; 2]>,
86 pub map_conversion: Option<MapConversion>,
87 pub application: Option<ExportingApplication>,
91 pub file_name: Option<String>,
93}
94
95fn length_unit(emit: &mut Emit, name: &str, metres: f64, metre: u32) -> Result<u32, String> {
97 let dimensions = emit.record(
98 "IFCDIMENSIONALEXPONENTS",
99 &[
100 ("LengthExponent", "1".into()),
101 ("MassExponent", "0".into()),
102 ("TimeExponent", "0".into()),
103 ("ElectricCurrentExponent", "0".into()),
104 ("ThermodynamicTemperatureExponent", "0".into()),
105 ("AmountOfSubstanceExponent", "0".into()),
106 ("LuminousIntensityExponent", "0".into()),
107 ],
108 )?;
109 let factor = emit.record(
110 "IFCMEASUREWITHUNIT",
111 &[("ValueComponent", format!("IFCLENGTHMEASURE({})", fmt(metres))), ("UnitComponent", format!("#{metre}"))],
112 )?;
113 emit.record(
114 "IFCCONVERSIONBASEDUNIT",
115 &[
116 ("Dimensions", format!("#{dimensions}")),
117 ("UnitType", ".LENGTHUNIT.".into()),
118 ("Name", format!("'{name}'")),
119 ("ConversionFactor", format!("#{factor}")),
120 ],
121 )
122}
123
124pub fn skeleton(s: &Skeleton) -> Result<Vec<u8>, String> {
132 build(s, true).map(|(bytes, _)| bytes)
133}
134
135pub fn skeleton_with_findings(s: &Skeleton) -> Result<(Vec<u8>, Vec<ValidationFinding>), String> {
143 build(s, false)
144}
145
146fn build(s: &Skeleton, strict: bool) -> Result<(Vec<u8>, Vec<ValidationFinding>), String> {
148 check(s)?;
149 let mut findings = Vec::new();
150 let mut ids = IdAllocator::after(0);
151 let mut out = Vec::new();
152 let mut emit = Emit {
153 schema: SKELETON_SCHEMA,
154 ids: &mut ids,
155 out: &mut out,
156 };
157 let identity = identity_of(s, strict, &mut findings)?;
159 let history = owner_slot(identity.as_ref(), &mut emit)?;
160 let name = |root: &SkeletonRoot| root.name.as_deref().map_or("$".to_string(), quoted);
161 let gid = |root: &SkeletonRoot| format!("'{}'", root.global_id.encode());
162
163 let si = |emit: &mut Emit, unit: &str, name: &str| {
164 emit.record(
165 "IFCSIUNIT",
166 &[
167 ("Dimensions", "*".into()),
169 ("UnitType", format!(".{unit}.")),
170 ("Name", format!(".{name}.")),
171 ],
172 )
173 };
174 let units = [
175 si(&mut emit, "LENGTHUNIT", "METRE")?,
176 si(&mut emit, "AREAUNIT", "SQUARE_METRE")?,
177 si(&mut emit, "VOLUMEUNIT", "CUBIC_METRE")?,
178 si(&mut emit, "PLANEANGLEUNIT", "RADIAN")?,
179 ];
180 let unit_assignment = emit.record("IFCUNITASSIGNMENT", &[("Units", ref_list(&units))])?;
181
182 let wcs = emit.identity_placement()?;
183 let mut context_fields = vec![
184 ("ContextType", "'Model'".to_string()),
185 ("CoordinateSpaceDimension", "3".into()),
186 ("Precision", "1.E-05".into()),
187 ("WorldCoordinateSystem", format!("#{wcs}")),
188 ];
189 if let Some([x, y]) = s.true_north {
190 let north = emit.record(
191 "IFCDIRECTION",
192 &[("DirectionRatios", format!("({},{})", fmt(x), fmt(y)))],
193 )?;
194 context_fields.push(("TrueNorth", format!("#{north}")));
195 }
196 let context = emit.record("IFCGEOMETRICREPRESENTATIONCONTEXT", &context_fields)?;
197 emit.record(
198 "IFCGEOMETRICREPRESENTATIONSUBCONTEXT",
199 &[
200 ("ContextIdentifier", "'Body'".into()),
201 ("ContextType", "'Model'".into()),
202 ("CoordinateSpaceDimension", "*".into()),
204 ("Precision", "*".into()),
205 ("WorldCoordinateSystem", "*".into()),
206 ("TrueNorth", "*".into()),
207 ("ParentContext", format!("#{context}")),
208 ("TargetView", ".MODEL_VIEW.".into()),
209 ],
210 )?;
211 if let Some(m) = &s.map_conversion {
212 map_conversion(m, context, units[0], &mut emit)?;
213 }
214
215 let project = emit.record(
216 "IFCPROJECT",
217 &[
218 ("GlobalId", gid(&s.project)),
219 ("OwnerHistory", history.clone()),
220 ("Name", name(&s.project)),
221 ("RepresentationContexts", format!("(#{context})")),
222 ("UnitsInContext", format!("#{unit_assignment}")),
223 ],
224 )?;
225
226 let site_a2p = emit.identity_placement()?;
227 let site_placement = emit.record(
228 "IFCLOCALPLACEMENT",
229 &[("RelativePlacement", format!("#{site_a2p}"))],
230 )?;
231 let site = emit.record(
232 "IFCSITE",
233 &[
234 ("GlobalId", gid(&s.site)),
235 ("OwnerHistory", history.clone()),
236 ("Name", name(&s.site)),
237 ("ObjectPlacement", format!("#{site_placement}")),
238 ("CompositionType", ".ELEMENT.".into()),
239 ],
240 )?;
241 let building_a2p = emit.identity_placement()?;
242 let building_placement = emit.record(
243 "IFCLOCALPLACEMENT",
244 &[
245 ("PlacementRelTo", format!("#{site_placement}")),
246 ("RelativePlacement", format!("#{building_a2p}")),
247 ],
248 )?;
249 let building = emit.record(
250 "IFCBUILDING",
251 &[
252 ("GlobalId", gid(&s.building)),
253 ("OwnerHistory", history.clone()),
254 ("Name", name(&s.building)),
255 ("ObjectPlacement", format!("#{building_placement}")),
256 ("CompositionType", ".ELEMENT.".into()),
257 ],
258 )?;
259 for (relating, related, root) in [(project, site, &s.site), (site, building, &s.building)] {
260 emit.record(
261 "IFCRELAGGREGATES",
262 &[
263 (
264 "GlobalId",
265 format!("'{}'", root.global_id.derive("rel/aggregates").encode()),
266 ),
267 ("OwnerHistory", history.clone()),
268 ("RelatingObject", format!("#{relating}")),
269 ("RelatedObjects", format!("(#{related})")),
270 ],
271 )?;
272 }
273
274 Ok((step_text(s.file_name.as_deref(), identity.as_ref(), &out)?, findings))
275}
276
277fn map_conversion(m: &MapConversion, context: u32, metre: u32, emit: &mut Emit) -> Result<(), String> {
280 let map_unit = match m.map_unit {
281 MapUnit::Metre => metre,
282 MapUnit::Foot => length_unit(emit, "FOOT", 0.3048, metre)?,
283 MapUnit::UsSurveyFoot => length_unit(emit, "US SURVEY FOOT", ifc_lite_core::US_SURVEY_FOOT_M, metre)?,
284 };
285 let crs = emit.record("IFCPROJECTEDCRS", &[("Name", quoted(&m.crs_name)), ("MapUnit", format!("#{map_unit}"))])?;
286 emit.record(
287 "IFCMAPCONVERSION",
288 &[
289 ("SourceCRS", format!("#{context}")),
290 ("TargetCRS", format!("#{crs}")),
291 ("Eastings", fmt(m.eastings)),
292 ("Northings", fmt(m.northings)),
293 ("OrthogonalHeight", fmt(m.orthogonal_height)),
294 ("XAxisAbscissa", fmt(m.x_axis_abscissa)),
295 ("XAxisOrdinate", fmt(m.x_axis_ordinate)),
296 ("Scale", m.scale.map_or("$".to_string(), fmt)),
297 ],
298 )?;
299 Ok(())
300}
301
302fn identity_of(s: &Skeleton, strict: bool, findings: &mut Vec<ValidationFinding>) -> Result<Option<Identity>, String> {
306 match s.application.as_ref().map(|app| Identity::resolve(app, findings)).transpose() {
307 Err(message) if strict => Err(message),
308 Err(message) => {
309 findings.push(ValidationFinding::new(None, message));
310 Ok(None)
311 }
312 Ok(identity) => Ok(identity),
313 }
314}
315
316fn owner_slot(identity: Option<&Identity>, emit: &mut Emit) -> Result<String, String> {
319 let Some(identity) = identity else { return Ok("$".to_string()) };
320 let id = identity.added_in(SKELETON_SCHEMA, emit.ids, None, &mut Made::default(), emit.out).ok_or("id space exhausted")?;
321 Ok(format!("#{id}"))
322}
323
324fn step_text(file_name: Option<&str>, identity: Option<&Identity>, out: &[(u32, String)]) -> Result<Vec<u8>, String> {
327 let empty = || Some(String::new());
330 let mut opts = crate::StepOptions {
331 description: empty(),
332 filename: Some(file_name.unwrap_or("").to_string()),
333 time_stamp: empty(),
334 application: empty(),
335 ..Default::default()
336 };
337 let originating = identity.map(|identity| identity.stamp_header(&mut opts));
338 let mut text = Vec::new();
339 crate::step_header::write_header_originating(&mut text, &opts, None, SKELETON_SCHEMA, originating.as_deref()).map_err(|e| e.to_string())?;
340 for (_, record) in out {
341 text.extend_from_slice(record.as_bytes());
342 text.push(b'\n');
343 }
344 text.extend_from_slice(b"ENDSEC;\nEND-ISO-10303-21;\n");
345 Ok(text)
346}
347
348fn check(s: &Skeleton) -> Result<(), String> {
349 let ids = [s.project.global_id, s.site.global_id, s.building.global_id];
350 if ids[0] == ids[1] || ids[1] == ids[2] || ids[0] == ids[2] {
351 return Err("the project, site and building need distinct GlobalIds".into());
352 }
353 if let Some(north) = s.true_north {
354 check_direction(north, "true north")?;
355 }
356 if let Some(m) = &s.map_conversion {
357 if m.crs_name.trim().is_empty() {
358 return Err("a map conversion needs a CRS name".into());
359 }
360 let values = [
361 m.eastings,
362 m.northings,
363 m.orthogonal_height,
364 m.scale.unwrap_or(1.0),
365 ];
366 if values.iter().any(|v| !v.is_finite()) {
367 return Err("a map conversion value is not finite".into());
368 }
369 if m.scale.is_some_and(|v| v <= 0.0) {
370 return Err("a map conversion scale must be positive".into());
371 }
372 check_direction(
373 [m.x_axis_abscissa, m.x_axis_ordinate],
374 "the map conversion's X axis",
375 )?;
376 }
377 Ok(())
378}
379
380fn check_direction([x, y]: [f64; 2], what: &str) -> Result<(), String> {
381 if !(x.is_finite() && y.is_finite() && x.hypot(y) > 1e-12) {
383 return Err(format!("{what} is not a direction"));
384 }
385 Ok(())
386}
387
388#[cfg(test)]
389#[path = "skeleton_tests.rs"]
390mod tests;