1use crate::{
4 collision::Aabb2,
5 input::{Action, Input},
6};
7use glam::Vec2;
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
11pub struct UiId(pub u64);
12
13#[derive(Clone, Copy, Debug)]
16pub struct UiRegion {
17 pub id: UiId,
19 pub bounds: Aabb2,
21 pub enabled: bool,
23 pub focusable: bool,
25 pub draggable: bool,
27}
28
29impl UiRegion {
30 pub fn new(id: UiId, bounds: Aabb2) -> Self {
32 Self {
33 id,
34 bounds,
35 enabled: true,
36 focusable: true,
37 draggable: false,
38 }
39 }
40}
41
42#[derive(Clone, Copy, Debug)]
44pub struct UiActions {
45 pub primary: Action,
47 pub next: Action,
49 pub previous: Action,
51 pub activate: Action,
53 pub cancel: Action,
55}
56
57#[derive(Clone, Copy, Debug, Default)]
59pub struct UiButton {
60 pub down: bool,
62 pub pressed: bool,
64 pub released: bool,
66}
67
68#[derive(Clone, Copy, Debug, Default)]
71pub struct UiInput {
72 pub pointer: Option<Vec2>,
74 pub primary: UiButton,
76 pub next: bool,
78 pub previous: bool,
80 pub activate: bool,
82 pub cancel: bool,
84 pub window_focused: bool,
86}
87
88impl UiInput {
89 pub fn from_actions(
92 input: &Input,
93 pointer: Option<Vec2>,
94 actions: UiActions,
95 window_focused: bool,
96 ) -> Self {
97 Self {
98 pointer,
99 primary: UiButton {
100 down: input.down(actions.primary),
101 pressed: input.pressed(actions.primary),
102 released: input.released(actions.primary),
103 },
104 next: input.pressed(actions.next),
105 previous: input.pressed(actions.previous),
106 activate: input.pressed(actions.activate),
107 cancel: input.pressed(actions.cancel),
108 window_focused: window_focused && !input.reset_pending(),
109 }
110 }
111}
112
113#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
116pub struct UiCapture {
117 pub pointer: bool,
119 pub keyboard: bool,
121}
122
123#[derive(Clone, Copy, Debug)]
125pub struct UiResponse {
126 pub id: UiId,
128 pub enabled: bool,
130 pub hovered: bool,
132 pub focused: bool,
134 pub pressed: bool,
136 pub held: bool,
138 pub released: bool,
140 pub activated: bool,
142 pub drag_started: bool,
144 pub drag_delta: Vec2,
146 pub drag_total: Vec2,
148 pub drag_ended: bool,
150 pub cancelled: bool,
152}
153
154impl UiResponse {
155 fn new(id: UiId, enabled: bool) -> Self {
156 Self {
157 id,
158 enabled,
159 hovered: false,
160 focused: false,
161 pressed: false,
162 held: false,
163 released: false,
164 activated: false,
165 drag_started: false,
166 drag_delta: Vec2::ZERO,
167 drag_total: Vec2::ZERO,
168 drag_ended: false,
169 cancelled: false,
170 }
171 }
172}
173
174#[derive(Clone, Copy)]
175struct Active {
176 id: UiId,
177 draggable: bool,
178 origin: Vec2,
179 last: Vec2,
180}
181
182#[derive(Default)]
186pub struct UiState {
187 focus: Option<UiId>,
188 active: Option<Active>,
189 responses: Vec<UiResponse>,
190}
191
192impl UiState {
193 pub fn with_capacity(regions: usize) -> Self {
195 Self {
196 responses: Vec::with_capacity(regions.saturating_add(1)),
197 ..Self::default()
198 }
199 }
200
201 pub fn focused(&self) -> Option<UiId> {
203 self.focus
204 }
205
206 pub fn response(&self, id: UiId) -> Option<&UiResponse> {
209 self.responses.iter().find(|response| response.id == id)
210 }
211
212 pub fn responses(&self) -> &[UiResponse] {
214 &self.responses
215 }
216
217 pub fn update(&mut self, regions: &[UiRegion], input: UiInput) -> UiCapture {
222 debug_assert!(
223 regions
224 .iter()
225 .enumerate()
226 .all(|(i, r)| regions[..i].iter().all(|other| other.id != r.id)),
227 "UI region IDs must be unique"
228 );
229 self.responses.clear();
230 self.responses
231 .extend(regions.iter().map(|r| UiResponse::new(r.id, r.enabled)));
232 let had_focus = self.focus.is_some();
233 let had_active = self.active.is_some();
234 if self.focus.is_some_and(|id| {
235 !regions
236 .iter()
237 .any(|r| r.id == id && r.enabled && r.focusable)
238 }) {
239 self.focus = None;
240 }
241 let invalid_active = self
242 .active
243 .is_some_and(|a| !regions.iter().any(|r| r.id == a.id && r.enabled));
244 if (invalid_active || !input.window_focused || input.cancel)
245 && let Some(active) = self.active.take()
246 {
247 if self.response(active.id).is_none() {
248 self.responses.push(UiResponse::new(active.id, false));
249 }
250 let response = self.response_mut(active.id);
251 response.released = true;
252 response.cancelled = true;
253 response.drag_ended = active.draggable;
254 response.drag_total = active.last - active.origin;
255 }
256 if !input.window_focused || input.cancel {
257 self.focus = None;
258 }
259 if !input.window_focused {
260 return UiCapture {
261 pointer: had_active,
262 keyboard: had_focus,
263 };
264 }
265 let pointer = input.pointer.filter(|p| p.is_finite());
266 let hovered = pointer.and_then(|p| regions.iter().rposition(|r| r.bounds.contains(p)));
267 if !input.cancel && self.active.is_none() && input.next != input.previous {
268 let current = self
269 .focus
270 .and_then(|id| regions.iter().position(|r| r.id == id));
271 let count = regions.len();
272 for offset in 0..count {
273 let index = if input.next {
274 current.map_or(offset, |i| (i + 1 + offset) % count)
275 } else {
276 current.map_or(count - 1 - offset, |i| (i + count - 1 - offset) % count)
277 };
278 if regions[index].enabled && regions[index].focusable {
279 self.focus = Some(regions[index].id);
280 break;
281 }
282 }
283 }
284 if !input.cancel && input.primary.pressed && self.active.is_none() {
285 self.focus = None;
286 if let Some(index) = hovered.filter(|&i| regions[i].enabled) {
287 let region = regions[index];
288 if region.focusable {
289 self.focus = Some(region.id);
290 }
291 let position = pointer.expect("hover requires a pointer");
292 self.active = Some(Active {
293 id: region.id,
294 draggable: region.draggable,
295 origin: position,
296 last: position,
297 });
298 let response = self.response_mut(region.id);
299 response.pressed = true;
300 response.drag_started = region.draggable;
301 }
302 }
303 if let Some(mut active) = self.active {
304 let response = self.response_mut(active.id);
305 response.held = input.primary.down;
306 if active.draggable {
307 if let Some(position) = pointer {
308 response.drag_delta = position - active.last;
309 active.last = position;
310 }
311 response.drag_total = active.last - active.origin;
312 }
313 if input.primary.released || !input.primary.down {
314 response.released = true;
315 response.held = false;
316 response.drag_ended = active.draggable;
317 response.cancelled = !input.primary.released;
318 response.activated = !active.draggable
319 && input.primary.released
320 && hovered.is_some_and(|i| regions[i].id == active.id);
321 self.active = None;
322 } else {
323 self.active = Some(active);
324 }
325 }
326 if !input.cancel
327 && !input.primary.pressed
328 && self.active.is_none()
329 && input.activate
330 && let Some(id) = self.focus
331 {
332 self.response_mut(id).activated = true;
334 }
335 if let Some(index) = hovered {
336 self.responses[index].hovered = true;
337 }
338 if let Some(id) = self.focus {
339 self.response_mut(id).focused = true;
340 }
341 UiCapture {
342 pointer: hovered.is_some() || had_active || self.active.is_some(),
343 keyboard: self.focus.is_some() || (had_focus && input.cancel),
344 }
345 }
346
347 fn response_mut(&mut self, id: UiId) -> &mut UiResponse {
348 self.responses
349 .iter_mut()
350 .find(|r| r.id == id)
351 .expect("active/focused region has a response")
352 }
353}
354
355#[cfg(test)]
356mod tests;