-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
backgroundMaterial.ts
1323 lines (1140 loc) · 51.2 KB
/
backgroundMaterial.ts
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
/* eslint-disable @typescript-eslint/naming-convention */
import {
SerializationHelper,
serialize,
serializeAsColor3,
expandToProperty,
serializeAsTexture,
serializeAsVector3,
serializeAsImageProcessingConfiguration,
} from "../../Misc/decorators";
import { SmartArray } from "../../Misc/smartArray";
import type { Observer } from "../../Misc/observable";
import { Logger } from "../../Misc/logger";
import type { Nullable, int, float } from "../../types";
import type { Scene } from "../../scene";
import type { Matrix } from "../../Maths/math.vector";
import { Vector3, Vector4 } from "../../Maths/math.vector";
import { VertexBuffer } from "../../Buffers/buffer";
import type { SubMesh } from "../../Meshes/subMesh";
import type { AbstractMesh } from "../../Meshes/abstractMesh";
import type { Mesh } from "../../Meshes/mesh";
import type { IEffectCreationOptions } from "../../Materials/effect";
import { MaterialHelper } from "../../Materials/materialHelper";
import { MaterialDefines } from "../../Materials/materialDefines";
import { PushMaterial } from "../../Materials/pushMaterial";
import type { ColorCurves } from "../../Materials/colorCurves";
import type { IImageProcessingConfigurationDefines } from "../../Materials/imageProcessingConfiguration";
import { ImageProcessingConfiguration } from "../../Materials/imageProcessingConfiguration";
import type { BaseTexture } from "../../Materials/Textures/baseTexture";
import { Texture } from "../../Materials/Textures/texture";
import type { RenderTargetTexture } from "../../Materials/Textures/renderTargetTexture";
import type { IShadowLight } from "../../Lights/shadowLight";
import { Constants } from "../../Engines/constants";
import { RegisterClass } from "../../Misc/typeStore";
import { MaterialFlags } from "../materialFlags";
import { Color3 } from "../../Maths/math.color";
import "../../Shaders/background.fragment";
import "../../Shaders/background.vertex";
import { EffectFallbacks } from "../effectFallbacks";
import { addClipPlaneUniforms, bindClipPlane } from "../clipPlaneMaterialHelper";
/**
* Background material defines definition.
* @internal Mainly internal Use
*/
class BackgroundMaterialDefines extends MaterialDefines implements IImageProcessingConfigurationDefines {
/**
* True if the diffuse texture is in use.
*/
public DIFFUSE = false;
/**
* The direct UV channel to use.
*/
public DIFFUSEDIRECTUV = 0;
/**
* True if the diffuse texture is in gamma space.
*/
public GAMMADIFFUSE = false;
/**
* True if the diffuse texture has opacity in the alpha channel.
*/
public DIFFUSEHASALPHA = false;
/**
* True if you want the material to fade to transparent at grazing angle.
*/
public OPACITYFRESNEL = false;
/**
* True if an extra blur needs to be added in the reflection.
*/
public REFLECTIONBLUR = false;
/**
* True if you want the material to fade to reflection at grazing angle.
*/
public REFLECTIONFRESNEL = false;
/**
* True if you want the material to falloff as far as you move away from the scene center.
*/
public REFLECTIONFALLOFF = false;
/**
* False if the current Webgl implementation does not support the texture lod extension.
*/
public TEXTURELODSUPPORT = false;
/**
* True to ensure the data are premultiplied.
*/
public PREMULTIPLYALPHA = false;
/**
* True if the texture contains cooked RGB values and not gray scaled multipliers.
*/
public USERGBCOLOR = false;
/**
* True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
* stays aligned with the desired configuration.
*/
public USEHIGHLIGHTANDSHADOWCOLORS = false;
/**
* True if only shadows must be rendered
*/
public BACKMAT_SHADOWONLY = false;
/**
* True to add noise in order to reduce the banding effect.
*/
public NOISE = false;
/**
* is the reflection texture in BGR color scheme?
* Mainly used to solve a bug in ios10 video tag
*/
public REFLECTIONBGR = false;
/**
* True if ground projection has been enabled.
*/
public PROJECTED_GROUND = false;
public IMAGEPROCESSING = false;
public VIGNETTE = false;
public VIGNETTEBLENDMODEMULTIPLY = false;
public VIGNETTEBLENDMODEOPAQUE = false;
public TONEMAPPING = false;
public TONEMAPPING_ACES = false;
public CONTRAST = false;
public COLORCURVES = false;
public COLORGRADING = false;
public COLORGRADING3D = false;
public SAMPLER3DGREENDEPTH = false;
public SAMPLER3DBGRMAP = false;
public DITHER = false;
public IMAGEPROCESSINGPOSTPROCESS = false;
public SKIPFINALCOLORCLAMP = false;
public EXPOSURE = false;
public MULTIVIEW = false;
// Reflection.
public REFLECTION = false;
public REFLECTIONMAP_3D = false;
public REFLECTIONMAP_SPHERICAL = false;
public REFLECTIONMAP_PLANAR = false;
public REFLECTIONMAP_CUBIC = false;
public REFLECTIONMAP_PROJECTION = false;
public REFLECTIONMAP_SKYBOX = false;
public REFLECTIONMAP_EXPLICIT = false;
public REFLECTIONMAP_EQUIRECTANGULAR = false;
public REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
public REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
public INVERTCUBICMAP = false;
public REFLECTIONMAP_OPPOSITEZ = false;
public LODINREFLECTIONALPHA = false;
public GAMMAREFLECTION = false;
public RGBDREFLECTION = false;
public EQUIRECTANGULAR_RELFECTION_FOV = false;
// Default BJS.
public MAINUV1 = false;
public MAINUV2 = false;
public UV1 = false;
public UV2 = false;
public CLIPPLANE = false;
public CLIPPLANE2 = false;
public CLIPPLANE3 = false;
public CLIPPLANE4 = false;
public CLIPPLANE5 = false;
public CLIPPLANE6 = false;
public POINTSIZE = false;
public FOG = false;
public NORMAL = false;
public NUM_BONE_INFLUENCERS = 0;
public BonesPerMesh = 0;
public INSTANCES = false;
public SHADOWFLOAT = false;
public LOGARITHMICDEPTH = false;
public NONUNIFORMSCALING = false;
public ALPHATEST = false;
/**
* Constructor of the defines.
*/
constructor() {
super();
this.rebuild();
}
}
/**
* Background material used to create an efficient environment around your scene.
*/
export class BackgroundMaterial extends PushMaterial {
/**
* Standard reflectance value at parallel view angle.
*/
public static StandardReflectance0 = 0.05;
/**
* Standard reflectance value at grazing angle.
*/
public static StandardReflectance90 = 0.5;
@serializeAsColor3()
protected _primaryColor: Color3;
/**
* Key light Color (multiply against the environment texture)
*/
@expandToProperty("_markAllSubMeshesAsLightsDirty")
public primaryColor = Color3.White();
@serializeAsColor3()
protected __perceptualColor: Nullable<Color3>;
/**
* Experimental Internal Use Only.
*
* Key light Color in "perceptual value" meaning the color you would like to see on screen.
* This acts as a helper to set the primary color to a more "human friendly" value.
* Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
* output color as close as possible from the chosen value.
* (This does not account for contrast color grading and color curves as they are considered post effect and not directly
* part of lighting setup.)
*/
public get _perceptualColor(): Nullable<Color3> {
return this.__perceptualColor;
}
public set _perceptualColor(value: Nullable<Color3>) {
this.__perceptualColor = value;
this._computePrimaryColorFromPerceptualColor();
this._markAllSubMeshesAsLightsDirty();
}
@serialize()
protected _primaryColorShadowLevel: float = 0;
/**
* Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
* The color opposite to the primary color is used at the level chosen to define what the black area would look.
*/
public get primaryColorShadowLevel(): float {
return this._primaryColorShadowLevel;
}
public set primaryColorShadowLevel(value: float) {
this._primaryColorShadowLevel = value;
this._computePrimaryColors();
this._markAllSubMeshesAsLightsDirty();
}
@serialize()
protected _primaryColorHighlightLevel: float = 0;
/**
* Defines the level of the highlights (highlight area of the reflection map) in order to help scaling the colors.
* The primary color is used at the level chosen to define what the white area would look.
*/
@expandToProperty("_markAllSubMeshesAsLightsDirty")
public get primaryColorHighlightLevel(): float {
return this._primaryColorHighlightLevel;
}
public set primaryColorHighlightLevel(value: float) {
this._primaryColorHighlightLevel = value;
this._computePrimaryColors();
this._markAllSubMeshesAsLightsDirty();
}
@serializeAsTexture()
protected _reflectionTexture: Nullable<BaseTexture>;
/**
* Reflection Texture used in the material.
* Should be author in a specific way for the best result (refer to the documentation).
*/
@expandToProperty("_markAllSubMeshesAsTexturesDirty")
public reflectionTexture: Nullable<BaseTexture> = null;
@serialize()
protected _reflectionBlur: float;
/**
* Reflection Texture level of blur.
*
* Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
* texture twice.
*/
@expandToProperty("_markAllSubMeshesAsTexturesDirty")
public reflectionBlur: float = 0;
@serializeAsTexture()
protected _diffuseTexture: Nullable<BaseTexture>;
/**
* Diffuse Texture used in the material.
* Should be author in a specific way for the best result (refer to the documentation).
*/
@expandToProperty("_markAllSubMeshesAsTexturesDirty")
public diffuseTexture: Nullable<BaseTexture> = null;
protected _shadowLights: Nullable<IShadowLight[]> = null;
/**
* Specify the list of lights casting shadow on the material.
* All scene shadow lights will be included if null.
*/
@expandToProperty("_markAllSubMeshesAsTexturesDirty")
public shadowLights: Nullable<IShadowLight[]> = null;
@serialize()
protected _shadowLevel: float;
/**
* Helps adjusting the shadow to a softer level if required.
* 0 means black shadows and 1 means no shadows.
*/
@expandToProperty("_markAllSubMeshesAsTexturesDirty")
public shadowLevel: float = 0;
@serializeAsVector3()
protected _sceneCenter: Vector3;
/**
* In case of opacity Fresnel or reflection falloff, this is use as a scene center.
* It is usually zero but might be interesting to modify according to your setup.
*/
@expandToProperty("_markAllSubMeshesAsTexturesDirty")
public sceneCenter: Vector3 = Vector3.Zero();
@serialize()
protected _opacityFresnel: boolean;
/**
* This helps specifying that the material is falling off to the sky box at grazing angle.
* This helps ensuring a nice transition when the camera goes under the ground.
*/
@expandToProperty("_markAllSubMeshesAsTexturesDirty")
public opacityFresnel: boolean = true;
@serialize()
protected _reflectionFresnel: boolean;
/**
* This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
* This helps adding a mirror texture on the ground.
*/
@expandToProperty("_markAllSubMeshesAsTexturesDirty")
public reflectionFresnel: boolean = false;
@serialize()
protected _reflectionFalloffDistance: number;
/**
* This helps specifying the falloff radius off the reflection texture from the sceneCenter.
* This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
*/
@expandToProperty("_markAllSubMeshesAsTexturesDirty")
public reflectionFalloffDistance: number = 0.0;
@serialize()
protected _reflectionAmount: number;
/**
* This specifies the weight of the reflection against the background in case of reflection Fresnel.
*/
@expandToProperty("_markAllSubMeshesAsTexturesDirty")
public reflectionAmount: number = 1.0;
@serialize()
protected _reflectionReflectance0: number;
/**
* This specifies the weight of the reflection at grazing angle.
*/
@expandToProperty("_markAllSubMeshesAsTexturesDirty")
public reflectionReflectance0: number = 0.05;
@serialize()
protected _reflectionReflectance90: number;
/**
* This specifies the weight of the reflection at a perpendicular point of view.
*/
@expandToProperty("_markAllSubMeshesAsTexturesDirty")
public reflectionReflectance90: number = 0.5;
/**
* Sets the reflection reflectance fresnel values according to the default standard
* empirically know to work well :-)
*/
public set reflectionStandardFresnelWeight(value: number) {
let reflectionWeight = value;
if (reflectionWeight < 0.5) {
reflectionWeight = reflectionWeight * 2.0;
this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
} else {
reflectionWeight = reflectionWeight * 2.0 - 1.0;
this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
}
}
@serialize()
protected _useRGBColor: boolean;
/**
* Helps to directly use the maps channels instead of their level.
*/
@expandToProperty("_markAllSubMeshesAsTexturesDirty")
public useRGBColor: boolean = true;
@serialize()
protected _enableNoise: boolean;
/**
* This helps reducing the banding effect that could occur on the background.
*/
@expandToProperty("_markAllSubMeshesAsTexturesDirty")
public enableNoise: boolean = false;
/**
* The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
* Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
* Recommended to be keep at 1.0 except for special cases.
*/
public get fovMultiplier(): number {
return this._fovMultiplier;
}
public set fovMultiplier(value: number) {
if (isNaN(value)) {
value = 1.0;
}
this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
}
private _fovMultiplier: float = 1.0;
/**
* Enable the FOV adjustment feature controlled by fovMultiplier.
*/
public useEquirectangularFOV: boolean = false;
@serialize()
private _maxSimultaneousLights: int = 4;
/**
* Number of Simultaneous lights allowed on the material.
*/
@expandToProperty("_markAllSubMeshesAsTexturesDirty")
public maxSimultaneousLights: int = 4;
@serialize()
private _shadowOnly: boolean = false;
/**
* Make the material only render shadows
*/
@expandToProperty("_markAllSubMeshesAsLightsDirty")
public shadowOnly: boolean = false;
/**
* Default configuration related to image processing available in the Background Material.
*/
@serializeAsImageProcessingConfiguration()
protected _imageProcessingConfiguration: ImageProcessingConfiguration;
/**
* Keep track of the image processing observer to allow dispose and replace.
*/
private _imageProcessingObserver: Nullable<Observer<ImageProcessingConfiguration>> = null;
/**
* Attaches a new image processing configuration to the PBR Material.
* @param configuration (if null the scene configuration will be use)
*/
protected _attachImageProcessingConfiguration(configuration: Nullable<ImageProcessingConfiguration>): void {
if (configuration === this._imageProcessingConfiguration) {
return;
}
// Detaches observer.
if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
}
// Pick the scene configuration if needed.
if (!configuration) {
this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
} else {
this._imageProcessingConfiguration = configuration;
}
// Attaches observer.
if (this._imageProcessingConfiguration) {
this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => {
this._computePrimaryColorFromPerceptualColor();
this._markAllSubMeshesAsImageProcessingDirty();
});
}
}
/**
* Gets the image processing configuration used either in this material.
*/
public get imageProcessingConfiguration(): Nullable<ImageProcessingConfiguration> {
return this._imageProcessingConfiguration;
}
/**
* Sets the Default image processing configuration used either in the this material.
*
* If sets to null, the scene one is in use.
*/
public set imageProcessingConfiguration(value: Nullable<ImageProcessingConfiguration>) {
this._attachImageProcessingConfiguration(value);
// Ensure the effect will be rebuilt.
this._markAllSubMeshesAsTexturesDirty();
}
/**
* Gets whether the color curves effect is enabled.
*/
public get cameraColorCurvesEnabled(): boolean {
return (<ImageProcessingConfiguration>this.imageProcessingConfiguration).colorCurvesEnabled;
}
/**
* Sets whether the color curves effect is enabled.
*/
public set cameraColorCurvesEnabled(value: boolean) {
(<ImageProcessingConfiguration>this.imageProcessingConfiguration).colorCurvesEnabled = value;
}
/**
* Gets whether the color grading effect is enabled.
*/
public get cameraColorGradingEnabled(): boolean {
return (<ImageProcessingConfiguration>this.imageProcessingConfiguration).colorGradingEnabled;
}
/**
* Gets whether the color grading effect is enabled.
*/
public set cameraColorGradingEnabled(value: boolean) {
(<ImageProcessingConfiguration>this.imageProcessingConfiguration).colorGradingEnabled = value;
}
/**
* Gets whether tonemapping is enabled or not.
*/
public get cameraToneMappingEnabled(): boolean {
return this._imageProcessingConfiguration.toneMappingEnabled;
}
/**
* Sets whether tonemapping is enabled or not
*/
public set cameraToneMappingEnabled(value: boolean) {
this._imageProcessingConfiguration.toneMappingEnabled = value;
}
/**
* The camera exposure used on this material.
* This property is here and not in the camera to allow controlling exposure without full screen post process.
* This corresponds to a photographic exposure.
*/
public get cameraExposure(): float {
return this._imageProcessingConfiguration.exposure;
}
/**
* The camera exposure used on this material.
* This property is here and not in the camera to allow controlling exposure without full screen post process.
* This corresponds to a photographic exposure.
*/
public set cameraExposure(value: float) {
this._imageProcessingConfiguration.exposure = value;
}
/**
* Gets The camera contrast used on this material.
*/
public get cameraContrast(): float {
return this._imageProcessingConfiguration.contrast;
}
/**
* Sets The camera contrast used on this material.
*/
public set cameraContrast(value: float) {
this._imageProcessingConfiguration.contrast = value;
}
/**
* Gets the Color Grading 2D Lookup Texture.
*/
public get cameraColorGradingTexture(): Nullable<BaseTexture> {
return this._imageProcessingConfiguration.colorGradingTexture;
}
/**
* Sets the Color Grading 2D Lookup Texture.
*/
public set cameraColorGradingTexture(value: Nullable<BaseTexture>) {
(<ImageProcessingConfiguration>this.imageProcessingConfiguration).colorGradingTexture = value;
}
/**
* The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT).
* They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
* These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
* corresponding to low luminance, medium luminance, and high luminance areas respectively.
*/
public get cameraColorCurves(): Nullable<ColorCurves> {
return (<ImageProcessingConfiguration>this.imageProcessingConfiguration).colorCurves;
}
/**
* The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT).
* They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
* These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
* corresponding to low luminance, medium luminance, and high luminance areas respectively.
*/
public set cameraColorCurves(value: Nullable<ColorCurves>) {
(<ImageProcessingConfiguration>this.imageProcessingConfiguration).colorCurves = value;
}
/**
* Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
* Setting this flag to true (not done automatically!) will convert it back to RGB.
*/
public switchToBGR: boolean = false;
private _enableGroundProjection: boolean = false;
/**
* Enables the ground projection mode on the material.
* @see https://doc.babylonjs.com/features/featuresDeepDive/environment/skybox#ground-projection
*/
@serialize()
@expandToProperty("_markAllSubMeshesAsMiscDirty")
public enableGroundProjection: boolean = false;
/**
* Defines the radius of the projected ground if enableGroundProjection is true.
* @see https://doc.babylonjs.com/features/featuresDeepDive/environment/skybox#ground-projection
*/
@serialize()
public projectedGroundRadius = 1000;
/**
* Defines the height of the projected ground if enableGroundProjection is true.
* @see https://doc.babylonjs.com/features/featuresDeepDive/environment/skybox#ground-projection
*/
@serialize()
public projectedGroundHeight = 10;
// Temp values kept as cache in the material.
private _renderTargets = new SmartArray<RenderTargetTexture>(16);
private _reflectionControls = Vector4.Zero();
private _white = Color3.White();
private _primaryShadowColor = Color3.Black();
private _primaryHighlightColor = Color3.Black();
/**
* Instantiates a Background Material in the given scene
* @param name The friendly name of the material
* @param scene The scene to add the material to
*/
constructor(name: string, scene?: Scene) {
super(name, scene);
// Setup the default processing configuration to the scene.
this._attachImageProcessingConfiguration(null);
this.getRenderTargetTextures = (): SmartArray<RenderTargetTexture> => {
this._renderTargets.reset();
if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
this._renderTargets.push(this._diffuseTexture as RenderTargetTexture);
}
if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
this._renderTargets.push(this._reflectionTexture as RenderTargetTexture);
}
return this._renderTargets;
};
}
/**
* Gets a boolean indicating that current material needs to register RTT
*/
public get hasRenderTargetTextures(): boolean {
if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
return true;
}
if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
return true;
}
return false;
}
/**
* The entire material has been created in order to prevent overdraw.
* @returns false
*/
public needAlphaTesting(): boolean {
return true;
}
/**
* The entire material has been created in order to prevent overdraw.
* @returns true if blending is enable
*/
public needAlphaBlending(): boolean {
return this.alpha < 1 || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha) || this._shadowOnly;
}
/**
* Checks whether the material is ready to be rendered for a given mesh.
* @param mesh The mesh to render
* @param subMesh The submesh to check against
* @param useInstances Specify wether or not the material is used with instances
* @returns true if all the dependencies are ready (Textures, Effects...)
*/
public isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances: boolean = false): boolean {
if (subMesh.effect && this.isFrozen) {
if (subMesh.effect._wasPreviouslyReady && subMesh.effect._wasPreviouslyUsingInstances === useInstances) {
return true;
}
}
if (!subMesh.materialDefines) {
subMesh.materialDefines = new BackgroundMaterialDefines();
}
const scene = this.getScene();
const defines = <BackgroundMaterialDefines>subMesh.materialDefines;
if (this._isReadyForSubMesh(subMesh)) {
return true;
}
const engine = scene.getEngine();
// Lights
MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
defines._needNormals = true;
// Multiview
MaterialHelper.PrepareDefinesForMultiview(scene, defines);
// Textures
if (defines._areTexturesDirty) {
defines._needUVs = false;
if (scene.texturesEnabled) {
if (scene.getEngine().getCaps().textureLOD) {
defines.TEXTURELODSUPPORT = true;
}
if (this._diffuseTexture && MaterialFlags.DiffuseTextureEnabled) {
if (!this._diffuseTexture.isReadyOrNotBlocking()) {
return false;
}
MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
defines.OPACITYFRESNEL = this._opacityFresnel;
} else {
defines.DIFFUSE = false;
defines.DIFFUSEDIRECTUV = 0;
defines.DIFFUSEHASALPHA = false;
defines.GAMMADIFFUSE = false;
defines.OPACITYFRESNEL = false;
}
const reflectionTexture = this._reflectionTexture;
if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {
if (!reflectionTexture.isReadyOrNotBlocking()) {
return false;
}
defines.REFLECTION = true;
defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
defines.RGBDREFLECTION = reflectionTexture.isRGBD;
defines.REFLECTIONBLUR = this._reflectionBlur > 0;
defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
defines.REFLECTIONBGR = this.switchToBGR;
if (reflectionTexture.coordinatesMode === Texture.INVCUBIC_MODE) {
defines.INVERTCUBICMAP = true;
}
defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
defines.REFLECTIONMAP_OPPOSITEZ = defines.REFLECTIONMAP_3D && this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
switch (reflectionTexture.coordinatesMode) {
case Texture.EXPLICIT_MODE:
defines.REFLECTIONMAP_EXPLICIT = true;
break;
case Texture.PLANAR_MODE:
defines.REFLECTIONMAP_PLANAR = true;
break;
case Texture.PROJECTION_MODE:
defines.REFLECTIONMAP_PROJECTION = true;
break;
case Texture.SKYBOX_MODE:
defines.REFLECTIONMAP_SKYBOX = true;
break;
case Texture.SPHERICAL_MODE:
defines.REFLECTIONMAP_SPHERICAL = true;
break;
case Texture.EQUIRECTANGULAR_MODE:
defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
break;
case Texture.FIXED_EQUIRECTANGULAR_MODE:
defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
break;
case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
break;
case Texture.CUBIC_MODE:
case Texture.INVCUBIC_MODE:
default:
defines.REFLECTIONMAP_CUBIC = true;
break;
}
if (this.reflectionFresnel) {
defines.REFLECTIONFRESNEL = true;
defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
this._reflectionControls.x = this.reflectionAmount;
this._reflectionControls.y = this.reflectionReflectance0;
this._reflectionControls.z = this.reflectionReflectance90;
this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
} else {
defines.REFLECTIONFRESNEL = false;
defines.REFLECTIONFALLOFF = false;
}
} else {
defines.REFLECTION = false;
defines.REFLECTIONFRESNEL = false;
defines.REFLECTIONFALLOFF = false;
defines.REFLECTIONBLUR = false;
defines.REFLECTIONMAP_3D = false;
defines.REFLECTIONMAP_SPHERICAL = false;
defines.REFLECTIONMAP_PLANAR = false;
defines.REFLECTIONMAP_CUBIC = false;
defines.REFLECTIONMAP_PROJECTION = false;
defines.REFLECTIONMAP_SKYBOX = false;
defines.REFLECTIONMAP_EXPLICIT = false;
defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
defines.INVERTCUBICMAP = false;
defines.REFLECTIONMAP_OPPOSITEZ = false;
defines.LODINREFLECTIONALPHA = false;
defines.GAMMAREFLECTION = false;
defines.RGBDREFLECTION = false;
}
}
defines.PREMULTIPLYALPHA = this.alphaMode === Constants.ALPHA_PREMULTIPLIED || this.alphaMode === Constants.ALPHA_PREMULTIPLIED_PORTERDUFF;
defines.USERGBCOLOR = this._useRGBColor;
defines.NOISE = this._enableNoise;
}
if (defines._areLightsDirty) {
defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
defines.BACKMAT_SHADOWONLY = this._shadowOnly;
}
if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
if (!this._imageProcessingConfiguration.isReady()) {
return false;
}
this._imageProcessingConfiguration.prepareDefines(defines);
}
if (defines._areMiscDirty) {
if (defines.REFLECTIONMAP_3D && this._enableGroundProjection) {
defines.PROJECTED_GROUND = true;
defines.REFLECTIONMAP_SKYBOX = true;
} else {
defines.PROJECTED_GROUND = false;
}
}
// Misc.
MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
// Values that need to be evaluated on every frame
MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, this, defines, useInstances, null, subMesh.getRenderingMesh().hasThinInstances);
// Attribs
if (MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
if (mesh) {
if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {
mesh.createNormals(true);
Logger.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
}
}
}
// Get correct effect
if (defines.isDirty) {
defines.markAsProcessed();
scene.resetCachedMaterial();
// Fallbacks
const fallbacks = new EffectFallbacks();
if (defines.FOG) {
fallbacks.addFallback(0, "FOG");
}
if (defines.POINTSIZE) {
fallbacks.addFallback(1, "POINTSIZE");
}
if (defines.MULTIVIEW) {
fallbacks.addFallback(0, "MULTIVIEW");
}
MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
//Attributes
const attribs = [VertexBuffer.PositionKind];
if (defines.NORMAL) {
attribs.push(VertexBuffer.NormalKind);
}
if (defines.UV1) {
attribs.push(VertexBuffer.UVKind);
}
if (defines.UV2) {
attribs.push(VertexBuffer.UV2Kind);
}
MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
MaterialHelper.PrepareAttributesForInstances(attribs, defines);
const uniforms = [
"world",
"view",
"viewProjection",
"vEyePosition",
"vLightsType",
"vFogInfos",
"vFogColor",
"pointSize",
"mBones",
"vPrimaryColor",
"vPrimaryColorShadow",
"vReflectionInfos",
"reflectionMatrix",
"vReflectionMicrosurfaceInfos",
"fFovMultiplier",
"shadowLevel",
"alpha",
"vBackgroundCenter",
"vReflectionControl",
"vDiffuseInfos",
"diffuseMatrix",
"projectedGroundInfos",
];
addClipPlaneUniforms(uniforms);
const samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
const uniformBuffers = ["Material", "Scene"];
if (ImageProcessingConfiguration) {
ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
}
MaterialHelper.PrepareUniformsAndSamplersList(<IEffectCreationOptions>{
uniformsNames: uniforms,
uniformBuffersNames: uniformBuffers,
samplers: samplers,
defines: defines,
maxSimultaneousLights: this._maxSimultaneousLights,
});
const join = defines.toString();
const effect = scene.getEngine().createEffect(
"background",
<IEffectCreationOptions>{
attributes: attribs,
uniformsNames: uniforms,
uniformBuffersNames: uniformBuffers,
samplers: samplers,
defines: join,
fallbacks: fallbacks,
onCompiled: this.onCompiled,
onError: this.onError,
indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights },
},
engine
);
subMesh.setEffect(effect, defines, this._materialContext);
this.buildUniformLayout();
}