openscenario-rs 0.3.0

Rust library for parsing and manipulating OpenSCENARIO files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
//! Trajectory action builders for path-following scenarios
//!
//! This module provides builders for creating trajectory-based actions, including
//! trajectory definitions with polyline shapes and follow trajectory actions.
//!
//! # Available Builders
//!
//! - [`TrajectoryBuilder`] - Build trajectory definitions with polyline shapes
//! - [`PolylineBuilder`] - Build polyline shapes with time-positioned vertices
//! - [`VertexBuilder`] - Build individual trajectory vertices
//! - [`FollowTrajectoryActionBuilder`] - Build follow trajectory actions
//!
//! # Usage Examples
//!
//! Trajectory actions are used within maneuver builders.
//! For detailed usage examples, see the storyboard module documentation.
//! ```
//! //
use crate::builder::actions::base::{ActionBuilder, ManeuverAction};
use crate::builder::{BuilderError, BuilderResult};
use crate::types::{
    actions::movement::{
        FollowTrajectoryAction, RoutingAction, TimeReference, Timing, Trajectory,
        TrajectoryFollowingMode,
    },
    actions::wrappers::PrivateAction,
    basic::{Boolean, Double, OSString},
    enums::FollowingMode,
    geometry::shapes::{Polyline, Shape, Vertex},
    positions::{world::WorldPosition, Position},
};

/// Builder for trajectory definitions
///
/// Creates trajectories with polyline shapes and multiple vertices.
/// Trajectories define paths that entities can follow in a scenario.
///
/// # Example
///
/// See storyboard module for usage examples.
///
#[derive(Debug, Default)]
pub struct TrajectoryBuilder {
    name: Option<String>,
    closed: bool,
    shape: Option<Shape>,
}

impl TrajectoryBuilder {
    /// Create a new trajectory builder
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the trajectory name
    pub fn name(mut self, name: &str) -> Self {
        self.name = Some(name.to_string());
        self
    }

    /// Set whether the trajectory is closed (forms a loop)
    pub fn closed(mut self, closed: bool) -> Self {
        self.closed = closed;
        self
    }

    /// Start building a polyline shape
    pub fn polyline(self) -> PolylineBuilder {
        PolylineBuilder::new(self)
    }

    /// Build the trajectory
    pub fn build(self) -> BuilderResult<Trajectory> {
        self.validate()?;

        Ok(Trajectory {
            name: OSString::literal(self.name.unwrap()),
            closed: Boolean::literal(self.closed),
            shape: self.shape.unwrap(),
        })
    }

    fn validate(&self) -> BuilderResult<()> {
        if self.name.is_none() {
            return Err(BuilderError::validation_error(
                "Trajectory name is required",
            ));
        }
        if self.shape.is_none() {
            return Err(BuilderError::validation_error(
                "Trajectory shape is required (use .polyline())",
            ));
        }
        Ok(())
    }
}

/// Builder for polyline shapes
///
/// Creates polyline shapes with multiple vertices. Each vertex has a time
/// and position along the trajectory.
///
/// # Example
///
/// See above for TrajectoryBuilder usage.
///
///
#[derive(Debug)]
pub struct PolylineBuilder {
    parent: TrajectoryBuilder,
    vertices: Vec<Vertex>,
}

impl PolylineBuilder {
    fn new(parent: TrajectoryBuilder) -> Self {
        Self {
            parent,
            vertices: Vec::new(),
        }
    }

    /// Add a vertex to the polyline
    pub fn add_vertex(self) -> VertexBuilder {
        VertexBuilder::new(self)
    }

    /// Finish building the polyline and return to trajectory builder
    pub fn finish(mut self) -> TrajectoryBuilder {
        let polyline = Polyline {
            vertices: self.vertices,
        };
        self.parent.shape = Some(Shape {
            polyline: Some(polyline),
        });
        self.parent
    }

    fn add_vertex_internal(&mut self, vertex: Vertex) {
        self.vertices.push(vertex);
    }
}

/// Builder for trajectory vertices
///
/// Creates individual vertices with time and position information.
/// Vertices must be added in chronological order (increasing time values).
///
/// # Example
///
/// See above for TrajectoryBuilder usage.
///
///
#[derive(Debug)]
pub struct VertexBuilder {
    parent: PolylineBuilder,
    time: Option<f64>,
    position: Option<Position>,
}

impl VertexBuilder {
    fn new(parent: PolylineBuilder) -> Self {
        Self {
            parent,
            time: None,
            position: None,
        }
    }

    /// Set the time at this vertex (in seconds)
    pub fn time(mut self, time: f64) -> Self {
        self.time = Some(time);
        self
    }

    /// Set position using an existing Position object
    pub fn position(mut self, position: Position) -> Self {
        self.position = Some(position);
        self
    }

    /// Set position using world coordinates
    ///
    /// # Arguments
    /// * `x` - X coordinate in world frame
    /// * `y` - Y coordinate in world frame
    /// * `z` - Z coordinate (elevation)
    /// * `h` - Heading angle in radians
    pub fn world_position(mut self, x: f64, y: f64, z: f64, h: f64) -> Self {
        let world_pos = WorldPosition {
            x: Double::literal(x),
            y: Double::literal(y),
            z: Some(Double::literal(z)),
            h: Some(Double::literal(h)),
            p: None,
            r: None,
        };
        self.position = Some(Position {
            world_position: Some(world_pos),
            relative_world_position: None,
            road_position: None,
            relative_road_position: None,
            lane_position: None,
            relative_lane_position: None,
            trajectory_position: None,
            geographic_position: None,
            relative_object_position: None,
        });
        self
    }

    /// Finish building the vertex and return to polyline builder
    pub fn finish(mut self) -> BuilderResult<PolylineBuilder> {
        self.validate()?;

        let vertex = Vertex {
            time: Double::literal(self.time.unwrap()),
            position: self.position.unwrap(),
        };

        self.parent.add_vertex_internal(vertex);
        Ok(self.parent)
    }

    fn validate(&self) -> BuilderResult<()> {
        if self.time.is_none() {
            return Err(BuilderError::validation_error("Vertex time is required"));
        }
        if self.position.is_none() {
            return Err(BuilderError::validation_error(
                "Vertex position is required",
            ));
        }
        Ok(())
    }
}

/// Builder for follow trajectory actions
///
/// Creates actions that make entities follow predefined trajectories.
/// Requires a trajectory definition and following mode.
///
/// # Example
///
/// See above for TrajectoryBuilder usage.
///
///
#[derive(Debug, Default)]
pub struct FollowTrajectoryActionBuilder {
    entity_ref: Option<String>,
    trajectory: Option<Trajectory>,
    following_mode: Option<FollowingMode>,
    initial_distance_offset: Option<f64>,
}

impl FollowTrajectoryActionBuilder {
    /// Create a new follow trajectory action builder
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the entity that will follow the trajectory
    pub fn for_entity(mut self, entity_ref: &str) -> Self {
        self.entity_ref = Some(entity_ref.to_string());
        self
    }

    /// Set the trajectory to follow
    pub fn with_trajectory(mut self, trajectory: Trajectory) -> Self {
        self.trajectory = Some(trajectory);
        self
    }

    /// Set following mode to "follow" (entity follows trajectory timing)
    pub fn following_mode_follow(mut self) -> Self {
        self.following_mode = Some(FollowingMode::Follow);
        self
    }

    /// Set following mode to "position" (entity reaches positions at specified times)
    pub fn following_mode_position(mut self) -> Self {
        self.following_mode = Some(FollowingMode::Position);
        self
    }

    /// Set initial distance offset along trajectory (in meters)
    pub fn initial_distance_offset(mut self, offset: f64) -> Self {
        self.initial_distance_offset = Some(offset);
        self
    }
}

impl ActionBuilder for FollowTrajectoryActionBuilder {
    fn build_action(self) -> BuilderResult<PrivateAction> {
        self.validate()?;

        let follow_trajectory_action = FollowTrajectoryAction {
            trajectory: self.trajectory,
            catalog_reference: None,
            time_reference: TimeReference {
                timing: Timing {
                    domain_absolute_relative: OSString::literal("absolute".to_string()),
                    scale: Double::literal(1.0),
                    offset: Double::literal(0.0),
                },
            },
            trajectory_ref: None,
            trajectory_following_mode: TrajectoryFollowingMode {
                following_mode: self.following_mode.unwrap(),
            },
            initial_distance_offset: self.initial_distance_offset.map(|v| Double::literal(v)),
        };

        Ok(PrivateAction::RoutingAction(RoutingAction {
            assign_route_action: None,
            follow_trajectory_action: Some(follow_trajectory_action),
            follow_route_action: None,
        }))
    }

    fn validate(&self) -> BuilderResult<()> {
        if self.trajectory.is_none() {
            return Err(BuilderError::validation_error(
                "Trajectory is required for follow trajectory action",
            ));
        }
        if self.following_mode.is_none() {
            return Err(BuilderError::validation_error(
                "Following mode is required (use .following_mode_follow() or .following_mode_position())",
            ));
        }
        Ok(())
    }
}

impl ManeuverAction for FollowTrajectoryActionBuilder {
    fn entity_ref(&self) -> Option<&str> {
        self.entity_ref.as_deref()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_trajectory_builder_basic() {
        let trajectory = TrajectoryBuilder::new()
            .name("test_trajectory")
            .closed(false)
            .polyline()
            .add_vertex()
            .time(0.0)
            .world_position(0.0, 0.0, 0.0, 0.0)
            .finish()
            .unwrap()
            .add_vertex()
            .time(1.0)
            .world_position(10.0, 0.0, 0.0, 0.0)
            .finish()
            .unwrap()
            .finish()
            .build()
            .unwrap();

        assert_eq!(
            trajectory.name.as_literal(),
            Some(&"test_trajectory".to_string())
        );
        assert_eq!(trajectory.closed.as_literal(), Some(&false));
        assert!(trajectory.shape.polyline.is_some());
        assert_eq!(
            trajectory.shape.polyline.as_ref().unwrap().vertices.len(),
            2
        );
    }

    #[test]
    fn test_trajectory_builder_closed() {
        let trajectory = TrajectoryBuilder::new()
            .name("loop_path")
            .closed(true)
            .polyline()
            .add_vertex()
            .time(0.0)
            .world_position(0.0, 0.0, 0.0, 0.0)
            .finish()
            .unwrap()
            .finish()
            .build()
            .unwrap();

        assert_eq!(trajectory.closed.as_literal(), Some(&true));
    }

    #[test]
    fn test_trajectory_validation_fails_without_name() {
        let result = TrajectoryBuilder::new()
            .polyline()
            .add_vertex()
            .time(0.0)
            .world_position(0.0, 0.0, 0.0, 0.0)
            .finish()
            .unwrap()
            .finish()
            .build();

        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Trajectory name is required"));
    }

    #[test]
    fn test_trajectory_validation_fails_without_shape() {
        let result = TrajectoryBuilder {
            name: Some("test".to_string()),
            closed: false,
            shape: None,
        }
        .build();

        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Trajectory shape is required"));
    }

    #[test]
    fn test_vertex_builder() {
        let trajectory = TrajectoryBuilder::new()
            .name("multi_vertex")
            .polyline()
            .add_vertex()
            .time(0.0)
            .world_position(0.0, 0.0, 0.0, 0.0)
            .finish()
            .unwrap()
            .add_vertex()
            .time(1.0)
            .world_position(10.0, 5.0, 0.0, 0.5)
            .finish()
            .unwrap()
            .add_vertex()
            .time(2.0)
            .world_position(20.0, 10.0, 0.0, 1.0)
            .finish()
            .unwrap()
            .finish()
            .build()
            .unwrap();

        let vertices = &trajectory.shape.polyline.as_ref().unwrap().vertices;
        assert_eq!(vertices.len(), 3);

        // Check first vertex
        assert_eq!(vertices[0].time.as_literal(), Some(&0.0));
        if let Some(ref pos) = vertices[0].position.world_position {
            assert_eq!(pos.x.as_literal(), Some(&0.0));
            assert_eq!(pos.y.as_literal(), Some(&0.0));
        } else {
            panic!("Expected WorldPosition");
        }

        // Check last vertex
        assert_eq!(vertices[2].time.as_literal(), Some(&2.0));
        if let Some(ref pos) = vertices[2].position.world_position {
            assert_eq!(pos.x.as_literal(), Some(&20.0));
            assert_eq!(pos.y.as_literal(), Some(&10.0));
        } else {
            panic!("Expected WorldPosition");
        }
    }

    #[test]
    fn test_vertex_validation_fails_without_time() {
        let result = TrajectoryBuilder::new()
            .name("test")
            .polyline()
            .add_vertex()
            .world_position(0.0, 0.0, 0.0, 0.0)
            .finish();

        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Vertex time is required"));
    }

    #[test]
    fn test_vertex_validation_fails_without_position() {
        let result = TrajectoryBuilder::new()
            .name("test")
            .polyline()
            .add_vertex()
            .time(0.0)
            .finish();

        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Vertex position is required"));
    }

    #[test]
    fn test_follow_trajectory_action_builder() {
        let trajectory = TrajectoryBuilder::new()
            .name("action_test_path")
            .closed(false)
            .polyline()
            .add_vertex()
            .time(0.0)
            .world_position(0.0, 0.0, 0.0, 0.0)
            .finish()
            .unwrap()
            .add_vertex()
            .time(5.0)
            .world_position(50.0, 0.0, 0.0, 0.0)
            .finish()
            .unwrap()
            .finish()
            .build()
            .unwrap();

        let action = FollowTrajectoryActionBuilder::new()
            .for_entity("ego")
            .with_trajectory(trajectory)
            .following_mode_follow()
            .build_action()
            .unwrap();

        // Verify action structure
        match action {
            PrivateAction::RoutingAction(ref routing) => {
                assert!(routing.follow_trajectory_action.is_some());
                let follow_action = routing.follow_trajectory_action.as_ref().unwrap();
                assert!(follow_action.trajectory.is_some());
                assert_eq!(
                    follow_action.trajectory_following_mode.following_mode,
                    FollowingMode::Follow
                );
            }
            _ => panic!("Expected RoutingAction"),
        }
    }

    #[test]
    fn test_follow_trajectory_action_with_position_mode() {
        let trajectory = TrajectoryBuilder::new()
            .name("position_mode_path")
            .polyline()
            .add_vertex()
            .time(0.0)
            .world_position(0.0, 0.0, 0.0, 0.0)
            .finish()
            .unwrap()
            .finish()
            .build()
            .unwrap();

        let action = FollowTrajectoryActionBuilder::new()
            .with_trajectory(trajectory)
            .following_mode_position()
            .build_action()
            .unwrap();

        match action {
            PrivateAction::RoutingAction(ref routing) => {
                let follow_action = routing.follow_trajectory_action.as_ref().unwrap();
                assert_eq!(
                    follow_action.trajectory_following_mode.following_mode,
                    FollowingMode::Position
                );
            }
            _ => panic!("Expected RoutingAction"),
        }
    }

    #[test]
    fn test_follow_trajectory_action_with_offset() {
        let trajectory = TrajectoryBuilder::new()
            .name("offset_path")
            .polyline()
            .add_vertex()
            .time(0.0)
            .world_position(0.0, 0.0, 0.0, 0.0)
            .finish()
            .unwrap()
            .finish()
            .build()
            .unwrap();

        let action = FollowTrajectoryActionBuilder::new()
            .with_trajectory(trajectory)
            .following_mode_follow()
            .initial_distance_offset(10.0)
            .build_action()
            .unwrap();

        match action {
            PrivateAction::RoutingAction(ref routing) => {
                let follow_action = routing.follow_trajectory_action.as_ref().unwrap();
                assert_eq!(
                    follow_action
                        .initial_distance_offset
                        .as_ref()
                        .unwrap()
                        .as_literal(),
                    Some(&10.0)
                );
            }
            _ => panic!("Expected RoutingAction"),
        }
    }

    #[test]
    fn test_follow_trajectory_validation_fails_without_trajectory() {
        let result = FollowTrajectoryActionBuilder::new()
            .following_mode_follow()
            .build_action();

        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Trajectory is required"));
    }

    #[test]
    fn test_follow_trajectory_validation_fails_without_mode() {
        let trajectory = TrajectoryBuilder::new()
            .name("test")
            .polyline()
            .add_vertex()
            .time(0.0)
            .world_position(0.0, 0.0, 0.0, 0.0)
            .finish()
            .unwrap()
            .finish()
            .build()
            .unwrap();

        let result = FollowTrajectoryActionBuilder::new()
            .with_trajectory(trajectory)
            .build_action();

        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Following mode is required"));
    }

    #[test]
    fn test_maneuver_action_trait() {
        let builder = FollowTrajectoryActionBuilder::new().for_entity("test_entity");

        assert_eq!(builder.entity_ref(), Some("test_entity"));
    }
}