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
//! Spatial condition types for position and distance-based triggering
//!
//! This file contains:
//! - Position-based conditions (reach position with tolerance)
//! - Distance conditions (absolute distance to position)
//! - Relative distance conditions (distance between entities)
//! - Coordinate system and routing algorithm support
//! - Distance measurement type configurations
//!
use crate::types::basic::{Boolean, Double, OSString};
use crate::types::enums::{CoordinateSystem, RelativeDistanceType, RoutingAlgorithm, Rule};
use crate::types::positions::Position;
use serde::{Deserialize, Serialize};

/// Condition for reaching a specific position within tolerance.
///
/// Note: Deprecated in the OpenSCENARIO XSD. Prefer [`DistanceCondition`] for new scenarios.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename = "ReachPositionCondition")]
pub struct ReachPositionCondition {
    /// Target position to reach
    #[serde(rename = "Position")]
    pub position: Position,

    /// Distance tolerance for considering position reached
    #[serde(rename = "@tolerance")]
    pub tolerance: Double,
}

/// Condition based on distance to a specific position
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename = "DistanceCondition")]
pub struct DistanceCondition {
    /// Reference position for distance measurement
    #[serde(rename = "Position")]
    pub position: Position,

    /// Distance value to compare against
    #[serde(rename = "@value")]
    pub value: Double,

    /// Whether to use freespace (true) or reference point (false) distance
    #[serde(rename = "@freespace")]
    pub freespace: Boolean,

    /// Comparison rule (greater than, less than, etc.)
    #[serde(rename = "@rule")]
    pub rule: Rule,

    /// Whether to measure distance along route (deprecated)
    #[serde(rename = "@alongRoute", skip_serializing_if = "Option::is_none")]
    pub along_route: Option<Boolean>,

    /// Coordinate system for distance measurement
    #[serde(rename = "@coordinateSystem", skip_serializing_if = "Option::is_none")]
    pub coordinate_system: Option<CoordinateSystem>,

    /// Type of relative distance measurement
    #[serde(
        rename = "@relativeDistanceType",
        skip_serializing_if = "Option::is_none"
    )]
    pub relative_distance_type: Option<RelativeDistanceType>,

    /// Algorithm for route-based distance calculation
    #[serde(rename = "@routingAlgorithm", skip_serializing_if = "Option::is_none")]
    pub routing_algorithm: Option<RoutingAlgorithm>,
}

/// Condition based on relative distance between entities
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename = "RelativeDistanceCondition")]
pub struct RelativeDistanceCondition {
    /// Reference entity for distance measurement
    #[serde(rename = "@entityRef")]
    pub entity_ref: OSString,

    /// Distance value to compare against
    #[serde(rename = "@value")]
    pub value: Double,

    /// Whether to use freespace (true) or reference point (false) distance
    #[serde(rename = "@freespace")]
    pub freespace: Boolean,

    /// Type of relative distance measurement
    #[serde(rename = "@relativeDistanceType")]
    pub relative_distance_type: RelativeDistanceType,

    /// Comparison rule (greater than, less than, etc.)
    #[serde(rename = "@rule")]
    pub rule: Rule,

    /// Coordinate system for distance measurement
    #[serde(rename = "@coordinateSystem", skip_serializing_if = "Option::is_none")]
    pub coordinate_system: Option<CoordinateSystem>,

    /// Algorithm for route-based distance calculation
    #[serde(rename = "@routingAlgorithm", skip_serializing_if = "Option::is_none")]
    pub routing_algorithm: Option<RoutingAlgorithm>,
}

// Builder implementations for ergonomic construction
impl ReachPositionCondition {
    /// Create a new reach position condition
    pub fn new(position: Position, tolerance: f64) -> Self {
        Self {
            position,
            tolerance: Double::literal(tolerance),
        }
    }

    /// Create with world position
    pub fn at_world_position(x: f64, y: f64, z: f64, h: f64, tolerance: f64) -> Self {
        use crate::types::positions::WorldPosition;

        let world_pos = WorldPosition {
            x: Double::literal(x),
            y: Double::literal(y),
            z: Some(Double::literal(z)),
            h: Some(Double::literal(h)),
            p: Some(Double::literal(0.0)),
            r: Some(Double::literal(0.0)),
        };
        let mut position = Position::default();
        position.world_position = Some(world_pos);
        position.relative_world_position = None;
        position.road_position = None;
        position.lane_position = None;

        Self::new(position, tolerance)
    }
}

impl DistanceCondition {
    /// Create a new distance condition
    pub fn new(position: Position, value: f64, freespace: bool, rule: Rule) -> Self {
        Self {
            position,
            value: Double::literal(value),
            freespace: Boolean::literal(freespace),
            rule,
            along_route: None,
            coordinate_system: None,
            relative_distance_type: None,
            routing_algorithm: None,
        }
    }

    /// Set coordinate system for distance measurement
    pub fn with_coordinate_system(mut self, system: CoordinateSystem) -> Self {
        self.coordinate_system = Some(system);
        self
    }

    /// Set distance measurement type
    pub fn with_distance_type(mut self, distance_type: RelativeDistanceType) -> Self {
        self.relative_distance_type = Some(distance_type);
        self
    }

    /// Set routing algorithm for route-based distance
    pub fn with_routing_algorithm(mut self, algorithm: RoutingAlgorithm) -> Self {
        self.routing_algorithm = Some(algorithm);
        self
    }

    /// Create condition for distance less than threshold
    pub fn less_than(position: Position, distance: f64, freespace: bool) -> Self {
        Self::new(position, distance, freespace, Rule::LessThan)
    }

    /// Create condition for distance greater than threshold
    pub fn greater_than(position: Position, distance: f64, freespace: bool) -> Self {
        Self::new(position, distance, freespace, Rule::GreaterThan)
    }
}

impl RelativeDistanceCondition {
    /// Create a new relative distance condition
    pub fn new(
        entity_ref: impl Into<OSString>,
        value: f64,
        freespace: bool,
        distance_type: RelativeDistanceType,
        rule: Rule,
    ) -> Self {
        Self {
            entity_ref: entity_ref.into(),
            value: Double::literal(value),
            freespace: Boolean::literal(freespace),
            relative_distance_type: distance_type,
            rule,
            coordinate_system: None,
            routing_algorithm: None,
        }
    }

    /// Set coordinate system for distance measurement
    pub fn with_coordinate_system(mut self, system: CoordinateSystem) -> Self {
        self.coordinate_system = Some(system);
        self
    }

    /// Set routing algorithm for route-based distance
    pub fn with_routing_algorithm(mut self, algorithm: RoutingAlgorithm) -> Self {
        self.routing_algorithm = Some(algorithm);
        self
    }

    /// Create longitudinal distance condition
    pub fn longitudinal(
        entity_ref: impl Into<OSString>,
        distance: f64,
        freespace: bool,
        rule: Rule,
    ) -> Self {
        Self::new(
            entity_ref,
            distance,
            freespace,
            RelativeDistanceType::Longitudinal,
            rule,
        )
    }

    /// Create lateral distance condition
    pub fn lateral(
        entity_ref: impl Into<OSString>,
        distance: f64,
        freespace: bool,
        rule: Rule,
    ) -> Self {
        Self::new(
            entity_ref,
            distance,
            freespace,
            RelativeDistanceType::Lateral,
            rule,
        )
    }

    /// Create cartesian distance condition
    pub fn cartesian(
        entity_ref: impl Into<OSString>,
        distance: f64,
        freespace: bool,
        rule: Rule,
    ) -> Self {
        Self::new(
            entity_ref,
            distance,
            freespace,
            RelativeDistanceType::Cartesian,
            rule,
        )
    }
}

// Default implementations for testing and fallback scenarios
impl Default for ReachPositionCondition {
    fn default() -> Self {
        Self {
            position: Position::default(),
            tolerance: Double::literal(1.0),
        }
    }
}

impl Default for DistanceCondition {
    fn default() -> Self {
        Self {
            position: Position::default(),
            value: Double::literal(10.0),
            freespace: Boolean::literal(true),
            rule: Rule::LessThan,
            along_route: None,
            coordinate_system: None,
            relative_distance_type: None,
            routing_algorithm: None,
        }
    }
}

impl Default for RelativeDistanceCondition {
    fn default() -> Self {
        Self {
            entity_ref: OSString::literal("DefaultEntity".to_string()),
            value: Double::literal(10.0),
            freespace: Boolean::literal(true),
            relative_distance_type: RelativeDistanceType::Cartesian,
            rule: Rule::LessThan,
            coordinate_system: None,
            routing_algorithm: None,
        }
    }
}

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

    #[test]
    fn test_reach_position_condition_creation() {
        let condition = ReachPositionCondition::at_world_position(100.0, 200.0, 0.0, 1.57, 2.0);

        assert_eq!(condition.tolerance, Double::literal(2.0));
        assert!(condition.position.world_position.is_some());

        let world_pos = condition.position.world_position.unwrap();
        assert_eq!(world_pos.x, Double::literal(100.0));
        assert_eq!(world_pos.y, Double::literal(200.0));
    }

    #[test]
    fn test_distance_condition_builder() {
        let position = Position::default();
        let condition = DistanceCondition::less_than(position, 50.0, true)
            .with_coordinate_system(CoordinateSystem::Entity)
            .with_distance_type(RelativeDistanceType::Cartesian);

        assert_eq!(condition.value, Double::literal(50.0));
        assert_eq!(condition.freespace, Boolean::literal(true));
        assert_eq!(condition.rule, Rule::LessThan);
        assert_eq!(condition.coordinate_system, Some(CoordinateSystem::Entity));
        assert_eq!(
            condition.relative_distance_type,
            Some(RelativeDistanceType::Cartesian)
        );
    }

    #[test]
    fn test_relative_distance_condition_types() {
        use crate::types::basic::OSString;

        let longitudinal = RelativeDistanceCondition::longitudinal(
            OSString::literal("vehicle1".to_string()),
            20.0,
            false,
            Rule::GreaterThan,
        );
        assert_eq!(
            longitudinal.relative_distance_type,
            RelativeDistanceType::Longitudinal
        );

        let lateral = RelativeDistanceCondition::lateral(
            OSString::literal("vehicle2".to_string()),
            5.0,
            true,
            Rule::LessThan,
        );
        assert_eq!(
            lateral.relative_distance_type,
            RelativeDistanceType::Lateral
        );

        let cartesian = RelativeDistanceCondition::cartesian(
            OSString::literal("vehicle3".to_string()),
            15.0,
            true,
            Rule::EqualTo,
        );
        assert_eq!(
            cartesian.relative_distance_type,
            RelativeDistanceType::Cartesian
        );
    }

    #[test]
    fn test_spatial_condition_defaults() {
        let reach_pos = ReachPositionCondition::default();
        assert_eq!(reach_pos.tolerance, Double::literal(1.0));

        let distance = DistanceCondition::default();
        assert_eq!(distance.value, Double::literal(10.0));
        assert_eq!(distance.rule, Rule::LessThan);

        let relative_distance = RelativeDistanceCondition::default();
        assert_eq!(
            relative_distance.relative_distance_type,
            RelativeDistanceType::Cartesian
        );
        assert_eq!(relative_distance.rule, Rule::LessThan);
    }

    #[test]
    fn test_xml_serialization() {
        use crate::types::basic::OSString;

        let condition = RelativeDistanceCondition::cartesian(
            OSString::literal("ego_vehicle".to_string()),
            25.0,
            true,
            Rule::GreaterThan,
        )
        .with_coordinate_system(CoordinateSystem::Road);

        let xml = quick_xml::se::to_string(&condition).expect("Failed to serialize");
        assert!(xml.contains("entityRef=\"ego_vehicle\""));
        assert!(xml.contains("value=\"25\""));
        assert!(xml.contains("freespace=\"true\""));
        assert!(xml.contains("relativeDistanceType=\"cartesianDistance\""));
        assert!(xml.contains("rule=\"greaterThan\""));
        assert!(xml.contains("coordinateSystem=\"road\""));
    }
}