770 lines
24 KiB
Rust
770 lines
24 KiB
Rust
use std::collections::HashMap;
|
|
use std::hash::{Hash, Hasher};
|
|
|
|
use winit::event::{ElementState, KeyEvent, MouseButton, MouseScrollDelta, WindowEvent};
|
|
use winit::keyboard::{Key as WinitKey, NamedKey};
|
|
|
|
use crate::engine::types::{Pos2, Rect, Vec2};
|
|
|
|
/// Strict Z-order rendering & hit-testing layers:
|
|
/// `Base < Drawer < Popover < Modal < Titlebar`.
|
|
/// Higher layers block pointer hover, clicks, and wheel scroll on lower layers!
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
|
|
#[repr(usize)]
|
|
pub enum ZLayer {
|
|
#[default]
|
|
Base = 0,
|
|
Drawer = 1,
|
|
Popover = 2,
|
|
Modal = 3,
|
|
Titlebar = 4,
|
|
}
|
|
|
|
impl ZLayer {
|
|
pub const COUNT: usize = 5;
|
|
pub const ALL: [ZLayer; 5] = [
|
|
ZLayer::Base,
|
|
ZLayer::Drawer,
|
|
ZLayer::Popover,
|
|
ZLayer::Modal,
|
|
ZLayer::Titlebar,
|
|
];
|
|
|
|
#[inline]
|
|
pub const fn index(self) -> usize {
|
|
self as usize
|
|
}
|
|
}
|
|
|
|
/// Fast deterministic widget identifier (FNV-1a 64-bit hash).
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
|
|
pub struct WidgetId(pub u64);
|
|
|
|
impl WidgetId {
|
|
#[inline]
|
|
pub fn new(source: impl Hash) -> Self {
|
|
let mut h = Fnv1aHasher::default();
|
|
source.hash(&mut h);
|
|
Self(h.finish())
|
|
}
|
|
|
|
#[inline]
|
|
pub fn from_pair(a: impl Hash, b: impl Hash) -> Self {
|
|
let mut h = Fnv1aHasher::default();
|
|
a.hash(&mut h);
|
|
0x9E37_79B9_7F4A_7C15u64.hash(&mut h);
|
|
b.hash(&mut h);
|
|
Self(h.finish())
|
|
}
|
|
|
|
#[inline]
|
|
pub fn with(self, child: impl Hash) -> Self {
|
|
let mut h = Fnv1aHasher(self.0);
|
|
0x517C_C1B7_2722_0A95u64.hash(&mut h);
|
|
child.hash(&mut h);
|
|
Self(h.finish())
|
|
}
|
|
}
|
|
|
|
#[derive(Default)]
|
|
struct Fnv1aHasher(u64);
|
|
|
|
impl Hasher for Fnv1aHasher {
|
|
#[inline]
|
|
fn finish(&self) -> u64 {
|
|
if self.0 == 0 {
|
|
0xCBF2_9CE4_8422_2325
|
|
} else {
|
|
self.0
|
|
}
|
|
}
|
|
|
|
#[inline]
|
|
fn write(&mut self, bytes: &[u8]) {
|
|
let mut hash = if self.0 == 0 {
|
|
0xCBF2_9CE4_8422_2325u64
|
|
} else {
|
|
self.0
|
|
};
|
|
for &b in bytes {
|
|
hash ^= b as u64;
|
|
hash = hash.wrapping_mul(0x0000_0100_0000_01B3);
|
|
}
|
|
self.0 = hash;
|
|
}
|
|
}
|
|
|
|
/// Clean egui-free keyboard key enum translated from `winit::keyboard::Key`.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
|
pub enum Key {
|
|
Enter,
|
|
Escape,
|
|
Backspace,
|
|
Delete,
|
|
Tab,
|
|
Space,
|
|
ArrowLeft,
|
|
ArrowRight,
|
|
ArrowUp,
|
|
ArrowDown,
|
|
Home,
|
|
End,
|
|
PageUp,
|
|
PageDown,
|
|
MediaPlayPause,
|
|
MediaNext,
|
|
MediaPrev,
|
|
MediaStop,
|
|
F1,
|
|
F2,
|
|
F3,
|
|
F4,
|
|
F5,
|
|
F6,
|
|
F7,
|
|
F8,
|
|
F9,
|
|
F10,
|
|
F11,
|
|
F12,
|
|
Char(char),
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
|
pub struct Modifiers {
|
|
pub ctrl: bool,
|
|
pub shift: bool,
|
|
pub alt: bool,
|
|
pub super_key: bool,
|
|
}
|
|
|
|
impl Modifiers {
|
|
/// Platform command modifier (`Ctrl` on Windows/Linux, `Cmd` on macOS).
|
|
#[inline]
|
|
pub const fn command(self) -> bool {
|
|
#[cfg(target_os = "macos")]
|
|
{
|
|
self.super_key
|
|
}
|
|
#[cfg(not(target_os = "macos"))]
|
|
{
|
|
self.ctrl
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct KeyPress {
|
|
pub key: Key,
|
|
pub modifiers: Modifiers,
|
|
pub text: Option<String>,
|
|
pub repeat: bool,
|
|
}
|
|
|
|
/// Result of hit-testing a widget rect on the current `ZLayer`.
|
|
#[derive(Debug, Clone, Copy, Default)]
|
|
pub struct Interaction {
|
|
pub rect: Rect,
|
|
pub hovered: bool,
|
|
pub pressed: bool,
|
|
pub clicked: bool,
|
|
pub double_clicked: bool,
|
|
pub right_clicked: bool,
|
|
pub dragged: bool,
|
|
pub drag_started: bool,
|
|
pub drag_stopped: bool,
|
|
pub drag_delta: Vec2,
|
|
}
|
|
|
|
impl Interaction {
|
|
#[inline]
|
|
pub fn any_click(&self) -> bool {
|
|
self.clicked || self.double_clicked || self.right_clicked
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy)]
|
|
struct LayerBlocker {
|
|
layer: ZLayer,
|
|
rect: Rect,
|
|
}
|
|
|
|
/// Per-frame translated winit 0.30 input state with Z-layered hit-testing,
|
|
/// drag tracking, double-click detection, keyboard/text events, and focus management.
|
|
pub struct InputState {
|
|
pub pointer_pos: Option<Pos2>,
|
|
pub pointer_delta: Vec2,
|
|
|
|
pub left_down: bool,
|
|
pub left_pressed: bool,
|
|
pub left_released: bool,
|
|
pub left_double_clicked: bool,
|
|
|
|
pub right_down: bool,
|
|
pub right_pressed: bool,
|
|
pub right_released: bool,
|
|
|
|
pub wheel_delta: Vec2,
|
|
pub modifiers: Modifiers,
|
|
pub key_events: Vec<KeyPress>,
|
|
pub text_input: String,
|
|
|
|
pub focused_id: Option<WidgetId>,
|
|
pub active_id: Option<WidgetId>,
|
|
pub drag_origin: Option<Pos2>,
|
|
pub is_dragging: bool,
|
|
|
|
pub window_focused: bool,
|
|
pub scale_factor: f32,
|
|
pub screen_size: Vec2,
|
|
pub time: f64,
|
|
pub dt: f32,
|
|
|
|
last_click_time: f64,
|
|
last_click_pos: Pos2,
|
|
prev_blockers: Vec<LayerBlocker>,
|
|
curr_blockers: Vec<LayerBlocker>,
|
|
}
|
|
|
|
impl Default for InputState {
|
|
fn default() -> Self {
|
|
Self::new()
|
|
}
|
|
}
|
|
|
|
impl InputState {
|
|
pub fn new() -> Self {
|
|
Self {
|
|
pointer_pos: None,
|
|
pointer_delta: Vec2::ZERO,
|
|
left_down: false,
|
|
left_pressed: false,
|
|
left_released: false,
|
|
left_double_clicked: false,
|
|
right_down: false,
|
|
right_pressed: false,
|
|
right_released: false,
|
|
wheel_delta: Vec2::ZERO,
|
|
modifiers: Modifiers::default(),
|
|
key_events: Vec::with_capacity(8),
|
|
text_input: String::new(),
|
|
focused_id: None,
|
|
active_id: None,
|
|
drag_origin: None,
|
|
is_dragging: false,
|
|
window_focused: true,
|
|
scale_factor: 1.0,
|
|
screen_size: Vec2::new(1280.0, 800.0),
|
|
time: 0.0,
|
|
dt: 1.0 / 60.0,
|
|
last_click_time: -10.0,
|
|
last_click_pos: Pos2::new(-1000.0, -1000.0),
|
|
prev_blockers: Vec::with_capacity(16),
|
|
curr_blockers: Vec::with_capacity(16),
|
|
}
|
|
}
|
|
|
|
/// Translate a `winit 0.30` `WindowEvent` into engine input state.
|
|
/// Returns `true` if the UI should repaint.
|
|
pub fn handle_winit_event(&mut self, event: &WindowEvent) -> bool {
|
|
let sf = self.scale_factor.max(0.5);
|
|
match event {
|
|
WindowEvent::CursorMoved { position, .. } => {
|
|
let next = Pos2::new(position.x as f32 / sf, position.y as f32 / sf);
|
|
if let Some(prev) = self.pointer_pos {
|
|
self.pointer_delta = self.pointer_delta + (next - prev);
|
|
}
|
|
self.pointer_pos = Some(next);
|
|
if self.left_down {
|
|
if let Some(origin) = self.drag_origin {
|
|
if origin.distance(next) >= 5.0 {
|
|
self.is_dragging = true;
|
|
}
|
|
}
|
|
}
|
|
true
|
|
}
|
|
WindowEvent::CursorLeft { .. } => {
|
|
self.pointer_pos = None;
|
|
true
|
|
}
|
|
WindowEvent::MouseInput { state, button, .. } => {
|
|
let is_down = *state == ElementState::Pressed;
|
|
match button {
|
|
MouseButton::Left => {
|
|
if is_down {
|
|
self.left_down = true;
|
|
self.left_pressed = true;
|
|
let pos = self.pointer_pos.unwrap_or(Pos2::ZERO);
|
|
self.drag_origin = Some(pos);
|
|
self.is_dragging = false;
|
|
if (self.time - self.last_click_time) <= 0.35
|
|
&& pos.distance(self.last_click_pos) <= 6.0
|
|
{
|
|
self.left_double_clicked = true;
|
|
self.last_click_time = -10.0;
|
|
} else {
|
|
self.last_click_time = self.time;
|
|
self.last_click_pos = pos;
|
|
}
|
|
} else {
|
|
self.left_down = false;
|
|
self.left_released = true;
|
|
}
|
|
true
|
|
}
|
|
MouseButton::Right => {
|
|
if is_down {
|
|
self.right_down = true;
|
|
self.right_pressed = true;
|
|
} else {
|
|
self.right_down = false;
|
|
self.right_released = true;
|
|
}
|
|
true
|
|
}
|
|
_ => false,
|
|
}
|
|
}
|
|
WindowEvent::MouseWheel { delta, .. } => {
|
|
match delta {
|
|
MouseScrollDelta::LineDelta(dx, dy) => {
|
|
self.wheel_delta.x += *dx * 42.0;
|
|
self.wheel_delta.y += *dy * 42.0;
|
|
}
|
|
MouseScrollDelta::PixelDelta(pos) => {
|
|
self.wheel_delta.x += pos.x as f32 / sf;
|
|
self.wheel_delta.y += pos.y as f32 / sf;
|
|
}
|
|
}
|
|
true
|
|
}
|
|
WindowEvent::ModifiersChanged(mods) => {
|
|
let s = mods.state();
|
|
self.modifiers = Modifiers {
|
|
ctrl: s.control_key(),
|
|
shift: s.shift_key(),
|
|
alt: s.alt_key(),
|
|
super_key: s.super_key(),
|
|
};
|
|
false
|
|
}
|
|
WindowEvent::KeyboardInput { event, .. } => self.handle_key_event(event),
|
|
WindowEvent::Focused(focused) => {
|
|
self.window_focused = *focused;
|
|
if !focused {
|
|
self.left_down = false;
|
|
self.right_down = false;
|
|
self.active_id = None;
|
|
self.is_dragging = false;
|
|
self.modifiers = Modifiers::default();
|
|
}
|
|
true
|
|
}
|
|
WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
|
|
self.scale_factor = *scale_factor as f32;
|
|
true
|
|
}
|
|
WindowEvent::Resized(size) => {
|
|
self.screen_size = Vec2::new(size.width as f32 / sf, size.height as f32 / sf);
|
|
true
|
|
}
|
|
_ => false,
|
|
}
|
|
}
|
|
|
|
fn handle_key_event(&mut self, event: &KeyEvent) -> bool {
|
|
if event.state != ElementState::Pressed {
|
|
return false;
|
|
}
|
|
let key_opt = translate_winit_key(&event.logical_key);
|
|
let text_opt = event.text.as_ref().map(|s| s.to_string()).filter(|s| {
|
|
!s.is_empty() && !self.modifiers.ctrl && !self.modifiers.alt && !self.modifiers.super_key
|
|
});
|
|
|
|
if let Some(ref txt) = text_opt {
|
|
for ch in txt.chars() {
|
|
if !ch.is_control() {
|
|
self.text_input.push(ch);
|
|
}
|
|
}
|
|
}
|
|
|
|
if let Some(key) = key_opt {
|
|
self.key_events.push(KeyPress {
|
|
key,
|
|
modifiers: self.modifiers,
|
|
text: text_opt,
|
|
repeat: event.repeat,
|
|
});
|
|
return true;
|
|
}
|
|
text_opt.is_some()
|
|
}
|
|
|
|
/// Call at the start of every UI frame.
|
|
pub fn begin_frame(&mut self, screen_size: Vec2, scale_factor: f32, time: f64) {
|
|
let prev_time = self.time;
|
|
self.time = time;
|
|
self.dt = if prev_time > 0.0 && time > prev_time {
|
|
((time - prev_time) as f32).clamp(0.001, 0.033)
|
|
} else {
|
|
1.0 / 60.0
|
|
};
|
|
self.screen_size = screen_size;
|
|
self.scale_factor = scale_factor.max(0.5);
|
|
std::mem::swap(&mut self.prev_blockers, &mut self.curr_blockers);
|
|
self.curr_blockers.clear();
|
|
}
|
|
|
|
/// Call at the end of every UI frame to clear single-frame edge flags.
|
|
pub fn end_frame(&mut self) {
|
|
if self.left_released {
|
|
self.active_id = None;
|
|
self.drag_origin = None;
|
|
self.is_dragging = false;
|
|
}
|
|
self.pointer_delta = Vec2::ZERO;
|
|
self.left_pressed = false;
|
|
self.left_released = false;
|
|
self.left_double_clicked = false;
|
|
self.right_pressed = false;
|
|
self.right_released = false;
|
|
self.wheel_delta = Vec2::ZERO;
|
|
self.key_events.clear();
|
|
self.text_input.clear();
|
|
}
|
|
|
|
/// Register an opaque hit-blocking region on `layer` (e.g. Popover, Modal, Drawer, Titlebar).
|
|
/// Prevents lower layers from receiving hover, click, or wheel events underneath `rect`.
|
|
#[inline]
|
|
pub fn register_blocker(&mut self, layer: ZLayer, rect: Rect) {
|
|
if !rect.is_empty() {
|
|
self.curr_blockers.push(LayerBlocker { layer, rect });
|
|
}
|
|
}
|
|
|
|
/// Returns `true` if `pos` is covered by an opaque surface on any layer strictly above `layer`.
|
|
pub fn is_blocked_at(&self, layer: ZLayer, pos: Pos2) -> bool {
|
|
self.prev_blockers
|
|
.iter()
|
|
.chain(self.curr_blockers.iter())
|
|
.any(|b| b.layer > layer && b.rect.contains(pos))
|
|
}
|
|
|
|
/// Returns `true` if pointer is inside `rect` (intersected with optional `clip`) and not blocked by a higher layer.
|
|
pub fn is_hovered_in(&self, layer: ZLayer, rect: Rect, clip: Option<Rect>) -> bool {
|
|
let Some(pos) = self.pointer_pos else {
|
|
return false;
|
|
};
|
|
let hit_rect = match clip {
|
|
Some(c) if !c.is_empty() => rect.intersect(c),
|
|
_ => rect,
|
|
};
|
|
if !hit_rect.contains(pos) {
|
|
return false;
|
|
}
|
|
!self.is_blocked_at(layer, pos)
|
|
}
|
|
|
|
/// Perform full Z-layered interaction testing for widget `id` at `rect`.
|
|
pub fn interact(&mut self, id: WidgetId, layer: ZLayer, rect: Rect, clip: Option<Rect>) -> Interaction {
|
|
let hovered = self.is_hovered_in(layer, rect, clip);
|
|
let mut pressed = false;
|
|
let mut clicked = false;
|
|
let mut double_clicked = false;
|
|
let mut right_clicked = false;
|
|
let mut dragged = false;
|
|
let mut drag_started = false;
|
|
let mut drag_stopped = false;
|
|
let mut drag_delta = Vec2::ZERO;
|
|
|
|
if hovered && self.left_pressed {
|
|
self.active_id = Some(id);
|
|
if self.left_double_clicked {
|
|
double_clicked = true;
|
|
}
|
|
}
|
|
|
|
if hovered && self.right_pressed {
|
|
right_clicked = true;
|
|
}
|
|
|
|
if self.active_id == Some(id) {
|
|
if self.left_down {
|
|
pressed = true;
|
|
if self.is_dragging {
|
|
dragged = true;
|
|
drag_delta = self.pointer_delta;
|
|
if self.drag_origin.is_some() && self.pointer_delta != Vec2::ZERO {
|
|
drag_started = false;
|
|
}
|
|
}
|
|
}
|
|
if self.left_released {
|
|
if self.is_dragging {
|
|
drag_stopped = true;
|
|
} else if hovered {
|
|
clicked = true;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Detect first frame of drag start
|
|
if dragged && self.drag_origin.map_or(false, |o| {
|
|
let p = self.pointer_pos.unwrap_or(o);
|
|
o.distance(p) >= 3.0 && o.distance(p - self.pointer_delta) < 3.0
|
|
}) {
|
|
drag_started = true;
|
|
}
|
|
|
|
Interaction {
|
|
rect,
|
|
hovered,
|
|
pressed,
|
|
clicked,
|
|
double_clicked,
|
|
right_clicked,
|
|
dragged,
|
|
drag_started,
|
|
drag_stopped,
|
|
drag_delta,
|
|
}
|
|
}
|
|
|
|
/// True if the user clicked (left or right mouse button) outside `rect` this frame.
|
|
pub fn clicked_outside(&self, rect: Rect) -> bool {
|
|
if !self.left_pressed && !self.right_pressed {
|
|
return false;
|
|
}
|
|
match self.pointer_pos {
|
|
Some(pos) => !rect.contains(pos),
|
|
None => true,
|
|
}
|
|
}
|
|
|
|
/// True if the user clicked outside ALL rects in `rects` (useful for parent menu + open submenu).
|
|
pub fn clicked_outside_any(&self, rects: &[Rect]) -> bool {
|
|
if !self.left_pressed && !self.right_pressed {
|
|
return false;
|
|
}
|
|
match self.pointer_pos {
|
|
Some(pos) => !rects.iter().any(|r| r.contains(pos)),
|
|
None => true,
|
|
}
|
|
}
|
|
|
|
/// Consume the current pointer press (`active_id = None`, `left_pressed = false`,
|
|
/// `right_pressed = false`) so releasing over an underlying widget cannot trigger a click/drag.
|
|
pub fn consume_pointer_press(&mut self) {
|
|
self.active_id = None;
|
|
self.left_pressed = false;
|
|
self.right_pressed = false;
|
|
}
|
|
|
|
/// Like `clicked_outside`, but also consumes the dismissing press (`active_id = None`,
|
|
/// `left_pressed = false`, `right_pressed = false`) so releasing over an underlying
|
|
/// toggle trigger button (e.g. PlayerBar EQ button) can NEVER re-open the overlay.
|
|
pub fn consume_clicked_outside(&mut self, rect: Rect) -> bool {
|
|
if self.clicked_outside(rect) {
|
|
self.consume_pointer_press();
|
|
true
|
|
} else {
|
|
false
|
|
}
|
|
}
|
|
|
|
/// Multi-rect variant of `consume_clicked_outside`.
|
|
pub fn consume_clicked_outside_any(&mut self, rects: &[Rect]) -> bool {
|
|
if self.clicked_outside_any(rects) {
|
|
self.consume_pointer_press();
|
|
true
|
|
} else {
|
|
false
|
|
}
|
|
}
|
|
|
|
pub fn key_pressed(&self, key: Key) -> bool {
|
|
self.key_events.iter().any(|e| e.key == key)
|
|
}
|
|
|
|
pub fn key_pressed_no_mods(&self, key: Key) -> bool {
|
|
self.key_events
|
|
.iter()
|
|
.any(|e| e.key == key && !e.modifiers.ctrl && !e.modifiers.alt && !e.modifiers.super_key)
|
|
}
|
|
|
|
pub fn shortcut(&self, command: bool, shift: bool, ch: char) -> bool {
|
|
let lower = ch.to_ascii_lowercase();
|
|
self.key_events.iter().any(|e| {
|
|
e.modifiers.command() == command
|
|
&& e.modifiers.shift == shift
|
|
&& matches!(e.key, Key::Char(c) if c.to_ascii_lowercase() == lower)
|
|
})
|
|
}
|
|
|
|
pub fn set_focus(&mut self, id: Option<WidgetId>) {
|
|
self.focused_id = id;
|
|
}
|
|
|
|
pub fn is_focused(&self, id: WidgetId) -> bool {
|
|
self.focused_id == Some(id)
|
|
}
|
|
|
|
pub fn has_text_focus(&self) -> bool {
|
|
self.focused_id.is_some()
|
|
}
|
|
}
|
|
|
|
fn translate_winit_key(key: &WinitKey) -> Option<Key> {
|
|
match key {
|
|
WinitKey::Named(named) => match named {
|
|
NamedKey::Enter => Some(Key::Enter),
|
|
NamedKey::Escape => Some(Key::Escape),
|
|
NamedKey::Backspace => Some(Key::Backspace),
|
|
NamedKey::Delete => Some(Key::Delete),
|
|
NamedKey::Tab => Some(Key::Tab),
|
|
NamedKey::Space => Some(Key::Space),
|
|
NamedKey::ArrowLeft => Some(Key::ArrowLeft),
|
|
NamedKey::ArrowRight => Some(Key::ArrowRight),
|
|
NamedKey::ArrowUp => Some(Key::ArrowUp),
|
|
NamedKey::ArrowDown => Some(Key::ArrowDown),
|
|
NamedKey::Home => Some(Key::Home),
|
|
NamedKey::End => Some(Key::End),
|
|
NamedKey::PageUp => Some(Key::PageUp),
|
|
NamedKey::PageDown => Some(Key::PageDown),
|
|
NamedKey::MediaPlayPause => Some(Key::MediaPlayPause),
|
|
NamedKey::MediaTrackNext => Some(Key::MediaNext),
|
|
NamedKey::MediaTrackPrevious => Some(Key::MediaPrev),
|
|
NamedKey::MediaStop => Some(Key::MediaStop),
|
|
NamedKey::F1 => Some(Key::F1),
|
|
NamedKey::F2 => Some(Key::F2),
|
|
NamedKey::F3 => Some(Key::F3),
|
|
NamedKey::F4 => Some(Key::F4),
|
|
NamedKey::F5 => Some(Key::F5),
|
|
NamedKey::F6 => Some(Key::F6),
|
|
NamedKey::F7 => Some(Key::F7),
|
|
NamedKey::F8 => Some(Key::F8),
|
|
NamedKey::F9 => Some(Key::F9),
|
|
NamedKey::F10 => Some(Key::F10),
|
|
NamedKey::F11 => Some(Key::F11),
|
|
NamedKey::F12 => Some(Key::F12),
|
|
_ => None,
|
|
},
|
|
WinitKey::Character(s) => s.chars().next().map(Key::Char),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
/// Smooth 60fps float & bool transition animator (matches `--ym-duration-transition: 0.3s`).
|
|
#[derive(Default)]
|
|
pub struct Animator {
|
|
values: HashMap<WidgetId, f32>,
|
|
active_this_frame: bool,
|
|
}
|
|
|
|
impl Animator {
|
|
pub fn new() -> Self {
|
|
Self {
|
|
values: HashMap::with_capacity(128),
|
|
active_this_frame: false,
|
|
}
|
|
}
|
|
|
|
pub fn begin_frame(&mut self) {
|
|
self.active_this_frame = false;
|
|
}
|
|
|
|
pub fn needs_repaint(&self) -> bool {
|
|
self.active_this_frame
|
|
}
|
|
|
|
/// Smoothly animate a boolean toward `0.0` or `1.0` over `duration_secs`.
|
|
pub fn animate_bool(&mut self, id: WidgetId, target: bool, duration_secs: f32, dt: f32) -> f32 {
|
|
self.animate_f32(id, if target { 1.0 } else { 0.0 }, duration_secs, dt)
|
|
}
|
|
|
|
/// Smoothly animate a float toward `target` over `duration_secs` (linear step with ease curve).
|
|
pub fn animate_f32(&mut self, id: WidgetId, target: f32, duration_secs: f32, dt: f32) -> f32 {
|
|
let entry = self.values.entry(id).or_insert(target);
|
|
let diff = target - *entry;
|
|
if diff.abs() <= 0.001 || duration_secs <= 0.001 {
|
|
*entry = target;
|
|
return target;
|
|
}
|
|
let max_step = (dt / duration_secs).max(0.001);
|
|
if diff.abs() <= max_step {
|
|
*entry = target;
|
|
} else {
|
|
*entry += diff.signum() * max_step;
|
|
self.active_this_frame = true;
|
|
}
|
|
*entry
|
|
}
|
|
|
|
/// Exponentially damped spring-like smoothing (great for scroll/hover scales).
|
|
pub fn damp_f32(&mut self, id: WidgetId, target: f32, speed: f32, dt: f32) -> f32 {
|
|
let entry = self.values.entry(id).or_insert(target);
|
|
let diff = target - *entry;
|
|
if diff.abs() <= 0.001 {
|
|
*entry = target;
|
|
return target;
|
|
}
|
|
let factor = 1.0 - (-speed * dt).exp();
|
|
*entry += diff * factor;
|
|
if (target - *entry).abs() > 0.001 {
|
|
self.active_this_frame = true;
|
|
} else {
|
|
*entry = target;
|
|
}
|
|
*entry
|
|
}
|
|
|
|
pub fn clear(&mut self) {
|
|
self.values.clear();
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use winit::dpi::PhysicalPosition;
|
|
|
|
#[test]
|
|
fn test_consume_clicked_outside_prevents_trigger_reopen_on_release() {
|
|
let mut input = InputState::new();
|
|
let screen = Vec2::new(1280.0, 800.0);
|
|
let trigger_id = WidgetId::new("pb_r_eq");
|
|
let trigger_r = Rect::from_xywh(1000.0, 740.0, 36.0, 36.0);
|
|
let pop_r = Rect::from_xywh(800.0, 400.0, 430.0, 300.0);
|
|
|
|
// Frame 1: Mouse down on the underlying trigger button while popover is open.
|
|
input.begin_frame(screen, 1.0, 1.0);
|
|
input.handle_winit_event(&WindowEvent::CursorMoved {
|
|
device_id: unsafe { std::mem::zeroed() },
|
|
position: PhysicalPosition::new(1018.0, 758.0),
|
|
});
|
|
input.handle_winit_event(&WindowEvent::MouseInput {
|
|
device_id: unsafe { std::mem::zeroed() },
|
|
state: ElementState::Pressed,
|
|
button: MouseButton::Left,
|
|
});
|
|
|
|
let press_resp = input.interact(trigger_id, ZLayer::Base, trigger_r, None);
|
|
assert!(!press_resp.clicked);
|
|
assert!(input.consume_clicked_outside(pop_r));
|
|
assert!(input.active_id.is_none());
|
|
input.end_frame();
|
|
|
|
// Frame 2: Mouse up over the same trigger button — MUST NOT fire clicked!
|
|
input.begin_frame(screen, 1.0, 1.05);
|
|
input.handle_winit_event(&WindowEvent::MouseInput {
|
|
device_id: unsafe { std::mem::zeroed() },
|
|
state: ElementState::Released,
|
|
button: MouseButton::Left,
|
|
});
|
|
let rel_resp = input.interact(trigger_id, ZLayer::Base, trigger_r, None);
|
|
assert!(!rel_resp.clicked);
|
|
input.end_frame();
|
|
}
|
|
}
|