-
Notifications
You must be signed in to change notification settings - Fork 376
/
Copy pathViewer.cpp
2576 lines (2314 loc) · 91.8 KB
/
Viewer.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
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 <MaterialXView/Viewer.h>
#include <MaterialXView/RenderPipeline.h>
#ifdef MATERIALXVIEW_METAL_BACKEND
#include <MaterialXView/RenderPipelineMetal.h>
#include <MaterialXGenMsl/MslShaderGenerator.h>
#include <nanogui/metal.h>
#else
#include <MaterialXRenderGlsl/GLUtil.h>
#include <MaterialXView/RenderPipelineGL.h>
#include <MaterialXGenGlsl/GlslShaderGenerator.h>
#endif
#include <MaterialXRender/ShaderRenderer.h>
#include <MaterialXRender/CgltfLoader.h>
#include <MaterialXRender/Harmonics.h>
#include <MaterialXRender/OiioImageLoader.h>
#include <MaterialXRender/StbImageLoader.h>
#include <MaterialXRender/TinyObjLoader.h>
#include <MaterialXGenShader/DefaultColorManagementSystem.h>
#include <MaterialXGenShader/ShaderTranslator.h>
#ifdef MATERIALX_BUILD_OCIO
#include <MaterialXGenShader/OcioColorManagementSystem.h>
#endif
#if MATERIALX_BUILD_GEN_MDL
#include <MaterialXGenMdl/MdlShaderGenerator.h>
#endif
#if MATERIALX_BUILD_GEN_OSL
#include <MaterialXGenOsl/OslShaderGenerator.h>
#endif
#include <MaterialXGenGlsl/EsslShaderGenerator.h>
#include <MaterialXFormat/Environ.h>
#include <MaterialXFormat/Util.h>
#include <nanogui/icons.h>
#include <nanogui/messagedialog.h>
#include <nanogui/opengl.h>
#include <nanogui/vscrollpanel.h>
#include <fstream>
#include <iostream>
#include <iomanip>
const mx::Vector3 DEFAULT_CAMERA_POSITION(0.0f, 0.0f, 5.0f);
const float DEFAULT_CAMERA_VIEW_ANGLE = 45.0f;
const float DEFAULT_CAMERA_ZOOM = 1.0f;
namespace
{
#ifdef MATERIALXVIEW_METAL_BACKEND
const bool USE_FLOAT_BUFFER = true;
#else
const bool USE_FLOAT_BUFFER = false;
#endif
const int MIN_ENV_SAMPLE_COUNT = 4;
const int MAX_ENV_SAMPLE_COUNT = 1024;
const int SHADOW_MAP_SIZE = 2048;
const int ALBEDO_TABLE_SIZE = 128;
const int IRRADIANCE_MAP_WIDTH = 256;
const int IRRADIANCE_MAP_HEIGHT = 128;
const std::string DIR_LIGHT_NODE_CATEGORY = "directional_light";
const std::string IRRADIANCE_MAP_FOLDER = "irradiance";
const float ORTHO_VIEW_DISTANCE = 1000.0f;
const float ORTHO_PROJECTION_HEIGHT = 1.8f;
const float ENV_MAP_SPLIT_RADIANCE = 16.0f;
const float MAX_ENV_TEXEL_RADIANCE = 100000.0f;
const float IDEAL_ENV_MAP_RADIANCE = 6.0f;
const float IDEAL_MESH_SPHERE_RADIUS = 2.0f;
const float PI = std::acos(-1.0f);
void writeTextFile(const std::string& text, const std::string& filePath)
{
std::ofstream file;
file.open(filePath);
file << text;
file.close();
}
void applyModifiers(mx::DocumentPtr doc, const DocumentModifiers& modifiers)
{
for (mx::ElementPtr elem : doc->traverseTree())
{
if (modifiers.remapElements.count(elem->getCategory()))
{
elem->setCategory(modifiers.remapElements.at(elem->getCategory()));
}
if (modifiers.remapElements.count(elem->getName()))
{
elem->setName(modifiers.remapElements.at(elem->getName()));
}
mx::StringVec attrNames = elem->getAttributeNames();
for (const std::string& attrName : attrNames)
{
if (modifiers.remapElements.count(elem->getAttribute(attrName)))
{
elem->setAttribute(attrName, modifiers.remapElements.at(elem->getAttribute(attrName)));
}
}
if (elem->hasFilePrefix() && !modifiers.filePrefixTerminator.empty())
{
std::string filePrefix = elem->getFilePrefix();
if (!mx::stringEndsWith(filePrefix, modifiers.filePrefixTerminator))
{
elem->setFilePrefix(filePrefix + modifiers.filePrefixTerminator);
}
}
mx::ElementVec children = elem->getChildren();
for (mx::ElementPtr child : children)
{
if (modifiers.skipElements.count(child->getCategory()) ||
modifiers.skipElements.count(child->getName()))
{
elem->removeChild(child->getName());
}
}
}
// Remap unsupported texture coordinate indices.
for (mx::ElementPtr elem : doc->traverseTree())
{
mx::NodePtr node = elem->asA<mx::Node>();
if (node && node->getCategory() == "texcoord")
{
mx::InputPtr index = node->getInput("index");
mx::ValuePtr value = index ? index->getValue() : nullptr;
if (value && value->isA<int>() && value->asA<int>() != 0)
{
index->setValue(0);
}
}
}
}
} // anonymous namespace
//
// Viewer methods
//
Viewer::Viewer(const std::string& materialFilename,
const std::string& meshFilename,
const std::string& envRadianceFilename,
const mx::FileSearchPath& searchPath,
const mx::FilePathVec& libraryFolders,
int screenWidth,
int screenHeight,
const mx::Color3& screenColor) :
ng::Screen(ng::Vector2i(screenWidth, screenHeight), "MaterialXView",
true, false, true, true, USE_FLOAT_BUFFER, 4, 0),
_materialFilename(materialFilename),
_meshFilename(meshFilename),
_envRadianceFilename(envRadianceFilename),
_searchPath(searchPath),
_libraryFolders(libraryFolders),
_meshScale(1.0f),
_turntableEnabled(false),
_turntableSteps(360),
_turntableStep(0),
_cameraPosition(DEFAULT_CAMERA_POSITION),
_cameraUp(0.0f, 1.0f, 0.0f),
_cameraViewAngle(DEFAULT_CAMERA_VIEW_ANGLE),
_cameraNearDist(0.05f),
_cameraFarDist(5000.0f),
_cameraZoom(DEFAULT_CAMERA_ZOOM),
_userCameraEnabled(true),
_userTranslationActive(false),
_lightRotation(0.0f),
_normalizeEnvironment(false),
_splitDirectLight(false),
_generateReferenceIrradiance(false),
_saveGeneratedLights(false),
_shadowSoftness(1),
_ambientOcclusionGain(0.6f),
_selectedGeom(0),
_selectedMaterial(0),
_identityCamera(mx::Camera::create()),
_viewCamera(mx::Camera::create()),
_envCamera(mx::Camera::create()),
_shadowCamera(mx::Camera::create()),
_lightHandler(mx::LightHandler::create()),
_typeSystem(mx::TypeSystem::create()),
#ifndef MATERIALXVIEW_METAL_BACKEND
_genContext(mx::GlslShaderGenerator::create(_typeSystem)),
_genContextEssl(mx::EsslShaderGenerator::create(_typeSystem)),
#else
_genContext(mx::MslShaderGenerator::create(_typeSystem)),
#endif
#if MATERIALX_BUILD_GEN_OSL
_genContextOsl(mx::OslShaderGenerator::create(_typeSystem)),
#endif
#if MATERIALX_BUILD_GEN_MDL
_genContextMdl(mx::MdlShaderGenerator::create(_typeSystem)),
#endif
_unitRegistry(mx::UnitConverterRegistry::create()),
_drawEnvironment(false),
_outlineSelection(false),
_renderTransparency(true),
_renderDoubleSided(true),
_colorTexture(nullptr),
_splitByUdims(true),
_mergeMaterials(false),
_showAllInputs(false),
_flattenSubgraphs(false),
_targetShader("standard_surface"),
_captureRequested(false),
_exitRequested(false),
_wedgeRequested(false),
_wedgePropertyName("base"),
_wedgePropertyMin(0.0f),
_wedgePropertyMax(1.0f),
_wedgeImageCount(8),
_bakeHdr(false),
_bakeAverage(false),
_bakeOptimize(true),
_bakeRequested(false),
_bakeWidth(0),
_bakeHeight(0),
_bakeDocumentPerMaterial(false),
_frameTiming(false),
_avgFrameTime(0.0)
{
// Resolve input filenames, taking both the provided search path and
// current working directory into account.
mx::FileSearchPath localSearchPath = searchPath;
localSearchPath.append(mx::FilePath::getCurrentPath());
_materialFilename = localSearchPath.find(_materialFilename);
_meshFilename = localSearchPath.find(_meshFilename);
_envRadianceFilename = localSearchPath.find(_envRadianceFilename);
// Set the requested background color.
set_background(ng::Color(screenColor[0], screenColor[1], screenColor[2], 1.0f));
// Set default Glsl generator options.
_genContext.getOptions().targetColorSpaceOverride = "lin_rec709";
_genContext.getOptions().fileTextureVerticalFlip = true;
_genContext.getOptions().hwShadowMap = true;
_genContext.getOptions().hwImplicitBitangents = false;
#ifdef MATERIALXVIEW_METAL_BACKEND
_renderPipeline = MetalRenderPipeline::create(this);
_renderPipeline->initialize(ng::metal_device(),
ng::metal_command_queue());
#else
_renderPipeline = GLRenderPipeline::create(this);
// Set Essl generator options
_genContextEssl.getOptions().targetColorSpaceOverride = "lin_rec709";
_genContextEssl.getOptions().fileTextureVerticalFlip = false;
_genContextEssl.getOptions().hwMaxActiveLightSources = 1;
#endif
#if MATERIALX_BUILD_GEN_OSL
// Set OSL generator options.
_genContextOsl.getOptions().targetColorSpaceOverride = "lin_rec709";
_genContextOsl.getOptions().fileTextureVerticalFlip = false;
#endif
#if MATERIALX_BUILD_GEN_MDL
// Set MDL generator options.
_genContextMdl.getOptions().targetColorSpaceOverride = "lin_rec709";
_genContextMdl.getOptions().fileTextureVerticalFlip = false;
#endif
}
void Viewer::initialize()
{
_window = new ng::Window(this, "Viewer Options");
_window->set_position(ng::Vector2i(15, 15));
_window->set_layout(new ng::GroupLayout());
// Initialize the standard libraries and color/unit management.
loadStandardLibraries();
// Initialize image handler.
_imageHandler = _renderPipeline->createImageHandler();
#if MATERIALX_BUILD_OIIO
_imageHandler->addLoader(mx::OiioImageLoader::create());
#endif
_imageHandler->setSearchPath(_searchPath);
// Initialize user interfaces.
createLoadMeshInterface((ng::ref<ng::Widget>) _window, "Load Mesh");
createLoadMaterialsInterface((ng::ref<ng::Widget>) _window, "Load Material");
createLoadEnvironmentInterface((ng::ref<ng::Widget>) _window, "Load Environment");
createPropertyEditorInterface((ng::ref<ng::Widget>) _window, "Property Editor");
createAdvancedSettings((ng::ref<ng::Widget>) _window);
// Create geometry selection box.
_geomLabel = new ng::Label(_window, "Select Geometry");
_geometrySelectionBox = new ng::ComboBox(_window, { "None" });
_geometrySelectionBox->set_chevron_icon(-1);
_geometrySelectionBox->set_callback([this](int choice)
{
size_t index = (size_t) choice;
if (index < _geometryList.size())
{
_selectedGeom = index;
if (_materialAssignments.count(getSelectedGeometry()))
{
setSelectedMaterial(_materialAssignments[getSelectedGeometry()]);
}
updateDisplayedProperties();
updateMaterialSelectionUI();
}
});
// Create material selection box.
_materialLabel = new ng::Label(_window, "Assigned Material");
_materialSelectionBox = new ng::ComboBox(_window, { "None" });
_materialSelectionBox->set_chevron_icon(-1);
_materialSelectionBox->set_callback([this](int choice)
{
size_t index = (size_t) choice;
if (index < _materials.size())
{
// Update selected material index
_selectedMaterial = index;
// Assign selected material to geometry
assignMaterial(getSelectedGeometry(), _materials[index]);
}
});
// Create frame timing display
if (_frameTiming)
{
_timingLabel = new ng::Label(_window, "Timing");
_timingPanel = new ng::Widget(_window);
_timingPanel->set_layout(new ng::BoxLayout(ng::Orientation::Horizontal,
ng::Alignment::Middle, 0, 6));
new ng::Label(_timingPanel, "Frame time:");
_timingText = new ng::TextBox(_timingPanel);
_timingText->set_value("0");
_timingText->set_units(" ms");
_timingText->set_fixed_size(ng::Vector2i(80, 25));
_timingText->set_alignment(ng::TextBox::Alignment::Right);
}
// Create geometry handler.
mx::TinyObjLoaderPtr objLoader = mx::TinyObjLoader::create();
mx::CgltfLoaderPtr gltfLoader = mx::CgltfLoader::create();
_geometryHandler = mx::GeometryHandler::create();
_geometryHandler->addLoader(objLoader);
_geometryHandler->addLoader(gltfLoader);
loadMesh(_searchPath.find(_meshFilename));
_renderPipeline->initFramebuffer(width(), height(), nullptr);
// Create environment geometry handler.
_envGeometryHandler = mx::GeometryHandler::create();
_envGeometryHandler->addLoader(objLoader);
mx::FilePath envSphere("resources/Geometry/sphere.obj");
_envGeometryHandler->loadGeometry(_searchPath.find(envSphere));
// Initialize environment light.
loadEnvironmentLight();
// Initialize camera.
initCamera();
set_resize_callback([this](ng::Vector2i size)
{
#ifdef MATERIALXVIEW_METAL_BACKEND
_colorTexture = metal_texture();
#endif
_renderPipeline->resizeFramebuffer(size.x(), size.y(), _colorTexture);
_viewCamera->setViewportSize(mx::Vector2(static_cast<float>(size[0]), static_cast<float>(size[1])));
});
// Update geometry selections.
updateGeometrySelections();
// Load the requested material document.
loadDocument(_materialFilename, _stdLib);
// Finalize the UI.
_propertyEditor.setVisible(false);
perform_layout();
_turntableTimer.startTimer();
}
void Viewer::loadEnvironmentLight()
{
// Load the requested radiance map.
mx::ImagePtr envRadianceMap = _imageHandler->acquireImage(_envRadianceFilename);
if (!envRadianceMap)
{
new ng::MessageDialog(this, ng::MessageDialog::Type::Warning, "Failed to load environment light");
return;
}
// If requested, normalize the environment upon loading.
if (_normalizeEnvironment)
{
envRadianceMap = mx::normalizeEnvironment(envRadianceMap, IDEAL_ENV_MAP_RADIANCE, MAX_ENV_TEXEL_RADIANCE);
if (_saveGeneratedLights)
{
_imageHandler->saveImage("NormalizedRadiance.hdr", envRadianceMap);
}
}
// If requested, split the environment into indirect and direct components.
if (_splitDirectLight)
{
splitDirectLight(envRadianceMap, envRadianceMap, _lightRigDoc);
if (_saveGeneratedLights)
{
_imageHandler->saveImage("IndirectRadiance.hdr", envRadianceMap);
mx::writeToXmlFile(_lightRigDoc, "DirectLightRig.mtlx");
}
}
// Look for an irradiance map using an expected filename convention.
mx::ImagePtr envIrradianceMap;
if (!_normalizeEnvironment && !_splitDirectLight)
{
mx::FilePath envIrradiancePath = _envRadianceFilename.getParentPath() / IRRADIANCE_MAP_FOLDER / _envRadianceFilename.getBaseName();
envIrradianceMap = _imageHandler->acquireImage(envIrradiancePath);
}
// If not found, then generate an irradiance map via spherical harmonics.
if (!envIrradianceMap || envIrradianceMap->getWidth() == 1)
{
if (_generateReferenceIrradiance)
{
envIrradianceMap = mx::renderReferenceIrradiance(envRadianceMap, IRRADIANCE_MAP_WIDTH, IRRADIANCE_MAP_HEIGHT);
if (_saveGeneratedLights)
{
_imageHandler->saveImage("ReferenceIrradiance.hdr", envIrradianceMap);
}
}
else
{
mx::Sh3ColorCoeffs shIrradiance = mx::projectEnvironment(envRadianceMap, true);
envIrradianceMap = mx::renderEnvironment(shIrradiance, IRRADIANCE_MAP_WIDTH, IRRADIANCE_MAP_HEIGHT);
if (_saveGeneratedLights)
{
_imageHandler->saveImage("SphericalHarmonicIrradiance.hdr", envIrradianceMap);
}
}
}
// Release any existing environment maps and store the new ones.
_imageHandler->releaseRenderResources(_lightHandler->getEnvRadianceMap());
_imageHandler->releaseRenderResources(_lightHandler->getEnvPrefilteredMap());
_imageHandler->releaseRenderResources(_lightHandler->getEnvIrradianceMap());
_lightHandler->setEnvRadianceMap(envRadianceMap);
_lightHandler->setEnvIrradianceMap(envIrradianceMap);
_lightHandler->setEnvPrefilteredMap(nullptr);
// Look for a light rig using an expected filename convention.
if (!_splitDirectLight)
{
_lightRigFilename = _envRadianceFilename;
_lightRigFilename.removeExtension();
_lightRigFilename.addExtension(mx::MTLX_EXTENSION);
_lightRigFilename = _searchPath.find(_lightRigFilename);
if (_lightRigFilename.exists())
{
_lightRigDoc = mx::createDocument();
mx::readFromXmlFile(_lightRigDoc, _lightRigFilename, _searchPath);
}
else
{
_lightRigDoc = nullptr;
}
}
// Invalidate the existing environment material, if any.
_envMaterial = nullptr;
}
void Viewer::applyDirectLights(mx::DocumentPtr doc)
{
if (_lightRigDoc)
{
doc->importLibrary(_lightRigDoc);
_xincludeFiles.insert(_lightRigFilename);
}
try
{
std::vector<mx::NodePtr> lights;
_lightHandler->findLights(doc, lights);
_lightHandler->registerLights(doc, lights, _genContext);
#ifndef MATERIALXVIEW_METAL_BACKEND
_lightHandler->registerLights(doc, lights, _genContextEssl);
#endif
_lightHandler->setLightSources(lights);
}
catch (std::exception& e)
{
new ng::MessageDialog(this, ng::MessageDialog::Type::Warning, "Failed to set up lighting", e.what());
}
}
void Viewer::assignMaterial(mx::MeshPartitionPtr geometry, mx::MaterialPtr material)
{
if (!geometry || _geometryHandler->getMeshes().empty())
{
return;
}
if (geometry == getSelectedGeometry())
{
setSelectedMaterial(material);
if (material)
{
updateDisplayedProperties();
}
}
if (material)
{
_materialAssignments[geometry] = material;
material->unbindGeometry();
}
else
{
_materialAssignments.erase(geometry);
}
}
mx::FilePath Viewer::getBaseOutputPath()
{
mx::FilePath baseFilename = _searchPath.find(_materialFilename);
baseFilename.removeExtension();
mx::FilePath outputPath = mx::getEnviron("MATERIALX_VIEW_OUTPUT_PATH");
if (!outputPath.isEmpty())
{
baseFilename = outputPath / baseFilename.getBaseName();
}
return baseFilename;
}
mx::ElementPredicate Viewer::getElementPredicate()
{
return [this](mx::ConstElementPtr elem)
{
if (elem->hasSourceUri())
{
return (_xincludeFiles.count(elem->getSourceUri()) == 0);
}
return true;
};
}
void Viewer::createLoadMeshInterface(ng::ref<Widget> parent, const std::string& label)
{
ng::ref<ng::Button> meshButton = new ng::Button(parent, label);
meshButton->set_icon(FA_FOLDER);
meshButton->set_tooltip("Load a new geometry in the OBJ or glTF format.");
meshButton->set_callback([this]()
{
m_process_events = false;
std::string filename = ng::file_dialog(
{
{ "obj", "Wavefront OBJ" },
{ "gltf", "GLTF ASCII" },
{ "glb", "GLTF Binary"}
}, false);
if (!filename.empty())
{
loadMesh(filename);
_meshRotation = mx::Vector3();
_meshScale = 1.0f;
_cameraTarget = mx::Vector3();
initCamera();
}
m_process_events = true;
});
}
void Viewer::createLoadMaterialsInterface(ng::ref<Widget> parent, const std::string& label)
{
ng::ref<ng::Button> materialButton = new ng::Button(parent, label);
materialButton->set_icon(FA_FOLDER);
materialButton->set_tooltip("Load a material document in the MTLX format.");
materialButton->set_callback([this]()
{
m_process_events = false;
std::string filename = ng::file_dialog({ { "mtlx", "MaterialX" } }, false);
if (!filename.empty())
{
_materialFilename = filename;
loadDocument(_materialFilename, _stdLib);
}
m_process_events = true;
});
}
void Viewer::createLoadEnvironmentInterface(ng::ref<Widget> parent, const std::string& label)
{
ng::ref<ng::Button> envButton = new ng::Button(parent, label);
envButton->set_icon(FA_FOLDER);
envButton->set_tooltip("Load a lat-long environment light in the HDR format.");
envButton->set_callback([this]()
{
m_process_events = false;
mx::StringSet extensions = _imageHandler->supportedExtensions();
std::vector<std::pair<std::string, std::string>> filetypes;
for (const auto& extension : extensions)
{
filetypes.emplace_back(extension, extension);
}
std::string filename = ng::file_dialog(filetypes, false);
if (!filename.empty())
{
_envRadianceFilename = filename;
loadEnvironmentLight();
loadDocument(_materialFilename, _stdLib);
invalidateShadowMap();
}
m_process_events = true;
});
}
void Viewer::createSaveMaterialsInterface(ng::ref<Widget> parent, const std::string& label)
{
ng::ref<ng::Button> materialButton = new ng::Button(parent, label);
materialButton->set_icon(FA_SAVE);
materialButton->set_tooltip("Save a material document in the MTLX format.");
materialButton->set_callback([this]()
{
m_process_events = false;
mx::MaterialPtr material = getSelectedMaterial();
mx::FilePath filename = ng::file_dialog({ { "mtlx", "MaterialX" } }, true);
// Save document
if (material && !filename.isEmpty())
{
if (filename.getExtension() != mx::MTLX_EXTENSION)
{
filename.addExtension(mx::MTLX_EXTENSION);
}
mx::XmlWriteOptions writeOptions;
writeOptions.elementPredicate = getElementPredicate();
mx::writeToXmlFile(material->getDocument(), filename, &writeOptions);
// Update material file name
_materialFilename = filename;
}
m_process_events = true;
});
}
void Viewer::createPropertyEditorInterface(ng::ref<Widget> parent, const std::string& label)
{
ng::ref<ng::Button> editorButton = new ng::Button(parent, label);
editorButton->set_flags(ng::Button::ToggleButton);
editorButton->set_tooltip("View or edit properties of the current material.");
editorButton->set_change_callback([this](bool state)
{
_propertyEditor.setVisible(state);
perform_layout();
});
}
void Viewer::createDocumentationInterface(ng::ref<Widget> parent)
{
ng::ref<ng::GridLayout> documentationLayout = new ng::GridLayout(ng::Orientation::Vertical, 3,
ng::Alignment::Minimum, 13, 5);
documentationLayout->set_row_alignment({ ng::Alignment::Minimum, ng::Alignment::Maximum });
ng::ref<ng::Widget> documentationGroup = new ng::Widget(parent);
documentationGroup->set_layout(documentationLayout);
ng::ref<ng::Label> documentationLabel = new ng::Label(documentationGroup, "Documentation");
documentationLabel->set_font_size(20);
documentationLabel->set_font("sans-bold");
_shortcutsButton = new ng::Button(documentationGroup, "Keyboard Shortcuts");
_shortcutsButton->set_flags(ng::Button::ToggleButton);
_shortcutsButton->set_icon(FA_CARET_RIGHT);
_shortcutsButton->set_fixed_width(230);
_shortcutsTable = new ng::Widget(documentationGroup);
_shortcutsTable->set_layout(new ng::GroupLayout(13));
_shortcutsTable->set_visible(false);
// Recompute layout when showing/hiding shortcuts.
_shortcutsButton->set_change_callback([this](bool state)
{
_shortcutsButton->set_icon(state ? FA_CARET_DOWN : FA_CARET_RIGHT);
_shortcutsTable->set_visible(state);
perform_layout();
});
// 2 cell layout for (key, description) pair.
ng::ref<ng::GridLayout> gridLayout2 = new ng::GridLayout(ng::Orientation::Horizontal, 2,
ng::Alignment::Minimum, 2, 2);
gridLayout2->set_col_alignment({ ng::Alignment::Minimum, ng::Alignment::Maximum });
const std::array<std::pair<std::string, std::string>, 16> KEYBOARD_SHORTCUTS =
{
std::make_pair("R", "Reload the current material from file. "
"Hold SHIFT to reload all standard libraries as well."),
std::make_pair("G", "Save the current GLSL shader source to file."),
std::make_pair("O", "Save the current OSL shader source to file."),
std::make_pair("M", "Save the current MDL shader source to file."),
std::make_pair("L", "Load GLSL shader source from file. "
"Editing the source files before loading provides a way "
"to debug and experiment with shader source code."),
std::make_pair("D", "Save each node graph in the current material as a DOT file. "
"See www.graphviz.org for more details on this format."),
std::make_pair("F", "Capture the current frame and save to file."),
std::make_pair("W", "Create a wedge rendering and save to file. "
"See Advanced Settings for additional controls."),
std::make_pair("T", "Translate the current material to a different shading model. "
"See Advanced Settings for additional controls."),
std::make_pair("B", "Bake the current material to textures. "
"See Advanced Settings for additional controls."),
std::make_pair("UP","Select the previous geometry."),
std::make_pair("DOWN","Select the next geometry."),
std::make_pair("RIGHT", "Switch to the next material."),
std::make_pair("LEFT", "Switch to the previous material."),
std::make_pair("+", "Zoom in with the camera."),
std::make_pair("-", "Zoom out with the camera.")
};
for (const auto& shortcut : KEYBOARD_SHORTCUTS)
{
ng::ref<ng::Widget> twoColumns = new ng::Widget(_shortcutsTable);
twoColumns->set_layout(gridLayout2);
ng::ref<ng::Label> keyLabel = new ng::Label(twoColumns, shortcut.first);
keyLabel->set_font("sans-bold");
keyLabel->set_font_size(16);
keyLabel->set_fixed_width(40);
ng::ref<ng::Label> descriptionLabel = new ng::Label(twoColumns, shortcut.second);
descriptionLabel->set_font_size(16);
descriptionLabel->set_fixed_width(160);
}
}
void Viewer::createAdvancedSettings(ng::ref<Widget> parent)
{
ng::ref<ng::PopupButton> advancedButton = new ng::PopupButton(parent, "Advanced Settings");
advancedButton->set_icon(FA_TOOLS);
advancedButton->set_chevron_icon(-1);
advancedButton->set_tooltip("Asset and rendering options.");
ng::ref<ng::Popup> advancedPopupParent = advancedButton->popup();
advancedPopupParent->set_layout(new ng::GroupLayout());
ng::ref<ng::VScrollPanel> scrollPanel = new ng::VScrollPanel(advancedPopupParent);
scrollPanel->set_fixed_height(500);
ng::ref<ng::Widget> advancedPopup = new ng::Widget(scrollPanel);
advancedPopup->set_layout(new ng::BoxLayout(ng::Orientation::Vertical));
ng::ref<ng::Widget> settingsGroup = new ng::Widget(advancedPopup);
settingsGroup->set_layout(new ng::GroupLayout(13));
ng::ref<ng::Label> viewLabel = new ng::Label(settingsGroup, "Viewing Options");
viewLabel->set_font_size(20);
viewLabel->set_font("sans-bold");
ng::ref<ng::CheckBox> drawEnvironmentBox = new ng::CheckBox(settingsGroup, "Draw Environment");
drawEnvironmentBox->set_checked(_drawEnvironment);
drawEnvironmentBox->set_callback([this](bool enable)
{
_drawEnvironment = enable;
});
ng::ref<ng::CheckBox> outlineSelectedGeometryBox = new ng::CheckBox(settingsGroup, "Outline Selected Geometry");
outlineSelectedGeometryBox->set_checked(_outlineSelection);
outlineSelectedGeometryBox->set_callback([this](bool enable)
{
_outlineSelection = enable;
});
ng::ref<ng::Label> renderLabel = new ng::Label(settingsGroup, "Render Options");
renderLabel->set_font_size(20);
renderLabel->set_font("sans-bold");
ng::ref<ng::CheckBox> transparencyBox = new ng::CheckBox(settingsGroup, "Render Transparency");
transparencyBox->set_checked(_renderTransparency);
transparencyBox->set_callback([this](bool enable)
{
_renderTransparency = enable;
});
ng::ref<ng::CheckBox> doubleSidedBox = new ng::CheckBox(settingsGroup, "Render Double-Sided");
doubleSidedBox->set_checked(_renderDoubleSided);
doubleSidedBox->set_callback([this](bool enable)
{
_renderDoubleSided = enable;
});
ng::ref<ng::CheckBox> importanceSampleBox = new ng::CheckBox(settingsGroup, "Environment FIS");
importanceSampleBox->set_checked(_genContext.getOptions().hwSpecularEnvironmentMethod == mx::SPECULAR_ENVIRONMENT_FIS);
_lightHandler->setUsePrefilteredMap(_genContext.getOptions().hwSpecularEnvironmentMethod != mx::SPECULAR_ENVIRONMENT_FIS);
importanceSampleBox->set_callback([this](bool enable)
{
_genContext.getOptions().hwSpecularEnvironmentMethod = enable ? mx::SPECULAR_ENVIRONMENT_FIS : mx::SPECULAR_ENVIRONMENT_PREFILTER;
#ifndef MATERIALXVIEW_METAL_BACKEND
_genContextEssl.getOptions().hwSpecularEnvironmentMethod = _genContext.getOptions().hwSpecularEnvironmentMethod;
#endif
_lightHandler->setUsePrefilteredMap(!enable);
reloadShaders();
});
ng::ref<ng::CheckBox> refractionBox = new ng::CheckBox(settingsGroup, "Transmission Refraction");
refractionBox->set_checked(_genContext.getOptions().hwTransmissionRenderMethod == mx::TRANSMISSION_REFRACTION);
refractionBox->set_callback([this](bool enable)
{
_genContext.getOptions().hwTransmissionRenderMethod = enable ? mx::TRANSMISSION_REFRACTION : mx::TRANSMISSION_OPACITY;
#ifndef MATERIALXVIEW_METAL_BACKEND
_genContextEssl.getOptions().hwTransmissionRenderMethod = _genContext.getOptions().hwTransmissionRenderMethod;
#endif
reloadShaders();
});
ng::ref<ng::CheckBox> refractionSidedBox = new ng::CheckBox(settingsGroup, "Refraction Two-Sided");
refractionSidedBox->set_checked(_lightHandler->getRefractionTwoSided());
refractionSidedBox->set_callback([this](bool enable)
{
_lightHandler->setRefractionTwoSided(enable);
});
ng::ref<ng::CheckBox> shaderInterfaceBox = new ng::CheckBox(settingsGroup, "Reduce Shader Interface");
shaderInterfaceBox->set_checked(_genContext.getOptions().shaderInterfaceType == mx::SHADER_INTERFACE_REDUCED);
shaderInterfaceBox->set_callback([this](bool enable)
{
mx::ShaderInterfaceType interfaceType = enable ? mx::SHADER_INTERFACE_REDUCED : mx::SHADER_INTERFACE_COMPLETE;
setShaderInterfaceType(interfaceType);
});
ng::ref<ng::Widget> albedoGroup = new Widget(settingsGroup);
albedoGroup->set_layout(new ng::BoxLayout(ng::Orientation::Horizontal));
new ng::Label(albedoGroup, "Albedo Method:");
mx::StringVec albedoOptions = { "Analytic", "Table", "MC" };
ng::ref<ng::ComboBox> albedoBox = new ng::ComboBox(albedoGroup, albedoOptions);
albedoBox->set_chevron_icon(-1);
albedoBox->set_selected_index((int) _genContext.getOptions().hwDirectionalAlbedoMethod );
albedoBox->set_callback([this](int index)
{
_genContext.getOptions().hwDirectionalAlbedoMethod = (mx::HwDirectionalAlbedoMethod) index;
reloadShaders();
try
{
_renderPipeline->updateAlbedoTable(ALBEDO_TABLE_SIZE);
}
catch (mx::ExceptionRenderError& e)
{
for (const std::string& error : e.errorLog())
{
std::cerr << error << std::endl;
}
new ng::MessageDialog(this, ng::MessageDialog::Type::Warning, "Shader generation error", e.what());
_materialAssignments.clear();
}
catch (std::exception& e)
{
new ng::MessageDialog(this, ng::MessageDialog::Type::Warning, "Failed to update albedo table", e.what());
_materialAssignments.clear();
}
});
ng::ref<ng::Widget> sampleGroup = new Widget(settingsGroup);
sampleGroup->set_layout(new ng::BoxLayout(ng::Orientation::Horizontal));
new ng::Label(sampleGroup, "Environment Samples:");
mx::StringVec sampleOptions;
for (int i = MIN_ENV_SAMPLE_COUNT; i <= MAX_ENV_SAMPLE_COUNT; i *= 4)
{
m_process_events = false;
sampleOptions.push_back(std::to_string(i));
m_process_events = true;
}
ng::ref<ng::ComboBox> sampleBox = new ng::ComboBox(sampleGroup, sampleOptions);
sampleBox->set_chevron_icon(-1);
sampleBox->set_selected_index((int)std::log2(_lightHandler->getEnvSampleCount() / MIN_ENV_SAMPLE_COUNT) / 2);
sampleBox->set_callback([this](int index)
{
_lightHandler->setEnvSampleCount(MIN_ENV_SAMPLE_COUNT * (int) std::pow(4, index));
});
ng::ref<ng::Label> lightingLabel = new ng::Label(settingsGroup, "Lighting Options");
lightingLabel->set_font_size(20);
lightingLabel->set_font("sans-bold");
ng::ref<ng::CheckBox> directLightingBox = new ng::CheckBox(settingsGroup, "Direct Lighting");
directLightingBox->set_checked(_lightHandler->getDirectLighting());
directLightingBox->set_callback([this](bool enable)
{
_lightHandler->setDirectLighting(enable);
});
ng::ref<ng::CheckBox> indirectLightingBox = new ng::CheckBox(settingsGroup, "Indirect Lighting");
indirectLightingBox->set_checked(_lightHandler->getIndirectLighting());
indirectLightingBox->set_callback([this](bool enable)
{
_lightHandler->setIndirectLighting(enable);
});
ng::ref<ng::Widget> lightRotationRow = new ng::Widget(settingsGroup);
lightRotationRow->set_layout(new ng::BoxLayout(ng::Orientation::Horizontal));
mx::UIProperties ui;
ui.uiMin = mx::Value::createValue(0.0f);
ui.uiMax = mx::Value::createValue(360.0f);
ng::ref<ng::FloatBox<float>> lightRotationBox = createFloatWidget(lightRotationRow, "Light Rotation:",
_lightRotation, &ui, [this](float value)
{
_lightRotation = value;
invalidateShadowMap();
});
lightRotationBox->set_editable(true);
ng::ref<ng::Label> shadowingLabel = new ng::Label(settingsGroup, "Shadowing Options");
shadowingLabel->set_font_size(20);
shadowingLabel->set_font("sans-bold");
ng::ref<ng::CheckBox> shadowMapBox = new ng::CheckBox(settingsGroup, "Shadow Map");
shadowMapBox->set_checked(_genContext.getOptions().hwShadowMap);
shadowMapBox->set_callback([this](bool enable)
{
_genContext.getOptions().hwShadowMap = enable;
reloadShaders();
});
ng::ref<ng::CheckBox> ambientOcclusionBox = new ng::CheckBox(settingsGroup, "Ambient Occlusion");
ambientOcclusionBox->set_checked(_genContext.getOptions().hwAmbientOcclusion);
ambientOcclusionBox->set_callback([this](bool enable)
{
_genContext.getOptions().hwAmbientOcclusion = enable;
reloadShaders();
});
ng::ref<ng::Widget> ambientOcclusionGainRow = new ng::Widget(settingsGroup);
ambientOcclusionGainRow->set_layout(new ng::BoxLayout(ng::Orientation::Horizontal));
ng::ref<ng::FloatBox<float>> ambientOcclusionGainBox = createFloatWidget(ambientOcclusionGainRow, "AO Gain:",
_ambientOcclusionGain, nullptr, [this](float value)
{
_ambientOcclusionGain = value;
});
ambientOcclusionGainBox->set_editable(true);
ng::ref<ng::Label> sceneLabel = new ng::Label(settingsGroup, "Scene Options");
sceneLabel->set_font_size(20);
sceneLabel->set_font("sans-bold");
ng::ref<Widget> unitGroup = new Widget(settingsGroup);
unitGroup->set_layout(new ng::BoxLayout(ng::Orientation::Horizontal));
new ng::Label(unitGroup, "Distance Unit:");
ng::ref<ng::ComboBox> distanceUnitBox = new ng::ComboBox(unitGroup, _distanceUnitOptions);
distanceUnitBox->set_fixed_size(ng::Vector2i(100, 20));
distanceUnitBox->set_chevron_icon(-1);
if (_distanceUnitConverter)
{
distanceUnitBox->set_selected_index(_distanceUnitConverter->getUnitAsInteger("meter"));
}
distanceUnitBox->set_callback([this](int index)
{
m_process_events = false;
_genContext.getOptions().targetDistanceUnit = _distanceUnitOptions[index];
#ifndef MATERIALXVIEW_METAL_BACKEND
_genContextEssl.getOptions().targetDistanceUnit = _distanceUnitOptions[index];
#endif
#if MATERIALX_BUILD_GEN_OSL
_genContextOsl.getOptions().targetDistanceUnit = _distanceUnitOptions[index];
#endif
#if MATERIALX_BUILD_GEN_MDL
_genContextMdl.getOptions().targetDistanceUnit = _distanceUnitOptions[index];
#endif
reloadShaders();
m_process_events = true;
});
ng::ref<ng::Label> meshLoading = new ng::Label(settingsGroup, "Mesh Loading Options");
meshLoading->set_font_size(20);
meshLoading->set_font("sans-bold");
ng::ref<ng::CheckBox> splitUdimsBox = new ng::CheckBox(settingsGroup, "Split By UDIMs");
splitUdimsBox->set_checked(_splitByUdims);
splitUdimsBox->set_callback([this](bool enable)
{
_splitByUdims = enable;
});
ng::ref<ng::Label> materialLoading = new ng::Label(settingsGroup, "Material Loading Options");
materialLoading->set_font_size(20);
materialLoading->set_font("sans-bold");
ng::ref<ng::CheckBox> mergeMaterialsBox = new ng::CheckBox(settingsGroup, "Merge Materials");
mergeMaterialsBox->set_checked(_mergeMaterials);
mergeMaterialsBox->set_callback([this](bool enable)