Skip to main content

traaains/editor/track/
removing.rs

1//! Takes care of the removing functionality of the track editor.
2//!
3//! Listens for pointer presses on track segments and removes the segments in the event of one, using the [RemoveSegment] command,
4//! which takes care of also removing node's and logical block's connections.
5
6use bevy::{
7    app::Plugin,
8    ecs::{
9        component::Component,
10        entity::Entity,
11        event::EntityEvent,
12        observer::{Observer, On},
13        query::With,
14        system::{Commands, Query, Single},
15    },
16    picking::events::PointerPress,
17    state::state::{OnEnter, OnExit},
18    ui::widget::Text,
19};
20
21use crate::{
22    editor::{StateText, track::TrackEditorState},
23    sim::track::segment::{TrackSegment, commands::RemoveSegment},
24};
25
26/// Marker component for the observers in this editor.
27#[derive(Component)]
28struct RemovingTrackObserver;
29
30/// Removes segments on pointer press. Relies on the [RemoveSegment] command.
31fn on_segment_press(
32    e: On<PointerPress>,
33    mut cmd: Commands,
34    mut q_segments: Query<Entity, With<TrackSegment>>,
35) {
36    // only target segments
37    let Ok(ts) = q_segments.get_mut(e.event_target()) else {
38        return;
39    };
40
41    cmd.queue(RemoveSegment::new(ts));
42}
43
44fn on_enter_removing(mut cmd: Commands, mut text: Single<&mut Text, With<StateText>>) {
45    cmd.spawn((RemovingTrackObserver, Observer::new(on_segment_press)));
46
47    text.0 = String::from("Removing\n[0] Place tracks\nEsc to exit");
48}
49
50fn on_leave_removing(mut cmd: Commands, q_observers: Query<Entity, With<RemovingTrackObserver>>) {
51    q_observers
52        .into_iter()
53        .for_each(|e| cmd.entity(e).despawn())
54}
55
56pub struct RemovingPlugin;
57
58impl Plugin for RemovingPlugin {
59    fn build(&self, app: &mut bevy::app::App) {
60        app.add_systems(OnEnter(TrackEditorState::Removing), on_enter_removing)
61            .add_systems(OnExit(TrackEditorState::Removing), on_leave_removing);
62    }
63}