openscenario-rs 0.3.1

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
//! Spatial condition builders (distance, position, etc.)
//!
//! This module provides builders for creating spatial conditions that trigger
//! based on entity positions, distances, and spatial relationships.
//!
//! # Supported Conditions
//!
//! - **DistanceCondition**: Triggers based on distance to a position
//! - **ReachPositionCondition**: Triggers when entity reaches a position
//! - **RelativeDistanceCondition**: Triggers based on distance between entities
//! - **CollisionCondition**: Triggers on collision detection
//!

use crate::builder::{BuilderError, BuilderResult};
use crate::types::{
    basic::{Double, OSString},
    conditions::entity::{ByEntityCondition, DistanceCondition, EntityCondition},
    enums::{ConditionEdge, RelativeDistanceType, Rule, TriggeringEntitiesRule},
    positions::Position,
    scenario::triggers::{Condition, EntityRef, TriggeringEntities},
};
/// Builder for distance conditions
///
/// Creates conditions that trigger when an entity is within a certain distance
/// of a target position. Supports both closer-than and farther-than triggers.
#[derive(Debug)]
pub struct DistanceConditionBuilder {
    entity_ref: Option<String>,
    target_position: Option<Position>,
    distance: Option<f64>,
    rule: Rule,
    freespace: bool,
}

impl DistanceConditionBuilder {
    /// Create a new distance condition builder
    pub fn new() -> Self {
        Self {
            entity_ref: None,
            target_position: None,
            distance: None,
            rule: Rule::LessThan,
            freespace: false,
        }
    }

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

    /// Set target position
    pub fn to_position(mut self, position: Position) -> Self {
        self.target_position = Some(position);
        self
    }

    /// Set distance threshold (entity closer than this distance triggers)
    pub fn closer_than(mut self, distance: f64) -> Self {
        self.distance = Some(distance);
        self.rule = Rule::LessThan;
        self
    }

    /// Set distance threshold (entity farther than this distance triggers)
    pub fn farther_than(mut self, distance: f64) -> Self {
        self.distance = Some(distance);
        self.rule = Rule::GreaterThan;
        self
    }

    /// Set distance with custom rule
    pub fn distance_rule(mut self, distance: f64, rule: Rule) -> Self {
        self.distance = Some(distance);
        self.rule = rule;
        self
    }

    /// Use freespace distance (bounding box edges) instead of reference point
    pub fn use_freespace(mut self, freespace: bool) -> Self {
        self.freespace = freespace;
        self
    }

    /// Build the condition
    pub fn build(self) -> BuilderResult<Condition> {
        if self.entity_ref.is_none() {
            return Err(BuilderError::validation_error(
                "Entity reference is required",
            ));
        }
        if self.target_position.is_none() {
            return Err(BuilderError::validation_error(
                "Target position is required",
            ));
        }
        if self.distance.is_none() {
            return Err(BuilderError::validation_error(
                "Distance threshold is required",
            ));
        }

        Ok(Condition {
            name: OSString::literal("DistanceCondition".to_string()),
            condition_edge: ConditionEdge::Rising,
            delay: Some(Double::literal(0.0)),
            by_value_condition: None,
            by_entity_condition: Some(ByEntityCondition {
                triggering_entities: TriggeringEntities {
                    triggering_entities_rule: TriggeringEntitiesRule::Any,
                    entity_refs: vec![EntityRef {
                        entity_ref: OSString::literal(self.entity_ref.unwrap()),
                    }],
                },
                entity_condition: EntityCondition::Distance(DistanceCondition {
                    position: self.target_position.unwrap(),
                    value: Double::literal(self.distance.unwrap()),
                    freespace: crate::types::basic::Value::Literal(self.freespace),
                    rule: self.rule,
                    along_route: None,
                    coordinate_system: None,
                    relative_distance_type: Some(RelativeDistanceType::Cartesian),
                    routing_algorithm: None,
                }),
            }),
        })
    }
}

/// Builder for relative distance conditions
#[derive(Debug)]
pub struct RelativeDistanceConditionBuilder {
    entity_ref: Option<String>,
    target_entity: Option<String>,
    distance: Option<f64>,
    rule: Rule,
    freespace: bool,
    relative_distance_type: RelativeDistanceType,
}

impl Default for RelativeDistanceConditionBuilder {
    fn default() -> Self {
        Self {
            entity_ref: None,
            target_entity: None,
            distance: None,
            rule: Rule::LessThan,
            freespace: true,
            relative_distance_type: RelativeDistanceType::Cartesian,
        }
    }
}

impl RelativeDistanceConditionBuilder {
    /// Create new relative distance condition builder
    pub fn new() -> Self {
        Self {
            rule: Rule::LessThan,
            relative_distance_type: RelativeDistanceType::Cartesian,
            ..Default::default()
        }
    }

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

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

    /// Set distance threshold (closer than)
    pub fn closer_than(mut self, distance: f64) -> Self {
        self.distance = Some(distance);
        self.rule = Rule::LessThan;
        self
    }

    /// Set distance threshold (farther than)
    pub fn farther_than(mut self, distance: f64) -> Self {
        self.distance = Some(distance);
        self.rule = Rule::GreaterThan;
        self
    }

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

    /// Set distance type to longitudinal
    pub fn longitudinal(mut self) -> Self {
        self.relative_distance_type = RelativeDistanceType::Longitudinal;
        self
    }

    /// Set distance type to lateral
    pub fn lateral(mut self) -> Self {
        self.relative_distance_type = RelativeDistanceType::Lateral;
        self
    }

    /// Build the condition
    pub fn build(self) -> BuilderResult<Condition> {
        if self.entity_ref.is_none() {
            return Err(BuilderError::validation_error(
                "Entity reference is required",
            ));
        }
        if self.target_entity.is_none() {
            return Err(BuilderError::validation_error("Target entity is required"));
        }
        if self.distance.is_none() {
            return Err(BuilderError::validation_error(
                "Distance threshold is required",
            ));
        }

        // Create a relative distance condition using entity condition structure
        Ok(Condition {
            name: OSString::literal("RelativeDistanceCondition".to_string()),
            condition_edge: ConditionEdge::Rising,
            delay: Some(Double::literal(0.0)),
            by_value_condition: None,
            by_entity_condition: Some(ByEntityCondition {
                triggering_entities: TriggeringEntities {
                    triggering_entities_rule: TriggeringEntitiesRule::Any,
                    entity_refs: vec![EntityRef {
                        entity_ref: OSString::literal(self.entity_ref.unwrap()),
                    }],
                },
                entity_condition: EntityCondition::RelativeDistance(
                    crate::types::conditions::entity::RelativeDistanceCondition {
                        entity_ref: OSString::literal(self.target_entity.unwrap()),
                        value: Double::literal(self.distance.unwrap()),
                        freespace: crate::types::basic::Value::Literal(self.freespace),
                        rule: self.rule,
                        relative_distance_type: self.relative_distance_type,
                        coordinate_system: None,
                        routing_algorithm: None,
                    },
                ),
            }),
        })
    }
}

/// Builder for collision conditions
#[derive(Debug, Default)]
pub struct CollisionConditionBuilder {
    entity_ref: Option<String>,
    target_entity: Option<String>,
    collision_type: Option<String>,
}

impl CollisionConditionBuilder {
    /// Create new collision condition builder
    pub fn new() -> Self {
        Self::default()
    }

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

    /// Set target entity for collision detection
    pub fn with_entity(mut self, target_entity: &str) -> Self {
        self.target_entity = Some(target_entity.to_string());
        self
    }

    /// Set collision type
    pub fn collision_type(mut self, collision_type: &str) -> Self {
        self.collision_type = Some(collision_type.to_string());
        self
    }

    /// Build the condition
    pub fn build(self) -> BuilderResult<Condition> {
        if self.entity_ref.is_none() {
            return Err(BuilderError::validation_error(
                "Entity reference is required",
            ));
        }

        Ok(Condition {
            name: OSString::literal("CollisionCondition".to_string()),
            condition_edge: ConditionEdge::Rising,
            delay: Some(Double::literal(0.0)),
            by_value_condition: None,
            by_entity_condition: Some(ByEntityCondition {
                triggering_entities: TriggeringEntities {
                    triggering_entities_rule: TriggeringEntitiesRule::Any,
                    entity_refs: vec![EntityRef {
                        entity_ref: OSString::literal(self.entity_ref.unwrap()),
                    }],
                },
                entity_condition: EntityCondition::Collision(
                    crate::types::conditions::entity::CollisionCondition {
                        target: self.target_entity.map(OSString::literal),
                        by_type: self.collision_type.map(|collision_type| {
                            crate::types::conditions::entity::CollisionTarget {
                                target_type: OSString::literal(collision_type),
                            }
                        }),
                        position: None,
                    },
                ),
            }),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::builder::positions::PositionBuilder;
    use crate::types::{
        basic::Value,
        positions::{Position, WorldPosition},
    };
    fn create_test_position() -> Position {
        Position {
            world_position: Some(WorldPosition {
                x: Double::literal(100.0),
                y: Double::literal(200.0),
                z: Some(Double::literal(0.0)),
                h: Some(Double::literal(0.0)),
                p: Some(Double::literal(0.0)),
                r: Some(Double::literal(0.0)),
            }),
            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,
        }
    }

    #[test]
    fn test_distance_condition_builder() {
        let position = create_test_position();

        let condition = DistanceConditionBuilder::new()
            .for_entity("ego")
            .to_position(position)
            .closer_than(10.0)
            .build()
            .unwrap();

        assert!(condition.by_entity_condition.is_some());
        let by_entity = condition.by_entity_condition.unwrap();

        match by_entity.entity_condition {
            EntityCondition::Distance(distance_condition) => {
                assert_eq!(distance_condition.value.as_literal().unwrap(), &10.0);
                assert_eq!(distance_condition.rule, Rule::LessThan);
                assert_eq!(distance_condition.freespace.as_literal().unwrap(), &false);
            }
            _ => panic!("Expected Distance condition"),
        }
    }

    #[test]
    fn test_distance_condition_farther_than() {
        let position = create_test_position();

        let condition = DistanceConditionBuilder::new()
            .for_entity("target")
            .to_position(position)
            .farther_than(50.0)
            .build()
            .unwrap();

        let by_entity = condition.by_entity_condition.unwrap();
        match by_entity.entity_condition {
            EntityCondition::Distance(distance_condition) => {
                assert_eq!(distance_condition.value.as_literal().unwrap(), &50.0);
                assert_eq!(distance_condition.rule, Rule::GreaterThan);
            }
            _ => panic!("Expected Distance condition"),
        }
    }

    #[test]
    fn test_distance_condition_with_freespace() {
        let position = create_test_position();

        let condition = DistanceConditionBuilder::new()
            .for_entity("ego")
            .to_position(position)
            .closer_than(5.0)
            .use_freespace(true)
            .build()
            .unwrap();

        let by_entity = condition.by_entity_condition.unwrap();
        match by_entity.entity_condition {
            EntityCondition::Distance(distance_condition) => {
                assert_eq!(distance_condition.freespace.as_literal().unwrap(), &true);
            }
            _ => panic!("Expected Distance condition"),
        }
    }

    #[test]
    fn test_distance_condition_validation() {
        // Missing entity reference
        let position = create_test_position();
        let result = DistanceConditionBuilder::new()
            .to_position(position)
            .closer_than(10.0)
            .build();
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Entity reference is required"));

        // Missing position
        let result = DistanceConditionBuilder::new()
            .for_entity("ego")
            .closer_than(10.0)
            .build();
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Target position is required"));

        // Missing distance
        let position = create_test_position();
        let result = DistanceConditionBuilder::new()
            .for_entity("ego")
            .to_position(position)
            .build();
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Distance threshold is required"));
    }

    #[test]
    fn test_distance_condition_custom_rule() {
        let position = create_test_position();

        let condition = DistanceConditionBuilder::new()
            .for_entity("ego")
            .to_position(position)
            .distance_rule(25.0, Rule::EqualTo)
            .build()
            .unwrap();

        let by_entity = condition.by_entity_condition.unwrap();
        match by_entity.entity_condition {
            EntityCondition::Distance(distance_condition) => {
                assert_eq!(distance_condition.value.as_literal().unwrap(), &25.0);
                assert_eq!(distance_condition.rule, Rule::EqualTo);
            }
            _ => panic!("Expected Distance condition"),
        }
    }
}