1use crate::error::GeometryResult;
35use crate::resource::direction::Direction;
36use crate::resource::resolve;
37use crate::slots::Slots;
38use ifc_model::{Entity, EntityId, Model};
39
40mod offset_2d_slot {
42 pub const BASIS_CURVE: usize = 0;
44 pub const DISTANCE: usize = 1;
46 pub const SELF_INTERSECT: usize = 2;
48}
49
50mod offset_3d_slot {
54 pub const BASIS_CURVE: usize = 0;
56 pub const DISTANCE: usize = 1;
58 pub const SELF_INTERSECT: usize = 2;
60 pub const REF_DIRECTION: usize = 3;
62}
63
64pub(crate) mod pcurve_slot {
66 pub const BASIS_SURFACE: usize = 0;
68 pub const REFERENCE_CURVE: usize = 1;
70}
71
72pub(crate) mod surface_curve_slot {
77 pub const CURVE_3D: usize = 0;
79 pub const ASSOCIATED_GEOMETRY: usize = 1;
81 pub const MASTER_REPRESENTATION: usize = 2;
83}
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum PreferredSurfaceCurveRepresentation {
88 Curve3D,
90 PCurveS1,
92 PCurveS2,
97}
98
99impl PreferredSurfaceCurveRepresentation {
100 pub fn from_token(token: &str) -> Option<Self> {
102 match token.to_ascii_uppercase().as_str() {
103 "CURVE3D" => Some(Self::Curve3D),
104 "PCURVE_S1" => Some(Self::PCurveS1),
105 "PCURVE_S2" => Some(Self::PCurveS2),
106 _ => None,
107 }
108 }
109
110 pub fn pcurve_index(&self) -> Option<usize> {
114 match self {
115 Self::Curve3D => None,
116 Self::PCurveS1 => Some(0),
117 Self::PCurveS2 => Some(1),
118 }
119 }
120}
121
122#[derive(Debug, Clone, Copy)]
124pub struct OffsetCurve2D<'m> {
125 slots: Slots<'m>,
126}
127
128impl<'m> OffsetCurve2D<'m> {
129 pub fn new(id: EntityId, entity: &'m Entity) -> Self {
131 Self {
132 slots: Slots::new(id, entity),
133 }
134 }
135
136 pub fn id(&self) -> EntityId {
138 self.slots.id()
139 }
140
141 pub fn basis_curve_ref(&self) -> GeometryResult<EntityId> {
143 self.slots
144 .req_ref(offset_2d_slot::BASIS_CURVE, "BasisCurve")
145 }
146
147 pub fn distance(&self) -> GeometryResult<f64> {
153 self.slots.req_f64(offset_2d_slot::DISTANCE, "Distance")
154 }
155
156 pub fn self_intersect(&self) -> Option<bool> {
158 self.slots.opt_bool(offset_2d_slot::SELF_INTERSECT)
159 }
160}
161
162#[derive(Debug, Clone, Copy)]
164pub struct OffsetCurve3D<'m> {
165 slots: Slots<'m>,
166}
167
168impl<'m> OffsetCurve3D<'m> {
169 pub fn new(id: EntityId, entity: &'m Entity) -> Self {
171 Self {
172 slots: Slots::new(id, entity),
173 }
174 }
175
176 pub fn id(&self) -> EntityId {
178 self.slots.id()
179 }
180
181 pub fn basis_curve_ref(&self) -> GeometryResult<EntityId> {
183 self.slots
184 .req_ref(offset_3d_slot::BASIS_CURVE, "BasisCurve")
185 }
186
187 pub fn distance(&self) -> GeometryResult<f64> {
189 self.slots.req_f64(offset_3d_slot::DISTANCE, "Distance")
190 }
191
192 pub fn self_intersect(&self) -> Option<bool> {
194 self.slots.opt_bool(offset_3d_slot::SELF_INTERSECT)
195 }
196
197 pub fn ref_direction_ref(&self) -> GeometryResult<EntityId> {
202 self.slots
203 .req_ref(offset_3d_slot::REF_DIRECTION, "RefDirection")
204 }
205
206 pub fn ref_direction<'v>(&self, model: &'v Model) -> GeometryResult<Direction<'v>> {
211 resolve::direction(model, self.id(), self.ref_direction_ref()?)
212 }
213}
214
215#[derive(Debug, Clone, Copy)]
221pub struct PCurve<'m> {
222 slots: Slots<'m>,
223}
224
225impl<'m> PCurve<'m> {
226 pub fn new(id: EntityId, entity: &'m Entity) -> Self {
228 Self {
229 slots: Slots::new(id, entity),
230 }
231 }
232
233 pub fn id(&self) -> EntityId {
235 self.slots.id()
236 }
237
238 pub fn basis_surface_ref(&self) -> GeometryResult<EntityId> {
240 self.slots
241 .req_ref(pcurve_slot::BASIS_SURFACE, "BasisSurface")
242 }
243
244 pub fn reference_curve_ref(&self) -> GeometryResult<EntityId> {
251 self.slots
252 .req_ref(pcurve_slot::REFERENCE_CURVE, "ReferenceCurve")
253 }
254}
255
256#[derive(Debug, Clone, Copy)]
258pub struct SurfaceCurve<'m> {
259 slots: Slots<'m>,
260}
261
262#[derive(Debug, Clone, Copy, PartialEq, Eq)]
264pub enum SurfaceCurveKind {
265 Plain,
267 Intersection,
271 Seam,
276}
277
278impl<'m> SurfaceCurve<'m> {
279 pub fn new(id: EntityId, entity: &'m Entity) -> Self {
281 Self {
282 slots: Slots::new(id, entity),
283 }
284 }
285
286 pub fn id(&self) -> EntityId {
288 self.slots.id()
289 }
290
291 pub fn kind(&self) -> Option<SurfaceCurveKind> {
293 match self.slots.entity().type_name.to_ascii_uppercase().as_str() {
294 "IFCSURFACECURVE" => Some(SurfaceCurveKind::Plain),
295 "IFCINTERSECTIONCURVE" => Some(SurfaceCurveKind::Intersection),
296 "IFCSEAMCURVE" => Some(SurfaceCurveKind::Seam),
297 _ => None,
298 }
299 }
300
301 pub fn curve_3d_ref(&self) -> GeometryResult<EntityId> {
303 self.slots.req_ref(surface_curve_slot::CURVE_3D, "Curve3D")
304 }
305
306 pub fn associated_pcurve_refs(&self) -> GeometryResult<Vec<EntityId>> {
312 let pcurves = self.slots.req_ref_list(
313 surface_curve_slot::ASSOCIATED_GEOMETRY,
314 "AssociatedGeometry",
315 )?;
316 if pcurves.is_empty() || pcurves.len() > 2 {
317 return Err(self.slots.degenerate(format!(
318 "AssociatedGeometry must hold 1 or 2 IfcPcurves, found {}",
319 pcurves.len()
320 )));
321 }
322 if matches!(
323 self.kind(),
324 Some(SurfaceCurveKind::Intersection) | Some(SurfaceCurveKind::Seam)
325 ) && pcurves.len() != 2
326 {
327 return Err(self.slots.degenerate(format!(
328 "{} requires exactly 2 associated IfcPcurves, found {}",
329 self.slots.type_name(),
330 pcurves.len()
331 )));
332 }
333 Ok(pcurves)
334 }
335
336 pub fn master_representation(&self) -> PreferredSurfaceCurveRepresentation {
341 self.slots
342 .opt_enum(surface_curve_slot::MASTER_REPRESENTATION)
343 .and_then(PreferredSurfaceCurveRepresentation::from_token)
344 .unwrap_or(PreferredSurfaceCurveRepresentation::Curve3D)
345 }
346
347 pub fn master_curve_ref(&self) -> GeometryResult<EntityId> {
353 match self.master_representation().pcurve_index() {
354 None => self.curve_3d_ref(),
355 Some(index) => {
356 let pcurves = self.associated_pcurve_refs()?;
357 pcurves.get(index).copied().ok_or_else(|| {
358 self.slots.degenerate(format!(
359 "MasterRepresentation names p-curve {} but AssociatedGeometry holds {}",
360 index + 1,
361 pcurves.len()
362 ))
363 })
364 }
365 }
366 }
367}
368
369#[cfg(test)]
370mod tests {
371 use super::*;
372 use ifc_model::Value;
373
374 fn offset_2d(distance: f64) -> Entity {
375 Entity::new(
376 "IFCOFFSETCURVE2D",
377 vec![
378 Value::Ref(EntityId(30)),
379 Value::Real(distance),
380 Value::Bool(false),
381 ],
382 )
383 }
384
385 fn offset_3d(distance: f64) -> Entity {
386 Entity::new(
387 "IFCOFFSETCURVE3D",
388 vec![
389 Value::Ref(EntityId(30)),
390 Value::Real(distance),
391 Value::Bool(false),
392 Value::Ref(EntityId(31)),
393 ],
394 )
395 }
396
397 fn surface_curve(type_name: &str, pcurves: &[u64], preference: &str) -> Entity {
398 Entity::new(
399 type_name,
400 vec![
401 Value::Ref(EntityId(40)),
402 Value::List(pcurves.iter().map(|i| Value::Ref(EntityId(*i))).collect()),
403 Value::Enum(preference.into()),
404 ],
405 )
406 }
407
408 #[test]
411 fn offset_distance_keeps_its_sign() {
412 let e = offset_2d(-0.5);
413 assert_eq!(
414 OffsetCurve2D::new(EntityId(1), &e).distance().unwrap(),
415 -0.5
416 );
417 }
418
419 #[test]
421 fn a_zero_offset_distance_is_accepted() {
422 let e = offset_2d(0.0);
423 assert_eq!(OffsetCurve2D::new(EntityId(1), &e).distance().unwrap(), 0.0);
424 }
425
426 #[test]
429 fn only_the_3d_offset_carries_a_reference_direction() {
430 let e = offset_3d(1.0);
431 let view = OffsetCurve3D::new(EntityId(1), &e);
432 assert_eq!(view.basis_curve_ref().unwrap(), EntityId(30));
433 assert_eq!(view.ref_direction_ref().unwrap(), EntityId(31));
434 assert_eq!(view.self_intersect(), Some(false));
435 }
436
437 #[test]
438 fn the_reference_direction_resolves_unnormalized() {
439 let mut model = Model::new();
440 let ratios = Value::List(vec![Value::Real(0.0), Value::Real(0.0), Value::Real(5.0)]);
441 model.insert(EntityId(31), Entity::new("IFCDIRECTION", vec![ratios]));
442 let e = offset_3d(1.0);
443 let direction = OffsetCurve3D::new(EntityId(1), &e)
444 .ref_direction(&model)
445 .unwrap();
446 assert_eq!(direction.ratios().unwrap(), vec![0.0, 0.0, 5.0]);
447 assert_eq!(direction.unit().unwrap(), [0.0, 0.0, 1.0]);
448 }
449
450 #[test]
451 fn a_reference_direction_that_is_a_point_is_a_typed_error() {
452 let mut model = Model::new();
453 model.insert(EntityId(31), Entity::new("IFCCARTESIANPOINT", vec![]));
454 let e = offset_3d(1.0);
455 let err = OffsetCurve3D::new(EntityId(1), &e)
456 .ref_direction(&model)
457 .unwrap_err();
458 assert!(matches!(
459 err,
460 crate::GeometryError::WrongEntityType {
461 entity: EntityId(31),
462 expected: "IfcDirection",
463 ..
464 }
465 ));
466 }
467
468 #[test]
469 fn a_3d_offset_missing_its_reference_direction_is_reported_by_name() {
470 let e = Entity::new(
471 "IFCOFFSETCURVE3D",
472 vec![
473 Value::Ref(EntityId(30)),
474 Value::Real(1.0),
475 Value::Bool(false),
476 ],
477 );
478 let err = OffsetCurve3D::new(EntityId(1), &e)
479 .ref_direction_ref()
480 .unwrap_err();
481 assert!(err.to_string().contains("RefDirection"), "got: {err}");
482 }
483
484 #[test]
485 fn pcurve_names_its_surface_and_its_parameter_space_curve() {
486 let e = Entity::new(
487 "IFCPCURVE",
488 vec![Value::Ref(EntityId(50)), Value::Ref(EntityId(51))],
489 );
490 let view = PCurve::new(EntityId(1), &e);
491 assert_eq!(view.basis_surface_ref().unwrap(), EntityId(50));
492 assert_eq!(view.reference_curve_ref().unwrap(), EntityId(51));
493 }
494
495 #[test]
498 fn master_representation_resolves_to_the_right_geometry() {
499 let by_3d = surface_curve("IFCSURFACECURVE", &[60, 61], "CURVE3D");
500 assert_eq!(
501 SurfaceCurve::new(EntityId(1), &by_3d)
502 .master_curve_ref()
503 .unwrap(),
504 EntityId(40)
505 );
506
507 let by_s1 = surface_curve("IFCSURFACECURVE", &[60, 61], "PCURVE_S1");
508 assert_eq!(
509 SurfaceCurve::new(EntityId(1), &by_s1)
510 .master_curve_ref()
511 .unwrap(),
512 EntityId(60)
513 );
514
515 let by_s2 = surface_curve("IFCSURFACECURVE", &[60, 61], "PCURVE_S2");
516 assert_eq!(
517 SurfaceCurve::new(EntityId(1), &by_s2)
518 .master_curve_ref()
519 .unwrap(),
520 EntityId(61)
521 );
522 }
523
524 #[test]
525 fn naming_a_pcurve_the_file_does_not_have_fails_instead_of_indexing_out_of_bounds() {
526 let e = surface_curve("IFCSURFACECURVE", &[60], "PCURVE_S2");
527 let err = SurfaceCurve::new(EntityId(3), &e)
528 .master_curve_ref()
529 .unwrap_err();
530 assert!(err.to_string().contains("#3"), "got: {err}");
531 }
532
533 #[test]
534 fn an_absent_master_representation_defaults_to_the_3d_curve() {
535 let e = Entity::new(
536 "IFCSURFACECURVE",
537 vec![
538 Value::Ref(EntityId(40)),
539 Value::List(vec![Value::Ref(EntityId(60))]),
540 ],
541 );
542 assert_eq!(
543 SurfaceCurve::new(EntityId(1), &e).master_representation(),
544 PreferredSurfaceCurveRepresentation::Curve3D
545 );
546 }
547
548 #[test]
551 fn intersection_and_seam_curves_require_exactly_two_pcurves() {
552 for type_name in ["IFCINTERSECTIONCURVE", "IFCSEAMCURVE"] {
553 let e = surface_curve(type_name, &[60], "CURVE3D");
554 let err = SurfaceCurve::new(EntityId(1), &e)
555 .associated_pcurve_refs()
556 .unwrap_err();
557 assert!(err.to_string().contains("exactly 2"), "{type_name}: {err}");
558 }
559 let plain = surface_curve("IFCSURFACECURVE", &[60], "CURVE3D");
561 assert_eq!(
562 SurfaceCurve::new(EntityId(1), &plain)
563 .associated_pcurve_refs()
564 .unwrap()
565 .len(),
566 1
567 );
568 }
569
570 #[test]
571 fn surface_curve_subtypes_are_classified_from_the_type_name() {
572 for (type_name, expected) in [
573 ("IFCSURFACECURVE", SurfaceCurveKind::Plain),
574 ("IFCINTERSECTIONCURVE", SurfaceCurveKind::Intersection),
575 ("IFCSEAMCURVE", SurfaceCurveKind::Seam),
576 ] {
577 let e = surface_curve(type_name, &[60, 61], "CURVE3D");
578 assert_eq!(SurfaceCurve::new(EntityId(1), &e).kind(), Some(expected));
579 }
580 let other = surface_curve("IFCPOLYLINE", &[60], "CURVE3D");
581 assert_eq!(SurfaceCurve::new(EntityId(1), &other).kind(), None);
582 }
583
584 #[test]
585 fn preferred_representation_tokens_map_to_list_positions() {
586 assert_eq!(
587 PreferredSurfaceCurveRepresentation::Curve3D.pcurve_index(),
588 None
589 );
590 assert_eq!(
591 PreferredSurfaceCurveRepresentation::PCurveS1.pcurve_index(),
592 Some(0)
593 );
594 assert_eq!(
595 PreferredSurfaceCurveRepresentation::PCurveS2.pcurve_index(),
596 Some(1)
597 );
598 assert_eq!(
599 PreferredSurfaceCurveRepresentation::from_token("NOPE"),
600 None
601 );
602 }
603}