1use ifc_model::{Entity, EntityId, Model, Value};
16use ifc_schema::{for_version, Attribute, Schema, SchemaVersion};
17
18use crate::{MaterialError, MaterialResult};
19
20pub(crate) const IFC4_LAYOUT: &[(&str, &[&str])] = &[
27 ("IFCMATERIAL", &["Name", "Description", "Category"]),
28 (
29 "IFCMATERIALCLASSIFICATIONRELATIONSHIP",
30 &["MaterialClassifications", "ClassifiedMaterial"],
31 ),
32 (
33 "IFCMATERIALCONSTITUENT",
34 &["Name", "Description", "Material", "Fraction", "Category"],
35 ),
36 (
37 "IFCMATERIALCONSTITUENTSET",
38 &["Name", "Description", "MaterialConstituents"],
39 ),
40 (
41 "IFCMATERIALDEFINITIONREPRESENTATION",
42 &[
43 "Name",
44 "Description",
45 "Representations",
46 "RepresentedMaterial",
47 ],
48 ),
49 ("IFCMATERIALLAYER", LAYER),
50 (
51 "IFCMATERIALLAYERSET",
52 &["MaterialLayers", "LayerSetName", "Description"],
53 ),
54 (
55 "IFCMATERIALLAYERSETUSAGE",
56 &[
57 "ForLayerSet",
58 "LayerSetDirection",
59 "DirectionSense",
60 "OffsetFromReferenceLine",
61 "ReferenceExtent",
62 ],
63 ),
64 (
65 "IFCMATERIALLAYERWITHOFFSETS",
66 &[
67 "Material",
68 "LayerThickness",
69 "IsVentilated",
70 "Name",
71 "Description",
72 "Category",
73 "Priority",
74 "OffsetDirection",
75 "OffsetValues",
76 ],
77 ),
78 ("IFCMATERIALLIST", &["Materials"]),
79 ("IFCMATERIALPROFILE", PROFILE),
80 (
81 "IFCMATERIALPROFILESET",
82 &[
83 "Name",
84 "Description",
85 "MaterialProfiles",
86 "CompositeProfile",
87 ],
88 ),
89 ("IFCMATERIALPROFILESETUSAGE", PROFILE_USAGE),
90 (
91 "IFCMATERIALPROFILESETUSAGETAPERING",
92 &[
93 "ForProfileSet",
94 "CardinalPoint",
95 "ReferenceExtent",
96 "ForProfileEndSet",
97 "CardinalEndPoint",
98 ],
99 ),
100 (
101 "IFCMATERIALPROFILEWITHOFFSETS",
102 &[
103 "Name",
104 "Description",
105 "Material",
106 "Profile",
107 "Priority",
108 "Category",
109 "OffsetValues",
110 ],
111 ),
112 (
113 "IFCMATERIALPROPERTIES",
114 &["Name", "Description", "Properties", "Material"],
115 ),
116 (
117 "IFCMATERIALRELATIONSHIP",
118 &[
119 "Name",
120 "Description",
121 "RelatingMaterial",
122 "RelatedMaterials",
123 "Expression",
124 ],
125 ),
126 ("IFCRELASSOCIATESMATERIAL", ROOT_RELATION_MATERIAL),
127 ("IFCRELDEFINESBYTYPE", ROOT_RELATION_TYPE),
128];
129
130const LAYER: &[&str] = &[
131 "Material",
132 "LayerThickness",
133 "IsVentilated",
134 "Name",
135 "Description",
136 "Category",
137 "Priority",
138];
139const PROFILE: &[&str] = &[
140 "Name",
141 "Description",
142 "Material",
143 "Profile",
144 "Priority",
145 "Category",
146];
147const PROFILE_USAGE: &[&str] = &["ForProfileSet", "CardinalPoint", "ReferenceExtent"];
148const ROOT_RELATION_MATERIAL: &[&str] = &[
149 "GlobalId",
150 "OwnerHistory",
151 "Name",
152 "Description",
153 "RelatedObjects",
154 "RelatingMaterial",
155];
156const ROOT_RELATION_TYPE: &[&str] = &[
157 "GlobalId",
158 "OwnerHistory",
159 "Name",
160 "Description",
161 "RelatedObjects",
162 "RelatingType",
163];
164
165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
167pub(crate) enum Release<'m> {
168 Bound(SchemaVersion),
170 Multiple(usize),
172 Unsupported(&'m str),
174}
175
176const fn proven(version: SchemaVersion) -> bool {
182 matches!(
183 version,
184 SchemaVersion::Ifc2x3 | SchemaVersion::Ifc4 | SchemaVersion::Ifc4x3
185 )
186}
187
188impl<'m> Release<'m> {
189 pub(crate) const LEGACY: Release<'static> = Release::Bound(SchemaVersion::Ifc4);
192
193 pub(crate) fn of(model: &'m Model) -> Self {
195 match model.header().schema.as_slice() {
196 [] => Release::LEGACY,
197 [token] => SchemaVersion::from_header_token(token)
198 .filter(|version| proven(*version))
199 .map_or(Self::Unsupported(token.as_str()), Self::Bound),
200 tokens => Self::Multiple(tokens.len()),
201 }
202 }
203
204 pub(crate) fn bound(self) -> MaterialResult<(SchemaVersion, &'static Schema)> {
209 match self {
210 Self::Bound(version) => match for_version(version) {
211 Ok(schema) => Ok((version, schema)),
212 Err(_) => Err(MaterialError::UnsupportedSchema {
213 schema: version.header_tokens()[0].to_owned(),
214 }),
215 },
216 Self::Multiple(schemas) => Err(MaterialError::MultipleSchemas { schemas }),
217 Self::Unsupported(schema) => Err(MaterialError::UnsupportedSchema {
218 schema: schema.to_owned(),
219 }),
220 }
221 }
222
223 pub(crate) fn instantiates(self, entity: &str) -> bool {
226 self.bound()
227 .is_ok_and(|(_, schema)| instantiable(schema, entity))
228 }
229
230 pub(crate) fn require_entity(
233 self,
234 entity: &'static str,
235 id: Option<EntityId>,
236 ) -> MaterialResult<(SchemaVersion, &'static Schema)> {
237 let (version, schema) = self.bound()?;
238 if instantiable(schema, entity) {
239 Ok((version, schema))
240 } else {
241 Err(MaterialError::EntityNotInSchema {
242 entity,
243 id,
244 schema: version,
245 })
246 }
247 }
248
249 pub(crate) fn attribute(
256 self,
257 entity: &'static str,
258 id: EntityId,
259 attribute: &'static str,
260 ) -> MaterialResult<(usize, &'static Attribute)> {
261 debug_assert!(
262 in_ifc4_layout(entity, attribute),
263 "{entity}.{attribute} is read but missing from IFC4_LAYOUT"
264 );
265 let (version, schema) = self.require_entity(entity, Some(id))?;
266 position(schema, version, entity, attribute).ok_or(MaterialError::NotInSchema {
267 entity,
268 id,
269 attribute,
270 schema: version,
271 })
272 }
273
274 pub(crate) fn slot(
276 self,
277 entity: &'static str,
278 id: EntityId,
279 attribute: &'static str,
280 ) -> MaterialResult<usize> {
281 self.attribute(entity, id, attribute).map(|(slot, _)| slot)
282 }
283
284 pub(crate) fn accepts(
288 self,
289 entity: &'static str,
290 attribute: &'static str,
291 candidate: &str,
292 ) -> MaterialResult<(bool, &'static str)> {
293 let (_, schema) = self.bound()?;
294 let declared = self.declared(entity, attribute)?.type_name.as_str();
295 Ok((
296 instantiable(schema, candidate) && schema.accepts_type(declared, candidate),
297 declared,
298 ))
299 }
300
301 pub(crate) fn declared(
305 self,
306 entity: &'static str,
307 attribute: &'static str,
308 ) -> MaterialResult<&'static Attribute> {
309 let (version, schema) = self.require_entity(entity, None)?;
310 position(schema, version, entity, attribute)
311 .map(|(_, declared)| declared)
312 .ok_or(MaterialError::AuthoringNotInSchema {
313 entity,
314 attribute,
315 schema: version,
316 })
317 }
318
319 pub(crate) fn record(
327 self,
328 entity: &'static str,
329 values: Vec<(&'static str, Value)>,
330 ) -> MaterialResult<Entity> {
331 let (version, schema) = self.require_entity(entity, None)?;
332 let declared = schema.attributes(entity);
333 let mut slots = vec![None; declared.len()];
334 for (attribute, value) in values {
335 debug_assert!(
336 in_ifc4_layout(entity, attribute),
337 "{entity}.{attribute} is written but missing from IFC4_LAYOUT"
338 );
339 match position(schema, version, entity, attribute) {
340 Some((slot, _)) => slots[slot] = Some(value),
341 None if value == Value::Null => {}
342 None => {
343 return Err(MaterialError::AuthoringNotInSchema {
344 entity,
345 attribute,
346 schema: version,
347 })
348 }
349 }
350 }
351 let mut attributes = Vec::with_capacity(slots.len());
352 for (slot, value) in slots.into_iter().enumerate() {
353 let declaration = declared[slot];
354 match value.unwrap_or(Value::Null) {
355 Value::Null if !declaration.optional => {
356 return Err(MaterialError::AuthoringRequired {
357 entity,
358 attribute: declaration.name.as_str(),
359 schema: version,
360 })
361 }
362 value => attributes.push(value),
363 }
364 }
365 Ok(Entity::new(entity, attributes))
366 }
367}
368
369fn instantiable(schema: &Schema, entity: &str) -> bool {
370 schema
371 .entity(entity)
372 .is_some_and(|declaration| !declaration.abstract_)
373}
374
375fn position(
376 schema: &'static Schema,
377 version: SchemaVersion,
378 entity: &str,
379 attribute: &'static str,
380) -> Option<(usize, &'static Attribute)> {
381 let name = release_name(version, entity, attribute);
382 schema
383 .attributes(entity)
384 .into_iter()
385 .enumerate()
386 .find(|(_, declared)| declared.name.eq_ignore_ascii_case(name))
387}
388
389fn in_ifc4_layout(entity: &str, attribute: &str) -> bool {
390 IFC4_LAYOUT.iter().any(|(declared, attributes)| {
391 declared.eq_ignore_ascii_case(entity) && attributes.contains(&attribute)
392 })
393}
394
395pub(crate) fn release_name(
402 release: SchemaVersion,
403 entity: &str,
404 attribute: &'static str,
405) -> &'static str {
406 match (release, attribute) {
407 (SchemaVersion::Ifc4x3, "Expression")
408 if entity.eq_ignore_ascii_case("IFCMATERIALRELATIONSHIP") =>
409 {
410 "MaterialExpression"
411 }
412 _ => attribute,
413 }
414}
415
416pub(crate) fn is_type_object(release: Release<'_>, entity: &str) -> MaterialResult<bool> {
422 let (_, schema) = release.bound()?;
423 Ok(instantiable(schema, entity) && schema.is_a(entity, "IFCTYPEOBJECT"))
424}
425
426pub fn material_schema(model: &Model) -> MaterialResult<SchemaVersion> {
438 Release::of(model).bound().map(|(version, _)| version)
439}
440
441#[cfg(test)]
442mod tests;
443
444#[cfg(test)]
445mod intermediate_release_tests {
446 use super::*;
447
448 #[test]
451 fn ifc4x1_and_ifc4x2_are_refused_not_aliased() {
452 for token in ["IFC4X1", "IFC4X2"] {
453 let mut model = Model::new();
454 model.header_mut().schema = vec![token.to_owned()];
455 assert!(
456 matches!(Release::of(&model).bound(), Err(MaterialError::UnsupportedSchema { schema }) if schema == token),
457 "{token} must be refused"
458 );
459 }
460 }
461}