-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathMaterialBuilder.cpp
1683 lines (1447 loc) · 65.6 KB
/
MaterialBuilder.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 (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "filamat/MaterialBuilder.h"
#include <filamat/Enums.h>
#include "Includes.h"
#include "MaterialVariants.h"
#include "PushConstantDefinitions.h"
#include "shaders/SibGenerator.h"
#include "shaders/UibGenerator.h"
#include "GLSLPostProcessor.h"
#include "sca/GLSLTools.h"
#include "shaders/MaterialInfo.h"
#include "shaders/ShaderGenerator.h"
#include "eiff/BlobDictionary.h"
#include "eiff/LineDictionary.h"
#include "eiff/MaterialInterfaceBlockChunk.h"
#include "eiff/MaterialTextChunk.h"
#include "eiff/MaterialBinaryChunk.h"
#include "eiff/ChunkContainer.h"
#include "eiff/SimpleFieldChunk.h"
#include "eiff/DictionaryTextChunk.h"
#include "eiff/DictionarySpirvChunk.h"
#include <private/filament/BufferInterfaceBlock.h>
#include <private/filament/SamplerInterfaceBlock.h>
#include <private/filament/UibStructs.h>
#include <private/filament/ConstantInfo.h>
#include <private/filament/DescriptorSets.h>
#include <private/filament/EngineEnums.h>
#include <backend/DriverEnums.h>
#include <backend/Program.h>
#include <utils/compiler.h>
#include <utils/debug.h>
#include <utils/FixedCapacityVector.h>
#include <utils/JobSystem.h>
#include <utils/Log.h>
#include <utils/Mutex.h>
#include <utils/Panic.h>
#include <utils/Hash.h>
#include <algorithm>
#include <atomic>
#include <tuple>
#include <utility>
#include <vector>
#include <iostream>
#include <fstream>
#include <stdint.h>
#include <stddef.h>
namespace filamat {
using namespace utils;
using namespace filament;
// Note: the VertexAttribute enum value must match the index in the array
const MaterialBuilder::AttributeDatabase MaterialBuilder::sAttributeDatabase = {{
{ "position", AttributeType::FLOAT4, VertexAttribute::POSITION },
{ "tangents", AttributeType::FLOAT4, VertexAttribute::TANGENTS },
{ "color", AttributeType::FLOAT4, VertexAttribute::COLOR },
{ "uv0", AttributeType::FLOAT2, VertexAttribute::UV0 },
{ "uv1", AttributeType::FLOAT2, VertexAttribute::UV1 },
{ "bone_indices", AttributeType::UINT4, VertexAttribute::BONE_INDICES },
{ "bone_weights", AttributeType::FLOAT4, VertexAttribute::BONE_WEIGHTS },
{ },
{ "custom0", AttributeType::FLOAT4, VertexAttribute::CUSTOM0 },
{ "custom1", AttributeType::FLOAT4, VertexAttribute::CUSTOM1 },
{ "custom2", AttributeType::FLOAT4, VertexAttribute::CUSTOM2 },
{ "custom3", AttributeType::FLOAT4, VertexAttribute::CUSTOM3 },
{ "custom4", AttributeType::FLOAT4, VertexAttribute::CUSTOM4 },
{ "custom5", AttributeType::FLOAT4, VertexAttribute::CUSTOM5 },
{ "custom6", AttributeType::FLOAT4, VertexAttribute::CUSTOM6 },
{ "custom7", AttributeType::FLOAT4, VertexAttribute::CUSTOM7 },
}};
std::atomic<int> MaterialBuilderBase::materialBuilderClients(0);
inline void assertSingleTargetApi(MaterialBuilderBase::TargetApi api) {
// Assert that a single bit is set.
UTILS_UNUSED uint8_t bits = (uint8_t)api;
assert(bits && !(bits & bits - 1u));
}
void MaterialBuilderBase::prepare(bool vulkanSemantics,
filament::backend::FeatureLevel featureLevel) {
mCodeGenPermutations.clear();
mShaderModels.reset();
if (mPlatform == Platform::MOBILE) {
mShaderModels.set(static_cast<size_t>(ShaderModel::MOBILE));
} else if (mPlatform == Platform::DESKTOP) {
mShaderModels.set(static_cast<size_t>(ShaderModel::DESKTOP));
} else if (mPlatform == Platform::ALL) {
mShaderModels.set(static_cast<size_t>(ShaderModel::MOBILE));
mShaderModels.set(static_cast<size_t>(ShaderModel::DESKTOP));
}
// OpenGL is a special case. If we're doing any optimization, then we need to go to Spir-V.
TargetLanguage glTargetLanguage = mOptimization > MaterialBuilder::Optimization::PREPROCESSOR ?
TargetLanguage::SPIRV : TargetLanguage::GLSL;
if (vulkanSemantics) {
// Currently GLSLPostProcessor.cpp is incapable of compiling SPIRV to GLSL without
// running the optimizer. For now we just activate the optimizer in that case.
mOptimization = MaterialBuilder::Optimization::PERFORMANCE;
glTargetLanguage = TargetLanguage::SPIRV;
}
// Select OpenGL as the default TargetApi if none was specified.
if (none(mTargetApi)) {
mTargetApi = TargetApi::OPENGL;
}
// Generally build for a minimum of feature level 1. If feature level 0 is specified, an extra
// permutation is specifically included for the OpenGL/mobile target.
MaterialBuilder::FeatureLevel effectiveFeatureLevel =
std::max(featureLevel, filament::backend::FeatureLevel::FEATURE_LEVEL_1);
// Build a list of codegen permutations, which is useful across all types of material builders.
static_assert(backend::SHADER_MODEL_COUNT == 2);
for (const auto shaderModel: { ShaderModel::MOBILE, ShaderModel::DESKTOP }) {
const auto i = static_cast<uint8_t>(shaderModel);
if (!mShaderModels.test(i)) {
continue; // skip this shader model since it was not requested.
}
if (any(mTargetApi & TargetApi::OPENGL)) {
mCodeGenPermutations.push_back({
shaderModel,
TargetApi::OPENGL,
glTargetLanguage,
effectiveFeatureLevel,
});
if (mIncludeEssl1
&& featureLevel == filament::backend::FeatureLevel::FEATURE_LEVEL_0
&& shaderModel == ShaderModel::MOBILE) {
mCodeGenPermutations.push_back({
shaderModel,
TargetApi::OPENGL,
glTargetLanguage,
filament::backend::FeatureLevel::FEATURE_LEVEL_0
});
}
}
if (any(mTargetApi & TargetApi::VULKAN)) {
mCodeGenPermutations.push_back({
shaderModel,
TargetApi::VULKAN,
TargetLanguage::SPIRV,
effectiveFeatureLevel,
});
}
if (any(mTargetApi & TargetApi::METAL)) {
mCodeGenPermutations.push_back({
shaderModel,
TargetApi::METAL,
TargetLanguage::SPIRV,
effectiveFeatureLevel,
});
}
}
}
MaterialBuilder::MaterialBuilder() : mMaterialName("Unnamed") {
std::fill_n(mProperties, MATERIAL_PROPERTIES_COUNT, false);
mShaderModels.reset();
initPushConstants();
}
MaterialBuilder::~MaterialBuilder() = default;
void MaterialBuilderBase::init() {
materialBuilderClients++;
GLSLTools::init();
}
void MaterialBuilderBase::shutdown() {
materialBuilderClients--;
GLSLTools::shutdown();
}
MaterialBuilder& MaterialBuilder::name(const char* name) noexcept {
mMaterialName = CString(name);
return *this;
}
MaterialBuilder& MaterialBuilder::fileName(const char* fileName) noexcept {
mFileName = CString(fileName);
return *this;
}
MaterialBuilder& MaterialBuilder::material(const char* code, size_t line) noexcept {
mMaterialFragmentCode.setUnresolved(CString(code));
mMaterialFragmentCode.setLineOffset(line);
return *this;
}
MaterialBuilder& MaterialBuilder::includeCallback(IncludeCallback callback) noexcept {
mIncludeCallback = std::move(callback);
return *this;
}
MaterialBuilder& MaterialBuilder::materialVertex(const char* code, size_t line) noexcept {
mMaterialVertexCode.setUnresolved(CString(code));
mMaterialVertexCode.setLineOffset(line);
return *this;
}
MaterialBuilder& MaterialBuilder::shading(Shading shading) noexcept {
mShading = shading;
return *this;
}
MaterialBuilder& MaterialBuilder::interpolation(Interpolation interpolation) noexcept {
mInterpolation = interpolation;
return *this;
}
MaterialBuilder& MaterialBuilder::variable(Variable v, const char* name) noexcept {
switch (v) {
case Variable::CUSTOM0:
case Variable::CUSTOM1:
case Variable::CUSTOM2:
case Variable::CUSTOM3:
assert(size_t(v) < MATERIAL_VARIABLES_COUNT);
mVariables[size_t(v)] = { CString(name), Precision::DEFAULT, false };
break;
}
return *this;
}
MaterialBuilder& MaterialBuilder::variable(Variable v,
const char* name, ParameterPrecision precision) noexcept {
switch (v) {
case Variable::CUSTOM0:
case Variable::CUSTOM1:
case Variable::CUSTOM2:
case Variable::CUSTOM3:
assert(size_t(v) < MATERIAL_VARIABLES_COUNT);
mVariables[size_t(v)] = { CString(name), precision, true };
break;
}
return *this;
}
MaterialBuilder& MaterialBuilder::parameter(const char* name, size_t size, UniformType type,
ParameterPrecision precision) noexcept {
FILAMENT_CHECK_POSTCONDITION(mParameterCount < MAX_PARAMETERS_COUNT) << "Too many parameters";
mParameters[mParameterCount++] = { name, type, size, precision };
return *this;
}
MaterialBuilder& MaterialBuilder::parameter(const char* name, UniformType type,
ParameterPrecision precision) noexcept {
return parameter(name, 1, type, precision);
}
MaterialBuilder& MaterialBuilder::parameter(const char* name, SamplerType samplerType,
SamplerFormat format, ParameterPrecision precision, bool multisample, const char* transformName) noexcept {
FILAMENT_CHECK_PRECONDITION(!multisample ||
(format != SamplerFormat::SHADOW &&
(samplerType == SamplerType::SAMPLER_2D ||
samplerType == SamplerType::SAMPLER_2D_ARRAY)))
<< "multisample samplers only possible with SAMPLER_2D or SAMPLER_2D_ARRAY,"
" as long as type is not SHADOW";
FILAMENT_CHECK_POSTCONDITION(mParameterCount < MAX_PARAMETERS_COUNT) << "Too many parameters";
mParameters[mParameterCount++] = { name, samplerType, format, precision, multisample, transformName };
return *this;
}
template<typename T, typename>
MaterialBuilder& MaterialBuilder::constant(const char* name, ConstantType type, T defaultValue) {
auto result = std::find_if(mConstants.begin(), mConstants.end(), [name](const Constant& c) {
return c.name == utils::CString(name);
});
FILAMENT_CHECK_POSTCONDITION(result == mConstants.end())
<< "There is already a constant parameter present with the name " << name << ".";
Constant constant {
.name = CString(name),
.type = type,
};
auto toString = [](ConstantType t) {
switch (t) {
case ConstantType::INT: return "INT";
case ConstantType::FLOAT: return "FLOAT";
case ConstantType::BOOL: return "BOOL";
}
};
if constexpr (std::is_same_v<T, int32_t>) {
FILAMENT_CHECK_POSTCONDITION(type == ConstantType::INT)
<< "Constant " << name << " was declared with type " << toString(type)
<< " but given an int default value.";
constant.defaultValue.i = defaultValue;
} else if constexpr (std::is_same_v<T, float>) {
FILAMENT_CHECK_POSTCONDITION(type == ConstantType::FLOAT)
<< "Constant " << name << " was declared with type " << toString(type)
<< " but given a float default value.";
constant.defaultValue.f = defaultValue;
} else if constexpr (std::is_same_v<T, bool>) {
FILAMENT_CHECK_POSTCONDITION(type == ConstantType::BOOL)
<< "Constant " << name << " was declared with type " << toString(type)
<< " but given a bool default value.";
constant.defaultValue.b = defaultValue;
} else {
assert_invariant(false);
}
mConstants.push_back(constant);
return *this;
}
template MaterialBuilder& MaterialBuilder::constant<int32_t>(
const char* name, ConstantType type, int32_t defaultValue);
template MaterialBuilder& MaterialBuilder::constant<float>(
const char* name, ConstantType type, float defaultValue);
template MaterialBuilder& MaterialBuilder::constant<bool>(
const char* name, ConstantType type, bool defaultValue);
MaterialBuilder& MaterialBuilder::buffer(BufferInterfaceBlock bib) noexcept {
FILAMENT_CHECK_POSTCONDITION(mBuffers.size() < MAX_BUFFERS_COUNT) << "Too many buffers";
mBuffers.emplace_back(std::make_unique<filament::BufferInterfaceBlock>(std::move(bib)));
return *this;
}
MaterialBuilder& MaterialBuilder::subpass(SubpassType subpassType, SamplerFormat format,
ParameterPrecision precision, const char* name) noexcept {
FILAMENT_CHECK_PRECONDITION(format == SamplerFormat::FLOAT)
<< "Subpass parameters must have FLOAT format.";
FILAMENT_CHECK_POSTCONDITION(mSubpassCount < MAX_SUBPASS_COUNT) << "Too many subpasses";
mSubpasses[mSubpassCount++] = { name, subpassType, format, precision };
return *this;
}
MaterialBuilder& MaterialBuilder::subpass(SubpassType subpassType, SamplerFormat format,
const char* name) noexcept {
return subpass(subpassType, format, ParameterPrecision::DEFAULT, name);
}
MaterialBuilder& MaterialBuilder::subpass(SubpassType subpassType, ParameterPrecision precision,
const char* name) noexcept {
return subpass(subpassType, SamplerFormat::FLOAT, precision, name);
}
MaterialBuilder& MaterialBuilder::subpass(SubpassType subpassType, const char* name) noexcept {
return subpass(subpassType, SamplerFormat::FLOAT, ParameterPrecision::DEFAULT, name);
}
MaterialBuilder& MaterialBuilder::require(VertexAttribute attribute) noexcept {
mRequiredAttributes.set(attribute);
return *this;
}
MaterialBuilder& MaterialBuilder::groupSize(filament::math::uint3 groupSize) noexcept {
mGroupSize = groupSize;
return *this;
}
MaterialBuilder& MaterialBuilder::materialDomain(
MaterialBuilder::MaterialDomain materialDomain) noexcept {
mMaterialDomain = materialDomain;
if (mMaterialDomain == MaterialDomain::COMPUTE) {
// compute implies feature level 2
if (mFeatureLevel < FeatureLevel::FEATURE_LEVEL_2) {
mFeatureLevel = FeatureLevel::FEATURE_LEVEL_2;
}
}
return *this;
}
MaterialBuilder& MaterialBuilder::refractionMode(RefractionMode refraction) noexcept {
mRefractionMode = refraction;
return *this;
}
MaterialBuilder& MaterialBuilder::refractionType(RefractionType refractionType) noexcept {
mRefractionType = refractionType;
return *this;
}
MaterialBuilder& MaterialBuilder::quality(ShaderQuality quality) noexcept {
mShaderQuality = quality;
return *this;
}
MaterialBuilder& MaterialBuilder::featureLevel(FeatureLevel featureLevel) noexcept {
mFeatureLevel = featureLevel;
return *this;
}
MaterialBuilder& MaterialBuilder::blending(BlendingMode blending) noexcept {
mBlendingMode = blending;
return *this;
}
MaterialBuilder& MaterialBuilder::customBlendFunctions(
BlendFunction srcRGB, BlendFunction srcA,
BlendFunction dstRGB, BlendFunction dstA) noexcept {
mCustomBlendFunctions[0] = srcRGB;
mCustomBlendFunctions[1] = srcA;
mCustomBlendFunctions[2] = dstRGB;
mCustomBlendFunctions[3] = dstA;
return *this;
}
MaterialBuilder& MaterialBuilder::postLightingBlending(BlendingMode blending) noexcept {
mPostLightingBlendingMode = blending;
return *this;
}
MaterialBuilder& MaterialBuilder::vertexDomain(VertexDomain domain) noexcept {
mVertexDomain = domain;
return *this;
}
MaterialBuilder& MaterialBuilder::culling(CullingMode culling) noexcept {
mCullingMode = culling;
return *this;
}
MaterialBuilder& MaterialBuilder::colorWrite(bool enable) noexcept {
mColorWrite = enable;
return *this;
}
MaterialBuilder& MaterialBuilder::depthWrite(bool enable) noexcept {
mDepthWrite = enable;
mDepthWriteSet = true;
return *this;
}
MaterialBuilder& MaterialBuilder::depthCulling(bool enable) noexcept {
mDepthTest = enable;
return *this;
}
MaterialBuilder& MaterialBuilder::instanced(bool enable) noexcept {
mInstanced = enable;
return *this;
}
MaterialBuilder& MaterialBuilder::doubleSided(bool doubleSided) noexcept {
mDoubleSided = doubleSided;
mDoubleSidedCapability = true;
return *this;
}
MaterialBuilder& MaterialBuilder::maskThreshold(float threshold) noexcept {
mMaskThreshold = threshold;
return *this;
}
MaterialBuilder& MaterialBuilder::alphaToCoverage(bool enable) noexcept {
mAlphaToCoverage = enable;
mAlphaToCoverageSet = true;
return *this;
}
MaterialBuilder& MaterialBuilder::shadowMultiplier(bool shadowMultiplier) noexcept {
mShadowMultiplier = shadowMultiplier;
return *this;
}
MaterialBuilder& MaterialBuilder::transparentShadow(bool transparentShadow) noexcept {
mTransparentShadow = transparentShadow;
return *this;
}
MaterialBuilder& MaterialBuilder::specularAntiAliasing(bool specularAntiAliasing) noexcept {
mSpecularAntiAliasing = specularAntiAliasing;
return *this;
}
MaterialBuilder& MaterialBuilder::specularAntiAliasingVariance(float screenSpaceVariance) noexcept {
mSpecularAntiAliasingVariance = screenSpaceVariance;
return *this;
}
MaterialBuilder& MaterialBuilder::specularAntiAliasingThreshold(float threshold) noexcept {
mSpecularAntiAliasingThreshold = threshold;
return *this;
}
MaterialBuilder& MaterialBuilder::clearCoatIorChange(bool clearCoatIorChange) noexcept {
mClearCoatIorChange = clearCoatIorChange;
return *this;
}
MaterialBuilder& MaterialBuilder::flipUV(bool flipUV) noexcept {
mFlipUV = flipUV;
return *this;
}
MaterialBuilder& MaterialBuilder::customSurfaceShading(bool customSurfaceShading) noexcept {
mCustomSurfaceShading = customSurfaceShading;
return *this;
}
MaterialBuilder& MaterialBuilder::multiBounceAmbientOcclusion(bool multiBounceAO) noexcept {
mMultiBounceAO = multiBounceAO;
mMultiBounceAOSet = true;
return *this;
}
MaterialBuilder& MaterialBuilder::specularAmbientOcclusion(SpecularAmbientOcclusion specularAO) noexcept {
mSpecularAO = specularAO;
mSpecularAOSet = true;
return *this;
}
MaterialBuilder& MaterialBuilder::transparencyMode(TransparencyMode mode) noexcept {
mTransparencyMode = mode;
return *this;
}
MaterialBuilder& MaterialBuilder::stereoscopicType(StereoscopicType stereoscopicType) noexcept {
mStereoscopicType = stereoscopicType;
return *this;
}
MaterialBuilder& MaterialBuilder::stereoscopicEyeCount(uint8_t eyeCount) noexcept {
mStereoscopicEyeCount = eyeCount;
return *this;
}
MaterialBuilder& MaterialBuilder::reflectionMode(ReflectionMode mode) noexcept {
mReflectionMode = mode;
return *this;
}
MaterialBuilder& MaterialBuilder::platform(Platform platform) noexcept {
mPlatform = platform;
return *this;
}
MaterialBuilder& MaterialBuilder::targetApi(TargetApi targetApi) noexcept {
mTargetApi |= targetApi;
return *this;
}
MaterialBuilder& MaterialBuilder::optimization(Optimization optimization) noexcept {
mOptimization = optimization;
return *this;
}
MaterialBuilder& MaterialBuilder::printShaders(bool printShaders) noexcept {
mPrintShaders = printShaders;
return *this;
}
MaterialBuilder& MaterialBuilder::saveRawVariants(bool saveRawVariants) noexcept {
mSaveRawVariants = saveRawVariants;
return *this;
}
MaterialBuilder& MaterialBuilder::generateDebugInfo(bool generateDebugInfo) noexcept {
mGenerateDebugInfo = generateDebugInfo;
return *this;
}
MaterialBuilder& MaterialBuilder::variantFilter(UserVariantFilterMask variantFilter) noexcept {
mVariantFilter = variantFilter;
return *this;
}
MaterialBuilder& MaterialBuilder::shaderDefine(const char* name, const char* value) noexcept {
mDefines.emplace_back(name, value);
return *this;
}
bool MaterialBuilder::hasSamplerType(SamplerType samplerType) const noexcept {
for (size_t i = 0, c = mParameterCount; i < c; i++) {
auto const& param = mParameters[i];
if (param.isSampler() && param.samplerType == samplerType) {
return true;
}
}
return false;
}
void MaterialBuilder::prepareToBuild(MaterialInfo& info) noexcept {
MaterialBuilderBase::prepare(mEnableFramebufferFetch, mFeatureLevel);
// Build the per-material sampler block and uniform block.
SamplerInterfaceBlock::Builder sbb;
BufferInterfaceBlock::Builder ibb;
// sampler bindings start at 1, 0 is the ubo
uint16_t binding = 1;
for (size_t i = 0, c = mParameterCount; i < c; i++) {
auto const& param = mParameters[i];
assert_invariant(!param.isSubpass());
if (param.isSampler()) {
sbb.add({ param.name.data(), param.name.size() },
binding, param.samplerType, param.format, param.precision, param.multisample);
if (!param.transformName.empty()) {
ibb.add({{{ param.transformName.data(), param.transformName.size() }, uint8_t(binding),
0, UniformType::MAT3, Precision::DEFAULT, FeatureLevel::FEATURE_LEVEL_0 }});
}
binding++;
} else if (param.isUniform()) {
ibb.add({{{ param.name.data(), param.name.size() },
uint32_t(param.size == 1u ? 0u : param.size), param.uniformType,
param.precision, FeatureLevel::FEATURE_LEVEL_0 }});
}
}
for (size_t i = 0, c = mSubpassCount; i < c; i++) {
auto const& param = mSubpasses[i];
assert_invariant(param.isSubpass());
// For now, we only support a single subpass for attachment 0.
// Subpasses belong to the "MaterialParams" block.
const uint8_t attachmentIndex = 0;
const uint8_t binding = 0;
info.subpass = { CString("MaterialParams"), param.name, param.subpassType,
param.format, param.precision, attachmentIndex, binding };
}
for (auto const& buffer : mBuffers) {
info.buffers.emplace_back(buffer.get());
}
if (mSpecularAntiAliasing) {
ibb.add({
{ "_specularAntiAliasingVariance", 0, UniformType::FLOAT },
{ "_specularAntiAliasingThreshold", 0, UniformType::FLOAT },
});
}
if (mBlendingMode == BlendingMode::MASKED) {
ibb.add({{ "_maskThreshold", 0, UniformType::FLOAT, Precision::DEFAULT, FeatureLevel::FEATURE_LEVEL_0 }});
}
if (mDoubleSidedCapability) {
ibb.add({{ "_doubleSided", 0, UniformType::BOOL, Precision::DEFAULT, FeatureLevel::FEATURE_LEVEL_0 }});
}
mRequiredAttributes.set(VertexAttribute::POSITION);
if (mShading != Shading::UNLIT || mShadowMultiplier) {
mRequiredAttributes.set(VertexAttribute::TANGENTS);
}
info.sib = sbb.name("MaterialParams").build();
info.uib = ibb.name("MaterialParams").build();
info.isLit = isLit();
info.hasDoubleSidedCapability = mDoubleSidedCapability;
info.hasExternalSamplers = hasSamplerType(SamplerType::SAMPLER_EXTERNAL);
info.has3dSamplers = hasSamplerType(SamplerType::SAMPLER_3D);
info.specularAntiAliasing = mSpecularAntiAliasing;
info.clearCoatIorChange = mClearCoatIorChange;
info.flipUV = mFlipUV;
info.requiredAttributes = mRequiredAttributes;
info.blendingMode = mBlendingMode;
info.postLightingBlendingMode = mPostLightingBlendingMode;
info.shading = mShading;
info.hasShadowMultiplier = mShadowMultiplier;
info.hasTransparentShadow = mTransparentShadow;
info.multiBounceAO = mMultiBounceAO;
info.multiBounceAOSet = mMultiBounceAOSet;
info.specularAO = mSpecularAO;
info.specularAOSet = mSpecularAOSet;
info.refractionMode = mRefractionMode;
info.refractionType = mRefractionType;
info.reflectionMode = mReflectionMode;
info.quality = mShaderQuality;
info.hasCustomSurfaceShading = mCustomSurfaceShading;
info.useLegacyMorphing = mUseLegacyMorphing;
info.instanced = mInstanced;
info.vertexDomainDeviceJittered = mVertexDomainDeviceJittered;
info.featureLevel = mFeatureLevel;
info.groupSize = mGroupSize;
info.stereoscopicType = mStereoscopicType;
info.stereoscopicEyeCount = mStereoscopicEyeCount;
// This is determined via static analysis of the glsl after prepareToBuild().
info.userMaterialHasCustomDepth = false;
}
void MaterialBuilder::initPushConstants() noexcept {
mPushConstants.reserve(PUSH_CONSTANTS.size());
mPushConstants.resize(PUSH_CONSTANTS.size());
std::transform(PUSH_CONSTANTS.cbegin(), PUSH_CONSTANTS.cend(), mPushConstants.begin(),
[](filament::MaterialPushConstant const& inConstant) -> PushConstant {
return {
.name = inConstant.name,
.type = inConstant.type,
.stage = inConstant.stage,
};
});
}
bool MaterialBuilder::findProperties(backend::ShaderStage type,
MaterialBuilder::PropertyList& allProperties,
CodeGenParams const& semanticCodeGenParams) noexcept {
GLSLTools glslTools;
std::string shaderCodeAllProperties = peek(type, semanticCodeGenParams, allProperties);
// Populate mProperties with the properties set in the shader.
if (!glslTools.findProperties(type, shaderCodeAllProperties, mProperties,
semanticCodeGenParams.targetApi,
semanticCodeGenParams.targetLanguage,
semanticCodeGenParams.shaderModel)) {
if (mPrintShaders) {
slog.e << shaderCodeAllProperties << io::endl;
}
return false;
}
return true;
}
bool MaterialBuilder::findAllProperties(CodeGenParams const& semanticCodeGenParams) noexcept {
if (mMaterialDomain != MaterialDomain::SURFACE) {
return true;
}
using namespace backend;
// Some fields in MaterialInputs only exist if the property is set (e.g: normal, subsurface
// for cloth shading model). Give our shader all properties. This will enable us to parse and
// static code analyse the AST.
MaterialBuilder::PropertyList allProperties;
std::fill_n(allProperties, MATERIAL_PROPERTIES_COUNT, true);
if (!findProperties(ShaderStage::FRAGMENT, allProperties, semanticCodeGenParams)) {
return false;
}
if (!findProperties(ShaderStage::VERTEX, allProperties, semanticCodeGenParams)) {
return false;
}
return true;
}
bool MaterialBuilder::runSemanticAnalysis(MaterialInfo* inOutInfo,
CodeGenParams const& semanticCodeGenParams) noexcept {
using namespace backend;
TargetApi targetApi = semanticCodeGenParams.targetApi;
TargetLanguage const targetLanguage = semanticCodeGenParams.targetLanguage;
assertSingleTargetApi(targetApi);
if (mEnableFramebufferFetch) {
// framebuffer fetch is only available with vulkan semantics
targetApi = TargetApi::VULKAN;
}
bool success = false;
std::string shaderCode;
ShaderModel const model = semanticCodeGenParams.shaderModel;
if (mMaterialDomain == filament::MaterialDomain::COMPUTE) {
shaderCode = peek(ShaderStage::COMPUTE, semanticCodeGenParams, mProperties);
success = GLSLTools::analyzeComputeShader(shaderCode, model,
targetApi, targetLanguage);
} else {
shaderCode = peek(ShaderStage::VERTEX, semanticCodeGenParams, mProperties);
success = GLSLTools::analyzeVertexShader(shaderCode, model, mMaterialDomain,
targetApi, targetLanguage);
if (success) {
shaderCode = peek(ShaderStage::FRAGMENT, semanticCodeGenParams, mProperties);
auto result = GLSLTools::analyzeFragmentShader(shaderCode, model, mMaterialDomain,
targetApi, targetLanguage, mCustomSurfaceShading);
success = result.has_value();
if (success) {
inOutInfo->userMaterialHasCustomDepth = result->userMaterialHasCustomDepth;
}
}
}
if (!success && mPrintShaders) {
slog.e << shaderCode << io::endl;
}
return success;
}
bool MaterialBuilder::ShaderCode::resolveIncludes(IncludeCallback callback,
const CString& fileName) noexcept {
if (!mCode.empty()) {
ResolveOptions options {
.insertLineDirectives = true,
.insertLineDirectiveCheck = true
};
IncludeResult source {
.includeName = fileName,
.text = mCode,
.lineNumberOffset = getLineOffset(),
.name = CString("")
};
if (!::filamat::resolveIncludes(source, std::move(callback), options)) {
return false;
}
mCode = source.text;
}
mIncludesResolved = true;
return true;
}
static void showErrorMessage(const char* materialName, filament::Variant variant,
MaterialBuilder::TargetApi targetApi, backend::ShaderStage shaderType,
MaterialBuilder::FeatureLevel featureLevel,
const std::string& shaderCode) {
using ShaderStage = backend::ShaderStage;
using TargetApi = MaterialBuilder::TargetApi;
const char* targetApiString;
switch (targetApi) {
case TargetApi::OPENGL:
targetApiString = (featureLevel == MaterialBuilder::FeatureLevel::FEATURE_LEVEL_0)
? "GLES 2.0.\n" : "OpenGL.\n";
break;
case TargetApi::VULKAN:
targetApiString = "Vulkan.\n";
break;
case TargetApi::METAL:
targetApiString = "Metal.\n";
break;
case TargetApi::WEBGPU:
targetApiString = "WebGPU.\n";
case TargetApi::ALL:
assert(0); // Unreachable.
break;
}
const char* shaderStageString;
switch (shaderType) {
case ShaderStage::VERTEX:
shaderStageString = "Vertex Shader\n";
break;
case ShaderStage::FRAGMENT:
shaderStageString = "Fragment Shader\n";
break;
case ShaderStage::COMPUTE:
shaderStageString = "Compute Shader\n";
break;
}
slog.e
<< "Error in \"" << materialName << "\""
<< ", Variant 0x" << io::hex << +variant.key
<< ", " << targetApiString
<< "=========================\n"
<< "Generated " << shaderStageString
<< "=========================\n"
<< shaderCode;
}
bool MaterialBuilder::generateShaders(JobSystem& jobSystem, const std::vector<Variant>& variants,
ChunkContainer& container, const MaterialInfo& info) const noexcept {
// Create a postprocessor to optimize / compile to Spir-V if necessary.
uint32_t flags = 0;
flags |= mPrintShaders ? GLSLPostProcessor::PRINT_SHADERS : 0;
flags |= mGenerateDebugInfo ? GLSLPostProcessor::GENERATE_DEBUG_INFO : 0;
GLSLPostProcessor postProcessor(mOptimization, flags);
// Start: must be protected by lock
Mutex entriesLock;
std::vector<TextEntry> glslEntries;
std::vector<TextEntry> essl1Entries;
std::vector<BinaryEntry> spirvEntries;
std::vector<TextEntry> metalEntries;
LineDictionary textDictionary;
BlobDictionary spirvDictionary;
// End: must be protected by lock
ShaderGenerator sg(mProperties, mVariables, mOutputs, mDefines, mConstants, mPushConstants,
mMaterialFragmentCode.getResolved(), mMaterialFragmentCode.getLineOffset(),
mMaterialVertexCode.getResolved(), mMaterialVertexCode.getLineOffset(),
mMaterialDomain);
container.emplace<bool>(ChunkType::MaterialHasCustomDepthShader, needsStandardDepthProgram());
std::atomic_bool cancelJobs(false);
bool firstJob = true;
for (const auto& params : mCodeGenPermutations) {
if (cancelJobs.load()) {
return false;
}
const ShaderModel shaderModel = ShaderModel(params.shaderModel);
const TargetApi targetApi = params.targetApi;
const TargetLanguage targetLanguage = params.targetLanguage;
const FeatureLevel featureLevel = params.featureLevel;
assertSingleTargetApi(targetApi);
// Metal Shading Language is cross-compiled from Vulkan.
const bool targetApiNeedsSpirv =
(targetApi == TargetApi::VULKAN || targetApi == TargetApi::METAL);
const bool targetApiNeedsMsl = targetApi == TargetApi::METAL;
const bool targetApiNeedsWgsl = targetApi == TargetApi::WEBGPU;
const bool targetApiNeedsGlsl = targetApi == TargetApi::OPENGL;
// Set when a job fails
JobSystem::Job* parent = jobSystem.createJob();
for (const auto& v : variants) {
JobSystem::Job* job = jobs::createJob(jobSystem, parent, [&]() {
if (cancelJobs.load()) {
return;
}
// TODO: avoid allocations when not required
std::vector<uint32_t> spirv;
std::string msl;
std::string wgsl;
std::vector<uint32_t>* pSpirv = targetApiNeedsSpirv ? &spirv : nullptr;
std::string* pMsl = targetApiNeedsMsl ? &msl : nullptr;
std::string* pWgsl = targetApiNeedsWgsl ? &wgsl : nullptr;
TextEntry glslEntry{};
BinaryEntry spirvEntry{};
TextEntry metalEntry{};
glslEntry.shaderModel = params.shaderModel;
spirvEntry.shaderModel = params.shaderModel;
metalEntry.shaderModel = params.shaderModel;
glslEntry.variant = v.variant;
spirvEntry.variant = v.variant;
metalEntry.variant = v.variant;
// Generate raw shader code.
// The quotes in Google-style line directives cause problems with certain drivers. These
// directives are optimized away when using the full filamat, so down below we
// explicitly remove them when using filamat lite.
std::string shader;
if (v.stage == backend::ShaderStage::VERTEX) {
shader = sg.createSurfaceVertexProgram(
shaderModel, targetApi, targetLanguage, featureLevel,
info, v.variant, mInterpolation, mVertexDomain);
} else if (v.stage == backend::ShaderStage::FRAGMENT) {
shader = sg.createSurfaceFragmentProgram(
shaderModel, targetApi, targetLanguage, featureLevel,
info, v.variant, mInterpolation, mVariantFilter);
} else if (v.stage == backend::ShaderStage::COMPUTE) {
shader = sg.createSurfaceComputeProgram(
shaderModel, targetApi, targetLanguage, featureLevel,
info);
}
// Write the variant to a file.
if (mSaveRawVariants) {
int const variantKey = v.variant.key;
auto getExtension = [](backend::ShaderStage stage) {
switch (stage) {
case backend::ShaderStage::VERTEX:
return "vert";
case backend::ShaderStage::FRAGMENT:
return "frag";
case backend::ShaderStage::COMPUTE:
return "comp";
}
};
char filename[256];
snprintf(filename, sizeof(filename), "%s_0x%02x.%s", mMaterialName.c_str_safe(),
variantKey, getExtension(v.stage));
printf("Writing variant 0x%02x to %s\n", variantKey, filename);
std::ofstream file(filename);
if (file.is_open()) {
file << shader;
file.close();
}
}
std::string* pGlsl = nullptr;
if (targetApiNeedsGlsl) {
pGlsl = &shader;
}
GLSLPostProcessor::Config config{
.variant = v.variant,
.variantFilter = mVariantFilter,
.targetApi = targetApi,
.targetLanguage = targetLanguage,
.shaderType = v.stage,
.shaderModel = shaderModel,
.featureLevel = featureLevel,