forked from AcademySoftwareFoundation/MaterialX
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.cpp
More file actions
4978 lines (4525 loc) · 180 KB
/
Copy pathGraph.cpp
File metadata and controls
4978 lines (4525 loc) · 180 KB
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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright Contributors to the MaterialX Project
// SPDX-License-Identifier: Apache-2.0
//
#include <MaterialXGraphEditor/Graph.h>
#include <MaterialXRenderGlsl/External/Glad/glad.h>
#include <MaterialXFormat/Util.h>
#include <imgui_stdlib.h>
#include <imgui_node_editor_internal.h>
#include <widgets.h>
#include <cctype>
#include <iostream>
#include <unordered_set>
namespace
{
// Based on the dimensions of the dot_color3 node, computed by calling ed::getNodeSize
const ImVec2 DEFAULT_NODE_SIZE = ImVec2(138, 116);
const int DEFAULT_ALPHA = 255;
const int FILTER_ALPHA = 50;
const std::array<std::string, 22> NODE_GROUP_ORDER = {
"texture2d",
"texture3d",
"procedural",
"procedural2d",
"procedural3d",
"geometric",
"translation",
"convolution2d",
"math",
"adjustment",
"compositing",
"conditional",
"channel",
"organization",
"global",
"application",
"material",
"shader",
"pbr",
"light",
"colortransform",
"none"
};
// Based on ImRect_Expanded function in ImGui Node Editor blueprints-example.cpp
ImRect expandImRect(const ImRect& rect, float x, float y)
{
ImRect result = rect;
result.Min.x -= x;
result.Min.y -= y;
result.Max.x += x;
result.Max.y += y;
return result;
}
// Based on the splitter function in the ImGui Node Editor blueprints-example.cpp
static bool splitter(bool split_vertically, float thickness, float* size1, float* size2, float min_size1, float min_size2, float splitter_long_axis_size = -1.0f)
{
using namespace ImGui;
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiID id = window->GetID("##Splitter");
ImRect bb;
bb.Min = window->DC.CursorPos + (split_vertically ? ImVec2(*size1, 0.0f) : ImVec2(0.0f, *size1));
bb.Max = bb.Min + CalcItemSize(split_vertically ? ImVec2(thickness, splitter_long_axis_size) : ImVec2(splitter_long_axis_size, thickness), 0.0f, 0.0f);
return SplitterBehavior(bb, id, split_vertically ? ImGuiAxis_X : ImGuiAxis_Y, size1, size2, min_size1, min_size2, 0.0f);
}
// Based on showLabel from ImGui Node Editor blueprints-example.cpp
auto showLabel = [](const char* label, ImColor color)
{
ImGui::SetCursorPosY(ImGui::GetCursorPosY() - ImGui::GetTextLineHeight());
auto size = ImGui::CalcTextSize(label);
auto padding = ImGui::GetStyle().FramePadding;
auto spacing = ImGui::GetStyle().ItemSpacing;
ImGui::SetCursorPos(ImGui::GetCursorPos() + ImVec2(spacing.x, -spacing.y));
auto rectMin = ImGui::GetCursorScreenPos() - padding;
auto rectMax = ImGui::GetCursorScreenPos() + size + padding;
auto drawList = ImGui::GetWindowDrawList();
drawList->AddRectFilled(rectMin, rectMax, color, size.y * 0.15f);
ImGui::TextUnformatted(label);
};
// Create a more user-friendly node definition name
std::string getUserNodeDefName(const std::string& val)
{
const std::string ND_PREFIX = "ND_";
std::string result = val;
if (mx::stringStartsWith(val, ND_PREFIX))
{
result = val.substr(3, val.length());
}
return result;
}
static void EnableSRGBCallback(const ImDrawList*, const ImDrawCmd*)
{
glEnable(GL_FRAMEBUFFER_SRGB);
}
static void DisableSRGBCallback(const ImDrawList*, const ImDrawCmd*)
{
glDisable(GL_FRAMEBUFFER_SRGB);
}
} // anonymous namespace
//
// Graph methods
//
Graph::Graph(const std::string& materialFilename,
const std::string& meshFilename,
const mx::FileSearchPath& searchPath,
const mx::FilePathVec& libraryFolders,
int viewWidth,
int viewHeight,
float previewWidth) :
_materialFilename(materialFilename),
_searchPath(searchPath),
_libraryFolders(libraryFolders),
_needsLayout(false),
_layoutPending(false),
_needsNavigation(false),
_delete(false),
_fileDialogSave(FileDialog::EnterNewFilename),
_popup(false),
_shaderPopup(false),
_searchNodeId(-1),
_addNewNode(false),
_ctrlClick(false),
_isCut(false),
_autoLayout(false),
_frameCount(INT_MIN),
_fontScale(1.0f),
_previewSize(previewWidth),
_saveNodePositions(true)
{
loadStandardLibraries();
setPinColor();
// Set up filters load and save
_mtlxFilter.push_back(".mtlx");
_geomFilter.push_back(".obj");
_geomFilter.push_back(".glb");
_geomFilter.push_back(".gltf");
_graphDoc = loadDocument(materialFilename);
createNodeUIList(_stdLib);
initializeGraph();
// Create a renderer using the initial startup document.
mx::FilePath captureFilename = "resources/Materials/Examples/example.png";
std::string envRadianceFilename = "resources/Lights/san_giuseppe_bridge_split.hdr";
_renderer = std::make_shared<RenderView>(_graphDoc, _stdLib, meshFilename, envRadianceFilename,
_searchPath, viewWidth, viewHeight);
_renderer->initialize();
for (const std::string& ext : _renderer->getImageHandler()->supportedExtensions())
{
_imageFilter.emplace_back("." + ext);
}
_renderer->updateMaterials(nullptr);
for (const std::string& incl : _renderer->getXincludeFiles())
{
_xincludeFiles.insert(incl);
}
}
mx::ElementPredicate Graph::getElementPredicate() const
{
return [this](mx::ConstElementPtr elem)
{
if (elem->hasSourceUri())
{
return (_xincludeFiles.count(elem->getSourceUri()) == 0);
}
return true;
};
}
void Graph::loadStandardLibraries()
{
// Initialize the standard library.
try
{
_stdLib = mx::createDocument();
_xincludeFiles = mx::loadLibraries(_libraryFolders, _searchPath, _stdLib);
if (_xincludeFiles.empty())
{
std::cerr << "Could not find standard data libraries on the given search path: " << _searchPath.asString() << std::endl;
}
}
catch (std::exception& e)
{
std::cerr << "Failed to load standard data libraries: " << e.what() << std::endl;
return;
}
}
mx::DocumentPtr Graph::loadDocument(const mx::FilePath& filename)
{
mx::FilePathVec libraryFolders = { "libraries" };
_libraryFolders = libraryFolders;
mx::XmlReadOptions readOptions;
readOptions.readXIncludeFunction = [](mx::DocumentPtr doc, const mx::FilePath& filename,
const mx::FileSearchPath& searchPath, const mx::XmlReadOptions* options)
{
mx::FilePath resolvedFilename = searchPath.find(filename);
if (resolvedFilename.exists())
{
try
{
readFromXmlFile(doc, resolvedFilename, searchPath, options);
}
catch (mx::Exception& e)
{
std::cerr << "Failed to read include file: " << filename.asString() << ". " << std::string(e.what()) << std::endl;
}
}
else
{
std::cerr << "Include file not found: " << filename.asString() << std::endl;
}
};
mx::DocumentPtr doc = mx::createDocument();
try
{
if (!filename.isEmpty())
{
mx::readFromXmlFile(doc, filename, _searchPath, &readOptions);
doc->setDataLibrary(_stdLib);
std::string message;
if (!doc->validate(&message))
{
std::cerr << "*** Validation warnings for " << filename.asString() << " ***" << std::endl;
std::cerr << message << std::endl;
}
// Cache the currently loaded file
_materialFilename = filename;
}
}
catch (mx::Exception& e)
{
std::cerr << "Failed to read file: " << filename.asString() << ": \"" << std::string(e.what()) << "\"" << std::endl;
}
_parentStates.clear();
return doc;
}
void Graph::addExtraNodes()
{
if (!_graphDoc)
{
return;
}
// Get all types from the doc
std::vector<std::string> types;
std::vector<mx::TypeDefPtr> typeDefs = _graphDoc->getTypeDefs();
types.reserve(typeDefs.size());
for (auto typeDef : typeDefs)
{
types.push_back(typeDef->getName());
}
// Add input and output nodes for all types
const std::set<std::string> emptySet;
for (const std::string& type : types)
{
std::string nodeName = "ND_input_" + type;
_nodesToAdd.emplace_back(nodeName, type, "input", "Input Nodes", emptySet, emptySet);
nodeName = "ND_output_" + type;
_nodesToAdd.emplace_back(nodeName, type, "output", "Output Nodes", emptySet, emptySet);
}
// Add group node
_nodesToAdd.emplace_back("ND_group", "", "group", "Group Nodes", emptySet, emptySet);
// Add nodegraph node
_nodesToAdd.emplace_back("ND_nodegraph", "", "nodegraph", "Node Graph", emptySet, emptySet);
}
ed::PinId Graph::getOutputPin(UiNodePtr node, UiNodePtr upNode, UiPinPtr input)
{
if (upNode->getNodeGraph() != nullptr)
{
// For nodegraph need to get the correct output pin according to the names of the output nodes
mx::OutputPtr output;
if (input->getUiNode()->getNode())
{
output = input->getUiNode()->getNode()->getConnectedOutput(input->getName());
}
else if (input->getUiNode()->getNodeGraph())
{
output = input->getUiNode()->getNodeGraph()->getConnectedOutput(input->getName());
}
if (output)
{
std::string outName = output->getName();
for (UiPinPtr outputs : upNode->getOutputPins())
{
if (outputs->getName() == outName)
{
return outputs->getPinId();
}
}
}
return ed::PinId();
}
else
{
// For node need to get the correct output pin based on the output attribute
if (!upNode->getOutputPins().empty())
{
std::string outputName = mx::EMPTY_STRING;
if (input->getInput())
{
outputName = input->getInput()->getOutputString();
}
else if (input->getOutput())
{
outputName = input->getOutput()->getOutputString();
}
size_t pinIndex = 0;
if (!outputName.empty())
{
for (size_t i = 0; i < upNode->getOutputPins().size(); i++)
{
if (upNode->getOutputPins()[i]->getName() == outputName)
{
pinIndex = i;
break;
}
}
}
return (upNode->getOutputPins()[pinIndex]->getPinId());
}
return ed::PinId();
}
}
std::string Graph::resolveUpstreamOutputType(mx::InputPtr input) const
{
mx::NodePtr upstream = input->getConnectedNode();
if (!upstream)
return mx::EMPTY_STRING;
std::string outputType = upstream->getType();
if (outputType == mx::MULTI_OUTPUT_TYPE_STRING)
{
mx::NodeDefPtr nodeDef = upstream->getNodeDef();
if (nodeDef)
{
mx::OutputPtr defOut = nodeDef->getOutput(input->getOutputString());
if (defOut)
outputType = defOut->getType();
}
}
return outputType;
}
bool Graph::addInvalidInputDiagnostic(mx::InputPtr input, const std::string& nodeName,
int uiNodeId, const std::string& graphPath,
mx::NodeGraphPtr ng)
{
if (!input || !input->getConnectedNode())
return false;
std::string message;
if (input->validate(&message))
return false;
LinkDiagnostic diag;
diag.nodeId = uiNodeId;
diag.nodeName = nodeName;
diag.inputName = input->getName();
diag.inputType = input->getType();
diag.outputType = resolveUpstreamOutputType(input);
message.erase(std::remove(message.begin(), message.end(), '\n'), message.end());
diag.message = message;
diag.graphPath = graphPath;
diag.nodeGraph = ng;
_diagnostics.push_back(diag);
return true;
}
void Graph::linkGraph()
{
_state.links.clear();
_diagnostics.clear();
// Start with bottom of graph
for (UiNodePtr node : _state.nodes)
{
std::vector<UiPinPtr> inputs = node->getInputPins();
if (node->getInput() == nullptr)
{
for (size_t i = 0; i < inputs.size(); i++)
{
// Get upstream node for all inputs
std::string inputName = inputs[i]->getName();
UiNodePtr inputNode = node->getConnectedNode(inputName);
if (inputNode != nullptr)
{
// Get the input connections for the current UiNode
ax::NodeEditor::PinId id = inputs[i]->getPinId();
inputs[i]->setConnected(true);
int end = int(id.Get());
// Get id number of output of node
ed::PinId outputId = getOutputPin(node, inputNode, inputs[i]);
int start = int(outputId.Get());
if (start >= 0)
{
// Connect the correct output pin to this input.
for (UiPinPtr outPin : inputNode->getOutputPins())
{
if (outPin->getPinId() == outputId)
{
outPin->setConnected(true);
outPin->addConnection(inputs[i]);
}
}
// Flag invalid connections via the core validation system.
bool invalid = addInvalidInputDiagnostic(
inputs[i]->getInput(), node->getName(), node->getId(),
mx::EMPTY_STRING, nullptr);
Link link(_state.nextUiId++, start, end, invalid);
if (!linkExists(link))
{
_state.links.push_back(link);
}
}
}
else if (inputs[i]->getInput())
{
if (inputs[i]->getInput()->getInterfaceInput())
{
inputs[i]->setConnected(true);
}
}
else
{
inputs[i]->setConnected(false);
}
}
}
}
// When at the top level, also scan all nested nodegraphs for type mismatches.
if (_parentStates.empty())
{
scanNestedGraphDiagnostics();
}
}
void Graph::scanNestedGraphDiagnostics()
{
for (mx::NodeGraphPtr ng : _graphDoc->getNodeGraphs())
{
const std::string& graphName = ng->getName();
for (mx::NodePtr node : ng->getNodes())
{
for (mx::InputPtr input : node->getInputs())
{
addInvalidInputDiagnostic(input, node->getName(), -1, graphName, ng);
}
}
}
}
void Graph::connectLinks()
{
for (Link const& link : _state.links)
{
if (link._invalid)
{
ed::Link(link._id, link._startAttr, link._endAttr, ImVec4(1.f, 0.1f, 0.1f, 1.f), 2.f);
}
else
{
ed::Link(link._id, link._startAttr, link._endAttr);
}
}
}
int Graph::findLinkPosition(int id)
{
int count = 0;
for (size_t i = 0; i < _state.links.size(); i++)
{
if (_state.links[i]._id == id)
{
return count;
}
count++;
}
return -1;
}
void Graph::applyLayout(const std::vector<int>& outputNodeIndices)
{
// If not auto-layouting and the first output node has saved positions, restore them.
if (!_autoLayout && !outputNodeIndices.empty())
{
UiNodePtr firstOutput = _state.nodes[outputNodeIndices[0]];
mx::ElementPtr elem = firstOutput->getElement();
if (elem && !elem->getAttribute(mx::Element::XPOS_ATTRIBUTE).empty())
{
restorePositions();
return;
}
}
// Build output node ID list from output node indices.
std::vector<int> outputNodeIds;
for (int idx : outputNodeIndices)
{
outputNodeIds.push_back(_state.nodes[idx]->getId());
}
// Compute layout directly from UI types.
LayoutResults results = _layout.compute(_state.nodes, _state.edges, outputNodeIds, _fontScale);
// Apply results to nodes.
for (const UiNodePtr& node : _state.nodes)
{
auto it = results.find(node->getId());
if (it != results.end())
{
ImVec2 pos(it->second[0], it->second[1]);
ed::SetNodePosition(node->getId(), pos);
node->setPos(pos);
}
}
}
void Graph::setPinColor()
{
_pinColor.emplace("integer", ImColor(255, 255, 28, 255));
_pinColor.emplace("boolean", ImColor(255, 0, 255, 255));
_pinColor.emplace("float", ImColor(50, 100, 255, 255));
_pinColor.emplace("color3", ImColor(178, 34, 34, 255));
_pinColor.emplace("color4", ImColor(50, 10, 255, 255));
_pinColor.emplace("vector2", ImColor(100, 255, 100, 255));
_pinColor.emplace("vector3", ImColor(0, 255, 0, 255));
_pinColor.emplace("vector4", ImColor(100, 0, 100, 255));
_pinColor.emplace("matrix33", ImColor(0, 100, 100, 255));
_pinColor.emplace("matrix44", ImColor(50, 255, 100, 255));
_pinColor.emplace("filename", ImColor(255, 184, 28, 255));
_pinColor.emplace("string", ImColor(100, 100, 50, 255));
_pinColor.emplace("geomname", ImColor(121, 60, 180, 255));
_pinColor.emplace("BSDF", ImColor(10, 181, 150, 255));
_pinColor.emplace("EDF", ImColor(255, 50, 100, 255));
_pinColor.emplace("VDF", ImColor(0, 100, 151, 255));
_pinColor.emplace(mx::SURFACE_SHADER_TYPE_STRING, ImColor(150, 255, 255, 255));
_pinColor.emplace(mx::MATERIAL_TYPE_STRING, ImColor(255, 255, 255, 255));
_pinColor.emplace(mx::DISPLACEMENT_SHADER_TYPE_STRING, ImColor(155, 50, 100, 255));
_pinColor.emplace(mx::VOLUME_SHADER_TYPE_STRING, ImColor(155, 250, 100, 255));
_pinColor.emplace(mx::LIGHT_SHADER_TYPE_STRING, ImColor(100, 150, 100, 255));
_pinColor.emplace("none", ImColor(140, 70, 70, 255));
_pinColor.emplace(mx::MULTI_OUTPUT_TYPE_STRING, ImColor(70, 70, 70, 255));
_pinColor.emplace("integerarray", ImColor(200, 10, 100, 255));
_pinColor.emplace("floatarray", ImColor(25, 250, 100));
_pinColor.emplace("color3array", ImColor(25, 200, 110));
_pinColor.emplace("color4array", ImColor(50, 240, 110));
_pinColor.emplace("vector2array", ImColor(50, 200, 75));
_pinColor.emplace("vector3array", ImColor(20, 200, 100));
_pinColor.emplace("vector4array", ImColor(100, 200, 100));
_pinColor.emplace("geomnamearray", ImColor(150, 200, 100));
_pinColor.emplace("stringarray", ImColor(120, 180, 100));
}
void Graph::setRenderMaterial(UiNodePtr node)
{
// For now only surface shaders and materials are considered renderable.
// This can be adjusted as desired to include being able to use outputs,
// and / a sub-graph in the nodegraph.
const mx::StringSet RENDERABLE_TYPES = { mx::MATERIAL_TYPE_STRING, mx::SURFACE_SHADER_TYPE_STRING };
// Set render node right away is node is renderable
if (node->getNode() && RENDERABLE_TYPES.count(node->getNode()->getType()))
{
// Only set new render node if different material has been selected
if (_currRenderNode != node)
{
_currRenderNode = node;
_frameCount = ImGui::GetFrameCount();
_renderer->setMaterialCompilation(true);
}
}
// Traverse downstream looking for the first renderable element.
else
{
mx::NodePtr mtlxNode = node->getNode();
mx::NodeGraphPtr mtlxNodeGraph = node->getNodeGraph();
mx::OutputPtr mtlxOutput = node->getOutput();
if (mtlxOutput)
{
mx::ElementPtr parent = mtlxOutput->getParent();
if (parent->isA<mx::NodeGraph>())
mtlxNodeGraph = parent->asA<mx::NodeGraph>();
else if (parent->isA<mx::Node>())
mtlxNode = parent->asA<mx::Node>();
else if (parent->isA<mx::Document>())
{
// Document-scope outputs are directly renderable.
if (_currRenderNode != node)
{
_currRenderNode = node;
_frameCount = ImGui::GetFrameCount();
_renderer->setMaterialCompilation(true);
}
return;
}
}
mx::StringSet testPaths;
if (mtlxNode)
{
mx::ElementPtr parent = mtlxNode->getParent();
if (parent->isA<mx::NodeGraph>())
{
// There is no logic to support traversing from inside a functional graph
// to it's instance and hence downstream so skip this from consideration.
// The closest approach would be to "flatten" all definitions to compound graphs.
mx::NodeGraphPtr parentGraph = parent->asA<mx::NodeGraph>();
if (parentGraph->getNodeDef())
{
return;
}
}
testPaths.insert(mtlxNode->getNamePath());
}
else if (mtlxNodeGraph)
{
// As above, there is no logic to support traversing from inside a functional graph.
// We add a check for output nodes to make sure it's accounted for in this case.
if (mtlxOutput)
{
if (mtlxNodeGraph->getNodeDef())
{
return;
}
}
testPaths.insert(mtlxNodeGraph->getNamePath());
}
mx::NodePtr foundNode = nullptr;
while (!testPaths.empty() && !foundNode)
{
mx::StringSet nextPaths;
for (const std::string& testPath : testPaths)
{
mx::ElementPtr testElem = _graphDoc->getDescendant(testPath);
mx::NodePtr testNode = testElem ? testElem->asA<mx::Node>() : nullptr;
std::vector<mx::PortElementPtr> downstreamPorts;
if (testNode)
{
downstreamPorts = testNode->getDownstreamPorts();
}
else
{
mx::NodeGraphPtr testGraph = testElem->asA<mx::NodeGraph>();
if (testGraph)
{
downstreamPorts = testGraph->getDownstreamPorts();
}
}
// Test all downstream ports. If the port's node is renderable
// then stop searching.
for (mx::PortElementPtr downstreamPort : downstreamPorts)
{
mx::ElementPtr parent = downstreamPort->getParent();
if (parent)
{
mx::NodePtr downstreamNode = parent->asA<mx::Node>();
if (downstreamNode)
{
mx::NodeDefPtr nodeDef = downstreamNode->getNodeDef();
if (nodeDef)
{
if (RENDERABLE_TYPES.count(nodeDef->getType()))
{
foundNode = downstreamNode;
break;
}
}
}
if (!foundNode)
{
nextPaths.insert(parent->getNamePath());
}
}
}
if (foundNode)
{
break;
}
}
// Set up next set of nodes to search downstream
testPaths = nextPaths;
}
// Update rendering. If found use that node, otherwise
// use the current fallback of using the first renderable node.
if (foundNode)
{
for (auto uiNode : _state.nodes)
{
if (uiNode->getNode() == foundNode)
{
if (_currRenderNode != uiNode)
{
_currRenderNode = uiNode;
_frameCount = ImGui::GetFrameCount();
_renderer->setMaterialCompilation(true);
}
break;
}
}
}
else
{
_currRenderNode = nullptr;
_frameCount = ImGui::GetFrameCount();
_renderer->setMaterialCompilation(true);
}
}
}
void Graph::updateMaterials(mx::InputPtr input /* = nullptr */, mx::ValuePtr value /* = nullptr */)
{
std::string renderablePath;
if (_currRenderNode)
{
if (_currRenderNode->getNode())
{
renderablePath = _currRenderNode->getNode()->getNamePath();
}
else if (_currRenderNode->getOutput())
{
renderablePath = _currRenderNode->getOutput()->getNamePath();
}
}
if (renderablePath.empty())
{
_renderer->updateMaterials(nullptr);
}
else
{
if (!input)
{
const mx::ElementPtr elem = _graphDoc->getDescendant(renderablePath);
mx::TypedElementPtr typedElem = elem ? elem->asA<mx::TypedElement>() : nullptr;
_renderer->updateMaterials(typedElem);
}
else
{
std::string name = input->getNamePath();
// Note that if there is a topogical change due to
// this value change or a transparency change, then
// this is not currently caught here.
_renderer->getMaterials()[0]->modifyUniform(name, value);
}
}
}
void Graph::showPropertyEditorValue(UiNodePtr node, mx::InputPtr input, const mx::UIProperties& uiProperties)
{
ImGui::PushItemWidth(-1);
mx::ValuePtr minVal = uiProperties.uiMin;
mx::ValuePtr maxVal = uiProperties.uiMax;
// If input is a float set the float slider UI to the value
if (input->getType() == "float")
{
mx::ValuePtr val = input->getValue();
if (val && val->isA<float>())
{
// Update the value to the default for new nodes
float prev, temp;
prev = temp = val->asA<float>();
float min = minVal ? minVal->asA<float>() : 0.f;
float max = maxVal ? maxVal->asA<float>() : 100.f;
float speed = (max - min) / 1000.0f;
ImGui::DragFloat("##hidelabel", &temp, speed, min, max);
// Set input value and update materials if different from previous value
if (prev != temp)
{
mx::InputPtr nodeInput = addNodeInput(_currUiNode, input);
nodeInput->setValue(temp, nodeInput->getType());
updateMaterials(nodeInput, nodeInput->getValue());
}
}
}
else if (input->getType() == "integer")
{
mx::ValuePtr val = input->getValue();
if (val && val->isA<int>())
{
int prev, temp;
prev = temp = val->asA<int>();
int min = minVal ? minVal->asA<int>() : 0;
int max = maxVal ? maxVal->asA<int>() : 100;
float speed = (max - min) / 100.0f;
ImGui::DragInt("##hidelabel", &temp, speed, min, max);
// Set input value and update materials if different from previous value
if (prev != temp)
{
mx::InputPtr nodeInput = addNodeInput(_currUiNode, input);
nodeInput->setValue(temp, nodeInput->getType());
updateMaterials(nodeInput, nodeInput->getValue());
}
}
}
else if (input->getType() == "color3")
{
mx::ValuePtr val = input->getValue();
if (val && val->isA<mx::Color3>())
{
mx::Color3 prev, temp;
// Read material value in converted display space
prev = temp = val->asA<mx::Color3>().linearToSrgb();
// Use ImGuiColorEditFlags_Uint8 flag for built-in Uint8 input fields
ImGui::ColorEdit3("##color", &temp[0], ImGuiColorEditFlags_Uint8);
if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled))
{
ImGui::SetTooltip("Color is selected and rendered to Viewer in sRGB display space, \nbut written to .mtlx file in linear format.");
}
// Set input value and update materials if different from previous value
if (prev != temp)
{
// Convert back to linear color space for writing to material and node input
mx::Color3 linearCol = temp.srgbToLinear();
mx::InputPtr nodeInput = addNodeInput(_currUiNode, input);
nodeInput->setValue(linearCol, nodeInput->getType());
updateMaterials(nodeInput, nodeInput->getValue());
}
}
}
else if (input->getType() == "color4")
{
mx::ValuePtr val = input->getValue();
if (val && val->isA<mx::Color4>())
{
// Read material value and convert RGB components to display space
mx::Color4 linearCol = val->asA<mx::Color4>();
mx::Color3 displayCol3 = mx::Color3(linearCol[0], linearCol[1], linearCol[2]).linearToSrgb();
mx::Color4 prev, temp;
// Create 4D vector with converted RGB and non-converted, stored Alpha value
prev = temp = mx::Color4(displayCol3[0], displayCol3[1], displayCol3[2], linearCol[3]);
// Use ImGuiColorEditFlags_Uint8 flag for built-in Uint8 input fields
ImGui::ColorEdit4("##color", &temp[0], ImGuiColorEditFlags_Uint8);
if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled))
{
ImGui::SetTooltip("Color is selected and rendered to Viewer in sRGB display space, \nbut written to .mtlx file in linear format.");
}
// Set input value and update materials if different from previous value
if (temp != prev)
{
// Convert back to linear color space for writing to material and node input
mx::Color3 linearCol3 = mx::Color3(temp[0], temp[1], temp[2]).srgbToLinear();
mx::Color4 linearCol = mx::Color4(linearCol3[0], linearCol3[1], linearCol3[2], temp[3]);
mx::InputPtr nodeInput = addNodeInput(_currUiNode, input);
nodeInput->setValue(linearCol, nodeInput->getType());
mx::ValuePtr linearVal = mx::Value::createValue<mx::Color4>(linearCol);
updateMaterials(nodeInput, linearVal);
}
}
}
else if (input->getType() == "vector2")
{
mx::ValuePtr val = input->getValue();
if (val && val->isA<mx::Vector2>())
{
mx::Vector2 prev, temp;
prev = temp = val->asA<mx::Vector2>();
float min = minVal ? minVal->asA<mx::Vector2>()[0] : 0.f;
float max = maxVal ? maxVal->asA<mx::Vector2>()[0] : 100.f;
float speed = (max - min) / 1000.0f;
ImGui::DragFloat2("##hidelabel", &temp[0], speed, min, max);
// Set input value and update materials if different from previous value
if (prev != temp)
{
mx::InputPtr nodeInput = addNodeInput(_currUiNode, input);
nodeInput->setValue(temp, nodeInput->getType());
updateMaterials(nodeInput, nodeInput->getValue());
}
}
}
else if (input->getType() == "vector3")
{
mx::ValuePtr val = input->getValue();
if (val && val->isA<mx::Vector3>())
{
mx::Vector3 prev, temp;
prev = temp = val->asA<mx::Vector3>();
float min = minVal ? minVal->asA<mx::Vector3>()[0] : 0.f;
float max = maxVal ? maxVal->asA<mx::Vector3>()[0] : 100.f;
float speed = (max - min) / 1000.0f;
ImGui::DragFloat3("##hidelabel", &temp[0], speed, min, max);
// Set input value and update materials if different from previous value
if (prev != temp)
{
mx::InputPtr nodeInput = addNodeInput(_currUiNode, input);
nodeInput->setValue(temp, nodeInput->getType());
updateMaterials(nodeInput, nodeInput->getValue());
}
}
}
else if (input->getType() == "vector4")
{
mx::ValuePtr val = input->getValue();
if (val && val->isA<mx::Vector4>())
{
mx::Vector4 prev, temp;
prev = temp = val->asA<mx::Vector4>();
float min = minVal ? minVal->asA<mx::Vector4>()[0] : 0.f;
float max = maxVal ? maxVal->asA<mx::Vector4>()[0] : 100.f;
float speed = (max - min) / 1000.0f;
ImGui::DragFloat4("##hidelabel", &temp[0], speed, min, max);
// Set input value and update materials if different from previous value
if (prev != temp)
{
mx::InputPtr nodeInput = addNodeInput(_currUiNode, input);
nodeInput->setValue(temp, nodeInput->getType());
updateMaterials(nodeInput, nodeInput->getValue());
}
}
}
else if (input->getType() == "string")
{
mx::ValuePtr val = input->getValue();
if (val && val->isA<std::string>())
{
std::string prev, temp;
prev = temp = val->asA<std::string>();
ImGui::InputText("##constant", &temp);
// Set input value and update materials if different from previous value
if (prev != temp)
{
mx::InputPtr nodeInput = addNodeInput(_currUiNode, input);
nodeInput->setValue(temp, nodeInput->getType());
updateMaterials();
}
}
}
else if (input->getType() == "filename")
{
mx::ValuePtr val = input->getResolvedValue();
if (val && val->isA<std::string>())
{
std::string prev, temp;
prev = temp = val->asA<std::string>();
mx::FilePath filePath(temp);