sensors are now normal

This commit is contained in:
2025-09-20 01:46:55 -04:00
parent 8ecd8bb171
commit fee03fddc8
7 changed files with 109 additions and 202 deletions

View File

@@ -1,16 +1,16 @@
use std::ops::{Index, IndexMut}; use std::ops::{Index, IndexMut};
use crate::{ use crate::{
layout::UiRegion, layout::{SenseShape, UiRegion},
render::{Primitive, PrimitiveHandle, Primitives}, render::{Primitive, PrimitiveHandle, Primitives},
util::Id, util::{HashMap, Id},
}; };
struct LayerNode<T> { struct LayerNode {
prev: Option<usize>, prev: Option<usize>,
next: Next, next: Next,
child: Option<usize>, child: Option<usize>,
data: T, data: Layer,
} }
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
@@ -23,29 +23,29 @@ enum Next {
None, None,
} }
pub struct Layers<T> { pub struct Layers {
vec: Vec<LayerNode<T>>, vec: Vec<LayerNode>,
} }
impl<T: Default> Layers<T> { #[derive(Default)]
pub fn new() -> Layers<T> pub struct Layer {
where pub primitives: Primitives,
T: Default, pub sensors: HashMap<Id, SenseShape>,
{ }
impl Layers {
pub fn new() -> Layers {
Self { Self {
vec: vec![LayerNode::head()], vec: vec![LayerNode::head()],
} }
} }
pub fn clear(&mut self) pub fn clear(&mut self) {
where
T: Default,
{
self.vec.clear(); self.vec.clear();
self.vec.push(LayerNode::head()); self.vec.push(LayerNode::head());
} }
fn push(&mut self, node: LayerNode<T>) -> usize { fn push(&mut self, node: LayerNode) -> usize {
let i = self.vec.len(); let i = self.vec.len();
self.vec.push(node); self.vec.push(node);
i i
@@ -55,7 +55,7 @@ impl<T: Default> Layers<T> {
if let Next::Same(i) = self.vec[i].next { if let Next::Same(i) = self.vec[i].next {
return i; return i;
} }
let i_next = self.push(LayerNode::new(T::default(), self.vec[i].next)); let i_next = self.push(LayerNode::new(Layer::default(), self.vec[i].next));
self.vec[i].next = Next::Same(i_next); self.vec[i].next = Next::Same(i_next);
self.vec[i_next].prev = Some(i); self.vec[i_next].prev = Some(i);
i_next i_next
@@ -65,42 +65,56 @@ impl<T: Default> Layers<T> {
if let Some(i) = self.vec[i].child { if let Some(i) = self.vec[i].child {
return i; return i;
} }
let i_next = self.push(LayerNode::new(T::default(), Next::Parent(i))); let i_next = self.push(LayerNode::new(Layer::default(), Next::Parent(i)));
self.vec[i].child = Some(i_next); self.vec[i].child = Some(i_next);
self.vec[i_next].prev = Some(i); self.vec[i_next].prev = Some(i);
i_next i_next
} }
pub fn iter_mut(&mut self) -> LayerIteratorMut<'_, T> { pub fn iter_mut(&mut self) -> LayerIteratorMut<'_> {
LayerIteratorMut { LayerIteratorMut {
next: Some(0), next: Some(0),
vec: &mut self.vec, vec: &mut self.vec,
} }
} }
pub fn write<P: Primitive>(
&mut self,
layer: usize,
id: Id,
primitive: P,
region: UiRegion,
) -> PrimitiveHandle {
self[layer].primitives.write(layer, id, primitive, region)
}
pub fn free(&mut self, h: &PrimitiveHandle) {
self[h.layer].primitives.free(h)
}
} }
impl<T: Default> Default for Layers<T> { impl Default for Layers {
fn default() -> Self { fn default() -> Self {
Self::new() Self::new()
} }
} }
impl<T> Index<usize> for Layers<T> { impl Index<usize> for Layers {
type Output = T; type Output = Layer;
fn index(&self, index: usize) -> &Self::Output { fn index(&self, index: usize) -> &Self::Output {
&self.vec[index].data &self.vec[index].data
} }
} }
impl<T> IndexMut<usize> for Layers<T> { impl IndexMut<usize> for Layers {
fn index_mut(&mut self, index: usize) -> &mut Self::Output { fn index_mut(&mut self, index: usize) -> &mut Self::Output {
&mut self.vec[index].data &mut self.vec[index].data
} }
} }
impl<T> LayerNode<T> { impl LayerNode {
pub fn new(data: T, next: Next) -> Self { pub fn new(data: Layer, next: Next) -> Self {
Self { Self {
prev: None, prev: None,
next, next,
@@ -109,26 +123,23 @@ impl<T> LayerNode<T> {
} }
} }
pub fn head() -> Self pub fn head() -> Self {
where Self::new(Layer::default(), Next::None)
T: Default,
{
Self::new(T::default(), Next::None)
} }
} }
pub struct LayerIteratorMut<'a, T> { pub struct LayerIteratorMut<'a> {
next: Option<usize>, next: Option<usize>,
vec: &'a mut Vec<LayerNode<T>>, vec: &'a mut Vec<LayerNode>,
} }
impl<'a, T> Iterator for LayerIteratorMut<'a, T> { impl<'a> Iterator for LayerIteratorMut<'a> {
type Item = (usize, &'a mut T); type Item = (usize, &'a mut Layer);
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {
// chat are we cooked? (if it's not set up correctly this could be catastrophic) // chat are we cooked? (if it's not set up correctly this could be catastrophic)
let ret_i = self.next?; let ret_i = self.next?;
let node: &mut LayerNode<T> = unsafe { std::mem::transmute(&mut self.vec[ret_i]) }; let node: &mut LayerNode = unsafe { std::mem::transmute(&mut self.vec[ret_i]) };
self.next = if let Some(i) = node.child { self.next = if let Some(i) = node.child {
Some(i) Some(i)
} else if let Next::Same(i) = node.next { } else if let Next::Same(i) = node.next {
@@ -146,19 +157,3 @@ impl<'a, T> Iterator for LayerIteratorMut<'a, T> {
Some((ret_i, &mut node.data)) Some((ret_i, &mut node.data))
} }
} }
impl Layers<Primitives> {
pub fn write<P: Primitive>(
&mut self,
layer: usize,
id: Id,
primitive: P,
region: UiRegion,
) -> PrimitiveHandle {
self[layer].write(layer, id, primitive, region)
}
pub fn free(&mut self, h: &PrimitiveHandle) {
self[h.layer].free(h)
}
}

View File

@@ -1,9 +1,9 @@
use crate::{ use crate::{
layout::{ layout::{
Active, Layers, TextAttrs, TextBuffer, TextData, TextOffset, TextureHandle, Textures, ActiveWidgets, Layers, TextAttrs, TextBuffer, TextData, TextOffset, TextureHandle,
UiRegion, UiVec2, Vec2, WidgetId, Widgets, Textures, UiRegion, UiVec2, Vec2, WidgetId, Widgets,
}, },
render::{Primitive, PrimitiveHandle, Primitives}, render::{Primitive, PrimitiveHandle},
util::{HashMap, HashSet, Id, IdUtil}, util::{HashMap, HashSet, Id, IdUtil},
}; };
@@ -20,8 +20,8 @@ pub struct Painter<'a, 'c> {
pub struct PainterCtx<'a> { pub struct PainterCtx<'a> {
pub widgets: &'a Widgets, pub widgets: &'a Widgets,
pub active: &'a mut Active, pub active: &'a mut ActiveWidgets,
pub layers: &'a mut Layers<Primitives>, pub layers: &'a mut Layers,
pub textures: &'a mut Textures, pub textures: &'a mut Textures,
pub text: &'a mut TextData, pub text: &'a mut TextData,
pub screen_size: Vec2, pub screen_size: Vec2,
@@ -42,8 +42,8 @@ pub struct WidgetInstance {
impl<'a> PainterCtx<'a> { impl<'a> PainterCtx<'a> {
pub fn new( pub fn new(
widgets: &'a Widgets, widgets: &'a Widgets,
layers: &'a mut Layers<Primitives>, layers: &'a mut Layers,
active: &'a mut Active, active: &'a mut ActiveWidgets,
textures: &'a mut Textures, textures: &'a mut Textures,
text: &'a mut TextData, text: &'a mut TextData,
screen_size: Vec2, screen_size: Vec2,
@@ -61,7 +61,7 @@ impl<'a> PainterCtx<'a> {
pub fn redraw(&mut self, id: &Id) { pub fn redraw(&mut self, id: &Id) {
self.drawing.clear(); self.drawing.clear();
let Some(active) = self.active.widgets.get(id) else { let Some(active) = self.active.get(id) else {
return; return;
}; };
@@ -83,7 +83,7 @@ impl<'a> PainterCtx<'a> {
active.parent.duplicate(), active.parent.duplicate(),
Some(active.children), Some(active.children),
); );
self.active.widgets.get_mut(id).unwrap().resize = active.resize; self.active.get_mut(id).unwrap().resize = active.resize;
} }
pub fn draw(&mut self, id: &Id) { pub fn draw(&mut self, id: &Id) {
@@ -111,7 +111,7 @@ impl<'a> PainterCtx<'a> {
} }
let mut old_children = old_children.unwrap_or_default(); let mut old_children = old_children.unwrap_or_default();
let mut resize = None; let mut resize = None;
if let Some(active) = self.active.widgets.get_mut(id) { if let Some(active) = self.active.get_mut(id) {
if active.parent != parent { if active.parent != parent {
panic!("Cannot draw the same widget twice (2)"); panic!("Cannot draw the same widget twice (2)");
} }
@@ -155,7 +155,7 @@ impl<'a> PainterCtx<'a> {
layer, layer,
}; };
for (cid, size) in sized_children { for (cid, size) in sized_children {
if let Some(w) = self.active.widgets.get_mut(&cid) { if let Some(w) = self.active.get_mut(&cid) {
w.resize = Some((id.duplicate(), size)) w.resize = Some((id.duplicate(), size))
} }
} }
@@ -165,7 +165,12 @@ impl<'a> PainterCtx<'a> {
} }
} }
self.active.add(id, instance, self.widgets); if self.widgets.data(id).is_some_and(|w| w.sensor) {
self.layers[layer]
.sensors
.insert(id.duplicate(), instance.region);
}
self.active.insert(id.duplicate(), instance);
} }
/// NOTE: instance textures are cleared and self.textures freed /// NOTE: instance textures are cleared and self.textures freed
@@ -177,6 +182,7 @@ impl<'a> PainterCtx<'a> {
} }
inst.textures.clear(); inst.textures.clear();
self.textures.free(); self.textures.free();
self.layers[inst.layer].sensors.remove(id);
} }
inst inst
} }

View File

@@ -2,7 +2,7 @@ use std::ops::{BitOr, Deref, DerefMut};
use crate::{ use crate::{
layout::{Ui, UiRegion, Vec2}, layout::{Ui, UiRegion, Vec2},
util::{HashMap, Id, IdVec}, util::{HashMap, Id},
}; };
pub trait CursorCtx { pub trait CursorCtx {
@@ -80,7 +80,6 @@ pub struct Sensor<Ctx> {
} }
pub type SensorMap<Ctx> = HashMap<Id, SensorGroup<Ctx>>; pub type SensorMap<Ctx> = HashMap<Id, SensorGroup<Ctx>>;
pub type ActiveSensors = IdVec<SenseShape>;
pub type SenseShape = UiRegion; pub type SenseShape = UiRegion;
pub struct SensorGroup<Ctx> { pub struct SensorGroup<Ctx> {
pub hover: ActivationState, pub hover: ActivationState,
@@ -105,26 +104,34 @@ pub trait UiCtx {
/// it extends so you can add to it, but you can't actually index sensors with it /// it extends so you can add to it, but you can't actually index sensors with it
/// should something be done about this? /// should something be done about this?
pub fn run_sensors<Ctx: UiCtx>(ctx: &mut Ctx, cursor: &CursorState, window_size: Vec2) { pub fn run_sensors<Ctx: UiCtx>(ctx: &mut Ctx, cursor: &CursorState, window_size: Vec2) {
let active = std::mem::take(&mut ctx.ui().active.sensors); let mut layers = std::mem::take(&mut ctx.ui().layers);
let mut map = std::mem::take(&mut ctx.ui().sensor_map); let mut map = std::mem::take(&mut ctx.ui().sensor_map);
for (id, shape) in active.iter().rev() { // temp solution, should probably cache somewhere
let group = &mut map.get_mut(id).unwrap(); let mut bruh = Vec::new();
let region = shape.to_screen(window_size); for (i, _) in layers.iter_mut() {
let in_shape = cursor.exists && region.contains(cursor.pos); bruh.push(i)
group.hover.update(in_shape); }
if group.hover == ActivationState::Off { for i in bruh.into_iter().rev() {
continue; let layer = &layers[i];
}
let mut ran = false; let mut ran = false;
for sensor in &mut group.sensors { for (id, shape) in &layer.sensors {
if should_run(&sensor.senses, &cursor.buttons, group.hover) { let group = &mut map.get_mut(id).unwrap();
ran = true; let region = shape.to_screen(window_size);
let sctx = SenseCtx { let in_shape = cursor.exists && region.contains(cursor.pos);
cursor: cursor.pos - region.top_left, group.hover.update(in_shape);
size: region.bot_right - region.top_left, if group.hover == ActivationState::Off {
}; continue;
(sensor.f)(ctx, sctx); }
for sensor in &mut group.sensors {
if should_run(&sensor.senses, &cursor.buttons, group.hover) {
ran = true;
let sctx = SenseCtx {
cursor: cursor.pos - region.top_left,
size: region.bot_right - region.top_left,
};
(sensor.f)(ctx, sctx);
}
} }
} }
if ran { if ran {
@@ -133,9 +140,10 @@ pub fn run_sensors<Ctx: UiCtx>(ctx: &mut Ctx, cursor: &CursorState, window_size:
} }
let ui = ctx.ui(); let ui = ctx.ui();
std::mem::swap(&mut ui.sensor_map, &mut map); std::mem::swap(&mut ui.sensor_map, &mut map);
// TODO: this removes existing sensors (if a new one is added to an id) lol
// the proper code is easy but writing this comment is easier and I'm tired
ui.sensor_map.extend(map); ui.sensor_map.extend(map);
assert!(ui.active.sensors.is_empty()); ui.layers = layers;
ui.active.sensors = active;
} }
pub fn should_run(senses: &Senses, cursor: &CursorButtons, hover: ActivationState) -> bool { pub fn should_run(senses: &Senses, cursor: &CursorButtons, hover: ActivationState) -> bool {

View File

@@ -3,10 +3,9 @@ use image::DynamicImage;
use crate::{ use crate::{
core::{TextEdit, TextEditCtx}, core::{TextEdit, TextEditCtx},
layout::{ layout::{
ActiveSensors, Layers, PainterCtx, Sensor, SensorMap, StaticWidgetId, TextData, Layers, PainterCtx, Sensor, SensorMap, StaticWidgetId, TextData, TextureHandle, Textures,
TextureHandle, Textures, Vec2, Widget, WidgetId, WidgetInstance, WidgetLike, Vec2, Widget, WidgetId, WidgetInstance, WidgetLike,
}, },
render::Primitives,
util::{DynBorrower, HashMap, HashSet, Id, IdTracker}, util::{DynBorrower, HashMap, HashSet, Id, IdTracker},
}; };
use std::{ use std::{
@@ -23,12 +22,12 @@ pub struct Ui<Ctx> {
pub(super) send: Sender<Id>, pub(super) send: Sender<Id>,
size: Vec2, size: Vec2,
// TODO: make these non pub(crate) // TODO: make these non pub(crate)
pub(crate) layers: Layers<Primitives>, pub(crate) layers: Layers,
pub(crate) textures: Textures, pub(crate) textures: Textures,
pub(crate) text: TextData, pub(crate) text: TextData,
full_redraw: bool, full_redraw: bool,
pub(crate) active: Active, pub(crate) active: ActiveWidgets,
pub(super) sensor_map: SensorMap<Ctx>, pub(super) sensor_map: SensorMap<Ctx>,
} }
@@ -182,7 +181,7 @@ impl<Ctx> Ui<Ctx> {
} }
pub fn active_widgets(&self) -> usize { pub fn active_widgets(&self) -> usize {
self.active.widgets.len() self.active.len()
} }
pub fn add_sensor<W>(&mut self, id: &WidgetId<W>, f: Sensor<Ctx>) { pub fn add_sensor<W>(&mut self, id: &WidgetId<W>, f: Sensor<Ctx>) {
@@ -357,29 +356,3 @@ impl<Ctx> Default for Ui<Ctx> {
} }
pub type ActiveWidgets = HashMap<Id, WidgetInstance>; pub type ActiveWidgets = HashMap<Id, WidgetInstance>;
#[derive(Default)]
pub struct Active {
pub sensors: ActiveSensors,
pub widgets: ActiveWidgets,
}
impl Active {
pub fn clear(&mut self) {
self.sensors.clear();
self.widgets.clear();
}
pub fn remove(&mut self, id: &Id) -> Option<WidgetInstance> {
let instance = self.widgets.remove(id);
self.sensors.remove(id);
instance
}
pub fn add(&mut self, id: &Id, instance: WidgetInstance, widgets: &Widgets) {
if widgets.data(id).is_some_and(|w| w.sensor) {
self.sensors.insert(id.duplicate(), instance.region);
}
self.widgets.insert(id.duplicate(), instance);
}
}

View File

@@ -59,10 +59,11 @@ impl UiRenderer {
pub fn update<Ctx>(&mut self, device: &Device, queue: &Queue, ui: &mut Ui<Ctx>) { pub fn update<Ctx>(&mut self, device: &Device, queue: &Queue, ui: &mut Ui<Ctx>) {
self.active.clear(); self.active.clear();
for (i, primitives) in ui.layers.iter_mut() { for (i, ulayer) in ui.layers.iter_mut() {
self.active.push(i); self.active.push(i);
let primitives = &mut ulayer.primitives;
for change in primitives.apply_free() { for change in primitives.apply_free() {
if let Some(inst) = ui.active.widgets.get_mut(&change.id) { if let Some(inst) = ui.active.get_mut(&change.id) {
for h in &mut inst.primitives { for h in &mut inst.primitives {
if h.inst_idx == change.old { if h.inst_idx == change.old {
h.inst_idx = change.new; h.inst_idx = change.new;
@@ -71,7 +72,7 @@ impl UiRenderer {
} }
} }
} }
let layer = self.layers.entry(i).or_insert_with(|| { let rlayer = self.layers.entry(i).or_insert_with(|| {
let primitives = PrimitiveBuffers::new(device); let primitives = PrimitiveBuffers::new(device);
let primitive_group = let primitive_group =
Self::primitive_group(device, &self.primitive_layout, primitives.buffers()); Self::primitive_group(device, &self.primitive_layout, primitives.buffers());
@@ -86,12 +87,14 @@ impl UiRenderer {
} }
}); });
if primitives.updated { if primitives.updated {
layer.instance.update(device, queue, primitives.instances()); rlayer
layer.primitives.update(device, queue, primitives.data()); .instance
layer.primitive_group = Self::primitive_group( .update(device, queue, primitives.instances());
rlayer.primitives.update(device, queue, primitives.data());
rlayer.primitive_group = Self::primitive_group(
device, device,
&self.primitive_layout, &self.primitive_layout,
layer.primitives.buffers(), rlayer.primitives.buffers(),
) )
} }
} }

View File

@@ -1,76 +0,0 @@
use std::ops::{Deref, Index, IndexMut};
use crate::util::{HashMap, id::Id};
/// a vec that's indexed with permanent ids rather than an offset
pub struct IdVec<T> {
map: HashMap<Id, usize>,
vec: Vec<(Id, T)>,
}
impl<T> IdVec<T> {
pub fn insert(&mut self, id: Id, v: T) {
let idx = self.vec.len();
self.map.insert(id.duplicate(), idx);
self.vec.push((id, v));
}
pub fn remove(&mut self, id: &Id) -> Option<T> {
let i = self.map.remove(id)?;
let v = self.vec.remove(i).1;
for (id, _) in &self.vec[i..] {
*self.map.get_mut(id).unwrap() -= 1;
}
Some(v)
}
pub fn len(&self) -> usize {
self.map.len()
}
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
pub fn idx(&self, id: &Id) -> usize {
self.map[id]
}
pub fn clear(&mut self) {
self.map.clear();
self.vec.clear();
}
}
impl<T> Default for IdVec<T> {
fn default() -> Self {
Self {
map: Default::default(),
vec: Default::default(),
}
}
}
impl<T> Index<&Id> for IdVec<T> {
type Output = T;
fn index(&self, id: &Id) -> &Self::Output {
let i = self.idx(id);
&self.vec[i].1
}
}
impl<T> IndexMut<&Id> for IdVec<T> {
fn index_mut(&mut self, id: &Id) -> &mut Self::Output {
let i = self.idx(id);
&mut self.vec[i].1
}
}
impl<T> Deref for IdVec<T> {
type Target = Vec<(Id, T)>;
fn deref(&self) -> &Self::Target {
&self.vec
}
}

View File

@@ -1,12 +1,10 @@
mod borrow; mod borrow;
mod id; mod id;
mod idvec;
mod math; mod math;
mod refcount; mod refcount;
pub(crate) use borrow::*; pub(crate) use borrow::*;
pub(crate) use id::*; pub(crate) use id::*;
pub(crate) use idvec::*;
pub(crate) use math::*; pub(crate) use math::*;
pub(crate) use refcount::*; pub(crate) use refcount::*;