-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.rs
703 lines (639 loc) · 23 KB
/
graph.rs
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
use crate::error::report_error;
use crate::m_try;
use crate::ui_props::{PROP_OBJECT_GRAPH_SEARCH_HIDE, PROP_OBJECT_PIN_COLOR};
use crate::widgets::report::diagnostic_widget;
use crate::workspace::graph::rects::NodeRects;
use crate::workspace::graph::viewer::get_viewer;
use ahash::AHashMap;
use dbe_backend::diagnostic::context::DiagnosticContextRef;
use dbe_backend::diagnostic::prelude::{Diagnostic, DiagnosticLevel};
use dbe_backend::etype::econst::ETypeConst;
use dbe_backend::etype::eobject::EObject;
use dbe_backend::etype::EDataType;
use dbe_backend::graph::editing::PartialGraphEditingContext;
use dbe_backend::graph::node::commands::SnarlCommands;
use dbe_backend::graph::node::ports::NodePortType;
use dbe_backend::graph::node::{
all_node_factories, node_factories_by_category, NodeFactory, SnarlNode,
};
use dbe_backend::registry::ETypesRegistry;
use dbe_backend::value::id::ETypeId;
use egui::epaint::PathShape;
use egui::{Color32, Frame, Painter, Pos2, Rect, Stroke, Style, Ui};
use egui_hooks::UseHookExt;
use egui_snarl::ui::{
AnyPins, BackgroundPattern, NodeLayout, PinInfo, SnarlStyle, SnarlViewer, Viewport,
};
use egui_snarl::{InPin, NodeId, OutPin, OutPinId, Snarl};
use inline_tweak::tweak;
use random_color::options::Luminosity;
use random_color::RandomColor;
use std::iter::Peekable;
use std::ops::DerefMut;
use std::sync::Arc;
use ustr::Ustr;
pub mod rects;
pub mod toolbar;
pub mod viewer;
#[derive(Debug)]
pub struct GraphViewer<'a> {
pub ctx: PartialGraphEditingContext<'a>,
pub diagnostics: DiagnosticContextRef<'a>,
pub node_rects: &'a mut NodeRects,
commands: SnarlCommands,
}
impl<'a> GraphViewer<'a> {
pub fn new(
ctx: PartialGraphEditingContext<'a>,
diagnostics: DiagnosticContextRef<'a>,
node_rects: &'a mut NodeRects,
) -> Self {
Self {
ctx,
diagnostics,
commands: Default::default(),
node_rects,
}
}
}
impl<'a> SnarlViewer<SnarlNode> for GraphViewer<'a> {
fn title(&mut self, _node: &SnarlNode) -> String {
unreachable!("Custom header doesn't call SnarlViewer::title")
}
fn node_frame(
&mut self,
default: Frame,
node: NodeId,
inputs: &[InPin],
outputs: &[OutPin],
snarl: &Snarl<SnarlNode>,
) -> Frame {
self.header_frame(default, node, inputs, outputs, snarl)
}
fn header_frame(
&mut self,
mut default: Frame,
node: NodeId,
_inputs: &[InPin],
_outputs: &[OutPin],
snarl: &Snarl<SnarlNode>,
) -> Frame {
if let Ok(data) = self.ctx.region_graph.try_as_data() {
if let Some(node_region) = data.node_region(&node) {
if let Some(reg) = self.ctx.regions.get(&node_region) {
let color = reg.color();
default =
default.stroke(Stroke::new(tweak!(1.0), color.gamma_multiply(tweak!(1.0))));
}
}
}
if let Some(scheme) = &snarl[node].color_scheme {
default = default.fill(scheme.theme.tokens.app_background)
}
default
}
fn node_style(
&mut self,
ui: &mut Ui,
node: NodeId,
_inputs: &[InPin],
_outputs: &[OutPin],
snarl: &Snarl<SnarlNode>,
) {
let Some(scheme) = &snarl[node].color_scheme else {
return;
};
scheme.theme.apply_local(ui);
}
fn node_layout(
&mut self,
_default: NodeLayout,
node_id: NodeId,
_inputs: &[InPin],
_outputs: &[OutPin],
snarl: &Snarl<SnarlNode>,
) -> NodeLayout {
let node = &snarl[node_id];
let viewer = get_viewer(&node.id());
viewer.node_layout(self, node)
}
fn show_header(
&mut self,
node_id: NodeId,
inputs: &[InPin],
outputs: &[OutPin],
ui: &mut Ui,
scale: f32,
snarl: &mut Snarl<SnarlNode>,
) {
m_try(|| {
let node = &snarl[node_id];
let viewer = get_viewer(&node.id());
let has_body = viewer.has_body(self, node)?;
let node = &mut snarl[node_id];
if !has_body {
node.update_state(self.ctx.as_node_context(), &mut self.commands, node_id)?;
self.commands.execute(&mut self.ctx.as_full(snarl))?;
}
viewer.show_header(self, node_id, inputs, outputs, ui, scale, snarl)?;
Ok(())
})
.unwrap_or_else(|err| {
ui.set_max_width(128.0);
diagnostic_widget(
ui,
&Diagnostic {
info: err,
level: DiagnosticLevel::Error,
},
);
})
}
fn inputs(&mut self, node: &SnarlNode) -> usize {
node.inputs_count(self.ctx.as_node_context())
}
fn show_input(
&mut self,
pin: &InPin,
ui: &mut Ui,
_scale: f32,
snarl: &mut Snarl<SnarlNode>,
) -> PinInfo {
m_try(|| get_viewer(&snarl[pin.id.node].id()).show_input(self, pin, ui, _scale, snarl))
.unwrap_or_else(|err| {
// ui.set_max_width(128.0);
diagnostic_widget(
ui,
&Diagnostic {
info: err,
level: DiagnosticLevel::Error,
},
);
PinInfo::circle().with_fill(Color32::BLACK)
})
}
fn outputs(&mut self, node: &SnarlNode) -> usize {
node.outputs_count(self.ctx.as_node_context())
}
fn show_output(
&mut self,
pin: &OutPin,
ui: &mut Ui,
_scale: f32,
snarl: &mut Snarl<SnarlNode>,
) -> PinInfo {
m_try(|| get_viewer(&snarl[pin.id.node].id()).show_output(self, pin, ui, _scale, snarl))
.unwrap_or_else(|err| {
ui.set_max_width(128.0);
diagnostic_widget(
ui,
&Diagnostic {
info: err,
level: DiagnosticLevel::Error,
},
);
PinInfo::circle().with_fill(Color32::BLACK)
})
}
fn has_body(&mut self, node: &SnarlNode) -> bool {
m_try(|| get_viewer(&node.id()).has_body(self, node)).unwrap_or_else(|err| {
report_error(err);
false
})
}
fn show_body(
&mut self,
node_id: NodeId,
inputs: &[InPin],
outputs: &[OutPin],
ui: &mut Ui,
scale: f32,
snarl: &mut Snarl<SnarlNode>,
) {
ui.vertical(|ui| {
m_try(|| {
get_viewer(&snarl[node_id].id())
.show_body(self, node_id, inputs, outputs, ui, scale, snarl)?;
snarl[node_id].update_state(
self.ctx.as_node_context(),
&mut self.commands,
node_id,
)?;
self.commands.execute(&mut self.ctx.as_full(snarl))?;
Ok(())
})
.unwrap_or_else(|err| {
diagnostic_widget(
ui,
&Diagnostic {
info: err,
level: DiagnosticLevel::Error,
},
);
})
});
}
fn final_node_rect(
&mut self,
node: NodeId,
_ui_rect: Rect,
graph_rect: Rect,
_ui: &mut Ui,
_scale: f32,
_snarl: &mut Snarl<SnarlNode>,
) {
self.node_rects.add_graph_space_rect(node, graph_rect);
}
fn has_graph_menu(&mut self, _pos: Pos2, _snarl: &mut Snarl<SnarlNode>) -> bool {
true
}
fn show_graph_menu(
&mut self,
pos: Pos2,
ui: &mut Ui,
_scale: f32,
snarl: &mut Snarl<SnarlNode>,
) {
ui.menu_button("Add node", |ui| {
#[derive(Debug, Copy, Clone)]
enum NodeCombo {
Factory(Ustr),
Object(ETypeId),
}
impl AsRef<str> for NodeCombo {
fn as_ref(&self) -> &str {
match self {
NodeCombo::Factory(id) => id.as_str(),
NodeCombo::Object(id) => id.as_raw().unwrap(),
}
}
}
let mut search_query = ui.use_state(|| "".to_string(), ()).into_var();
let search_nodes = ui.use_memo(
|| {
let factories = all_node_factories();
let all_nodes = factories.iter().map(|(id, _)| NodeCombo::Factory(*id));
let objects = self
.ctx
.registry
.all_objects()
.filter(|obj| {
!PROP_OBJECT_GRAPH_SEARCH_HIDE.get(obj.extra_properties(), false)
})
.map(|s| NodeCombo::Object(s.ident()));
all_nodes
.chain(objects)
.map(|n| (n.as_ref().to_string(), n))
.collect::<AHashMap<_, _>>()
},
(),
);
let search_bar = ui.text_edit_singleline(search_query.deref_mut());
search_bar.request_focus();
if search_query.trim() != "" {
for (name, node) in search_nodes
.iter()
.filter(|(k, _)| k.contains(search_query.as_str()))
.take(10)
{
if ui.button(name).clicked() {
let node = match node {
NodeCombo::Factory(id) => {
self.ctx
.as_full(snarl)
.create_node(*id, pos, &mut self.commands)
}
NodeCombo::Object(id) => self.ctx.as_full(snarl).create_object_node(
*id,
pos,
&mut self.commands,
),
};
if let Err(err) = node {
report_error(err);
}
*search_query = "".to_string();
ui.close_menu();
return;
}
}
} else {
let categories = node_factories_by_category();
let mut categories = categories.iter().peekable();
fn is_sub_category(category: &str, parent: &str) -> bool {
category.starts_with(parent)
&& category.chars().nth(parent.len()).is_some_and(|c| c == '.')
}
fn show<'a>(
ui: &mut Ui,
parent: &'static str,
categories: &mut Peekable<
impl Iterator<Item = (&'a &'static str, &'a Vec<Arc<dyn NodeFactory>>)>,
>,
) -> Option<Ustr> {
while let Some((cat, _)) = categories.peek() {
if !parent.is_empty() && !is_sub_category(cat, parent) {
return None;
}
if !parent.is_empty() {
ui.separator();
}
let (category, factories) = categories.next().unwrap();
let cat_name = category
.strip_prefix(parent)
.and_then(|c| c.strip_prefix("."))
.unwrap_or(category);
if let Some(node) = ui
.menu_button(cat_name, |ui| {
for factory in factories.iter() {
if ui.button(factory.id().as_str()).clicked() {
// let node = factory.create();
ui.close_menu();
return Some(factory.id());
}
}
show(ui, category, categories)
})
.inner
.flatten()
{
return Some(node);
}
while let Some((next_cat, _)) = categories.peek() {
if !is_sub_category(next_cat, category) {
break;
}
categories.next();
}
}
None
}
if let Some(to_insert) = show(ui, "", &mut categories) {
if let Err(err) =
self.ctx
.as_full(snarl)
.create_node(to_insert, pos, &mut self.commands)
{
report_error(err)
}
}
}
});
}
fn has_dropped_wire_menu(&mut self, _src_pins: AnyPins, _snarl: &mut Snarl<SnarlNode>) -> bool {
true
}
fn show_dropped_wire_menu(
&mut self,
pos: Pos2,
ui: &mut Ui,
_scale: f32,
src_pins: AnyPins,
snarl: &mut Snarl<SnarlNode>,
) {
match src_pins {
AnyPins::Out(_) => ui.close_menu(),
AnyPins::In(pins) => {
for pin in pins {
m_try(|| {
let node = &snarl[pin.node];
let data = node.try_input(self.ctx.as_node_context(), pin.input)?;
match data.ty.ty() {
EDataType::Object { ident } => {
if ui.button(ident.as_raw().unwrap()).clicked() {
let nodes = self.ctx.as_full(snarl).create_object_node(
ident,
pos,
&mut self.commands,
)?;
if let Some(node) = nodes.last() {
let out_pin = &snarl.out_pin(OutPinId {
node: *node,
output: 0,
});
let in_pin = snarl.in_pin(*pin);
self.ctx.as_full(snarl).connect(
out_pin,
&in_pin,
&mut self.commands,
)?;
}
ui.close_menu();
}
}
EDataType::List { id } => {
if ui.button("List").clicked() {
let nodes = self.ctx.as_full(snarl).create_list_node(
id,
pos,
&mut self.commands,
)?;
if let Some(node) = nodes.last() {
let out_pin = &snarl.out_pin(OutPinId {
node: *node,
output: 0,
});
let in_pin = snarl.in_pin(*pin);
self.ctx.as_full(snarl).connect(
out_pin,
&in_pin,
&mut self.commands,
)?;
}
ui.close_menu();
}
}
// TODO: search by output type
_ => ui.close_menu(),
}
Ok(())
})
.unwrap_or_else(|err| {
report_error(err);
ui.close_menu()
})
}
}
}
}
fn has_node_menu(&mut self, _node: &SnarlNode) -> bool {
true
}
fn show_node_menu(
&mut self,
node: NodeId,
_inputs: &[InPin],
_outputs: &[OutPin],
ui: &mut Ui,
_scale: f32,
snarl: &mut Snarl<SnarlNode>,
) {
m_try(|| {
ui.label("Node menu");
if ui.button("Remove").clicked() {
self.ctx
.as_full(snarl)
.remove_node(node, &mut self.commands)?;
ui.close_menu();
}
Ok(())
})
.unwrap_or_else(report_error)
}
fn connect(&mut self, from: &OutPin, to: &InPin, snarl: &mut Snarl<SnarlNode>) {
if let Err(err) = self
.ctx
.as_full(snarl)
.connect(from, to, &mut self.commands)
{
report_error(err)
}
}
fn disconnect(&mut self, from: &OutPin, to: &InPin, snarl: &mut Snarl<SnarlNode>) {
if let Err(err) = self
.ctx
.as_full(snarl)
.disconnect(from, to, &mut self.commands)
{
report_error(err);
}
}
fn drop_outputs(&mut self, pin: &OutPin, snarl: &mut Snarl<SnarlNode>) {
if let Err(err) = m_try(|| {
for remote in &pin.remotes {
let in_pin = snarl.in_pin(*remote);
self.ctx
.as_full(snarl)
.disconnect(pin, &in_pin, &mut self.commands)?;
}
Ok(())
}) {
report_error(err);
}
}
fn drop_inputs(&mut self, pin: &InPin, snarl: &mut Snarl<SnarlNode>) {
if let Err(err) = m_try(|| {
for remote in &pin.remotes {
let out_pin = snarl.out_pin(*remote);
self.ctx
.as_full(snarl)
.disconnect(&out_pin, pin, &mut self.commands)?;
}
Ok(())
}) {
report_error(err);
}
}
fn draw_background(
&mut self,
_background: Option<&BackgroundPattern>,
viewport: &Viewport,
snarl_style: &SnarlStyle,
style: &Style,
painter: &Painter,
snarl: &Snarl<SnarlNode>,
) {
BackgroundPattern::Grid(Default::default()).draw(viewport, snarl_style, style, painter);
self.ctx.region_graph.ensure_ready(snarl);
let Ok(data) = self.ctx.region_graph.try_as_data() else {
return;
};
let scale = viewport.scale;
// TODO: cache region hull calculations
for region in data.ordered_regions() {
let Some(region_info) = self.ctx.regions.get(region) else {
continue;
};
let Some(points) = self.node_rects.screen_space_hull(region, data, viewport) else {
continue;
};
let shape = PathShape::convex_polygon(
points,
region_info.color().gamma_multiply(tweak!(0.2)),
Stroke::new(
tweak!(2.0) * scale,
region_info.color().gamma_multiply(tweak!(0.5)),
),
);
painter.add(shape);
}
}
}
fn pin_color(ty: EDataType, registry: &ETypesRegistry) -> Color32 {
const NUMBER_COLOR: Color32 = Color32::from_rgb(161, 161, 161);
const BOOLEAN_COLOR: Color32 = Color32::from_rgb(204, 166, 214);
const STRING_COLOR: Color32 = Color32::from_rgb(112, 178, 255);
const NULL_COLOR: Color32 = Color32::from_rgb(0, 0, 0);
match ty {
EDataType::Number => NUMBER_COLOR,
EDataType::String => STRING_COLOR,
EDataType::Boolean => BOOLEAN_COLOR,
EDataType::Const { value } => match value {
ETypeConst::String(_) => STRING_COLOR,
ETypeConst::Number(_) => NUMBER_COLOR,
ETypeConst::Boolean(_) => BOOLEAN_COLOR,
ETypeConst::Null => NULL_COLOR,
},
EDataType::Object { ident } => match registry.get_object(&ident) {
None => NULL_COLOR,
Some(data) => PROP_OBJECT_PIN_COLOR
.try_get(data.extra_properties())
.map(|e| e.0)
.unwrap_or_else(|| {
let c = RandomColor::new()
.seed(ident.to_string())
.luminosity(Luminosity::Light)
.alpha(1.0)
.to_rgb_array();
Color32::from_rgb(c[0], c[1], c[2])
}),
},
EDataType::List { id } => registry
.get_list(&id)
.map(|e| pin_color(e.value_type, registry))
.unwrap_or(NULL_COLOR),
EDataType::Map { id } => registry
.get_map(&id)
.map(|e| pin_color(e.value_type, registry))
.unwrap_or(NULL_COLOR),
}
}
fn pin_stroke(ty: EDataType, registry: &ETypesRegistry) -> Stroke {
if let EDataType::Map { id } = ty {
let color = registry
.get_map(&id)
.map(|e| pin_color(e.key_type, registry))
.unwrap_or_else(|| pin_color(ty, registry));
Stroke::new(tweak!(2.0), color)
} else {
Stroke::NONE
}
}
fn pin_info(ty: &NodePortType, registry: &ETypesRegistry) -> PinInfo {
match ty {
NodePortType::BasedOnSource | NodePortType::BasedOnTarget => any_pin(),
NodePortType::Specific(ty) => {
let shape = match ty.ty() {
EDataType::Boolean
| EDataType::Number
| EDataType::String
| EDataType::Const { .. } => PinInfo::circle(),
EDataType::Object { .. } => PinInfo::circle(),
EDataType::List { .. } => PinInfo::square(),
EDataType::Map { .. } => PinInfo::star(),
};
shape
.with_fill(pin_color(ty.ty(), registry))
.with_stroke(pin_stroke(ty.ty(), registry))
}
NodePortType::Invalid => PinInfo::circle().with_fill(Color32::BLACK),
}
}
fn any_pin() -> PinInfo {
PinInfo::circle()
.with_fill(Color32::from_rgb(tweak!(128), tweak!(128), tweak!(128)))
.with_stroke(Stroke::new(
tweak!(2.0),
Color32::from_rgb(tweak!(44), tweak!(44), tweak!(44)),
))
}