Skip to main content

traaains/sim/
mod.rs

1//! Module containing the main parts of the simulation.
2//!
3//! Systems are stored in modules that best describe their main interest, e.g. system that moves a train's bogies is stored in the [train] module.
4
5use bevy::{
6    app::{Plugin, Update},
7    color::Color,
8    ecs::{
9        component::Component,
10        query::With,
11        schedule::{IntoScheduleConfigs, common_conditions::resource_exists_and_equals},
12        system::{Query, Res},
13    },
14    gizmos::gizmos::Gizmos,
15    math::Isometry2d,
16    time::Time,
17    transform::components::Transform,
18};
19
20use crate::{
21    game::pausing::IsPaused,
22    sim::{
23        track::pos::update_on_track_pos,
24        train::{
25            Bogie,
26            systems::{
27                apply_brakes, move_carriages_to_bogies, move_on_rail_to_diff_segment,
28                move_trains_with_velocity, update_trains_acceleration,
29            },
30        },
31    },
32};
33
34pub mod driver;
35pub mod logical_graph;
36pub mod signal;
37pub mod track;
38pub mod train;
39
40const GRAVITY: f32 = 9.81;
41const STEEL_SLIP: f32 = 0.3;
42
43#[derive(Clone, Component, Default)]
44pub struct Controls {
45    pub throttle: f32,
46    pub brake: f32,
47}
48
49#[derive(Clone, Component, Debug, Default)]
50#[require(Velocity)]
51pub struct Acceleration(pub f32);
52
53#[derive(Clone, Component, Debug, Default)]
54pub struct Velocity(pub f32);
55
56pub fn integrate_acceleration(mut q_acc: Query<(&mut Velocity, &Acceleration)>, time: Res<Time>) {
57    q_acc.par_iter_mut().for_each(|(mut vel, acc)| {
58        vel.0 += acc.0 * time.delta_secs();
59    });
60}
61
62pub struct SimPlugin;
63
64impl Plugin for SimPlugin {
65    fn build(&self, app: &mut bevy::app::App) {
66        app.add_systems(
67            Update,
68            (
69                update_trains_acceleration,
70                apply_brakes,
71                integrate_acceleration,
72                move_trains_with_velocity,
73                update_on_track_pos,
74                move_carriages_to_bogies,
75            )
76                .chain()
77                .run_if(resource_exists_and_equals(IsPaused(false))),
78        )
79        .add_systems(Update, move_on_rail_to_diff_segment)
80        .add_systems(
81            Update,
82            |q_bogies: Query<&Transform, With<Bogie>>, mut gizmos: Gizmos| {
83                for b in q_bogies {
84                    gizmos.circle_2d(
85                        Isometry2d::from_translation(b.translation.truncate()),
86                        0.5,
87                        Color::srgb(1.0, 0.5, 0.0),
88                    );
89                }
90            },
91        );
92    }
93}