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
use std::fmt;

use bevy::{
    input::{
        mouse::{MouseButtonInput, MouseMotion},
        ButtonState,
    },
    prelude::*,
    window::PrimaryWindow,
};
use de_camera::MoveFocusEvent;
use de_core::{gamestate::GameState, schedule::InputSchedule};
use de_map::size::MapBounds;

use super::nodes::MinimapNode;
use crate::{
    commands::{CommandsSet, DeliveryLocationSelectedEvent, SendSelectedEvent},
    hud::HudNodes,
};

pub(super) struct InteractionPlugin;

impl Plugin for InteractionPlugin {
    fn build(&self, app: &mut App) {
        app.add_event::<MinimapPressEvent>()
            .add_event::<MinimapDragEvent>()
            .insert_resource(DraggingButtons(Vec::new()))
            .add_systems(
                InputSchedule,
                (
                    press_handler
                        .in_set(InteractionSet::PressHandler)
                        .run_if(on_event::<MouseButtonInput>()),
                    drag_handler
                        .in_set(InteractionSet::DragHandler)
                        .after(InteractionSet::PressHandler)
                        .run_if(on_event::<MouseMotion>()),
                    move_camera_system
                        .after(InteractionSet::PressHandler)
                        .after(InteractionSet::DragHandler),
                    send_units_system
                        .after(InteractionSet::PressHandler)
                        .before(CommandsSet::SendSelected),
                    delivery_location_system
                        .after(InteractionSet::PressHandler)
                        .before(CommandsSet::DeliveryLocation),
                )
                    .run_if(in_state(GameState::Playing)),
            );
    }
}

#[derive(Copy, Clone, Hash, Debug, PartialEq, Eq, SystemSet)]
enum InteractionSet {
    PressHandler,
    DragHandler,
}

#[derive(Event)]
struct MinimapPressEvent {
    button: MouseButton,
    position: Vec2,
}

impl MinimapPressEvent {
    fn new(button: MouseButton, position: Vec2) -> Self {
        Self { button, position }
    }

    fn button(&self) -> MouseButton {
        self.button
    }

    /// Position on the map in 2D flat coordinates (these are not minimap
    /// coordinates).
    fn position(&self) -> Vec2 {
        self.position
    }
}

impl fmt::Debug for MinimapPressEvent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?} -> {:?}", self.button, self.position)
    }
}

#[derive(Event)]
struct MinimapDragEvent {
    button: MouseButton,
    position: Vec2,
}

impl MinimapDragEvent {
    fn new(button: MouseButton, position: Vec2) -> Self {
        Self { button, position }
    }

    fn button(&self) -> MouseButton {
        self.button
    }

    /// Position on the map in 2D flat coordinates (these are not minimap
    /// coordinates).
    fn position(&self) -> Vec2 {
        self.position
    }
}

#[derive(Resource, Deref, DerefMut)]
struct DraggingButtons(Vec<MouseButton>);

fn press_handler(
    window_query: Query<&Window, With<PrimaryWindow>>,
    mut input_events: EventReader<MouseButtonInput>,
    hud: HudNodes<With<MinimapNode>>,
    bounds: Res<MapBounds>,
    mut dragging: ResMut<DraggingButtons>,
    mut press_events: EventWriter<MinimapPressEvent>,
) {
    let cursor = window_query.single().cursor_position();

    for event in input_events.read() {
        match event.state {
            ButtonState::Released => {
                dragging.retain(|b| *b != event.button);
                continue;
            }
            ButtonState::Pressed => (),
        }

        let Some(cursor) = cursor else {
            continue;
        };

        if let Some(mut relative) = hud.relative_position(cursor) {
            dragging.push(event.button);
            relative.y = 1. - relative.y;
            let event = MinimapPressEvent::new(event.button, bounds.rel_to_abs(relative));
            info!("Sending minimap press event {event:?}.");
            press_events.send(event);
        }
    }
}

fn drag_handler(
    window_query: Query<&Window, With<PrimaryWindow>>,
    hud: HudNodes<With<MinimapNode>>,
    bounds: Res<MapBounds>,
    dragging: Res<DraggingButtons>,
    mut drag_events: EventWriter<MinimapDragEvent>,
) {
    if dragging.is_empty() {
        return;
    }

    let Some(cursor) = window_query.single().cursor_position() else {
        return;
    };

    if let Some(relative) = hud.relative_position(cursor) {
        let proportional = Vec2::new(relative.x, 1. - relative.y);
        let world = bounds.rel_to_abs(proportional);

        for button in &**dragging {
            let event = MinimapDragEvent::new(*button, world);
            drag_events.send(event);
        }
    }
}

fn move_camera_system(
    mut press_events: EventReader<MinimapPressEvent>,
    mut drag_events: EventReader<MinimapDragEvent>,
    mut camera_events: EventWriter<MoveFocusEvent>,
) {
    for press in press_events.read() {
        if press.button() != MouseButton::Left {
            continue;
        }

        let event = MoveFocusEvent::new(press.position());
        camera_events.send(event);
    }

    for drag in drag_events.read() {
        if drag.button() != MouseButton::Left {
            continue;
        }

        let event = MoveFocusEvent::new(drag.position());
        camera_events.send(event);
    }
}

fn send_units_system(
    mut press_events: EventReader<MinimapPressEvent>,
    mut send_events: EventWriter<SendSelectedEvent>,
) {
    for press in press_events.read() {
        if press.button() != MouseButton::Right {
            continue;
        }
        send_events.send(SendSelectedEvent::new(press.position()));
    }
}

fn delivery_location_system(
    mut press_events: EventReader<MinimapPressEvent>,
    mut location_events: EventWriter<DeliveryLocationSelectedEvent>,
) {
    for press in press_events.read() {
        if press.button() != MouseButton::Right {
            continue;
        }
        location_events.send(DeliveryLocationSelectedEvent::new(press.position()));
    }
}