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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
use crate::behaviour::BehaviourType;
use crate::agents_types::AgentType;
use crate::agents::{VehicleIntention, TailIntentionManeuver};
use crate::grid::cell::CellID;
use crate::maneuver::LaneChangeType;
use crate::grid::road_network::GridRoads;
use crate::trips::trip::TripID;
use std::fmt;
use std::rc::Rc;
use std::cell::RefCell;
/// Errors returned by vehicle-related operations.
#[derive(Debug, Clone)]
pub enum VehicleError {
/// Indicates that a tail cell with the given ID was not found for the vehicle
TailCellNotFound {
/// The ID of the tail cell that was not found
cell_id: CellID,
/// The position (index) of the tail cell in the vehicle's tail cells list
position: usize,
/// The vehicle's identifier
vehicle_id: VehicleID,
},
/// Indicates that the provided cell ID is invalid
InvalidCell(CellID),
}
impl fmt::Display for VehicleError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
VehicleError::TailCellNotFound {
cell_id,
position,
vehicle_id,
} => {
write!(
f,
"Can't find tail cell with ID '{}' at position '{}' for vehicle '{}'",
cell_id, position, vehicle_id
)
}
VehicleError::InvalidCell(cell_id) => {
write!(f, "Invalid cell ID '{}'", cell_id)
}
}
}
}
/// Just a shorthand for vehicle reference type
/// Obsolete in terms of internal usage (it was used before passing VehiclesStorage
/// to the simulation engine). Could be useful for external usage.
pub type VehicleRef = Rc<RefCell<Vehicle>>;
/// Vehicle unique identifier type
pub type VehicleID = u64;
/// Represents basic agent in simulation
#[derive(Debug)]
pub struct Vehicle {
/// Unique identifier
pub id: VehicleID,
/// Agent type. See the ref. at `AgentType`
pub vehicle_type: AgentType,
/// Movement strategy. See the ref. at `BehaviourType`
pub strategy_type: BehaviourType,
/// Currently occupied cell
pub cell_id: CellID,
/// Currently occupied cells by tail (in case when vehicle has size more that one cell)
/// Order: [furthest from head, ..., closest to head]
/// E.g. grid [1->2->3->4->5], vehicle's head in cell 4, size is 2. Then the tail cells are [2, 3]
/// where index 0 (cell 2) is furthest and index 1 (cell 3) is closest to head
///
/// NOTE: Gradual Materialization - When a vehicle is spawned from a trip generator, this vector
/// starts empty even if tail_size > 0. The tail "materializes" gradually as the vehicle moves:
/// each cell the head passes through becomes a tail cell. This models a vehicle "entering" the
/// network head-first. During this growth period, len(tail_cells) < tail_size is expected.
/// See also: Trip::vehicle_tail_size.
pub tail_cells: Vec<CellID>,
/// Current speed
pub speed: i32,
/// Maximum speed which can be reached by the vehicle. If value is greater than maximum speed
/// in cell then the vehicle will be limited to cell's speed limit
pub speed_limit: i32,
/// Current bearing (direction angle)
pub bearing: f64,
/// Minimal safe distance (in cells) to the vehicle in front
pub min_safe_distance: i32,
/// Final cell for the vehicle's trip
pub destination: CellID,
/// A boolean indicating if the vehicle is a confclict participant
pub is_conflict_participant: bool,
/// Corresponding trip identifier
pub trip: TripID,
/// Number of transits have been made by the vehicle
transits_made: u64,
/// Cells which must be traversed in exact given order by the vehicle
pub transit_cells: Vec<CellID>,
/// A value in (0; 1] representing the probability of the vehicle randomly slowing down.
pub slow_down_factor: f64,
/// A value in (0; 1] representing cooperative behaviour of the vehicle.
/// 0 - when behaviour considered to be "aggressive"
/// 1 - fully cooperative
pub cooperativity: f64,
/// Delay time (in time units) between two possible accelerations vehicle can do.
/// It could be used to prohibit to the vehicle to do sequential acceleration during simulation.
pub timer_non_acceleration: i64,
/// Delay time (in time units) between two possible maneuvers vehicle can perform.
/// It could be used to prohibit to the vehicle to perform sequential maneuvers during simulation.
pub timer_non_maneuvers: i64,
/// Delay time (in time units) between two possible slowdowns vehicle can do.
/// It could be used to prohibit to the vehicle to do sequential maneuvers during simulation.
pub timer_non_slowdown: i64,
/// Relaxation time (in time units) in the transit cells (in case when they are set)
pub relax_time: i32,
// Timer for `relax_time` field
relax_countdown: i32,
/// Travel time (in time units) which vehicle has been in movement state.
pub travel_time: i64,
/// @todo: for further research and development needs
pub confusion: bool,
/// Vehicle's intention to perform maneuver and other actions
pub intention: VehicleIntention,
}
impl Vehicle {
/// Constructs a new `VehicleBuilder` for building a `Vehicle` object.
///
/// # Arguments
/// * `id` - A unique identifier for the vehicle.
///
/// # Returns
/// A `VehicleBuilder` struct which is used to configure and build the `Vehicle` object.
///
/// # Example
/// ```
/// use micro_traffic_sim_core::agents_types::AgentType;
/// use micro_traffic_sim_core::agents::Vehicle;
/// let vehicle = Vehicle::new(1)
/// .with_cell(1)
/// .with_destination(100)
/// .with_type(AgentType::Car)
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// ```
pub fn new(id: u64) -> VehicleBuilder {
VehicleBuilder {
vehicle: Vehicle {
id,
vehicle_type: AgentType::Car,
strategy_type: BehaviourType::Aggressive,
cell_id: -1,
tail_cells: Vec::new(),
speed: 1,
speed_limit: 4,
bearing: 0.0,
min_safe_distance: 0,
destination: -1,
is_conflict_participant: false,
trip: -1,
transits_made: 0,
transit_cells: Vec::new(),
slow_down_factor: 0.1,
cooperativity: 0.0,
timer_non_acceleration: 0,
timer_non_maneuvers: 0,
timer_non_slowdown: 0,
relax_time: 0,
relax_countdown: 0,
travel_time: 0,
confusion: false,
intention: VehicleIntention::default(),
},
}
}
/// Increments number of transit have been made by vehicle
///
/// # Returns
/// Nothing
///
/// # Example
/// ```
/// use micro_traffic_sim_core::agents_types::AgentType;
/// use micro_traffic_sim_core::agents::Vehicle;
/// let mut vehicle = Vehicle::new(1)
/// .with_cell(1)
/// .with_destination(100)
/// .with_type(AgentType::Car)
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// vehicle.transits_made_inc();
/// ```
pub fn transits_made_inc(&mut self) {
self.transits_made += 1;
}
/// Returns number of transits have been made by vehicle
///
/// # Returns
/// Number of transits have been made by vehicle
///
/// # Example
/// ```
/// use micro_traffic_sim_core::agents_types::AgentType;
/// use micro_traffic_sim_core::agents::Vehicle;
/// let mut vehicle = Vehicle::new(1)
/// .with_cell(1)
/// .with_destination(100)
/// .with_type(AgentType::Car)
/// .build();
/// vehicle.transits_made_inc();
/// vehicle.transits_made_inc();
/// println!("Vehicle: {:?}", vehicle);
/// println!("Transits have been made: {:?}", vehicle.get_transits_made()); // Should output 2
/// ```
pub fn get_transits_made(&self) -> u64 {
self.transits_made
}
/// Decrements decrements countdown timer for relaxation in occupied transit cell
///
/// # Returns
/// Nothing
///
/// # Example
/// ```
/// use micro_traffic_sim_core::agents_types::AgentType;
/// use micro_traffic_sim_core::agents::Vehicle;
/// let mut vehicle = Vehicle::new(1)
/// .with_cell(3)
/// .with_destination(100)
/// .with_type(AgentType::Car)
/// .with_transit_cells(vec![3, 8])
/// .with_relax_time(9)
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// vehicle.relax_countdown_dec();
/// ```
pub fn relax_countdown_dec(&mut self) {
self.relax_countdown -= 1;
}
/// Resets resets countdown timer for relaxation (to a value of `RelaxTime“ field) in occupied transit cell
///
/// # Returns
/// Nothing
///
/// # Example
/// ```
/// use micro_traffic_sim_core::agents_types::AgentType;
/// use micro_traffic_sim_core::agents::Vehicle;
/// let mut vehicle = Vehicle::new(1)
/// .with_cell(3)
/// .with_destination(100)
/// .with_type(AgentType::Car)
/// .with_transit_cells(vec![3, 8])
/// .with_relax_time(9)
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// vehicle.relax_countdown_reset();
/// ```
pub fn relax_countdown_reset(&mut self) {
self.relax_countdown = self.relax_time
}
/// Returns number of time units which is remaining for the vehicle to be in occupied transit cell
///
/// # Returns
/// Number of time units which is remaining for the vehicle to be in occupied transit cell
///
/// # Example
/// ```
/// use micro_traffic_sim_core::agents_types::AgentType;
/// use micro_traffic_sim_core::agents::Vehicle;
/// let mut vehicle = Vehicle::new(1)
/// .with_cell(3)
/// .with_destination(100)
/// .with_type(AgentType::Car)
/// .with_transit_cells(vec![3, 8])
/// .with_relax_time(9)
/// .build();
/// vehicle.relax_countdown_dec();
/// vehicle.relax_countdown_dec();
/// println!("Vehicle: {:?}", vehicle);
/// println!("Remaining time units to be in transit cell: {:?}", vehicle.get_relax_countdown()); // Should output 7
/// vehicle.relax_countdown_reset();
/// println!("Remaining time units to be in transit cell: {:?}", vehicle.get_relax_countdown()); // Should output 9
/// ```
pub fn get_relax_countdown(&self) -> i32 {
self.relax_countdown
}
/// Sets the vehicle's intention
///
/// # Arguments
/// * `intention` - The vehicle's intention. See the ref. at `VehicleIntention`
///
/// # Example
/// ```
/// use micro_traffic_sim_core::maneuver::LaneChangeType;
/// use micro_traffic_sim_core::agents_types::AgentType;
/// use micro_traffic_sim_core::agents::{Vehicle, VehicleIntention};
/// let mut vehicle = Vehicle::new(1)
/// .with_cell(3)
/// .with_destination(100)
/// .with_type(AgentType::Car)
/// .build();
/// let mut intention = VehicleIntention::default();
/// intention.intention_maneuver = LaneChangeType::ChangeRight;
/// intention.intention_cell_id = 10;
/// vehicle.set_intention(intention);
/// println!("Vehicle: {:?}", vehicle);
/// ```
pub fn set_intention(&mut self, intention: VehicleIntention) {
self.intention = intention;
}
/// Blocks the vehicle in its current cell with a specified speed.
pub fn block_with_speed(&mut self, speed: i32) {
self.intention.intention_cell_id = self.cell_id;
self.intention.intention_speed = speed;
self.intention.intention_maneuver = LaneChangeType::Block;
self.intention.intermediate_cells = vec![];
}
/// Updates the vehicle's tail maneuver by scanning occupied cells and determining if vehicle is in lane changing process
///
/// # Arguments
/// * `net` - The road network grid
///
/// Returns [`VehicleError::TailCellNotFound`] if a tail cell ID doesn't exist in the grid,
/// or [`VehicleError::InvalidCell`] if a cell ID is invalid.
///
/// # Example
/// ```rust
/// use micro_traffic_sim_core::agents::Vehicle;
/// use micro_traffic_sim_core::grid::road_network::GridRoads;
///
/// let net = GridRoads::new();
/// let mut vehicle = Vehicle::new(1)
/// .with_cell(10)
/// .with_tail_size(2, vec![8, 9])
/// .build();
/// let tail_maneuver = vehicle.scan_tail_maneuver(&net);
/// println!("Tail maneuver: {:?}", tail_maneuver);
/// ```
pub fn scan_tail_maneuver(
&self,
net: &GridRoads,
) -> Result<TailIntentionManeuver, VehicleError> {
if self.tail_cells.is_empty() {
return Ok(TailIntentionManeuver::default());
}
// Scan sequential cells
for (idx, window) in self.tail_cells.windows(2).enumerate() {
let [from_id, to_id] = window else { continue };
if *from_id < 1 {
continue;
}
let from_cell = net
.get_cell(from_id)
.ok_or(VehicleError::TailCellNotFound {
cell_id: *from_id,
position: idx,
vehicle_id: self.id,
})?;
match (*to_id, from_cell) {
(id, _) if id == from_cell.get_forward_id() => continue,
(id, _) if id == from_cell.get_right_id() => {
return Ok(TailIntentionManeuver {
source_cell_maneuver: *from_id,
target_cell_maneuver: *to_id,
intention_maneuver: LaneChangeType::ChangeRight,
})
}
(id, _) if id == from_cell.get_left_id() => {
return Ok(TailIntentionManeuver {
source_cell_maneuver: *from_id,
target_cell_maneuver: *to_id,
intention_maneuver: LaneChangeType::ChangeLeft,
})
}
_ => continue,
}
}
// Check final cell
let last_id = self.tail_cells[self.tail_cells.len() - 1];
if last_id > 0 {
let last_cell = net
.get_cell(&last_id)
.ok_or(VehicleError::TailCellNotFound {
cell_id: last_id,
position: self.tail_cells.len() - 1,
vehicle_id: self.id,
})?;
if self.cell_id == last_cell.get_right_id() {
return Ok(TailIntentionManeuver {
source_cell_maneuver: last_id,
target_cell_maneuver: self.cell_id,
intention_maneuver: LaneChangeType::ChangeRight,
});
}
if self.cell_id == last_cell.get_left_id() {
return Ok(TailIntentionManeuver {
source_cell_maneuver: last_id,
target_cell_maneuver: self.cell_id,
intention_maneuver: LaneChangeType::ChangeLeft,
});
}
}
Ok(TailIntentionManeuver {
source_cell_maneuver: self.cell_id,
target_cell_maneuver: if self.intention.intention_cell_id < 1 {
self.cell_id
} else {
self.intention.intention_cell_id
},
intention_maneuver: self.intention.intention_maneuver,
})
}
/// Applies vehicle's intention to the vehicle's current state
///
/// # Example
/// ```rust
/// use micro_traffic_sim_core::agents::Vehicle;
/// use micro_traffic_sim_core::maneuver::LaneChangeType;
///
/// let mut vehicle = Vehicle::new(1)
/// .with_cell(10)
/// .with_destination(100)
/// .with_speed(1)
/// .build();
///
/// // Set some intention
/// vehicle.intention.intention_speed = 3;
/// vehicle.intention.destination = Some(200);
/// vehicle.intention.confusion = Some(true);
///
/// // Apply the intention
/// vehicle.apply_intention();
///
/// // Now vehicle state is updated
/// assert_eq!(vehicle.speed, 3);
/// assert_eq!(vehicle.destination, 200);
/// assert_eq!(vehicle.confusion, true);
/// ```
pub fn apply_intention(&mut self) {
// No need to update cell_id. It is done in movement.rs
self.speed = self.intention.intention_speed;
// Apply destination if set in intention
if let Some(destination) = self.intention.destination {
self.destination = destination;
}
// Apply confusion state if set in intention
if let Some(confusion) = self.intention.confusion {
self.confusion = confusion;
}
// No need to update tails cells. It is done in movement.rs
}
}
/// A builder pattern implementation for constructing `Vehicle` objects.
///
/// `VehicleBuilder` allows for optional configuration of `Vehicle` fields before building the final `Vehicle` object.
pub struct VehicleBuilder {
vehicle: Vehicle,
}
impl VehicleBuilder {
/// Sets the agent type of the vehicle.
///
/// # Arguments
/// * `typ` - The type of the agent. See the ref. at `AgentType`
///
/// # Returns
/// A `VehicleBuilder` instance for further method chaining.
///
/// # Example
/// ```rust
/// use micro_traffic_sim_core::agents_types::AgentType;
/// use micro_traffic_sim_core::agents::Vehicle;
/// let vehicle = Vehicle::new(1)
/// .with_type(AgentType::Bus)
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// ```
pub fn with_type(mut self, typ: AgentType) -> Self {
self.vehicle.vehicle_type = typ;
self
}
/// Sets the movement strategy for the vehicle.
///
/// # Arguments
/// * `typ` - The behavior type. See the ref. at `BehaviourType`
///
/// # Returns
/// A `VehicleBuilder` instance for further method chaining.
///
/// # Example
/// ```rust
/// use micro_traffic_sim_core::behaviour::BehaviourType;
/// use micro_traffic_sim_core::agents::{Vehicle};
/// let vehicle = Vehicle::new(1)
/// .with_behaviour(BehaviourType::Cooperative)
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// ```
pub fn with_behaviour(mut self, typ: BehaviourType) -> Self {
self.vehicle.strategy_type = typ;
self
}
/// Sets the current cell ID where the vehicle is located.
///
/// # Arguments
/// * `cell` - The ID of the cell where the vehicle is currently positioned.
///
/// # Returns
/// A `VehicleBuilder` instance for further method chaining.
///
/// # Example
/// ```rust
/// use micro_traffic_sim_core::agents::Vehicle;
/// let vehicle = Vehicle::new(1)
/// .with_cell(10)
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// ```
pub fn with_cell(mut self, cell_id: CellID) -> Self {
self.vehicle.cell_id = cell_id;
self
}
/// Sets currently occupied cells by tail (in case when vehicle has size more that one cell).
/// The occupied cells must be provided in order: [furthest from head, ..., closest to head].
///
/// # Arguments
/// * `size` - The size of the vehicle's tail (number of cells behind head).
/// * `cells` - A list of cell IDs currently occupied by the tail.
///
/// # Returns
/// A `VehicleBuilder` instance for further method chaining.
///
/// # Example
/// ```rust
/// use micro_traffic_sim_core::agents::Vehicle;
/// // For head at cell 13 with tail size 2, cell 11 is furthest, cell 12 is closest
/// let vehicle = Vehicle::new(1)
/// .with_cell(13)
/// .with_tail_size(2, vec![11, 12])
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// ```
pub fn with_tail_size(mut self, size: usize, cells: Vec<CellID>) -> Self {
self.vehicle.tail_cells = vec![0; size];
if !cells.is_empty() {
self.vehicle.tail_cells.copy_from_slice(&cells);
}
self
}
/// Sets the current speed of the vehicle.
///
/// # Arguments
/// * `speed` - The speed (in cells per time unit)
///
/// # Returns
/// A `VehicleBuilder` instance for further method chaining.
///
/// # Example
/// ```rust
/// use micro_traffic_sim_core::agents::Vehicle;
/// let vehicle = Vehicle::new(1)
/// .with_speed(5)
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// ```
pub fn with_speed(mut self, speed: i32) -> Self {
self.vehicle.speed = speed;
self
}
/// Sets the speed limit for the vehicle, which is the maximum speed it can travel at.
///
/// # Arguments
/// * `speed_limit` - The speed limit (in cells per time unit)
///
/// # Returns
/// A `VehicleBuilder` instance for further method chaining.
///
/// # Example
/// ```rust
/// use micro_traffic_sim_core::agents::Vehicle;
/// let vehicle = Vehicle::new(1)
/// .with_speed_limit(10)
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// ```
pub fn with_speed_limit(mut self, speed_limit: i32) -> Self {
self.vehicle.speed_limit = speed_limit;
self
}
/// Sets the bearing (direction angle) for the vehicle.
///
/// # Arguments
/// * `bearing` - The bearing in degrees (clockwise angle from the north).
///
/// # Returns
/// A `VehicleBuilder` instance for further method chaining.
///
/// # Example
/// ```rust
/// use micro_traffic_sim_core::agents::Vehicle;
/// let vehicle = Vehicle::new(1)
/// .with_bearing(45.0)
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// ```
pub fn with_bearing(mut self, bearing: f64) -> Self {
self.vehicle.bearing = bearing;
self
}
/// Sets the minimum safe distance (in cells) to the vehicle in front
///
/// # Arguments
/// * `min_safe_distance` - The minimum safe distance (in cells)
///
/// # Returns
/// A `VehicleBuilder` instance for further method chaining.
///
/// # Example
/// ```rust
/// use micro_traffic_sim_core::agents::Vehicle;
/// let vehicle = Vehicle::new(1)
/// .with_min_safe_distance(3)
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// ```
pub fn with_min_safe_distance(mut self, min_safe_distance: i32) -> Self {
self.vehicle.min_safe_distance = min_safe_distance;
self
}
/// Sets final cell for the vehicle's trip
///
/// # Arguments
/// * `cell_id` - Cell's identifier
///
/// # Returns
/// A `VehicleBuilder` instance for further method chaining.
///
/// # Example
/// ```rust
/// use micro_traffic_sim_core::agents::Vehicle;
/// let vehicle = Vehicle::new(1)
/// .with_destination(20)
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// ```
pub fn with_destination(mut self, cell_id: CellID) -> Self {
self.vehicle.destination = cell_id;
self
}
/// Establishes source and target cells of maneuver for the vehicle's tail and vehicle's tail intention maneuver (in case when vehicle has size more that one cell)
///
/// # Arguments
/// * `source_cell` - The ID of the source cell
/// * `target_cell` - The ID of the target cell
/// * `maneuver` - The type of lane change the vehicle's tail is performing. This can be `Left`, `Right`, or `None`. Should not be 'Undefined' (except initialization). See the ref. at `LaneChangeType`
///
/// # Returns
/// A `VehicleBuilder` instance for further method chaining.
///
/// # Example
/// ```rust
/// use micro_traffic_sim_core::agents::Vehicle;
/// use micro_traffic_sim_core::maneuver::LaneChangeType;
/// let vehicle = Vehicle::new(1)
/// .with_tail_intention_maneuver(10, 20, LaneChangeType::ChangeRight)
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// ```
pub fn with_tail_intention_maneuver(
mut self,
source_cell: CellID,
target_cell: CellID,
maneuver: LaneChangeType,
) -> Self {
self.vehicle.intention.tail_maneuver.source_cell_maneuver = source_cell;
self.vehicle.intention.tail_maneuver.target_cell_maneuver = target_cell;
self.vehicle.intention.tail_maneuver.intention_maneuver = maneuver;
self
}
/// Sets whether the vehicle is a conflict participant.
///
/// # Arguments
/// * `is_in_conflict` - A boolean indicating if the vehicle is in a conflict state.
///
/// # Returns
/// A `VehicleBuilder` instance for further method chaining.
///
/// # Example
/// ```rust
/// use micro_traffic_sim_core::agents::Vehicle;
/// let vehicle = Vehicle::new(1)
/// .with_conflict_participation(true)
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// ```
pub fn with_conflict_participation(mut self, is_in_conflict: bool) -> Self {
self.vehicle.is_conflict_participant = is_in_conflict;
self
}
/// Sets corresponding trip identifier
///
/// # Arguments
/// * `trip` - The ID of the trip
///
/// # Returns
/// A `VehicleBuilder` instance for further method chaining.
///
/// # Example
/// ```rust
/// use micro_traffic_sim_core::agents::Vehicle;
/// let vehicle = Vehicle::new(1)
/// .with_trip(12345)
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// ```
pub fn with_trip(mut self, trip_id: TripID) -> Self {
self.vehicle.trip = trip_id;
self
}
/// Sets the cells IDs list in which each cell must be traversed in exact given order by the vehicle
///
/// # Arguments
/// * `cells` - A list of IDs of cells
///
/// # Returns
/// A `VehicleBuilder` instance for further method chaining.
///
/// # Example
/// ```rust
/// use micro_traffic_sim_core::agents::Vehicle;
/// let vehicle = Vehicle::new(1)
/// .with_transit_cells(vec![3, 50, 77])
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// ```
pub fn with_transit_cells(mut self, cells: Vec<CellID>) -> Self {
self.vehicle.transit_cells = cells;
self
}
/// Sets the probability of the vehicle slowing down randomly.
///
/// # Arguments
/// * `p` - A value in (0; 1]. 0 - never slowdowns, 1 - slowdowns every time unit
///
/// # Returns
/// A `VehicleBuilder` instance for further method chaining.
///
/// # Example
/// ```rust
/// use micro_traffic_sim_core::agents::Vehicle;
/// let vehicle = Vehicle::new(1)
/// .with_slowdown(0.5)
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// ```
pub fn with_slowdown(mut self, p: f64) -> Self {
self.vehicle.slow_down_factor = p;
self
}
/// Sets the level of cooperative behavior for the vehicle.
///
/// # Arguments
/// * `level` - A value in (0; 1]
/// `0` being non-cooperative (fully aggressive) and `1` being fully cooperative
///
/// # Returns
/// A `VehicleBuilder` instance for further method chaining.
///
/// # Example
/// ```rust
/// use micro_traffic_sim_core::agents::Vehicle;
/// let vehicle = Vehicle::new(1)
/// .with_cooperative_level(0.4)
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// ```
///
pub fn with_cooperative_level(mut self, level: f64) -> Self {
self.vehicle.cooperativity = level;
self
}
/// Sets the level of aggressive behavior (which is (1.0 - cooperativity) basically) for the vehicle
///
/// # Arguments
/// * `level` - A value in (0; 1]
/// `1` being fully agressive and `1` being non-aggressive (fully cooperative).
///
/// # Returns
/// A `VehicleBuilder` instance for further method chaining.
///
/// # Example
/// ```rust
/// use micro_traffic_sim_core::agents::Vehicle;
/// let vehicle = Vehicle::new(1)
/// .with_aggressive_level(0.8) // So cooperativity becomes 0.2
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// ```
pub fn with_aggressive_level(mut self, level: f64) -> Self {
self.vehicle.cooperativity = 1.0 - level;
self
}
/// Sets the delay time between two possible accelerations vehicle can do. Use it when it is needed
/// to prohibit to the vehicle to do sequential accelerations during simulation.
///
/// # Arguments
/// * `delay` - The delay time (in time units)
///
/// # Returns
/// A `VehicleBuilder` instance for further method chaining.
///
/// # Example
/// ```rust
/// use micro_traffic_sim_core::agents::Vehicle;
/// let vehicle = Vehicle::new(1)
/// .with_acceleration_delay(3)
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// ```
pub fn with_acceleration_delay(mut self, delay: i64) -> Self {
self.vehicle.timer_non_acceleration = delay;
self
}
/// Sets the delay time between two possible maneuvers vehicle can perform. Use it when it is needed
/// to prohibit to the vehicle to perform sequential maneuvers during simulation.
///
/// # Arguments
/// * `delay` - The delay time (in time units)
///
/// # Returns
/// A `VehicleBuilder` instance for further method chaining.
///
/// # Example
/// ```rust
/// use micro_traffic_sim_core::agents::Vehicle;
/// let vehicle = Vehicle::new(1)
/// .with_maneuver_delay(3)
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// ```
pub fn with_maneuver_delay(mut self, delay: i64) -> Self {
self.vehicle.timer_non_maneuvers = delay;
self
}
/// Sets the delay time between two possible slowdowns vehicle can do. Use it when it is needed
/// to prohibit to the vehicle to do sequential slowdowns during simulation.
///
/// # Arguments
/// * `delay` - The delay time (in time units)
///
/// # Returns
/// A `VehicleBuilder` instance for further method chaining.
///
/// # Example
/// ```rust
/// use micro_traffic_sim_core::agents::Vehicle;
/// let vehicle = Vehicle::new(1)
/// .with_slowdown_delay(3)
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// ```
pub fn with_slowdown_delay(mut self, delay: i64) -> Self {
self.vehicle.timer_non_slowdown = delay;
self
}
/// Sets the relaxation time (in time units) in transit cells (in case when they are set)
///
/// # Arguments
/// * `t` - The time (in time units) should be spent at each transit stop.
///
/// # Returns
/// A `VehicleBuilder` instance for further method chaining.
///
/// # Example
/// ```rust
/// use micro_traffic_sim_core::agents::Vehicle;
/// let vehicle = Vehicle::new(1)
/// .with_relax_time(5)
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// ```
pub fn with_relax_time(mut self, t: i32) -> Self {
self.vehicle.relax_time = t;
self.vehicle.relax_countdown = t;
self
}
/// Sets the travel time (in time units) which vehicle has been in movement state.
///
/// # Arguments
/// * `t` - The travel time (in time units).
///
/// # Returns
/// A `VehicleBuilder` instance for further method chaining.
///
/// # Example
/// ```rust
/// use micro_traffic_sim_core::agents::Vehicle;
/// let vehicle = Vehicle::new(1)
/// .with_travel_time(30)
/// .build();
/// println!("Vehicle: {:?}", vehicle);
/// ```
pub fn with_travel_time(mut self, t: i64) -> Self {
self.vehicle.travel_time = t;
self
}
/// Builds the final `Vehicle` object with the configured properties.
///
/// # Returns
/// The fully constructed `Vehicle` object.
pub fn build(self) -> Vehicle {
self.vehicle
}
/// Builds a reference to the `Vehicle` object.
///
/// Obsolete in terms of internal usage (it was used before passing VehiclesStorage
/// to the simulation engine). Could be useful for external usage.
///
/// # Returns
/// A reference to the `Vehicle` object.
pub fn build_ref(self) -> VehicleRef {
Rc::new(RefCell::new(self.vehicle))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_relaxation_countdown() {
let relax_time = 9;
let sim_steps = 3;
let mut vehicle = Vehicle::new(1)
.with_cell(3)
.with_destination(100)
.with_type(AgentType::Car)
.with_transit_cells(vec![3, 8])
.with_relax_time(relax_time)
.build();
for _ in 0..sim_steps {
vehicle.relax_countdown_dec();
}
assert_eq!(
relax_time - sim_steps,
vehicle.get_relax_countdown(),
"Incorrect countdown after specified number of steps"
);
vehicle.relax_countdown_reset();
assert_eq!(
relax_time,
vehicle.get_relax_countdown(),
"Incorrect countdown after reset"
);
}
#[test]
fn test_cooperative_level() {
let coop_level = 0.75;
let aggr_level = 1.0 - coop_level;
let vehicle = Vehicle::new(1).with_aggressive_level(aggr_level).build();
assert_eq!(
coop_level, vehicle.cooperativity,
"Incorrect cooperativity level"
)
}
}