Add GraphLayout::pointer_target()

This commit is contained in:
mars 2022-09-19 07:42:09 -06:00
parent 36edf051ff
commit be6693b20a
1 changed files with 46 additions and 6 deletions

View File

@ -10,7 +10,6 @@ pub enum PointerTarget {
Node(usize),
Input(SlotIndex),
Output(SlotIndex),
Edge(Edge),
}
#[derive(Debug)]
@ -18,7 +17,7 @@ pub struct EdgeLayout {
pub points: [Vec2; 4],
}
#[derive(Debug)]
#[derive(Clone, Debug)]
pub struct GraphStyle {
pub grid_spacing: f32,
pub grid_stroke: Stroke,
@ -34,7 +33,7 @@ pub struct GraphStyle {
impl GraphStyle {
pub fn from_ui_style(style: &egui::Style) -> Self {
let node_alpha = 192;
let node_bg = if style.visuals.dark_mode {
Color32::from_black_alpha(node_alpha)
} else {
@ -55,8 +54,9 @@ impl GraphStyle {
}
}
#[derive(Debug, Default)]
#[derive(Debug)]
pub struct GraphLayout {
pub style: GraphStyle,
pub node_rects: HashMap<usize, egui::Rect>,
pub input_positions: HashMap<SlotIndex, Vec2>,
pub output_positions: HashMap<SlotIndex, Vec2>,
@ -65,7 +65,14 @@ pub struct GraphLayout {
impl GraphLayout {
pub fn layout(style: &GraphStyle, graph: &Graph) -> Self {
let mut layout = Self::default();
let mut layout = Self {
style: style.clone(),
node_rects: Default::default(),
input_positions: Default::default(),
output_positions: Default::default(),
edges: Default::default(),
};
let mut edges = Vec::new();
for (node_index, node) in graph.nodes.iter() {
@ -129,6 +136,39 @@ impl GraphLayout {
layout
}
pub fn pointer_target(&self, pointer: egui::Pos2) -> PointerTarget {
let test_slots = |positions: &HashMap<SlotIndex, Vec2>| -> Option<SlotIndex> {
for (index, position) in positions.iter() {
let dx = pointer.x - position.x;
let dy = pointer.y - position.y;
let d2 = (dx * dx) + (dy * dy);
let slot_radius2 = self.style.slot_radius.powi(2);
if d2 < slot_radius2 {
return Some(*index);
}
}
None
};
if let Some(index) = test_slots(&self.input_positions) {
return PointerTarget::Input(index);
}
if let Some(index) = test_slots(&self.output_positions) {
return PointerTarget::Output(index);
}
for (node_index, node_rect) in self.node_rects.iter() {
if node_rect.contains(pointer) {
return PointerTarget::Node(*node_index);
}
}
PointerTarget::Grid
}
}
pub fn draw_graph(ui: &mut egui::Ui, graph: &Graph) {
@ -140,7 +180,7 @@ pub fn draw_graph(ui: &mut egui::Ui, graph: &Graph) {
let layout = GraphLayout::layout(&style, graph);
let pointer_pos = ui.input().pointer.interact_pos();
let mut pointer_target: Option<PointerTarget> = None;
let pointer_target = pointer_pos.map(|pointer| layout.pointer_target(pointer));
let grid_spacing = style.grid_spacing;
let grid_pos = rect.left_top().to_vec2() / egui::vec2(grid_spacing, grid_spacing);