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
//! Lateral action builders (LaneChangeAction, LateralDistanceAction, LaneOffsetAction)

use crate::builder::actions::base::{ActionBuilder, ManeuverAction};
use crate::builder::{BuilderError, BuilderResult};
use crate::types::{
    actions::movement::{
        AbsoluteTargetLane, AbsoluteTargetLaneOffset, DynamicConstraints, LaneChangeAction,
        LaneChangeTarget, LaneChangeTargetChoice, LaneOffsetAction, LaneOffsetActionDynamics,
        LaneOffsetTarget, LaneOffsetTargetChoice, LateralAction, LateralDistanceAction,
        RelativeTargetLane, RelativeTargetLaneOffset, TransitionDynamics,
    },
    actions::wrappers::PrivateAction,
    basic::{Boolean, Double, Int, OSString},
    enums::{DynamicsDimension, DynamicsShape},
};

/// Builder for lane change actions
#[derive(Debug, Default)]
pub struct LaneChangeActionBuilder {
    entity_ref: Option<String>,
    target_lane_offset: Option<f64>,
    dynamics: Option<TransitionDynamics>,
    target: Option<LaneChangeTargetChoice>,
}

impl LaneChangeActionBuilder {
    /// Create new lane change action builder
    pub fn new() -> Self {
        Self::default()
    }

    /// Set target entity for this action
    pub fn for_entity(mut self, entity_ref: &str) -> Self {
        self.entity_ref = Some(entity_ref.to_string());
        self
    }

    /// Set target lane offset
    pub fn with_lane_offset(mut self, offset: f64) -> Self {
        self.target_lane_offset = Some(offset);
        self
    }

    /// Set transition dynamics
    pub fn with_dynamics(mut self, dynamics: TransitionDynamics) -> Self {
        self.dynamics = Some(dynamics);
        self
    }

    /// Set dynamics with simple parameters
    pub fn with_simple_dynamics(mut self, duration: f64) -> Self {
        self.dynamics = Some(TransitionDynamics {
            dynamics_dimension: DynamicsDimension::Time,
            dynamics_shape: DynamicsShape::Linear,
            value: Double::literal(duration),
        });
        self
    }

    /// Target relative lane change (relative to another entity)
    pub fn to_relative_lane(mut self, entity_ref: &str, lane_offset: i32) -> Self {
        self.target = Some(LaneChangeTargetChoice::RelativeTargetLane(
            RelativeTargetLane {
                entity_ref: OSString::literal(entity_ref.to_string()),
                value: Int::literal(lane_offset),
            },
        ));
        self
    }

    /// Target absolute lane change
    pub fn to_absolute_lane(mut self, lane_id: &str) -> Self {
        self.target = Some(LaneChangeTargetChoice::AbsoluteTargetLane(
            AbsoluteTargetLane {
                value: OSString::literal(lane_id.to_string()),
            },
        ));
        self
    }
}

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

        let lane_change_action = LaneChangeAction {
            target_lane_offset: self.target_lane_offset.map(Double::literal),
            lane_change_action_dynamics: self.dynamics.unwrap_or_else(|| TransitionDynamics {
                dynamics_dimension: DynamicsDimension::Time,
                dynamics_shape: DynamicsShape::Linear,
                value: Double::literal(2.0),
            }),
            lane_change_target: LaneChangeTarget {
                target_choice: self.target.unwrap(),
            },
        };

        Ok(PrivateAction::LateralAction(LateralAction::lane_change(
            lane_change_action,
        )))
    }

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

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

/// Builder for lateral distance actions
#[derive(Debug, Default)]
pub struct LateralDistanceActionBuilder {
    entity_ref: Option<String>,
    target_entity: Option<String>,
    distance: Option<f64>,
    freespace: bool,
    continuous: bool,
    dynamic_constraints: Option<DynamicConstraints>,
}

impl LateralDistanceActionBuilder {
    /// Create new lateral distance action builder
    pub fn new() -> Self {
        Self::default()
    }

    /// Set target entity for this action
    pub fn for_entity(mut self, entity_ref: &str) -> Self {
        self.entity_ref = Some(entity_ref.to_string());
        self
    }

    /// Set target entity to maintain distance from
    pub fn from_entity(mut self, target_entity: &str) -> Self {
        self.target_entity = Some(target_entity.to_string());
        self
    }

    /// Set target distance
    pub fn at_distance(mut self, distance: f64) -> Self {
        self.distance = Some(distance);
        self
    }

    /// Use freespace calculation
    pub fn with_freespace(mut self, freespace: bool) -> Self {
        self.freespace = freespace;
        self
    }

    /// Set continuous mode
    pub fn continuous(mut self, continuous: bool) -> Self {
        self.continuous = continuous;
        self
    }

    /// Set dynamic constraints
    pub fn with_constraints(mut self, constraints: DynamicConstraints) -> Self {
        self.dynamic_constraints = Some(constraints);
        self
    }
}

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

        let lateral_distance_action = LateralDistanceAction {
            entity_ref: OSString::literal(self.target_entity.unwrap()),
            distance: self.distance.map(Double::literal),
            freespace: Boolean::literal(self.freespace),
            continuous: Boolean::literal(self.continuous),
            dynamic_constraints: self.dynamic_constraints,
        };

        Ok(PrivateAction::LateralAction(
            LateralAction::lateral_distance(lateral_distance_action),
        ))
    }

    fn validate(&self) -> BuilderResult<()> {
        if self.target_entity.is_none() {
            return Err(BuilderError::validation_error(
                "Target entity is required for lateral distance action",
            ));
        }
        Ok(())
    }
}

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

/// Builder for lane offset actions
#[derive(Debug, Default)]
pub struct LaneOffsetActionBuilder {
    entity_ref: Option<String>,
    continuous: bool,
    dynamics: Option<LaneOffsetActionDynamics>,
    target: Option<LaneOffsetTargetChoice>,
}

impl LaneOffsetActionBuilder {
    /// Create new lane offset action builder
    pub fn new() -> Self {
        Self::default()
    }

    /// Set target entity for this action
    pub fn for_entity(mut self, entity_ref: &str) -> Self {
        self.entity_ref = Some(entity_ref.to_string());
        self
    }

    /// Set continuous mode
    pub fn continuous(mut self, continuous: bool) -> Self {
        self.continuous = continuous;
        self
    }

    /// Set dynamics
    pub fn with_dynamics(mut self, dynamics: LaneOffsetActionDynamics) -> Self {
        self.dynamics = Some(dynamics);
        self
    }

    /// Set simple dynamics
    pub fn with_simple_dynamics(
        mut self,
        shape: DynamicsShape,
        max_lateral_acc: Option<f64>,
    ) -> Self {
        self.dynamics = Some(LaneOffsetActionDynamics {
            dynamics_shape: shape,
            max_lateral_acc: max_lateral_acc.map(Double::literal),
        });
        self
    }

    /// Target relative lane offset (relative to another entity)
    pub fn to_relative_offset(mut self, entity_ref: &str, offset: f64) -> Self {
        self.target = Some(LaneOffsetTargetChoice::RelativeTargetLaneOffset(
            RelativeTargetLaneOffset {
                entity_ref: OSString::literal(entity_ref.to_string()),
                value: Double::literal(offset),
            },
        ));
        self
    }

    /// Target absolute lane offset
    pub fn to_absolute_offset(mut self, offset: f64) -> Self {
        self.target = Some(LaneOffsetTargetChoice::AbsoluteTargetLaneOffset(
            AbsoluteTargetLaneOffset {
                value: Double::literal(offset),
            },
        ));
        self
    }
}

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

        let lane_offset_action = LaneOffsetAction {
            continuous: Boolean::literal(self.continuous),
            dynamics: self.dynamics.unwrap_or_else(|| LaneOffsetActionDynamics {
                dynamics_shape: DynamicsShape::Linear,
                max_lateral_acc: None,
            }),
            target: LaneOffsetTarget {
                target_choice: self.target.unwrap(),
            },
        };

        Ok(PrivateAction::LateralAction(LateralAction::lane_offset(
            lane_offset_action,
        )))
    }

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

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::enums::DynamicsShape;

    #[test]
    fn test_lane_change_action_builder() {
        let action = LaneChangeActionBuilder::new()
            .for_entity("ego")
            .to_absolute_lane("1")
            .with_lane_offset(0.5)
            .with_simple_dynamics(2.0)
            .build_action()
            .unwrap();

        // Verify the action was built correctly
        if let PrivateAction::LateralAction(lateral_action) = action {
            if let crate::types::actions::movement::LateralActionChoice::LaneChangeAction(
                lane_change,
            ) = lateral_action.lateral_choice
            {
                assert_eq!(
                    *lane_change
                        .target_lane_offset
                        .unwrap()
                        .as_literal()
                        .unwrap(),
                    0.5
                );
                assert_eq!(
                    *lane_change
                        .lane_change_action_dynamics
                        .value
                        .as_literal()
                        .unwrap(),
                    2.0
                );
            } else {
                panic!("Expected LaneChangeAction");
            }
        } else {
            panic!("Expected LateralAction");
        }
    }

    #[test]
    fn test_lateral_distance_action_builder() {
        let action = LateralDistanceActionBuilder::new()
            .for_entity("ego")
            .from_entity("target")
            .at_distance(5.0)
            .with_freespace(true)
            .continuous(true)
            .build_action()
            .unwrap();

        // Verify the action was built correctly
        if let PrivateAction::LateralAction(lateral_action) = action {
            if let crate::types::actions::movement::LateralActionChoice::LateralDistanceAction(
                distance_action,
            ) = lateral_action.lateral_choice
            {
                assert_eq!(distance_action.entity_ref.as_literal().unwrap(), "target");
                assert_eq!(
                    *distance_action.distance.unwrap().as_literal().unwrap(),
                    5.0
                );
                assert!(*distance_action.freespace.as_literal().unwrap());
                assert!(*distance_action.continuous.as_literal().unwrap());
            } else {
                panic!("Expected LateralDistanceAction");
            }
        } else {
            panic!("Expected LateralAction");
        }
    }

    #[test]
    fn test_lane_offset_action_builder() {
        let action = LaneOffsetActionBuilder::new()
            .for_entity("ego")
            .to_absolute_offset(1.5)
            .continuous(false)
            .with_simple_dynamics(DynamicsShape::Linear, Some(2.0))
            .build_action()
            .unwrap();

        // Verify the action was built correctly
        if let PrivateAction::LateralAction(lateral_action) = action {
            if let crate::types::actions::movement::LateralActionChoice::LaneOffsetAction(
                offset_action,
            ) = lateral_action.lateral_choice
            {
                assert!(!*offset_action.continuous.as_literal().unwrap());
                assert_eq!(
                    *offset_action
                        .dynamics
                        .max_lateral_acc
                        .unwrap()
                        .as_literal()
                        .unwrap(),
                    2.0
                );
            } else {
                panic!("Expected LaneOffsetAction");
            }
        } else {
            panic!("Expected LateralAction");
        }
    }
}