1use crate::cant::segment::{CantSegment, CantSegmentType};
40use crate::curve::SeamTolerance;
41use crate::error::{AlignmentError, AlignmentResult};
42
43pub(crate) const MOVING_VIENNESE_PIVOT: &str =
47 "the section's rotation point moves through a Viennese bend and neither rail is held: \
48 IFC4.3 states the bend for the section's cant angle only, so the rail heights are not \
49 determined";
50
51#[derive(Debug, Clone, Copy, PartialEq)]
53pub(crate) enum VienneseRotation {
54 FixedPivot(f64),
56 HeldLeft(f64),
58 HeldRight(f64),
60}
61
62pub(crate) fn viennese_rotation(
67 entity: ifc_model::EntityId,
68 left: [f64; 2],
69 right: [f64; 2],
70 tolerance: SeamTolerance,
71) -> AlignmentResult<VienneseRotation> {
72 let pivot = 0.5 * (left[0] + right[0]);
73 if tolerance.same_length(pivot, 0.5 * (left[1] + right[1])) {
74 Ok(VienneseRotation::FixedPivot(pivot))
75 } else if tolerance.same_length(left[0], left[1]) {
76 Ok(VienneseRotation::HeldLeft(left[0]))
77 } else if tolerance.same_length(right[0], right[1]) {
78 Ok(VienneseRotation::HeldRight(right[0]))
79 } else {
80 Err(AlignmentError::Unsupported {
81 entity,
82 type_name: "VIENNESEBEND".to_owned(),
83 detail: MOVING_VIENNESE_PIVOT,
84 })
85 }
86}
87
88#[derive(Debug, Clone, Copy, PartialEq)]
90#[non_exhaustive]
91pub struct CantAtStation {
92 pub left: f64,
94 pub right: f64,
96}
97
98pub fn cant_at(
128 segment: &CantSegment,
129 xi: f64,
130 rail_head_distance: Option<f64>,
131) -> AlignmentResult<CantAtStation> {
132 cant_within(segment, xi, rail_head_distance, SeamTolerance::strict())
133}
134
135pub(crate) fn cant_within(
137 segment: &CantSegment,
138 xi: f64,
139 rail_head_distance: Option<f64>,
140 tolerance: SeamTolerance,
141) -> AlignmentResult<CantAtStation> {
142 if !(0.0..=1.0).contains(&xi) || !xi.is_finite() {
143 return Err(AlignmentError::InvalidSegment {
144 entity: segment.entity,
145 detail: "normalized position must lie in [0.0, 1.0]",
146 });
147 }
148
149 match &segment.predefined_type {
150 CantSegmentType::ConstantCant => {
151 if segment
152 .end_cant_left
153 .is_some_and(|end| end != segment.start_cant_left)
154 || segment
155 .end_cant_right
156 .is_some_and(|end| end != segment.start_cant_right)
157 {
158 return Err(AlignmentError::InvalidSegment {
159 entity: segment.entity,
160 detail: "CONSTANTCANT requires equal (or absent) start and end cant",
161 });
162 }
163 Ok(CantAtStation {
164 left: segment.start_cant_left,
165 right: segment.start_cant_right,
166 })
167 }
168 CantSegmentType::VienneseBend => {
169 let b = rail_head_distance.ok_or(AlignmentError::InvalidSegment {
170 entity: segment.entity,
171 detail: "VIENNESEBEND requires the parent IfcAlignmentCant.RailHeadDistance",
172 })?;
173 if !(b.is_finite() && b > 0.0) {
174 return Err(AlignmentError::InvalidUnits {
175 detail: "RailHeadDistance must be finite and positive",
176 });
177 }
178 vienna_bend(segment, xi, b, tolerance)
179 }
180 other => {
181 let fraction =
182 shape_fraction(other, xi).ok_or_else(|| AlignmentError::Unsupported {
183 entity: segment.entity,
184 type_name: segment.predefined_type_name().to_owned(),
185 detail: "cant PredefinedType has no defined base formula",
186 })?;
187 let (end_left, end_right) = required_ends(segment)?;
188 Ok(CantAtStation {
189 left: segment.start_cant_left + fraction * (end_left - segment.start_cant_left),
190 right: segment.start_cant_right + fraction * (end_right - segment.start_cant_right),
191 })
192 }
193 }
194}
195
196fn required_ends(segment: &CantSegment) -> AlignmentResult<(f64, f64)> {
197 match (segment.end_cant_left, segment.end_cant_right) {
198 (Some(left), Some(right)) => Ok((left, right)),
199 _ => Err(AlignmentError::InvalidSegment {
200 entity: segment.entity,
201 detail: "transition cant segments require both end cant values",
202 }),
203 }
204}
205
206fn shape_fraction(kind: &CantSegmentType, xi: f64) -> Option<f64> {
209 match kind {
210 CantSegmentType::LinearTransition => Some(xi),
211 CantSegmentType::BlossCurve => Some((3.0 - 2.0 * xi) * xi * xi),
212 CantSegmentType::CosineCurve => Some(0.5 * (1.0 - (std::f64::consts::PI * xi).cos())),
213 CantSegmentType::SineCurve => Some(
214 xi - (2.0 * std::f64::consts::PI).recip() * (2.0 * std::f64::consts::PI * xi).sin(),
215 ),
216 CantSegmentType::HelmertCurve => Some(if xi <= 0.5 {
217 2.0 * xi * xi
218 } else {
219 1.0 - 2.0 * (1.0 - xi) * (1.0 - xi)
220 }),
221 _ => None,
222 }
223}
224
225fn vienna_bend(
230 segment: &CantSegment,
231 xi: f64,
232 b: f64,
233 tolerance: SeamTolerance,
234) -> AlignmentResult<CantAtStation> {
235 let (end_left, end_right) = required_ends(segment)?;
236 let start = CantAtStation {
237 left: segment.start_cant_left,
238 right: segment.start_cant_right,
239 };
240 let end = CantAtStation {
241 left: end_left,
242 right: end_right,
243 };
244 let ratio = |at: &CantAtStation| (at.left - at.right) / b;
245 let (ratio_start, ratio_end) = (ratio(&start), ratio(&end));
246 if !(-1.0..=1.0).contains(&ratio_start) || !(-1.0..=1.0).contains(&ratio_end) {
247 return Err(AlignmentError::InvalidSegment {
248 entity: segment.entity,
249 detail: "VIENNESEBEND cant exceeds the rail head distance (|D| > b)",
250 });
251 }
252 if xi == 0.0 {
254 return Ok(start);
255 }
256 if xi == 1.0 {
257 return Ok(end);
258 }
259 let rotation = viennese_rotation(
260 segment.entity,
261 [start.left, end.left],
262 [start.right, end.right],
263 tolerance,
264 )?;
265 let psi_start = ratio_start.asin();
266 let delta_psi = ratio_end.asin() - psi_start;
267 let blend = xi.powi(4) * (35.0 - 84.0 * xi + 70.0 * xi * xi - 20.0 * xi * xi * xi);
268 let sin_psi = (psi_start + delta_psi * blend).sin();
269 Ok(match rotation {
270 VienneseRotation::FixedPivot(pivot) => {
271 let half = 0.5 * b * sin_psi;
272 CantAtStation {
273 left: pivot + half,
274 right: pivot - half,
275 }
276 }
277 VienneseRotation::HeldLeft(held) => CantAtStation {
278 left: held,
279 right: held - b * sin_psi,
280 },
281 VienneseRotation::HeldRight(held) => CantAtStation {
282 left: held + b * sin_psi,
283 right: held,
284 },
285 })
286}
287
288#[cfg(test)]
289mod tests {
290 use super::*;
291 use ifc_model::EntityId;
292
293 fn segment(
294 predefined_type: CantSegmentType,
295 start_left: f64,
296 end_left: Option<f64>,
297 start_right: f64,
298 end_right: Option<f64>,
299 ) -> CantSegment {
300 CantSegment {
301 entity: EntityId(1),
302 start_dist_along: 0.0,
303 horizontal_length: 100.0,
304 start_cant_left: start_left,
305 end_cant_left: end_left,
306 start_cant_right: start_right,
307 end_cant_right: end_right,
308 predefined_type,
309 }
310 }
311
312 #[test]
313 fn constant_cant_holds_its_value_across_the_whole_segment() {
314 let s = segment(CantSegmentType::ConstantCant, 0.15, None, -0.15, None);
315 for xi in [0.0, 0.25, 0.5, 1.0] {
316 let at = cant_at(&s, xi, None).expect("constant cant");
317 assert_eq!(
318 at,
319 CantAtStation {
320 left: 0.15,
321 right: -0.15
322 }
323 );
324 }
325 }
326
327 #[test]
328 fn constant_cant_refuses_a_declared_end_that_disagrees_with_the_start() {
329 let s = segment(CantSegmentType::ConstantCant, 0.15, Some(0.20), -0.15, None);
330 assert!(cant_at(&s, 0.5, None).is_err());
331 }
332
333 #[test]
334 fn linear_transition_interpolates_exactly() {
335 let s = segment(
336 CantSegmentType::LinearTransition,
337 0.0,
338 Some(0.20),
339 0.0,
340 Some(-0.20),
341 );
342 let at = cant_at(&s, 0.25, None).expect("linear cant");
343 assert!((at.left - 0.05).abs() < 1e-12);
344 assert!((at.right - (-0.05)).abs() < 1e-12);
345 }
346
347 #[test]
348 fn bloss_curve_matches_the_published_base_formula_at_the_quarter_point() {
349 let s = segment(CantSegmentType::BlossCurve, 0.0, Some(1.0), 0.0, Some(1.0));
350 let at = cant_at(&s, 0.25, None).expect("bloss cant");
352 assert!((at.left - 0.15625).abs() < 1e-12);
353 }
354
355 #[test]
356 fn bloss_curve_is_symmetric_boundary_exact() {
357 let s = segment(CantSegmentType::BlossCurve, 0.0, Some(1.0), 0.0, Some(1.0));
358 assert!((cant_at(&s, 0.0, None).unwrap().left - 0.0).abs() < 1e-12);
359 assert!((cant_at(&s, 1.0, None).unwrap().left - 1.0).abs() < 1e-12);
360 }
361
362 #[test]
363 fn cosine_curve_matches_the_published_base_formula_at_the_midpoint() {
364 let s = segment(CantSegmentType::CosineCurve, 0.0, Some(1.0), 0.0, Some(1.0));
365 let at = cant_at(&s, 0.5, None).expect("cosine cant");
367 assert!((at.left - 0.5).abs() < 1e-9);
368 }
369
370 #[test]
371 fn sine_curve_starts_and_ends_exactly_on_the_endpoints() {
372 let s = segment(CantSegmentType::SineCurve, 0.0, Some(1.0), 0.0, Some(1.0));
373 assert!((cant_at(&s, 0.0, None).unwrap().left - 0.0).abs() < 1e-12);
374 assert!((cant_at(&s, 1.0, None).unwrap().left - 1.0).abs() < 1e-9);
375 }
376
377 #[test]
378 fn helmert_curve_is_continuous_across_its_own_midpoint_seam() {
379 let s = segment(
380 CantSegmentType::HelmertCurve,
381 0.0,
382 Some(1.0),
383 0.0,
384 Some(1.0),
385 );
386 let just_below = cant_at(&s, 0.5 - 1e-9, None).unwrap().left;
387 let at_mid = cant_at(&s, 0.5, None).unwrap().left;
388 let just_above = cant_at(&s, 0.5 + 1e-9, None).unwrap().left;
389 assert!((just_below - at_mid).abs() < 1e-6);
390 assert!((just_above - at_mid).abs() < 1e-6);
391 }
392
393 #[test]
394 fn transitions_refuse_a_missing_end_value() {
395 let s = segment(CantSegmentType::LinearTransition, 0.0, None, 0.0, None);
396 assert!(cant_at(&s, 0.5, None).is_err());
397 }
398
399 #[test]
400 fn vienna_bend_reproduces_the_endpoints_exactly() {
401 let s = segment(
402 CantSegmentType::VienneseBend,
403 0.0,
404 Some(0.15),
405 0.0,
406 Some(-0.15),
407 );
408 let start = cant_at(&s, 0.0, Some(1.5)).expect("vienna bend start");
409 let end = cant_at(&s, 1.0, Some(1.5)).expect("vienna bend end");
410 assert!((start.left - 0.0).abs() < 1e-9);
411 assert!((end.left - 0.15).abs() < 1e-9);
412 assert!((start.right - 0.0).abs() < 1e-9);
413 assert!((end.right - (-0.15)).abs() < 1e-9);
414 }
415
416 #[test]
421 fn vienna_bend_blends_the_sections_cant_angle_not_each_rail() {
422 let s = segment(
423 CantSegmentType::VienneseBend,
424 0.0,
425 Some(0.075),
426 0.0,
427 Some(-0.075),
428 );
429 let at = cant_at(&s, 0.5, Some(1.5)).expect("vienna bend");
430 let cant = at.left - at.right;
431 let standard = 1.5 * (0.5 * 0.1_f64.asin()).sin();
432 assert!((cant - standard).abs() < 1e-15, "{cant} != {standard}");
433 assert!((cant - 0.075_094_2).abs() < 5e-8, "{cant}");
434 let per_rail = 2.0 * 1.5 * (0.5 * 0.05_f64.asin()).sin();
435 assert!((per_rail - 0.075_023_5).abs() < 5e-8, "{per_rail}");
436 assert!((cant - per_rail).abs() > 7e-5, "the per-rail reading");
437 assert!((at.left + at.right).abs() < 1e-15);
439 }
440
441 #[test]
444 fn vienna_bend_places_the_rails_about_a_pivot_that_stays_put() {
445 let s = segment(
446 CantSegmentType::VienneseBend,
447 0.05,
448 Some(0.125),
449 0.05,
450 Some(-0.025),
451 );
452 let psi2 = (0.15_f64 / 1.5).asin();
453 for xi in [0.1_f64, 0.25, 0.5, 0.75, 0.9] {
454 let blend = xi.powi(4) * (35.0 - 84.0 * xi + 70.0 * xi * xi - 20.0 * xi.powi(3));
455 let d = 1.5 * (psi2 * blend).sin();
456 let at = cant_at(&s, xi, Some(1.5)).expect("vienna bend");
457 assert!((at.left - (0.05 + d / 2.0)).abs() < 1e-15, "left at {xi}");
458 assert!((at.right - (0.05 - d / 2.0)).abs() < 1e-15, "right at {xi}");
459 }
460 }
461
462 #[test]
469 fn vienna_bend_rotates_about_a_held_low_rail() {
470 let s = segment(
471 CantSegmentType::VienneseBend,
472 0.0,
473 Some(0.15),
474 0.0,
475 Some(0.0),
476 );
477 for (xi, left) in [
478 (0.25, 0.010_601_126_852_313_474),
479 (0.5, 0.075_094_162_589_728_31),
480 (0.75, 0.139_448_265_786_310_37),
481 ] {
482 let at = cant_at(&s, xi, Some(1.5)).expect("held low rail");
483 assert_eq!(at.right, 0.0, "the held rail stays at {xi}");
484 assert!((at.left - left).abs() < 1e-15, "left at {xi}: {}", at.left);
485 }
486 let mid = cant_at(&s, 0.5, Some(1.5)).expect("mid");
489 assert!((mid.left - 1.5 * (0.5 * 0.1_f64.asin()).sin()).abs() < 1e-15);
490 let start = cant_at(&s, 0.0, Some(1.5)).expect("authored start");
492 let end = cant_at(&s, 1.0, Some(1.5)).expect("authored end");
493 assert_eq!(
494 (start.left, start.right, end.left, end.right),
495 (0.0, 0.0, 0.15, 0.0)
496 );
497 let near_start = cant_at(&s, 1e-6, Some(1.5)).expect("near start");
499 let near_end = cant_at(&s, 1.0 - 1e-6, Some(1.5)).expect("near end");
500 assert!(near_start.left.abs() < 1e-12 && near_start.right == 0.0);
501 assert!((near_end.left - 0.15).abs() < 1e-12 && near_end.right == 0.0);
502 }
503
504 #[test]
507 fn vienna_bend_rotates_about_a_held_left_rail() {
508 let s = segment(
509 CantSegmentType::VienneseBend,
510 0.1,
511 Some(0.1),
512 0.1,
513 Some(0.25),
514 );
515 let psi2 = (-0.15_f64 / 1.5).asin();
516 for xi in [0.1_f64, 0.25, 0.5, 0.75, 0.9] {
517 let blend = xi.powi(4) * (35.0 - 84.0 * xi + 70.0 * xi * xi - 20.0 * xi.powi(3));
518 let d = 1.5 * (psi2 * blend).sin();
519 let at = cant_at(&s, xi, Some(1.5)).expect("held left rail");
520 assert_eq!(at.left, 0.1, "the held rail stays at {xi}");
521 assert!((at.right - (0.1 - d)).abs() < 1e-15, "right at {xi}");
522 }
523 let end = cant_at(&s, 1.0, Some(1.5)).expect("authored end");
524 assert_eq!((end.left, end.right), (0.1, 0.25));
525 }
526
527 #[test]
531 fn vienna_bend_refuses_a_moving_pivot_without_a_held_rail() {
532 let s = segment(
533 CantSegmentType::VienneseBend,
534 0.0,
535 Some(0.15),
536 0.02,
537 Some(-0.01),
538 );
539 for xi in [1e-9_f64, 0.5, 1.0 - 1e-9] {
540 assert_eq!(
541 cant_at(&s, xi, Some(1.5)),
542 Err(AlignmentError::Unsupported {
543 entity: EntityId(1),
544 type_name: "VIENNESEBEND".to_owned(),
545 detail: MOVING_VIENNESE_PIVOT,
546 }),
547 "at {xi}"
548 );
549 }
550 let start = cant_at(&s, 0.0, Some(1.5)).expect("authored start");
551 let end = cant_at(&s, 1.0, Some(1.5)).expect("authored end");
552 assert_eq!(
553 (start.left, start.right, end.left, end.right),
554 (0.0, 0.02, 0.15, -0.01)
555 );
556 }
557
558 #[test]
561 fn vienna_bend_compares_held_rails_at_the_given_tolerance() {
562 let s = segment(
563 CantSegmentType::VienneseBend,
564 0.0,
565 Some(0.15),
566 0.0,
567 Some(0.000_002),
568 );
569 assert!(matches!(
570 cant_at(&s, 0.5, Some(1.5)),
571 Err(AlignmentError::Unsupported { .. })
572 ));
573 let precise = SeamTolerance::from_precision(1e-5).expect("precision");
574 let at = cant_within(&s, 0.5, Some(1.5), precise).expect("rail held within precision");
575 assert_eq!(at.right, 0.0, "the start height holds");
576 }
577
578 #[test]
581 fn vienna_bend_compares_pivots_at_the_given_tolerance() {
582 let s = segment(
583 CantSegmentType::VienneseBend,
584 0.0,
585 Some(0.075_002),
586 0.0,
587 Some(-0.075),
588 );
589 assert!(matches!(
590 cant_at(&s, 0.5, Some(1.5)),
591 Err(AlignmentError::Unsupported { .. })
592 ));
593 let precise = SeamTolerance::from_precision(1e-5).expect("precision");
594 let at = cant_within(&s, 0.5, Some(1.5), precise).expect("pivot within precision");
595 assert!((at.left + at.right).abs() < 1e-15, "the start pivot holds");
596 }
597
598 #[test]
599 fn vienna_bend_refuses_without_a_rail_head_distance() {
600 let s = segment(
601 CantSegmentType::VienneseBend,
602 0.0,
603 Some(0.15),
604 0.0,
605 Some(-0.15),
606 );
607 assert!(cant_at(&s, 0.5, None).is_err());
608 }
609
610 #[test]
611 fn vienna_bend_refuses_cant_exceeding_the_rail_head_distance() {
612 let s = segment(
613 CantSegmentType::VienneseBend,
614 0.0,
615 Some(2.0),
616 0.0,
617 Some(-0.15),
618 );
619 assert!(cant_at(&s, 0.5, Some(1.5)).is_err());
620 }
621
622 #[test]
623 fn user_defined_predefined_type_is_a_typed_refusal_not_a_guess() {
624 let s = segment(CantSegmentType::UserDefined, 0.0, Some(1.0), 0.0, Some(1.0));
625 assert!(matches!(
626 cant_at(&s, 0.5, None),
627 Err(AlignmentError::Unsupported { .. })
628 ));
629 }
630}