elevator-core 20.15.0

Engine-agnostic elevator simulation library with pluggable dispatch strategies
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
use crate::components::Orientation;
use crate::config::SimConfig;
use crate::error::SimError;

#[test]
fn deserialize_default_ron() {
    let ron_str = include_str!("../../../../assets/config/default.ron");
    let config: SimConfig = ron::from_str(ron_str).expect("Failed to deserialize default.ron");

    assert_eq!(config.building.name, "Demo Tower");
    assert_eq!(config.building.stops.len(), 8);
    let first = config.building.stops.first().expect("at least one stop");
    let last = config.building.stops.last().expect("at least one stop");
    assert!((first.position - 0.0).abs() < f64::EPSILON);
    assert!((last.position - 25.0).abs() < f64::EPSILON);
    assert_eq!(config.elevators.len(), 3);
    let express = &config.elevators[0];
    assert_eq!(express.name, "Express");
    assert!((express.max_speed.value() - 3.5).abs() < f64::EPSILON);
    assert!((express.weight_capacity.value() - 1200.0).abs() < f64::EPSILON);
    assert!((config.simulation.ticks_per_second - 60.0).abs() < f64::EPSILON);
    assert_eq!(config.passenger_spawning.mean_interval_ticks, 30);
}

#[test]
fn roundtrip_ron() {
    let ron_str = include_str!("../../../../assets/config/default.ron");
    let config: SimConfig = ron::from_str(ron_str).unwrap();
    let serialized = ron::to_string(&config).unwrap();
    let config2: SimConfig = ron::from_str(&serialized).unwrap();
    assert_eq!(config.building.stops.len(), config2.building.stops.len());
    assert_eq!(config.elevators.len(), config2.elevators.len());
}

#[test]
fn rejects_nan_stop_position() {
    use super::helpers;
    let mut config = helpers::default_config();
    config.building.stops[1].position = f64::NAN;
    let result = crate::sim::Simulation::new(&config, helpers::scan());
    assert!(
        matches!(
            result,
            Err(SimError::InvalidConfig {
                field: "building.stops.position",
                ..
            })
        ),
        "NaN position should be rejected, got {result:?}"
    );
}

#[test]
fn rejects_infinite_stop_position() {
    use super::helpers;
    let mut config = helpers::default_config();
    config.building.stops[0].position = f64::INFINITY;
    let result = crate::sim::Simulation::new(&config, helpers::scan());
    assert!(
        matches!(
            result,
            Err(SimError::InvalidConfig {
                field: "building.stops.position",
                ..
            })
        ),
        "infinite position should be rejected, got {result:?}"
    );
}

#[test]
fn rejects_neg_infinite_stop_position() {
    use super::helpers;
    let mut config = helpers::default_config();
    config.building.stops[2].position = f64::NEG_INFINITY;
    let result = crate::sim::Simulation::new(&config, helpers::scan());
    assert!(
        matches!(
            result,
            Err(SimError::InvalidConfig {
                field: "building.stops.position",
                ..
            })
        ),
        "negative infinity position should be rejected, got {result:?}"
    );
}

#[test]
fn rejects_zero_door_transition_ticks() {
    use super::helpers;
    let mut config = helpers::default_config();
    config.elevators[0].door_transition_ticks = 0;
    let result = crate::sim::Simulation::new(&config, helpers::scan());
    assert!(
        matches!(
            result,
            Err(SimError::InvalidConfig {
                field: "elevators.door_transition_ticks",
                ..
            })
        ),
        "zero door_transition_ticks should be rejected, got {result:?}"
    );
}

#[test]
fn rejects_zero_door_open_ticks() {
    use super::helpers;
    let mut config = helpers::default_config();
    config.elevators[0].door_open_ticks = 0;
    let result = crate::sim::Simulation::new(&config, helpers::scan());
    assert!(
        matches!(
            result,
            Err(SimError::InvalidConfig {
                field: "elevators.door_open_ticks",
                ..
            })
        ),
        "zero door_open_ticks should be rejected, got {result:?}"
    );
}

/// Non-finite `ticks_per_second` produces NaN/zero `dt` that silently
/// corrupts every physics step (#261).
#[test]
fn rejects_non_finite_ticks_per_second() {
    use super::helpers;
    for (label, value) in [
        ("NaN", f64::NAN),
        ("+inf", f64::INFINITY),
        ("-inf", f64::NEG_INFINITY),
        ("zero", 0.0),
        ("negative", -1.0),
    ] {
        let mut config = helpers::default_config();
        config.simulation.ticks_per_second = value;
        let result = crate::sim::Simulation::new(&config, helpers::scan());
        assert!(
            matches!(
                result,
                Err(SimError::InvalidConfig {
                    field: "simulation.ticks_per_second",
                    ..
                })
            ),
            "ticks_per_second={label} should be rejected, got {result:?}"
        );
    }
}

/// `PassengerSpawnConfig` is now validated; previously bad inputs survived
/// to `PoissonSource::from_config` and panicked later (#272).
#[test]
fn rejects_invalid_passenger_spawning() {
    use super::helpers;
    use crate::config::PassengerSpawnConfig;

    let cases: Vec<(&'static str, PassengerSpawnConfig, &'static str)> = vec![
        (
            "weight_range=(NaN, 50)",
            PassengerSpawnConfig {
                mean_interval_ticks: 120,
                weight_range: (f64::NAN, 50.0),
            },
            "passenger_spawning.weight_range",
        ),
        (
            "weight_range=(50, +inf)",
            PassengerSpawnConfig {
                mean_interval_ticks: 120,
                weight_range: (50.0, f64::INFINITY),
            },
            "passenger_spawning.weight_range",
        ),
        (
            "weight_range=(-50, -50)",
            PassengerSpawnConfig {
                mean_interval_ticks: 120,
                weight_range: (-50.0, -50.0),
            },
            "passenger_spawning.weight_range",
        ),
        (
            "weight_range=(100, 50) inverted",
            PassengerSpawnConfig {
                mean_interval_ticks: 120,
                weight_range: (100.0, 50.0),
            },
            "passenger_spawning.weight_range",
        ),
        (
            "mean_interval_ticks=0",
            PassengerSpawnConfig {
                mean_interval_ticks: 0,
                weight_range: (50.0, 100.0),
            },
            "passenger_spawning.mean_interval_ticks",
        ),
    ];

    for (label, spawn, expected_field) in cases {
        let mut config = helpers::default_config();
        config.passenger_spawning = spawn;
        let result = crate::sim::Simulation::new(&config, helpers::scan());
        match result {
            Err(SimError::InvalidConfig { field, .. }) if field == expected_field => {}
            _ => panic!(
                "{label} should produce InvalidConfig{{field={expected_field}}}, got {result:?}"
            ),
        }
    }
}

#[test]
fn rejects_empty_line_serves() {
    use super::helpers;
    use crate::config::LineConfig;
    let mut config = helpers::default_config();
    config.building.lines = Some(vec![LineConfig {
        id: 0,
        name: "Empty".into(),
        serves: vec![],
        elevators: config.elevators.clone(),
        orientation: Orientation::default(),
        position: None,
        min_position: None,
        max_position: None,
        kind: None,
        max_cars: None,
    }]);
    let result = crate::sim::Simulation::new(&config, helpers::scan());
    assert!(
        matches!(
            result,
            Err(SimError::InvalidConfig {
                field: "building.lines.serves",
                ..
            })
        ),
        "empty line.serves should be rejected, got {result:?}"
    );
}

// ===== schema_version validation (#654) =====

#[test]
fn rejects_legacy_zero_schema_version() {
    use super::helpers;
    // `serde(default)` deserializes a missing schema_version field as
    // `0`. The validator must surface this as an explicit migration
    // prompt, not a silent serde-default smear.
    let mut config = helpers::default_config();
    config.schema_version = 0;
    let result = crate::sim::Simulation::new(&config, helpers::scan());
    assert!(
        matches!(
            result,
            Err(SimError::InvalidConfig {
                field: "schema_version",
                ..
            })
        ),
        "schema_version=0 must be rejected with a migration hint, got {result:?}"
    );
}

#[test]
fn rejects_forward_incompatible_schema_version() {
    use super::helpers;
    let mut config = helpers::default_config();
    config.schema_version = crate::config::CURRENT_CONFIG_SCHEMA_VERSION + 1;
    let result = crate::sim::Simulation::new(&config, helpers::scan());
    assert!(
        matches!(
            result,
            Err(SimError::InvalidConfig {
                field: "schema_version",
                ..
            })
        ),
        "schema_version > CURRENT must be rejected as forward-incompatible, got {result:?}"
    );
}

#[test]
fn accepts_current_schema_version() {
    use super::helpers;
    let config = helpers::default_config();
    assert_eq!(
        config.schema_version,
        crate::config::CURRENT_CONFIG_SCHEMA_VERSION,
        "test fixture must pin to current version so this test isn't vacuous"
    );
    assert!(crate::sim::Simulation::new(&config, helpers::scan()).is_ok());
}

#[test]
fn ron_without_schema_version_field_deserializes_to_zero() {
    // The `#[serde(default)]` contract: a RON file with no
    // schema_version field must deserialize successfully but with
    // schema_version=0, which the validator then catches.
    let ron_str = r#"
        SimConfig(
            building: BuildingConfig(
                name: "Legacy",
                stops: [
                    StopConfig(id: StopId(0), name: "G", position: 0.0),
                ],
            ),
            elevators: [],
            simulation: SimulationParams(ticks_per_second: 60.0),
            passenger_spawning: PassengerSpawnConfig(
                mean_interval_ticks: 120,
                weight_range: (50.0, 100.0),
            ),
        )
    "#;
    let config: SimConfig = ron::from_str(ron_str).expect("legacy RON deserializes");
    assert_eq!(
        config.schema_version, 0,
        "RON without schema_version field must deserialize as 0, the legacy marker"
    );
}

#[test]
fn shipped_assets_pin_to_current_schema_version() {
    // Every config under assets/config/ must declare the current
    // version explicitly; otherwise the asset itself becomes a legacy
    // file the next time someone bumps CURRENT_CONFIG_SCHEMA_VERSION.
    let mut assets = vec![
        include_str!("../../../../assets/config/default.ron"),
        include_str!("../../../../assets/config/space_elevator.ron"),
        include_str!("../../../../assets/config/annotated.ron"),
    ];
    // `loop_demo.ron` carries a Loop-kind line and can only be parsed
    // when the feature is enabled. The deserializer rejects Loop
    // variants outright with the feature off, so listing it
    // unconditionally would fail the schema pin on the default
    // feature configuration. Gating the read mirrors how the binary
    // would handle the same config at runtime.
    #[cfg(feature = "loop_lines")]
    assets.push(include_str!("../../../../assets/config/loop_demo.ron"));
    #[cfg(feature = "loop_lines")]
    assets.push(include_str!("../../../../assets/config/airport_apm.ron"));

    for asset in assets {
        let config: SimConfig = ron::from_str(asset).expect("shipped asset deserializes");
        assert_eq!(
            config.schema_version,
            crate::config::CURRENT_CONFIG_SCHEMA_VERSION,
            "shipped asset must pin to CURRENT_CONFIG_SCHEMA_VERSION"
        );
    }
}

#[cfg(feature = "loop_lines")]
#[test]
fn loop_demo_config_loads_and_runs() {
    // End-to-end smoke check: the shipped loop demo deserializes,
    // constructs through `Simulation::new`, and survives a handful of
    // ticks without panicking. Catches RON-schema drift (field names,
    // variant shape) and runtime-invariant regressions that
    // construction validation would surface.
    use crate::dispatch::LoopSweepDispatch;
    use crate::sim::Simulation;

    let ron_str = include_str!("../../../../assets/config/loop_demo.ron");
    let config: SimConfig = ron::from_str(ron_str).expect("loop_demo.ron must deserialize cleanly");

    let mut sim = Simulation::new(&config, LoopSweepDispatch::new())
        .expect("loop_demo.ron must construct a valid Simulation");

    // Run a few hundred ticks — enough for the kickstart pass, the
    // first door cycle on each car, and the door FSM continuation
    // handing off to the next forward stop. Smoke test, not a
    // behavioural assertion, so a successful run = no panics + no
    // out-of-bounds entity references in the pipeline.
    for _ in 0..600 {
        sim.step();
    }
}

#[cfg(feature = "loop_lines")]
#[test]
fn airport_apm_config_loads_and_runs() {
    // Two independent LineKind::Loop groups with LoopSchedule dispatch
    // on each — distinct from `loop_demo` which has a single group.
    // `Simulation::new`'s builder dispatcher overrides GroupId(0)'s
    // RON dispatch, so pass `LoopScheduleDispatch::default()` to keep
    // the test exercising what the RON declares for both groups.
    use crate::dispatch::LoopScheduleDispatch;
    use crate::sim::Simulation;

    let ron_str = include_str!("../../../../assets/config/airport_apm.ron");
    let config: SimConfig =
        ron::from_str(ron_str).expect("airport_apm.ron must deserialize cleanly");

    let mut sim = Simulation::new(&config, LoopScheduleDispatch::default())
        .expect("airport_apm.ron must construct a valid Simulation");

    for _ in 0..600 {
        sim.step();
    }
}