forked from AcademySoftwareFoundation/MaterialX
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Util.cpp
612 lines (563 loc) · 18.3 KB
/
Util.cpp
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
//
// TM & (c) 2017 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd.
// All rights reserved. See LICENSE.txt for license.
//
#include <MaterialXGenShader/Util.h>
#include <MaterialXGenShader/HwShaderGenerator.h>
MATERIALX_NAMESPACE_BEGIN
namespace
{
bool isEqual(const float& v1, const float& v2)
{
const float EPSILON = 0.00001f;
return std::abs(v1 - v2) < EPSILON;
}
bool isEqual(ValuePtr value, const float& f)
{
if (value->isA<float>() && isEqual(value->asA<float>(), f))
{
return true;
}
else if (value->isA<Color3>())
{
const Color3& color = value->asA<Color3>();
if (isEqual(color[0], f) && isEqual(color[1], f) && isEqual(color[2], f))
{
return true;
}
}
return false;
}
using OpaqueTestPair = std::pair<string, float>;
using OpaqueTestPairList = vector<OpaqueTestPair>;
// Get corresponding input for an interfacename for a nodegraph.
// The check is done for any corresponding nodedef first and then for
// any direct child input of the nodegraph.
InputPtr getInputInterface(const string& interfaceName , NodePtr node)
{
InputPtr interfaceInput = nullptr;
ElementPtr parent = node->getParent();
NodeGraphPtr nodeGraph = parent ? parent->asA<NodeGraph>() : nullptr;
if (nodeGraph)
{
NodeDefPtr nodeDef = nodeGraph->getNodeDef();
if (nodeDef)
{
interfaceInput = nodeDef->getInput(interfaceName);
}
else
{
interfaceInput = nodeGraph->getInput(interfaceName);
}
}
return interfaceInput;
}
bool hasTransparentInputs(const OpaqueTestPairList& opaqueInputList, NodePtr node)
{
for (auto opaqueInput : opaqueInputList)
{
InputPtr interfaceInput = node->getInput(opaqueInput.first);
if (interfaceInput)
{
if (interfaceInput->getConnectedNode())
{
return true;
}
ValuePtr value = interfaceInput->getValue();
if (value && !isEqual(value, opaqueInput.second))
{
return true;
}
}
}
return false;
}
bool isTransparentShaderNode(NodePtr node, NodePtr interfaceNode)
{
if (!node || node->getType() != SURFACE_SHADER_TYPE_STRING)
{
return false;
}
// Inputs on a surface shader which are checked for transparency
const OpaqueTestPairList inputPairList = { {"opacity", 1.0f},
{"existence", 1.0f},
{"alpha", 1.0f},
{"transmission", 0.0f} };
// Check against the interface if a node is passed in to check against
OpaqueTestPairList interfaceNames;
if (interfaceNode)
{
for (auto inputPair : inputPairList)
{
InputPtr checkInput = node->getActiveInput(inputPair.first);
if (checkInput)
{
const string& interfaceName = checkInput->getInterfaceName();
if (!interfaceName.empty())
{
interfaceNames.push_back(std::make_pair(interfaceName, inputPair.second));
}
}
}
if (!interfaceNames.empty())
{
if (hasTransparentInputs(interfaceNames, interfaceNode))
{
return true;
}
}
}
// Check against the child input or the corresponding
// functional nodegraph's interface if the input is mapped
// via an interface name.
for (auto inputPair : inputPairList)
{
InputPtr checkInput = node->getActiveInput(inputPair.first);
if (checkInput)
{
const string& interfaceName = checkInput->getInterfaceName();
if (!interfaceName.empty())
{
InputPtr interfaceInput = getInputInterface(interfaceName, node);
if (interfaceInput)
{
checkInput = interfaceInput;
}
else
{
return false;
}
}
// If mapped but not an adjustment then assume transparency
NodePtr inputNode = checkInput->getConnectedNode();
if (inputNode)
{
NodeDefPtr nodeDef = inputNode->getNodeDef();
if (nodeDef && nodeDef->getAttribute(NodeDef::NODE_GROUP_ATTRIBUTE) != NodeDef::ADJUSTMENT_NODE_GROUP)
{
return true;
}
}
else
{
ValuePtr value = checkInput->getValue();
if (value && !isEqual(value, inputPair.second))
{
return true;
}
}
}
}
return false;
}
bool isTransparentShaderGraph(OutputPtr output, const string& target, NodePtr interfaceNode)
{
for (GraphIterator it = output->traverseGraph().begin(); it != GraphIterator::end(); ++it)
{
ElementPtr upstreamElem = it.getUpstreamElement();
if (!upstreamElem)
{
continue;
}
if (upstreamElem->isA<Node>())
{
// Handle shader nodes.
NodePtr node = upstreamElem->asA<Node>();
if (isTransparentShaderNode(node, interfaceNode))
{
return true;
}
// Handle graph definitions.
NodeDefPtr nodeDef = node->getNodeDef();
if (nodeDef)
{
const TypeDesc* nodeDefType = TypeDesc::get(nodeDef->getType());
if (nodeDefType == Type::BSDF)
{
InterfaceElementPtr impl = nodeDef->getImplementation(target);
if (impl && impl->isA<NodeGraph>())
{
NodeGraphPtr graph = impl->asA<NodeGraph>();
vector<OutputPtr> outputs = graph->getActiveOutputs();
if (outputs.size() > 0)
{
const OutputPtr& graphOutput = outputs[0];
if (isTransparentShaderGraph(graphOutput, target, node))
{
return true;
}
}
}
}
}
}
}
return false;
}
}
bool isTransparentSurface(ElementPtr element, const string& target)
{
NodePtr node = element->asA<Node>();
if (node)
{
// Handle material nodes.
if (node->getCategory() == SURFACE_MATERIAL_NODE_STRING)
{
vector<NodePtr> shaderNodes = getShaderNodes(node);
if (!shaderNodes.empty())
{
node = shaderNodes[0];
}
}
// Handle shader nodes.
if (isTransparentShaderNode(node, nullptr))
{
return true;
}
// Handle graph definitions.
NodeDefPtr nodeDef = node->getNodeDef();
InterfaceElementPtr impl = nodeDef ? nodeDef->getImplementation(target) : nullptr;
if (impl && impl->isA<NodeGraph>())
{
NodeGraphPtr graph = impl->asA<NodeGraph>();
vector<OutputPtr> outputs = graph->getActiveOutputs();
if (!outputs.empty())
{
const OutputPtr& output = outputs[0];
if (output->getType() == SURFACE_SHADER_TYPE_STRING)
{
if (isTransparentShaderGraph(output, target, node))
{
return true;
}
}
}
}
}
else if (element->isA<Output>())
{
// Handle output elements.
OutputPtr output = element->asA<Output>();
NodePtr outputNode = output->getConnectedNode();
if (outputNode)
{
return isTransparentSurface(outputNode, target);
}
}
return false;
}
void mapValueToColor(ConstValuePtr value, Color4& color)
{
color = { 0.0, 0.0, 0.0, 1.0 };
if (!value)
{
return;
}
if (value->isA<float>())
{
color[0] = value->asA<float>();
}
else if (value->isA<Color3>())
{
Color3 v = value->asA<Color3>();
color[0] = v[0];
color[1] = v[1];
color[2] = v[2];
}
else if (value->isA<Color4>())
{
color = value->asA<Color4>();
}
else if (value->isA<Vector2>())
{
Vector2 v = value->asA<Vector2>();
color[0] = v[0];
color[1] = v[1];
}
else if (value->isA<Vector3>())
{
Vector3 v = value->asA<Vector3>();
color[0] = v[0];
color[1] = v[1];
color[2] = v[2];
}
else if (value->isA<Vector4>())
{
Vector4 v = value->asA<Vector4>();
color[0] = v[0];
color[1] = v[1];
color[2] = v[2];
color[3] = v[3];
}
}
bool requiresImplementation(ConstNodeDefPtr nodeDef)
{
if (!nodeDef)
{
return false;
}
static string ORGANIZATION_STRING("organization");
if (nodeDef->getNodeGroup() == ORGANIZATION_STRING)
{
return false;
}
static string TYPE_NONE("none");
const string& typeAttribute = nodeDef->getType();
return !typeAttribute.empty() && typeAttribute != TYPE_NONE;
}
bool elementRequiresShading(ConstTypedElementPtr element)
{
string elementType(element->getType());
static StringSet colorClosures =
{
"material", "surfaceshader", "volumeshader", "lightshader",
"BSDF", "EDF", "VDF"
};
return colorClosures.count(elementType) > 0;
}
void findRenderableMaterialNodes(ConstDocumentPtr doc,
vector<TypedElementPtr>& elements,
bool includeReferencedGraphs,
std::unordered_set<ElementPtr>& processedSources)
{
for (const NodePtr& material : doc->getMaterialNodes())
{
// Scan for any upstream shader outputs and put them on the "processed" list
// if we don't want to consider them for rendering.
vector<NodePtr> shaderNodes = getShaderNodes(material);
if (!shaderNodes.empty())
{
// Push the material node only once if any shader nodes are found
elements.push_back(material);
processedSources.insert(material);
if (!includeReferencedGraphs)
{
for (NodePtr shaderNode : shaderNodes)
{
for (InputPtr input : shaderNode->getActiveInputs())
{
OutputPtr outputPtr = input->getConnectedOutput();
if (outputPtr && !outputPtr->hasSourceUri() && !processedSources.count(outputPtr))
{
processedSources.insert(outputPtr);
}
}
}
}
}
}
}
void findRenderableElements(ConstDocumentPtr doc, vector<TypedElementPtr>& elements, bool includeReferencedGraphs)
{
std::unordered_set<ElementPtr> processedSources;
findRenderableMaterialNodes(doc, elements, includeReferencedGraphs, processedSources);
// Find node graph outputs. Skip any light shaders
vector<OutputPtr> testOutputs;
for (NodeGraphPtr nodeGraph : doc->getNodeGraphs())
{
// Skip anything from an include file including libraries.
// Skip any nodegraph which is a definition
if (!nodeGraph->hasSourceUri() && !nodeGraph->hasAttribute(InterfaceElement::NODE_DEF_ATTRIBUTE))
{
for (auto graphOutput : nodeGraph->getOutputs())
{
testOutputs.push_back(graphOutput);
}
}
}
// Add in all top-level outputs not already processed.
auto docOutputs = doc->getOutputs();
for (auto docOutput : docOutputs)
{
if (!docOutput->hasSourceUri())
{
testOutputs.push_back(docOutput);
}
}
for (OutputPtr output : testOutputs)
{
if (processedSources.count(output))
{
continue;
}
NodePtr node = output->getConnectedNode();
if (node && node->getType() != LIGHT_SHADER_TYPE_STRING)
{
NodeDefPtr nodeDef = node->getNodeDef();
if (!nodeDef)
{
throw ExceptionShaderGenError("Could not find a nodedef for node '" + node->getNamePath() + "'");
}
if (requiresImplementation(nodeDef))
{
if (node->getType() == MATERIAL_TYPE_STRING)
{
if (processedSources.count(node))
{
continue;
}
elements.push_back(node);
processedSources.insert(node);
}
else
{
elements.push_back(output);
}
}
}
processedSources.insert(output);
}
}
InputPtr getNodeDefInput(InputPtr nodeInput, const string& target)
{
ElementPtr parent = nodeInput ? nodeInput->getParent() : nullptr;
NodePtr node = parent ? parent->asA<Node>() : nullptr;
if (node)
{
NodeDefPtr nodeDef = node->getNodeDef(target);
if (nodeDef)
{
return nodeDef->getActiveInput(nodeInput->getName());
}
}
return nullptr;
}
namespace
{
const char TOKEN_PREFIX = '$';
}
void tokenSubstitution(const StringMap& substitutions, string& source)
{
string buffer;
size_t pos = 0, len = source.length();
while (pos < len)
{
size_t p1 = source.find_first_of(TOKEN_PREFIX, pos);
if (p1 != string::npos && p1 + 1 < len)
{
buffer += source.substr(pos, p1 - pos);
pos = p1 + 1;
string token = { TOKEN_PREFIX };
while (pos < len && isalnum(source[pos]))
{
token += source[pos++];
}
auto it = substitutions.find(token);
buffer += (it != substitutions.end() ? it->second : token);
}
else
{
buffer += source.substr(pos);
break;
}
}
source = buffer;
}
vector<Vector2> getUdimCoordinates(const StringVec& udimIdentifiers)
{
vector<Vector2> udimCoordinates;
if (udimIdentifiers.empty())
{
return udimCoordinates;
}
for (const string& udimIdentifier : udimIdentifiers)
{
if (udimIdentifier.empty())
{
continue;
}
int udimVal = std::stoi(udimIdentifier);
if (udimVal <= 1000 || udimVal >= 2000)
{
throw Exception("Invalid UDIM identifier specified" + udimIdentifier);
}
// Compute UDIM coordinate and add to list to return
udimVal -= 1000;
int uVal = udimVal % 10;
uVal = (uVal == 0) ? 9 : uVal - 1;
int vVal = (udimVal - uVal - 1) / 10;
udimCoordinates.emplace_back(static_cast<float>(uVal), static_cast<float>(vVal));
}
return udimCoordinates;
}
void getUdimScaleAndOffset(const vector<Vector2>& udimCoordinates, Vector2& scaleUV, Vector2& offsetUV)
{
if (udimCoordinates.empty())
{
return;
}
// Find range for lower left corner of each tile based on coordinate
Vector2 minUV = udimCoordinates[0];
Vector2 maxUV = udimCoordinates[0];
for (size_t i = 1; i < udimCoordinates.size(); i++)
{
if (udimCoordinates[i][0] < minUV[0])
{
minUV[0] = udimCoordinates[i][0];
}
if (udimCoordinates[i][1] < minUV[1])
{
minUV[1] = udimCoordinates[i][1];
}
if (udimCoordinates[i][0] > maxUV[0])
{
maxUV[0] = udimCoordinates[i][0];
}
if (udimCoordinates[i][1] > maxUV[1])
{
maxUV[1] = udimCoordinates[i][1];
}
}
// Extend to upper right corner of a tile
maxUV[0] += 1.0f;
maxUV[1] += 1.0f;
scaleUV[0] = 1.0f / (maxUV[0] - minUV[0]);
scaleUV[1] = 1.0f / (maxUV[1] - minUV[1]);
offsetUV[0] = -minUV[0];
offsetUV[1] = -minUV[1];
}
NodePtr connectsToWorldSpaceNode(OutputPtr output)
{
const StringSet WORLD_SPACE_NODE_CATEGORIES{ "normalmap" };
NodePtr connectedNode = output ? output->getConnectedNode() : nullptr;
if (connectedNode && WORLD_SPACE_NODE_CATEGORIES.count(connectedNode->getCategory()))
{
return connectedNode;
}
return nullptr;
}
bool hasElementAttributes(OutputPtr output, const StringVec& attributes)
{
if (!output || attributes.empty())
{
return false;
}
for (GraphIterator it = output->traverseGraph().begin(); it != GraphIterator::end(); ++it)
{
ElementPtr upstreamElem = it.getUpstreamElement();
NodePtr upstreamNode = upstreamElem ? upstreamElem->asA<Node>() : nullptr;
if (!upstreamNode)
{
it.setPruneSubgraph(true);
continue;
}
NodeDefPtr nodeDef = upstreamNode->getNodeDef();
for (ValueElementPtr nodeDefElement : nodeDef->getActiveValueElements())
{
ValueElementPtr testElement = upstreamNode->getActiveValueElement(nodeDefElement->getName());
if (!testElement)
{
testElement = nodeDefElement;
}
for (auto attr : attributes)
{
if (testElement->hasAttribute(attr))
{
return true;
}
}
}
}
return false;
}
MATERIALX_NAMESPACE_END