1use crate::record::{Field, Record, ToRecord};
33use crate::{BindingError, IfcModel};
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37#[non_exhaustive]
38pub struct LengthUnitOptions {
39 pub area_and_volume: bool,
42 pub remove_replaced_units: bool,
44 pub dry_run: bool,
46}
47
48impl Default for LengthUnitOptions {
49 fn default() -> Self {
50 Self::new()
51 }
52}
53
54impl LengthUnitOptions {
55 #[must_use]
58 pub const fn new() -> Self {
59 Self {
60 area_and_volume: true,
61 remove_replaced_units: true,
62 dry_run: false,
63 }
64 }
65}
66
67#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct ConvertedValues {
70 pub entity_type: String,
72 pub attribute: String,
74 pub kind: String,
77 pub entities: usize,
79 pub values: usize,
81}
82
83#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct KeptValues {
86 pub entity_type: String,
88 pub attribute: String,
90 pub reason: String,
93 pub values: usize,
95}
96
97#[derive(Debug, Clone, PartialEq)]
99pub struct LengthUnitReport {
100 pub from: String,
102 pub to: String,
104 pub length_factor: f64,
106 pub area_factor: Option<f64>,
108 pub volume_factor: Option<f64>,
110 pub length_unit: Option<u64>,
112 pub area_unit: Option<u64>,
114 pub volume_unit: Option<u64>,
116 pub converted: Vec<ConvertedValues>,
118 pub kept: Vec<KeptValues>,
120 pub entities_changed: usize,
122 pub values_converted: usize,
124 pub created: Vec<u64>,
126 pub removed: Vec<u64>,
128 pub applied: bool,
130}
131
132impl ToRecord for ConvertedValues {
133 fn to_record(&self) -> Record {
134 Record::new(
135 "ConvertedValues",
136 vec![
137 ("entity_type", Field::Text(self.entity_type.clone())),
138 ("attribute", Field::Text(self.attribute.clone())),
139 ("kind", Field::Text(self.kind.clone())),
140 ("entities", Field::Count(self.entities)),
141 ("values", Field::Count(self.values)),
142 ],
143 )
144 }
145}
146
147impl ToRecord for KeptValues {
148 fn to_record(&self) -> Record {
149 Record::new(
150 "KeptValues",
151 vec![
152 ("entity_type", Field::Text(self.entity_type.clone())),
153 ("attribute", Field::Text(self.attribute.clone())),
154 ("reason", Field::Text(self.reason.clone())),
155 ("values", Field::Count(self.values)),
156 ],
157 )
158 }
159}
160
161impl ToRecord for LengthUnitReport {
162 fn to_record(&self) -> Record {
163 Record::new(
164 "LengthUnitReport",
165 vec![
166 ("from", Field::Text(self.from.clone())),
167 ("to", Field::Text(self.to.clone())),
168 ("length_factor", Field::Real(self.length_factor)),
169 (
170 "area_factor",
171 Field::optional(self.area_factor, Field::Real),
172 ),
173 (
174 "volume_factor",
175 Field::optional(self.volume_factor, Field::Real),
176 ),
177 ("length_unit", Field::id(self.length_unit)),
178 ("area_unit", Field::id(self.area_unit)),
179 ("volume_unit", Field::id(self.volume_unit)),
180 ("converted", Field::records(&self.converted)),
181 ("kept", Field::records(&self.kept)),
182 ("entities_changed", Field::Count(self.entities_changed)),
183 ("values_converted", Field::Count(self.values_converted)),
184 ("created", Field::ids(self.created.iter().copied())),
185 ("removed", Field::ids(self.removed.iter().copied())),
186 ("applied", Field::Bool(self.applied)),
187 ],
188 )
189 }
190}
191
192pub fn convert_unit(value: f64, from: &str, to: &str) -> Result<f64, BindingError> {
198 #[cfg(feature = "properties")]
199 {
200 let from = imp::parse(from)?;
201 let to = imp::parse(to)?;
202 ifc::properties::convert_value(value, &from, &to).map_err(imp::error)
203 }
204 #[cfg(not(feature = "properties"))]
205 {
206 let _ = (value, from, to);
207 Err(BindingError::FeatureDisabled("properties"))
208 }
209}
210
211pub fn format_length(
221 value: f64,
222 unit: &str,
223 style: &str,
224 places: u32,
225 display_unit: Option<&str>,
226 suppress_zero_inches: bool,
227) -> Result<String, BindingError> {
228 #[cfg(feature = "properties")]
229 {
230 use ifc::properties::LengthFormat;
231 let unit = imp::parse(unit)?;
232 let format = match style {
233 "decimal" => {
234 let display = match display_unit {
235 Some(display) => imp::parse(display)?,
236 None => unit.clone(),
237 };
238 let places = u8::try_from(places)
239 .map_err(|_| BindingError::OutOfRange(format!("{places} decimal places")))?;
240 LengthFormat::decimal(display, places)
241 }
242 "feet-inches" => LengthFormat::feet_inches(places, suppress_zero_inches),
243 "inches" => LengthFormat::inches(places),
244 other => {
245 return Err(BindingError::InvalidValue(format!(
246 "{other:?} is not a length style: decimal, feet-inches or inches"
247 )))
248 }
249 };
250 ifc::properties::format_length(value, &unit, &format).map_err(imp::error)
251 }
252 #[cfg(not(feature = "properties"))]
253 {
254 let _ = (
255 value,
256 unit,
257 style,
258 places,
259 display_unit,
260 suppress_zero_inches,
261 );
262 Err(BindingError::FeatureDisabled("properties"))
263 }
264}
265
266impl IfcModel {
267 pub fn convert_unit_value(&self, value: f64, from: u64, to: u64) -> Result<f64, BindingError> {
274 #[cfg(feature = "properties")]
275 {
276 for id in [from, to] {
277 if self.inner.get(ifc::EntityId(id)).is_none() {
278 return Err(BindingError::MissingEntity(id));
279 }
280 }
281 ifc::properties::convert_between(
282 &self.inner,
283 value,
284 ifc::EntityId(from),
285 ifc::EntityId(to),
286 )
287 .map_err(imp::error)
288 }
289 #[cfg(not(feature = "properties"))]
290 {
291 let _ = (value, from, to);
292 Err(BindingError::FeatureDisabled("properties"))
293 }
294 }
295
296 pub fn convert_length_unit(
305 &mut self,
306 target: &str,
307 options: LengthUnitOptions,
308 ) -> Result<LengthUnitReport, BindingError> {
309 #[cfg(feature = "properties")]
310 {
311 self.tracked(|this| imp::convert_length_unit(this, target, options))
312 }
313 #[cfg(not(feature = "properties"))]
314 {
315 let _ = (target, options);
316 Err(BindingError::FeatureDisabled("properties"))
317 }
318 }
319}
320
321#[cfg(feature = "properties")]
322mod imp {
323 use ifc::properties::{ConversionUnit, UnitConversionError};
324 use ifc::{ConvertedKind, KeptReason, LengthUnitError, RefusalReason};
325
326 use super::{ConvertedValues, KeptValues, LengthUnitOptions, LengthUnitReport};
327 use crate::{BindingError, IfcModel};
328
329 pub(super) fn parse(spec: &str) -> Result<ConversionUnit, BindingError> {
330 ConversionUnit::parse(spec).map_err(error)
331 }
332
333 pub(super) fn error(error: UnitConversionError) -> BindingError {
334 match error {
335 UnitConversionError::DimensionMismatch { .. } => {
336 BindingError::TypeMismatch(error.to_string())
337 }
338 UnitConversionError::MonetaryUnit { .. }
339 | UnitConversionError::ContextDependentUnit { .. }
340 | UnitConversionError::OffsetUnit { .. } => {
341 BindingError::Unsupported(error.to_string())
342 }
343 UnitConversionError::Resolve(_) => BindingError::InvalidModel(error.to_string()),
344 _ => BindingError::InvalidValue(error.to_string()),
345 }
346 }
347
348 fn kind(kind: ConvertedKind) -> &'static str {
349 match kind {
350 ConvertedKind::Length => "length",
351 ConvertedKind::Area => "area",
352 ConvertedKind::Volume => "volume",
353 ConvertedKind::InverseLength => "inverse-length",
354 ConvertedKind::InverseArea => "inverse-area",
355 ConvertedKind::MapScale => "map-scale",
356 _ => "other",
357 }
358 }
359
360 fn reason(reason: KeptReason) -> &'static str {
361 match reason {
362 KeptReason::ExplicitUnit => "explicit-unit",
363 KeptReason::MapUnit => "map-unit",
364 KeptReason::UnitlessParameter => "unitless-parameter",
365 KeptReason::UnitNotFollowed => "unit-not-followed",
366 _ => "other",
367 }
368 }
369
370 fn refusal(reason: &RefusalReason) -> String {
371 match reason {
372 RefusalReason::ParameterSpace {
373 host,
374 host_type,
375 detail,
376 } => format!("a parameter value on #{} {host_type}: {detail}", host.0),
377 RefusalReason::ParameterSpaceCurve {
378 surface,
379 surface_type,
380 } => format!(
381 "a p-curve in the parameter space of #{} {surface_type}, which is not a plane",
382 surface.0
383 ),
384 RefusalReason::PolynomialCoefficients => {
385 "IfcPolynomialCurve coefficients, whose unit IFC4.3 does not state".into()
386 }
387 RefusalReason::TextureGeneratorParameters => {
388 "IfcTextureCoordinateGenerator parameters, whose meaning depends on the mode".into()
389 }
390 RefusalReason::UntypedSelectValue { select } => {
391 format!("an untyped number in a {select}")
392 }
393 RefusalReason::MapTarget { target_type } => {
394 format!("a coordinate operation onto a {target_type}")
395 }
396 RefusalReason::AmbiguousUnit => "a value two owners give different units".into(),
397 RefusalReason::NotInSchema => "an entity the release does not declare".into(),
398 RefusalReason::Unresolved { detail } => detail.to_string(),
399 RefusalReason::ContextUnits => "a context with units of its own".into(),
400 other => format!("{other:?}"),
401 }
402 }
403
404 fn length_error(error: LengthUnitError) -> BindingError {
405 match error {
406 LengthUnitError::Target { target, reason } => {
407 BindingError::InvalidValue(format!("{target}: {reason}"))
408 }
409 LengthUnitError::Schema(error) => BindingError::UnsupportedSchema(error.to_string()),
410 LengthUnitError::ProjectUnit { unit_type, error } => match error {
411 UnitConversionError::Resolve(_) => {
412 BindingError::InvalidModel(format!("the project {unit_type}: {error}"))
413 }
414 other => super::imp::error(other),
415 },
416 LengthUnitError::Refused(refusals) => BindingError::Unsupported(format!(
417 "{} value(s) cannot be converted: {}",
418 refusals.len(),
419 refusals
420 .iter()
421 .take(10)
422 .map(|r| {
423 let attribute = r
424 .attribute
425 .as_deref()
426 .map(|a| format!(".{a}"))
427 .unwrap_or_default();
428 format!(
429 "#{} {}{attribute}: {}",
430 r.entity.0,
431 r.entity_type,
432 refusal(&r.reason)
433 )
434 })
435 .collect::<Vec<_>>()
436 .join("; ")
437 )),
438 LengthUnitError::Authoring(error) => BindingError::InvalidValue(error.to_string()),
439 LengthUnitError::Conflict(conflicts) => {
440 BindingError::InvalidModel(format!("{} conflict(s)", conflicts.len()))
441 }
442 other => BindingError::InvalidModel(other.to_string()),
443 }
444 }
445
446 pub(super) fn convert_length_unit(
447 model: &mut IfcModel,
448 target: &str,
449 options: LengthUnitOptions,
450 ) -> Result<LengthUnitReport, BindingError> {
451 let target = parse(target)?;
452 let facade = ifc::LengthUnitOptions::new()
453 .area_and_volume(options.area_and_volume)
454 .remove_replaced_units(options.remove_replaced_units);
455 let report = if options.dry_run {
456 ifc::stage_length_unit_conversion(&model.inner, &target, &facade)
457 .map_err(length_error)?
458 .report
459 } else {
460 ifc::convert_length_unit(&mut model.inner, &target, &facade).map_err(length_error)?
461 };
462 Ok(LengthUnitReport {
463 from: report.from.name.to_string(),
464 to: report.to.name.to_string(),
465 length_factor: report.length.factor(),
466 area_factor: report.area.map(|c| c.factor()),
467 volume_factor: report.volume.map(|c| c.factor()),
468 length_unit: report.length_unit.map(|id| id.0),
469 area_unit: report.area_unit.map(|id| id.0),
470 volume_unit: report.volume_unit.map(|id| id.0),
471 converted: report
472 .converted
473 .iter()
474 .map(|c| ConvertedValues {
475 entity_type: c.entity_type.to_string(),
476 attribute: c.attribute.to_string(),
477 kind: kind(c.kind).into(),
478 entities: c.entities,
479 values: c.values,
480 })
481 .collect(),
482 kept: report
483 .kept
484 .iter()
485 .map(|k| KeptValues {
486 entity_type: k.entity_type.to_string(),
487 attribute: k.attribute.to_string(),
488 reason: reason(k.reason).into(),
489 values: k.values,
490 })
491 .collect(),
492 entities_changed: report.entities_changed,
493 values_converted: report.values_converted,
494 created: report.created.iter().map(|id| id.0).collect(),
495 removed: report.removed.iter().map(|id| id.0).collect(),
496 applied: report.applied,
497 })
498 }
499}