This repository has been archived by the owner on Apr 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 137
/
app.rs
609 lines (563 loc) · 22.9 KB
/
app.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
use std::{borrow::Cow, collections::HashMap};
use eframe::egui::{self, DragValue, TextStyle};
use egui_node_graph::*;
// ========= First, define your user data types =============
/// The NodeData holds a custom data struct inside each node. It's useful to
/// store additional information that doesn't live in parameters. For this
/// example, the node data stores the template (i.e. the "type") of the node.
#[cfg_attr(feature = "persistence", derive(serde::Serialize, serde::Deserialize))]
pub struct MyNodeData {
template: MyNodeTemplate,
}
/// `DataType`s are what defines the possible range of connections when
/// attaching two ports together. The graph UI will make sure to not allow
/// attaching incompatible datatypes.
#[derive(PartialEq, Eq)]
#[cfg_attr(feature = "persistence", derive(serde::Serialize, serde::Deserialize))]
pub enum MyDataType {
Scalar,
Vec2,
}
/// In the graph, input parameters can optionally have a constant value. This
/// value can be directly edited in a widget inside the node itself.
///
/// There will usually be a correspondence between DataTypes and ValueTypes. But
/// this library makes no attempt to check this consistency. For instance, it is
/// up to the user code in this example to make sure no parameter is created
/// with a DataType of Scalar and a ValueType of Vec2.
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "persistence", derive(serde::Serialize, serde::Deserialize))]
pub enum MyValueType {
Vec2 { value: egui::Vec2 },
Scalar { value: f32 },
}
impl Default for MyValueType {
fn default() -> Self {
// NOTE: This is just a dummy `Default` implementation. The library
// requires it to circumvent some internal borrow checker issues.
Self::Scalar { value: 0.0 }
}
}
impl MyValueType {
/// Tries to downcast this value type to a vector
pub fn try_to_vec2(self) -> anyhow::Result<egui::Vec2> {
if let MyValueType::Vec2 { value } = self {
Ok(value)
} else {
anyhow::bail!("Invalid cast from {:?} to vec2", self)
}
}
/// Tries to downcast this value type to a scalar
pub fn try_to_scalar(self) -> anyhow::Result<f32> {
if let MyValueType::Scalar { value } = self {
Ok(value)
} else {
anyhow::bail!("Invalid cast from {:?} to scalar", self)
}
}
}
/// NodeTemplate is a mechanism to define node templates. It's what the graph
/// will display in the "new node" popup. The user code needs to tell the
/// library how to convert a NodeTemplate into a Node.
#[derive(Clone, Copy)]
#[cfg_attr(feature = "persistence", derive(serde::Serialize, serde::Deserialize))]
pub enum MyNodeTemplate {
MakeScalar,
AddScalar,
SubtractScalar,
MakeVector,
AddVector,
SubtractVector,
VectorTimesScalar,
}
/// The response type is used to encode side-effects produced when drawing a
/// node in the graph. Most side-effects (creating new nodes, deleting existing
/// nodes, handling connections...) are already handled by the library, but this
/// mechanism allows creating additional side effects from user code.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MyResponse {
SetActiveNode(NodeId),
ClearActiveNode,
}
/// The graph 'global' state. This state struct is passed around to the node and
/// parameter drawing callbacks. The contents of this struct are entirely up to
/// the user. For this example, we use it to keep track of the 'active' node.
#[derive(Default)]
#[cfg_attr(feature = "persistence", derive(serde::Serialize, serde::Deserialize))]
pub struct MyGraphState {
pub active_node: Option<NodeId>,
}
// =========== Then, you need to implement some traits ============
// A trait for the data types, to tell the library how to display them
impl DataTypeTrait<MyGraphState> for MyDataType {
fn data_type_color(&self, _user_state: &mut MyGraphState) -> egui::Color32 {
match self {
MyDataType::Scalar => egui::Color32::from_rgb(38, 109, 211),
MyDataType::Vec2 => egui::Color32::from_rgb(238, 207, 109),
}
}
fn name(&self) -> Cow<'_, str> {
match self {
MyDataType::Scalar => Cow::Borrowed("scalar"),
MyDataType::Vec2 => Cow::Borrowed("2d vector"),
}
}
}
// A trait for the node kinds, which tells the library how to build new nodes
// from the templates in the node finder
impl NodeTemplateTrait for MyNodeTemplate {
type NodeData = MyNodeData;
type DataType = MyDataType;
type ValueType = MyValueType;
type UserState = MyGraphState;
type CategoryType = &'static str;
fn node_finder_label(&self, _user_state: &mut Self::UserState) -> Cow<'_, str> {
Cow::Borrowed(match self {
MyNodeTemplate::MakeScalar => "New scalar",
MyNodeTemplate::AddScalar => "Scalar add",
MyNodeTemplate::SubtractScalar => "Scalar subtract",
MyNodeTemplate::MakeVector => "New vector",
MyNodeTemplate::AddVector => "Vector add",
MyNodeTemplate::SubtractVector => "Vector subtract",
MyNodeTemplate::VectorTimesScalar => "Vector times scalar",
})
}
// this is what allows the library to show collapsible lists in the node finder.
fn node_finder_categories(&self, _user_state: &mut Self::UserState) -> Vec<&'static str> {
match self {
MyNodeTemplate::MakeScalar
| MyNodeTemplate::AddScalar
| MyNodeTemplate::SubtractScalar => vec!["Scalar"],
MyNodeTemplate::MakeVector
| MyNodeTemplate::AddVector
| MyNodeTemplate::SubtractVector => vec!["Vector"],
MyNodeTemplate::VectorTimesScalar => vec!["Vector", "Scalar"],
}
}
fn node_graph_label(&self, user_state: &mut Self::UserState) -> String {
// It's okay to delegate this to node_finder_label if you don't want to
// show different names in the node finder and the node itself.
self.node_finder_label(user_state).into()
}
fn user_data(&self, _user_state: &mut Self::UserState) -> Self::NodeData {
MyNodeData { template: *self }
}
fn build_node(
&self,
graph: &mut Graph<Self::NodeData, Self::DataType, Self::ValueType>,
_user_state: &mut Self::UserState,
node_id: NodeId,
) {
// The nodes are created empty by default. This function needs to take
// care of creating the desired inputs and outputs based on the template
// We define some closures here to avoid boilerplate. Note that this is
// entirely optional.
let input_scalar = |graph: &mut MyGraph, name: &str| {
graph.add_input_param(
node_id,
name.to_string(),
MyDataType::Scalar,
MyValueType::Scalar { value: 0.0 },
InputParamKind::ConnectionOrConstant,
true,
);
};
let input_vector = |graph: &mut MyGraph, name: &str| {
graph.add_input_param(
node_id,
name.to_string(),
MyDataType::Vec2,
MyValueType::Vec2 {
value: egui::vec2(0.0, 0.0),
},
InputParamKind::ConnectionOrConstant,
true,
);
};
let output_scalar = |graph: &mut MyGraph, name: &str| {
graph.add_output_param(node_id, name.to_string(), MyDataType::Scalar);
};
let output_vector = |graph: &mut MyGraph, name: &str| {
graph.add_output_param(node_id, name.to_string(), MyDataType::Vec2);
};
match self {
MyNodeTemplate::AddScalar => {
// The first input param doesn't use the closure so we can comment
// it in more detail.
graph.add_input_param(
node_id,
// This is the name of the parameter. Can be later used to
// retrieve the value. Parameter names should be unique.
"A".into(),
// The data type for this input. In this case, a scalar
MyDataType::Scalar,
// The value type for this input. We store zero as default
MyValueType::Scalar { value: 0.0 },
// The input parameter kind. This allows defining whether a
// parameter accepts input connections and/or an inline
// widget to set its value.
InputParamKind::ConnectionOrConstant,
true,
);
input_scalar(graph, "B");
output_scalar(graph, "out");
}
MyNodeTemplate::SubtractScalar => {
input_scalar(graph, "A");
input_scalar(graph, "B");
output_scalar(graph, "out");
}
MyNodeTemplate::VectorTimesScalar => {
input_scalar(graph, "scalar");
input_vector(graph, "vector");
output_vector(graph, "out");
}
MyNodeTemplate::AddVector => {
input_vector(graph, "v1");
input_vector(graph, "v2");
output_vector(graph, "out");
}
MyNodeTemplate::SubtractVector => {
input_vector(graph, "v1");
input_vector(graph, "v2");
output_vector(graph, "out");
}
MyNodeTemplate::MakeVector => {
input_scalar(graph, "x");
input_scalar(graph, "y");
output_vector(graph, "out");
}
MyNodeTemplate::MakeScalar => {
input_scalar(graph, "value");
output_scalar(graph, "out");
}
}
}
}
pub struct AllMyNodeTemplates;
impl NodeTemplateIter for AllMyNodeTemplates {
type Item = MyNodeTemplate;
fn all_kinds(&self) -> Vec<Self::Item> {
// This function must return a list of node kinds, which the node finder
// will use to display it to the user. Crates like strum can reduce the
// boilerplate in enumerating all variants of an enum.
vec![
MyNodeTemplate::MakeScalar,
MyNodeTemplate::MakeVector,
MyNodeTemplate::AddScalar,
MyNodeTemplate::SubtractScalar,
MyNodeTemplate::AddVector,
MyNodeTemplate::SubtractVector,
MyNodeTemplate::VectorTimesScalar,
]
}
}
impl WidgetValueTrait for MyValueType {
type Response = MyResponse;
type UserState = MyGraphState;
type NodeData = MyNodeData;
fn value_widget(
&mut self,
param_name: &str,
_node_id: NodeId,
ui: &mut egui::Ui,
_user_state: &mut MyGraphState,
_node_data: &MyNodeData,
) -> Vec<MyResponse> {
// This trait is used to tell the library which UI to display for the
// inline parameter widgets.
match self {
MyValueType::Vec2 { value } => {
ui.label(param_name);
ui.horizontal(|ui| {
ui.label("x");
ui.add(DragValue::new(&mut value.x));
ui.label("y");
ui.add(DragValue::new(&mut value.y));
});
}
MyValueType::Scalar { value } => {
ui.horizontal(|ui| {
ui.label(param_name);
ui.add(DragValue::new(value));
});
}
}
// This allows you to return your responses from the inline widgets.
Vec::new()
}
}
impl UserResponseTrait for MyResponse {}
impl NodeDataTrait for MyNodeData {
type Response = MyResponse;
type UserState = MyGraphState;
type DataType = MyDataType;
type ValueType = MyValueType;
// This method will be called when drawing each node. This allows adding
// extra ui elements inside the nodes. In this case, we create an "active"
// button which introduces the concept of having an active node in the
// graph. This is done entirely from user code with no modifications to the
// node graph library.
fn bottom_ui(
&self,
ui: &mut egui::Ui,
node_id: NodeId,
_graph: &Graph<MyNodeData, MyDataType, MyValueType>,
user_state: &mut Self::UserState,
) -> Vec<NodeResponse<MyResponse, MyNodeData>>
where
MyResponse: UserResponseTrait,
{
// This logic is entirely up to the user. In this case, we check if the
// current node we're drawing is the active one, by comparing against
// the value stored in the global user state, and draw different button
// UIs based on that.
let mut responses = vec![];
let is_active = user_state
.active_node
.map(|id| id == node_id)
.unwrap_or(false);
// Pressing the button will emit a custom user response to either set,
// or clear the active node. These responses do nothing by themselves,
// the library only makes the responses available to you after the graph
// has been drawn. See below at the update method for an example.
if !is_active {
if ui.button("👁 Set active").clicked() {
responses.push(NodeResponse::User(MyResponse::SetActiveNode(node_id)));
}
} else {
let button =
egui::Button::new(egui::RichText::new("👁 Active").color(egui::Color32::BLACK))
.fill(egui::Color32::GOLD);
if ui.add(button).clicked() {
responses.push(NodeResponse::User(MyResponse::ClearActiveNode));
}
}
responses
}
}
type MyGraph = Graph<MyNodeData, MyDataType, MyValueType>;
type MyEditorState =
GraphEditorState<MyNodeData, MyDataType, MyValueType, MyNodeTemplate, MyGraphState>;
#[derive(Default)]
pub struct NodeGraphExample {
// The `GraphEditorState` is the top-level object. You "register" all your
// custom types by specifying it as its generic parameters.
state: MyEditorState,
user_state: MyGraphState,
}
#[cfg(feature = "persistence")]
const PERSISTENCE_KEY: &str = "egui_node_graph";
#[cfg(feature = "persistence")]
impl NodeGraphExample {
/// If the persistence feature is enabled, Called once before the first frame.
/// Load previous app state (if any).
pub fn new(cc: &eframe::CreationContext<'_>) -> Self {
let state = cc
.storage
.and_then(|storage| eframe::get_value(storage, PERSISTENCE_KEY))
.unwrap_or_default();
Self {
state,
user_state: MyGraphState::default(),
}
}
}
impl eframe::App for NodeGraphExample {
#[cfg(feature = "persistence")]
/// If the persistence function is enabled,
/// Called by the frame work to save state before shutdown.
fn save(&mut self, storage: &mut dyn eframe::Storage) {
eframe::set_value(storage, PERSISTENCE_KEY, &self.state);
}
/// Called each time the UI needs repainting, which may be many times per second.
/// Put your widgets into a `SidePanel`, `TopPanel`, `CentralPanel`, `Window` or `Area`.
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
egui::TopBottomPanel::top("top").show(ctx, |ui| {
egui::menu::bar(ui, |ui| {
egui::widgets::global_dark_light_mode_switch(ui);
});
});
let graph_response = egui::CentralPanel::default()
.show(ctx, |ui| {
self.state.draw_graph_editor(
ui,
AllMyNodeTemplates,
&mut self.user_state,
Vec::default(),
)
})
.inner;
for node_response in graph_response.node_responses {
// Here, we ignore all other graph events. But you may find
// some use for them. For example, by playing a sound when a new
// connection is created
if let NodeResponse::User(user_event) = node_response {
match user_event {
MyResponse::SetActiveNode(node) => self.user_state.active_node = Some(node),
MyResponse::ClearActiveNode => self.user_state.active_node = None,
}
}
}
if let Some(node) = self.user_state.active_node {
if self.state.graph.nodes.contains_key(node) {
let text = match evaluate_node(&self.state.graph, node, &mut HashMap::new()) {
Ok(value) => format!("The result is: {:?}", value),
Err(err) => format!("Execution error: {}", err),
};
ctx.debug_painter().text(
egui::pos2(10.0, 35.0),
egui::Align2::LEFT_TOP,
text,
TextStyle::Button.resolve(&ctx.style()),
egui::Color32::WHITE,
);
} else {
self.user_state.active_node = None;
}
}
}
}
type OutputsCache = HashMap<OutputId, MyValueType>;
/// Recursively evaluates all dependencies of this node, then evaluates the node itself.
pub fn evaluate_node(
graph: &MyGraph,
node_id: NodeId,
outputs_cache: &mut OutputsCache,
) -> anyhow::Result<MyValueType> {
// To solve a similar problem as creating node types above, we define an
// Evaluator as a convenience. It may be overkill for this small example,
// but something like this makes the code much more readable when the
// number of nodes starts growing.
struct Evaluator<'a> {
graph: &'a MyGraph,
outputs_cache: &'a mut OutputsCache,
node_id: NodeId,
}
impl<'a> Evaluator<'a> {
fn new(graph: &'a MyGraph, outputs_cache: &'a mut OutputsCache, node_id: NodeId) -> Self {
Self {
graph,
outputs_cache,
node_id,
}
}
fn evaluate_input(&mut self, name: &str) -> anyhow::Result<MyValueType> {
// Calling `evaluate_input` recursively evaluates other nodes in the
// graph until the input value for a paramater has been computed.
evaluate_input(self.graph, self.node_id, name, self.outputs_cache)
}
fn populate_output(
&mut self,
name: &str,
value: MyValueType,
) -> anyhow::Result<MyValueType> {
// After computing an output, we don't just return it, but we also
// populate the outputs cache with it. This ensures the evaluation
// only ever computes an output once.
//
// The return value of the function is the "final" output of the
// node, the thing we want to get from the evaluation. The example
// would be slightly more contrived when we had multiple output
// values, as we would need to choose which of the outputs is the
// one we want to return. Other outputs could be used as
// intermediate values.
//
// Note that this is just one possible semantic interpretation of
// the graphs, you can come up with your own evaluation semantics!
populate_output(self.graph, self.outputs_cache, self.node_id, name, value)
}
fn input_vector(&mut self, name: &str) -> anyhow::Result<egui::Vec2> {
self.evaluate_input(name)?.try_to_vec2()
}
fn input_scalar(&mut self, name: &str) -> anyhow::Result<f32> {
self.evaluate_input(name)?.try_to_scalar()
}
fn output_vector(&mut self, name: &str, value: egui::Vec2) -> anyhow::Result<MyValueType> {
self.populate_output(name, MyValueType::Vec2 { value })
}
fn output_scalar(&mut self, name: &str, value: f32) -> anyhow::Result<MyValueType> {
self.populate_output(name, MyValueType::Scalar { value })
}
}
let node = &graph[node_id];
let mut evaluator = Evaluator::new(graph, outputs_cache, node_id);
match node.user_data.template {
MyNodeTemplate::AddScalar => {
let a = evaluator.input_scalar("A")?;
let b = evaluator.input_scalar("B")?;
evaluator.output_scalar("out", a + b)
}
MyNodeTemplate::SubtractScalar => {
let a = evaluator.input_scalar("A")?;
let b = evaluator.input_scalar("B")?;
evaluator.output_scalar("out", a - b)
}
MyNodeTemplate::VectorTimesScalar => {
let scalar = evaluator.input_scalar("scalar")?;
let vector = evaluator.input_vector("vector")?;
evaluator.output_vector("out", vector * scalar)
}
MyNodeTemplate::AddVector => {
let v1 = evaluator.input_vector("v1")?;
let v2 = evaluator.input_vector("v2")?;
evaluator.output_vector("out", v1 + v2)
}
MyNodeTemplate::SubtractVector => {
let v1 = evaluator.input_vector("v1")?;
let v2 = evaluator.input_vector("v2")?;
evaluator.output_vector("out", v1 - v2)
}
MyNodeTemplate::MakeVector => {
let x = evaluator.input_scalar("x")?;
let y = evaluator.input_scalar("y")?;
evaluator.output_vector("out", egui::vec2(x, y))
}
MyNodeTemplate::MakeScalar => {
let value = evaluator.input_scalar("value")?;
evaluator.output_scalar("out", value)
}
}
}
fn populate_output(
graph: &MyGraph,
outputs_cache: &mut OutputsCache,
node_id: NodeId,
param_name: &str,
value: MyValueType,
) -> anyhow::Result<MyValueType> {
let output_id = graph[node_id].get_output(param_name)?;
outputs_cache.insert(output_id, value);
Ok(value)
}
// Evaluates the input value of
fn evaluate_input(
graph: &MyGraph,
node_id: NodeId,
param_name: &str,
outputs_cache: &mut OutputsCache,
) -> anyhow::Result<MyValueType> {
let input_id = graph[node_id].get_input(param_name)?;
// The output of another node is connected.
if let Some(other_output_id) = graph.connection(input_id) {
// The value was already computed due to the evaluation of some other
// node. We simply return value from the cache.
if let Some(other_value) = outputs_cache.get(&other_output_id) {
Ok(*other_value)
}
// This is the first time encountering this node, so we need to
// recursively evaluate it.
else {
// Calling this will populate the cache
evaluate_node(graph, graph[other_output_id].node, outputs_cache)?;
// Now that we know the value is cached, return it
Ok(*outputs_cache
.get(&other_output_id)
.expect("Cache should be populated"))
}
}
// No existing connection, take the inline value instead.
else {
Ok(graph[input_id].value)
}
}