1use std::sync::Arc;
4
5use ifc_model::{Edit, Entity, EntityId, Model, Transaction, Value};
6use ifc_schema::Schema;
7
8use crate::annotation::{AnnotationType, BoxAlignment, TextPath};
9use crate::error::{StyleError, StyleResult};
10
11mod external;
12mod fill;
13mod light;
14mod presentation;
15mod surface;
16mod texture;
17
18pub use surface::{
19 create_colour_rgb, create_presentation_layer_with_style, create_styled_item,
20 create_surface_style, create_surface_style_rendering, create_surface_style_shading,
21 ColourRgbDraft, PresentationLayerDraft, StyledItemDraft, SurfaceStyleDraft,
22 SurfaceStyleRenderingDraft, SurfaceStyleShadingDraft,
23};
24
25pub use external::{
26 create_blob_texture, create_externally_defined_style, create_indexed_polygonal_texture_map,
27 create_indexed_triangle_texture_map, create_light_distribution_data,
28 create_light_intensity_distribution, create_surface_style_with_textures, create_text_style,
29 create_text_style_text_model, create_texture_coordinate_indices,
30 create_texture_coordinate_indices_with_voids, BlobTextureDraft, ExternalStyleKind, SizeValue,
31 TextModelDraft,
32};
33pub use fill::{create_fill_area_style_hatching, create_fill_area_style_tiles, HatchLineDistance};
34pub use light::{
35 create_light_source_ambient, create_light_source_directional, create_light_source_goniometric,
36 create_light_source_positional, create_light_source_spot, create_surface_style_lighting,
37 create_surface_style_refraction, Attenuation, GoniometricLight, LightSourceDraft, PointLight,
38 SpotCone,
39};
40pub use presentation::{
41 create_colour_rgb_list, create_curve_style, create_curve_style_font,
42 create_curve_style_font_and_scaling, create_curve_style_font_pattern,
43 create_draughting_predefined_colour, create_draughting_predefined_curve_font,
44 create_fill_area_style, create_indexed_colour_map, create_pixel_texture,
45 create_presentation_layer_assignment, create_text_style_font_model,
46 create_text_style_for_defined_font, create_texture_vertex, create_texture_vertex_list,
47 CurveStyleDraft, CurveWidth, FillStyleKind, PixelTextureDraft, PREDEFINED_COLOUR_NAMES,
48 PREDEFINED_CURVE_FONT_NAMES,
49};
50pub use texture::{
51 create_image_texture, create_texture_coordinate_generator, create_texture_map,
52 ImageTextureDraft,
53};
54
55#[derive(Debug, Clone, Default)]
58#[non_exhaustive]
59pub struct AnnotationDraft<'a> {
60 pub global_id: &'a str,
62 pub owner_history: Option<EntityId>,
64 pub name: Option<&'a str>,
66 pub description: Option<&'a str>,
68 pub object_type: Option<&'a str>,
71 pub object_placement: Option<EntityId>,
73 pub representation: Option<EntityId>,
75 pub predefined_type: Option<AnnotationType>,
77}
78
79impl<'a> AnnotationDraft<'a> {
80 #[must_use]
83 pub fn new(global_id: &'a str) -> Self {
84 Self {
85 global_id,
86 owner_history: None,
87 name: None,
88 description: None,
89 object_type: None,
90 object_placement: None,
91 representation: None,
92 predefined_type: None,
93 }
94 }
95
96 #[must_use]
100 pub fn owner_history(mut self, value: EntityId) -> Self {
101 self.owner_history = Some(value);
102 self
103 }
104
105 #[must_use]
109 pub fn name(mut self, value: &'a str) -> Self {
110 self.name = Some(value);
111 self
112 }
113
114 #[must_use]
118 pub fn description(mut self, value: &'a str) -> Self {
119 self.description = Some(value);
120 self
121 }
122
123 #[must_use]
128 pub fn object_type(mut self, value: &'a str) -> Self {
129 self.object_type = Some(value);
130 self
131 }
132
133 #[must_use]
137 pub fn object_placement(mut self, value: EntityId) -> Self {
138 self.object_placement = Some(value);
139 self
140 }
141
142 #[must_use]
146 pub fn representation(mut self, value: EntityId) -> Self {
147 self.representation = Some(value);
148 self
149 }
150
151 #[must_use]
155 pub fn predefined_type(mut self, value: AnnotationType) -> Self {
156 self.predefined_type = Some(value);
157 self
158 }
159}
160
161#[derive(Debug, Clone, Copy)]
164#[non_exhaustive]
165pub struct TextLiteralDraft<'a> {
166 pub literal: &'a str,
168 pub placement: EntityId,
170 pub path: TextPath,
172}
173
174impl<'a> TextLiteralDraft<'a> {
175 #[must_use]
178 pub fn new(literal: &'a str, placement: EntityId, path: TextPath) -> Self {
179 Self {
180 literal,
181 placement,
182 path,
183 }
184 }
185}
186
187#[derive(Debug, Clone, Copy)]
190#[non_exhaustive]
191pub struct TextLiteralWithExtentDraft<'a> {
192 pub literal: &'a str,
194 pub placement: EntityId,
196 pub path: TextPath,
198 pub extent: EntityId,
200 pub box_alignment: BoxAlignment,
202}
203
204impl<'a> TextLiteralWithExtentDraft<'a> {
205 #[must_use]
208 pub fn new(
209 literal: &'a str,
210 placement: EntityId,
211 path: TextPath,
212 extent: EntityId,
213 box_alignment: BoxAlignment,
214 ) -> Self {
215 Self {
216 literal,
217 placement,
218 path,
219 extent,
220 box_alignment,
221 }
222 }
223}
224
225#[derive(Debug, Clone)]
228#[non_exhaustive]
229pub struct AnnotationFillAreaDraft {
230 pub outer_boundary: EntityId,
232 pub inner_boundaries: Vec<EntityId>,
235}
236
237impl AnnotationFillAreaDraft {
238 #[must_use]
241 pub fn new(outer_boundary: EntityId) -> Self {
242 Self {
243 outer_boundary,
244 inner_boundaries: Vec::new(),
245 }
246 }
247
248 #[must_use]
253 pub fn inner_boundaries(mut self, value: Vec<EntityId>) -> Self {
254 self.inner_boundaries = value;
255 self
256 }
257}
258
259pub fn create_annotation(
263 tx: &mut Transaction,
264 model: &Model,
265 schema: &Schema,
266 draft: AnnotationDraft<'_>,
267) -> StyleResult<EntityId> {
268 if ifc_model::guid::Guid::parse(draft.global_id).is_none() {
269 return Err(invalid_authoring(
270 "IfcAnnotation",
271 "GlobalId",
272 draft.global_id,
273 ));
274 }
275 if draft.predefined_type == Some(AnnotationType::UserDefined)
276 && draft
277 .object_type
278 .is_none_or(|value| value.trim().is_empty())
279 {
280 return Err(invalid_authoring(
281 "IfcAnnotation",
282 "ObjectType",
283 "USERDEFINED requires a non-empty ObjectType",
284 ));
285 }
286 validate_optional_ref(tx, model, schema, draft.owner_history, "IfcOwnerHistory")?;
287 validate_optional_ref(
288 tx,
289 model,
290 schema,
291 draft.object_placement,
292 "IfcObjectPlacement",
293 )?;
294 validate_optional_ref(
295 tx,
296 model,
297 schema,
298 draft.representation,
299 "IfcProductRepresentation",
300 )?;
301
302 let mut values = vec![("GlobalId", text(draft.global_id))];
303 optional_reference(&mut values, "OwnerHistory", draft.owner_history);
304 optional_text(&mut values, "Name", draft.name);
305 optional_text(&mut values, "Description", draft.description);
306 optional_text(&mut values, "ObjectType", draft.object_type);
307 optional_reference(&mut values, "ObjectPlacement", draft.object_placement);
308 optional_reference(&mut values, "Representation", draft.representation);
309 if let Some(value) = draft.predefined_type {
310 values.push(("PredefinedType", enumeration(value.as_ifc())));
311 }
312 Ok(tx.create(build_named(schema, "IfcAnnotation", values)?))
313}
314
315pub fn create_text_literal(
318 tx: &mut Transaction,
319 model: &Model,
320 schema: &Schema,
321 draft: TextLiteralDraft<'_>,
322) -> StyleResult<EntityId> {
323 if draft.literal.is_empty() {
324 return Err(invalid_authoring("IfcTextLiteral", "Literal", "empty"));
325 }
326 validate_ref(tx, model, schema, draft.placement, "IfcPlacement")?;
327 Ok(tx.create(build_named(
328 schema,
329 "IfcTextLiteral",
330 vec![
331 ("Literal", text(draft.literal)),
332 ("Placement", Value::Ref(draft.placement)),
333 ("Path", enumeration(draft.path.as_ifc())),
334 ],
335 )?))
336}
337
338pub fn create_text_literal_with_extent(
341 tx: &mut Transaction,
342 model: &Model,
343 schema: &Schema,
344 draft: TextLiteralWithExtentDraft<'_>,
345) -> StyleResult<EntityId> {
346 if draft.literal.is_empty() {
347 return Err(invalid_authoring(
348 "IfcTextLiteralWithExtent",
349 "Literal",
350 "empty",
351 ));
352 }
353
354 validate_ref(tx, model, schema, draft.placement, "IfcPlacement")?;
355 validate_ref(tx, model, schema, draft.extent, "IfcPlanarExtent")?;
356 Ok(tx.create(build_named(
357 schema,
358 "IfcTextLiteralWithExtent",
359 vec![
360 ("Literal", text(draft.literal)),
361 ("Placement", Value::Ref(draft.placement)),
362 ("Path", enumeration(draft.path.as_ifc())),
363 ("Extent", Value::Ref(draft.extent)),
364 ("BoxAlignment", text(draft.box_alignment.as_ifc())),
365 ],
366 )?))
367}
368
369pub fn create_annotation_fill_area(
372 tx: &mut Transaction,
373 model: &Model,
374 schema: &Schema,
375 draft: AnnotationFillAreaDraft,
376) -> StyleResult<EntityId> {
377 validate_ref(tx, model, schema, draft.outer_boundary, "IfcCurve")?;
378 for inner in &draft.inner_boundaries {
379 validate_ref(tx, model, schema, *inner, "IfcCurve")?;
380 }
381 let inner = if draft.inner_boundaries.is_empty() {
382 Value::Null
383 } else {
384 Value::List(draft.inner_boundaries.into_iter().map(Value::Ref).collect())
385 };
386 Ok(tx.create(build_named(
387 schema,
388 "IfcAnnotationFillArea",
389 vec![
390 ("OuterBoundary", Value::Ref(draft.outer_boundary)),
391 ("InnerBoundaries", inner),
392 ],
393 )?))
394}
395
396pub fn create_planar_extent(
423 tx: &mut Transaction,
424 model: &Model,
425 schema: &Schema,
426 size_in_x: f64,
427 size_in_y: f64,
428 placement: Option<EntityId>,
429) -> StyleResult<EntityId> {
430 let entity = if placement.is_some() {
431 "IfcPlanarBox"
432 } else {
433 "IfcPlanarExtent"
434 };
435 for (attribute, value) in [("SizeInX", size_in_x), ("SizeInY", size_in_y)] {
436 if !value.is_finite() || value <= 0.0 {
437 return Err(invalid_authoring(entity, attribute, format!("{value}")));
438 }
439 }
440 let mut values = vec![
441 ("SizeInX", Value::Real(size_in_x)),
442 ("SizeInY", Value::Real(size_in_y)),
443 ];
444 if let Some(placement) = placement {
445 let placement_type = schema_placement_type(tx, model, placement)?;
449 if !matches!(
450 placement_type.as_str(),
451 "IFCAXIS2PLACEMENT2D" | "IFCAXIS2PLACEMENT3D"
452 ) {
453 return Err(StyleError::ReferenceType {
454 target: placement,
455 expected: "IfcAxis2Placement",
456 actual: placement_type,
457 });
458 }
459 values.push(("Placement", Value::Ref(placement)));
460 }
461 Ok(tx.create(build_named(schema, entity, values)?))
462}
463
464fn schema_placement_type(tx: &Transaction, model: &Model, target: EntityId) -> StyleResult<String> {
470 tx.edits()
471 .iter()
472 .rev()
473 .find_map(|edit| match edit {
474 Edit::Create { id, entity } if *id == target => Some(entity.type_name.to_string()),
475 _ => None,
476 })
477 .or_else(|| model.get(target).map(|e| e.type_name.to_string()))
478 .ok_or(StyleError::DanglingReference {
479 source_id: EntityId(0),
480 target,
481 })
482}
483
484pub(crate) fn schema_attribute(
485 schema: &Schema,
486 entity: &str,
487 candidates: [&'static str; 2],
488) -> &'static str {
489 candidates
490 .into_iter()
491 .find(|candidate| {
492 schema
493 .attributes(entity)
494 .iter()
495 .any(|attribute| attribute.name.eq_ignore_ascii_case(candidate))
496 })
497 .unwrap_or(candidates[0])
498}
499
500pub(crate) fn build_named(
501 schema: &Schema,
502 entity: &'static str,
503 values: Vec<(&'static str, Value)>,
504) -> StyleResult<Entity> {
505 let declared = schema.attributes(entity);
506 if declared.is_empty() && schema.entity(entity).is_none() {
507 return Err(StyleError::UnsupportedEntity {
508 schema: schema.name().to_owned(),
509 entity,
510 });
511 }
512 let mut slots = vec![Value::Null; declared.len()];
513 let mut filled = vec![false; declared.len()];
514 for (name, value) in values {
515 let Some(index) = declared
516 .iter()
517 .position(|attribute| attribute.name.eq_ignore_ascii_case(name))
518 else {
519 return Err(StyleError::UnsupportedAttribute {
520 schema: schema.name().to_owned(),
521 entity,
522 attribute: name,
523 });
524 };
525 slots[index] = value;
526 filled[index] = true;
527 }
528 for (index, attribute) in declared.iter().enumerate() {
529 if !filled[index] && !attribute.optional {
530 return Err(StyleError::AuthoringInvalid {
531 entity,
532 attribute: "required attribute",
533 value: attribute.name.clone(),
534 });
535 }
536 }
537 Ok(Entity::new(entity.to_ascii_uppercase(), slots))
538}
539
540pub(crate) fn staged_type<'a>(
542 tx: &'a Transaction,
543 model: &'a Model,
544 target: EntityId,
545) -> StyleResult<&'a str> {
546 tx.edits()
547 .iter()
548 .rev()
549 .find_map(|edit| match edit {
550 Edit::Create { id, entity } if *id == target => Some(entity.type_name.as_ref()),
551 _ => None,
552 })
553 .or_else(|| model.get(target).map(|entity| entity.type_name.as_ref()))
554 .ok_or(StyleError::DanglingReference {
555 source_id: EntityId(0),
556 target,
557 })
558}
559
560pub(crate) fn validate_ref(
561 tx: &Transaction,
562 model: &Model,
563 schema: &Schema,
564 target: EntityId,
565 expected: &'static str,
566) -> StyleResult<()> {
567 let type_name = staged_type(tx, model, target)?;
568 if !schema.is_a(type_name, expected) {
569 return Err(StyleError::ReferenceType {
570 target,
571 expected,
572 actual: type_name.to_owned(),
573 });
574 }
575 Ok(())
576}
577
578pub(crate) fn validate_optional_ref(
579 tx: &Transaction,
580 model: &Model,
581 schema: &Schema,
582 target: Option<EntityId>,
583 expected: &'static str,
584) -> StyleResult<()> {
585 if let Some(target) = target {
586 validate_ref(tx, model, schema, target, expected)?;
587 }
588 Ok(())
589}
590
591fn text(value: &str) -> Value {
592 Value::Text(Arc::from(value))
593}
594
595pub(crate) fn enumeration(value: &str) -> Value {
596 Value::Enum(Arc::from(value.to_ascii_uppercase()))
597}
598
599fn optional_text(values: &mut Vec<(&'static str, Value)>, name: &'static str, value: Option<&str>) {
600 if let Some(value) = value {
601 values.push((name, text(value)));
602 }
603}
604
605fn optional_reference(
606 values: &mut Vec<(&'static str, Value)>,
607 name: &'static str,
608 value: Option<EntityId>,
609) {
610 if let Some(value) = value {
611 values.push((name, Value::Ref(value)));
612 }
613}
614
615pub(crate) fn invalid_authoring(
616 entity: &'static str,
617 attribute: &'static str,
618 value: impl ToString,
619) -> StyleError {
620 StyleError::AuthoringInvalid {
621 entity,
622 attribute,
623 value: value.to_string(),
624 }
625}
626
627pub(crate) fn validate_ratio(
628 entity: &'static str,
629 attribute: &'static str,
630 value: f64,
631) -> StyleResult<()> {
632 if value.is_finite() && (0.0..=1.0).contains(&value) {
633 Ok(())
634 } else {
635 Err(invalid_authoring(entity, attribute, value))
636 }
637}